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/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-material/angular-material-tests.ts b/angular-material/angular-material-tests.ts index 552ba7a95e..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({ diff --git a/angular-material/angular-material.d.ts b/angular-material/angular-material.d.ts index 3fa0290904..68d645abfa 100644 --- a/angular-material/angular-material.d.ts +++ b/angular-material/angular-material.d.ts @@ -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; @@ -216,6 +226,12 @@ declare namespace angular.material { hues: IThemeHues; } + interface IBrowserColors{ + theme: string; + palette: string; + hue: string; + } + interface IThemeColors { accent: IThemePalette; background: IThemePalette; @@ -245,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 { diff --git a/angularjs/angular-tests.ts b/angularjs/angular-tests.ts index 07f67a7375..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); diff --git a/angularjs/angular.d.ts b/angularjs/angular.d.ts index d78f39bec9..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; @@ -214,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; @@ -266,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. @@ -302,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; @@ -613,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. */ @@ -1221,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; @@ -1243,7 +1202,8 @@ declare namespace angular { imgSrcSanitizationWhitelist(): RegExp; imgSrcSanitizationWhitelist(regexp: RegExp): ICompileProvider; - debugInfoEnabled(enabled?: boolean): any; + debugInfoEnabled(): boolean; + debugInfoEnabled(enabled: boolean): ICompileProvider; } interface ICloneAttachFunction { @@ -1256,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, 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; } /////////////////////////////////////////////////////////////////////////// @@ -1413,12 +1377,12 @@ declare namespace angular { */ url: string; /** - * Event listeners to be bound to the XMLHttpRequest object. + * 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. + * 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 }; @@ -1549,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; @@ -1697,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; /** @@ -1712,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?: IComponentBindings; + 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. @@ -1739,26 +1702,33 @@ declare namespace angular { require?: {[controller: string]: string}; } - interface IComponentBindings { - [binding: 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 @@ -1781,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; } @@ -1828,16 +1798,12 @@ declare namespace angular { * that is passed to the link function instead. */ transclude: ITranscludeFunction - ): void | IDirectivePrePost; - } - - interface IDirectiveScope { - [property: string]: string; + ): void | IDirectiveLinkFn | IDirectivePrePost; } interface IDirective { compile?: IDirectiveCompileFn; - controller?: any; + controller?: string | Injectable; controllerAs?: string; /** * @deprecated @@ -1845,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 @@ -1856,12 +1821,12 @@ declare namespace angular { replace?: boolean; require?: string | string[] | {[controller: string]: string}; restrict?: string; - scope?: boolean | IDirectiveScope; - 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}; } /** @@ -1874,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/aws-sdk/aws-sdk.d.ts b/aws-sdk/aws-sdk.d.ts index 869f61071b..2a92a4bcc4 100644 --- a/aws-sdk/aws-sdk.d.ts +++ b/aws-sdk/aws-sdk.d.ts @@ -163,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; @@ -532,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 { diff --git a/diff-match-patch/diff-match-patch.d.ts b/diff-match-patch/diff-match-patch.d.ts index 028fe9d65c..b648363ead 100644 --- a/diff-match-patch/diff-match-patch.d.ts +++ b/diff-match-patch/diff-match-patch.d.ts @@ -5,6 +5,13 @@ declare module "diff-match-patch" { type Diff = [number, string]; + export class Patch { + diffs: Diff[]; + start1: number; + start2: number; + length1: number; + length2: number; + } export class diff_match_patch { static new (): diff_match_patch; @@ -31,6 +38,12 @@ declare module "diff-match-patch" { diff_levenshtein(diffs: Diff[]): number; diff_toDelta(diffs: Diff[]): string; diff_fromDelta(text1: string, delta: string): Diff[]; + + patch_make(text1: any, text2?: string): Patch[]; + patch_deepCopy(patches: Patch[]): Patch[]; + patch_apply(patches: Patch[], text: string): [string, boolean[]]; + patch_fromText(text: string): Patch[]; + patch_toText(patches: Patch[]): string; } export var DIFF_DELETE: number; diff --git a/elasticsearch/elasticsearch.d.ts b/elasticsearch/elasticsearch.d.ts index d983817869..a73dfe1406 100644 --- a/elasticsearch/elasticsearch.d.ts +++ b/elasticsearch/elasticsearch.d.ts @@ -109,7 +109,7 @@ declare module Elasticsearch { export interface CreateDocumentParams extends GenericParams { consistency?: "one" | "quorum" | "all"; parent?: string; - refressh?: boolean; + refresh?: boolean; routing?: string; timeout?: number | Date; timestamp?: number | Date; diff --git a/electron-devtools-installer/electron-devtools-installer-tests.ts b/electron-devtools-installer/electron-devtools-installer-tests.ts new file mode 100644 index 0000000000..daf19a1daf --- /dev/null +++ b/electron-devtools-installer/electron-devtools-installer-tests.ts @@ -0,0 +1,20 @@ +/// +/// + +import installExtension, { + EMBER_INSPECTOR, REACT_DEVELOPER_TOOLS, + BACKBONE_DEBUGGER, JQUERY_DEBUGGER, + ANGULARJS_BATARANG, VUEJS_DEVTOOLS, + REDUX_DEVTOOLS, REACT_PERF, +} from 'electron-devtools-installer'; + + +installExtension(EMBER_INSPECTOR); +installExtension(REACT_DEVELOPER_TOOLS); +installExtension(BACKBONE_DEBUGGER); +installExtension(JQUERY_DEBUGGER); +installExtension(ANGULARJS_BATARANG); +installExtension(VUEJS_DEVTOOLS); +installExtension(REDUX_DEVTOOLS); +installExtension(REACT_PERF); +installExtension('abcdefghijkl'); \ No newline at end of file diff --git a/electron-devtools-installer/electron-devtools-installer.d.ts b/electron-devtools-installer/electron-devtools-installer.d.ts new file mode 100644 index 0000000000..8a108c1d2f --- /dev/null +++ b/electron-devtools-installer/electron-devtools-installer.d.ts @@ -0,0 +1,24 @@ +// Type definitions for electron-devtools-installer v2.0.1 +// Project: https://github.com/MarshallOfSound/electron-devtools-installer +// Definitions by: Robin Van den Broeck +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module "electron-devtools-installer" { + interface ExtensionReference { + id: string, + electron: string, + } + + // Default installation function + export default function (extensionReference: ExtensionReference | string, forceDownload?: boolean): Promise; + + // Devtools themself + export const EMBER_INSPECTOR: ExtensionReference; + export const REACT_DEVELOPER_TOOLS: ExtensionReference; + export const BACKBONE_DEBUGGER: ExtensionReference; + export const JQUERY_DEBUGGER: ExtensionReference; + export const ANGULARJS_BATARANG: ExtensionReference; + export const VUEJS_DEVTOOLS: ExtensionReference; + export const REDUX_DEVTOOLS: ExtensionReference; + export const REACT_PERF: ExtensionReference; +} \ No newline at end of file diff --git a/express-serve-static-core/express-serve-static-core.d.ts b/express-serve-static-core/express-serve-static-core.d.ts index e80ffa85a9..624ed5ae5d 100644 --- a/express-serve-static-core/express-serve-static-core.d.ts +++ b/express-serve-static-core/express-serve-static-core.d.ts @@ -97,6 +97,10 @@ declare module "express-serve-static-core" { use: IRouterHandler & IRouterMatcher; route(prefix: PathParams): IRoute; + /** + * Stack of configured routes + */ + stack: any[]; } interface IRoute { @@ -1048,7 +1052,7 @@ declare module "express-serve-static-core" { routes: any; /** - * Using to all registered routes in Express Application + * Used to get all registered routes in Express Application */ _router: any; } diff --git a/faker/faker-tests.ts b/faker/faker-tests.ts index 77f3a2c2ca..97e53d57fb 100644 --- a/faker/faker-tests.ts +++ b/faker/faker-tests.ts @@ -123,6 +123,7 @@ resultStr = faker.internet.mac(); resultStr = faker.internet.password(); resultStr = faker.internet.password(0, false, '#', 'foo'); +resultStr = faker.lorem.word(); resultStr = faker.lorem.words(); resultStr = faker.lorem.words(0); resultStr = faker.lorem.sentence(); diff --git a/faker/faker.d.ts b/faker/faker.d.ts index 7860a72745..c5f69eeefd 100644 --- a/faker/faker.d.ts +++ b/faker/faker.d.ts @@ -1,4 +1,4 @@ -// Type definitions for faker +// Type definitions for faker v3.1 // Project: http://marak.com/faker.js/ // Definitions by: Bas Pennings , Yuki Kokubun // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -135,6 +135,7 @@ declare namespace Faker { }; lorem: { + word(): string; words(num?: number): string; sentence(wordCount?: number, range?: number): string; sentences(sentenceCount?: number): string; diff --git a/i18next-xhr-backend/i18next-xhr-backend-tests.ts b/i18next-xhr-backend/i18next-xhr-backend-tests.ts new file mode 100644 index 0000000000..404eb30297 --- /dev/null +++ b/i18next-xhr-backend/i18next-xhr-backend-tests.ts @@ -0,0 +1,21 @@ +/// +/// + +import * as i18next from 'i18next'; +import XHR from 'i18next-xhr-backend'; + +let options = { + loadPath: '', + addPath: '', + allowMultiLoading: false, + parse: function(data:string) { return data.replace(/a/g, ''); }, + crossDomain: false, + withCredentials: false, + ajax: function (url:string, options:Object, callback: Function, data: Object) {} +}; + +i18next.use(XHR).init({ + backend: options +}); + +let xhr = new XHR(null, options); \ No newline at end of file diff --git a/i18next-xhr-backend/i18next-xhr-backend.d.ts b/i18next-xhr-backend/i18next-xhr-backend.d.ts new file mode 100644 index 0000000000..d1c95a0bd3 --- /dev/null +++ b/i18next-xhr-backend/i18next-xhr-backend.d.ts @@ -0,0 +1,36 @@ +// Type definitions for i18next-xhr-backend 1.2.0 +// Project: https://github.com/i18next/i18next-xhr-backend +// Definitions by: Jan Mühlemann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'i18next-xhr-backend' { + + interface Interpolator { + interpolate: () => string + } + interface Services { + interpolator: Interpolator + } + + interface BackendOptions { + loadPath?: string | Function, + addPath?: string, + allowMultiLoading?: boolean, + parse?: Function, + crossDomain?: boolean, + withCredentials?: boolean, + ajax?: Function + } + + export default class Backend { + type: 'backend'; + services: Services; + options: BackendOptions; + constructor(services?: Services, options?: BackendOptions); + init(services?: Services, options?: BackendOptions): void; + readMulti(languages: any[], namespaces: any[], callback: Function): void; + read(language: {}, namespace: {}, callback: Function): void; + loadUrl(url: string, callback: Function): void; + create(languages: any[], namespace: string, key: string, fallbackValue: string): void; + } +} \ No newline at end of file diff --git a/imap-simple/imap-simple-tests.ts b/imap-simple/imap-simple-tests.ts new file mode 100644 index 0000000000..c4d0dee1d3 --- /dev/null +++ b/imap-simple/imap-simple-tests.ts @@ -0,0 +1,85 @@ +/// + +import * as imaps from "imap-simple"; + +let config = { + imap: { + user: "your@email.address", + password: "yourpassword", + host: "imap.gmail.com", + port: 993, + tls: true, + authTimeout: 3000 + } +}; + +imaps.connect(config).then(function (connection) { + + return connection.openBox("INBOX").then(function () { + let searchCriteria = [ + "UNSEEN" + ]; + + let fetchOptions = { + bodies: ["HEADER", "TEXT"], + markSeen: false + }; + + return connection.search(searchCriteria, fetchOptions).then(function (results) { + let subjects = results.map(function (res) { + return res.parts.filter(function (part) { + return part.which === "HEADER"; + })[0].body.subject[0]; + }); + + console.log(subjects); + // => + // [ "Hey Chad, long time no see!", + // "Your amazon.com monthly statement", + // "Hacker Newsletter Issue #445" ] + }); + }); +}); + +imaps.connect(config).then(function (connection) { + + connection.openBox("INBOX").then(function () { + + // Fetch emails from the last 24h + let delay = 24 * 3600 * 1000; + let yesterday = new Date(); + yesterday.setTime(Date.now() - delay); + let yesterdayString = yesterday.toISOString(); + let searchCriteria = ["UNSEEN", ["SINCE", yesterdayString]]; + let fetchOptions = { bodies: ["HEADER.FIELDS (FROM TO SUBJECT DATE)"], struct: true }; + + // retrieve only the headers of the messages + return connection.search(searchCriteria, fetchOptions); + }).then(function (messages) { + + let attachments: Promise<{filename: string, data: any}>[] = []; + + messages.forEach(function (message) { + let parts = imaps.getParts(message.attributes.struct); + attachments = attachments.concat(parts.filter(function (part) { + return part.disposition && part.disposition.type === "ATTACHMENT"; + }).map(function (part) { + // retrieve the attachments only of the messages with attachments + return connection.getPartData(message, part) + .then(function (partData) { + return { + filename: part.disposition.params.filename, + data: partData + }; + }); + })); + }); + + return Promise.all<{filename: string, data: any}>(attachments); + }).then(function (attachments: {filename: string, data: any}[]) { + console.log(attachments); + // => + // [ { filename: "cats.jpg", data: Buffer() }, + // { filename: "pay-stub.pdf", data: Buffer() } ] + }); +}); diff --git a/imap-simple/imap-simple.d.ts b/imap-simple/imap-simple.d.ts new file mode 100644 index 0000000000..c7e66c4997 --- /dev/null +++ b/imap-simple/imap-simple.d.ts @@ -0,0 +1,75 @@ +// Type definitions for imap-simple v1.6.3 +// Project: https://github.com/chadxz/imap-simple +// Definitions by: Jeffery Grajkowski +// Definitions: https://github.com/psnider/DefinitelyTyped/imap-simple + +/// + +declare namespace IMAPS { + + export interface ImapSimpleOptions { + /** Options to pass to node-imap constructor. */ + imap: IMAP.Config; + + /** Time in milliseconds to wait before giving up on a connection attempt. (Deprecated: please use options.imap.authTimeout instead) */ + connectTimeout?: number; + } + + export interface MessageBodyPart extends IMAP.ImapMessageBodyInfo { + /** string type where which=='TEXT', complex Object where which=='HEADER' */ + body: any; + } + + export interface Message { + attributes: IMAP.ImapMessageAttributes; + parts: MessageBodyPart[]; + } + + export class ImapSimple { + constructor(imap: IMAP.Connection); + + /** Open a mailbox, calling the provided callback with signature (err, boxName), or resolves the returned promise with boxName. */ + openBox(boxName: string, callback: (err: Error, boxName: string) => void): void; + openBox(boxName: string): Promise; + + /** Search for and retrieve mail in the previously opened mailbox. */ + search(searchCriteria: any[], fetchOptions: IMAP.FetchOptions, callback: (err: Error, messages: Message[]) => void): void; + search(searchCriteria: any[], fetchOptions: IMAP.FetchOptions): Promise; + + /** Close the connection to the imap server. */ + end(): void; + + /** Downloads part data (which is either part of the message body, or an attachment). Upon success, either the provided callback will be called with signature (err, data), or the returned promise will be resolved with data. The data will be automatically decoded based on its encoding. If the encoding of the part is not supported, an error will occur. */ + getPartData(message: Message, part: any, callback: (err: Error, data: any) => void): void; + getPartData(message: Message, part: any): Promise; + + /** Adds the provided label(s) to the specified message(s). source corresponds to a node-imap MessageSource which specifies the messages to be moved. label is either a string or array of strings indicating the labels to add. When completed, either calls the provided callback with signature (err), or resolves the returned promise. */ + addMessageLabel(source: string | string[], label: string | string[], callback: (err: Error) => void): void; + addMessageLabel(source: string | string[], label: string | string[]): Promise; + + /** Moves the specified message(s) in the currently open mailbox to another mailbox. source corresponds to a node-imap MessageSource which specifies the messages to be moved. When completed, either calls the provided callback with signature (err), or resolves the returned promise. */ + moveMessage(source: string | string[], boxName: string, callback: (err: Error) => void): void; + moveMessage(source: string | string[], boxName: string): Promise; + } + + /** Error thrown when a connection attempt has timed out. */ + export class ConnectionTimeoutError extends Error { + timeout: number; + constructor(timeout: number); + } +} + +declare module "imap-simple" { + /** Main entry point. Connect to an Imap server. */ + export function connect(options: IMAPS.ImapSimpleOptions, callback: (err: Error, connection: IMAPS.ImapSimple) => void): void; + export function connect(options: IMAPS.ImapSimpleOptions): Promise; + + export namespace errors { + export import ConnectionTimeoutError = IMAPS.ConnectionTimeoutError; + } + + export import ImapSimple = IMAPS.ImapSimple; + + /** Given the message.attributes.struct, retrieve a flattened array of parts objects that describe the structure of the different parts of the message's body. Useful for getting a simple list to iterate for the purposes of, for example, finding all attachments. */ + export function getParts(struct: any[]): any[]; +} diff --git a/mapbox-gl/mapbox-gl-tests.ts b/mapbox-gl/mapbox-gl-tests.ts new file mode 100644 index 0000000000..f77a9f4af7 --- /dev/null +++ b/mapbox-gl/mapbox-gl-tests.ts @@ -0,0 +1,374 @@ +// These examples adapted from Mapbox's examples (https://www.mapbox.com/mapbox-gl-js/examples) +/// +/// + +/** + * Set API Access Token + */ +mapboxgl.accessToken = 'foo'; + + +/** + * Display a Map + */ +let map = new mapboxgl.Map({ + container: 'map', + style: 'mapbox://styles/mapbox/streets-v8', + center: [-50, 50], + zoom: 10, + minZoom: 1, + maxZoom: 2, + interactive: true, + attributionControl: false, + bearingSnap: 7, + scrollZoom: true, + maxBounds: [[-100,-90],[100,90]], + boxZoom: true, + dragRotate: false, + dragPan: true, +}); + + +/** + * Create and style marker clusters + */ +map.on('load', function(){ + + // Add a new source from our GeoJSON data and set the + // 'cluster' option to true. + map.addSource("data", { + type: "geojson", + data: "/data.geojson", + cluster: true, + clusterMaxZoom: 14, // Max zoom to cluster points on + clusterRadius: 50 // Radius of each cluster when clustering points (defaults to 50) + }); + + map.addLayer({ + "id": "layer", + "type": "symbol", + "source": "data", + "layout": { + "icon-image": "marker-15" + } + }); + + var layers = [ + [150, '#f28cb1'], + [20, '#f1f075'], + [0, '#51bbd6'] + ]; + + layers.forEach(function (layer, i) { + map.addLayer({ + "id": "cluster-" + i, + "type": "circle", + "source": "data", + "paint": { + "circle-color": layer[1], + "circle-radius": 18 + }, + "filter": i == 0 ? + [">=", "point_count", layer[0]] : + ["all", + [">=", "point_count", layer[0]], + ["<", "point_count", layers[i - 1][0]]] + }); + }); + + // Add a layer for the clusters' count labels + map.addLayer({ + "id": "cluster-count", + "type": "symbol", + "source": "data", + "layout": { + "text-field": "{point_count}", + "text-font": [ + "DIN Offc Pro Medium", + "Arial Unicode MS Bold" + ], + "text-size": 12 + } + }); + +/** + * Add a GeoJSON line + */ + map.addSource("route", { + "type": "geojson", + "data": { + "type": "Feature", + "properties": {}, + "geometry": { + "type": "LineString", + "coordinates": [ + [-122.48369693756104, 37.83381888486939], + [-122.48348236083984, 37.83317489144141], + [-122.48339653015138, 37.83270036637107], + [-122.48356819152832, 37.832056363179625], + [-122.48404026031496, 37.83114119107971], + [-122.48404026031496, 37.83049717427869], + [-122.48348236083984, 37.829920943955045], + [-122.48356819152832, 37.82954808664175], + [-122.48507022857666, 37.82944639795659], + [-122.48610019683838, 37.82880236636284], + [-122.48695850372314, 37.82931081282506], + [-122.48700141906738, 37.83080223556934], + [-122.48751640319824, 37.83168351665737], + [-122.48803138732912, 37.832158048267786], + [-122.48888969421387, 37.83297152392784], + [-122.48987674713133, 37.83263257682617], + [-122.49043464660643, 37.832937629287755], + [-122.49125003814696, 37.832429207817725], + [-122.49163627624512, 37.832564787218985], + [-122.49223709106445, 37.83337825839438], + [-122.49378204345702, 37.83368330777276] + ] + } + } + }); + + map.addLayer({ + "id": "route", + "type": "line", + "source": "route", + "layout": { + "line-join": "round", + "line-cap": "round" + }, + "paint": { + "line-color": "#888", + "line-width": 8 + } + }); +}); + +// FlyTo +map.flyTo({ + center: [0, 0], + zoom: 10, + speed: 0.5, + curve: 1, + screenSpeed: 1, + easing: function(t: any) { + return t; + } +}); + +/** + * GeoJSONSource + */ +var geoJSONSourceObj = new mapboxgl.GeoJSONSource({ + data: { + "type": "FeatureCollection", + "features": [{ + "type": "Feature", + "properties": null, + "geometry": { + "type": "Point", + "coordinates": [-50, 0] + } + }] + } +}); +map.addSource('some id', geoJSONSourceObj); // add +map.removeSource('some id'); // remove + +/** + * ImageSource + */ +var imageSourceObj = new mapboxgl.ImageSource({ + url: '/foo.png', + coordinates: [ + [-76.54335737228394, 39.18579907229748], + [-76.52803659439087, 39.1838364847587], + [-76.5295386314392, 39.17683392507606], + [-76.54520273208618, 39.17876344106642] + ] +}); +map.addSource('some id', imageSourceObj); // add +map.removeSource('some id'); // remove + +/** + * Video Source + */ +var videoSourceObj = new mapboxgl.VideoSource({ + urls: [ + '/blah.mp4', + '/blah.webm' + ], + coordinates: [ + [-76.54335737228394, 39.18579907229748], + [-76.52803659439087, 39.1838364847587], + [-76.5295386314392, 39.17683392507606], + [-76.54520273208618, 39.17876344106642] + ] +}); +map.addSource('some id', videoSourceObj); // add +map.removeSource('some id'); // remove + +/** + * Popup + */ +var popup = new mapboxgl.Popup({closeOnClick: false, closeButton: true, anchor: 'top-right', offset: {'top': [0,0], 'bottom': [25,-50]} }) + .setLngLat([-50, 50]) + .setHTML('

Hello World!

') + .addTo(map); + +/** + * Add an image + */ +var mapStyle = { + "version": 8, + "name": "Dark", + "sources": { + "mapbox": { + "type": "vector", + "url": "mapbox://mapbox.mapbox-streets-v6" + }, + "overlay": { + "type": "image", + "url": "/mapbox-gl-js/assets/radar.gif", + "coordinates": [ + [-50, 40], + [0, 40], + [0, 0], + [-50, 0] + ] + } + }, + "sprite": "mapbox://sprites/mapbox/dark-v8", + "glyphs": "mapbox://fonts/mapbox/{fontstack}/{range}.pbf", + "layers": [ + { + "id": "background", + "type": "background", + "paint": {"background-color": "#111"} + }, + { + "id": "water", + "source": "mapbox", + "source-layer": "water", + "type": "fill", + "paint": {"fill-color": "#2c2c2c"} + }, + { + "id": "boundaries", + "source": "mapbox", + "source-layer": "admin", + "type": "line", + "paint": {"line-color": "#797979", "line-dasharray": [2, 2, 6, 2]}, + "filter": ["all", ["==", "maritime", 0]], + }, + { + "id": "overlay", + "source": "overlay", + "type": "raster", + "paint": {"raster-opacity": 0.85} + }, + { + "id": "cities", + "source": "mapbox", + "source-layer": "place_label", + "type": "symbol", + "layout": { + "text-field": "{name_en}", + "text-font": ["DIN Offc Pro Bold", "Arial Unicode MS Bold"], + "text-size": {"stops": [[4, 9], [6, 12]]} + }, + "paint": { + "text-color": "#969696", + "text-halo-width": 2, + "text-halo-color": "rgba(0, 0, 0, 0.85)" + } + }, + { + "id": "states", + "source": "mapbox", + "source-layer": "state_label", + "type": "symbol", + "layout": { + "text-transform": "uppercase", + "text-field": "{name_en}", + "text-font": ["DIN Offc Pro Bold", "Arial Unicode MS Bold"], + "text-letter-spacing": 0.15, + "text-max-width": 7, + "text-size": {"stops": [[4, 10], [6, 14]]} + }, + "filter": [">=", "area", 80000], + "paint": { + "text-color": "#969696", + "text-halo-width": 2, + "text-halo-color": "rgba(0, 0, 0, 0.85)" + } + } + ] +}; + +map = new mapboxgl.Map({ + container: 'map', + minZoom: 14, + zoom: 17, + center: [-122.514426, 37.562984], + bearing: -96, + style: videoStyle, + hash: false +}); + +/** + * Add video + */ +var videoStyle: mapboxgl.Style = { + "version": 8, + "sources": { + "satellite": { + "type": "raster", + "url": "mapbox://mapbox.satellite", + "tileSize": 256 + }, + "video": { + "type": "video", + "urls": ["drone.mp4", "drone.webm"], + "coordinates": [ + [-122.51596391201019, 37.56238816766053], + [-122.51467645168304, 37.56410183312965], + [-122.51309394836426, 37.563391708549425], + [-122.51423120498657, 37.56161849366671] + ] + } + }, + "layers": [{ + "id": "background", + "type": "background", + "paint": { + "background-color": "rgb(4,7,14)" + } + }, { + "id": "satellite", + "type": "raster", + "source": "satellite" + }, { + "id": "video", + "type": "raster", + "source": "video" + }] +}; + +map = new mapboxgl.Map({ + container: 'map', + minZoom: 14, + zoom: 17, + center: [-122.514426, 37.562984], + bearing: -96, + style: videoStyle, + hash: false +}); + +/** + * Marker + */ +let marker = new mapboxgl.Marker(null,{offset: [10, 0]}) + .setLngLat([-50,50]) + .addTo(map); + +marker.remove(); \ No newline at end of file diff --git a/mapbox-gl/mapbox-gl.d.ts b/mapbox-gl/mapbox-gl.d.ts new file mode 100644 index 0000000000..2ee8d30949 --- /dev/null +++ b/mapbox-gl/mapbox-gl.d.ts @@ -0,0 +1,936 @@ +// Type definitions for Mapbox GL JS v0.24.0 +// Project: https://github.com/mapbox/mapbox-gl-js +// Definitions by: Dominik Bruderer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare namespace mapboxgl { + let accessToken: string; + let version: string; + export function supported(options?: {failIfMajorPerformanceCaveat?: boolean}): boolean; + + /** + * Map + */ + export class Map extends Evented { + constructor(options?: MapboxOptions); + + addControl(control: Control): this; + + addClass(klass: string, options?: mapboxgl.StyleOptions): this; + + removeClass(klass: string, options?: mapboxgl.StyleOptions): this; + + setClasses(klasses: string[], options?: mapboxgl.StyleOptions): this; + + hasClass(klass: string): boolean; + + getClasses(): string[]; + + resize(): this; + + getBounds(): mapboxgl.LngLatBounds; + + setMaxBounds(lnglatbounds?: mapboxgl.LngLatBounds | number[][]): this; + + setMinZoom(minZoom?: number): this; + + setMaxZoom(maxZoom?: number): this; + + project(lnglat: mapboxgl.LngLat | number[]): mapboxgl.Point; + + unproject(point: mapboxgl.Point | number[]): mapboxgl.LngLat; + + queryRenderedFeatures(pointOrBox?: mapboxgl.Point|number[]|mapboxgl.Point[]|number[][], parameters?: {layers?: string[], filter?: any[]}): GeoJSON.Feature[]; + + querySourceFeatures(sourceID: string, parameters: {sourceLayer?: string, filter?: any[]}): GeoJSON.Feature[]; + + setStyle(style: mapboxgl.Style | string): this; + + getStyle(): mapboxgl.Style; + + addSource(id: string, source: VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource | GeoJSONSourceRaw): this; + + removeSource(id: string): this; + + getSource(id: string): VectorSource | RasterSource | GeoJSONSource | ImageSource | VideoSource; + + addLayer(layer: mapboxgl.Layer, before?: string): this; + + removeLayer(id: string): this; + + getLayer(id: string): mapboxgl.Layer; + + setFilter(layer: string, filter: any[]): this; + + setLayerZoomRange(layerId: string, minzoom: number, maxzoom: number): this; + + getFilter(layer: string): any[]; + + setPaintProperty(layer: string, name: string, value: any, klass?: string): this; + + getPaintProperty(layer: string, name: string, klass?: string): any; + + setLayoutProperty(layer: string, name: string, value: any): this; + + getLayoutProperty(layer: string, name: string, klass?: string): any; + + getContainer(): HTMLElement; + + getCanvasContainer(): HTMLElement; + + getCanvas(): HTMLCanvasElement; + + loaded(): boolean; + + remove(): void; + + onError(): void; + + showTileBoundaries: boolean; + + showCollisionBoxes: boolean; + + repaint: boolean; + + getCenter(): mapboxgl.LngLat; + + setCenter(center: LngLat|number[], eventData?: mapboxgl.EventData): this; + + panBy(offset: number[], options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + panTo(lnglat: mapboxgl.LngLat, options?: mapboxgl.AnimationOptions, eventdata?: mapboxgl.EventData): this; + + getZoom(): number; + + setZoom(zoom: number, eventData?: mapboxgl.EventData): this; + + zoomTo(zoom: number, options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + zoomIn(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + zoomOut(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + getBearing(): number; + + setBearing(bearing: number, eventData?: mapboxgl.EventData): this; + + rotateTo(bearing: number, options?: mapboxgl.AnimationOptions, eventData?: EventData): this; + + resetNorth(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + snapToNorth(options?: mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + getPitch(): number; + + setPitch(pitch: number, eventData?: EventData): this; + + fitBounds(bounds: mapboxgl.LngLatBounds | number[][], options?: { linear?: boolean, easing?: Function, padding?: number, offset?: Point|number[],maxZoom?: number }): this; + + jumpTo(options: mapboxgl.CameraOptions, eventData?: mapboxgl.EventData): this; + + easeTo(options: mapboxgl.CameraOptions | mapboxgl.AnimationOptions, eventData?: mapboxgl.EventData): this; + + flyTo(options: mapboxgl.FlyToOptions, eventData?: mapboxgl.EventData): this; + + stop(): this; + + scrollZoom: ScrollZoomHandler; + + boxZoom: BoxZoomHandler; + + dragRotate: DragRotateHandler; + + dragPan: DragPanHandler; + + keyboard: KeyboardHandler; + + doublClickZoom: DoubleClickZoomHandler; + + touchZoomRotate: TouchZoomRotateHandler; + } + + export interface MapboxOptions { + /** If true, an attribution control will be added to the map. */ + attributionControl?: boolean; + + bearing?: number; + + /** Snap to north threshold in degrees. */ + bearingSnap?: number; + + /** If true, enable the "box zoom" interaction (see BoxZoomHandler) */ + boxZoom?: boolean; + + /** initial map center */ + center?: mapboxgl.LngLat | number[]; + + /** Style class names with which to initialize the map */ + classes?: string[]; + + /** ID of the container element */ + container?: string | Element; + + /** If true, enable the "drag to pan" interaction (see DragPanHandler). */ + dragPan?: boolean; + + /** If true, enable the "drag to rotate" interaction (see DragRotateHandler). */ + dragRotate?: boolean; + + /** If true, enable the "double click to zoom" interaction (see DoubleClickZoomHandler). */ + doubleClickZoom?: boolean; + + /** If true, the map will track and update the page URL according to map position */ + hash?: boolean; + + /** If true, map creation will fail if the implementation determines that the performance of the created WebGL context would be dramatically lower than expected. */ + failIfMayorPerformanceCaveat?: boolean; + + /** If false, no mouse, touch, or keyboard listeners are attached to the map, so it will not respond to input */ + interactive?: boolean; + + /** If true, enable keyboard shortcuts (see KeyboardHandler). */ + keyboard?: boolean; + + /** If set, the map is constrained to the given bounds. */ + maxBounds?: mapboxgl.LngLatBounds | number[][]; + + /** Maximum zoom of the map */ + maxZoom?: number; + + /** Minimum zoom of the map */ + minZoom?: number; + + /** If true, The maps canvas can be exported to a PNG using map.getCanvas().toDataURL();. This is false by default as a performance optimization. */ + preserveDrawingBuffer?: boolean; + + pitch?: number; + + /** If true, enable the "scroll to zoom" interaction */ + scrollZoom?: boolean; + + /** stylesheet location */ + style?: mapboxgl.Style | string; + + /** If true, the map will automatically resize when the browser window resizes */ + trackResize?: boolean; + + /** If true, enable the "pinch to rotate and zoom" interaction (see TouchZoomRotateHandler). */ + touchZoomRotate?: boolean; + + /** Initial zoom level */ + zoom?: number; + } + + /** + * BoxZoomHandler + */ + export class BoxZoomHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + isActive(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * ScrollZoomHandler + */ + export class ScrollZoomHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * DragPenHandler + */ + export class DragPanHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + isActive(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * DragRotateHandler + */ + export class DragRotateHandler { + constructor(map: mapboxgl.Map, options?: {bearingSnap?: number, pitchWithRotate?: boolean}); + + isEnabled(): boolean; + + isActive(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * KeyboardHandler + */ + export class KeyboardHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * DoubleClickZoomHandler + */ + export class DoubleClickZoomHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + enable(): void; + + disable(): void; + } + + /** + * TouchZoomRotateHandler + */ + export class TouchZoomRotateHandler { + constructor(map: mapboxgl.Map); + + isEnabled(): boolean; + + enable(): void; + + disable(): void; + + disableRotation(): void; + + enableRotation(): void; + } + + /** + * Control + */ + export class Control extends Evented { + addTo(map: mapboxgl.Map): this; + + remove(): this; + } + + /** + * ControlOptions + */ + export interface ControlOptions { + position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left'; + } + + /** + * Navigation + */ + export class Navigation extends Control { + constructor(options?: mapboxgl.ControlOptions); + } + + /** + * Geolocate + */ + export class Geolocate extends Control { + constructor(options?: mapboxgl.ControlOptions); + } + + /** + * Attribution + */ + export class Attribution extends Control { + constructor(options?: mapboxgl.ControlOptions); + } + + /** + * Scale + */ + export class Scale extends Control { + constructor(options?: {position?: 'top-right' | 'top-left' | 'bottom-right' | 'bottom-left', maxWidth?: number, unit?: string}) + } + + /** + * Popup + */ + export class Popup extends Evented { + constructor(options?: mapboxgl.PopupOptions); + + addTo(map: mapboxgl.Map): this; + + isOpen(): boolean; + + remove(): this; + + getLngLat(): mapboxgl.LngLat; + + setLngLat(lnglat: mapboxgl.LngLat | number[]): this; + + setText(text: string): this; + + setHTML(html: string): this; + + setDOMContent(htmlNode: Node): this; + } + + export interface PopupOptions { + closeButton?: boolean; + + closeOnClick?: boolean; + + anchor?: 'top' | 'bottom' | 'left' | 'right' | 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; + + offset?: number | Point | number[] | { [key:string]: Point | number[];}; + } + + export interface Style { + bearing?: number; + center?: number[]; + glyphs?: string; + layers?: Layer[]; + metadata?: any; + name?: string; + pitch?: number; + sources?: any; + sprite?: string; + transition?: Transition; + version: number; + zoom?: number; + } + + export interface Transition { + delay?: number; + duration?: number; + } + + export interface Source { + type: "vector" | "raster" | "geojson" | "image" | "video"; + } + + /** + * GeoJSONSource + */ + + export interface GeoJSONSourceRaw extends Source, GeoJSONSourceOptions { + type: "geojson"; + } + + export class GeoJSONSource implements GeoJSONSourceRaw { + type: "geojson"; + + constructor(options?: mapboxgl.GeoJSONSourceOptions); + + setData(data: GeoJSON.Feature | GeoJSON.FeatureCollection | String): this; + } + + export interface GeoJSONSourceOptions { + data?: GeoJSON.Feature | GeoJSON.FeatureCollection | string; + + maxzoom?: number; + + buffer?: number; + + tolerance?: number; + + cluster?: number | boolean; + + clusterRadius?: number; + + clusterMaxZoom?: number; + } + + /** + * VideoSource + */ + export class VideoSource implements Source, VideoSourceOptions { + type: "video"; + + constructor(options?: mapboxgl.VideoSourceOptions); + + getVideo(): HTMLVideoElement; + + setCoordinates(coordinates: number[][]): this; + } + + export interface VideoSourceOptions { + urls?: string[]; + + coordinates?: number[][]; + } + + /** + * ImageSource + */ + export class ImageSource implements Source, ImageSourceOptions { + type: "image"; + + constructor(options?: mapboxgl.ImageSourceOptions); + + setCoordinates(coordinates: number[][]): this; + } + + export interface ImageSourceOptions { + url?: string; + + coordinates?: number[][]; + } + + interface VectorSource extends Source { + type: "vector"; + url?: string; + tiles?: string[]; + minzoom?: number; + maxzoom?: number; + } + + interface RasterSource extends Source { + type: "raster"; + url: string; + tiles?: string[]; + minzoom?: number; + maxzoom?: number; + tileSize?: number; + } + + /** + * LngLat + */ + export class LngLat { + lng: number; + lat: number; + + constructor(lng: number, lat: number); + + /** Return a new LngLat object whose longitude is wrapped to the range (-180, 180). */ + wrap(): mapboxgl.LngLat; + + /** Return a LngLat as an array */ + toArray(): number[]; + + /** Return a LngLat as a string */ + toString(): string; + + static convert(input: number[]|mapboxgl.LngLat): mapboxgl.LngLat; + } + + /** + * LngLatBounds + */ + export class LngLatBounds { + sw: LngLat | number[]; + ne: LngLat | number[]; + constructor(sw?: LngLat, ne?: LngLat); + + /** Extend the bounds to include a given LngLat or LngLatBounds. */ + extend(obj: mapboxgl.LngLat | mapboxgl.LngLatBounds): this; + + /** Get the point equidistant from this box's corners */ + getCenter(): mapboxgl.LngLat; + + /** Get southwest corner */ + getSouthWest(): mapboxgl.LngLat; + + /** Get northeast corner */ + getNorthEast(): mapboxgl.LngLat; + + /** Get northwest corner */ + getNorthWest(): mapboxgl.LngLat; + + /** Get southeast corner */ + getSouthEast(): mapboxgl.LngLat; + + /** Get west edge longitude */ + getWest(): number; + + /** Get south edge latitude */ + getSouth(): number; + + /** Get east edge longitude */ + getEast(): number; + + /** Get north edge latitude */ + getNorth(): number; + + /** Returns a LngLatBounds as an array */ + toArray(): number[][]; + + /** Return a LngLatBounds as a string */ + toString(): string; + + /** Convert an array to a LngLatBounds object, or return an existing LngLatBounds object unchanged. */ + static convert(input: mapboxgl.LngLatBounds | number[] | number[][]): mapboxgl.LngLatBounds; + } + + /** + * Point + */ + // Todo: Pull out class to seperate definition for Module "point-geometry" + export class Point { + constructor(options?: Object); + + clone(): Point; + + add(p: number): Point; + + sub(p: number): Point; + + mult(k: number): Point; + + div(k: number): Point; + + rotate(a: number): Point; + + matMult(m: number): Point; + + unit(): Point; + + perp(): Point; + + round(): Point; + + mag(): number; + + equals(): boolean; + + dist(): number; + + distSqr(): number; + + angle(): number; + + angleTo(): number; + + angleWidth(): number; + + angleWidthSep(): number; + } + + export class Marker { + constructor(element?: HTMLElement, options?: { offset?: Point | number[] }); + + addTo(map: Map): this; + + remove(): this; + + getLngLat(): LngLat; + + setLngLat(lngLat: LngLat | number[]): this; + + setPopup(popup?: Popup): this; + + getPopup(): Popup; + + togglePopup(): this; + } + + /** + * Evented + */ + export class Evented { + on(type: string, listener: Function): this; + + off(type?: string | any, listener?: Function): this; + + once(type: string, listener: Function): this; + + fire(type: string, data?: mapboxgl.EventData | Object): this; + + listens(type: string): boolean; + } + + /** + * StyleOptions + */ + export interface StyleOptions { + transition?: boolean; + } + + /** + * EventData + */ + export class EventData { + type: string; + target: Map; + originalEvent: Event; + point: mapboxgl.Point; + lngLat: mapboxgl.LngLat; + } + + export class MapMouseEvent { + type: string; + target: Map; + originalEvent: MouseEvent; + point: mapboxgl.Point; + lngLat: mapboxgl.LngLat; + } + + export class MapTouchEvent { + type: string; + target: Map; + originalEvent: TouchEvent; + point: mapboxgl.Point; + lngLat: mapboxgl.LngLat; + points: Point[]; + lngLats: LngLat[]; + } + + export class MapBoxZoomEvent { + originalEvent: MouseEvent; + boxZoomBounds: LngLatBounds; + } + + /** + * AnimationOptions + */ + export interface AnimationOptions { + /** Number in milliseconds */ + duration?: number; + easing?: Function; + /** point, origin of movement relative to map center */ + offset?: Point | number[]; + /** When set to false, no animation happens */ + animate?: boolean; + } + + /** + * CameraOptions + */ + export interface CameraOptions { + /** Map center */ + center?: mapboxgl.LngLat | number[]; + /** Map zoom level */ + zoom?: number; + /** Map rotation bearing in degrees counter-clockwise from north */ + bearing?: number; + /** Map angle in degrees at which the camera is looking at the ground */ + pitch?: number; + /** If zooming, the zoom center (defaults to map center) */ + around?: mapboxgl.LngLat | number[]; + } + + /** + * FlyToOptions + */ + export interface FlyToOptions extends AnimationOptions, CameraOptions { + curve?: number; + minZoom?: number; + speed?: number; + screenSpeed?: number; + easing?: Function; + } + + /** + * MapEvent + */ + export interface MapEvent { + webglcontextlost?: {originalEvent: WebGLContextEvent}; + webglcontextrestored?: {originalEvent: WebGLContextEvent}; + render?: void; + contextmenu?: {data: mapboxgl.MapMouseEvent}; + dblclick?: {data: mapboxgl.MapMouseEvent}; + click?: {data: mapboxgl.MapMouseEvent}; + touchcancel?: {data: mapboxgl.MapTouchEvent}; + touchmove?: {data: mapboxgl.MapTouchEvent}; + touchend?: {data: mapboxgl.MapTouchEvent}; + touchstart?: {data: mapboxgl.MapTouchEvent}; + mousemove?: {data: mapboxgl.MapMouseEvent}; + mouseup?: {data: mapboxgl.MapMouseEvent}; + mousedown?: {data: mapboxgl.MapMouseEvent}; + moveend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + move?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + movestart?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + mouseout?:{data: mapboxgl.MapMouseEvent}; + load?: void; + zoomend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + zoom?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + zoomstart?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + boxzoomcancel?: {data: mapboxgl.MapBoxZoomEvent}; + boxzoomstart?: {data: mapboxgl.MapBoxZoomEvent}; + boxzoomend?: {data: mapboxgl.MapBoxZoomEvent}; + rotate?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + rotatestart?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + rotateend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + drag?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + dragend?: {data: mapboxgl.MapMouseEvent | mapboxgl.MapTouchEvent}; + pitch?: {data: mapboxgl.EventData}; + } + + export interface Layer { + id: string; + type?: "fill" | "line" | "symbol" | "circle" | "raster" | "background" | string; //TODO: Ideally we wouldn't accept string here, just these specific strings + + metadata?: any; + ref?: string; + + source?: string; + + "source-layer"?: string; + + minzoom?: number; + maxzoom?: number; + + interactive?: boolean; + + filter?: any[]; + layout?: BackgroundLayout | FillLayout | LineLayout | SymbolLayout | RasterLayout | CircleLayout; + paint?: BackgroundPaint | FillPaint | LinePaint | SymbolPaint | RasterPaint | CirclePaint; + } + + export interface StyleFunction { + stops: any[][]; + property?: string; + base?: number; + type?: "continuous" | "interval" | "categorical"; + } + + export interface BackgroundLayout { + visibility?: "visible" | "none"; + } + export interface BackgroundPaint { + "background-color"?: string; + "background-pattern"?: string; + "background-opacity"?: number; + } + + export interface FillLayout { + visibility?: "visible" | "none"; + } + export interface FillPaint { + "fill-antialias"?: boolean; + "fill-opacity"?: number | StyleFunction; + "fill-color"?: string | StyleFunction; + "fill-outline-color": string | StyleFunction; + "fill-translate"?: number[]; + "fill-translate-anchor"?: "map" | "viewport"; + "fill-pattern"?: "string"; + } + + export interface LineLayout { + visibility?: "visible" | "none"; + + "line-cap"?: "butt" | "round" | "square"; + "line-join"?: "bevel" | "round" | "miter"; + "line-miter-limit"?: number; + "line-round-limit"?: number; + } + export interface LinePaint { + "line-opacity"?: number; + "line-color"?: string| StyleFunction; + "line-translate"?: number[]; + "line-translate-anchor"?: "map" | "viewport"; + "line-width"?: number; + "line-gap-width"?: number; + "line-offset"?: number; + "line-blur"?: number; + "line-dasharray"?: number[]; + "line-dasharray-transition"?: Transition; + "line-pattern"?: string; + } + + export interface SymbolLayout { + visibility?: "visible" | "none"; + + "symbol-placement"?: "point" | "line"; + "symbol-spacing"?: number; + "symbol-avoid-edges"?: boolean; + "icon-allow-overlap"?: boolean; + "icon-ignore-placement"?: boolean; + "icon-optional"?: boolean; + "icon-rotation-alignment"?: "map" | "viewport" | "auto"; + "icon-size"?: number; + "icon-text-fit"?: "none" | "both" | "width" | "height"; + "icon-text-fit-padding"?: number[]; + "icon-image"?: string; + "icon-rotate"?: number | StyleFunction; + "icon-padding"?: number; + "icon-keep-upright"?: boolean; + "icon-offset"?: number[]; + "text-pitch-alignment"?: "map" | "viewport" | "auto"; + "text-rotation-alignment"?: "map" | "viewport" | "auto"; + "text-field"?: string; + "text-font"?: string | string[]; + "text-size"?: number; + "text-max-width"?: number; + "text-line-height"?: number; + "text-letter-spacing"?: number; + "text-justify"?: "left" | "center" | "right"; + "text-anchor"?: "center" | "left" | "right" | "top" | "bottom" | "top-left" | "top-right" | "bottom-left" | "bottom-right"; + "text-max-angle"?: number; + "text-rotate"?: number; + "text-padding"?: number; + "text-keep-upright"?: boolean; + "text-transform"?: "none" | "uppercase" | "lowercase"; + "text-offset"?: number[]; + "text-allow-overlap"?: boolean; + "text-ignore-placement"?: boolean; + "text-optional"?: boolean; + + } + export interface SymbolPaint { + "icon-opacity"?: number; + "icon-color"?: string; + "icon-halo-color"?: string; + "icon-halo-width"?: number; + "icon-halo-blur"?: number; + "icon-translate"?: number[]; + "icon-translate-anchor"?: "map" | "viewport"; + "text-opacity"?: number; + "text-color"?: "string"; + "text-halo-color"?: "string"; + "text-halo-width"?: number; + "text-halo-blur"?: number; + "text-translate"?: number[]; + "text-translate-anchor"?: "map" | "viewport"; + } + + export interface RasterLayout { + visibility?: "visible" | "none"; + } + + export interface RasterPaint { + "raster-opacity"?: number; + "raster-hue-rotate"?: number; + "raster-brightness-min"?: number; + "raster-brightness-max"?: number; + "raster-saturation"?: number; + "raster-contrast"?: number; + "raster-fade-duration"?: number; + } + + export interface CircleLayout { + visibility?: "visible" | "none"; + } + + export interface CirclePaint { + "circle-radius"?: number | StyleFunction; + "circle-radius-transition"?: Transition; + "circle-color"?: number | StyleFunction; + "circle-blur"?: number | StyleFunction; + "circle-opacity"?: number | StyleFunction; + "circle-translate"?: number[]; + "circle-translate-anchor"?: "map" | "viewport"; + "circle-pitch-scale"?: "map" | "viewport"; + } +} + +declare module 'mapbox-gl' { + export = mapboxgl; +} diff --git a/mongoose/mongoose-tests.ts b/mongoose/mongoose-tests.ts index 6262fe35bf..7c5e9adcfc 100644 --- a/mongoose/mongoose-tests.ts +++ b/mongoose/mongoose-tests.ts @@ -961,6 +961,7 @@ schematype.unique(true).unique(true); schematype.validate(/re/) .validate({}, 'error') .validate(cb, 'try', 'tri'); +schematype.options.required; /* * section promise.js diff --git a/mongoose/mongoose.d.ts b/mongoose/mongoose.d.ts index 17675e9aa0..24664cc350 100644 --- a/mongoose/mongoose.d.ts +++ b/mongoose/mongoose.d.ts @@ -2011,6 +2011,12 @@ declare module "mongoose" { */ validate(obj: RegExp | Function | Object, errorMsg?: string, type?: string): this; + + /** + * http://mongoosejs.com/docs/api.html#schematype_SchemaType + * Options for this schema type (required, index, etc.) + */ + options: any; } /* diff --git a/oclazyload/oclazyload-tests.ts b/oclazyload/oclazyload-tests.ts index e9c4661e29..e368d3624b 100644 --- a/oclazyload/oclazyload-tests.ts +++ b/oclazyload/oclazyload-tests.ts @@ -11,7 +11,7 @@ angular.module('app', ['oc.lazyLoad']).config(['$ocLazyLoadProvider', function ( }) }]); -angular.module('app').controller(['$ocLazyLoadProvider', function ($ocLazyLoad: oc.ILazyLoad) { +angular.module('app').controller('FooCtrl', ['$ocLazyLoad', function ($ocLazyLoad: oc.ILazyLoad) { $ocLazyLoad.load('testModule.js'); $ocLazyLoad.load(['testModule.js', 'testModuleCtrl.js', 'testModuleService.js']); diff --git a/polymer/polymer.d.ts b/polymer/polymer.d.ts index 0daecee079..57135e54e1 100644 --- a/polymer/polymer.d.ts +++ b/polymer/polymer.d.ts @@ -127,15 +127,16 @@ declare namespace polymer { unlinkPaths?(path: string): void; - push?(path: string): number; + push?(path: string, ...item: any[]): number; pop?(path: string): any; - splice?(path: string, start: number, deleteCount: number): number; + splice?(path: string, index: number, removeCount: number, ...item: any[]): + number; shift?(path: string): any; - unshift?(path: string): number; + unshift?(path: string, ...item: any[]): number; // ResolveUrl diff --git a/pouchdb-core/pouchdb-core-tests.ts b/pouchdb-core/pouchdb-core-tests.ts index b46bce834d..3da5e929b7 100644 --- a/pouchdb-core/pouchdb-core-tests.ts +++ b/pouchdb-core/pouchdb-core-tests.ts @@ -38,6 +38,23 @@ namespace PouchDBCoreTests { }); } + function testBulkDocs() { + const db = new PouchDB(); + type MyModel = { property: 'someProperty '}; + let model: PouchDB.Core.Document; + let model2: PouchDB.Core.Document; + + db.bulkDocs([model, model2]).then((result) => { + result.forEach(({ ok, id, rev }) => { + isString(id); + isString(rev); + }); + }); + + db.bulkDocs([model, model2], null, (error, response) => { + }); + } + function testCompact() { const db = new PouchDB<{}>(); // Promise version diff --git a/pouchdb-core/pouchdb-core.d.ts b/pouchdb-core/pouchdb-core.d.ts index b0498e76af..cdd078f54f 100644 --- a/pouchdb-core/pouchdb-core.d.ts +++ b/pouchdb-core/pouchdb-core.d.ts @@ -268,6 +268,12 @@ declare namespace PouchDB { allDocs(options?: Core.AllDocsOptions): Promise>; + bulkDocs(docs: Core.Document[], + options: Core.PutOptions | void, + callback: Core.Callback): void; + bulkDocs(docs: Core.Document[], + options?: Core.PutOptions): Promise; + /** Compact the database */ compact(options?: Core.CompactOptions): Promise; compact(options: Core.CompactOptions, diff --git a/rrule/rrule-test.ts b/rrule/rrule-test.ts new file mode 100644 index 0000000000..11a48c5126 --- /dev/null +++ b/rrule/rrule-test.ts @@ -0,0 +1,62 @@ +/// + +import * as RRule from 'rrule'; + +// Create a rule: +let rule: RRule = new RRule({ + freq: RRule.WEEKLY, + interval: 5, + byweekday: [RRule.MO, RRule.FR], + dtstart: new Date(2012, 1, 1, 10, 30), + until: new Date(2012, 12, 31) +}); + +let x: Date[]; +let y: string[]; + +// Get all occurrence dates (Date instances): +x = rule.all(); + +// Get a slice: +x = rule.between(new Date(2012, 7, 1), new Date(2012, 8, 1)) + +// Get an iCalendar RRULE string representation: +// The output can be used with RRule.fromString(). +y.push(rule.toString()); + +// Get a human-friendly text representation: +// The output can be used with RRule.fromText(). +y.push(rule.toText()); + +// Get full a string representation of all options, +// including the default and inferred ones. +y.push(RRule.optionsToString(rule.options)) + + +// Cherry-pick only some options from an rrule: +y.push(RRule.optionsToString({ + freq: rule.options.freq, + dtstart: rule.options.dtstart, +})) + +rule = RRule.fromString("FREQ=WEEKLY;DTSTART=20120201T093000Z") + +// This is equivalent +rule = new RRule(RRule.parseString("FREQ=WEEKLY;DTSTART=20120201T093000Z")) + +var options = RRule.parseString('FREQ=DAILY;INTERVAL=6') +options.dtstart = new Date(2000, 1, 1) +rule = new RRule(options) + +rule = new RRule({ + freq: RRule.WEEKLY, + count: 23 +}) +y.push(rule.toText()) + +rule = RRule.fromText('every day for 3 times') + +options = RRule.parseText('every day for 3 times') +// {freq: 3, count: "3"} +options.dtstart = new Date(2000, 1, 1) +rule = new RRule(options) \ No newline at end of file diff --git a/rrule/rrule.d.ts b/rrule/rrule.d.ts new file mode 100644 index 0000000000..247defc92b --- /dev/null +++ b/rrule/rrule.d.ts @@ -0,0 +1,161 @@ +// Type definitions for rrule 2.1.0 +// Project: https://github.com/jkbrzt/rrule +// Definitions by: James Bracy +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare module 'rrule' { + export = RRule; +} + +declare namespace RRule { + + /** + * see + * The only required option is `freq`, one of RRule.YEARLY, RRule.MONTHLY, ... + */ + interface Options { + freq: RRule.Frequency; + dtstart?: Date; + interval?: number; + wkst?: number | Weekday + count?: number; + until?: Date; + bysetpos?: number; + bymonth?: number; + bymonthday?: number; + byyearday?: number; + byweekno?: number; + byweekday?: Weekday[]; + byhour?: number; + byminute?: number; + bysecond?: number; + } + + class Weekday { + constructor(weekday: number, n: number); + + nth(n: number): Weekday; + + equals(other: Weekday): boolean; + + toString(): string; + + getJsWeekday(): number; + } + +} + +declare class RRule { + + /** + * @param {Object?} options - see + * The only required option is `freq`, one of RRule.YEARLY, RRule.MONTHLY, ... + * @constructor + */ + constructor(options: RRule.Options, noCache?: boolean); + + options: RRule.Options; + + origOptions: RRule.Options; + + /** + * Returns the first recurrence after the given datetime instance. + * The inc keyword defines what happens if dt is an occurrence. + * With inc == True, if dt itself is an occurrence, it will be returned. + * @return Date or null + */ + after(dt: Date, inc?: boolean): Date; + + /** + * @param {Function} iterator - optional function that will be called + * on each date that is added. It can return false + * to stop the iteration. + * @return Array containing all recurrences. + */ + all(iterator?: (date: Date) => void): Date[]; + + /** + * Returns all the occurrences of the rrule between after and before. + * The inc keyword defines what happens if after and/or before are + * themselves occurrences. With inc == True, they will be included in the + * list, if they are found in the recurrence set. + * @return Array + */ + between(a: Date, b: Date, iterator?: (date: Date) => void): Date[]; + + /** + * Returns the last recurrence before the given datetime instance. + * The inc keyword defines what happens if dt is an occurrence. + * With inc == True, if dt itself is an occurrence, it will be returned. + * @return Date or null + */ + before(dt: Date, inc?: boolean): Date; + + /** + * Returns the number of recurrences in this set. It will have go trough + * the whole recurrence, if this hasn't been done before. + */ + count(): number; + + /** + * Converts the rrule into its string representation + * @see + * @return String + */ + toString(): string; + + /** + * Will convert all rules described in nlp:ToText + * to text. + */ + toText(gettext?: (str: string) => string, language?: any): string; + + isFullyConvertibleToText(): boolean; + + clone(): RRule; + +} + +declare namespace RRule { + + const FREQUENCIES: "YEARLY" | "MONTHLY" | "WEEKLY" | "DAILY" | "HOURLY" | "MINUTELY" | "SECONDLY"; + + enum Frequency { + YEARLY = 0, + MONTHLY = 1, + WEEKLY = 2, + DAILY = 3, + HOURLY = 4, + MINUTELY = 5, + SECONDLY = 6 + } + + const YEARLY: Frequency; + const MONTHLY: Frequency; + const WEEKLY: Frequency; + const DAILY: Frequency; + const HOURLY: Frequency; + const MINUTELY: Frequency; + const SECONDLY: Frequency; + + const MO: Weekday; + const TU: Weekday; + const WE: Weekday; + const TH: Weekday; + const FR: Weekday; + const SA: Weekday; + const SU: Weekday; + + const DEFAULT_OPTIONS: RRule.Options; + + function parseText(text: string, language?: any): RRule.Options; + + function fromText(text: string, language?: any): RRule; + + function optionsToString(options: RRule.Options): string; + + function parseString(rfcString: string): RRule.Options; + + function fromString(value: string): RRule; + +} diff --git a/ws/ws.d.ts b/ws/ws.d.ts index b7ce3bd829..a3c34fa54b 100644 --- a/ws/ws.d.ts +++ b/ws/ws.d.ts @@ -22,7 +22,7 @@ declare module "ws" { protocolVersion: string; url: string; supports: any; - upgradeReq: http.ServerRequest; + upgradeReq: http.IncomingMessage; protocol: string; CONNECTING: number; @@ -77,8 +77,8 @@ declare module "ws" { namespace WebSocket { - type VerifyClientCallbackSync = (info: {origin: string; secure: boolean; req: http.ServerRequest}) => boolean; - type VerifyClientCallbackAsync = (info: {origin: string; secure: boolean; req: http.ServerRequest} + type VerifyClientCallbackSync = (info: {origin: string; secure: boolean; req: http.IncomingMessage}) => boolean; + type VerifyClientCallbackAsync = (info: {origin: string; secure: boolean; req: http.IncomingMessage} , callback: (res: boolean) => void) => void; export interface IClientOptions { @@ -117,7 +117,7 @@ declare module "ws" { constructor(options?: IServerOptions, callback?: Function); close(cb?: () => {}): void; - handleUpgrade(request: http.ServerRequest, socket: net.Socket, + handleUpgrade(request: http.IncomingMessage, socket: net.Socket, upgradeHead: Buffer, callback: (client: WebSocket) => void): void; // Events diff --git a/xrm/xrm-7.1.d.ts b/xrm/xrm-7.1.d.ts new file mode 100644 index 0000000000..824c91ba0c --- /dev/null +++ b/xrm/xrm-7.1.d.ts @@ -0,0 +1,2590 @@ +// Type definitions for Microsoft Dynamics xRM API v7.1 +// Project: http://www.microsoft.com/en-us/download/details.aspx?id=44567 +// Definitions by: David Berry , Matt Ngan , Markus Mauch , Daryl LaBar +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare var Xrm: Xrm.XrmStatic; +declare function GetGlobalContext(): Xrm.Context; + +interface Window +{ + Xrm: Xrm.XrmStatic; + GetGlobalContext(): Xrm.Context; +} + +declare namespace Xrm +{ + /** + * Static xRM object. + */ + export interface XrmStatic + { + /** + * Provides a namespace container for the context, data and ui objects. + */ + Page: { + /** + * Provides methods to retrieve information specific to an organization, a user, or parameters passed to a page. + */ + context: Context; + + /** + * Provides methods to work with the form. + */ + data: Data; + + /** + * Contains properties and methods to retrieve information about the user interface as well as collections for several subcomponents of the form. + */ + ui: Ui; + + /** + * Gets all attributes. + * + * @return An array of attributes. + */ + getAttribute(): Page.Attribute[]; + + /** + * Gets an attribute matching attributeName. + * + * @tparam T An Attribute type. + * @param {string} attributeName Name of the attribute. + * + * @return The attribute. + */ + getAttribute( attributeName: string ): T; + + /** + * Gets an attribute matching attributeName. + * + * @param {string} attributeName Name of the attribute. + * + * @return The attribute. + */ + getAttribute( attributeName: string ): Page.Attribute; + + /** + * Gets an attribute by index. + * + * @param {number} index The attribute index. + * + * @return The attribute. + */ + getAttribute( index: number ): Page.Attribute; + + /** + * Gets an attribute. + * + * @param {Collection.MatchingDelegate{Attribute}} delegateFunction A matching delegate function + * + * @return An array of attribute. + */ + getAttribute( delegateFunction: Collection.MatchingDelegate ): Page.Attribute[]; + + /** + * Gets all controls. + * + * @return An array of controls. + */ + getControl(): Page.Control[]; + + /** + * Gets a control matching controlName. + * + * @tparam T A Control type + * @param {string} controlName Name of the control. + * + * @return The control. + */ + getControl( controlName: string ): T; + + /** + * Gets a control matching controlName. + * + * @param {string} controlName Name of the control. + * + * @return The control. + */ + getControl( controlName: string ): Page.Control; + + /** + * Gets a control by index. + * + * @param {number} index The control index. + * + * @return The control. + */ + getControl( index: number ): Page.Control; + + /** + * Gets a control. + * + * @param {Collection.MatchingDelegate{Control}} delegateFunction A matching delegate function. + * + * @return An array of control. + */ + getControl( delegateFunction: Collection.MatchingDelegate ): Page.Control[]; + } + + /** + * Provides a container for useful functions not directly related to the current page. + */ + Utility: { + /** + * Displays an alert dialog, with an "OK" button. + * + * @param {string} message The message. + * @param {function()} onCloseCallback The "OK" callback. + */ + alertDialog( message: string, onCloseCallback: () => void ): void; + + /** + * Displays a confirmation dialog, with "OK" and "Cancel" buttons. + * + * @param {string} message The message. + * @param {function()} yesCloseCallback The "OK" callback. + * @param {function()} noCloseCallback The "Cancel" callback. + */ + confirmDialog( message: string, yesCloseCallback: () => void, noCloseCallback: () => void ): void; + + /** + * Query if 'entityType' is an Activity entity. + * + * @param {string} entityType Type of the entity. + * + * @return true if the entity is an Activity, false if not. + */ + isActivityType( entityType: string ): boolean; + + /** + * Opens quick create. + * + * @param {Function} callback The function that will be called when a record is created. This + * function is passed a LookupValue object as a parameter. + * @param {string} entityLogicalName The logical name of the entity to create. + * @param {Page.LookupValue} createFromEntity (Optional) Designates a record that will provide default values + * based on mapped attribute values. + * @param {OpenParameters} parameters (Optional) A dictionary object that passes extra query string + * parameters to the form. Invalid query string parameters will cause an + * error. + */ + openQuickCreate( + callback: ( recordReference: Page.LookupValue ) => void, + entityLogicalName: string, + createFromEntity?: Page.LookupValue, + parameters?: Utility.OpenParameters ): void; + + /** + * Opens an entity form. + * + * @param {string} name The entity's logical name. + * @param {string} id (Optional) The unique identifier for the record. + * @param {FormParameters} parameters (Optional) A dictionary object that passes extra query string parameters to the form. + * @param {WindowOptions} windowOptions (Optional) Options for controlling the window. + */ + openEntityForm( name: string, id?: string, parameters?: Utility.FormOpenParameters, windowOptions?: Utility.WindowOptions ): void; + + /** + * Opens an HTML Web Resource in a new browser window. + * + * @param {string} webResourceName Name of the HTML web resource. Can be used to pass URL + * parameters. See Remarks. + * @param {string} webResourceData (Optional) Data to pass into the Web Resource's data parameter. + * It is advised to use encodeURIcomponent() to encode the value. + * @param {number} width (Optional) The width of the new window. + * @param {number} height (Optional) The height of the new window. + * + * @return A Window reference, containing the opened Web Resource. + * + * @remarks This function will not work with Microsoft Dynamics CRM for tablets. + * Valid WebResource URL Parameters: typename + * type + * id + * orgname + * userlcid + * data (identical to this method's webResourceData parameter) + * formid + */ + openWebResource( webResourceName: string, webResourceData?: string, width?: number, height?: number ): Window; + } + } + + /** + * Client Types for Xrm.Page.context.getClient(). + */ + export type Client = "Web" | "Outlook" | "Mobile"; + /** + * Client States for Xrm.Page.context.getClientState(). + */ + export type ClientState = "Online" | "Offline"; + /** + * Themes for Xrm.Page.context.getCurrentTheme(). + */ + export type Theme = "default" | "Office12Blue" | "Office14Silver"; + + /** + * Interface for the client context. + */ + export interface ClientContext + { + /** + * Returns a value to indicate which client the script is executing in. + * + * @return The client, as either "Web", "Outlook", or "Mobile" + */ + getClient(): Client; + + /** + * Gets client's current state. + * + * @return The client state, as either "Online" or "Offline" + */ + getClientState(): ClientState; + } + + /** + * Interface for the xRM application context. + */ + interface Context + { + /** + * The client's context instance. + */ + client: ClientContext; + + /** + * Gets client's base URL for Dynamics CRM + * + * @return The client's base URL + * @remarks For Dynamics CRM On-Premises: http(s)://server/org + * For Dynamics CRM Online: https://org.crm.dynamics.com + * For Dynamics CRM for Outlook (Offline): http://localhost:2525 + */ + getClientUrl(): string; + + /** + * Gets current styling theme. + * + * @return The name of the current theme, as either "default", "Office12Blue", or "Office14Silver" + * + * @remarks This function does not work with Dynamics CRM for tablets. + */ + getCurrentTheme(): Theme; + + /** + * Gets whether automatic save is enabled. + * + * @return true if automatic saving is enabled, otherwise false. + */ + getIsAutoSaveEnabled(): boolean; + + /** + * Gets organization's LCID (language code). + * + * @return The organization language code. + * + * @see {@link http://msdn.microsoft.com/en-us/library/ms912047(WinEmbedded.10).aspx|Microsoft Locale ID Values} + */ + getOrgLcid(): number; + + /** + * Gets organization's unique name. + * + * @return The organization's unique name. + * + * @remarks This value can be found on the Developer Resources page within Dynamics CRM + */ + getOrgUniqueName(): string; + + /** + * Gets query string parameters. + * + * @return The query string parameters, in a dictionary object representing name and value pairs. + */ + getQueryStringParameters(): { [index: string]: any }; + + /** + * Returns the difference between the local time and Coordinated Universal Time (UTC). + * + * @return The time zone offset, in minutes. + */ + getTimeZoneOffsetMinutes(): number; + + /** + * Gets user's unique identifier. + * + * @return The user's identifier in Guid format. + * + * @remarks Example: "{B05EC7CE-5D51-DF11-97E0-00155DB232D0}" + */ + getUserId(): string; + + /** + * Gets user's LCID (language code). + * + * @return The user's language code. + * + * @see {@link http://msdn.microsoft.com/en-us/library/ms912047(WinEmbedded.10).aspx|Microsoft Locale ID Values} + */ + getUserLcid(): number; + + /** + * Gets the name of the current user. + * + * @return The user's name. + */ + getUserName(): string; + + /** + * Gets all user security roles. + * + * @return An array of user role identifiers, in Guid format. + * + * @remarks Example: ["cf4cc7ce-5d51-df11-97e0-00155db232d0"] + */ + getUserRoles(): string[]; + + /** + * Prefixes the current organization's unique name to a string; typically a URL path. + * + * @param {string} sPath Local pathname of the resource. + * + * @return A path string with the organization name. + * + * @remarks Format: "/"+ OrgName + sPath + */ + prependOrgName( sPath: string ): string; + } + + /** + * Interface for the Xrm.Page.data object. + */ + export interface Data + { + /** + * Asynchronously refreshes data on the form, without reloading the page. + * + * @param {boolean} save true to save the record, after the refresh. + * + * @return An Async.XrmPromise. + */ + refresh( save: boolean ): Async.XrmPromise; + + /** + * Asynchronously saves the record. + * + * @return An Async.XrmPromise. + */ + save(): Async.XrmPromise; + + /** + * The record context of the form. + */ + entity: Page.Entity; + + /** + * The process API for Xrm.Page.data. + * + * @remarks This member may be undefined when Process Flows are not used by the current entity. + */ + process: Page.data.ProcessManager; + } + + /** + * Interface for the Xrm.Page.ui object. + */ + export interface Ui + { + /** + * Clears the form notification described by uniqueId. + * + * @param {string} uniqueId Unique identifier. + * + * @return true if it succeeds, otherwise false. + */ + clearFormNotification( uniqueId: string ): boolean; + + /** + * Closes the form. + */ + close(): void; + + /** + * Gets form type. + * + * @return The form type. + * + * @remarks Values returned are: 0 Undefined + * 1 Create + * 2 Update + * 3 Read Only + * 4 Disabled + * 6 Bulk Edit + * Deprecated values are 5 (Quick Create), and 11 (Read Optimized) + */ + getFormType(): XrmEnum.FormType; + + /** + * Gets view port height. + * + * @return The view port height, in pixels. + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + getViewPortHeight(): number; + + /** + * Gets view port width. + * + * @return The view port width, in pixels. + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + getViewPortWidth(): number; + + /** + * Re-evaluates the ribbon's configured EnableRules + * + * @remarks This method does not work with Microsoft Dynamics CRM for tablets. + */ + refreshRibbon(): void; + + setFormNotification(message: string, level: Page.ui.FormNotificationLevel | string, uniqueId: string ): boolean; + + process: Page.data.ProcessManager; + + /** + * A reference to the collection of controls on the form. + */ + controls: Collection.ItemCollection; + + /** + * The form selector API. + * + * @remarks This API does not exist with Microsoft Dynamics CRM for tablets. + */ + formSelector: Page.FormSelector; + + /** + * The navigation API. + * + * @remarks This API does not exist with Microsoft Dynamics CRM for tablets. + */ + navigation: Page.Navigation; + + /** + * A reference to the collection of tabs on the form. + */ + tabs: Collection.ItemCollection; + } + + /** + * A definition module for asynchronous interface declarations. + */ + export module Async + { + /** + * Called when the operation is successful. + */ + export type SuccessCallbackDelegate = () => void; + + /** + * Called when the operation fails. + * + * @param {number} errorCode The error code. + * @param {string} message The message. + */ + export type ErrorCallbackDelegate = ( errorCode: number, message: string ) => void; + + /** + * Interface for Xrm.Page.data promises. + */ + export interface XrmPromise + { + /** + * A basic 'then' promise. + * + * @param {SuccessCallbackDelegate} successCallback The success callback. + * @param {ErrorCallbackDelegate} errorCallback The error callback. + */ + then( successCallback: SuccessCallbackDelegate, errorCallback: ErrorCallbackDelegate ): void; + } + } + + /** + * A definition module for collection interface declarations. + */ + export module Collection + { + /** + * Interface for a matching delegate. + * + * @tparam T Generic type parameter. + */ + export interface MatchingDelegate + { + /** + * Called for each item in an array + * + * @param {T} item The item. + * @param {number} index Zero-based index of the item array. + * + * @return true if the item matches, false if it does not. + */ + ( item: T, index?: number ): boolean; + } + + /** + * Interface for iterative delegate. + * + * @tparam T Generic type parameter. + */ + export interface IterativeDelegate + { + /** + * Called for each item in an array + * + * @param {T} item The item. + * @param {number} index Zero-based index of the item array. + */ + ( item: T, index?: number ): void; + } + + /** + * Interface for an item collection. + * + * @tparam T Generic type parameter. + */ + export interface ItemCollection + { + /** + * Applies an operation to all items in this collection. + * + * @param {IterativeDelegate{T}} delegate An iterative delegate function + */ + forEach( delegate: IterativeDelegate ): void; + + /** + * Gets. + * + * @param {MatchingDelegate{T}} delegate A matching delegate function + * + * @return A T[] whose members have been validated by delegate. + */ + get( delegate: MatchingDelegate ): T[]; + + /** + * Gets the item given by the index. + * + * @param {number} itemNumber The item number to get. + * + * @return The T in the itemNumber-th place. + */ + get( itemNumber: number ): T; + + /** + * Gets the item given by the key. + * + * @param {string} itemName The item name to get. + * + * @return The T matching the key itemName. + * + * @see {@link Xrm.Page.Control.getName()} for Control-naming schemes. + */ + get( itemName: string ): T; + + /** + * Gets the entire array of T. + * + * @return A T[]. + */ + get(): T[]; + + /** + * Gets the length of the collection. + * + * @return The length. + */ + getLength(): number; + } + } + + /** + * The Xrm.Page API + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328255.aspx|Documentation} for details. + */ + export module Page + { + /** + * Requirement Level for Xrm.Page.Attribute.getRequiredLevel() and Xrm.Page.Attribute.setRequiredLevel(). + */ + export type RequirementLevel = "none" | "recommended" | "required"; + /** + * Save Modes for Xrm.Page.Entity.save(). + */ + export type SaveMode = "saveandclose" | "saveandnew"; + /** + * Status for Xrm.Page.Stage.getStatus(). + */ + export type Status = "active" | "inactive"; + /** + * Submit Mode for Xrm.Page.Attribute.getSubmitMode() and Xrm.Page.Attribute.setSubmitMode(). + */ + export type SubmitMode = "always" | "dirty" | "never"; + + /** + * Interface for a CRM Business Process Flow instance. + */ + export interface Process + { + /** + * Returns the unique identifier of the process. + * + * @return The identifier for this process, in GUID format. + * + * @remarks Example: "{825CB223-A651-DF11-AA8B-00155DBA3804}". + */ + getId(): string; + + /** + * Returns the name of the process. + * + * @return The name. + */ + getName(): string; + + /** + * Returns an collection of stages in the process. + * + * @return The stages. + */ + getStages(): Collection.ItemCollection; + + /** + * Returns a boolean value to indicate if the process is rendered. + * + * @return true if the process is rendered, false if not. + */ + isRendered(): boolean; + } + + /** + * Interface for CRM Business Process Flow stages. + */ + export interface Stage + { + /** + * Returns an object with a getValue method which will return the integer value of the business process flow + * category. + * + * @return The stage category. + */ + getCategory(): { getValue(): XrmEnum.StageCategory }; + + /** + * Returns the logical name of the entity associated with the stage. + * + * @return The entity name. + */ + getEntityName(): string; + + /** + * Returns the unique identifier of the stage. + * + * @return The identifier of the Stage, in GUID format. + * + * @remarks Example: "{825CB223-A651-DF11-AA8B-00155DBA3804}". + */ + getId(): string; + + /** + * Returns the name of the stage. + * + * @return The name. + */ + getName(): string; + + /** + * Returns the status of the stage. + * + * @return The status. + * + * @remarks This method will return either "active" or "inactive". + */ + getStatus(): Status; + + /** + * Returns a collection of steps in the stage. + * + * @return An array of Step. + */ + getSteps(): Step[]; + } + + export interface Step + { + /** + * Returns the logical name of the attribute associated to the step. + * + * @return The attribute. + * + * @remarks Some steps don’t contain an attribute value. + */ + getAttribute(): string; + + /** + * Returns the name of the step. + * + * @return The name. + */ + getName(): string; + + /** + * Returns whether the step is required in the business process flow. + * + * @return true if required, false if not. + * + * @remarks Returns true if the step is marked as required in the Business Process Flow editor; otherwise, false. + * There is no connection between this value and the values you can change in the Xrm.Page.data.entity + * attribute RequiredLevel methods. + */ + isRequired(): boolean; + } + + /** + * Interface for the event context. + */ + export interface EventContext + { + /** + * Gets the Xrm context. + * + * @return The Xrm context. + */ + getContext(): Context; + + /** + * Gets the handler's depth, which is the order in which the handler is executed. + * + * @return The depth, a 0-based index. + */ + getDepth(): number; + + /** + * Gets save-event arguments. + * + * @return The event arguments. + * + * @remarks Returns null for all but the "save" event. + */ + getEventArgs(): SaveEventArguments; + + /** + * Gets a reference to the object for which event occurred. + * + * @return The event source. + */ + getEventSource(): Attribute | Control | Entity; + + /** + * Gets the shared variable with the specified key. + * + * @tparam T Generic type parameter. + * @param {string} key The key. + * + * @return The shared variable. + * + * @remarks Used to pass values between handlers of an event. + */ + getSharedVariable( key: string ): T; + + /** + * Sets a shared variable. + * + * @tparam T Generic type parameter. + * @param {string} key The key. + * @param {T} value The value. + * + * @remarks Used to pass values between handlers of an event. + */ + setSharedVariable( key: string, value: T ): void; + } + + /** + * Interface for a context-sensitive handler. + */ + export interface ContextSensitiveHandler + { + /** + * @param {EventContext} context The context. + */ + ( context?: EventContext ): void; + } + + /** + * Base interface for UI elements. + */ + export interface UiElement + { + /** + * Gets the label. + * + * @return The label. + */ + getLabel(): string; + + /** + * Gets the visibility state. + * + * @return true if the tab is visible, otherwise false. + */ + getVisible(): boolean; + + /** + * Sets the label. + * + * @param {string} label The label. + */ + setLabel( label: string ): void; + + /** + * Sets the visibility state. + * + * @param {boolean} visible true to show, false to hide. + */ + setVisible( visible: boolean ): void; + } + + /** + * Interface for focusable UI elements. + */ + export interface UiFocusable + { + /** + * Sets focus on the element. + */ + setFocus(): void; + } + + /** + * Interface for a Lookup value. + */ + export interface LookupValue + { + /** + * The identifier. + */ + id: string; + + /** + * The name + */ + name?: string; + + /** + * Type of the entity. + */ + entityType: string; + } + + /** + * Interface for an OptionSet value. + */ + export interface OptionSetValue + { + /** + * The label text. + */ + text: string; + + /** + * The value, as a number + */ + value: number; + } + + /** + * Interface for a privilege. + */ + export interface Privilege + { + /** + * true if the user can read. + */ + canRead: boolean; + + /** + * true if the user can update. + */ + canUpdate: boolean; + + /** + * true if the user can create. + */ + canCreate: boolean; + } + + /** + * Interface for an Entity attribute. + */ + export interface Attribute + { + /** + * Adds a handler to be called when the attribute's value is changed. + * + * @param {ContextSensitiveHandler} handler The function reference. + */ + addOnChange( handler: ContextSensitiveHandler ): void; + + /** + * Fire all "on change" event handlers. + */ + fireOnChange(): void; + + /** + * Gets attribute type. + * + * @return The attribute's type name. + * + * @remarks Values returned are: boolean + * datetime + * decimal + * double + * integer + * lookup + * memo + * money + * optionset + * string + */ + getAttributeType(): string; + + /** + * Gets the attribute format. + * + * @return The format of the attribute. + * + * @see {@link getAttributeType()} + * + * @remarks Values returned are: date (datetime) + * datetime (datetime) + * duration (integer) + * email (string) + * language (optionset) + * none (integer) + * phone (string) + * text (string) + * textarea (string) + * tickersymbol (string) + * timezone (optionset) + * url (string) + */ + getFormat(): string; + + /** + * Gets a boolean value indicating whether this Attribute has unsaved changes. + * + * @return true if there are unsaved changes, otherwise false. + */ + getIsDirty(): boolean; + + /** + * Gets the logical name of the attribute. + * + * @return The logical name. + */ + getName(): string; + + /** + * Gets a reference to the record context of this attribute. + * + * @return The parent record context. + */ + getParent(): Entity; + + /** + * Gets the current level of requirement for the attribute. + * + * @return The required level, as either "none", "required", or "recommended" + */ + getRequiredLevel(): RequirementLevel; + + /** + * Gets current submit mode for the attribute. + * + * @return The submit mode, as either "always", "never", or "dirty" + * + * @remarks The default value is "dirty" + */ + getSubmitMode(): SubmitMode; + + /** + * Gets the current user's privileges for the attribute. + * + * @return The user privileges. + */ + getUserPrivilege(): Privilege; + + /** + * Removes the handler from the "on change" event. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + removeOnChange( handler: ContextSensitiveHandler ): void; + + /** + * Sets the required level. + * + * @param {string} requirementLevel The requirement level, as either "none", "required", or "recommended" + */ + setRequiredLevel(requirementLevel: RequirementLevel | string): void; + + /** + * Sets the submit mode. + * + * @param {string} submitMode The submit mode, as either "always", "never", or "dirty". + * + * @remarks The default value is "dirty" + */ + setSubmitMode(submitMode: SubmitMode | string): void; + + /** + * A collection of all the controls on the form that interface with this attribute. + */ + controls: Collection.ItemCollection; + } + + /** + * Interface for a Number attribute. + * + * @sa Attribute + */ + export interface NumberAttribute extends Attribute + { + /** + * Gets the maximum value allowed. + * + * @return The maximum value allowed. + */ + getMax(): number; + + /** + * Gets the minimum value allowed. + * + * @return The minimum value allowed. + */ + getMin(): number; + + /** + * Gets the attribute's configured precision. + * + * @return The total number of allowed decimal places. + */ + getPrecision(): number; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): number; + + /** + * Sets the value. + * + * @param {number} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: number ): void; + } + + /** + * Interface for a String attribute. + * + * @sa Attribute + */ + export interface StringAttribute extends Attribute + { + /** + * Gets maximum length allowed. + * + * @return The maximum length allowed. + * + * @remarks The email form's "Description" attribute does not have the this method. + */ + getMaxLength(): number; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): string; + + /** + * Sets the value. + * + * @param {string} value The value. + * + * @remarks A String field with the {@link Attribute.getFormat|email} format enforces email + * address formatting. Attributes on Quick Create Forms will not save values set + * with this method. + */ + setValue( value: string ): void; + } + + /** + * Common interface for enumeration attributes (OptionSet and Boolean). + * + * @sa Attribute + */ + export interface EnumAttribute extends Attribute + { + /** + * Gets the initial value of the attribute. + * + * @return The initial value. + * @remarks Valid for optionset and boolean attribute types + */ + getInitialValue(): number | boolean; + } + + /** + * Interface for a Boolean attribute. + * + * @sa EnumAttribute + */ + export interface BooleanAttribute extends EnumAttribute + { + /** + * Gets the value. + * + * @return true if it succeeds, false if it fails. + */ + getValue(): boolean; + + /** + * Sets the value. + * + * @param {boolean} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: boolean ): void; + } + + /** + * Interface for a Date attribute. + * + * @sa Attribute + */ + export interface DateAttribute extends Attribute + { + /** + * Gets the value. + * + * @return The value. + */ + getValue(): Date; + + /** + * Sets the value. + * + * @param {Date} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: Date ): void; + } + + /** + * Interface an OptionSet attribute. + * + * @sa EnumAttribute + */ + export interface OptionSetAttribute extends EnumAttribute + { + /** + * Gets the option matching a value. + * + * @param {number} value The enumeration value of the option desired. + * + * @return The option. + */ + getOption( value: number ): OptionSetValue; + + /** + * Gets the option matching a label. + * + * @param {string} label The label of the option desired. + * + * @return The option. + */ + getOption( label: string ): OptionSetValue; + + /** + * Gets all of the options. + * + * @return An array of options. + */ + getOptions(): OptionSetValue[]; + + /** + * Gets selected option. + * + * @return The selected option. + */ + getSelectedOption(): OptionSetValue; + + /** + * Gets the label of the currently selected option. + * + * @return The current value's label. + */ + getText(): string; + + /** + * Gets the value. + * + * @return The value. + */ + getValue(): number; + + /** + * Sets the value. + * + * @param {number} value The value. + * + * @remarks The getOptions() method returns option values as strings. You must use parseInt + * to convert them to numbers before you can use those values to set the value of an + * OptionSet attribute. Attributes on Quick Create Forms will not save values set + * with this method. + */ + setValue( value: number ): void; + } + + /** + * Interface a Lookup attribute. + * + * @sa Attribute + */ + export interface LookupAttribute extends Attribute + { + /** + * Gets a boolean value indicating whether the Lookup is a multi-value PartyList. + * + * @return true the attribute is a PartyList, otherwise false. + */ + getIsPartyList(): boolean; + + /** + * Gets the value. + * + * @return An array of LookupValue. + */ + getValue(): LookupValue[]; + + /** + * Sets the value. + * + * @param {LookupValue[]} value The value. + * + * @remarks Attributes on Quick Create Forms will not save values set with this method. + */ + setValue( value: LookupValue[] ): void; + } + + /** + * Interface for the form's record context, Xrm.Page.data.entity + */ + export interface Entity + { + /** + * Adds a handler to be called when the record is saved. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + addOnSave( handler: ContextSensitiveHandler ): void; + + /** + * Gets an serialized-XML string representing data that will be passed to the server upon saving + * the record. + * + * @return The XML in string format. + * + * @remarks This function does not work with Microsoft Dynamics CRM for tablets. Example: + * "Contoso55555425 + * 555-1234". + */ + getDataXml(): string; + + /** + * Gets entity's logical name. + * + * @return The logical name. + */ + getEntityName(): string; + + /** + * Gets the record's unique identifier. + * + * @return The identifier, in Guid format. + * + * @remarks Example: "{825CB223-A651-DF11-AA8B-00155DBA3804}". + */ + getId(): string; + + /** + * Gets a boolean value indicating whether the record has unsaved changes. + * + * @return true if there are unsaved changes, otherwise false. + */ + getIsDirty(): boolean; + + /** + * Gets the record's primary attribute value. + * + * @return The primary attribute value. + * + * @remarks The value for this attribute is used when links to the record are displayed. + */ + getPrimaryAttributeValue(): string; + + /** + * Removes the handler from the "on save" event. + * + * @param {ContextSensitiveHandler} handler The handler. + */ + removeOnSave( handler: ContextSensitiveHandler ): void; + + /** + * Saves the record. + * + * @remarks When using quick create forms in the web application the saveandnew option is not + * applied. It will always work as if saveandclose were used. Quick create forms in + * Microsoft Dynamics CRM for tablets will apply the saveandnew behavior. + */ + save(): void; + + /** + * Saves the record with the given save mode. + * + * @param {string} saveMode (Optional) the save mode to save, as either "saveandclose" or + * "saveandnew". + */ + save( saveMode: SaveMode | string): void; + + /** + * The collection of attributes for the record. + */ + attributes: Collection.ItemCollection; + } + + /** + * Interface for save event arguments. + */ + export interface SaveEventArguments + { + /** + * Gets save mode, as an integer. + * + * @return The save mode. + * @remarks Values returned are: 1 Save + * 2 Save and Close + * 59 Save and New + * 70 AutoSave (Where enabled; can be used with an OnSave handler + * to conditionally disable auto-saving) + * 58 Save as Completed (Activities) + * 5 Deactivate + * 6 Reactivate + * 47 Assign (All user- or team-owned entities) + * 7 Send (Email) + * 16 Qualify (Lead) + * 15 Disqualify (Lead) + */ + getSaveMode(): XrmEnum.SaveMode; + + /** + * Returns a boolean value to indicate if the record's save has been prevented. + * + * @return true if saving is prevented, otherwise false. + */ + isDefaultPrevented(): boolean; + + /** + * Prevents the save operation from being submitted to the server. + * @remarks All remaining "on save" handlers will continue execution. + */ + preventDefault(): void; + } + + /** + * Module for the Xrm.Page.data API. + */ + export module data + { + /** + * Interface for the Xrm.Page.data.process API. + */ + export interface ProcessManager + { + /** + * Returns a Process object representing the active process. + * + * @return current active process. + */ + getActiveProcess(): Process; + + /** + * Set a Process as the active process. + * + * @param {string} processId The Id of the process to make the active process. + * @param {function} callbackFunction (Optional) a function to call when the operation is complete. + */ + setActiveProcess( processId: string, callbackFunction?: ProcessCallbackDelegate ): void; + + /** + * Returns a Stage object representing the active stage. + * + * @return current active stage. + */ + getActiveStage(): Stage; + + /** + * Set a stage as the active stage. + * + * @param {string} stageId the Id of the stage to make the active stage. + * @param {function} callbackFunction (Optional) a function to call when the operation is complete. + */ + setActiveStage( stageId: string, callbackFunction?: ProcessCallbackDelegate ): void; + + /** + * Use this method to get a collection of stages currently in the active path with methods to interact with the + * stages displayed in the business process flow control. The active path represents stages currently rendered in + * the process control based on the branching rules and current data in the record. + * + * @return A collection of all completed stages, the currently active stage, and the predicted set of future stages + * based on satisfied conditions in the branching rule. This may be a subset of the stages returned with + * Xrm.Page.data.process.getActiveProcess because it will only include those stages which represent a valid + * transition from the current stage based on branching that has occurred in the process. + */ + getActivePath(): Collection.ItemCollection; + + /** + * Use this method to asynchronously retrieve the enabled business process flows that the user can switch to for an + * entity. + * + * @param {Function} callbackFunction The callback function must accept a parameter that contains an object with + * dictionary properties where the name of the property is the Id of the + * business process flow and the value of the property is the name of the + * business process flow. + * + * The enabled processes are filtered according to the user’s privileges. The + * list of enabled processes is the same ones a user can see in the UI if they + * want to change the process manually. + */ + getEnabledProcesses( callbackFunction: ( enabledProcesses: ProcessDictionary ) => void ): void; + + /** + * Use this method to get the currently selected stage. + * + * @return The currently selected stage. + */ + getSelectedStage(): Stage; + + /** + * Use this to add a function as an event handler for the OnStageChange event so that it will be called when the + * business process flow stage changes. + * @param {ContextSensitiveHandler} handler The function will be added to the bottom of the event + * handler pipeline. The execution context is automatically + * set to be the first parameter passed to the event handler. + * + * Use a reference to a named function rather than an + * anonymous function if you may later want to remove the + * event handler. + */ + addOnStageChange( handler: ContextSensitiveHandler ): void; + + /** + * Use this to add a function as an event handler for the OnStageSelected event so that it will be called + * when a business process flow stage is selected. + * + * @param {ContextSensitiveHandler} handler The function will be added to the bottom of the event + * handler pipeline. The execution context is automatically + * set to be the first parameter passed to the event handler. + * + * Use a reference to a named function rather than an + * anonymous function if you may later want to remove the + * event handler. + */ + addOnStageSelected(handler: ContextSensitiveHandler): void; + + /** + * Use this to remove a function as an event handler for the OnStageChange event. + * + * @param {ContextSensitiveHandler} handler If an anonymous function is set using the addOnStageChange method it + * cannot be removed using this method. + */ + removeOnStageChange(handler: ContextSensitiveHandler): void; + + /** + * Use this to remove a function as an event handler for the OnStageChange event. + * + * @param {ContextSensitiveHandler} handler If an anonymous function is set using the addOnStageChange method it + * cannot be removed using this method. + */ + removeOnStageSelected( handler: ContextSensitiveHandler ): void; + + /** + * Progresses to the next stage. + * + * @param {ProcessCallbackDelegate} callbackFunction (Optional) A function to call when the operation is + * complete. + */ + moveNext( callbackFunction?: ProcessCallbackDelegate ): void; + + /** + * Moves to the previous stage. + * + * @param {ProcessCallbackDelegate} callbackFunction (Optional) A function to call when the operation is + * complete. + */ + movePrevious( callbackFunction?: ProcessCallbackDelegate ): void; + } + + /** + * Called when process change methods have completed. + * + * @param {string} status The result of the process change operation. + * @remarks Values returned are: success (The operation succeeded.) + * crossEntity (The previous stage is for a different entity.) + * beginning (The active stage is the first stage of the active path.) + * invalid (The operation failed because the selected stage isn’t the same + * as the active stage.) + * unreachable (The stage exists on a different path.) + */ + export type ProcessCallbackDelegate = ( status: string ) => void; + + /** + * Represents a key-value pair, where the key is the Process Flow's ID, and the value is the name thereof. + */ + export type ProcessDictionary = { [index: string]: string }; + } + + /** + * Interface for Xrm.Page.ui controls. + * + * @sa UiElement + */ + export interface Control extends UiElement, UiFocusable + { + /** + * Clears the notification identified by uniqueId. + * + * @param {string} uniqueId (Optional) Unique identifier. + * + * @return true if it succeeds, false if it fails. + * + * @remarks If the uniqueId parameter is not used, the current notification shown will be removed. + */ + clearNotification( uniqueId?: string ): boolean; + + /** + * Gets the control's type. + * + * @return The control type. + * @remarks Values returned are: standard + * iframe + * lookup + * optionset + * subgrid + * webresource + * notes + * timercontrol + * kbsearch (CRM Online Only, use parature.d.ts) + */ + getControlType(): string; + + /** + * Gets a boolean value, indicating whether the control is disabled. + * + * @return true if it is disabled, otherwise false. + */ + getDisabled(): boolean; + + /** + * Gets the name of the control on the form. + * + * @return The name of the control. + * + * @remarks The name assigned to a control is not determined until the form loads. Changes to + * the form may change the name assigned to a given control. + * When you use the control getName method the name of the first control will be the + * same as the name of the attribute. The second instance of a control for that + * attribute will be "1". The pattern +N + * will continue for each additional control added to the form for a specific + * attribute. When a form displays a business process flow control in the header, + * additional controls will be added for each attribute that is displayed in the + * business process flow. These controls have a unique name like the following: + * header_process_. + */ + getName(): string; + + /** + * Gets a reference to the Section parent of the control. + * + * @return The parent Section. + */ + getParent(): Section; + + /** + * Sets the state of the control to either enabled, or disabled. + * + * @param {boolean} disabled true to disable, false to enable. + */ + setDisabled( disabled: boolean ): void; + + /** + * Sets a control-local notification message. + * + * @param {string} message The message. + * @param {string} uniqueId Unique identifier. + * + * @return true if it succeeds, false if it fails. + * + * @remarks When this method is used on Microsoft Dynamics CRM for tablets a red "X" icon + * appears next to the control. Tapping on the icon will display the message. + */ + setNotification( message: string, uniqueId: string ): boolean; + } + + /** + * Interface for a standard control. + * + * @sa Control + */ + export interface StandardControl extends Control + { + /** + * Gets the control's bound attribute. + * + * @tparam T An Attribute type. + * + * @return The attribute. + */ + getAttribute(): T; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): Attribute; + } + + /** + * Interface for a Date control. + * + * @sa StandardControl + */ + export interface DateControl extends StandardControl + { + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): DateAttribute; + + /** + * Gets the status of the time-of-day component of the Date control. + * + * @return true if the time is shown, otherwise false. + */ + getShowTime(): boolean; + + /** + * Sets the visibility of the time component of the Date control. + * + * @param {boolean} showTimeValue true to show, false to hide the time value. + */ + setShowTime( showTimeValue: boolean ): void; + } + + /** + * Interface for a Lookup control. + * + * @sa StandardControl + */ + export interface LookupControl extends StandardControl + { + /** + * Adds a handler to the "pre search" event of the Lookup control. + * + * @param {Function} handler The handler. + */ + addPreSearch( handler: ContextSensitiveHandler ): void; + + /** + * Adds an additional custom filter to the lookup, with the "AND" filter operator. + * Can only be used within a "pre search" event handler + * + * @sa addPreSearch + * + * @param {string} filter Specifies the filter, as a serialized FetchXML + * "filter" node. + * @param {string} entityLogicalName (Optional) The logical name of the entity. + * + * @remarks If entityLogicalName is not specified, the filter will be applied to all entities + * valid for the Lookup control. + * Example filter: + * + * + */ + addCustomFilter( filter: string, entityLogicalName?: string ): void; + + /** + * Adds a custom view for the Lookup dialog. + * + * @param {string} viewId Unique identifier for the view, in Guid format. + * @param {string} entityName Name of the entity. + * @param {string} viewDisplayName Name of the view to display. + * @param {string} fetchXml The FetchXML query for the view's contents, serialized as a string. + * @param {string} layoutXml The Layout XML, serialized as a string. + * @param {boolean} isDefault true, to treat this view as default. + * + * @remarks Cannot be used on "Owner" Lookup controls. + * The viewId is never saved to CRM, but must be unique across available views. Generating + * a new value can be accomplished with a {@link http://www.guidgen.com/|Guid generator}. + * Example viewId value: "{00000000-0000-0000-0000-000000000001}" + * Layout XML Reference: {@link http://msdn.microsoft.com/en-us/library/gg334522.aspx} + */ + addCustomView( viewId: string, entityName: string, viewDisplayName: string, fetchXml: string, layoutXml: string, isDefault: boolean ): void; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): LookupAttribute; + + /** + * Gets the unique identifier of the default view. + * + * @return The default view, in Guid format. + * + * @remarks Example: "{00000000-0000-0000-0000-000000000000}" + */ + getDefaultView(): string; + + /** + * Removes the handler from the "pre search" event of the Lookup control. + * + * @param {Function} handler The handler. + */ + removePreSearch( handler: () => void ): void; + + /** + * Sets the Lookup's default view. + * + * @param {string} viewGuid Unique identifier for the view. + * + * @remarks Example viewGuid value: "{00000000-0000-0000-0000-000000000000}" + */ + setDefaultView( viewGuid: string ): void; + } + + /** + * Interface for an OptionSet control. + * + * @sa StandardControl + */ + export interface OptionSetControl extends StandardControl + { + /** + * Adds an option. + * + * @param {OptionSetValue} option The option. + * @param {number} index (Optional) zero-based index of the option. + * + * @remarks This method does not check that the values within the options you add are valid. + * If index is not provided, the new option will be added to the end of the list. + */ + addOption( option: OptionSetValue, index?: number ): void; + + /** + * Clears all options. + */ + clearOptions(): void; + + /** + * Gets the control's bound attribute. + * + * @return The attribute. + */ + getAttribute(): OptionSetAttribute; + + /** + * Removes the option matching the value. + * + * @param {number} value The value. + */ + removeOption( value: number ): void; + } + + /** + * Interface for a CRM grid control. + * + * @sa Control + */ + export interface GridControl extends Control + { + /** + * Use this method to add event handlers to the GridControl's OnLoad event. + * + * @param {Function} handler The event handler. + */ + addOnLoad( handler: () => void ): void; + + /** + * This method returns context information about the GridControl. + * + * @return The context type. + */ + getContextType(): XrmEnum.GridControlContext; + + /** + * Use this method to get the logical name of the entity data displayed in the grid. + * + * @return The entity name. + */ + getEntityName(): string; + + /** + * Use this method to get access to the Grid available in the GridControl. + * + * @return The grid. + */ + getGrid(): ui.Grid; + + /** + * Use this method to get access to the ViewSelector available for the GridControl when it is configured to display views. + * + * @return The view selector. + */ + getViewSelector(): ui.ViewSelector; + + /** + * Refreshes the sub grid. + * + * @remarks Not available during the "on load" event of the form. + */ + refresh(): void; + + /** + * Use this method to remove event handlers from the GridControl's OnLoad event. + * + * @param {Function} handler The handler. + */ + removeOnLoad( handler: () => void ): void; + } + + /** + * Interface for a framed control, which is either a Web Resource or an Iframe. + * + * @sa Control + * + * @remarks An Iframe control provides additional methods, so use {@link IframeControl} where + * appropriate. Silverlight controls should use {@link SilverlightControl}. + */ + export interface FramedControl extends Control + { + /** + * Gets the DOM element containing the control. + * + * @return The container object. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getObject(): HTMLIFrameElement; + + /** + * Gets the URL value of the control. + * + * @return The source URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getSrc(): string; + + /** + * Sets the URL value of the control. + * + * @param {string} src The source URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + setSrc( src: string ): void; + } + + /** + * Interface for an Iframe control. + * + * @sa FramedControl + */ + export interface IframeControl extends FramedControl + { + /** + * Gets initial URL defined for the Iframe. + * + * @return The initial URL. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getInitialUrl(): string; + } + + /** + * Interface for a Silverlight control. + * + * @sa Control + */ + export interface SilverlightControl extends Control + { + /** + * Gets the query string value passed to Silverlight. + * + * @return The data. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getData(): string; + + /** + * Sets the query string value passed to Silverlight. + * + * @param {string} data The data. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + setData( data: string ): void; + + /** + * Gets the DOM element containing the control. + * + * @return The container object. + * + * @remarks Unavailable for Microsoft Dynamics CRM for tablets. + */ + getObject(): HTMLObjectElement; + } + + /** + * Interface for a form tab. + * + * @sa UiElement + * @sa UiFocusable + */ + export interface Tab extends UiElement, UiFocusable + { + /** + * Gets display state of the tab. + * + * @return The display state, as either "expanded" or "collapsed" + */ + getDisplayState(): ui.DisplayState; + + /** + * Gets the name of the tab. + * + * @return The name. + */ + getName(): string; + + /** + * Gets a reference to the Xrm.Page.ui parent of the tab. + * + * @return The parent. + */ + getParent(): Ui; + + /** + * Sets display state of the tab. + * + * @param {string} displayState Display state of the tab, as either "expanded" or "collapsed" + */ + setDisplayState(displayState: ui.DisplayState | string ): void; + + /** + * A reference to the collection of form sections within this tab. + */ + sections: Collection.ItemCollection
; + } + + /** + * Interface for a form section. + * + * @sa UiElement + */ + export interface Section extends UiElement + { + /** + * Gets the name of the section. + * + * @return The name. + */ + getName(): string; + + /** + * Gets a reference to the Xrm.Page.Tab parent of this item. + * + * @return The parent. + */ + getParent(): Tab; + + /** + * A reference to the collection of controls within this tab. + */ + controls: Collection.ItemCollection; + } + + /** + * Module for Xrm.Page.ui API. + */ + export module ui + { + /** + * Form Notification Levels for Xrm.Ui.setFormNotification(). + */ + export type FormNotificationLevel = "ERROR" | "INFO" | "WARNING"; + + /** + * Display States for Xrm.ui.ProcessMonitor.setDisplayState(). + */ + export type DisplayState = "collapsed" | "expanded"; + + /** + * Interface for Xrm.Page.ui.process API + */ + export interface ProcessManager + { + /** + * Sets display state of the process flow control. + * + * @param {string} displayState Display state of the process flow control, as either "expanded" or "collapsed" + */ + setDisplayState(displayState: ui.DisplayState ): void; + + /** + * Sets the visibility state. + * + * @param {boolean} visible true to show, false to hide. + */ + setVisible( visible: boolean ): void; + } + + /** + * Interface for a grid. Use Grid methods to access information about data in the grid. Grid is returned by the + * GridControl.getGrid method. + */ + export interface Grid + { + /** + * Returns a collection of every GridRow in the Grid. + * + * @return The rows. + */ + getRows(): Collection.ItemCollection; + + /** + * Returns a collection of every selected GridRow in the Grid. + * + * @return The selected rows. + */ + getSelectedRows(): Collection.ItemCollection; + + /** + * Returns the total number of records in the Grid. + * + * @return The total record count. + */ + getTotalRecordCount(): number; + } + + /** + * Interface for a grid row. Use the GridRow.getData method to access the GridRowData. A collection of GridRow is + * returned by Grid.getRows and Grid.getSelectedRows methods. + */ + export interface GridRow + { + /** + * Returns the GridRowData for the GridRow. + * + * @return The data. + */ + getData(): GridRowData; + } + + /** + * Interface for grid row data. Use the GridRowData.getEntity method to access the GridEntity. GridRowData is + * returned by the GridRow.getData method. + */ + export interface GridRowData + { + /** + * Returns the GridEntity for the GridRowData. + * + * @return The entity. + */ + getEntity(): GridEntity; + } + + /** + * Interface for a grid entity. Use the GridEntity methods to access data about the specific records in the rows. + * GridEntity is returned by the GridRowData.getEntity method. + */ + export interface GridEntity + { + /** + * Returns the logical name for the record in the row. + * + * @return The entity name. + */ + getEntityName(): string; + + /** + * Returns a LookupValue that references this record. + * + * @return The entity reference. + */ + getEntityReference(): LookupValue; + + /** + * Returns the id for the record in the row. + * + * @return The identifier of the GridEntity, in GUID format. + * + * @remarks Example return: "{00000000-0000-0000-0000-000000000000}" + */ + getId(): string; + + /** + * Returns the primary attribute value for the record in the row. (Commonly the name.) + * + * @return The primary attribute value. + */ + getPrimaryAttributeValue(): string; + } + + /** + * Interface for the view selector. Use the ViewSelector methods to get or set information about the view selector + * of the grid control. + */ + export interface ViewSelector + { + /** + * Use this method to get a reference to the current view. + * + * @return The current view. + */ + getCurrentView(): ViewSelectorItem; + + /** + * Use this method to determine whether the view selector is visible. + * + * @return true if visible, false if not. + */ + isVisible(): boolean; + + /** + * Use this method to set the current view. + * + * @param {ViewSelectorItem} viewSelectorItem The view selector item. + */ + setCurrentView( viewSelectorItem: ViewSelectorItem ): void; + } + + /** + * Interface for a view selector item. This object contains data that identifies a view. Use this as a parameter to + * the ViewSelector.setCurrentView method. + */ + export interface ViewSelectorItem + { + /** + * Returns a LookupValue that references this view. + * + * @return The entity reference. + */ + getEntityReference(): LookupValue; + } + } + + /** + * Interface for a navigation item. + * + * @sa UiElement + * @sa UiFocusable + */ + export interface NavigationItem extends UiElement, UiFocusable + { + /** + * Gets the name of the item. + * + * @return The identifier. + */ + getId(): string; + } + + /** + * Interface for Xrm.Page.ui.navigation. + */ + export interface Navigation + { + /** + * A reference to the collection of available navigation items. + */ + items: Collection.ItemCollection; + } + + /** + * Interface for an entity's form selector item. + */ + export interface FormItem + { + /** + * Gets the unique identifier of the form. + * + * @return The identifier, in Guid format. + */ + getId(): string; + + /** + * Gets the label for the form. + * + * @return The label. + */ + getLabel(): string; + + /** + * Navigates the user to this form. + */ + navigate(): void; + } + + /** + * Interface for the form selector API. + */ + export interface FormSelector + { + /** + * Gets current form. + * + * @return The current item. + * + * @remarks When only one form is available this method will return null. + */ + getCurrentItem(): FormItem; + + /** + * A reference to the collection of available forms. + */ + items: Collection.ItemCollection; + } + } + + /** + * An definition module for URL-based, CRM component parameters. + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export module Url + { + /** + * Command Bar Display options for Xrm.Url.FormOpenParameters.cmdbar, Xrm.Url.ViewOpenParameters.cmdbar, and Xrm.Utility.FormOpenParameters.cmdbar. + */ + export type CmdBarDisplay = "true" | "false"; + /** + * Navigation Bar Display options for Xrm.Url.FormOpenParameters.navbar, Xrm.Url.ViewOpenParameters.navbar, and Xrm.Utility.FormOpenParameters.navbar. + */ + export type NavBarDisplay = "entity" | "off" | "on"; + /** + * Report Open Action options for Xrm.Url.ReportOpenParameters.actions. + */ + export type ReportAction = "filter" | "run"; + + /** + * Interface for defining parameters on a request to open a form with main.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + * + * @remarks A member for "pagetype" is not provided. The value "entityrecord" is required in + * the URL, for forms. Example: "pagetype=entityrecord" + */ + export interface FormOpenParameters + { + /** + * The logical name of the entity. + */ + etn: string; + + /** + * Additional parameters can be provided to the request. This can only be used to provide + * default field values for the form, or pass data to custom parameters that have been + * customized for the form. See example below for setting the selected form. + * + * @remarks Example: encodeURIComponent( "formid={8c9f3e6f-7839-e211-831e-00155db7d98f}" ); + */ + extraqs?: string; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: CmdBarDisplay; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: NavBarDisplay; + } + + /** + * Interface for defining parameters on a request to open a view with main.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + * + * @remarks A member for "pagetype" is not provided. The value "entitylist" is required in + * the URL, for views. Example: "pagetype=entitylist" + */ + export interface ViewOpenParameters + { + /** + * The logical name of the entity. + */ + etn: string; + + /** + * The unique identifier of a view, in Guid format, which is valid for the entity described by + * {@link etn}. + */ + viewid: string; + + /** + * The type of view identified by {@link viewid}. + * + * @remarks Accepted values are: 1039 System View + * 4230 User View. + */ + viewtype: XrmEnum.ViewType; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: CmdBarDisplay; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: NavBarDisplay; + } + + /** + * Interface for defining parameters of a request to open a dialog with rundialog.aspx (as with + * window.open). Useful for parsing the keys and values into a string of the format: + * "&key=value". + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export interface DialogOpenParameters + { + /** + * The unique identifier of the dialog, in Guid format, which is valid for the entity described + * by: {@link EntityName} + */ + DialogId: string; + + /** + * The logical name of the entity. + */ + EntityName: string; + + /** + * The unique identifier for the targeted record. + */ + ObjectId: string; + } + + /** + * Interface for defining parameters of a request to open a report with viewer.apsx (as with + * window.open). Useful for parsing out the keys and values into a string of the format: + * "&key=value" + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328483.aspx} for details. + */ + export interface ReportOpenParameters + { + /** + * The action to perform, as either "run" or "filter". + * + * @remarks "run" Executes the report with default filters. + * "filter" Presents the user with the filter editor, and a "Run Report" button. + */ + action: ReportAction; + + /** + * The file name of the report. For out-of-box reports, this parameter enables context-sensitive + * help. + */ + helpID?: string; + + /** + * The unique identifier, held in the report's 'reportid' attribute, in Guid format. + */ + id: string; + } + } + + /** + * The Xrm.Utility API + * + * @see {@link http://msdn.microsoft.com/en-us/library/gg328255.aspx|Documentation} for details. + */ + export module Utility + { + export interface OpenParameters + { + /** + * Additional parameters can be provided to the request, by overloading + * this object with additional key and value pairs. This can only be used + * to provide default field values for the form, or pass data to custom + * parameters that have been customized for the form. + */ + [index: string]: string; + } + + /** + * Interface for defining parameters on a Xrm.Utility.openEntityForm() request. + */ + export interface FormOpenParameters extends OpenParameters + { + /** + * The identifier of the form to use, when several are available. + */ + formid: string; + + /** + * Controls whether the Navigation bar is displayed on the form. + * Accepted values are: "on" (The navigation bar is displayed.) + * "off" (The navigation bar is not displayed.) + * "entity" (On an entity form, only the navigation options for related + * entities are available.) + */ + navbar?: Url.NavBarDisplay; + + /** + * Controls whether the command bar is displayed. + * Accepted values are: "true" (The command bar is displayed.) + * "false" (The command bar is not displayed.) + */ + cmdbar?: Url.CmdBarDisplay; + } + + /** + * Interface for window options. + */ + export interface WindowOptions + { + /** + * Direct the form to open in a new window. + */ + openInNewWindow: boolean; + } + } +} + +declare namespace XrmEnum +{ + /** + * Enumeration of entity form states/types. + */ + export const enum FormType + { + Undefined = 0, + Create = 1, + Update = 2, + ReadOnly = 3, + Disabled = 4, + BulkEdit = 6 + } + + /** + * Enumeration of entity form save modes. + */ + export const enum SaveMode + { + Save = 1, + SaveAndClose = 2, + SaveAndNew = 59, + AutoSave = 70, + SaveAsCompleted = 58, + Deactivate = 5, + Reactivate = 6, + Assign = 47, + Send = 7, + Qualify = 16, + Disqualify = 15 + } + + /** + * Enumeration of stage categories. + */ + export const enum StageCategory + { + Qualify = 0, + Develop = 1, + Propose = 2, + Close = 3, + Identify = 4, + Research = 5, + Resolve = 6 + } + + /** + * Enumeration of grid control context resolutions. + */ + export const enum GridControlContext + { + Unknown = 0, + RibbonContextForm = 1, + RibbonContextListing = 2, + FormContextUnrelated = 3, + FormContextRelated = 4 + } + + /** + * An enumeration for view types. + */ + export const enum ViewType + { + SystemView = 1039, + UserView = 4230 + } +} \ No newline at end of file diff --git a/xrm/xrm-7.1.tests.ts b/xrm/xrm-7.1.tests.ts new file mode 100644 index 0000000000..f3f4576b02 --- /dev/null +++ b/xrm/xrm-7.1.tests.ts @@ -0,0 +1,137 @@ +/// +/// + +/// Demonstrate usage in the browser's window object + +window.Xrm.Utility.alertDialog( "message", () => {} ); +parent.Xrm.Page.context.getOrgLcid(); + +/// Demonstrate clientglobalcontext.d.ts + +function _getContext() +{ + var errorMessage = "Context is not available."; + if ( typeof GetGlobalContext != "undefined" ) + { return GetGlobalContext(); } + else + { + if ( typeof Xrm != "undefined" ) + { + return Xrm.Page.context; + } + else { throw new Error( errorMessage ); } + } +} + +var crmContext = _getContext(); + +/// Demonstrate iterator typing + +var grids = Xrm.Page.getControl(( control ) => +{ + return control.getControlType() === "subgrid"; +}); + +var selectedGridReferences: Xrm.Page.LookupValue[] = []; + +/// Demonstrate iterator typing with v7.1 additions + +grids.forEach(( gridControl: Xrm.Page.GridControl ) => +{ + gridControl.getGrid().getSelectedRows().forEach(( row ) => + { + selectedGridReferences.push( row.getData().getEntity().getEntityReference() ); + }) +}); + +/// Demonstrate generic overload vs typecast + +var lookupAttribute = Xrm.Page.getControl( "customerid" ); +var lookupAttribute2 = Xrm.Page.getControl( "customerid" ); + +/// Demonstrate ES6 String literal syntax + +lookupAttribute.addCustomFilter( ` + +`, "account" ); + +lookupAttribute.addPreSearch(() => { alert( "A search was performed." ); }); + +/// Demonstrate strong-typed attribute association with strong-typed control + +var lookupValues = lookupAttribute.getAttribute().getValue(); + +if ( lookupValues !== null ) + if ( !lookupValues[0].id || !lookupValues[0].entityType ) + throw new Error("Invalid value in Lookup control."); + +/// Demonstrate v7.0 BPF API + +if (Xrm.Page.data.process != null) + Xrm.Page.data.process.moveNext(( status ) => { alert( `Process moved forward with status: ${status}` ) }); + +/// Demonstrate v7.1 Quick Create form + +Xrm.Utility.openQuickCreate(( newRecord ) => { alert( `Newly created record Id: ${newRecord.id}` ); }, "account" ); + +/// Make all controls visible. + +Xrm.Page.ui.controls.forEach(( control ) => { control.setVisible( true ); }); + +/// Make all tabs and sections visible. + +Xrm.Page.ui.tabs.forEach(( tab ) => +{ + tab.setVisible( true ); + + tab.sections.forEach(( section ) => + { + section.setVisible( true ); + }); +}); + +/// Demonstrate OnSave event context. + +Xrm.Page.data.entity.addOnSave(( context ) => +{ + var eventArgs = context.getEventArgs(); + + if ( eventArgs.getSaveMode() === XrmEnum.SaveMode.AutoSave || eventArgs.getSaveMode() === XrmEnum.SaveMode.SaveAndClose ) + eventArgs.preventDefault(); +}); + +/// Demonstrate ES6 String literal with templates + +alert( `The current form type is: ${Xrm.Page.ui.getFormType() }` ); + +alert( `The current entity type is: ${Xrm.Page.data.entity.getEntityName() }` ); + +/// Demonstrate Optionset Value as int in Turbo Forms + +var optionSetAttribute = Xrm.Page.getAttribute( "statuscode" ); +const optionValue: number = optionSetAttribute.getOptions()[0].value; + +/// Demonstrate Control.setFocus(); + +optionSetAttribute.controls.get(0).setFocus(); + +/// Demonstrate setFormNotification + +var level: Xrm.Page.ui.FormNotificationLevel; +level = "ERROR"; +Xrm.Page.ui.setFormNotification("Test", level, "uniqueId"); + +/// Demonstrate Requirement Level and Submit Mode both via string parameters and String Literal Types + +let requirementLevel: Xrm.Page.RequirementLevel = "none"; +let requirementLevelString = "none"; +let submitMode: Xrm.Page.SubmitMode = "always"; +let submitModeString = "always"; + +let attribute = Xrm.Page.getAttribute("customerid"); +attribute.setSubmitMode(submitMode); +attribute.setSubmitMode(submitMode); +attribute.setRequiredLevel(requirementLevel); +attribute.setRequiredLevel(requirementLevelString); + + diff --git a/xrm/xrm-tests.ts b/xrm/xrm-tests.ts index 5cf69227ed..ac0f115154 100644 --- a/xrm/xrm-tests.ts +++ b/xrm/xrm-tests.ts @@ -133,3 +133,38 @@ attribute.setSubmitMode(submitMode); attribute.setSubmitMode(submitMode); attribute.setRequiredLevel(requirementLevel); attribute.setRequiredLevel(requirementLevelString); + +/// Demonstrate v8 AutoComplete + +let autoCompleteControl = Xrm.Page.getControl("name"); +var userInput = autoCompleteControl.getValue(); +const accountResult = { }; +const resultSet: Xrm.Page.AutoCompleteResultSet = { + results: new Array() as Xrm.Page.AutoCompleteResult[], + commands: { + id: "sp_commands", + label: "Learn More", + action() { + // Specify what you want to do when the user + // clicks the "Learn More" link at the bottom + // of the auto-completion list. + // For this sample, we are just opening a page + // that provides information on working with + // accounts in CRM. + window.open("http://www.microsoft.com/en-us/dynamics/crm-customer-center/create-or-edit-an-account.aspx"); + } + } as Xrm.Page.AutoCompleteCommand +}; +resultSet.results.push({ + id: 0, + fields: ["A. Datum Corporation"] +}); +autoCompleteControl.addOnKeyPress(() => { }); +autoCompleteControl.fireOnKeyPress(); +autoCompleteControl.removeOnKeyPress(() => {}); +autoCompleteControl.showAutoComplete(resultSet); +autoCompleteControl.hideAutoComplete(); + + + + diff --git a/xrm/xrm.d.ts b/xrm/xrm.d.ts index 986ce7e78a..11dd24c389 100644 --- a/xrm/xrm.d.ts +++ b/xrm/xrm.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Microsoft Dynamics xRM API v7.1 +// Type definitions for Microsoft Dynamics xRM API v8.0 // Project: http://www.microsoft.com/en-us/download/details.aspx?id=44567 // Definitions by: David Berry , Matt Ngan , Markus Mauch , Daryl LaBar // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -865,6 +865,66 @@ declare namespace Xrm setFocus(): void; } + /** + * Interface for Result value of AutoCompleteResultSet + */ + export interface AutoCompleteResult { + /** + * The Identifier + */ + id: string|number; + + /** + * Url of the icon to display + */ + icon?: string; + + /** + * Display value(s) for this auto-complete option + */ + fields: string[]; + } + + /** + * Interface for command of AutoCompleteResultSet. This is displayed at the bottom of the auto complete view + */ + export interface AutoCompleteCommand { + /** + * The Identifier + */ + id: string; + + /** + * Url of the icon to display + */ + icon?: string; + + /** + * Label to display at the bottom of the auto complete view + */ + label: string; + + /** + * Action to perform when user clicks on label + */ + action(): void; + } + + /** + * Interface for showAutoComplete argument + */ + export interface AutoCompleteResultSet { + /** + * Results to show + */ + results: AutoCompleteResult[]; + + /** + * Command to show/execute at the bottom of the results displayed + */ + commands?: AutoCompleteCommand; + } + /** * Interface for a Lookup value. */ @@ -1682,6 +1742,56 @@ declare namespace Xrm getAttribute(): Attribute; } + /** + * Interace for Auto Lookup Control + * This is not an Entity Lookup, but a control that supports AutoComplete/KeyPress Events (Text) + * NOTE * This interface is not supported for CRM mobile clients (phones or tablets) and the interactive service hub. It is only available for Updated entities. + * + * @sa StandardControl + */ + export interface AutoLookupControl extends StandardControl { + /** + * Use this to add a function as an event handler for the keypress event so that the function is called when you type a character in the specific text or number field. + * For a sample JavaScript code that uses the addOnKeyPress method to configure the auto-completion experience, see Sample: Auto-complete in CRM controls. + * + * @param {ContextSensitiveHandler} handler The function reference. + */ + addOnKeyPress(handler: ContextSensitiveHandler): void; + + /** + * Use this to manually fire an event handler that you created for a specific text or number field to be executed on the keypress event. + */ + fireOnKeyPress(): void; + + /** + * Gets the latest value in a control as the user types characters in a specific text or number field. + * This method helps you to build interactive experiences by validating data and alerting users as they type characters in a control. + * The getValue method is different from the attribute getValue method because the control method retrieves the value from the control + * as the user is typing in the control as opposed to the attribute getValue method that retrieves the value after the user commits (saves) the field. + */ + getValue(): string; + + /** + * Hides the auto-completion drop-down list configured for a specific text field + */ + hideAutoComplete(): void; + + /** + * Use this to remove an event handler for a text or number field that you added using addOnKeyPress. + * + * Remarks: If an anonymous function is set using addOnKeyPress, it can’t be removed using this method. + * @param {ContextSensitiveHandler} handler The function reference. + */ + removeOnKeyPress(handler: ContextSensitiveHandler): void; + + /** + * Shows upt to 10 matching strings in a drop-down list as users press keys to type charactrer in a specific text field. + * On selecting an item in the drop-down list, the value in the text field changes to the selected item, the drop-down list disappears, and the OnChange event for the text field is invoked + * @param resultSet + */ + showAutoComplete(resultSet: AutoCompleteResultSet): void; + } + /** * Interface for a Date control. *