diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md
index 7ebdcc514f..44f0d8e9a0 100644
--- a/CONTRIBUTORS.md
+++ b/CONTRIBUTORS.md
@@ -401,6 +401,7 @@ This document generated by [dt-contributors-generator](https://github.com/vvakam
* [:link:](egg.js/egg.js.d.ts) [Egg.js](https://github.com/mikeflynn/egg.js) by [Markus Peloso](https://github.com/ToastHawaii)
* [:link:](ejs-locals/ejs-locals.d.ts) [ejs-locals](https://github.com/randometc/ejs-locals) by [jt000](https://github.com/jt000)
* [:link:](ejs/ejs.d.ts) [ejs.js](http://ejs.co) by [Ben Liddicott](https://github.com/benliddicott/DefinitelyTyped)
+* [:link:](elasticsearch/elasticsearch.d.ts) [elasticsearch](https://www.elastic.co) by [Casper Skydt](https://github.com/CasperSkydt/DefinitelyTyped), [Blake Smith](https://github.com/bfsmith/DefinitelyTyped)
* [:link:](jquery.elang/jquery.elang.d.ts) [eLang](https://github.com/sumegizoltan/ELang) by [Zoltan Sumegi](https://github.com/sumegizoltan)
* [:link:](github-electron/github-electron.d.ts) [Electron](http://electron.atom.io) by [jedmao](https://github.com/jedmao), [rhysd](https://rhysd.github.io), [Milan Burda](https://github.com/miniak)
* [:link:](electron-builder/electron-builder.d.ts) [electron-builder](https://github.com/loopline-systems/electron-builder) by [Maxime LUCE](https://github.com/SomaticIT)
diff --git a/algoliasearch-client-js/algoliasearch-client-js-tests.ts b/algoliasearch-client-js/algoliasearch-client-js-tests.ts
new file mode 100644
index 0000000000..f0ccd447c0
--- /dev/null
+++ b/algoliasearch-client-js/algoliasearch-client-js-tests.ts
@@ -0,0 +1,136 @@
+///
+///
+
+var algoliasearch = require('algoliasearch');
+
+var _clientOptions: ClientOptions = {
+ timeout : 12,
+ protocol: "",
+ httpAgent: ""
+};
+
+var _synonymOption: SynonymOption = {
+ forwardToSlaves: false,
+ replaceExistingSynonyms: false
+};
+
+var _algoliaUserKeyOptions : AlgoliaUserKeyOptions = {
+ validity: 0,
+ maxQueriesPerIPPerHour: 0,
+ indexes: [""],
+ queryParameters: { attributesToRetrieve: ["algolia"] },
+ description: ""
+};
+
+var _searchSynonymOptions : SearchSynonymOptions = {
+ query: "",
+ page: 0,
+ type: "",
+ hitsPerPage: 0
+};
+
+var _algoliaSecuredApiOptions: AlgoliaSecuredApiOptions = {
+ filters: "",
+ validUntil: 0,
+ restrictIndices: "",
+ userToken: ""
+};
+
+var _algoliaIndexSettings : AlgoliaIndexSettings = {
+ attributesToIndex: [""],
+ attributesforFaceting: [""],
+ unretrievableAttributes: [""],
+ attributesToRetrieve: [""],
+ ranking: [""],
+ customRanking: [""],
+ slaves: [""],
+ maxValuesPerFacet: '',
+ attributesToHighlight: [""],
+ attributesToSnippet: [""],
+ highlightPreTag: '',
+ highlightPostTag: '',
+ snippetEllipsisText: '',
+ restrictHighlightAndSnippetArrays: false,
+ hitsPerPage: 0,
+ minWordSizefor1Typo: 0,
+ minWordSizefor2Typos: 0,
+ typoTolerance: false,
+ allowTyposOnNumericTokens: false,
+ ignorePlurals: false,
+ disableTypoToleranceOnAttributes: '',
+ separatorsToIndex: '',
+ queryType: '',
+ removeWordsIfNoResults: '',
+ advancedSyntax: false,
+ optionalWords: [""],
+ removeStopWords: [""],
+ disablePrefixOnAttributes: [""],
+ disableExactOnAttributes: [""],
+ exactOnSingleWordQuery: '',
+ alternativesAsExact: false,
+ attributeForDistinct: "",
+ distinct: false,
+ numericAttributesToIndex: [""],
+ allowCompressionOfIntegerArray: false,
+ altCorrections: [{}],
+ minProximity: 0,
+ placeholders: ''
+};
+
+var _algoliaQueryParameters : AlgoliaQueryParameters = {
+ query: '',
+ filters: '',
+ attributesToRetrieve: [""],
+ restrictSearchableAttributes: [""],
+ facets: '',
+ maxValuesPerFacet: '',
+ attributesToHighlight: [''],
+ attributesToSnippet: [''],
+ highlightPreTag: '',
+ highlightPostTag: '',
+ snippetEllipsisText: '',
+ restrictHighlightAndSnippetArrays: false,
+ hitsPerPage: 0,
+ page: 0,
+ offset: 0,
+ length: 0,
+ minWordSizefor1Typo: 0,
+ minWordSizefor2Typos: 0,
+ typoTolerance: false,
+ allowTyposOnNumericTokens: false,
+ ignorePlurals: false,
+ disableTypoToleranceOnAttributes: '',
+ aroundLatLng: '',
+ aroundLatLngViaIP: '',
+ aroundRadius: '',
+ aroundPrecision: 0,
+ minimumAroundRadius: 0,
+ insideBoundingBox: '',
+ queryType: '',
+ insidePolygon: '',
+ removeWordsIfNoResults: '',
+ advancedSyntax: false,
+ optionalWords: [''],
+ removeStopWords: [''],
+ disableExactOnAttributes: [''],
+ exactOnSingleWordQuery: '',
+ alternativesAsExact: true,
+ distinct: 0,
+ getRankingInfo: false,
+ numericAttributesToIndex: [''],
+ numericFilters: [''],
+ tagFilters: '',
+ facetFilters: '',
+ analytics: false,
+ analyticsTags: [''],
+ synonyms: true,
+ replaceSynonymsInHighlight: false,
+ minProximity: 0
+};
+
+var index: AlgoliaIndex = algoliasearch('', '').initIndex('');
+
+var search = index.search({query: ""});
+index.search({query: ""}, function(err, res){});
+
+
diff --git a/algoliasearch-client-js/algoliasearch-client-js.d.ts b/algoliasearch-client-js/algoliasearch-client-js.d.ts
new file mode 100644
index 0000000000..b0eeb9968b
--- /dev/null
+++ b/algoliasearch-client-js/algoliasearch-client-js.d.ts
@@ -0,0 +1,1571 @@
+// Type definitions for algoliasearch-client-js 3.18.1
+// Project: https://github.com/algolia/algoliasearch-client-js
+// Definitions by: Baptiste Coquelle
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+interface AlgoliaResponse {
+ /**
+ * Contains all the hits matching the query
+ * https://github.com/algolia/algoliasearch-client-js#response-format
+ */
+ hits: any[];
+ /**
+ * Current page
+ * https://github.com/algolia/algoliasearch-client-js#response-format
+ */
+ page: number;
+ /**
+ * Number of total hits matching the query
+ * https://github.com/algolia/algoliasearch-client-js#response-format
+ */
+ nbHits: number;
+ /**
+ * Number of pages
+ * https://github.com/algolia/algoliasearch-client-js#response-format
+ */
+ nbPage: number;
+ /**
+ * Number of hits per pages
+ * https://github.com/algolia/algoliasearch-client-js#response-format
+ */
+ hitsPerPage: number;
+ /**
+ * Engine processing time (excluding network transfer)
+ * https://github.com/algolia/algoliasearch-client-js#response-format
+ */
+ processingTimeMS: number;
+ /**
+ * Query used to perform the search
+ * https://github.com/algolia/algoliasearch-client-js#response-format
+ */
+ query: string;
+ /**
+ * GET parameters used to perform the search
+ * https://github.com/algolia/algoliasearch-client-js#response-format
+ */
+ params: string;
+}
+/*
+ Interface for the algolia client object
+ */
+interface AlgoliaClient {
+ /**
+ * Initialization of the index
+ * @param name: index name
+ * return algolia index object
+ * https://github.com/algolia/algoliasearch-client-js#init-index---initindex
+ */
+ initIndex(name: string): AlgoliaIndex;
+ /**
+ * Query on multiple index
+ * @param queries index name, query and query parameters
+ * @param cb callback(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#multiple-queries---multiplequeries
+ */
+ search(queries: { indexName: string, query: string, options: AlgoliaQueryParameters }, cb: (err: Error, res: any) => void): void;
+ /**
+ * Query on multiple index
+ * @param queries index name, query and query parameters
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#multiple-queries---multiplequeries
+ */
+ search(queries: { indexName: string, query: string, options: AlgoliaQueryParameters }): Promise;
+ /**
+ * clear browser cache
+ * https://github.com/algolia/algoliasearch-client-js#cache
+ */
+ clearCache(): void;
+ /**
+ * kill alive connections
+ * https://github.com/algolia/algoliasearch-client-js#keep-alive
+ */
+ destroy(): void;
+ /**
+ * List all your indices along with their associated information (number of entries, disk size, etc.)
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#list-indices---listindexes
+ */
+ listIndexes(cb: (err: Error, res: any) => void): void;
+ /**
+ * List all your indices along with their associated information (number of entries, disk size, etc.)
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#list-indices---listindexes
+ */
+ listIndexes(): Promise;
+ /**
+ * Delete a specific index
+ * @param name
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#delete-index---deleteindex
+ */
+ deleteIndex(name: string, cb: (err: Error, res: any) => void): void;
+ /**
+ * Delete a specific index
+ * @param name
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#delete-index---deleteindex
+ */
+ deleteIndex(name: string): Promise;
+ /**
+ * Copy an index from a specific index to a new one
+ * @param from origin index
+ * @param to destination index
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#copy-index---copyindex
+ */
+ copyIndex(from: string, to: string, cb: (err: Error, res: any) => void): void;
+ /**
+ * Copy an index from a specific index to a new one
+ * @param from origin index
+ * @param to destination index
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#copy-index---copyindex
+ */
+ copyIndex(from: string, to: string): Promise;
+ /**
+ * Move index to a new one (and will overwrite the original one)
+ * @param from origin index
+ * @param to destination index
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#move-index---moveindex
+ */
+ moveIndex(from: string, to: string, cb: (err: Error, res: any) => void): void;
+ /**
+ * Move index to a new one (and will overwrite the original one)
+ * @param from origin index
+ * @param to destination index
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#move-index---moveindex
+ */
+ moveIndex(from: string, to: string): Promise;
+ /**
+ * Generate a public API key
+ * @param key api key
+ * @param filters
+ * https://github.com/algolia/algoliasearch-client-js#generate-key---generatesecuredapikey
+ */
+ generateSecuredApiKey(key: string, filters: AlgoliaSecuredApiOptions): void;
+ /**
+ * Perform multiple operations with one API call to reduce latency
+ * @param action
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#custom-batch---batch
+ */
+ batch(action: AlgoliaAction, cb: (err: Error, res: any) => void): void;
+ /**
+ * Perform multiple operations with one API call to reduce latency
+ * @param action
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#custom-batch---batch
+ */
+ batch(action: AlgoliaAction): Promise;
+ /**
+ * Lists global API Keys
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
+ */
+ listUserKeys(cb: (err: Error, res: any) => void): void;
+ /**
+ * Lists global API Keys
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
+ */
+ listUserKeys(): Promise;
+ /**
+ * Add global API Keys
+ * @param scopes
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey
+ */
+ addUserKey(scopes: string[], cb: (err: Error, res: any) => void): void;
+ /**
+ * Add global API Keys
+ * @param scopes
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey
+ */
+ addUserKey(scopes: string[]): Promise;
+ /**
+ * Add global API Key
+ * @param scopes
+ * @param options
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey
+ */
+ addUserKey(scopes: string[], options: AlgoliaUserKeyOptions, cb: (err: Error, res: any) => void): void;
+ /**
+ * Add global API Key
+ * @param scopes
+ * @param options
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey
+ */
+ addUserKey(scopes: string[], options: AlgoliaUserKeyOptions): Promise;
+ /**
+ * Update global API key
+ * @param key
+ * @param scopes
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateuserkey
+ */
+ updateUserKey(key: string, scopes: string[], cb: (err: Error, res: any) => void): void;
+ /**
+ * Update global API key
+ * @param key
+ * @param scopes
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateuserkey
+ */
+ updateUserKey(key: string, scopes: string[]): Promise;
+ /**
+ * Update global API key
+ * @param key
+ * @param scopes
+ * @param options
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateuserkey
+ */
+ updateUserKey(key: string, scopes: string[], options: AlgoliaUserKeyOptions, cb: (err: Error, res: any) => void): void;
+ /**
+ * Update global API key
+ * @param key
+ * @param scopes
+ * @param options
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateuserkey
+ */
+ updateUserKey(key: string, scopes: string[], options: AlgoliaUserKeyOptions): Promise;
+ /**
+ * Gets the rights of a global key
+ * @param key
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateuserkey
+ */
+ getUserKeyACL(key: string, cb: (err: Error, res: any) => void): void;
+ /**
+ * Gets the rights of a global key
+ * @param key
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateuserkey
+ */
+ getUserKeyACL(key: string): Promise;
+ /**
+ * Deletes a global key
+ * @param key
+ * @param cb(err,res)
+ * https://github.com/algolia/algoliasearch-client-js#delete-user-key---deleteuserkey
+ */
+ deleteUserKey(key: string, cb: (err: Error, res: any) => void): void;
+ /**
+ * Deletes a global key
+ * @param key
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#delete-user-key---deleteuserkey
+ */
+ deleteUserKey(key: string): Promise;
+ /**
+ * Get 1000 last events
+ * @param options
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#get-logs---getlogs
+ */
+ getLogs(options: LogsOptions, cb: (err: Error, res: any) => void): void;
+ /**
+ * Get 1000 last events
+ * @param options
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#get-logs---getlogs
+ */
+ getLogs(options: LogsOptions): Promise;
+}
+/**
+ * Interface for the index algolia object
+ */
+interface AlgoliaIndex {
+ /**
+ * Gets a specific object
+ * @param objectID
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects
+ */
+ getObject(objectID: string, cb: (err: Error, res: any) => void): void;
+ /**
+ * Gets specific attributes from an object
+ * @param objectID
+ * @param attributes
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects
+ */
+ getObject(objectID: string, attributes: string[], cb: (err: Error, res: any) => void): void;
+ /**
+ * Gets a list of objects
+ * @param objectIDs
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects
+ */
+ getObjects(objectIDs: string[], cb: (err: Error, res: any) => void): void;
+ /**
+ * Add a specific object
+ * @param object without objectID
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#add-objects---addobjects
+ */
+ addObject(object: {}, cb: (err: Error, res: any) => void): void;
+ /**
+ * Add a list of objects
+ * @param object with objectID
+ * @param objectID
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#add-objects---addobjects
+ */
+ addObject(object: {}, objectID: string, cb: (err: Error, res: any) => void): void;
+ /**
+ * Add list of objects
+ * @param objects
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#add-objects---addobjects
+ */
+ addObjects(objects: [{}], cb: (err: Error, res: any) => void): void;
+ /**
+ * Add or replace a specific object
+ * @param object
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects
+ */
+ saveObject(object: {}, cb: (err: Error, res: any) => void): void;
+ /**
+ * Add or replace several objects
+ * @param objects
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects
+ */
+ saveObjects(objects: [{}], cb: (err: Error, res: any) => void): void;
+ /**
+ * Update parameters of a specific object
+ * @param object
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects
+ */
+ partialUpdateObject(object: {}, cb: (err: Error, res: any) => void): void;
+ /**
+ * Update parameters of a list of objects
+ * @param objects
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects
+ */
+ partialUpdateObjects(objects: [{}], cb: (err: Error, res: any) => void): void;
+ /**
+ * Delete a specific object
+ * @param objectID
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#delete-objects---deleteobjects
+ */
+ deleteObject(objectID: string, cb: (err: Error, res: any) => void): void;
+ /**
+ * Delete a list of objects
+ * @param objectIDs
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#delete-objects---deleteobjects
+ */
+ deleteObjects(objectIDs: string[], cb: (err: Error, res: any) => void): void;
+ /**
+ * Delete objects that matches the query
+ * @param query
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#delete-by-query---deletebyquery
+ */
+ deleteByQuery(query: string, cb: (err: Error, res: any) => void): void;
+ /**
+ * Delete objects that matches the query
+ * @param query
+ * @param params of the object
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#delete-by-query---deletebyquery
+ */
+ deleteByQuery(query: string, params: {}, cb: (err: Error, res: any) => void): void;
+ /**
+ * Wait for an indexing task to be compete
+ * @param taskID
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#wait-for-operations---waittask
+ */
+ waitTask(taskID: number, cb: (err: Error, res: any) => void): void;
+ /**
+ * Get an index settings
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#get-settings---getsettings
+ */
+ getSettings(cb: (err: Error, res: any) => void): void;
+ /**
+ * Set an index settings
+ * @param settings
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#set-settings---setsettings
+ */
+ setSettings(settings: AlgoliaIndexSettings, cb: (err: Error, res: any) => void): void;
+ /**
+ * Clear cache of an index
+ * https://github.com/algolia/algoliasearch-client-js#cache
+ */
+ clearCache(): void;
+ /**
+ * Clear an index content
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#clear-index---clearindex
+ */
+ clearIndex(cb: (err: Error, res: any) => void): void;
+ /**
+ * Save a synonym object
+ * @param synonym
+ * @param options
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#save-synonym---savesynonym
+ */
+ saveSynonym(synonym: AlgoliaSynonym, option: SynonymOption, cb: (err: Error, res: any) => void): void;
+ /**
+ * Save a synonym object
+ * @param synonyms
+ * @param options
+ * @param cb(err, res)
+ */
+ batchSynonyms(synonyms: AlgoliaSynonym[], options: SynonymOption, cb: (err: Error, res: any) => void): void;
+ /**
+ * Delete a specific synonym
+ * @param identifier
+ * @param options
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#batch-synonyms---batchsynonyms
+ */
+ deleteSynonym(identifier: string, options: SynonymOption, cb: (err: Error, res: any) => void): void;
+ /**
+ * Clear all synonyms of an index
+ * @param options
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#clear-all-synonyms---clearsynonyms
+ */
+ clearSynonyms(options: SynonymOption, cb: (err: Error, res: any) => void): void;
+ /**
+ * Get a specific synonym
+ * @param identifier
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#get-synonym---getsynonym
+ */
+ getSynonym(identifier: string, cb: (err: Error, res: any) => void): void;
+ /**
+ * Search a synonyms
+ * @param options
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms
+ */
+ searchSynonyms(options: SearchSynonymOptions, cb: (err: Error, res: any) => void): void;
+ /**
+ * List index user keys
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#list-api-keys---listapikeys
+ */
+ listUserKeys(cb: (err: Error, res: any) => void): void;
+ /**
+ * Add key for this index
+ * @param scopes
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey
+ */
+ addUserKey(scopes: string[], cb: (err: Error, res: any) => void): void;
+ /**
+ * Add key for this index
+ * @param scopes
+ * @param options
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey
+ */
+ addUserKey(scopes: string[], options: AlgoliaUserKeyOptions, cb: (err: Error, res: any) => void): void;
+ /**
+ * Update a key for this index
+ * @param key
+ * @param scopes
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateuserkey
+ */
+ updateUserKey(key: string, scopes: string[], cb: (err: Error, res: any) => void): void;
+ /**
+ * Update a key for this index
+ * @param key
+ * @param scopes
+ * @param options
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateuserkey
+ */
+ updateUserKey(key: string, scopes: string[], options: AlgoliaUserKeyOptions, cb: (err: Error, res: any) => void): void;
+ /**
+ * Gets the rights of an index specific key
+ * @param key
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#get-key-permissions---getuserkeyacl
+ */
+ getUserKeyACL(key: string, cb: (err: Error, res: any) => void): void;
+ /**
+ * Deletes an index specific key
+ * @param key
+ * @param cb(err, res)
+ * https://github.com/algolia/algoliasearch-client-js#delete-user-key---deleteuserkey
+ */
+ deleteUserKey(key: string, cb: (err: Error, res: any) => void): void;
+ /**
+ * Gets a specific object
+ * @param objectID
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects
+ */
+ getObject(objectID: string): Promise ;
+ /**
+ * Gets specific attributes from an object
+ * @param objectID
+ * @param attributes
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects
+ */
+ getObject(objectID: string, attributes: string[]): Promise ;
+ /**
+ * Gets a list of objects
+ * @param objectIDs
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#find-by-ids---getobjects
+ */
+ getObjects(objectIDs: string[]): Promise ;
+ /**
+ * Add a specific object
+ * @param object without objectID
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#add-objects---addobjects
+ */
+ addObject(object: {}): Promise ;
+ /**
+ * Add a list of objects
+ * @param object with objectID
+ * @param objectID
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#add-objects---addobjects
+ */
+ addObject(object: {}, objectID: string): Promise ;
+ /**
+ * Add list of objects
+ * @param objects
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#add-objects---addobjects
+ */
+ addObjects(objects: [{}]): Promise ;
+ /**
+ * Add or replace a specific object
+ * @param object
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects
+ */
+ saveObject(object: {}): Promise ;
+ /**
+ * Add or replace several objects
+ * @param objects
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects
+ */
+ saveObjects(objects: [{}]): Promise ;
+ /**
+ * Update parameters of a specific object
+ * @param object
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects
+ */
+ partialUpdateObject(object: {}): Promise ;
+ /**
+ * Update parameters of a list of objects
+ * @param objects
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#update-objects---saveobjects
+ */
+ partialUpdateObjects(objects: [{}]): Promise ;
+ /**
+ * Delete a specific object
+ * @param objectID
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#delete-objects---deleteobjects
+ */
+ deleteObject(objectID: string): Promise ;
+ /**
+ * Delete a list of objects
+ * @param objectIDs
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#delete-objects---deleteobjects
+ */
+ deleteObjects(objectIDs: string[]): Promise ;
+ /**
+ * Delete objects that matches the query
+ * @param query
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#delete-by-query---deletebyquery
+ */
+ deleteByQuery(query: string): Promise ;
+ /**
+ * Delete objects that matches the query
+ * @param query
+ * @param params of the object
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#delete-by-query---deletebyquery
+ */
+ deleteByQuery(query: string, params: {}): Promise ;
+ /**
+ * Wait for an indexing task to be compete
+ * @param taskID
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#wait-for-operations---waittask
+ */
+ waitTask(taskID: number): Promise ;
+ /**
+ * Get an index settings
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#get-settings---getsettings
+ */
+ getSettings(): Promise ;
+ /**
+ * Set an index settings
+ * @param settings
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#set-settings---setsettings
+ */
+ setSettings(settings: AlgoliaIndexSettings): Promise ;
+ /**
+ * Search in an index
+ * @param params query parameter
+ * return {Promise}
+ * @param err() error callback
+ * https://github.com/algolia/algoliasearch-client-js#search-in-an-index---search
+ */
+ search(params: AlgoliaQueryParameters): Promise ;
+ /**
+ * Search in an index
+ * @param params query parameter
+ * @param cb(err, res)
+ * @param err() error callback
+ * https://github.com/algolia/algoliasearch-client-js#search-in-an-index---search
+ */
+ search(params: AlgoliaQueryParameters, cb: (err: Error, res: any) => void): void;
+ /**
+ * Browse an index
+ * @param query
+ * @param cb(err, content)
+ * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
+ */
+ browse(query: string, cb: (err: Error, res: any) => void): void;
+ /**
+ * Browse an index
+ * @param query
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
+ */
+ browse(query: string): Promise;
+ /**
+ * Browse an index from a cursor
+ * @param cursor
+ * @param cb(err, content)
+ * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
+ */
+ browseFrom(cursor: string, cb: (err: Error, res: any) => void): void;
+ /**
+ * Browse an index from a cursor
+ * @param cursor
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
+ */
+ browseFrom(cursor: string): Promise;
+ /**
+ * Browse an entire index
+ * return Promise
+ * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse
+ */
+ browseAll(): Promise;
+ /**
+ * Clear an index content
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#clear-index---clearindex
+ */
+ clearIndex(): Promise ;
+ /**
+ * Save a synonym object
+ * @param synonym
+ * @param options
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#save-synonym---savesynonym
+ */
+ saveSynonym(synonym: AlgoliaSynonym, option: SynonymOption): Promise ;
+ /**
+ * Save a synonym object
+ * @param synonyms
+ * @param options
+ * return {Promise}
+ */
+ batchSynonyms(synonyms: AlgoliaSynonym[], options: SynonymOption): Promise ;
+ /**
+ * Delete a specific synonym
+ * @param identifier
+ * @param options
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#batch-synonyms---batchsynonyms
+ */
+ deleteSynonym(identifier: string, options: SynonymOption): Promise ;
+ /**
+ * Clear all synonyms of an index
+ * @param options
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#clear-all-synonyms---clearsynonyms
+ */
+ clearSynonyms(options: SynonymOption): Promise ;
+ /**
+ * Get a specific synonym
+ * @param identifier
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#get-synonym---getsynonym
+ */
+ getSynonym(identifier: string): Promise ;
+ /**
+ * Search a synonyms
+ * @param options
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms
+ */
+ searchSynonyms(options: SearchSynonymOptions): Promise ;
+ /**
+ * List index user keys
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#list-api-keys---listapikeys
+ */
+ listUserKeys(): Promise ;
+ /**
+ * Add key for this index
+ * @param scopes
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey
+ */
+ addUserKey(scopes: string[]): Promise ;
+ /**
+ * Add key for this index
+ * @param scopes
+ * @param options
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey
+ */
+ addUserKey(scopes: string[], options: AlgoliaUserKeyOptions): Promise ;
+ /**
+ * Update a key for this index
+ * @param key
+ * @param scopes
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateuserkey
+ */
+ updateUserKey(key: string, scopes: string[]): Promise ;
+ /**
+ * Update a key for this index
+ * @param key
+ * @param scopes
+ * @param options
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#update-user-key---updateuserkey
+ */
+ updateUserKey(key: string, scopes: string[], options: AlgoliaUserKeyOptions): Promise ;
+ /**
+ * Gets the rights of an index specific key
+ * @param key
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#get-key-permissions---getuserkeyacl
+ */
+ getUserKeyACL(key: string): Promise ;
+ /**
+ * Deletes an index specific key
+ * @param key
+ * return {Promise}
+ * https://github.com/algolia/algoliasearch-client-js#delete-user-key---deleteuserkey
+ */
+ deleteUserKey(key: string): Promise ;
+}
+/*
+ Interface describing available options when initializing a client
+ */
+interface ClientOptions {
+ /**
+ * Timeout for requests to our servers, in milliseconds
+ * default: 15s (node), 2s (browser)
+ * https://github.com/algolia/algoliasearch-client-js#client-options
+ */
+ timeout?: number;
+ /**
+ * Protocol to use when communicating with algolia
+ * default: current protocol(browser), https(node)
+ * https://github.com/algolia/algoliasearch-client-js#client-options
+ */
+ protocol?: string;
+ /**
+ * (node only) httpAgent instance to use when communicating with Algolia servers.
+ * https://github.com/algolia/algoliasearch-client-js#client-options
+ */
+ httpAgent?: any;
+ /**
+ * read: array of read hosts to use to call Algolia servers, computed automatically
+ * write: array of read hosts to use to call Algolia servers, computed automatically
+ * https://github.com/algolia/algoliasearch-client-js#client-options
+ */
+ hosts?: { read?: string[], write?: string[] };
+}
+/*
+ Interface describing options available for gettings the logs
+ */
+interface LogsOptions {
+ /**
+ * Specify the first entry to retrieve (0-based, 0 is the most recent log entry).
+ * default: 0
+ * https://github.com/algolia/algoliasearch-client-js#get-logs---getlogs
+ */
+ offset?: number;
+ /**
+ * Specify the maximum number of entries to retrieve starting at the offset.
+ * default: 10
+ * maximum: 1000
+ * https://github.com/algolia/algoliasearch-client-js#get-logs---getlogs
+ */
+ length?: number;
+ /**
+ * @deprecated
+ * Retrieve only logs with an HTTP code different than 200 or 201
+ * https://github.com/algolia/algoliasearch-client-js#get-logs---getlogs
+ */
+ onlyErrors?: boolean;
+ /**
+ * Specify the type of logs to retrieve
+ * 'query' Retrieve only the queries
+ * 'build' Retrieve only the build operations
+ * 'error' Retrieve only the errors (same as onlyErrors parameters)
+ * https://github.com/algolia/algoliasearch-client-js#get-logs---getlogs
+ */
+ type?: string;
+}
+/**
+ * Describe the action object used for batch operation
+ */
+interface AlgoliaAction {
+ /**
+ * Type of the batch action
+ * values: addObject, updateObject, partialUpdateObject, partialUpdateObjectNoCreate, deleteObject
+ * https://github.com/algolia/algoliasearch-client-js#custom-batch---batch
+ */
+ action: string;
+ /**
+ * Name of the index where the bact will be performed
+ * https://github.com/algolia/algoliasearch-client-js#custom-batch---batch
+ */
+ indexName: string;
+ /**
+ * Object
+ * https://github.com/algolia/algoliasearch-client-js#custom-batch---batch
+ */
+ body: {};
+}
+/**
+ * Describes the option used when creating user key
+ */
+interface AlgoliaUserKeyOptions {
+ /**
+ * Add a validity period. The key will be valid for a specific period of time (in seconds).
+ * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey
+ */
+ validity?: number;
+ /**
+ * Specify the maximum number of API calls allowed from an IP address per hour
+ * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey
+ */
+ maxQueriesPerIPPerHour?: number;
+ /**
+ * Specify the maximum number of hits this API key can retrieve in one call
+ * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey
+ */
+ maxHitsPerQuery?: boolean;
+ /**
+ * Specify the list of targeted indices
+ * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey
+ */
+ indexes?: string[];
+ /**
+ * Specify the list of referers
+ * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey
+ */
+ referers?: string[];
+ /**
+ * Specify the list of query parameters
+ * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey
+ */
+ queryParameters?: AlgoliaQueryParameters;
+ /**
+ * Specify a description to describe where the key is used.
+ * https://github.com/algolia/algoliasearch-client-js#add-user-key---adduserkey
+ */
+ description?: string;
+}
+/**
+ * Describes option used when making operation on synonyms
+ */
+interface SynonymOption {
+ /**
+ * You can forward all settings updates to the slaves of an index
+ * https://github.com/algolia/algoliasearch-client-js#slave-settings
+ */
+ forwardToSlaves?: boolean;
+ /**
+ * Replace all existing synonyms on the index with the content of the batch
+ * https://github.com/algolia/algoliasearch-client-js#batch-synonyms---batchsynonyms
+ */
+ replaceExistingSynonyms?: boolean;
+}
+/**
+ * Describes options used when searching for synonyms
+ */
+interface SearchSynonymOptions {
+ /**
+ * The actual search query to find synonyms
+ * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms
+ */
+ query?: string;
+ /**
+ * The page to fetch when browsing through several pages of results
+ * default: 100
+ * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms
+ */
+ page?: number;
+ /**
+ * Restrict the search to a specific type of synonym
+ * Use an empty string to search all types (default behavior)
+ * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms
+ */
+ type?: string;
+ /**
+ * Number of hits per page
+ * default: 100
+ * https://github.com/algolia/algoliasearch-client-js#search-synonyms---searchsynonyms
+ */
+ hitsPerPage?: number
+}
+interface AlgoliaBrowseResponse {
+ cursor?: string,
+ hits: any[],
+ params: string,
+ query: string,
+ processingTimeMS: number
+}
+/**
+ * Describes a synonym object
+ */
+interface AlgoliaSynonym {
+ /**
+ * ObjectID of the synonym
+ * https://github.com/algolia/algoliasearch-client-js#save-synonym---savesynonym
+ */
+ objectID: string;
+ /**
+ * Type of synonym
+ * values: synonym,oneWaySynonym
+ * https://github.com/algolia/algoliasearch-client-js#save-synonym---savesynonym
+ */
+ type: string;
+ /**
+ * Values used for the synonym
+ * https://github.com/algolia/algoliasearch-client-js#save-synonym---savesynonym
+ */
+ synonyms: string[];
+}
+/**
+ * Describes the options used when generating new api keys
+ */
+interface AlgoliaSecuredApiOptions {
+ /**
+ * Filter the query with numeric, facet or/and tag filters
+ * default: ""
+ * https://github.com/algolia/algoliasearch-client-js#filters-1
+ */
+ filters?: string;
+ /**
+ * Defines the expiration date of the API key
+ * https://github.com/algolia/algoliasearch-client-js#valid-until
+ */
+ validUntil?: number;
+ /**
+ * Restricts the key to a list of index names allowed for the secured API key
+ * https://github.com/algolia/algoliasearch-client-js#index-restriction
+ */
+ restrictIndices?: string;
+ /**
+ * Allows you to restrict a single user to performing a maximum of N API calls per hour
+ * https://github.com/algolia/algoliasearch-client-js#user-rate-limiting
+ */
+ userToken?: string;
+}
+
+/**
+ * Describes the settings available for configure your index
+ */
+interface AlgoliaIndexSettings {
+ /**
+ * The list of attributes you want index
+ * default: *
+ * https://github.com/algolia/algoliasearch-client-js#attributestoindex
+ */
+ attributesToIndex?: string[];
+ /**
+ * The list of attributes you want to use for faceting
+ * default: null
+ * https://github.com/algolia/algoliasearch-client-js#attributesforfaceting
+ */
+ attributesforFaceting?: string[];
+ /**
+ * The list of attributes that cannot be retrieved at query time
+ * default: null
+ * https://github.com/algolia/algoliasearch-client-js#unretrievableattributes
+ */
+ unretrievableAttributes?: string[];
+ /**
+ * A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer
+ * default: *
+ * https://github.com/algolia/algoliasearch-client-js#attributestoretrieve
+ */
+ attributesToRetrieve?: string[];
+ /**
+ * Controls the way results are sorted
+ * default: ['typo', 'geo', 'words', 'filters', 'proximity', 'attribute', 'exact', 'custom']
+ * https://github.com/algolia/algoliasearch-client-js#ranking
+ */
+ ranking?: string[];
+ /**
+ * Lets you specify part of the ranking
+ * default: []
+ * https://github.com/algolia/algoliasearch-client-js#customranking
+ */
+ customRanking?: string[];
+ /**
+ * The list of indices on which you want to replicate all write operations
+ * default: []
+ * https://github.com/algolia/algoliasearch-client-js#slaves
+ */
+ slaves?: string[];
+ /**
+ * Limit the number of facet values returned for each facet
+ * default: ""
+ * https://github.com/algolia/algoliasearch-client-js#maxvaluesperfacet
+ */
+ maxValuesPerFacet?: string;
+ /**
+ * Default list of attributes to highlight. If set to null, all indexed attributes are highlighted.
+ * default: null
+ * https://github.com/algolia/algoliasearch-client-js#attributestohighlight
+ */
+ attributesToHighlight?: string[];
+ /**
+ * Default list of attributes to snippet alongside the number of words to return
+ * default: null
+ * https://github.com/algolia/algoliasearch-client-js#attributestosnippet
+ */
+ attributesToSnippet?: string[];
+ /**
+ * Specify the string that is inserted before the highlighted parts in the query result
+ * default:
+ * https://github.com/algolia/algoliasearch-client-js#highlightpretag
+ */
+ highlightPreTag?: string;
+ /**
+ * Specify the string that is inserted after the highlighted parts in the query result
+ * default:
+ * https://github.com/algolia/algoliasearch-client-js#highlightposttag
+ */
+ highlightPostTag?: string;
+ /**
+ * String used as an ellipsis indicator when a snippet is truncated.
+ * default: …
+ * https://github.com/algolia/algoliasearch-client-js#snippetellipsistext
+ */
+ snippetEllipsisText?: string;
+ /**
+ * If set to true, restrict arrays in highlights and snippets to items that matched the query at least partially else return all array items in highlights and snippets
+ * default: false
+ * https://github.com/algolia/algoliasearch-client-js#restricthighlightandsnippetarrays
+ */
+ restrictHighlightAndSnippetArrays?: boolean;
+ /**
+ * Pagination parameter used to select the number of hits per page
+ * default: 20
+ * https://github.com/algolia/algoliasearch-client-js#hitsperpage
+ */
+ hitsPerPage?: number;
+ /**
+ * The minimum number of characters needed to accept one typo
+ * default: 4
+ * https://github.com/algolia/algoliasearch-client-js#minwordsizefor1typo
+ */
+ minWordSizefor1Typo?: number;
+ /**
+ * The minimum number of characters needed to accept two typos.
+ * default: 8
+ * https://github.com/algolia/algoliasearch-client-js#highlightposttag
+ */
+ minWordSizefor2Typos?: number;
+ /**
+ * This option allows you to control the number of typos allowed in the result set
+ * default: true
+ * 'true' The typo tolerance is enabled and all matching hits are retrieved (default behavior).
+ * 'false' The typo tolerance is disabled. All results with typos will be hidden.
+ * 'min' Only keep results with the minimum number of typos. For example, if one result matches without typos, then all results with typos will be hidden.
+ * 'strict' Hits matching with 2 typos are not retrieved if there are some matching without typos.
+ * https://github.com/algolia/algoliasearch-client-js#typotolerance
+ */
+ typoTolerance?: any;
+ /**
+ * If set to false, disables typo tolerance on numeric tokens (numbers).
+ * default: true
+ * https://github.com/algolia/algoliasearch-client-js#allowtyposonnumerictokens
+ */
+ allowTyposOnNumericTokens?: boolean;
+ /**
+ * If set to true, plural won't be considered as a typo
+ * default: false
+ * https://github.com/algolia/algoliasearch-client-js#ignoreplurals
+ */
+ ignorePlurals?: boolean;
+ /**
+ * List of attributes on which you want to disable typo tolerance
+ * default: ""
+ * https://github.com/algolia/algoliasearch-client-js#disabletypotoleranceonattributes
+ */
+ disableTypoToleranceOnAttributes?: string;
+ /**
+ * Specify the separators (punctuation characters) to index.
+ * default: ""
+ * https://github.com/algolia/algoliasearch-client-js#separatorstoindex
+ */
+ separatorsToIndex?: string;
+ /**
+ * Selects how the query words are interpreted
+ * default: 'prefixLast'
+ * 'prefixAll' All query words are interpreted as prefixes. This option is not recommended.
+ * 'prefixLast' Only the last word is interpreted as a prefix (default behavior).
+ * 'prefixNone' No query word is interpreted as a prefix. This option is not recommended.
+ * https://github.com/algolia/algoliasearch-client-js#querytype
+ */
+ queryType?: any;
+ /**
+ * This option is used to select a strategy in order to avoid having an empty result page
+ * default: 'none'
+ * 'lastWords' When a query does not return any results, the last word will be added as optional
+ * 'firstWords' When a query does not return any results, the first word will be added as optional
+ * 'allOptional' When a query does not return any results, a second trial will be made with all words as optional
+ * 'none' No specific processing is done when a query does not return any results
+ * https://github.com/algolia/algoliasearch-client-js#removewordsifnoresults
+ */
+ removeWordsIfNoResults?: string;
+ /**
+ * Enables the advanced query syntax
+ * default: false
+ * https://github.com/algolia/algoliasearch-client-js#advancedsyntax
+ */
+ advancedSyntax?: boolean;
+ /**
+ * A string that contains the comma separated list of words that should be considered as optional when found in the query
+ * default: []
+ * https://github.com/algolia/algoliasearch-client-js#optionalwords
+ */
+ optionalWords?: string[];
+ /**
+ * Remove stop words from the query before executing it
+ * default: false
+ * true|false: enable or disable stop words for all 41 supported languages; or
+ * a list of language ISO codes (as a comma-separated string) for which stop words should be enable
+ * https://github.com/algolia/algoliasearch-client-js#removestopwords
+ */
+ removeStopWords?: string[];
+ /**
+ * List of attributes on which you want to disable prefix matching
+ * default: []
+ * https://github.com/algolia/algoliasearch-client-js#disableprefixonattributes
+ */
+ disablePrefixOnAttributes?: string[];
+ /**
+ * List of attributes on which you want to disable the computation of exact criteria
+ * default: []
+ * https://github.com/algolia/algoliasearch-client-js#disableexactonattributes
+ */
+ disableExactOnAttributes?: string[];
+ /**
+ * This parameter control how the exact ranking criterion is computed when the query contains one word
+ * default: attribute
+ * 'none': no exact on single word query
+ * 'word': exact set to 1 if the query word is found in the record
+ * 'attribute': exact set to 1 if there is an attribute containing a string equals to the query
+ * https://github.com/algolia/algoliasearch-client-js#exactonsinglewordquery
+ */
+ exactOnSingleWordQuery?: string;
+ /**
+ * Specify the list of approximation that should be considered as an exact match in the ranking formula
+ * default: ['ignorePlurals', 'singleWordSynonym']
+ * 'ignorePlurals': alternative words added by the ignorePlurals feature
+ * 'singleWordSynonym': single-word synonym (For example "NY" = "NYC")
+ * 'multiWordsSynonym': multiple-words synonym
+ * https://github.com/algolia/algoliasearch-client-js#alternativesasexact
+ */
+ alternativesAsExact?: any;
+ /**
+ * The name of the attribute used for the Distinct feature
+ * default: null
+ * https://github.com/algolia/algoliasearch-client-js#attributefordistinct
+ */
+ attributeForDistinct?: string;
+ /**
+ * If set to 1, enables the distinct feature, disabled by default, if the attributeForDistinct index setting is set.
+ * https://github.com/algolia/algoliasearch-client-js#distinct
+ */
+ distinct?: any;
+ /**
+ * All numerical attributes are automatically indexed as numerical filters
+ * default ''
+ * https://github.com/algolia/algoliasearch-client-js#numericattributestoindex
+ */
+ numericAttributesToIndex?: string[];
+ /**
+ * Allows compression of big integer arrays.
+ * default: false
+ * https://github.com/algolia/algoliasearch-client-js#allowcompressionofintegerarray
+ */
+ allowCompressionOfIntegerArray?: boolean;
+ /**
+ * Specify alternative corrections that you want to consider.
+ * default: []
+ * https://github.com/algolia/algoliasearch-client-js#altcorrections
+ */
+ altCorrections?: [{}];
+ /**
+ * Configure the precision of the proximity ranking criterion
+ * default: 1
+ * https://github.com/algolia/algoliasearch-client-js#minproximity
+ */
+ minProximity?: number;
+ /**
+ * This is an advanced use-case to define a token substitutable by a list of words without having the original token searchable
+ * default: ''
+ * https://github.com/algolia/algoliasearch-client-js#placeholders
+ */
+ placeholders?: any;
+}
+
+interface AlgoliaQueryParameters {
+ /**
+ * Query string used to perform the search
+ * default: ''
+ * https://github.com/algolia/algoliasearch-client-js#query
+ */
+ query?: string;
+ /**
+ * Filter the query with numeric, facet or/and tag filters
+ * default: ""
+ * https://github.com/algolia/algoliasearch-client-js#filters
+ */
+ filters?: string;
+ /**
+ * A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer.
+ * default: *
+ * https://github.com/algolia/algoliasearch-client-js#attributestoretrieve
+ */
+ attributesToRetrieve?: string[];
+ /**
+ * List of attributes you want to use for textual search
+ * default: attributeToIndex
+ * https://github.com/algolia/algoliasearch-client-js#restrictsearchableattributes
+ */
+ restrictSearchableAttributes?: string[];
+ /**
+ * You can use facets to retrieve only a part of your attributes declared in attributesForFaceting attributes
+ * default: ""
+ * https://github.com/algolia/algoliasearch-client-js#facets
+ */
+ facets?: string;
+ /**
+ * Limit the number of facet values returned for each facet.
+ * default: ""
+ * https://github.com/algolia/algoliasearch-client-js#maxvaluesperfacet
+ */
+ maxValuesPerFacet?: string;
+ /**
+ * Default list of attributes to highlight. If set to null, all indexed attributes are highlighted.
+ * default: null
+ * https://github.com/algolia/algoliasearch-client-js#attributestohighlight
+ */
+ attributesToHighlight?: string[];
+ /**
+ * Default list of attributes to snippet alongside the number of words to return
+ * default: null
+ * https://github.com/algolia/algoliasearch-client-js#attributestosnippet
+ */
+ attributesToSnippet?: string[];
+ /**
+ * Specify the string that is inserted before the highlighted parts in the query result
+ * default:
+ * https://github.com/algolia/algoliasearch-client-js#highlightpretag
+ */
+ highlightPreTag?: string;
+ /**
+ * Specify the string that is inserted after the highlighted parts in the query result
+ * default:
+ * https://github.com/algolia/algoliasearch-client-js#highlightposttag
+ */
+ highlightPostTag?: string;
+ /**
+ * String used as an ellipsis indicator when a snippet is truncated.
+ * default: …
+ * https://github.com/algolia/algoliasearch-client-js#snippetellipsistext
+ */
+ snippetEllipsisText?: string;
+ /**
+ * If set to true, restrict arrays in highlights and snippets to items that matched the query at least partially else return all array items in highlights and snippets
+ * default: false
+ * https://github.com/algolia/algoliasearch-client-js#restricthighlightandsnippetarrays
+ */
+ restrictHighlightAndSnippetArrays?: boolean;
+ /**
+ * Pagination parameter used to select the number of hits per page
+ * default: 20
+ * https://github.com/algolia/algoliasearch-client-js#hitsperpage
+ */
+ hitsPerPage?: number;
+ /**
+ * Pagination parameter used to select the page to retrieve.
+ * default: 0
+ * https://github.com/algolia/algoliasearch-client-js#page
+ */
+ page?: number;
+ /**
+ * Offset of the first hit to return
+ * default: null
+ * https://github.com/algolia/algoliasearch-client-js#offset
+ */
+ offset?: number;
+ /**
+ * Number of hits to return.
+ * default: null
+ * https://github.com/algolia/algoliasearch-client-js#length
+ */
+ length?: number;
+ /**
+ * The minimum number of characters needed to accept one typo.
+ * default: 4
+ * https://github.com/algolia/algoliasearch-client-js#minwordsizefor1typo
+ */
+ minWordSizefor1Typo?: number;
+ /**
+ * The minimum number of characters needed to accept two typo.
+ * fault: 8
+ * https://github.com/algolia/algoliasearch-client-js#minwordsizefor2typos
+ */
+ minWordSizefor2Typos?: number;
+ /**
+ * This option allows you to control the number of typos allowed in the result set:
+ * default: true
+ * 'true' The typo tolerance is enabled and all matching hits are retrieved
+ * 'false' The typo tolerance is disabled. All results with typos will be hidden.
+ * 'min' Only keep results with the minimum number of typos
+ * 'strict' Hits matching with 2 typos are not retrieved if there are some matching without typos.
+ * https://github.com/algolia/algoliasearch-client-js#minwordsizefor2typos
+ */
+ typoTolerance?: boolean;
+ /**
+ * If set to false, disables typo tolerance on numeric tokens (numbers).
+ * default:
+ * https://github.com/algolia/algoliasearch-client-js#allowtyposonnumerictokens
+ */
+ allowTyposOnNumericTokens?: boolean;
+ /**
+ * If set to true, plural won't be considered as a typo
+ * default: false
+ * https://github.com/algolia/algoliasearch-client-js#ignoreplurals
+ */
+ ignorePlurals?: boolean;
+ /**
+ * List of attributes on which you want to disable typo tolerance
+ * default: ""
+ * https://github.com/algolia/algoliasearch-client-js#disabletypotoleranceonattributes
+ */
+ disableTypoToleranceOnAttributes?: string;
+ /**
+ * Search for entries around a given location
+ * default: ""
+ * https://github.com/algolia/algoliasearch-client-js#aroundlatlng
+ */
+ aroundLatLng?: string;
+ /**
+ * Search for entries around a given latitude/longitude automatically computed from user IP address.
+ * default: ""
+ * https://github.com/algolia/algoliasearch-client-js#aroundlatlngviaip
+ */
+ aroundLatLngViaIP?: string;
+ /**
+ * Control the radius associated with a geo search. Defined in meters.
+ * default: null
+ * You can specify aroundRadius=all if you want to compute the geo distance without filtering in a geo area
+ * https://github.com/algolia/algoliasearch-client-js#aroundradius
+ */
+ aroundRadius?: any;
+ /**
+ * Control the precision of a geo search
+ * default: null
+ * https://github.com/algolia/algoliasearch-client-js#aroundprecision
+ */
+ aroundPrecision?: number;
+ /**
+ * Define the minimum radius used for a geo search when aroundRadius is not set.
+ * default: null
+ * https://github.com/algolia/algoliasearch-client-js#minimumaroundradius
+ */
+ minimumAroundRadius?: number;
+ /**
+ * Search entries inside a given area defined by the two extreme points of a rectangle
+ * default: null
+ * https://github.com/algolia/algoliasearch-client-js#insideboundingbox
+ */
+ insideBoundingBox?: string;
+ /**
+ * Selects how the query words are interpreted
+ * default: 'prefixLast'
+ * 'prefixAll' All query words are interpreted as prefixes. This option is not recommended.
+ * 'prefixLast' Only the last word is interpreted as a prefix (default behavior).
+ * 'prefixNone' No query word is interpreted as a prefix. This option is not recommended.
+ * https://github.com/algolia/algoliasearch-client-js#querytype
+ */
+ queryType?: any;
+ /**
+ * Search entries inside a given area defined by a set of points
+ * defauly: ''
+ * https://github.com/algolia/algoliasearch-client-js#insidepolygon
+ */
+ insidePolygon?: string;
+ /**
+ * This option is used to select a strategy in order to avoid having an empty result page
+ * default: 'none'
+ * 'lastWords' When a query does not return any results, the last word will be added as optional
+ * 'firstWords' When a query does not return any results, the first word will be added as optional
+ * 'allOptional' When a query does not return any results, a second trial will be made with all words as optional
+ * 'none' No specific processing is done when a query does not return any results
+ * https://github.com/algolia/algoliasearch-client-js#removewordsifnoresults
+ */
+ removeWordsIfNoResults?: string;
+ /**
+ * Enables the advanced query syntax
+ * default: false
+ * https://github.com/algolia/algoliasearch-client-js#advancedsyntax
+ */
+ advancedSyntax?: boolean;
+ /**
+ * A string that contains the comma separated list of words that should be considered as optional when found in the query
+ * default: []
+ * https://github.com/algolia/algoliasearch-client-js#optionalwords
+ */
+ optionalWords?: string[];
+ /**
+ * Remove stop words from the query before executing it
+ * default: false
+ * true|false: enable or disable stop words for all 41 supported languages; or
+ * a list of language ISO codes (as a comma-separated string) for which stop words should be enable
+ * https://github.com/algolia/algoliasearch-client-js#removestopwords
+ */
+ removeStopWords?: string[];
+ /**
+ * List of attributes on which you want to disable the computation of exact criteria
+ * default: []
+ * https://github.com/algolia/algoliasearch-client-js#disableexactonattributes
+ */
+ disableExactOnAttributes?: string[];
+ /**
+ * This parameter control how the exact ranking criterion is computed when the query contains one word
+ * default: attribute
+ * 'none': no exact on single word query
+ * 'word': exact set to 1 if the query word is found in the record
+ * 'attribute': exact set to 1 if there is an attribute containing a string equals to the query
+ * https://github.com/algolia/algoliasearch-client-js#exactonsinglewordquery
+ */
+ exactOnSingleWordQuery?: string;
+ /**
+ * Specify the list of approximation that should be considered as an exact match in the ranking formula
+ * default: ['ignorePlurals', 'singleWordSynonym']
+ * 'ignorePlurals': alternative words added by the ignorePlurals feature
+ * 'singleWordSynonym': single-word synonym (For example "NY" = "NYC")
+ * 'multiWordsSynonym': multiple-words synonym
+ * https://github.com/algolia/algoliasearch-client-js#alternativesasexact
+ */
+ alternativesAsExact?: any;
+ /**
+ * If set to 1, enables the distinct feature, disabled by default, if the attributeForDistinct index setting is set.
+ * https://github.com/algolia/algoliasearch-client-js#distinct
+ */
+ distinct?: any;
+ /**
+ * If set to true, the result hits will contain ranking information in the _rankingInfo attribute.
+ * default: false
+ * https://github.com/algolia/algoliasearch-client-js#getrankinginfo
+ */
+ getRankingInfo?: boolean;
+ /**
+ * All numerical attributes are automatically indexed as numerical filters
+ * default: ''
+ * https://github.com/algolia/algoliasearch-client-js#numericattributestoindex
+ */
+ numericAttributesToIndex?: string[];
+ /**
+ * @deprecated please use filters instead
+ * A string that contains the comma separated list of numeric filters you want to apply.
+ * https://github.com/algolia/algoliasearch-client-js#numericfilters-deprecated
+ */
+ numericFilters?: string[];
+ /**
+ * @deprecated
+ * Filter the query by a set of tags.
+ * https://github.com/algolia/algoliasearch-client-js#tagfilters-deprecated
+ */
+ tagFilters?: string;
+ /**
+ * @deprecated
+ * Filter the query by a set of facets.
+ * https://github.com/algolia/algoliasearch-client-js#facetfilters-deprecated
+ */
+ facetFilters?: string;
+ /**
+ * If set to false, this query will not be taken into account in the analytics feature.
+ * default true
+ * https://github.com/algolia/algoliasearch-client-js#analytics
+ */
+ analytics?: boolean;
+ /**
+ * If set, tag your query with the specified identifiers
+ * default: null
+ * https://github.com/algolia/algoliasearch-client-js#analyticstags
+ */
+ analyticsTags?: string[];
+ /**
+ * If set to false, the search will not use the synonyms defined for the targeted index.
+ * default: true
+ * https://github.com/algolia/algoliasearch-client-js#synonyms
+ */
+ synonyms?: boolean;
+ /**
+ * If set to false, words matched via synonym expansion will not be replaced by the matched synonym in the highlighted result.
+ * default: true
+ * https://github.com/algolia/algoliasearch-client-js#replacesynonymsinhighlight
+ */
+ replaceSynonymsInHighlight?: boolean;
+ /**
+ * Configure the precision of the proximity ranking criterion
+ * default: 1
+ * https://github.com/algolia/algoliasearch-client-js#minproximity
+ */
+ minProximity?: number;
+}
+
+declare module "algoliasearch" {
+ function algoliasearch(applicationId: string, apiKey: string, options?: ClientOptions) : AlgoliaClient;
+ export = algoliasearch;
+}
diff --git a/amcharts/AmCharts.d.ts b/amcharts/AmCharts.d.ts
index bbd732bb1c..4f5dbe90f7 100644
--- a/amcharts/AmCharts.d.ts
+++ b/amcharts/AmCharts.d.ts
@@ -27,6 +27,9 @@ declare namespace AmCharts {
/** Clears all the charts on page, removes listeners and intervals. */
function clear();
+ /** Handle ready event */
+ function ready(Function): void;
+
/** Create chart by params. */
function makeChart(selector: string, params: any, delay?: number): AmChart;
diff --git a/angular-breadcrumb/angular-breadcrumb.d.ts b/angular-breadcrumb/angular-breadcrumb.d.ts
index 7df33ddef5..b9df64e366 100644
--- a/angular-breadcrumb/angular-breadcrumb.d.ts
+++ b/angular-breadcrumb/angular-breadcrumb.d.ts
@@ -14,7 +14,7 @@ declare namespace angular.ui {
/**
* Override the parent state (only for the breadcrumb)
**/
- parent?: string;
+ parent?: string|Function;
/**
* When defined to true, the state is never included in the chain of states and never appears in the breadcrumb
**/
@@ -76,4 +76,4 @@ declare namespace ncy {
**/
getLastStep(): angular.ui.IState;
}
-}
\ No newline at end of file
+}
diff --git a/angular-es/angular-es.d.ts b/angular-es/angular-es.d.ts
index 10979ae15c..0972b42da0 100644
--- a/angular-es/angular-es.d.ts
+++ b/angular-es/angular-es.d.ts
@@ -45,12 +45,12 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Component: (component: iComponent) => ngESDecorator;
+ function Component(component: iComponent): ngESDecorator;
/**
* Register config block
*/
- var Config: () => ngESDecorator;
+ function Config(): ngESDecorator;
/**
* Register constant
@@ -59,7 +59,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Constant: (name: string) => ngESDecorator;
+ function Constant(name: string): ngESDecorator;
/**
* Register controller
@@ -68,7 +68,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Controller: (name: string) => ngESDecorator;
+ function Controller(name: string): ngESDecorator;
/**
* Register decorator
@@ -77,7 +77,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Decorator: (name: string) => ngESDecorator;
+ function Decorator(name: string): ngESDecorator;
/**
* Register directive
@@ -86,7 +86,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Directive: (name: string) => ngESDecorator;
+ function Directive(name: string): ngESDecorator;
/**
* Register factory
@@ -95,7 +95,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Factory: (name: string) => ngESDecorator;
+ function Factory(name: string): ngESDecorator;
/**
* Register filter
@@ -104,7 +104,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Filter: (name: string) => ngESDecorator;
+ function Filter(name: string): ngESDecorator;
/**
* Add $inject property to target
@@ -113,7 +113,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Inject: (...dependencies: Array) => ngESDecorator;
+ function Inject(...dependencies: Array): ngESDecorator;
/**
* Inject dependencies as properties to target
@@ -122,7 +122,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var InjectAsProperty: (...dependencies: Array) => ngESDecorator;
+ function InjectAsProperty(...dependencies: Array): ngESDecorator;
/**
* Attach target to the specified module
@@ -131,7 +131,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Module: (name: string) => ngESDecorator;
+ function Module(name: string): ngESDecorator;
/**
* Register provider
@@ -140,14 +140,14 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Provider: (name: string) => ngESDecorator;
+ function Provider(name: string): ngESDecorator;
/**
* Register run block
*
* @returns {ngESDecorator} - decorated class
*/
- var Run: () => ngESDecorator;
+ function Run(): ngESDecorator;
/**
* Register service
@@ -156,7 +156,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Service: (name: string) => ngESDecorator;
+ function Service(name: string): ngESDecorator;
/**
* Register value
@@ -165,7 +165,7 @@ declare module 'angular-es' {
*
* @returns {ngESDecorator} - decorated class
*/
- var Value: (name: string) => ngESDecorator;
+ function Value(name: string): ngESDecorator;
export {
Component,
diff --git a/angular-feature-flags/angular-feature-flags-tests.ts b/angular-feature-flags/angular-feature-flags-tests.ts
new file mode 100644
index 0000000000..a36eaba3d0
--- /dev/null
+++ b/angular-feature-flags/angular-feature-flags-tests.ts
@@ -0,0 +1,31 @@
+///
+
+let myApp = angular.module('myApp', ['feature-flags']);
+
+const flagsData: Array = [
+ {
+ key: '1',
+ active: true,
+ name: 'flag1',
+ description: 'This is the first flag'
+ },
+ {
+ key: '2',
+ active: false,
+ name: 'flag2',
+ description: 'This is the second flag'
+ }
+];
+
+myApp.config(function (featureFlagsProvider: angular.featureflags.FeatureFlagsProvider) {
+ featureFlagsProvider.setInitialFlags(flagsData);
+});
+
+myApp.run(function ($q: angular.IQService, $http: angular.IHttpService, featureFlags: angular.featureflags.FeatureFlagsService) {
+ let deferred = $q.defer();
+ deferred.resolve(flagsData);
+
+ featureFlags.set(deferred.promise);
+
+ featureFlags.set($http.get('/data/flags.json'));
+});
\ No newline at end of file
diff --git a/angular-feature-flags/angular-feature-flags.d.ts b/angular-feature-flags/angular-feature-flags.d.ts
new file mode 100644
index 0000000000..99ef300976
--- /dev/null
+++ b/angular-feature-flags/angular-feature-flags.d.ts
@@ -0,0 +1,38 @@
+// Type definitions for angular-feature-flags 1.4.0
+// Project: https://github.com/mjt01/angular-feature-flags
+// Definitions by: Borislav Zhivkov
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+///
+
+declare namespace angular.featureflags {
+ export interface FlagData {
+ /**
+ * Unique key that is used from the markup to resolve whether a flag is active or not.
+ */
+ key: string;
+
+ /**
+ * Boolean value for enabling/disabling the feature
+ */
+ active: boolean;
+
+ /**
+ * A short name of the flag (only visible in the list of flags)
+ */
+ name: string;
+
+ /**
+ * A long description of the flag to further explain the feature being toggled (only visible in the list of flags)
+ */
+ description: string;
+ }
+
+ export interface FeatureFlagsProvider {
+ setInitialFlags(flags: Array): void;
+ }
+
+ export interface FeatureFlagsService {
+ set(flagsPromise: angular.IPromise | angular.IHttpPromise): void;
+ }
+}
\ No newline at end of file
diff --git a/angular-material/angular-material-tests.ts b/angular-material/angular-material-tests.ts
index 4464c599e3..70d7b413ae 100644
--- a/angular-material/angular-material-tests.ts
+++ b/angular-material/angular-material-tests.ts
@@ -20,6 +20,13 @@ myApp.config((
.warnPalette('red')
.dark(true);
+ var browserColors: ng.material.IBrowserColors = {
+ theme: 'default',
+ palette: 'neonRed',
+ hue: '500'
+ };
+ $mdThemingProvider.enableBrowserColor(browserColors);
+
$mdIconProvider
.defaultIconSet('my/app/icons.svg') // Register a default set of SVG icons
.iconSet('social', 'my/app/social.svg') // Register a named icon set of SVGs
@@ -41,6 +48,25 @@ myApp.controller('BottomSheetController', ($scope: ng.IScope, $mdBottomSheet: ng
$scope['cancelBottomSheet'] = $mdBottomSheet.cancel.bind($mdBottomSheet, 'cancel');
});
+myApp.controller('ColorController', ($scope: ng.IScope, $mdColor: ng.material.IColorService) => {
+ var colorExpression : ng.material.IColorExpression;
+ var element : Element;
+
+ colorExpression = { color: '#FFFFFF' }
+
+ element = new Element();
+
+ $scope['applyThemeColors'] = () => {
+ $mdColor.applyThemeColors(element, colorExpression);
+ };
+ $scope['getThemeColor'] = () => {
+ $mdColor.getThemeColor('default-neonRed')
+ };
+ $scope['hasTheme'] = () => {
+ $mdColor.hasTheme();
+ };
+});
+
myApp.controller('DialogController', ($scope: ng.IScope, $mdDialog: ng.material.IDialogService) => {
$scope['openDialog'] = () => {
$mdDialog.show({
@@ -127,15 +153,33 @@ myApp.controller('SidenavController', ($scope: ng.IScope, $mdSidenav: ng.materia
instance.isOpen();
instance.isLockedOpen();
});
+
+ $scope['onClose'] = $mdSidenav(componentId).onClose(() => {});
});
myApp.controller('ToastController', ($scope: ng.IScope, $mdToast: ng.material.IToastService) => {
- $scope['openToast'] = () => $mdToast.show($mdToast.simple().textContent('Hello!'));
+ $scope['openToast'] = () => {
+ $mdToast.show($mdToast.simple().textContent('Hello!'));
+ $mdToast.updateTextContent('New Content');
+ }
+
+ $scope['customToast'] = () => {
+ var options = {
+ hideDelay: 3000,
+ position: 'top right',
+ controller : 'ToastCtrl',
+ templateUrl : 'toast-template.html',
+ toastClass: 'my-class'
+ };
+
+ $mdToast.show(options);
+ }
});
myApp.controller('PanelController', ($scope: ng.IScope, $mdPanel: ng.material.IPanelService) => {
$scope['createPanel'] = () => {
var config = {
+ id: 'myPanel',
template: '
Hello!
',
hasBackdrop: true,
disableParentScroll: true,
diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts
index 23da7bceb2..68d645abfa 100644
--- a/angular-material/angular-material.d.ts
+++ b/angular-material/angular-material.d.ts
@@ -22,7 +22,7 @@ declare namespace angular.material {
clickOutsideToClose?: boolean;
disableBackdrop?: boolean;
escapeToClose?: boolean;
- resolve?: {[index: string]: angular.IPromise};
+ resolve?: {[index: string]: () => angular.IPromise};
controllerAs?: string;
parent?: Function|string|Object; // default: root node
disableParentScroll?: boolean; // default: true
@@ -53,7 +53,7 @@ declare namespace angular.material {
controller(controller?: string|Function): T;
locals(locals?: {[index: string]: any}): T;
bindToController(bindToController?: boolean): T; // default: false
- resolve(resolve?: {[index: string]: angular.IPromise}): T;
+ resolve(resolve?: {[index: string]: () => angular.IPromise}): T;
controllerAs(controllerAs?: string): T;
parent(parent?: string|Element|JQuery): T; // default: root node
onComplete(onComplete?: Function): T;
@@ -73,6 +73,16 @@ declare namespace angular.material {
initialValue(initialValue: string): IPromptDialog;
}
+ interface IColorExpression {
+ [cssPropertyName: string]: string
+ }
+
+ interface IColorService {
+ applyThemeColors(element: Element|JQuery, colorExpression: IColorExpression): void;
+ getThemeColor(expression: string): string;
+ hasTheme(): boolean;
+ }
+
interface IDialogOptions {
templateUrl?: string;
template?: string;
@@ -91,7 +101,7 @@ declare namespace angular.material {
controller?: string|Function;
locals?: {[index: string]: any};
bindToController?: boolean; // default: false
- resolve?: {[index: string]: angular.IPromise}
+ resolve?: {[index: string]: () => angular.IPromise}
controllerAs?: string;
parent?: string|Element|JQuery; // default: root node
onShowing?: Function;
@@ -132,6 +142,7 @@ declare namespace angular.material {
close(): angular.IPromise;
isOpen(): boolean;
isLockedOpen(): boolean;
+ onClose(onClose: Function): void;
}
interface ISidenavService {
@@ -162,10 +173,11 @@ declare namespace angular.material {
preserveScope?: boolean; // default: false
hideDelay?: number; // default (ms): 3000
position?: string; // any combination of 'bottom'/'left'/'top'/'right'/'fit'; default: 'bottom left'
+ toastClass?: string;
controller?: string|Function;
locals?: {[index: string]: any};
bindToController?: boolean; // default: false
- resolve?: {[index: string]: angular.IPromise}
+ resolve?: {[index: string]: () => angular.IPromise}
controllerAs?: string;
parent?: string|Element|JQuery; // default: root node
}
@@ -175,7 +187,8 @@ declare namespace angular.material {
showSimple(content: string): angular.IPromise;
simple(): ISimpleToastPreset;
build(): IToastPreset;
- updateContent(): void;
+ updateContent(newContent: string): void;
+ updateTextContent(newContent: string): void
hide(response?: any): void;
cancel(response?: any): void;
}
@@ -213,6 +226,12 @@ declare namespace angular.material {
hues: IThemeHues;
}
+ interface IBrowserColors{
+ theme: string;
+ palette: string;
+ hue: string;
+ }
+
interface IThemeColors {
accent: IThemePalette;
background: IThemePalette;
@@ -242,12 +261,14 @@ declare namespace angular.material {
}
interface IThemingProvider {
- theme(name: string, inheritFrom?: string): ITheme;
- definePalette(name: string, palette: IPalette): IThemingProvider;
- extendPalette(name: string, palette: IPalette): IPalette;
- setDefaultTheme(theme: string): void;
alwaysWatchTheme(alwaysWatch: boolean): void;
+ definePalette(name: string, palette: IPalette): IThemingProvider;
+ enableBrowserColor(browserColors: IBrowserColors): Function;
+ extendPalette(name: string, palette: IPalette): IPalette;
+ registerStyles(styles: String): void;
+ setDefaultTheme(theme: string): void;
setNonce(nonce: string): void;
+ theme(name: string, inheritFrom?: string): ITheme;
}
interface IDateLocaleProvider {
@@ -291,13 +312,14 @@ declare namespace angular.material {
}
interface IPanelConfig {
+ id?: string;
template?: string;
templateUrl?: string;
controller?: string|Function;
controllerAs?: string;
bindToController?: boolean; // default: true
locals?: {[index: string]: any};
- resolve?: {[index: string]: angular.IPromise}
+ resolve?: {[index: string]: () => angular.IPromise}
attachTo?: string|JQuery|Element;
propagateContainerEvents?: boolean;
panelClass?: string;
diff --git a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts
index dd129d141d..d6c389146b 100644
--- a/angular-ui-bootstrap/angular-ui-bootstrap.d.ts
+++ b/angular-ui-bootstrap/angular-ui-bootstrap.d.ts
@@ -400,6 +400,17 @@ declare namespace angular.ui.bootstrap {
* @default 'body'
*/
appendTo?: angular.IAugmentedJQuery;
+
+ /**
+ * A string reference to the component to be rendered that is registered with Angular's compiler. If using a directive, the directive must have `restrict: 'E'` and a template or templateUrl set.
+ *
+ * It supports these bindings:
+ * - `close` - A method that can be used to close a modal, passing a result. The result must be passed in this format: `{$value: myResult}`
+ * - `dismiss` - A method that can be used to dismiss a modal, passing a result. The result must be passed in this format: `{$value: myRejectedResult}`
+ * - `modalInstance` - The modal instance. This is the same `$uibModalInstance` injectable found when using `controller`.
+ * - `resolve` - An object of the modal resolve values. See [UI Router resolves] for details.
+ */
+ component?: string;
}
interface IModalStackService {
diff --git a/angular-ui-scroll/angular-ui-scroll.d.ts b/angular-ui-scroll/angular-ui-scroll.d.ts
index 168c6ba271..5f24c8ec38 100644
--- a/angular-ui-scroll/angular-ui-scroll.d.ts
+++ b/angular-ui-scroll/angular-ui-scroll.d.ts
@@ -42,9 +42,10 @@ declare namespace angular.ui {
*/
topVisibleScope: ng.IRepeatScope;
/**
- * calling this method reinitializes and reloads the scroller content.
+ * calling this method reinitializes and reloads the scroller content.
+ * @param startIndex is an integer indicating what item index the scroller will use to start the load process.
*/
- reload(): void;
+ reload(startIndex?: number): void;
/**
* Replaces the item in the buffer at the given index with the new items.
*
diff --git a/angularjs/angular-resource.d.ts b/angularjs/angular-resource.d.ts
index 441a7e1d3d..f7e803c1c8 100644
--- a/angularjs/angular-resource.d.ts
+++ b/angularjs/angular-resource.d.ts
@@ -42,15 +42,20 @@ declare namespace angular.resource {
(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
- actions?: any, options?: IResourceOptions): IResourceClass>;
+ actions?: IActionHash, options?: IResourceOptions): IResourceClass>;
(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
- actions?: any, options?: IResourceOptions): U;
+ actions?: IActionHash, options?: IResourceOptions): U;
(url: string, paramDefaults?: any,
/** example: {update: { method: 'PUT' }, delete: deleteDescriptor }
where deleteDescriptor : IActionDescriptor */
- actions?: any, options?: IResourceOptions): IResourceClass;
+ actions?: IActionHash, options?: IResourceOptions): IResourceClass;
+ }
+
+ // Hash of action descriptors allows custom action names
+ interface IActionHash {
+ [action: string]: IActionDescriptor
}
// Just a reference to facilitate describing new actions
@@ -186,6 +191,12 @@ declare namespace angular {
/** creating a resource service factory */
factory(name: string, resourceServiceFactoryFunction: angular.resource.IResourceServiceFactoryFunction): IModule;
}
+
+ namespace auto {
+ interface IInjectorService {
+ get(name: '$resource'): ng.resource.IResourceService;
+ }
+ }
}
interface Array
diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts
index ef3e29b4c8..4c03e7c219 100644
--- a/angularjs/angular-tests.ts
+++ b/angularjs/angular-tests.ts
@@ -180,25 +180,51 @@ namespace My.Namespace {
// IModule Registering Test
var mod = angular.module('tests', []);
-mod.controller('name', function ($scope: ng.IScope) { })
-mod.controller('name', ['$scope', function ($scope: ng.IScope) { }])
-mod.controller(My.Namespace);
+mod.controller('name', function ($scope: ng.IScope) { });
+mod.controller('name', ['$scope', function ($scope: ng.IScope) { }]);
+mod.controller('name', class {
+ // Uncommenting the next line should lead to a type error because this signature isn't compatible
+ // with the signature of the `$onChanges` hook:
+ // $onChanges(x: number) { }
+});
+mod.controller({
+ MyCtrl: class{},
+ MyCtrl2: function() {},
+ MyCtrl3: ['$fooService', function($fooService: any) { }]
+});
mod.directive('name', function ($scope: ng.IScope) { })
mod.directive('name', ['$scope', function ($scope: ng.IScope) { }])
-mod.directive(My.Namespace);
+mod.directive({
+ myFooDir: () => ({
+ template: 'my-foo-dir.tpl.html'
+ }),
+ myBarDir: ['$fooService', ($fooService: any) => ({
+ template: 'my-bar-dir.tpl.html'
+ })]
+});
mod.factory('name', function ($scope: ng.IScope) { })
-mod.factory('name', ['$scope', function ($scope: ng.IScope) { }])
-mod.factory(My.Namespace);
+mod.factory('name', ['$scope', function ($scope: ng.IScope) { }])
+mod.factory({
+ name1: function (foo: any) { },
+ name2: ['foo', function (foo: any) { }]
+});
mod.filter('name', function ($scope: ng.IScope) { })
-mod.filter('name', ['$scope', function ($scope: ng.IScope) { }])
-mod.filter(My.Namespace);
+mod.filter('name', ['$scope', function ($scope: ng.IScope) { }])
+mod.filter({
+ name1: function (foo: any) { },
+ name2: ['foo', function (foo: any) { }]
+});
mod.provider('name', function ($scope: ng.IScope) { return { $get: () => { } } })
mod.provider('name', TestProvider);
mod.provider('name', ['$scope', function ($scope: ng.IScope) { }])
mod.provider(My.Namespace);
mod.service('name', function ($scope: ng.IScope) { })
mod.service('name', ['$scope', function ($scope: ng.IScope) { }])
-mod.service(My.Namespace);
+mod.service({
+ MyCtrl: class{},
+ MyCtrl2: function() {},
+ MyCtrl3: ['$fooService', function($fooService: any) { }]
+});
mod.constant('name', 23);
mod.constant('name', "23");
mod.constant(My.Namespace);
@@ -867,6 +893,26 @@ angular.module('docsTabsExample', [])
};
});
+angular.module('multiSlotTranscludeExample', [])
+ .directive('dropDownMenu', function() {
+ return {
+ transclude: {
+ button: 'button',
+ list: 'ul',
+ },
+ link: function(scope, element, attrs, ctrl, transclude) {
+ // without scope
+ transclude().appendTo(element);
+ transclude(clone => clone.appendTo(element));
+
+ // with scope
+ transclude(scope, clone => clone.appendTo(element));
+ transclude(scope, clone => clone.appendTo(element), element, 'button');
+ transclude(scope, null, element, 'list').addClass('drop-down-list').appendTo(element);
+ }
+ };
+ });
+
angular.module('componentExample', [])
.component('counter', {
require: {'ctrl': '^ctrl'},
diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts
index 3d5e5a7b19..e879668039 100644
--- a/angularjs/angular.d.ts
+++ b/angularjs/angular.d.ts
@@ -25,6 +25,8 @@ declare module 'angular' {
///////////////////////////////////////////////////////////////////////////////
declare namespace angular {
+ type Injectable = T | (string | T)[];
+
// not directly implemented, but ensures that constructed class implements $get
interface IServiceProviderClass {
new (...args: any[]): IServiceProvider;
@@ -125,6 +127,7 @@ declare namespace angular {
isFunction(value: any): value is Function;
isNumber(value: any): value is number;
isObject(value: any): value is Object;
+ isObject(value: any): value is T;
isString(value: any): value is string;
isUndefined(value: any): boolean;
lowercase(str: string): string;
@@ -213,50 +216,26 @@ declare namespace angular {
* @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors.
* @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation).
*/
- controller(name: string, controllerConstructor: Function): IModule;
- /**
- * The $controller service is used by Angular to create new controllers.
- *
- * This provider allows controller registration via the register method.
- *
- * @param name Controller name, or an object map of controllers where the keys are the names and the values are the constructors.
- * @param controllerConstructor Controller constructor fn (optionally decorated with DI annotations in the array notation).
- */
- controller(name: string, inlineAnnotatedConstructor: any[]): IModule;
- controller(object: Object): IModule;
+ controller(name: string, controllerConstructor: Injectable): IModule;
+ controller(object: {[name: string]: Injectable}): IModule;
/**
* Register a new directive with the compiler.
*
* @param name Name of the directive in camel-case (i.e. ngBind which will match as ng-bind)
* @param directiveFactory An injectable directive factory function.
*/
- directive(name: string, directiveFactory: IDirectiveFactory): IModule;
- /**
- * Register a new directive with the compiler.
- *
- * @param name Name of the directive in camel-case (i.e. ngBind which will match as ng-bind)
- * @param directiveFactory An injectable directive factory function.
- */
- directive(name: string, inlineAnnotatedFunction: any[]): IModule;
- directive(object: Object): IModule;
+ directive(name: string, directiveFactory: Injectable): IModule;
+ directive(object: {[directiveName: string]: Injectable}): IModule;
/**
* Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider.
*
* @param name The name of the instance.
* @param $getFn The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}).
*/
- factory(name: string, $getFn: Function): IModule;
- /**
- * Register a service factory, which will be called to return the service instance. This is short for registering a service where its provider consists of only a $get property, which is the given service factory function. You should use $provide.factory(getFn) if you do not need to configure your service in a provider.
- *
- * @param name The name of the instance.
- * @param inlineAnnotatedFunction The $getFn for the instance creation. Internally this is a short hand for $provide.provider(name, {$get: $getFn}).
- */
- factory(name: string, inlineAnnotatedFunction: any[]): IModule;
- factory(object: Object): IModule;
- filter(name: string, filterFactoryFunction: Function): IModule;
- filter(name: string, inlineAnnotatedFunction: any[]): IModule;
- filter(object: Object): IModule;
+ factory(name: string, $getFn: Injectable): IModule;
+ factory(object: {[name: string]: Injectable}): IModule;
+ filter(name: string, filterFactoryFunction: Injectable): IModule;
+ filter(object: {[name: string]: Injectable}): IModule;
provider(name: string, serviceProviderFactory: IServiceProviderFactory): IModule;
provider(name: string, serviceProviderConstructor: IServiceProviderClass): IModule;
provider(name: string, inlineAnnotatedConstructor: any[]): IModule;
@@ -265,26 +244,15 @@ declare namespace angular {
/**
* Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.
*/
- run(initializationFunction: Function): IModule;
- /**
- * Run blocks are the closest thing in Angular to the main method. A run block is the code which needs to run to kickstart the application. It is executed after all of the service have been configured and the injector has been created. Run blocks typically contain code which is hard to unit-test, and for this reason should be declared in isolated modules, so that they can be ignored in the unit-tests.
- */
- run(inlineAnnotatedFunction: any[]): IModule;
+ run(initializationFunction: Injectable): IModule;
/**
* Register a service constructor, which will be invoked with new to create the service instance. This is short for registering a service where its provider's $get property is a factory function that returns an instance instantiated by the injector from the service constructor function.
*
* @param name The name of the instance.
* @param serviceConstructor An injectable class (constructor function) that will be instantiated.
*/
- service(name: string, serviceConstructor: Function): IModule;
- /**
- * Register a service constructor, which will be invoked with new to create the service instance. This is short for registering a service where its provider's $get property is a factory function that returns an instance instantiated by the injector from the service constructor function.
- *
- * @param name The name of the instance.
- * @param inlineAnnotatedConstructor An injectable class (constructor function) that will be instantiated.
- */
- service(name: string, inlineAnnotatedConstructor: any[]): IModule;
- service(object: Object): IModule;
+ service(name: string, serviceConstructor: Injectable): IModule;
+ service(object: {[name: string]: Injectable}): IModule;
/**
* Register a value service with the $injector, such as a string, a number, an array, an object or a function. This is short for registering a service where its provider's $get property is a factory function that takes no arguments and returns the value service.
@@ -301,8 +269,7 @@ declare namespace angular {
* @param name The name of the service to decorate
* @param decorator This function will be invoked when the service needs to be instantiated and should return the decorated service instance. The function is called using the injector.invoke method and is therefore fully injectable. Local injection arguments: $delegate - The original service instance, which can be monkey patched, configured, decorated or delegated to.
*/
- decorator(name:string, decoratorConstructor: Function): IModule;
- decorator(name:string, inlineAnnotatedConstructor: any[]): IModule;
+ decorator(name: string, decorator: Injectable): IModule;
// Properties
name: string;
@@ -612,11 +579,11 @@ declare namespace angular {
/**
* calling stopPropagation function will cancel further event propagation (available only for events that were $emit-ed).
*/
- stopPropagation?: Function;
+ stopPropagation?(): void;
/**
* calling preventDefault sets defaultPrevented flag to true.
*/
- preventDefault: Function;
+ preventDefault(): void;
/**
* true if preventDefault was called.
*/
@@ -1220,19 +1187,12 @@ declare namespace angular {
// see http://docs.angularjs.org/api/ng.$compileProvider
///////////////////////////////////////////////////////////////////////////
interface ICompileService {
- (element: string, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction;
- (element: Element, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction;
- (element: JQuery, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction;
+ (element: string | Element | JQuery, transclude?: ITranscludeFunction, maxPriority?: number): ITemplateLinkingFunction;
}
interface ICompileProvider extends IServiceProvider {
- directive(name: string, directiveFactory: Function): ICompileProvider;
- directive(directivesMap: Object, directiveFactory: Function): ICompileProvider;
- directive(name: string, inlineAnnotatedFunction: any[]): ICompileProvider;
- directive(directivesMap: Object, inlineAnnotatedFunction: any[]): ICompileProvider;
-
- // Undocumented, but it is there...
- directive(directivesMap: any): ICompileProvider;
+ directive(name: string, directiveFactory: Injectable): ICompileProvider;
+ directive(object: {[directiveName: string]: Injectable}): ICompileProvider;
component(name: string, options: IComponentOptions): ICompileProvider;
@@ -1242,7 +1202,8 @@ declare namespace angular {
imgSrcSanitizationWhitelist(): RegExp;
imgSrcSanitizationWhitelist(regexp: RegExp): ICompileProvider;
- debugInfoEnabled(enabled?: boolean): any;
+ debugInfoEnabled(): boolean;
+ debugInfoEnabled(enabled: boolean): ICompileProvider;
}
interface ICloneAttachFunction {
@@ -1255,12 +1216,16 @@ declare namespace angular {
(scope: IScope, cloneAttachFn?: ICloneAttachFunction): JQuery;
}
- // This corresponds to $transclude (and also the transclude function passed to link).
+ /**
+ * This corresponds to $transclude passed to controllers and to the transclude function passed to link functions.
+ * https://docs.angularjs.org/api/ng/service/$compile#-controller-
+ * http://teropa.info/blog/2015/06/09/transclusion.html
+ */
interface ITranscludeFunction {
// If the scope is provided, then the cloneAttachFn must be as well.
- (scope: IScope, cloneAttachFn: ICloneAttachFunction): JQuery;
+ (scope: IScope, cloneAttachFn: ICloneAttachFunction, futureParentElement?: JQuery, slotName?: string): JQuery;
// If one argument is provided, then it's assumed to be the cloneAttachFn.
- (cloneAttachFn?: ICloneAttachFunction): JQuery;
+ (cloneAttachFn?: ICloneAttachFunction, futureParentElement?: JQuery, slotName?: string): JQuery;
}
///////////////////////////////////////////////////////////////////////////
@@ -1411,6 +1376,16 @@ declare namespace angular {
* Absolute or relative URL of the resource that is being requested.
*/
url: string;
+ /**
+ * Event listeners to be bound to the XMLHttpRequest object.
+ * To bind events to the XMLHttpRequest upload object, use uploadEventHandlers. The handler will be called in the context of a $apply block.
+ */
+ eventHandlers?: { [type: string]: EventListenerOrEventListenerObject };
+ /**
+ * Event listeners to be bound to the XMLHttpRequest upload object.
+ * To bind events to the XMLHttpRequest object, use eventHandlers. The handler will be called in the context of a $apply block.
+ */
+ uploadEventHandlers?: { [type: string]: EventListenerOrEventListenerObject };
}
interface IHttpHeadersGetter {
@@ -1538,7 +1513,7 @@ declare namespace angular {
* Register service factories (names or implementations) for interceptors which are called before and after
* each request.
*/
- interceptors: (string|IHttpInterceptorFactory|(string|IHttpInterceptorFactory)[])[];
+ interceptors: (string | Injectable)[];
useApplyAsync(): boolean;
useApplyAsync(value: boolean): IHttpProvider;
@@ -1686,11 +1661,10 @@ declare namespace angular {
* controller if passed as a string. Empty function by default.
* Use the array form to define dependencies (necessary if strictDi is enabled and you require dependency injection)
*/
- controller?: string | Function | (string | Function)[] | IComponentController;
+ controller?: string | Injectable;
/**
- * An identifier name for a reference to the controller. If present, the controller will be published to scope under
- * the controllerAs name. If not present, this will default to be the same as the component name.
- * @default "$ctrl"
+ * An identifier name for a reference to the controller. If present, the controller will be published to its scope under
+ * the specified name. If not present, this will default to '$ctrl'.
*/
controllerAs?: string;
/**
@@ -1701,24 +1675,24 @@ declare namespace angular {
* $attrs - Current attributes object for the element
* Use the array form to define dependencies (necessary if strictDi is enabled and you require dependency injection)
*/
- template?: string | Function | (string | Function)[];
+ template?: string | Injectable<(...args: any[]) => string>;
/**
- * path or function that returns a path to an html template that should be used as the contents of this component.
+ * Path or function that returns a path to an html template that should be used as the contents of this component.
* If templateUrl is a function, then it is injected with the following locals:
* $element - Current element
* $attrs - Current attributes object for the element
* Use the array form to define dependencies (necessary if strictDi is enabled and you require dependency injection)
*/
- templateUrl?: string | Function | (string | Function)[];
+ templateUrl?: string | Injectable<(...args: any[]) => string>;
/**
* Define DOM attribute binding to component properties. Component properties are always bound to the component
* controller and not to the scope.
*/
- bindings?: {[binding: string]: string};
+ bindings?: {[boundProperty: string]: string};
/**
- * Whether transclusion is enabled. Enabled by default.
+ * Whether transclusion is enabled. Disabled by default.
*/
- transclude?: boolean | string | {[slot: string]: string};
+ transclude?: boolean | {[slot: string]: string};
/**
* Requires the controllers of other directives and binds them to this component's controller.
* The object keys specify the property names under which the required controllers (object values) will be bound.
@@ -1728,22 +1702,33 @@ declare namespace angular {
require?: {[controller: string]: string};
}
- interface IComponentTemplateFn {
- ( $element?: JQuery, $attrs?: IAttributes ): string;
- }
+ type IControllerConstructor =
+ (new (...args: any[]) => IController) |
+ // Instead of classes, plain functions are often used as controller constructors, especially in examples.
+ ((...args: any[]) => (void | IController));
/**
- * Components have a well-defined lifecycle Each component can implement "lifecycle hooks". These are methods that
- * will be called at certain points in the life of the component.
- * @url https://docs.angularjs.org/guide/component
+ * Directive controllers have a well-defined lifecycle. Each controller can implement "lifecycle hooks". These are methods that
+ * will be called by Angular at certain points in the life cycle of the directive.
+ * https://docs.angularjs.org/api/ng/service/$compile#life-cycle-hooks
+ * https://docs.angularjs.org/guide/component
*/
- interface IComponentController {
+ interface IController {
/**
* Called on each controller after all the controllers on an element have been constructed and had their bindings
* initialized (and before the pre & post linking functions for the directives on this element). This is a good
* place to put initialization code for your controller.
*/
$onInit?(): void;
+ /**
+ * Called on each turn of the digest cycle. Provides an opportunity to detect and act on changes.
+ * Any actions that you wish to take in response to the changes that you detect must be invoked from this hook;
+ * implementing this has no effect on when `$onChanges` is called. For example, this hook could be useful if you wish
+ * to perform a deep equality check, or to check a `Dat`e object, changes to which would not be detected by Angular's
+ * change detector and thus not trigger `$onChanges`. This hook is invoked with no arguments; if detecting changes,
+ * you must store the previous value(s) for comparison to the current values.
+ */
+ $doCheck?(): void;
/**
* Called whenever one-way bindings are updated. The onChangesObj is a hash whose keys are the names of the bound
* properties that have changed, and the values are an {@link IChangesObject} object of the form
@@ -1766,14 +1751,14 @@ declare namespace angular {
*/
$postLink?(): void;
}
-
+
interface IOnChangesObject {
- [property: string]: IChangesObject;
+ [property: string]: IChangesObject;
}
- interface IChangesObject {
- currentValue: any;
- previousValue: any;
+ interface IChangesObject {
+ currentValue: T;
+ previousValue: T;
isFirstChange(): boolean;
}
@@ -1813,12 +1798,12 @@ declare namespace angular {
* that is passed to the link function instead.
*/
transclude: ITranscludeFunction
- ): void | IDirectivePrePost;
+ ): void | IDirectiveLinkFn | IDirectivePrePost;
}
interface IDirective {
compile?: IDirectiveCompileFn;
- controller?: any;
+ controller?: string | Injectable;
controllerAs?: string;
/**
* @deprecated
@@ -1826,10 +1811,9 @@ declare namespace angular {
* the controller constructor is called, this use is now deprecated. Please place initialization code that
* relies upon bindings inside a $onInit method on the controller, instead.
*/
- bindToController?: boolean | Object;
+ bindToController?: boolean | {[boundProperty: string]: string};
link?: IDirectiveLinkFn | IDirectivePrePost;
multiElement?: boolean;
- directiveName?: string;
priority?: number;
/**
* @deprecated
@@ -1837,12 +1821,12 @@ declare namespace angular {
replace?: boolean;
require?: string | string[] | {[controller: string]: string};
restrict?: string;
- scope?: boolean | Object;
- template?: string | Function;
+ scope?: boolean | {[boundProperty: string]: string};
+ template?: string | ((tElement: JQuery, tAttrs: IAttributes) => string);
templateNamespace?: string;
- templateUrl?: string | Function;
+ templateUrl?: string | ((tElement: JQuery, tAttrs: IAttributes) => string);
terminal?: boolean;
- transclude?: boolean | string | {[slot: string]: string};
+ transclude?: boolean | 'element' | {[slot: string]: string};
}
/**
@@ -1855,6 +1839,11 @@ declare namespace angular {
interface IAugmentedJQueryStatic extends JQueryStatic {}
interface IAugmentedJQuery extends JQuery {}
+ /**
+ * Same as IController. Keeping it for compatibility with older versions of these type definitions.
+ */
+ interface IComponentController extends IController {}
+
///////////////////////////////////////////////////////////////////////////
// AUTO module (angular.js)
///////////////////////////////////////////////////////////////////////////
diff --git a/atom/atom.d.ts b/atom/atom.d.ts
index 389d6ef16e..ac899ba5ac 100644
--- a/atom/atom.d.ts
+++ b/atom/atom.d.ts
@@ -946,9 +946,14 @@ declare namespace AtomCore {
registry: any;
repository: Object;
scopeName: string;
+ tokenizeLines: (text: string) => any;
// TBD
}
+
+ interface IGrammars {
+ grammarForScopeName(scope: string): IGrammar;
+ }
interface IPane /* extends Theorist.Model */ {
itemForURI: (uri:string)=>IEditor;
@@ -1302,6 +1307,7 @@ declare namespace AtomCore {
deserializers:IDeserializerManager;
config: IConfig;
commands: ICommandRegistry;
+ grammars: IGrammars;
keymaps: IKeymapManager;
keymap: IKeymapManager;
packages: IPackageManager;
diff --git a/auth0.lock/auth0.lock.d.ts b/auth0.lock/auth0.lock.d.ts
index 43d842aecc..2d74f6e6a5 100644
--- a/auth0.lock/auth0.lock.d.ts
+++ b/auth0.lock/auth0.lock.d.ts
@@ -92,7 +92,7 @@ interface Auth0LockConstructorOptions {
initialScreen?: "login" | "signUp" | "forgotPassword";
language?: string;
languageDictionary?: any;
- loginAfterSignup?: boolean;
+ loginAfterSignUp?: boolean;
mustAcceptTerms?: boolean;
popupOptions?: Auth0LockPopupOptions;
prefill?: { email?: string, username?: string};
diff --git a/autobind-decorator/autobind-decorator-tests.ts b/autobind-decorator/autobind-decorator-tests.ts
new file mode 100644
index 0000000000..e428604802
--- /dev/null
+++ b/autobind-decorator/autobind-decorator-tests.ts
@@ -0,0 +1,43 @@
+///
+
+import autobind = require('autobind-decorator');
+
+class Test {
+ public static what: string = 'static';
+
+ @autobind
+ public static test(): void {
+ console.log(this.what);
+ }
+
+ public constructor(public what: string) {
+ this.what = what;
+ }
+
+ @autobind
+ public test(): void {
+ console.warn(this.what);
+ }
+}
+
+const tester: Test = new Test('bind');
+const { test } = tester;
+tester.test(); // warns 'bind'.
+test(); // warns 'bind'.
+Test.test(); // logs 'static'.
+
+@autobind
+class Component {
+ public constructor(private someMember: string) {
+ this.someMember = someMember;
+ }
+
+ public someMethod(): void {
+ console.error(this.someMember);
+ }
+}
+
+const component: Component = new Component('React vs Angular2');
+const { someMethod } = component;
+component.someMethod(); // errors 'React vs Angular2'
+someMethod(); // errors 'React vs Angular2'
diff --git a/autobind-decorator/autobind-decorator.d.ts b/autobind-decorator/autobind-decorator.d.ts
new file mode 100644
index 0000000000..51ba89c9bf
--- /dev/null
+++ b/autobind-decorator/autobind-decorator.d.ts
@@ -0,0 +1,10 @@
+// Type definitions for autobind-decorator v1.3.3
+// Project: https://github.com/andreypopp/autobind-decorator
+// Definitions by: Ivo Stratev
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+declare module 'autobind-decorator' {
+ function autobind(target: TFunction): TFunction | void;
+ function autobind(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor): TypedPropertyDescriptor | void;
+ export = autobind;
+}
diff --git a/autobind-decorator/autobind-decorator.ts.tscparams b/autobind-decorator/autobind-decorator.ts.tscparams
new file mode 100644
index 0000000000..1ee3d05cb6
--- /dev/null
+++ b/autobind-decorator/autobind-decorator.ts.tscparams
@@ -0,0 +1 @@
+--experimentalDecorators
diff --git a/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts
index 90f56d0702..2a92a4bcc4 100644
--- a/aws-sdk/aws-sdk.d.ts
+++ b/aws-sdk/aws-sdk.d.ts
@@ -49,6 +49,51 @@ declare module "aws-sdk" {
stack: string;
}
+ export interface RetryDelayOption {
+ base?: number;
+ customBackoff?: (retryCount: number) => number;
+ }
+
+ export interface Ebs {
+ SnapshotId?: string;
+ VolumeSize?: number;
+ VolumeType?: string;
+ DeleteOnTermination?: boolean;
+ Iops?: number;
+ Encrypted?: boolean;
+ }
+
+ export interface BlockDeviceMapping {
+ VirtualName?: string;
+ DeviceName: string;
+ Ebs?: Ebs;
+ NoDevice?: boolean;
+ }
+
+ export interface InstanceMonitoring {
+ SpotPrice?: string;
+ Enabled?: boolean;
+ }
+
+ export interface Filter {
+ Name?: string;
+ Values?: boolean;
+ }
+
+ export interface StepAdjustment {
+ scalingAdjustment: number;
+ metricIntervalLowerBound?: number;
+ metricIntervalUpperBound?: number;
+ }
+
+ export interface Tags {
+ resourceId?: string;
+ resourceType?: string;
+ key: string;
+ value?: string;
+ propagateAtLaunch?: boolean;
+ }
+
export interface Services {
autoscaling?: any;
cloudformation?: any;
@@ -118,6 +163,37 @@ declare module "aws-sdk" {
region: string;
}
+ export class CloudFormation {
+ constructor(options?: CloudFormation.Options);
+ endpoint: Endpoint;
+
+ cancelUpdateStack(params: CloudFormation.CancelUpdateStackParams, callback: (err: AwsError, data: any) => void): void;
+ continueUpdateRollback(params: CloudFormation.ContinueUpdateRollbackParams, callback: (err: AwsError, data: any) => void): void;
+ createChangeSet(params: CloudFormation.CreateChangeSetParams, callback: (err: AwsError, data: any) => void): void;
+ createStack(params: CloudFormation.CreateStackParams, callback: (err: AwsError, data: any) => void): void;
+ deleteChangeSet(params: CloudFormation.DeleteChangeSetParams, callback: (err: AwsError, data: any) => void): void;
+ deleteStack(params: CloudFormation.DeleteStackParams, callback: (err: AwsError, data: any) => void): void;
+ describeAccountLimits(params: CloudFormation.DescribeAccountLimitsParams, callback: (err: AwsError, data: any) => void): void;
+ describeChangeSet(params: CloudFormation.DescribeChangeSetParams, callback: (err: AwsError, data: any) => void): void;
+ describeStackEvents(params: CloudFormation.DescribeStackEventsParams, callback: (err: AwsError, data: any) => void): void;
+ describeStackResource(params: CloudFormation.DescribeStackResourceParams, callback: (err: AwsError, data: any) => void): void;
+ describeStackResources(params: CloudFormation.DescribeStackResourcesParams, callback: (err: AwsError, data: any) => void): void;
+ describeStacks(params: CloudFormation.DescribeStacksParams, callback: (err: AwsError, data: any) => void): void;
+ estimateTemplateCost(params: CloudFormation.EstimateTemplateCostParams, callback: (err: AwsError, data: any) => void): void;
+ executeChangeSet(params: CloudFormation.ExecuteChangeSetParams, callback: (err: AwsError, data: any) => void): void;
+ getStackPolicy(params: CloudFormation.GetStackPolicyParams, callback: (err: AwsError, data: any) => void): void;
+ getTemplate(params: CloudFormation.GetTemplateParams, callback: (err: AwsError, data: any) => void): void;
+ getTemplateSummary(params: CloudFormation.GetTemplateSummaryParams, callback: (err: AwsError, data: any) => void): void;
+ listChangeSets(params: CloudFormation.ListChangeSetsParams, callback: (err: AwsError, data: any) => void): void;
+ listStackResources(params: CloudFormation.ListStackResourcesParams, callback: (err: AwsError, data: any) => void): void;
+ listStacks(params: CloudFormation.ListStacksParams, callback: (err: AwsError, data: any) => void): void;
+ setStackPolicy(params: CloudFormation.SetStackPolicyParams, callback: (err: AwsError, data: any) => void): void;
+ signalResource(params: CloudFormation.SignalResourceParams, callback: (err: AwsError, data: any) => void): void;
+ updateStack(params: CloudFormation.UpdateStackParams, callback: (err: AwsError, data: any) => void): void;
+ validateTemplate(params: CloudFormation.ValidateTemplateParams, callback: (err: AwsError, data: any) => void): void;
+ waitFor(state: string, params: CloudFormation.WaitForParams, callback: (err: AwsError, data: any) => void): void;
+ }
+
export class Lambda {
constructor(options?: any);
endpoint: Endpoint;
@@ -147,6 +223,64 @@ declare module "aws-sdk" {
updateFunctionConfiguration(params: Lambda.UpdateFunctionConfigurationParams, callback: (err: AwsError, data: any) => void): void;
}
+ export class AutoScaling {
+ constructor(options?: any);
+ endpoint: Endpoint;
+
+ attachInstances(params: AutoScaling.AttachInstancesParams, callback: (err: AwsError, data: any) => void): void;
+ attachLoadBalancers(params: AutoScaling.AttachLoadBalancersParams, callback: (err: AwsError, data: any) => void): void;
+ attachLoadBalancerTargetGroups(param: AutoScaling.AttachLoadBalancerTargetGroupsParams, callback: (err: AwsError, data: any) => void): void;
+ completeLifecycleAction(param: AutoScaling.CompleteLifecycleActionParams, callback: (err: AwsError, data: any) => void): void;
+ createAutoScalingGroup(param: AutoScaling.CreateAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void;
+ createLaunchConfiguration(param: AutoScaling.CreateLaunchConfigurationParams, callback: (err: AwsError, data: any) => void): void;
+ createOrUpdateTags(param: AutoScaling.CreateOrUpdateTagsParams, callback: (err: AwsError, data: any) => void): void;
+ deleteAutoScalingGroup(param: AutoScaling.DeleteAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void;
+ deleteLaunchConfiguration(param: AutoScaling.DeleteLaunchConfigurationParams, callback: (err: AwsError, data: any) => void): void;
+ deleteLifecycleHook(param: AutoScaling.DeleteLifecycleHookParams, callback: (err: AwsError, data: any) => void): void;
+ deleteNotificationConfiguration(param: AutoScaling.DeleteNotificationConfigurationParams, callback: (err: AwsError, data: any) => void): void;
+ deletePolicy(param: AutoScaling.DeletePolicyParams, callback: (err: AwsError, data: any) => void): void;
+ deleteScheduledAction(param: AutoScaling.DeleteScheduledActionParams, callback: (err: AwsError, data: any) => void): void;
+ deleteTags(param: AutoScaling.DeleteTagsParams, callback: (err: AwsError, data: any) => void): void;
+ describeAccountLimits(callback: (err: AwsError, data: any) => void): void;
+ describeAdjustmentTypes(callback: (err: AwsError, data: any) => void): void;
+ describeAutoScalingGroups(param: AutoScaling.DescribeAutoScalingGroupsParams, callback: (err: AwsError, data: any) => void): void;
+ describeAutoScalingInstances(param: AutoScaling.DescribeAutoScalingInstancesParams, callback: (err: AwsError, data: any) => void): void;
+ describeAutoScalingNotificationTypes(callback: (err: AwsError, data: any) => void): void;
+ describeLaunchConfigurations(param: AutoScaling.DescribeLaunchConfigurationsParams, callback: (err: AwsError, data: any) => void): void;
+ describeLifecycleHooks(param: AutoScaling.DescribeLifecycleHooksParams, callback: (err: AwsError, data: any) => void): void;
+ describeLifecycleHookTypes(callback: (err: AwsError, data: any) => void): void;
+ describeLoadBalancers(param: AutoScaling.DescribeLoadBalancersParams, callback: (err: AwsError, data: any) => void): void;
+ describeLoadBalancerTargetGroups(param: AutoScaling.DescribeLoadBalancerTargetGroupsParams, callback: (err: AwsError, data: any) => void): void;
+ describeMetricCollectionTypes(callback: (err: AwsError, data: any) => void): void;
+ describeNotificationConfigurations(param: AutoScaling.DescribeNotificationConfigurationsParams, callback: (err: AwsError, data: any) => void): void;
+ describePolicies(param: AutoScaling.DescribePoliciesParams, callback: (err: AwsError, data: any) => void): void;
+ describeScalingActivities(param: AutoScaling.DescribeScalingActivitiesParams, callback: (err: AwsError, data: any) => void): void;
+ describeScalingProcessTypes(callback: (err: AwsError, data: any) => void): void;
+ describeScheduledActions(param: AutoScaling.DescribeScheduledActionsParams, callback: (err: AwsError, data: any) => void): void;
+ describeTags(param: AutoScaling.DescribeTagsParams, callback: (err: AwsError, data: any) => void): void;
+ describeTerminationPolicyTypes(callback: (err: AwsError, data: any) => void): void;
+ detachInstances(param: AutoScaling.DetachInstancesParams, callback: (err: AwsError, data: any) => void): void;
+ detachLoadBalancers(param: AutoScaling.DetachLoadBalancersParams, callback: (err: AwsError, data: any) => void): void;
+ detachLoadBalancerTargetGroups(param: AutoScaling.DetachLoadBalancerTargetGroupsParams, callback: (err: AwsError, data: any) => void): void;
+ disableMetricsCollection(param: AutoScaling.DisableMetricsCollectionParams, callback: (err: AwsError, data: any) => void): void;
+ enableMetricsCollection(param: AutoScaling.EnableMetricsCollectionParams, callback: (err: AwsError, data: any) => void): void;
+ enterStandby(param: AutoScaling.EnterStandbyParams, callback: (err: AwsError, data: any) => void): void;
+ executePolicy(param: AutoScaling.ExecutePolicyParams, callback: (err: AwsError, data: any) => void): void;
+ exitStandby(param: AutoScaling.ExitStandbyParams, callback: (err: AwsError, data: any) => void): void;
+ putLifecycleHook(param: AutoScaling.PutLifecycleHookParams, callback: (err: AwsError, data: any) => void): void;
+ putNotificationConfiguration(param: AutoScaling.PutNotificationConfigurationParams, callback: (err: AwsError, data: any) => void): void;
+ putScalingPolicy(param: AutoScaling.PutScalingPolicyParams, callback: (err: AwsError, data: any) => void): void;
+ putScheduledUpdateGroupAction(param: AutoScaling.PutScheduledUpdateGroupActionParams, callback: (err: AwsError, data: any) => void): void;
+ recordLifecycleActionHeartbeat(params: AutoScaling.RecordLifecycleActionHeartbeatParams, callback: (err: AwsError, data: any) => void): void;
+ resumeProcesses(params: AutoScaling.ResumeProcessesParams, callback: (err: AwsError, data: any) => void): void;
+ setDesiredCapacity(params: AutoScaling.SetDesiredCapacityParams, callback: (err: AwsError, data: any) => void): void;
+ setInstanceHealth(params: AutoScaling.SetInstanceHealthParams, callback: (err: AwsError, data: any) => void): void;
+ setInstanceProtection(params: AutoScaling.SetInstanceProtectionParams, callback: (err: AwsError, data: any) => void): void;
+ suspendProcesses(params: AutoScaling.SuspendProcessesParams, callback: (err: AwsError, data: any) => void): void;
+ terminateInstanceInAutoScalingGroup(params: AutoScaling.TerminateInstanceInAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void;
+ updateAutoScalingGroup(params: AutoScaling.UpdateAutoScalingGroupParams, callback: (err: AwsError, data: any) => void): void;
+ }
+
export class SQS {
constructor(options?: any);
endpoint: Endpoint;
@@ -226,7 +360,7 @@ declare module "aws-sdk" {
constructor(options?: any);
endpoint: Endpoint;
- getObject(params: s3.GetObjectRequest, callback: (err: Error, data: any) => void): void;
+ getObject(params: s3.GetObjectRequest, callback?: (err: Error, data: any) => void): any;
putObject(params: s3.PutObjectRequest, callback: (err: Error, data: any) => void): void;
deleteObject(params: s3.DeleteObjectRequest, callback: (err: Error, data: any) => void): void;
headObject(params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void;
@@ -236,6 +370,11 @@ declare module "aws-sdk" {
listObjects(params: s3.ListObjectRequest, callback: (err: Error, data: s3.ListObjectResponse) => void): void;
listObjectsV2(params: s3.ListObjectV2Request, callback: (err: Error, data: s3.ListObjectV2Response) => void): void;
waitFor(state: string, params: s3.HeadObjectRequest, callback: (err: Error, data: any) => void): void;
+
+ createMultipartUpload(params: any, callback: (err: Error, data: any) => void): void;
+ uploadPart(params: any, callback: (err: Error, data: any) => void): void;
+ listParts(params: any, callback: (err: Error, data: any) => void): void;
+ completeMultipartUpload(params: any, callback: (err: Error, data: any) => void): void;
}
export class STS {
@@ -424,6 +563,214 @@ declare module "aws-sdk" {
// ===========================================================
+ export module CloudFormation {
+
+ export interface CancelUpdateStackParams {
+ StackName: string;
+ }
+
+ export interface ContinueUpdateRollbackParams {
+ StackName: string;
+ }
+
+ export interface CreateChangeSetParams {
+ StackName: string;
+ TemplateBody?: string; // specify either TemplateBody or TemplateURL
+ TemplateURL?: string; // specify either TemplateBody or TemplateURL
+ UsePreviousTemplate?: boolean;
+ Parameters?: CloudFormation.Parameter[];
+ Capabilities?: string[]; // CAPABILITY_IAM | CAPABILITY_NAMED_IAM
+ ResourceTypes?: string[];
+ NotificationARNs?: string[];
+ Tags?: CloudFormation.Tag[];
+ ChangeSetName: string;
+ ClientToken?: string;
+ Description?: string;
+ }
+
+ export interface CreateStackParams {
+ StackName: string;
+ TemplateBody?: string; // specify either TemplateBody or TemplateURL
+ TemplateURL?: string; // specify either TemplateBody or TemplateURL
+ Parameters?: CloudFormation.Parameter[];
+ DisableRollback?: boolean; // cannot specify both DisableRollback and OnFailure
+ TimeoutInMinutes?: number;
+ NotificationARNs?: string[];
+ Capabilities?: string[];
+ ResourceTypes?: string[];
+ OnFailure?: string[]; // cannot specify both DisableRollback and OnFailure
+ // DO_NOTHING | ROLLBACK | DELETE
+ StackPolicyBody?: string[]; // cannot specify both StackPolicyBody and StackPolicyURL
+ StackPolicyURL?: string[]; // cannot specify both StackPolicyBody and StackPolicyURL
+ Tags?: CloudFormation.Tag[];
+ }
+
+ export interface DeleteChangeSetParams {
+ ChangeSetName: string;
+ StackName?: string;
+ }
+
+ export interface DeleteStackParams {
+ StackName: string;
+ RetainResources?: string[];
+ }
+
+ export interface DescribeAccountLimitsParams {
+ NextToken?: string;
+ }
+
+ export interface DescribeChangeSetParams {
+ ChangeSetName: string;
+ StackName?: string;
+ NextToken?: string;
+ }
+
+ export interface DescribeStackEventsParams {
+ StackName?: string;
+ NextToken?: string;
+ }
+
+ export interface DescribeStackResourceParams {
+ StackName: string;
+ LogicalResourceId: string;
+ }
+
+ export interface DescribeStackResourcesParams {
+ StackName?: string; // must specify either StackName or PhysicalResourceId
+ LogicalResourceId?: string;
+ PhysicalResourceId?: string; // must specify either StackName or PhysicalResourceId
+ }
+
+ export interface DescribeStacksParams {
+ StackName?: string;
+ NextToken?: string;
+ }
+
+ export interface EstimateTemplateCostParams {
+ TemplateBody?: string; // must specify either TemplateBody or TemplateURL
+ // if both are passed, only TemplateBody is used
+ TemplateURL?: string; // must specify either TemplateBody or TemplateURL
+ Parameters?: CloudFormation.Parameter[];
+ }
+
+ export interface ExecuteChangeSetParams {
+ ChangeSetName: string;
+ StackName?: string;
+ }
+
+ export interface GetStackPolicyParams {
+ StackName: string;
+ }
+
+ export interface GetTemplateParams {
+ StackName: string;
+ }
+
+ export interface GetTemplateSummaryParams {
+ // must specify one of the three
+ TemplateBody?: string;
+ TemplateURL?: string;
+ StackName?: string;
+ }
+
+ export interface ListChangeSetsParams {
+ StackName: string;
+ NextToken?: string;
+ }
+
+ export interface ListStackResourcesParams {
+ StackName: string;
+ NextToken?: string;
+ }
+
+ export interface ListStacksParams {
+ NextToken?: string;
+ StackStatusFilter?: string[];
+ }
+
+ export interface SetStackPolicyParams {
+ StackName: string;
+ StackPolicyBody?: string; // cannot set both StackPolicyBody and StackPolicyURL
+ StackPolicyURL?: string; // cannot set both StackPolicyBody and StackPolicyURL
+ }
+
+ export interface SignalResourceParams {
+ StackName: string;
+ LogicalResourceId: string;
+ UniqueId: string;
+ Status: string; // SUCCESS | FAILURE
+ }
+
+ export interface UpdateStackParams {
+ StackName: string;
+ TemplateBody?: string; // specify either TemplateBody or TemplateURL, not both
+ TemplateURL?: string; // specify either TemplateBody or TemplateURL, not both
+ UsePreviousTemplate?: boolean;
+ StackPolicyDuringUpdateBody?: string; // cannot set both StackPolicyDuringUpdateBody and StackPolicyDuringUpdateURL
+ StackPolicyDuringUpdateURL?: string; // cannot set both StackPolicyDuringUpdateBody and StackPolicyDuringUpdateURL
+ Parameters?: CloudFormation.Parameter[];
+ Capabilities?: string[]; // CAPABILITY_IAM | CAPABILITY_NAMED_IAM
+ ResourceTypes?: string[];
+ StackPolicyBody?: string; // cannot set both StackPolicyBody and StackPolicyURL
+ StackPolicyURL?: string; // cannot set both StackPolicyBody and StackPolicyURL
+ NotificationARNs?: string[];
+ Tags?: CloudFormation.Tag[];
+ }
+
+ export interface ValidateTemplateParams {
+ TemplateBody?: string; // must pass either TemplateBody or TemplateURL
+ // if both are specified, only TemplateBody is used
+ TemplateURL?: string; // must pass either TemplateBody or TemplateURL
+ }
+
+ export interface WaitForParams {
+ StackName: string;
+ NextToken?: string;
+ }
+
+ export interface Options {
+ params?: any;
+ endpoint?: string;
+ accessKeyId?: string;
+ secretAccessKey?: string;
+ sessionToken?: any;
+ credentials?: any;
+ credentialProvider?: any;
+ region?: string;
+ maxRetries?: number;
+ maxRedirects?: number;
+ sslEnabled?: boolean;
+ paramValidation?: any;
+ computeChecksums?: boolean;
+ convertResponseTypes?: boolean;
+ correctClockSkew?: boolean;
+ s3ForcePathStyle?: boolean;
+ s3BucketEndpoint?: boolean;
+ s3DisableBodySigning?: boolean;
+ retryDelayOptions?: any;
+ httpOptions?: any;
+ apiVersion?: any;
+ apiVersions?: any;
+ logger?: any;
+ systemClockOffset?: number;
+ signatureVersion?: string;
+ signatureCache?: boolean;
+ }
+
+ export interface Parameter {
+ ParameterKey: string;
+ ParameterValue: string;
+ UsePreviousValue?: boolean; // if you specify true, do not specify ParameterValue
+ }
+
+ export interface Tag {
+ Key: string;
+ Value: string;
+ }
+ }
+
+ // ===========================================================
+
export module Lambda {
export interface AddPermissionParams {
@@ -593,6 +940,355 @@ declare module "aws-sdk" {
}
}
+ export module AutoScaling {
+ export interface AutoScalingOptions {
+ params?: any;
+ endpoint?: string;
+ accessKeyId?: string;
+ secretAccessKey?: string;
+ sessionToken?: Credentials;
+ credentials?: Credentials;
+ credentialProvider?: any;
+ region?: string;
+ maxRetries?: number;
+ maxRedirects?: number;
+ sslEnabled?: boolean;
+ paramValidation?: boolean;
+ computeChecksums?: boolean;
+ convertResponseTypes?: boolean;
+ correctClockSkew?: boolean;
+ s3ForcePathStyle?: boolean;
+ s3BucketEndpoint?: boolean;
+ s3DisableBodySigning?: boolean;
+ retryDelayOptions?: RetryDelayOption;
+ httpOptions?: HttpOptions;
+ apiVersion?: string;
+ apiVersions?: { [serviceName: string]: string };
+ logger?: Logger;
+ systemClockOffset?: number;
+ signatureVersion?: string;
+ signatureCache?: boolean;
+ }
+
+ export interface AttachInstancesParams {
+ AutoScalingGroupName: string;
+ InstanceIds: string[];
+ }
+
+ export interface AttachLoadBalancersParams {
+ AutoScalingGroupName: string;
+ LoadBalancerNames: string[];
+ }
+
+ export interface AttachLoadBalancerTargetGroupsParams {
+ AutoScalingGroupName: string;
+ TargetGroupARNs: string[];
+ }
+
+ export interface CompleteLifecycleActionParams {
+ AutoScalingGroupName: string;
+ LifecycleActionResult: string;
+ LifecycleHookName: string;
+ lifecycleActionToken?: string;
+ InstanceId?: string;
+ }
+
+ export interface CreateAutoScalingGroupParams {
+ AutoScalingGroupName: string;
+ MinSize: number;
+ MaxSize: number;
+ LaunchConfigurationName?: string;
+ InstanceId?: string;
+ DesiredCapacity?: number;
+ DefaultCooldown?: number;
+ AvailabilityZones?: string[];
+ LoadBalancerNames?: string[];
+ TargetGroupARNs?: string[];
+ HealthCheckType?: string;
+ HealthCheckGracePeriod?: number;
+ PlacementGroup?: string;
+ VPCZoneIdentifier?: string;
+ TerminationPolicies?: string;
+ NewInstancesProtectedFromScaleIn?: boolean;
+ Tags?: Tags;
+ }
+
+ export interface CreateLaunchConfigurationParams {
+ LaunchConfigurationName: string;
+ AssociatePublicIpAddress?: boolean;
+ ImageId?: string;
+ KeyName?: string;
+ SecurityGroups?: string[];
+ ClassicLinkVPCId?: string;
+ ClassicLinkVPCSecurityGroups?: string[];
+ UserData?: string;
+ InstanceId?: string;
+ InstanceType?: string;
+ KernelId?: string;
+ RamdiskId?: string;
+ BlockDeviceMappings?: BlockDeviceMapping[];
+ InstanceMonitoring?: InstanceMonitoring;
+ SpotPrice?: string;
+ IamInstanceProfile?: string;
+ EbsOptimized?: boolean;
+ PlacementTenancy?: string;
+ }
+
+ export interface CreateOrUpdateTagsParams {
+ Tags: Tags[];
+ }
+
+ export interface DeleteAutoScalingGroupParams {
+ AutoScalingGroupName: string;
+ ForceDelete?: boolean;
+ }
+
+ export interface DeleteLaunchConfigurationParams {
+ LaunchConfigurationName: string;
+ }
+
+ export interface DeleteLifecycleHookParams {
+ AutoScalingGroupName: string;
+ LifecycleHookName: string;
+ }
+
+ export interface DeleteNotificationConfigurationParams {
+ AutoScalingGroupName: string;
+ TopicARN: string;
+ }
+
+ export interface DeletePolicyParams {
+ PolicyName: string;
+ AutoScalingGroupName?: string;
+ }
+
+ export interface DeleteScheduledActionParams {
+ AutoScalingGroupName: string;
+ ScheduledActionName: string;
+ }
+
+ export interface DeleteTagsParams {
+ Tags: Tags[];
+ }
+
+ export interface DescribeAutoScalingGroupsParams {
+ AutoScalingGroupName?: string;
+ NextToken?: string;
+ MaxRecords?: number;
+ }
+
+ export interface DescribeAutoScalingInstancesParams {
+ InstanceIds?: string[];
+ NextToken?: string;
+ MaxRecords?: number;
+ }
+
+ export interface DescribeLaunchConfigurationsParams {
+ LaunchConfigurationNames?: string[];
+ NextToken?: string;
+ MaxRecords?: number;
+ }
+
+ export interface DescribeLifecycleHooksParams {
+ AutoScalingGroupName: string;
+ LifecycleHookNames?: string[];
+ }
+
+ export interface DescribeLoadBalancersParams {
+ AutoScalingGroupName: string;
+ NextToken?: string;
+ MaxRecords?: number;
+ }
+
+ export interface DescribeLoadBalancerTargetGroupsParams {
+ AutoScalingGroupName: string;
+ NextToken?: string;
+ MaxRecords?: number;
+ }
+
+ export interface DescribeNotificationConfigurationsParams {
+ AutoScalingGroupName?: string;
+ NextToken?: string;
+ MaxRecords?: number;
+ }
+
+ export interface DescribePoliciesParams {
+ AutoScalingGroupName?: string;
+ PolicyNames?: string[];
+ PolicyTypes?: string[];
+ NextToken?: string;
+ MaxRecords?: number;
+ }
+
+ export interface DescribeScalingActivitiesParams {
+ AutoScalingGroupName?: string;
+ ActivityIds?: string[];
+ NextToken?: string;
+ MaxRecords?: number;
+ }
+
+ export interface DescribeScheduledActionsParams {
+ AutoScalingGroupName?: string;
+ ScheduledActionNames?: string[];
+ StartTime?: Date;
+ EndTime?: Date;
+ NextToken?: string;
+ MaxRecords?: number;
+ }
+
+ export interface DescribeTagsParams {
+ Filters?: Filter[];
+ NextToken?: string;
+ MaxRecords?: number;
+ }
+
+ export interface DetachInstancesParams {
+ AutoScalingGroupName: string;
+ ShouldDecrementDesiredCapacity: boolean;
+ InstanceIds?: string[];
+ }
+
+ export interface DetachLoadBalancersParams {
+ AutoScalingGroupName: string;
+ LoadBalancerNames: string;
+ }
+
+ export interface DetachLoadBalancerTargetGroupsParams {
+ AutoScalingGroupName: string;
+ TargetGroupARNs: string[];
+ }
+
+ export interface DisableMetricsCollectionParams {
+ AutoScalingGroupName: string;
+ Metrics?: string[];
+ }
+
+ export interface EnableMetricsCollectionParams {
+ AutoScalingGroupName: string;
+ Granularity: string;
+ Metrics?: string[];
+ }
+
+ export interface EnterStandbyParams {
+ AutoScalingGroupName: string;
+ ShouldDecrementDesiredCapacity: boolean;
+ InstanceIds?: string[];
+ }
+
+ export interface ExecutePolicyParams {
+ PolicyName: string;
+ AutoScalingGroupName?: string;
+ HonorCooldown?: boolean;
+ MetricValue?: number;
+ BreachThreshold?: number;
+ }
+
+ export interface ExitStandbyParams {
+ AutoScalingGroupName: string;
+ InstanceIds?: string[];
+ }
+
+ export interface PutLifecycleHookParams {
+ AutoScalingGroupName: string;
+ LifecycleHookName: string;
+ LifecycleTransition?: string;
+ RoleARN?: string;
+ NotificationTargetARN?: string;
+ NotificationMetadata?: string;
+ HeartbeatTimeout?: number;
+ DefaultResult?: string;
+ }
+
+ export interface PutNotificationConfigurationParams {
+ AutoScalingGroupName: string;
+ NotificationTypes: string[];
+ TopicARN: string;
+ }
+
+ export interface PutScalingPolicyParams {
+ AutoScalingGroupName: string;
+ AdjustmentType: string;
+ PolicyName: string;
+ PolicyType?: string;
+ MinAdjustmentStep?: number;
+ MinAdjustmentMagnitude?: number;
+ ScalingAdjustment?: number;
+ Cooldown?: number;
+ MetricAggregationType?: string;
+ StepAdjustments?: StepAdjustment[];
+ EstimatedInstanceWarmup: number;
+ }
+
+ export interface PutScheduledUpdateGroupActionParams {
+ AutoScalingGroupName: string;
+ ScheduledActionName: string;
+ Time?: Date;
+ StartTime?: Date;
+ EndTime?: Date;
+ Recurrence?: string;
+ MinSize?: number;
+ MaxSize?: number;
+ DesiredCapacity?: number;
+ }
+
+ export interface RecordLifecycleActionHeartbeatParams {
+ AutoScalingGroupName: string;
+ LifecycleHookName: string;
+ LifecycleActionToken?: string;
+ InstanceId?: string;
+ }
+
+ export interface ResumeProcessesParams {
+ AutoScalingGroupName: string;
+ ScalingProcesses?: string[];
+ }
+
+ export interface SetDesiredCapacityParams {
+ AutoScalingGroupName: string;
+ DesiredCapacity: number;
+ HonorCooldown?: boolean;
+ }
+
+ export interface SetInstanceHealthParams {
+ HealthStatus: string;
+ InstanceId: string;
+ ShouldRespectGracePeriod?: boolean;
+ }
+
+ export interface SetInstanceProtectionParams {
+ AutoScalingGroupName: string;
+ InstanceIds: string[];
+ ProtectedFromScaleIn: boolean;
+ }
+
+ export interface SuspendProcessesParams {
+ AutoScalingGroupName: string;
+ ScalingProcesses?: string[];
+ }
+
+ export interface TerminateInstanceInAutoScalingGroupParams {
+ InstanceId: string;
+ ShouldDecrementDesiredCapacity: boolean;
+ }
+
+ export interface UpdateAutoScalingGroupParams {
+ AutoScalingGroupName: string;
+ LaunchConfigurationName: string;
+ MinSize: number;
+ MaxSize: number;
+ DesiredCapacity: number;
+ DefaultCooldown: number;
+ AvailabilityZones: string[];
+ HealthCheckType: string;
+ HealthCheckGracePeriod: number;
+ PlacementGroup: string;
+ VPCZoneIdentifier: string;
+ TerminationPolicies: string[];
+ NewInstancesProtectedFromScaleIn?: boolean;
+ }
+ }
+
+
export module SQS {
export interface SqsOptions {
diff --git a/axe-core/axe-core-tests.ts b/axe-core/axe-core-tests.ts
new file mode 100644
index 0000000000..7decb865c2
--- /dev/null
+++ b/axe-core/axe-core-tests.ts
@@ -0,0 +1,91 @@
+///
+
+var context:any = document
+var $fixture:any = {}
+
+// axe.a11yCheck config
+axe.a11yCheck(context, {}, (results) => {
+ // axe's results object
+ console.log(results.passes.length)
+ console.log(results.violations.length)
+});
+// axe.a11yCheck include/exclude
+axe.a11yCheck({include: [['#id1'], ['#id2']]}, {}, (results) => {
+ console.log(results)
+})
+axe.a11yCheck({exclude: [$fixture[0]]}, {}, (results) => {
+ console.log(results)
+})
+var tagConfigRunOnly: axe.RunOnly = {
+ type: 'tag',
+ values: ['wcag2a']
+}
+var tagConfig = {
+ runOnly: tagConfigRunOnly
+}
+axe.a11yCheck(context, tagConfig, (results) => {
+ console.log(results)
+})
+var includeExcludeTagsRunOnly: axe.RunOnly = {
+ type: 'tags',
+ value: {
+ include: ['wcag2a', 'wcag2aa'],
+ exclude: ['experimental']
+ }
+}
+var includeExcludeTagsConfig = {
+ runOnly: includeExcludeTagsRunOnly
+}
+axe.a11yCheck(context, includeExcludeTagsConfig, (results) => {
+ console.log(results)
+})
+var someRulesConfig = {
+ rules: {
+ "color-contrast": {enabled: 'false'},
+ "heading-order": {enabled: 'true'}
+ }
+}
+axe.a11yCheck(context, someRulesConfig, (results) => {
+ console.log(results)
+})
+
+// axe.configure
+var spec: axe.Spec = {
+ branding: {
+ brand: 'foo',
+ application: 'bar'
+ },
+ reporter: 'v1',
+ checks: [{
+ id: 'custom-check',
+ evaluate: function() {
+ return true
+ }
+ }],
+ rules: [{
+ id: 'custom-rule',
+ any: ['custom-check']
+ }]
+}
+axe.configure(spec)
+
+axe.reset()
+
+axe.getRules(['wcag2aa'])
+typeof axe.getRules() === 'object'
+
+// Plugins
+var pluginSrc: axe.AxePlugin = {
+ id: 'doStuff',
+ run: (data:any, callback:Function) => {
+ callback()
+ },
+ commands: [{
+ id: 'run-doStuff',
+ callback: (data:any, callback:Function) => {
+ axe.plugins['doStuff'].run(data, callback)
+ }
+ }]
+}
+axe.registerPlugin(pluginSrc)
+axe.cleanup()
diff --git a/axe-core/axe-core.d.ts b/axe-core/axe-core.d.ts
new file mode 100644
index 0000000000..98818e75cc
--- /dev/null
+++ b/axe-core/axe-core.d.ts
@@ -0,0 +1,159 @@
+// Type definitions for axe-core 2.0.5
+// Project: https://github.com/dequelabs/axe-core
+// Definitions by: Marcy Sutton
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+declare namespace axe {
+
+ export type ImpactValue = "minor" | "moderate" | "serious" | "critical";
+
+ export type TagValue = "wcag2a" | "wcag2aa" | "section508" | "best-practice";
+
+ export type ReporterVersion = "v1" | "v2";
+
+ export type RunOnlyType = "rule" | "rules" | "tag" | "tags";
+
+ export interface ElementContext {
+ node?: Object,
+ selector?: string,
+ include?: any[],
+ exclude?: any[]
+ }
+ export interface RunOnly {
+ type: RunOnlyType,
+ value?: {
+ include?: string[],
+ exclude?: string[]
+ }
+ values?: TagValue[]
+ }
+ export interface AxeResults {
+ url: string,
+ timestamp: string,
+ passes: Pass[],
+ violations: Violation[]
+ }
+ export interface Pass {
+ description: string,
+ help: string,
+ helpUrl: string,
+ id: string,
+ impact: ImpactValue,
+ tags: TagValue[],
+ nodes: NodeResult[]
+ }
+ export interface Violation {
+ description: string,
+ help: string,
+ helpUrl: string,
+ id: string,
+ impact: ImpactValue,
+ tags: TagValue[],
+ nodes: NodeResult[]
+ }
+ export interface NodeResult {
+ html: string,
+ impact: ImpactValue,
+ target: string[],
+ any: CheckResult[],
+ all: CheckResult[],
+ none: CheckResult[]
+ }
+ export interface CheckResult {
+ id: string,
+ impact: string,
+ message: string,
+ data: any,
+ relatedNodes?: RelatedNode[]
+ }
+ export interface RelatedNode {
+ target: string[],
+ html: string
+ }
+ export interface Spec {
+ branding?: {
+ brand: string,
+ application: string
+ },
+ reporter?: ReporterVersion,
+ checks?: Check[],
+ rules?: Rule[]
+ }
+ export interface Check {
+ id: string,
+ evaluate: Function,
+ after?: Function,
+ options?: any,
+ matches?: string,
+ enabled?: boolean
+ }
+ export interface Rule {
+ id: string,
+ selector?: string,
+ excludeHidden?: boolean,
+ enabled?: boolean,
+ pageLevel?: boolean,
+ any?: string[],
+ all?: string[],
+ none?: string[],
+ tags?: string[],
+ matches?: string
+ }
+ export interface AxePlugin {
+ id: string,
+ run(...args:any[]): any,
+ commands: {
+ id: string,
+ callback(...args:any[]): void
+ }[],
+ cleanup?(callback:Function): void
+ }
+
+ export let plugins: any
+
+ /**
+ * Starts analysis on the current document and its subframes
+ *
+ * @param {Object} context The `Context` specification object @see Context
+ * @param {Array} options Options passed into rules or checks, temporarily modifyint them.
+ * @param {Function} callback The function to invoke when analysis is complete.
+ * @returns {Object} results The aXe results object
+ */
+ export function a11yCheck(context: ElementContext, options: {runOnly?: RunOnly, rules?: Object}, callback: (results:AxeResults) => void): AxeResults
+
+ /**
+ * Method for configuring the data format used by aXe. Helpful for adding new
+ * rules, which must be registered with the library to execute.
+ * @param {Spec} Spec Object with valid `branding`, `reporter`, `checks` and `rules` data
+ */
+ export function configure(spec: Spec): void
+
+ /**
+ * Searches and returns rules that contain a tag in the list of tags.
+ * @param {Array} tags Optional array of tags
+ * @return {Array} Array of rules
+ */
+ export function getRules(tags?: string[]): Object[]
+
+ /**
+ * Restores the default axe configuration
+ */
+ export function reset(): void
+
+ /**
+ * Function to register a plugin configuration in document and its subframes
+ * @param {Object} plugin A plugin configuration object
+ */
+ export function registerPlugin(plugin: AxePlugin): void
+
+ /**
+ * Function to clean up plugin configuration in document and its subframes
+ */
+ export function cleanup(): void
+
+}
+
+// axe is also available as a module
+declare module "axe-core" {
+ export = axe;
+}
diff --git a/azure-mobile-apps/azure-mobile-apps-tests.ts b/azure-mobile-apps/azure-mobile-apps-tests.ts
index 093932c2fb..f8f3bcef52 100644
--- a/azure-mobile-apps/azure-mobile-apps-tests.ts
+++ b/azure-mobile-apps/azure-mobile-apps-tests.ts
@@ -8,7 +8,7 @@ import queries = require('azure-mobile-apps/src/query');
var app = express(),
mobileApp = mobileApps();
-// various configuration permutations
+// various configuration permutations
mobileApps({
debug: true,
data: {
@@ -17,7 +17,8 @@ mobileApps({
user: '',
database: '',
password: ''
- }
+ },
+ webhook: { url: 'http://localhost/' }
});
mobileApps({
@@ -29,7 +30,7 @@ mobileApps({
// it would be nice to integrate with winston
mobileApps({ logging: { level: 'silly', transports: [{}] } })
-// various custom middleware syntaxes
+// various custom middleware syntaxes
mobileApp.use(function (req: any, res: any, next: any) { next(); });
mobileApp.use([function () {}, function () {}]);
mobileApp.use(function () {}, function () {});
@@ -43,6 +44,9 @@ mobileApp.tables.import('tables');
mobileApp.api.add('api', { authorize: true, get: function () {}, delete: function () {} });
mobileApp.api.import('api');
+// ensure the mobile app instance can be correctly mounted as an express router
+app.use(mobileApp);
+
// Express.Table, instantiated from the mobile app
var table = mobileApp.table()
table.use(function (req: Express.Request, res: Express.Response, next: any) {
@@ -61,21 +65,45 @@ table.read(function (context: Azure.MobileApps.Context) {
table.insert(function (context: Azure.MobileApps.Context) {
context.query.id = 'anotherId';
context.query.single = true;
- context.item.userId = context.user.id;
+ context.item.userId = context.user.id;
context.push.send('tag', {}, function (error, result) {});
context.push.gcm.send('tag', {}, function (error, result) {});
context.push.apns.send('tag', { payload: { } }, function (error, result) {});
context.push.wns.sendToastText01('tag', '', { headers: { } }, function (error, result) {});
+ context.next(new Error());
+ context.next('An error occurred');
});
table.read.use(function () {});
table.read.use([function () {}, function () {}]);
table.read.use(function () {}, function () {});
-table.use(function () {}).use(function () {}).read(function () {}).use(function () {})
+table.use(function () {}).use(function () {}).read(function () {}).use(function () {});
+
+table.access = undefined;
+table.access = 'authenticated';
+table.read.access = 'anonymous';
+table.update.access = 'disabled';
+table.delete.access = 'authenticated';
+table.insert.access = 'authenticated';
+
+table.filters = [function (query, context) { }];
+table.transforms = [function (item, context) { }];
+table.hooks = [function (results, context) { }];
+
+table.perUser = true;
+table.recordsExpire = { milliseconds: 1, seconds: 1, minutes: 1, hours: 1, days: 1, weeks: 1, months: 1, years: 1 };
+table.webhook = { url: 'http://localhost/' }
+table.webhook = true;
// Express.Table, instantiated from the static require('azure-mobile-apps').table()
// This is going to be interesting if we ever support more than one provider
var table2 = mobileApps.table();
-table2.read(function (context: Azure.MobileApps.Context) {})
+table2.read(function (context: Azure.MobileApps.Context) {});
+
+// ApiDefinition, from the static require('azure-mobile-apps').api()
+var api2 = mobileApps.api({
+ get: function (req, res, next) { }
+});
+api2.post = function (req, res, next) {};
// Logger
logger.silly('test', 'message');
@@ -83,5 +111,15 @@ logger.error('Something happened', new Error());
mobileApps.logger.debug('a debug message')
// Query
-queries.create('table').where({ x: 10 }).select('col1,col2');
-mobileApps.query.create('table');
\ No newline at end of file
+queries.create('table').where({ x: 10 }).select('col1,col2').includeDeleted().includeTotalCount();
+mobileApps.query.create('table');
+
+// Custom SQL query
+mobileApp.api.add('query', { authorize: true, get: (req, res, next) => {
+ req.azureMobile.data.execute({
+ sql: "SELECT * FROM TODOITEM WHERE COMPLETE = :complete",
+ parameters: [
+ { name: 'complete', value: 1 }
+ ]
+ }).then(x => {});
+}, delete: function () {} });
diff --git a/azure-mobile-apps/azure-mobile-apps.d.ts b/azure-mobile-apps/azure-mobile-apps.d.ts
index 0a42fa9ecf..54aaa66f8b 100644
--- a/azure-mobile-apps/azure-mobile-apps.d.ts
+++ b/azure-mobile-apps/azure-mobile-apps.d.ts
@@ -1,4 +1,4 @@
-// Type definitions for azure-mobile-apps v2.0.0-beta3
+// Type definitions for azure-mobile-apps v2.1.7
// Project: https://github.com/Azure/azure-mobile-apps-node/
// Definitions by: Microsoft Azure
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -10,6 +10,7 @@ declare module "azure-mobile-apps" {
interface AzureMobileApps {
(configuration?: Azure.MobileApps.Configuration): Azure.MobileApps.Platforms.Express.MobileApp;
table(): Azure.MobileApps.Platforms.Express.Table;
+ api(definition?: Azure.MobileApps.ApiDefinition): Azure.MobileApps.ApiDefinition;
logger: Azure.MobileApps.Logger;
query: Azure.MobileApps.Query;
}
@@ -31,7 +32,7 @@ declare namespace Azure.MobileApps {
// the additional Platforms namespace is required to avoid collisions with the main Express namespace
export module Platforms {
export module Express {
- interface MobileApp {
+ interface MobileApp extends Middleware {
configuration: Configuration;
tables: Tables;
table(): Table;
@@ -45,14 +46,7 @@ declare namespace Azure.MobileApps {
import(fileOrFolder: string): void;
}
- interface Table {
- authorize?: boolean;
- autoIncrement?: boolean;
- dynamicSchema?: boolean;
- name: string;
- columns?: any;
- schema: string;
-
+ interface Table extends TableDefinition {
use(...middleware: Middleware[]): Table;
use(middleware: Middleware[]): Table;
read: TableOperation;
@@ -66,6 +60,7 @@ declare namespace Azure.MobileApps {
(operationHandler: (context: Context) => void): Table;
use(...middleware: Middleware[]): Table;
use(middleware: Middleware[]): Table;
+ access?: AccessType;
}
interface Tables {
@@ -132,6 +127,7 @@ declare namespace Azure.MobileApps {
auth?: Configuration.Auth;
cors?: Configuration.Cors;
notifications?: Configuration.Notifications;
+ webhook?: Webhook;
}
export module Configuration {
@@ -148,6 +144,7 @@ declare namespace Azure.MobileApps {
options?: { encrypt: boolean };
schema?: string;
dynamicSchema?: boolean;
+ filename?: string;
}
interface Auth {
@@ -163,8 +160,9 @@ declare namespace Azure.MobileApps {
interface LoggingTransport { }
interface Cors {
+ exposeHeaders: string;
maxAge?: number;
- origins: string[];
+ hostnames: string[];
}
interface Notifications {
@@ -184,7 +182,8 @@ declare namespace Azure.MobileApps {
}
interface QueryJs {
- includeTotalCount?: boolean;
+ includeTotalCount(): QueryJs;
+ includeDeleted(): QueryJs;
orderBy(properties: string): QueryJs;
orderByDescending(properties: string): QueryJs;
select(properties: string): QueryJs;
@@ -209,27 +208,75 @@ declare namespace Azure.MobileApps {
// general
var nh: Azure.ServiceBus.NotificationHubService;
+
interface Context {
query: QueryJs;
id: string | number;
item: any;
req: Express.Request;
res: Express.Response;
- data: (table: TableDefinition) => Data.Table;
+ data: ContextData;
tables: (tableName: string) => Data.Table;
user: User;
push: typeof nh;
logger: Logger;
execute(): Thenable;
+ next(error: string|Error): any;
}
+ interface ContextData {
+ (table: TableDefinition): Data.Table;
+ execute(q: SqlQueryDefinition): Thenable;
+ }
+
+ interface SqlQueryDefinition {
+ sql: string;
+ parameters?: SqlParameterDefinition[];
+ }
+
+ interface SqlParameterDefinition {
+ name: string;
+ value: any;
+ }
+
interface TableDefinition {
+ access?: AccessType;
authorize?: boolean;
autoIncrement?: boolean;
- dynamicSchema?: boolean;
- name?: string;
columns?: any;
+ databaseTableName?: string;
+ dynamicSchema?: boolean;
+ maxTop?: number;
+ name?: string;
+ pageSize?: number;
schema?: string;
+ softDelete?: boolean;
+ userIdColumn?: string;
+
+ filters?: [(query: QueryJs, context: Context) => void | QueryJs];
+ transforms?: [(item: any, context: Context) => void | any];
+ hooks?: [(results: any, context: Context) => void];
+
+ perUser?: boolean;
+ recordsExpire?: Duration;
+ webhook?: Webhook | boolean;
+ }
+
+ type AccessType = 'anonymous' | 'authenticated' | 'disabled';
+
+ interface Duration {
+ milliseconds?: number;
+ seconds?: number;
+ minutes?: number;
+ hours?: number;
+ days?: number;
+ weeks?: number;
+ months?: number;
+ years?: number;
+ }
+
+ interface Webhook {
+ url: string;
}
interface ApiDefinition {
diff --git a/base16/base16-tests.ts b/base16/base16-tests.ts
new file mode 100644
index 0000000000..e4cf78d559
--- /dev/null
+++ b/base16/base16-tests.ts
@@ -0,0 +1,24 @@
+///
+
+import * as base16 from 'base16';
+
+const colorScheme: base16.ColorScheme = base16.solarized
+
+const scheme: string = colorScheme.scheme
+const author: string = colorScheme.author
+const base00: string = colorScheme.base00
+const base01: string = colorScheme.base01
+const base02: string = colorScheme.base02
+const base03: string = colorScheme.base03
+const base04: string = colorScheme.base04
+const base05: string = colorScheme.base05
+const base06: string = colorScheme.base06
+const base07: string = colorScheme.base07
+const base08: string = colorScheme.base08
+const base09: string = colorScheme.base09
+const base0A: string = colorScheme.base0A
+const base0B: string = colorScheme.base0B
+const base0C: string = colorScheme.base0C
+const base0D: string = colorScheme.base0D
+const base0E: string = colorScheme.base0E
+const base0F: string = colorScheme.base0F
diff --git a/base16/base16.d.ts b/base16/base16.d.ts
new file mode 100644
index 0000000000..32717e99f2
--- /dev/null
+++ b/base16/base16.d.ts
@@ -0,0 +1,70 @@
+// Type definitions for base16-js 1.0.0
+// Project: https://github.com/gaearon/base16-js
+// Definitions by: Alec Hill
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+declare module 'base16' {
+
+ /**
+ * Type describing a syntax highlighting scheme as a JS object, as used in redux dev tools
+ * Based on https://github.com/chriskempson/base16
+ */
+ export interface ColorScheme {
+ scheme: string
+ author: string
+ base00: string
+ base01: string
+ base02: string
+ base03: string
+ base04: string
+ base05: string
+ base06: string
+ base07: string
+ base08: string
+ base09: string
+ base0A: string
+ base0B: string
+ base0C: string
+ base0D: string
+ base0E: string
+ base0F: string
+ }
+
+ // predefined schemes...
+ export var threezerotwofour: ColorScheme
+ export var apathy: ColorScheme
+ export var ashes: ColorScheme
+ export var atelierDune: ColorScheme
+ export var atelierForest: ColorScheme
+ export var atelierHeath: ColorScheme
+ export var atelierLakeside: ColorScheme
+ export var atelierSeaside: ColorScheme
+ export var bespin: ColorScheme
+ export var brewer: ColorScheme
+ export var bright: ColorScheme
+ export var chalk: ColorScheme
+ export var codeschool: ColorScheme
+ export var colors: ColorScheme
+ export var eighties: ColorScheme
+ export var embers: ColorScheme
+ export var flat: ColorScheme
+ export var google: ColorScheme
+ export var grayscale: ColorScheme
+ export var greenscreen: ColorScheme
+ export var harmonic: ColorScheme
+ export var hopscotch: ColorScheme
+ export var isotope: ColorScheme
+ export var marrakesh: ColorScheme
+ export var monokai: ColorScheme
+ export var ocean: ColorScheme
+ export var paraiso: ColorScheme
+ export var pop: ColorScheme
+ export var railscasts: ColorScheme
+ export var shapeshifter: ColorScheme
+ export var solarized: ColorScheme
+ export var summerfruit: ColorScheme
+ export var tomorrow: ColorScheme
+ export var tube: ColorScheme
+ export var twilight: ColorScheme
+
+}
diff --git a/braintree-web/braintree-web-tests.ts b/braintree-web/braintree-web-tests.ts
new file mode 100644
index 0000000000..40b34df418
--- /dev/null
+++ b/braintree-web/braintree-web-tests.ts
@@ -0,0 +1,432 @@
+///
+
+let version: string = braintree.VERSION;
+
+let clientToken: string = "eyJ2ZXJzaW9uIjoyLCJhdXRob3JpemF0aW9uRmluZ2VycHJpbnQiOiI0YjlhYzVmYmI4ZTNkYzQzMmFkZjJhNzBlNjZlMWNjY2M5ODRkYzE4ZTM4YmY4NjYzZTM5NjM3NWZjYmQzY2U5fGNyZWF0ZWRfYXQ9MjAxNi0wOS0wOFQwNTowMzo0MC4xNjk1NTUwMzUrMDAwMFx1MDAyNm1lcmNoYW50X2lkPTM0OHBrOWNnZjNiZ3l3MmJcdTAwMjZwdWJsaWNfa2V5PTJuMjQ3ZHY4OWJxOXZtcHIiLCJjb25maWdVcmwiOiJodHRwczovL2FwaS5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tOjQ0My9tZXJjaGFudHMvMzQ4cGs5Y2dmM2JneXcyYi9jbGllbnRfYXBpL3YxL2NvbmZpZ3VyYXRpb24iLCJjaGFsbGVuZ2VzIjpbXSwiZW52aXJvbm1lbnQiOiJzYW5kYm94IiwiY2xpZW50QXBpVXJsIjoiaHR0cHM6Ly9hcGkuc2FuZGJveC5icmFpbnRyZWVnYXRld2F5LmNvbTo0NDMvbWVyY2hhbnRzLzM0OHBrOWNnZjNiZ3l3MmIvY2xpZW50X2FwaSIsImFzc2V0c1VybCI6Imh0dHBzOi8vYXNzZXRzLmJyYWludHJlZWdhdGV3YXkuY29tIiwiYXV0aFVybCI6Imh0dHBzOi8vYXV0aC52ZW5tby5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tIiwiYW5hbHl0aWNzIjp7InVybCI6Imh0dHBzOi8vY2xpZW50LWFuYWx5dGljcy5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tLzM0OHBrOWNnZjNiZ3l3MmIifSwidGhyZWVEU2VjdXJlRW5hYmxlZCI6dHJ1ZSwicGF5cGFsRW5hYmxlZCI6dHJ1ZSwicGF5cGFsIjp7ImRpc3BsYXlOYW1lIjoiQWNtZSBXaWRnZXRzLCBMdGQuIChTYW5kYm94KSIsImNsaWVudElkIjpudWxsLCJwcml2YWN5VXJsIjoiaHR0cDovL2V4YW1wbGUuY29tL3BwIiwidXNlckFncmVlbWVudFVybCI6Imh0dHA6Ly9leGFtcGxlLmNvbS90b3MiLCJiYXNlVXJsIjoiaHR0cHM6Ly9hc3NldHMuYnJhaW50cmVlZ2F0ZXdheS5jb20iLCJhc3NldHNVcmwiOiJodHRwczovL2NoZWNrb3V0LnBheXBhbC5jb20iLCJkaXJlY3RCYXNlVXJsIjpudWxsLCJhbGxvd0h0dHAiOnRydWUsImVudmlyb25tZW50Tm9OZXR3b3JrIjp0cnVlLCJlbnZpcm9ubWVudCI6Im9mZmxpbmUiLCJ1bnZldHRlZE1lcmNoYW50IjpmYWxzZSwiYnJhaW50cmVlQ2xpZW50SWQiOiJtYXN0ZXJjbGllbnQzIiwiYmlsbGluZ0FncmVlbWVudHNFbmFibGVkIjp0cnVlLCJtZXJjaGFudEFjY291bnRJZCI6ImFjbWV3aWRnZXRzbHRkc2FuZGJveCIsImN1cnJlbmN5SXNvQ29kZSI6IlVTRCJ9LCJjb2luYmFzZUVuYWJsZWQiOmZhbHNlLCJtZXJjaGFudElkIjoiMzQ4cGs5Y2dmM2JneXcyYiIsInZlbm1vIjoib2ZmIn0=";
+
+braintree.client.create({
+ authorization: clientToken
+}, function (error: BraintreeError, clientInstance: any) {
+
+ var form: HTMLFormElement = document.getElementById('my-form-id') as HTMLFormElement;
+ var data: { creditCard: BraintreeWeb.CreditCardInfo } = {
+ creditCard: {
+ number: form['cc-number'].value,
+ cvv: form['cc-cvv'].value,
+ expirationDate: form['cc-date'].value,
+ billingAddress: {
+ postalCode: form['cc-postal'].value
+ }
+ }
+ };
+
+ clientInstance.request({
+ endpoint: 'payment_methods/credit_cards',
+ method: 'post',
+ data: data
+ }, function (requestErr: BraintreeError, response: { creditCards: any[]; }) {
+ if (requestErr) { throw new Error(requestErr.message); }
+
+ console.log('Got nonce:', response.creditCards[0].nonce);
+ });
+
+ braintree.hostedFields.create({
+ client: clientInstance,
+ styles: {
+ 'input': {
+ 'font-size': '16pt',
+ 'color': '#3A3A3A'
+ },
+
+ '.number': {
+ 'font-family': 'monospace'
+ },
+ '.valid': {
+ 'color': 'green'
+ }
+ },
+ fields: {
+ number: {
+ selector: '#card-number'
+ },
+ cvv: {
+ selector: '#cvv'
+ },
+ expirationDate: {
+ selector: '#expiration-date'
+ }
+ }
+ }, function (hostedFieldsErr?: BraintreeError, hostedFieldsInstance?: any) {
+
+ if (hostedFieldsErr) {
+ // Handle error in Hosted Fields creation
+ console.log(`Error Code: ${error.code}, Type: ${error.type}, Message: ${error.message}, Details: ${error.details}`);
+ return;
+ }
+
+ let form = new HTMLFormElement();
+
+ form.addEventListener('submit', function (event: Event) {
+ event.preventDefault();
+
+ hostedFieldsInstance.tokenize(function (tokenizeErr: BraintreeError, payload: BraintreeWeb.HostedFieldsTokenizePayload) {
+ if (tokenizeErr) {
+ // Handle error in Hosted Fields tokenization
+ switch (tokenizeErr.code) {
+ case 'HOSTED_FIELDS_FIELDS_EMPTY':
+ console.error('All fields are empty! Please fill out the form.');
+ break;
+ case 'HOSTED_FIELDS_FIELDS_INVALID':
+ console.error('Some fields are invalid:', tokenizeErr.details.invalidFieldKeys);
+ break;
+ case 'HOSTED_FIELDS_FAILED_TOKENIZATION':
+ console.error('Tokenization failed server side. Is the card valid?');
+ break;
+ case 'HOSTED_FIELDS_TOKENIZATION_NETWORK_ERROR':
+ console.error('Network error occurred when tokenizing.');
+ break;
+ default:
+ console.error('Something bad happened!', tokenizeErr);
+ }
+ return;
+ }
+
+ // Put `payload.nonce` into the `payment-method-nonce` input, and then
+ // submit the form. Alternatively, you could send the nonce to your server
+ // with AJAX.
+ (document.querySelector('input[name="payment-method-nonce"]') as HTMLInputElement).value = payload.nonce;
+ form.submit();
+ });
+ }, false);
+
+ hostedFieldsInstance.on('focus', function (event: BraintreeWeb.HostedFieldsStateObject) {
+ console.log(event.emittedBy, 'has been focused');
+ });
+
+ hostedFieldsInstance.teardown(function (teardownErr: BraintreeError) {
+ if (teardownErr) {
+ console.error('Could not tear down Hosted Fields!');
+ } else {
+ console.info('Hosted Fields has been torn down!');
+ }
+ });
+
+ hostedFieldsInstance.tokenize({
+ vault: true
+ }, function (tokenizeErr: BraintreeError, payload: BraintreeWeb.HostedFieldsTokenizePayload) {
+ if (tokenizeErr) {
+ console.error(tokenizeErr);
+ } else {
+ console.log('Got nonce:', payload.nonce);
+ }
+ });
+
+ hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: BraintreeError) {
+ if (addClassErr) {
+ console.error(addClassErr);
+ }
+ });
+
+ hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr: BraintreeError) {
+ if (addClassErr) {
+ console.error(addClassErr);
+ return;
+ }
+
+ // some time later...
+ hostedFieldsInstance.removeClass('number', 'custom-class');
+ });
+
+ hostedFieldsInstance.setPlaceholder('number', '4111 1111 1111 1111', function (placeholderErr: BraintreeError) {
+ if (placeholderErr) {
+ console.error(placeholderErr);
+ }
+ });
+
+ hostedFieldsInstance.on('cardTypeChange', function (event: BraintreeWeb.HostedFieldsStateObject) {
+ // Update the placeholder value if there is only one possible card type
+ if (event.cards.length === 1) {
+ braintree.hostedFields.setPlaceholder('cvv', event.cards[0].code.name, function (placeholderErr: BraintreeError) {
+ if (placeholderErr) {
+ // Handle errors, such as invalid field name
+ console.error(placeholderErr);
+ }
+ });
+ }
+ });
+
+ hostedFieldsInstance.clear('number', function (clearErr: BraintreeError) {
+ if (clearErr) {
+ console.error(clearErr);
+ }
+ });
+
+ hostedFieldsInstance.clear('number');
+ hostedFieldsInstance.clear('cvv');
+ hostedFieldsInstance.clear('expirationDate');
+
+ var state = braintree.hostedFields.getState();
+
+ var formValid = Object.keys(state.fields).every(function (key) {
+ return state.fields[key].isValid;
+ });
+ });
+
+ braintree.applePay.create({ client: clientInstance }, function (createErr?: BraintreeError, applePayInstance?: any) {
+ if (createErr) {
+ // Handle error in client creation
+ console.log(`Error Code: ${error.code}, Type: ${error.type}, Message: ${error.message}, Details: ${error.details}`);
+
+ return;
+ }
+
+ let request = {
+ countryCode: 'US',
+ currencyCode: 'USD',
+ supportedNetworks: ['visa', 'masterCard'],
+ merchantCapabilities: ['supports3DS'],
+ total: { label: 'Your Label', amount: '10.00' },
+ };
+
+ var paymentRequest = braintree.applePay.createPaymentRequest(request);
+
+ console.log(paymentRequest);
+ // { total: { }, countryCode: 'US', currencyCode: 'USD', merchantCapabilities: [ ], supportedNetworks: [ ] }
+ });
+
+ braintree.applePay.create({ client: clientInstance }, function (createErr, applePayInstance) {
+ let request = {
+ countryCode: 'US',
+ currencyCode: 'USD',
+ supportedNetworks: ['visa', 'masterCard'],
+ merchantCapabilities: ['supports3DS'],
+ total: { label: 'Your Label', amount: '10.00' },
+ };
+
+ var session = new ApplePaySession(1, request);
+
+ session.onvalidatemerchant = function (event: { validationURL: string }) {
+ braintree.applePay.performValidation({
+ validationURL: event.validationURL
+ }, function (err, validationData) {
+ if (err) {
+ console.error(err);
+ session.abort();
+ return;
+ }
+ session.completeMerchantValidation(validationData);
+ });
+ };
+ });
+
+ braintree.applePay.create({ client: clientInstance }, function (createErr, applePayInstance) {
+ let request = {
+ countryCode: 'US',
+ currencyCode: 'USD',
+ supportedNetworks: ['visa', 'masterCard'],
+ merchantCapabilities: ['supports3DS'],
+ total: { label: 'Your Label', amount: '10.00' },
+ };
+
+ var session = new ApplePaySession(1, request);
+
+ session.onpaymentauthorized = function (event) {
+ braintree.applePay.tokenize({
+ token: event.payment.token
+ }, function (err, tokenizedPayload) {
+ if (err) {
+ session.completePayment(ApplePayStatusCodes.STATUS_FAILURE);
+ return;
+ }
+ session.completePayment(ApplePayStatusCodes.STATUS_SUCCESS);
+
+ // Send the tokenizedPayload to your server.
+ });
+ };
+ });
+
+ braintree.paypal.create({
+ client: clientInstance
+ }, function (createErr, paypalInstance) {
+ if (createErr) {
+ if (createErr.code === 'PAYPAL_BROWSER_NOT_SUPPORTED') {
+ console.error('This browser is not supported.');
+ } else {
+ console.error('Error!', createErr);
+ }
+ }
+
+ let button = new HTMLButtonElement();
+
+ button.addEventListener('click', function () {
+ // Disable the button so that we don't attempt to open multiple popups.
+ button.setAttribute('disabled', 'disabled');
+
+ // Because PayPal tokenization opens a popup, this must be called
+ // as a result of a user action, such as a button click.
+ paypalInstance.tokenize({
+ flow: 'vault' // Required
+ // Any other tokenization options
+ }, function (tokenizeErr: BraintreeError, payload: BraintreeWeb.PayPalTokenizePayload) {
+ button.removeAttribute('disabled');
+
+ if (tokenizeErr) {
+ // Handle tokenization errors or premature flow closure
+
+ switch (tokenizeErr.code) {
+ case 'PAYPAL_POPUP_CLOSED':
+ console.error('Customer closed PayPal popup.');
+ break;
+ case 'PAYPAL_ACCOUNT_TOKENIZATION_FAILED':
+ console.error('PayPal tokenization failed. See details:', tokenizeErr.details);
+ break;
+ case 'PAYPAL_FLOW_FAILED':
+ console.error('Unable to initialize PayPal flow. Are your options correct?', tokenizeErr.details);
+ break;
+ default:
+ console.error('Error!', tokenizeErr);
+ }
+ } else {
+ // Submit payload.nonce to your server
+ }
+ });
+ });
+ });
+
+ braintree.unionpay.create({ client: clientInstance }, function (createErr, unionpayInstance) {
+ if (createErr) {
+ console.error(createErr);
+ return;
+ }
+
+ unionpayInstance.fetchCapabilities({
+ card: {
+ number: '4111111111111111'
+ }
+ }, function (fetchErr: BraintreeError, cardCapabilities: BraintreeWeb.UnionPayFetchCapabilitiesPayload) {
+ if (fetchErr) {
+ console.error(fetchErr);
+ return;
+ }
+
+ if (cardCapabilities.isUnionPay) {
+ if (cardCapabilities.unionPay && !cardCapabilities.unionPay.isSupported) {
+ // Braintree cannot process this UnionPay card.
+ // Ask the user for a different card.
+ return;
+ }
+
+ if (cardCapabilities.isDebit) {
+ // CVV and expiration date are not required
+ } else {
+ // CVV and expiration date are required
+ }
+
+ // Show mobile phone number field for enrollment
+ }
+ });
+
+ unionpayInstance.enroll({
+ card: {
+ number: '4111111111111111',
+ expirationMonth: '12',
+ expirationYear: '2038'
+ },
+ mobile: {
+ countryCode: '62',
+ number: '111111111111'
+ }
+ }, function (enrollErr: BraintreeError, response: BraintreeWeb.UnionPayEnrollPayload) {
+ if (enrollErr) {
+ console.error(enrollErr);
+ return;
+ }
+
+ if (response.smsCodeRequired) {
+ // If smsCodeRequired, wait for SMS auth code from customer
+ // Then use response.enrollmentId during {@link UnionPay#tokenize}
+ } else {
+ // SMS code is not required from the user.
+ // {@link UnionPay#tokenize} can be called immediately
+ }
+ });
+
+ let enrollResponse: {
+ enrollmentId: string
+ };
+
+ unionpayInstance.tokenize({
+ card: {
+ number: '4111111111111111',
+ expirationMonth: '12',
+ expirationYear: '2038',
+ cvv: '123'
+ },
+ enrollmentId: enrollResponse.enrollmentId, // Returned from enroll
+ smsCode: '11111' // Received by customer's phone, if SMS enrollment was required. Otherwise it should be omitted
+ }, function (tokenizeErr: BraintreeError, response: BraintreeWeb.UnionPayTokenizePayload) {
+ if (tokenizeErr) {
+ console.error(tokenizeErr);
+ return;
+ }
+
+ // Send response.nonce to your server
+ });
+
+ unionpayInstance.teardown(function (teardownErr: BraintreeError) {
+ if (teardownErr) {
+ console.error('Could not tear down UnionPay.');
+ } else {
+ console.log('UnionPay has been torn down.');
+ }
+ });
+ });
+});
+
+let existingNonce = "fake-valid-nonce";
+let submitNonceToServer: (nonce: string) => void;
+
+braintree.threeDSecure.verifyCard({
+ nonce: existingNonce,
+ amount: 123.45,
+ addFrame: function (err, iframe) {
+ // Set up your UI and add the iframe.
+ let my3DSContainer = document.createElement('div');
+ my3DSContainer.appendChild(iframe);
+ document.body.appendChild(my3DSContainer);
+ },
+ removeFrame: function () {
+ let my3DSContainer = document.createElement('div');
+
+ // Remove UI that you added in addFrame.
+ document.body.removeChild(my3DSContainer);
+ }
+}, function (err: BraintreeError, payload: BraintreeWeb.ThreeDSecureVerifyPayload) {
+ if (err) {
+ console.error(err);
+ return;
+ }
+
+ if (payload.liabilityShifted) {
+ // Liablity has shifted
+ submitNonceToServer(payload.nonce);
+ } else if (payload.liabilityShiftPossible) {
+ // Liablity may still be shifted
+ // Decide if you want to submit the nonce
+ } else {
+ // Liablity has not shifted and will not shift
+ // Decide if you want to submit the nonce
+ }
+});
+
+braintree.threeDSecure.cancelVerifyCard(function (err: BraintreeError, verifyPayload: BraintreeWeb.ThreeDSecureVerifyPayload) {
+ if (err) {
+ // Handle error
+ console.log(err.message); // No verification payload available
+ return;
+ }
+
+ verifyPayload.nonce; // The nonce returned from the 3ds lookup call
+ verifyPayload.liabilityShifted; // boolean
+ verifyPayload.liabilityShiftPossible; // boolean
+});
\ No newline at end of file
diff --git a/braintree-web/braintree-web.d.ts b/braintree-web/braintree-web.d.ts
new file mode 100644
index 0000000000..2cf2d89467
--- /dev/null
+++ b/braintree-web/braintree-web.d.ts
@@ -0,0 +1,1738 @@
+// Type definitions for Braintree-web v3.0.2
+// Project: https://github.com/braintree/braintree-web
+// Definitions by: Guy Shahine
+// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
+
+/**
+ * @module braintree-web/american-express
+ * @description This module is for use with Amex Express Checkout. To accept American Express cards, use Hosted Fields.
+ */
+declare namespace BraintreeWeb {
+ export interface AmericanExpress {
+ /**
+ * @static
+ * @function create
+ * @param {object} options Creation options:
+ * @param {Client} options.client A {@link Client} instance.
+ * @param {callback} callback The second argument, `data`, is the {@link AmericanExpress} instance.
+ * @returns {void}
+ */
+ create: (options: { client: Client }, callback: callback) => void;
+
+ /**
+ * @description The current version of the SDK, i.e. `3.0.2`.
+ * @type {string}
+ */
+ VERSION: string;
+ }
+
+ /**
+ * @class
+ * @param {object} options Options
+ * @description You cannot use this constructor directly. Use {@link module:braintree-web/american-express.create|braintree.american-express.create} instead.
+ * @classdesc This class allows you use a nonce to interact with American Express Checkout. To accept American Express cards, use Hosted Fields.
+ */
+ export class AmericanExpress {
+ /**
+ * @class
+ * @param {object} options Options
+ * @description You cannot use this constructor directly. Use {@link module:braintree-web/american-express.create|braintree.american-express.create} instead.
+ * @classdesc This class allows you use a nonce to interact with American Express Checkout. To accept American Express cards, use Hosted Fields.
+ */
+ constructor(options: any);
+
+ /**
+ * Gets the rewards balance associated with a Braintree nonce.
+ * @public
+ * @param {object} options Request options
+ * @param {string} options.nonce An existing Braintree nonce.
+ * @param {callback} callback The second argument, data, is the returned server data.
+ * @returns {void}
+ * @example
+ * var americanExpress = require('braintree-web/american-express');
+ *
+ * americanExpress.create({client: clientInstance}, function (createErr, americanExpressInstance) {
+ * var options = {nonce: existingBraintreeNonce};
+ * americanExpressInstance.getRewardsBalance(options, function (getErr, payload) {
+ * if (getErr || payload.error) {
+ * // Handle error
+ * return;
+ * }
+ *
+ * console.log('Rewards amount: ' + payload.rewardsAmount);
+ * });
+ * });
+ */
+ public getRewardsBalance(options: { nonce: string }, callback: callback): void;
+
+ /**
+ * Gets the Express Checkout nonce profile given a nonce from American Express.
+ * @public
+ * @param {object} options Request options
+ * @param {string} options.nonce An existing nonce from American Express (note that this is not a nonce from Braintree).
+ * @param {callback} callback The second argument, data, is the returned server data.
+ * @returns {void}
+ * @example
+ * var americanExpress = require('braintree-web/american-express');
+ *
+ * americanExpress.create({client: clientInstance}, function (createErr, americanExpressInstance) {
+ * var options = {nonce: existingAmericanExpressNonce};
+ * americanExpressInstance.getExpressCheckoutProfile(options, function (getErr, payload) {
+ * if (getErr) {
+ * // Handle error
+ * return;
+ * }
+ *
+ * console.log('Number of cards: ' + payload.amexExpressCheckoutCards.length);
+ * });
+ * });
+ */
+ public getExpressCheckoutProfile(options: { nonce: string }, callback: callback): void;
+ }
+}
+
+
+// more info https://developer.apple.com/reference/applepayjs/1916082-applepay_js_data_types/paymentrequest
+
+// billingContact
+// Billing contact information for the user.
+// countryCode
+//Required.The merchant’s two- letter ISO 3166 country code.
+// currencyCode
+// Required.The three- letter ISO 4217 currency code for the payment.
+// lineItems
+//A set of line items that explain recurring payments and additional charges.
+// merchantCapabilities
+// Required.The payment capabilities supported by the merchant.The value must be one or more of supports3DS, supportsEMV, supportsCredit, or supportsDebit.
+// requiredBillingContactFields
+// The billing information that is required from the user.The value must be one or more of postalAddress, phone, email, or name.
+// requiredShippingContactFields
+// The shipping information that is required from the user.The value must be one or more of postalAddress, phone, email, or name.
+// shippingContact
+// Shipping contact information for the user.
+// shippingMethods
+//A set of available shipping methods.Totals for all shipping methods must be non- negative to pass validation.
+// shippingType
+// How the items are to be shipped.This property is optional.If specified, it must be one or more of shipping, delivery, storePickup, or servicePickup.The default value is shipping.
+// supportedNetworks
+// Required.The payment networks supported by the merchant.The value must be one or more of amex, discover, interac, masterCard, privateLabel, or visa.
+// total
+// Required.The total amount for the payment.The total must be greater than zero and have a label to pass validation.
+interface ApplePayPaymentRequest {
+ total: {
+ label: string;
+ amount: string;
+ };
+ countryCode: string;
+ currencyCode: string;
+ supportedNetworks: string[];
+ merchantCapabilities: string[];
+
+ billingContact?: any;
+ shippingContact?: any;
+ shippingMethods?: any;
+ shippingType?: any;
+ requiredBillingContactFields?: any;
+ requiredShippingContactFields?: any;
+}
+
+declare enum ApplePayStatusCodes {
+ // The requested action succeeded.
+ STATUS_SUCCESS = 1,
+ // The requested action failed.
+ STATUS_FAILURE,
+ // The billing address is not valid.
+ STATUS_INVALID_BILLING_POSTAL_ADDRESS,
+ // The shipping address is not valid.
+ STATUS_INVALID_SHIPPING_POSTAL_ADDRESS,
+ // The shipping contact information is not valid.
+ STATUS_INVALID_SHIPPING_CONTACT,
+ // The required PIN information was not provided. Cards on the China Union Pay payment network may require a PIN to authenticate the transaction.
+ STATUS_PIN_REQUIRED,
+ // The PIN information is not valid.Cards on the China Union Pay network may require a PIN.
+ STATUS_PIN_INCORRECT,
+ // The maximum number of tries for a PIN has been reached and the user has been locked out. Cards on the China Union Pay network may require a PIN.
+ STATUS_PIN_LOCKOUT,
+}
+
+interface ApplePayPayload {
+ merchantIdentifier: string;
+ domainName: string;
+ displayName: string;
+}
+
+declare class ApplePaySession {
+ constructor(version: number, request: ApplePayPaymentRequest);
+
+ canMakePayments(): boolean;
+
+ canMakePaymentsWithActiveCard(merchantIdentifier: string): boolean;
+
+ completeMerchantValidation(merchantSession: any): void;
+
+ abort(): void;
+
+ begin(): void;
+
+ completePayment(status: ApplePayStatusCodes): void;
+
+ completePaymentMethodSelection(newTotal: any, newLineItems: any): void;
+
+ completeShippingContactSelection(status: ApplePayStatusCodes, newShippingMethods: any, newTotal: any, newLineItems: any): void;
+
+ completeShippingMethodSelection(status: ApplePayStatusCodes, newTotal: any, newLineItems: any): void;
+
+ supportsVersion(version: number): boolean;
+
+ oncancel: (event: any) => void;
+
+ onpaymentauthorized: (event: any) => void;
+
+ onpaymentmethodselected: (event: any) => void;
+
+ onshippingcontactselected: (event: any) => void;
+
+ onshippingmethodselected: (event: any) => void;
+
+ onvalidatemerchant: (event: any) => void;
+}
+
+/**
+ * @module braintree-web/apple-pay
+ * @description Accept Apple Pay on the Web. *This component is currently in beta and is subject to change.*
+ */
+declare namespace BraintreeWeb {
+ export interface ApplePay {
+ /**
+ * @static
+ * @function create
+ * @param {object} options Creation options:
+ * @param {Client} options.client A {@link Client} instance.
+ * @param {callback} callback The second argument, `data`, is the {@link ApplePay} instance.
+ * @returns {void}
+ */
+ create: (options: { client: Client }, callback: callback) => void;
+
+ /**
+ * @description The current version of the SDK, i.e. `3.0.2`.
+ * @type {string}
+ */
+ VERSION: string;
+ }
+
+ /**
+ * @class
+ * @param {object} options Options
+ * @description You cannot use this constructor directly. Use {@link module:braintree-web/apple-pay.create|braintree.apple-pay.create} instead.
+ * @classdesc This class represents an Apple Pay component. Instances of this class have methods for validating the merchant server and tokenizing payments.
+ */
+ export class ApplePay {
+ /**
+ * @class
+ * @param {object} options Options
+ * @description You cannot use this constructor directly. Use {@link module:braintree-web/apple-pay.create|braintree.apple-pay.create} instead.
+ * @classdesc This class represents an Apple Pay component. Instances of this class have methods for validating the merchant server and tokenizing payments.
+ */
+ constructor(options: any);
+
+ /**
+ * Merges a payment request with Braintree defaults
+ * The following properties are assigned to `paymentRequest` if not already defined
+ * - countryCode
+ * - currencyCode
+ * - merchantCapabilities
+ * - supportedNetworks
+ * @public
+ * @param {external:ApplePayPaymentRequest} paymentRequest The payment request details to apply on top of those from Braintree.
+ * @returns {external:ApplePayPaymentRequest} The decorated `paymentRequest`.
+ * @example
+ * var applePay = require('braintree-web/apple-pay');
+ *
+ * applePay.create({client: clientInstance}, function (createErr, applePayInstance) {
+ * // ...
+ * var paymentRequest = applePay.createPaymentRequest({
+ * total: {
+ * label: 'My Company',
+ * amount: '19.99'
+ * });
+ *
+ * console.log(paymentRequest);
+ * // { total: { }, countryCode: 'US', currencyCode: 'USD', merchantCapabilities: [ ], supportedNetworks: [ ] }
+ *
+ */
+ public createPaymentRequest(paymentRequest: ApplePayPaymentRequest): ApplePayPaymentRequest
+
+ /**
+ * Validates the merchant website, as required by ApplePaySession before payment can be authorized.
+ * @public
+ * @param {object} options Options
+ * @param {string} options.validationURL The validationURL fram an ApplePayValidateMerchantEvent.
+ * @param {string} [options.displayName]
+ * - The canonical name for your store.
+ * - The system may display this name to the user.
+ * - Use a 128-character or less, UTF-8 string.
+ * - Do not localize the name.
+ * @param {string} [options.merchantIdentifier]
+ * Your Apple merchant identifier. This is the Apple Merchant ID created on the Apple Developer Portal.
+ * Defaults to the merchant identifier specified in the Braintree Control Panel.
+ * You can use this field to override the merchant identifier for this transaction.
+ * @param {callback} callback The second argument, data, is the Apple Pay merchant session object.
+ * Pass the merchant session to your Apple Pay session's completeMerchantValidation method.
+ * @returns {void}
+ * @example
+ * var applePay = require('braintree-web/apple-pay');
+ *
+ * applePay.create({client: clientInstance}, function (createErr, applePayInstance) {
+ * var session = new ApplePaySession(1, {
+ * // This should be the payment request object that
+ * // contains the information needed to display the payment sheet.
+ * });
+ *
+ * session.onvalidatemerchant = function (event) {
+ * applePay.performValidation({
+ * validationURL: event.validationURL
+ * }, function(err, validationData) {
+ * if (err) {
+ * console.error(err);
+ * session.abort();
+ * return;
+ * }
+ * session.completeMerchantValidation(validationData);
+ * });
+ * };
+ * });
+ */
+ public performValidation(options: { validationURL: string, displayName?: string, merchantIdentifier?: string }, callback: callback): void;
+
+ /**
+ * Tokenizes an Apple Pay payment.
+ * @public
+ * @param {object} options Options
+ * @param {object} options.token The `payment.token` property of an {@link external:ApplePayPaymentAuthorizedEvent}
+ * @param {callback} callback The second argument, data, is the tokenized payload.
+ * @returns {void}
+ * @example
+ * var applePay = require('braintree-web/apple-pay');
+ *
+ * applePay.create({client: clientInstance}, function (createErr, applePayInstance) {
+ * var session = new ApplePaySession(1, { });
+ *
+ * session.onpaymentauthorized = function (event) {
+ * applePay.tokenize({
+ * token: event.payment.token
+ * }, function (err, tokenizedPayload) {
+ * if (err) {
+ * session.completePayment(ApplePaySession.STATUS_FAILURE);
+ * return;
+ * }
+ * session.completePayment(ApplePaySession.STATUS_SUCCESS);
+ *
+ * // Send the tokenizedPayload to your server.
+ * });
+ * };
+ * });
+ */
+ public tokenize(options: { token: any }, callback: callback): void;
+
+ }
+}
+
+/** @module braintree-web/client */
+declare namespace BraintreeWeb {
+ /**
+ * This object is returned by {@link Client#getConfiguration|getConfiguration}. This information is used extensively by other Braintree modules to properly configure themselves.
+ * @typedef {object} Client~configuration
+ * @property {object} client The braintree-web/client parameters.
+ * @property {string} client.authorization A tokenizationKey or clientToken.
+ * @property {object} gatewayConfiguration Gateway-supplied configuration.
+ * @property {object} analyticsMetadata Analytics-specific data.
+ * @property {string} analyticsMetadata.sessionId Uniquely identifies a browsing session.
+ * @property {string} analyticsMetadata.sdkVersion The braintree.js version.
+ * @property {string} analyticsMetadata.merchantAppId Identifies the merchant's web app.
+ */
+ interface ClientAnalyticsMetadata {
+ sessionId: string;
+ sdkVersion: string;
+ merchantAppId: string;
+ }
+
+ interface Configuration {
+ client: Client;
+ gatewayConfiguration: any;
+ analyticsMetadata: ClientAnalyticsMetadata;
+ }
+
+ interface CreditCardInfo {
+ number: string;
+ cvv: string;
+ expirationDate: string;
+ billingAddress: {
+ postalCode?: string;
+ }
+ }
+
+ export interface Client {
+ authorization: string;
+
+ /**
+ * @function
+ * @description This function is the entry point for the braintree.client module. It is used for creating {@link Client} instances that service communication to Braintree servers.
+ * @param {object} options Object containing all {@link Client} options:
+ * @param {string} options.authorization A tokenizationKey or clientToken.
+ * @param {callback} callback The second argument, data, is the {@link Client} instance.
+ * @returns {void}
+ * @example
+ * var createClient = require('braintree-web/client').create;
+ *
+ * createClient({
+ * authorization: CLIENT_AUTHORIZATION
+ * }, function (createErr, clientInstance) {
+ * ...
+ * });
+ * @static
+ */
+ create: (options: { authorization: string }, callback: callback) => void;
+
+ /**
+ * @description The current version of the SDK, i.e. `3.0.2`.
+ * @type {string}
+ */
+ VERSION: string;
+ }
+
+ /**
+ * @class
+ * @param {Client~configuration} configuration Options
+ * @description Do not use this constructor directly. Use {@link module:braintree-web/client.create|braintree.client.create} instead.
+ * @classdesc This class is required by many other Braintree components. It serves as the base API layer that communicates with our servers. It is also capable of being used to formulate direct calls to our servers, such as direct credit card tokenization. See {@link Client#request}.
+ */
+ export class Client {
+ /**
+ * @class
+ * @param {Client~configuration} configuration Options
+ * @description Do not use this constructor directly. Use {@link module:braintree-web/client.create|braintree.client.create} instead.
+ * @classdesc This class is required by many other Braintree components. It serves as the base API layer that communicates with our servers. It is also capable of being used to formulate direct calls to our servers, such as direct credit card tokenization. See {@link Client#request}.
+ */
+ constructor(configuration: Configuration);
+
+
+ /**
+ * Returns a copy of the configuration values.
+ * @public
+ * @returns {Client~configuration} configuration
+ */
+ public getConfiguration(): Configuration;
+
+ /**
+ * Used by other modules to formulate all network requests to the Braintree gateway. It is also capable of being used directly from your own form to tokenize credit card information. However, be sure to satisfy PCI compliance if you use direct card tokenization.
+ * @public
+ * @param {object} options Request options:
+ * @param {string} options.method HTTP method. i.e. "get" or "post"
+ * @param {string} options.endpoint Enpoint path. i.e. "payment_methods"
+ * @param {object} options.data Data to send with the request
+ * @param {string} [options.timeout=60000] Timeout limit
+ * @param {callback} callback The second argument, data, is the returned server data.
+ * @example
+ *
Direct Credit Card Tokenization
+ * var createClient = require('braintree-web/client').create;
+ *
+ * createClient({
+ * authorization: CLIENT_AUTHORIZATION
+ * }, function (createErr, clientInstance) {
+ * var form = document.getElementById('my-form-id');
+ * var data = {
+ * creditCard: {
+ * number: form['cc-number'].value,
+ * cvv: form['cc-cvv'].value,
+ * expirationDate: form['cc-date'].value,
+ * billingAddress: {
+ * postalCode: form['cc-postal'].value
+ * }
+ * }
+ * };
+ *
+ * // Warning: For a merchant to be eligible for the easiest level of PCI compliance (SAQ A),
+ * // payment fields cannot be hosted on your checkout page.
+ * // For an alternative to the following, use Hosted Fields.
+ * clientInstance.request({
+ * endpoint: 'payment_methods/credit_cards',
+ * method: 'post',
+ * data: data
+ * }, function (requestErr, response) {
+ * if (requestErr) { throw new Error(requestErr); }
+ *
+ * console.log('Got nonce:', response.creditCards[0].nonce);
+ * });
+ * });
+ * @returns {void}
+ */
+ public request(options: { method: string, endpoint: string, data: any, timeout?: number }, callback: callback): void;
+
+ }
+}
+
+/** @module braintree-web/data-collector */
+declare namespace BraintreeWeb {
+ export interface DataCollector {
+ /**
+ * @static
+ * @function create
+ * @param {object} options Creation options:
+ * @param {Client} options.client A {@link Client} instance.
+ * @param {boolean} [options.kount] If true, Kount fraud data collection is enabled.
+ * @param {boolean} [options.paypal] If true, PayPal fraud data collection is enabled.
+ * @param {callback} callback The second argument, `data`, is the {@link DataCollector} instance.
+ * @returns {void}
+ */
+ create: (options: { client: Client, kount: boolean, paypal: boolean }, callback: callback) => void;
+
+ /**
+ * @description The current version of the SDK, i.e. `3.0.2`.
+ * @type {string}
+ */
+ VERSION: string;
+ }
+
+ /**
+ * @class
+ * @global
+ * @name DataCollector
+ * @description Do not use this constructor directly. Use {@link module:braintree-web/data-collector.create|braintree-web.data-collector.create} instead.
+ * @classdesc This class is used for advanced fraud integration with PayPal and Kount. Instances of this class have {@link DataCollector#deviceData|deviceData} which is used to correlate user sessions with server transactions.
+ */
+ export class DataCollector {
+ /**
+ * @class
+ * @global
+ * @name DataCollector
+ * @description Do not use this constructor directly. Use {@link module:braintree-web/data-collector.create|braintree-web.data-collector.create} instead.
+ * @classdesc This class is used for advanced fraud integration with PayPal and Kount. Instances of this class have {@link DataCollector#deviceData|deviceData} which is used to correlate user sessions with server transactions.
+ */
+ constructor();
+
+ /**
+ * @memberof DataCollector
+ * @name deviceData
+ * @type string
+ * @description JSON string to pass with server transactions.
+ * @instance
+ */
+ deviceData: string;
+
+ /**
+ * @memberof DataCollector
+ * @name teardown
+ * @function
+ * @description Cleanly remove all event handlers and DOM nodes that were added.
+ * @param {callback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully.
+ * @instance
+ * @returns {void}
+ */
+ teardown(callback?: callback): void;
+
+ }
+}
+
+/** @module braintree-web/hosted-fields */
+declare namespace BraintreeWeb {
+ /**
+ * Fields used in {@link module:braintree-web/hosted-fields~fieldOptions fields options}
+ * @typedef {object} field
+ * @property {string} selector A CSS selector to find the container where the hosted field will be inserted.
+ * @property {string} [placeholder] Will be used as the `placeholder` attribute of the input. If `placeholder` is not natively supported by the browser, it will be polyfilled.
+ * @property {boolean} [formatInput=true] - Enable or disable automatic formatting on this field. Note: Input formatting does not work properly on Android and iOS, so input formatting is automatically disabled on those browsers.
+ */
+ interface HostedFieldsField {
+ selector: string;
+ placeholder?: string;
+ formatInput?: boolean;
+ }
+
+ /**
+ * An object that has {@link module:braintree-web/hosted-fields~field field objects} for each field. Used in {@link module:braintree-web/hosted-fields~create create}.
+ * @typedef {object} fieldOptions
+ * @property {field} [number] A field for card number.
+ * @property {field} [expirationDate] A field for expiration date in `MM/YYYY` format. This should not be used with the `expirationMonth` and `expirationYear` properties.
+ * @property {field} [expirationMonth] A field for expiration month in `MM` format. This should be used with the `expirationYear` property.
+ * @property {field} [expirationYear] A field for expiration year in `YYYY` format. This should be used with the `expirationMonth` property.
+ * @property {field} [cvv] A field for 3 or 4 digit CVV or CID.
+ * @property {field} [postalCode] A field for postal or region code.
+ */
+ interface HostedFieldFieldOptions {
+ number: HostedFieldsField;
+ expirationDate?: HostedFieldsField;
+ expirationMonth?: HostedFieldsField;
+ expirationYear?: HostedFieldsField;
+ cvv: HostedFieldsField;
+ postalCode?: HostedFieldsField;
+ }
+
+ /**
+ * @typedef {object} HostedFields~hostedFieldsCard
+ * @description Information about the card type, sent in {@link HostedFields~stateObject|stateObjects}.
+ * @property {string} type The code-friendly representation of the card type. It will be one of the following strings:
+ * - `american-express`
+ * - `diners-club`
+ * - `discover`
+ * - `jcb`
+ * - `maestro`
+ * - `master-card`
+ * - `unionpay`
+ * - `visa`
+ * @property {string} niceType The pretty-printed card type. It will be one of the following strings:
+ * - `American Express`
+ * - `Diners Club`
+ * - `Discover`
+ * - `JCB`
+ * - `Maestro`
+ * - `MasterCard`
+ * - `UnionPay`
+ * - `Visa`
+ * @property {object} code
+ * This object contains data relevant to the security code requirements of the card brand.
+ * For example, on a Visa card there will be a CVV of 3 digits, whereas an
+ * American Express card requires a 4-digit CID.
+ * @property {string} code.name "CVV""CID""CVC"
+ * @property {number} code.size The expected length of the security code. Typically, this is 3 or 4.
+ */
+
+ interface HostedFieldsCardCode {
+ name: string;
+ size: number;
+ }
+
+ interface HostedFieldsHostedFieldsCard {
+ type: string;
+ niceType: string;
+ code: HostedFieldsCardCode;
+ }
+
+ /**
+ * @typedef {object} HostedFields~hostedFieldsFieldData
+ * @description Data about Hosted Fields fields, sent in {@link HostedFields~stateObject|stateObjects}.
+ * @property {HTMLElement} container Reference to the container DOM element on your page associated with the current event.
+ * @property {boolean} isFocused Whether or not the input is currently focused.
+ * @property {boolean} isEmpty Whether or not the user has entered a value in the input.
+ * @property {boolean} isPotentiallyValid
+ * A determination based on the future validity of the input value.
+ * This is helpful when a user is entering a card number and types "41".
+ * While that value is not valid for submission, it is still possible for
+ * it to become a fully qualified entry. However, if the user enters "4x"
+ * it is clear that the card number can never become valid and isPotentiallyValid will
+ * return false.
+ * @property {boolean} isValid Whether or not the value of the associated input is fully qualified for submission.
+ */
+ interface HostedFieldsHostedFieldsFieldData {
+ container: HTMLElement;
+ isFocused: boolean;
+ isEmpty: boolean;
+ isPotentiallyValid: boolean;
+ isValid: boolean;
+ }
+
+ /**
+ * @typedef {object} HostedFields~stateObject
+ * @description The event payload sent from {@link HostedFields#on|on} or {@link HostedFields#getState|getState}.
+ * @property {HostedFields~hostedFieldsCard[]} cards
+ * This will return an array of potential {@link HostedFields~hostedFieldsCard|cards}. If the card type has been determined, the array will contain only one card.
+ * Internally, Hosted Fields uses credit-card-type,
+ * an open-source card detection library.
+ * @property {string} emittedBy
+ * The name of the field associated with an event. This will not be included if returned by {@link HostedFields#getState|getState}. It will be one of the following strings:
+ * - `"number"`
+ * - `"cvv"`
+ * - `"expirationDate"`
+ * - `"expirationMonth"`
+ * - `"expirationYear"`
+ * - `"postalCode"`
+ * @property {object} fields
+ * @property {?HostedFields~hostedFieldsFieldData} fields.number {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the number field, if it is present.
+ * @property {?HostedFields~hostedFieldsFieldData} fields.cvv {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the CVV field, if it is present.
+ * @property {?HostedFields~hostedFieldsFieldData} fields.expirationDate {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the expiration date field, if it is present.
+ * @property {?HostedFields~hostedFieldsFieldData} fields.expirationMonth {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the expiration month field, if it is present.
+ * @property {?HostedFields~hostedFieldsFieldData} fields.expirationYear {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the expiration year field, if it is present.
+ * @property {?HostedFields~hostedFieldsFieldData} fields.postalCode {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the postal code field, if it is present.
+ */
+ interface HostedFieldsFieldDataFields {
+ number: HostedFieldsHostedFieldsFieldData;
+ cvv: HostedFieldsHostedFieldsFieldData;
+ expirationDate: HostedFieldsHostedFieldsFieldData;
+ expirationMonth: HostedFieldsHostedFieldsFieldData;
+ expirationYear: HostedFieldsHostedFieldsFieldData;
+ postalCode: HostedFieldsHostedFieldsFieldData;
+ }
+
+ interface HostedFieldsStateObject {
+ cards: HostedFieldsHostedFieldsCard[];
+ emittedBy: string;
+ fields: HostedFieldsFieldDataFields;
+ }
+
+ /**
+ * @typedef {object} HostedFields~tokenizePayload
+ * @property {string} nonce The payment method nonce.
+ * @property {object} details Additional account details.
+ * @property {string} details.cardType Type of card, ex: Visa, MasterCard.
+ * @property {string} details.lastTwo Last two digits of card number.
+ * @property {string} description A human-readable description.
+ * @property {string} type The payment method type, always `CreditCard`.
+ */
+ interface HostedFieldsAccountDetails {
+ cardType: string;
+ lastTwo: string;
+ }
+
+ interface HostedFieldsTokenizePayload {
+ nonce: string;
+ details: HostedFieldsAccountDetails;
+ type: string;
+ description: string;
+ }
+
+ export interface HostedFields {
+ /**
+ * @static
+ * @function create
+ * @param {object} options Creation options:
+ * @param {Client} options.client A {@link Client} instance.
+ * @param {fieldOptions} options.fields A {@link module:braintree-web/hosted-fields~fieldOptions set of options for each field}.
+ * @param {styleOptions} options.styles {@link module:braintree-web/hosted-fields~styleOptions Styles} applied to each field.
+ * @param {callback} callback The second argument, `data`, is the {@link HostedFields} instance.
+ * @returns {void}
+ * @example
+ * braintree.hostedFields.create({
+ * client: clientInstance,
+ * styles: {
+ * 'input': {
+ * 'font-size': '16pt',
+ * 'color': '#3A3A3A'
+ * },
+ * '.number': {
+ * 'font-family': 'monospace'
+ * },
+ * '.valid': {
+ * 'color': 'green'
+ * }
+ * },
+ * fields: {
+ * number: {
+ * selector: '#card-number'
+ * },
+ * cvv: {
+ * selector: '#cvv'
+ * },
+ * expirationDate: {
+ * selector: '#expiration-date'
+ * }
+ * }
+ * }, callback);
+ */
+ create: (options: { client: Client, fields: HostedFieldFieldOptions, styles: any }, callback: callback) => void;
+
+
+ /**
+ * An object that represents CSS that will be applied in each hosted field. This object looks similar to CSS. Typically, these styles involve fonts (such as `font-family` or `color`).
+ *
+ * These are the CSS properties that Hosted Fields supports. Any other CSS should be specified on your page and outside of any Braintree configuration. Trying to set unsupported properties will fail and put a warning in the console.
+ *
+ * `color` `font-family` `font-size-adjust` `font-size` `font-stretch` `font-style` `font-variant-alternates` `font-variant-caps` `font-variant-east-asian` `font-variant-ligatures` `font-variant-numeric` `font-variant` `font-weight` `font` `line-height` `opacity` `outline` `text-shadow` `transition` `-moz-osx-font-smoothing` `-moz-tap-highlight-color` `-moz-transition` `-webkit-font-smoothing` `-webkit-tap-highlight-color` `-webkit-transition`
+ * @typedef {object} styleOptions
+ */
+ styleOptions: any;
+
+ /**
+ * @description The current version of the SDK, i.e. `3.0.2`.
+ * @type {string}
+ */
+ VERSION: string;
+ }
+
+ /**
+ * @class HostedFields
+ * @param {object} options The Hosted Fields {@link module:braintree-web/hosted-fields.create create} options.
+ * @description Do not use this constructor directly. Use {@link module:braintree-web/hosted-fields.create|braintree-web.hosted-fields.create} instead.
+ * @classdesc This class represents a Hosted Fields component produced by {@link module:braintree-web/hosted-fields.create|braintree-web/hosted-fields.create}. Instances of this class have methods for interacting with the input fields within Hosted Fields' iframes.
+ */
+ export class HostedFields {
+ /**
+ * @class HostedFields
+ * @param {object} options The Hosted Fields {@link module:braintree-web/hosted-fields.create create} options.
+ * @description Do not use this constructor directly. Use {@link module:braintree-web/hosted-fields.create|braintree-web.hosted-fields.create} instead.
+ * @classdesc This class represents a Hosted Fields component produced by {@link module:braintree-web/hosted-fields.create|braintree-web/hosted-fields.create}. Instances of this class have methods for interacting with the input fields within Hosted Fields' iframes.
+ */
+ constructor(options: any);
+
+ /**
+ * @name HostedFields#on
+ * @function
+ * @param {string} event The name of the event to which you are subscribing.
+ * @param {function} handler A callback to handle the event.
+ * @description Subscribes a handler function to a named event. `event` should be {@link HostedFields#event:blur|blur}, {@link HostedFields#event:focus|focus}, {@link HostedFields#event:empty|empty}, {@link HostedFields#event:notEmpty|notEmpty}, {@link HostedFields#event:cardTypeChange|cardTypeChange}, or {@link HostedFields#event:validityChange|validityChange}. Events will emit a {@link HostedFields~stateObject|stateObject}.
+ * @example
+ *
Listening to a Hosted Field event, in this case 'focus'
+ * hostedFields.create({ ... }, function (createErr, hostedFieldsInstance) {
+ * hostedFieldsInstance.on('focus', function (event) {
+ * console.log(event.emittedBy, 'has been focused');
+ * });
+ * });
+ * @returns {void}
+ */
+ on(event: string, handler: (() => any)): void;
+
+ /**
+ * Cleanly tear down anything set up by {@link module:braintree-web/hosted-fields.create|create}
+ * @public
+ * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if teardown completes successfully.
+ * @example
+ * hostedFieldsInstance.teardown(function (teardownErr) {
+ * if (teardownErr) {
+ * console.error('Could not tear down Hosted Fields!');
+ * } else {
+ * console.info('Hosted Fields has been torn down!');
+ * }
+ * });
+ * @returns {void}
+ */
+ public teardown(callback?: callback): void;
+
+ /**
+ * Tokenizes fields and returns a nonce payload.
+ * @public
+ * @param {object} [options] All tokenization options for the Hosted Fields component.
+ * @param {boolean} [options.vault=false] When true, will vault the tokenized card. Cards will only be vaulted when using a client created with a client token that includes a customer ID.
+ * @param {callback} callback The second argument, data, is a {@link HostedFields~tokenizePayload|tokenizePayload}
+ * @example
Tokenize a card
+ * hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
+ * if (tokenizeErr) {
+ * switch (tokenizeErr.code) {
+ * case 'HOSTED_FIELDS_FIELDS_EMPTY':
+ * console.error('All fields are empty! Please fill out the form.');
+ * break;
+ * case 'HOSTED_FIELDS_FIELDS_INVALID':
+ * console.error('Some fields are invalid:', tokenizeErr.details.invalidFieldKeys);
+ * break;
+ * case 'HOSTED_FIELDS_FAILED_TOKENIZATION':
+ * console.error('Tokenization failed server side. Is the card valid?');
+ * break;
+ * case 'HOSTED_FIELDS_TOKENIZATION_NETWORK_ERROR':
+ * console.error('Network error occurred when tokenizing.');
+ * break;
+ * default:
+ * console.error('Something bad happened!', tokenizeErr);
+ * }
+ * } else {
+ * console.log('Got nonce:', payload.nonce);
+ * }
+ * });
+ * @example
Tokenize and vault a card
+ * hostedFieldsInstance.tokenize({
+ * vault: true
+ * }, function (tokenizeErr, payload) {
+ * if (tokenizeErr) {
+ * console.error(tokenizeErr);
+ * } else {
+ * console.log('Got nonce:', payload.nonce);
+ * }
+ * });
+ * @returns {void}
+ */
+ public tokenize(options?: { vault: boolean }, callback?: callback): void;
+
+ /**
+ * Add a class to a {@link module:braintree-web/hosted-fields~field field}. Useful for updating field styles when events occur elsewhere in your checkout.
+ * @public
+ * @param {string} field The field you wish to add a class to. Must be a valid {@link module:braintree-web/hosted-fields~fieldOptions fieldOption}.
+ * @param {string} classname The class to be added.
+ * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if the class is added successfully.
+ *
+ * @example
+ * hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr) {
+ * if (addClassErr) {
+ * console.error(addClassErr);
+ * }
+ * });
+ * @returns {void}
+ */
+ public addClass(field: string, classname: string, callback?: callback): void;
+
+ /**
+ * Removes a class to a {@link module:braintree-web/hosted-fields~field field}. Useful for updating field styles when events occur elsewhere in your checkout.
+ * @public
+ * @param {string} field The field you wish to remove a class from. Must be a valid {@link module:braintree-web/hosted-fields~fieldOptions fieldOption}.
+ * @param {string} classname The class to be removed.
+ * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if the class is removed successfully.
+ *
+ * @example
+ * hostedFieldsInstance.addClass('number', 'custom-class', function (addClassErr) {
+ * if (addClassErr) {
+ * console.error(addClassErr);
+ * return;
+ * }
+ *
+ * // some time later...
+ * hostedFieldsInstance.removeClass('number', 'custom-class');
+ * });
+ * @returns {void}
+ */
+ public removeClass(field: string, classname: string, callback?: callback): void;
+
+ /**
+ * Sets the placeholder of a {@link module:braintree-web/hosted-fields~field field}.
+ * @public
+ * @param {string} field The field whose placeholder you wish to change. Must be a valid {@link module:braintree-web/hosted-fields~fieldOptions fieldOption}.
+ * @param {string} placeholder Will be used as the `placeholder` attribute of the input.
+ * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if the placeholder updated successfully.
+ *
+ * @example
+ * hostedFieldsInstance.setPlaceholder('number', '4111 1111 1111 1111', function (placeholderErr) {
+ * if (placeholderErr) {
+ * console.error(placeholderErr);
+ * }
+ * });
+ *
+ * @example
Update CVV field on card type change
+ * hostedFieldsInstance.on('cardTypeChange', function (event) {
+ * // Update the placeholder value if there is only one possible card type
+ * if (event.cards.length === 1) {
+ * hostedFields.setPlaceholder('cvv', event.cards[0].code.name, function (placeholderErr) {
+ * if (placeholderErr) {
+ * // Handle errors, such as invalid field name
+ * console.error(placeholderErr);
+ * }
+ * });
+ * }
+ * });
+ * @returns {void}
+ */
+ public setPlaceholder(field: string, placeholder: string, callback?: callback): void;
+
+ /**
+ * Clear the value of a {@link module:braintree-web/hosted-fields~field field}.
+ * @public
+ * @param {string} field The field whose placeholder you wish to clear. Must be a valid {@link module:braintree-web/hosted-fields~fieldOptions fieldOption}.
+ * @param {callback} [callback] Callback executed on completion, containing an error if one occurred. No data is returned if the field cleared successfully.
+ * @returns {void}
+ * @example
+ * hostedFieldsInstance.clear('number', function (clearErr) {
+ * if (clearErr) {
+ * console.error(clearErr);
+ * }
+ * });
+ *
+ * @example
Clear several fields
+ * hostedFieldsInstance.clear('number');
+ * hostedFieldsInstance.clear('cvv');
+ * hostedFieldsInstance.clear('expirationDate');
+ */
+ public clear(field: string, callback?: callback): void;
+
+ /**
+ * Returns an {@link HostedFields~stateObject|object} that includes the state of all fields and possible card types.
+ * @public
+ * @returns {object} {@link HostedFields~stateObject|stateObject}
+ * @example
Check if all fields are valid
+ * var state = hostedFields.getState();
+ *
+ * var formValid = Object.keys(state.fields).every(function (key) {
+ * return state.fields[key].isValid;
+ * });
+ */
+ public getState(): any;
+ }
+}
+
+/** @module braintree-web/paypal */
+declare namespace BraintreeWeb {
+ /**
+ * @typedef {object} PayPal~tokenizeReturn
+ * @property {Function} close A handle to close the PayPal checkout flow.
+ */
+ interface PayPalTokenizeReturn {
+ close: (() => any);
+ }
+
+ /**
+ * @typedef {object} PayPal~tokenizePayload
+ * @property {string} nonce The payment method nonce.
+ * @property {string} type The payment method type, always `PayPalAccount`.
+ * @property {object} details Additional PayPal account details.
+ * @property {string} details.email User's email address.
+ * @property {string} details.payerId User's payer ID, the unique identifier for each PayPal account.
+ * @property {string} details.firstName User's given name.
+ * @property {string} details.lastName User's surname.
+ * @property {?string} details.countryCode User's 2 character country code.
+ * @property {?string} details.phone User's phone number (e.g. 555-867-5309).
+ * @property {?object} details.shippingAddress User's shipping address details, only available if shipping address is enabled.
+ * @property {string} details.shippingAddress.recipientName Recipient of postage.
+ * @property {string} details.shippingAddress.line1 Street number and name.
+ * @property {string} details.shippingAddress.line2 Extended address.
+ * @property {string} details.shippingAddress.city City or locality.
+ * @property {string} details.shippingAddress.state State or region.
+ * @property {string} details.shippingAddress.postalCode Postal code.
+ * @property {string} details.shippingAddress.countryCode 2 character country code (e.g. US).
+ * @property {?object} details.billingAddress User's billing address details.
+ * You will also need to enable the PayPal Billing Address Request feature in your PayPal account.
+ * To enable this feature, [contact PayPal](https://developers.braintreepayments.com/support/guides/paypal/setup-guide#contacting-paypal-support).
+ * @property {string} details.billingAddress.line1 Street number and name.
+ * @property {string} details.billingAddress.line2 Extended address.
+ * @property {string} details.billingAddress.city City or locality.
+ * @property {string} details.billingAddress.state State or region.
+ * @property {string} details.billingAddress.postalCode Postal code.
+ * @property {string} details.billingAddress.countryCode 2 character country code (e.g. US).
+ */
+ interface PayPalShippingAddress {
+ recipientName: string;
+ line1: string;
+ line2: string;
+ city: string;
+ state: string;
+ postalCode: string;
+ countryCode: string;
+ }
+
+ interface PayPalBillingAddress {
+ line1: string;
+ line2: string;
+ city: string;
+ state: string;
+ postalCode: string;
+ countryCode: string;
+ }
+
+ interface PayPalAccountDetails {
+ email: string;
+ payerId: string;
+ firstName: string;
+ lastName: string;
+ countryCode: string;
+ phone: string;
+ shippingAddress: PayPalShippingAddress;
+ billingAddress: PayPalBillingAddress;
+ }
+
+ interface PayPalTokenizePayload {
+ nonce: string;
+ type: string;
+ details: PayPalAccountDetails;
+ }
+
+ export interface PayPal {
+ /**
+ * @static
+ * @function create
+ * @param {object} options Creation options:
+ * @param {Client} options.client A {@link Client} instance.
+ * @param {callback} callback The second argument, `data`, is the {@link PayPal} instance.
+ * @example
+ * braintree.paypal.create(
+ * client: clientInstance
+ * }, function (createErr, paypalInstance) {
+ * if (createErr) {
+ * if (createErr.code === 'PAYPAL_BROWSER_NOT_SUPPORTED') {
+ * console.error('This browser is not supported.');
+ * } else {
+ * console.error('Error!', createErr);
+ * }
+ * }
+ * }
+ * @returns {void}
+ */
+ create: (options: { client: Client }, callback: callback) => void;
+
+ /**
+ * @description The current version of the SDK, i.e. `3.0.2`.
+ * @type {string}
+ */
+ VERSION: string;
+ }
+
+ /**
+ * @class
+ * @param {object} options see {@link module:braintree-web/paypal.create|paypal.create}
+ * @classdesc This class represents a PayPal component. Instances of this class have methods for launching auth dialogs and other programmatic interactions with the PayPal component.
+ */
+ export class PayPal {
+ /**
+ * @class
+ * @param {object} options see {@link module:braintree-web/paypal.create|paypal.create}
+ * @classdesc This class represents a PayPal component. Instances of this class have methods for launching auth dialogs and other programmatic interactions with the PayPal component.
+ */
+ constructor(options: any);
+
+ /**
+ * Launches the PayPal login flow and returns a nonce payload. Only one PayPal login flow should be active at a time. One way to achieve this is to disable your PayPal button while the flow is open.
+ * @public
+ * @param {object} options All tokenization options for the PayPal component.
+ * @param {string} options.flow Set to 'checkout' for one-time payment flow, or 'vault' for Vault flow. If 'vault' is used with a client token generated with a customer id, the PayPal account will be added to that customer as a saved payment method.
+ * @param {string} [options.intent=authorize]
+ * Checkout flows only.
+ * * `authorize` - Submits the transaction for authorization but not settlement.
+ * * `sale` - Payment will be immediately submitted for settlement upon creating a transaction.
+ * @param {boolean} [options.offerCredit=false] Offers the customer PayPal Credit if they qualify. Checkout flows only.
+ * @param {string} [options.useraction]
+ * Changes the call-to-action in the PayPal flow. By default the final button will show the localized
+ * word for "Continue" and implies that the final amount billed is not yet known.
+ *
+ * Setting this option to `commit` changes the button text to "Pay Now" and page text will convey to
+ * the user that billing will take place immediately.
+ * @param {string|number} [options.amount] The amount of the transaction. Required when using the Checkout flow.
+ * @param {string} [options.currency] The currency code of the amount, such as 'USD'. Required when using the Checkout flow.
+ * @param {string} [options.displayName] The merchant name displayed inside of the PayPal lightbox; defaults to the company name on your Braintree account
+ * @param {string} [options.locale=en_US] Use this option to change the language, links, and terminology used in the PayPal flow to suit the country and language of your customer.
+ * @param {boolean} [options.enableShippingAddress=false] Returns a shipping address object in {@link PayPal#tokenize}.
+ * @param {object} [options.shippingAddressOverride] Allows you to pass a shipping address you have already collected into the PayPal payment flow.
+ * @param {string} options.shippingAddressOverride.line1 Street address.
+ * @param {string} [options.shippingAddressOverride.line2] Street address (extended).
+ * @param {string} options.shippingAddressOverride.city City.
+ * @param {string} options.shippingAddressOverride.state State.
+ * @param {string} options.shippingAddressOverride.postalCode Postal code.
+ * @param {string} options.shippingAddressOverride.countryCode Country.
+ * @param {string} [options.shippingAddressOverride.phone] Phone number.
+ * @param {string} [options.shippingAddressOverride.recipientName] Recipient's name.
+ * @param {boolean} [options.shippingAddressEditable=true] Set to false to disable user editing of the shipping address.
+ * @param {string} [options.billingAgreementDescription] Use this option to set the description of the preapproved payment agreement visible to customers in their PayPal profile during Vault flows. Max 255 characters.
+ * @param {callback} callback The second argument, data, is a {@link PayPal~tokenizePayload|tokenizePayload}.
+ * @example
+ * button.addEventListener('click', function () {
+ * // Disable the button so that we don't attempt to open multiple popups.
+ * button.setAttribute('disabled', 'disabled');
+ *
+ * // Because PayPal tokenization opens a popup, this must be called
+ * // as a result of a user action, such as a button click.
+ * paypalInstance.tokenize({
+ * flow: 'vault' // Required
+ * // Any other tokenization options
+ * }, function (tokenizeErr, payload) {
+ * button.removeAttribute('disabled');
+ *
+ * if (tokenizeErr) {
+ * // Handle tokenization errors or premature flow closure
+ *
+ * switch (tokenizeErr.code) {
+ * case 'PAYPAL_POPUP_CLOSED':
+ * console.error('Customer closed PayPal popup.');
+ * break;
+ * case 'PAYPAL_ACCOUNT_TOKENIZATION_FAILED':
+ * console.error('PayPal tokenization failed. See details:', tokenizeErr.details);
+ * break;
+ * case 'PAYPAL_FLOW_FAILED':
+ * console.error('Unable to initialize PayPal flow. Are your options correct?', tokenizeErr.details);
+ * break;
+ * default:
+ * console.error('Error!', tokenizeErr);
+ * }
+ * } else {
+ * // Submit payload.nonce to your server
+ * }
+ * });
+ * });
+ * @returns {PayPal~tokenizeReturn} A handle to close the PayPal checkout frame.
+ */
+ public tokenize(options: { flow: string, intent: string, offerCredit: boolean, useraction: string, amount: (string | number), currency: string, displayName: string, locale: string, enableShippingAddress: boolean, shippingAddressOverride: PayPalShippingAddress, shippingAddressEditable: boolean, billingAgreementDescription: string }, callback: callback): PayPalTokenizeReturn;
+
+ /**
+ * Cleanly tear down anything set up by {@link module:braintree-web/paypal.create|create}.
+ * @public
+ * @param {callback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully.
+ * @returns {void}
+ */
+ public teardown(callback?: () => void): void;
+
+ }
+}
+
+/** @module braintree-web/three-d-secure */
+declare namespace BraintreeWeb {
+ /**
+ * @typedef {object} ThreeDSecure~verifyPayload
+ * @property {string} nonce The new payment method nonce produced by the 3D Secure lookup. The original nonce passed into {@link ThreeDSecure#verifyCard|verifyCard} was consumed. This new nonce should be used to transact on your server.
+ * @property {object} details Additional account details.
+ * @property {string} details.cardType Type of card, ex: Visa, MasterCard.
+ * @property {string} details.lastTwo Last two digits of card number.
+ * @property {string} description A human-readable description.
+ * @property {boolean} liabilityShiftPossible Indicates whether the card was eligible for 3D Secure.
+ * @property {boolean} liabilityShifted Indicates whether the liability for fraud has been shifted away from the merchant.
+ */
+ interface ThreeDSecureAccountDetails {
+ cardType: string;
+ lastTwo: string;
+ }
+
+ interface ThreeDSecureVerifyPayload {
+ nonce: string;
+ details: ThreeDSecureAccountDetails;
+ description: string;
+ liabilityShiftPossible: boolean;
+ liabilityShifted: boolean;
+ }
+
+ export interface ThreeDSecure {
+ /**
+ * @static
+ * @function create
+ * @param {object} options Creation options:
+ * @param {Client} options.client A {@link Client} instance.
+ * @param {callback} callback The second argument, `data`, is the {@link ThreeDSecure} instance.
+ * @returns {void}
+ * @example
+ * braintree.threeDSecure.create({
+ * client: client
+ * }, callback);
+ */
+ create: (options: { client: Client }, callback: callback) => void;
+
+ /**
+ * @description The current version of the SDK, i.e. `3.0.2`.
+ * @type {string}
+ */
+ VERSION: string;
+ }
+
+ /**
+ * @class
+ * @param {object} options 3D Secure {@link module:braintree-web/three-d-secure.create create} options
+ * @description Do not use this constructor directly. Use {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create} instead.
+ * @classdesc This class represents a ThreeDSecure component produced by {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create}. Instances of this class have a method for launching a 3D Secure authentication flow.
+ */
+ export class ThreeDSecure {
+ /**
+ * @class
+ * @param {object} options 3D Secure {@link module:braintree-web/three-d-secure.create create} options
+ * @description Do not use this constructor directly. Use {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create} instead.
+ * @classdesc This class represents a ThreeDSecure component produced by {@link module:braintree-web/three-d-secure.create|braintree.threeDSecure.create}. Instances of this class have a method for launching a 3D Secure authentication flow.
+ */
+ constructor(options: any);
+
+
+ /**
+ * @callback ThreeDSecure~addFrameCallback
+ * @param {?BraintreeError} [err] `null` or `undefined` if there was no error.
+ * @param {HTMLIFrameElement} iframe An iframe element containing the bank's authentication page that you must put on your page.
+ * @description The callback used for options.addFrame in {@link ThreeDSecure#verifyCard|verifyCard}.
+ * @returns {void}
+ */
+ addFrameCallback: (err?: BraintreeError, iframe?: HTMLIFrameElement) => void;
+
+ /**
+ * @callback ThreeDSecure~removeFrameCallback
+ * @description The callback used for options.removeFrame in {@link ThreeDSecure#verifyCard|verifyCard}.
+ * @returns {void}
+ */
+ removeFrameCallback: () => void;
+
+ /**
+ * Launch the 3D Secure login flow, returning a nonce payload.
+ * @public
+ * @param {object} options Options for card verification.
+ * @param {string} options.nonce A nonce referencing the card to be verified. For example, this can be a nonce that was returned by Hosted Fields.
+ * @param {number} options.amount The amount of the transaction in the current merchant account's currency. For example, if you are running a transaction of $123.45 US dollars, `amount` would be 123.45.
+ * @param {errback} options.addFrame This {@link ThreeDSecure~addFrameCallback|addFrameCallback} will be called when the bank frame needs to be added to your page.
+ * @param {callback} options.removeFrame This {@link ThreeDSecure~removeFrameCallback|removeFrameCallback} will be called when the bank frame needs to be removed from your page.
+ * @param {errback} callback The second argument, data, is a {@link ThreeDSecure~verifyPayload|verifyPayload}
+ * @returns {void}
+ * @example
+ *
Verifying an existing nonce with 3DS
+ * var my3DSContainer;
+ *
+ * threeDSecure.verifyCard({
+ * nonce: existingNonce,
+ * amount: 123.45,
+ * addFrame: function (err, iframe) {
+ * // Set up your UI and add the iframe.
+ * my3DSContainer = document.createElement('div');
+ * my3DSContainer.appendChild(iframe);
+ * document.body.appendChild(my3DSContainer);
+ * },
+ * removeFrame: function () {
+ * // Remove UI that you added in addFrame.
+ * document.body.removeChild(my3DSContainer);
+ * }
+ * }, function (err, payload) {
+ * if (err) {
+ * console.error(err);
+ * return;
+ * }
+ *
+ * if (payload.liabilityShifted) {
+ * // Liablity has shifted
+ * submitNonceToServer(payload.nonce);
+ * } else if (payload.liabilityShiftPossible) {
+ * // Liablity may still be shifted
+ * // Decide if you want to submit the nonce
+ * } else {
+ * // Liablity has not shifted and will not shift
+ * // Decide if you want to submit the nonce
+ * }
+ * });
+ */
+ public verifyCard(options: { nonce: string, amount: number, addFrame: (err?: BraintreeError, iframe?: HTMLIFrameElement) => void, removeFrame: () => void }, callback: callback): void;
+
+ /**
+ * Cancel the 3DS flow and return the verification payload if available.
+ * @public
+ * @param {errback} callback The second argument is a {@link ThreeDSecure~verifyPayload|verifyPayload}. If there is no verifyPayload (the initial lookup did not complete), an error will be returned.
+ * @returns {void}
+ * @example
+ * threeDSecure.cancelVerifyCard(function (err, verifyPayload) {
+ * if (err) {
+ * // Handle error
+ * console.log(err.message); // No verification payload available
+ * return;
+ * }
+ *
+ * verifyPayload.nonce; // The nonce returned from the 3ds lookup call
+ * verifyPayload.liabilityShifted; // boolean
+ * verifyPayload.liabilityShiftPossible; // boolean
+ * });
+ */
+ public cancelVerifyCard(callback: callback): void;
+
+ /**
+ * Cleanly tear down anything set up by {@link module:braintree-web/three-d-secure.create|create}
+ * @public
+ * @param {errback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully.
+ * @returns {void}
+ */
+ public teardown(callback?: callback): void;
+ }
+}
+
+/**
+ * @module braintree-web/unionpay
+ * @description This module allows you to accept UnionPay payments. *It is currently in beta and is subject to change.*
+ */
+declare namespace BraintreeWeb {
+ /**
+ * @typedef {object} UnionPay~tokenizePayload
+ * @property {string} nonce The payment method nonce.
+ * @property {string} type Always CreditCard.
+ * @property {object} details Additional account details:
+ * @property {string} details.cardType Type of card, ex: Visa, MasterCard.
+ * @property {string} details.lastTwo Last two digits of card number.
+ * @property {string} description A human-readable description.
+ */
+ interface UnionPayAccountDetails {
+ cardType: string;
+ lastTwo: string;
+ description: string;
+ }
+
+ interface UnionPayTokenizePayload {
+ nonce: string;
+ type: string;
+ details: UnionPayAccountDetails;
+ }
+
+ /**
+ * @typedef {object} UnionPay~enrollPayload
+ * @property {string} enrollmentId UnionPay enrollment ID. This value should be passed to `tokenize`.
+ * @property {boolean} smsCodeRequired UnionPay `smsCodeRequired` flag.
+ *
true - the user will receive an SMS code that needs to be supplied for tokenization.
+ * false - the card can be immediately tokenized.
+ */
+ interface UnionPayEnrollPayload {
+ enrollmentId: string;
+ smsCodeRequired: boolean;
+ }
+
+ /**
+ * @typedef {object} UnionPay~fetchCapabilitiesPayload
+ * @property {boolean} isUnionPay Determines if this card is a UnionPay card.
+ * @property {boolean} isDebit Determines if this card is a debit card. This property is only present if `isUnionPay` is `true`.
+ * @property {object} unionPay UnionPay specific properties. This property is only present if `isUnionPay` is `true`.
+ * @property {boolean} unionPay.supportsTwoStepAuthAndCapture Determines if the card allows for an authorization, but settling the transaction later.
+ * @property {boolean} unionPay.isSupported Determines if Braintree can process this UnionPay card. When false, Braintree cannot process this card and the user should use a different card.
+ */
+
+ interface UnionPayProperties {
+ supportsTwoStepAuthAndCapture: boolean;
+ isSupported: boolean;
+ }
+
+ interface UnionPayFetchCapabilitiesPayload {
+ isUnionPay: boolean;
+ isDebit: boolean;
+ unionPay: UnionPayProperties;
+ }
+
+ export interface UnionPay {
+ /**
+ * @static
+ * @function create
+ * @param {object} options Creation options:
+ * @param {Client} options.client A {@link Client} instance.
+ * @param {callback} callback The second argument, `data`, is the {@link UnionPay} instance.
+ * @returns {void}
+ * @example
+ * braintree.unionpay.create({ client: clientInstance }, function (createErr, unionpayInstance) {
+ * if (createErr) {
+ * console.error(createErr);
+ * return;
+ * }
+ * // ...
+ * });
+ */
+ create: (options: { client: Client }, callback: callback) => void;
+
+ /**
+ * @description The current version of the SDK, i.e. `3.0.2`.
+ * @type {string}
+ */
+ VERSION: string;
+ }
+
+ /**
+ * @class
+ * @param {object} options See {@link module:braintree-web/unionpay.create|unionpay.create}.
+ * @description You cannot use this constructor directly. Use {@link module:braintree-web/unionpay.create|braintree-web.unionpay.create} instead.
+ * @classdesc This class represents a UnionPay component. Instances of this class have methods for {@link UnionPay#fetchCapabilities fetching capabilities} of UnionPay cards, {@link UnionPay#enroll enrolling} a UnionPay card, and {@link UnionPay#tokenize tokenizing} a UnionPay card.
+ */
+ export class UnionPay {
+ /**
+ * @class
+ * @param {object} options See {@link module:braintree-web/unionpay.create|unionpay.create}.
+ * @description You cannot use this constructor directly. Use {@link module:braintree-web/unionpay.create|braintree-web.unionpay.create} instead.
+ * @classdesc This class represents a UnionPay component. Instances of this class have methods for {@link UnionPay#fetchCapabilities fetching capabilities} of UnionPay cards, {@link UnionPay#enroll enrolling} a UnionPay card, and {@link UnionPay#tokenize tokenizing} a UnionPay card.
+ */
+ constructor(options: any);
+
+ /**
+ * Fetches the capabilities of a card, including whether or not the SMS enrollment process is required.
+ * @public
+ * @param {object} options UnionPay {@link UnionPay#fetchCapabilities fetchCapabilities} options
+ * @param {object} [options.card] The card from which to fetch capabilities. Note that this will only have one property, `number`. Required if you are not using the `hostedFields` option.
+ * @param {string} options.card.number Card number.
+ * @param {HostedFields} [options.hostedFields] The Hosted Fields instance used to collect card data. Required if you are not using the `card` option.
+ * @param {callback} callback The second argument, data, is a {@link UnionPay#fetchCapabilitiesPayload fetchCapabilitiesPayload}.
+ * @example
With raw card data
+ * unionpayInstance.fetchCapabilities({
+ * card: {
+ * number: '4111111111111111'
+ * }
+ * }, function (fetchErr, cardCapabilities) {
+ * if (fetchErr) {
+ * console.error(fetchErr);
+ * return;
+ * }
+ *
+ * if (cardCapabilities.isUnionPay) {
+ * if (cardCapabilities.unionPay && !cardCapabilities.unionPay.isSupported) {
+ * // Braintree cannot process this UnionPay card.
+ * // Ask the user for a different card.
+ * return;
+ * }
+ *
+ * if (cardCapabilities.isDebit) {
+ * // CVV and expiration date are not required
+ * } else {
+ * // CVV and expiration date are required
+ * }
+ *
+ * // Show mobile phone number field for enrollment
+ * }
+ * });
+ * @example
With Hosted Fields
+ * // Fetch capabilities on `blur` inside of the Hosted Fields `create` callback
+ * hostedFieldsInstance.on('blur', function (event) {
+ * // Only attempt to fetch capabilities when a valid card number has been entered
+ * if (event.emittedBy === 'number' && event.fields.number.isValid) {
+ * unionpayInstance.fetchCapabilities({
+ * hostedFields: hostedFieldsInstance
+ * }, function (fetchErr, cardCapabilities) {
+ * if (fetchErr) {
+ * console.error(fetchErr);
+ * return;
+ * }
+ *
+ * if (cardCapabilities.isUnionPay) {
+ * if (cardCapabilities.unionPay && !cardCapabilities.unionPay.isSupported) {
+ * // Braintree cannot process this UnionPay card.
+ * // Ask the user for a different card.
+ * return;
+ * }
+ * if (cardCapabilities.isDebit) {
+ * // CVV and expiration date are not required
+ * // Hide the containers with your `cvv` and `expirationDate` fields
+ * } else {
+ * // CVV and expiration date are required
+ * }
+ * } else {
+ * // Not a UnionPay card
+ * // When form is complete, tokenize using your Hosted Fields instance
+ * }
+ *
+ * // Show your own mobile country code and phone number inputs for enrollment
+ * });
+ * });
+ * });
+ * @returns {void}
+ */
+ public fetchCapabilities(options: { card: any, hostedFields: HostedFields }, callback: callback): void;
+
+ /**
+ * Enrolls a UnionPay card. Use {@link UnionPay#fetchCapabilities|fetchCapabilities} to determine if the SMS enrollment process is required.
+ * @public
+ * @param {object} options UnionPay enrollment options:
+ * @param {object} [options.card] The card to enroll. Required if you are not using the `hostedFields` option.
+ * @param {string} options.card.number The card number.
+ * @param {string} [options.card.expirationDate] The card's expiration date. May be in the form `MM/YY` or `MM/YYYY`. When defined `expirationMonth` and `expirationYear` are ignored.
+ * @param {string} [options.card.expirationMonth] The card's expiration month. This should be used with the `expirationYear` parameter. When `expirationDate` is defined this parameter is ignored.
+ * @param {string} [options.card.expirationYear] The card's expiration year. This should be used with the `expirationMonth` parameter. When `expirationDate` is defined this parameter is ignored.
+ * @param {HostedFields} [options.hostedFields] The Hosted Fields instance used to collect card data. Required if you are not using the `card` option.
+ * @param {object} options.mobile The mobile information collected from the customer.
+ * @param {string} options.mobile.countryCode The country code of the customer's mobile phone number.
+ * @param {string} options.mobile.number The customer's mobile phone number.
+ * @param {callback} callback The second argument, data, is a {@link UnionPay~enrollPayload|enrollPayload}.
+ * @example
With raw card data
+ * unionpayInstance.enroll({
+ * card: {
+ * number: '4111111111111111',
+ * expirationMonth: '12',
+ * expirationYear: '2038'
+ * },
+ * mobile: {
+ * countryCode: '62',
+ * number: '111111111111'
+ * }
+ * }, function (enrollErr, response) {
+ * if (enrollErr) {
+ * console.error(enrollErr);
+ * return;
+ * }
+ *
+ * if (response.smsCodeRequired) {
+ * // If smsCodeRequired, wait for SMS auth code from customer
+ * // Then use response.enrollmentId during {@link UnionPay#tokenize}
+ * } else {
+ * // SMS code is not required from the user.
+ * // {@link UnionPay#tokenize} can be called immediately
+ * });
+ * @example
With Hosted Fields
+ * unionpayInstance.enroll({
+ * hostedFields: hostedFields,
+ * mobile: {
+ * countryCode: '62',
+ * number: '111111111111'
+ * }
+ * }, function (enrollErr, response) {
+ * if (enrollErr) {
+ * console.error(enrollErr);
+ * return;
+ * }
+ *
+ * if (response.smsCodeRequired) {
+ * // If smsCodeRequired, wait for SMS auth code from customer
+ * // Then use response.enrollmentId during {@link UnionPay#tokenize}
+ * } else {
+ * // SMS code is not required from the user.
+ * // {@link UnionPay#tokenize} can be called immediately
+ * }
+ * });
+ * @returns {void}
+ */
+ public enroll(options: { card: any, hostedFields: HostedFields, mobile: any }, callback: callback): void;
+
+ /**
+ * Tokenizes a UnionPay card and returns a nonce payload.
+ * @public
+ * @param {object} options UnionPay tokenization options:
+ * @param {object} [options.card] The card to enroll. Required if you are not using the `hostedFields` option.
+ * @param {string} options.card.number The card number.
+ * @param {string} [options.card.expirationDate] The card's expiration date. May be in the form `MM/YY` or `MM/YYYY`. When defined `expirationMonth` and `expirationYear` are ignored.
+ * @param {string} [options.card.expirationMonth] The card's expiration month. This should be used with the `expirationYear` parameter. When `expirationDate` is defined this parameter is ignored.
+ * @param {string} [options.card.expirationYear] The card's expiration year. This should be used with the `expirationMonth` parameter. When `expirationDate` is defined this parameter is ignored.
+ * @param {string} [options.card.cvv] The card's security number.
+ * @param {HostedFields} [options.hostedFields] The Hosted Fields instance used to collect card data. Required if you are not using the `card` option.
+ * @param {string} options.enrollmentId The enrollment ID from {@link UnionPay#enroll}.
+ * @param {string} [options.smsCode] The SMS code received from the user if {@link UnionPay#enroll} payload have `smsCodeRequired`. if `smsCodeRequired` is false, smsCode should not be passed.
+ * @param {callback} callback The second argument, data, is a {@link UnionPay~tokenizePayload|tokenizePayload}.
+ * @example
With raw card data
+ * unionpayInstance.tokenize({
+ * card: {
+ * number: '4111111111111111',
+ * expirationMonth: '12',
+ * expirationYear: '2038',
+ * cvv: '123'
+ * },
+ * enrollmentId: enrollResponse.enrollmentId, // Returned from enroll
+ * smsCode: '11111' // Received by customer's phone, if SMS enrollment was required. Otherwise it should be omitted
+ * }, function (tokenizeErr, response) {
+ * if (tokenizeErr) {
+ * console.error(tokenizeErr);
+ * return;
+ * }
+ *
+ * // Send response.nonce to your server
+ * });
+ * @example
With Hosted Fields
+ * unionpayInstance.tokenize({
+ * hostedFields: hostedFieldsInstance,
+ * enrollmentId: enrollResponse.enrollmentId, // Returned from enroll
+ * smsCode: '11111' // Received by customer's phone, if SMS enrollment was required. Otherwise it should be omitted
+ * }, function (tokenizeErr, response) {
+ * if (tokenizeErr) {
+ * console.error(tokenizeErr);
+ * return;
+ * }
+ *
+ * // Send response.nonce to your server
+ * });
+ * @returns {void}
+ */
+ public tokenize(options: { card: any, hostedFields: HostedFields, enrollmentId: string, smsCode: string }, callback: callback): void;
+
+ /**
+ * Cleanly tear down anything set up by {@link module:braintree-web/unionpay.create|create}. This only needs to be called when using UnionPay with Hosted Fields.
+ * @public
+ * @param {callback} [callback] Called once teardown is complete. No data is returned if teardown completes successfully.
+ * @example
+ * unionpayInstance.teardown(function (teardownErr) {
+ * if (teardownErr) {
+ * console.error('Could not tear down UnionPay.');
+ * } else {
+ * console.log('UnionPay has been torn down.');
+ * }
+ * });
+ * @returns {void}
+ */
+ public teardown(callback?: callback): void;
+
+ }
+}
+
+declare namespace BraintreeError {
+ /**
+ * Enum for {@link BraintreeError} types.
+ * @name BraintreeError.types
+ * @enum
+ * @readonly
+ * @memberof BraintreeError
+ * @property {string} CUSTOMER An error caused by the customer.
+ * @property {string} MERCHANT An error that is actionable by the merchant.
+ * @property {string} NETWORK An error due to a network problem.
+ * @property {string} INTERNAL An error caused by Braintree code.
+ * @property {string} UNKNOWN An error where the origin is unknown.
+ */
+ export enum Types {
+ CUSTOMER,
+ MERCHANT,
+ NETWORK,
+ INTERNAL,
+ UNKNOWN
+ }
+}
+
+/**
+ * @class
+ * @global
+ * @param {object} options Construction options
+ * @classdesc This class is used to report error conditions, frequently as the first parameter to callbacks throughout the Braintree SDK.
+ * @description You cannot use this constructor directly. Interact with instances of this class through {@link callback callbacks}.
+ */
+declare class BraintreeError {
+ /**
+ * @class
+ * @global
+ * @param {object} options Construction options
+ * @classdesc This class is used to report error conditions, frequently as the first parameter to callbacks throughout the Braintree SDK.
+ * @description You cannot use this constructor directly. Interact with instances of this class through {@link callback callbacks}.
+ */
+ constructor(options: any);
+
+ /**
+ * @type {string}
+ * @description A code that corresponds to specific errors.
+ */
+ code: string;
+
+ /**
+ * @type {string}
+ * @description A short description of the error.
+ */
+ message: string;
+
+ /**
+ * @type {BraintreeError.types}
+ * @description The type of error.
+ */
+ type: BraintreeError.Types;
+
+ /**
+ * @type {object=}
+ * @description Additional information about the error, such as an underlying network error response.
+ */
+ details: any;
+}
+
+declare namespace BraintreeWeb {
+ /**
+ * @global
+ * @callback callback
+ * @param {?BraintreeError} [err] `null` or `undefined` if there was no error.
+ * @param {?any} [data] The successful result of the asynchronous function call (if data exists).
+ * @description The Node.js-style callback pattern used throughout the SDK.
+ * @returns {void}
+ */
+ type callback = (err?: BraintreeError, data?: any) => void;
+}
+
+/**
+ * @module braintree-web
+ * @description This is the top-level module exported by the Braintree JavaScript SDK. In a browser environment, this will be the global braintree object. In a CommonJS environment (like Browserify or Webpack), it will be the default export of the braintree-web package. In AMD environments (like RequireJS), it can be `require`d like other modules.
+ * @example
+ *