diff --git a/angular-ui-bootstrap/index.d.ts b/angular-ui-bootstrap/index.d.ts index bc80d96b5a..1e4d15d282 100644 --- a/angular-ui-bootstrap/index.d.ts +++ b/angular-ui-bootstrap/index.d.ts @@ -15,6 +15,7 @@ export type IDropdownConfig = angular.ui.bootstrap.IDropdownConfig; export type IModalProvider = angular.ui.bootstrap.IModalProvider; export type IModalService = angular.ui.bootstrap.IModalService; export type IModalServiceInstance = angular.ui.bootstrap.IModalServiceInstance; +export type IModalInstanceService = angular.ui.bootstrap.IModalInstanceService; export type IModalScope = angular.ui.bootstrap.IModalScope; export type IModalSettings = angular.ui.bootstrap.IModalSettings; export type IModalStackService = angular.ui.bootstrap.IModalStackService; @@ -320,12 +321,12 @@ declare module 'angular' { interface IModalService { /** * @param {IModalSettings} options - * @returns {IModalServiceInstance} + * @returns {IModalInstanceService} */ - open(options: IModalSettings): IModalServiceInstance; + open(options: IModalSettings): IModalInstanceService; } - interface IModalServiceInstance { + interface IModalInstanceService { /** * A method that can be used to close a modal, passing a result. If `preventDefault` is called on the `modal.closing` event then the modal will remain open. */ @@ -357,6 +358,11 @@ declare module 'angular' { closed: angular.IPromise; } + /** + * @deprecated use IModalInstanceService instead. + */ + interface IModalServiceInstance extends IModalInstanceService { } + interface IModalScope extends angular.IScope { /** * Dismiss the dialog without assigning a value to the promise output. If `preventDefault` is called on the `modal.closing` event then the modal will remain open. @@ -512,17 +518,17 @@ declare module 'angular' { /** * Opens a new modal instance. */ - open(modalInstance: IModalServiceInstance, modal: any): void; + open(modalInstance: IModalInstanceService, modal: any): void; /** * Closes a modal instance with an optional result. */ - close(modalInstance: IModalServiceInstance, result?: any): void; + close(modalInstance: IModalInstanceService, result?: any): void; /** * Dismisses a modal instance with an optional reason. */ - dismiss(modalInstance: IModalServiceInstance, reason?: any): void; + dismiss(modalInstance: IModalInstanceService, reason?: any): void; /** * Dismiss all open modal instances with an optional reason that will be passed to each instance. @@ -536,7 +542,7 @@ declare module 'angular' { } interface IModalStackedMapKeyValuePair { - key: IModalServiceInstance; + key: IModalInstanceService; value: any; } diff --git a/axel/axel-tests.ts b/axel/axel-tests.ts new file mode 100644 index 0000000000..553973b210 --- /dev/null +++ b/axel/axel-tests.ts @@ -0,0 +1,7 @@ + +import * as axel from 'axel'; + +axel.clear(); +axel.bg(0,255,0); +axel.line(1,1,10,10); +axel.cursor.restore(); diff --git a/axel/index.d.ts b/axel/index.d.ts new file mode 100644 index 0000000000..751e2c33fa --- /dev/null +++ b/axel/index.d.ts @@ -0,0 +1,37 @@ +// Type definitions for Axel module +// Project: https://github.com/F1LT3R/axel +// Definitions by: Ruslan Molodyko +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare class Axel { + brush: string; + rows: number; + cols: number; + cursor: cursorInterface; + + lerp(p1: number, p2: number, m: number): number; + circ(x: number, y: number, m: number): number; + goto(x: number, y: number): void; + scrub(x1: number, y1: number, w: number, h: number): void; + box(x1: number, y1: number, w: number, h: number): void; + point(x: number, y: number, char: string): void; + dist(x1: number, y1: number, x2: number, y2: number): number; + line(x1: number, y1: number, x2: number, y2: number): void; + text(x: number, y: number, text: string): void; + fg(r: number, g: number, b: number): void; + bg(r: number, g: number, b: number): void; + draw(cb: Function): void; + clear(): void; +} + +declare interface cursorInterface { + on(): void; + off(): void; + reset(): void; + restore(): void; +} + +declare module 'axel' { + const instance: Axel; + export = instance; +} diff --git a/xmpp-jid/tsconfig.json b/axel/tsconfig.json similarity index 80% rename from xmpp-jid/tsconfig.json rename to axel/tsconfig.json index f4d02187a2..0ac3689676 100644 --- a/xmpp-jid/tsconfig.json +++ b/axel/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": true, + "strictNullChecks": false, "baseUrl": "../", "typeRoots": [ "../" @@ -16,7 +16,7 @@ "forceConsistentCasingInFileNames": true }, "files": [ - "index.d.ts", - "xmpp-jid-tests.ts" + "axel-tests.ts", + "index.d.ts" ] } \ No newline at end of file diff --git a/bootbox/bootbox-tests.ts b/bootbox/bootbox-tests.ts index b5f32931ae..f5604d5312 100644 --- a/bootbox/bootbox-tests.ts +++ b/bootbox/bootbox-tests.ts @@ -38,7 +38,29 @@ bootbox.prompt({ console.log(result); } }); - +bootbox.prompt({ + title: "This is a prompt with a set of checkbox inputs!", + inputType: 'checkbox', + inputOptions: [ + { + text: 'Choice One', + value: '1', + group: 'Group 1' + }, + { + text: 'Choice Two', + value: '2', + group: 'Group 1' + }, + { + text: 'Choice Three', + value: '3' + } + ], + callback: function (result) { + console.log(result); + } +}); bootbox.dialog({ title: "Wassup?", diff --git a/bootbox/index.d.ts b/bootbox/index.d.ts index d5ceb5ef62..28d30e2ba0 100644 --- a/bootbox/index.d.ts +++ b/bootbox/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Bootbox 4.4.0 // Project: https://github.com/makeusabrew/bootbox -// Definitions by: Vincent Bortone , Kon Pik , Anup Kattel , Dominik Schroeter , Troy McKinnon +// Definitions by: Vincent Bortone , Kon Pik , Anup Kattel , Dominik Schroeter , Troy McKinnon , Stanny Nuytkens // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -44,6 +44,7 @@ interface BootboxPromptOptions extends BootboxBaseOptions { inputType?: "text" | "textarea" | "email" | "select" | "checkbox" | "date" | "time" | "number" | "password"; callback: (result: string) => any; buttons?: BootboxConfirmPromptButtonMap; + inputOptions?: { text: string, value: string, group?: string }[]; } /** Bootbox options available when setting defaults for modals */ diff --git a/c3/c3-tests.ts b/c3/c3-tests.ts index 4a0695af1f..d9057eabb6 100644 --- a/c3/c3-tests.ts +++ b/c3/c3-tests.ts @@ -368,7 +368,9 @@ function line_examples() { data: {}, line: { connectNull: true, - step_type: "step-after" + step: { + type: "step-after" + } } }); } diff --git a/c3/index.d.ts b/c3/index.d.ts index 5edb096395..748b19bfc5 100644 --- a/c3/index.d.ts +++ b/c3/index.d.ts @@ -145,7 +145,9 @@ declare namespace c3 { /** * Change step type for step chart. 'step', 'step-before' and 'step-after' can be used. */ - step_type?: string; + step?: { + type: string; + }; }; area?: { diff --git a/htmlescape/htmlescape-tests.ts b/htmlescape/htmlescape-tests.ts new file mode 100644 index 0000000000..c3e174787c --- /dev/null +++ b/htmlescape/htmlescape-tests.ts @@ -0,0 +1,8 @@ +import * as htmlescape from "htmlescape"; +import { sanitize } from "htmlescape"; + +// === '{"x":"a\\u0026\\u003c\\u003e\\u2028\\u2029"}' +htmlescape({ x: "a&<>\u2028\u2029" }); + +// === 'a&<>\\u2028\\u2029' +sanitize("a&<>\u2028\u2029"); diff --git a/htmlescape/index.d.ts b/htmlescape/index.d.ts new file mode 100644 index 0000000000..51d8eae58d --- /dev/null +++ b/htmlescape/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for htmlescape 1.1 +// Project: https://github.com/zertosh/htmlescape +// Definitions by: bouzuya +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function htmlescape(o: any): string; +declare namespace htmlescape { + export function sanitize(s: string): string; +} + +export = htmlescape; +export as namespace htmlescape; diff --git a/htmlescape/tsconfig.json b/htmlescape/tsconfig.json new file mode 100644 index 0000000000..6ba5d9819a --- /dev/null +++ b/htmlescape/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "htmlescape-tests.ts" + ] +} diff --git a/xmpp-jid/tslint.json b/htmlescape/tslint.json similarity index 100% rename from xmpp-jid/tslint.json rename to htmlescape/tslint.json diff --git a/koa-cache-control/index.d.ts b/koa-cache-control/index.d.ts new file mode 100644 index 0000000000..19329fcfec --- /dev/null +++ b/koa-cache-control/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for koa-cache-control 2.0 +// Project: https://github.com/DaMouse404/koa-cache-control +// Definitions by: Peter Safranek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as Koa from "koa"; + +declare function cacheControl(options?: { + private?: boolean; + public?: boolean; + noStore?: boolean; + noCache?: boolean; + noTransform?: boolean; + mustRevalidate?: boolean; + staleIfError?: number; + staleWhileRevalidate?: number; + maxAge?: number; + sMaxAge?: number; +}): Koa.Middleware; + +declare namespace cacheControl {} + +export = cacheControl; diff --git a/koa-cache-control/koa-cache-control-tests.ts b/koa-cache-control/koa-cache-control-tests.ts new file mode 100644 index 0000000000..c99f4fe862 --- /dev/null +++ b/koa-cache-control/koa-cache-control-tests.ts @@ -0,0 +1,19 @@ +import * as Koa from "koa"; +import * as cacheControl from "koa-cache-control"; + +const app = new Koa(); + +app.use(cacheControl()); +app.use(cacheControl({})); +app.use(cacheControl({ + private: true, + public: true, + noStore: true, + noCache: true, + noTransform: true, + mustRevalidate: true, + staleIfError: 0, + staleWhileRevalidate: 0, + maxAge: 0, + sMaxAge: 0, +})); diff --git a/node-form/tsconfig.json b/koa-cache-control/tsconfig.json similarity index 82% rename from node-form/tsconfig.json rename to koa-cache-control/tsconfig.json index d0fa4eb87b..ae4aea7b85 100644 --- a/node-form/tsconfig.json +++ b/koa-cache-control/tsconfig.json @@ -11,15 +11,12 @@ "typeRoots": [ "../" ], - "paths": { - "q": [ "q/v0" ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", - "node-form-tests.ts" + "koa-cache-control-tests.ts" ] -} \ No newline at end of file +} diff --git a/koa-cache-control/tslint.json b/koa-cache-control/tslint.json new file mode 100644 index 0000000000..eb88e553a5 --- /dev/null +++ b/koa-cache-control/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "../tslint.json", + + "noImplicitAny": "true", + "noImplicitThis": "true", + "strictNullChecks": "true" +} diff --git a/meteor/README.md b/meteor/README.md index f560dd005e..374a6213e7 100644 --- a/meteor/README.md +++ b/meteor/README.md @@ -2,7 +2,7 @@ ## Description -These are the definitions for version 1.4 of Meteor. These definitions were generated from the from the same [Meteor data.js file] (https://github.com/meteor/meteor/blob/devel/docs/client/data.js) that is used to generate the official [Meteor docs] (http://docs.meteor.com/). The code that generates these definitions can be found [here](https://github.com/meteor-typescript/meteor-typescript-libs/). +These are the definitions for version 1.4 of Meteor. These definitions were generated from the same [Meteor data.js file](https://github.com/meteor/meteor/blob/devel/docs/client/data.js) that is used to generate the official [Meteor docs](http://docs.meteor.com/). The code that generates these definitions can be found [here](https://github.com/meteor-typescript/meteor-typescript-libs/). ## Upcoming Meteor `typescript` package @@ -33,19 +33,21 @@ Compilation will be much faster and code will be cleaner - it's always better to With the exception of the **body** and **head** templates, Meteor's Template dot notation cannot be used (ie. *Template.mytemplate*). Thanks to Typescript static typing checks, you will need to use the *bracket notation* to access the Template. - Template['myTemplateName'].helpers({ - foo: function () { - return Session.get("foo"); - } - }); - - Template['myTemplateName'].onRendered(function ( ) { ... }); +```js +Template['myTemplateName'].helpers({ + foo: function () { + return Session.get("foo"); + } +}); +Template['myTemplateName'].onRendered(function ( ) { ... }); +``` The same is true for `Meteor.settings`: - Meteor.settings.public[''] - +```ts +Meteor.settings.public[''] +``` ### Form fields @@ -55,11 +57,11 @@ Form fields typically need to be cast to ``. For instance to r ### Global variables Preface any global variable declarations with a TypeScript `declare var` statement (or place the statement in a definition file): - - declare var NavbarHelpers; - NavbarHelpers = {}; - NavbarHelpers.someMethod = function() {...} - +```ts +declare var NavbarHelpers; +NavbarHelpers = {}; +NavbarHelpers.someMethod = function() {...} +``` ### Collections @@ -67,18 +69,21 @@ The majority of extra work required to use TypeScript with Meteor is creating an To define collections, you will need to create an interface representing the collection and then declare a Collection type variable with that interface type (as a generic): - interface JobDAO { - _id?: string; - name: string; - status?: string; - queuedAt?: string; - } - - declare var Jobs: Mongo.Collection; - Jobs = new Mongo.Collection('jobs'); +```js +interface JobDAO { + _id?: string; + name: string; + status?: string; + queuedAt?: string; +} +declare var Jobs: Mongo.Collection; +Jobs = new Mongo.Collection('jobs'); +``` Finally, any TypeScript file using collections will need to contain a reference at the top pointing to the collection definitions: - /// - /// +```ts +/// +/// +``` diff --git a/node-form/index.d.ts b/node-form/index.d.ts deleted file mode 100644 index ddeb3d542f..0000000000 --- a/node-form/index.d.ts +++ /dev/null @@ -1,709 +0,0 @@ -// Type definitions for node-form v1.0.13 -// Project: https://github.com/rsamec/form -// Definitions by: Roman Samec -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -import * as Q from "q"; - -export as namespace Validation; - -export = Validation; - -declare namespace Validation { - /** - * Custom message functions. - */ - interface IErrorCustomMessage { - (config: any, args: any): string; - } - /** - * It represents a property validator for atomic object. - */ - interface IPropertyValidator { - isAcceptable(s: any): boolean; - customMessage?: IErrorCustomMessage; - tagName?: string; - } - /** - * It represents a property validator for simple string value. - */ - interface IStringValidator extends IPropertyValidator { - isAcceptable(s: string): boolean; - } - /** - * It represents an async property validator for atomic object. - */ - interface IAsyncPropertyValidator { - isAcceptable(s: any): Q.Promise; - customMessage?: IErrorCustomMessage; - isAsync: boolean; - tagName?: string; - } - /** - * It represents an async property validator for simple string value. - */ - interface IAsyncStringPropertyValidator extends IAsyncPropertyValidator { - isAcceptable(s: string): Q.Promise; - } - /** - * It defines compare operators. - */ - enum CompareOperator { - LessThan = 0, - LessThanEqual = 1, - Equal = 2, - NotEqual = 3, - GreaterThanEqual = 4, - GreaterThan = 5, - } - class StringFce { - static format(s: string, args: any): string; - } - class NumberFce { - static GetNegDigits(value: string): number; - } - class LettersOnlyValidator implements IStringValidator { - public isAcceptable(s: string): boolean; - public tagName: string; - } - class ZipCodeValidator implements IStringValidator { - public isAcceptable(s: string): boolean; - public tagName: string; - } - class EmailValidator implements IStringValidator { - public isAcceptable(s: string): boolean; - public tagName: string; - } - class UrlValidator implements IStringValidator { - public isAcceptable(s: string): boolean; - public tagName: string; - } - class RequiredValidator implements IStringValidator { - public isAcceptable(s: string): boolean; - public tagName: string; - } - class DateValidator implements IStringValidator { - public isAcceptable(s: string): boolean; - public tagName: string; - } - class DateISOValidator implements IStringValidator { - public isAcceptable(s: string): boolean; - public tagName: string; - } - class NumberValidator implements IStringValidator { - public isAcceptable(s: string): boolean; - public tagName: string; - } - class DigitValidator implements IStringValidator { - public isAcceptable(s: string): boolean; - public tagName: string; - } - class SignedDigitValidator implements IStringValidator { - public isAcceptable(s: string): boolean; - public tagName: string; - } - class MinLengthValidator implements IStringValidator { - public MinLength: number; - constructor(MinLength?: number); - public isAcceptable(s: string): boolean; - public tagName: string; - } - class MaxLengthValidator implements IStringValidator { - public MaxLength: number; - constructor(MaxLength?: number); - public isAcceptable(s: string): boolean; - public tagName: string; - } - class RangeLengthValidator implements IStringValidator { - public RangeLength: number[]; - constructor(RangeLength?: number[]); - public isAcceptable(s: string): boolean; - public MinLength : number; - public MaxLength : number; - public tagName: string; - } - class MinValidator implements IPropertyValidator { - public Min: number; - constructor(Min?: number); - public isAcceptable(s: any): boolean; - public tagName: string; - } - class MaxValidator implements IPropertyValidator { - public Max: number; - constructor(Max?: number); - public isAcceptable(s: any): boolean; - public tagName: string; - } - class RangeValidator implements IPropertyValidator { - public Range: number[]; - constructor(Range?: number[]); - public isAcceptable(s: any): boolean; - public Min : number; - public Max : number; - public tagName: string; - } - class StepValidator implements IPropertyValidator { - public Step: string; - constructor(Step?: string); - public isAcceptable(s: any): boolean; - public tagName: string; - } - class PatternValidator implements IStringValidator { - public Pattern: string; - constructor(Pattern?: string); - public isAcceptable(s: string): boolean; - public tagName: string; - } - class ContainsValidator implements IAsyncPropertyValidator { - public Options: Q.Promise; - constructor(Options: Q.Promise); - public isAcceptable(s: string): Q.Promise; - public isAsync: boolean; - public tagName: string; - } -} -declare namespace Validation { - /** - * basic error structure - */ - interface IError { - HasError: boolean; - ErrorMessage: string; - TranslateArgs?: IErrorTranslateArgs; - } - /** - * support for localization of error messages - */ - interface IErrorTranslateArgs { - TranslateId: string; - MessageArgs: any; - CustomMessage?: IErrorCustomMessage; - } - /** - * It defines conditional function. - */ - interface IOptional { - (): boolean; - } - /** - * It represents the validation result. - */ - interface IValidationFailure extends IError { - IsAsync: boolean; - Error: IError; - } - /** - * This class provides unit of information about error. - * Implements composite design pattern to enable nesting of error information. - */ - interface IValidationResult { - /** - * The name of error collection. - */ - Name: string; - /** - * Add error information to child collection of errors. - * @param validationResult - error information to be added. - */ - Add(validationResult: IValidationResult): void; - /** - * Remove error information from child collection of errors. - * @param index - index of error information to be removed. - */ - Remove(index: number): void; - /** - * Return collections of child errors information. - */ - Children: IValidationResult[]; - /** - * Return true if there is any error. - */ - HasErrors: boolean; - /** - * Return true if there is any error and hasw dirty state. - */ - HasErrorsDirty: boolean; - /** - * Return error message, if there is no error, return empty string. - */ - ErrorMessage: string; - /** - * Return number of errors. - */ - ErrorCount: number; - /** - * It enables to have errors optional. - */ - Optional?: IOptional; - /** - * It enables support for localization of error messages. - */ - TranslateArgs?: IErrorTranslateArgs[]; - } - /** - * - * @ngdoc object - * @name Error - * @module Validation - * - * - * @description - * It represents basic error structure. - */ - class Error implements IError { - public HasError: boolean; - public ErrorMessage: string; - constructor(); - } - /** - * - * @ngdoc object - * @name ValidationFailure - * @module Validation - * - * - * @description - * It represents validation failure. - */ - class ValidationFailure implements IError { - public Error: IError; - public IsAsync: boolean; - constructor(Error: IError, IsAsync: boolean); - public HasError : boolean; - public ErrorMessage : string; - public TranslateArgs : IErrorTranslateArgs; - } - /** - * - * @ngdoc object - * @name ValidationResult - * @module Validation - * - * - * @description - * It represents simple abstract error object. - */ - class ValidationResult implements IValidationResult { - public Name: string; - constructor(Name: string); - public IsDirty: boolean; - public Children : IValidationResult[]; - public Add(error: IValidationResult): void; - public Remove(index: number): void; - public Optional: IOptional; - public TranslateArgs: IErrorTranslateArgs[]; - public HasErrorsDirty : boolean; - public HasErrors : boolean; - public ErrorCount : number; - public ErrorMessage : string; - } - /** - * - * @ngdoc object - * @name CompositeValidationResult - * @module Validation - * - * - * @description - * It represents composite error object. - */ - class CompositeValidationResult implements IValidationResult { - public Name: string; - public Children: IValidationResult[]; - constructor(Name: string); - public Optional: IOptional; - public AddFirst(error: IValidationResult): void; - public Add(error: IValidationResult): void; - public Remove(index: number): void; - public HasErrorsDirty : boolean; - public HasErrors : boolean; - public ErrorCount : number; - public ErrorMessage : string; - public TranslateArgs : IErrorTranslateArgs[]; - public LogErrors(headerMessage?: string): void; - public Errors : { - [name: string]: IValidationResult; - }; - private FlattenErros; - public SetDirty(): void; - public SetPristine(): void; - private SetDirtyEx(node, dirty); - private flattenErrors(node, errorCollection); - private traverse(node, indent); - } -} -declare namespace Validation { - /** - * @ngdoc module - * @name Validation - * - * - * @description - * # Validation (core module) - * The module itself contains the essential components for an validation engine to function. The table below - * lists a high level breakdown of each of the components (object, functions) available within this core module. - * - *
- */ - /** - * It defines validation function. - */ - interface IValidate { - (args: IError): void; - } - /** - * It defines async validation function. - */ - interface IAsyncValidate { - (args: IError): Q.Promise; - } - /** - * It represents named validation function. - */ - interface IValidatorFce { - Name: string; - ValidationFce?: IValidate; - AsyncValidationFce?: IAsyncValidate; - } - /** - * This class represents custom validator. - */ - interface IValidator { - Validate(context: any): IValidationFailure; - ValidateAsync(context: any): Q.Promise; - Error: IError; - } - /** - * It represents abstract validator for type of . - */ - interface IAbstractValidator { - RuleFor(prop: string, validator: IPropertyValidator): any; - ValidationFor(prop: string, validator: IValidatorFce): any; - ValidatorFor(prop: string, validator: IAbstractValidator): any; - /** - * It creates new concrete validation rule and assigned data context to this rule. - * @param name of the rule - * @constructor - */ - CreateRule(name: string): IAbstractValidationRule; - CreateAbstractRule(name: string): IAbstractValidationRule; - CreateAbstractListRule(name: string): IAbstractValidationRule; - /** - * return true if this validation rule is intended for list of items, otherwise true - */ - ForList: boolean; - } - /** - * It represents concrete validation rule for type of . - */ - interface IAbstractValidationRule { - /** - * Performs validation using a validation context and returns a collection of Validation Failures. - */ - Validate(context: T): IValidationResult; - /** - * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. - */ - ValidateAsync(context: T): Q.Promise; - /** - * Performs validation and async validation using a validation context. - */ - ValidateAll(context: T): void; - /** - * Performs validation and async validation using a validation context for a passed field. - */ - ValidateField(context: T, propName: string): void; - /** - * Return validation results. - */ - ValidationResult: IValidationResult; - Rules: { - [name: string]: IPropertyValidationRule; - }; - Validators: { - [name: string]: IValidator; - }; - Children: { - [name: string]: AbstractValidationRule; - }; - } - /** - * It represents property validation rule for type of . - */ - interface IPropertyValidationRule { - /** - *The validators that are grouped under this rule. - */ - Validators: { - [name: string]: any; - }; - /** - * Performs validation using a validation context and returns a collection of Validation Failures. - */ - Validate(context: IValidationContext): IValidationFailure[]; - /** - * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. - */ - ValidateAsync(context: IValidationContext): Q.Promise; - } - /** - * It represents a data context for validation rule. - */ - interface IValidationContext { - /** - * Return current value. - */ - Value: string; - /** - * Return property name for current data context. - */ - Key: string; - /** - * Data context for validation rule. - */ - Data: T; - } - /** - * - * @ngdoc object - * @name AbstractValidator - * @module Validation - * - * - * @description - * It enables to create custom validator for your own abstract object (class) and to assign validation rules to its properties. - * You can assigned these rules - * - * + property validation rules - use _RuleFor_ property - * + property async validation rules - use _RuleFor_ property - * + shared validation rules - use _ValidationFor_ property - * + custom object validator - use _ValidatorFor_ property - enables composition of child custom validators - */ - class AbstractValidator implements IAbstractValidator { - public Validators: { - [name: string]: IPropertyValidator[]; - }; - public AbstractValidators: { - [name: string]: IAbstractValidator; - }; - public ValidationFunctions: { - [name: string]: IValidatorFce[]; - }; - public RuleFor(prop: string, validator: IPropertyValidator): void; - public ValidationFor(prop: string, fce: IValidatorFce): void; - public ValidatorFor(prop: string, validator: IAbstractValidator, forList?: boolean): void; - public CreateAbstractRule(name: string): AbstractValidationRule; - public CreateAbstractListRule(name: string): AbstractListValidationRule; - public CreateRule(name: string): AbstractValidationRule; - /** - * Return true if this validation rule is intended for list of items, otherwise true. - */ - public ForList: boolean; - } - /** - * - * @ngdoc object - * @name AbstractValidationRule - * @module Validation - * - * - * @description - * It represents concreate validator for custom object. It enables to assign validation rules to custom object properties. - */ - class AbstractValidationRule implements IAbstractValidationRule { - public Name: string; - public validator: AbstractValidator; - public ValidationResult: IValidationResult; - public Rules: { - [name: string]: IPropertyValidationRule; - }; - public Validators: { - [name: string]: IValidator; - }; - public Children: { - [name: string]: AbstractValidationRule; - }; - /** - * Return true if this validation rule is intended for list of items, otherwise true. - */ - public ForList: boolean; - constructor(Name: string, validator: AbstractValidator, forList?: boolean); - public addChildren(): void; - public SetOptional(fce: IOptional): void; - private createRuleFor(prop); - /** - * Performs validation using a validation context and returns a collection of Validation Failures. - */ - public Validate(context: T): IValidationResult; - /** - * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. - */ - public ValidateAsync(context: T): Q.Promise; - public ValidateAll(context: T): void; - public ValidateField(context: T, propName: string): void; - } - /** - * - * @ngdoc object - * @name AbstractListValidationRule - * @module Validation - * - * - * @description - * It represents an validator for custom object. It enables to assign rules to custom object properties. - */ - class AbstractListValidationRule extends AbstractValidationRule { - public Name: string; - public validator: AbstractValidator; - constructor(Name: string, validator: AbstractValidator); - /** - * Performs validation using a validation context and returns a collection of Validation Failures. - */ - public Validate(context: any): IValidationResult; - /** - * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. - */ - public ValidateAsync(context: any): Q.Promise; - private getValidationRule(i); - private getIndexedKey(i); - public NotifyListChanged(list: any[]): void; - } - /** - * - * @ngdoc object - * @name ValidationContext - * @module Validation - * - * - * @description - * It represents a data context for validation rule. - */ - class ValidationContext implements IValidationContext { - public Key: string; - public Data: T; - constructor(Key: string, Data: T); - public Value : any; - } - class MessageLocalization { - static customMsg: string; - static defaultMessages: { - "required": string; - "remote": string; - "email": string; - "url": string; - "date": string; - "dateISO": string; - "number": string; - "digits": string; - "signedDigits": string; - "creditcard": string; - "equalTo": string; - "maxlength": string; - "minlength": string; - "rangelength": string; - "range": string; - "max": string; - "min": string; - "step": string; - "contains": string; - "mask": string; - "custom": string; - }; - static ValidationMessages: { - "required": string; - "remote": string; - "email": string; - "url": string; - "date": string; - "dateISO": string; - "number": string; - "digits": string; - "signedDigits": string; - "creditcard": string; - "equalTo": string; - "maxlength": string; - "minlength": string; - "rangelength": string; - "range": string; - "max": string; - "min": string; - "step": string; - "contains": string; - "mask": string; - "custom": string; - }; - static GetValidationMessage(validator: any): string; - } - /** - * - * @ngdoc object - * @name PropertyValidationRule - * @module Validation - * - * - * @description - * It represents a property validation rule. The property has assigned collection of property validators. - */ - class PropertyValidationRule extends ValidationResult implements IPropertyValidationRule { - public Name: string; - public Validators: { - [name: string]: any; - }; - public ValidationFailures: { - [name: string]: IValidationFailure; - }; - constructor(Name: string, validatorsToAdd?: IPropertyValidator[]); - public AddValidator(validator: any): void; - public Errors : { - [name: string]: IValidationFailure; - }; - public HasErrors : boolean; - public ErrorCount : number; - public ErrorMessage : string; - public TranslateArgs : IErrorTranslateArgs[]; - /** - * Performs validation using a validation context and returns a collection of Validation Failures. - */ - public Validate(context: IValidationContext): IValidationFailure[]; - public ValidateEx(value: any): IValidationFailure[]; - /** - * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. - */ - public ValidateAsync(context: IValidationContext): Q.Promise; - /** - * Performs validation using a validation context and returns a collection of Validation Failures asynchronoulsy. - */ - public ValidateAsyncEx(value: string): Q.Promise; - } - /** - * - * @ngdoc object - * @name Validator - * @module Validation - * - * - * @description - * It represents a custom validator. It enables to define your own shared validation rules - */ - class Validator extends ValidationResult implements IValidator { - public Name: string; - private ValidateFce; - private AsyncValidationFce; - public Error: IError; - public ValidationFailures: { - [name: string]: IValidationFailure; - }; - constructor(Name: string, ValidateFce?: IValidate, AsyncValidationFce?: IAsyncValidate); - public Optional: IOptional; - public Validate(context: any): IValidationFailure; - public ValidateAsync(context: any): Q.Promise; - public HasError : boolean; - public Errors : { - [name: string]: IValidationFailure; - }; - public HasErrors : boolean; - public ErrorCount : number; - public ErrorMessage : string; - public TranslateArgs : IErrorTranslateArgs[]; - } -} diff --git a/node-form/node-form-tests.ts b/node-form/node-form-tests.ts deleted file mode 100644 index 75d98f6b13..0000000000 --- a/node-form/node-form-tests.ts +++ /dev/null @@ -1,25 +0,0 @@ -interface IPerson{ - Checked:boolean; - FirstName:string; - LastName:string; - Email:string; -} - -//create custom composite validator -var personValidator = new Validation.AbstractValidator(); - -//create field validators -var required = new Validation.RequiredValidator(); -var email = new Validation.EmailValidator(); -var maxLength = new Validation.MaxLengthValidator(); -maxLength.MaxLength = 15; - - -personValidator.RuleFor("FirstName", required); -personValidator.RuleFor("FirstName", maxLength); - -personValidator.RuleFor("LastName", required); -personValidator.RuleFor("LastName", maxLength); - -personValidator.RuleFor("Email", required); -personValidator.RuleFor("Email", email); diff --git a/notNeededPackages.json b/notNeededPackages.json index f9d50c929f..b49c089d9a 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -341,6 +341,12 @@ "typingsPackageName": "vue-router", "sourceRepoURL": "https://github.com/vuejs/vue-router", "asOfVersion": "2.0.0" + }, + { + "libraryName": "@xmpp/jid", + "typingsPackageName": "xmpp-jid", + "sourceRepoURL": "github.com/node-xmpp/node-xmpp/", + "asOfVersion": "1.2.0" } ] } \ No newline at end of file diff --git a/qajax/index.d.ts b/qajax/index.d.ts deleted file mode 100644 index fcfbea6649..0000000000 --- a/qajax/index.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -// Type definitions for Qajax -// Project: https://github.com/gre/qajax -// Definitions by: Boltmade -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -import * as Q from "q"; - -export = Qajax; -export as namespace Qajax; - -declare function Qajax(url : string) : Q.Promise; -declare function Qajax(options : any) : Q.Promise; -declare function Qajax(url : string, options : any) : Q.Promise; - -declare namespace Qajax { - export var defaults : any; - export function filterStatus(validStatus : number) : (xhr : XMLHttpRequest) => Q.Promise; - export function filterStatus(validStatus : (status : number) => boolean) : (xhr : XMLHttpRequest) => Q.Promise; - export function filterSuccess() : Q.Promise; - - export function toJSON(xhr : XMLHttpRequest) : Q.Promise; - - export function getJSON(url : string) : Q.Promise; - - export function serialize(paramsObj : any) : string; -} \ No newline at end of file diff --git a/qajax/qajax-tests.ts b/qajax/qajax-tests.ts deleted file mode 100644 index 6770270cf4..0000000000 --- a/qajax/qajax-tests.ts +++ /dev/null @@ -1,69 +0,0 @@ -import Qajax = require("qajax"); -import * as Q from 'q'; - -// Based on https://github.com/gre/qajax/blob/master/test/qajax.js - -function resetDefaults () { - Qajax.defaults.logs = true; - Qajax.defaults.timeout = 1000; - Qajax.defaults.method = "GET"; - Qajax.defaults.headers = {}; - Qajax.defaults.base = ""; -} - -var sample01url = "/test/dataset/sample01.json"; -var sample01json = [ - { "name": "Jerome", "age": 20 }, - { "name": "Gerard", "age": 30 }, - { "name": "Martine", "age": 43 } -]; - -var emptyUrl = "/test/dataset/empty"; - -function urlWithOptions (url : string, options : any) { - return url+"?"+Qajax.serialize(options); -} - -Qajax; -Qajax.filterStatus; -Qajax.filterSuccess; -Qajax.getJSON; -Qajax.serialize({ foo: 123, bar: "toto" }); -Qajax.getJSON(sample01url).then((res) => true, (err) => true); -Qajax(sample01url).then(Qajax.filterSuccess).then(Qajax.toJSON); -Qajax(emptyUrl, { params: { status: 404 } }).then(Qajax.filterSuccess).then(Qajax.toJSON); -Qajax({method: "POST", url: "/ECHO", data: "1234567890\nazerty\nuiopqsdfghjklm\nwxcvbn\n"}).then(Qajax.filterSuccess); -Qajax({method: "POST", url: "/ECHO", data: { foo: 123, bar: { value: 42 }, arr: [1, 2, 3] }}).then(Qajax.filterSuccess).then(Qajax.toJSON); -Qajax({ url: emptyUrl, params: { status: 201 } }).then(Qajax.filterStatus(200)); -Qajax({method: "POST", url: emptyUrl, params: { status: 500 }}).then(Qajax.filterSuccess).then(Qajax.toJSON); - -var cancellationD = Q.defer(); -var cancellation = cancellationD.promise; -Qajax({ cancellation: cancellation, url: urlWithOptions(emptyUrl, { latency: 400 }) }).then(Qajax.filterSuccess).then(Qajax.toJSON); - -Qajax.defaults.timeout = 200; -Qajax({method: "DELETE", url: sample01url, params: { latency: 500 }}); - -resetDefaults(); -Qajax({method: "POST", url: sample01url, params: { latency: 300 }, timeout: 2000}); - -Qajax.defaults.timeout = 200; -Qajax({method: "DELETE", url: sample01url, params: { latency: 500 }, timeout: 0}); - -resetDefaults(); -Qajax({headers: { "X-Hello": "world" }, method: "GET", url: "/ECHO_HEADERS"}).then(Qajax.filterSuccess).then(Qajax.toJSON); -Qajax({headers: { "X-Hi": "world" }, method: "GET", url: "/ECHO_HEADERS"}).then(Qajax.filterSuccess).then(Qajax.toJSON); -Qajax.defaults.headers = {"X-Foo": "bar"}; -Qajax({method: "GET", url: "/ECHO_HEADERS"}).then(Qajax.filterSuccess).then(Qajax.toJSON); - -resetDefaults(); -Qajax("sample01.json", {base: "/test/dataset/"}).then(Qajax.filterSuccess).then(Qajax.toJSON); -Qajax.defaults.base = "/test/dataset/"; -Qajax("empty").then(Qajax.filterSuccess); - -resetDefaults(); -Qajax.defaults.method = "POST"; -Qajax("/ECHO", { data: "1234567890\nazerty\nuiopqsdfghjklm\nwxcvbn\n", responseType: "text/plain" }).then(Qajax.filterSuccess); - -resetDefaults(); -Qajax.getJSON(urlWithOptions(sample01url, { latency: 50 })).then((res) => true, (err) => true, () => true); diff --git a/react-svg-pan-zoom/index.d.ts b/react-svg-pan-zoom/index.d.ts new file mode 100644 index 0000000000..837890a507 --- /dev/null +++ b/react-svg-pan-zoom/index.d.ts @@ -0,0 +1,198 @@ +// Type definitions for react-svg-pan-zoom 2.5 +// Project: https://github.com/chrvadala/react-svg-pan-zoom#readme +// Definitions by: Huy Nguyen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 +import * as React from 'react'; + +declare module 'react-svg-pan-zoom' { + + // String constants: + const MODE_IDLE = 'idle'; + const MODE_PANNING = 'panning'; + const MODE_ZOOMING = 'zooming'; + + export const TOOL_AUTO = 'auto'; + export const TOOL_NONE = 'none'; + export const TOOL_PAN = 'pan'; + export const TOOL_ZOOM_IN = 'zoom-in'; + export const TOOL_ZOOM_OUT = 'zoom-out'; + + export const POSITION_NONE = 'none'; + export const POSITION_TOP = 'top'; + export const POSITION_RIGHT = 'right'; + export const POSITION_BOTTOM = 'bottom'; + export const POSITION_LEFT = 'left'; + + export type Mode = typeof MODE_IDLE | typeof MODE_PANNING | typeof MODE_ZOOMING; + + export interface Value { + version: 2, + mode: Mode, + focus: boolean, + a: number, + b: number, + c: number, + d: number, + e: number, + f: number, + viewerWidth: number, + viewerHeight: number, + SVGWidth: number, + SVGHeight: number, + startX?: number | null, + startY?: number | null, + endX?: number | null, + endY?: number | null, + + } + + export type Tool = typeof TOOL_AUTO | typeof TOOL_NONE | typeof TOOL_PAN | + typeof TOOL_ZOOM_IN | typeof TOOL_ZOOM_OUT + export type ToolbarPosition = typeof POSITION_NONE | typeof POSITION_TOP | typeof POSITION_RIGHT | + typeof POSITION_BOTTOM | typeof POSITION_LEFT + + + export interface OptionalProps { + //background of the viewer + background: React.CSSProperties, + + //background of the svg + SVGBackground: string, + + //value of the viewer (current point of view) + value: Value | null, + + //CSS style of the Viewer + style: object, + + //className of the Viewer + className: string, + + //detect zoom operation performed trough pinch gesture or mouse scroll + detectWheel: boolean, + + //perform PAN if the mouse is on viewer border + detectAutoPan: boolean, + + //toolbar position + toolbarPosition: ToolbarPosition, + + //handler something changed + onChangeValue: (value: Value) => void, + + //handler tool changed + onChangeTool: (tool: Tool) => void, + + // Note: The `T` type parameter is the type of the `target` of the event: + //handler click + onClick: (event: ViewerMouseEvent) => void, + + //handler double click + onDoubleClick: (event: ViewerMouseEvent) => void, + + //handler mouseup + onMouseUp: (event: ViewerMouseEvent) => void, + + //handler mousemove + onMouseMove: (event: ViewerMouseEvent) => void, + + //handler mousedown + onMouseDown: (event: ViewerMouseEvent) => void, + + //if disabled the user can move the image outside the viewer + preventPanOutside: boolean, + + //how much scale in or out + scaleFactor: number, + + //current active tool (TOOL_NONE, TOOL_PAN, TOOL_ZOOM_IN, TOOL_ZOOM_OUT) + tool: Tool, + + //modifier keys //https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/getModifierState + modifierKeys: string[], + + //override default toolbar component + // TODO: specify function type more clearly + customToolbar: React.Component | React.StatelessComponent, + + // How about touch events? They are in README but not in `propTypes`. + } + + export interface RequiredProps { + //width of the viewer displayed on screen + width: number, + //height of the viewer displayed on screen + height: number, + + //accept only one node SVG + // TODO: Figure out how to constrain `children` or maybe just leave it commented out + // because `children` is already implicit props + // children: () => any + } + + export type Props = RequiredProps & Partial + + class ReactSVGPanZoom extends React.Component { + pan(SVGDeltaX: number, SVGDeltaY: number): void + zoom(SVGPointX: number, SVGPointY: number, scaleFactor: number): void + fitSelection(selectionSVGPointX: number, selectionSVGPointY: number, selectionWidth: number, selectionHeight: number): void + fitToViewer(): void + setPointOnViewerCenter(SVGPointX: number, SVGPointY: number, zoomLevel: number): void + reset(): void + zoomOnViewerCenter(scaleFactor: number): void + getValue(): Value + setValue(value: Value): void + getTool(): Tool + setTool(tool: Tool): void + } + + + export interface Point { + x: number, + y: number, + } + + export interface ViewerMouseEvent{ + originalEvent: React.MouseEvent, + SVGViewer: SVGSVGElement, + point: Point, + x: number, + y: number, + scaleFactor: number, + translationX: number, + translationY: number, + preventDefault(): void + stopPropagation(): void + } + + export interface ViewerTouchEvent { + originalEvent: React.TouchEvent, + SVGViewer: SVGSVGElement, + points: Point[], + changedPoints: Point[], + scaleFactor: number, + translationX: number, + translationY: number, + preventDefault(): void + stopPropagation(): void + } + + // Utility functions exposed: + export function pan(value: Value, SVGDeltaX: number, SVGDeltaY: number, panLimit?: number): Value + + export function zoom(value: Value, SVGPointX: number, SVGPointY: number, scaleFactor: number): Value + + export function fitSelection( + value: Value, selectionSVGPointX: number, selectionSVGPointY: number, selectionWidth: number, selectionHeight: number): Value + + export function fitToViewer(value: Value): Value + + export function zoomOnViewerCenter(value: Value, scaleFactor: number): Value + + export function setPointOnViewerCenter(value: Value, SVGPointX: number, SVGPointY: number, zoomLevel: number): Value + + export function reset(value: Value): Value +} + + diff --git a/react-svg-pan-zoom/react-svg-pan-zoom-tests.tsx b/react-svg-pan-zoom/react-svg-pan-zoom-tests.tsx new file mode 100644 index 0000000000..dbe8f0d55e --- /dev/null +++ b/react-svg-pan-zoom/react-svg-pan-zoom-tests.tsx @@ -0,0 +1,57 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import { + ReactSVGPanZoom, + Props, + fitToViewer, + ViewerMouseEvent +} from 'react-svg-pan-zoom'; + + +class Example1 extends React.Component<{}, {}> { + Viewer: ReactSVGPanZoom + constructor(props: Props) { + super(props); + } + + componentDidMount() { + this.Viewer.fitToViewer(); + } + + render() { + return ( +
+ + + + +
+ + this.Viewer = Viewer} + onClick={(event: ViewerMouseEvent) => console.log('click', event.x, event.y, event.originalEvent)} + onMouseUp={(event: ViewerMouseEvent) => console.log('up', event.x, event.y)} + onMouseMove={(event: ViewerMouseEvent) => console.log('move', event.x, event.y)} + onMouseDown={(event: ViewerMouseEvent) => console.log('down', event.x, event.y)}> + + + + + + + + + + + + +
+ ); + } +} + +ReactDOM.render( + , + document.getElementById('app') +); diff --git a/qajax/tsconfig.json b/react-svg-pan-zoom/tsconfig.json similarity index 77% rename from qajax/tsconfig.json rename to react-svg-pan-zoom/tsconfig.json index 17bb7d92b2..c1b72dd378 100644 --- a/qajax/tsconfig.json +++ b/react-svg-pan-zoom/tsconfig.json @@ -1,26 +1,24 @@ { "compilerOptions": { "module": "commonjs", + "jsx": "react", "lib": [ "es6", "dom" ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" ], - "paths": { - "q": [ "q/v0" ] - }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true }, "files": [ "index.d.ts", - "qajax-tests.ts" + "react-svg-pan-zoom-tests.tsx" ] -} \ No newline at end of file +} diff --git a/react-svg-pan-zoom/tslint.json b/react-svg-pan-zoom/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/react-svg-pan-zoom/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/redux-action/index.d.ts b/redux-action/index.d.ts new file mode 100644 index 0000000000..eff19178e9 --- /dev/null +++ b/redux-action/index.d.ts @@ -0,0 +1,93 @@ +// Type definitions for redux-action 1.2 +// Project: https://github.com/coderhaoxin/redux-action +// Definitions by: newraina +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * inspired by @types/redux-actions, thanks. + */ + +import * as Redux from 'redux'; + +export as namespace ReduxAction; + +interface BaseAction { + type: string; +} + +interface Action extends BaseAction { + payload: Payload; +} + +interface MetaAction extends Action { + meta: Meta; +} + +type ThunkAction = (dispatch: Redux.Dispatch, getState: () => any) => Promise>; +type ThunkMetaAction = (dispatch: Redux.Dispatch, getState: () => any) => Promise>; + +/** argument inferring borrowed from redux-actions definitions */ +type ActionFunction0 = () => R; +type ActionFunction1 = (t1: T1) => R; +type ActionFunction2 = (t1: T1, t2: T2) => R; +type ActionFunction3 = (t1: T1, t2: T2, t3: T3) => R; +type ActionFunctionAny = (...args: any[]) => R; + +type ReducerHandler = (payload: any, state?: State, action?: A) => S; + +interface ReducerHandlers { + [type: string]: ReducerHandler; +} + +export function createAction( + type: string, + payloadCreator: ActionFunctionAny | Payload>, +): ActionFunctionAny>; + +export function createAction( + payloadCreator: ActionFunctionAny | Payload>, +): ActionFunctionAny>; + +export function createAction( + payloadCreator: ActionFunction1 | Payload>, +): ActionFunction1>; + +export function createAction( + payloadCreator: ActionFunction2 | Payload>, +): ActionFunction2>; + +export function createAction( + payloadCreator: ActionFunction3 | Payload>, +): ActionFunction3>; + +export function createAction( + type: string, + payloadCreator: ActionFunctionAny | Payload>, + metaCreator: ActionFunctionAny +): ActionFunctionAny>; + +export function createAction( + payloadCreator: ActionFunctionAny | Payload>, + metaCreator: ActionFunctionAny +): ActionFunctionAny>; + +export function createAction( + type?: string, +): ActionFunction1>; + +export function createAction( + type?: string, +): ActionFunction1>; + +export function createSyncAction( + type: string, + payloadCreator?: ActionFunctionAny, +): ActionFunctionAny>; + +export function createSyncAction( + type: string, + payloadCreator: ActionFunctionAny, + metaCreator: ActionFunctionAny +): ActionFunctionAny>; + +export function createReducer(defaultState: State, handlers: ReducerHandlers): Redux.Reducer; diff --git a/redux-action/package.json b/redux-action/package.json new file mode 100644 index 0000000000..973078f95d --- /dev/null +++ b/redux-action/package.json @@ -0,0 +1,6 @@ +{ + "dependencies": { + "redux": "^3.6.0", + "redux-thunk": "^2.2.0" + } +} diff --git a/redux-action/redux-action-tests.ts b/redux-action/redux-action-tests.ts new file mode 100644 index 0000000000..cad92bba34 --- /dev/null +++ b/redux-action/redux-action-tests.ts @@ -0,0 +1,84 @@ + +import * as ReduxAction from 'redux-action'; +import * as ReduxThunk from 'redux-thunk'; +import * as Redux from 'redux'; + +interface Payload { + name: string; + id: number; +} + +const dispatch: Redux.Dispatch = (...args: any[]): any => { }; + +const actionCreator0 = ReduxAction.createAction('get items'); + +dispatch(actionCreator0(1)) + .then(action => { + const type: string = action.type; + const payload: Payload = action.payload; + }); + +const actionCreator1 = ReduxAction.createAction(); + +dispatch(actionCreator1(1)) + .then(action => { + const type: string = action.type; + const payload: Payload = action.payload; + }); + +const actionCreator2 = ReduxAction.createAction('get items', (name: string) => name); + +dispatch(actionCreator2(1)) + .then(action => { + const type: string = action.type; + const payload: string = action.payload; + }); + +const actionCreator3 = ReduxAction.createAction('get items', (name: string) => Promise.resolve(name)); + +dispatch(actionCreator3(1)) + .then(action => { + const type: string = action.type; + const payload: string = action.payload; + }); + +const actionCreator4 = ReduxAction.createAction((name: string) => name); + +dispatch(actionCreator4(1)) + .then(action => { + const type: string = action.type; + const payload: string = action.payload; + }); + +const actionCreator5 = ReduxAction.createAction((name: string) => 1); + +dispatch(actionCreator5('items')) + .then(action => { + const type: string = action.type; + const payload: number = action.payload; + }); + +const actionCreator6 = ReduxAction.createAction((name: string) => 1); + +dispatch(actionCreator6('items', false)) + .then(action => { + const type: string = action.type; + const payload: number = action.payload; + }); + +const syncActionCreator0 = ReduxAction.createSyncAction('get items'); +const syncAction0: ReduxAction.Action = dispatch(syncActionCreator0(1)); + +const syncActionCreator1 = ReduxAction.createSyncAction('get items', (name: string) => name); +const syncAction1: ReduxAction.Action = dispatch(syncActionCreator1(1)); + +interface State { + name: string; +} +const reducer = ReduxAction.createReducer({ name: 'name' }, { + 'get items': () => { + return 'new name'; + } +}); + +const combinedReducer: Redux.Reducer = Redux.combineReducers({ reducer }); diff --git a/redux-action/tsconfig.json b/redux-action/tsconfig.json new file mode 100644 index 0000000000..0acc89b041 --- /dev/null +++ b/redux-action/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "redux-action-tests.ts" + ] +} diff --git a/redux-action/tslint.json b/redux-action/tslint.json new file mode 100644 index 0000000000..377cc837d4 --- /dev/null +++ b/redux-action/tslint.json @@ -0,0 +1 @@ +{ "extends": "../tslint.json" } diff --git a/sinon/index.d.ts b/sinon/index.d.ts index 7c44ab9d7a..e4ba1ad612 100644 --- a/sinon/index.d.ts +++ b/sinon/index.d.ts @@ -102,6 +102,7 @@ declare namespace Sinon { throws(type?: string): SinonStub; throws(obj: any): SinonStub; callsArg(index: number): SinonStub; + callThrough(): SinonStub; callsArgOn(index: number, context: any): SinonStub; callsArgWith(index: number, ...args: any[]): SinonStub; callsArgOnWith(index: number, context: any, ...args: any[]): SinonStub; diff --git a/sparkpost/index.d.ts b/sparkpost/index.d.ts index c88fab5d92..fc6e408949 100644 --- a/sparkpost/index.d.ts +++ b/sparkpost/index.d.ts @@ -1,9 +1,8 @@ -// Type definitions for sparkpost v1.3 +// Type definitions for sparkpost 2.1 // Project: https://github.com/SparkPost/node-sparkpost -// Definitions by: Joshua DeVinney +// Definitions by: Joshua DeVinney , Bond // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -/// /// import * as Request from "request"; @@ -16,25 +15,48 @@ declare class SparkPost { * List all your inbound domains. * @param callback The request callback with Domain results array */ - all(callback: SparkPost.ResultsCallback): void; + list(callback: SparkPost.ResultsCallback): void; + /** + * List all your inbound domains. + * @returns Promise The Domain results array + */ + list(): SparkPost.ResultsPromise; /** * Retrieve an inbound domain by specifying its domain name in the URI path. * @param domain Domain name * @param callback The request callback with Domain results */ - find(domain: string, callback: SparkPost.ResultsCallback): void; + get(domain: string, callback: SparkPost.ResultsCallback): void; + /** + * Retrieve an inbound domain by specifying its domain name in the URI path. + * @param domain Domain name + * @returns Promise The Domain results + */ + get(domain: string): SparkPost.ResultsPromise; /** * Create an inbound domain by providing an inbound domains object as the POST request body. - * @param domain Domain name + * @param createOpts a hash of [inbound domain attributes]{@link https://developers.sparkpost.com/api/inbound-domains#header-inbound-domains-attributes} * @param callback The request callback */ - create(domain: string, callback: SparkPost.Callback): void; + create(createOpts: SparkPost.CreateOpts, callback: SparkPost.Callback): void; + /** + * Create an inbound domain by providing an inbound domains object as the POST request body. + * @param createOpts a hash of [inbound domain attributes]{@link https://developers.sparkpost.com/api/inbound-domains#header-inbound-domains-attributes} + * @returns Promise void + */ + create(createOpts: SparkPost.CreateOpts): Promise; /** * Delete an inbound domain by specifying its domain name in the URI path. * @param domain Domain name * @param callback The request callback */ delete(domain: string, callback: SparkPost.Callback): void; + /** + * Delete an inbound domain by specifying its domain name in the URI path. + * @param domain Domain name + * @returns Promise void + */ + delete(domain: string): Promise; }; /** The Message Events API provides the means to search the raw events generated by SparkPost. */ messageEvents: { @@ -44,29 +66,57 @@ declare class SparkPost { * @param callback The request callback with MessageEvent results array */ search(parameters: SparkPost.MessageEventParameters, callback: SparkPost.ResultsCallback): void; + /** + * Retrieves list of message events according to given params + * @param parameters Query parameters + * @returns Promise The MessageEvent results array + */ + search(parameters: SparkPost.MessageEventParameters): SparkPost.ResultsPromise; }; /** A recipient list is a collection of recipients that can be used in a transmission. */ recipientLists: { /** * List a summary of all recipient lists. The recipients for each list are not included in the results. - * To retrieve recipient details, use the RETRIEVE API for a specified recipient list. + * To retrieve recipient details, use the [Retrieve a Recipient List endpoint]{@link https://developers.sparkpost.com/api/recipient-lists.html#recipient-lists-retrieve-get}, + * and specify the recipient list. + * * @param callback The request callback with RecipientList results array */ - all(callback: SparkPost.ResultsCallback): void; + list(callback: SparkPost.ResultsCallback): void; + /** + * List a summary of all recipient lists. The recipients for each list are not included in the results. + * To retrieve recipient details, use the [Retrieve a Recipient List endpoint]{@link https://developers.sparkpost.com/api/recipient-lists.html#recipient-lists-retrieve-get}, + * and specify the recipient list. + * + * @returns Promise The RecipientList results array + */ + list(): SparkPost.ResultsPromise; /** * Retrieve details about a specified recipient list by specifying its id in the URI path. * To retrieve the recipients contained in a list, the show_recipients parameter must be set to true. - * @param options The find options - * @param callback The request callback with RecipientList results + * + * @param {string} id + * @param {{ show_recipients?: boolean }} specifies whether to retrieve the recipients. Defaults to false + * @param {SparkPost.Callback} callback */ - find(options: { id: string, show_recipients?: false }, callback: SparkPost.Callback): void; + get(id: string, options: { show_recipients?: boolean }, callback: SparkPost.Callback): void; /** * Retrieve details about a specified recipient list by specifying its id in the URI path. * To retrieve the recipients contained in a list, the show_recipients parameter must be set to true. - * @param options The find options - * @param callback The request callback with RecipientList results (with recipients) + * + * @param {string} id + * @param {SparkPost.Callback} callback */ - find(options: { id: string, show_recipients: true }, callback: SparkPost.Callback): void; + get(id: string, callback: SparkPost.Callback): void; + /** + * Retrieve details about a specified recipient list by specifying its id in the URI path. + * To retrieve the recipients contained in a list, the show_recipients parameter must be set to true. + * + * @param {string} id + * @param {{ show_recipients?: boolean }} [options] specifies whether to retrieve the recipients. Defaults to false + * @returns {Promise} + */ + get(id: string, options?: { show_recipients?: boolean }): SparkPost.ResultsPromise; /** * Create a recipient list by providing a recipient list object as the POST request body. * At a minimum, the “recipients” array is required, which must contain a valid “address”. @@ -76,19 +126,47 @@ declare class SparkPost { * @param callback The request callback with metadata results */ create(options: SparkPost.CreateRecipientList, callback: SparkPost.ResultsCallback): void; + /** + * Create a recipient list by providing a recipient list object as the POST request body. + * At a minimum, the “recipients” array is required, which must contain a valid “address”. + * If the recipient list “id” is not provided in the POST request body, one will be generated and returned in the results body. + * Use the num_rcpt_errors parameter to limit the number of recipient errors returned. + * @param options The create options + * @returns Promise metadata results + */ + create(options: SparkPost.CreateRecipientList): SparkPost.ResultsPromise; /** * Update an existing recipient list by specifying its ID in the URI path and use a recipient list object as the PUT request body. * Use the num_rcpt_errors parameter to limit the number of recipient errors returned. + * + * @param {string} id Identifier of the recipient list * @param options The update options * @param callback The request callback with metadata results */ - update(options: SparkPost.UpdateRecipientList, callback: SparkPost.ResultsCallback): void; + update(id: string, options: SparkPost.UpdateRecipientList, callback: SparkPost.ResultsCallback): void; + /** + * Update an existing recipient list by specifying its ID in the URI path and use a recipient list object as the PUT request body. + * Use the num_rcpt_errors parameter to limit the number of recipient errors returned. + * + * @param {string} id Identifier of the recipient list + * @param {SparkPost.UpdateRecipientList} options + * @returns {SparkPost.ResultsPromise} + */ + update(id: string, options: SparkPost.UpdateRecipientList): SparkPost.ResultsPromise; /** * Permanently delete the specified recipient list. + * * @param id The list id * @param callback The request callback */ delete(id: string, callback: SparkPost.Callback): void; + /** + * Permanently delete the specified recipient list. + * + * @param id The list id + * @returns Promise void + */ + delete(id: string): Promise; }; /** Relay Webhooks are a way to instruct SparkPost to accept inbound email on your behalf and forward it to you over HTTP for your own consumption. */ relayWebhooks: { @@ -96,68 +174,142 @@ declare class SparkPost { * List all your relay webhooks. * @param callback The request callback with RelayWebhook results array */ - all(callback: SparkPost.ResultsCallback): void; + list(callback: SparkPost.ResultsCallback): void; + /** + * List all your relay webhooks. + * @returns Promise The RelayWebhook results array + */ + list(): SparkPost.ResultsPromise; /** * Delete a relay webhook by specifying the webhook ID in the URI path. * @param relayWebhookId The webhook id * @param callback The request callback with RelayWebhook results */ - find(relayWebhookId: string, callback: SparkPost.ResultsCallback): void; + get(relayWebhookId: string, callback: SparkPost.ResultsCallback): void; + /** + * Delete a relay webhook by specifying the webhook ID in the URI path. + * @param relayWebhookId The webhook id + * @returns Promise The RelayWebhook results + */ + get(relayWebhookId: string): SparkPost.ResultsPromise; /** * Create a relay webhook by providing a relay webhooks object as the POST request body. * @param options The create options * @param callback The request callback with webhook id results */ create(options: SparkPost.RelayWebhook, callback: SparkPost.ResultsCallback<{ id: string }>): void; + /** + * Create a relay webhook by providing a relay webhooks object as the POST request body. + * @param options The create options + * @returns Promise The webhook id results + */ + create(options: SparkPost.RelayWebhook): SparkPost.ResultsPromise<{ id: string }>; /** * Update a relay webhook by specifying the webhook ID in the URI path. * @param options The update options * @param callback The request callback with webhook id results */ - update(options: SparkPost.UpdateRelayWebhook & { relayWebhookId: string }, callback: SparkPost.ResultsCallback<{ id: string }>): void; + update(id: string, options: SparkPost.UpdateRelayWebhook, callback: SparkPost.ResultsCallback<{ id: string }>): void; + /** + * Update a relay webhook by specifying the webhook ID in the URI path. + * @param options The update options + * @returns Promise The webhook id results + */ + update(id: string, options: SparkPost.UpdateRelayWebhook): SparkPost.ResultsPromise<{ id: string }>; /** * Delete a relay webhook by specifying the webhook ID in the URI path. * @param relayWebhookId The webhook id * @param callback The request callback */ delete(relayWebhookId: string, callback: SparkPost.Callback): void; + /** + * Delete a relay webhook by specifying the webhook ID in the URI path. + * @param relayWebhookId The webhook id + * @returns Promise void + */ + delete(relayWebhookId: string): Promise; }; sendingDomains: { /** * List an overview of all sending domains in the system. * @param callback The request callback with SendingDomain results array */ - all(callback: SparkPost.ResultsCallback): void; + list(callback: SparkPost.ResultsCallback): void; + /** + * List an overview of all sending domains in the system. + * + * @returns The SendingDomain results array + */ + list(): SparkPost.ResultsPromise; /** * Retrieve a sending domain by specifying its domain name in the URI path. The response includes details about its DKIM key configuration. * @param domain The domain * @param callback The request callback with SendingDomain results */ - find(domain: string, callback: SparkPost.ResultsCallback): void; + get(domain: string, callback: SparkPost.ResultsCallback): void; + /** + * Retrieve a sending domain by specifying its domain name in the URI path. The response includes details about its DKIM key configuration. + * + * @param domain The domain + * @returns Promise The SendingDomain results + */ + get(domain: string): SparkPost.ResultsPromise; /** * Create a sending domain by providing a sending domain object as the POST request body. * @param options The create options * @param callback The request callback with basic info results */ create(options: SparkPost.CreateSendingDomain, callback: SparkPost.ResultsCallback<{ message: string, domain: string }>): void; + /** + * Create a sending domain by providing a sending domain object as the POST request body. + * + * @param options The create options + * @returns Promise The basic info results + */ + create(options: SparkPost.CreateSendingDomain): SparkPost.ResultsPromise<{ message: string, domain: string }>; /** * Update the attributes of an existing sending domain by specifying its domain name in the URI path and use a sending domain object as the PUT request body. - * @param options The update options + * @param domain The domain + * @param updateOpts The update options * @param callback The request callback with basic info results */ - update(options: SparkPost.UpdateSendingDomain, callback: SparkPost.ResultsCallback<{ message: string, domain: string }>): void; + update(domain: string, updateOpts: SparkPost.UpdateSendingDomain, callback: SparkPost.ResultsCallback<{ message: string, domain: string }>): void; + /** + * Update the attributes of an existing sending domain by specifying its domain name in the URI path and use a sending domain object as the PUT request body. + * + * @param domain The domain + * @param updateOpts The update options + * @returns Promise The basic info results + */ + update(domain: string, updateOpts: SparkPost.UpdateSendingDomain): SparkPost.ResultsPromise<{ message: string, domain: string }>; /** * Delete an existing sending domain. * @param domain The domain * @param callback The request callback */ delete(domain: string, callback: SparkPost.Callback): void; + /** + * Delete an existing sending domain. + * + * @param domain The domain + * @returns Promise void + */ + delete(domain: string): Promise; /** * Verify a Sending Domain - * @param options The verify options + * @param domain The domain + * @param options a hash of [verify attributes]{@link https://developers.sparkpost.com/api/sending-domains#header-verify-attributes} * @param callback The request callback with verify results */ - verify(options: SparkPost.VerifyOptions, callback: SparkPost.ResultsCallback): void; + verify(domain: string, options: SparkPost.VerifyOptions, callback: SparkPost.ResultsCallback): void; + /** + * Verify a Sending Domain + * + * @param domain The domain + * @param options a hash of [verify attributes]{@link https://developers.sparkpost.com/api/sending-domains#header-verify-attributes} + * @returns Promise The verify results + */ + verify(domain: string, options: SparkPost.VerifyOptions): SparkPost.ResultsPromise; }; subaccounts: { /** @@ -165,164 +317,412 @@ declare class SparkPost { * This endpoint only returns information about the subaccounts themselves, not the data associated with the subaccount. * @param callback The request callback with subaccount information results array */ - all(callback: SparkPost.ResultsCallback): void; + list(callback: SparkPost.ResultsCallback): void; /** - * - * @param subaccountId The webhook id + * Endpoint for retrieving a list of your subaccounts. + * This endpoint only returns information about the subaccounts themselves, not the data associated with the subaccount. + * + * @returns Promise The subaccount information results array + */ + list(): SparkPost.ResultsPromise; + /** + * Get details about a specified subaccount by its id + * + * @param id the id of the subaccount you want to look up * @param callback The request callback with subaccount information results */ - find(subaccountId: string | number, callback: SparkPost.ResultsCallback): void; + get(id: string | number, callback: SparkPost.ResultsCallback): void; + /** + * Get details about a specified subaccount by its id + * + * @param id the id of the subaccount you want to look up + * @returns Promise The subaccount information results + */ + get(id: string | number): SparkPost.ResultsPromise; /** * Provisions a new subaccount and an initial subaccount API key. - * @param options The create options + * @param subaccount The create options * @param callback The request callback with basic subaccount information results */ - create(options: SparkPost.CreateSubaccount, callback: SparkPost.ResultsCallback): void; + create(subaccount: SparkPost.CreateSubaccount, callback: SparkPost.ResultsCallback): void; + /** + * Provisions a new subaccount and an initial subaccount API key. + * + * @param subaccount The create options + * @returns Promise The basic subaccount information results + */ + create(subaccount: SparkPost.CreateSubaccount): SparkPost.ResultsPromise; /** * Update an existing subaccount’s information. - * @param options The create options + * + * @param id the id of the subaccount you want to update + * @param subaccount an object of [updatable subaccount attributes]{@link https://developers.sparkpost.com/api/subaccounts#header-request-body-attributes-1} * @param callback The request callback with webhook id results */ - update(options: SparkPost.UpdateSubaccount, callback: SparkPost.ResultsCallback<{ message: string }>): void; + update(id: string, subaccount: SparkPost.UpdateSubaccount, callback: SparkPost.ResultsCallback<{ message: string }>): void; + /** + * Update an existing subaccount’s information. + * + * @param id the id of the subaccount you want to update + * @param subaccount an object of [updatable subaccount attributes]{@link https://developers.sparkpost.com/api/subaccounts#header-request-body-attributes-1} + * @returns Promise The webhook id results + */ + update(id: string, subaccount: SparkPost.UpdateSubaccount): SparkPost.ResultsPromise<{ message: string }>; }; suppressionList: { /** - * Perform a filtered search for entries in your suppression list. - * @param parameters Object of search parameters - * @param callback The request callback with RelayWebhook results + * List all entries in your suppression list, filtered by an optional set of search parameters. + * + * @param {SparkPost.ResultsCallback} callback The request callback with supression lists. */ - search(parameters: SparkPost.SupressionSearch, callback: SparkPost.ResultsCallback): void; + list(callback: SparkPost.ResultsCallback): void; /** - * Retrieve the suppression status for a specific recipient by specifying the recipient’s email address in the URI path. - * @param email Email address to check - * @param callback The request callback with webhook id results + * List all entries in your suppression list, filtered by an optional set of search parameters. + * + * @param {SparkPost.SupressionSearchParameters} parameters an object of [search parameters]{@link https://developers.sparkpost.com/api/suppression-list#suppression-list-search-get} + * @param {SparkPost.ResultsCallback} callback The request callback with supression lists. */ - checkStatus(email: string, callback: SparkPost.ResultsCallback): void; + list(parameters: SparkPost.SupressionSearchParameters, callback: SparkPost.ResultsCallback): void; + /** + * List all entries in your suppression list, filtered by an optional set of search parameters. + * + * @param {SparkPost.SupressionSearchParameters} [parameters] an object of [search parameters]{@link https://developers.sparkpost.com/api/suppression-list#suppression-list-search-get} + * @returns {Promise} Promise The supression lists + */ + list(parameters?: SparkPost.SupressionSearchParameters): SparkPost.ResultsPromise; + /** + * Retrieve an entry by recipient email. + * + * @param {string} email address to check + * @returns void + */ + get(email: string, callback: SparkPost.ResultsCallback): void; + /** + * Retrieve an entry by recipient email. + * + * @param {string} email address to check + * @returns void + */ + get(email: string): SparkPost.ResultsPromise; /** * Delete a recipient from the list by specifying the recipient’s email address in the URI path. - * @param email Email address to check - * @param callback The request callback + * + * @param {string} email Recipient email address + * @param callback */ - removeStatus(email: string, callback: SparkPost.Callback): void; + delete(email: string, callback: SparkPost.Callback): void; /** - * Bulk insert or update entries in the customer-specific exclusion list. - * @param parameters The suppression entry list + * Delete a recipient from the list by specifying the recipient’s email address in the URI path. + * + * @param {string} email Recipient email address + * @returns {Promise} void + */ + delete(email: string): Promise; + /** + * Insert or update one or many entries. + * + * @param listEntries The suppression entry list * @param callback The request callback */ - upsert(parameters: SparkPost.CreateSupressionListEntry | SparkPost.CreateSupressionListEntry[], callback: SparkPost.ResultsCallback<{ message: string }>): void; + upsert(listEntries: SparkPost.CreateSupressionListEntry | SparkPost.CreateSupressionListEntry[], callback: SparkPost.ResultsCallback<{ message: string }>): void; + /** + * Insert or update one or many entries. + * + * @param {(SparkPost.CreateSupressionListEntry | SparkPost.CreateSupressionListEntry[])} listEntries The suppression entry list + * @returns {Promise<{ message: string }>} + */ + upsert(listEntries: SparkPost.CreateSupressionListEntry | SparkPost.CreateSupressionListEntry[]): SparkPost.ResultsPromise<{ message: string }>; }; templates: { /** * List a summary of all templates. * @param callback The request callback with TemplateMeta results array */ - all(callback: SparkPost.ResultsCallback): void; + list(callback: SparkPost.ResultsCallback): void; + /** + * List a summary of all templates. + * + * @returns {SparkPost.ResultsPromise} The TemplateMeta results array + */ + list(): SparkPost.ResultsPromise; /** * Retrieve details about a specified template by its id - * @param options The id and draft status information + * + * @param id the id of the template you want to look up + * @param options specifies a draft or published template * @param callback The request callback with Template results */ - find(options: { id: string, draft?: boolean }, callback: SparkPost.ResultsCallback): void; + get(id: string, options: { draft?: boolean }, callback: SparkPost.ResultsCallback): void; + /** + * Retrieve details about a specified template by its id + * + * @param {string} id the id of the template you want to look up + * @param {SparkPost.ResultsCallback} callback The request callback with Template results + */ + get(id: string, callback: SparkPost.ResultsCallback): void; + /** + * Retrieve details about a specified template by its id + * + * @param {string} id the id of the template you want to look up + * @param {{ draft?: boolean }} [options] specifies a draft or published template + * @returns {SparkPost.ResultsPromise} The Template results + */ + get(id: string, options?: { draft?: boolean }): SparkPost.ResultsPromise; /** * Create a new template - * @param options The create options + * + * @param template an object of [template attributes]{@link https://developers.sparkpost.com/api/templates#header-template-attributes} * @param callback The request callback with template id results */ - create(options: { template: SparkPost.CreateTemplate }, callback: SparkPost.ResultsCallback<{ id: string }>): void; + create(template: SparkPost.CreateTemplate, callback: SparkPost.ResultsCallback<{ id: string }>): void; + /** + * Create a new template + * + * @param {SparkPost.CreateTemplate} template an object of [template attributes]{@link https://developers.sparkpost.com/api/templates#header-template-attributes} + * @returns {SparkPost.ResultsPromise<{ id: string }>} The template id results + */ + create(template: SparkPost.CreateTemplate): SparkPost.ResultsPromise<{ id: string }>; /** * Update an existing template - * @param options The create options + * + * @param {string} id the id of the template you want to update + * @param template an object of [template attributes]{@link https://developers.sparkpost.com/api/templates#header-template-attributes} + * @param options The create options. If true, directly overwrite the existing published template. If false, create a new draft * @param callback The request callback with template id results */ - update(options: { - id: string, - template: SparkPost.UpdateTemplate, + update(id: string, template: SparkPost.UpdateTemplate, options: { update_published?: boolean; }, callback: SparkPost.ResultsCallback<{ id: string }>): void; + /** + * Update an existing template + * + * @param {string} id the id of the template you want to update + * @param {SparkPost.UpdateTemplate} template an object of [template attributes]{@link https://developers.sparkpost.com/api/templates#header-template-attributes} + * @param {SparkPost.ResultsCallback<{ id: string }>} callback The request callback with template id results + */ + update(id: string, template: SparkPost.UpdateTemplate, + callback: SparkPost.ResultsCallback<{ id: string }>): void; + /** + * Update an existing template + * + * @param {string} id the id of the template you want to update + * @param {SparkPost.UpdateTemplate} template an object of [template attributes]{@link https://developers.sparkpost.com/api/templates#header-template-attributes} + * @param {{ + * update_published?: boolean; + * }} [options] If true, directly overwrite the existing published template. If false, create a new draft + * @returns {SparkPost.ResultsPromise<{ id: string }>} The template id results + */ + update(id: string, template: SparkPost.UpdateTemplate, options?: { + update_published?: boolean; + }): SparkPost.ResultsPromise<{ id: string }>; /** * Delete an existing template * @param id The template id * @param callback The request callback */ delete(id: string, callback: SparkPost.Callback): void; + /** + * Delete an existing template + * + * @param id The template id + * @returns Promise void + */ + delete(id: string): Promise; /** * Preview the most recent version of an existing template by id + * + * @param {string} id the id of the template you want to look up * @param options The preview options * @param callback The request callback with webhook id results */ - preview(options: { id: string, data: any, draft?: boolean }, callback: SparkPost.ResultsCallback): void; + preview(id: string, options: { substitution_data?: any, draft?: boolean }, callback: SparkPost.ResultsCallback): void; + /** + * Preview the most recent version of an existing template by id + * + * @param {string} id the id of the template you want to look up + * @param {SparkPost.ResultsCallback} callback The request callback with webhook id results + */ + preview(id: string, callback: SparkPost.ResultsCallback): void; + /** + * Preview the most recent version of an existing template by id + * + * @param {string} id the id of the template you want to look up + * @param {{ substitution_data: any, draft?: boolean }} [options] + * @returns {SparkPost.ResultsPromise} The webhook id results + */ + preview(id: string, options?: { substitution_data?: any, draft?: boolean }): SparkPost.ResultsPromise; }; transmissions: { /** * List an overview of all transmissions in the account + * * @param callback The request callback with Transmission results array */ - all(callback: SparkPost.ResultsCallback): void; + list(callback: SparkPost.ResultsCallback): void; /** - * List an overview of all transmissions in the account, with added filters - * @param options The search options { campaign_id?, template_id? } - * @param callback The request callback with Transmission results array + * List an overview of all transmissions in the account + * + * @param {{ campaign_id?: string, template_id: string }} options + * @param {SparkPost.ResultsCallback} callback The request callback with Transmission results array */ - all(options: { campaign_id?: string, template_id?: string }, callback: SparkPost.ResultsCallback): void; + list(options: { campaign_id?: string, template_id?: string }, callback: SparkPost.ResultsCallback): void; + /** + * List an overview of all transmissions in the account + * + * @param {{ campaign_id?: string, template_id: string }} [options] + * @returns {SparkPost.ResultsPromise} The Transmission results array + */ + list(options?: { campaign_id?: string, template_id?: string }): SparkPost.ResultsPromise; /** * Retrieve the details about a transmission by its ID - * @param transmissionID The transmission id + * + * @param id The id of the transmission you want to look up * @param callback The request callback with Transmission results */ - find(transmissionID: string, callback: SparkPost.ResultsCallback): void; + get(transmissionID: string, callback: SparkPost.ResultsCallback): void; + /** + * Retrieve the details about a transmission by its ID + * + * @param {string} id The id of the transmission you want to look up + * @returns {SparkPost.ResultsPromise} The Transmission results + */ + get(id: string): SparkPost.ResultsPromise; /** * Sends a message by creating a new transmission - * @param options The create options + * + * @param transmission an object of [transmission attributes]{@link https://developers.sparkpost.com/api/transmissions#header-transmission-attributes} + * @param options The create options. Specify maximum number of recipient errors returned * @param callback The request callback with metadata and id results */ - send(options: { transmissionBody: SparkPost.CreateTransmission, num_rcpt_errors?: number }, callback: SparkPost.ResultsCallback<{ + send(transmission: SparkPost.CreateTransmission, options: { num_rcpt_errors?: number }, callback: SparkPost.ResultsCallback<{ total_rejected_recipients: number; total_accepted_recipients: number; id: string; }>): void; + /** + * + * + * @param {SparkPost.CreateTransmission} transmission an object of [transmission attributes]{@link https://developers.sparkpost.com/api/transmissions#header-transmission-attributes} + * @param {SparkPost.ResultsCallback<{ + * total_rejected_recipients: number; + * total_accepted_recipients: number; + * id: string; + * }>} callback The request callback with metadata and id results + */ + send(transmission: SparkPost.CreateTransmission, callback: SparkPost.ResultsCallback<{ + total_rejected_recipients: number; + total_accepted_recipients: number; + id: string; + }>): void; + /** + * Sends a message by creating a new transmission + * + * @param {SparkPost.CreateTransmission} transmission an object of [transmission attributes]{@link https://developers.sparkpost.com/api/transmissions#header-transmission-attributes} + * @param {{ num_rcpt_errors?: number }} [options] specify maximum number of recipient errors returned + * @returns {SparkPost.ResultsPromise<{ + * total_rejected_recipients: number; + * total_accepted_recipients: number; + * id: string; + * }>} The metadata and id results + */ + send(transmission: SparkPost.CreateTransmission, options?: { num_rcpt_errors?: number }): SparkPost.ResultsPromise<{ + total_rejected_recipients: number; + total_accepted_recipients: number; + id: string; + }>; }; webhooks: { /** * List currently existing webhooks. * @param callback The request callback with RelayWebhook results array */ - all(callback: SparkPost.ResultsCallback>): void; + list(callback: SparkPost.ResultsCallback>): void; /** * List currently existing webhooks. * @param options Object containing optional timezone * @param callback The request callback with RelayWebhook results array */ - all(options: { timezone?: string }, callback: SparkPost.ResultsCallback>): void; + list(options: { timezone?: string }, callback: SparkPost.ResultsCallback>): void; + /** + * List currently existing webhooks.the timezone to use for the last_successful and last_failure properties | Default: UTC + * + * @param {{ timezone?: string }} [options] + * @returns {(SparkPost.ResultsPromise>)} + */ + list(options?: { timezone?: string }): SparkPost.ResultsPromise>; /** * Retrieve details about a specified webhook by its id + * + * @param {string} id The id of the webhook to get * @param options Object containing id and optional timezone * @param callback The request callback with RelayWebhook results */ - describe(options: { id: string, timezone?: string }, callback: SparkPost.ResultsCallback): void; + get(id: string, options: { timezone?: string }, callback: SparkPost.ResultsCallback): void; + /** + * Retrieve details about a specified webhook by its id + * + * @param {string} id The id of the webhook to get + * @param {(SparkPost.ResultsCallback)} callback The request callback with RelayWebhook results + */ + get(id: string, callback: SparkPost.ResultsCallback): void; + /** + * Retrieve details about a specified webhook by its id + * + * @param {string} id The id of the webhook to get + * @param {{ timezone?: string }} [options] the timezone to use for the last_successful and last_failure properties + * @returns {(SparkPost.ResultsPromise)} The RelayWebhook results + */ + get(id: string, options?: { timezone?: string }): SparkPost.ResultsPromise; /** * Create a new webhook - * @param options The create options + * + * @param options a hash of [webhook attributes]{@link https://developers.sparkpost.com/api/webhooks#header-webhooks-object-properties} * @param callback The request callback with webhook id results */ create(options: SparkPost.Webhook, callback: SparkPost.ResultsCallback): void; + /** + * Create a new webhook + * + * @param {SparkPost.Webhook} options a hash of [webhook attributes]{@link https://developers.sparkpost.com/api/webhooks#header-webhooks-object-properties} + * @returns {(SparkPost.ResultsPromise)} The webhook id results + */ + create(options: SparkPost.Webhook): SparkPost.ResultsPromise; /** * Update an existing webhook - * @param options The update options + * @param {string} id the id of the webhook to update + * @param options A hash of [webhook attribues]{@link https://developers.sparkpost.com/api/webhooks#header-webhooks-object-properties} * @param callback The request callback with webhook id results */ - update(options: SparkPost.UpdateWebhook, callback: SparkPost.ResultsCallback): void; + update(id: string, options: SparkPost.UpdateWebhook, callback: SparkPost.ResultsCallback): void; + /** + * Update an existing webhook + * + * @param {string} id + * @param {SparkPost.UpdateWebhook} options + * @returns {(SparkPost.ResultsPromise)} + */ + update(id: string, options: SparkPost.UpdateWebhook): SparkPost.ResultsPromise; /** * Delete an existing webhook * @param id The webhook id * @param callback The request callback */ delete(id: string, callback: SparkPost.Callback): void; + /** + * Delete an existing webhook. + * + * @param {string} id The id of the webhook to delete + * @returns {Promise} + */ + delete(id: string): Promise; /** * Sends an example message event batch from the Webhook API to the target URL - * @param options The webhook id and message + * + * @param {string} id The id of the webhook to validate + * @param options the message (payload) to send to the webhook consumer * @param callback The request callback with validation results */ - validate(options: { id: string, message: any }, callback: SparkPost.ResultsCallback<{ + validate(id: string, options: { message: any }, callback: SparkPost.ResultsCallback<{ msg: string; response: { status: number; @@ -331,21 +731,86 @@ declare class SparkPost { } }>): void; /** - * Sends an example message event batch from the Webhook API to the target URL - * @param options The webhook id and optional limit + * Sends an example message event batch from the Webhook API to the target URL. + * + * @param {string} id The id of the webhook to validate + * @param {{ message: any }} options The message (payload) to send to the webhook consumer + * @returns {SparkPost.ResultsPromise<{ + * msg: string; + * response: { + * status: number; + * headers: any; + * body: string; + * } + * }>} The validation results + */ + validate(id: string, options: { message: any }): SparkPost.ResultsPromise<{ + msg: string; + response: { + status: number; + headers: any; + body: string; + } + }>; + /** + * Gets recent status information about a webhook. + * + * @param {string} id The id of the webhook + * @param options An optional limit that specifies the maximum number of results to return. Defaults to 1000 * @param callback The request callback with status results */ - getBatchStatus(options: { id: string, limit?: number }, callback: SparkPost.ResultsCallback<{ + getBatchStatus(id: string, options: { limit?: number }, callback: SparkPost.ResultsCallback<{ batch_id: string; ts: string; attempts: number; response_code: number; }[]>): void; + /** + * Gets recent status information about a webhook. + * + * @param {string} id The id of the webhook + * @param {SparkPost.ResultsCallback<{ + * batch_id: string; + * ts: string; + * attempts: number; + * response_code: number; + * }[]>} callback The request callback with status results + */ + getBatchStatus(id: string, callback: SparkPost.ResultsCallback<{ + batch_id: string; + ts: string; + attempts: number; + response_code: number; + }[]>): void; + /** + * Gets recent status information about a webhook. + * + * @param {string} id The id of the webhook + * @param {{ limit?: number }} Maximum number of results to return. Defaults to 1000 + * @returns {SparkPost.ResultsPromise<{ + * batch_id: string; + * ts: string; + * attempts: number; + * response_code: number; + * }[]>} The status results + */ + getBatchStatus(id: string, options: { limit?: number }): SparkPost.ResultsPromise<{ + batch_id: string; + ts: string; + attempts: number; + response_code: number; + }[]>; /** * Lists descriptions of the events, event types, and event fields that could be included in a Webhooks post to your target URL. - * @param callback The request callback containing documentation results + * @param callback The request callback containing documentation results */ getDocumentation(callback: SparkPost.ResultsCallback): void; + /** + * Lists descriptions of the events, event types, and event fields that could be included in a Webhooks post to your target URL. + * + * @returns {SparkPost.ResultsPromise} The documentation results + */ + getDocumentation(): SparkPost.ResultsPromise; /** * List an example of the event data that will be posted by a Webhook for the specified events. * @param callback The request callback containing examples @@ -357,6 +822,14 @@ declare class SparkPost { * @param callback The request callback containing examples */ getSamples(options: { events?: string }, callback: SparkPost.Callback): void; + /** + * List an example of the event data that will be posted by a Webhook for the specified events. + * + * @param {{ events?: string }} options [event types]{@link https://support.sparkpost.com/customer/portal/articles/1976204} for which to get a sample payload + * Default: all event types returned + * @returns {Promise>} + */ + getSamples(options?: { events?: string }): Promise>; }; /** @@ -367,10 +840,15 @@ declare class SparkPost { constructor(apiKey?: string, options?: SparkPost.ConstructorOptions); request(options: Request.Options, callback: SparkPost.Callback): void; + request(options: Request.Options): Promise>; get(options: Request.Options, callback: SparkPost.Callback): void; + get(options: Request.Options): Promise>; post(options: Request.Options, callback: SparkPost.Callback): void; + post(options: Request.Options): Promise>; put(options: Request.Options, callback: SparkPost.Callback): void; + put(options: Request.Options): Promise>; delete(options: Request.Options, callback: SparkPost.Callback): void; + delete(options: Request.Options): Promise>; } declare namespace SparkPost { @@ -405,6 +883,7 @@ declare namespace SparkPost { (err: Error | SparkPostError | null, res: Response): void; } export type ResultsCallback = Callback<{ results: T }>; + export type ResultsPromise = Promise<{ results: T }>; export interface Domain { domain: string; @@ -543,10 +1022,8 @@ declare namespace SparkPost { description?: string; /** Recipient list attribute object */ attributes?: any; - /** limit the number of recipient errors returned. */ - num_rcpt_errors?: number; /** Array of recipient objects */ - recipients?: Recipient[]; + recipients: Recipient[]; } export interface BaseRecipient { @@ -564,9 +1041,21 @@ declare namespace SparkPost { address: Address | string; } export interface RecipientWithMultichannelAddresses { - /** Address information for a recipient. At a minimum, address or multichannel_addresses is required. If both address and multichannel_addresses are specified only multichannel_addresses will be used. */ + /** + * Address information for a recipient. At a minimum, address or multichannel_addresses is required. + * If both address and multichannel_addresses are specified only multichannel_addresses will be used. + * + * @type {(Address | string)} + * @memberOf RecipientWithMultichannelAddresses + */ address?: Address | string; - /** Array of Multichannel Address objects for a recipient. At a minimum, address or multichannel_addresses is required. If both address and multichannel_addresses are specified only multichannel_addresses will be used. */ + /** + * Array of Multichannel Address objects for a recipient. At a minimum, address or multichannel_addresses is required. + * If both address and multichannel_addresses are specified only multichannel_addresses will be used. + * + * @type {MultichannelAddress[]} + * @memberOf RecipientWithMultichannelAddresses + */ multichannel_addresses: MultichannelAddress[]; } export type Recipient = (RecipientWithAddress | RecipientWithMultichannelAddresses) & BaseRecipient; @@ -610,7 +1099,7 @@ declare namespace SparkPost { /** User-friendly name no example: Inbound Customer Replies */ name?: string; /** URL of the target to which to POST relay batches */ - target?: string; + target: string; /** Authentication token to present in the X-MessageSystems-Webhook-Token header of POST requests to target */ auth_token?: string; /** Restrict which inbound messages will be relayed to the target */ @@ -661,8 +1150,6 @@ declare namespace SparkPost { } export interface UpdateSendingDomain { - /** Name of the sending domain. */ - domain: string; /** Associated tracking domain. */ tracking_domain?: string; /** JSON object in which DKIM key configuration is defined. */ @@ -704,9 +1191,49 @@ declare namespace SparkPost { } export interface VerifyOptions { - domain: string; - verifyDKIM?: boolean; - verifySPF?: boolean; + /** + * Request verification of DKIM record + * + * @type {boolean} + * @memberOf VerifyOptions + */ + dkim_verify?: boolean; + /** + * Request verification of SPF record + * + * @type {boolean} + * @deprecated + * @memberOf VerifyOptions + */ + spf_verify?: boolean; + /** + * Request an email with a verification link to be sent to the sending domain’s postmaster@ mailbox. + * + * @type {boolean} + * @memberOf VerifyOptions + */ + postmaster_at_verify?: boolean; + /** + * Request an email with a verification link to be sent to the sending domain’s abuse@ mailbox. + * + * @type {boolean} + * @memberOf VerifyOptions + */ + abuse_at_verify?: boolean; + /** + * A token retrieved from the verification link contained in the postmaster@ verification email. + * + * @type {string} + * @memberOf VerifyOptions + */ + postmaster_at_token?: string; + /** + * A token retrieved from the verification link contained in the abuse@ verification email. + * + * @type {string} + * @memberOf VerifyOptions + */ + abuse_at_token?: string; } export interface VerifyResults extends Status { @@ -720,13 +1247,13 @@ declare namespace SparkPost { /** user-friendly name */ name: string; /** user-friendly identifier for subaccount API key */ - keyLabel: string; + key_label: string; /** list of grants to give the subaccount API key */ - keyGrants: string[]; + key_grants: string[]; /** list of IPs the subaccount may be used from */ - keyValidIps?: string[]; + key_valid_ips?: string[]; /** id of the default IP pool assigned to subaccount"s transmissions */ - ipPool?: string; + ip_pool?: string; } export interface CreateSubaccountResponse { @@ -737,14 +1264,12 @@ declare namespace SparkPost { } export interface UpdateSubaccount { - /** the id of the subaccount you want to update */ - subaccountId: string | number; /** user-friendly name */ name: string; /** status of the subaccount */ status: string; /** id of the default IP pool assigned to subaccount"s transmissions */ - ipPool?: string; + ip_pool?: string; } export interface SubaccountInformation { @@ -760,41 +1285,149 @@ declare namespace SparkPost { } export interface CreateSupressionListEntry { + /** + * Email address to be suppressed + * + * @type {string} + * @memberOf CreateSupressionListEntry + */ recipient: string; - /** Whether the recipient requested to not receive any transactional messages. At a minimum, transactional or non_transactional is required upon creation of the entry. */ + /** + * Type of suppression record + * + * @type {("transactional" | "non_transactional")} + * @memberOf CreateSupressionListEntry + */ + type?: "transactional" | "non_transactional"; + /** + * Whether the recipient requested to not receive any non-transactional messages + * Not required if a valid type is passed + * + * @deprecated Available, but deprecated in favor of type + * @type {boolean} + * @memberOf CreateSupressionListEntry + */ transactional?: boolean; - /** Whether the recipient requested to not receive any non-transactional messages. At a minimum, transactional or non_transactional is required upon creation of the entry. */ + /** + * Whether the recipient requested to not receive any non-transactional messages + * Not required if a valid type is passed + * + * @deprecated Available, but deprecated in favor of type + * @type {boolean} + * @memberOf CreateSupressionListEntry + */ non_transactional?: boolean; + /** + * Source responsible for inserting the list entry + * no - entries created by the user are marked as Manually Added + * + * @type {("Spam Complaint" | "List Unsubscribe" | "Bounce Rule" | "Unsubscribe Link" | "Manually Added" | "Compliance")} + * @memberOf CreateSupressionListEntry + */ + readonly source?: "Spam Complaint" | "List Unsubscribe" | "Bounce Rule" | "Unsubscribe Link" | "Manually Added" | "Compliance"; /** Short explanation of the suppression */ description?: string; } export interface SupressionListEntry { + /** + * Email address to be suppressed + * + * @type {string} + * @memberOf SupressionListEntry + */ recipient: string; - /** Whether the recipient requested to not receive any transactional messages. At a minimum, transactional or non_transactional is required upon creation of the entry. */ + /** + * Whether the recipient requested to not receive any transactional messages + * Not required if a valid type is passed + * + * @deprecated Available, but deprecated in favor of type + * @type {boolean} + * @memberOf SupressionListEntry + */ transactional?: boolean; - /** Whether the recipient requested to not receive any non-transactional messages. At a minimum, transactional or non_transactional is required upon creation of the entry. */ + /** + * Whether the recipient requested to not receive any non-transactional messages + * Not required if a valid type is passed + * + * @deprecated Available, but deprecated in favor of type + * @type {boolean} + * @memberOf SupressionListEntry + */ non_transactional?: boolean; - /** Coming soon */ + /** Type of suppression record: transactional or non_transactional */ type?: "transactional" | "non_transactional"; - /** Source responsible for inserting the list entry. Valid values include: Spam Complaint, List Unsubscribe, Bounce Rule, Unsubscribe Link, Manually Added, Compliance. */ - source?: string; + /** + * Source responsible for inserting the list entry + * + * no - entries created by the user are marked as Manually Added + * + * @type {("Spam Complaint" | "List Unsubscribe" | "Bounce Rule" | "Unsubscribe Link" | "Manually Added" | "Compliance")} + * @memberOf SupressionListEntry + */ + source?: "Spam Complaint" | "List Unsubscribe" | "Bounce Rule" | "Unsubscribe Link" | "Manually Added" | "Compliance"; /** Short explanation of the suppression */ description?: string; created: string; updated: string; } - export interface SupressionSearch { + export interface SupressionSearchParameters { /** Datetime the entries were last updated, in the format of YYYY-MM-DDTHH:mm:ssZ */ to?: string; /** Datetime the entries were last updated, in the format YYYY-MM-DDTHH:mm:ssZ */ from?: string; + /** + * Domain of entries to include in the search. ( Note: SparkPost only) + * + * @type {string} + * @memberOf SupressionSearch + */ + domain?: string; + /** + * The results cursor location to return, to start paging with cursor, use the value of ‘initial’. + * When cursor is provided the page parameter is ignored. (Note: SparkPost only) + * + * @type {string} + * @memberOf SupressionSearch + */ + cursor?: string; + /** + * Maximum number of results to return per page. Must be between 1 and 10,000. + * ( Note: SparkPost only) + * @default 1000 + * @type {string} + * @memberOf SupressionSearch + */ + per_page?: string | number; + /** + * The results page number to return. Used with per_page for paging through results. + * The page parameter works up to 10,000 results. + * You must use the cursor parameter and start with cursor=initial to page result sets larger than 10,000 + * ( Note: SparkPost only) + * + * @type {string} + * @memberOf SupressionSearch + */ + page?: string | number; /** Types of entries to include in the search, i.e. entries with “transactional” and/or “non_transactional” keys set to true */ types?: string; /** Sources of the entries to include in the search, i.e. entries that were added by this source */ sources?: string; - /** Maximum number of results to return. Must be between 1 and 100000. Default value is 100000. */ + /** + * Description of the entries to include in the search, i.e descriptions that include the text submitted. + * ( Note: SparkPost only) + * + * @type {string} + * @memberOf SupressionSearch + */ + description?: string; + /** + * Maximum number of results to return per page. Must be between 1 and 10,000. + * @type {number} + * @deprecated use per_page instead + * @memberOf SupressionSearch + */ limit?: number; } @@ -805,7 +1438,13 @@ declare namespace SparkPost { text: string; /** Email subject line. */ subject: string; - /** Address “from” : "deals@company.com" or JSON object composed of the “name” and “email” fields “from” : { “name” : “My Company”, “email” : "deals@company.com" } used to compose the email’s “From” header. */ + /** + * Address "from" : "deals@company.com" or JSON object composed of the "name" and "email" fields. + * "from" : { "name" : "My Company", "email" : "deals@company.com" } used to compose the email’s "From" header. + * + * @type {(Address | string)} + * @memberOf TemplateContent + */ from: Address | string; /** Email address used to compose the email’s “Reply-To” header. */ reply_to?: string; @@ -820,7 +1459,13 @@ declare namespace SparkPost { text?: string; /** Email subject line. */ subject: string; - /** Address “from” : "deals@company.com" or JSON object composed of the “name” and “email” fields “from” : { “name” : “My Company”, “email” : "deals@company.com" } used to compose the email’s “From” header. */ + /** + * Address "from" : "deals@company.com" or JSON object composed of the "name" and "email" fields. + * "from" : { "name" : "My Company", "email" : "deals@company.com" } used to compose the email’s "From" header. + * + * @type {(Address | string)} + * @memberOf TemplateContent + */ from: Address | string; /** Email address used to compose the email’s “Reply-To” header. */ reply_to?: string; @@ -840,7 +1485,15 @@ declare namespace SparkPost { } export interface Template { - /** Short, unique, alphanumeric ID used to reference the template At a minimum, id or name is required upon creation. It is auto generated if not provided. After a template has been created, this property cannot be changed. Maximum length - 64 bytes */ + /** + * Short, unique, alphanumeric ID used to reference the template. + * At a minimum, id or name is required upon creation. + * It is auto generated if not provided. + * After a template has been created, this property cannot be changed. Maximum length - 64 bytes + * + * @type {string} + * @memberOf Template + */ id: string; /** Content that will be used to construct a message yes For a full description, see the Content Attributes. Maximum length - 20 MBs */ content: TemplateContent | { email_rfc822: string }; @@ -859,7 +1512,15 @@ declare namespace SparkPost { } export interface CreateTemplate { - /** Short, unique, alphanumeric ID used to reference the template At a minimum, id or name is required upon creation. It is auto generated if not provided. After a template has been created, this property cannot be changed. Maximum length - 64 bytes */ + /** + * Short, unique, alphanumeric ID used to reference the template. + * At a minimum, id or name is required upon creation. + * It is auto generated if not provided. + * After a template has been created, this property cannot be changed. Maximum length - 64 bytes + * + * @type {string} + * @memberOf CreateTemplate + */ id?: string; /** Content that will be used to construct a message yes For a full description, see the Content Attributes. Maximum length - 20 MBs */ content: CreateTemplateContent | { email_rfc822: string }; @@ -907,6 +1568,20 @@ declare namespace SparkPost { export interface CreateTransmission { /** JSON object in which transmission options are defined */ options?: TransmissionOptions; + /** + * Recipients to receive a carbon copy of the transmission + * + * @type {Recipient[]} + * @memberOf CreateTransmission + */ + cc?: Recipient[]; + /** + * Recipients to discreetly receive a carbon copy of the transmission + * + * @type {Recipient[]} + * @memberOf CreateTransmission + */ + bcc?: Recipient[]; /** Inline recipient objects or object containing stored recipient list ID */ recipients?: Recipient[] | { list_id: string }; /** Name of the campaign */ @@ -1011,11 +1686,25 @@ declare namespace SparkPost { } export interface Attachment { - /** The MIME type of the attachment; e.g., “text/plain”, “image/jpeg”, “audio/mp3”, “video/mp4”, “application/msword”, “application/pdf”, etc., including the “charset” parameter (text/html; charset=“UTF-8”) if needed. The value will apply “as-is” to the “Content-Type” header of the generated MIME part for the attachment. */ + /** + * The MIME type of the attachment; e.g., “text/plain”, “image/jpeg”, “audio/mp3”, “video/mp4”, “application/msword”, “application/pdf”, etc., + * including the “charset” parameter (text/html; charset=“UTF-8”) if needed. + * The value will apply “as-is” to the “Content-Type” header of the generated MIME part for the attachment. + * + * @type {string} + * @memberOf Attachment + */ type: string; /** The filename of the attachment (for example, “document.pdf”). This is inserted into the filename parameter of the Content-Disposition header. */ name: string; - /** The content of the attachment as a Base64 encoded string. The string should not contain \r\n line breaks. The SparkPost systems will add line breaks as necessary to ensure the Base64 encoded lines contain no more than 76 characters each. */ + /** + * The content of the attachment as a Base64 encoded string. + * The string should not contain \r\n line breaks. + * The SparkPost systems will add line breaks as necessary to ensure the Base64 encoded lines contain no more than 76 characters each. + * + * @type {string} + * @memberOf Attachment + */ data: string; } @@ -1026,6 +1715,14 @@ declare namespace SparkPost { target: string; /** Array of event types this webhook will receive */ events: string[]; + /** + * Reserved for future use + * + * @default {true} + * @type {boolean} + * @memberOf Webhook + */ + active?: boolean; /** Type of authentication to be used during POST requests to target */ auth_type?: string; /** Object containing details needed to request authorization credentials, as necessary */ @@ -1037,13 +1734,13 @@ declare namespace SparkPost { } export interface UpdateWebhook { - id: string; /** User-friendly name for webhook */ name?: string; /** URL of the target to which to POST event batches */ target?: string; /** Array of event types this webhook will receive */ events?: string[]; + active?: boolean; /** Type of authentication to be used during POST requests to target */ auth_type?: string; /** Object containing details needed to request authorization credentials, as necessary */ @@ -1061,6 +1758,16 @@ declare namespace SparkPost { method: string[]; }[]; } + + export interface CreateOpts { + /** + * Domain (or subdomain) name for which SparkPost will receive inbound emails + * + * @type {string} + * @memberOf CreateOpts + */ + domain: string; + } } export = SparkPost; diff --git a/sparkpost/sparkpost-tests.ts b/sparkpost/sparkpost-tests.ts index 9f7f47b44d..d3fef264f0 100644 --- a/sparkpost/sparkpost-tests.ts +++ b/sparkpost/sparkpost-tests.ts @@ -3,6 +3,7 @@ import * as SparkPost from "sparkpost"; let key = "YOURAPIKEY"; let client = new SparkPost(key); +// Callback client.get({ uri: "metrics/domains" }, function(err, data) { @@ -14,7 +15,19 @@ client.get({ console.log(data.body); }); -client.inboundDomains.create("example1.com", function(err, res) { +// Promise +client.get({ + uri: 'metrics/domains' +}) + .then(data => { + console.log(data); + }) + .catch(err => { + console.log(err); + }); + +// Callback +client.inboundDomains.create({ domain: 'example1.com' }, function(err, res) { if (err) { console.log(err); } else { @@ -23,6 +36,18 @@ client.inboundDomains.create("example1.com", function(err, res) { } }); +// Promise +client.inboundDomains.create({ domain: 'example1.com' }) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback client.inboundDomains.delete("example1.com", function(err, res) { if (err) { console.log(err); @@ -32,7 +57,19 @@ client.inboundDomains.delete("example1.com", function(err, res) { } }); -client.inboundDomains.find("example1.com", function(err, res) { +// Promise +client.inboundDomains.delete('example1.com') + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback +client.inboundDomains.get("example1.com", function(err, res) { if (err) { console.log(err); } else { @@ -41,7 +78,19 @@ client.inboundDomains.find("example1.com", function(err, res) { } }); -client.inboundDomains.all(function(err, res) { +// Promise +client.inboundDomains.get('example1.com') + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback +client.inboundDomains.list(function(err, res) { if (err) { console.log(err); } else { @@ -50,6 +99,18 @@ client.inboundDomains.all(function(err, res) { } }); +// Promise +client.inboundDomains.list() + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback client.messageEvents.search({}, function(err, res) { if (err) { console.log(err); @@ -59,6 +120,7 @@ client.messageEvents.search({}, function(err, res) { } }); +// Callback client.messageEvents.search({ events: "click", campaign_ids: "monday_mailshot" @@ -71,6 +133,7 @@ client.messageEvents.search({ } }); +// Callback client.messageEvents.search({ from: "2016-01-01T00:00", to: "2016-01-02T23:59", @@ -87,6 +150,50 @@ client.messageEvents.search({ } }); +// Promise +client.messageEvents.search({ + events: 'click', + campaign_ids: 'monday_mailshot' +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Promise +client.messageEvents.search({}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Promise +client.messageEvents.search({ + from: '2016-01-01T00:00', + to: '2016-01-02T23:59', + page: 1, + per_page: 5, + events: ['bounce', 'out_of_band'], + bounce_classes: [10] +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback client.recipientLists.create({ id: "UNIQUE_TEST_ID", name: "Test Recipient List", @@ -114,6 +221,36 @@ client.recipientLists.create({ } }); +// Promise +client.recipientLists.create({ + id: "UNIQUE_TEST_ID", + name: "Test Recipient List", + recipients: [ + { + address: { + email: "test1@test.com" + } + }, { + address: { + email: "test2@test.com" + } + }, { + address: { + email: "test3@test.com" + } + } + ] +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback client.recipientLists.delete("UNIQUE_TEST_ID", function(err, res) { if (err) { console.log(err); @@ -123,7 +260,19 @@ client.recipientLists.delete("UNIQUE_TEST_ID", function(err, res) { } }); -client.recipientLists.all(function(err, res) { +// Promise +client.recipientLists.delete('UNIQUE_TEST_ID') + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback +client.recipientLists.list(function(err, res) { if (err) { console.log(err); } else { @@ -132,9 +281,19 @@ client.recipientLists.all(function(err, res) { } }); -client.recipientLists.find({ - id: "UNIQUE_TEST_ID" -}, function(err, res) { +// Promise +client.recipientLists.list() + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback +client.recipientLists.get('UNIQUE_TEST_ID', function(err, res) { if (err) { console.log(err); } else { @@ -143,8 +302,8 @@ client.recipientLists.find({ } }); -client.recipientLists.find({ - id: "UNIQUE_TEST_ID", +// Callback +client.recipientLists.get('UNIQUE_TEST_ID', { show_recipients: true }, function(err, res) { if (err) { @@ -155,8 +314,32 @@ client.recipientLists.find({ } }); -client.recipientLists.update({ - id: "EXISTING_TEST_ID", +// Promise +client.recipientLists.get('UNIQUE_TEST_ID', { + show_recipients: true +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Promise +client.recipientLists.get('UNIQUE_TEST_ID') + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback +client.recipientLists.update('EXISTING_TEST_ID', { name: "Test Recipient List", recipients: [ { @@ -182,6 +365,34 @@ client.recipientLists.update({ } }); +// Promise +client.recipientLists.update('EXISTING_TEST_ID', { + name: "Test Recipient List", + recipients: [ + { + address: { + email: "test1@test.com" + } + }, { + address: { + email: "test2@test.com" + } + }, { + address: { + email: "test3@test.com" + } + } + ] +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log(err); + }); + +// Callback client.relayWebhooks.create({ name: "Test Relay Webhook", target: "http://client.test.com/test-webhook", @@ -197,6 +408,24 @@ client.relayWebhooks.create({ } }); +// Promise +client.relayWebhooks.create({ + name: 'Test Relay Webhook', + target: 'http://client.test.com/test-webhook', + match: { + domain: 'inbound.example.com' + } +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback client.relayWebhooks.delete("123456789", function(err, res) { if (err) { console.log(err); @@ -206,7 +435,19 @@ client.relayWebhooks.delete("123456789", function(err, res) { } }); -client.relayWebhooks.find("123456789", function(err, res) { +// Promise +client.relayWebhooks.delete('123456789') + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback +client.relayWebhooks.get('123456789', function(err, res) { if (err) { console.log(err); } else { @@ -215,7 +456,18 @@ client.relayWebhooks.find("123456789", function(err, res) { } }); -client.relayWebhooks.all(function(err, res) { +// Promise +client.relayWebhooks.get('123456789') + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +client.relayWebhooks.list(function(err, res) { if (err) { console.log(err); } else { @@ -224,8 +476,19 @@ client.relayWebhooks.all(function(err, res) { } }); -client.relayWebhooks.update({ - relayWebhookId: "123456789", +// Promise +client.relayWebhooks.list() + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback +client.relayWebhooks.update('123456789', { target: "http://client.test.com/test-webhook" }, function(err, res) { if (err) { @@ -236,11 +499,25 @@ client.relayWebhooks.update({ } }); +// Promise +client.relayWebhooks.update('123456789', { + target: 'http://client.test.com/test-webhook' +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback client.sendingDomains.create({ domain: "example1.com", dkim: { - "private": "MIICXgIBAAKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/xFar2wjmzxp2+SnJ5pspaF77VZveN3P/HVmXZVghr3asoV9WBx/uW1nDIUxU35L4juXiTwsMAbgMyh3NqIKTNKyMDy4P8vpEhtH1iv/BrwMdBjHDVCycB8WnwIDAQABAoGBAITb3BCRPBi5lGhHdn+1RgC7cjUQEbSb4eFHm+ULRwQ0UIPWHwiVWtptZ09usHq989fKp1g/PfcNzm8c78uTS6gCxfECweFCRK6EdO6cCCr1cfWvmBdSjzYhODUdQeyWZi2ozqd0FhGWoV4VHseh4iLj36DzleTLtOZj3FhAo1WJAkEA68T+KkGeDyWwvttYtuSiQCCTrXYAWTQnkIUxduCp7Ap6tVeIDn3TaXTj74UbEgaNgLhjG4bX//fdeDW6PaK9YwJBAM6xJmwHLPMgwNVjiz3u/6fhY3kaZTWcxtMkXCjh1QE82KzDwqyrCg7EFjTtFysSHCAZxXZMcivGl4TZLHnydJUCQQCx16+M+mAatuiCnvxlQUMuMiSTNK6Amzm45u9v53nlZeY3weYMYFdHdfe1pebMiwrT7MI9clKebz6svYJVmdtXAkApDAc8VuR3WB7TgdRKNWdyGJGfoD1PO1ZE4iinOcoKV+IT1UCY99Kkgg6C7j62n/8T5OpRBvd5eBPpHxP1F9BNAkEA5Nf2VO9lcTetksHdIeKK+F7sio6UZn0Rv7iUo3ALrN1D1cGfWIh2dj3ko1iSreyNVSwGW0ePP27qDmU+u6/Y1g==", - "public": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/xFar2wjmzxp2+SnJ5pspaF77VZveN3P/HVmXZVghr3asoV9WBx/uW1nDIUxU35L4juXiTwsMAbgMyh3NqIKTNKyMDy4P8vpEhtH1iv/BrwMdBjHDVCycB8WnwIDAQAB", + "private": "MIICXgIBAAKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/==", + "public": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+W6scd3XWwvC/==", selector: "brisbane", headers: "from:to:subject:date" } @@ -253,7 +530,26 @@ client.sendingDomains.create({ } }); +// Promise +client.sendingDomains.create({ + domain: 'example1.com', + dkim: { + 'private': 'MIICXgIBAAKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/==', + 'public': 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+W6scd3XWwvC/==', + selector: 'brisbane', + headers: 'from:to:subject:date' + } +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); +// Callback client.sendingDomains.delete("example1.com", function(err, data) { if (err) { console.log(err); @@ -263,7 +559,19 @@ client.sendingDomains.delete("example1.com", function(err, data) { } }); -client.sendingDomains.all(function(err, res) { +// Promise +client.sendingDomains.delete('example1.com') + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback +client.sendingDomains.list(function(err, res) { if (err) { console.log(err); } else { @@ -272,7 +580,19 @@ client.sendingDomains.all(function(err, res) { } }); -client.sendingDomains.find("example1.com", function(err, res) { +// Promise +client.sendingDomains.list() + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback +client.sendingDomains.get('example1.com', function(err, res) { if (err) { console.log(err); } else { @@ -281,11 +601,22 @@ client.sendingDomains.find("example1.com", function(err, res) { } }); -client.sendingDomains.update({ - domain: "example1.com", +// Promise +client.sendingDomains.get('example1.com') + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback +client.sendingDomains.update('example1.com', { dkim: { - "private": "MIICXgIBAAKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/xFar2wjmzxp2+SnJ5pspaF77VZveN3P/HVmXZVghr3asoV9WBx/uW1nDIUxU35L4juXiTwsMAbgMyh3NqIKTNKyMDy4P8vpEhtH1iv/BrwMdBjHDVCycB8WnwIDAQABAoGBAITb3BCRPBi5lGhHdn+1RgC7cjUQEbSb4eFHm+ULRwQ0UIPWHwiVWtptZ09usHq989fKp1g/PfcNzm8c78uTS6gCxfECweFCRK6EdO6cCCr1cfWvmBdSjzYhODUdQeyWZi2ozqd0FhGWoV4VHseh4iLj36DzleTLtOZj3FhAo1WJAkEA68T+KkGeDyWwvttYtuSiQCCTrXYAWTQnkIUxduCp7Ap6tVeIDn3TaXTj74UbEgaNgLhjG4bX//fdeDW6PaK9YwJBAM6xJmwHLPMgwNVjiz3u/6fhY3kaZTWcxtMkXCjh1QE82KzDwqyrCg7EFjTtFysSHCAZxXZMcivGl4TZLHnydJUCQQCx16+M+mAatuiCnvxlQUMuMiSTNK6Amzm45u9v53nlZeY3weYMYFdHdfe1pebMiwrT7MI9clKebz6svYJVmdtXAkApDAc8VuR3WB7TgdRKNWdyGJGfoD1PO1ZE4iinOcoKV+IT1UCY99Kkgg6C7j62n/8T5OpRBvd5eBPpHxP1F9BNAkEA5Nf2VO9lcTetksHdIeKK+F7sio6UZn0Rv7iUo3ALrN1D1cGfWIh2dj3ko1iSreyNVSwGW0ePP27qDmU+u6/Y1g==", - "public": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/xFar2wjmzxp2+SnJ5pspaF77VZveN3P/HVmXZVghr3asoV9WBx/uW1nDIUxU35L4juXiTwsMAbgMyh3NqIKTNKyMDy4P8vpEhtH1iv/BrwMdBjHDVCycB8WnwIDAQAB", + "private": "MIICXgIBAAKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/Y1g==", + "public": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+W6scd3XWwvC/==", selector: "hello_selector", headers: "from:to:subject:date" } @@ -298,8 +629,29 @@ client.sendingDomains.update({ } }); -client.sendingDomains.verify({ - domain: "example1.com" +client.sendingDomains.update('example1.com', { + dkim: { + 'private': 'MIICXgIBAAKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx/Y1g==', + 'public': 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+W6scd3XWwvC/==', + selector: 'hello_selector', + headers: 'from:to:subject:date' + } +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback +client.sendingDomains.verify('example1.com', { + dkim_verify: true, + spf_verify: true, + abuse_at_verify: true, + postmaster_at_verify: true }, function(err, res) { if (err) { console.log(err); @@ -309,9 +661,9 @@ client.sendingDomains.verify({ } }); -client.sendingDomains.verify({ - domain: "example1.com", - verifySPF: false +// Callback +client.sendingDomains.verify('example1.com', { + dkim_verify: false }, function(err, res) { if (err) { console.log(err); @@ -321,22 +673,27 @@ client.sendingDomains.verify({ } }); -client.sendingDomains.verify({ - domain: "example1.com", - verifyDKIM: false -}, function(err, res) { - if (err) { +// Promise +client.sendingDomains.verify('example1.com', { + dkim_verify: true, + spf_verify: true, + abuse_at_verify: true, + postmaster_at_verify: true +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); console.log(err); - } else { - console.log(res.body); - console.log("Congrats you can use our SDK!"); - } }); +// Callback client.subaccounts.create({ name: "Test Subaccount", - keyLabel: "Test Subaccount key", - keyGrants: [ + key_label: 'Test Subaccount key', + key_grants: [ "smtp/inject", "transmissions/modify" ] @@ -349,7 +706,26 @@ client.subaccounts.create({ } }); -client.subaccounts.all(function(err, res) { +// Promise +client.subaccounts.create({ + name: 'Test Subaccount', + key_label: 'Test Subaccount key', + key_grants: [ + 'smtp/inject', + 'transmissions/modify' + ] +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback +client.subaccounts.list(function(err, res) { if (err) { console.log(err); } else { @@ -358,7 +734,19 @@ client.subaccounts.all(function(err, res) { } }); -client.subaccounts.find(123, function(err, res) { +// Promise +client.subaccounts.list() + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback +client.subaccounts.get(123, function(err, res) { if (err) { console.log(err); } else { @@ -367,8 +755,19 @@ client.subaccounts.find(123, function(err, res) { } }); -client.subaccounts.update({ - subaccountId: 123, +// Promise +client.subaccounts.get('123') + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback +client.subaccounts.update('123', { name: "Test Subaccount", status: "suspended" }, function(err, res) { @@ -380,67 +779,199 @@ client.subaccounts.update({ } }); -client.suppressionList.checkStatus("test@test.com", function(err, res) { +// Promise +client.subaccounts.update('123', { + name: 'Test Subaccount', + status: 'suspended' +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback +client.suppressionList.delete('test@test.com', function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(res.body); - console.log("Congrats you can use our client library!"); + console.log('Congrats you can use our client library!'); + console.log(data); } }); -client.suppressionList.removeStatus("test@test.com", function(err, res) { +// Promise +client.suppressionList.delete('test@test.com') + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Promise +client.suppressionList.get('test@test.com') + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback +client.suppressionList.get('test@test.com', function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(res.body); - console.log("Congrats you can use our client library!"); + console.log('Congrats you can use our client library!'); + console.log(data); } }); -client.suppressionList.search({ - from: "2015-05-07T00:00:00+0000", - to: "2015-05-07T23:59:59+0000", - limit: 5 -}, function(err, res) { +// Promise +client.suppressionList.list({ + from: '2015-05-07T00:00:00+0000', + to: '2015-05-07T23:59:59+0000', + limit: 5 +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); + +// Callback +client.suppressionList.list({ + from: '2015-05-07T00:00:00+0000', + to: '2015-05-07T23:59:59+0000', + limit: 5 +}, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(res.body); - console.log("Congrats you can use our client library!"); + console.log('Congrats you can use our client library!'); + console.log(data); } }); -client.suppressionList.upsert([ - { - recipient: "test1@test.com", +// Callback +client.suppressionList.list(function(err, data) { + if (err) { + console.log('Whoops! Something went wrong'); + console.log(err); + } else { + console.log('Congrats you can use our client library!'); + console.log(data); + } +}); + +// Promise +client.suppressionList.upsert({ + recipient: 'test1@test.com', transactional: false, non_transactional: true, - description: "Test description 1" - }, - { - recipient: "test2@test.com", - transactional: true, + description: 'Test description 1' +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); + +// Callback +client.suppressionList.upsert({ + recipient: 'test1@test.com', + transactional: false, non_transactional: true, - description: "Test description 2" - }, - { - recipient: "test3@test.com", - transactional: true, - non_transactional: false, - description: "Test description 3" - } -], function(err, res) { + description: 'Test description 1' +}, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(res.body); - console.log("Congrats you can use our client library!"); + console.log('Congrats you can use our client library!'); + console.log(data); } }); +// Promise +client.suppressionList.upsert([ + { + recipient: 'test1@test.com', + transactional: false, + non_transactional: true, + description: 'Test description 1' + }, + { + recipient: 'test2@test.com', + transactional: true, + non_transactional: true, + description: 'Test description 2' + }, + { + recipient: 'test3@test.com', + transactional: true, + non_transactional: false, + description: 'Test description 3' + } +]) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); + +// Callback +client.suppressionList.upsert([ + { + recipient: 'test1@test.com', + transactional: false, + non_transactional: true, + description: 'Test description 1' + }, + { + recipient: 'test2@test.com', + transactional: true, + non_transactional: true, + description: 'Test description 2' + }, + { + recipient: 'test3@test.com', + transactional: true, + non_transactional: false, + description: 'Test description 3' + } +], function(err, data) { + if (err) { + console.log('Whoops! Something went wrong'); + console.log(err); + } else { + console.log('Congrats you can use our client library!'); + console.log(data); + } +}); + +// Callback client.templates.create({ - template: { id: "TEST_ID", name: "Test Template", content: { @@ -448,7 +979,6 @@ client.templates.create({ subject: "Test email template!", html: "This is a test email template!" } - } }, function(err, res) { if (err) { console.log(err); @@ -458,6 +988,26 @@ client.templates.create({ } }); +// Promise +client.templates.create({ + id: 'TEST_ID', + name: 'Test Template', + content: { + from: 'test@test.com', + subject: 'Test email template!', + html: 'This is a test email template!' + } +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback client.templates.delete("TEST_ID", function(err, res) { if (err) { console.log(err); @@ -467,8 +1017,19 @@ client.templates.delete("TEST_ID", function(err, res) { } }); +// Promise +client.templates.delete('TEST_ID') + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); -client.templates.all(function(err, res) { +// Callback +client.templates.list(function(err, res) { if (err) { console.log(err); } else { @@ -477,8 +1038,19 @@ client.templates.all(function(err, res) { } }); -client.templates.find({ - id: "TEST_ID", +// Promise +client.templates.list() + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback +client.templates.get('TEST_ID', { draft: true }, function(err, res) { if (err) { @@ -489,8 +1061,30 @@ client.templates.find({ } }); -client.templates.find({ - id: "TEST_ID" +// Callback +client.templates.get('TEST_ID', function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +// Promise +client.templates.get('TEST_ID') + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback +client.templates.preview('TEST_ID', { + substitution_data: {} }, function(err, res) { if (err) { console.log(err); @@ -500,29 +1094,33 @@ client.templates.find({ } }); -client.templates.preview({ - id: "TEST_ID", - data: {} -}, function(err, res) { - if (err) { +// Promise +client.templates.preview('TEST_ID', { + substitution_data: { + name: 'Natalie', + age: 35, + member: true + }, + draft: true +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); console.log(err); - } else { - console.log(res.body); - console.log("Congrats you can use our SDK!"); - } }); -client.templates.update({ - id: "TEST_ID", - template: { +// Callback +client.templates.update('TEST_ID', { content: { from: "test@test.com", subject: "Updated Published Test email template!", html: "This is a published test email template! Updated!" - } - }, - update_published: true -}, function(err, res) { + }, +}, { update_published: true }, +function(err, res) { if (err) { console.log(err); } else { @@ -531,15 +1129,13 @@ client.templates.update({ } }); -client.templates.update({ - id: "TEST_ID", - template: { +// Callback +client.templates.update('TEST_ID', { content: { from: "test@test.com", subject: "Updated Test email template!", html: "This is a test email template! Updated!" } - } }, function(err, res) { if (err) { console.log(err); @@ -549,7 +1145,25 @@ client.templates.update({ } }); -client.transmissions.all(function(err, res) { +// Promise +client.templates.update('TEST_ID', { + content: { + from: 'test@test.com', + subject: 'Updated Test email template!', + html: 'This is a test email template! Updated!' + } +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); + +// Callback +client.transmissions.list(function(err, res) { if (err) { console.log(err); } else { @@ -558,16 +1172,17 @@ client.transmissions.all(function(err, res) { } }); -client.transmissions.find("YOUR-TRANSMISSION-KEY", function(err, res) { - if (err) { +// Promise +client.transmissions.list() + .then(data => { + console.log(data); + console.log('Congrats you can use our client library!'); + }) + .catch(err => { console.log(err); - } else { - console.log(res.body); - console.log("Congrats you can use our SDK!"); - } -}); + }); -client.transmissions.all({ +client.transmissions.list({ campaign_id: "my_campaign" }, function(err, res) { if (err) { @@ -578,7 +1193,7 @@ client.transmissions.all({ } }); -client.transmissions.all({ +client.transmissions.list({ template_id: "my_template" }, function(err, res) { if (err) { @@ -589,8 +1204,29 @@ client.transmissions.all({ } }); +// Callback +client.transmissions.get("YOUR-TRANSMISSION-KEY", function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +// Promise +client.transmissions.get('YOUR-TRANSMISSION-KEY') + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); + +// Callback client.transmissions.send({ - transmissionBody: { recipients: [{ address: { email: "john.doe@example.com" } }], content: { from: "From Envelope ", @@ -602,7 +1238,6 @@ client.transmissions.send({ open_tracking: true, click_tracking: true } - } }, function(err, res) { if (err) { console.log(err); @@ -612,13 +1247,12 @@ client.transmissions.send({ } }); +// Callback client.transmissions.send({ - transmissionBody: { recipients: [{address: {email: "john.doe@example.com"}}], content: { email_rfc822: "Content-Type: text/plain\nFrom: From Envelope \nSubject: Example Email\n\nHello World" } - } }, function(err, res) { if (err) { console.log(err); @@ -628,8 +1262,8 @@ client.transmissions.send({ } }); +// Callback client.transmissions.send({ - transmissionBody: { options: { open_tracking: true, click_tracking: true @@ -674,9 +1308,8 @@ client.transmissions.send({ "X-Customer-Campaign-ID": "christmas_campaign" }, text: "Hi {{address.name}} \nSave big this Christmas in your area {{place}}! \nClick http://www.mysite.com and get huge discount\n Hurry, this offer is only to {{customer_type}}\n {{sender}}", - html: "

Hi {{address.name}} \nSave big this Christmas in your area {{place}}! \nClick http://www.mysite.com and get huge discount\n

Hurry, this offer is only to {{customer_type}}\n

{{sender}}

" - } - } + html: "

Hi {{address.name}} \nSave big this Christmas in your area {{place}}! \nClick http://www.mysite.com and get huge discount\n

" + } }, function(err, res) { if (err) { console.log(err); @@ -686,8 +1319,8 @@ client.transmissions.send({ } }); +// Callback client.transmissions.send({ - transmissionBody: { recipients: [ { address: { @@ -717,7 +1350,6 @@ client.transmissions.send({ text: "An example email using bcc with SparkPost to the {{recipient_type}} recipient.", html: "

An example email using bcc with SparkPost to the {{recipient_type}} recipient.

" } - } }, function(err, res) { if (err) { console.log(err); @@ -727,8 +1359,8 @@ client.transmissions.send({ } }); +// Callback client.transmissions.send({ - transmissionBody: { recipients: [ { address: { @@ -762,7 +1394,6 @@ client.transmissions.send({ text: "An example email using cc with SparkPost to the {{recipient_type}} recipient.", html: "

An example email using cc with SparkPost to the {{recipient_type}} recipient.

" } - } }, function(err, res) { if (err) { console.log(err); @@ -772,8 +1403,8 @@ client.transmissions.send({ } }); +// Callback client.transmissions.send({ - transmissionBody: { recipients: { list_id: "example-list" }, @@ -783,7 +1414,6 @@ client.transmissions.send({ html: "

Hello World

", text: "Hello World!" } - } }, function(err, res) { if (err) { console.log(err); @@ -793,8 +1423,8 @@ client.transmissions.send({ } }); +// Callback client.transmissions.send({ - transmissionBody: { recipients: { list_id: "example-list" }, @@ -803,7 +1433,6 @@ client.transmissions.send({ subject: "Example Email for Stored List and Template", template_id: "my-template" } - } }, function(err, res) { if (err) { console.log(err); @@ -813,15 +1442,15 @@ client.transmissions.send({ } }); +// Callback client.transmissions.send({ - num_rcpt_errors: 3, - transmissionBody: { campaign_id: "ricks-campaign", content: { template_id: "ricks-template" }, recipients: [{ address: { email: "rick.sanchez@rickandmorty100years.com", name: "Rick Sanchez" } }] - } +}, { + num_rcpt_errors: 3 }, function(err, res) { if (err) { console.log(err); @@ -831,6 +1460,111 @@ client.transmissions.send({ } }); + +// Promise +client.transmissions.send({ + options: { + open_tracking: true, + click_tracking: true + }, + campaign_id: 'christmas_campaign', + metadata: { + user_type: 'students' + }, + substitution_data: { + sender: 'Big Store Team' + }, + cc: [], + bcc: [], + recipients: [ + { + address: { + email: 'wilma@flintstone.com', + name: 'Wilma Flintstone' + }, + tags: [ + 'greeting', + 'prehistoric', + 'fred', + 'flintstone' + ], + metadata: { + place: 'Bedrock' + }, + substitution_data: { + customer_type: 'Platinum' + } + } + ], + content: { + from: { + name: 'Fred Flintstone', + email: 'fred@flintstone.com' + }, + subject: 'Big Christmas savings!', + reply_to: 'Christmas Sales ', + headers: { + 'X-Customer-Campaign-ID': 'christmas_campaign' + }, + text: 'Hi {{address.name}} \nSave big this Christmas in your area {{place}}! \nClick http://www.mysite.com and get huge discount\n Hurry, this offer is only to {{customer_type}}\n {{sender}}', + html: '

Hi {{address.name}} \nSave big this Christmas in your area {{place}}! \nClick http://www.mysite.com and get huge discount\n

' + } +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Promise +client.transmissions.send({ + recipients: [ + { + address: { + email: 'original.recipient@example.com', + name: 'Original Recipient' + }, + substitution_data: { + recipient_type: 'Original' + } + }, + { + address: { + email: 'cc.recipient@example.com', + name: 'Carbon Copy Recipient', + header_to: '"Original Recipient" ' + }, + substitution_data: { + recipient_type: 'CC' + } + } + ], + content: { + from: { + name: 'Node CC Test', + email: 'from@example.com' + }, + headers: { + 'CC': '"Carbon Copy Recipient" ' + }, + subject: 'Example email using cc', + text: 'An example email using cc with SparkPost to the {{recipient_type}} recipient.', + html: '

An example email using cc with SparkPost to the {{recipient_type}} recipient.

' + } +}) + .then(data => { + console.log('Congrats! You sent an email with cc using SparkPost!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback client.webhooks.create({ name: "Test webhook", target: "http://client.test.com/test-webhook", @@ -850,6 +1584,28 @@ client.webhooks.create({ } }); +// Promise +client.webhooks.create({ + name: 'Test Webhook', + target: 'http://client.test.com/test-webhook', + auth_token: 'AUTH_TOKEN', + events: [ + 'delivery', + 'injection', + 'open', + 'click' + ] +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback client.webhooks.delete("TEST_WEBHOOK_UUID", function(err, res) { if (err) { console.log(err); @@ -859,20 +1615,45 @@ client.webhooks.delete("TEST_WEBHOOK_UUID", function(err, res) { } }); -client.webhooks.describe({ - id: "TEST_WEBHOOK_UUID", - timezone: "America/New_York" -}, function(err, res) { +// Promise +client.webhooks.delete('TEST_WEBHOOK_UUID') + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); + +// Callback +client.webhooks.get('TEST_WEBHOOK_UUID', { + timezone: 'America/New_York' +}, function(err, data) { if (err) { + console.log('Whoops! Something went wrong'); console.log(err); } else { - console.log(res.body); - console.log("Congrats you can use our SDK!"); + console.log('Congrats you can use our client library!'); + console.log(data); } }); -client.webhooks.getBatchStatus({ - id: "TEST_WEBHOOK_UUID", +// Promise +client.webhooks.get('TEST_WEBHOOK_UUID', { + timezone: 'America/New_York' +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); + +// Callback +client.webhooks.getBatchStatus('TEST_WEBHOOK_UUID', { limit: 1000 }, function(err, res) { if (err) { @@ -883,7 +1664,20 @@ client.webhooks.getBatchStatus({ } }); +// Promise +client.webhooks.getBatchStatus('TEST_WEBHOOK_UUID', { + limit: 1000 +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); +// Callback client.webhooks.getDocumentation(function(err, res) { if (err) { console.log(err); @@ -893,6 +1687,18 @@ client.webhooks.getDocumentation(function(err, res) { } }); +// Promise +client.webhooks.getDocumentation() + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback client.webhooks.getSamples({ events: "bounce" }, function(err, res) { @@ -904,7 +1710,21 @@ client.webhooks.getSamples({ } }); -client.webhooks.all(function(err, res) { +// Promise +client.webhooks.getSamples({ + events: 'bounce' +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback +client.webhooks.list(function(err, res) { if (err) { console.log(err); } else { @@ -913,8 +1733,19 @@ client.webhooks.all(function(err, res) { } }); -client.webhooks.update({ - id: "TEST_WEBHOOK_UUID", +// Promise +client.webhooks.list() + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback +client.webhooks.update('TEST_WEBHOOK_UUID', { name: "Renamed Test webhook", events: [ "policy_rejection", @@ -929,8 +1760,25 @@ client.webhooks.update({ } }); -client.webhooks.validate({ - id: "TEST_WEBHOOK_UUID", +// Promise +client.webhooks.update('TEST_WEBHOOK_UUID', { + name: 'Renamed Test Webhook', + events: [ + 'policy_rejection', + 'delay' + ] +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); +}); + +// Callback +client.webhooks.validate('TEST_WEBHOOK_UUID', { message: { msys: {} } @@ -942,3 +1790,18 @@ client.webhooks.validate({ console.log("Congrats you can use our SDK!"); } }); + +// Promise +client.webhooks.validate('TEST_WEBHOOK_UUID', { + message: { + msys: {} + } +}) + .then(data => { + console.log('Congrats you can use our client library!'); + console.log(data); + }) + .catch(err => { + console.log('Whoops! Something went wrong'); + console.log(err); + }); diff --git a/sparkpost/tsconfig.json b/sparkpost/tsconfig.json index 0ef33f26af..e40a56608b 100644 --- a/sparkpost/tsconfig.json +++ b/sparkpost/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -19,4 +19,4 @@ "index.d.ts", "sparkpost-tests.ts" ] -} \ No newline at end of file +} diff --git a/sparkpost/tslint.json b/sparkpost/tslint.json new file mode 100644 index 0000000000..e77aa7b0ee --- /dev/null +++ b/sparkpost/tslint.json @@ -0,0 +1,8 @@ +{ + "extends": "../tslint.json", + "rules": { + "only-arrow-functions-2": [ + false + ] + } +} diff --git a/sparkpost/v1/index.d.ts b/sparkpost/v1/index.d.ts new file mode 100644 index 0000000000..b12f3712ab --- /dev/null +++ b/sparkpost/v1/index.d.ts @@ -0,0 +1,1119 @@ +// Type definitions for sparkpost v1.3 +// Project: https://github.com/SparkPost/node-sparkpost +// Definitions by: Joshua DeVinney +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as Request from "request"; +import * as Http from "http"; + +declare class SparkPost { + /** Specifying an inbound domain enables you to customize the address to which inbound messages are sent. */ + inboundDomains: { + /** + * List all your inbound domains. + * @param callback The request callback with Domain results array + */ + all(callback: SparkPost.ResultsCallback): void; + /** + * Retrieve an inbound domain by specifying its domain name in the URI path. + * @param domain Domain name + * @param callback The request callback with Domain results + */ + find(domain: string, callback: SparkPost.ResultsCallback): void; + /** + * Create an inbound domain by providing an inbound domains object as the POST request body. + * @param domain Domain name + * @param callback The request callback + */ + create(domain: string, callback: SparkPost.Callback): void; + /** + * Delete an inbound domain by specifying its domain name in the URI path. + * @param domain Domain name + * @param callback The request callback + */ + delete(domain: string, callback: SparkPost.Callback): void; + }; + /** The Message Events API provides the means to search the raw events generated by SparkPost. */ + messageEvents: { + /** + * Retrieves list of message events according to given params + * @param parameters Query parameters + * @param callback The request callback with MessageEvent results array + */ + search(parameters: SparkPost.MessageEventParameters, callback: SparkPost.ResultsCallback): void; + }; + /** A recipient list is a collection of recipients that can be used in a transmission. */ + recipientLists: { + /** + * List a summary of all recipient lists. The recipients for each list are not included in the results. + * To retrieve recipient details, use the RETRIEVE API for a specified recipient list. + * @param callback The request callback with RecipientList results array + */ + all(callback: SparkPost.ResultsCallback): void; + /** + * Retrieve details about a specified recipient list by specifying its id in the URI path. + * To retrieve the recipients contained in a list, the show_recipients parameter must be set to true. + * @param options The find options + * @param callback The request callback with RecipientList results + */ + find(options: { id: string, show_recipients?: false }, callback: SparkPost.Callback): void; + /** + * Retrieve details about a specified recipient list by specifying its id in the URI path. + * To retrieve the recipients contained in a list, the show_recipients parameter must be set to true. + * @param options The find options + * @param callback The request callback with RecipientList results (with recipients) + */ + find(options: { id: string, show_recipients: true }, callback: SparkPost.Callback): void; + /** + * Create a recipient list by providing a recipient list object as the POST request body. + * At a minimum, the “recipients” array is required, which must contain a valid “address”. + * If the recipient list “id” is not provided in the POST request body, one will be generated and returned in the results body. + * Use the num_rcpt_errors parameter to limit the number of recipient errors returned. + * @param options The create options + * @param callback The request callback with metadata results + */ + create(options: SparkPost.CreateRecipientList, callback: SparkPost.ResultsCallback): void; + /** + * Update an existing recipient list by specifying its ID in the URI path and use a recipient list object as the PUT request body. + * Use the num_rcpt_errors parameter to limit the number of recipient errors returned. + * @param options The update options + * @param callback The request callback with metadata results + */ + update(options: SparkPost.UpdateRecipientList, callback: SparkPost.ResultsCallback): void; + /** + * Permanently delete the specified recipient list. + * @param id The list id + * @param callback The request callback + */ + delete(id: string, callback: SparkPost.Callback): void; + }; + /** Relay Webhooks are a way to instruct SparkPost to accept inbound email on your behalf and forward it to you over HTTP for your own consumption. */ + relayWebhooks: { + /** + * List all your relay webhooks. + * @param callback The request callback with RelayWebhook results array + */ + all(callback: SparkPost.ResultsCallback): void; + /** + * Delete a relay webhook by specifying the webhook ID in the URI path. + * @param relayWebhookId The webhook id + * @param callback The request callback with RelayWebhook results + */ + find(relayWebhookId: string, callback: SparkPost.ResultsCallback): void; + /** + * Create a relay webhook by providing a relay webhooks object as the POST request body. + * @param options The create options + * @param callback The request callback with webhook id results + */ + create(options: SparkPost.RelayWebhook, callback: SparkPost.ResultsCallback<{ id: string }>): void; + /** + * Update a relay webhook by specifying the webhook ID in the URI path. + * @param options The update options + * @param callback The request callback with webhook id results + */ + update(options: SparkPost.UpdateRelayWebhook & { relayWebhookId: string }, callback: SparkPost.ResultsCallback<{ id: string }>): void; + /** + * Delete a relay webhook by specifying the webhook ID in the URI path. + * @param relayWebhookId The webhook id + * @param callback The request callback + */ + delete(relayWebhookId: string, callback: SparkPost.Callback): void; + }; + sendingDomains: { + /** + * List an overview of all sending domains in the system. + * @param callback The request callback with SendingDomain results array + */ + all(callback: SparkPost.ResultsCallback): void; + /** + * Retrieve a sending domain by specifying its domain name in the URI path. The response includes details about its DKIM key configuration. + * @param domain The domain + * @param callback The request callback with SendingDomain results + */ + find(domain: string, callback: SparkPost.ResultsCallback): void; + /** + * Create a sending domain by providing a sending domain object as the POST request body. + * @param options The create options + * @param callback The request callback with basic info results + */ + create(options: SparkPost.CreateSendingDomain, callback: SparkPost.ResultsCallback<{ message: string, domain: string }>): void; + /** + * Update the attributes of an existing sending domain by specifying its domain name in the URI path and use a sending domain object as the PUT request body. + * @param options The update options + * @param callback The request callback with basic info results + */ + update(options: SparkPost.UpdateSendingDomain, callback: SparkPost.ResultsCallback<{ message: string, domain: string }>): void; + /** + * Delete an existing sending domain. + * @param domain The domain + * @param callback The request callback + */ + delete(domain: string, callback: SparkPost.Callback): void; + /** + * Verify a Sending Domain + * @param options The verify options + * @param callback The request callback with verify results + */ + verify(options: SparkPost.VerifyOptions, callback: SparkPost.ResultsCallback): void; + }; + subaccounts: { + /** + * Endpoint for retrieving a list of your subaccounts. + * This endpoint only returns information about the subaccounts themselves, not the data associated with the subaccount. + * @param callback The request callback with subaccount information results array + */ + all(callback: SparkPost.ResultsCallback): void; + /** + * + * @param subaccountId The webhook id + * @param callback The request callback with subaccount information results + */ + find(subaccountId: string | number, callback: SparkPost.ResultsCallback): void; + /** + * Provisions a new subaccount and an initial subaccount API key. + * @param options The create options + * @param callback The request callback with basic subaccount information results + */ + create(options: SparkPost.CreateSubaccount, callback: SparkPost.ResultsCallback): void; + /** + * Update an existing subaccount’s information. + * @param options The create options + * @param callback The request callback with webhook id results + */ + update(options: SparkPost.UpdateSubaccount, callback: SparkPost.ResultsCallback<{ message: string }>): void; + }; + suppressionList: { + /** + * Perform a filtered search for entries in your suppression list. + * @param parameters Object of search parameters + * @param callback The request callback with RelayWebhook results + */ + search(parameters: SparkPost.SupressionSearch, callback: SparkPost.ResultsCallback): void; + /** + * Retrieve the suppression status for a specific recipient by specifying the recipient’s email address in the URI path. + * @param email Email address to check + * @param callback The request callback with webhook id results + */ + checkStatus(email: string, callback: SparkPost.ResultsCallback): void; + /** + * Delete a recipient from the list by specifying the recipient’s email address in the URI path. + * @param email Email address to check + * @param callback The request callback + */ + removeStatus(email: string, callback: SparkPost.Callback): void; + /** + * Bulk insert or update entries in the customer-specific exclusion list. + * @param parameters The suppression entry list + * @param callback The request callback + */ + upsert(parameters: SparkPost.CreateSupressionListEntry | SparkPost.CreateSupressionListEntry[], callback: SparkPost.ResultsCallback<{ message: string }>): void; + }; + templates: { + /** + * List a summary of all templates. + * @param callback The request callback with TemplateMeta results array + */ + all(callback: SparkPost.ResultsCallback): void; + /** + * Retrieve details about a specified template by its id + * @param options The id and draft status information + * @param callback The request callback with Template results + */ + find(options: { id: string, draft?: boolean }, callback: SparkPost.ResultsCallback): void; + /** + * Create a new template + * @param options The create options + * @param callback The request callback with template id results + */ + create(options: { template: SparkPost.CreateTemplate }, callback: SparkPost.ResultsCallback<{ id: string }>): void; + /** + * Update an existing template + * @param options The create options + * @param callback The request callback with template id results + */ + update(options: { + id: string, + template: SparkPost.UpdateTemplate, + update_published?: boolean; + }, callback: SparkPost.ResultsCallback<{ id: string }>): void; + /** + * Delete an existing template + * @param id The template id + * @param callback The request callback + */ + delete(id: string, callback: SparkPost.Callback): void; + /** + * Preview the most recent version of an existing template by id + * @param options The preview options + * @param callback The request callback with webhook id results + */ + preview(options: { id: string, data: any, draft?: boolean }, callback: SparkPost.ResultsCallback): void; + }; + transmissions: { + /** + * List an overview of all transmissions in the account + * @param callback The request callback with Transmission results array + */ + all(callback: SparkPost.ResultsCallback): void; + /** + * List an overview of all transmissions in the account, with added filters + * @param options The search options { campaign_id?, template_id? } + * @param callback The request callback with Transmission results array + */ + all(options: { campaign_id?: string, template_id?: string }, callback: SparkPost.ResultsCallback): void; + /** + * Retrieve the details about a transmission by its ID + * @param transmissionID The transmission id + * @param callback The request callback with Transmission results + */ + find(transmissionID: string, callback: SparkPost.ResultsCallback): void; + /** + * Sends a message by creating a new transmission + * @param options The create options + * @param callback The request callback with metadata and id results + */ + send(options: { transmissionBody: SparkPost.CreateTransmission, num_rcpt_errors?: number }, callback: SparkPost.ResultsCallback<{ + total_rejected_recipients: number; + total_accepted_recipients: number; + id: string; + }>): void; + }; + webhooks: { + /** + * List currently existing webhooks. + * @param callback The request callback with RelayWebhook results array + */ + all(callback: SparkPost.ResultsCallback>): void; + /** + * List currently existing webhooks. + * @param options Object containing optional timezone + * @param callback The request callback with RelayWebhook results array + */ + all(options: { timezone?: string }, callback: SparkPost.ResultsCallback>): void; + /** + * Retrieve details about a specified webhook by its id + * @param options Object containing id and optional timezone + * @param callback The request callback with RelayWebhook results + */ + describe(options: { id: string, timezone?: string }, callback: SparkPost.ResultsCallback): void; + /** + * Create a new webhook + * @param options The create options + * @param callback The request callback with webhook id results + */ + create(options: SparkPost.Webhook, callback: SparkPost.ResultsCallback): void; + /** + * Update an existing webhook + * @param options The update options + * @param callback The request callback with webhook id results + */ + update(options: SparkPost.UpdateWebhook, callback: SparkPost.ResultsCallback): void; + /** + * Delete an existing webhook + * @param id The webhook id + * @param callback The request callback + */ + delete(id: string, callback: SparkPost.Callback): void; + /** + * Sends an example message event batch from the Webhook API to the target URL + * @param options The webhook id and message + * @param callback The request callback with validation results + */ + validate(options: { id: string, message: any }, callback: SparkPost.ResultsCallback<{ + msg: string; + response: { + status: number; + headers: any; + body: string; + } + }>): void; + /** + * Sends an example message event batch from the Webhook API to the target URL + * @param options The webhook id and optional limit + * @param callback The request callback with status results + */ + getBatchStatus(options: { id: string, limit?: number }, callback: SparkPost.ResultsCallback<{ + batch_id: string; + ts: string; + attempts: number; + response_code: number; + }[]>): void; + /** + * Lists descriptions of the events, event types, and event fields that could be included in a Webhooks post to your target URL. + * @param callback The request callback containing documentation results + */ + getDocumentation(callback: SparkPost.ResultsCallback): void; + /** + * List an example of the event data that will be posted by a Webhook for the specified events. + * @param callback The request callback containing examples + */ + getSamples(callback: SparkPost.Callback): void; + /** + * List an example of the event data that will be posted by a Webhook for the specified events. + * @param options The optional event name + * @param callback The request callback containing examples + */ + getSamples(options: { events?: string }, callback: SparkPost.Callback): void; + }; + + /** + * The official Node.js binding for your favorite SparkPost APIs! + * @param apiKey A passed in apiKey will take precedence over an environment variable + * @param options Additional options + */ + constructor(apiKey?: string, options?: SparkPost.ConstructorOptions); + + request(options: Request.Options, callback: SparkPost.Callback): void; + get(options: Request.Options, callback: SparkPost.Callback): void; + post(options: Request.Options, callback: SparkPost.Callback): void; + put(options: Request.Options, callback: SparkPost.Callback): void; + delete(options: Request.Options, callback: SparkPost.Callback): void; +} + +declare namespace SparkPost { + + export interface ErrorWithDescription { + message: string; + code: string; + description: string; + } + export interface ErrorWithParam { + message: string; + param: string; + value: string | null; + } + export interface SparkPostError extends Error { + name: "SparkPostError"; + errors: ErrorWithDescription[] | ErrorWithParam[]; + statusCode: number; + } + + export interface ConstructorOptions { + origin?: string; + endpoint?: string; + apiVersion?: string; + headers?: any; + } + + export interface Response extends Http.IncomingMessage { + body: T; + } + export interface Callback { + (err: Error | SparkPostError | null, res: Response): void; + } + export type ResultsCallback = Callback<{ results: T }>; + + export interface Domain { + domain: string; + } + + export interface MessageEvent { + /** Type of event this record describes */ + type: string; + /** Classification code for a given message (see [Bounce Classification Codes](https://support.sparkpost.com/customer/portal/articles/1929896)) */ + bounce_class: string; + /** Campaign of which this message was a part */ + campaign_id: string; + /** SparkPost-customer identifier through which this message was sent */ + customer_id: string; + /** Protocol by which SparkPost delivered this message */ + delv_method: string; + /** Token of the device / application targeted by this PUSH notification message. Applies only when delv_method is gcm or apn. */ + device_token: string; + /** Error code by which the remote server described a failed delivery attempt */ + error_code: string; + /** IP address of the host to which SparkPost delivered this message; in engagement events, the IP address of the host where the HTTP request originated */ + ip_address: string; + /** SparkPost-cluster-wide unique identifier for this message */ + message_id: string; + /** Sender address used on this message"s SMTP envelope */ + msg_from: string; + /** Message"s size in bytes */ + msg_size: string; + /** Number of failed attempts before this message was successfully delivered; when the first attempt succeeds, zero */ + num_retries: string; + /** Metadata describing the message recipient */ + rcpt_meta: any; + /** Tags applied to the message which generated this event */ + rcpt_tags: string[]; + /** Recipient address used on this message"s SMTP envelope */ + rcpt_to: string; + /** Indicates that a recipient address appeared in the Cc or Bcc header or the archive JSON array */ + rcpt_type: string; + /** Unmodified, exact response returned by the remote server due to a failed delivery attempt */ + raw_reason: string; + /** Canonicalized text of the response returned by the remote server due to a failed delivery attempt */ + reason: string; + /** Domain receiving this message */ + routing_domain: string; + /** Subject line from the email header */ + subject: string; + /** Slug of the template used to construct this message */ + template_id: string; + /** Version of the template used to construct this message */ + template_version: string; + /** Event date and time formatted as: YYYY-MM-DDTHH:MM:SS.SSS±hh:mm */ + timestamp: string; + /** Transmission which originated this message */ + transmission_id: string; + } + + export interface MessageEventParameters { + /** delimited list of bounce classification codes to search. (See Bounce Classification Codes.) */ + bounce_classes?: Array | string | number; + /** delimited list of campaign ID’s to search (i.e. the campaign id used during creation of a transmission). */ + campaign_ids?: string[] | string; + /** Specifies the delimiter for query parameter lists */ + delimiter?: string; + /** delimited list of event types to search. Defaults to all event types. */ + events?: string[] | string; + /** delimited list of friendly from emails to search. */ + friendly_froms?: string[] | string; + /** Datetime in format of YYYY-MM-DDTHH:MM. */ + from?: string; + /** delimited list of message ID’s to search. */ + message_ids?: string[] | string; + /** The results page number to return. Used with per_page for paging through results. */ + page?: number; + /** Number of results to return per page. Must be between 1 and 10,000 (inclusive). */ + per_page?: number; + /** Bounce/failure/rejection reason that will be matched using a wildcard (e.g., %reason%). */ + reason?: string[] | string; + /** delimited list of recipients to search. */ + recipients?: string[] | string; + /** delimited list of subaccount ID’s to search. */ + subaccounts?: number[] | number; + /** delimited list of template ID’s to search. */ + template_ids?: string[] | string; + /** Standard timezone identification string. */ + timezone?: string; + /** Datetime in format of YYYY-MM-DDTHH:MM. */ + to?: string; + /** delimited list of transmission ID’s to search (i.e. id generated during creation of a transmission). */ + transmission_ids?: string[] | string; + } + + export interface RecipientListMetadata { + total_rejected_recipients: number; + total_accepted_recipients: number; + id: string; + name: string; + } + + export interface RecipientList { + /** Short, unique, recipient list identifier */ + id: string; + /** Short, pretty/readable recipient list display name, not required to be unique */ + name: string; + /** Detailed description of the recipient list */ + description: string; + /** Recipient list attribute object */ + attributes: any; + /** Number of accepted recipients */ + total_accepted_recipients: number; + } + export interface RecipientListWithRecipients extends RecipientList { + /** Array of recipient objects */ + recipients: Recipient[]; + } + + export interface CreateRecipientList { + /** Short, unique, recipient list identifier */ + id?: string; + /** Short, pretty/readable recipient list display name, not required to be unique */ + name?: string; + /** Detailed description of the recipient list */ + description?: string; + /** Recipient list attribute object */ + attributes?: any; + /** limit the number of recipient errors returned. */ + num_rcpt_errors?: number; + /** Array of recipient objects */ + recipients: Recipient[]; + } + export interface UpdateRecipientList { + /** Short, unique, recipient list identifier */ + id?: string; + /** Short, pretty/readable recipient list display name, not required to be unique */ + name?: string; + /** Detailed description of the recipient list */ + description?: string; + /** Recipient list attribute object */ + attributes?: any; + /** limit the number of recipient errors returned. */ + num_rcpt_errors?: number; + /** Array of recipient objects */ + recipients?: Recipient[]; + } + + export interface BaseRecipient { + /** SparkPost Enterprise API only. Email to use for envelope FROM. */ + return_path?: string; + /** Array of text labels associated with a recipient. */ + tags?: string[]; + /** Key/value pairs associated with a recipient. */ + metadata?: any; + /** Key/value pairs associated with a recipient that are provided to the substitution engine. */ + substitution_data?: any; + } + export interface RecipientWithAddress { + /** Address information for a recipient At a minimum, address or multichannel_addresses is required. */ + address: Address | string; + } + export interface RecipientWithMultichannelAddresses { + /** + * Address information for a recipient. + * At a minimum, address or multichannel_addresses is required. + * If both address and multichannel_addresses are specified only multichannel_addresses will be used. + * + * @type {(Address | string)} + * @memberOf RecipientWithMultichannelAddresses + */ + address?: Address | string; + /** + * Array of Multichannel Address objects for a recipient. + * At a minimum, address or multichannel_addresses is required. + * If both address and multichannel_addresses are specified only multichannel_addresses will be used. + * + * @type {MultichannelAddress[]} + * @memberOf RecipientWithMultichannelAddresses + */ + multichannel_addresses: MultichannelAddress[]; + } + export type Recipient = (RecipientWithAddress | RecipientWithMultichannelAddresses) & BaseRecipient; + + export interface Address { + /** Valid email address */ + email: string; + /** User-friendly name for the email address */ + name?: string; + /** Email address to display in the “To” header instead of address.email (for CC and BCC) */ + header_to?: string; + } + + export interface MultichannelAddress { + /** The communication channel used to reach recipient. Valid values are “email”, “gcm”, “apns”. */ + channel: string; + /** Valid email address. Required if channel is “email”. */ + email: string; + /** User-friendly name for the email address. Used when channel is “email” */ + name: string; + /** Email address to display in the “To” header instead of address.email (for BCC). Used when channel is “email” */ + header_to: string; + /** SparkPost Enterprise API only. Required if channel is “gcm” or “apns” */ + token: string; + /** SparkPost Enterprise API only. Required if channel is “gcm” or “apns” */ + app_id: string; + } + + export interface RelayWebhook { + /** User-friendly name no example: Inbound Customer Replies */ + name?: string; + /** URL of the target to which to POST relay batches */ + target: string; + /** Authentication token to present in the X-MessageSystems-Webhook-Token header of POST requests to target */ + auth_token?: string; + /** Restrict which inbound messages will be relayed to the target */ + match: Match; + } + + export interface UpdateRelayWebhook { + /** User-friendly name no example: Inbound Customer Replies */ + name?: string; + /** URL of the target to which to POST relay batches */ + target?: string; + /** Authentication token to present in the X-MessageSystems-Webhook-Token header of POST requests to target */ + auth_token?: string; + /** Restrict which inbound messages will be relayed to the target */ + match?: Match; + } + + export interface Match { + /** Inbound messaging protocol associated with this webhook. Defaults to “SMTP” */ + protocol?: string; + /** Inbound domain associated with this webhook. Required when protocol is “SMTP”. */ + domain?: string; + /** ESME address binding associated with this webhook yes, when protocol is “SMPP”. SparkPost Enterprise API only. */ + esme_address?: string; + } + + export interface SendingDomain { + /** Name of the sending domain. */ + domain: string; + /** Associated tracking domain. */ + tracking_domain: string; + /** JSON object containing status details, including whether this domain’s ownership has been verified. */ + status: Status; + /** JSON object in which DKIM key configuration is defined. */ + dkim?: DKIM; + /** Whether to generate a DKIM keypair on creation. */ + generate_dkim?: boolean; + /** Size, in bits, of the DKIM private key to be generated. This option only applies if generate_dkim is ‘true’. */ + dkim_key_length?: number; + /** Setting to true allows this domain to be used by subaccounts. Defaults to false, only available to domains belonging to a master account. */ + shared_with_subaccounts: boolean; + } + + export interface CreateSendingDomain { + /** Name of the sending domain. */ + domain: string; + /** Associated tracking domain. */ + tracking_domain?: string; + /** JSON object containing status details, including whether this domain’s ownership has been verified. */ + status?: Status; + /** JSON object in which DKIM key configuration is defined. */ + dkim?: DKIM; + /** Whether to generate a DKIM keypair on creation. */ + generate_dkim?: boolean; + /** Size, in bits, of the DKIM private key to be generated. This option only applies if generate_dkim is ‘true’. */ + dkim_key_length?: number; + /** Setting to true allows this domain to be used by subaccounts. Defaults to false, only available to domains belonging to a master account. */ + shared_with_subaccounts?: boolean; + } + + export interface UpdateSendingDomain { + /** Name of the sending domain. */ + domain: string; + /** Associated tracking domain. */ + tracking_domain?: string; + /** JSON object in which DKIM key configuration is defined. */ + dkim?: DKIM; + /** Whether to generate a DKIM keypair on creation. */ + generate_dkim?: boolean; + /** Size, in bits, of the DKIM private key to be generated. This option only applies if generate_dkim is ‘true’. */ + dkim_key_length?: number; + /** Setting to true allows this domain to be used by subaccounts. Defaults to false, only available to domains belonging to a master account. */ + shared_with_subaccounts?: boolean; + } + + export interface DKIM { + /** Signing Domain Identifier (SDID). SparkPost Enterprise API only. */ + signing_domain?: string; + /** DKIM private key. */ + private?: string; + /** DKIM public key. */ + public: string; + /** DomainKey selector. */ + selector: string; + /** Header fields to be included in the DKIM signature. This field is currently ignored. */ + headers?: string; + } + + export interface Status { + /** Whether domain ownership has been verified */ + ownership_verified: boolean; + /** Verification status of SPF configuration */ + spf_status: "valid" | "invalid" | "unverified" | "pending"; + /** Compliance status */ + compliance_status: "valid" | "pending" | "blocked"; + /** Verification status of DKIM configuration */ + dkim_status: "valid" | "invalid" | "unverified" | "pending"; + /** Verification status of abuse@ mailbox */ + abuse_at_status: "valid" | "invalid" | "unverified" | "pending"; + /** Verification status of postmaster@ mailbox */ + postmaster_at_status: "valid" | "invalid" | "unverified" | "pending"; + } + + export interface VerifyOptions { + domain: string; + verifyDKIM?: boolean; + verifySPF?: boolean; + } + + export interface VerifyResults extends Status { + dns?: { + dkim_record: string; + spf_record: string; + }; + } + + export interface CreateSubaccount { + /** user-friendly name */ + name: string; + /** user-friendly identifier for subaccount API key */ + keyLabel: string; + /** list of grants to give the subaccount API key */ + keyGrants: string[]; + /** list of IPs the subaccount may be used from */ + keyValidIps?: string[]; + /** id of the default IP pool assigned to subaccount"s transmissions */ + ipPool?: string; + } + + export interface CreateSubaccountResponse { + subaccount_id: number; + key: string; + label: string; + short_key: string; + } + + export interface UpdateSubaccount { + /** the id of the subaccount you want to update */ + subaccountId: string | number; + /** user-friendly name */ + name: string; + /** status of the subaccount */ + status: string; + /** id of the default IP pool assigned to subaccount"s transmissions */ + ipPool?: string; + } + + export interface SubaccountInformation { + /** ID of subaccount */ + id: number; + /** User friendly identifier for a specific subaccount */ + name: string; + /** Status of the account */ + status: "active" | "suspended" | "terminated"; + /** The ID of the default IP Pool assigned to this subaccount’s transmissions */ + ip_pool?: string; + compliance_status: string; + } + + export interface CreateSupressionListEntry { + recipient: string; + /** Whether the recipient requested to not receive any transactional messages. At a minimum, transactional or non_transactional is required upon creation of the entry. */ + transactional?: boolean; + /** Whether the recipient requested to not receive any non-transactional messages. At a minimum, transactional or non_transactional is required upon creation of the entry. */ + non_transactional?: boolean; + /** Short explanation of the suppression */ + description?: string; + } + + export interface SupressionListEntry { + recipient: string; + /** Whether the recipient requested to not receive any transactional messages. At a minimum, transactional or non_transactional is required upon creation of the entry. */ + transactional?: boolean; + /** Whether the recipient requested to not receive any non-transactional messages. At a minimum, transactional or non_transactional is required upon creation of the entry. */ + non_transactional?: boolean; + /** Coming soon */ + type?: "transactional" | "non_transactional"; + /** Source responsible for inserting the list entry. Valid values include: Spam Complaint, List Unsubscribe, Bounce Rule, Unsubscribe Link, Manually Added, Compliance. */ + source?: string; + /** Short explanation of the suppression */ + description?: string; + created: string; + updated: string; + } + + export interface SupressionSearch { + /** Datetime the entries were last updated, in the format of YYYY-MM-DDTHH:mm:ssZ */ + to?: string; + /** Datetime the entries were last updated, in the format YYYY-MM-DDTHH:mm:ssZ */ + from?: string; + /** Types of entries to include in the search, i.e. entries with “transactional” and/or “non_transactional” keys set to true */ + types?: string; + /** Sources of the entries to include in the search, i.e. entries that were added by this source */ + sources?: string; + /** Maximum number of results to return. Must be between 1 and 100000. Default value is 100000. */ + limit?: number; + } + + export interface TemplateContent { + /** HTML content for the email’s text/html MIME part */ + html: string; + /** Text content for the email’s text/plain MIME part */ + text: string; + /** Email subject line. */ + subject: string; + /** + * Address “from” : "deals@company.com" or JSON object composed of the “name” and “email” fields + * “from” : { “name” : “My Company”, “email” : "deals@company.com" } used to compose the email’s “From” header. + * + * @type {(Address | string)} + * @memberOf CreateTemplateContent + */ + from: Address | string; + /** Email address used to compose the email’s “Reply-To” header. */ + reply_to?: string; + /** JSON dictionary containing headers other than “Subject”, “From”, “To”, and “Reply-To”. */ + headers?: any; + } + + export interface CreateTemplateContent { + /** HTML content for the email’s text/html MIME part */ + html?: string; + /** Text content for the email’s text/plain MIME part */ + text?: string; + /** Email subject line. */ + subject: string; + /** + * Address “from” : "deals@company.com" or JSON object composed of the “name” and “email” fields + * “from” : { “name” : “My Company”, “email” : "deals@company.com" } used to compose the email’s “From” header. + * + * @type {(Address | string)} + * @memberOf CreateTemplateContent + */ + from: Address | string; + /** Email address used to compose the email’s “Reply-To” header. */ + reply_to?: string; + /** JSON dictionary containing headers other than “Subject”, “From”, “To”, and “Reply-To”. */ + headers?: any; + } + + export interface TemplateMeta { + /** Unique template ID */ + id: string; + /** Template name */ + name: string; + /** Published state of the template (true = published, false = draft) */ + published: boolean; + /** Template description */ + description: string; + } + + export interface Template { + /** + * Short, unique, alphanumeric ID used to reference the template. + * At a minimum, id or name is required upon creation. It is auto generated if not provided. + * After a template has been created, this property cannot be changed. Maximum length - 64 bytes + * + * @type {string} + * @memberOf CreateTemplate + */ + id: string; + /** Content that will be used to construct a message yes For a full description, see the Content Attributes. Maximum length - 20 MBs */ + content: TemplateContent | { email_rfc822: string }; + /** Whether the template is published or is a draft version no - defaults to false A template cannot be changed from published to draft. */ + published: boolean; + /** Editable display name At a minimum, id or name is required upon creation. The name does not have to be unique. Maximum length - 1024 bytes */ + name: string; + /** Detailed description of the template no Maximum length - 1024 bytes */ + description: string; + /** JSON object in which template options are defined no For a full description, see the Options Attributes. */ + options: TemplateOptions; + /** The “last_update_time” is the time the template was last updated, for both draft and published versions */ + last_update_time: string; + /** The “last_use” time represents the last time any version of this template was used (draft or published). */ + last_use?: string; + } + + export interface CreateTemplate { + /** + * Short, unique, alphanumeric ID used to reference the template. + * At a minimum, id or name is required upon creation. It is auto generated if not provided. + * After a template has been created, this property cannot be changed. Maximum length - 64 bytes + * + * @type {string} + * @memberOf CreateTemplate + */ + id?: string; + /** Content that will be used to construct a message yes For a full description, see the Content Attributes. Maximum length - 20 MBs */ + content: CreateTemplateContent | { email_rfc822: string }; + /** Whether the template is published or is a draft version no - defaults to false A template cannot be changed from published to draft. */ + published?: boolean; + /** Editable display name At a minimum, id or name is required upon creation. The name does not have to be unique. Maximum length - 1024 bytes */ + name?: string; + /** Detailed description of the template no Maximum length - 1024 bytes */ + description?: string; + /** JSON object in which template options are defined no For a full description, see the Options Attributes. */ + options?: CreateTemplateOptions; + } + + export interface UpdateTemplate { + /** Content that will be used to construct a message yes For a full description, see the Content Attributes. Maximum length - 20 MBs */ + content?: CreateTemplateContent | { email_rfc822: string }; + /** Whether the template is published or is a draft version no - defaults to false A template cannot be changed from published to draft. */ + published?: boolean; + /** Editable display name At a minimum, id or name is required upon creation. The name does not have to be unique. Maximum length - 1024 bytes */ + name?: string; + /** Detailed description of the template no Maximum length - 1024 bytes */ + description?: string; + /** JSON object in which template options are defined no For a full description, see the Options Attributes. */ + options?: CreateTemplateOptions; + } + + export interface TemplateOptions { + /** Enable or disable open tracking */ + open_tracking: boolean; + /** Enable or disable click tracking */ + click_tracking: boolean; + /** Distinguish between transactional and non-transactional messages for unsubscribe and suppression purposes */ + transactional: boolean; + } + + export interface CreateTemplateOptions { + /** Enable or disable open tracking */ + open_tracking?: boolean; + /** Enable or disable click tracking */ + click_tracking?: boolean; + /** Distinguish between transactional and non-transactional messages for unsubscribe and suppression purposes */ + transactional?: boolean; + } + + export interface CreateTransmission { + /** JSON object in which transmission options are defined */ + options?: TransmissionOptions; + /** Inline recipient objects or object containing stored recipient list ID */ + recipients?: Recipient[] | { list_id: string }; + /** Name of the campaign */ + campaign_id?: string; + /** Description of the transmission */ + description?: string; + /** Transmission level metadata containing key/value pairs */ + metadata?: any; + /** Key/value pairs that are provided to the substitution engine */ + substitution_data?: any; + /** SparkPost Enterprise API only: email to use for envelope FROM */ + return_path?: string; + /** Content that will be used to construct a message */ + content: InlineContent | { template_id: string, use_draft_template?: boolean } | { email_rfc822: string }; + } + + export interface TransmissionSummary { + /** ID of the transmission */ + id: string; + /** State of the transmission */ + state: "submitted" | "Generating" | "Success" | "Canceled"; + /** Description of the transmission */ + description: string; + /** Name of the campaign */ + campaign_id: string; + /** Content that will be used to construct a message */ + content: { template_id: string }; + } + + export interface Transmission { + /** ID of the transmission */ + id: string; + /** State of the transmission */ + state: "submitted" | "Generating" | "Success" | "Canceled"; + /** JSON object in which transmission options are defined */ + options: TransmissionOptions; + /** Name of the campaign */ + campaign_id: string; + /** Description of the transmission */ + description: string; + /** Transmission level metadata containing key/value pairs */ + metadata: any; + /** Key/value pairs that are provided to the substitution engine */ + substitution_data: any; + /** Content that will be used to construct a message */ + content: InlineContent | { template_id: string, use_draft_template?: boolean } | { email_rfc822: string }; + /** Computed total number of messages generated */ + num_generated: number; + /** Computed total number of failed messages */ + num_failed_generation: number; + /** Number of recipients that failed input validation */ + num_invalid_recipients: number; + rcpt_list_chunk_size: number; + rcpt_list_total_chunks: number; + } + + export interface TransmissionOptions { + /** Delay generation of messages until this datetime. */ + start_time?: string; + /** Whether open tracking is enabled for this transmission */ + open_tracking?: boolean; + /** Whether click tracking is enabled for this transmission */ + click_tracking?: boolean; + /** Whether message is transactional or non-transactional for unsubscribe and suppression purposes */ + transactional?: boolean; + /** Whether or not to use the sandbox sending domain */ + sandbox?: boolean; + /** SparkPost Enterprise API only: Whether or not to ignore customer suppression rules, for this transmission only. Only applicable if your configuration supports this parameter. */ + skip_suppression?: boolean; + /** The ID of a dedicated IP pool associated with your account ( Note: SparkPost only ). */ + ip_pool?: string; + /** Whether or not to perform CSS inlining in HTML content */ + inline_css?: boolean; + } + + export interface InlineContent { + /** HTML content for the email’s text/html MIME part At a minimum, html, text, or push is required. */ + html?: string; + /** Text content for the email’s text/plain MIME part At a minimum, html, text, or push is required. */ + text?: string; + /** Content of push notifications At a minimum, html, text, or push is required. SparkPost Enterprise API only. */ + push?: PushData; + /** Email subject line required for email transmissions Expected in the UTF-8 charset without RFC2047 encoding. Substitution syntax is supported. */ + subject?: string; + /** "deals@company.com" or JSON object composed of the “name” and “email” fields “from” : { “name” : “My Company”, “email” : "deals@company.com" } used to compose the email’s “From” header */ + from?: string | { email: string, name: string }; + /** Email address used to compose the email’s “Reply-To” header */ + reply_to?: string; + /** JSON dictionary containing headers other than “Subject”, “From”, “To”, and “Reply-To” */ + headers?: any; + /** JSON array of attachments. */ + attachments?: Attachment[]; + /** JSON array of inline images. */ + inline_images?: Attachment[]; + } + + export interface PushData { + /** payload for APNs messages */ + apns?: any; + /** payload for GCM messages */ + gcm?: any; + } + + export interface Attachment { + /** + * The MIME type of the attachment; e.g., “text/plain”, “image/jpeg”, “audio/mp3”, “video/mp4”, “application/msword”, “application/pdf”, etc., + * including the “charset” parameter (text/html; charset=“UTF-8”) if needed. + * The value will apply “as-is” to the “Content-Type” header of the generated MIME part for the attachment. + * + * @type {string} + * @memberOf Attachment + */ + type: string; + /** The filename of the attachment (for example, “document.pdf”). This is inserted into the filename parameter of the Content-Disposition header. */ + name: string; + /** + * The content of the attachment as a Base64 encoded string. + * The string should not contain \r\n line breaks. + * The SparkPost systems will add line breaks as necessary to ensure the Base64 encoded lines contain no more than 76 characters each. + * + * @type {string} + * @memberOf Attachment + */ + data: string; + } + + export interface Webhook { + /** User-friendly name for webhook */ + name: string; + /** URL of the target to which to POST event batches */ + target: string; + /** Array of event types this webhook will receive */ + events: string[]; + /** Type of authentication to be used during POST requests to target */ + auth_type?: string; + /** Object containing details needed to request authorization credentials, as necessary */ + auth_request_details?: any; + /** Object containing credentials needed to make authorized POST requests to target */ + auth_credentials?: any; + /** Authentication token to present in the X-MessageSystems-Webhook-Token header of POST requests to target */ + auth_token?: string; + } + + export interface UpdateWebhook { + id: string; + /** User-friendly name for webhook */ + name?: string; + /** URL of the target to which to POST event batches */ + target?: string; + /** Array of event types this webhook will receive */ + events?: string[]; + /** Type of authentication to be used during POST requests to target */ + auth_type?: string; + /** Object containing details needed to request authorization credentials, as necessary */ + auth_request_details?: any; + /** Object containing credentials needed to make authorized POST requests to target */ + auth_credentials?: any; + /** Authentication token to present in the X-MessageSystems-Webhook-Token header of POST requests to target */ + auth_token?: string; + } + + export interface WebhookLinks { + links: { + href: string; + rel: string; + method: string[]; + }[]; + } +} + +export = SparkPost; diff --git a/sparkpost/v1/sparkpost-tests.ts b/sparkpost/v1/sparkpost-tests.ts new file mode 100644 index 0000000000..0b8a41ab0a --- /dev/null +++ b/sparkpost/v1/sparkpost-tests.ts @@ -0,0 +1,944 @@ +import * as SparkPost from "sparkpost"; + +let key = "YOURAPIKEY"; +let client = new SparkPost(key); + +client.get({ + uri: "metrics/domains" +}, function(err, data) { + if (err) { + console.log(err); + return; + } + + console.log(data.body); +}); + +client.inboundDomains.create("example1.com", function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our client library!"); + } +}); + +client.inboundDomains.delete("example1.com", function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our client library!"); + } +}); + +client.inboundDomains.find("example1.com", function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our client library!"); + } +}); + +client.inboundDomains.all(function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our client library!"); + } +}); + +client.messageEvents.search({}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.messageEvents.search({ + events: "click", + campaign_ids: "monday_mailshot" +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.messageEvents.search({ + from: "2016-01-01T00:00", + to: "2016-01-02T23:59", + page: 1, + per_page: 5, + events: ["bounce", "out_of_band"], + bounce_classes: [10] +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.recipientLists.create({ + id: "UNIQUE_TEST_ID", + name: "Test Recipient List", + recipients: [ + { + address: { + email: "test1@test.com" + } + }, { + address: { + email: "test2@test.com" + } + }, { + address: { + email: "test3@test.com" + } + } + ] +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.recipientLists.delete("UNIQUE_TEST_ID", function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.recipientLists.all(function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.recipientLists.find({ + id: "UNIQUE_TEST_ID" +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.recipientLists.find({ + id: "UNIQUE_TEST_ID", + show_recipients: true +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.recipientLists.update({ + id: "EXISTING_TEST_ID", + name: "Test Recipient List", + recipients: [ + { + address: { + email: "test1@test.com" + } + }, { + address: { + email: "test2@test.com" + } + }, { + address: { + email: "test3@test.com" + } + } + ] +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.relayWebhooks.create({ + name: "Test Relay Webhook", + target: "http://client.test.com/test-webhook", + match: { + domain: "inbound.example.com" + } +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our client library!"); + } +}); + +client.relayWebhooks.delete("123456789", function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our client library!"); + } +}); + +client.relayWebhooks.find("123456789", function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our client library!"); + } +}); + +client.relayWebhooks.all(function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our client library!"); + } +}); + +client.relayWebhooks.update({ + relayWebhookId: "123456789", + target: "http://client.test.com/test-webhook" +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our client library!"); + } +}); + +client.sendingDomains.create({ + domain: "example1.com", + dkim: { + "private": "MIICXgIBAAKBgQC+W6scd3XWwvC//Y1g==", + "public": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+W6scd3XWwvC/==", + selector: "brisbane", + headers: "from:to:subject:date" + } +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + + +client.sendingDomains.delete("example1.com", function(err, data) { + if (err) { + console.log(err); + } else { + console.log(data); + console.log("Congrats you can use our client library!"); + } +}); + +client.sendingDomains.all(function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.sendingDomains.find("example1.com", function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.sendingDomains.update({ + domain: "example1.com", + dkim: { + "private": "MIICXgIBAAKBgQC+W6scd3XWwvC/hPRksfDYFi3ztgyS9OSqnnjtNQeDdTSD1DRx//Y1g==", + "public": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+W6scd3XWwvC/==", + selector: "hello_selector", + headers: "from:to:subject:date" + } +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.sendingDomains.verify({ + domain: "example1.com" +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.sendingDomains.verify({ + domain: "example1.com", + verifySPF: false +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.sendingDomains.verify({ + domain: "example1.com", + verifyDKIM: false +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.subaccounts.create({ + name: "Test Subaccount", + keyLabel: "Test Subaccount key", + keyGrants: [ + "smtp/inject", + "transmissions/modify" + ] +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res); + console.log("Congrats you can use our client library!"); + } +}); + +client.subaccounts.all(function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our client library!"); + } +}); + +client.subaccounts.find(123, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our client library!"); + } +}); + +client.subaccounts.update({ + subaccountId: 123, + name: "Test Subaccount", + status: "suspended" +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our client library!"); + } +}); + +client.suppressionList.checkStatus("test@test.com", function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our client library!"); + } +}); + +client.suppressionList.removeStatus("test@test.com", function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our client library!"); + } +}); + +client.suppressionList.search({ + from: "2015-05-07T00:00:00+0000", + to: "2015-05-07T23:59:59+0000", + limit: 5 +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our client library!"); + } +}); + +client.suppressionList.upsert([ + { + recipient: "test1@test.com", + transactional: false, + non_transactional: true, + description: "Test description 1" + }, + { + recipient: "test2@test.com", + transactional: true, + non_transactional: true, + description: "Test description 2" + }, + { + recipient: "test3@test.com", + transactional: true, + non_transactional: false, + description: "Test description 3" + } +], function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our client library!"); + } +}); + +client.templates.create({ + template: { + id: "TEST_ID", + name: "Test Template", + content: { + from: "test@test.com", + subject: "Test email template!", + html: "This is a test email template!" + } + } +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.templates.delete("TEST_ID", function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + + +client.templates.all(function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.templates.find({ + id: "TEST_ID", + draft: true +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.templates.find({ + id: "TEST_ID" +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.templates.preview({ + id: "TEST_ID", + data: {} +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.templates.update({ + id: "TEST_ID", + template: { + content: { + from: "test@test.com", + subject: "Updated Published Test email template!", + html: "This is a published test email template! Updated!" + } + }, + update_published: true +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.templates.update({ + id: "TEST_ID", + template: { + content: { + from: "test@test.com", + subject: "Updated Test email template!", + html: "This is a test email template! Updated!" + } + } +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.transmissions.all(function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.transmissions.find("YOUR-TRANSMISSION-KEY", function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.transmissions.all({ + campaign_id: "my_campaign" +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.transmissions.all({ + template_id: "my_template" +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.transmissions.send({ + transmissionBody: { + recipients: [{ address: { email: "john.doe@example.com" } }], + content: { + from: "From Envelope ", + subject: "Example Email for MIME Parts", + html: "

Hello World!

", + text: "Hello World!" + }, + options: { + open_tracking: true, + click_tracking: true + } + } +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.transmissions.send({ + transmissionBody: { + recipients: [{address: {email: "john.doe@example.com"}}], + content: { + email_rfc822: "Content-Type: text/plain\nFrom: From Envelope \nSubject: Example Email\n\nHello World" + } + } +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.transmissions.send({ + transmissionBody: { + options: { + open_tracking: true, + click_tracking: true + }, + campaign_id: "christmas_campaign", + return_path: "bounces-christmas-campaign@flintstone.com", + metadata: { + user_type: "students" + }, + substitution_data: { + sender: "Big Store Team" + }, + recipients: [ + { + return_path: "123@bounces.flintstone.com", + address: { + email: "wilma@flintstone.com", + name: "Wilma Flintstone" + }, + tags: [ + "greeting", + "prehistoric", + "fred", + "flintstone" + ], + metadata: { + place: "Bedrock" + }, + substitution_data: { + customer_type: "Platinum" + } + } + ], + content: { + from: { + name: "Fred Flintstone", + email: "fred@flintstone.com" + }, + subject: "Big Christmas savings!", + reply_to: "Christmas Sales ", + headers: { + "X-Customer-Campaign-ID": "christmas_campaign" + }, + text: "Hi {{address.name}} \nSave big this Christmas in your area {{place}}! \nClick http://www.mysite.com and get huge discount\n Hurry, this offer is only to {{customer_type}}\n {{sender}}", + html: "

Hi {{address.name}} \nSave big this Christmas in your area {{place}}! \nClick http://www.mysite.com and get huge discount\n

" + } + } +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.transmissions.send({ + transmissionBody: { + recipients: [ + { + address: { + email: "original.recipient@example.com", + name: "Original Recipient" + }, + substitution_data: { + recipient_type: "Original" + } + }, + { + address: { + email: "bcc.recipient@example.com", + header_to: "\"Original Recipient\" " + }, + substitution_data: { + recipient_type: "BCC" + } + } + ], + content: { + from: { + name: "Node BCC Test", + email: "from@example.com" + }, + subject: "Example email using bcc", + text: "An example email using bcc with SparkPost to the {{recipient_type}} recipient.", + html: "

An example email using bcc with SparkPost to the {{recipient_type}} recipient.

" + } + } +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats! You sent an email with bcc using SparkPost!"); + } +}); + +client.transmissions.send({ + transmissionBody: { + recipients: [ + { + address: { + email: "original.recipient@example.com", + name: "Original Recipient" + }, + substitution_data: { + recipient_type: "Original" + } + }, + { + address: { + email: "cc.recipient@example.com", + name: "Carbon Copy Recipient", + header_to: "\"Original Recipient\" " + }, + substitution_data: { + recipient_type: "CC" + } + } + ], + content: { + from: { + name: "Node CC Test", + email: "from@example.com" + }, + headers: { + "CC": "\"Carbon Copy Recipient\" " + }, + subject: "Example email using cc", + text: "An example email using cc with SparkPost to the {{recipient_type}} recipient.", + html: "

An example email using cc with SparkPost to the {{recipient_type}} recipient.

" + } + } +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats! You sent an email with cc using SparkPost!"); + } +}); + +client.transmissions.send({ + transmissionBody: { + recipients: { + list_id: "example-list" + }, + content: { + from: "From Envelope ", + subject: "Example Email for Stored List and Inline Content", + html: "

Hello World

", + text: "Hello World!" + } + } +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.transmissions.send({ + transmissionBody: { + recipients: { + list_id: "example-list" + }, + content: { + from: "From Envelope ", + subject: "Example Email for Stored List and Template", + template_id: "my-template" + } + } +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.transmissions.send({ + num_rcpt_errors: 3, + transmissionBody: { + campaign_id: "ricks-campaign", + content: { + template_id: "ricks-template" + }, + recipients: [{ address: { email: "rick.sanchez@rickandmorty100years.com", name: "Rick Sanchez" } }] + } +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("What up my glib globs! SparkPost!"); + } +}); + +client.webhooks.create({ + name: "Test webhook", + target: "http://client.test.com/test-webhook", + auth_token: "AUTH_TOKEN", + events: [ + "delivery", + "injection", + "open", + "click" + ] +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.webhooks.delete("TEST_WEBHOOK_UUID", function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.webhooks.describe({ + id: "TEST_WEBHOOK_UUID", + timezone: "America/New_York" +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.webhooks.getBatchStatus({ + id: "TEST_WEBHOOK_UUID", + limit: 1000 +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + + +client.webhooks.getDocumentation(function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.webhooks.getSamples({ + events: "bounce" +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.webhooks.all(function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.webhooks.update({ + id: "TEST_WEBHOOK_UUID", + name: "Renamed Test webhook", + events: [ + "policy_rejection", + "delay" + ] +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); + +client.webhooks.validate({ + id: "TEST_WEBHOOK_UUID", + message: { + msys: {} + } +}, function(err, res) { + if (err) { + console.log(err); + } else { + console.log(res.body); + console.log("Congrats you can use our SDK!"); + } +}); diff --git a/sparkpost/v1/tsconfig.json b/sparkpost/v1/tsconfig.json new file mode 100644 index 0000000000..54f30b3435 --- /dev/null +++ b/sparkpost/v1/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "sparkpost": ["sparkpost/v1"], + "sparkpost/*": ["sparkpost/v1/*"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "sparkpost-tests.ts" + ] +} diff --git a/speakeasy/index.d.ts b/speakeasy/index.d.ts index 15ec90c09a..4e281f996f 100644 --- a/speakeasy/index.d.ts +++ b/speakeasy/index.d.ts @@ -49,6 +49,7 @@ interface TotpOptions { counter?: number; epoch?: number; secret?: string; + digits?: number; digest?: () => string; algorithm?: string; } diff --git a/tslint.json b/tslint.json index 6b04ae7f36..7847d36674 100644 --- a/tslint.json +++ b/tslint.json @@ -1 +1 @@ -{ "extends": "./node_modules/types-publisher/tslint-definitions.json" } \ No newline at end of file +{ "extends": "./node_modules/types-publisher/tslint-definitions.json" } diff --git a/victory/index.d.ts b/victory/index.d.ts index 70d1ecb6f1..d1d241354d 100644 --- a/victory/index.d.ts +++ b/victory/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Victory 0.9.0 // Project: https://github.com/FormidableLabs/victory -// Definitions by: Alexey Svetliakov +// Definitions by: Alexey Svetliakov , snerks // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -299,6 +299,11 @@ declare module "victory" { before?: (datum: any) => AnimationStyle; after?: (datum: any) => AnimationStyle; }; + /** + * The easing prop specifies an easing function name to use for tweening. + * @default "quadInOut" + */ + easing?: AnimationEasing; } /** diff --git a/victory/victory-tests.tsx b/victory/victory-tests.tsx index 7947f5f0ec..601780ffaf 100644 --- a/victory/victory-tests.tsx +++ b/victory/victory-tests.tsx @@ -601,4 +601,8 @@ test = ( } }} /> -); \ No newline at end of file +); + +test = ( + +); diff --git a/xmpp-jid/index.d.ts b/xmpp-jid/index.d.ts deleted file mode 100644 index 678e306abc..0000000000 --- a/xmpp-jid/index.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Type definitions for @xmpp/jid 0.0 -// Project: github.com/node-xmpp/node-xmpp/ -// Definitions by: PJakcson -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 -import {JID} from './lib/JID'; - -export declare function createJID(local: string, domain: string, resource: string): JID; - -export {JID} from './lib/JID'; - -export declare function equal(a: JID, b: JID): boolean; -export declare function is(a: any): boolean; diff --git a/xmpp-jid/lib/JID.d.ts b/xmpp-jid/lib/JID.d.ts deleted file mode 100644 index a1d2558b30..0000000000 --- a/xmpp-jid/lib/JID.d.ts +++ /dev/null @@ -1,46 +0,0 @@ -/** - * Created by marcneumann on 17.02.17. - */ - -export declare class JID { - local: string; - domain: string; - resource: string; - - constructor(local: string, domain?: string, resource?: string); - - parseJID(jid: string): void; - - toString(unescape?: any): string; - - /** - * Convenience method to distinguish users - **/ - bare(): JID; - - /** - * Comparison function - **/ - equals(other: JID): boolean; - - /** - * http://xmpp.org/rfcs/rfc6122.html#addressing-localpart - **/ - setLocal(local: string, escape?: any): void; - - getLocal(unescape?: any): string; - - /** - * http://xmpp.org/rfcs/rfc6122.html#addressing-domain - */ - setDomain(value: string): void; - - getDomain(): string; - - /** - * http://xmpp.org/rfcs/rfc6122.html#addressing-resourcepart - */ - setResource(value: string): void; - - getResource(): string; -} diff --git a/xmpp-jid/xmpp-jid-tests.ts b/xmpp-jid/xmpp-jid-tests.ts deleted file mode 100644 index 2514d5fb8a..0000000000 --- a/xmpp-jid/xmpp-jid-tests.ts +++ /dev/null @@ -1,40 +0,0 @@ -import {JID} from './index'; - -/* - * All return an instance of JID.JID, the new operator is optional. - */ -let addr = new JID('alice@wonderland.net/rabbithole'); // OK -addr = new JID('alice', 'wonderland.net', 'rabbithole'); // BEST; see section on escaping below - -/* - * local - */ -addr.local = 'alice'; -addr.local; // alice -// same as -addr.setLocal('alice'); -addr.getLocal(); // alice - -/* - * domain - */ -addr.domain = 'wonderland.net'; -addr.domain; // wonderland.net -// same as -addr.setDomain('wonderland.net'); -addr.getDomain(); // wonderland.net - -/* - * resource - */ -addr.resource = 'rabbithole'; -addr.resource; // rabbithole -// same as -addr.setResource('rabbithole'); -addr.getResource(); // rabbithole - -addr.toString(); // alice@wonderland.net/rabbithole -addr.bare(); // returns a JID without resource - -const some_jid = new JID('is', 'a', 'test'); -addr.equals(some_jid); // returns true if the two JIDs are equal, false otherwise diff --git a/youtube/index.d.ts b/youtube/index.d.ts index ca5d99550a..a45ec6a8c8 100644 --- a/youtube/index.d.ts +++ b/youtube/index.d.ts @@ -1,166 +1,935 @@ // Type definitions for YouTube // Project: https://developers.google.com/youtube/ -// Definitions by: Daz Wilkin , Ian Obermiller +// Definitions by: Daz Wilkin , +// Ian Obermiller , +// Josh Goldberg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 -declare namespace YT { - interface EventArgs { - target: Player; - data: any; - } - - interface EventHandler { - (event: EventArgs): void; - } - - export interface Events { - onReady?: EventHandler; - onPlayback?: EventHandler; - onStateChange?: EventHandler; - onError?: EventHandler; - } - - export enum ListType { - search, - user_uploads, - playlist, +/** + * @see https://developers.google.com/youtube/iframe_api_reference + * @see https://developers.google.com/YouTube/player_parameters + */ +declare namespace YT +{ + /** + * State of a video player. + */ + export enum PlayerState + { + UNSTARTED = -1, + ENDED = 0, + PLAYING = 1, + PAUSED = 2, + BUFFERING = 3, + CUED = 5 } - export interface PlayerVars { - autohide?: number; - autoplay?: number; - cc_load_policy?: any; - color?: string; - controls?: number; - disablekb?: number; - enablejsapi?: number; + /** + * Known causes for player errors. + */ + export const enum PlayerError + { + /** + * The request contained an invalid parameter value. + */ + InvalidParam = 2, + + /** + * The requested content cannot be played in an HTML5 player. + */ + Html5Error = 5, + + /** + * The video requested was not found. + */ + VideoNotFound = 100, + + /** + * The owner of the requested video does not allow it to be played in embedded players. + */ + EmbeddingNotAllowed = 101, + + /** + * This error is the same as 101. It's just a 101 error in disguise! + */ + EmbeddingNotAllowed2 = 150 + } + + /** + * Whether to auto-hide video controls. + */ + export const enum AutoHide + { + /** + * Controls are visible throughout the video + */ + AlwaysVisible = 0, + + /** + * Progress bar and player controls slide out of view after a couple of seconds. + */ + HideAllControls = 1, + + /** + * Progress bar fades out while the player controls remain visible. + */ + HideProgressBar = 2 + } + + /** + * Whether to autoplay the video. + */ + export const enum AutoPlay + { + /** + * Video does not autoplay. + */ + NoAutoPlay = 0, + + /** + * Video will autoplay when loaded. + */ + AutoPlay = 1 + } + + /** + * Whether to use user-preferred or forced caption loading. + */ + export const enum ClosedCaptionsLoadPolicy + { + /** + * Defaults to the user's preferences. + */ + UserDefault = 0, + + /** + * For closed captions to be shown. + */ + ForceOn = 1 + } + + /** + * Allowed progress bar colors. + */ + export type ProgressBarColor = "red" | "white"; + + /** + * How video controls are shown. + */ + export const enum Controls + { + /** + * Player controls do not display. + */ + Hide = 0, + + /** + * Player controls display. + */ + ShowLoadPlayer = 1, + + /** + * Player controls display after a delay. + */ + ShowDelayLoadPlayer = 2 + } + + /** + * Whether to allow keyboard controls. + */ + export const enum KeyboardControls + { + /** + * Keyboard controls are enabled. + */ + Enable = 0, + + /** + * Keyboard controls are disabled. + */ + Disable = 1 + } + + /** + * Whether the JavaScript API should be enabled. + */ + export const enum JsApi + { + /** + * JavaScript API will be disabled. + */ + Disable = 0, + + /** + * JavaScript API will be enabled. + */ + Enable = 1 + } + + /** + * Whether to display the full-screen button. + */ + export const enum FullscreenButton + { + /** + * The full screen button is hidden. + */ + Hide = 0, + + /** + * The full screen button is visible. + */ + Show = 1 + } + + /** + * Whether to show video annotations. + */ + export const enum IvLoadPolicy + { + /** + * Video annotations will be shown. + */ + Show = 1, + + /** + * Video annotations will not be shown. + */ + Hide = 3 + } + + /** + * Which type of content loads in the player. + */ + export type ListType = ListTypePlayer | ListTypeSearch | ListTypeUserUploads; + + /** + * The requested video should be shown in the player. + */ + export type ListTypePlayer = "player"; + + /** + * A search area should be shown in the player. + */ + export type ListTypeSearch = "search"; + + /** + * The user's uploads should load in the player. + */ + export type ListTypeUserUploads = "user_uploads"; + + /** + * Whether a single video should be looped. + */ + export const enum Loop + { + /** + * Video or playlist will be played only once. + */ + SinglePlay = 0, + + /** + * Video or playlist will be played over and over again. + */ + Loop = 1 + } + + /** + * Comma separated list of video IDs to play after the URL path's video. + */ + export const enum ModestBranding + { + /** + * Player will contain full YouTube branding. + */ + Full = 0, + + /** + * YouTube logo will not display in the control bar. + */ + Modest = 1 + } + + /** + * Whether to show related videos after the video finishes. + */ + export const enum RelatedVideos + { + /** + * Hide related videos after playback is complete. + */ + Hide = 0, + + /** + * Show related videos after playback is complete. + */ + Show = 1 + } + + /** + * Whether to show video information before playing. + */ + export const enum ShowInfo + { + /** + * Hide video title and uploader before video starts playing. + */ + Hide = 0, + + /** + * Show video title and uploader before video starts playing. + */ + Show = 1 + } + + /** + * Base interface for events triggered by a player. + */ + export interface PlayerEvent + { + /** + * Video player corresponding to the event. + */ + target: Player; + } + + /** + * Event for player state change. + */ + export interface OnStateChangeEvent extends PlayerEvent + { + /** + * New player state. + */ + data: PlayerState; + } + + /** + * Event for playback quality change. + */ + export interface OnPlaybackQualityChangeEvent extends PlayerEvent + { + /** + * New playback quality. + */ + data: string; + } + + /** + * Event for playback rate change. + */ + export interface OnPlaybackRateChangeEvent extends PlayerEvent + { + /** + * New playback rate. + */ + data: number; + } + + /** + * Event for a player error. + */ + export interface OnErrorEvent extends PlayerEvent + { + /** + * Which type of error occurred. + */ + data: PlayerError; + } + + /** + * Handles a player event. + * + * @param event The triggering event. + */ + export interface PlayerEventHandler + { + (event: TEvent): void; + } + + /** + * YouTube player options. + */ + export interface PlayerOptions + { + /** + * Player width. + */ + width?: number; + + /** + * Player height + */ + height?: number; + + /** + * ID of the video to load. + */ + videoId: string; + + /** + * Player parameters. + */ + playerVars?: PlayerVars; + + /** + * Handlers for events fired by the player. + */ + events?: Events; + } + + /** + * Allowed suggested player video qualities. + */ + export type SuggestedVideoQuality = ( + VideoQualityDefault + | VideoQualitySmall + | VideoQualityMedium + | VideoQualityLarge + | VideoQualityHD720 + | VideoQualityHD1080 + | VideoQualityHighRes); + + /** + * Default video quality chosen by YouTube. + */ + export type VideoQualityDefault = "default"; + + /** + * Player height is 240px, and player dimensions are at least 320px by 240px for 4:3 aspect ratio. + */ + export type VideoQualitySmall = "small"; + + /** + * Player height is 360px, and player dimensions are 640px by 360px (for 16:9 aspect ratio) or 480px by 360px (for 4:3 aspect ratio). + */ + export type VideoQualityMedium = "medium"; + + /** + * Player height is 480px, and player dimensions are 853px by 480px (for 16:9 aspect ratio) or 640px by 480px (for 4:3 aspect ratio). + */ + export type VideoQualityLarge = "large"; + + /** + * Player height is 720px, and player dimensions are 1280px by 720px (for 16:9 aspect ratio) or 960px by 720px (for 4:3 aspect ratio). + */ + export type VideoQualityHD720 = "hd720"; + + /** + * Player height is 1080px, and player dimensions are 1920px by 1080px (for 16:9 aspect ratio) or 1440px by 1080px (for 4:3 aspect ratio). + */ + export type VideoQualityHD1080 = "hd1080"; + + /** + * Player height is greater than 1080px, which means that the player's aspect ratio is greater than 1920px by 1080px. + */ + export type VideoQualityHighRes = "highres"; + + /** + * Player parameters. + */ + export interface PlayerVars + { + /** + * Whether to autohide video controls (by default, HideProgressBar). + */ + autohide?: AutoHide; + + /** + * Whether to autoplay the video (by default, NoAutoPlay). + */ + autoplay?: AutoPlay; + + /** + * Whether to use user-preferred or forced caption loading (by default, UserDefault). + */ + cc_load_policy?: ClosedCaptionsLoadPolicy; + + /** + * Player progress bar color + */ + color?: ProgressBarColor; + + /** + * How video controls are shown (by default, ShowLoadPlayer). + */ + controls?: Controls; + + /** + * Whether to allow keyboard controls (by default, Enable). + */ + disablekb?: KeyboardControls; + + /** + * Whether the JavaScript API should be enabled (by default, Disable). + */ + enablejsapi?: JsApi; + + /** + * Time, in seconds from the beginning of the video, when to stop playing. + */ end?: number; - fs?: number; - iv_load_policy?: number; + + /** + * Whether to display the full-screen button (by default, Show). + */ + fs?: FullscreenButton; + + /** + * Player language as an ISO 639-1 two-letter language code or fully-specified locale. + */ + hl?: string; + + /** + * Whether to show video annotations (by default, Show). + */ + iv_load_policy?: IvLoadPolicy; + + /** + * Identifies content that will load. + * If listType is search, this is the search query. + * If listType is user_uploads, this is the YouTube user. + * If listType is playlist, this is the playlist ID, prepended by 'PL'. + */ list?: string; + + /** + * Which type of content loads in the player. + */ listType?: ListType; - loop?: number; - modestbranding?: number; + + /** + * Whether a single video should be looped (by default, SinglePlay). + */ + loop?: Loop; + + /** + * Whether to hide some YouTube branding (by default, Full). + */ + modestbranding?: ModestBranding; + + /** + * Origin domain for additional security if using the JavaScript API. + */ origin?: string; - playerpiid?: string; - playlist?: string[]; - playsinline?: number; - rel?: number; - showinfo?: number; + + /** + * Comma separated list of video IDs to play after the URL path's video. + */ + playlist?: string; + + /** + * Whether to show related videos after the video finishes (by default, Show). + */ + rel?: RelatedVideos; + + /** + * Whether to show video information before playing (by default, Show). + */ + showinfo?: ShowInfo; + + /** + * Time, in seconds from the beginning of the video, when to start playing. + */ start?: number; - theme?: string; - } + } - export interface PlayerOptions { - width?: string | number; - height?: string | number; - videoId?: string; - playerVars?: PlayerVars; - events?: Events; - } + /** + * Handlers for events fired by the player. + */ + export interface Events + { + /** + * Event fired when a player has finished loading and is ready to begin receiving API calls. + */ + onReady?: PlayerEventHandler; - interface VideoByIdParams { - videoId: string; - startSeconds?: number; - endSeconds?: number; - suggestedQuality?: string; - } + /** + * Event fired when the player's state changes. + */ + onStateChange?: PlayerEventHandler; - interface VideoByUrlParams { - mediaContentUrl: string; - startSeconds?: number; - endSeconds?: number; - suggestedQuality?: string; - } + /** + * Event fired when the playback quality of the player changes. + */ + onPlaybackQualityChange?: PlayerEventHandler; - export interface VideoData - { - video_id: string; - author: string; - title: string; - } + /** + * Event fired when the playback rate of the player changes. + */ + onPlaybackRateChange?: PlayerEventHandler; - export class Player { - // Constructor - constructor(id: string, playerOptions: PlayerOptions); - constructor(element: HTMLElement, playerOptions: PlayerOptions); + /** + * Event fired when an error in the player occurs + */ + onError?: PlayerEventHandler; - // Queueing functions - loadVideoById(videoId: string, startSeconds?: number, suggestedQuality?: string): void; - loadVideoById(VideoByIdParams: Object): void; - cueVideoById(videoId: string, startSeconds?: number, suggestedQuality?: string): void; - cueVideoById(VideoByIdParams: Object): void; + /** + * Event fired to indicate thath the player has loaded, or unloaded, a module + * with exposed API methods. This currently only occurs for closed captioning. + */ + onApiChange?: PlayerEventHandler; + } - loadVideoByUrl(mediaContentUrl: string, startSeconds?: number, suggestedQuality?: string): void; - loadVideoByUrl(VideoByUrlParams: Object): void; - cueVideoByUrl(mediaContentUrl: string, startSeconds?: number, suggestedQuality?: string): void; - cueVideoByUrl(VideoByUrlParams: Object): void; + /** + * Settings to load, play, or queue a video or playlist. + */ + export interface VideoOrPlaylistSettings { + /** + * Time, in seconds from the beginning of the (first) video, when to start playing. + */ + startSeconds?: number; - // Properties - size: any; + /** + * Time, in seconds from the end of the (first) video, when to end playing. + */ + endSeconds?: number; - // Playing - playVideo(): void; - pauseVideo(): void; - stopVideo(): void; - seekTo(seconds:number, allowSeekAhead:boolean): void; - clearVideo(): void; + /** + * Suggested video player quality. + */ + suggestedQuality?: SuggestedVideoQuality + } - // Playlist - nextVideo(): void; - previousVideo(): void; - playVideoAt(index: number): void; + /** + * Settings to play or queue a video by ID. + */ + export interface VideoByIdSettings extends VideoOrPlaylistSettings { + /** + * Video ID. + */ + videoId: string; + } - // Volume - mute(): void; - unMute(): void; - isMuted(): boolean; - setVolume(volume: number): void; - getVolume(): number; + /** + * Settings to play or queue a video by media content URL. + */ + export interface VideoByMediaContentUrlSettings extends VideoOrPlaylistSettings { + /** + * Fully qualified player URL. + */ + mediaContentUrl: string; + } - // Sizing - setSize(width: number, height: number): any; + /** + * Settings to load or queue a playlist. + */ + export interface IPlaylistSettings extends VideoOrPlaylistSettings { + /** + * Identifier for the listType videos list. + */ + list: string; - // Playback - getPlaybackRate(): number; - setPlaybackRate(suggestedRate:number): void; - getAvailablePlaybackRates(): number[]; + /** + * Which type of content loads in the player. + */ + listType?: ListType; - // Behavior - setLoop(loopPlaylists: boolean): void; - setShuffle(shufflePlaylist: boolean): void; + /** + * Start index of the playlist, if not 0. + */ + index?: number; + } - // Status - getVideoLoadedFraction(): number; - getPlayerState(): number; - getCurrentTime(): number; - getVideoStartBytes(): number; - getVideoBytesLoaded(): number; - getVideoBytesTotal(): number; + /** + * Creates and controls a YouTube player in an