Merge branch 'master' into execa

This commit is contained in:
Mick Dekkers
2017-12-28 22:56:33 +01:00
committed by GitHub
1744 changed files with 135249 additions and 48019 deletions
+13 -1
View File
@@ -38,7 +38,7 @@ or just look for any ".d.ts" files in the package and manually include them with
These can be used by TypeScript 1.0.
* [Typings](https://github.com/typings/typings)
* ~~[NuGet](http://nuget.org/Tpackages?q=DefinitelyTyped)~~ (use preferred alternatives, nuget DT type publishing has been turned off)
* ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (use preferred alternatives, nuget DT type publishing has been turned off)
* Manually download from the `master` branch of this repository
You may need to add manual [references](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html).
@@ -313,6 +313,18 @@ When `dts-gen` is used to scaffold a scoped package, the `paths` property has to
GitHub doesn't [support](http://stackoverflow.com/questions/5646174/how-to-make-github-follow-directory-history-after-renames) file history for renamed files. Use [`git log --follow`](https://www.git-scm.com/docs/git-log) instead.
#### Should I add an empty namespace to a package that doesn't export a module to use ES6 style imports?
Some packages, like [chai-http](https://github.com/chaijs/chai-http), export a function.
Importing this module with an ES6 style import in the form `import * as foo from "foo";` leads to the error:
> error TS2497: Module 'foo' resolves to a non-module entity and cannot be imported using this construct
This error can be suppressed by merging the function declaration with an empty namespace of the same name, but this practice is discouraged.
This is a commonly cited [Stack Overflow answer](https://stackoverflow.com/questions/39415661/what-does-resolves-to-a-non-module-entity-and-cannot-be-imported-using-this) regarding this matter.
It is more appropriate to import the module using the `import foo = require("foo");` syntax, or to use a default import like `import foo from "foo";` if using the `--allowSyntheticDefaultImports` flag if your module runtime supports an interop scheme for non-ECMAScript modules as such.
## License
+192
View File
@@ -60,6 +60,18 @@
"sourceRepoURL": "https://github.com/AlexTeixeira/Askmethat-Rating",
"asOfVersion": "0.4.0"
},
{
"libraryName": "aurelia-knockout",
"typingsPackageName": "aurelia-knockout",
"sourceRepoURL": "https://github.com/code-chris/aurelia-knockout",
"asOfVersion": "2.1.0"
},
{
"libraryName": "autobind-decorator",
"typingsPackageName": "autobind-decorator",
"sourceRepoURL": "https://github.com/andreypopp/autobind-decorator",
"asOfVersion": "2.1.0"
},
{
"libraryName": "aws-sdk",
"typingsPackageName": "aws-sdk",
@@ -78,6 +90,12 @@
"sourceRepoURL": "https://github.com/mzabriskie/axios",
"asOfVersion": "0.14.0"
},
{
"libraryName": "axios-mock-adapter",
"typingsPackageName": "axios-mock-adapter",
"sourceRepoURL": "https://github.com/ctimmerm/axios-mock-adapter",
"asOfVersion": "1.10.0"
},
{
"libraryName": "azure-mobile-apps",
"typingsPackageName": "azure-mobile-apps",
@@ -102,6 +120,12 @@
"sourceRepoURL": "https://github.com/peterolson/BigInteger.js",
"asOfVersion": "0.0.31"
},
{
"libraryName": "Bowser",
"typingsPackageName": "bowser",
"sourceRepoURL": "https://github.com/ded/bowser",
"asOfVersion": "1.1.1"
},
{
"libraryName": "Bugsnag Browser",
"typingsPackageName": "bugsnag-js",
@@ -132,18 +156,42 @@
"sourceRepoURL": "https://github.com/mapbox/cheap-ruler",
"asOfVersion": "2.5.0"
},
{
"libraryName": "chunked-dc",
"typingsPackageName": "chunked-dc",
"sourceRepoURL": "https://github.com/saltyrtc/chunked-dc-js",
"asOfVersion": "0.2.2"
},
{
"libraryName": "commander",
"typingsPackageName": "commander",
"sourceRepoURL": "https://github.com/tj/commander.js",
"asOfVersion": "2.12.2"
},
{
"libraryName": "constant-case",
"typingsPackageName": "constant-case",
"sourceRepoURL": "https://github.com/blakeembrey/constant-case",
"asOfVersion": "1.1.2"
},
{
"libraryName": "cypress",
"typingsPackageName": "cypress",
"sourceRepoURL": "https://cypress.io",
"asOfVersion": "1.1.3"
},
{
"libraryName": "date-fns",
"typingsPackageName": "date-fns",
"sourceRepoURL": "https://github.com/date-fns/date-fns",
"asOfVersion": "2.6.0"
},
{
"libraryName": "decimal.js",
"typingsPackageName": "decimal.js",
"sourceRepoURL": "https://github.com/MikeMcl/decimal.js",
"asOfVersion": "7.4.0"
},
{
"libraryName": "DevExtreme",
"typingsPackageName": "devextreme",
@@ -156,6 +204,12 @@
"sourceRepoURL": "https://github.com/dfahlander/Dexie.js",
"asOfVersion": "1.3.1"
},
{
"libraryName": "docker-file-parser",
"typingsPackageName": "docker-file-parser",
"sourceRepoURL": "https://github.com/joyent/docker-file-parser",
"asOfVersion": "1.0.3"
},
{
"libraryName": "dot-case",
"typingsPackageName": "dot-case",
@@ -186,6 +240,12 @@
"sourceRepoURL": "https://github.com/loopline-systems/electron-builder",
"asOfVersion": "2.8.0"
},
{
"libraryName": "error-stack-parser",
"typingsPackageName": "error-stack-parser",
"sourceRepoURL": "https://github.com/stacktracejs/error-stack-parser",
"asOfVersion": "2.0.0"
},
{
"libraryName": "eventemitter2",
"typingsPackageName": "eventemitter2",
@@ -204,6 +264,12 @@
"sourceRepoURL": "https://github.com/ctavan/express-validator",
"asOfVersion": "3.0.0"
},
{
"libraryName": "extended-listbox",
"typingsPackageName": "extended-listbox",
"sourceRepoURL": "https://github.com/code-chris/extended-listbox",
"asOfVersion": "4.0.1"
},
{
"libraryName": "JSON-Patch",
"typingsPackageName": "fast-json-patch",
@@ -216,6 +282,12 @@
"sourceRepoURL": "https://www.npmjs.com/package/fast-simplex-noise",
"asOfVersion": "3.0.0"
},
{
"libraryName": "fecha",
"typingsPackageName": "fecha",
"sourceRepoURL": "https://github.com/taylorhakes/fecha",
"asOfVersion": "2.3.1"
},
{
"libraryName": "FineUploader",
"typingsPackageName": "fine-uploader",
@@ -228,6 +300,12 @@
"sourceRepoURL": "https://github.com/chmln/flatpickr",
"asOfVersion": "3.1.2"
},
{
"libraryName": "flux-standard-action",
"typingsPackageName": "flux-standard-action",
"sourceRepoURL": "https://github.com/acdlite/flux-standard-action",
"asOfVersion": "1.1.0"
},
{
"libraryName": "gaea-model",
"typingsPackageName": "gaea-model",
@@ -246,6 +324,18 @@
"sourceRepoURL": "https://github.com/ivogabe/gulp-typescript",
"asOfVersion": "2.13.0"
},
{
"libraryName": "http-status-codes",
"typingsPackageName": "http-status-codes",
"sourceRepoURL": "https://github.com/prettymuchbryce/node-http-status",
"asOfVersion": "1.2.0"
},
{
"libraryName": "iconv-lite",
"typingsPackageName": "iconv-lite",
"sourceRepoURL": "https://github.com/ashtuchkin/iconv-lite",
"asOfVersion": "0.4.14"
},
{
"libraryName": "Facebook's Immutable",
"typingsPackageName": "immutable",
@@ -288,6 +378,12 @@
"sourceRepoURL": "https://github.com/inversify/inversify-restify-utils",
"asOfVersion": "2.0.0"
},
{
"libraryName": "Ionic",
"typingsPackageName": "ionic",
"sourceRepoURL": "http://ionicframework.com",
"asOfVersion": "3.19.0"
},
{
"libraryName": "is-lower-case",
"typingsPackageName": "is-lower-case",
@@ -300,6 +396,12 @@
"sourceRepoURL": "https://github.com/blakeembrey/is-upper-case",
"asOfVersion": "1.1.2"
},
{
"libraryName": "jimp",
"typingsPackageName": "jimp",
"sourceRepoURL": "https://github.com/oliver-moran/jimp#readme",
"asOfVersion": "0.2.28"
},
{
"libraryName": "jpush-react-native",
"typingsPackageName": "jpush-react-native",
@@ -336,6 +438,12 @@
"sourceRepoURL": "https://github.com/jsplumb/jsPlumb",
"asOfVersion": "2.5.7"
},
{
"libraryName": "keycloak-js",
"typingsPackageName": "keycloak-js",
"sourceRepoURL": "https://github.com/keycloak/keycloak",
"asOfVersion": "3.4.1"
},
{
"libraryName": "knockout-paging",
"typingsPackageName": "knockout-paging",
@@ -354,6 +462,18 @@
"sourceRepoURL": "https://github.com/elitechance/lambda-phi",
"asOfVersion": "1.0.1"
},
{
"libraryName": "ldclient-js",
"typingsPackageName": "ldclient-js",
"sourceRepoURL": "https://github.com/launchdarkly/js-client",
"asOfVersion": "1.1.11"
},
{
"libraryName": "left-pad",
"typingsPackageName": "left-pad",
"sourceRepoURL": "https://github.com/stevemao/left-pad",
"asOfVersion": "1.2.0"
},
{
"libraryName": "Linq.JS",
"typingsPackageName": "linq",
@@ -486,12 +606,24 @@
"sourceRepoURL": "https://github.com/pillarjs/path-to-regexp",
"asOfVersion": "1.7.0"
},
{
"libraryName": "pg-connection-string",
"typingsPackageName": "pg-connection-string",
"sourceRepoURL": "https://github.com/iceddev/pg-connection-string",
"asOfVersion": "2.0.0"
},
{
"libraryName": "pg-promise",
"typingsPackageName": "pg-promise",
"sourceRepoURL": "https://github.com/vitaly-t/pg-promise",
"asOfVersion": "5.4.3"
},
{
"libraryName": "phonegap-plugin-push",
"typingsPackageName": "phonegap-plugin-push",
"sourceRepoURL": "https://github.com/phonegap/phonegap-plugin-push",
"asOfVersion": "2.1.2"
},
{
"libraryName": "pixi-spine",
"typingsPackageName": "pixi-spine",
@@ -504,6 +636,12 @@
"sourceRepoURL": "https://github.com/PeculiarVentures/pkcs11js",
"asOfVersion": "1.0.4"
},
{
"libraryName": "plottable",
"typingsPackageName": "plottable",
"sourceRepoURL": "http://plottablejs.org/",
"asOfVersion": "3.7.0"
},
{
"libraryName": "poly2tri.js",
"typingsPackageName": "poly2tri",
@@ -552,6 +690,24 @@
"sourceRepoURL": "https://github.com/gpbl/react-day-picker",
"asOfVersion": "5.3.0"
},
{
"libraryName": "react-native-elements",
"typingsPackageName": "react-native-elements",
"sourceRepoURL": "https://github.com/react-native-training/react-native-elements",
"asOfVersion": "0.18.0"
},
{
"libraryName": "react-native-google-analytics-bridge",
"typingsPackageName": "react-native-google-analytics-bridge",
"sourceRepoURL": "https://github.com/idehub/react-native-google-analytics-bridge",
"asOfVersion": "5.3.3"
},
{
"libraryName": "react-split-pane",
"typingsPackageName": "react-split-pane",
"sourceRepoURL": "https://github.com/tomkp/react-split-pane",
"asOfVersion": "0.1.67"
},
{
"libraryName": "realm",
"typingsPackageName": "realm",
@@ -570,6 +726,12 @@
"sourceRepoURL": "https://github.com/tshelburne/redux-batched-actions",
"asOfVersion": "0.1.5"
},
{
"libraryName": "react-bootstrap",
"typingsPackageName": "redux-bootstrap",
"sourceRepoURL": "https://github.com/remojansen/redux-bootstrap",
"asOfVersion": "1.1.0"
},
{
"libraryName": "redux-devtools-extension",
"typingsPackageName": "redux-devtools-extension",
@@ -678,12 +840,24 @@
"sourceRepoURL": "https://github.com/blakeembrey/snake-case",
"asOfVersion": "1.1.2"
},
{
"libraryName": "Spin.js",
"typingsPackageName": "spin.js",
"sourceRepoURL": "http://fgnass.github.com/spin.js/",
"asOfVersion": "3.0.0"
},
{
"libraryName": "spotify-web-api-js",
"typingsPackageName": "spotify-web-api-js",
"sourceRepoURL": "https://github.com/JMPerez/spotify-web-api-js",
"asOfVersion": "0.21.0"
},
{
"libraryName": "striptags",
"typingsPackageName": "striptags",
"sourceRepoURL": "https://github.com/ericnorris/striptags",
"asOfVersion": "3.1.1"
},
{
"libraryName": "Sugar",
"typingsPackageName": "sugar",
@@ -714,6 +888,12 @@
"sourceRepoURL": "http://gcanti.github.io/tcomb/guide/index.html",
"asOfVersion": "2.6.0"
},
{
"libraryName": "timezonecomplete",
"typingsPackageName": "timezonecomplete",
"sourceRepoURL": "https://github.com/SpiritIT/timezonecomplete",
"asOfVersion": "5.5.0"
},
{
"libraryName": "title-case",
"typingsPackageName": "title-case",
@@ -762,6 +942,12 @@
"sourceRepoURL": "https://github.com/blakeembrey/upper-case-first",
"asOfVersion": "1.1.2"
},
{
"libraryName": "Validate.js",
"typingsPackageName": "validate.js",
"sourceRepoURL": "https://github.com/ansman/validate.js",
"asOfVersion": "0.11.0"
},
{
"libraryName": "vso-node-api",
"typingsPackageName": "vso-node-api",
@@ -810,6 +996,12 @@
"sourceRepoURL": "github.com/node-xmpp/node-xmpp/",
"asOfVersion": "1.2.0"
},
{
"libraryName": "zetapush-js",
"typingsPackageName": "zetapush-js",
"sourceRepoURL": "https://github.com/zetapush/zetapush-js",
"asOfVersion": "3.1.2"
},
{
"libraryName": "Zone.js",
"typingsPackageName": "zone.js",
+6 -5
View File
@@ -1,13 +1,14 @@
// Type definitions for accepts 1.3
// Project: https://github.com/jshttp/accepts
// Definitions by: Stefan Reichel <https://github.com/bomret>
// Brice BERNARD <https://github.com/brikou>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare namespace accepts {
interface Headers {
[key: string]: string | string[];
}
/// <reference types="node" />
import { IncomingMessage } from "http";
declare namespace accepts {
interface Accepts {
/**
* Return the first accepted charset. If nothing in `charsets` is accepted, then `false` is returned.
@@ -55,6 +56,6 @@ declare namespace accepts {
}
}
declare function accepts(req: { headers: accepts.Headers }): accepts.Accepts;
declare function accepts(req: IncomingMessage): accepts.Accepts;
export = accepts;
+51 -15
View File
@@ -345,18 +345,47 @@ declare namespace AceAjax {
insert(position: Position, text: string): any;
/**
* Inserts the elements in `lines` into the document, starting at the row index given by `row`. This method also triggers the `'change'` event.
* @param row The index of the row to insert at
* @param lines An array of strings
**/
* @deprecated Use the insertFullLines method instead.
*/
insertLines(row: number, lines: string[]): any;
/**
* Inserts a new line into the document at the current row's `position`. This method also triggers the `'change'` event.
* @param position The position to insert at
**/
* Inserts the elements in `lines` into the document as full lines (does not merge with existing line), starting at the row index given by `row`. This method also triggers the `"change"` event.
* @param {Number} row The index of the row to insert at
* @param {Array} lines An array of strings
* @returns {Object} Contains the final row and column, like this:
* ```
* {row: endRow, column: 0}
* ```
* If `lines` is empty, this function returns an object containing the current row, and column, like this:
* ```
* {row: row, column: 0}
* ```
*
**/
insertFullLines(row: number, lines: string[]): any;
/**
* @deprecated Use insertMergedLines(position, ['', '']) instead.
*/
insertNewLine(position: Position): any;
/**
* Inserts the elements in `lines` into the document, starting at the position index given by `row`. This method also triggers the `"change"` event.
* @param {Number} row The index of the row to insert at
* @param {Array} lines An array of strings
* @returns {Object} Contains the final row and column, like this:
* ```
* {row: endRow, column: 0}
* ```
* If `lines` is empty, this function returns an object containing the current row, and column, like this:
* ```
* {row: row, column: 0}
* ```
*
**/
insertMergedLines(row: number, lines: string[]): any;
/**
* Inserts `text` into the `position` at the current row. This method also triggers the `'change'` event.
* @param position The position to insert at
@@ -379,12 +408,19 @@ declare namespace AceAjax {
removeInLine(row: number, startColumn: number, endColumn: number): any;
/**
* Removes a range of full lines. This method also triggers the `'change'` event.
* @param firstRow The first row to be removed
* @param lastRow The last row to be removed
**/
* @deprecated Use the removeFullLines method instead.
*/
removeLines(firstRow: number, lastRow: number): string[];
/**
* Removes a range of full lines. This method also triggers the `"change"` event.
* @param {Number} firstRow The first row to be removed
* @param {Number} lastRow The last row to be removed
* @returns {[String]} Returns all the removed lines.
*
**/
removeFullLines(firstRow: number, lastRow: number): string[];
/**
* Removes the new line between `row` and the row immediately following it. This method also triggers the `'change'` event.
* @param row The row to check
@@ -474,9 +510,9 @@ declare namespace AceAjax {
removeFold(arg: any): void;
expandFold(arg: any): void;
foldAll(startRow?: number, endRow?: number, depth?: number): void
unfold(arg1: any, arg2: boolean): void;
screenToDocumentColumn(row: number, column: number): void;
@@ -2659,9 +2695,9 @@ declare namespace AceAjax {
characterWidth: number;
lineHeight: number;
setScrollMargin(top:number, bottom:number, left: number, right: number): void;
screenToTextCoordinates(left: number, top: number): void;
/**
+13
View File
@@ -0,0 +1,13 @@
License Notices:
The API definitions are from Actions on Google reference site [1] and actions-on-google library [2].
The actions-on-google library is licensed under the Apache 2.0 License [3].
The code documentation is reproduced from work created and shared by Google [4]
and used according to terms described in the Creative Commons 3.0 Attribution License [5].
[1] https://developers.google.com/actions/
[2] https://github.com/actions-on-google/actions-on-google-nodejs
[3] http://www.apache.org/licenses/LICENSE-2.0
[4] https://developers.google.com/readme/policies/
[5] http://creativecommons.org/licenses/by/3.0/
@@ -0,0 +1,33 @@
import { ActionsSdkApp, ActionsSdkAppOptions, DialogflowApp, DialogflowAppOptions, AssistantApp,
Responses, Transactions } from 'actions-on-google';
import * as express from 'express';
function testActionsSdk(request: express.Request, response: express.Response) {
const app = new ActionsSdkApp({request, response});
const actionMap = new Map();
actionMap.set(app.StandardIntents.MAIN, () => {
const richResponse: Responses.RichResponse = app.buildRichResponse()
.addSimpleResponse('Hello world')
.addSuggestions(['foo', 'bar']);
app.ask(richResponse);
});
app.handleRequest(actionMap);
}
function testDialogflow(request: express.Request, response: express.Response) {
const app = new DialogflowApp({request, response});
const actionMap = new Map();
actionMap.set(app.StandardIntents.MAIN, () => {
const order: Transactions.Order = app.buildOrder('foo');
app.askForTransactionDecision(order, {
type: app.Transactions.PaymentType.PAYMENT_CARD,
displayName: 'VISA-1234',
deliveryAddressRequired: true
});
});
app.handleRequest(actionMap);
}
const expressApp = express();
expressApp.get('/actionssdk', testActionsSdk);
expressApp.get('/dialogflow', testDialogflow);
+415
View File
@@ -0,0 +1,415 @@
import * as express from 'express';
import { AssistantApp } from './assistant-app';
import { Carousel, List, RichResponse, SimpleResponse } from './response-builder';
// ---------------------------------------------------------------------------
// Actions SDK support
// ---------------------------------------------------------------------------
export interface ActionsSdkAppOptions {
/** Express HTTP request object. */
request: express.Request;
/** Express HTTP response object. */
response: express.Response;
/** Function callback when session starts. */
sessionStarted?(): any;
}
/**
* This is the class that handles the conversation API directly from Assistant,
* providing implementation for all the methods available in the API.
*/
export class ActionsSdkApp extends AssistantApp {
/**
* Constructor for ActionsSdkApp object.
* To be used in the Actions SDK HTTP endpoint logic.
*
* @example
* const ActionsSdkApp = require('actions-on-google').ActionsSdkApp;
* const app = new ActionsSdkApp({request: request, response: response,
* sessionStarted:sessionStarted});
*
* @actionssdk
*/
constructor(options: ActionsSdkAppOptions);
/**
* @deprecated
* Validates whether request is from Assistant through signature verification.
* Uses Google-Auth-Library to verify authorization token against given
* Google Cloud Project ID. Auth token is given in request header with key,
* "Authorization".
*
* @example
* const app = new ActionsSdkApp({request, response});
* app.isRequestFromAssistant('nodejs-cloud-test-project-1234')
* .then(() => {
* app.ask('Hey there, thanks for stopping by!');
* })
* .catch(err => {
* response.status(400).send();
* });
*
* @param projectId Google Cloud Project ID for the Assistant app.
* @return Promise resolving with google-auth-library LoginTicket
* if request is from a valid source, otherwise rejects with the error reason
* for an invalid token.
* @actionssdk
*/
isRequestFromAssistant(projectId: string): Promise<object>;
/**
* Validates whether request is from Google through signature verification.
* Uses Google-Auth-Library to verify authorization token against given
* Google Cloud Project ID. Auth token is given in request header with key,
* "Authorization".
*
* @example
* const app = new ActionsSdkApp({request, response});
* app.isRequestFromGoogle('nodejs-cloud-test-project-1234')
* .then(() => {
* app.ask('Hey there, thanks for stopping by!');
* })
* .catch(err => {
* response.status(400).send();
* });
*
* @param projectId Google Cloud Project ID for the Assistant app.
* @return Promise resolving with google-auth-library LoginTicket
* if request is from a valid source, otherwise rejects with the error reason
* for an invalid token.
* @actionssdk
*/
isRequestFromGoogle(projectId: string): Promise<object>;
/**
* Gets the request Conversation API version.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
* const apiVersion = app.getApiVersion();
*
* @return Version value or null if no value.
* @actionssdk
*/
getApiVersion(): string;
/**
* Gets the user's raw input query.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
* app.tell('You said ' + app.getRawInput());
*
* @return User's raw query or null if no value.
* @actionssdk
*/
getRawInput(): string;
/**
* Gets previous JSON dialog state that the app sent to Assistant.
* Alternatively, use the app.data field to store JSON values between requests.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
* const dialogState = app.getDialogState();
*
* @return JSON object provided to the Assistant in the previous
* user turn or {} if no value.
* @actionssdk
*/
getDialogState(): any;
/**
* Gets the "versionLabel" specified inside the Action Package.
* Used by app to do version control.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
* const actionVersionLabel = app.getActionVersionLabel();
*
* @return The specified version label or null if unspecified.
* @actionssdk
*/
getActionVersionLabel(): string;
/**
* Gets the unique conversation ID. It's a new ID for the initial query,
* and stays the same until the end of the conversation.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
* const conversationId = app.getConversationId();
*
* @return Conversation ID or null if no value.
* @actionssdk
*/
getConversationId(): string;
/**
* Get the current intent. Alternatively, using a handler Map with
* {@link AssistantApp#handleRequest|handleRequest}, the client library will
* automatically handle the incoming intents.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
*
* function responseHandler (app) {
* const intent = app.getIntent();
* switch (intent) {
* case app.StandardIntents.MAIN:
* const inputPrompt = app.buildInputPrompt(false, 'Welcome to action snippets! Say anything.');
* app.ask(inputPrompt);
* break;
*
* case app.StandardIntents.TEXT:
* app.tell('You said ' + app.getRawInput());
* break;
* }
* }
*
* app.handleRequest(responseHandler);
*
* @return Intent id or null if no value.
* @actionssdk
*/
getIntent(): string;
/**
* Get the argument value by name from the current intent. If the argument
* is not a text argument, the entire argument object is returned.
*
* Note: If incoming request is using an API version under 2 (e.g. 'v1'),
* the argument object will be in Proto2 format (snake_case, etc).
*
* @param argName Name of the argument.
* @return Argument value matching argName
* or null if no matching argument.
* @actionssdk
*/
getArgument(argName: string): string;
/**
* Returns the option key user chose from options response.
*
* @example
* const app = new App({request: req, response: res});
*
* function pickOption (app) {
* if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) {
* app.askWithCarousel('Which of these looks good?',
* app.buildCarousel().addItems(
* app.buildOptionItem('another_choice', ['Another choice']).
* setTitle('Another choice').setDescription('Choose me!')));
* } else {
* app.ask('What would you like?');
* }
* }
*
* function optionPicked (app) {
* app.ask('You picked ' + app.getSelectedOption());
* }
*
* const actionMap = new Map();
* actionMap.set(app.StandardIntents.TEXT, pickOption);
* actionMap.set(app.StandardIntents.OPTION, optionPicked);
*
* app.handleRequest(actionMap);
*
* @return Option key of selected item. Null if no option selected or
* if current intent is not OPTION intent.
* @actionssdk
*/
getSelectedOption(): string;
/**
* Asks to collect user's input; all user's queries need to be sent to
* the app.
* {@link https://developers.google.com/actions/policies/general-policies#user_experience|The guidelines when prompting the user for a response must be followed at all times}.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
*
* function mainIntent (app) {
* const inputPrompt = app.buildInputPrompt(true, '<speak>Hi! <break time="1"/> ' +
* 'I can read out an ordinal like ' +
* '<say-as interpret-as="ordinal">123</say-as>. Say a number.</speak>',
* ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']);
* app.ask(inputPrompt);
* }
*
* function rawInput (app) {
* if (app.getRawInput() === 'bye') {
* app.tell('Goodbye!');
* } else {
* const inputPrompt = app.buildInputPrompt(true, '<speak>You said, <say-as interpret-as="ordinal">' +
* app.getRawInput() + '</say-as></speak>',
* ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']);
* app.ask(inputPrompt);
* }
* }
*
* const actionMap = new Map();
* actionMap.set(app.StandardIntents.MAIN, mainIntent);
* actionMap.set(app.StandardIntents.TEXT, rawInput);
*
* app.handleRequest(actionMap);
*
* @param inputPrompt Holding initial and
* no-input prompts.
* @param dialogState JSON object the app uses to hold dialog state that
* will be circulated back by App.
* @return The response that is sent to Assistant to ask user to provide input.
* @actionssdk
*/
ask(inputPrompt: object | SimpleResponse | RichResponse, dialogState?: object): express.Response | null;
/**
* Asks to collect user's input with a list.
*
* @example
* const app = new ActionsSdkApp({request, response});
*
* function welcomeIntent (app) {
* app.askWithlist('Which of these looks good?',
* app.buildList('List title')
* .addItems([
* app.buildOptionItem(SELECTION_KEY_ONE,
* ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2'])
* .setTitle('Number one'),
* app.buildOptionItem(SELECTION_KEY_TWO,
* ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2'])
* .setTitle('Number two'),
* ]));
* }
*
* function optionIntent (app) {
* if (app.getSelectedOption() === SELECTION_KEY_ONE) {
* app.tell('Number one is a great choice!');
* } else {
* app.tell('Number two is a great choice!');
* }
* }
*
* const actionMap = new Map();
* actionMap.set(app.StandardIntents.TEXT, welcomeIntent);
* actionMap.set(app.StandardIntents.OPTION, optionIntent);
* app.handleRequest(actionMap);
*
* @param inputPrompt Holding initial and
* no-input prompts. Cannot contain basic card.
* @param list List built with {@link AssistantApp#buildList|buildList}.
* @param dialogState JSON object the app uses to hold dialog state that
* will be circulated back by Assistant.
* @return The response that is sent to Assistant to ask user to provide input.
* @actionssdk
*/
askWithList(inputPrompt: object | SimpleResponse | RichResponse, list: List, dialogState?: object): express.Response | null;
/**
* Asks to collect user's input with a carousel.
*
* @example
* const app = new ActionsSdkApp({request, response});
*
* function welcomeIntent (app) {
* app.askWithCarousel('Which of these looks good?',
* app.buildCarousel()
* .addItems([
* app.buildOptionItem(SELECTION_KEY_ONE,
* ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2'])
* .setTitle('Number one'),
* app.buildOptionItem(SELECTION_KEY_TWO,
* ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2'])
* .setTitle('Number two'),
* ]));
* }
*
* function optionIntent (app) {
* if (app.getSelectedOption() === SELECTION_KEY_ONE) {
* app.tell('Number one is a great choice!');
* } else {
* app.tell('Number two is a great choice!');
* }
* }
*
* const actionMap = new Map();
* actionMap.set(app.StandardIntents.TEXT, welcomeIntent);
* actionMap.set(app.StandardIntents.OPTION, optionIntent);
* app.handleRequest(actionMap);
*
* @param inputPrompt Holding initial and
* no-input prompts. Cannot contain basic card.
* @param carousel Carousel built with
* {@link AssistantApp#buildCarousel|buildCarousel}.
* @param dialogState JSON object the app uses to hold dialog state that
* will be circulated back by Assistant.
* @return The response that is sent to Assistant to ask user to provide input.
* @actionssdk
*/
askWithCarousel(inputPrompt: object | SimpleResponse | RichResponse, carousel: Carousel, dialogState?: object): express.Response | null;
/**
* Tells Assistant to render the speech response and close the mic.
*
* @example
* const app = new ActionsSdkApp({request: request, response: response});
*
* function mainIntent (app) {
* const inputPrompt = app.buildInputPrompt(true, '<speak>Hi! <break time="1"/> ' +
* 'I can read out an ordinal like ' +
* '<say-as interpret-as="ordinal">123</say-as>. Say a number.</speak>',
* ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']);
* app.ask(inputPrompt);
* }
*
* function rawInput (app) {
* if (app.getRawInput() === 'bye') {
* app.tell('Goodbye!');
* } else {
* const inputPrompt = app.buildInputPrompt(true, '<speak>You said, <say-as interpret-as="ordinal">' +
* app.getRawInput() + '</say-as></speak>',
* ['I didn\'t hear a number', 'If you\'re still there, what\'s the number?', 'What is the number?']);
* app.ask(inputPrompt);
* }
* }
*
* const actionMap = new Map();
* actionMap.set(app.StandardIntents.MAIN, mainIntent);
* actionMap.set(app.StandardIntents.TEXT, rawInput);
*
* app.handleRequest(actionMap);
*
* @param textToSpeech Final response.
* Spoken response can be SSML.
* @return The HTTP response that is sent back to Assistant.
* @actionssdk
*/
tell(textToSpeech: string | SimpleResponse | RichResponse): express.Response | null;
/**
* Builds the {@link https://developers.google.com/actions/reference/conversation#InputPrompt|InputPrompt object}
* from initial prompt and no-input prompts.
*
* The App needs one initial prompt to start the conversation. If there is no user response,
* the App re-opens the mic and renders the no-input prompts three times
* (one for each no-input prompt that was configured) to help the user
* provide the right response.
*
* Note: we highly recommend app to provide all the prompts required here in order to ensure a
* good user experience.
*
* @example
* const inputPrompt = app.buildInputPrompt(false, 'Welcome to action snippets! Say a number.',
* ['Say any number', 'Pick a number', 'What is the number?']);
* app.ask(inputPrompt);
*
* @param isSsml Indicates whether the text to speech is SSML or not.
* @param initialPrompt The initial prompt the App asks the user.
* @param noInputs Array of re-prompts when the user does not respond (max 3).
* @return.
* @actionssdk
*/
buildInputPrompt(isSsml: boolean, initialPrompt: string, noInputs?: string[]): object;
}
File diff suppressed because it is too large Load Diff
+571
View File
@@ -0,0 +1,571 @@
import * as express from 'express';
import { AssistantApp } from './assistant-app';
import { Carousel, List, RichResponse, SimpleResponse } from './response-builder';
// ---------------------------------------------------------------------------
// Dialogflow support
// ---------------------------------------------------------------------------
/**
* Dialogflow {@link https://dialogflow.com/docs/concept-contexts|Context}.
*/
export interface Context {
/** Full name of the context. */
name: string;
/**
* Parameters carried within this context.
* See {@link https://dialogflow.com/docs/concept-actions#section-extracting-values-from-contexts|here}.
*/
parameters: object;
/** Remaining number of intents */
lifespan: number;
}
export interface DialogflowAppOptions {
/** Express HTTP request object. */
request: express.Request;
/** Express HTTP response object. */
response: express.Response;
/**
* Function callback when session starts.
* Only called if webhook is enabled for welcome/triggering intents, and
* called from Web Simulator or Google Home device (i.e., not Dialogflow simulator).
*/
sessionStarted?(): any;
}
/**
* This is the class that handles the communication with Dialogflow's fulfillment API.
*/
export class DialogflowApp extends AssistantApp {
/**
* Constructor for DialogflowApp object.
* To be used in the Dialogflow fulfillment webhook logic.
*
* @example
* const DialogflowApp = require('actions-on-google').DialogflowApp;
* const app = new DialogflowApp({request: request, response: response,
* sessionStarted:sessionStarted});
*
* @dialogflow
*/
constructor(options: DialogflowAppOptions);
/**
* @deprecated
* Verifies whether the request comes from Dialogflow.
*
* @param key The header key specified by the developer in the
* Dialogflow Fulfillment settings of the app.
* @param value The private value specified by the developer inside the
* fulfillment header.
* @return True if the request comes from Dialogflow.
* @dialogflow
*/
isRequestFromApiAi(key: string, value: string): boolean;
/**
* Verifies whether the request comes from Dialogflow.
*
* @param key The header key specified by the developer in the
* Dialogflow Fulfillment settings of the app.
* @param value The private value specified by the developer inside the
* fulfillment header.
* @return True if the request comes from Dialogflow.
* @dialogflow
*/
isRequestFromDialogflow(key: string, value: string): boolean;
/**
* Get the current intent. Alternatively, using a handler Map with
* {@link AssistantApp#handleRequest|handleRequest},
* the client library will automatically handle the incoming intents.
* 'Intent' in the Dialogflow context translates into the current action.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
*
* function responseHandler (app) {
* const intent = app.getIntent();
* switch (intent) {
* case WELCOME_INTENT:
* app.ask('Welcome to action snippets! Say a number.');
* break;
*
* case NUMBER_INTENT:
* const number = app.getArgument(NUMBER_ARGUMENT);
* app.tell('You said ' + number);
* break;
* }
* }
*
* app.handleRequest(responseHandler);
*
* @return Intent id or null if no value (action name).
* @dialogflow
*/
getIntent(): string;
/**
* Get the argument value by name from the current intent. If the argument
* is included in originalRequest, and is not a text argument, the entire
* argument object is returned.
*
* Note: If incoming request is using an API version under 2 (e.g. 'v1'),
* the argument object will be in Proto2 format (snake_case, etc).
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* const WELCOME_INTENT = 'input.welcome';
* const NUMBER_INTENT = 'input.number';
*
* function welcomeIntent (app) {
* app.ask('Welcome to action snippets! Say a number.');
* }
*
* function numberIntent (app) {
* const number = app.getArgument(NUMBER_ARGUMENT);
* app.tell('You said ' + number);
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(NUMBER_INTENT, numberIntent);
* app.handleRequest(actionMap);
*
* @param argName Name of the argument.
* @return Argument value matching argName
* or null if no matching argument.
* @dialogflow
*/
getArgument(argName: string): object;
/**
* Get the context argument value by name from the current intent. Context
* arguments include parameters collected in previous intents during the
* lifespan of the given context. If the context argument has an original
* value, usually representing the underlying entity value, that will be given
* as part of the return object.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* const WELCOME_INTENT = 'input.welcome';
* const NUMBER_INTENT = 'input.number';
* const OUT_CONTEXT = 'output_context';
* const NUMBER_ARG = 'myNumberArg';
*
* function welcomeIntent (app) {
* const parameters = {};
* parameters[NUMBER_ARG] = '42';
* app.setContext(OUT_CONTEXT, 1, parameters);
* app.ask('Welcome to action snippets! Ask me for your number.');
* }
*
* function numberIntent (app) {
* const number = app.getContextArgument(OUT_CONTEXT, NUMBER_ARG);
* // number === { value: 42 }
* app.tell('Your number is ' + number.value);
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(NUMBER_INTENT, numberIntent);
* app.handleRequest(actionMap);
*
* @param contextName Name of the context.
* @param argName Name of the argument.
* @return Object containing value property and optional original
* property matching context argument. Null if no matching argument.
* @dialogflow
*/
getContextArgument(contextName: string, argName: string): object;
/**
* Returns the RichResponse constructed in Dialogflow response builder.
*
* @example
* const app = new App({request: req, response: res});
*
* function tellFact (app) {
* let fact = 'Google was founded in 1998';
*
* if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) {
* app.ask(app.getIncomingRichResponse().addSimpleResponse('Here\'s a ' +
* 'fact for you. ' + fact + ' Which one do you want to hear about ' +
* 'next, Google\'s history or headquarters?'));
* } else {
* app.ask('Here\'s a fact for you. ' + fact + ' Which one ' +
* 'do you want to hear about next, Google\'s history or headquarters?');
* }
* }
*
* const actionMap = new Map();
* actionMap.set('tell.fact', tellFact);
*
* app.handleRequest(actionMap);
*
* @return RichResponse created in Dialogflow. If no RichResponse was
* created, an empty RichResponse is returned.
* @dialogflow
*/
getIncomingRichResponse(): RichResponse;
/**
* Returns the List constructed in Dialogflow response builder.
*
* @example
* const app = new App({request: req, response: res});
*
* function pickOption (app) {
* if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) {
* app.askWithList('Which of these looks good?',
* app.getIncomingList().addItems(
* app.buildOptionItem('another_choice', ['Another choice']).
* setTitle('Another choice')));
* } else {
* app.ask('What would you like?');
* }
* }
*
* const actionMap = new Map();
* actionMap.set('pick.option', pickOption);
*
* app.handleRequest(actionMap);
*
* @return List created in Dialogflow. If no List was created, an empty
* List is returned.
* @dialogflow
*/
getIncomingList(): List;
/**
* Returns the Carousel constructed in Dialogflow response builder.
*
* @example
* const app = new App({request: req, response: res});
*
* function pickOption (app) {
* if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) {
* app.askWithCarousel('Which of these looks good?',
* app.getIncomingCarousel().addItems(
* app.buildOptionItem('another_choice', ['Another choice']).
* setTitle('Another choice').setDescription('Choose me!')));
* } else {
* app.ask('What would you like?');
* }
* }
*
* const actionMap = new Map();
* actionMap.set('pick.option', pickOption);
*
* app.handleRequest(actionMap);
*
* @return Carousel created in Dialogflow. If no Carousel was created,
* an empty Carousel is returned.
* @dialogflow
*/
getIncomingCarousel(): Carousel;
/**
* Returns the option key user chose from options response.
*
* @example
* const app = new App({request: req, response: res});
*
* function pickOption (app) {
* if (app.hasSurfaceCapability(app.SurfaceCapabilities.SCREEN_OUTPUT)) {
* app.askWithCarousel('Which of these looks good?',
* app.getIncomingCarousel().addItems(
* app.buildOptionItem('another_choice', ['Another choice']).
* setTitle('Another choice').setDescription('Choose me!')));
* } else {
* app.ask('What would you like?');
* }
* }
*
* function optionPicked (app) {
* app.ask('You picked ' + app.getSelectedOption());
* }
*
* const actionMap = new Map();
* actionMap.set('pick.option', pickOption);
* actionMap.set('option.picked', optionPicked);
*
* app.handleRequest(actionMap);
*
* @return Option key of selected item. Null if no option selected or
* if current intent is not OPTION intent.
* @dialogflow
*/
getSelectedOption(): string;
/**
* Asks to collect the user's input.
* {@link https://developers.google.com/actions/policies/general-policies#user_experience|The guidelines when prompting the user for a response must be followed at all times}.
*
* NOTE: Due to a bug, if you specify the no-input prompts,
* the mic is closed after the 3rd prompt, so you should use the 3rd prompt
* for a bye message until the bug is fixed.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* const WELCOME_INTENT = 'input.welcome';
* const NUMBER_INTENT = 'input.number';
*
* function welcomeIntent (app) {
* app.ask('Welcome to action snippets! Say a number.',
* ['Say any number', 'Pick a number', 'We can stop here. See you soon.']);
* }
*
* function numberIntent (app) {
* const number = app.getArgument(NUMBER_ARGUMENT);
* app.tell('You said ' + number);
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(NUMBER_INTENT, numberIntent);
* app.handleRequest(actionMap);
*
* @param inputPrompt The input prompt
* response.
* @param noInputs Array of re-prompts when the user does not respond (max 3).
* @return HTTP response.
* @dialogflow
*/
ask(inputPrompt: string | SimpleResponse | RichResponse, noInputs?: string[]): express.Response | null;
/**
* Asks to collect the user's input with a list.
*
* @example
* const app = new DialogflowApp({request, response});
* const WELCOME_INTENT = 'input.welcome';
* const OPTION_INTENT = 'option.select';
*
* function welcomeIntent (app) {
* app.askWithList('Which of these looks good?',
* app.buildList('List title')
* .addItems([
* app.buildOptionItem(SELECTION_KEY_ONE,
* ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2'])
* .setTitle('Title of First List Item'),
* app.buildOptionItem(SELECTION_KEY_TWO,
* ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2'])
* .setTitle('Title of Second List Item'),
* ]));
* }
*
* function optionIntent (app) {
* if (app.getSelectedOption() === SELECTION_KEY_ONE) {
* app.tell('Number one is a great choice!');
* } else {
* app.tell('Number two is a great choice!');
* }
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(OPTION_INTENT, optionIntent);
* app.handleRequest(actionMap);
*
* @param inputPrompt The input prompt
* response.
* @param.list List built with {@link AssistantApp#buildList|buildList}
* @return HTTP response.
* @dialogflow
*/
askWithList(inputPrompt: string | RichResponse | SimpleResponse, list: List): express.Response | null;
/**
* Asks to collect the user's input with a carousel.
*
* @example
* const app = new DialogflowApp({request, response});
* const WELCOME_INTENT = 'input.welcome';
* const OPTION_INTENT = 'option.select';
*
* function welcomeIntent (app) {
* app.askWithCarousel('Which of these looks good?',
* app.buildCarousel()
* .addItems([
* app.buildOptionItem(SELECTION_KEY_ONE,
* ['synonym of KEY_ONE 1', 'synonym of KEY_ONE 2'])
* .setTitle('Number one'),
* app.buildOptionItem(SELECTION_KEY_TWO,
* ['synonym of KEY_TWO 1', 'synonym of KEY_TWO 2'])
* .setTitle('Number two'),
* ]));
* }
*
* function optionIntent (app) {
* if (app.getSelectedOption() === SELECTION_KEY_ONE) {
* app.tell('Number one is a great choice!');
* } else {
* app.tell('Number two is a great choice!');
* }
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(OPTION_INTENT, optionIntent);
* app.handleRequest(actionMap);
*
* @param inputPrompt The input prompt
* response.
* @param carousel Carousel built with
* {@link AssistantApp#buildCarousel|buildCarousel}.
* @return HTTP response.
* @dialogflow
*/
askWithCarousel(inputPrompt: string | RichResponse | SimpleResponse, carousel: Carousel): express.Response | null;
/**
* Tells the Assistant to render the speech response and close the mic.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* const WELCOME_INTENT = 'input.welcome';
* const NUMBER_INTENT = 'input.number';
*
* function welcomeIntent (app) {
* app.ask('Welcome to action snippets! Say a number.');
* }
*
* function numberIntent (app) {
* const number = app.getArgument(NUMBER_ARGUMENT);
* app.tell('You said ' + number);
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(NUMBER_INTENT, numberIntent);
* app.handleRequest(actionMap);
*
* @param speechResponse Final response.
* Spoken response can be SSML.
* @return The response that is sent back to Assistant.
* @dialogflow
*/
tell(speechResponse: string | SimpleResponse | RichResponse): express.Response | null;
/**
* Set a new context for the current intent.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* const CONTEXT_NUMBER = 'number';
* const NUMBER_ARGUMENT = 'myNumber';
*
* function welcomeIntent (app) {
* app.setContext(CONTEXT_NUMBER);
* app.ask('Welcome to action snippets! Say a number.');
* }
*
* function numberIntent (app) {
* const number = app.getArgument(NUMBER_ARGUMENT);
* app.tell('You said ' + number);
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(NUMBER_INTENT, numberIntent);
* app.handleRequest(actionMap);
*
* @param name Name of the context. Dialogflow converts to lowercase.
* @param [lifespan=1] Context lifespan.
* @param parameters Context JSON parameters.
* @return Null if the context name is not defined.
* @dialogflow
*/
setContext(name: string, lifespan?: number, parameters?: any): null | undefined;
/**
* Returns the incoming contexts for this intent.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* const CONTEXT_NUMBER = 'number';
* const NUMBER_ARGUMENT = 'myNumber';
*
* function welcomeIntent (app) {
* app.setContext(CONTEXT_NUMBER);
* app.ask('Welcome to action snippets! Say a number.');
* }
*
* function numberIntent (app) {
* let contexts = app.getContexts();
* // contexts === [{
* // name: 'number',
* // lifespan: 0,
* // parameters: {
* // myNumber: '23',
* // myNumber.original: '23'
* // }
* // }]
* const number = app.getArgument(NUMBER_ARGUMENT);
* app.tell('You said ' + number);
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(NUMBER_INTENT, numberIntent);
* app.handleRequest(actionMap);
*
* @return Empty if no active contexts.
* @dialogflow
*/
getContexts(): Context[];
/**
* Returns the incoming context by name for this intent.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* const CONTEXT_NUMBER = 'number';
* const NUMBER_ARGUMENT = 'myNumber';
*
* function welcomeIntent (app) {
* app.setContext(CONTEXT_NUMBER);
* app.ask('Welcome to action snippets! Say a number.');
* }
*
* function numberIntent (app) {
* let context = app.getContext(CONTEXT_NUMBER);
* // context === {
* // name: 'number',
* // lifespan: 0,
* // parameters: {
* // myNumber: '23',
* // myNumber.original: '23'
* // }
* // }
* const number = app.getArgument(NUMBER_ARGUMENT);
* app.tell('You said ' + number);
* }
*
* const actionMap = new Map();
* actionMap.set(WELCOME_INTENT, welcomeIntent);
* actionMap.set(NUMBER_INTENT, numberIntent);
* app.handleRequest(actionMap);
*
* @param name The name of the Context to retrieve.
* @return Context value matching name
* or null if no matching context.
* @dialogflow
*/
getContext(name: string): object;
/**
* Gets the user's raw input query.
*
* @example
* const app = new DialogflowApp({request: request, response: response});
* app.tell('You said ' + app.getRawInput());
*
* @return User's raw query or null if no value.
* @dialogflow
*/
getRawInput(): string;
}
+24
View File
@@ -0,0 +1,24 @@
// Type definitions for actions-on-google 1.6
// Project: https://github.com/actions-on-google/actions-on-google-nodejs
// Definitions by: Joel Hegg <https://github.com/joelhegg>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
/**
* The Actions on Google client library.
* https://developers.google.com/actions/
*/
import * as Transactions from './transactions';
import * as Responses from './response-builder';
export { AssistantApp } from './assistant-app';
export { ActionsSdkApp, ActionsSdkAppOptions } from './actions-sdk-app';
export { DialogflowApp, DialogflowAppOptions } from './dialogflow-app';
export { Transactions };
export { Responses };
// Backwards compatibility
export { AssistantApp as Assistant } from './assistant-app';
export { ActionsSdkApp as ActionsSdkAssistant } from './actions-sdk-app';
export { DialogflowApp as ApiAiAssistant } from './dialogflow-app';
export { DialogflowApp as ApiAiApp } from './dialogflow-app';
+404
View File
@@ -0,0 +1,404 @@
/**
* A collection of response builders.
*/
import { OrderUpdate } from './transactions';
/**
* Simple Response type.
*/
export interface SimpleResponse {
/** Speech to be spoken to user. SSML allowed. */
speech: string;
/** Optional text to be shown to user */
displayText?: string;
}
/**
* Suggestions to show with response.
*/
export interface Suggestion {
/** Text of the suggestion. */
title: string;
}
/**
* Link Out Suggestion. Used in rich response as a suggestion chip which, when
* selected, links out to external URL.
*/
export interface LinkOutSuggestion {
/** Text shown on the suggestion chip. */
title: string;
/** String URL to open. */
url: string;
}
/**
* Image type shown on visual elements.
*/
export interface Image {
/** Image source URL. */
url: string;
/** Text to replace for image for accessibility. */
accessibilityText: string;
/** Width of the image. */
width: number;
/** Height of the image. */
height: number;
}
/**
* Basic Card Button. Shown below basic cards. Open a URL when selected.
*/
export interface Button {
/** Text shown on the button. */
title: string;
/** Action to take when selected. */
openUrlAction: {
/** String URL to open. */
url: string;
};
}
/**
* Option info. Provides unique identifier for a given OptionItem.
*/
export interface OptionInfo {
/** Unique string ID for this option. */
key: string;
/** Synonyms that can be used by the user to indicate this option if they do not use the key. */
synonyms: string[];
}
export interface StructuredResponse {
orderUpdate: OrderUpdate;
}
export interface RichResponseItemBasicCard {
basicCard: BasicCard;
}
export interface RichResponseItemSimpleResponse {
simpleResponse: SimpleResponse;
}
export interface RichResponseItemStructuredResponse {
structuredResponse: StructuredResponse;
}
export type RichResponseItem = RichResponseItemBasicCard | RichResponseItemSimpleResponse | RichResponseItemStructuredResponse;
/**
* Class for initializing and constructing Rich Responses with chainable interface.
*/
export class RichResponse {
/**
* Constructor for RichResponse. Accepts optional RichResponse to clone.
*
* @param richResponse Optional RichResponse to clone.
*/
constructor(richResponse?: RichResponse);
/**
* Ordered list of either SimpleResponse objects or BasicCard objects.
* First item must be SimpleResponse. There can be at most one card.
*/
items: RichResponseItem[];
/**
* Ordered list of text suggestions to display. Optional.
*/
suggestions: Suggestion[];
/**
* Link Out Suggestion chip for this rich response. Optional.
*/
linkOutSuggestion?: LinkOutSuggestion;
/**
* Adds a SimpleResponse to list of items.
*
* @param simpleResponse Simple response to present to
* user. If just a string, display text will not be set.
* @return Returns current constructed RichResponse.
*/
addSimpleResponse(simpleResponse: string | SimpleResponse): RichResponse;
/**
* Adds a BasicCard to list of items.
*
* @param basicCard Basic card to include in response.
* @return Returns current constructed RichResponse.
*/
addBasicCard(basicCard: BasicCard): RichResponse;
/**
* Adds a single suggestion or list of suggestions to list of items.
*
* @param suggestions Either a single string suggestion
* or list of suggestions to add.
* @return Returns current constructed RichResponse.
*/
addSuggestions(suggestions: string | string[]): RichResponse;
/**
* Returns true if the given suggestion text is valid to be added to the suggestion list. A valid
* text string is not longer than 25 characters.
* @param suggestionText Text to validate as suggestion.
* @return True if the text is valid, false otherwise.s
*/
isValidSuggestionText(suggestionText: string): boolean;
/**
* Sets the suggestion link for this rich response.
*
* @param destinationName Name of the link out destination.
* @param suggestionUrl - String URL to open when suggestion is used.
* @return Returns current constructed RichResponse.
*/
addSuggestionLink(destinationName: string, suggestionUrl: string): RichResponse;
/**
* Adds an order update to this response. Use after a successful transaction
* decision to confirm the order.
*
* @param orderUpdate OrderUpdate object to add.
* @return Returns current constructed RichResponse.
*/
addOrderUpdate(orderUpdate: OrderUpdate): RichResponse;
}
/**
* Class for initializing and constructing Basic Cards with chainable interface.
*/
export class BasicCard {
/**
* Constructor for BasicCard. Accepts optional BasicCard to clone.
*
* @param basicCard Optional BasicCard to clone.
*/
constructor(basicCard?: BasicCard);
/**
* Title of the card. Optional.
*/
title?: string;
/**
* Body text to show on the card. Required, unless image is present.
*/
formattedText: string;
/**
* Subtitle of the card. Optional.
*/
subtitle?: string;
/**
* Image to show on the card. Optional.
*/
image?: Image;
/**
* Ordered list of buttons to show below card. Optional.
*/
buttons: Button[];
/**
* Sets the title for this Basic Card.
*
* @param title Title to show on card.
* @return Returns current constructed BasicCard.
*/
setTitle(title: string): BasicCard;
/**
* Sets the subtitle for this Basic Card.
*
* @param subtitle Subtitle to show on card.
* @return Returns current constructed BasicCard.
*/
setSubtitle(subtitle: string): BasicCard;
/**
* Sets the body text for this Basic Card.
*
* @param bodyText Body text to show on card.
* @return Returns current constructed BasicCard.
*/
setBodyText(bodyText: string): BasicCard;
/**
* Sets the image for this Basic Card.
*
* @param url Image source URL.
* @param accessibilityText Text to replace for image for
* accessibility.
* @param width Width of the image.
* @param height Height of the image.
* @return Returns current constructed BasicCard.
*/
setImage(url: string, accessibilityText: string, width?: number, height?: number): BasicCard;
/**
* Adds a button below card.
*
* @param text Text to show on button.
* @param url URL to open when button is selected.
* @return Returns current constructed BasicCard.
*/
addButton(text: string, url: string): BasicCard;
}
/**
* Class for initializing and constructing Lists with chainable interface.
*/
export class List {
/**
* Constructor for List. Accepts optional List to clone, string title, or
* list of items to copy.
*
* @param list Either a list to clone, a title
* to set for a new List, or an array of OptionItem to initialize a new
* list.
*/
constructor(list?: List | string | OptionItem[]);
/**
* Title of the list. Optional.
*/
title?: string;
/**
* List of 2-20 items to show in this list. Required.
*/
items: OptionItem[];
/**
* Sets the title for this List.
*
* @param title Title to show on list.
* @return Returns current constructed List.
*/
setTitle(title: string): List;
/**
* Adds a single item or list of items to the list.
*
* @param optionItems OptionItems to add.
* @return Returns current constructed List.
*/
addItems(optionItems: OptionItem | OptionItem[]): List;
}
/**
* Class for initializing and constructing Carousel with chainable interface.
*/
export class Carousel {
/**
* Constructor for Carousel. Accepts optional Carousel to clone or list of
* items to copy.
*
* @param carousel Either a carousel to clone
* or an array of OptionItem to initialize a new carousel
*/
constructor(carousel?: Carousel | OptionItem[]);
/**
* List of 2-20 items to show in this carousel. Required.
*/
items: OptionItem[];
/**
* Adds a single item or list of items to the carousel.
*
* @param optionItems OptionItems to add.
* @return Returns current constructed Carousel.
*/
addItems(optionItems: OptionItem | OptionItem[]): Carousel;
}
/**
* Class for initializing and constructing Option Items with chainable interface.
*/
export class OptionItem {
/**
* Constructor for OptionItem. Accepts optional OptionItem to clone.
*
* @param optionItem Optional OptionItem to clone.
*/
constructor(optionItem?: OptionItem);
/**
* Option info of the option item. Required.
*/
optionInfo: OptionInfo;
/**
* Title of the option item. Required.
*/
title: string;
/**
* Description text of the item. Optional.
*/
description?: string;
/**
* Image to show on item. Optional.
*/
image?: Image;
/**
* Sets the title for this Option Item.
*
* @param title Title to show on item.
* @return Returns current constructed OptionItem.
*/
setTitle(title: string): OptionItem;
/**
* Sets the description for this Option Item.
*
* @param description Description to show on item.
* @return Returns current constructed OptionItem.
*/
setDescription(description: string): OptionItem;
/**
* Sets the image for this Option Item.
*
* @param url Image source URL.
* @param accessibilityText Text to replace for image for
* accessibility.
* @param width Width of the image.
* @param height Height of the image.
* @return Returns current constructed OptionItem.
*/
setImage(url: string, accessibilityText: string, width?: number, height?: number): OptionItem;
/**
* Sets the key for the OptionInfo of this Option Item. This will be returned
* as an argument in the resulting actions.intent.OPTION intent.
*
* @param key Key to uniquely identify this item.
* @return Returns current constructed OptionItem.
*/
setKey(key: string): OptionItem;
/**
* Adds a single synonym or list of synonyms to item.
*
* @param synonyms Either a single string synonyms
* or list of synonyms to add.
* @return Returns current constructed OptionItem.
*/
addSynonyms(synonyms: string | string[]): OptionItem;
}
/**
* Check if given text contains SSML.
* @param text Text to check.
* @return True if text contains SSML, false otherwise.
*/
export function isSsml(text: string): boolean;
File diff suppressed because it is too large Load Diff
+28
View File
@@ -0,0 +1,28 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"assistant-app.d.ts",
"actions-sdk-app.d.ts",
"dialogflow-app.d.ts",
"response-builder.d.ts",
"transactions.d.ts",
"actions-on-google-tests.ts"
]
}
+3
View File
@@ -0,0 +1,3 @@
import addZero from "add-zero";
addZero(5, 2);
+6
View File
@@ -0,0 +1,6 @@
// Type definitions for add-zero 1.0
// Project: https://github.com/rafaelrinaldi/add-zero#readme
// Definitions by: Giles Roadnight <https://github.com/Roaders>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export default function addZero(value: string | number, digits?: number): string;
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"add-zero-tests.ts"
]
}
+10 -2
View File
@@ -1,5 +1,4 @@
// Global
const threeCamera = new AFRAME.THREE.Camera();
AFRAME.TWEEN.Easing;
@@ -42,9 +41,18 @@ entity.addEventListener('child-detached', (event) => {
const Component = AFRAME.registerComponent('test', {});
// Scene
const scene = document.querySelector('a-scene');
scene.hasLoaded;
// System
const system = scene.systems['systemName'];
// Register Custom Geometry
AFRAME.registerGeometry('a-test-geometry', {
schema: {
groupIndex: { default: 0 }
},
init(data) {
this.geometry = new THREE.Geometry();
}
});
+9 -4
View File
@@ -1,6 +1,7 @@
// Type definitions for AFRAME 0.5
// Type definitions for AFRAME 0.7
// Project: https://aframe.io/
// Definitions by: Paul Shannon <https://github.com/devpaul>
// Roberto Ritger <https://github.com/bertoritger>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -40,7 +41,7 @@ declare namespace AFrame {
primitives: { [ key: string ]: Entity };
registerComponent(name: string, component: ComponentDefinition): ComponentConstructor;
registerElement(name: string, element: ANode): void;
registerGeometry(name: string, geometery: THREE.Geometry): Geometry;
registerGeometry(name: string, geometry: GeometryDefinition): Geometry;
registerPrimitive(name: string, primitive: PrimitiveDefinition): void;
registerShader(name: string, shader: any): void;
registerSystem(name: string, definition: SystemDefinition): void;
@@ -101,7 +102,7 @@ declare namespace AFrame {
name: string;
schema: Schema;
init(): void;
init(data?: any): void;
pause(): void;
play(): void;
remove(): void;
@@ -124,7 +125,7 @@ declare namespace AFrame {
multiple?: boolean;
schema?: Schema;
init?(): void;
init?(data?: any): void;
pause?(): void;
play?(): void;
remove?(): void;
@@ -222,6 +223,10 @@ declare namespace AFrame {
[ key: string ]: any;
}
interface GeometryDefinition extends ComponentDefinition {
geometry?: THREE.Geometry;
}
interface GeometryDescriptor {
Geometry: Geometry;
schema: Schema;
+2 -2
View File
@@ -113,8 +113,8 @@ declare class Agenda extends EventEmitter {
* @param options The options for the job.
* @param handler The handler to execute.
*/
define(name: string, handler: (job?: Agenda.Job, done?: (err?: Error) => void) => void): void;
define(name: string, options: Agenda.JobOptions, handler: (job?: Agenda.Job, done?: (err?: Error) => void) => void): void;
define(name: string, handler: (job: Agenda.Job, done: (err?: Error) => void) => void): void;
define(name: string, options: Agenda.JobOptions, handler: (job: Agenda.Job, done: (err?: Error) => void) => void): void;
/**
* Runs job name at the given interval. Optionally, data and options can be passed in.
+779 -18
View File
@@ -4,15 +4,85 @@
// Huw <https://github.com/hoo29>
// pascalwhoop <https://github.com/pascalwhoop>
// Ben <https://github.com/blforce>
// rk-7 <https://github.com/rk-7>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
export function handler<T>(event: RequestBody<T>, context: Context, callback?: (err: any, response: any) => void): AlexaObject<T>;
export function CreateStateHandler(state: string, obj: any): any;
export let StateString: string;
export type ConfirmationStatuses = "NONE" | "DENIED" | "CONFIRMED";
export type DialogStates = "STARTED" | "IN_PROGRESS" | "COMPLETED";
export type ListItemObjectStatus = "active" | "completed";
export type ListObjectState = "active" | "archived";
export type ImageSourceSize = "X_SMALL" | "SMALL" | "MEDIUM" | "LARGE" | "X_LARGE";
export type TemplateBackButtonVisibility = "HIDDEN" | "VISIBLE";
export type TemplateType = "BodyTemplate1" | "BodyTemplate2" | "BodyTemplate3" | "BodyTemplate6" | "BodyTemplate6" | "ListTemplate1" | "ListTemplate2";
export type AudioPlayerActivity = "IDLE" | "PAUSED" | "PLAYING" | "BUFFER_UNDERRUN" | "FINISHED" | "STOPPED";
export type CardType = "Standard" | "Simple" | "LinkAccount" | "AskForPermissionsConsent";
export type HintType = "PlainText";
export type DirectiveTypes = "AudioPlayer.Play" | "AudioPlayer.Stop" | "AudioPlayer.ClearQueue" | "Display.RenderTemplate" | "Hint" | "VideoApp.Launch";
export type TextContentType = "PlainText" | "RichText";
//#region Types
export interface CardImage {
/**
* Recommended size (in px): 720w x 480h
*/
smallImageUrl: string;
/**
* Recommended size (in px): 1200w x 800h
*/
largeImageUrl: string;
}
export interface ImageSource {
url: string;
widthPixels?: number;
heightPixels?: number;
/**
* Recommended sizes for the following dimensions (in px):
* 480 x 320 for X_SMALL,
* 720 x 480 for SMALL,
* 960 x 640 for MEDIUM,
* 1200 x 800 for LARGE,
* 1920 x 1280 for X_LARGE
*/
size?: ImageSourceSize;
}
export interface Image {
contentDescription: string;
sources: ImageSource[];
}
export interface TextField {
text: string;
type: string;
}
export interface TextContent {
primaryText?: TextField;
secondaryText?: TextField;
tertiaryText?: TextField;
}
export interface ListItem {
image?: Image;
token: string;
textContent?: TextContent;
}
export interface Template {
title?: string;
token: string;
backgroundImage?: Image;
/**
* Visibility of the back button.
*/
backButton?: TemplateBackButtonVisibility;
/**
* Template type.
*/
type: TemplateType;
image?: Image;
listItems?: ListItem[];
}
export interface AlexaObject<T> extends Handler<T> {
_event: any;
@@ -38,12 +108,16 @@ export interface Handler<T> {
emitWithState: any;
state: any;
handler: any;
i18n: any;
locale: any;
event: RequestBody<T>;
attributes: any;
context: any;
callback: (param: any) => void;
name: any;
isOverriden: any;
t: (token: string, ...args: any[]) => void;
response: ResponseBuilder;
}
export interface Context {
@@ -55,8 +129,28 @@ export interface Context {
functionVersion: string;
invokeid: string;
awsRequestId: string;
System?: System;
AudioPlayer?: AudioPlayer;
}
export interface Application {
applicationId: string;
[key: string]: string;
}
export interface System {
apiAccessToken: string;
apiEndpoint: string;
application: Application;
device: any;
user: any;
}
export interface AudioPlayer {
token: string;
offsetInMilliseconds: number;
/**
* Player activity
*/
playerActivity: AudioPlayerActivity;
}
export interface RequestBody<T> {
version: string;
session: Session;
@@ -66,20 +160,22 @@ export interface RequestBody<T> {
export interface Session {
new: boolean;
sessionId: string;
attributes: any;
application: SessionApplication;
attributes: { [key: string]: any };
application: Application;
user: SessionUser;
}
export interface SessionApplication {
applicationId: string;
}
export interface SessionUser {
userId: string;
accessToken?: string;
permissions: Permissions;
}
export interface Permissions {
/**
* @deprecated
*/
consentToken: string;
[key: string]: string;
}
export interface LaunchRequest extends Request { }
export interface IntentRequest extends Request {
@@ -144,7 +240,8 @@ export interface Response {
outputSpeech?: OutputSpeech;
card?: Card;
reprompt?: Reprompt;
shouldEndSession: boolean;
directives?: any;
shouldEndSession?: boolean;
}
export interface OutputSpeech {
@@ -154,18 +251,682 @@ export interface OutputSpeech {
}
export interface Card {
type: "Simple" | "Standard" | "LinkAccount";
type: CardType;
title?: string;
content?: string;
text?: string;
image?: Image;
}
export interface Image {
smallImageUrl: string;
largeImageUrl: string;
image?: CardImage;
}
export interface Reprompt {
outputSpeech: OutputSpeech;
}
export interface ApiClientOptions {
hostname: string;
port: string;
path: string;
protocol: string;
headers: string;
method: string;
}
export interface ApiClientResponse {
statusCode: string;
statusText: string;
body: object;
headers: object;
}
/**
* Todo-ListItem class
* Refer https://developer.amazon.com/docs/custom-skills/access-the-alexa-shopping-and-to-do-lists.html
*/
export interface ListItemObject {
/**
* item id (String, limit 60 characters)
*/
id: string;
/**
* item value (String, limit is 256 characters)
*/
value: string;
/**
* item status
*/
status?: ListItemObjectStatus;
/**
* item version (Positive integer)
*/
version?: number | string;
/**
* created time (ISO 8601 time format with time zone)
*/
createdTime: Date;
/**
* updated time (ISO 8601 time format with time zone)
*/
updatedTime: Date;
/**
* URL to retrieve the item (String)
*/
href?: string;
}
/**
* Todo-List class
* Refer https://developer.amazon.com/docs/custom-skills/access-the-alexa-shopping-and-to-do-lists.html
*/
export interface ListObject {
/**
* list id (String)
*/
listId: string;
/**
* list name (String)
*/
name: string;
/**
* state
* "active" or "archived" (Enum)
*/
state?: ListObjectState;
/**
* Possibly status of the list (or state?)
* Fetched from commit eebba0d at https://github.com/alexa/alexa-skills-kit-sdk-for-nodejs/
* File path: alexa-skills-kit-sdk-for-nodejs/lib/services/listManagementService.js
*/
status?: string;
/**
* list version (Positive integer)
*/
version?: number;
/**
* Urls to active and completed items
* href is lint to the items having certain status.
* The status can be "active" or "completed".
*/
statusMap: { href: string; status: ListItemObjectStatus; };
/**
* Items that belong to this list.
*/
items: ListItemObject[];
}
//#endregion
//#region templateBuilders
/**
* Generates templates for Echo Show device.
*/
export namespace templateBuilders {
interface SetTextContent<T extends TemplateBuilder<T>> {
setTextContent(primaryText: TextField, secondaryText?: TextField, tertiaryText?: TextField): T;
}
interface SetListItems<T extends TemplateBuilder<T>> {
setListItems(listItems: ListItem[]): T;
}
/**
* Refer https://developer.amazon.com/docs/custom-skills/display-interface-reference.html#image-sizes
*/
abstract class TemplateBuilder<T extends TemplateBuilder<T>> {
template: Template;
constructor();
/**
* Sets the title of the template
* @param title title
* @returns TemplateBuilder
*/
setTitle(title: string): T;
/**
* Sets the token of the template
* @param token token
* @returns TemplateBuilder
*/
setToken(token: string): T;
/**
* Sets the background image of the template
* @param image image
* @returns TemplateBuilder
*/
setBackgroundImage(image: Image): T;
/**
* Sets the backButton behavior
* @param backButtonBehavior "VISIBLE" or "HIDDEN"
* @returns TemplateBuilder
*/
setBackButtonBehavior(backButtonBehavior: string): T;
/**
* Builds the template JSON object
* @returns Template
*/
build(): Template;
}
/**
* Used to build a list of ListItems for ListTemplate
*/
class ListItemBuilder {
constructor();
items: ListItem[];
/**
* Add an item to the list of template
* @param image image
* @param token token
* @param primaryText primaryText
* @param secondaryText secondaryText
* @param tertiaryText tertiaryText
*/
addItem(image: Image, token: string, primaryText: TextField, secondaryText?: TextField, tertiaryText?: TextField): ListItemBuilder;
build(): ListItem[];
}
/**
* Used to create BodyTemplate1 objects
*/
class BodyTemplate1Builder extends TemplateBuilder<BodyTemplate1Builder> implements SetTextContent<BodyTemplate1Builder> {
constructor();
/**
* Sets the text content for the template
* @param primaryText primaryText
* @param secondaryText secondaryText
* @param tertiaryText tertiaryText
* @returns BodyTemplate1Builder
*/
setTextContent(primaryText: TextField, secondaryText?: TextField, tertiaryText?: TextField): BodyTemplate1Builder;
}
/**
* Used to create BodyTemplate2 objects
*/
class BodyTemplate2Builder extends TemplateBuilder<BodyTemplate2Builder> implements SetTextContent<BodyTemplate2Builder> {
constructor();
/**
* Sets the image for the template
* @param image image
* @returns BodyTemplate2Builder
*/
setImage(image: Image): BodyTemplate2Builder;
/**
* Sets the text content for the template
* @param primaryText primaryText
* @param secondaryText secondaryText
* @param tertiaryText tertiaryText
* @returns BodyTemplate2Builder
*/
setTextContent(primaryText: TextField, secondaryText?: TextField, tertiaryText?: TextField): BodyTemplate2Builder;
}
/**
* Used to create BodyTemplate3 objects
*/
class BodyTemplate3Builder extends TemplateBuilder<BodyTemplate3Builder> implements SetTextContent<BodyTemplate3Builder> {
constructor();
/**
* Sets the image for the template
* @param image image
* @returns BodyTemplate3Builder
*/
setImage(image: Image): BodyTemplate3Builder;
/**
* Sets the text content for the template
* @param primaryText primaryText
* @param secondaryText secondaryText
* @param tertiaryText tertiaryText
* @returns BodyTemplate3Builder
*/
setTextContent(primaryText: TextField, secondaryText?: TextField, tertiaryText?: TextField): BodyTemplate3Builder;
}
/**
* Used to create BodyTemplate6 objects
*/
class BodyTemplate6Builder extends TemplateBuilder<BodyTemplate6Builder> implements SetTextContent<BodyTemplate6Builder> {
constructor();
/**
* Sets the image for the template
* @param image image
* @returns BodyTemplate6Builder
*/
setImage(image: Image): BodyTemplate6Builder;
/**
* Sets the text content for the template
* @param primaryText primaryText
* @param secondaryText secondaryText
* @param tertiaryText tertiaryText
* @returns BodyTemplate6Builder
*/
setTextContent(primaryText: TextField, secondaryText?: TextField, tertiaryText?: TextField): BodyTemplate6Builder;
}
/**
* Used to create BodyTemplate7 objects
*/
class BodyTemplate7Builder extends TemplateBuilder<BodyTemplate7Builder> {
constructor();
/**
* Sets the image for the template
* @param image image
* @returns BodyTemplate7Builder
*/
setImage(image: Image): BodyTemplate7Builder;
}
/**
* Used to create ListTemplate1 objects
*/
class ListTemplate1Builder extends TemplateBuilder<ListTemplate1Builder> implements SetListItems<ListTemplate1Builder> {
constructor();
/**
* Set the items for the list
* @param listItems listItems
* @returns ListTemplate1Builder
*/
setListItems(listItems: ListItem[]): ListTemplate1Builder;
}
/**
* Used to create ListTemplate2 objects
*/
class ListTemplate2Builder extends TemplateBuilder<ListTemplate2Builder> implements SetListItems<ListTemplate2Builder> {
constructor();
/**
* Set the items for the list
* @param listItems listItems
* @returns ListTemplate2Builder
*/
setListItems(listItems: ListItem[]): ListTemplate2Builder;
}
}
//#endregion
//#region services
export namespace services {
interface ApiClient {
/**
* Make a POST API call to the specified uri with headers and optional body
* @param uri http(s?) endpoint to call
* @param headers Key value pair of headers
* @param body post body to send
* @returns Promise<ApiClientResponse>
*/
post(uri: string, headers: object, body?: string): Promise<ApiClientResponse>;
/**
* Make a PUT API call to the specified uri with headers and optional body
* @param uri http(s?) endpoint to call
* @param headers Key value pair of headers
* @param body post body to send
* @returns Promise<ApiClientResponse>
*/
put(uri: string, headers: object, body?: string): Promise<ApiClientResponse>;
/**
* Make a GET API call to the specified uri with headers
* @param uri http(s?) endpoint to call
* @param headers key value pair of headers
* @returns Promise<ApiClientResponse>
*/
get(uri: string, headers: object): Promise<ApiClientResponse>;
/**
* Make a DELETE API call to the specified uri with headers
* @param uri http(s?) endpoint to call
* @param headers key value pair of headers
* @returns Promise<ApiClientResponse>
*/
delete(uri: string, headers: object): Promise<ApiClientResponse>;
}
class DeviceAddressService {
/**
* Create an instance of DeviceAddressService
* @param [apiClient=new ApiClient()] ApiClient
*/
constructor(apiClient: ApiClient);
/**
* Get full address information from Alexa Device Address API
* @param deviceId deviceId from Alexa request
* @param apiEndpoint API apiEndpoint from Alexa request
* @param token bearer token for device address permission
* @returns Promise<object>
*/
getFullAddress(deviceId: string, apiEndpoint: string, token: string): Promise<object>;
/**
* Get country and postal information from Alexa Device Address API
* @param deviceId deviceId from Alexa request
* @param apiEndpoint API apiEndpoint from Alexa request
* @param token bearer token for device address permission
* @returns Promise<object>
*/
getCountryAndPostalCode(deviceId: string, apiEndpoint: string, token: string): Promise<object>;
}
class DirectiveService {
/**
* Creates an instance of DirectiveService.
* @param [apiClient=new ApiClient()] ApiClient
*/
constructor(apiClient: ApiClient);
/**
* Send the specified directiveObj to Alexa directive service
*
* @param directive directive to send to service
* @param apiEndpoint API endpoint from Alexa request
* @param token bearer token for directive service
* @returns Promise<void>
*/
enqueue(directive: object, apiEndpoint: string, token: string): Promise<void>;
}
class ListManagementService {
/**
* Create an instance of ListManagementService
* @param apiClient apiClient
*/
constructor(apiClient: ApiClient);
/**
* Set apiEndpoint address, default is "https://api.amazonalexa.com"
* @param apiEndpoint apiEndpoint
* @returns void
*/
setApiEndpoint(apiEndpoint: string): void;
/**
* Get currently set apiEndpoint address
* @returns string
*/
getApiEndpoint(): string;
/**
* Retrieve the metadata for all customer lists, including the customer's default lists
* @param token bearer token for list management permission
* @returns Promise<object>
*/
getListsMetadata(token: string): Promise<object>;
/**
* Create a custom list. The new list name must be different than any existing list name
* @param listObject listObject
* @param token bearer token for list management permission
* @returns Promise<object>
*/
createList(listObject: ListObject, token: string): Promise<object>;
/**
* Retrieve list metadata including the items in the list with requested status
* @param listId unique Id associated with the list
* @param itemStatus itemsStatus can be either "active" or "completed"
* @param token bearer token for list management permission
* @returns Promise<object>
*/
getList(listId: string, itemStatus: ListItemObjectStatus, token: string): Promise<object>;
/**
* Update a custom list. Only the list name or state can be updated
* @param listId unique Id associated with the list
* @param listObject listObject
* @param token bearer token for list management permission
* @returns Promise<object>
*/
updateList(listId: string, listObject: ListObject, token: string): Promise<object>;
/**
* Delete a custom list
* @param listId unique Id associated with the list
* @param token bearer token for list management permission
* @returns Promise<object>
*/
deleteList(listId: string, token: string): Promise<object>;
/**
* Create an item in an active list or in a default list
* @param listId unique Id associated with the list
* @param listItemObject listItemObject
* @param token bearer token for list management permission
* @returns Promise<object>
*/
createListItem(listId: string, listItemObject: ListItemObject, token: string): Promise<object>;
/**
* Retrieve single item within any list by listId and itemId
* @param listId unique Id associated with the list
* @param itemId unique Id associated with the item
* @param token bearer token for list management permission
* @returns Promise<object>
*/
getListItem(listId: string, itemId: string, token: string): Promise<object>;
/**
* Update an item value or item status
* @param listId unique Id associated with the list
* @param itemId unique Id associated with the item
* @param listItemObject listItemObject
* @param token bearer token for list management permission
* @returns Promise<object>
*/
updateListItem(listId: string, itemId: string, listItemObject: ListItemObject, token: string): Promise<object>;
/**
* Delete an item in the specified list
* @param listId unique Id associated with the list
* @param itemId unique Id associated with the item
* @param token bearer token for list management permission
* @returns Promise<object>
*/
deleteListItem(listId: string, itemId: string, token: string): Promise<object>;
}
}
//#endregion
//#region ResponseBuilder
/**
* Responsible for building JSON responses as per the Alexa skills kit interface
* https://developer.amazon.com/public/solutions/alexa/alexa-skills-kit/docs/alexa-skills-kit-interface-reference#response-body-syntax
*/
export class ResponseBuilder {
constructor(alexaHandler: Handler<Request>);
/**
* Have Alexa say the provided speechOutput to the user
* @param speechOutput speechOutput
* @returns ResponseBuilder
*/
speak(speechOutput: string): ResponseBuilder;
/**
* Have alexa listen for speech from the user. If the user doesn't respond within 8 seconds
* then have alexa reprompt with the provided reprompt speech
* @param repromptSpeech repromptSpeech
* @returns ResponseBuilder
*/
listen(repromptSpeech: string): ResponseBuilder;
/**
* Render a card with the following title, content and image
* @param cardTitle cardTitle
* @param cardContent cardContent
* @param cardImage cardImage
* @returns ResponseBuilder
*/
cardRenderer(cardTitle: string, cardContent: string, cardImage: CardImage): ResponseBuilder;
/**
* Render a link account card
* @returns ResponseBuilder
*/
linkAccountCard(): ResponseBuilder;
/**
* Render a askForPermissionsConsent card
* @param permissions permissions
* @returns ResponseBuilder
*/
askForPermissionsConsentCard(permissions: [{ [key: string]: string }]): ResponseBuilder;
/**
* Creates a play, stop or clearQueue audioPlayer directive depending on the directive type passed in.
* @deprecated - use audioPlayerPlay, audioPlayerStop, audioPlayerClearQueue instead
* @param directiveType directiveType
* @param behavior behavior
* @param url url
* @param token token
* @param expectedPreviousToken expectedPreviousToken
* @param offsetInMilliseconds offsetInMilliseconds
* @returns ResponseBuilder
*/
audioPlayer(directiveType: string, behavior: string, url: string, token: string, expectedPreviousToken: string, offsetInMilliseconds: number): ResponseBuilder;
/**
* Creates an AudioPlayer play directive
* @param behavior Describes playback behavior. Accepted values:
* REPLACE_ALL: Immediately begin playback of the specified stream, and replace current and enqueued streams.
* ENQUEUE: Add the specified stream to the end of the current queue. This does not impact the currently playing stream.
* REPLACE_ENQUEUED: Replace all streams in the queue. This does not impact the currently playing stream.
* @param url Identifies the location of audio content at a remote HTTPS location.
* The audio file must be hosted at an Internet-accessible HTTPS endpoint. HTTPS is required, and the domain hosting the
* files must present a valid, trusted SSL certificate. Self-signed certificates cannot be used.
* The supported formats for the audio file include AAC/MP4, MP3, HLS, PLS and M3U. Bitrates: 16kbps to 384 kbps.
* @param token A token that represents the audio stream. This token cannot exceed 1024 characters
* @param expectedPreviousToken A token that represents the expected previous stream.
* This property is required and allowed only when the playBehavior is ENQUEUE. This is used to prevent potential race conditions
* if requests to progress through a playlist and change tracks occur at the same time.
* @param offsetInMilliseconds The timestamp in the stream from which Alexa should begin playback.
* Set to 0 to start playing the stream from the beginning. Set to any other value to start playback from that associated point in the stream
* @returns ResponseBuilder
*/
audioPlayerPlay(behavior: string, url: string, token: string, expectedPreviousToken: string, offsetInMilliseconds: number): ResponseBuilder;
/**
* Creates an AudioPlayer Stop directive - Stops the current audio Playback
* @returns ResponseBuilder
*/
audioPlayerStop(): ResponseBuilder;
/**
* Creates an AudioPlayer ClearQueue directive - clear the queue without stopping the currently playing stream,
* or clear the queue and stop any currently playing stream.
* @param clearBehavior Describes the clear queue behavior. Accepted values:
* CLEAR_ENQUEUED: clears the queue and continues to play the currently playing stream
* CLEAR_ALL: clears the entire playback queue and stops the currently playing stream (if applicable).
* @returns ResponseBuilder
*/
audioPlayerClearQueue(clearBehavior: string): ResponseBuilder;
/**
* Creates a Display RenderTemplate Directive
* Use a template builder to generate a template object
* @param template template
* @returns ResponseBuilder
*/
renderTemplate(template: Template): ResponseBuilder;
/**
* Creates a hint directive - show a hint on the screen of the echo show
* @param hintText text to show on the hint
* @param hintType (optional) Default value : PlainText
* @returns ResponseBuilder
*/
hint(hintText: string, hintType?: HintType): ResponseBuilder;
/**
* Creates a VideoApp play directive to play a video
* @param source Identifies the location of video content at a remote HTTPS location.
* The video file must be hosted at an Internet-accessible HTTPS endpoint.
* @param metadata (optional) Contains an object that provides the
* information that can be displayed on VideoApp.
* @returns ResponseBuilder
*/
playVideo(source: string, metadata?: { title: string, subtitle: string }): ResponseBuilder;
}
//#endregion
//#region directives
export namespace directives {
class VoicePlayerSpeakDirective {
header: { requestId: string };
directive: { type: string, speech: string };
/**
* Creates an instance of VoicePlayerSpeakDirective.
* @param requestId - requestId from which the call is originated from
* @param speechContent - Contents of the speech directive either in plain text or SSML.
*/
constructor(requestId: string, speechContent: string);
}
}
//#endregion
//#region utils
export namespace utils {
namespace ImageUtils {
/**
* Creates an image object with a single source
* These images may be in either JPEG or PNG formats, with the appropriate file extensions.
* An image cannot be larger than 2 MB
* You must host the images at HTTPS URLs that are publicly accessible.
* widthPixels and heightPixels are optional - Do not include them unless they are exactly correct.
* By default, for Echo Show, size takes the value X_SMALL. If the other size values are included,
* then the order of precedence for displaying images begins with X_LARGE and proceeds downward,
* which means that larger images will be downscaled for display on Echo Show if provided.
* example : ImageUtils.makeImage("https://url/to/my/img.png", 300, 400, "SMALL", "image description")
* @param url url of the image
* @param widthPixels (optional) width of the image in pixels
* @param heightPixels (optional) height of the image in pixels
* @param size size of the image (X_SMALL, SMALL, MEDIUM, LARGE, X_LARGE)
* @param description text used to describe the image in a screen reader
* @returns Image
*/
function makeImage(url: string, widthPixels?: number, heightPixels?: number, size?: ImageSourceSize, description?: string): Image;
/**
* Creates an image object with a multiple sources, source images are provided as an array of image objects
* These images may be in either JPEG or PNG formats, with the appropriate file extensions.
* An image cannot be larger than 2 MB
* You must host the images at HTTPS URLs that are publicly accessible.
* widthPixels and heightPixels are optional - Do not include them unless they are exactly correct.
* By default, for Echo Show, size takes the value X_SMALL. If the other size values are included,
* then the order of precedence for displaying images begins with X_LARGE and proceeds downward,
* which means that larger images will be downscaled for display on Echo Show if provided.
* example :
* let imgArr = [
* { "https://url/to/my/small.png", 300, 400, "SMALL" },
* { "https://url/to/my/large.png", 900, 1200, "LARGE" },
* ]
* ImageUtils.makeImage(imgArr, "image description")
*
* @param imgArr Array of Image
* @param description text used to describe the image in a screen reader
* @returns Image
*/
function makeImages(imgArr: Array<{ url: string, widthPixels?: number, heightPixels?: number, size: ImageSourceSize }>, description: string): Image;
}
/**
* Utility methods for building TextField objects
*/
namespace TextUtils {
/**
* Creates a plain TextField object with contents : text
* @param text contents of plain text object
* @returns TextField
*/
function makePlainText(text: string): TextField;
/**
* Creates a rich TextField object with contents : text
* @param text text
* @returns TextField
*/
function makeRichText(text: string): TextField;
/**
* Creates a textContent
* @param primaryText primary Text
* @param secondaryText secondary Text
* @param tertiaryText tertiary Text
* @returns TextContent
*/
function makeTextContent(primaryText: { type: TextContentType, text: string },
secondaryText: { type: TextContentType, text: string }, tertiaryText: { type: TextContentType, text: string }): TextContent;
}
}
//#endregion
+1 -1
View File
@@ -20,4 +20,4 @@
"index.d.ts",
"alexa-sdk-tests.ts"
]
}
}
+10 -9
View File
@@ -1,10 +1,11 @@
{ "extends": "dtslint/dt.json",
"rules": {
"object-literal-shorthand": false,
"object-literal-key-quote": false,
"no-empty-interface": false,
"prefer-method-signature": false,
"object-literal-key-quotes": false,
"no-any": false
}
{
"extends": "dtslint/dt.json",
"rules": {
"object-literal-shorthand": false,
"object-literal-key-quote": false,
"no-empty-interface": false,
"prefer-method-signature": false,
"object-literal-key-quotes": false,
"no-any": false
}
}
+3 -3
View File
@@ -121,12 +121,12 @@ let _algoliaQueryParameters: AlgoliaQueryParameters = {
disableTypoToleranceOnAttributes: '',
aroundLatLng: '',
aroundLatLngViaIP: '',
aroundRadius: '',
aroundRadius: 0,
aroundPrecision: 0,
minimumAroundRadius: 0,
insideBoundingBox: '',
insideBoundingBox: [[0]],
queryType: '',
insidePolygon: '',
insidePolygon: [[0]],
removeWordsIfNoResults: '',
advancedSyntax: false,
optionalWords: [''],
+22 -21
View File
@@ -1,4 +1,4 @@
// Type definitions for algoliasearch-client-js 3.24.5
// Type definitions for algoliasearch-client-js 3.24.6
// Project: https://github.com/algolia/algoliasearch-client-js
// Definitions by: Baptiste Coquelle <https://github.com/cbaptiste>
// Haroen Viaene <https://github.com/haroenv>
@@ -49,6 +49,9 @@ declare namespace algoliasearch {
*/
params: string;
}
interface AlgoliaMultiResponse {
results: AlgoliaResponse[];
}
/*
Interface for the algolia client object
*/
@@ -71,8 +74,8 @@ declare namespace algoliasearch {
indexName: string;
query: string;
params: AlgoliaQueryParameters;
},
cb: (err: Error, res: any) => void
}[],
cb: (err: Error, res: AlgoliaMultiResponse) => void
): void;
/**
* Query on multiple index
@@ -84,7 +87,7 @@ declare namespace algoliasearch {
indexName: string;
query: string;
params: AlgoliaQueryParameters;
}): Promise<AlgoliaResponse>;
}[]): Promise<AlgoliaMultiResponse>;
/**
* clear browser cache
* https://github.com/algolia/algoliasearch-client-js#cache
@@ -319,8 +322,8 @@ declare namespace algoliasearch {
getLogs(options: LogsOptions): Promise<any>;
}
/**
* Interface for the index algolia object
*/
* Interface for the index algolia object
*/
interface AlgoliaIndex {
/**
* Gets a specific object
@@ -783,7 +786,7 @@ declare namespace algoliasearch {
* @param err() error callback
* https://github.com/algolia/algoliasearch-client-js#search-in-an-index---search
*/
search(params: AlgoliaQueryParameters): Promise<any>;
search(params: AlgoliaQueryParameters): Promise<AlgoliaResponse>;
/**
* Search in an index
* @param params query parameter
@@ -793,7 +796,7 @@ declare namespace algoliasearch {
*/
search(
params: AlgoliaQueryParameters,
cb: (err: Error, res: any) => void
cb: (err: Error, res: AlgoliaResponse) => void
): void;
/**
* Search in an index
@@ -809,8 +812,7 @@ declare namespace algoliasearch {
}: {
facetName: string;
facetQuery: string;
qp: AlgoliaQueryParameters;
}): Promise<any>;
} & AlgoliaQueryParameters): Promise<any>;
/**
* Search in an index
* @param params query parameter
@@ -826,8 +828,7 @@ declare namespace algoliasearch {
}: {
facetName: string;
facetQuery: string;
qp: AlgoliaQueryParameters;
},
} & AlgoliaQueryParameters,
cb: (err: Error, res: any) => void
): void;
/**
@@ -1072,8 +1073,8 @@ Interface describing options available for gettings the logs
type?: string;
}
/**
* Describe the action object used for batch operation
*/
* Describe the action object used for batch operation
*/
interface AlgoliaAction {
/**
* Type of the batch action
@@ -1099,8 +1100,8 @@ Interface describing options available for gettings the logs
body: {};
}
/**
* Describes the option used when creating user key
*/
* Describes the option used when creating user key
*/
interface AlgoliaApiKeyOptions {
/**
* Add a validity period. The key will be valid for a specific period of time (in seconds).
@@ -1365,8 +1366,8 @@ Interface describing options available for gettings the logs
}
/**
* Describes the settings available for configure your index
*/
* Describes the settings available for configure your index
*/
interface AlgoliaIndexSettings {
/**
* The list of attributes you want index
@@ -1771,7 +1772,7 @@ Interface describing options available for gettings the logs
* You can specify aroundRadius=all if you want to compute the geo distance without filtering in a geo area
* https://github.com/algolia/algoliasearch-client-js#aroundradius
*/
aroundRadius?: any;
aroundRadius?: number | 'all';
/**
* Control the precision of a geo search
* default: null
@@ -1789,7 +1790,7 @@ Interface describing options available for gettings the logs
* default: null
* https://github.com/algolia/algoliasearch-client-js#insideboundingbox
*/
insideBoundingBox?: string;
insideBoundingBox?: number[][];
/**
* Selects how the query words are interpreted
* default: 'prefixLast'
@@ -1804,7 +1805,7 @@ Interface describing options available for gettings the logs
* defauly: ''
* https://github.com/algolia/algoliasearch-client-js#insidepolygon
*/
insidePolygon?: string;
insidePolygon?: number[][];
/**
* This option is used to select a strategy in order to avoid having an empty result page
* default: 'none'
+7
View File
@@ -0,0 +1,7 @@
import { AmCharts } from "amcharts";
// TODO: provide much more tests
const gauge = new AmCharts.AmAngularGauge({
theme: "light"
});
+994 -130
View File
File diff suppressed because it is too large Load Diff
+4 -3
View File
@@ -5,9 +5,9 @@
"es6",
"dom"
],
"noImplicitAny": false,
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
@@ -18,6 +18,7 @@
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts"
"index.d.ts",
"amcharts-tests.ts"
]
}
+1 -71
View File
@@ -1,79 +1,9 @@
{
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
"unified-signatures": false
}
}
+1 -1
View File
@@ -63,4 +63,4 @@ export interface ConfirmChannel extends Channel {
waitForConfirms(): Promise<void>;
}
export function connect(url: string, socketOptions?: any): Promise<Connection>;
export function connect(url: string | Options.Connect, socketOptions?: any): Promise<Connection>;
+59 -1
View File
@@ -21,6 +21,64 @@ export namespace Replies {
}
export namespace Options {
interface Connect {
/**
* The to be used protocol
*
* Default value: 'amqp'
*/
protocol?: string;
/**
* Hostname used for connecting to the server.
*
* Default value: 'localhost'
*/
hostname?: string;
/**
* Port used for connecting to the server.
*
* Default value: 5672
*/
port?: number;
/**
* Username used for authenticating against the server.
*
* Default value: 'guest'
*/
username?: string;
/**
* Password used for authenticating against the server.
*
* Default value: 'guest'
*/
password?: string;
/**
* The desired locale for error messages. RabbitMQ only ever uses en_US
*
* Default value: 'en_US'
*/
locale?: string;
/**
* The size in bytes of the maximum frame allowed over the connection. 0 means
* no limit (but since frames have a size field which is an unsigned 32 bit integer, its perforce 2^32 - 1).
*
* Default value: 0x1000 (4kb) - That's the allowed minimum, it will fit many purposes
*/
frameMax?: number;
/**
* The period of the connection heartbeat in seconds.
*
* Default value: 0
*/
heartbeat?: number;
/**
* What VHost shall be used.
*
* Default value: '/'
*/
vhost?: string;
}
interface AssertQueue {
exclusive?: boolean;
durable?: boolean;
@@ -85,4 +143,4 @@ export interface Message {
content: Buffer;
fields: any;
properties: any;
}
}
-55
View File
@@ -1,55 +0,0 @@
## What is it?
This is a typescript interface to be used with [angular-hotkeys](https://github.com/chieffancypants/angular-hotkeys/).
## What are declaration files?
See the [TypeScript handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html).
## How do I get them?
### npm
This is the preferred method. This is only available for TypeScript 2.0+ users. For these typings:
```sh
npm install --save-dev @types/angular-hotkeys
```
The types should then be automatically included by the compiler.
See more in the [handbook](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html).
### Other methods
These can be used by TypeScript 1.0.
* [Typings](https://github.com/typings/typings)
* ~~[NuGet](http://nuget.org/Tpackages?q=DefinitelyTyped)~~ (use preferred alternatives, nuget DT type publishing has been turned off)
* Manually download from the `master` branch of this repository
You may need to add manual [references](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html).
## How to use
After installing a package you can import the definition file and begin using it as so:
```ts
import * as hotkeys from '../../node_modules/@types/angular-hotkeys'
class FooController {
static $inject = [
'hotkeys'
];
constructor(
private hotkeys: ng.hotkeys.HotkeysProvider
) { }
}
```
for a detailed explanation of the behavior of angular-hotkeys please refer to [its documentation](https://github.com/chieffancypants/angular-hotkeys/)
+64 -27
View File
@@ -1,30 +1,67 @@
var scope: ng.IScope;
var hotkeyProvider: ng.hotkeys.HotkeysProvider;
var hotkeyObj: ng.hotkeys.Hotkey;
import { HotkeysProvider, Hotkey } from 'angular-hotkeys';
import { module } from 'angular';
hotkeyProvider.add("mod+s", "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => {} );
hotkeyProvider.add(["mod+s"], "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => {} );
hotkeyProvider.add(hotkeyObj);
hotkeyProvider.bindTo(scope);
hotkeyProvider.del("mod+s");
hotkeyProvider.del(["mod+s"]);
hotkeyProvider.get("mod+s");
hotkeyProvider.get(["mod+s"]);
hotkeyProvider.toggleCheatSheet();
hotkeyProvider.add(hotkeyObj.combo, hotkeyObj.description ,hotkeyObj.callback);
hotkeyProvider.bindTo(scope)
.add(hotkeyObj)
.add(hotkeyObj)
.add({
combo: 'w',
description: 'blah blah',
callback: function() {}
})
.add({
combo: ['w', 'mod+w'],
description: 'blah blah',
callback: function() {}
module('myApp', ['cfp.hotkeys'])
.config((hotkeysProvider: HotkeysProvider) => {
hotkeysProvider.includeCheatSheet = false;
const somehotKeyObj: Hotkey = {
combo: '',
callback: () => { }
};
});
function someInjectionService(
scope: ng.IScope,
hotkeyProvider: ng.hotkeys.HotkeysProvider,
hotkeyObj: ng.hotkeys.Hotkey
) {
hotkeyProvider.add("mod+s", "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => { });
hotkeyProvider.add(["mod+s"], "saves a file", (event: Event, hotkey: ng.hotkeys.Hotkey) => { });
hotkeyProvider.add(hotkeyObj);
hotkeyProvider.bindTo(scope);
hotkeyProvider.del("mod+s");
hotkeyProvider.del(["mod+s"]);
hotkeyProvider.get("mod+s");
hotkeyProvider.get(["mod+s"]);
hotkeyProvider.toggleCheatSheet();
hotkeyProvider.add(hotkeyObj.combo, hotkeyObj.description, hotkeyObj.callback);
hotkeyProvider.bindTo(scope)
.add(hotkeyObj)
.add(hotkeyObj)
.add({
combo: 'w',
description: 'blah blah',
callback: () => { }
})
.add({
combo: ['w', 'mod+w'],
description: 'blah blah',
callback: () => { }
});
hotkeyProvider.add({
combo: 'ctrl+w',
description: 'Description goes here',
callback: (event, hotkey) => {
event.preventDefault();
}
});
hotkeyProvider.add({
combo: 'ctrl+x',
callback: (event, hotkey) => {
//
}
});
hotkeyProvider.add({
combo: 'ctrl+w',
description: 'Description goes here',
allowIn: ['INPUT', 'SELECT', 'TEXTAREA'],
callback(event, hotkey) {
event.preventDefault();
}
});
}
+99 -24
View File
@@ -1,12 +1,10 @@
// Type definitions for angular-hotkeys
// Type definitions for angular-hotkeys 1.7
// Project: https://github.com/chieffancypants/angular-hotkeys
// Definitions by: Jason Zhao <https://github.com/jlz27>, Stefan Steinhart <https://github.com/reppners>
// Definitions by: Jason Zhao <https://github.com/jlz27>
// Stefan Steinhart <https://github.com/reppners>
// Cyril Gandon <https://github.com/cyrilgandon>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
//readme written by David Valentine <https://github.com/dvalenti314>
/// <reference types="angular" />
import * as ng from 'angular';
@@ -15,46 +13,123 @@ export type HotkeysProviderChained = ng.hotkeys.HotkeysProviderChained;
export type Hotkey = ng.hotkeys.Hotkey;
declare module 'angular' {
export namespace hotkeys {
namespace hotkeys {
interface HotkeysProvider {
template: string;
templateTitle: string;
/**
* Configurable setting to disable the cheatsheet entirely.
* @default true
*/
includeCheatSheet: boolean;
/**
* Configurable setting to disable ngRoute hooks.
*/
useNgRoute: boolean;
/**
* Configurable setting for the cheat sheet title
* @default 'Keyboard Shortcuts'
*/
templateTitle: string;
/**
* Configurable settings for the cheat sheet header in HTML.
* This overrides the normal title if specified.
* @default null
*/
templateHeader: string | null;
/**
* Configurable settings for the cheat sheet footer in HTML.
* @default null
*/
templateFooter: string | null;
/**
* Cheat sheet template in the event you want to totally customize it.
*/
template: string;
/**
* Configurable setting for the cheat sheet hotkey.
* @default '?'
*/
cheatSheetHotkey: string;
/**
* Configurable setting for the cheat sheet description.
* @default 'Show / hide this help menu'
*/
cheatSheetDescription: string;
add(combo: string | string[], callback: (event: Event, hotkey?: Hotkey) => void, action?: string, allowIn?: Array<string>, persistent?: boolean): ng.hotkeys.Hotkey;
/**
* Creates a new Hotkey and creates the Mousetrap binding.
*/
add(combo: string | string[], description?: string, callback?: (event: Event, hotkey: Hotkey) => void, action?: string, allowIn?: string[], persistent?: boolean): Hotkey;
add(combo: string | string[], description: string, callback: (event: Event, hotkey?: Hotkey) => void, action?: string, allowIn?: Array<string>, persistent?: boolean): ng.hotkeys.Hotkey;
/**
* Creates a new Hotkey and creates the Mousetrap binding.
*/
add(hotkeyObj: Hotkey): Hotkey;
add(hotkeyObj: ng.hotkeys.Hotkey): ng.hotkeys.Hotkey;
/**
* Binds the hotkey to a particular scope.
* Useful if the scope is destroyed, we can automatically destroy the hotkey binding.
* @param scope The scope to bind to
*/
bindTo(scope: IScope): HotkeysProviderChained;
bindTo(scope: ng.IScope): ng.hotkeys.HotkeysProviderChained;
/**
* Removes and unbinds a hotkey
* @param combo The keyboard combo (shortcut) or the HotKey object
*/
del(combo: string | string[] | Hotkey): void;
del(combo: string | string[]): void;
del(hotkeyObj: ng.hotkeys.Hotkey): void;
get(combo: string | string[]): ng.hotkeys.Hotkey;
/**
* Returns the Hotkey object
* @param combo The keyboard combo (shortcut)
*/
get(combo: string | string[]): Hotkey;
/**
* Toggles the help menu element's visiblity
*/
toggleCheatSheet(): void;
/**
* Purges all non-persistent hotkeys (such as those defined in routes)
*
* Without this, the same hotkey would get recreated everytime
* the route is accessed.
*/
purgeHotkeys(): void;
}
interface HotkeysProviderChained {
add(combo: string | string[], description: string, callback: (event: Event, hotkeys: ng.hotkeys.Hotkey) => void): HotkeysProviderChained;
add(combo: string | string[], description: string, callback: (event: Event, hotkeys: Hotkey) => void): HotkeysProviderChained;
add(hotkeyObj: ng.hotkeys.Hotkey): HotkeysProviderChained;
add(hotkeyObj: Hotkey): HotkeysProviderChained;
}
interface Hotkey {
/**
* They keyboard combo (shortcut) you want to bind to.
*/
combo: string | string[];
/**
* The description for what the combo does and is only used for the Cheat Sheet.
* If it is not supplied, it will not show up, and in effect, allows you to have unlisted hotkeys.
*/
description?: string;
callback: (event: Event, hotkey: ng.hotkeys.Hotkey) => void;
/**
* The function to execute when the key(s) are pressed. Passes along two arguments, event and hotkey
*/
callback(event: Event, hotkey: Hotkey): void;
/**
* The type of event to listen for, such as keypress, keydown or keyup.
* Usage of this parameter is discouraged as the underlying library will pick the most suitable option automatically.
* This should only be necessary in advanced situations.
*/
action?: string;
allowIn?: Array<string>;
/**
* An array of tag names to allow this combo in ('INPUT', 'SELECT', and/or 'TEXTAREA')
*/
allowIn?: Array<'INPUT' | 'SELECT' | 'TEXTAREA'>;
/**
* Whether the hotkey persists navigation events
*/
persistent?: boolean;
}
}
+2 -2
View File
@@ -7,7 +7,7 @@
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
@@ -21,4 +21,4 @@
"index.d.ts",
"angular-hotkeys-tests.ts"
]
}
}
+1 -79
View File
@@ -1,79 +1 @@
{
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
}
}
{ "extends": "dtslint/dt.json" }
@@ -5,6 +5,7 @@ interface TestScope extends ng.IScope {
}
myApp.config((
$mdAriaProvider: ng.material.IAriaProvider,
$mdThemingProvider: ng.material.IThemingProvider,
$mdIconProvider: ng.material.IIconProvider,
$mdProgressCircularProvider: ng.material.IProgressCircularProvider) => {
@@ -52,6 +53,9 @@ myApp.config((
return c * Math.pow(2, (t / d - 1) * 10) + b;
}
});
// Globally disables all ARIA warnings.
$mdAriaProvider.disableWarnings();
});
myApp.controller('BottomSheetController', ($scope: TestScope, $mdBottomSheet: ng.material.IBottomSheetService, $q: ng.IQService) => {
@@ -136,6 +140,9 @@ myApp.controller('DialogController', ($scope: TestScope, $mdDialog: ng.material.
$scope['promptDialog'] = () => {
$mdDialog.show($mdDialog.prompt().initialValue('Buddy'));
};
$scope['promptDialog'] = () => {
$mdDialog.show($mdDialog.prompt().required(true));
};
$scope['prerenderedDialog'] = () => {
$mdDialog.show({
template: '<md-dialog>Hello!</md-dialog>',
+6 -1
View File
@@ -1,6 +1,6 @@
// Type definitions for angular-material 1.1
// Project: https://github.com/angular/material
// Definitions by: Blake Bigelow <https://github.com/blbigelow>, Peter Hajdu <https://github.com/PeterHajdu>, Davide Donadello <https://github.com/Dona278>, Geert Jansen <https://github.com/geertjansen>
// Definitions by: Blake Bigelow <https://github.com/blbigelow>, Peter Hajdu <https://github.com/PeterHajdu>, Davide Donadello <https://github.com/Dona278>, Geert Jansen <https://github.com/geertjansen>, Edward Knowles <https://github.com/eknowles>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
@@ -11,6 +11,10 @@ export = _;
declare module 'angular' {
namespace material {
interface IAriaProvider {
disableWarnings(): void;
}
interface ResolveObject {
[name: string]: Injectable<(...args: any[]) => PromiseLike<any>>;
}
@@ -76,6 +80,7 @@ declare module 'angular' {
interface IPromptDialog extends IPresetDialog<IPromptDialog> {
cancel(cancel: string): IPromptDialog;
required(required: boolean): IPromptDialog; // default: false
placeholder(placeholder: string): IPromptDialog;
initialValue(initialValue: string): IPromptDialog;
}
@@ -4,5 +4,6 @@ declare var $sanitizeService: ng.sanitize.ISanitizeService;
shouldBeString = $sanitizeService(shouldBeString);
declare var $linky: ng.sanitize.filter.ILinky;
shouldBeString = $linky(shouldBeString);
shouldBeString = $linky(shouldBeString, "target");
shouldBeString = $linky(shouldBeString, shouldBeString);
+1 -1
View File
@@ -36,7 +36,7 @@ declare module 'angular' {
* see https://docs.angularjs.org/api/ngSanitize/filter/linky
*/
interface ILinky {
(text: string, target: string, attributes?: { [attribute: string]: string } | ((url: string) => { [attribute: string]: string })): string;
(text: string, target?: string, attributes?: { [attribute: string]: string } | ((url: string) => { [attribute: string]: string })): string;
}
}
@@ -1,69 +1,62 @@
let dummySocket: ng.websocket.IWebSocket;
let dummyPromise: ng.IPromise<void>;
let dummyScope: ng.IScope;
import * as ng from 'angular';
let provider: ng.websocket.IWebSocketProvider = (url: string, protocols?:string[] | ng.websocket.IWebSocketConfigOptions, options?: ng.websocket.IWebSocketConfigOptions) => {
return dummySocket;
}
(promise: angular.IPromise<void>, scope: ng.IScope, provider: ng.websocket.IWebSocketProvider) => {
const socket = provider("wss://localhost");
const socketWithProtocols = provider("wss://localhost", ["protocol-a", "protocol-b"]);
let socketWithProtocol = provider("wss://localhost", "protocol");
let socketWithProtocols = provider("wss://localhost", ["protocol-a", "protocol-b"]);
const socketWithOptions = provider("wss://localhost", {
scope,
rootScopeFailOver: true,
useApplyAsync: true,
initialTimeout: 100,
maxTimeout: 300000,
reconnectIfNotNormalClose: true,
binaryType: "blob"
});
let socketWithOptions = provider("wss://localhost", {
scope: dummyScope,
rootScopeFailOver: true,
useApplyAsync: true,
initialTimeout: 100,
maxTimeout: 300000,
reconnectIfNotNormalClose: true,
binaryType: "blob"
});
const socketWithProtocolAndOptions = provider("wss://localhost", "protocol", {
scope,
rootScopeFailOver: true,
useApplyAsync: true,
initialTimeout: 100,
maxTimeout: 300000,
reconnectIfNotNormalClose: true,
binaryType: "blob"
});
let socketWithProtocolAndOptions = provider("wss://localhost", "protocol", {
scope: dummyScope,
rootScopeFailOver: true,
useApplyAsync: true,
initialTimeout: 100,
maxTimeout: 300000,
reconnectIfNotNormalClose: true,
binaryType: "blob"
});
socket.onOpen((event: Event) => {})
.onClose((event: Event) => {})
.onError((event: Event) => {})
.onMessage((event: Event) => {});
let socket = provider("wss://localhost");
socket.onMessage((event: Event) => {}, { filter: /Some Filter/ })
.onMessage((event: Event) => {}, { filter: 'Some Filter' })
.onMessage((event: Event) => {}, { filter: 'Some Filter', autoApply: true })
.onMessage((event: Event) => {}, { autoApply: false });
socket.onOpen((event) => {})
.onClose((event) => {})
.onError((event) => {})
.onMessage((event) => {});
socket.close(true);
socket.close();
socket.onMessage((event) => {}, { filter: /Some Filter/ })
.onMessage((event) => {}, { filter: 'Some Filter' })
.onMessage((event) => {}, { filter: 'Some Filter', autoApply: true })
.onMessage((event) => {}, { autoApply: false });
socket.send("Some great data here!").finally(() => {});
socket.send({ list: [1, 2, 3, 4] });
socket.close(true);
socket.close();
socket.socket.send("data");
socket.socket.close();
socket.socket.close(1);
socket.socket.close(1, "reason");
socket.send("Some great data here!").finally(() => {});
socket.send({ list: [1, 2, 3, 4] });
socket.sendQueue.push({ message: "msg", defered: promise });
socket.socket.send("data");
socket.socket.close();
socket.socket.close(1);
socket.socket.close(1, "reason");
socket.onOpenCallbacks.push((event: Event) => {});
socket.onCloseCallbacks.push((event: CloseEvent) => {});
socket.onErrorCallbacks.push((event: Event) => {});
socket.onMessageCallbacks.push({ fn: (event: MessageEvent) => {}, pattern: 'Some Filter', autoApply: true });
socket.onMessageCallbacks.push({ fn: (event: MessageEvent) => {}, pattern: /Some Filter/, autoApply: true });
socket.onMessageCallbacks.push({ fn: (event: MessageEvent) => {}, autoApply: true });
socket.sendQueue.push({ message: "msg", defered: dummyPromise });
socket.readyState = 0;
socket.onOpenCallbacks.push((event: Event) => {});
socket.onCloseCallbacks.push((event: CloseEvent) => {});
socket.onErrorCallbacks.push((event: Event) => {});
socket.onMessageCallbacks.push({ fn: (event: MessageEvent) => {}, pattern: 'Some Filter', autoApply: true });
socket.onMessageCallbacks.push({ fn: (event: MessageEvent) => {}, pattern: /Some Filter/, autoApply: true });
socket.onMessageCallbacks.push({ fn: (event: MessageEvent) => {}, pattern: undefined, autoApply: true });
socket.readyState = 0;
socket.initialTimeout = 10;
socket.maxTimeout = 5000;
socket.initialTimeout = 10;
socket.maxTimeout = 5000;
};
+40 -35
View File
@@ -1,39 +1,45 @@
// Type definitions for angular-websocket v2.0
// Type definitions for angular-websocket 2.0
// Project: https://github.com/AngularClass/angular-websocket
// Definitions by: Nick Veys <https://github.com/nickveys>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
import * as ng from "angular";
import * as angular from "angular";
export type IWebSocketConfigOptions = angular.websocket.IWebSocketConfigOptions;
export type IWebSocketProvider = angular.websocket.IWebSocketProvider;
export type IWebSocketMessageOptions = angular.websocket.IWebSocketMessageOptions;
export type IWebSocketMessageHandler = angular.websocket.IWebSocketMessageHandler;
export type IWebSocketQueueItem = angular.websocket.IWebSocketQueueItem;
export type IWebSocket = angular.websocket.IWebSocket;
declare module "angular" {
namespace websocket {
/**
* Options available to be specified for IWebSocketProvider.
*/
type IWebSocketConfigOptions = {
scope?: ng.IScope;
rootScopeFailOver?: boolean;
useApplyAsync?: boolean;
initialTimeout?: number;
maxTimeout?: number;
binaryType?: "blob" | "arraybuffer";
reconnectIfNotNormalClose?: boolean;
}
interface IWebSocketProvider {
/**
* Creates and opens an IWebSocket instance.
*
* @param url url to connect to
* @return websocket instance
*/
(url: string, protocols?: string | string[] | IWebSocketConfigOptions, options?: IWebSocketConfigOptions): IWebSocket;
interface IWebSocketConfigOptions {
scope?: IScope;
rootScopeFailOver?: boolean;
useApplyAsync?: boolean;
initialTimeout?: number;
maxTimeout?: number;
binaryType?: "blob" | "arraybuffer";
reconnectIfNotNormalClose?: boolean;
}
/**
* Creates and opens an IWebSocket instance.
*
* @param url url to connect to
* @return websocket instance
*/
type IWebSocketProvider =
(url: string, protocols?: string | string[] | IWebSocketConfigOptions,
options?: IWebSocketConfigOptions) => IWebSocket;
/** Options available to be specified for IWebSocket.onMessage */
type IWebSocketMessageOptions = {
interface IWebSocketMessageOptions {
/**
* If specified, only messages that match the filter will cause the message event
* to be fired.
@@ -44,21 +50,20 @@ declare module "angular" {
autoApply?: boolean;
}
/** Type corresponding to onMessage callbaks stored in $Websocket#onMessageCallbacks instance. */
type IWebSocketMessageHandler = {
fn: (evt: MessageEvent) => void;
pattern: string | RegExp;
autoApply: boolean;
/** Type corresponding to onMessage callbacks stored in $Websocket#onMessageCallbacks instance. */
interface IWebSocketMessageHandler {
fn: (evt: MessageEvent) => void;
pattern?: string | RegExp;
autoApply: boolean;
}
/** Type corresponding to items stored in $WebSocket#sendQueue instance. */
type IWebSocketQueueItem = {
message: any;
defered: ng.IPromise<void>;
interface IWebSocketQueueItem {
message: any;
defered: IPromise<void>;
}
interface IWebSocket {
/**
* Adds a callback to be executed each time a socket connection is opened for
* this instance.
@@ -108,7 +113,7 @@ declare module "angular" {
*
* @param data data to send, if this is an object, it will be stringified before sending
*/
send(data: string | {}): ng.IPromise<any>;
send(data: string | {}): IPromise<any>;
/**
* WebSocket instance.
@@ -123,7 +128,7 @@ declare module "angular" {
/**
* List of callbacks to be executed when the socket is opened.
*/
onOpenCallbacks: ((evt: Event) => void)[];
onOpenCallbacks: Array<((evt: Event) => void)>;
/**
* List of callbacks to be executed when a message is received from the socket.
@@ -133,12 +138,12 @@ declare module "angular" {
/**
* List of callbacks to be executed when an error is received from the socket.
*/
onErrorCallbacks: ((evt: Event) => void)[];
onErrorCallbacks: Array<((evt: Event) => void)>;
/**
* List of callbacks to be executed when the socket is closed.
*/
onCloseCallbacks: ((evt: CloseEvent) => void)[];
onCloseCallbacks: Array<((evt: CloseEvent) => void)>;
/**
* Returns either the readyState value from the underlying WebSocket instance
+8 -8
View File
@@ -1,8 +1,4 @@
{
"files": [
"index.d.ts",
"angular-websocket-tests.ts"
],
"compilerOptions": {
"module": "commonjs",
"lib": [
@@ -11,8 +7,8 @@
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": false,
"strictFunctionTypes": false,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
@@ -20,5 +16,9 @@
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
}
}
},
"files": [
"index.d.ts",
"angular-websocket-tests.ts"
]
}
+1 -74
View File
@@ -1,79 +1,6 @@
{
"extends": "dtslint/dt.json",
"rules": {
"adjacent-overload-signatures": false,
"array-type": false,
"arrow-return-shorthand": false,
"ban-types": false,
"callable-types": false,
"comment-format": false,
"dt-header": false,
"eofline": false,
"export-just-namespace": false,
"import-spacing": false,
"interface-name": false,
"interface-over-type-literal": false,
"jsdoc-format": false,
"max-line-length": false,
"member-access": false,
"new-parens": false,
"no-any-union": false,
"no-boolean-literal-compare": false,
"no-conditional-assignment": false,
"no-consecutive-blank-lines": false,
"no-construct": false,
"no-declare-current-package": false,
"no-duplicate-imports": false,
"no-duplicate-variable": false,
"no-empty-interface": false,
"no-for-in-array": false,
"no-inferrable-types": false,
"no-internal-module": false,
"no-irregular-whitespace": false,
"no-mergeable-namespace": false,
"no-misused-new": false,
"no-namespace": false,
"no-object-literal-type-assertion": false,
"no-padding": false,
"no-redundant-jsdoc": false,
"no-redundant-jsdoc-2": false,
"no-redundant-undefined": false,
"no-reference-import": false,
"no-relative-import-in-test": false,
"no-self-import": false,
"no-single-declare-module": false,
"no-string-throw": false,
"no-unnecessary-callback-wrapper": false,
"no-unnecessary-class": false,
"no-unnecessary-generics": false,
"no-unnecessary-qualifier": false,
"no-unnecessary-type-assertion": false,
"no-useless-files": false,
"no-var-keyword": false,
"no-var-requires": false,
"no-void-expression": false,
"no-trailing-whitespace": false,
"object-literal-key-quotes": false,
"object-literal-shorthand": false,
"one-line": false,
"one-variable-per-declaration": false,
"only-arrow-functions": false,
"prefer-conditional-expression": false,
"prefer-const": false,
"prefer-declare-function": false,
"prefer-for-of": false,
"prefer-method-signature": false,
"prefer-template": false,
"radix": false,
"semicolon": false,
"space-before-function-paren": false,
"space-within-parens": false,
"strict-export-declare-modifiers": false,
"trim-file": false,
"triple-equals": false,
"typedef-whitespace": false,
"unified-signatures": false,
"void-return": false,
"whitespace": false
"interface-name": false
}
}
-2
View File
@@ -6,8 +6,6 @@
* License: MIT
*/
/* tslint:disable:no-empty no-shadowed-variable */
class AuthService {
/**
* Holds all the requests which failed due to 401 response,
+30
View File
@@ -0,0 +1,30 @@
import * as colors from 'ansi-colors';
let s: string;
s = colors.bgblack("hello");
s = colors.bgblue("hello");
s = colors.bgcyan("hello");
s = colors.bggreen("hello");
s = colors.bgmagenta("hello");
s = colors.bgred("hello");
s = colors.bgwhite("hello");
s = colors.bgyellow("hello");
s = colors.black("hello");
s = colors.blue("hello");
s = colors.bold("hello");
s = colors.cyan("hello");
s = colors.dim("hello");
s = colors.gray("hello");
s = colors.green("hello");
s = colors.grey("hello");
s = colors.hidden("hello");
s = colors.inverse("hello");
s = colors.italic("hello");
s = colors.magenta("hello");
s = colors.red("hello");
s = colors.reset("hello");
s = colors.strikethrough("hello");
s = colors.underline("hello");
s = colors.white("hello");
s = colors.yellow("hello");
+31
View File
@@ -0,0 +1,31 @@
// Type definitions for ansi-colors 1.0
// Project: https://github.com/doowb/ansi-colors
// Definitions by: Rogier Schouten <https://github.com/rogierschouten>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export function bgblack(s: string): string;
export function bgblue(s: string): string;
export function bgcyan(s: string): string;
export function bggreen(s: string): string;
export function bgmagenta(s: string): string;
export function bgred(s: string): string;
export function bgwhite(s: string): string;
export function bgyellow(s: string): string;
export function black(s: string): string;
export function blue(s: string): string;
export function bold(s: string): string;
export function cyan(s: string): string;
export function dim(s: string): string;
export function gray(s: string): string;
export function green(s: string): string;
export function grey(s: string): string;
export function hidden(s: string): string;
export function inverse(s: string): string;
export function italic(s: string): string;
export function magenta(s: string): string;
export function red(s: string): string;
export function reset(s: string): string;
export function strikethrough(s: string): string;
export function underline(s: string): string;
export function white(s: string): string;
export function yellow(s: string): string;
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"ansi-colors-tests.ts"
]
}
+13
View File
@@ -0,0 +1,13 @@
import ansiRegex = require("ansi-regex");
ansiRegex(); // $ExpectType RegExp
// From the ansi-regex README.md
ansiRegex().test('\u001B[4mcake\u001B[0m'); // $ExpectType boolean
// => true
ansiRegex().test('cake'); // $ExpectType boolean
// => false
'\u001B[4mcake\u001B[0m'.match(ansiRegex()); // $ExpectType RegExpMatchArray | null
// => ['\u001B[4m', '\u001B[0m']
+7
View File
@@ -0,0 +1,7 @@
// Type definitions for ansi-regex 3.0
// Project: https://github.com/chalk/ansi-regex#readme
// Definitions by: Manish Vachharajani <https://github.com/mvachhar>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function r(): RegExp;
export = r;
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"ansi-regex-tests.ts"
]
}
+47
View File
@@ -0,0 +1,47 @@
import appdmg = require("appdmg");
import { Options, Specification, SpecificationOptions } from "appdmg";
const proc = appdmg({
target: "/foo/bar.dmg",
basepath: "/baz",
specification: {
title: "Happy",
icon: "happy.icns",
background: "happy.tiff",
format: "UDBZ",
"icon-size": 98,
contents: [
{
x: 405,
y: 150,
type: "link",
path: "/Applications"
},
{
x: 127,
y: 150,
type: "file",
path: "/foo/bar.app"
}
]
}
});
proc.on("progress", info => {
if (info.type === "step-begin") {
process.stdout.write(`${info.title}... `);
}
if (info.type === "step-end") {
process.stdout.write(`${info.status}\n`);
}
});
proc.on("finish", () => {
console.log('Installer was created successfully!');
});
proc.on("error", (err) => {
console.error('Installer could not be created', err);
process.exit(1);
});
+70
View File
@@ -0,0 +1,70 @@
// Type definitions for appdmg 0.5
// Project: https://github.com/LinusU/node-appdmg#readme
// Definitions by: Daniel Perez Alvarez <https://github.com/unindented>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
declare namespace appdmg {
interface Progress {
current: number;
total: number;
type: "step-begin" | "step-end";
title: string;
status: "ok" | "skip" | "fail";
}
interface EventEmitter extends NodeJS.EventEmitter {
on(event: "progress", listener: (info: Progress) => void): this;
on(event: "finish", listener: () => void): this;
on(event: "error", listener: (err: any) => void): this;
}
interface SpecificationOptions {
app: string;
background: string;
icon: string;
iconSize: number;
title: string;
}
interface SpecificationWindow {
position?: { x: number; y: number };
size?: { width: number; height: number };
}
interface SpecificationContents {
x: number;
y: number;
type: "link" | "file" | "position";
path: string;
name?: string;
}
interface SpecificationCodeSign {
"signing-identity": string;
identifier?: string;
}
interface Specification {
title: string;
icon?: string;
background?: string;
"background-color"?: string;
"icon-size"?: number;
window?: SpecificationWindow;
format: "UDRW" | "UDRO" | "UDCO" | "UDZO" | "UDBZ" | "ULFO";
contents: SpecificationContents[];
"code-sign"?: SpecificationCodeSign;
}
interface Options {
target: string;
basepath: string;
specification: Specification;
}
}
declare function appdmg(options?: appdmg.Options): appdmg.EventEmitter;
export = appdmg;
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"appdmg-tests.ts"
]
}
+51 -9
View File
@@ -22,7 +22,7 @@ describe("ApplePaySession", () => {
});
it("can create a new instance", () => {
const version = 1;
const paymentRequest = {
const paymentRequest: ApplePayJS.ApplePayPaymentRequest = {
countryCode: "US",
currencyCode: "USD",
supportedNetworks: [
@@ -57,8 +57,8 @@ describe("ApplePaySession", () => {
});
});
it("can call instance methods", () => {
const version = 1;
const paymentRequest = {
const version = 3;
const paymentRequest: ApplePayJS.ApplePayPaymentRequest = {
countryCode: "US",
currencyCode: "USD",
supportedNetworks: [
@@ -66,7 +66,9 @@ describe("ApplePaySession", () => {
"visa"
],
merchantCapabilities: [
"supports3DS"
"supports3DS",
"supportsCredit",
"supportsDebit"
],
total: {
label: "My Store",
@@ -80,15 +82,29 @@ describe("ApplePaySession", () => {
session.completeMerchantValidation({
foo: "bar"
});
session.completePayment(ApplePaySession.STATUS_SUCCESS);
const total = {
const authorizationResult: ApplePayJS.ApplePayPaymentAuthorizationResult = {
status: ApplePaySession.STATUS_FAILURE,
errors: [
{
code: "addressUnserviceable",
contactField: "postalCode",
message: "The specified postal code cannot be delivered to."
}
]
};
session.completePayment(authorizationResult);
const total: ApplePayJS.ApplePayLineItem = {
label: "Subtotal",
type: "final",
amount: "35.00"
};
const lineItems = [
const lineItems: ApplePayJS.ApplePayLineItem[] = [
{
label: "Subtotal",
type: "final",
@@ -97,11 +113,12 @@ describe("ApplePaySession", () => {
{
label: "Free Shipping",
amount: "0.00",
type: "pending"
type: "final"
},
{
label: "Estimated Tax",
amount: "3.06"
amount: "3.06",
type: "pending"
}
];
@@ -120,17 +137,35 @@ describe("ApplePaySession", () => {
session.completePaymentMethodSelection(total, lineItems);
const paymentUpdate = {
newTotal: total
};
session.completePaymentMethodSelection(paymentUpdate);
session.completeShippingContactSelection(
ApplePaySession.STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,
shippingMethods,
total,
lineItems);
const contactUpdate = {
newTotal: total
};
session.completeShippingContactSelection(contactUpdate);
session.completeShippingMethodSelection(
ApplePaySession.STATUS_SUCCESS,
total,
lineItems);
const shippingUpdate = {
newTotal: total
};
session.completeShippingMethodSelection(shippingUpdate);
session.oncancel = (event: ApplePayJS.Event): void => {
event.cancelBubble = true;
};
@@ -201,7 +236,9 @@ describe("ApplePayPaymentRequest", () => {
"1 Infinite Loop"
],
locality: "Cupertino",
subLocality: "",
administrativeArea: "CA",
subAdministrativeArea: "",
postalCode: "95014",
country: "United States",
countryCode: "US"
@@ -233,7 +270,7 @@ describe("ApplePayPaymentRequest", () => {
"postalAddress",
"name",
"phone",
"email"
"name"
];
paymentRequest.shippingContact = {
@@ -241,11 +278,15 @@ describe("ApplePayPaymentRequest", () => {
familyName: "Patel",
givenName: "Ravi",
phoneNumber: "(408) 555-5555",
phoneticFamilyName: "Patel",
phoneticGivenName: "Ravi",
addressLines: [
"1 Infinite Loop"
],
locality: "Cupertino",
subLocality: "",
administrativeArea: "CA",
subAdministrativeArea: "",
postalCode: "95014",
country: "United States",
countryCode: "US"
@@ -265,5 +306,6 @@ describe("ApplePayPaymentRequest", () => {
];
paymentRequest.shippingType = "storePickup";
paymentRequest.shippingType = "delivery";
});
});
+322 -52
View File
@@ -1,26 +1,26 @@
// Type definitions for Apple Pay JS 1.0
// Type definitions for Apple Pay JS 3.0
// Project: https://developer.apple.com/reference/applepayjs
// Definitions by: Martin Costello <https://martincostello.com/>
// Definitions by: Martin Costello <https://github.com/martincostello>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/**
* A session object for managing the payment process on the web.
* ApplePaySession is the entry point for Apple Pay on the web.
*/
declare class ApplePaySession extends EventTarget {
/**
* Creates a new instance of the ApplePaySession class.
* @param version - The version of the ApplePay JS API you are using.
* @param paymentRequest - An ApplePayPaymentRequest object that contains the information that is displayed on the Apple Pay payment sheet.
* The entry point for Apple Pay on the web.
* @param version - The version number of the ApplePay JS API you are using. The current API version number is 3.
* @param paymentRequest - An ApplePayPaymentRequest object that contains the information to be displayed on the Apple Pay payment sheet.
*/
constructor(version: number, paymentRequest: ApplePayJS.ApplePayPaymentRequest);
/**
* A callback function that is automatically called when the payment UI is dismissed with an error.
* A callback function that is automatically called when the payment UI is dismissed.
*/
oncancel: (event: ApplePayJS.Event) => void;
/**
* A callback function that is automatically called when the user has authorized the Apple Pay payment, typically via TouchID.
* A callback function that is automatically called when the user has authorized the Apple Pay payment with Touch ID, Face ID, or passcode.
*/
onpaymentauthorized: (event: ApplePayJS.ApplePayPaymentAuthorizedEvent) => void;
@@ -45,28 +45,28 @@ declare class ApplePaySession extends EventTarget {
onvalidatemerchant: (event: ApplePayJS.ApplePayValidateMerchantEvent) => void;
/**
* Indicates whether or not the device supports Apple Pay.
* Indicates whether the device supports Apple Pay.
* @returns true if the device supports making payments with Apple Pay; otherwise, false.
*/
static canMakePayments(): boolean;
/**
* Indicates whether or not the device supports Apple Pay and if the user has an active card in Wallet.
* @param merchantIdentifier - The merchant ID received when the merchant enrolled in Apple Pay.
* @returns true if the device supports Apple Pay and there is at least one active card in Wallet; otherwise, false.
* Indicates whether the device supports Apple Pay and whether the user has an active card in Wallet.
* @param merchantIdentifier - The merchant ID created when the merchant enrolled in Apple Pay.
* @returns true if the device supports Apple Pay and there is at least one active card in Wallet that is qualified for payments on the web; otherwise, false.
*/
static canMakePaymentsWithActiveCard(merchantIdentifier: string): Promise<boolean>;
/**
* Displays the Set up Apple Pay button.
* @param merchantIdentifier - The merchant ID received when the merchant enrolled in Apple Pay.
* @param merchantIdentifier - The merchant ID created when the merchant enrolled in Apple Pay.
* @returns A boolean value indicating whether setup was successful.
*/
static openPaymentSetup(merchantIdentifier: string): Promise<boolean>;
/**
* Verifies if a web browser supports a given Apple Pay JS API version.
* @param version - A number representing the Apple Pay JS API version being checked. The initial version is 1.
* Verifies whether a web browser supports a given Apple Pay JS API version.
* @param version - A number representing the Apple Pay JS API version being checked. The initial version is 1. The latest version is 3.
* @returns A boolean value indicating whether the web browser supports the given API version. Returns false if the web browser does not support the specified version.
*/
static supportsVersion(version: number): boolean;
@@ -82,26 +82,33 @@ declare class ApplePaySession extends EventTarget {
begin(): void;
/**
* Call after the merchant has been validated.
* Completes the validation for a merchant session.
* @param merchantSession - An opaque message session object.
*/
completeMerchantValidation(merchantSession: any): void;
/**
* Call when a payment has been authorized.
* @param status - The status of the payment.
* Completes the payment authorization with a result.
* @param result - The status of the payment, whether it succeeded or failed for Apple Pay JS versions 1 and 2,
* or the result of the payment authorization, including its status and list of errors for Apple Pay JS version 3.
*/
completePayment(status: number): void;
completePayment(result: number | ApplePayJS.ApplePayPaymentAuthorizationResult): void;
/**
* Call after a payment method has been selected.
* Call after a payment method has been selected for Apple Pay JS versions 1 and 2.
* @param newTotal - An ApplePayLineItem dictionary representing the total price for the purchase.
* @param newLineItems - A sequence of ApplePayLineItem dictionaries.
*/
completePaymentMethodSelection(newTotal: ApplePayJS.ApplePayLineItem, newLineItems: ApplePayJS.ApplePayLineItem[]): void;
/**
* Call after a shipping contact has been selected.
* Completes the selection of a payment method with an update for Apple Pay JS version 3.
* @param update - The updated payment method.
*/
completePaymentMethodSelection(update: ApplePayJS.ApplePayPaymentMethodUpdate): void;
/**
* Completes the selection of a shipping contact with an update for Apple Pay JS versions 1 and 2.
* @param status - The status of the shipping contact update.
* @param newShippingMethods - A sequence of ApplePayShippingMethod dictionaries.
* @param newTotal - An ApplePayLineItem dictionary representing the total price for the purchase.
@@ -114,13 +121,25 @@ declare class ApplePaySession extends EventTarget {
newLineItems: ApplePayJS.ApplePayLineItem[]): void;
/**
* Call after the shipping method has been selected.
* Completes the selection of a shipping contact with an update for Apple Pay JS version 3.
* @param update - The updated shipping contact.
*/
completeShippingContactSelection(update: ApplePayJS.ApplePayShippingContactUpdate): void;
/**
* Call after the shipping method has been selected for Apple Pay JS versions 1 and 2.
* @param status - The status of the shipping method update.
* @param newTotal - An ApplePayLineItem dictionary representing the total price for the purchase.
* @param newLineItems - A sequence of ApplePayLineItem dictionaries.
*/
completeShippingMethodSelection(status: number, newTotal: ApplePayJS.ApplePayLineItem, newLineItems: ApplePayJS.ApplePayLineItem[]): void;
/**
* Completes the selection of a shipping method with an update for Apple Pay JS version 3.
* @param update - The updated shipping method.
*/
completeShippingMethodSelection(update: ApplePayJS.ApplePayShippingMethodUpdate): void;
/**
* The requested action succeeded.
*/
@@ -163,6 +182,78 @@ declare class ApplePaySession extends EventTarget {
}
declare namespace ApplePayJS {
/**
* Field names used for requesting contact information in a payment request.
*/
type ApplePayContactField =
'email' |
'name' |
'phone' |
'postalAddress' |
'phoneticName';
/**
* A customizable error type that you create to indicate problems with the address or contact information on an Apple Pay sheet.
*/
interface ApplePayError {
/**
* The error code for this instance.
*/
code: ApplePayErrorCode;
/**
* The name of the field that contains the error.
*/
contactField?: ApplePayErrorContactField;
/**
* A localized, user-facing string that describes the error.
*/
message: string;
}
/**
* The error code that indicates whether an error on the payment sheet is for shipping or billing information, or for another kind of error.
*/
type ApplePayErrorCode =
/**
* Shipping address or contact information is invalid or missing.
*/
'shippingContactInvalid' |
/**
* Billing address information is invalid or missing.
*/
'billingContactInvalid' |
/**
* The merchant cannot provide service to the shipping address (for example, can't deliver to a P.O. Box).
*/
'addressUnserviceable' |
/**
* An unknown but nonfatal error occurred during payment processing. The user can attempt authorization again.
*/
'unknown';
/**
* Names of the fields in the shipping or billing contact information, used to locate errors in the payment sheet.
*/
type ApplePayErrorContactField =
'phoneNumber' |
'emailAddress' |
'name' |
'phoneticName' |
'postalAddress' |
'addressLines' |
'locality' |
'subLocality' |
'postalCode' |
'administrativeArea' |
'subAdministrativeArea' |
'country' |
'countryCode';
/**
* Defines a line item in a payment request - for example, total, tax, discount, or grand total.
*/
@@ -180,15 +271,53 @@ declare namespace ApplePayJS {
/**
* A value that indicates if the line item is final or pending.
*/
type?: string;
type?: ApplePayLineItemType;
}
/**
* A type that indicates whether a line item is final or pending.
*/
type ApplePayLineItemType =
/**
* A line item representing the known, final cost.
*/
'final' |
/**
* A line item representing an estimated or unknown cost.
*/
'pending';
/**
* The payment capabilities supported by the merchant.
*/
type ApplePayMerchantCapability =
/**
* Required. This value must be supplied.
*/
'supports3DS' |
/**
* Include this value only if you support China Union Pay transactions.
*/
'supportsEMV' |
/**
* Optional. If present, only transactions that are categorized as credit cards are allowed.
*/
'supportsCredit' |
/**
* Optional. If present, only transactions that are categorized as debit cards are allowed.
*/
'supportsDebit';
/**
* Represents the result of authorizing a payment request and contains encrypted payment information.
*/
interface ApplePayPayment {
/**
* The encrypted token for an authorized payment.
* The encrypted information for an authorized payment.
*/
token: ApplePayPaymentToken;
@@ -208,11 +337,26 @@ declare namespace ApplePayJS {
*/
abstract class ApplePayPaymentAuthorizedEvent extends Event {
/**
* The payment token used to authorize a payment.
* The authorized payment information for this transaction.
*/
readonly payment: ApplePayPayment;
}
/**
* The result of payment authorization, including status and errors.
*/
interface ApplePayPaymentAuthorizationResult {
/**
* The status code for the authorization result.
*/
status: number;
/**
* A list of custom errors to display on the payment sheet.
*/
errors?: ApplePayError[];
}
/**
* Encapsulates contact information needed for billing and shipping.
*/
@@ -220,56 +364,76 @@ declare namespace ApplePayJS {
/**
* An email address for the contact.
*/
emailAddress: string;
emailAddress?: string;
/**
* The contact's family name.
*/
familyName: string;
familyName?: string;
/**
* The contact's given name.
*/
givenName: string;
givenName?: string;
/**
* A phone number for the contact.
*/
phoneNumber: string;
phoneNumber?: string;
/**
* The address for the contact.
* The phonetic spelling of the contact's family name.
*/
addressLines: string[];
phoneticFamilyName?: string;
/**
* The phonetic spelling of the contact's given name.
*/
phoneticGivenName?: string;
/**
* The street portion of the address for the contact.
*/
addressLines?: string[];
/**
* The city for the contact.
*/
locality: string;
locality?: string;
/**
* Additional information associated with the location, typically defined at the city or town level (such as district or neighborhood), in a postal address.
*/
subLocality?: string;
/**
* The state for the contact.
*/
administrativeArea: string;
administrativeArea?: string;
/**
* The zip code, where applicable, for the contact.
* The subadministrative area (such as a county or other region) in a postal address.
*/
postalCode: string;
subAdministrativeArea?: string;
/**
* The colloquial country name for the contact.
* The zip code or postal code, where applicable, for the contact.
*/
country: string;
postalCode?: string;
/**
* The contact's ISO country code.
* The name of the country for the contact.
*/
countryCode: string;
country?: string;
/**
* The contacts two-letter ISO 3166 country code.
*/
countryCode?: string;
}
/**
* Contains information about an Apple Pay payment card.
* A dictionary that describes an Apple Pay payment card.
*/
interface ApplePayPaymentMethod {
/**
@@ -279,21 +443,29 @@ declare namespace ApplePayJS {
/**
* A string, suitable for display, that is the name of the payment network backing the card.
* The value is one of the supported networks specified in the supportedNetworks property of the ApplePayPaymentRequest.
*/
network: string;
/**
* A value representing the card's type of payment.
*/
type: string;
type: ApplePayPaymentMethodType;
/**
* The payment pass object associated with the payment.
* The payment pass object currently selected to complete the payment.
*/
paymentPass: ApplePayPaymentPass;
}
/**
* A payment card's type of payment.
*/
type ApplePayPaymentMethodType =
'debit' |
'credit' |
'prepaid' |
'store';
/**
* The ApplePayPaymentMethodSelectedEvent class defines the attributes contained by the ApplePaySession.onpaymentmethodselected callback function.
*/
@@ -304,6 +476,21 @@ declare namespace ApplePayJS {
readonly paymentMethod: ApplePayPaymentMethod;
}
/**
* Updated transaction details resulting from a change in payment method.
*/
interface ApplePayPaymentMethodUpdate {
/**
* An optional list of line items.
*/
newLineItems?: ApplePayLineItem[];
/**
* The new total resulting from a change in the payment method.
*/
newTotal: ApplePayLineItem;
}
/**
* Represents a provisioned payment card for Apple Pay payments.
*/
@@ -331,9 +518,38 @@ declare namespace ApplePayJS {
/**
* The activation state of the pass.
*/
activationState: string;
activationState: ApplePayPaymentPassActivationState;
}
/**
* Payment pass activation states.
*/
type ApplePayPaymentPassActivationState =
/**
* Active and ready to be used for payment.
*/
'activated' |
/**
* Not active but may be activated by the issuer.
*/
'requiresActivation' |
/**
* Not ready for use but activation is in progress.
*/
'activating' |
/**
* Not active and can't be activated.
*/
'suspended' |
/**
* Not active because the issuer has disabled the account associated with the device.
*/
'deactivated';
/**
* Encapsulates a request for payment, including information about payment processing capabilities, the payment amount, and shipping information.
*/
@@ -357,7 +573,7 @@ declare namespace ApplePayJS {
* The payment capabilities supported by the merchant.
* The value must at least contain ApplePayMerchantCapability.supports3DS.
*/
merchantCapabilities: string[];
merchantCapabilities: ApplePayMerchantCapability[];
/**
* The payment networks supported by the merchant.
@@ -377,12 +593,12 @@ declare namespace ApplePayJS {
/**
* The billing information that you require from the user in order to process the transaction.
*/
requiredBillingContactFields?: string[];
requiredBillingContactFields?: ApplePayContactField[];
/**
* The shipping information that you require from the user in order to fulfill the order.
*/
requiredShippingContactFields?: string[];
requiredShippingContactFields?: ApplePayContactField[];
/**
* Shipping contact information for the user.
@@ -397,7 +613,12 @@ declare namespace ApplePayJS {
/**
* How the items are to be shipped.
*/
shippingType?: string;
shippingType?: ApplePayShippingType;
/**
* A list of ISO 3166 country codes for limiting payments to cards from specific countries.
*/
supportedCountries?: string[];
/**
* Optional user-defined data.
@@ -406,7 +627,7 @@ declare namespace ApplePayJS {
}
/**
* Contains the user's payment credentials.
* An object that contains the user's payment credentials.
*/
interface ApplePayPaymentToken {
/**
@@ -426,7 +647,7 @@ declare namespace ApplePayJS {
}
/**
* The ApplePayShippingContactSelectedEvent class defines the attributes contained by the ApplePaySession.onshippingcontactselected callback function.
* Encapsulates the attributes contained by the onshippingcontactselected callback function.
*/
abstract class ApplePayShippingContactSelectedEvent extends Event {
/**
@@ -435,6 +656,31 @@ declare namespace ApplePayJS {
readonly shippingContact: ApplePayPaymentContact;
}
/**
* Updated transaction details resulting from a change in shipping contact, including any errors.
*/
class ApplePayShippingContactUpdate {
/**
* List of custom errors to display on the payment sheet.
*/
errors?: ApplePayError[];
/**
* An optional list of updated line items.
*/
newLineItems?: ApplePayLineItem[];
/**
* A list of shipping methods that are available to the updated shipping contact.
*/
newShippingMethods?: ApplePayShippingMethod[];
/**
* The new total resulting from a change in the shipping contact.
*/
newTotal: ApplePayLineItem;
}
/**
* Defines a shipping method for delivering physical goods.
*/
@@ -471,11 +717,35 @@ declare namespace ApplePayJS {
}
/**
* The ApplePayValidateMerchantEvent class defines the attributes contained by the ApplePaySession.onvalidatemerchant callback function.
* Updated transaction details resulting from a change in shipping method.
*/
interface ApplePayShippingMethodUpdate {
/**
* An optional list of updated line items.
*/
newLineItems?: ApplePayLineItem[];
/**
* The new total resulting from a change in the shipping method.
*/
newTotal: ApplePayLineItem;
}
/**
* A type that indicates how purchased items are to be shipped.
*/
type ApplePayShippingType =
'shipping' |
'delivery' |
'storePickup' |
'servicePickup';
/**
* The attributes contained by the onvalidatemerchant callback function.
*/
abstract class ApplePayValidateMerchantEvent extends Event {
/**
* The URL used to validate the merchant server.
* The URL your server must use to validate itself and obtain a merchant session object.
*/
readonly validationURL: string;
}
+1 -1
View File
@@ -777,7 +777,7 @@ declare module Microsoft.ApplicationInsights {
* @param authenticatedUserId {string} - The authenticated user id. A unique and persistent string that represents each authenticated user in the service.
* @param accountId {string} - An optional string to represent the account associated with the authenticated user.
*/
setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string): any;
setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string, storeInCookie?: boolean): any;
/**
* Clears the authenticated user id and the account id from the user context.
*/
+37640 -1077
View File
File diff suppressed because it is too large Load Diff
+137 -34
View File
@@ -1,4 +1,4 @@
// Type definitions for ArcGIS API for JavaScript 3.22
// Type definitions for ArcGIS API for JavaScript 3.23
// Project: https://developers.arcgis.com/javascript/3/
// Definitions by: Esri <https://github.com/Esri>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -110,7 +110,10 @@ declare module "esri" {
resourceInfo?: any;
/** When true, the layer's attribution is displayed on the map. */
showAttribution?: boolean;
/** By default, images are exported in MIME format, and the image is streamed to the client. */
/**
* By default, images are exported in MIME format, and the image is streamed to the client.
* @deprecated
*/
useMapImage?: boolean;
/** When true, the layer will update its content based on the map's time extent. */
useMapTime?: boolean;
@@ -478,6 +481,10 @@ declare module "esri" {
zoomOptions?: any;
}
export interface ColorPickerOptions {
/** Indicates whether the widget displays collapsed. */
collapsed?: boolean;
/** Indicates whether the widget can be collapsed. */
collapsible?: boolean;
/** The selected color. */
color: Color;
/** The row size of the palette. */
@@ -1830,8 +1837,10 @@ declare module "esri" {
whereFields: any;
}
export interface QueryTaskOptions {
/** Specify the geodatabase version to display. */
/** The geodatabase version to display. */
gdbVersion?: string;
/** The dynamic layer or table source. */
source?: LayerSource;
}
export interface RasterLayerOptions {
/** Sets the layer's draw mode. */
@@ -2150,9 +2159,15 @@ declare module "esri" {
export interface SymbolStylerOptions {
/** Added at v. */
portal?: string | any;
/** Self response of Portal used as symbol provider. */
/**
* Self response of Portal used as symbol provider.
* @deprecated
*/
portalSelf?: any;
/** URL to Portal used as symbol provider. */
/**
* URL to Portal used as symbol provider.
* @deprecated
*/
portalUrl?: string;
}
export interface TemplatePickerOptions {
@@ -3852,6 +3867,10 @@ declare module "esri/dijit/ColorPicker" {
/** A widget to assist choosing a color from a color palette. */
class ColorPicker {
/** Indicates whether the widget displays collapsed. */
collapsed: boolean;
/** Indicates whether the widget is collapsible. */
collapsible: boolean;
/** The selected color. */
color: Color;
/** The set of available color options. */
@@ -3921,7 +3940,10 @@ declare module "esri/dijit/Directions" {
* @param srcNodeRef Reference or id of a HTML element that this dijit is rendered into.
*/
constructor(options: esri.DirectionsOptions, srcNodeRef: Node | string);
/** Deprecated at v3.13. */
/**
* Deprecated at v3.13.
* @deprecated
*/
activate(): void;
/**
* Add a stop to the directions widget at the specified index location.
@@ -3942,7 +3964,10 @@ declare module "esri/dijit/Directions" {
centerAtSegmentStart(index: number): void;
/** Remove the route directions from the directions list. */
clearDirections(): void;
/** Deprecated at v3.13. */
/**
* Deprecated at v3.13.
* @deprecated
*/
deactivate(): void;
/** Destroy the Directions widget. */
destroy(): void;
@@ -4106,7 +4131,10 @@ declare module "esri/dijit/FeatureTable" {
featureLayer: FeatureLayer;
/** An array of objects representing field information. */
fieldInfos: any[];
/** Reference to the dGrid. */
/**
* Reference to the dGrid.
* @deprecated
*/
grid: any;
/** Reference to the 'Options' drop-down menu. */
gridMenu: any;
@@ -8158,9 +8186,9 @@ declare module "esri/geometry/geometryEngine" {
*/
nearestVertices(geometry: Geometry, inputPoint: Point, searchRadius: number, maxVertexCountToReturn: number): any[];
/**
* Creates offset version of the input geometry.
* The offset operation creates a geometry that is a constant planar distance from an input polyline or polygon.
* @param geometry The geometries to offset.
* @param offsetDistance The offset distance for the Geometries.
* @param offsetDistance The planar distance to offset from the input geometry.
* @param offsetUnit Measurement unit for the offset.
* @param joinType The join type.
* @param bevelRatio Applicable to MITER, bevelRatio is multiplied by the offset distance and the result determines how far a mitered offset intersection can be located before it is beveled.
@@ -8401,9 +8429,9 @@ declare module "esri/geometry/geometryEngineAsync" {
*/
nearestVertices(geometry: Geometry, inputPoint: Point, searchRadius: number, maxVertexCountToReturn: number): any;
/**
* Creates offset version of the input geometry.
* The offset operation creates a geometry that is a constant planar distance from an input polyline or polygon.
* @param geometry The geometries to offset.
* @param offsetDistance The offset distance for the Geometries.
* @param offsetDistance The planar distance to offset from the input geometry.
* @param offsetUnit Measurement unit for the offset.
* @param joinType The join type.
* @param bevelRatio Applicable to MITER, bevelRatio is multiplied by the offset distance and the result determines how far a mitered offset intersection can be located before it is beveled.
@@ -8583,6 +8611,7 @@ declare module "esri/geometry/screenUtils" {
* @param width The current width of the map in screen units.
* @param height The current height of the map in screen units.
* @param screenPoint The screenPoint to convert from screen to map units.
* @deprecated
*/
toMapPoint(extent: Extent, width: number, height: number, screenPoint: ScreenPoint): Point;
/**
@@ -8599,6 +8628,7 @@ declare module "esri/geometry/screenUtils" {
* @param width The current width of the map in screen units.
* @param height The current height of the map in screen units.
* @param mapPoint The point to convert from map to screen units.
* @deprecated
*/
toScreenPoint(extent: Extent, width: number, height: number, mapPoint: Point): ScreenPoint;
};
@@ -8691,14 +8721,14 @@ declare module "esri/graphic" {
clone(): Graphic;
/** Draws the graphic. */
draw(): Graphic;
/**
* Returns the graphics summarized by the given aggregate graphic in a clustering or feature reduction visualization.
* @param aggregateGraphic A graphic representing the aggregation (or reduction) of several individual graphics in a layer.
*/
getChildGraphics(aggregateGraphic: Graphic): Graphic[];
/** Returns the graphics summarized by an aggregate graphic in a clustering or feature reduction visualization. */
getChildGraphics(): Graphic[];
/** Returns the content string based on attributes and infoTemplate values. */
getContent(): string;
/** Returns the dojo/gfx/shape.Shape of the Esri graphic. */
/**
* Returns the dojo/gfx/shape.Shape of the Esri graphic.
* @deprecated
*/
getDojoShape(): any;
/** Returns the info template associated with the graphic. */
getInfoTemplate(): InfoTemplate;
@@ -8880,7 +8910,10 @@ declare module "esri/layers/ArcGISDynamicMapServiceLayer" {
timeInfo: TimeInfo;
/** Default units of the layer as defined by the service. */
units: string;
/** When true, the image is saved to the server, and a JSON formatted response is sent to the client with the URL location of the image. */
/**
* When true, the image is saved to the server, and a JSON formatted response is sent to the client with the URL location of the image.
* @deprecated
*/
useMapImage: boolean;
/** The version of ArcGIS Server where the map service is published. */
version: number;
@@ -10836,7 +10869,10 @@ declare module "esri/layers/RasterDataSource" {
declare module "esri/layers/RasterFunction" {
/** Specifies the processing to be done to the image service. */
class RasterFunction {
/** Deprecated at v3.10, use functionArguments instead. */
/**
* Deprecated at v3.10, use functionArguments instead.
* @deprecated
*/
arguments: any;
/** The arguments for the raster function. */
functionArguments: any;
@@ -12326,7 +12362,10 @@ declare module "esri/opsdashboard/ExtensionBase" {
portalHelperServices: any;
/** Read-only: The URL to the ArcGIS.com site or in-house portal that you are currently signed in to. */
portalUrl: string;
/** Get the collection of data sources from the host application. */
/**
* Get the collection of data sources from the host application.
* @deprecated
*/
getDataSourceProxies(): any;
/**
* Get the data source corresponding to the data source id from the host application.
@@ -12954,7 +12993,10 @@ declare module "esri/renderers/ClassBreaksRenderer" {
attributeField: string;
/** To symbolize polygon features with graduated symbols, use backgroundFillSymbol to specify a simple fill symbol to represent polygon features, and use marker symbols of varying sizes in class breaks to indicate the quantity. */
backgroundFillSymbol: FillSymbol;
/** Deprecated at v2.0, use infos instead. */
/**
* Deprecated at v2.0, use infos instead.
* @deprecated
*/
breaks: any[];
/** The classification method used to generate class breaks. */
classificationMethod: string;
@@ -13136,13 +13178,25 @@ declare module "esri/renderers/Renderer" {
/** The base class for the renderers - SimpleRenderer, ClassBreaksRenderer, UniqueValueRenderer, DotDensityRenderer, ScaleDependentRenderer, TemporalRenderer, HeatmapRenderer, and VectorFieldRenderer used with a GraphicsLayer and FeatureLayer. */
class Renderer {
/** Deprecated. */
/**
* Deprecated.
* @deprecated
*/
colorInfo: any;
/** Deprecated. */
/**
* Deprecated.
* @deprecated
*/
opacityInfo: any;
/** Deprecated. */
/**
* Deprecated.
* @deprecated
*/
rotationInfo: any;
/** Deprecated. */
/**
* Deprecated.
* @deprecated
*/
sizeInfo: any;
/** This property allows you to define how to render values in a layer. */
visualVariables: any[];
@@ -13185,21 +13239,25 @@ declare module "esri/renderers/Renderer" {
/**
* Deprecated.
* @param info An info object that defines the color.
* @deprecated
*/
setColorInfo(info: any): Renderer;
/**
* Deprecated.
* @param info The info parameter is an object with the same properties as opacityInfo.
* @deprecated
*/
setOpacityInfo(info: any): Renderer;
/**
* Deprecated.
* @param info An object with the same properties as rotationInfo.
* @deprecated
*/
setRotationInfo(info: any): Renderer;
/**
* Deprecated.
* @param info An object with the same properties as sizeInfo.
* @deprecated
*/
setSizeInfo(info: any): Renderer;
/**
@@ -13417,7 +13475,10 @@ declare module "esri/renderers/UniqueValueRenderer" {
valueExpression: string;
/** The title identifying and describing the associated Arcade expression as defined in the valueExpression property. */
valueExpressionTitle: string;
/** Deprecated at v2.0, use infos instead. */
/**
* Deprecated at v2.0, use infos instead.
* @deprecated
*/
values: string[];
/**
* Creates a new UniqueValueRenderer object.
@@ -13588,6 +13649,20 @@ declare module "esri/request" {
export = request;
}
declare module "esri/support/expressionUtils" {
/** A utility module that allows you to enable geometry operations referenced inside Arcade expressions. */
var expressionUtils: {
/** Loads all geometry operations for use in any Arcade expression within the given application. */
enableGeometryOperations(): any;
/**
* Indicates if the given Arcade expression contains one or more geometry operations.
* @param expression The Arcade expression to evaluate for the presence of one or more geometry operations.
*/
hasGeometryOperations(expression: string): boolean;
};
export = expressionUtils;
}
declare module "esri/symbols/CartographicLineSymbol" {
import SimpleLineSymbol = require("esri/symbols/SimpleLineSymbol");
import Color = require("esri/Color");
@@ -13718,7 +13793,10 @@ declare module "esri/symbols/Font" {
size: number;
/** Text style. */
style: string;
/** Text variant. */
/**
* Text variant (deprecated).
* @deprecated
*/
variant: string;
/** Text weight. */
weight: string;
@@ -13759,8 +13837,9 @@ declare module "esri/symbols/Font" {
*/
setStyle(style: string): Font;
/**
* Sets the font variant.
* Sets the font variant (deprecated).
* @param variant Font variant.
* @deprecated
*/
setVariant(variant: string): Font;
/**
@@ -14018,6 +14097,8 @@ declare module "esri/symbols/SimpleLineSymbol" {
static STYLE_SHORTDOT: any;
/** The line is solid. */
static STYLE_SOLID: any;
/** Indicates marker symbols present at the beginning and/or end of a SimpleLineSymbol. */
marker: any;
/** The line style. */
style: string;
/** Creates a new empty SimpleLineSymbol object. */
@@ -14034,6 +14115,11 @@ declare module "esri/symbols/SimpleLineSymbol" {
* @param json JSON object representing the SimpleLineSymbol.
*/
constructor(json: Object);
/**
* Sets marker symbols at the beginning and/or end of a SimpleLineSymbol.
* @param options The options defining the marker style and placement.
*/
setMarker(options: any): void;
/**
* Sets the line symbol style.
* @param style Line style.
@@ -14143,11 +14229,17 @@ declare module "esri/symbols/TextSymbol" {
static DECORATION_OVERLINE: any;
/** Text is underlined. */
static DECORATION_UNDERLINE: any;
/** The text alignment in relation to the point. */
/**
* The text alignment in relation to the point.
* @deprecated
*/
align: string;
/** Text angle. */
angle: number;
/** The decoration on the text. */
/**
* The decoration on the text.
* @deprecated
*/
decoration: string;
/** Font for displaying text. */
font: Font;
@@ -14189,6 +14281,7 @@ declare module "esri/symbols/TextSymbol" {
/**
* Sets the alignment of the text.
* @param align The text alignment.
* @deprecated
*/
setAlign(align: string): TextSymbol;
/**
@@ -14199,6 +14292,7 @@ declare module "esri/symbols/TextSymbol" {
/**
* Sets the decoration for the text.
* @param decoration The decoration on the text.
* @deprecated
*/
setDecoration(decoration: string): TextSymbol;
/**
@@ -15038,7 +15132,7 @@ declare module "esri/tasks/GeometryService" {
*/
lengths(lengthsParameter: LengthsParameters, callback?: Function, errback?: Function): any;
/**
* Constructs the offset of the input geometries.
* Constructs the offset of the input geometries based on a planar distance.
* @param params Set the geometries to offset, distance and units.
* @param callback The function to call when the method has completed.
* @param errback An error object is returned if an error occurs during task execution.
@@ -15150,7 +15244,10 @@ declare module "esri/tasks/Geoprocessor" {
/** Represents a GP Task resource exposed by the ArcGIS Server REST API. */
class Geoprocessor {
/** Deprecated at v2.0, use outSpatialReference instead. */
/**
* Deprecated at v2.0, use outSpatialReference instead.
* @deprecated
*/
outputSpatialReference: SpatialReference;
/** The spatial reference of the output geometries. */
outSpatialReference: SpatialReference;
@@ -15219,6 +15316,7 @@ declare module "esri/tasks/Geoprocessor" {
/**
* Deprecated at v2.0, use setOutSpatialReference instead.
* @param spatialReference The well-known ID of a spatial reference.
* @deprecated
*/
setOutputSpatialReference(spatialReference: SpatialReference): void;
/**
@@ -15680,7 +15778,7 @@ declare module "esri/tasks/OffsetParameters" {
bevelRatio: number;
/** The array of geometries to be offset. */
geometries: Geometry[];
/** Specifies the distance for constructing an offset based on the input geometries. */
/** Specifies the planar distance for constructing an offset based on the input geometries. */
offsetDistance: number;
/** Options that determine how the ends intersect. */
offsetHow: string;
@@ -15806,12 +15904,17 @@ declare module "esri/tasks/ProjectParameters" {
declare module "esri/tasks/QueryTask" {
import esri = require("esri");
import LayerSource = require("esri/layers/LayerSource");
import Query = require("esri/tasks/query");
import RelationshipQuery = require("esri/tasks/RelationshipQuery");
import FeatureSet = require("esri/tasks/FeatureSet");
/** Executes a query operation on a layer resource of a map service exposed by the ArcGIS Server REST API. */
class QueryTask {
/** The geodatabase version to display. */
gdbVersion: string;
/** The dynamic layer or table source. */
source: LayerSource;
/** URL to the ArcGIS Server REST resource that represents a map service layer. */
url: string;
/**
+7
View File
@@ -0,0 +1,7 @@
import union = require('arr-union');
// $ExpectType string[]
union(['a'], ['b', 'c'], ['d', 'e', 'f']);
// $ExpectType number[]
union([1, 1], [2, 3]);
+8
View File
@@ -0,0 +1,8 @@
// Type definitions for arr-union 3.1
// Project: https://github.com/jonschlinkert/arr-union
// Definitions by: mrmlnc <https://github.com/mrmlnc>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare function union<T>(...arrays: Array<ArrayLike<T>>): T[];
export = union;
+23
View File
@@ -0,0 +1,23 @@
{
"compilerOptions": {
"module": "commonjs",
"lib": [
"es6"
],
"noImplicitAny": true,
"noImplicitThis": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"baseUrl": "../",
"typeRoots": [
"../"
],
"types": [],
"noEmit": true,
"forceConsistentCasingInFileNames": true
},
"files": [
"index.d.ts",
"arr-union-tests.ts"
]
}
+1 -1
View File
@@ -1,6 +1,6 @@
import * as ascii2mathml from 'ascii2mathml';
const fn = ascii2mathml({}); // $ExpectType any
const fn = ascii2mathml({}); // $ExpectType ascii2mathml
fn(''); // $ExpectType string
ascii2mathml('', {}); // $ExpectType string
+8 -4
View File
@@ -11,7 +11,7 @@ export interface Dictionary<T> { [key: string]: T; }
export interface ErrorCallback<T> { (err?: T): void; }
export interface AsyncBooleanResultCallback<E> { (err?: E, truthValue?: boolean): void; }
export interface AsyncResultCallback<T, E> { (err?: E, result?: T): void; }
export interface AsyncResultArrayCallback<T, E> { (err?: E, results?: (T | undefined)[]): void; }
export interface AsyncResultArrayCallback<T, E> { (err?: E, results?: Array<T | undefined>): void; }
export interface AsyncResultObjectCallback<T, E> { (err: E | undefined, results: Dictionary<T | undefined>): void; }
export interface AsyncFunction<T, E> { (callback: (err?: E, result?: T) => void): void; }
@@ -116,8 +116,12 @@ export const eachOfLimit: typeof forEachOfLimit;
export function map<T, R, E>(arr: T[] | IterableIterator<T>, iterator: AsyncResultIterator<T, R, E>, callback?: AsyncResultArrayCallback<R, E>): void;
export function map<T, R, E>(arr: Dictionary<T>, iterator: AsyncResultIterator<T, R, E>, callback?: AsyncResultArrayCallback<R, E>): void;
export const mapSeries: typeof map;
export function mapLimit<T, R, E>(arr: T[] | IterableIterator<T>, limit: number, iterator: AsyncResultIterator<T, R, E>, callback?: AsyncResultArrayCallback<R, E>): void;
export function mapLimit<T, R, E>(arr: Dictionary<T>, limit: number, iterator: AsyncResultIterator<T, R, E>, callback?: AsyncResultArrayCallback<R, E>): void;
export function mapLimit<T, R, E>(
arr: T[] | Dictionary<T> | IterableIterator<T>,
limit: number,
iterator: AsyncResultIterator<T, R, E>,
callback?: AsyncResultArrayCallback<R, E>
): void;
export function mapValuesLimit<T, R, E>(obj: Dictionary<T>, limit: number, iteratee: (value: T, key: string, callback: AsyncResultCallback<R, E>) => void, callback: AsyncResultObjectCallback<R, E>): void;
export function mapValues<T, R, E>(obj: Dictionary<T>, iteratee: (value: T, key: string, callback: AsyncResultCallback<R, E>) => void, callback: AsyncResultObjectCallback<R, E>): void;
export const mapValuesSeries: typeof mapValues;
@@ -222,7 +226,7 @@ export function memoize(fn: Function, hasher?: Function): Function;
export function unmemoize(fn: Function): Function;
export function ensureAsync(fn: (... argsAndCallback: any[]) => void): Function;
export function constant(...values: any[]): Function;
export function asyncify(fn: Function): Function;
export function asyncify(fn: Function): (...args: any[]) => any;
export function wrapSync(fn: Function): Function;
export function log(fn: Function, ...args: any[]): void;
export function dir(fn: Function, ...args: any[]): void;
+37 -37
View File
@@ -9,16 +9,16 @@
import { EventEmitter } from "events";
export abstract class AsyncIterator<T> extends NodeJS.EventEmitter {
protected static STATES: ['INIT', 'OPEN', 'CLOSING', 'CLOSED', 'ENDED'];
protected static INIT: 0;
protected static OPEN: 1;
protected static CLOSING: 2;
protected static CLOSED: 3;
protected static ENDED: 4;
static STATES: ['INIT', 'OPEN', 'CLOSING', 'CLOSED', 'ENDED'];
static INIT: 0;
static OPEN: 1;
static CLOSING: 2;
static CLOSED: 3;
static ENDED: 4;
protected _state: number;
protected _readable: boolean;
protected _destination?: AsyncIterator<any>;
_state: number;
_readable: boolean;
_destination?: AsyncIterator<any>;
readable: boolean;
closed: boolean;
@@ -30,11 +30,11 @@ export abstract class AsyncIterator<T> extends NodeJS.EventEmitter {
each(callback: (data: T) => void, self?: any): void;
close(): void;
protected _changeState(newState: number, eventAsync?: boolean): void;
_changeState(newState: number, eventAsync?: boolean): void;
private _hasListeners(eventName: string | symbol): boolean;
// tslint:disable-next-line ban-types
private _addSingleListener(eventName: string | symbol, listener: Function): void;
protected _end(): void;
_end(): void;
getProperty(propertyName: string, callback?: (value: any) => void): any;
setProperty(propertyName: string, value: any): void;
@@ -43,7 +43,7 @@ export abstract class AsyncIterator<T> extends NodeJS.EventEmitter {
copyProperties(source: AsyncIterator<any>, propertyNames: string[]): void;
toString(): string;
protected _toStringDetails(): string;
_toStringDetails(): string;
transform<T2>(options?: SimpleTransformIteratorOptions<T, T2>): SimpleTransformIterator<T, T2>;
map<T2>(mapper: (item: T) => T2, self?: object): SimpleTransformIterator<T, T2>;
@@ -78,9 +78,9 @@ export interface IntegerIteratorOptions {
}
export class IntegerIterator extends AsyncIterator<number> {
protected _step: number;
protected _last: number;
protected _next: number;
_step: number;
_last: number;
_next: number;
constructor(options?: IntegerIteratorOptions);
}
@@ -92,16 +92,16 @@ export interface BufferedIteratorOptions {
export class BufferedIterator<T> extends AsyncIterator<T> {
maxBufferSize: number;
protected _pushedCount: number;
protected _buffer: T[];
_pushedCount: number;
_buffer: T[];
protected _init(autoStart: boolean): void;
protected _begin(done: () => void): void;
protected _read(count: number, done: () => void): void;
protected _push(item: T): void;
protected _fillBuffer(): void;
protected _completeClose(): void;
protected _flush(done: () => void): void;
_init(autoStart: boolean): void;
_begin(done: () => void): void;
_read(count: number, done: () => void): void;
_push(item: T): void;
_fillBuffer(): void;
_completeClose(): void;
_flush(done: () => void): void;
constructor(options?: BufferedIteratorOptions);
}
@@ -112,12 +112,12 @@ export interface TransformIteratorOptions<S> extends BufferedIteratorOptions {
}
export class TransformIterator<S, T> extends BufferedIterator<T> {
protected _optional: boolean;
_optional: boolean;
source: AsyncIterator<S>;
protected _validateSource(source: AsyncIterator<S>, allowDestination?: boolean): void;
protected _transform(item: S, done: (result: T) => void): void;
protected _closeWhenDone(): void;
_validateSource(source: AsyncIterator<S>, allowDestination?: boolean): void;
_transform(item: S, done: (result: T) => void): void;
_closeWhenDone(): void;
constructor(source?: AsyncIterator<S> | TransformIteratorOptions<S>, options?: TransformIteratorOptions<S>);
}
@@ -134,16 +134,16 @@ export interface SimpleTransformIteratorOptions<S, T> extends TransformIteratorO
}
export class SimpleTransformIterator<S, T> extends TransformIterator<S, T> {
protected _offset: number;
protected _limit: number;
protected _prepender?: ArrayIterator<T>;
protected _appender?: ArrayIterator<T>;
_offset: number;
_limit: number;
_prepender?: ArrayIterator<T>;
_appender?: ArrayIterator<T>;
protected _filter?(item: S): boolean;
protected _map?(item: S): T;
protected _transform(item: S, done: (result: T) => void): void;
_filter?(item: S): boolean;
_map?(item: S): T;
_transform(item: S, done: (result: T) => void): void;
protected _insert(inserter: AsyncIterator<S>, done: () => void): void;
_insert(inserter: AsyncIterator<S>, done: () => void): void;
constructor(source?: AsyncIterator<S> | SimpleTransformIteratorOptions<S, T>,
options?: SimpleTransformIteratorOptions<S, T>);
@@ -152,7 +152,7 @@ export class SimpleTransformIterator<S, T> extends TransformIterator<S, T> {
export class MultiTransformIterator<S, T> extends TransformIterator<S, T> {
_transformerQueue: S[];
protected _createTransformer(): AsyncIterator<S>;
_createTransformer(element: S): AsyncIterator<T>;
constructor(source?: AsyncIterator<S> | TransformIteratorOptions<S>, options?: TransformIteratorOptions<S>);
}
+1 -1
View File
@@ -2,7 +2,7 @@
// Project: https://github.com/atom/atom-keymap
// Definitions by: GlenCFL <https://github.com/GlenCFL>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
// TypeScript Version: 2.3
import { Disposable } from "event-kit";
+120 -15
View File
@@ -13,6 +13,7 @@ declare let element: HTMLElement;
declare let elements: HTMLElement[];
declare const div: HTMLDivElement;
declare const event: KeyboardEvent;
declare const mouseEvent: MouseEvent;
declare let buffer: Atom.TextBuffer;
declare const color: Atom.Color;
@@ -65,6 +66,9 @@ declare let subscription: Atom.Disposable;
declare let subscriptions: Atom.CompositeDisposable;
declare let tooltips: Atom.Tooltip[];
declare let workspaceCenter: Atom.WorkspaceCenter;
declare let pixelPos: Atom.PixelPosition;
declare let textEditorElement: Atom.TextEditorElement;
declare let textEditorComponent: Atom.TextEditorComponent;
// AtomEnvironment ============================================================
function testAtomEnvironment() {
@@ -196,6 +200,8 @@ function testAtomEnvironment() {
}
atom.executeJavaScriptInDevTools("Test");
const path: string = atom.getConfigDirPath();
}
// BufferedNodeProcess ========================================================
@@ -267,6 +273,16 @@ function testCommandRegistry() {
description: "A Command Test",
displayName: "Command: Test",
});
atom.commands.add("atom-text-editor", {
"test-function": (event) => event.currentTarget.getModel(),
"test-function2": (event) => event.currentTarget.getComponent(),
});
atom.commands.add("atom-workspace", {
"test-command": {
didDispatch: (event) => {},
hiddenInCommandPalette: true
}
});
const commands = atom.commands.findCommands({ target: element });
atom.commands.dispatch(element, "test:function");
@@ -505,6 +521,8 @@ function testDecoration() {
// Decoration Details
num = decoration.getId();
displayMarker = decoration.getMarker();
bool = decoration.isType("line-number");
bool = decoration.isType(["line-number", "line"]);
// Properties
const decorationProps = decoration.getProperties();
@@ -844,9 +862,12 @@ function testDock() {
}
// Emitter ====================================================================
interface TestEmissions {
"test-event": string;
}
function testEmitter() {
emitter = new Atom.Emitter();
emitter.clear();
emitter.dispose();
@@ -858,6 +879,27 @@ function testEmitter() {
// Event Emission
emitter.emit("test-event");
emitter.emit("test-event", 42);
// Optional Value Emitter
const optEmitter = new Atom.Emitter<{ "test-event": string }>();
optEmitter.emit("test-event");
optEmitter.emit("test-event", "test");
optEmitter.on("test-event", value => {
str = value ? value : "";
});
// Required Value Emitter
const reqEmitter = new Atom.Emitter<{}, TestEmissions>();
reqEmitter.on("test-event", value => {
str = value;
});
reqEmitter.emit("test-event", "test");
// Mixed Value Emitter
const mixedEmitter = new Atom.Emitter<{ "t1": "test" }, { "t2": "test" }>();
mixedEmitter.emit("t1");
mixedEmitter.emit("t1", "test");
mixedEmitter.emit("t2", "test");
}
// File =======================================================================
@@ -1032,6 +1074,10 @@ function testGrammar() {
tokenizeLineResult.tokens;
grammar.tokenizeLine("Test String", tokenizeLineResult.ruleStack);
grammar.tokenizeLine("Test String", tokenizeLineResult.ruleStack, false);
let str: string;
str = grammar.name;
str = grammar.scopeName;
}
// GrammarRegistry ============================================================
@@ -1039,6 +1085,7 @@ function testGrammarRegistry() {
// Event Subscription
subscription = registry.onDidAddGrammar(grammar => grammar.name);
subscription = registry.onDidUpdateGrammar(grammar => grammar.name);
subscription = registry.onDidRemoveGrammar(grammar => grammar.name);
// Managing Grammars
grammars = registry.getGrammars();
@@ -1372,6 +1419,9 @@ function testPackageManager() {
subscription = atom.packages.onDidDeactivatePackage(pack => pack.path);
subscription = atom.packages.onDidLoadPackage(pack => pack.isCompatible());
subscription = atom.packages.onDidUnloadPackage(pack => pack.name);
subscription = atom.packages.onDidTriggerActivationHook(
'language-javascript:grammar-used', () => {}
);
// Package system data
str = atom.packages.getApmPath();
@@ -1563,7 +1613,8 @@ function testPanel() {
}
// PathWatcher ================================================================
function testPathWatcher() {
async function testPathWatcher() {
const pathWatcher = await pathWatcherPromise;
pathWatcher.dispose();
subscription = pathWatcher.onDidError((error) => str = error.name);
@@ -1854,7 +1905,7 @@ function testSelection() {
selection.insertText("Replacement", { undo: "skip" });
selection.insertText("Replacement", { select: true, autoIndent: true,
autoIndentNewline: true, autoDecreaseIndent: true, normalizeLineEndings: true,
undo: "skip" });
undo: "skip", preserveTrailingLineIndentation: false });
selection.backspace();
selection.deleteToPreviousWordBoundary();
@@ -1956,7 +2007,14 @@ function testTextBuffer() {
// Event Subscription
subscription = buffer.onWillChange(() => void {});
subscription = buffer.onDidChange(() => void {});
subscription = buffer.onDidChange((event): void => {
range = event.newRange;
for (const change of event.changes) {
range = change.newRange;
}
});
subscription = buffer.onDidChangeText(() => void {});
subscription = buffer.onDidStopChanging((event): void => {
@@ -2328,14 +2386,14 @@ function testTextEditor() {
// Mutating Text
editor.setText("Test");
editor.setTextInBufferRange(range, "Test");
editor.setTextInBufferRange([pos, pos], "Test");
editor.setTextInBufferRange([pos, [0, 0]], "Test");
editor.setTextInBufferRange([[0, 0], pos], "Test");
editor.setTextInBufferRange([[0, 0], [0, 0]], "Test");
editor.setTextInBufferRange(range, "Test", {});
editor.setTextInBufferRange([pos, pos], "Test", { normalizeLineEndings: true });
editor.setTextInBufferRange(range, "Test", { normalizeLineEndings: true,
range = editor.setTextInBufferRange(range, "Test");
range = editor.setTextInBufferRange([pos, pos], "Test");
range = editor.setTextInBufferRange([pos, [0, 0]], "Test");
range = editor.setTextInBufferRange([[0, 0], pos], "Test");
range = editor.setTextInBufferRange([[0, 0], [0, 0]], "Test");
range = editor.setTextInBufferRange(range, "Test", {});
range = editor.setTextInBufferRange([pos, pos], "Test", { normalizeLineEndings: true });
range = editor.setTextInBufferRange(range, "Test", { normalizeLineEndings: true,
undo: "skip" });
editor.insertText("Test");
@@ -2347,7 +2405,8 @@ function testTextEditor() {
editor.insertText("Test", { select: true });
editor.insertText("Test", { undo: "skip" });
editor.insertText("Text", { autoDecreaseIndent: false, autoIndent: false,
autoIndentNewline: false, normalizeLineEndings: false, select: false, undo: "skip" });
autoIndentNewline: false, normalizeLineEndings: false, select: false,
undo: "skip", preserveTrailingLineIndentation: true });
editor.insertNewline();
editor.delete();
@@ -2898,6 +2957,15 @@ function testTextEditor() {
// TextEditor Rendering
str = editor.getPlaceholderText();
editor.setPlaceholderText("Test");
range = editor.bufferRangeForScopeAtPosition('source.js', [0, 0]);
range = editor.bufferRangeForScopeAtPosition('source.js', {row: 10, column: 11});
range = editor.bufferRangeForScopeAtPosition('source.js', pos);
let token: {value: string, scopes: string[]};
token = editor.tokenForBufferPosition([5, 6]);
token = editor.tokenForBufferPosition({row: 0, column: 1});
token = editor.tokenForBufferPosition(pos);
}
// ThemeManager ===============================================================
@@ -2939,7 +3007,7 @@ function testTooltipManager() {
subscription = atom.tooltips.add(element, { class: "test-class" });
subscription = atom.tooltips.add(element, { placement: "top" });
subscription = atom.tooltips.add(element, { placement: () => "left" });
subscription = atom.tooltips.add(element, { placement: () => "auto left" });
subscription = atom.tooltips.add(element, { trigger: "click" });
subscription = atom.tooltips.add(element, { delay: { hide: 42, show: 42 }});
@@ -2957,6 +3025,7 @@ function testViewRegistry() {
});
element = atom.views.getView(element);
textEditorElement = atom.views.getView(editor);
}
// Workspace ==================================================================
@@ -3189,10 +3258,46 @@ function testWorkspaceCenter() {
}
// watchPath ==================================================================
const pathWatcher = Atom.watchPath("/var/test", {}, (events) => {
const pathWatcherPromise = Atom.watchPath("/var/test", {}, (events) => {
for (const event of events) {
str = event.path;
str = event.action;
if (event.oldPath) str = event.oldPath;
}
});
// TextEditorElement ==========================================================
function testTextEditorElement() {
textEditorComponent = textEditorElement.getComponent();
editor = textEditorElement.getModel();
textEditorElement.getNextUpdatePromise().then(() => {});
let num: number = textEditorElement.getBaseCharacterWidth();
textEditorElement.scrollToTop();
textEditorElement.scrollToBottom();
textEditorElement.setScrollTop(num);
num = textEditorElement.getScrollTop();
textEditorElement.setScrollLeft(num);
num = textEditorElement.getScrollLeft();
num = textEditorElement.getScrollHeight();
pixelPos = textEditorElement.pixelPositionForBufferPosition(pos);
pixelPos = textEditorElement.pixelPositionForScreenPosition({row: 1, column: 2});
pixelPos = textEditorElement.pixelPositionForScreenPosition(pos);
subscription = textEditorElement.onDidChangeScrollTop((scrollTop: number) => {});
subscription = textEditorElement.onDidChangeScrollLeft((scrollLeft: number) => {});
subscription = textEditorElement.onDidAttach(() => {});
subscription = textEditorElement.onDidDetach(() => {});
textEditorElement = document.createElement('atom-text-editor');
}
// TextEditorComponent ========================================================
function testTextEditorComponent() {
pixelPos = textEditorComponent.pixelPositionForMouseEvent(mouseEvent);
pixelPos = textEditorComponent.pixelPositionForScreenPosition(pos);
pos = textEditorComponent.screenPositionForMouseEvent(mouseEvent);
pos = textEditorComponent.screenPositionForPixelPosition(pixelPos);
}
+234 -72
View File
@@ -1,12 +1,13 @@
// Type definitions for Atom 1.22
// Type definitions for Atom 1.23
// Project: https://github.com/atom/atom
// Definitions by: GlenCFL <https://github.com/GlenCFL>,
// Definitions by: GlenCFL <https://github.com/GlenCFL>
// smhxx <https://github.com/smhxx>
// lierdakil <https://github.com/lierdakil>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.3
// NOTE: only those classes exported within this file should be retain that status below.
// https://github.com/atom/atom/blob/v1.22.0/exports/atom.js
// https://github.com/atom/atom/blob/v1.23.0/exports/atom.js
/// <reference types="jquery" />
/// <reference types="node" />
@@ -16,6 +17,10 @@ import { ChildProcess } from "child_process";
declare global {
const atom: AtomEnvironment;
interface HTMLElementTagNameMap {
"atom-text-editor": TextEditorElement;
}
}
/**
@@ -24,7 +29,7 @@ declare global {
* Project::onDidChangeFiles instead.
*/
export function watchPath(rootPath: string, options: {}, eventCallback: (events:
FilesystemChangeEvent) => void): PathWatcher;
FilesystemChangeEvent) => void): Promise<PathWatcher>;
// Essential Classes ==========================================================
@@ -137,11 +142,11 @@ export interface AtomEnvironment {
// Managing the Atom Window
/** Open a new Atom window using the given options. */
open(params: {
open(params?: {
pathsToOpen: ReadonlyArray<string>,
newWindow: boolean,
devMode: boolean,
safeMode: boolean,
newWindow?: boolean,
devMode?: boolean,
safeMode?: boolean,
}): void;
/** Close the current window. */
@@ -238,6 +243,9 @@ export interface AtomEnvironment {
/** Execute code in dev tools. */
executeJavaScriptInDevTools(code: string): void;
/** Undocumented: get Atom config directory path */
getConfigDirPath(): string;
}
/**
@@ -252,33 +260,55 @@ export interface Color {
toRGBAString(): string;
}
export interface CommandRegistryTargetMap extends HTMLElementTagNameMap {
[key: string]: EventTarget;
}
export type CommandRegistryListener<TargetType extends EventTarget> = {
didDispatch(event: CommandEvent<TargetType>): void,
displayName?: string,
description?: string,
hiddenInCommandPalette?: boolean,
} | ((event: CommandEvent<TargetType>) => void);
/**
* Associates listener functions with commands in a context-sensitive way
* using CSS selectors.
*/
export interface CommandRegistry {
/** Register a single command. */
add(target: string|Node, commandName: string, listener: {
didDispatch(event: CommandEvent): void,
displayName?: string,
description?: string,
} | ((event: CommandEvent) => void)): Disposable;
add<T extends keyof CommandRegistryTargetMap>(
target: T, commandName: string,
listener: CommandRegistryListener<CommandRegistryTargetMap[T]>
): Disposable;
/** Register a single command. */
add<T extends Node>(
target: T, commandName: string,
listener: CommandRegistryListener<T>
): Disposable;
/** Register multiple commands. */
add(target: string|Node, commands: {
[key: string]: (event: CommandEvent) => void
add<T extends keyof CommandRegistryTargetMap>(target: T, commands: {
[key: string]: CommandRegistryListener<CommandRegistryTargetMap[T]>
}): CompositeDisposable;
/** Register multiple commands. */
add<T extends Node>(target: T, commands: {
[key: string]: CommandRegistryListener<T>
}): CompositeDisposable;
/** Find all registered commands matching a query. */
findCommands(params: { target: Node }): Array<{
findCommands(params: { target: string|Node }): Array<{
name: string,
displayName: string,
description?: string,
tags?: string[],
}>;
/** Simulate the dispatch of a command on a DOM node. */
dispatch(target: Node, commandName: string): void;
/**
* Simulate the dispatch of a command on a DOM node.
* @return Whether or not there was a matching command for the target.
*/
dispatch(target: Node, commandName: string): boolean;
/** Invoke the given callback before dispatching a command event. */
onWillDispatch(callback: (event: CommandEvent) => void): Disposable;
@@ -440,6 +470,14 @@ export interface Decoration {
/** Returns the marker associated with this Decoration. */
getMarker(): DisplayMarker;
/**
* Check if this decoration is of the given type.
* @param type A decoration type, such as `line-number` or `line`. This may also
* be an array of decoration types, with isType returning true if the decoration's
* type matches any in the array.
*/
isType(type: string|string[]): boolean;
// Properties
/** Returns the Decoration's properties. */
getProperties(): DecorationOptions;
@@ -714,7 +752,9 @@ export class Disposable implements DisposableLike {
* Utility class to be used when implementing event-based APIs that allows
* for handlers registered via ::on to be invoked with calls to ::emit.
*/
export class Emitter implements DisposableLike {
// tslint:disable-next-line:no-any
export class Emitter<OptionalEmissions = { [key: string]: any }, RequiredEmissions = {}>
implements DisposableLike {
/** Construct an emitter. */
constructor();
@@ -726,27 +766,47 @@ export class Emitter implements DisposableLike {
// Event Subscription
/** Registers a handler to be invoked whenever the given event is emitted. */
on<T extends keyof Emissions>(eventName: T, handler: (value?: Emissions[T]) => void):
Disposable;
on<T extends keyof OptionalEmissions>(eventName: T, handler: (value?:
OptionalEmissions[T]) => void): Disposable;
/** Registers a handler to be invoked whenever the given event is emitted. */
on<T extends keyof RequiredEmissions>(eventName: T, handler: (value:
RequiredEmissions[T]) => void): Disposable;
/**
* Register the given handler function to be invoked the next time an event
* with the given name is emitted via ::emit.
*/
once<T extends keyof Emissions>(eventName: T, handler: (value?: Emissions[T]) => void):
Disposable;
once<T extends keyof OptionalEmissions>(eventName: T, handler: (value?:
OptionalEmissions[T]) => void): Disposable;
/**
* Register the given handler function to be invoked the next time an event
* with the given name is emitted via ::emit.
*/
once<T extends keyof RequiredEmissions>(eventName: T, handler: (value:
RequiredEmissions[T]) => void): Disposable;
/**
* Register the given handler function to be invoked before all other
* handlers existing at the time of subscription whenever events by the
* given name are emitted via ::emit.
*/
preempt<T extends keyof Emissions>(eventName: T, handler: (value?: Emissions[T]) => void):
Disposable;
preempt<T extends keyof OptionalEmissions>(eventName: T, handler: (value?:
OptionalEmissions[T]) => void): Disposable;
/**
* Register the given handler function to be invoked before all other
* handlers existing at the time of subscription whenever events by the
* given name are emitted via ::emit.
*/
preempt<T extends keyof RequiredEmissions>(eventName: T, handler: (value:
RequiredEmissions[T]) => void): Disposable;
// Event Emission
/** Invoke the handlers registered via ::on for the given event name. */
emit<T extends keyof Emissions>(eventName: T, value?: Emissions[T]): void;
emit<T extends keyof OptionalEmissions>(eventName: T, value?:
OptionalEmissions[T]): void;
/** Invoke the handlers registered via ::on for the given event name. */
emit<T extends keyof RequiredEmissions>(eventName: T, value:
RequiredEmissions[T]): void;
}
/**
@@ -1012,10 +1072,7 @@ export class Point {
* Create a Point from an array containing two numbers representing the
* row and column.
*/
static fromObject(object: [number, number]): Point;
/** Create a Point from an existing object which implements PointLike. */
static fromObject(object: PointLike, copy?: boolean): Point;
static fromObject(object: PointCompatible, copy?: boolean): Point;
/** Construct a Point object */
constructor(row?: number, column?: number);
@@ -1092,10 +1149,10 @@ export class Point {
export class Range {
// Properties
/** A Point representing the start of the Range. */
start: PointLike;
start: Point;
/** A Point representing the end of the Range. */
end: PointLike;
end: Point;
// Construction
/** Convert any range-compatible object to a Range. */
@@ -1114,7 +1171,7 @@ export class Range {
negate(): Range;
// Serialization and Deserialization
/** Returns a plain javascript object representation of the range. */
/** Returns a plain javascript object representation of the Range. */
serialize(): number[][];
// Range Details
@@ -1434,17 +1491,10 @@ export class TextEditor {
/** Set the text in the given Range in buffer coordinates. */
setTextInBufferRange(range: RangeCompatible, text: string, options?:
{ normalizeLineEndings?: boolean, undo?: "skip" }): void;
{ normalizeLineEndings?: boolean, undo?: "skip" }): Range;
/* For each selection, replace the selected text with the given text. */
insertText(text: string, options?: {
select?: boolean,
autoIndent?: boolean,
autoIndentNewline?: boolean,
autoDecreaseIndent?: boolean,
normalizeLineEndings?: boolean,
undo?: "skip"
}): Range|boolean;
insertText(text: string, options?: TextInsertionOptions): Range|false;
/** For each selection, replace the selected text with a newline. */
insertNewline(): void;
@@ -1772,7 +1822,8 @@ export class TextEditor {
void;
/** Add a cursor at the given position in buffer coordinates. */
addCursorAtBufferPosition(bufferPosition: PointCompatible): Cursor;
addCursorAtBufferPosition(bufferPosition: PointCompatible, options?:
{ autoscroll?: boolean }): Cursor;
/** Add a cursor at the position in screen coordinates. */
addCursorAtScreenPosition(screenPosition: PointCompatible): Cursor;
@@ -2356,6 +2407,74 @@ export class TextEditor {
* displayed when the editor has no content.
*/
setPlaceholderText(placeholderText: string): void;
/** Undocumented: Buffer range for syntax scope at position */
bufferRangeForScopeAtPosition(scope: string, point: PointCompatible): Range;
/** Undocumented: Get syntax token at buffer position */
tokenForBufferPosition(pos: PointCompatible): {value: string, scopes: string[]};
}
export interface PixelPosition {
left: number;
top: number;
}
/**
* Undocumented: Rendering component for TextEditor
*/
export interface TextEditorComponent {
/** Does not clip screenPosition, unlike similar method on TextEditorElement */
pixelPositionForScreenPosition(screenPosition: PointLike): PixelPosition;
screenPositionForPixelPosition(pos: PixelPosition): Point;
pixelPositionForMouseEvent(event: {
clientX: number, clientY: number
}): PixelPosition;
screenPositionForMouseEvent(event: {clientX: number, clientY: number}): Point;
}
/**
* Undocumented: Custom HTML elemnent for TextEditor, atom-text-editor
*/
export interface TextEditorElement extends HTMLElement {
getModel(): TextEditor;
getComponent(): TextEditorComponent;
/**
* Extended: Get a promise that resolves the next time the element's
* DOM is updated in any way.
*/
getNextUpdatePromise(): Promise<void>;
/** Extended: get the width of an `x` character displayed in this element. */
getBaseCharacterWidth(): number;
/** Essential: Scrolls the editor to the top. */
scrollToTop(): void;
/** Essential: Scrolls the editor to the bottom. */
scrollToBottom(): void;
setScrollTop(scrollTop: number): void;
getScrollTop(): number;
setScrollLeft(scrollLeft: number): void;
getScrollLeft(): number;
getScrollHeight(): number;
/** Extended: Converts a buffer position to a pixel position. */
pixelPositionForBufferPosition(bufferPosition: PointLike): PixelPosition;
/** Extended: Converts a screen position to a pixel position. */
pixelPositionForScreenPosition(screenPosition: PointLike): PixelPosition;
// Event subscription
onDidChangeScrollTop(callback: (scrollTop: number) => void): Disposable;
onDidChangeScrollLeft(callback: (scrollLeft: number) => void): Disposable;
/** Called when the editor is attached to the DOM. */
onDidAttach(callback: () => void): Disposable;
/** Called when the editor is detached from the DOM. */
onDidDetach(callback: () => void): Disposable;
}
/** Experimental: This global registry tracks registered TextEditors. */
@@ -2400,27 +2519,25 @@ export interface TextEditorRegistry {
observe(callback: (editor: TextEditor) => void): Disposable;
}
export type TooltipPlacement =
|"top"|"bottom"|"left"|"right"
|"auto"|"auto top"|"auto bottom"|"auto left"|"auto right";
/** Associates tooltips with HTML elements or selectors. */
export interface TooltipManager {
/** Add a tooltip to the given element. */
add(target: HTMLElement, options: {
title?: string,
html?: boolean,
item?: HTMLElement|{ element: HTMLElement },
class?: string,
placement?: "top"|"bottom"|"left"|"right"|"auto"|(() => string),
trigger?: "click"|"hover"|"focus"|"manual",
delay?: { show: number, hide: number },
keyBindingCommand?: string,
keyBindingTarget?: HTMLElement
item?: object,
} | {
title?: string|(() => string),
html?: boolean,
item?: HTMLElement|{ element: HTMLElement },
class?: string,
placement?: "top"|"bottom"|"left"|"right"|"auto"|(() => string),
keyBindingCommand?: string,
keyBindingTarget?: HTMLElement
} & {
class?: string;
placement?: TooltipPlacement|(() => TooltipPlacement),
trigger?: "click"|"hover"|"focus"|"manual",
delay?: { show: number, hide: number },
delay?: { show: number, hide: number }
}): Disposable;
/** Find the tooltips that have been applied to the given element. */
@@ -2448,6 +2565,7 @@ export interface ViewRegistry {
(instance: T) => HTMLElement|undefined): Disposable;
/** Get the view associated with an object in the workspace. */
getView(obj: TextEditor): TextEditorElement;
getView(obj: object): HTMLElement;
}
@@ -3589,7 +3707,10 @@ export class GitRepository {
/** Grammar that tokenizes lines of text. */
export interface Grammar {
/** The name of the Grammar. */
name: string;
readonly name: string;
/** Undocumented: scope name of the Grammar. */
readonly scopeName: string;
// Event Subscription
onDidUpdate(callback: () => void): Disposable;
@@ -3643,6 +3764,13 @@ export interface GrammarRegistry {
*/
onDidUpdateGrammar(callback: (grammar: Grammar) => void): Disposable;
/**
* Invoke the given callback when a grammar is removed from the registry.
* @param callback The callback to be invoked whenever a grammar is removed.
* @return A Disposable on which `.dispose()` can be called to unsubscribe.
*/
onDidRemoveGrammar(callback: (grammar: Grammar) => void): Disposable;
// Managing Grammars
/**
* Get all the grammars in this registry.
@@ -3917,6 +4045,9 @@ export interface PackageManager {
/** Invoke the given callback when a package is unloaded. */
onDidUnloadPackage(callback: (package: Package) => void): Disposable;
/** Undocumented: invoke the given callback when an activation hook is triggered */
onDidTriggerActivationHook(hook: string, callback: () => void): Disposable;
// Package System Data
/** Get the path to the apm command. */
getApmPath(): string;
@@ -4710,7 +4841,7 @@ export class TextBuffer {
destroyed: boolean;
/** Create a new buffer backed by the given file path. */
static load(source: string, params?: BufferLoadOptions): Promise<TextBuffer>;
static load(filePath: string, params?: BufferLoadOptions): Promise<TextBuffer>;
/**
* Create a new buffer backed by the given file path. For better performance,
@@ -4737,6 +4868,9 @@ export class TextBuffer {
shouldDestroyOnFileDelete?(): boolean
});
/** Returns a plain javascript object representation of the TextBuffer. */
serialize(options?: { markerLayers?: boolean, history?: boolean }): object;
/** Returns the unique identifier for this buffer. */
getId(): string;
@@ -5221,6 +5355,21 @@ export interface BufferChangingEvent {
}
export interface BufferChangedEvent {
/**
* An array of objects summarizing the aggregated changes that occurred
* during the transaction.
*/
changes: Array<{
/**
* The Range of the deleted text in the contents of the buffer as it existed
* before the batch of changes reported by this event.
*/
oldRange: Range;
/** The Range of the inserted text in the current contents of the buffer. */
newRange: Range;
}>;
/** Range of the old text. */
oldRange: Range;
@@ -5244,13 +5393,14 @@ export interface BufferStoppedChangingEvent {
* intent to stop propagation so event bubbling can be properly simulated for
* detached elements.
*/
export interface CommandEvent extends CustomEvent {
export interface CommandEvent<CurrentTarget extends EventTarget = EventTarget> extends CustomEvent {
keyBindingAborted: boolean;
propagationStopped: boolean;
abortKeyBinding(): void;
stopPropagation(): CustomEvent;
stopImmediatePropagation(): CustomEvent;
currentTarget: CurrentTarget;
}
export interface CursorPositionChangedEvent {
@@ -5259,7 +5409,7 @@ export interface CursorPositionChangedEvent {
newBufferPosition: Point;
newScreenPosition: Point;
textChanged: boolean;
Cursor: Cursor;
cursor: Cursor;
}
export interface DecorationPropsChangedEvent {
@@ -5541,7 +5691,7 @@ export interface TextEditorObservedEvent {
// information under certain contexts.
// NOTE: the config schema with these defaults can be found here:
// https://github.com/atom/atom/blob/v1.22.0/src/config-schema.js
// https://github.com/atom/atom/blob/v1.23.0/src/config-schema.js
/**
* Allows you to strongly type Atom configuration variables. Additional key:value
* pairings merged into this interface will result in configuration values under
@@ -5789,16 +5939,6 @@ export interface ConfigValues {
[key: string]: any;
}
/**
* Allows you to strongly type event emissions across your codebase. Additional
* key:value pairings merged into this interface will result in emissions under
* the value of each key being templated by the type of the associated value.
*/
export interface Emissions {
// tslint:disable-next-line:no-any
[key: string]: any;
}
// Options ====================================================================
// The option objects that the user is expected to fill out and provide to
// specific API call.
@@ -6088,7 +6228,7 @@ export interface SharedDecorationOptions {
* An HTMLElement or a model Object with a corresponding view registered. Only
* applicable to the gutter, overlay and block types.
*/
item?: HTMLElement;
item?: object;
/**
* If true, the decoration will only be applied to the head of the DisplayMarker.
@@ -6151,11 +6291,33 @@ export interface SpawnProcessOptions {
}
export interface TextInsertionOptions {
/** If true, selects the newly added text. */
select?: boolean;
/** If true, indents all inserted text appropriately. */
autoIndent?: boolean;
/** If true, indent newline appropriately. */
autoIndentNewline?: boolean;
/**
* If true, decreases indent level appropriately (for example, when a closing
* bracket is inserted).
*/
autoDecreaseIndent?: boolean;
/**
* By default, when pasting multiple lines, Atom attempts to preserve the relative
* indent level between the first line and trailing lines, even if the indent
* level of the first line has changed from the copied text. If this option is
* true, this behavior is suppressed.
*/
preserveTrailingLineIndentation?: boolean;
/** If true, all line endings will be normalized to match the editor's current mode. */
normalizeLineEndings?: boolean;
/** If skip, skips the undo stack for this operation. */
undo?: "skip";
}
@@ -1,9 +0,0 @@
export class ViewModel {
constructor(private knockoutBindable: KnockoutBindable) {
}
activate(settings: any): void {
this.knockoutBindable.applyBindableValues(settings, this);
this.knockoutBindable.applyBindableValues(settings, this, true);
}
}
-18
View File
@@ -1,18 +0,0 @@
// Type definitions for aurelia-knockout 2.0
// Project: https://github.com/code-chris/aurelia-knockout
// Definitions by: Christian Kotzbauer <https://github.com/code-chris>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
interface KnockoutBindable {
/**
* Applys all values from a data object (usually the activation data) to the corresponding instance fields
* in the current view model if they are marked as @bindable. By default all matching values from the data object
* are applied. To only apply observable values set the last parameter to `true`. Subscriptions are created
* for all Knockout observables in the data object to update the view-model values respectively.
*
* @param data - the data object
* @param target - the target view model
* @param applyOnlyObservables - `true` if only observable values should be applied, false by default.
*/
applyBindableValues(data: any, target: any, applyOnlyObservables?: boolean): void;
}
+20 -1
View File
@@ -109,7 +109,9 @@ webAuth.renewAuth({}, (err, authResult) => {});
webAuth.renewAuth({
nonce: '123',
state: '456',
postMessageDataType: 'auth0:silent-authentication'
postMessageDataType: 'auth0:silent-authentication',
usePostMessage: true,
timeout: 30 * 1000
}, (err, authResult) => {
// Renewed tokens or error
});
@@ -172,6 +174,23 @@ webAuth.login({username: 'bar', password: 'foo'}, (err, data) => {});
webAuth.crossOriginAuthenticationCallback();
webAuth.checkSession({
audience: 'https://mystore.com/api/v2',
scope: 'read:order write:order',
redirectUri: 'https://example.com/auth/silent-callback'
}, (err, authResult) => {
// Authentication tokens or error
});
webAuth.checkSession({
audience: 'https://mystore.com/api/v2',
scope: 'read:order write:order',
redirectUri: 'https://example.com/auth/silent-callback',
usePostMessage: true
}, (err, authResult) => {
// Renewed tokens or error
});
const authentication = new auth0.Authentication({
domain: 'me.auth0.com',
clientID: '...',
+78 -2
View File
@@ -1,7 +1,8 @@
// Type definitions for Auth0.js 8.10
// Type definitions for Auth0.js 8.11
// Project: https://github.com/auth0/auth0.js
// Definitions by: Adrian Chia <https://github.com/adrianchia>
// Matt Durrant <https://github.com/mdurrant>
// Peter Blazejewicz <https://github.com/peterblazejewicz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export as namespace auth0;
@@ -267,6 +268,14 @@ export class WebAuth {
* @param options:
*/
passwordlessVerify(options: PasswordlessVerifyOptions, callback: Auth0Callback<any>): void;
/**
* Renews an existing session on Auth0's servers using `response_mode=web_message` (i.e. Auth0's hosted login page)
*
* @param options options used in {@link authorize} call
* @param callback: any(err, token_payload)
*/
checkSession(options: CheckSessionOptions, callback: Auth0Callback<any>): void;
}
export class Redirect {
@@ -525,14 +534,19 @@ export interface Auth0Error {
statusText?: string;
}
/**
* The contents of the authResult object returned by {@link WebAuth#parseHash }
*/
export interface Auth0DecodedHash {
accessToken?: string;
idToken?: string;
idTokenPayload?: any;
appState?: any;
refreshToken?: string;
state?: string;
expiresIn?: number;
tokenType?: string;
scope?: string;
}
/** Represents the response from an API Token Delegation request. */
@@ -667,17 +681,72 @@ export interface ParseHashOptions {
}
export interface RenewAuthOptions {
/**
* your Auth0 domain
*/
domain?: string;
/**
* your Auth0 client identifier obtained when creating the client in the Auth0 Dashboard
*/
clientID?: string;
/**
* url that the Auth0 will redirect after Auth with the Authorization Response
*/
redirectUri?: string;
/**
* type of the response used by OAuth 2.0 flow. It can be any space separated
* list of the values `code`, `token`, `id_token`.
* {@link https://openid.net/specs/oauth-v2-multiple-response-types-1_0}
*/
responseType?: string;
/**
* how the Auth response is encoded and redirected back to the client.
* Supported values are `query`, `fragment` and `form_post`.
* The `query` value is only supported when `responseType` is `code`.
* {@link https://openid.net/specs/oauth-v2-multiple-response-types-1_0.html#ResponseModes}
*/
responseMode?: string;
/**
* value used to mitigate XSRF attacks.
* {@link https://auth0.com/docs/protocols/oauth2/oauth-state}
*/
state?: string;
/**
* value used to mitigate replay attacks when using Implicit Grant.
* {@link https://auth0.com/docs/api-auth/tutorials/nonce}
*/
nonce?: string;
/**
* scopes to be requested during Auth. e.g. `openid email`
*/
scope?: string;
/**
* identifier of the resource server who will consume the access token issued after Auth
*/
audience?: string;
usePostMessage?: boolean;
/**
* identifier data type to look for in postMessage event data, where events are initiated
* from silent callback urls, before accepting a message event is the event expected.
* A value of false means any postMessage event will trigger a callback.
*/
postMessageDataType?: string;
/**
* origin of redirectUri to expect postMessage response from.
* Defaults to the origin of the receiving window. Only used if usePostMessage is truthy.
*/
postMessageOrigin?: string;
/**
* value in milliseconds used to timeout when the `/authorize` call is failing
* as part of the silent authentication with postmessage enabled due to a configuration.
*/
timeout?: number;
/**
* use postMessage to comunicate between the silent callback and the SPA.
* When false the SDK will attempt to parse the url hash should ignore the url hash
* and no extra behaviour is needed
* @default false
*/
usePostMessage?: boolean;
}
export interface AuthorizeOptions {
@@ -692,3 +761,10 @@ export interface AuthorizeOptions {
scope?: string;
audience?: string;
}
export interface CheckSessionOptions extends AuthorizeOptions {
/**
* optional parameter for auth0 to use postMessage to communicate between the silent callback and the SPA.
*/
usePostMessage?: boolean;
}
+13 -2
View File
@@ -10,6 +10,17 @@ lock.show();
lock.hide();
lock.logout(() => {});
lock.checkSession({}, function(error: auth0.Auth0Error, authResult: AuthResult): void {
if (error || !authResult) {
lock.show();
} else {
// user has an active session, so we can use the accessToken directly.
lock.getUserInfo(authResult.accessToken, function(error, profile) {
console.log(error, profile);
});
}
});
// Show supports UI arguments
const showOptions : Auth0LockShowOptions = {
@@ -37,7 +48,7 @@ lock.show(showOptions);
// "on" event-driven example
lock.on("authenticated", function(authResult : any) {
lock.on("authenticated", function(authResult: AuthResult) {
lock.getProfile(authResult.idToken, function(error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) {
if (error) {
// Handle error
@@ -49,7 +60,7 @@ lock.on("authenticated", function(authResult : any) {
});
});
lock.on("authenticated", function(authResult : any) {
lock.on("authenticated", function(authResult: AuthResult) {
lock.getUserInfo(authResult.accessToken, function(error, profile) {
if (error) {
// Handle error
+1
View File
@@ -154,6 +154,7 @@ interface Auth0LockStatic {
// deprecated
getProfile(token: string, callback: (error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) => void): void;
getUserInfo(token: string, callback: (error: auth0.Auth0Error, profile: auth0.Auth0UserProfile) => void): void;
checkSession(options: any, callback: (error: auth0.Auth0Error, authResult: AuthResult | undefined) => void): void;
// https://github.com/auth0/lock#resumeauthhash-callback
resumeAuth(hash: string, callback: (error: auth0.Auth0Error, authResult: AuthResult) => void): void;
show(options?: Auth0LockShowOptions): void;
+20
View File
@@ -111,3 +111,23 @@ management
// Update app metadata using callback
management
.updateAppMetadata({id: "user_id"}, {"key": "value"}, (err: Error, users: auth0.User) => {});
management.getUsersByEmail('email@address.com', (err, users) => {
console.log(users);
});
management.getUsersByEmail('email@address.com').then((users) => {
console.log(users);
});
// Using different client settings.
const retryableManagementClient = new auth0.ManagementClient({
clientId: '',
clientSecret: '',
domain: 'xxx.auth0.com',
retry: {
enabled : true
}
});
+112 -25
View File
@@ -1,4 +1,4 @@
// Type definitions for auth0 2.5
// Type definitions for auth0 2.6
// Project: https://github.com/auth0/node-auth0
// Definitions by: Wilson Hobbs <https://github.com/wbhob>, Seth Westphal <https://github.com/westy92>, Amiram Korach <https://github.com/amiram>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -14,6 +14,7 @@ export interface ManagementClientOptions {
audience?: string;
scope?: string;
tokenProvider?: TokenProvider;
retry?: RetryOptions;
}
export interface TokenProvider {
@@ -21,6 +22,17 @@ export interface TokenProvider {
cacheTTLInSeconds?: number;
}
export interface RetryOptions {
/**
* Default value is `true`.
*/
enabled?: boolean;
/**
* Default value is `10`.
*/
maxRetries?: number;
}
export interface UserMetadata { }
export interface AppMetadata { }
@@ -165,6 +177,82 @@ export interface Client {
mobile?: any;
}
export interface ResourceServer {
scopes?: { description: string, value: string }[];
/**
* The algorithm used to sign tokens.
*/
signing_alg?: 'HS256' | 'RS256';
/**
* The secret used to sign tokens when using symmetric algorithms.
*/
signing_secret?: string;
/**
* Allows issuance of refresh tokens for this entity.
*/
allow_offline_access?: boolean;
/**
* Flag this entity as capable of skipping consent.
*/
skip_consent_for_verifiable_first_party_clients?: boolean;
/**
* The amount of time (in seconds) that the token will be valid after being issued.
*/
token_lifetime?: number;
/**
* The amount of time (in seconds) that the token will be valid after being issued from browser based flows. Value cannot be larger than token_lifetime..
*/
token_lifetime_for_web?: number;
/**
* The ID of the resource server.
*/
id?: string;
/**
* A friendly name for the resource server.
*/
name?: string;
}
export interface CreateResourceServer extends ResourceServer {
/**
* The identifier of the client.
*/
identifier?: string;
}
export interface CreateClientGrant {
/**
* The identifier of the resource server.
*/
client_id: string;
/**
* The audience.
*/
audience: string;
scope: string[];
}
export type UpdateClientGrant = Pick<Partial<CreateClientGrant>, 'scope'>;
export type ClientGrant = Partial<CreateClientGrant> & {
/**
* The id of the client grant.
*/
id?: string;
};
export interface CreateClientGrant {
/**
* The identifier of the resource server.
*/
client_id: string;
/**
* The audience.
*/
audience: string;
scope: string[];
}
export interface User {
email?: string;
email_verified?: boolean;
@@ -433,17 +521,17 @@ export class ManagementClient {
// Client Grants
getClientGrants(): Promise<User>;
getClientGrants(cb: (err: Error, data: any) => void): void;
getClientGrants(): Promise<ClientGrant[]>;
getClientGrants(cb: (err: Error, data: ClientGrant[]) => void): void;
createClientGrant(data: Data): Promise<User>;
createClientGrant(data: Data, cb: (err: Error, data: any) => void): void;
createClientGrant(data: CreateClientGrant): Promise<ClientGrant>;
createClientGrant(data: CreateClientGrant, cb: (err: Error, data: ClientGrant) => void): void;
updateClientGrant(params: ObjectWithId, data: Data): Promise<User>;
updateClientGrant(params: ObjectWithId, data: Data, cb: (err: Error, data: any) => void): void;
updateClientGrant(params: ObjectWithId, data: UpdateClientGrant): Promise<ClientGrant>;
updateClientGrant(params: ObjectWithId, data: UpdateClientGrant, cb: (err: Error, data: ClientGrant) => void): void;
deleteClientGrant(params: ObjectWithId): Promise<User>;
deleteClientGrant(params: ObjectWithId, cb: (err: Error, data: any) => void): void;
deleteClientGrant(params: ObjectWithId): Promise<void>;
deleteClientGrant(params: ObjectWithId, cb: (err: Error) => void): void;
// Device Keys
@@ -482,6 +570,9 @@ export class ManagementClient {
getUser(params: ObjectWithId): Promise<User>;
getUser(params: ObjectWithId, cb?: (err: Error, user: User) => void): void;
getUsersByEmail(email: string): Promise<User[]>;
getUsersByEmail(email: string, cb?: (err: Error, users: User[]) => void): void;
createUser(data: CreateUserData): Promise<User>;
createUser(data: CreateUserData, cb: (err: Error, user: User) => void): void;
@@ -529,8 +620,8 @@ export class ManagementClient {
deleteEmailProvider(): Promise<any>;
deleteEmailProvider(cb?: (err: Error, data: any) => void): void;
updateEmailProvider(data: Data): Promise<any>;
updateEmailProvider(data: Data, cb?: (err: Error, data: any) => void): void;
updateEmailProvider(params: {}, data: Data): Promise<any>;
updateEmailProvider(params: {}, data: Data, cb?: (err: Error, data: any) => void): void;
// Statistics
@@ -575,22 +666,18 @@ export class ManagementClient {
// Resource Server
createResourceServer(data: Data): Promise<any>;
createResourceServer(data: Data, cb?: (err: Error, data: any) => void): void;
getResourceServers(): Promise<any>;
getResourceServers(cb?: (err: Error, data: any) => void): void;
getResourceServer(data: ObjectWithId): Promise<any>;
getResourceServer(data: ObjectWithId, cb?: (err: Error, data: any) => void): void;
deleteResourceServer(params: ObjectWithId): Promise<any>;
deleteResourceServer(params: ObjectWithId, cb?: (err: Error, data: any) => void): void;
updateResourceServer(params: ObjectWithId, data: Data): Promise<any>;
updateResourceServer(params: ObjectWithId, data: Data, cb?: (err: Error, data: any) => void): void;
createResourceServer(data: CreateResourceServer): Promise<ResourceServer>;
createResourceServer(data: CreateResourceServer, cb?: (err: Error, data: ResourceServer) => void): void;
getResourceServers(): Promise<ResourceServer[]>;
getResourceServers(cb?: (err: Error, data: ResourceServer[]) => void): void;
getResourceServer(data: ObjectWithId): Promise<ResourceServer>;
getResourceServer(data: ObjectWithId, cb?: (err: Error, data: ResourceServer) => void): void;
deleteResourceServer(params: ObjectWithId): Promise<void>;
deleteResourceServer(params: ObjectWithId, cb?: (err: Error) => void): void;
updateResourceServer(params: ObjectWithId, data: ResourceServer): Promise<ResourceServer>;
updateResourceServer(params: ObjectWithId, data: ResourceServer, cb?: (err: Error, data: ResourceServer) => void): void;
}
+2 -1
View File
@@ -1,6 +1,6 @@
// Type definitions for AutobahnJS v0.9.7
// Project: http://autobahn.ws/js/
// Definitions by: Elad Zelingher <https://github.com/darkl>, Andy Hawkins <https://github.com/a904guy/,http://a904guy.com/,http://www.bmbsqd.com>, Wladimir Totino <https://github.com/valepu>
// Definitions by: Elad Zelingher <https://github.com/darkl>, Andy Hawkins <https://github.com/a904guy/,http://a904guy.com/,http://www.bmbsqd.com>, Wladimir Totino <https://github.com/valepu>, Mathias Teier <https://github.com/glenroy37/,http://kagent.at>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="when" />
@@ -179,6 +179,7 @@ declare namespace autobahn {
interface ISubscribeOptions {
match?: string;
get_retained?: boolean;
}
interface IRegisterOptions {
@@ -1,42 +0,0 @@
import autobind = require('autobind-decorator');
class Test {
public static what: string = 'static';
@autobind
public static test(): void {
console.log(this.what);
}
public constructor(public what: string) {
this.what = what;
}
@autobind
public test(): void {
console.warn(this.what);
}
}
const tester: Test = new Test('bind');
const { test } = tester;
tester.test(); // warns 'bind'.
test(); // warns 'bind'.
Test.test(); // logs 'static'.
@autobind
class Component {
public constructor(private someMember: string) {
this.someMember = someMember;
}
public someMethod(): void {
console.error(this.someMember);
}
}
const component: Component = new Component('React vs Angular2');
const { someMethod } = component;
component.someMethod(); // errors 'React vs Angular2'
someMethod(); // errors 'React vs Angular2'
-10
View File
@@ -1,10 +0,0 @@
// Type definitions for autobind-decorator v1.3.3
// Project: https://github.com/andreypopp/autobind-decorator
// Definitions by: Ivo Stratev <https://github.com/NoHomey>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'autobind-decorator' {
function autobind<TFunction extends Function>(target: TFunction): TFunction | void;
function autobind<T extends Function>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>): TypedPropertyDescriptor<T> | void;
export = autobind;
}
+224
View File
@@ -69,6 +69,7 @@ var cloudformationCustomResourceResponse: AWSLambda.CloudFormationCustomResource
/* API Gateway Event request context */
str = apiGwEvtReqCtx.accountId;
str = apiGwEvtReqCtx.apiId;
authResponseContext = apiGwEvtReqCtx.authorizer;
str = apiGwEvtReqCtx.httpMethod;
str = apiGwEvtReqCtx.identity.accessKey;
str = apiGwEvtReqCtx.identity.accountId;
@@ -108,6 +109,101 @@ str = apiGwEvt.queryStringParameters["example"];
str = apiGwEvt.stageVariables["example"];
apiGwEvtReqCtx = apiGwEvt.requestContext;
/* DynamoDB Stream Event */
var dynamoDBStreamEvent: AWSLambda.DynamoDBStreamEvent = {
Records: [
{
eventID: '1',
eventVersion: '1.0',
dynamodb: {
Keys: {
Id: {
N: 101
}
},
NewImage: {
Message: {
S: 'New item!'
},
Id: {
N: 101
}
},
StreamViewType: 'NEW_AND_OLD_IMAGES',
SequenceNumber: '111',
SizeBytes: 26
},
awsRegion: 'us-west-2',
eventName: 'INSERT',
eventSourceARN:
'arn:aws:dynamodb:us-west-2:account-id:table/ExampleTableWithStream/stream/2015-06-27T00:48:05.899',
eventSource: 'aws:dynamodb'
},
{
eventID: '2',
eventVersion: '1.0',
dynamodb: {
OldImage: {
Message: {
S: 'New item!'
},
Id: {
N: 101
}
},
SequenceNumber: '222',
Keys: {
Id: {
N: 101
}
},
SizeBytes: 59,
NewImage: {
Message: {
S: 'This item has changed'
},
Id: {
N: 101
}
},
StreamViewType: 'NEW_AND_OLD_IMAGES'
},
awsRegion: 'us-west-2',
eventName: 'MODIFY',
eventSourceARN:
'arn:aws:dynamodb:us-west-2:account-id:table/ExampleTableWithStream/stream/2015-06-27T00:48:05.899',
eventSource: 'aws:dynamodb'
},
{
eventID: '3',
eventVersion: '1.0',
dynamodb: {
Keys: {
Id: {
N: 101
}
},
SizeBytes: 38,
SequenceNumber: '333',
OldImage: {
Message: {
S: 'This item has changed'
},
Id: {
N: 101
}
},
StreamViewType: 'NEW_AND_OLD_IMAGES'
},
awsRegion: 'us-west-2',
eventName: 'REMOVE',
eventSourceARN:
'arn:aws:dynamodb:us-west-2:account-id:table/ExampleTableWithStream/stream/2015-06-27T00:48:05.899',
eventSource: 'aws:dynamodb'
}
]
};
/* SNS Event */
snsEvtRecs = snsEvt.Records;
@@ -293,6 +389,9 @@ function callback(cb: AWSLambda.Callback) {
cb(null);
cb(error);
cb(null, anyObj);
cb(null, b);
cb(null, str);
cb(null, num);
}
/* Proxy Callback */
@@ -311,6 +410,131 @@ function customAuthorizerCallback(cb: AWSLambda.CustomAuthorizerCallback) {
cb(null, authResponse);
}
/* CloudFront events, see http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html */
var CloudFrontRequestEvent: AWSLambda.CloudFrontRequestEvent = {
"Records": [
{
"cf": {
"config": {
"distributionId": "EDFDVBD6EXAMPLE",
"requestId": "MRVMF7KydIvxMWfJIglgwHQwZsbG2IhRJ07sn9AkKUFSHS9EXAMPLE=="
},
"request": {
"clientIp": "2001:0db8:85a3:0:0:8a2e:0370:7334",
"method": "GET",
"uri": "/picture.jpg",
"querystring": "size=large",
"headers": {
"host": [
{
"key": "Host",
"value": "d111111abcdef8.cloudfront.net"
}
],
"user-agent": [
{
"key": "User-Agent",
"value": "curl/7.51.0"
}
]
},
"origin": {
"custom": {
"customHeaders": {
"my-origin-custom-header": [
{
"key": "My-Origin-Custom-Header",
"value": "Test"
}
]
},
"domainName": "example.com",
"keepaliveTimeout": 5,
"path": "/custom_path",
"port": 443,
"protocol": "https",
"readTimeout": 5,
"sslProtocols": [
"TLSv1",
"TLSv1.1"
]
},
"s3": {
"authMethod": "origin-access-identity",
"customHeaders": {
"my-origin-custom-header": [
{
"key": "My-Origin-Custom-Header",
"value": "Test"
}
]
},
"domainName": "my-bucket.s3.amazonaws.com",
"path": "/s3_path",
"region": "us-east-1"
}
}
}
}
}
]
};
var CloudFrontResponseEvent: AWSLambda.CloudFrontResponseEvent = {
"Records": [
{
"cf": {
"config": {
"distributionId": "EDFDVBD6EXAMPLE",
"requestId": "xGN7KWpVEmB9Dp7ctcVFQC4E-nrcOcEKS3QyAez--06dV7TEXAMPLE=="
},
"request": {
"clientIp": "2001:0db8:85a3:0:0:8a2e:0370:7334",
"method": "GET",
"uri": "/picture.jpg",
"querystring": "size=large",
"headers": {
"host": [
{
"key": "Host",
"value": "d111111abcdef8.cloudfront.net"
}
],
"user-agent": [
{
"key": "User-Agent",
"value": "curl/7.18.1"
}
]
}
},
"response": {
"status": "200",
"statusDescription": "OK",
"headers": {
"server": [
{
"key": "Server",
"value": "MyCustomOrigin"
}
],
"set-cookie": [
{
"key": "Set-Cookie",
"value": "theme=light"
},
{
"key": "Set-Cookie",
"value": "sessionToken=abc123; Expires=Wed, 09 Jun 2021 10:18:14 GMT"
}
]
}
}
}
}
]
};
/* Compatibility functions */
context.done();
context.done(error);
+101 -1
View File
@@ -8,7 +8,10 @@
// Yoriki Yamaguchi <https://github.com/y13i>
// wwwy3y3 <https://github.com/wwwy3y3>
// Ishaan Malhi <https://github.com/OrthoDex>
// Michael Marner <https://github.com/MichaelMarner>
// Daniel Cottone <https://github.com/daniel-cottone>
// Kostya Misura <https://github.com/kostya-misura>
// Markus Tacker <https://github.com/coderbyheart>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.2
@@ -16,6 +19,7 @@
interface APIGatewayEventRequestContext {
accountId: string;
apiId: string;
authorizer?: AuthResponseContext | null | undefined;
httpMethod: string;
identity: {
accessKey: string | null;
@@ -62,6 +66,53 @@ interface CustomAuthorizerEvent {
requestContext?: APIGatewayEventRequestContext;
}
// Context
// http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_AttributeValue.html
interface AttributeValue {
B?: string;
BS?: Array<string>;
BOOL?: boolean;
L?: Array<AttributeValue>;
M?: { [id: string]: AttributeValue };
N?: number;
NS?: Array<string>;
NULL?: boolean;
S?: string;
SS?: Array<string>;
}
// Context
// http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_StreamRecord.html
interface StreamRecord {
ApproximateCreationTime?: number;
Keys?: { [key: string]: AttributeValue };
NewImage?: { [key: string]: AttributeValue };
OldImage?: { [key: string]: AttributeValue };
SequenceNumber?: string;
SizeBytes?: number;
StreamViewType?: 'KEYS_ONLY' | 'NEW_IMAGE' | 'OLD_IMAGE' | 'NEW_AND_OLD_IMAGES';
}
// Context
// http://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_streams_Record.html
interface DynamoDBRecord {
awsRegion?: string;
dynamodb?: StreamRecord;
eventID?: string;
eventName?: 'INSERT' | 'MODIFY' | 'REMOVE';
eventSource?: string;
eventSourceARN?: string;
eventVersion?: string;
userIdentity?: any;
}
// AWS Lambda Stream event
// Context
// http://docs.aws.amazon.com/lambda/latest/dg/eventsources.html#eventsources-ddb-update
interface DynamoDBStreamEvent {
Records: Array<DynamoDBRecord>;
}
// SNS "event"
interface SNSMessageAttribute {
Type: string;
@@ -344,6 +395,55 @@ interface AuthResponseContext {
[name: string]: string | number | boolean;
}
/**
* CloudFront events
* http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/lambda-event-structure.html
*/
type CloudFrontHeaders = {
[name: string]: {
key: string;
value: string;
}[]
};
type CloudFrontResponse = {
status: string;
statusDescription: string;
headers: CloudFrontHeaders;
};
type CloudFrontRequest = {
clientIp: string;
method: string;
uri: string;
querystring: string;
headers: CloudFrontHeaders;
};
type CloudFrontEvent = {
config: {
distributionId: string;
requestId: string;
}
}
export type CloudFrontResponseEvent = {
Records: {
cf: CloudFrontEvent & {
request: CloudFrontRequest;
response: CloudFrontResponse;
}
}[]
};
export type CloudFrontRequestEvent = {
Records: {
cf: CloudFrontEvent & {
request: CloudFrontRequest;
}
}[]
};
/**
* AWS Lambda handler function.
* http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html
@@ -363,7 +463,7 @@ export type CustomAuthorizerHandler = (event: CustomAuthorizerEvent, context: Co
* @param error an optional parameter that you can use to provide results of the failed Lambda function execution.
* @param result an optional parameter that you can use to provide the result of a successful function execution. The result provided must be JSON.stringify compatible.
*/
export type Callback = (error?: Error | null, result?: object) => void;
export type Callback = (error?: Error | null, result?: object | boolean | number | string) => void;
export type ProxyCallback = (error?: Error | null, result?: ProxyResult) => void;
export type CustomAuthorizerCallback = (error?: Error | null, result?: AuthResponse) => void;
@@ -1,113 +0,0 @@
import axios from "axios";
import MockAdapter = require("axios-mock-adapter");
const instance = axios.create();
const mock = new MockAdapter(instance);
namespace AllowsConstructing {
new MockAdapter(instance);
}
namespace AllowsConstructingWithOptions {
new MockAdapter(instance, {
delayResponse: 2000,
});
}
namespace ExposesAdapter {
mock.adapter();
}
namespace SupportsReset {
mock.reset();
}
namespace SupportsRestore {
mock.restore();
}
namespace SupportsAllHttpVerbs {
mock.onGet;
mock.onPost;
mock.onPut;
mock.onHead;
mock.onDelete;
mock.onPatch;
}
namespace SupportsAnyVerb {
mock.onAny;
}
namespace AllowsVerbOnlyMatcher {
mock.onGet();
}
namespace AllowsUrlMatcher {
mock.onGet("/foo");
}
namespace AllowsUrlRegExpMatcher {
mock.onGet(/\/fo+/);
}
namespace AllowsStringBodyMatcher {
mock.onPatch("/foo", "bar");
}
namespace AllowsBodyMatcher {
mock.onGet("/foo", {
id: 4,
name: "foo",
});
}
namespace AllowsParameterMatcher {
mock.onGet("/foo", {
params: {
searchText: "John",
},
});
}
namespace AllowsReplyWithStatus {
mock.onGet().reply(200);
}
namespace SupportsReplyOnce {
mock.onGet().replyOnce(200);
}
namespace SupportsPassThrough {
mock.onGet().passThrough();
}
namespace SupportsTimeout {
mock.onGet().timeout();
}
namespace AllowsFunctionReply {
mock.onGet().reply((config) => {
return [
200,
{ data: "foo" },
{ RequestedURL: config.url },
];
});
}
namespace AllowsPromiseReply {
mock.onGet().reply((config) => {
return Promise.resolve([
200,
{ data: "bar" },
{ RequestedURL: config.url },
]);
});
}
namespace SupportsChanining {
mock
.onGet("/users").reply(200, [/* users */])
.onGet("/posts").reply(200, [/* posts */]);
}
-51
View File
@@ -1,51 +0,0 @@
// Type definitions for axios-mock-adapter 1.9
// Project: https://github.com/ctimmerm/axios-mock-adapter
// Definitions by: Tomasz Kryskiewicz <https://github.com/tkryskiewicz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version 2.1
import { AxiosAdapter, AxiosInstance, AxiosRequestConfig } from "axios";
type CallbackResponseSpecFunc = (config: AxiosRequestConfig) => any[] | Promise<any[]>;
type ResponseSpecFunc = (statusOrCallback: number | CallbackResponseSpecFunc, data?: any, headers?: any) => MockAdapter;
interface RequestHandler {
reply: ResponseSpecFunc;
replyOnce: ResponseSpecFunc;
passThrough(): void;
networkError(): void;
timeout(): void;
}
interface MockAdapterOptions {
delayResponse?: number;
}
interface RequestDataMatcher {
[index: string]: any;
params?: {
[index: string]: any,
};
}
type RequestMatcherFunc = (matcher?: string | RegExp, body?: string | RequestDataMatcher) => RequestHandler;
declare class MockAdapter {
constructor(axiosInstance: AxiosInstance, options?: MockAdapterOptions);
adapter(): AxiosAdapter;
reset(): void;
restore(): void;
onGet: RequestMatcherFunc;
onPost: RequestMatcherFunc;
onPut: RequestMatcherFunc;
onHead: RequestMatcherFunc;
onDelete: RequestMatcherFunc;
onPatch: RequestMatcherFunc;
onAny: RequestMatcherFunc;
}
export = MockAdapter;
+79 -13
View File
@@ -1,16 +1,82 @@
import { Azure } from 'azure-sb';
import AzureSB = require('azure-sb');
import Models = Azure.ServiceBus.Results.Models;
var nh = new Azure.ServiceBus.NotificationHubService();
nh.send('tag', '<payload></payload>', function (error, result) {});
nh.send('tag', '<payload></payload>', { headers: {} }, function (error, result) {});
function createResultCallback<T>() {
return (err: Error | null, result: T, response: Azure.ServiceBus.Response) => {
};
}
nh.apns.send('tag', { payload: { } }, function (error, result) {});
nh.apns.send(['tag'], { payload: { } }, function (error, result) {});
nh.gcm.send('tag', { }, function (error, result) {});
nh.gcm.send(['tag'], { }, function (error, result) {});
nh.wns.send('tag', '<payload></payload>', 'wns/toast', function (error, result) {});
nh.wns.send(['tag'], '<payload></payload>', 'wns/toast', function (error, result) {});
nh.wns.send('tag', '<payload></payload>', 'wns/toast', { headers: {} }, function (error, result) {});
nh.wns.sendToastText01('tag', '<payload></payload>', function (error, result) {});
nh.wns.sendToastText01(['tag'], '<payload></payload>', function (error, result) {});
nh.wns.sendToastText01('tag', '<payload></payload>', { headers: {} }, function (error, result) {});
function ResponseCallback(err: Error | null, response: Azure.ServiceBus.Response) {
}
const ServiceBus = AzureSB.createServiceBusService('connectionstring');
// Queues
ServiceBus.listQueues('', createResultCallback<Models.Queue[]>());
ServiceBus.createQueue('test', createResultCallback<Models.Queue>());
ServiceBus.createQueueIfNotExists('test', createResultCallback<boolean>());
ServiceBus.getQueue('test', createResultCallback<Models.Queue>());
ServiceBus.deleteQueue('test', ResponseCallback);
// Topics
ServiceBus.listTopics('', createResultCallback<Models.Topic[]>());
ServiceBus.createTopic('test', createResultCallback<Models.Topic>());
ServiceBus.createTopicIfNotExists('test', createResultCallback<boolean>());
ServiceBus.getTopic('test', createResultCallback<Models.Topic>());
ServiceBus.deleteTopic('test', ResponseCallback);
// Subscriptions
ServiceBus.listSubscriptions('test', createResultCallback<Models.Subscription[]>());
ServiceBus.createSubscription('test', 'test', createResultCallback<Models.Subscription>());
ServiceBus.createSubscription('test', 'test', {
DefaultMessageTimeToLive: 'PT10M'
}, createResultCallback<Models.Subscription>());
ServiceBus.getSubscription('test', 'test', createResultCallback<Models.Subscription>());
ServiceBus.deleteSubscription('test', 'test', ResponseCallback);
ServiceBus.listRules('testTopic', 'testSub', createResultCallback<Models.Rule[]>());
ServiceBus.createRule('testTopic', 'testSub', 'testRule', createResultCallback<Models.Rule>());
ServiceBus.getRule('testTopic', 'testSub', 'testRule', createResultCallback<Models.Rule>());
ServiceBus.deleteRule('testTopic', 'testSub', 'testRule', ResponseCallback);
// Messages
ServiceBus.sendQueueMessage('testTopic', 'My data', ResponseCallback);
ServiceBus.sendQueueMessage('testTopic', {
body: '{"data":"MyData"}',
contentType: 'application/json',
brokerProperties: {
CorrelationId: '123'
}
}, ResponseCallback);
ServiceBus.receiveQueueMessage('testQueue', createResultCallback<Azure.ServiceBus.Message>());
ServiceBus.sendTopicMessage('testTopic', 'My data', ResponseCallback);
ServiceBus.sendTopicMessage('testTopic', {
body: '{"data":"MyData"}',
contentType: 'application/json',
brokerProperties: {
CorrelationId: '123'
}
}, ResponseCallback);
ServiceBus.receiveSubscriptionMessage('testTopic', 'testSub', createResultCallback<Azure.ServiceBus.Message>());
ServiceBus.renewLockForMessage('test', ResponseCallback);
ServiceBus.unlockMessage('test', ResponseCallback);
ServiceBus.deleteMessage('test', ResponseCallback);
// NotificationHub
const nh = AzureSB.createNotificationHubService('test');
nh.send('tag', '<payload></payload>', ResponseCallback);
nh.send('tag', '<payload></payload>', { headers: {} }, ResponseCallback);
nh.apns.send('tag', { payload: {} }, ResponseCallback);
nh.apns.send(['tag'], { payload: {} }, ResponseCallback);
nh.gcm.send('tag', {}, ResponseCallback);
nh.gcm.send(['tag'], {}, ResponseCallback);
nh.wns.send('tag', '<payload></payload>', 'wns/toast', ResponseCallback);
nh.wns.send(['tag'], '<payload></payload>', 'wns/toast', ResponseCallback);
nh.wns.send('tag', '<payload></payload>', 'wns/toast', { headers: {} }, ResponseCallback);
nh.wns.sendToastText01('tag', '<payload></payload>', ResponseCallback);
nh.wns.sendToastText01(['tag'], '<payload></payload>', ResponseCallback);
nh.wns.sendToastText01('tag', '<payload></payload>', { headers: {} }, ResponseCallback);
+299 -149
View File
@@ -2,172 +2,322 @@
// Project: https://github.com/Azure/azure-sdk-for-node/tree/master/lib/services/serviceBus
// Definitions by: Microsoft Azure <https://github.com/Azure>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
declare namespace Azure.ServiceBus {
interface Callback {
(error: any, response: any): void;
export import ServiceBusService = require('./lib/servicebusservice');
export import NotificationHubService = require('./lib/notificationhubservice');
export import WrapService = require('./lib/wrapservice');
export function createServiceBusService(namespaceOrConnectionString?: string,
accessKey?: string,
issuer?: string,
acsNamespace?: string,
host?: string,
authenticationProvider?: object): ServiceBusService;
export function createNotificationHubService(hubName: string,
endpointOrConnectionString?: string,
sharedAccessKeyName?: string,
sharedAccessKeyValue?: string): NotificationHubService;
export function createWrapService(acsHost: string,
issuer?: string,
accessKey?: string): WrapService;
export namespace Azure.ServiceBus {
export type Duration = string;
export type DateString = string;
export interface Dictionary<T> {
[k: string]: T;
}
interface NotificationHubRegistration {
RegistrationId: string;
export interface ReceiveQueueMessageOptions {
timeoutIntervalInS?: number;
}
export interface ReceiveSubscriptionMessageOptions extends ReceiveQueueMessageOptions {
isPeekLock?: boolean;
}
interface IBrokerPropertiesResponse {
readonly DeliveryCount: number;
readonly LockedUntil: DateString;
readonly LockToken: string;
readonly SequenceNumber: number;
}
interface IBrokerProperties {
CorrelationId: string;
Label: string;
MessageId: string;
PartitionKey: string;
ReplyTo: string;
ReplyToSessionId: string;
ScheduledEnqueueTimeUtc: string;
SessionId: string;
TimeToLive: string;
To: string;
}
export interface Message {
body: string;
brokerProperties?: BrokerProperties;
contentType?: string;
customProperties?: Dictionary<any>;
}
/*
* Options interfaces
*/
interface CreateOptions {
DefaultMessageTimeToLive: string;
DuplicateDetectionHistoryTimeWindow: string;
EnablePartitioning: boolean;
MaxSizeInMegaBytes: number;
RequiresDuplicateDetection: boolean;
}
interface IQueueOptions extends CreateOptions {
AutoDeleteOnIdle: string;
DeadLetteringOnMessageExpiration: boolean;
LockDuration: string;
RequiresSession: boolean;
}
interface ICreateTopicOptions extends CreateOptions {
EnableBatchedOperations: boolean;
SizeInBytes: boolean;
SupportOrdering: boolean;
}
interface ICreateTopicIfNotExistsOptions extends ICreateTopicOptions {
EnableDeadLetteringOnFilterEvaluationExceptions: boolean;
EnableDeadLetteringOnMessageExpiration: boolean;
MaxCorrelationFiltersPerTopic: number;
MaxSqlFiltersPerTopic: number;
MaxSubscriptionsPerTopic: number;
}
interface ICreateSubscriptionOptions {
DefaultMessageTimeToLive: string;
EnableDeadLetteringOnFilterEvaluationExceptions: boolean;
EnableDeadLetteringOnMessageExpiration: boolean;
LockDuration: string;
RequiresSession: boolean;
}
interface PaginationOptions {
top: number;
skip: number;
}
interface ICreateRuleOptions {
trueFilter: string;
falseFilter: string;
sqlExpressionFilter: string;
correlationIdFilter: string;
sqlRuleAction: string;
}
interface ICreateNotificationHubOptions {
apns: Dictionary<string>;
gcm: Dictionary<string>;
mpns: Dictionary<string>;
wns: Dictionary<string>;
}
export interface NotificationHubRegistration {
BodyTemplate?: any;
ChannelUri?: string;
DeviceToken?: string;
gcmRegistrationId?: string;
Tags?: string;
BodyTemplate?: any;
WnsHeaders?: any;
MpnsHeaders?: any;
Expiry?: Date;
gcmRegistrationId?: string;
MpnsHeaders?: any;
RegistrationId: string;
Tags?: string;
WnsHeaders?: any;
}
export class NotificationHubService {
new(hubName: string, endpointOrConnectionString: string, sharedAccessKeyName?: string, sharedAccessKeyValue?: string): NotificationHubService;
hubName: string;
wns: Wns.Service;
apns: Apns.Service;
gcm: Gcm.Service;
mpns: Mpns.Service;
send(tags: string, payload: Object | string, optionsOrCallback?: { headers: Object } | Callback, callback?: Callback): void;
createOrUpdateInstallation(installation: string, options: any, callback?: Callback): void;
patchInstallation(installationId: string, partialUpdateOperations: any[], options: any, callback?: Callback): void;
deleteInstallation(installationId: string, options: any, callback?: Callback): void;
getInstallation(installationId: string, options: any, callback?: Callback): void;
/*
// old school?
createRegistrationId(callback?: Callback): void;
getRegistration(registrationId: string, options: any, callback?: Callback): void;
deleteRegistration(registrationId: string, options?: { etag: any }, callback?: Callback): void;
updateRegistration(registration: NotificationHubRegistration, options?: { etag: any }, callback?: Callback): void;
createOrUpdateRegistration(registration: NotificationHubRegistration, options?: { etag: any }, callback?: Callback): void;
listRegistrations(options?: { top: number, skip: number }, callback?: Callback): void;
listRegistrationsByTag(tag: string, options?: { top: number, skip: number }, callback?: Callback): void;
*/
export interface Response {
body: Dictionary<string | object>;
headers: Dictionary<string>;
isSuccessful: boolean;
md5?: string;
statusCode: number;
}
export module Apns {
interface Payload {
expiry?: Date;
aps?: Object;
badge?: number;
alert?: string;
sound?: string;
payload: Object;
export interface ErrorResponse extends Response {
body: {
Error: {
Code: string;
Detail: string;
};
};
}
export namespace Results.Models {
export enum EntityStatus {
Active = 'Active',
Creating = 'Creating',
Deleting = 'Deleting',
Disabled = 'Disabled',
ReceiveDisabled = 'ReceiveDisabled',
Renaming = 'Renaming',
Restoring = 'Restoring',
SendDisabled = 'SendDisabled',
Unknown = 'Unknown'
}
interface Service {
new(service: NotificationHubService): Service;
send(tags: string | string[], payload: Apns.Payload, callback?: Callback): void;
createNativeRegistration(token: string, tags: string | string[], optionsOrCallback?: Object | Callback, callback?: Callback): void;
createOrUpdateNativeRegistration(registrationId: string, token: string, tags: string | string[], optionsOrCallback?: Object | Callback, callback?: Callback): void;
createTemplateRegistration(token: string, tags: string | string[], template: Apns.Payload, optionsOrCallback?: Object | Callback, callback?: Callback): void;
createOrUpdateTemplateRegistration(registrationId: string, token: string, tags: string | string[], template: Apns.Payload, optionsOrCallback?: Object | Callback, callback?: Callback): void;
updateTemplateRegistration(registrationId: string, token: string, tags: string | string[], template: Apns.Payload, optionsOrCallback?: Object | Callback, callback?: Callback): void;
listRegistrationsByToken(token: string, optionsOrCallback?: { top: number, skip: number } | Callback, callback?: Callback): void;
export enum EntityAvailabilityStatus {
Available = 'Available',
Limited = 'Limited',
Renaming = 'Renaming',
Restoring = 'Restoring',
Unknown = 'Unknown'
}
}
export module Gcm {
interface Service {
new(service: NotificationHubService): Service;
send(tags: string | string[], payload: any, callback?: Callback): void;
createNativeRegistration(gcmRegistrationId: string, tags: string | string[], optionsOrCallback?: Object | Callback, callback?: Callback): void;
createOrUpdateNativeRegistration(registrationId: string, gcmRegistrationId: string, tags: string | string[], optionsOrCallback?: Object | Callback, callback?: Callback): void;
createTemplateRegistration(gcmRegistrationId: string, tags: string | string[], template: any, optionsOrCallback?: Object | Callback, callback?: Callback): void;
createOrUpdateTemplateRegistration(registrationId: string, gcmRegistrationId: string, tags: string | string[], template: any, optionsOrCallback?: Object | Callback, callback?: Callback): void;
updateTemplateRegistration(registrationId: string, gcmRegistrationId: string, tags: string | string[], template: any, optionsOrCallback?: Object | Callback, callback?: Callback): void;
listRegistrationsByGcmRegistrationId(gcmRegistrationId: string, optionsOrCallback?: { top: number, skip: number } | Callback, callback?: Callback): void;
interface Base {
_: {
ContentRootElement: string;
id: string;
title: string;
published: DateString;
updated: DateString;
author?: {
name: string;
};
link: string;
};
CreatedAt: DateString;
}
interface ExtendedBase extends Base {
AuthorizationRules: string;
AutoDeleteOnIdle: string;
DefaultMessageTimeToLive: string;
DuplicateDetectionHistoryTimeWindow: Duration;
EnableBatchedOperations: string;
EnableExpress: string;
EnablePartitioning: string;
EntityAvailabilityStatus: string;
IsAnonymousAccessible: string;
MaxSizeInMegabytes: string;
RequiresDuplicateDetection: string;
SizeInBytes: string;
Status: EntityStatus;
UpdatedAt: DateString;
}
// export interface Generic extends Base {
// [x: string]: string | Dictionary<string | object>;
// }
export interface Topic extends ExtendedBase {
AccessedAt: DateString;
CountDetails: {
'd2p1:ActiveMessageCount': string;
'd2p1:DeadLetterMessageCount': string;
'd2p1:ScheduledMessageCount': string;
'd2p1:TransferMessageCount': string;
'd2p1:TransferDeadLetterMessageCount': string;
};
EnableSubscriptionPartitioning: string;
FilteringMessagesBeforePublishing: string;
IsExpress: string;
SubscriptionCount: string;
SupportOrdering: string;
TopicName: string;
}
export interface Queue extends ExtendedBase {
DeadLetteringOnMessageExpiration: string;
LockDuration: Duration;
MaxDeliveryCount: string;
MessageCount: string;
QueueName: string;
RequiresSession: string;
SupportOrdering: string;
}
export interface Subscription extends ExtendedBase {
CountDetails: {
'd3p1:ActiveMessageCount': string;
'd3p1:DeadLetterMessageCount': string;
'd3p1:ScheduledMessageCount': string;
'd3p1:TransferMessageCount': string;
'd3p1:TransferDeadLetterMessageCount': string;
};
DeadLetteringOnFilterEvaluationExceptions: string;
DeadLetteringOnMessageExpiration: string;
LockDuration: string;
MaxDeliveryCount: string;
MessageCount: string;
RequiresSession: string;
SubscriptionName: string;
TopicName: string;
}
/**
* @see https://docs.microsoft.com/en-us/azure/service-bus-messaging/service-bus-messaging-sql-filter
*/
interface SqlFilter {
readonly CompatibilityLevel: string;
Parameters?: Dictionary<any>;
RequiresPreprocessing?: string;
SqlExpression: string;
}
type CorrelationFilter = Partial<{
ContentType: string;
CorrelationId: string;
Label: string;
Properties: string;
ReplyTo: string;
ReplyToSessionId: string;
RequiresPreprocessing: string;
SessionId: string;
To: string;
}>;
export interface Rule extends Base {
Action: string | SqlFilter;
Filter: SqlFilter | CorrelationFilter;
Name: string;
TopicName: string;
SubscriptionName: string;
RuleName: string;
}
}
export module Mpns { interface Service { } }
/*
* Callbacks
*/
export type ResponseCallback = (error: Error | null, response: Response) => void;
export module Wns {
interface Payload {
text1?: string;
text2?: string;
text3?: string;
text4?: string;
image1src?: string;
image1alt?: string;
image2src?: string;
image2alt?: string;
image3src?: string;
image3alt?: string;
image4src?: string;
image4alt?: string;
lang?: string;
type?: string;
}
export type ResultAndResponseCallback = (error: Error | null,
result: boolean | Results.Models.Base | Results.Models.Base[],
response: Response) => void;
interface Options {
headers: Object;
}
export type TypedResultAndResponseCallback<T> = (error: Error | null,
result: T,
response: Response) => void;
interface Service {
new(service: NotificationHubService): Service;
sendTileSquareBlock(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquareText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquareText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquareText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquareText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText05(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText06(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText07(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText08(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText09(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText10(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideText11(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquareImage(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquarePeekImageAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquarePeekImageAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquarePeekImageAndText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileSquarePeekImageAndText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideImage(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideImageCollection(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideImageAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideImageAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideBlockAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideBlockAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideSmallImageAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideSmallImageAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideSmallImageAndText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideSmallImageAndText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWideSmallImageAndText05(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageCollection01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageCollection02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageCollection03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageCollection04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageCollection05(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageCollection06(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImageAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImage01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImage02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImage03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImage04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImage05(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendTileWidePeekImage06(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastImageAndText01(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastImageAndText02(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastImageAndText03(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendToastImageAndText04(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
// badges = ['none','activity','alert','available','away','busy','newMessage','paused','playing','unavailable','error', 'attention']
sendBadge(tags: string | string[], value: string | number, optionsOrCallback?: Options | Callback, callback?: Callback): void;
sendRaw(tags: string | string[], payload: any, optionsOrCallback?: Options | Callback, callback?: Callback): void;
// types = ['wns/toast', 'wns/badge', 'wns/tile', 'wns/raw']
send(tags: string | string[], payload: string, type: string, optionsOrCallback?: Options | Callback, callback?: Callback): void;
createNativeRegistration(channel: string, tags: string | string[], optionsOrCallback?: Options | Callback, callback?: Callback): void;
createOrUpdateNativeRegistration(registrationId: string, channel: string, tags: string | string[], optionsOrCallback?: Options | Callback, callback?: Callback): void;
listRegistrationsByChannel(channel: string, optionsOrCallback?: { top: number, skip: number } | Callback, callback?: Callback): void;
}
}
/*
* Options interfaces with all properties as optional
*/
export type BrokerProperties = Partial<IBrokerProperties>;
export type BrokerPropertiesResponse = IBrokerPropertiesResponse & Partial<IBrokerProperties>;
export type CreateQueueOptions = Partial<IQueueOptions>;
export type CreateTopicOptions = Partial<ICreateTopicOptions>;
export type CreateTopicIfNotExistsOptions = Partial<ICreateTopicIfNotExistsOptions>;
export type CreateSubscriptionOptions = Partial<ICreateSubscriptionOptions>;
export type ListSubscriptionsOptions = Partial<PaginationOptions>;
export type ListRulesOptions = Partial<PaginationOptions>;
export type CreateRuleOptions = Partial<ICreateRuleOptions>;
export type CreateNotificationHubOptions = Partial<ICreateNotificationHubOptions>;
export type ListNotificationHubsOptions = Partial<PaginationOptions>;
export type MessageOrName = Message | string;
}
+83
View File
@@ -0,0 +1,83 @@
import { Azure } from '../index';
import NotificationHubService = require('azure-sb/lib/notificationhubservice');
import ResponseCallback = Azure.ServiceBus.ResponseCallback;
import NotificationHubRegistration = Azure.ServiceBus.NotificationHubRegistration;
import ListNotificationHubsOptions = Azure.ServiceBus.ListNotificationHubsOptions;
import Dictionary = Azure.ServiceBus.Dictionary;
type Template = Partial<{
expiry: Date;
aps: object;
badge: number;
alert: string;
sound: string;
payload: object;
}>;
declare class ApnsService {
constructor(notificationHubService: NotificationHubService);
public notificationHubService: NotificationHubService;
public send(tags: string | string[],
payload: object | string,
callback: ResponseCallback): void;
public send(tags: string | string[],
payload: object | string,
options: { headers: Dictionary<string> },
callback: ResponseCallback): void;
public createNativeRegistration(token: string,
tags: string | string[],
callback: ResponseCallback): void;
public createNativeRegistration(token: string,
tags: string | string[],
options: object,
callback: ResponseCallback): void;
public createOrUpdateNativeRegistration(registrationId: string,
token: string,
tags: string | string[],
callback: ResponseCallback): void;
public createOrUpdateNativeRegistration(registrationId: string,
token: string,
tags: string | string[],
options: object,
callback: ResponseCallback): void;
public createTemplateRegistration(token: string,
tags: string | string[],
template: Template | string,
callback: ResponseCallback): void;
public createTemplateRegistration(token: string,
tags: string | string[],
template: Template | string,
options: object,
callback: ResponseCallback): void;
public updateTemplateRegistration(registrationId: string,
token: string,
tags: string | string[],
template: Template | string,
callback: ResponseCallback): void;
public updateTemplateRegistration(registrationId: string,
token: string,
tags: string | string[],
template: Template | string,
options: { headers: Dictionary<string> },
callback: ResponseCallback): void;
public listRegistrationsByToken(token: string,
callback: ResponseCallback): void;
public listRegistrationsByToken(token: string,
options: ListNotificationHubsOptions,
callback: ResponseCallback): void;
}
export = ApnsService;
+71
View File
@@ -0,0 +1,71 @@
import { Azure } from '../index';
import NotificationHubService = require('azure-sb/lib/notificationhubservice');
import ResponseCallback = Azure.ServiceBus.ResponseCallback;
import NotificationHubRegistration = Azure.ServiceBus.NotificationHubRegistration;
import ListNotificationHubsOptions = Azure.ServiceBus.ListNotificationHubsOptions;
import Dictionary = Azure.ServiceBus.Dictionary;
type Template = Partial<{}>;
declare class GcmService {
constructor(notificationHubService: NotificationHubService);
public notificationHubService: NotificationHubService;
public send(tags: string | string[],
payload: object | string,
callback: ResponseCallback): void;
public createNativeRegistration(gcmRegistrationId: string,
tags: string | string[],
callback: ResponseCallback): void;
public createNativeRegistration(token: string,
tags: string | string[],
options: object,
callback: ResponseCallback): void;
public createOrUpdateNativeRegistration(registrationId: string,
gcmRegistrationId: string,
tags: string | string[],
callback: ResponseCallback): void;
public createOrUpdateNativeRegistration(registrationId: string,
gcmRegistrationId: string,
tags: string | string[],
options: object,
callback: ResponseCallback): void;
public createTemplateRegistration(gcmRegistrationId: string,
tags: string | string[],
template: Template | string,
callback: ResponseCallback): void;
public createTemplateRegistration(gcmRegistrationId: string,
tags: string | string[],
template: Template | string,
options: object,
callback: ResponseCallback): void;
public updateTemplateRegistration(registrationId: string,
gcmRegistrationId: string,
tags: string | string[],
template: Template | string,
callback: ResponseCallback): void;
public updateTemplateRegistration(registrationId: string,
gcmRegistrationId: string,
tags: string | string[],
template: Template | string,
options: { headers: Dictionary<string> },
callback: ResponseCallback): void;
public listRegistrationsByGcmRegistrationId(gcmRegistrationId: string,
callback: ResponseCallback): void;
public listRegistrationsByGcmRegistrationId(gcmRegistrationId: string,
options: ListNotificationHubsOptions,
callback: ResponseCallback): void;
}
export = GcmService;
+29
View File
@@ -0,0 +1,29 @@
//
// Copyright (c) Microsoft and contributors. 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
//
// 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.
//
import { Azure } from 'azure-sb';
import Dictionary = Azure.ServiceBus.Dictionary;
export namespace Azure.ServiceBus.Results {
export interface AcsTokenResponse extends Dictionary<string | Dictionary<string>> {
WrapAccessToken: Dictionary<string>;
WrapAccessTokenExpiresIn: Dictionary<string>;
}
export interface AcsTokenResult {
parse(acsTokenQueryString: string): AcsTokenResponse;
}
}
+26
View File
@@ -0,0 +1,26 @@
//
// Copyright (c) Microsoft and contributors. 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
//
// 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.
//
import { Azure } from 'azure-sb';
import Dictionary = Azure.ServiceBus.Dictionary;
export namespace Azure.ServiceBus.Results {
export interface NotificationHubResult {
serialize(resource: Azure.ServiceBus.CreateNotificationHubOptions): string;
parse(xml: object): object | object[];
}
}
+40
View File
@@ -0,0 +1,40 @@
//
// Copyright (c) Microsoft and contributors. 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
//
// 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.
//
// Module dependencies.
import { Azure } from 'azure-sb';
import Dictionary = Azure.ServiceBus.Dictionary;
export namespace Azure.ServiceBus.Results {
export interface QueueResponse {
body: any;
headers: Dictionary<string>
}
export interface QueueMessageResponse {
body: any;
brokerProperties?: Azure.ServiceBus.BrokerProperties;
customProperties?: Dictionary<any>;
contentType?: string;
location?: string;
}
export interface QueueMessageResult {
parse(responseObject: object): QueueMessageResponse;
isRFC1123(value: string | any): boolean;
}
}
+41
View File
@@ -0,0 +1,41 @@
//
// Copyright (c) Microsoft and contributors. 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
//
// 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.
//
import { Azure } from 'azure-sb';
import Dictionary = Azure.ServiceBus.Dictionary;
export namespace Azure.ServiceBus.Results {
export interface QueueProperties {
DeadLetteringOnMessageExpiration: string;
DefaultMessageTimeToLive: string;
DuplicateDetectionHistoryTimeWindow: string;
EnableBatchedOperations: boolean;
EnablePartitioning: boolean;
LockDuration: string;
MaxDeliveryCount: number;
MaxSizeInMegabytes: number;
MessageCount: number;
RequiresDuplicateDetection: boolean;
RequiresSession: boolean;
SizeInBytes: number;
}
export interface QueueResult {
serialize(resource: QueueProperties): string;
parse(xml: object): object | object[];
}
}
+26
View File
@@ -0,0 +1,26 @@
//
// Copyright (c) Microsoft and contributors. 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
//
// 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.
//
import { Azure } from 'azure-sb';
import Dictionary = Azure.ServiceBus.Dictionary;
export namespace Azure.ServiceBus.Results {
export interface RegistrationResult {
serialize(type: string, resource: object, properties: string[]): string;
parse(xml: object): object | object[];
}
}
+28
View File
@@ -0,0 +1,28 @@
//
// Copyright (c) Microsoft and contributors. 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
//
// 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.
//
import { Azure } from 'azure-sb';
import Dictionary = Azure.ServiceBus.Dictionary;
export namespace Azure.ServiceBus.Results {
export interface ResourceResult {
setName(entry: Dictionary<any> | { _: { id: string } }, nameProperty: string): void;
serialize(resourceName: string, resource: object, properties: string[]): string;
parse(resourceName: string, nameProperty: string, xml: object): object | object[];
}
}
+26
View File
@@ -0,0 +1,26 @@
//
// Copyright (c) Microsoft and contributors. 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
//
// 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.
//
// Module dependencies.
import { Azure } from 'azure-sb';
export namespace Azure.ServiceBus.Results {
export interface RuleResult {
serialize(rule: Azure.ServiceBus.CreateRuleOptions): string;
parse(xml: object): object | object[];
}
}
+37
View File
@@ -0,0 +1,37 @@
//
// Copyright (c) Microsoft and contributors. 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
//
// 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.
//
import { Azure } from 'azure-sb';
export namespace Azure.ServiceBus.Results {
export interface SubscriptionProperties {
LockDuration: string;
RequiresSession: boolean;
DefaultMessageTimeToLive: string;
DeadLetteringOnMessageExpiration: string;
DeadLetteringOnFilterEvaluationExceptions: string;
MessageCount: number;
MaxDeliveryCount: number;
EnableBatchedOperations: boolean;
AutoDeleteOnIdle: boolean;
}
export interface SubscriptionResult {
serialize(resource: SubscriptionProperties): string;
parse(xml: object): object | object[];
}
}

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