From 9248fda26ca29dd975534fdcd4703cd4b638cb51 Mon Sep 17 00:00:00 2001 From: Saeed Tabrizi Date: Fri, 21 Jul 2017 00:54:17 +0430 Subject: [PATCH 001/710] fix string case in PropertyType - a minor patch --- types/orientjs/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/orientjs/index.d.ts b/types/orientjs/index.d.ts index 9be45a4fea..e57fc8d076 100644 --- a/types/orientjs/index.d.ts +++ b/types/orientjs/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/orientechnologies/orientjs // Definitions by: [Saeed Tabrizi] // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// Last Update : 19-7-2017 +// Last Update : 20-7-2017 // Compatible with Orientdb >= 2.2.15 and orientjs >= 2.2.x features . // Developed with love in www.nowcando.com // @@ -32,7 +32,7 @@ import Promise = require('bluebird'); * @description Official node.js driver for OrientDB. Fast, lightweight, uses the binary protocol. * * @author Saeed Tabrizi (saeed a_t nowcando.com) - * @version 3.0.0 + * @version 3.0.1 * */ @@ -44,7 +44,7 @@ declare function orientjs(config: orientjs.ServerConfig): orientjs.Server; declare namespace orientjs { type Version = number | string; type PropertyType = "Boolean" | "Integer" | "Short" | "Long" | - "Float" | "Double" | "DateTime" | "string" | "Binary" | + "Float" | "Double" | "DateTime" | "String" | "Binary" | "Embedded" | "EmbeddedList" | "EmbeddedSet" | "EmbeddedMap" | "Link" | "LinkList" | "LinkSet" | "LinkMap" | "Byte" | "Transient" | "Date" | "Custom" | "Decimal" | "LinkBag"; From d2d1346c31c6d6aa4abd1d37af5184e2f3c5db44 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20=C3=96llinger?= Date: Tue, 24 Apr 2018 14:16:16 +0200 Subject: [PATCH 002/710] add ReactCreatableSelectProps to our props --- types/react-virtualized-select/index.d.ts | 6 +++--- .../react-virtualized-select-tests.tsx | 12 +++++++++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/types/react-virtualized-select/index.d.ts b/types/react-virtualized-select/index.d.ts index 78454990f7..83c062eab7 100644 --- a/types/react-virtualized-select/index.d.ts +++ b/types/react-virtualized-select/index.d.ts @@ -5,7 +5,7 @@ // TypeScript Version: 2.6 import * as React from "react"; -import { ReactSelectProps, ReactAsyncSelectProps, LoadOptionsHandler, OptionValues } from "react-select"; +import { ReactSelectProps, ReactAsyncSelectProps, ReactCreatableSelectProps, LoadOptionsHandler, OptionValues } from "react-select"; import { ListProps } from "react-virtualized"; export interface VirtualizedOptionRenderOptions { @@ -29,8 +29,8 @@ export interface AdditionalVirtualizedSelectProps { selectComponent?: React.ComponentClass | React.StatelessComponent; } -type VirtualizedSelectProps = (ReactAsyncSelectProps & AdditionalVirtualizedSelectProps & { async: true }) | - ReactSelectProps & AdditionalVirtualizedSelectProps; +type VirtualizedSelectProps = (ReactCreatableSelectProps & ReactAsyncSelectProps & AdditionalVirtualizedSelectProps & { async: true }) | + ReactCreatableSelectProps & ReactSelectProps & AdditionalVirtualizedSelectProps; declare class VirtualizedSelect extends React.PureComponent> {} export default VirtualizedSelect; diff --git a/types/react-virtualized-select/react-virtualized-select-tests.tsx b/types/react-virtualized-select/react-virtualized-select-tests.tsx index 380828e864..2502c2f97d 100644 --- a/types/react-virtualized-select/react-virtualized-select-tests.tsx +++ b/types/react-virtualized-select/react-virtualized-select-tests.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Select from "react-select"; +import Select, * as ReactSelect from "react-select"; import VirtualizedSelect from "react-virtualized-select"; /*Example TValue.*/ @@ -11,6 +11,9 @@ interface Example { class ExampleSelectAsync extends VirtualizedSelect { } +class ExampleSelectCreatable extends VirtualizedSelect { +} +
{ maxHeight={0} optionHeight={0} optionRenderer={() =>
} - selectComponent={Select} - loadOptions={(input: string) => Promise.resolve([{name: 'Hi'}])} + selectComponent={Select} + loadOptions={(input: string) => Promise.resolve([{name: 'Hi'}])} + /> + arg.label.length > 1} />
; From af67f903d01e647b7608de8052fb14d591b6ec2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20=C3=96llinger?= Date: Wed, 25 Apr 2018 09:01:03 +0200 Subject: [PATCH 003/710] fix formatting issues --- .../react-virtualized-select-tests.tsx | 33 ++++++++++--------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/types/react-virtualized-select/react-virtualized-select-tests.tsx b/types/react-virtualized-select/react-virtualized-select-tests.tsx index 2502c2f97d..2ed0579386 100644 --- a/types/react-virtualized-select/react-virtualized-select-tests.tsx +++ b/types/react-virtualized-select/react-virtualized-select-tests.tsx @@ -4,7 +4,7 @@ import VirtualizedSelect from "react-virtualized-select"; /*Example TValue.*/ interface Example { - name: string; + name: string; } /*Example generic class.*/ @@ -15,21 +15,22 @@ class ExampleSelectCreatable extends VirtualizedSelect { }
-
} - selectComponent={Select} - options={[]} - /> -
} +
} + selectComponent={Select} + options={[]} + /> +
} selectComponent={Select} loadOptions={(input: string) => Promise.resolve([{name: 'Hi'}])} - /> - arg.label.length > 1} - /> + /> + arg.label.length > 1} + />
; From 7cbe3ae33abcaa74f47bf2a927dc93b6c077660f Mon Sep 17 00:00:00 2001 From: Hugues Stefanski Date: Sun, 27 Jan 2019 12:51:22 +0100 Subject: [PATCH 004/710] d3-array : Added group, rollup, and quickselect methods --- types/d3-array/d3-array-tests.ts | 26 ++++++++++++++- types/d3-array/index.d.ts | 57 +++++++++++++++++++++++++++++++- 2 files changed, 81 insertions(+), 2 deletions(-) diff --git a/types/d3-array/d3-array-tests.ts b/types/d3-array/d3-array-tests.ts index 11f208f869..76e7773732 100644 --- a/types/d3-array/d3-array-tests.ts +++ b/types/d3-array/d3-array-tests.ts @@ -485,6 +485,12 @@ num = mixedObjectDateBisectorObject.right(readonlyMixedObjectArray, new Date(201 num = mixedObjectDateBisectorObject.right(readonlyMixedObjectArray, new Date(2015, 3, 14), 1); num = mixedObjectDateBisectorObject.right(readonlyMixedObjectArray, new Date(2015, 3, 14), 3, 4); +// quickselect +numbersArray = d3Array.quickselect(numbersArray, 3); +numbersArray = d3Array.quickselect(numbersArray, 3, 0); +numbersArray = d3Array.quickselect(numbersArray, 3, 0, 5); +numbersArray = d3Array.quickselect(numbersArray, 3, 0, 5, d3Array.descending); + // ascending() ----------------------------------------------------------------- num = d3Array.ascending(undefined, 20); @@ -536,6 +542,24 @@ mergedArray = d3Array.merge([testArray1, [15, 30]]); // fails, type mismatch mergedArray = d3Array.merge(readonlyTestArrays); // inferred type mergedArray = d3Array.merge(readonlyTestArrays); // explicit type +interface ObjDefinition { + name: string; + amount: string; + date: string; +} + +const objArray: Array = [ + { name: "jim", amount: "34.0", date: "11/12/2015" }, + { name: "carl", amount: "120.11", date: "11/12/2015" }, + { name: "stacy", amount: "12.01", date: "01/04/2016" }, + { name: "stacy", amount: "34.05", date: "01/04/2016" } +]; + +let myMap: Map; + +myMap = d3Array.group(objArray, d => d.name); +myMap = d3Array.rollup(objArray, d => d.length, d => d.name); + // cross() --------------------------------------------------------------------- let crossed: Array<[string, number]>; @@ -779,7 +803,7 @@ histoMixedObject_Date = histoMixedObject_Date.domain(timeScale.domain()); // fai domainFnDate = histoMixedObject_Date.domain(); histoMixedObject_DateOrUndefined = histoMixedObject_DateOrUndefined.domain([new Date(2014, 3, 15), new Date(2017, 4, 15)]); histoMixedObject_DateOrUndefined = histoMixedObject_DateOrUndefined.domain([domain[0], domain[domain.length]]); -histoMixedObject_DateOrUndefined = histoMixedObject_DateOrUndefined.domain((values) => [values[0]!, values[values.length]!]); +histoMixedObject_DateOrUndefined = histoMixedObject_DateOrUndefined.domain((values) => [values[0]!, values[values.length]!]); // thresholds(...) ------------------------------------------------------------- diff --git a/types/d3-array/index.d.ts b/types/d3-array/index.d.ts index 391e2786be..37c725a6dd 100644 --- a/types/d3-array/index.d.ts +++ b/types/d3-array/index.d.ts @@ -3,7 +3,8 @@ // Definitions by: Alex Ford // Boris Yankov // Tom Wanzek -// denisname +// denisname , +// Hugues Stefanski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -173,6 +174,44 @@ export interface Bisector { export function bisector(comparator: (a: T, b: U) => number): Bisector; export function bisector(accessor: (x: T) => U): Bisector; +/** + * Rearranges items so that all items in the [left, k] are the smallest. The k-th element will have the (k - left + 1)-th smallest value in [left, right]. + * + * @param array The array to partially sort (in place). + * @param k The middle index for partial sorting. + */ +export function quickselect(array: Array, k: number): Array; + +/** + * Rearranges items so that all items in the [left, k] are the smallest. The k-th element will have the (k - left + 1)-th smallest value in [left, right]. + * + * @param array The array to partially sort (in place). + * @param k The middle index for partial sorting. + * @param left The left index of the range to sort. + */ +export function quickselect(array: Array, k: number, left: number): Array; + +/** + * Rearranges items so that all items in the [left, k] are the smallest. The k-th element will have the (k - left + 1)-th smallest value in [left, right]. + * + * @param array The array to partially sort (in place). + * @param k The middle index for partial sorting. + * @param left The left index of the range to sort. + * @param right The right index. + */ +export function quickselect(array: Array, k: number, left: number, right: number): Array; + +/** + * Rearranges items so that all items in the [left, k] are the smallest. The k-th element will have the (k - left + 1)-th smallest value in [left, right]. + * + * @param array The array to partially sort (in place). + * @param k The middle index for partial sorting. + * @param left The left index of the range to sort. + * @param right The right index. + * @param compare The compare function. + */ +export function quickselect(array: Array, k: number, left: number, right: number, compare: (a: Primitive | undefined, b: Primitive | undefined) => number): Array; + // NB. this is limited to primitive values due to D3's use of the <, >, and >= operators. Results get weird for object instances. /** * Compares two primitive values for sorting (in ascending order). @@ -189,6 +228,22 @@ export function descending(a: Primitive | undefined, b: Primitive | undefined): // Transforming Arrays // -------------------------------------------------------------------------------------- +/** + * Groups the specified array of values into a Map from key to array of value. + * @param a The array to group. + * @param key The key function. + */ +export function group(a: ArrayLike, key: (value: TObject) => TKey): Map; + + +/** + * Groups and reduces the specified array of values into a Map from key to value. + * @param a The array to group. + * @param reduce The reduce function. + * @param key The key function. + */ +export function rollup(a: ArrayLike, reduce: (value: Array) => number, key: (value: TObject) => TKey): Map; + /** * Returns the Cartesian product of the two arrays a and b. * For each element i in the specified array a and each element j in the specified array b, in order, From a6ad97bab4373efd361df2692b99b8aada92e2b7 Mon Sep 17 00:00:00 2001 From: Hugues Stefanski Date: Sun, 27 Jan 2019 12:54:26 +0100 Subject: [PATCH 005/710] d3-array : Updated version number --- types/d3-array/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/d3-array/index.d.ts b/types/d3-array/index.d.ts index 37c725a6dd..9a48411b4e 100644 --- a/types/d3-array/index.d.ts +++ b/types/d3-array/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for D3JS d3-array module 1.2 +// Type definitions for D3JS d3-array module 2.0 // Project: https://github.com/d3/d3-array // Definitions by: Alex Ford // Boris Yankov @@ -8,7 +8,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -// Last module patch version validated against: 1.2.1 +// Last module patch version validated against: 2.0.3 // -------------------------------------------------------------------------- // Shared Types and Interfaces From 5251033d220a1a1958e8519ac671c2fca2dec7cb Mon Sep 17 00:00:00 2001 From: Hugues Stefanski Date: Sun, 27 Jan 2019 13:00:35 +0100 Subject: [PATCH 006/710] d3-array : fix linting errors --- types/d3-array/d3-array-tests.ts | 2 +- types/d3-array/index.d.ts | 30 +++++++++++++++--------------- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/types/d3-array/d3-array-tests.ts b/types/d3-array/d3-array-tests.ts index 76e7773732..a957213bbc 100644 --- a/types/d3-array/d3-array-tests.ts +++ b/types/d3-array/d3-array-tests.ts @@ -548,7 +548,7 @@ interface ObjDefinition { date: string; } -const objArray: Array = [ +const objArray: ObjDefinition[] = [ { name: "jim", amount: "34.0", date: "11/12/2015" }, { name: "carl", amount: "120.11", date: "11/12/2015" }, { name: "stacy", amount: "12.01", date: "01/04/2016" }, diff --git a/types/d3-array/index.d.ts b/types/d3-array/index.d.ts index 9a48411b4e..eae332ca54 100644 --- a/types/d3-array/index.d.ts +++ b/types/d3-array/index.d.ts @@ -176,41 +176,41 @@ export function bisector(accessor: (x: T) => U): Bisector; /** * Rearranges items so that all items in the [left, k] are the smallest. The k-th element will have the (k - left + 1)-th smallest value in [left, right]. - * + * * @param array The array to partially sort (in place). - * @param k The middle index for partial sorting. + * @param k The middle index for partial sorting. */ -export function quickselect(array: Array, k: number): Array; +export function quickselect(array: ArrayLike, k: number): T[]; /** * Rearranges items so that all items in the [left, k] are the smallest. The k-th element will have the (k - left + 1)-th smallest value in [left, right]. - * + * * @param array The array to partially sort (in place). - * @param k The middle index for partial sorting. + * @param k The middle index for partial sorting. * @param left The left index of the range to sort. */ -export function quickselect(array: Array, k: number, left: number): Array; +export function quickselect(array: ArrayLike, k: number, left: number): T[]; /** * Rearranges items so that all items in the [left, k] are the smallest. The k-th element will have the (k - left + 1)-th smallest value in [left, right]. - * + * * @param array The array to partially sort (in place). - * @param k The middle index for partial sorting. + * @param k The middle index for partial sorting. * @param left The left index of the range to sort. * @param right The right index. */ -export function quickselect(array: Array, k: number, left: number, right: number): Array; +export function quickselect(array: ArrayLike, k: number, left: number, right: number): T[]; /** * Rearranges items so that all items in the [left, k] are the smallest. The k-th element will have the (k - left + 1)-th smallest value in [left, right]. - * + * * @param array The array to partially sort (in place). - * @param k The middle index for partial sorting. + * @param k The middle index for partial sorting. * @param left The left index of the range to sort. * @param right The right index. * @param compare The compare function. */ -export function quickselect(array: Array, k: number, left: number, right: number, compare: (a: Primitive | undefined, b: Primitive | undefined) => number): Array; +export function quickselect(array: ArrayLike, k: number, left: number, right: number, compare: (a: Primitive | undefined, b: Primitive | undefined) => number): T[]; // NB. this is limited to primitive values due to D3's use of the <, >, and >= operators. Results get weird for object instances. /** @@ -235,14 +235,14 @@ export function descending(a: Primitive | undefined, b: Primitive | undefined): */ export function group(a: ArrayLike, key: (value: TObject) => TKey): Map; - /** - * Groups and reduces the specified array of values into a Map from key to value. + * Groups and reduces the specified array of values into a Map from key to value. + * * @param a The array to group. * @param reduce The reduce function. * @param key The key function. */ -export function rollup(a: ArrayLike, reduce: (value: Array) => number, key: (value: TObject) => TKey): Map; +export function rollup(a: ArrayLike, reduce: (value: ArrayLike) => number, key: (value: TObject) => TKey): Map; /** * Returns the Cartesian product of the two arrays a and b. From 677187f7ad49195546aaade3f5b00d8995977e94 Mon Sep 17 00:00:00 2001 From: Hugues Stefanski Date: Sun, 3 Feb 2019 08:53:06 +0100 Subject: [PATCH 007/710] d3-array : fixed group and rollup types #32528 --- types/d3-array/d3-array-tests.ts | 7 +++---- types/d3-array/index.d.ts | 4 ++-- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/types/d3-array/d3-array-tests.ts b/types/d3-array/d3-array-tests.ts index a957213bbc..381d49869c 100644 --- a/types/d3-array/d3-array-tests.ts +++ b/types/d3-array/d3-array-tests.ts @@ -555,10 +555,9 @@ const objArray: ObjDefinition[] = [ { name: "stacy", amount: "34.05", date: "01/04/2016" } ]; -let myMap: Map; - -myMap = d3Array.group(objArray, d => d.name); -myMap = d3Array.rollup(objArray, d => d.length, d => d.name); +const grouped: Map = d3Array.group(objArray, d => d.name); +const rolledup: Map = d3Array.rollup(objArray, d => d.length, d => d.name); +const rolledup2: Map = d3Array.rollup(objArray, d => d.map(u => u.name).join(' '), d => d.name); // cross() --------------------------------------------------------------------- diff --git a/types/d3-array/index.d.ts b/types/d3-array/index.d.ts index eae332ca54..7971478581 100644 --- a/types/d3-array/index.d.ts +++ b/types/d3-array/index.d.ts @@ -233,7 +233,7 @@ export function descending(a: Primitive | undefined, b: Primitive | undefined): * @param a The array to group. * @param key The key function. */ -export function group(a: ArrayLike, key: (value: TObject) => TKey): Map; +export function group(a: ArrayLike, key: (value: TObject) => TKey): Map; /** * Groups and reduces the specified array of values into a Map from key to value. @@ -242,7 +242,7 @@ export function group(a: ArrayLike, key: (value: TObject * @param reduce The reduce function. * @param key The key function. */ -export function rollup(a: ArrayLike, reduce: (value: ArrayLike) => number, key: (value: TObject) => TKey): Map; +export function rollup(a: ArrayLike, reduce: (value: TObject[]) => TReduce, key: (value: TObject) => TKey): Map; /** * Returns the Cartesian product of the two arrays a and b. From f04d918623b3e16862a335b1caa7587e3f8ce3be Mon Sep 17 00:00:00 2001 From: Hugues Stefanski Date: Sun, 3 Feb 2019 09:06:07 +0100 Subject: [PATCH 008/710] d3-array v2 : added paths for other libraries --- types/d3-array/v1/d3-array-tests.ts | 941 ++++++++++++++++++++++++++++ types/d3-array/v1/index.d.ts | 547 ++++++++++++++++ types/d3-array/v1/tsconfig.json | 24 + types/d3-array/v1/tslint.json | 7 + types/d3/tsconfig.json | 5 + types/d3/v4/tsconfig.json | 3 + 6 files changed, 1527 insertions(+) create mode 100644 types/d3-array/v1/d3-array-tests.ts create mode 100644 types/d3-array/v1/index.d.ts create mode 100644 types/d3-array/v1/tsconfig.json create mode 100644 types/d3-array/v1/tslint.json diff --git a/types/d3-array/v1/d3-array-tests.ts b/types/d3-array/v1/d3-array-tests.ts new file mode 100644 index 0000000000..66d99dc9b1 --- /dev/null +++ b/types/d3-array/v1/d3-array-tests.ts @@ -0,0 +1,941 @@ +/** + * Typescript definition tests for d3/d3-array module + * + * Note: These tests are intended to test the definitions only + * in the sense of typing and call signature consistency. They + * are not intended as functional tests. + */ + +import * as d3Array from 'd3-array'; +import { scaleTime } from 'd3-scale'; +import { timeYear } from 'd3-time'; + +// ----------------------------------------------------------------------------- +// Preparatory Steps +// ----------------------------------------------------------------------------- + +class NumCoercible { + a: number; + + constructor(a: number) { + this.a = a; + } + valueOf() { + return this.a; + } +} + +class MixedObject { + num: number; + str: string; + numeric: NumCoercible; + date: Date; + + constructor(a: number, date: Date) { + this.num = a; + this.str = a.toString(); + this.numeric = new NumCoercible(a); + this.date = date; + } +} + +let num: number; +let undef: undefined; +let mixedObject: MixedObject; + +let numOrUndefined: number | undefined; +let strOrUndefined: string | undefined; +let numericOrUndefined: NumCoercible | undefined; +let dateOrUndefined: Date | undefined; +let mixedObjectOrUndefined: MixedObject | undefined; +let numOrUndefinedExtent: [number, number] | [undefined, undefined]; +let strOrUndefinedExtent: [string, string] | [undefined, undefined]; +let numericOrUndefinedExtent: [NumCoercible, NumCoercible] | [undefined, undefined]; +let dateMixedOrUndefined: [Date, Date] | [undefined, undefined]; +let mixedOrUndefinedExtent: [d3Array.Primitive | NumCoercible, d3Array.Primitive | NumCoercible] | [undefined, undefined]; +let dateOrUndefinedExtent: [Date, Date] | [undefined, undefined]; + +let numbersArray = [10, 20, 30, 40, 50]; +const numbersOrUndefinedArray = [10, 20, undefined, null, 40, 50]; +let stringyNumbersArray = ['10', '20', '30', '40', '50']; +const numericArray = [new NumCoercible(10), new NumCoercible(20), new NumCoercible(30), new NumCoercible(40), new NumCoercible(50)]; +let dateArray = [new Date(2016, 6, 1), new Date(2016, 7, 30), new Date(2015, 3, 15)]; + +const mixedObjectArray = [ + new MixedObject(10, new Date(2016, 6, 1)), + new MixedObject(20, new Date(2016, 7, 30)), + new MixedObject(30, new Date(2015, 3, 15)), + new MixedObject(40, new Date(2014, 3, 15)), + new MixedObject(50, new Date(2017, 4, 15)) +]; + +const mixedObjectOrUndefinedArray = [...mixedObjectArray, undefined]; +const mixedObjectArrayLike = mixedObjectArray as ArrayLike; + +let typedArray = Uint8Array.from(numbersArray); +let readonlyNumbersArray = numbersArray as ReadonlyArray; +const readonlyNumbersOrUndefinedArray = numbersOrUndefinedArray as ReadonlyArray; +const readonlyStringyNumbersArray = stringyNumbersArray as ReadonlyArray; +const readonlyNumericArray = numericArray as ReadonlyArray; +const readonlyDateArray = dateArray as ReadonlyArray; +const readonlyMixedObjectArray = mixedObjectArray as ReadonlyArray; +const readonlyMixedObjectOrUndefinedArray = mixedObjectOrUndefinedArray as ReadonlyArray; + +function accessorMixedObjectToNum(datum: MixedObject, index: number, array: ArrayLike): number { + return datum.num; +} + +function accessorMixedObjectToStr(datum: MixedObject, index: number, array: ArrayLike): string { + return datum.str; +} + +function accessorMixedObjectToNumeric(datum: MixedObject, index: number, array: ArrayLike): NumCoercible { + return datum.numeric; +} + +function accessorMixedObjectToDate(datum: MixedObject, index: number, array: ArrayLike): Date { + return datum.date; +} + +function accessorMixedObjectToNumOrUndefined(datum: MixedObject | undefined, index: number, array: ArrayLike): number | undefined | null { + return datum ? datum.num : undefined; +} + +function accessorMixedObjectToStrOrUndefined(datum: MixedObject | undefined, index: number, array: ArrayLike): string | undefined | null { + return datum ? datum.str : undefined; +} + +function accessorLikeMixedObjectToNum(datum: MixedObject, index: number, array: ArrayLike): number { + return datum.num; +} + +function accessorLikeMixedObjectToStr(datum: MixedObject, index: number, array: ArrayLike): string { + return datum.str; +} + +function accessorLikeMixedObjectToNumeric(datum: MixedObject, index: number, array: ArrayLike): NumCoercible { + return datum.numeric; +} + +function accessorLikeMixedObjectToDate(datum: MixedObject, index: number, array: ArrayLike): Date { + return datum.date; +} + +function accessorLikeMixedObjectToNumOrUndefined(datum: MixedObject | undefined, index: number, array: ArrayLike): number | undefined | null { + return datum ? datum.num : undefined; +} + +function accessorLikeMixedObjectToStrOrUndefined(datum: MixedObject | undefined, index: number, array: ArrayLike): string | undefined | null { + return datum ? datum.str : undefined; +} + +function accessorReadOnlyMixedObjectToNumOrUndefined(datum: MixedObject | undefined, index: number, array: ArrayLike): number | undefined | null { + return datum ? datum.num : undefined; +} + +// ----------------------------------------------------------------------------- +// Test Statistics +// ----------------------------------------------------------------------------- + +// max() ----------------------------------------------------------------------- + +// without accessors + +numOrUndefined = d3Array.max(numbersArray); +strOrUndefined = d3Array.max(stringyNumbersArray); +numericOrUndefined = d3Array.max(numericArray); +dateOrUndefined = d3Array.max(dateArray); + +// ArrayLike test cases + +numOrUndefined = d3Array.max(typedArray); +numOrUndefined = d3Array.max(readonlyNumbersOrUndefinedArray); +strOrUndefined = d3Array.max(readonlyStringyNumbersArray); +numericOrUndefined = d3Array.max(readonlyNumericArray); +dateOrUndefined = d3Array.max(readonlyDateArray); + +// with accessors + +numOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToNum); +strOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToStr); +numericOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToNumeric); +dateOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToDate); +numOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToNumOrUndefined); +strOrUndefined = d3Array.max(mixedObjectArray, accessorMixedObjectToStrOrUndefined); +numOrUndefined = d3Array.max(readonlyMixedObjectOrUndefinedArray, accessorReadOnlyMixedObjectToNumOrUndefined); + +numOrUndefined = d3Array.max(mixedObjectArrayLike, accessorLikeMixedObjectToNum); +numOrUndefined = d3Array.max(mixedObjectArray, accessorLikeMixedObjectToNum); +numOrUndefined = d3Array.max(mixedObjectArray, accessorReadOnlyMixedObjectToNumOrUndefined); + +numOrUndefined = d3Array.max(mixedObjectArray, (d) => { + const l: MixedObject = d; + return l.num; +}); + +strOrUndefined = d3Array.max(mixedObjectArray, (d) => { + const l: MixedObject = d; + return l.str; +}); + +// $ExpectError +numOrUndefined = d3Array.max(readonlyNumbersArray, (d, i, a) => { a.push(3); return 0; }); + +// min() ----------------------------------------------------------------------- + +// without accessors + +numOrUndefined = d3Array.min(numbersArray); +strOrUndefined = d3Array.min(stringyNumbersArray); +numericOrUndefined = d3Array.min(numericArray); +dateOrUndefined = d3Array.min(dateArray); + +// ArrayLike test cases + +numOrUndefined = d3Array.min(typedArray); +numOrUndefined = d3Array.min(readonlyNumbersOrUndefinedArray); +strOrUndefined = d3Array.min(readonlyStringyNumbersArray); +numericOrUndefined = d3Array.min(readonlyNumericArray); +dateOrUndefined = d3Array.min(readonlyDateArray); + +// with accessors + +numOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToNum); +strOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToStr); +numericOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToNumeric); +dateOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToDate); +numOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToNumOrUndefined); +strOrUndefined = d3Array.min(mixedObjectArray, accessorMixedObjectToStrOrUndefined); +numOrUndefined = d3Array.min(readonlyMixedObjectOrUndefinedArray, accessorReadOnlyMixedObjectToNumOrUndefined); + +// extent() -------------------------------------------------------------------- + +// without accessors + +numOrUndefinedExtent = d3Array.extent(numbersArray); +strOrUndefinedExtent = d3Array.extent(stringyNumbersArray); +numericOrUndefinedExtent = d3Array.extent(numericArray); +dateOrUndefinedExtent = d3Array.extent(dateArray); + +// ArrayLike test cases + +numOrUndefinedExtent = d3Array.extent(typedArray); +numOrUndefinedExtent = d3Array.extent(readonlyNumbersOrUndefinedArray); +strOrUndefinedExtent = d3Array.extent(readonlyStringyNumbersArray); +numericOrUndefinedExtent = d3Array.extent(readonlyNumericArray); +dateOrUndefinedExtent = d3Array.extent(readonlyDateArray); + +// with accessors + +numOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToNum); +strOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToStr); +mixedOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToNumeric); +dateMixedOrUndefined = d3Array.extent(mixedObjectArray, accessorMixedObjectToDate); +numOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToNumOrUndefined); +strOrUndefinedExtent = d3Array.extent(mixedObjectArray, accessorMixedObjectToStrOrUndefined); +numOrUndefinedExtent = d3Array.extent(readonlyMixedObjectOrUndefinedArray, accessorReadOnlyMixedObjectToNumOrUndefined); + +// mean() ---------------------------------------------------------------------- + +numOrUndefined = d3Array.mean(numbersArray); +numOrUndefined = d3Array.mean(numericArray); +numOrUndefined = d3Array.mean(numbersOrUndefinedArray); + +numOrUndefined = d3Array.mean(typedArray); +numOrUndefined = d3Array.mean(readonlyNumbersOrUndefinedArray); +numOrUndefined = d3Array.mean(readonlyNumericArray); +numOrUndefined = d3Array.mean(readonlyNumbersOrUndefinedArray); + +numOrUndefined = d3Array.mean(mixedObjectArray, accessorMixedObjectToNum); +numOrUndefined = d3Array.mean(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); +numOrUndefined = d3Array.mean(readonlyMixedObjectOrUndefinedArray, accessorReadOnlyMixedObjectToNumOrUndefined); + +// median() -------------------------------------------------------------------- + +numOrUndefined = d3Array.median(numbersArray); +numOrUndefined = d3Array.median(numericArray); +numOrUndefined = d3Array.median(numbersOrUndefinedArray); + +numOrUndefined = d3Array.median(typedArray); +numOrUndefined = d3Array.median(readonlyNumbersArray); +numOrUndefined = d3Array.median(readonlyNumericArray); +numOrUndefined = d3Array.median(readonlyNumbersOrUndefinedArray); + +numOrUndefined = d3Array.median(mixedObjectArray, accessorMixedObjectToNum); +numOrUndefined = d3Array.median(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); +numOrUndefined = d3Array.median(readonlyMixedObjectOrUndefinedArray, accessorReadOnlyMixedObjectToNumOrUndefined); + +// quantile() ------------------------------------------------------------------ + +numOrUndefined = d3Array.quantile(numbersArray, 0.5); +numOrUndefined = d3Array.quantile(numericArray, 0.5); +numOrUndefined = d3Array.quantile(numbersOrUndefinedArray, 0.5); + +numOrUndefined = d3Array.quantile(typedArray, 0.5); +numOrUndefined = d3Array.quantile(readonlyNumbersArray, 0.5); +numOrUndefined = d3Array.quantile(readonlyNumericArray, 0.5); +numOrUndefined = d3Array.quantile(readonlyNumbersOrUndefinedArray, 0.5); + +numOrUndefined = d3Array.quantile(mixedObjectArray, 0.5, accessorMixedObjectToNum); +numOrUndefined = d3Array.quantile(mixedObjectOrUndefinedArray, 0.5, accessorMixedObjectToNumOrUndefined); +numOrUndefined = d3Array.quantile(readonlyMixedObjectOrUndefinedArray, 0.5, accessorReadOnlyMixedObjectToNumOrUndefined); + +// sum() ----------------------------------------------------------------------- + +numOrUndefined = d3Array.sum(numbersArray); +numOrUndefined = d3Array.sum(numericArray); +numOrUndefined = d3Array.sum(numbersOrUndefinedArray); + +numOrUndefined = d3Array.sum(typedArray); +numOrUndefined = d3Array.sum(readonlyNumbersArray); +numOrUndefined = d3Array.sum(readonlyNumericArray); +numOrUndefined = d3Array.sum(readonlyNumbersOrUndefinedArray); + +numOrUndefined = d3Array.sum(mixedObjectArray, accessorMixedObjectToNum); +numOrUndefined = d3Array.sum(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); +numOrUndefined = d3Array.sum(readonlyMixedObjectOrUndefinedArray, accessorReadOnlyMixedObjectToNumOrUndefined); + +// deviation() ----------------------------------------------------------------- + +numOrUndefined = d3Array.deviation(numbersArray); +numOrUndefined = d3Array.deviation(numericArray); +numOrUndefined = d3Array.deviation(numbersOrUndefinedArray); + +numOrUndefined = d3Array.deviation(typedArray); +numOrUndefined = d3Array.deviation(readonlyNumbersArray); +numOrUndefined = d3Array.deviation(readonlyNumericArray); +numOrUndefined = d3Array.deviation(readonlyNumbersOrUndefinedArray); + +numOrUndefined = d3Array.deviation(mixedObjectArray, accessorMixedObjectToNum); +numOrUndefined = d3Array.deviation(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); +numOrUndefined = d3Array.deviation(readonlyMixedObjectOrUndefinedArray, accessorReadOnlyMixedObjectToNumOrUndefined); + +// variance() ------------------------------------------------------------------ + +numOrUndefined = d3Array.variance(numbersArray); +numOrUndefined = d3Array.variance(numericArray); +numOrUndefined = d3Array.variance(numbersOrUndefinedArray); + +numOrUndefined = d3Array.variance(typedArray); +numOrUndefined = d3Array.variance(readonlyNumbersArray); +numOrUndefined = d3Array.variance(readonlyNumericArray); +numOrUndefined = d3Array.variance(readonlyNumbersOrUndefinedArray); + +numOrUndefined = d3Array.variance(mixedObjectArray, accessorMixedObjectToNum); +numOrUndefined = d3Array.variance(mixedObjectOrUndefinedArray, accessorMixedObjectToNumOrUndefined); +numOrUndefined = d3Array.variance(readonlyMixedObjectOrUndefinedArray, accessorReadOnlyMixedObjectToNumOrUndefined); + +// ----------------------------------------------------------------------------- +// Test Searching Arrays +// ----------------------------------------------------------------------------- + +numbersArray = [0, 2, 3, 4, 7, 8]; +stringyNumbersArray = ['0', '2', '3', '4', '7', '8']; +dateArray = [new Date(2010, 1, 1), new Date(2011, 1, 1), new Date(2012, 1, 1), new Date(2013, 1, 1)]; +typedArray = Uint8Array.from(numbersArray); + +// scan() ---------------------------------------------------------------------- + +numOrUndefined = d3Array.scan(numbersArray); +numOrUndefined = d3Array.scan(typedArray); +numOrUndefined = d3Array.scan(readonlyNumbersArray); + +numOrUndefined = d3Array.scan(mixedObjectArray, (a, b) => { + const aElem: MixedObject = a; + const bElem: MixedObject = b; + return a.num - b.num; +}); + +numOrUndefined = d3Array.scan(readonlyMixedObjectArray, (a, b) => { + const aElem: MixedObject = a; + const bElem: MixedObject = b; + return a.num - b.num; +}); + +numOrUndefined = d3Array.scan(mixedObjectOrUndefinedArray, (a, b) => { + const aElem: MixedObject | undefined = a; + const bElem: MixedObject | undefined = b; + return a && b ? a.num - b.num : NaN; +}); + +numOrUndefined = d3Array.scan(readonlyMixedObjectOrUndefinedArray, (a, b) => { + const aElem: MixedObject | undefined = a; + const bElem: MixedObject | undefined = b; + return a && b ? a.num - b.num : NaN; +}); + +// bisectLeft() ---------------------------------------------------------------- + +num = d3Array.bisectLeft(numbersArray, 4); +num = d3Array.bisectLeft(numbersArray, 4, 1); +num = d3Array.bisectLeft(numbersArray, 4, 1, 4); + +num = d3Array.bisectLeft(stringyNumbersArray, '21'); +num = d3Array.bisectLeft(stringyNumbersArray, '21', 1); +num = d3Array.bisectLeft(stringyNumbersArray, '21', 1, 4); + +num = d3Array.bisectLeft(dateArray, new Date(2011, 2, 1)); +num = d3Array.bisectLeft(dateArray, new Date(2011, 2, 1), 1); +num = d3Array.bisectLeft(dateArray, new Date(2011, 2, 1), 1, 2); + +num = d3Array.bisectLeft(typedArray, 4); +num = d3Array.bisectLeft(typedArray, 4, 1); +num = d3Array.bisectLeft(typedArray, 4, 1, 4); + +num = d3Array.bisectLeft(readonlyNumbersArray, 4); +num = d3Array.bisectLeft(readonlyNumbersArray, 4, 1); +num = d3Array.bisectLeft(readonlyNumbersArray, 4, 1, 4); + +num = d3Array.bisectLeft(readonlyStringyNumbersArray, '21'); +num = d3Array.bisectLeft(readonlyStringyNumbersArray, '21', 1); +num = d3Array.bisectLeft(readonlyStringyNumbersArray, '21', 1, 4); + +num = d3Array.bisectLeft(readonlyDateArray, new Date(2011, 2, 1)); +num = d3Array.bisectLeft(readonlyDateArray, new Date(2011, 2, 1), 1); +num = d3Array.bisectLeft(readonlyDateArray, new Date(2011, 2, 1), 1, 2); + +// bisectRight() --------------------------------------------------------------- + +num = d3Array.bisectRight(numbersArray, 4); +num = d3Array.bisectRight(numbersArray, 4, 1); +num = d3Array.bisectRight(numbersArray, 4, 1, 4); + +num = d3Array.bisectRight(stringyNumbersArray, '21'); +num = d3Array.bisectRight(stringyNumbersArray, '21', 1); +num = d3Array.bisectRight(stringyNumbersArray, '21', 1, 4); + +num = d3Array.bisectRight(dateArray, new Date(2011, 2, 1)); +num = d3Array.bisectRight(dateArray, new Date(2011, 2, 1), 1); +num = d3Array.bisectRight(dateArray, new Date(2011, 2, 1), 1, 2); + +num = d3Array.bisectRight(typedArray, 4); +num = d3Array.bisectRight(typedArray, 4, 1); +num = d3Array.bisectRight(typedArray, 4, 1, 4); + +num = d3Array.bisectRight(readonlyNumbersArray, 4); +num = d3Array.bisectRight(readonlyNumbersArray, 4, 1); +num = d3Array.bisectRight(readonlyNumbersArray, 4, 1, 4); + +num = d3Array.bisectRight(readonlyStringyNumbersArray, '21'); +num = d3Array.bisectRight(readonlyStringyNumbersArray, '21', 1); +num = d3Array.bisectRight(readonlyStringyNumbersArray, '21', 1, 4); + +num = d3Array.bisectRight(readonlyDateArray, new Date(2011, 2, 1)); +num = d3Array.bisectRight(readonlyDateArray, new Date(2011, 2, 1), 1); +num = d3Array.bisectRight(readonlyDateArray, new Date(2011, 2, 1), 1, 2); + +// bisect() -------------------------------------------------------------------- + +num = d3Array.bisect(numbersArray, 4); +num = d3Array.bisect(numbersArray, 4, 1); +num = d3Array.bisect(numbersArray, 4, 1, 4); + +num = d3Array.bisect(stringyNumbersArray, '21'); +num = d3Array.bisect(stringyNumbersArray, '21', 1); +num = d3Array.bisect(stringyNumbersArray, '21', 1, 4); + +num = d3Array.bisect(dateArray, new Date(2011, 2, 1)); +num = d3Array.bisect(dateArray, new Date(2011, 2, 1), 1); +num = d3Array.bisect(dateArray, new Date(2011, 2, 1), 1, 2); + +num = d3Array.bisect(typedArray, 4); +num = d3Array.bisect(typedArray, 4, 1); +num = d3Array.bisect(typedArray, 4, 1, 4); + +num = d3Array.bisect(readonlyNumbersArray, 4); +num = d3Array.bisect(readonlyNumbersArray, 4, 1); +num = d3Array.bisect(readonlyNumbersArray, 4, 1, 4); + +num = d3Array.bisect(readonlyStringyNumbersArray, '21'); +num = d3Array.bisect(readonlyStringyNumbersArray, '21', 1); +num = d3Array.bisect(readonlyStringyNumbersArray, '21', 1, 4); + +num = d3Array.bisect(readonlyDateArray, new Date(2011, 2, 1)); +num = d3Array.bisect(readonlyDateArray, new Date(2011, 2, 1), 1); +num = d3Array.bisect(readonlyDateArray, new Date(2011, 2, 1), 1, 2); + +// bisector() ------------------------------------------------------------------ + +mixedObjectArray.sort((a, b) => a.date.valueOf() - b.date.valueOf()); + +let mixedObjectDateBisectorObject: d3Array.Bisector; + +// define using accessor +mixedObjectDateBisectorObject = d3Array.bisector(el => el.date); + +// define using comparator +mixedObjectDateBisectorObject = d3Array.bisector((el, x) => + el.date.valueOf() - x.valueOf()); + +// bisect left +num = mixedObjectDateBisectorObject.left(mixedObjectArray, new Date(2015, 3, 14)); +num = mixedObjectDateBisectorObject.left(mixedObjectArray, new Date(2015, 3, 14), 1); +num = mixedObjectDateBisectorObject.left(mixedObjectArray, new Date(2015, 3, 14), 3, 4); + +num = mixedObjectDateBisectorObject.left(readonlyMixedObjectArray, new Date(2015, 3, 14)); +num = mixedObjectDateBisectorObject.left(readonlyMixedObjectArray, new Date(2015, 3, 14), 1); +num = mixedObjectDateBisectorObject.left(readonlyMixedObjectArray, new Date(2015, 3, 14), 3, 4); + +// bisect right +num = mixedObjectDateBisectorObject.right(mixedObjectArray, new Date(2015, 3, 14)); +num = mixedObjectDateBisectorObject.right(mixedObjectArray, new Date(2015, 3, 14), 1); +num = mixedObjectDateBisectorObject.right(mixedObjectArray, new Date(2015, 3, 14), 3, 4); + +num = mixedObjectDateBisectorObject.right(readonlyMixedObjectArray, new Date(2015, 3, 14)); +num = mixedObjectDateBisectorObject.right(readonlyMixedObjectArray, new Date(2015, 3, 14), 1); +num = mixedObjectDateBisectorObject.right(readonlyMixedObjectArray, new Date(2015, 3, 14), 3, 4); + +// ascending() ----------------------------------------------------------------- + +num = d3Array.ascending(undefined, 20); +num = d3Array.ascending(10, 20); +num = d3Array.ascending('10', '20'); +num = d3Array.ascending(new Date(2016, 6, 13), new Date(2016, 6, 14)); + +// descending() ---------------------------------------------------------------- + +num = d3Array.descending(undefined, 20); +num = d3Array.descending(10, 20); +num = d3Array.descending('10', '20'); +num = d3Array.descending(new Date(2016, 6, 13), new Date(2016, 6, 14)); + +// ----------------------------------------------------------------------------- +// Test Transforming Arrays +// ----------------------------------------------------------------------------- + +// merge() --------------------------------------------------------------------- + +const testArray1 = [ + new MixedObject(10, new Date(2016, 6, 1)), + new MixedObject(20, new Date(2016, 7, 30)), + new MixedObject(30, new Date(2015, 3, 15)), + new MixedObject(40, new Date(2014, 3, 15)), + new MixedObject(50, new Date(2017, 4, 15)) +]; + +const testArray2 = [ + new MixedObject(40, new Date(2016, 3, 1)), + new MixedObject(50, new Date(2016, 9, 30)), +]; + +let testArrays: MixedObject[][] = [testArray1, testArray2]; + +const readonlyTestArray1 = testArray1 as ReadonlyArray; +const readonlyTestArray2 = testArray2 as ReadonlyArray; +const readonlyTestArrays = [testArray1, testArray2] as ReadonlyArray>; + +let mergedArray: MixedObject[]; + +mergedArray = d3Array.merge(testArrays); // inferred type +mergedArray = d3Array.merge(testArrays); // explicit type +// $ExpectError +mergedArray = d3Array.merge([[10, 40, 30], [15, 30]]); // fails, type mismatch +// $ExpectError +mergedArray = d3Array.merge([testArray1, [15, 30]]); // fails, type mismatch + +mergedArray = d3Array.merge(readonlyTestArrays); // inferred type +mergedArray = d3Array.merge(readonlyTestArrays); // explicit type + +// cross() --------------------------------------------------------------------- + +let crossed: Array<[string, number]>; + +const chars = ['x', 'y']; +const nums = [1, 2]; + +crossed = d3Array.cross(chars, nums); +crossed = d3Array.cross(chars, nums); + +let strArray: string[] = d3Array.cross([2, 3], [5, 6], (a, b) => (a + b) + 'px'); +strArray = d3Array.cross([2, 3], [5, 6], (a, b) => { + const aa: number = a; + const bb: number = b; + return (aa + bb) + 'px'; +}); + +const readonlyChars = chars as ReadonlyArray; +const readonlyNums = new Uint8Array(nums); + +crossed = d3Array.cross(readonlyChars, readonlyNums); +crossed = d3Array.cross(readonlyChars, readonlyNums); + +strArray = d3Array.cross([2, 3] as ReadonlyArray, new Uint8ClampedArray([5, 6]), (a, b) => (a + b) + 'px'); +strArray = d3Array.cross([2, 3] as ReadonlyArray, new Uint8ClampedArray([5, 6]), (a, b) => { + const aa: number = a; + const bb: number = b; + return (aa + bb) + 'px'; +}); + +d3Array.cross(new Uint8Array([1, 2, 3, 4, 5]), new Uint8Array([10, 20, 30, 40, 50])); + +// pairs() --------------------------------------------------------------------- + +let pairs: Array<[MixedObject, MixedObject]>; + +pairs = d3Array.pairs(mergedArray); + +numbersArray = d3Array.pairs(mergedArray, (a, b) => b.num - a.num); +numbersArray = d3Array.pairs(mergedArray, (a, b) => { + const aa: MixedObject = a; + const bb: MixedObject = b; + return bb.num - aa.num; +}); + +const readonlyMergedArray = mergedArray as ReadonlyArray; +pairs = d3Array.pairs(readonlyMergedArray); + +numbersArray = d3Array.pairs(readonlyMergedArray, (a, b) => b.num - a.num); +numbersArray = d3Array.pairs(readonlyMergedArray, (a, b) => { + const aa: MixedObject = a; + const bb: MixedObject = b; + return bb.num - aa.num; +}); + +// permute() ------------------------------------------------------------------- + +// getting a permutation of array elements +mergedArray = d3Array.permute(mergedArray, [1, 0, 2, 5, 3, 4, 6]); +mergedArray = d3Array.permute(readonlyMergedArray, [1, 0, 2, 5, 3, 4, 6]); +mergedArray = d3Array.permute(readonlyMergedArray, nums); + +// Getting an ordered array with object properties + +const testObject = { + val: 10, + name: 'Test', + when: new Date(), + more: [10, 30, 40] +}; + +const p1: Array = d3Array.permute(testObject, ['name', 'val', 'when', 'more']); +const p2: Array = d3Array.permute(testObject, ['when', 'more']); +// $ExpectError +const p3 = d3Array.permute(testObject, ['when', 'unknown']); + +// range() --------------------------------------------------------------------- + +numbersArray = d3Array.range(10); +numbersArray = d3Array.range(1, 10); +numbersArray = d3Array.range(1, 10, 0.5); + +// shuffle() ------------------------------------------------------------------- + +mergedArray = d3Array.shuffle(mergedArray); +mergedArray = d3Array.shuffle(mergedArray, 1); +mergedArray = d3Array.shuffle(mergedArray, 1, 3); +// $ExpectError +mergedArray = d3Array.shuffle(readonlyMergedArray); // fails, shuffle mutates input array in-place + +// Test each TypedArray explicitly. Can't use ArrayLike in this case because shuffle is mutable and ArrayLike would include ReadonlyArray +const resultInt8: Int8Array = d3Array.shuffle(new Int8Array(numbersArray)); +const resultUint8: Uint8Array = d3Array.shuffle(new Uint8Array(numbersArray)); +const resultUint8Clamped: Uint8ClampedArray = d3Array.shuffle(new Uint8ClampedArray(numbersArray)); +const resultInt16: Int16Array = d3Array.shuffle(new Int16Array(numbersArray)); +const resultUint6: Uint16Array = d3Array.shuffle(new Uint16Array(numbersArray)); +const resultInt32: Int32Array = d3Array.shuffle(new Int32Array(numbersArray)); +const resultUint32: Uint32Array = d3Array.shuffle(new Uint32Array(numbersArray)); +const resultFloat32: Float32Array = d3Array.shuffle(new Float32Array(numbersArray)); +const resultFloat64: Float64Array = d3Array.shuffle(new Float64Array(numbersArray)); + +// ticks() --------------------------------------------------------------------- + +numbersArray = d3Array.ticks(1, 10, 5); + +// tickIncrement() ------------------------------------------------------------------ + +let numDiff: number = d3Array.tickIncrement(1, 10, 5); + +// tickStep() ------------------------------------------------------------------ + +numDiff = d3Array.tickStep(1, 10, 5); + +// transpose() ----------------------------------------------------------------- + +testArrays = d3Array.transpose([testArray1, testArray2]); +testArrays = d3Array.transpose([readonlyTestArray1, readonlyTestArray2] as ReadonlyArray>); + +// zip() ----------------------------------------------------------------------- + +testArrays = d3Array.zip(testArray1, testArray2); +testArrays = d3Array.zip(readonlyTestArray1, readonlyTestArray2); + +// ----------------------------------------------------------------------------- +// Test Histogram +// ----------------------------------------------------------------------------- + +const timeScale = scaleTime(); + +// Create histogram generator ================================================== + +// number - number +let histoNumber_Number: d3Array.HistogramGeneratorNumber; +histoNumber_Number = d3Array.histogram(); +histoNumber_Number = d3Array.histogram(); + +// MixedObject - number | undefined +let histoMixed_NumberOrUndefined: d3Array.HistogramGeneratorNumber; +histoMixed_NumberOrUndefined = d3Array.histogram(); + +// MixedObject | undefined - number | undefined +let histoMixedOrUndefined_NumberOrUndefined: d3Array.HistogramGeneratorNumber; +histoMixedOrUndefined_NumberOrUndefined = d3Array.histogram(); + +// MixedObject | undefined - number +let histoMixedOrUndefined_Number: d3Array.HistogramGeneratorNumber; +histoMixedOrUndefined_Number = d3Array.histogram(); + +// MixedObject - Date +let histoMixedObject_Date: d3Array.HistogramGeneratorDate; +histoMixedObject_Date = d3Array.histogram(); + +// MixedObject - Date | undefined +let histoMixedObject_DateOrUndefined: d3Array.HistogramGeneratorDate; +histoMixedObject_DateOrUndefined = d3Array.histogram(); + +let defaultHistogram: d3Array.HistogramGeneratorNumber; +defaultHistogram = d3Array.histogram(); + +// Configure histogram generator =============================================== + +// value(...) ------------------------------------------------------------------ + +let valueAccessorFn: (d: MixedObject, i: number, data: MixedObject[]) => Date; +valueAccessorFn = histoMixedObject_Date.value(); + +type valueAccessor = (d: D, i: number, data: D[]) => V; + +// number - number +const valueFnNumber_Number: valueAccessor = histoNumber_Number.value(); +histoNumber_Number = histoNumber_Number.value((d: number, i: number, data: ArrayLike) => { + return d - num; +}); + +// MixedObject - number | undefined +const valueFnMixedObject_NumberOrUndefined: valueAccessor = histoMixed_NumberOrUndefined.value(); +histoMixed_NumberOrUndefined = histoMixed_NumberOrUndefined.value((d: MixedObject, i: number, data: ArrayLike) => { + return d.str === "NA" ? undefined : d.num; +}); + +// MixedObject | undefined - number | undefined +const valueFnMixedOrUndefined_NumberOrUndefined: valueAccessor = histoMixedOrUndefined_NumberOrUndefined.value(); +histoMixedOrUndefined_NumberOrUndefined = histoMixedOrUndefined_NumberOrUndefined.value((d: MixedObject | undefined, i: number, data: ArrayLike) => { + return d ? d.num : undefined; +}); + +// MixedObject | undefined - number +const valueFnMixedOrUndefined_Number: valueAccessor = histoMixedOrUndefined_Number.value(); +histoMixedOrUndefined_Number = histoMixedOrUndefined_Number.value((d: MixedObject | undefined, i: number, data: ArrayLike) => { + return d ? d.num : 0; +}); + +// MixedObject - Date +const valueFnMixedObject_Date: valueAccessor = histoMixedObject_Date.value(); +histoMixedObject_Date = histoMixedObject_Date.value((d: MixedObject, i: number, data: ArrayLike) => { + return d.date; +}); + +// MixedObject - Date | undefined +const valueFnMixedObject_DateOrUndefined: valueAccessor = histoMixedObject_DateOrUndefined.value(); +histoMixedObject_DateOrUndefined = histoMixedObject_DateOrUndefined.value((d: MixedObject, i: number, data: ArrayLike) => { + return d.date; +}); + +// domain(...) ----------------------------------------------------------------- + +const domain = timeScale.domain(); +let domainFnNumber: (array: number[]) => [number, number] | [undefined, undefined]; +let domainFnNumberOrUndef: (array: Array) => [number, number] | [undefined, undefined]; +let domainFnDate: (values: Date[]) => [Date, Date]; + +// number - number +domainFnNumber = histoNumber_Number.domain(); +histoNumber_Number = histoNumber_Number.domain([0, 100]); +histoNumber_Number = histoNumber_Number.domain(d3Array.extent); + +// MixedObject - number | undefined +domainFnNumber = histoNumber_Number.domain(); +histoMixed_NumberOrUndefined = histoMixed_NumberOrUndefined.domain([0, 100]); +histoMixed_NumberOrUndefined = histoMixed_NumberOrUndefined.domain(d3Array.extent); + +// MixedObject | undefined - number | undefined +domainFnNumberOrUndef = histoMixedOrUndefined_NumberOrUndefined.domain(); +histoMixedOrUndefined_NumberOrUndefined = histoMixedOrUndefined_NumberOrUndefined.domain([0, 100]); +histoMixedOrUndefined_NumberOrUndefined = histoMixedOrUndefined_NumberOrUndefined.domain(d3Array.extent); + +// MixedObject | undefined - number +domainFnNumber = histoMixedOrUndefined_Number.domain(); +histoMixedOrUndefined_Number = histoMixedOrUndefined_Number.domain([0, 100]); +histoMixedOrUndefined_Number = histoMixedOrUndefined_Number.domain(d3Array.extent); + +// MixedObject - Date +domainFnDate = histoMixedObject_Date.domain(); +histoMixedObject_Date = histoMixedObject_Date.domain([new Date(2014, 3, 15), new Date(2017, 4, 15)]); +histoMixedObject_Date = histoMixedObject_Date.domain([domain[0], domain[domain.length]]); +histoMixedObject_Date = histoMixedObject_Date.domain((values) => [values[0], values[values.length]]); +// $ExpectError +histoMixedObject_Date = histoMixedObject_Date.domain(timeScale.domain()); // fails, as scale domain is an array with possibly more than the two elements expected by histogram + +// MixedObject - Date | undefined +domainFnDate = histoMixedObject_Date.domain(); +histoMixedObject_DateOrUndefined = histoMixedObject_DateOrUndefined.domain([new Date(2014, 3, 15), new Date(2017, 4, 15)]); +histoMixedObject_DateOrUndefined = histoMixedObject_DateOrUndefined.domain([domain[0], domain[domain.length]]); +histoMixedObject_DateOrUndefined = histoMixedObject_DateOrUndefined.domain((values) => [values[0]!, values[values.length]!]); + +// thresholds(...) ------------------------------------------------------------- + +type thresholdsWithUndefinedCont = d3Array.ThresholdCountGenerator; +type thresholdsWithUndefinedArray = d3Array.ThresholdNumberArrayGenerator; + +let thresholds: d3Array.ThresholdCountGenerator | d3Array.ThresholdNumberArrayGenerator; +let thresholdsWithUndefined: thresholdsWithUndefinedCont | thresholdsWithUndefinedArray; +const thresholdsArray: d3Array.ThresholdNumberArrayGenerator = (x: ArrayLike) => [5, 10, 20]; + +let thresholdsDate: d3Array.ThresholdDateArrayGenerator; +let thresholdsDateOrUndefined: d3Array.ThresholdDateArrayGenerator; + +// number - number +thresholds = histoNumber_Number.thresholds(); +histoNumber_Number = histoNumber_Number.thresholds(3); +histoNumber_Number = histoNumber_Number.thresholds([5, 10, 20]); +histoNumber_Number = histoNumber_Number.thresholds(d3Array.thresholdScott); +histoNumber_Number = histoNumber_Number.thresholds(thresholdsArray); + +// MixedObject - number | undefined +thresholdsWithUndefined = histoMixed_NumberOrUndefined.thresholds(); +histoMixed_NumberOrUndefined = histoMixed_NumberOrUndefined.thresholds(3); +histoMixed_NumberOrUndefined = histoMixed_NumberOrUndefined.thresholds([5, 10, 20]); +histoMixed_NumberOrUndefined = histoMixed_NumberOrUndefined.thresholds(d3Array.thresholdScott); + +// MixedObject | undefined - number | undefined +thresholdsWithUndefined = histoMixedOrUndefined_NumberOrUndefined.thresholds(); +histoMixedOrUndefined_NumberOrUndefined = histoMixedOrUndefined_NumberOrUndefined.thresholds(3); +histoMixedOrUndefined_NumberOrUndefined = histoMixedOrUndefined_NumberOrUndefined.thresholds([5, 10, 20]); +histoMixedOrUndefined_NumberOrUndefined = histoMixedOrUndefined_NumberOrUndefined.thresholds(d3Array.thresholdScott); + +// MixedObject | undefined - number +thresholds = histoMixedOrUndefined_Number.thresholds(); +histoMixedOrUndefined_Number = histoMixedOrUndefined_Number.thresholds(5); +histoMixedOrUndefined_Number = histoMixedOrUndefined_Number.thresholds([5, 10, 20]); +histoMixedOrUndefined_Number = histoMixedOrUndefined_Number.thresholds(d3Array.thresholdSturges); + +// MixedObject - Date +thresholdsDate = histoMixedObject_Date.thresholds(); +histoMixedObject_Date = histoMixedObject_Date.thresholds([new Date(2015, 11, 15), new Date(2016, 6, 1), new Date(2016, 8, 30)]); +histoMixedObject_Date = histoMixedObject_Date.thresholds(timeScale.ticks(timeYear)); +histoMixedObject_Date = histoMixedObject_Date.thresholds((values: ArrayLike) => [new Date(2015, 11, 15), new Date(2016, 6, 1), new Date(2016, 8, 30)]); +histoMixedObject_Date = histoMixedObject_Date.thresholds((values: ArrayLike, min: Date, max: Date) => { + const thresholds: Date[] = [values[0], values[2], values[4]]; + return thresholds; +}); +// $ExpectError +histoMixedObject_Date = histoMixedObject_Date.thresholds(d3Array.thresholdScott); + +// MixedObject - Date | undefined +thresholdsDateOrUndefined = histoMixedObject_DateOrUndefined.thresholds(); +histoMixedObject_DateOrUndefined = histoMixedObject_DateOrUndefined.thresholds([new Date(2015, 11, 15), new Date(2016, 6, 1), new Date(2016, 8, 30)]); +histoMixedObject_DateOrUndefined = histoMixedObject_DateOrUndefined.thresholds(timeScale.ticks(timeYear)); +histoMixedObject_DateOrUndefined = histoMixedObject_DateOrUndefined.thresholds((values: ArrayLike, min: Date, max: Date) => { + const thresholds: Date[] = [values[0]!, new Date(2015, 11, 15), values[values.length]!]; + return thresholds; +}); + +// Use histogram generator ===================================================== + +undef = d3Array.histogram()([])[0].x0 as undefined; +undef = d3Array.histogram()([undefined])[0].x0 as undefined; + +// number - number +let binsNumber_Number: Array>; +binsNumber_Number = histoNumber_Number([-1, 0, 1, 1, 3, 20, 234]); + +let binNumber_Number: d3Array.Bin; +binNumber_Number = binsNumber_Number[0]; + +num = binNumber_Number.length; +num = binNumber_Number[0]; +numOrUndefined = binNumber_Number.x0; +numOrUndefined = binNumber_Number.x1; + +// MixedObject - number | undefined +let binsNumberMixed_NumberOrUndefined: Array>; +binsNumberMixed_NumberOrUndefined = histoMixed_NumberOrUndefined(mixedObjectArray); + +let binNumberMixed_NumberOrUndefined: d3Array.Bin; +binNumberMixed_NumberOrUndefined = binsNumberMixed_NumberOrUndefined[0]; + +num = binNumberMixed_NumberOrUndefined.length; +mixedObject = binNumberMixed_NumberOrUndefined[0]; +numOrUndefined = binNumberMixed_NumberOrUndefined.x0; +numOrUndefined = binNumberMixed_NumberOrUndefined.x1; + +// MixedObject | undefined - number | undefined +let binsNumberMixedOrUndefined_NumberOrUndefined: Array>; +binsNumberMixedOrUndefined_NumberOrUndefined = histoMixedOrUndefined_NumberOrUndefined(mixedObjectArray); + +let binNumberMixedOrUndefined_NumberOrUndefined: d3Array.Bin; +binNumberMixedOrUndefined_NumberOrUndefined = binsNumberMixedOrUndefined_NumberOrUndefined[0]; + +num = binNumberMixedOrUndefined_NumberOrUndefined.length; +mixedObjectOrUndefined = binNumberMixedOrUndefined_NumberOrUndefined[0]; +numOrUndefined = binNumberMixedOrUndefined_NumberOrUndefined.x0; +numOrUndefined = binNumberMixedOrUndefined_NumberOrUndefined.x1; + +// MixedObject | undefined - number +let binsNumberMixedOrUndefined_Number: Array>; +binsNumberMixedOrUndefined_Number = histoMixedOrUndefined_Number(mixedObjectArray); + +let binNumberMixedOrUndefined_Number: d3Array.Bin; +binNumberMixedOrUndefined_Number = binsNumberMixedOrUndefined_Number[0]; + +num = binNumberMixedOrUndefined_Number.length; +mixedObjectOrUndefined = binNumberMixedOrUndefined_Number[0]; +numOrUndefined = binNumberMixedOrUndefined_Number.x0; +numOrUndefined = binNumberMixedOrUndefined_Number.x1; + +// MixedObject - Date +let binsMixedObject_Date: Array>; +binsMixedObject_Date = histoMixedObject_Date(mixedObjectArray); +binsMixedObject_Date = histoMixedObject_Date(readonlyMixedObjectArray); + +let binMixedObject_Date: d3Array.Bin; +binMixedObject_Date = binsMixedObject_Date[0]; + +num = binMixedObject_Date.length; +mixedObject = binMixedObject_Date[0]; +dateOrUndefined = binMixedObject_Date.x0; +dateOrUndefined = binMixedObject_Date.x1; + +// MixedObject - Date | undefined +let binsMixedObject_DateOrUndefined: Array>; +binsMixedObject_DateOrUndefined = histoMixedObject_DateOrUndefined(mixedObjectArray); + +let binMixedObject_DateOrUndefined: d3Array.Bin; +binMixedObject_DateOrUndefined = binsMixedObject_DateOrUndefined[0]; + +num = binMixedObject_DateOrUndefined.length; +mixedObject = binMixedObject_DateOrUndefined[0]; +dateOrUndefined = binMixedObject_DateOrUndefined.x0; +dateOrUndefined = binMixedObject_DateOrUndefined.x1; + +// Histogram Thresholds ======================================================== + +numbersArray = [-1, 0, 1, 1, 3, 20, 234]; +typedArray = new Uint8Array(numbersArray); +readonlyNumbersArray = numbersArray as ReadonlyArray; + +num = d3Array.thresholdFreedmanDiaconis(numbersArray, -1, 234); +num = d3Array.thresholdFreedmanDiaconis(typedArray, -1, 234); +num = d3Array.thresholdFreedmanDiaconis(readonlyNumbersArray, -1, 234); + +num = d3Array.thresholdScott(numbersArray, -1, 234); +num = d3Array.thresholdScott(typedArray, -1, 234); +num = d3Array.thresholdScott(readonlyNumbersArray, -1, 234); + +num = d3Array.thresholdSturges(numbersArray); +num = d3Array.thresholdSturges(typedArray); +num = d3Array.thresholdSturges(readonlyNumbersArray); + +// Deprecated ================================================================== + +const histDeprecatedNumber: d3Array.HistogramGenerator = d3Array.histogram(); +const histDeprecatedDate: d3Array.HistogramGenerator = d3Array.histogram(); diff --git a/types/d3-array/v1/index.d.ts b/types/d3-array/v1/index.d.ts new file mode 100644 index 0000000000..7320e1c223 --- /dev/null +++ b/types/d3-array/v1/index.d.ts @@ -0,0 +1,547 @@ +// Type definitions for D3JS d3-array module 1.2 +// Project: https://github.com/d3/d3-array +// Definitions by: Alex Ford +// Boris Yankov +// Tom Wanzek +// denisname , +// Hugues Stefanski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +// Last module patch version validated against: 1.2.1 + +// -------------------------------------------------------------------------- +// Shared Types and Interfaces +// -------------------------------------------------------------------------- + +/** + * Administrivia: JavaScript primitive types and Date + */ +export type Primitive = number | string | boolean | Date; + +/** + * Administrivia: anything with a valueOf(): number method is comparable, so we allow it in numeric operations + */ +export interface Numeric { + valueOf(): number; +} + +// -------------------------------------------------------------------------------------- +// Descriptive Statistics +// -------------------------------------------------------------------------------------- + +/** + * Return the maximum value in the array of strings using natural order. + */ +export function max(array: ArrayLike): string | undefined; + +/** + * Return the maximum value in the array of numbers using natural order. + */ +export function max(array: ArrayLike): T | undefined; + +/** + * Return the maximum value in the array using natural order and a projection function to map values to strings. + */ +export function max(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => string | undefined | null): string | undefined; + +/** + * Return the maximum value in the array using natural order and a projection function to map values to easily-sorted values. + */ +export function max(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => U | undefined | null): U | undefined; + +/** + * Return the minimum value in the array using natural order. + */ +export function min(array: ArrayLike): string | undefined; + +/** + * Return the minimum value in the array using natural order. + */ +export function min(array: ArrayLike): T | undefined; + +/** + * Return the minimum value in the array using natural order. + */ +export function min(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => string | undefined | null): string | undefined; + +/** + * Return the minimum value in the array using natural order. + */ +export function min(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => U | undefined | null): U | undefined; + +/** + * Return the min and max simultaneously. + */ +export function extent(array: ArrayLike): [string, string] | [undefined, undefined]; + +/** + * Return the min and max simultaneously. + */ +export function extent(array: ArrayLike): [T, T] | [undefined, undefined]; + +/** + * Return the min and max simultaneously. + */ +export function extent(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => string | undefined | null): [string, string] | [undefined, undefined]; + +/** + * Return the min and max simultaneously. + */ +export function extent(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => U | undefined | null): [U, U] | [undefined, undefined]; + +/** + * Return the mean of an array of numbers + */ +export function mean(array: ArrayLike): number | undefined; + +/** + * Return the mean of an array of numbers + */ +export function mean(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => number | undefined | null): number | undefined; + +/** + * Return the median of an array of numbers + */ +export function median(array: ArrayLike): number | undefined; + +/** + * Return the median of an array of numbers + */ +export function median(array: ArrayLike, accessor: (element: T, i: number, array: ArrayLike) => number | undefined | null): number | undefined; + +/** + * Returns the p-quantile of an array of numbers + */ +export function quantile(array: ArrayLike, p: number): number | undefined; + +export function quantile(array: ArrayLike, p: number, accessor: (element: T, i: number, array: ArrayLike) => number | undefined | null): number | undefined; + +/** + * Compute the sum of an array of numbers. + */ +export function sum(array: ArrayLike): number; + +/** + * Compute the sum of an array, using the given accessor to convert values to numbers. + */ +export function sum(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => number | undefined | null): number; + +/** + * Compute the standard deviation, defined as the square root of the bias-corrected variance, of the given array of numbers. + */ +export function deviation(array: ArrayLike): number | undefined; + +/** + * Compute the standard deviation, defined as the square root of the bias-corrected variance, of the given array, + * using the given accessor to convert values to numbers. + */ +export function deviation(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => number | undefined | null): number | undefined; + +/** + * Compute an unbiased estimator of the population variance of the given array of numbers. + */ +export function variance(array: ArrayLike): number | undefined; + +/** + * Compute an unbiased estimator of the population variance of the given array, + * using the given accessor to convert values to numbers. + */ +export function variance(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => number | undefined | null): number | undefined; + +// -------------------------------------------------------------------------------------- +// Searching Arrays +// -------------------------------------------------------------------------------------- + +export function scan(array: ArrayLike, comparator?: (a: number, b: number) => number): number | undefined; +export function scan(array: ArrayLike, comparator: (a: T, b: T) => number): number | undefined; + +export function bisectLeft(array: ArrayLike, x: number, lo?: number, hi?: number): number; +export function bisectLeft(array: ArrayLike, x: string, lo?: number, hi?: number): number; +export function bisectLeft(array: ArrayLike, x: Date, lo?: number, hi?: number): number; + +export function bisectRight(array: ArrayLike, x: number, lo?: number, hi?: number): number; +export function bisectRight(array: ArrayLike, x: string, lo?: number, hi?: number): number; +export function bisectRight(array: ArrayLike, x: Date, lo?: number, hi?: number): number; + +export const bisect: typeof bisectRight; + +export interface Bisector { + left(array: ArrayLike, x: U, lo?: number, hi?: number): number; + right(array: ArrayLike, x: U, lo?: number, hi?: number): number; +} + +export function bisector(comparator: (a: T, b: U) => number): Bisector; +export function bisector(accessor: (x: T) => U): Bisector; + +/** + * Rearranges items so that all items in the [left, k] are the smallest. The k-th element will have the (k - left + 1)-th smallest value in [left, right]. + * + * @param array The array to partially sort (in place). + * @param k The middle index for partial sorting. + */ +export function quickselect(array: ArrayLike, k: number): T[]; + +/** + * Rearranges items so that all items in the [left, k] are the smallest. The k-th element will have the (k - left + 1)-th smallest value in [left, right]. + * + * @param array The array to partially sort (in place). + * @param k The middle index for partial sorting. + * @param left The left index of the range to sort. + */ +export function quickselect(array: ArrayLike, k: number, left: number): T[]; + +/** + * Rearranges items so that all items in the [left, k] are the smallest. The k-th element will have the (k - left + 1)-th smallest value in [left, right]. + * + * @param array The array to partially sort (in place). + * @param k The middle index for partial sorting. + * @param left The left index of the range to sort. + * @param right The right index. + */ +export function quickselect(array: ArrayLike, k: number, left: number, right: number): T[]; + +/** + * Rearranges items so that all items in the [left, k] are the smallest. The k-th element will have the (k - left + 1)-th smallest value in [left, right]. + * + * @param array The array to partially sort (in place). + * @param k The middle index for partial sorting. + * @param left The left index of the range to sort. + * @param right The right index. + * @param compare The compare function. + */ +export function quickselect(array: ArrayLike, k: number, left: number, right: number, compare: (a: Primitive | undefined, b: Primitive | undefined) => number): T[]; + +// NB. this is limited to primitive values due to D3's use of the <, >, and >= operators. Results get weird for object instances. +/** + * Compares two primitive values for sorting (in ascending order). + */ +export function ascending(a: Primitive | undefined, b: Primitive | undefined): number; + +// NB. this is limited to primitive values due to D3's use of the <, >, and >= operators. Results get weird for object instances. +/** + * Compares two primitive values for sorting (in ascending order). + */ +export function descending(a: Primitive | undefined, b: Primitive | undefined): number; + +// -------------------------------------------------------------------------------------- +// Transforming Arrays +// -------------------------------------------------------------------------------------- + +/** + * Groups the specified array of values into a Map from key to array of value. + * @param a The array to group. + * @param key The key function. + */ +export function group(a: ArrayLike, key: (value: TObject) => TKey): Map; + +/** + * Groups and reduces the specified array of values into a Map from key to value. + * + * @param a The array to group. + * @param reduce The reduce function. + * @param key The key function. + */ +export function rollup(a: ArrayLike, reduce: (value: TObject[]) => TReduce, key: (value: TObject) => TKey): Map; + +/** + * Returns the Cartesian product of the two arrays a and b. + * For each element i in the specified array a and each element j in the specified array b, in order, + * it creates a two-element array for each pair. + * + * @param a First input array. + * @param b Second input array. + */ +export function cross(a: ArrayLike, b: ArrayLike): Array<[S, T]>; + +/** + * Returns the Cartesian product of the two arrays a and b. + * For each element i in the specified array a and each element j in the specified array b, in order, + * invokes the specified reducer function passing the element i and element j. + * + * @param a First input array. + * @param b Second input array. + * @param reducer A reducer function taking as input an element from "a" and "b" and returning a reduced value. + */ +export function cross(a: ArrayLike, b: ArrayLike, reducer: (a: S, b: T) => U): U[]; + +/** + * Merges the specified arrays into a single array. + */ +export function merge(arrays: ArrayLike>): T[]; + +/** + * For each adjacent pair of elements in the specified array, returns a new array of tuples of elements i and i - 1. + * Returns the empty array if the input array has fewer than two elements. + * + * @param array Array of input elements + */ +export function pairs(array: ArrayLike): Array<[T, T]>; +/** + * For each adjacent pair of elements in the specified array, in order, invokes the specified reducer function passing the element i and element i - 1. + * Returns the resulting array of pair-wise reduced elements. + * Returns the empty array if the input array has fewer than two elements. + * + * @param array Array of input elements + * @param reducer A reducer function taking as input to adjacent elements of the input array and returning a reduced value. + */ +export function pairs(array: ArrayLike, reducer: (a: T, b: T) => U): U[]; + +/** + * Returns a permutation of the specified array using the specified array of indexes. + * The returned array contains the corresponding element in array for each index in indexes, in order. + * For example, `permute(["a", "b", "c"], [1, 2, 0]) // ["b", "c", "a"]` + */ +export function permute(array: { [key: number]: T }, keys: ArrayLike): T[]; + +/** + * Extract the values from an object into an array with a stable order. For example: + * `var object = {yield: 27, year: 1931, site: "University Farm"};` + * `d3.permute(object, ["site", "yield"]); // ["University Farm", 27]` + */ +export function permute(object: T, keys: ArrayLike): Array; + +/** + * Generates a 0-based numeric sequence. The output range does not include 'stop'. + */ +export function range(stop: number): number[]; + +/** + * Generates a numeric sequence starting from the given start and stop values. 'step' defaults to 1. The output range does not include 'stop'. + */ +export function range(start: number, stop: number, step?: number): number[]; + +/** + * Randomizes the order of the specified array using the Fisher–Yates shuffle. + */ +export function shuffle(array: T[], lo?: number, hi?: number): T[]; +export function shuffle(array: Int8Array, lo?: number, hi?: number): Int8Array; +export function shuffle(array: Uint8Array, lo?: number, hi?: number): Uint8Array; +export function shuffle(array: Uint8ClampedArray, lo?: number, hi?: number): Uint8ClampedArray; +export function shuffle(array: Int16Array, lo?: number, hi?: number): Int16Array; +export function shuffle(array: Uint16Array, lo?: number, hi?: number): Uint16Array; +export function shuffle(array: Int32Array, lo?: number, hi?: number): Int32Array; +export function shuffle(array: Uint32Array, lo?: number, hi?: number): Uint32Array; +export function shuffle(array: Float32Array, lo?: number, hi?: number): Float32Array; +export function shuffle(array: Float64Array, lo?: number, hi?: number): Float64Array; + +/** + * Generate an array of approximately count + 1 uniformly-spaced, nicely-rounded values between start and stop (inclusive). + * Each value is a power of ten multiplied by 1, 2 or 5. See also d3.tickIncrement, d3.tickStep and linear.ticks. + * + * Ticks are inclusive in the sense that they may include the specified start and stop values if (and only if) they are exact, + * nicely-rounded values consistent with the inferred step. More formally, each returned tick t satisfies start ≤ t and t ≤ stop. + * + * @param start Start value for ticks + * @param stop Stop value for ticks + * @param count count + 1 is the approximate number of ticks to be returned by d3.ticks. + */ +export function ticks(start: number, stop: number, count: number): number[]; + +/** + * Returns the difference between adjacent tick values if the same arguments were passed to d3.ticks: + * a nicely-rounded value that is a power of ten multiplied by 1, 2 or 5. + * + * Like d3.tickStep, except requires that start is always less than or equal to step, and if the tick step for the given start, + * stop and count would be less than one, returns the negative inverse tick step instead. + * + * This method is always guaranteed to return an integer, and is used by d3.ticks to avoid guarantee that the returned tick values + * are represented as precisely as possible in IEEE 754 floating point. + * + * @param start Start value for ticks + * @param stop Stop value for ticks + * @param count count + 1 is the approximate number of ticks to be returned by d3.ticks. + */ +export function tickIncrement(start: number, stop: number, count: number): number; + +/** + * Returns the difference between adjacent tick values if the same arguments were passed to d3.ticks: + * a nicely-rounded value that is a power of ten multiplied by 1, 2 or 5. + * + * Note that due to the limited precision of IEEE 754 floating point, the returned value may not be exact decimals; + * use d3-format to format numbers for human consumption. + * + * @param start Start value for ticks + * @param stop Stop value for ticks + * @param count count + 1 is the approximate number of ticks to be returned by d3.ticks. + */ +export function tickStep(start: number, stop: number, count: number): number; + +/** + * Transpose a matrix provided in Array of Arrays format. + */ +export function transpose(matrix: ArrayLike>): T[][]; + +/** + * Returns an array of arrays, where the ith array contains the ith element from each of the argument arrays. + * The returned array is truncated in length to the shortest array in arrays. If arrays contains only a single array, the returned array + * contains one-element arrays. With no arguments, the returned array is empty. + */ +export function zip(...arrays: Array>): T[][]; + +// -------------------------------------------------------------------------------------- +// Histogram +// -------------------------------------------------------------------------------------- + +export interface Bin extends Array { + x0: Value | undefined; + x1: Value | undefined; +} + +/** + * Type definition for threshold generator which returns the count of recommended thresholds + */ +export type ThresholdCountGenerator = + (values: ArrayLike, min: number, max: number) => number; + +/** + * Type definition for threshold generator which returns an array of recommended numbers thresholds + */ +export type ThresholdNumberArrayGenerator = + (values: ArrayLike, min: number, max: number) => Value[]; + +/** + * Type definition for threshold generator which returns an array of recommended dates thresholds + */ +export type ThresholdDateArrayGenerator = + (values: ArrayLike, min: Date, max: Date) => Value[]; + +/** + * @deprecated Use ThresholdNumberArrayGenerator or ThresholdDateArrayGenerator. + */ +export type ThresholdArrayGenerator = ThresholdNumberArrayGenerator; + +/** + * @deprecated Use `HistogramGeneratorNumber` for `number` values and `HistogramGeneratorDate for `Date` values. + */ +export interface HistogramGenerator { + (data: ArrayLike): Array>; + + value(): (d: Datum, i: number, data: ArrayLike) => Value; + value(valueAccessor: (d: Datum, i: number, data: ArrayLike) => Value): this; + + domain(): (values: ArrayLike) => [Value, Value] | [undefined, undefined]; + domain(domain: [Value, Value]): this; + domain(domainAccessor: (values: ArrayLike) => [Value, Value] | [undefined, undefined]): this; + + /** + * Set the array of values to be used as thresholds in determining the bins. + * + * Any threshold values outside the domain are ignored. The first bin.x0 is always equal to the minimum domain value, + * and the last bin.x1 is always equal to the maximum domain value. + * + * @param thresholds Array of threshold values used for binning. The elements must + * be of the same type as the materialized values of the histogram. + */ + thresholds(thresholds: ArrayLike): this; +} + +export interface HistogramCommon { + (data: ArrayLike): Array>; + + value(): (d: Datum, i: number, data: ArrayLike) => Value; + value(valueAccessor: (d: Datum, i: number, data: ArrayLike) => Value): this; +} + +export interface HistogramGeneratorDate extends HistogramCommon { + domain(): (values: ArrayLike) => [Date, Date]; + domain(domain: [Date, Date]): this; + domain(domainAccessor: (values: ArrayLike) => [Date, Date]): this; + + thresholds(): ThresholdDateArrayGenerator; + /** + * Set the array of values to be used as thresholds in determining the bins. + * + * Any threshold values outside the domain are ignored. The first bin.x0 is always equal to the minimum domain value, + * and the last bin.x1 is always equal to the maximum domain value. + * + * @param thresholds Array of threshold values used for binning. The elements must + * be of the same type as the materialized values of the histogram. + */ + thresholds(thresholds: ArrayLike): this; + /** + * Set a threshold accessor function, which returns the array of values to be used as + * thresholds in determining the bins. + * + * Any threshold values outside the domain are ignored. The first bin.x0 is always equal to the minimum domain value, + * and the last bin.x1 is always equal to the maximum domain value. + * + * @param thresholds A function which accepts as arguments the array of materialized values, and + * optionally the domain minimum and maximum. The function calculates and returns the array of values to be used as + * thresholds in determining the bins. + */ + thresholds(thresholds: ThresholdDateArrayGenerator): this; +} + +export interface HistogramGeneratorNumber extends HistogramCommon { + domain(): (values: ArrayLike) => [number, number] | [undefined, undefined]; + domain(domain: [number, number]): this; + domain(domainAccessor: (values: ArrayLike) => [number, number] | [undefined, undefined]): this; + + thresholds(): ThresholdCountGenerator | ThresholdNumberArrayGenerator; + /** + * Divide the domain uniformly into approximately count bins. IMPORTANT: This threshold + * setting approach only works, when the materialized values are numbers! + * + * Any threshold values outside the domain are ignored. The first bin.x0 is always equal to the minimum domain value, + * and the last bin.x1 is always equal to the maximum domain value. + * + * @param count The desired number of uniform bins. + */ + thresholds(count: number): this; + /** + * Set a threshold accessor function, which returns the desired number of bins. + * Divides the domain uniformly into approximately count bins. IMPORTANT: This threshold + * setting approach only works, when the materialized values are numbers! + * + * Any threshold values outside the domain are ignored. The first bin.x0 is always equal to the minimum domain value, + * and the last bin.x1 is always equal to the maximum domain value. + * + * @param count A function which accepts as arguments the array of materialized values, and + * optionally the domain minimum and maximum. The function calculates and returns the suggested + * number of bins. + */ + thresholds(count: ThresholdCountGenerator): this; + /** + * Set the array of values to be used as thresholds in determining the bins. + * + * Any threshold values outside the domain are ignored. The first bin.x0 is always equal to the minimum domain value, + * and the last bin.x1 is always equal to the maximum domain value. + * + * @param thresholds Array of threshold values used for binning. The elements must + * be of the same type as the materialized values of the histogram. + */ + thresholds(thresholds: ArrayLike): this; + /** + * Set a threshold accessor function, which returns the array of values to be used as + * thresholds in determining the bins. + * + * Any threshold values outside the domain are ignored. The first bin.x0 is always equal to the minimum domain value, + * and the last bin.x1 is always equal to the maximum domain value. + * + * @param thresholds A function which accepts as arguments the array of materialized values, and + * optionally the domain minimum and maximum. The function calculates and returns the array of values to be used as + * thresholds in determining the bins. + */ + thresholds(thresholds: ThresholdNumberArrayGenerator): this; +} + +export function histogram(): HistogramGeneratorNumber; +export function histogram(): HistogramGeneratorNumber; +export function histogram(): HistogramGeneratorDate; + +/** + * @deprecated Do not use Value generic which mixes number and Date types. Use either number or Date + * (in combination with undefined, as applicable) to obtain a type-specific histogram generator. + */ +export function histogram(): HistogramGenerator; + +// -------------------------------------------------------------------------------------- +// Histogram Thresholds +// -------------------------------------------------------------------------------------- + +export function thresholdFreedmanDiaconis(values: ArrayLike, min: number, max: number): number; // of type ThresholdCountGenerator + +export function thresholdScott(values: ArrayLike, min: number, max: number): number; // of type ThresholdCountGenerator + +export function thresholdSturges(values: ArrayLike): number; // of type ThresholdCountGenerator diff --git a/types/d3-array/v1/tsconfig.json b/types/d3-array/v1/tsconfig.json new file mode 100644 index 0000000000..978bc1a042 --- /dev/null +++ b/types/d3-array/v1/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "d3-array-tests.ts" + ] +} \ No newline at end of file diff --git a/types/d3-array/v1/tslint.json b/types/d3-array/v1/tslint.json new file mode 100644 index 0000000000..54efb0b84e --- /dev/null +++ b/types/d3-array/v1/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "unified-signatures": false, + "no-unnecessary-generics": false + } +} diff --git a/types/d3/tsconfig.json b/types/d3/tsconfig.json index bc3e8cf886..9a4848b338 100644 --- a/types/d3/tsconfig.json +++ b/types/d3/tsconfig.json @@ -13,6 +13,11 @@ "typeRoots": [ "../" ], + "paths": { + "d3-array": [ + "d3-array/v1" + ] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/d3/v4/tsconfig.json b/types/d3/v4/tsconfig.json index bf267af99d..6b2cee09dd 100644 --- a/types/d3/v4/tsconfig.json +++ b/types/d3/v4/tsconfig.json @@ -19,6 +19,9 @@ ], "d3": [ "d3/v4" + ], + "d3-array": [ + "d3-array/v1" ] }, "types": [], From a9867db3728248437c89851894be42301160f6e3 Mon Sep 17 00:00:00 2001 From: Hugues Stefanski Date: Sun, 3 Feb 2019 09:12:40 +0100 Subject: [PATCH 009/710] d3-array v2 : fix path mapping --- types/d3-array/v1/tsconfig.json | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/types/d3-array/v1/tsconfig.json b/types/d3-array/v1/tsconfig.json index 978bc1a042..3edd84862c 100644 --- a/types/d3-array/v1/tsconfig.json +++ b/types/d3-array/v1/tsconfig.json @@ -14,6 +14,11 @@ "../../" ], "types": [], + "paths": { + "d3-array": [ + "d3-array/v1" + ] + }, "noEmit": true, "forceConsistentCasingInFileNames": true }, From 8a7b21dd73cdf6c0bd44aab2fb12d8d97c3af922 Mon Sep 17 00:00:00 2001 From: Hugues Stefanski Date: Sun, 3 Feb 2019 09:21:26 +0100 Subject: [PATCH 010/710] d3-array v2.0 : fixed c3 paths --- types/c3/tsconfig.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/c3/tsconfig.json b/types/c3/tsconfig.json index aa923e91c0..c1485cd666 100644 --- a/types/c3/tsconfig.json +++ b/types/c3/tsconfig.json @@ -11,7 +11,8 @@ "types": [], "paths": { "d3-scale": ["d3-scale/v1"], - "d3": ["d3/v4"] + "d3": ["d3/v4"], + "d3-array": ["d3-array/v1"], }, "noEmit": true, "forceConsistentCasingInFileNames": true From 597464103021eeeac805309ba44547e0d63f0e61 Mon Sep 17 00:00:00 2001 From: Hugues Stefanski Date: Sun, 3 Feb 2019 09:24:59 +0100 Subject: [PATCH 011/710] d3-array v2.0 : Deleted useless comma --- types/c3/tsconfig.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/c3/tsconfig.json b/types/c3/tsconfig.json index c1485cd666..60849b491f 100644 --- a/types/c3/tsconfig.json +++ b/types/c3/tsconfig.json @@ -12,7 +12,7 @@ "paths": { "d3-scale": ["d3-scale/v1"], "d3": ["d3/v4"], - "d3-array": ["d3-array/v1"], + "d3-array": ["d3-array/v1"] }, "noEmit": true, "forceConsistentCasingInFileNames": true From 31edcdfd3a32356d0d0b0482a8af404e9c6e29ba Mon Sep 17 00:00:00 2001 From: Hugues Stefanski Date: Sun, 3 Feb 2019 09:37:07 +0100 Subject: [PATCH 012/710] d3-array v2 : updated d3Kit --- types/d3kit/tsconfig.json | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/types/d3kit/tsconfig.json b/types/d3kit/tsconfig.json index 40e266f6f9..79051ab233 100644 --- a/types/d3kit/tsconfig.json +++ b/types/d3kit/tsconfig.json @@ -13,6 +13,11 @@ "typeRoots": [ "../" ], + "paths": { + "d3-array": [ + "d3-array/v1" + ] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true From a07a4f7b5502d67a75ee9250d0e70a203f12914e Mon Sep 17 00:00:00 2001 From: Hugues Stefanski Date: Sun, 3 Feb 2019 10:08:13 +0100 Subject: [PATCH 013/710] d3-array v2 : fixed react-faux-dom --- types/react-faux-dom/tsconfig.json | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/types/react-faux-dom/tsconfig.json b/types/react-faux-dom/tsconfig.json index 198db32576..ed6a386404 100644 --- a/types/react-faux-dom/tsconfig.json +++ b/types/react-faux-dom/tsconfig.json @@ -13,6 +13,11 @@ "typeRoots": [ "../" ], + "paths": { + "d3-array": [ + "d3-array/v1" + ] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true, From 211311f18c28e930a893d94a4cdf2d9c4114668e Mon Sep 17 00:00:00 2001 From: Hugues Stefanski Date: Sun, 3 Feb 2019 10:15:30 +0100 Subject: [PATCH 014/710] d3-arrray v2.0 : fixed reference in venn --- types/venn/tsconfig.json | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/types/venn/tsconfig.json b/types/venn/tsconfig.json index 1c2dcb77e6..4981507227 100644 --- a/types/venn/tsconfig.json +++ b/types/venn/tsconfig.json @@ -13,6 +13,11 @@ "typeRoots": [ "../" ], + "paths": { + "d3-array": [ + "d3-array/v1" + ] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true From 6bbbd1695a47f0d646b23798f33a79df7bad8911 Mon Sep 17 00:00:00 2001 From: Hugues Stefanski Date: Sun, 3 Feb 2019 15:09:56 +0100 Subject: [PATCH 015/710] d3-array v2 : Replace ArrayLike by Iterable --- types/d3-array/d3-array-tests.ts | 28 ++++----- types/d3-array/index.d.ts | 100 +++++++++++++++---------------- 2 files changed, 64 insertions(+), 64 deletions(-) diff --git a/types/d3-array/d3-array-tests.ts b/types/d3-array/d3-array-tests.ts index 381d49869c..ab6338b965 100644 --- a/types/d3-array/d3-array-tests.ts +++ b/types/d3-array/d3-array-tests.ts @@ -70,7 +70,7 @@ const mixedObjectArray = [ ]; const mixedObjectOrUndefinedArray = [...mixedObjectArray, undefined]; -const mixedObjectArrayLike = mixedObjectArray as ArrayLike; +const mixedObjectArrayLike = mixedObjectArray as Iterable; let typedArray = Uint8Array.from(numbersArray); let readonlyNumbersArray = numbersArray as ReadonlyArray; @@ -81,55 +81,55 @@ const readonlyDateArray = dateArray as ReadonlyArray; const readonlyMixedObjectArray = mixedObjectArray as ReadonlyArray; const readonlyMixedObjectOrUndefinedArray = mixedObjectOrUndefinedArray as ReadonlyArray; -function accessorMixedObjectToNum(datum: MixedObject, index: number, array: ArrayLike): number { +function accessorMixedObjectToNum(datum: MixedObject, index: number, array: Iterable): number { return datum.num; } -function accessorMixedObjectToStr(datum: MixedObject, index: number, array: ArrayLike): string { +function accessorMixedObjectToStr(datum: MixedObject, index: number, array: Iterable): string { return datum.str; } -function accessorMixedObjectToNumeric(datum: MixedObject, index: number, array: ArrayLike): NumCoercible { +function accessorMixedObjectToNumeric(datum: MixedObject, index: number, array: Iterable): NumCoercible { return datum.numeric; } -function accessorMixedObjectToDate(datum: MixedObject, index: number, array: ArrayLike): Date { +function accessorMixedObjectToDate(datum: MixedObject, index: number, array: Iterable): Date { return datum.date; } -function accessorMixedObjectToNumOrUndefined(datum: MixedObject | undefined, index: number, array: ArrayLike): number | undefined | null { +function accessorMixedObjectToNumOrUndefined(datum: MixedObject | undefined, index: number, array: Iterable): number | undefined | null { return datum ? datum.num : undefined; } -function accessorMixedObjectToStrOrUndefined(datum: MixedObject | undefined, index: number, array: ArrayLike): string | undefined | null { +function accessorMixedObjectToStrOrUndefined(datum: MixedObject | undefined, index: number, array: Iterable): string | undefined | null { return datum ? datum.str : undefined; } -function accessorLikeMixedObjectToNum(datum: MixedObject, index: number, array: ArrayLike): number { +function accessorLikeMixedObjectToNum(datum: MixedObject, index: number, array: Iterable): number { return datum.num; } -function accessorLikeMixedObjectToStr(datum: MixedObject, index: number, array: ArrayLike): string { +function accessorLikeMixedObjectToStr(datum: MixedObject, index: number, array: Iterable): string { return datum.str; } -function accessorLikeMixedObjectToNumeric(datum: MixedObject, index: number, array: ArrayLike): NumCoercible { +function accessorLikeMixedObjectToNumeric(datum: MixedObject, index: number, array: Iterable): NumCoercible { return datum.numeric; } -function accessorLikeMixedObjectToDate(datum: MixedObject, index: number, array: ArrayLike): Date { +function accessorLikeMixedObjectToDate(datum: MixedObject, index: number, array: Iterable): Date { return datum.date; } -function accessorLikeMixedObjectToNumOrUndefined(datum: MixedObject | undefined, index: number, array: ArrayLike): number | undefined | null { +function accessorLikeMixedObjectToNumOrUndefined(datum: MixedObject | undefined, index: number, array: Iterable): number | undefined | null { return datum ? datum.num : undefined; } -function accessorLikeMixedObjectToStrOrUndefined(datum: MixedObject | undefined, index: number, array: ArrayLike): string | undefined | null { +function accessorLikeMixedObjectToStrOrUndefined(datum: MixedObject | undefined, index: number, array: Iterable): string | undefined | null { return datum ? datum.str : undefined; } -function accessorReadOnlyMixedObjectToNumOrUndefined(datum: MixedObject | undefined, index: number, array: ArrayLike): number | undefined | null { +function accessorReadOnlyMixedObjectToNumOrUndefined(datum: MixedObject | undefined, index: number, array: Iterable): number | undefined | null { return datum ? datum.num : undefined; } diff --git a/types/d3-array/index.d.ts b/types/d3-array/index.d.ts index 7971478581..b7949ec870 100644 --- a/types/d3-array/index.d.ts +++ b/types/d3-array/index.d.ts @@ -33,142 +33,142 @@ export interface Numeric { /** * Return the maximum value in the array of strings using natural order. */ -export function max(array: ArrayLike): string | undefined; +export function max(array: Iterable): string | undefined; /** * Return the maximum value in the array of numbers using natural order. */ -export function max(array: ArrayLike): T | undefined; +export function max(array: Iterable): T | undefined; /** * Return the maximum value in the array using natural order and a projection function to map values to strings. */ -export function max(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => string | undefined | null): string | undefined; +export function max(array: Iterable, accessor: (datum: T, index: number, array: Iterable) => string | undefined | null): string | undefined; /** * Return the maximum value in the array using natural order and a projection function to map values to easily-sorted values. */ -export function max(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => U | undefined | null): U | undefined; +export function max(array: Iterable, accessor: (datum: T, index: number, array: Iterable) => U | undefined | null): U | undefined; /** * Return the minimum value in the array using natural order. */ -export function min(array: ArrayLike): string | undefined; +export function min(array: Iterable): string | undefined; /** * Return the minimum value in the array using natural order. */ -export function min(array: ArrayLike): T | undefined; +export function min(array: Iterable): T | undefined; /** * Return the minimum value in the array using natural order. */ -export function min(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => string | undefined | null): string | undefined; +export function min(array: Iterable, accessor: (datum: T, index: number, array: Iterable) => string | undefined | null): string | undefined; /** * Return the minimum value in the array using natural order. */ -export function min(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => U | undefined | null): U | undefined; +export function min(array: Iterable, accessor: (datum: T, index: number, array: Iterable) => U | undefined | null): U | undefined; /** * Return the min and max simultaneously. */ -export function extent(array: ArrayLike): [string, string] | [undefined, undefined]; +export function extent(array: Iterable): [string, string] | [undefined, undefined]; /** * Return the min and max simultaneously. */ -export function extent(array: ArrayLike): [T, T] | [undefined, undefined]; +export function extent(array: Iterable): [T, T] | [undefined, undefined]; /** * Return the min and max simultaneously. */ -export function extent(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => string | undefined | null): [string, string] | [undefined, undefined]; +export function extent(array: Iterable, accessor: (datum: T, index: number, array: Iterable) => string | undefined | null): [string, string] | [undefined, undefined]; /** * Return the min and max simultaneously. */ -export function extent(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => U | undefined | null): [U, U] | [undefined, undefined]; +export function extent(array: Iterable, accessor: (datum: T, index: number, array: Iterable) => U | undefined | null): [U, U] | [undefined, undefined]; /** * Return the mean of an array of numbers */ -export function mean(array: ArrayLike): number | undefined; +export function mean(array: Iterable): number | undefined; /** * Return the mean of an array of numbers */ -export function mean(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => number | undefined | null): number | undefined; +export function mean(array: Iterable, accessor: (datum: T, index: number, array: Iterable) => number | undefined | null): number | undefined; /** * Return the median of an array of numbers */ -export function median(array: ArrayLike): number | undefined; +export function median(array: Iterable): number | undefined; /** * Return the median of an array of numbers */ -export function median(array: ArrayLike, accessor: (element: T, i: number, array: ArrayLike) => number | undefined | null): number | undefined; +export function median(array: Iterable, accessor: (element: T, i: number, array: Iterable) => number | undefined | null): number | undefined; /** * Returns the p-quantile of an array of numbers */ -export function quantile(array: ArrayLike, p: number): number | undefined; +export function quantile(array: Iterable, p: number): number | undefined; -export function quantile(array: ArrayLike, p: number, accessor: (element: T, i: number, array: ArrayLike) => number | undefined | null): number | undefined; +export function quantile(array: Iterable, p: number, accessor: (element: T, i: number, array: Iterable) => number | undefined | null): number | undefined; /** * Compute the sum of an array of numbers. */ -export function sum(array: ArrayLike): number; +export function sum(array: Iterable): number; /** * Compute the sum of an array, using the given accessor to convert values to numbers. */ -export function sum(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => number | undefined | null): number; +export function sum(array: Iterable, accessor: (datum: T, index: number, array: Iterable) => number | undefined | null): number; /** * Compute the standard deviation, defined as the square root of the bias-corrected variance, of the given array of numbers. */ -export function deviation(array: ArrayLike): number | undefined; +export function deviation(array: Iterable): number | undefined; /** * Compute the standard deviation, defined as the square root of the bias-corrected variance, of the given array, * using the given accessor to convert values to numbers. */ -export function deviation(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => number | undefined | null): number | undefined; +export function deviation(array: Iterable, accessor: (datum: T, index: number, array: Iterable) => number | undefined | null): number | undefined; /** * Compute an unbiased estimator of the population variance of the given array of numbers. */ -export function variance(array: ArrayLike): number | undefined; +export function variance(array: Iterable): number | undefined; /** * Compute an unbiased estimator of the population variance of the given array, * using the given accessor to convert values to numbers. */ -export function variance(array: ArrayLike, accessor: (datum: T, index: number, array: ArrayLike) => number | undefined | null): number | undefined; +export function variance(array: Iterable, accessor: (datum: T, index: number, array: Iterable) => number | undefined | null): number | undefined; // -------------------------------------------------------------------------------------- // Searching Arrays // -------------------------------------------------------------------------------------- -export function scan(array: ArrayLike, comparator?: (a: number, b: number) => number): number | undefined; -export function scan(array: ArrayLike, comparator: (a: T, b: T) => number): number | undefined; +export function scan(array: Iterable, comparator?: (a: number, b: number) => number): number | undefined; +export function scan(array: Iterable, comparator: (a: T, b: T) => number): number | undefined; -export function bisectLeft(array: ArrayLike, x: number, lo?: number, hi?: number): number; -export function bisectLeft(array: ArrayLike, x: string, lo?: number, hi?: number): number; -export function bisectLeft(array: ArrayLike, x: Date, lo?: number, hi?: number): number; +export function bisectLeft(array: Iterable, x: number, lo?: number, hi?: number): number; +export function bisectLeft(array: Iterable, x: string, lo?: number, hi?: number): number; +export function bisectLeft(array: Iterable, x: Date, lo?: number, hi?: number): number; -export function bisectRight(array: ArrayLike, x: number, lo?: number, hi?: number): number; -export function bisectRight(array: ArrayLike, x: string, lo?: number, hi?: number): number; -export function bisectRight(array: ArrayLike, x: Date, lo?: number, hi?: number): number; +export function bisectRight(array: Iterable, x: number, lo?: number, hi?: number): number; +export function bisectRight(array: Iterable, x: string, lo?: number, hi?: number): number; +export function bisectRight(array: Iterable, x: Date, lo?: number, hi?: number): number; export const bisect: typeof bisectRight; export interface Bisector { - left(array: ArrayLike, x: U, lo?: number, hi?: number): number; - right(array: ArrayLike, x: U, lo?: number, hi?: number): number; + left(array: Iterable, x: U, lo?: number, hi?: number): number; + right(array: Iterable, x: U, lo?: number, hi?: number): number; } export function bisector(comparator: (a: T, b: U) => number): Bisector; @@ -180,7 +180,7 @@ export function bisector(accessor: (x: T) => U): Bisector; * @param array The array to partially sort (in place). * @param k The middle index for partial sorting. */ -export function quickselect(array: ArrayLike, k: number): T[]; +export function quickselect(array: Iterable, k: number): T[]; /** * Rearranges items so that all items in the [left, k] are the smallest. The k-th element will have the (k - left + 1)-th smallest value in [left, right]. @@ -189,7 +189,7 @@ export function quickselect(array: ArrayLike, k: number): T[]; * @param k The middle index for partial sorting. * @param left The left index of the range to sort. */ -export function quickselect(array: ArrayLike, k: number, left: number): T[]; +export function quickselect(array: Iterable, k: number, left: number): T[]; /** * Rearranges items so that all items in the [left, k] are the smallest. The k-th element will have the (k - left + 1)-th smallest value in [left, right]. @@ -199,7 +199,7 @@ export function quickselect(array: ArrayLike, k: number, left: number): T[ * @param left The left index of the range to sort. * @param right The right index. */ -export function quickselect(array: ArrayLike, k: number, left: number, right: number): T[]; +export function quickselect(array: Iterable, k: number, left: number, right: number): T[]; /** * Rearranges items so that all items in the [left, k] are the smallest. The k-th element will have the (k - left + 1)-th smallest value in [left, right]. @@ -210,7 +210,7 @@ export function quickselect(array: ArrayLike, k: number, left: number, rig * @param right The right index. * @param compare The compare function. */ -export function quickselect(array: ArrayLike, k: number, left: number, right: number, compare: (a: Primitive | undefined, b: Primitive | undefined) => number): T[]; +export function quickselect(array: Iterable, k: number, left: number, right: number, compare: (a: Primitive | undefined, b: Primitive | undefined) => number): T[]; // NB. this is limited to primitive values due to D3's use of the <, >, and >= operators. Results get weird for object instances. /** @@ -233,7 +233,7 @@ export function descending(a: Primitive | undefined, b: Primitive | undefined): * @param a The array to group. * @param key The key function. */ -export function group(a: ArrayLike, key: (value: TObject) => TKey): Map; +export function group(a: Iterable, key: (value: TObject) => TKey): Map; /** * Groups and reduces the specified array of values into a Map from key to value. @@ -242,7 +242,7 @@ export function group(a: ArrayLike, key: (value: TObject * @param reduce The reduce function. * @param key The key function. */ -export function rollup(a: ArrayLike, reduce: (value: TObject[]) => TReduce, key: (value: TObject) => TKey): Map; +export function rollup(a: Iterable, reduce: (value: TObject[]) => TReduce, key: (value: TObject) => TKey): Map; /** * Returns the Cartesian product of the two arrays a and b. @@ -252,7 +252,7 @@ export function rollup(a: ArrayLike, reduce: (v * @param a First input array. * @param b Second input array. */ -export function cross(a: ArrayLike, b: ArrayLike): Array<[S, T]>; +export function cross(a: Iterable, b: ArrayLike): Array<[S, T]>; /** * Returns the Cartesian product of the two arrays a and b. @@ -263,12 +263,12 @@ export function cross(a: ArrayLike, b: ArrayLike): Array<[S, T]>; * @param b Second input array. * @param reducer A reducer function taking as input an element from "a" and "b" and returning a reduced value. */ -export function cross(a: ArrayLike, b: ArrayLike, reducer: (a: S, b: T) => U): U[]; +export function cross(a: Iterable, b: Iterable, reducer: (a: S, b: T) => U): U[]; /** * Merges the specified arrays into a single array. */ -export function merge(arrays: ArrayLike>): T[]; +export function merge(arrays: Iterable>): T[]; /** * For each adjacent pair of elements in the specified array, returns a new array of tuples of elements i and i - 1. @@ -276,7 +276,7 @@ export function merge(arrays: ArrayLike>): T[]; * * @param array Array of input elements */ -export function pairs(array: ArrayLike): Array<[T, T]>; +export function pairs(array: Iterable): Array<[T, T]>; /** * For each adjacent pair of elements in the specified array, in order, invokes the specified reducer function passing the element i and element i - 1. * Returns the resulting array of pair-wise reduced elements. @@ -285,7 +285,7 @@ export function pairs(array: ArrayLike): Array<[T, T]>; * @param array Array of input elements * @param reducer A reducer function taking as input to adjacent elements of the input array and returning a reduced value. */ -export function pairs(array: ArrayLike, reducer: (a: T, b: T) => U): U[]; +export function pairs(array: Iterable, reducer: (a: T, b: T) => U): U[]; /** * Returns a permutation of the specified array using the specified array of indexes. @@ -415,14 +415,14 @@ export type ThresholdArrayGenerator = ThresholdNumberArrayGenerator; * @deprecated Use `HistogramGeneratorNumber` for `number` values and `HistogramGeneratorDate for `Date` values. */ export interface HistogramGenerator { - (data: ArrayLike): Array>; + (data: Iterable): Array>; - value(): (d: Datum, i: number, data: ArrayLike) => Value; - value(valueAccessor: (d: Datum, i: number, data: ArrayLike) => Value): this; + value(): (d: Datum, i: number, data: Iterable) => Value; + value(valueAccessor: (d: Datum, i: number, data: Iterable) => Value): this; - domain(): (values: ArrayLike) => [Value, Value] | [undefined, undefined]; + domain(): (values: Iterable) => [Value, Value] | [undefined, undefined]; domain(domain: [Value, Value]): this; - domain(domainAccessor: (values: ArrayLike) => [Value, Value] | [undefined, undefined]): this; + domain(domainAccessor: (values: Iterable) => [Value, Value] | [undefined, undefined]): this; /** * Set the array of values to be used as thresholds in determining the bins. From 5bf8a129ba7b22f1df1bb8fb140994d795b87477 Mon Sep 17 00:00:00 2001 From: Hugues Stefanski Date: Sun, 3 Feb 2019 15:29:04 +0100 Subject: [PATCH 016/710] Replaced d3-array v1 tests with previous version --- types/d3-array/v1/d3-array-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/d3-array/v1/d3-array-tests.ts b/types/d3-array/v1/d3-array-tests.ts index 66d99dc9b1..11f208f869 100644 --- a/types/d3-array/v1/d3-array-tests.ts +++ b/types/d3-array/v1/d3-array-tests.ts @@ -779,7 +779,7 @@ histoMixedObject_Date = histoMixedObject_Date.domain(timeScale.domain()); // fai domainFnDate = histoMixedObject_Date.domain(); histoMixedObject_DateOrUndefined = histoMixedObject_DateOrUndefined.domain([new Date(2014, 3, 15), new Date(2017, 4, 15)]); histoMixedObject_DateOrUndefined = histoMixedObject_DateOrUndefined.domain([domain[0], domain[domain.length]]); -histoMixedObject_DateOrUndefined = histoMixedObject_DateOrUndefined.domain((values) => [values[0]!, values[values.length]!]); +histoMixedObject_DateOrUndefined = histoMixedObject_DateOrUndefined.domain((values) => [values[0]!, values[values.length]!]); // thresholds(...) ------------------------------------------------------------- From 61d9b36abe11b677132428c2dc1544b407119c9f Mon Sep 17 00:00:00 2001 From: Hugues Stefanski Date: Sun, 3 Feb 2019 15:43:37 +0100 Subject: [PATCH 017/710] d3-array v2.0 : changed typing for testing purpose --- types/d3-array/v1/d3-array-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/d3-array/v1/d3-array-tests.ts b/types/d3-array/v1/d3-array-tests.ts index 11f208f869..01529191b8 100644 --- a/types/d3-array/v1/d3-array-tests.ts +++ b/types/d3-array/v1/d3-array-tests.ts @@ -608,7 +608,7 @@ const testObject = { }; const p1: Array = d3Array.permute(testObject, ['name', 'val', 'when', 'more']); -const p2: Array = d3Array.permute(testObject, ['when', 'more']); +const p2: Array = d3Array.permute(testObject, ['when', 'more']); // $ExpectError const p3 = d3Array.permute(testObject, ['when', 'unknown']); From a9fed9d7eb4ac99d562422f989f4251a4019b259 Mon Sep 17 00:00:00 2001 From: Hugues Stefanski Date: Sun, 3 Feb 2019 15:54:47 +0100 Subject: [PATCH 018/710] d3-array v2.0 : augmented type --- types/d3-array/d3-array-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/d3-array/d3-array-tests.ts b/types/d3-array/d3-array-tests.ts index 381d49869c..a4d21546d9 100644 --- a/types/d3-array/d3-array-tests.ts +++ b/types/d3-array/d3-array-tests.ts @@ -631,7 +631,7 @@ const testObject = { }; const p1: Array = d3Array.permute(testObject, ['name', 'val', 'when', 'more']); -const p2: Array = d3Array.permute(testObject, ['when', 'more']); +const p2: Array = d3Array.permute(testObject, ['when', 'more']); // $ExpectError const p3 = d3Array.permute(testObject, ['when', 'unknown']); From 52727c99f10e6b7a5b563b982ca0b86cdae0d248 Mon Sep 17 00:00:00 2001 From: Hugues Stefanski Date: Wed, 20 Feb 2019 18:39:17 +0100 Subject: [PATCH 019/710] d3-array : removed deprecated Corrected ArrayLike vs Iterable --- types/d3-array/d3-array-tests.ts | 5 ----- types/d3-array/index.d.ts | 26 +++++++++++++------------- 2 files changed, 13 insertions(+), 18 deletions(-) diff --git a/types/d3-array/d3-array-tests.ts b/types/d3-array/d3-array-tests.ts index 04478567e6..f202ab2fb9 100644 --- a/types/d3-array/d3-array-tests.ts +++ b/types/d3-array/d3-array-tests.ts @@ -957,8 +957,3 @@ num = d3Array.thresholdScott(readonlyNumbersArray, -1, 234); num = d3Array.thresholdSturges(numbersArray); num = d3Array.thresholdSturges(typedArray); num = d3Array.thresholdSturges(readonlyNumbersArray); - -// Deprecated ================================================================== - -const histDeprecatedNumber: d3Array.HistogramGenerator = d3Array.histogram(); -const histDeprecatedDate: d3Array.HistogramGenerator = d3Array.histogram(); diff --git a/types/d3-array/index.d.ts b/types/d3-array/index.d.ts index b7949ec870..1e73813965 100644 --- a/types/d3-array/index.d.ts +++ b/types/d3-array/index.d.ts @@ -156,19 +156,19 @@ export function variance(array: Iterable, accessor: (datum: T, index: numb export function scan(array: Iterable, comparator?: (a: number, b: number) => number): number | undefined; export function scan(array: Iterable, comparator: (a: T, b: T) => number): number | undefined; -export function bisectLeft(array: Iterable, x: number, lo?: number, hi?: number): number; -export function bisectLeft(array: Iterable, x: string, lo?: number, hi?: number): number; -export function bisectLeft(array: Iterable, x: Date, lo?: number, hi?: number): number; +export function bisectLeft(array: ArrayLike, x: number, lo?: number, hi?: number): number; +export function bisectLeft(array: ArrayLike, x: string, lo?: number, hi?: number): number; +export function bisectLeft(array: ArrayLike, x: Date, lo?: number, hi?: number): number; -export function bisectRight(array: Iterable, x: number, lo?: number, hi?: number): number; -export function bisectRight(array: Iterable, x: string, lo?: number, hi?: number): number; -export function bisectRight(array: Iterable, x: Date, lo?: number, hi?: number): number; +export function bisectRight(array: ArrayLike, x: number, lo?: number, hi?: number): number; +export function bisectRight(array: ArrayLike, x: string, lo?: number, hi?: number): number; +export function bisectRight(array: ArrayLike, x: Date, lo?: number, hi?: number): number; export const bisect: typeof bisectRight; export interface Bisector { - left(array: Iterable, x: U, lo?: number, hi?: number): number; - right(array: Iterable, x: U, lo?: number, hi?: number): number; + left(array: ArrayLike, x: U, lo?: number, hi?: number): number; + right(array: ArrayLike, x: U, lo?: number, hi?: number): number; } export function bisector(comparator: (a: T, b: U) => number): Bisector; @@ -180,7 +180,7 @@ export function bisector(accessor: (x: T) => U): Bisector; * @param array The array to partially sort (in place). * @param k The middle index for partial sorting. */ -export function quickselect(array: Iterable, k: number): T[]; +export function quickselect(array: ArrayLike, k: number): T[]; /** * Rearranges items so that all items in the [left, k] are the smallest. The k-th element will have the (k - left + 1)-th smallest value in [left, right]. @@ -189,7 +189,7 @@ export function quickselect(array: Iterable, k: number): T[]; * @param k The middle index for partial sorting. * @param left The left index of the range to sort. */ -export function quickselect(array: Iterable, k: number, left: number): T[]; +export function quickselect(array: ArrayLike, k: number, left: number): T[]; /** * Rearranges items so that all items in the [left, k] are the smallest. The k-th element will have the (k - left + 1)-th smallest value in [left, right]. @@ -199,7 +199,7 @@ export function quickselect(array: Iterable, k: number, left: number): T[] * @param left The left index of the range to sort. * @param right The right index. */ -export function quickselect(array: Iterable, k: number, left: number, right: number): T[]; +export function quickselect(array: ArrayLike, k: number, left: number, right: number): T[]; /** * Rearranges items so that all items in the [left, k] are the smallest. The k-th element will have the (k - left + 1)-th smallest value in [left, right]. @@ -210,7 +210,7 @@ export function quickselect(array: Iterable, k: number, left: number, righ * @param right The right index. * @param compare The compare function. */ -export function quickselect(array: Iterable, k: number, left: number, right: number, compare: (a: Primitive | undefined, b: Primitive | undefined) => number): T[]; +export function quickselect(array: ArrayLike, k: number, left: number, right: number, compare: (a: Primitive | undefined, b: Primitive | undefined) => number): T[]; // NB. this is limited to primitive values due to D3's use of the <, >, and >= operators. Results get weird for object instances. /** @@ -252,7 +252,7 @@ export function rollup(a: Iterable, reduce: (va * @param a First input array. * @param b Second input array. */ -export function cross(a: Iterable, b: ArrayLike): Array<[S, T]>; +export function cross(a: Iterable, b: Iterable): Array<[S, T]>; /** * Returns the Cartesian product of the two arrays a and b. From 4e92922dea7ea1752461fa6ae001532977af3b94 Mon Sep 17 00:00:00 2001 From: Hugues Stefanski Date: Wed, 20 Feb 2019 18:46:44 +0100 Subject: [PATCH 020/710] d3-array : fixed last Iterable vs ArrayLike --- types/d3-array/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/d3-array/index.d.ts b/types/d3-array/index.d.ts index 1e73813965..6d128323f5 100644 --- a/types/d3-array/index.d.ts +++ b/types/d3-array/index.d.ts @@ -474,9 +474,9 @@ export interface HistogramGeneratorDate e } export interface HistogramGeneratorNumber extends HistogramCommon { - domain(): (values: ArrayLike) => [number, number] | [undefined, undefined]; + domain(): (values: Iterable) => [number, number] | [undefined, undefined]; domain(domain: [number, number]): this; - domain(domainAccessor: (values: ArrayLike) => [number, number] | [undefined, undefined]): this; + domain(domainAccessor: (values: Iterable) => [number, number] | [undefined, undefined]): this; thresholds(): ThresholdCountGenerator | ThresholdNumberArrayGenerator; /** From bfc6fa1f4f7b9bb2bcda4f917d84d75563934f68 Mon Sep 17 00:00:00 2001 From: Hugues Stefanski Date: Wed, 20 Feb 2019 19:01:40 +0100 Subject: [PATCH 021/710] Re added npm url --- types/d3-array/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/d3-array/index.d.ts b/types/d3-array/index.d.ts index bc271ccffd..083fa77940 100644 --- a/types/d3-array/index.d.ts +++ b/types/d3-array/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for D3JS d3-array module 2.0 -// Project: https://github.com/d3/d3-array +// Project: https://github.com/d3/d3-array, https://d3js.org/d3-array // Definitions by: Alex Ford // Boris Yankov // Tom Wanzek From c746ba11416c96d340a909ec6b15f364757dbab9 Mon Sep 17 00:00:00 2001 From: Hugues Stefanski Date: Wed, 20 Feb 2019 21:00:03 +0100 Subject: [PATCH 022/710] d3-array : removed deprecated methods --- types/d3-array/index.d.ts | 36 ------------------------------------ 1 file changed, 36 deletions(-) diff --git a/types/d3-array/index.d.ts b/types/d3-array/index.d.ts index 083fa77940..5de77e4e10 100644 --- a/types/d3-array/index.d.ts +++ b/types/d3-array/index.d.ts @@ -406,36 +406,6 @@ export type ThresholdNumberArrayGenerator = export type ThresholdDateArrayGenerator = (values: ArrayLike, min: Date, max: Date) => Value[]; -/** - * @deprecated Use ThresholdNumberArrayGenerator or ThresholdDateArrayGenerator. - */ -export type ThresholdArrayGenerator = ThresholdNumberArrayGenerator; - -/** - * @deprecated Use `HistogramGeneratorNumber` for `number` values and `HistogramGeneratorDate for `Date` values. - */ -export interface HistogramGenerator { - (data: Iterable): Array>; - - value(): (d: Datum, i: number, data: Iterable) => Value; - value(valueAccessor: (d: Datum, i: number, data: Iterable) => Value): this; - - domain(): (values: Iterable) => [Value, Value] | [undefined, undefined]; - domain(domain: [Value, Value]): this; - domain(domainAccessor: (values: Iterable) => [Value, Value] | [undefined, undefined]): this; - - /** - * Set the array of values to be used as thresholds in determining the bins. - * - * Any threshold values outside the domain are ignored. The first bin.x0 is always equal to the minimum domain value, - * and the last bin.x1 is always equal to the maximum domain value. - * - * @param thresholds Array of threshold values used for binning. The elements must - * be of the same type as the materialized values of the histogram. - */ - thresholds(thresholds: ArrayLike): this; -} - export interface HistogramCommon { (data: ArrayLike): Array>; @@ -530,12 +500,6 @@ export function histogram(): HistogramGeneratorNumber; export function histogram(): HistogramGeneratorNumber; export function histogram(): HistogramGeneratorDate; -/** - * @deprecated Do not use Value generic which mixes number and Date types. Use either number or Date - * (in combination with undefined, as applicable) to obtain a type-specific histogram generator. - */ -export function histogram(): HistogramGenerator; - // -------------------------------------------------------------------------------------- // Histogram Thresholds // -------------------------------------------------------------------------------------- From 8484128935801c923936b3afc4095851e2ef104c Mon Sep 17 00:00:00 2001 From: Jonathan Ly Date: Mon, 4 Mar 2019 12:05:55 +1100 Subject: [PATCH 023/710] [react-request] add more types --- types/react-request/index.d.ts | 63 +++++++++++++++++++++++----------- 1 file changed, 43 insertions(+), 20 deletions(-) diff --git a/types/react-request/index.d.ts b/types/react-request/index.d.ts index 0806dda260..a161ff9339 100644 --- a/types/react-request/index.d.ts +++ b/types/react-request/index.d.ts @@ -1,50 +1,73 @@ // Type definitions for react-request 3.1 // Project: https://github.com/jamesplease/react-request // Definitions by: Danny Cochran +// Angus Fretwell +// Jonathan Ly // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 import * as React from 'react'; -export interface RenderProps { - requestName: string; - requestKey: string; - fetching: boolean; - failed: boolean; - error: Error | null; - response: Response | null; - url: string; - data: T | null; +export interface FetchResponse { + url: string; + init: any; + failed: boolean; + requestKey: string; + response: Response | null; + data: T | null; + error: Error | null; + didUnmount: boolean; +} + +export interface RenderProps extends FetchResponse { + requestName: string; + fetching: boolean; + doFetch: DoFetch; } export interface FetchRequestProps extends RequestInit { - lazy?: boolean; - url: string; + lazy?: boolean; + url: string; } export interface FetchProps extends FetchRequestProps { - children?: (renderProps: RenderProps) => React.ReactNode; + afterFetch?: (args: FetchResponse) => void; + transformData?: (data: any) => T; + children?: (renderProps: RenderProps) => React.ReactNode; } +export interface DoFetchOptions extends RequestInit { + url?: string; +} + +export type DoFetch = ( + options?: DoFetchOptions +) => Promise>; + // TODO(dannycochran) RequestKeyOptions, ProxyRequest, fetchDedupe, getRequestKey, isRequestInFlight, clearRequestCache // should all be defined in an adjacent typings directory for fetch-dedupe. export interface RequestKeyOptions { - url?: string; - method?: string; - responseType?: string; - body?: string; + url?: string; + method?: string; + responseType?: string; + body?: string; } export interface ProxyRequest { - requestKey: string; - res: Response; + requestKey: string; + res: Response; } // TODO(dannycochran) Fill out fetchDedupe options. -export function fetchDedupe(input: any, init?: any, dedupeOptions?: any): Promise; +export function fetchDedupe( + input: any, + init?: any, + dedupeOptions?: any +): Promise; + export function getRequestKey(keyOptions?: RequestKeyOptions): string; export function isRequestInFlight(): boolean; export function clearRequestCache(): void; export function clearResponseCache(): void; -export class Fetch extends React.Component> { } +export class Fetch extends React.Component> {} From 46f86b5961f9a625cb91c59abcda9c2ee5b68e43 Mon Sep 17 00:00:00 2001 From: Tyler Krupicka Date: Thu, 7 Mar 2019 13:38:51 -0800 Subject: [PATCH 024/710] update axe-webdriverjs analyze --- types/axe-webdriverjs/axe-webdriverjs-tests.ts | 2 +- types/axe-webdriverjs/index.d.ts | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/types/axe-webdriverjs/axe-webdriverjs-tests.ts b/types/axe-webdriverjs/axe-webdriverjs-tests.ts index 47eeadc8c5..d269b1ef28 100644 --- a/types/axe-webdriverjs/axe-webdriverjs-tests.ts +++ b/types/axe-webdriverjs/axe-webdriverjs-tests.ts @@ -20,7 +20,7 @@ const inTest = async (webDriver: WebDriver) => { .disableRules("rule") .disableRules(["rule", "rule"]) .configure(spec) - .analyze((internalResults: AxeAnalysis) => {}); + .analyze((err: Error, internalResults: AxeAnalysis) => {}); const inapplicable: Result[] = analysis.inapplicable; const incomplete: Result[] = analysis.incomplete; diff --git a/types/axe-webdriverjs/index.d.ts b/types/axe-webdriverjs/index.d.ts index 3c8ae27249..f9d7ed2bbc 100644 --- a/types/axe-webdriverjs/index.d.ts +++ b/types/axe-webdriverjs/index.d.ts @@ -74,7 +74,9 @@ export interface AxeBuilder { * Perform analysis and retrieve results. * @param callback Function to execute when analysis completes. */ - analyze(callback: (results: AxeAnalysis) => void): Promise; + analyze( + callback?: (err: Error, results: AxeAnalysis) => void + ): Promise; } export const AxeBuilder: { From 587f09d9bc235af1ad86d35bb55f60501cb6a645 Mon Sep 17 00:00:00 2001 From: Tyler Krupicka Date: Thu, 7 Mar 2019 14:05:43 -0800 Subject: [PATCH 025/710] axe-webdriverjs increment version --- types/axe-webdriverjs/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/axe-webdriverjs/index.d.ts b/types/axe-webdriverjs/index.d.ts index f9d7ed2bbc..bbd054f7e4 100644 --- a/types/axe-webdriverjs/index.d.ts +++ b/types/axe-webdriverjs/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for axe-webdriverjs 2.0 +// Type definitions for axe-webdriverjs 2.1 // Project: https://github.com/dequelabs/axe-webdriverjs#readme // Definitions by: My Self // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 87632ff8f1032c866cc83884c6a3a8ee117248ca Mon Sep 17 00:00:00 2001 From: Flexmonster Date: Fri, 8 Mar 2019 14:18:01 +0200 Subject: [PATCH 026/710] Updated to 2.7 API --- types/flexmonster/index.d.ts | 104 ++++++++++++++++++++++++++++------- 1 file changed, 85 insertions(+), 19 deletions(-) diff --git a/types/flexmonster/index.d.ts b/types/flexmonster/index.d.ts index fad76ca64d..6d92a20ddc 100644 --- a/types/flexmonster/index.d.ts +++ b/types/flexmonster/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for flexmonster 2.6 +// Type definitions for flexmonster 2.7 // Project: https://flexmonster.com/ // Definitions by: Flexmonster // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -10,7 +10,7 @@ declare const Flexmonster: FlexmonsterConstructor; export = Flexmonster; interface FlexmonsterConstructor { - new (params: Flexmonster.Params): Flexmonster.Pivot; + new(params: Flexmonster.Params): Flexmonster.Pivot; (params: Flexmonster.Params): Flexmonster.Pivot; } @@ -75,7 +75,7 @@ declare namespace Flexmonster { clear(): void; clearFilter(hierarchyName: string): void; clearXMLACache(proxyUrl: string, databaseId: string, callbackHandler: ((reponse: object) => void) | string, cubeId: string, measuresGroupId: string, - username?: string, password?: string): void; + username?: string, password?: string): void; closeFieldsList(): void; collapseAllData(): void; collapseData(hierarchyName: string): void; @@ -93,8 +93,7 @@ declare namespace Flexmonster { getColumns(): Hierarchy[]; getCondition(id: string): ConditionalFormat; getData(options: { slice?: Slice }, callbackHandler: ((rawData: any) => void) | string, updateHandler?: ((rawData: any) => void) | string): void; - getFilter(hierarchyName: string): FilterItem[]; - getFilterProperties(hierarchyName: string): FilterProperties; + getFilter(hierarchyName: string): Filter; getFormat(measureName: string): Format; getMeasures(): Measure[]; getMembers(hierarchyName: string, memberName: string, callbackHandler: ((members: Member[]) => void) | string): Member[]; @@ -123,13 +122,11 @@ declare namespace Flexmonster { removeSelection(): void; runQuery(slice: Slice): void; save(filename: string, destination: string, callbackHandler?: (() => void) | string, url?: string, embedData?: boolean): string; - setBottomX(hierarchyName: string, num: number, measure: MeasureObject): void; - setFilter(hierarchyName: string, items: string[], negation?: boolean): void; + setFilter(hierarchyName: string, filter: Filter): void; setFormat(format: Format, measureName: string): void; setOptions(options: Options): void; setReport(report: Report): void; setSort(hierarchyName: string, sortName: string, customSorting?: string[]): void; - setTopX(hierarchyName: string, num: number, measure: MeasureObject): void; showCharts(type?: string, multiple?: boolean): void; showGrid(): void; showGridAndCharts(type?: string, position?: string, multiple?: boolean): void; @@ -140,18 +137,18 @@ declare namespace Flexmonster { version: string; fusioncharts?: { getData(options: { type: string; slice?: Slice; prepareDataFunction?: (rawData: any) => any }, callbackHandler: ((rawData: any) => void) | string, - updateHandler?: ((rawData: any) => void) | string): void; + updateHandler?: ((rawData: any) => void) | string): void; getNumberFormat(format: object): object; }; googlecharts?: { getData(options: { type?: string; slice?: Slice; prepareDataFunction?: (rawData: any) => any }, callbackHandler: ((rawData: any) => void) | string, - updateHandler?: ((rawData: any) => void) | string): void; + updateHandler?: ((rawData: any) => void) | string): void; getNumberFormat(format: object): object; getNumberFormatPattern(format: object): string; }; highcharts?: { getData(options: { type?: string; slice?: Slice; xAxisType?: string; valuesOnly?: boolean, withDrilldown?: boolean, prepareDataFunction?: (rawData: any) => any }, - callbackHandler: ((rawData: any) => void) | string, updateHandler?: ((rawData: any) => void) | string): void; + callbackHandler: ((rawData: any) => void) | string, updateHandler?: ((rawData: any) => void) | string): void; getAxisFormat(format: object): string; getPointXFormat(format: object): string; getPointYFormat(format: object): string; @@ -194,7 +191,11 @@ declare namespace Flexmonster { username?: string; password?: string; requestHeader?: object; - subquery?: string; + subquery?: string | object; + // elasticsearch + host?: string | string[] | object; + index?: string; + mapping?: object; } interface Slice { @@ -256,6 +257,11 @@ declare namespace Flexmonster { grandTotalsPosition?: string; drillThroughMaxRows?: number; }; + filter?: { + timezoneOffset?: number; + weekOffset?: number; + dateFormat?: string; + }; configuratorActive?: boolean; configuratorButton?: boolean; dateTimezoneOffset?: number; @@ -354,18 +360,78 @@ declare namespace Flexmonster { interface Hierarchy { caption?: string; dimensionName?: string; - filter?: { - members?: string[]; - negation?: boolean; - measure?: MeasureObject; - quantity?: number; - type?: string; - }; + filter?: Filter; sortName?: string; sortOrder?: string[]; uniqueName?: string; } + interface Filter { + members?: string[]; + exclude?: string[]; + include?: string[]; + query?: NumberQuery | LabelQuery | DateQuery | TimeQuery | ValueQuery; + measure?: string | MeasureObject; + } + + interface NumberQuery { + equal?: number; + not_equal?: number; + greater?: number; + greater_equal?: number; + less?: number; + less_equal?: number; + between?: number[]; + not_between?: number[]; + } + + interface LabelQuery { + equal?: string; + not_equal?: string; + begin?: string; + not_begin?: string; + end?: string; + not_end?: string; + contain?: string; + not_contain?: string; + greater?: string; + greater_equal?: string; + less?: string; + less_equal?: string; + between?: string[]; + not_between?: string[]; + } + + interface DateQuery { + equal?: string; + not_equal?: string; + before?: string; + before_equal?: string; + after?: string; + after_equal?: string; + between?: string[]; + not_between?: string[]; + last?: string; + current?: string; + next?: string; + } + + interface TimeQuery { + equal?: string; + not_equal?: string; + greater?: string; + greater_equal?: string; + less?: string; + less_equal?: string; + between?: string[]; + not_between?: string[]; + } + + interface ValueQuery extends NumberQuery { + top?: number; + bottom?: number; + } + interface Measure { uniqueName?: string; active?: boolean; From e632ad855598b9e17604c95f6db657a90d165417 Mon Sep 17 00:00:00 2001 From: Tyler Krupicka Date: Fri, 8 Mar 2019 09:45:28 -0800 Subject: [PATCH 027/710] axe-webdriverjs - error can be null --- types/axe-webdriverjs/axe-webdriverjs-tests.ts | 2 +- types/axe-webdriverjs/index.d.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/axe-webdriverjs/axe-webdriverjs-tests.ts b/types/axe-webdriverjs/axe-webdriverjs-tests.ts index d269b1ef28..14bd0fd0bd 100644 --- a/types/axe-webdriverjs/axe-webdriverjs-tests.ts +++ b/types/axe-webdriverjs/axe-webdriverjs-tests.ts @@ -20,7 +20,7 @@ const inTest = async (webDriver: WebDriver) => { .disableRules("rule") .disableRules(["rule", "rule"]) .configure(spec) - .analyze((err: Error, internalResults: AxeAnalysis) => {}); + .analyze((err: Error | null, internalResults: AxeAnalysis) => {}); const inapplicable: Result[] = analysis.inapplicable; const incomplete: Result[] = analysis.incomplete; diff --git a/types/axe-webdriverjs/index.d.ts b/types/axe-webdriverjs/index.d.ts index bbd054f7e4..c557746a64 100644 --- a/types/axe-webdriverjs/index.d.ts +++ b/types/axe-webdriverjs/index.d.ts @@ -75,7 +75,7 @@ export interface AxeBuilder { * @param callback Function to execute when analysis completes. */ analyze( - callback?: (err: Error, results: AxeAnalysis) => void + callback?: (err: Error | null, results: AxeAnalysis) => void ): Promise; } From bb08f89827df36ddb21ed15061ffdf26165c9bf4 Mon Sep 17 00:00:00 2001 From: Tyler Krupicka Date: Sun, 10 Mar 2019 20:00:07 -0700 Subject: [PATCH 028/710] axe-webdriverjs: try method overloading --- types/axe-webdriverjs/index.d.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/types/axe-webdriverjs/index.d.ts b/types/axe-webdriverjs/index.d.ts index c557746a64..d455e07354 100644 --- a/types/axe-webdriverjs/index.d.ts +++ b/types/axe-webdriverjs/index.d.ts @@ -70,6 +70,13 @@ export interface AxeBuilder { */ configure(config: Spec): this; + /** + * Perform analysis and retrieve results. + * Old API without error parameter for callback + * @param callback Function to execute when analysis completes. + */ + analyze(callback?: (results: AxeAnalysis) => void): Promise; + /** * Perform analysis and retrieve results. * @param callback Function to execute when analysis completes. From 80521fca637bb8c61b4054afd9b6294cb522af26 Mon Sep 17 00:00:00 2001 From: Tyler Krupicka Date: Sun, 10 Mar 2019 20:09:10 -0700 Subject: [PATCH 029/710] axe-wedriverjs: move to unified analyze signature --- types/axe-webdriverjs/index.d.ts | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/types/axe-webdriverjs/index.d.ts b/types/axe-webdriverjs/index.d.ts index d455e07354..1e6323f331 100644 --- a/types/axe-webdriverjs/index.d.ts +++ b/types/axe-webdriverjs/index.d.ts @@ -16,6 +16,9 @@ export interface AxeAnalysis { violations: Result[]; } +type OldAnalyzeCallbackType = (results: AxeAnalysis) => void; +type AnalyzeCallbackType = (err: Error | null, results: AxeAnalysis) => void; + export interface AxeBuilder { /** * Includes a selector in analysis. @@ -70,19 +73,12 @@ export interface AxeBuilder { */ configure(config: Spec): this; - /** - * Perform analysis and retrieve results. - * Old API without error parameter for callback - * @param callback Function to execute when analysis completes. - */ - analyze(callback?: (results: AxeAnalysis) => void): Promise; - /** * Perform analysis and retrieve results. * @param callback Function to execute when analysis completes. */ analyze( - callback?: (err: Error | null, results: AxeAnalysis) => void + callback?: OldAnalyzeCallbackType | AnalyzeCallbackType ): Promise; } From 5cc526244c4df4bed79065135da915767a7c4a9c Mon Sep 17 00:00:00 2001 From: Tyler Krupicka Date: Sun, 10 Mar 2019 20:17:13 -0700 Subject: [PATCH 030/710] axe-webdriverjs: explict exports --- types/axe-webdriverjs/index.d.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/axe-webdriverjs/index.d.ts b/types/axe-webdriverjs/index.d.ts index 1e6323f331..13aeff0fc5 100644 --- a/types/axe-webdriverjs/index.d.ts +++ b/types/axe-webdriverjs/index.d.ts @@ -16,8 +16,8 @@ export interface AxeAnalysis { violations: Result[]; } -type OldAnalyzeCallbackType = (results: AxeAnalysis) => void; -type AnalyzeCallbackType = (err: Error | null, results: AxeAnalysis) => void; +export type DeprecatedAnalyzeCallback = (results: AxeAnalysis) => void; +export type AnalyzeCallback = (err: Error | null, results: AxeAnalysis) => void; export interface AxeBuilder { /** @@ -78,7 +78,7 @@ export interface AxeBuilder { * @param callback Function to execute when analysis completes. */ analyze( - callback?: OldAnalyzeCallbackType | AnalyzeCallbackType + callback?: DeprecatedAnalyzeCallback | AnalyzeCallback ): Promise; } From fc03469ff506dc28501c3d1c7916d69fa0e67a2d Mon Sep 17 00:00:00 2001 From: Tyler Krupicka Date: Sun, 10 Mar 2019 20:20:48 -0700 Subject: [PATCH 031/710] axe-webdriverjs: add deprecated analyze test --- types/axe-webdriverjs/axe-webdriverjs-tests.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/types/axe-webdriverjs/axe-webdriverjs-tests.ts b/types/axe-webdriverjs/axe-webdriverjs-tests.ts index 14bd0fd0bd..963e430c62 100644 --- a/types/axe-webdriverjs/axe-webdriverjs-tests.ts +++ b/types/axe-webdriverjs/axe-webdriverjs-tests.ts @@ -22,6 +22,10 @@ const inTest = async (webDriver: WebDriver) => { .configure(spec) .analyze((err: Error | null, internalResults: AxeAnalysis) => {}); + const deprecatedAnalysis: AxeAnalysis = await AxeBuilder(webDriver).analyze( + (internalResults: AxeAnalysis) => {} + ); + const inapplicable: Result[] = analysis.inapplicable; const incomplete: Result[] = analysis.incomplete; const passes: Result[] = analysis.passes; From 6f1e198243cd0cfb6398fb988886c80464d4d234 Mon Sep 17 00:00:00 2001 From: Tyler Krupicka Date: Sun, 10 Mar 2019 20:23:14 -0700 Subject: [PATCH 032/710] axe-wedriverjs: analyze callback type order --- types/axe-webdriverjs/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/axe-webdriverjs/index.d.ts b/types/axe-webdriverjs/index.d.ts index 13aeff0fc5..7d5d013afb 100644 --- a/types/axe-webdriverjs/index.d.ts +++ b/types/axe-webdriverjs/index.d.ts @@ -78,7 +78,7 @@ export interface AxeBuilder { * @param callback Function to execute when analysis completes. */ analyze( - callback?: DeprecatedAnalyzeCallback | AnalyzeCallback + callback?: AnalyzeCallback | DeprecatedAnalyzeCallback ): Promise; } From b0ddea4f92d95a4432f1f38f92a7bc51fc133fd5 Mon Sep 17 00:00:00 2001 From: Tyler Krupicka Date: Sun, 10 Mar 2019 20:41:32 -0700 Subject: [PATCH 033/710] axe-webdriverjs: update authors based on new linting rules --- types/axe-webdriverjs/index.d.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/types/axe-webdriverjs/index.d.ts b/types/axe-webdriverjs/index.d.ts index 7d5d013afb..3b6aab18ce 100644 --- a/types/axe-webdriverjs/index.d.ts +++ b/types/axe-webdriverjs/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for axe-webdriverjs 2.1 // Project: https://github.com/dequelabs/axe-webdriverjs#readme -// Definitions by: My Self +// Definitions by: Joshua Goldberg +// Tyler Krupicka // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 From 342e36c3356724014a9ec55c7c67426998e3a87f Mon Sep 17 00:00:00 2001 From: Flexmonster Pivot Table Date: Tue, 12 Mar 2019 18:48:45 +0200 Subject: [PATCH 034/710] update package to version 2.7 the package was updated to version 2.7 --- types/flexmonster/index.d.ts | 2 +- types/flexmonster/v2.6/flexmonster-tests.ts | 7 + types/flexmonster/v2.6/index.d.ts | 513 ++++++++++++++++++++ types/flexmonster/v2.6/tsconfig.json | 31 ++ types/flexmonster/v2.6/tslint.json | 3 + 5 files changed, 555 insertions(+), 1 deletion(-) create mode 100644 types/flexmonster/v2.6/flexmonster-tests.ts create mode 100644 types/flexmonster/v2.6/index.d.ts create mode 100644 types/flexmonster/v2.6/tsconfig.json create mode 100644 types/flexmonster/v2.6/tslint.json diff --git a/types/flexmonster/index.d.ts b/types/flexmonster/index.d.ts index 6d92a20ddc..eeb8ed56d7 100644 --- a/types/flexmonster/index.d.ts +++ b/types/flexmonster/index.d.ts @@ -2,7 +2,7 @@ // Project: https://flexmonster.com/ // Definitions by: Flexmonster // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 2.9 export as namespace Flexmonster; diff --git a/types/flexmonster/v2.6/flexmonster-tests.ts b/types/flexmonster/v2.6/flexmonster-tests.ts new file mode 100644 index 0000000000..fb9840c6cb --- /dev/null +++ b/types/flexmonster/v2.6/flexmonster-tests.ts @@ -0,0 +1,7 @@ +import Flexmonster = require('flexmonster'); + +new Flexmonster({ + container: 'pivot-container', + height: '550px', + width: '100%' +}); diff --git a/types/flexmonster/v2.6/index.d.ts b/types/flexmonster/v2.6/index.d.ts new file mode 100644 index 0000000000..fad76ca64d --- /dev/null +++ b/types/flexmonster/v2.6/index.d.ts @@ -0,0 +1,513 @@ +// Type definitions for flexmonster 2.6 +// Project: https://flexmonster.com/ +// Definitions by: Flexmonster +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export as namespace Flexmonster; + +declare const Flexmonster: FlexmonsterConstructor; +export = Flexmonster; + +interface FlexmonsterConstructor { + new (params: Flexmonster.Params): Flexmonster.Pivot; + (params: Flexmonster.Params): Flexmonster.Pivot; +} + +declare namespace Flexmonster { + interface Params { + // params + toolbar?: boolean; + licenseKey?: string; + width?: string | number; + height?: string | number; + componentFolder?: string; + report?: Report | string; + global?: Report; + customizeCell?: (cell: CellBuilder, data: CellData) => void; + customizeContextMenu?: (items: ContextMenuItem[], data: CellData | ChartData, viewType: string) => ContextMenuItem[]; + // events + afterchartdraw?: () => void; + aftergriddraw?: (param: object) => void; + beforegriddraw?: (param: object) => void; + beforetoolbarcreated?: (toolbar: Toolbar) => void; + cellclick?: (cell: CellData) => void; + celldoubleclick?: (cell: CellData) => void; + datachanged?: (param: object) => void; + dataerror?: (param: object) => void; + datafilecancelled?: () => void; + dataloaded?: () => void; + exportcomplete?: () => void; + exportstart?: () => void; + fieldslistclose?: () => void; + fieldslistopen?: () => void; + filterclose?: () => void; + filteropen?: () => void; + loadingdata?: () => void; + loadinglocalization?: () => void; + loadingolapstructure?: () => void; + loadingreportfile?: () => void; + localizationerror?: () => void; + localizationloaded?: () => void; + olapstructureerror?: () => void; + olapstructureloaded?: () => void; + openingreportfile?: () => void; + printcomplete?: () => void; + printstart?: () => void; + querycomplete?: () => void; + queryerror?: () => void; + ready?: () => void; + reportchange?: () => void; + reportcomplete?: () => void; + reportfilecancelled?: () => void; + reportfileerror?: () => void; + runningquery?: () => void; + update?: () => void; + // other + container?: string; + } + + interface Pivot { + addCalculatedMeasure(measure: Measure): void; + addCondition(condition: ConditionalFormat): void; + addJSON(json: object[]): void; + alert(options: { title?: string; message?: string; type?: string; buttons?: Array<{ label: string; handler?: () => void; }>; blocking?: boolean; }): void; + clear(): void; + clearFilter(hierarchyName: string): void; + clearXMLACache(proxyUrl: string, databaseId: string, callbackHandler: ((reponse: object) => void) | string, cubeId: string, measuresGroupId: string, + username?: string, password?: string): void; + closeFieldsList(): void; + collapseAllData(): void; + collapseData(hierarchyName: string): void; + connectTo(object: DataSource): void; + customizeCell(customizeCellFunction: (cell: CellBuilder, data: CellData) => void): void; + customizeContextMenu(customizeFunction: (items: ContextMenuItem[], data: CellData | ChartData, viewType: string) => ContextMenuItem[]): void; + dispose(): void; + expandAllData(withAllChildren?: boolean): void; + expandData(hierarchyName: string): void; + exportTo(type: string, exportOptions?: ExportOptions, callbackHandler?: ((result: object) => void) | string): void; + getAllConditions(): ConditionalFormat[]; + getAllHierarchies(): Hierarchy[]; + getAllMeasures(): Measure[]; + getCell(rowIdx: number, colIdx: number): CellData; + getColumns(): Hierarchy[]; + getCondition(id: string): ConditionalFormat; + getData(options: { slice?: Slice }, callbackHandler: ((rawData: any) => void) | string, updateHandler?: ((rawData: any) => void) | string): void; + getFilter(hierarchyName: string): FilterItem[]; + getFilterProperties(hierarchyName: string): FilterProperties; + getFormat(measureName: string): Format; + getMeasures(): Measure[]; + getMembers(hierarchyName: string, memberName: string, callbackHandler: ((members: Member[]) => void) | string): Member[]; + getOptions(): Options; + getReport(format?: string): Report | string; + getReportFilters(): Hierarchy[]; + getRows(): Hierarchy[]; + getSelectedCell(): CellData | CellData[]; + getSort(hierarchyName: string): string; + getXMLACatalogs(proxyURL: string, dataSource: string, callbackHandler: ((response: any) => void) | string, username?: string, password?: string): void; + getXMLACubes(proxyURL: string, dataSource: string, catalog: string, callbackHandler: ((response: any) => void) | string, username?: string, password?: string): void; + getXMLADataSources(proxyURL: string, callbackHandler: ((response: any) => void) | string, username?: string, password?: string): void; + getXMLAProviderName(proxyURL: string, callbackHandler: ((response: any) => void) | string, username?: string, password?: string): string; + load(url: string, componentFolder?: string): void; + off(eventType: string, handler?: ((...args: any[]) => any) | string): void; + on(eventType: string, handler: ((...args: any[]) => any) | string): void; + open(): void; + openFieldsList(): void; + openFilter(hierarchyName: string): void; + print(options?: PrintOptions): void; + refresh(): void; + removeAllCalculatedMeasures(): void; + removeAllConditions(): void; + removeCalculatedMeasure(uniqueName: string): void; + removeCondition(id: string): void; + removeSelection(): void; + runQuery(slice: Slice): void; + save(filename: string, destination: string, callbackHandler?: (() => void) | string, url?: string, embedData?: boolean): string; + setBottomX(hierarchyName: string, num: number, measure: MeasureObject): void; + setFilter(hierarchyName: string, items: string[], negation?: boolean): void; + setFormat(format: Format, measureName: string): void; + setOptions(options: Options): void; + setReport(report: Report): void; + setSort(hierarchyName: string, sortName: string, customSorting?: string[]): void; + setTopX(hierarchyName: string, num: number, measure: MeasureObject): void; + showCharts(type?: string, multiple?: boolean): void; + showGrid(): void; + showGridAndCharts(type?: string, position?: string, multiple?: boolean): void; + sortingMethod(hierarchyName: string, compareFunction: (a: string, b: string) => boolean): void; + sortValues(axisName: string, type: string, tuple: number[], measure: MeasureObject): void; + toolbar: Toolbar; + updateData(object: DataSource | object[]): void; + version: string; + fusioncharts?: { + getData(options: { type: string; slice?: Slice; prepareDataFunction?: (rawData: any) => any }, callbackHandler: ((rawData: any) => void) | string, + updateHandler?: ((rawData: any) => void) | string): void; + getNumberFormat(format: object): object; + }; + googlecharts?: { + getData(options: { type?: string; slice?: Slice; prepareDataFunction?: (rawData: any) => any }, callbackHandler: ((rawData: any) => void) | string, + updateHandler?: ((rawData: any) => void) | string): void; + getNumberFormat(format: object): object; + getNumberFormatPattern(format: object): string; + }; + highcharts?: { + getData(options: { type?: string; slice?: Slice; xAxisType?: string; valuesOnly?: boolean, withDrilldown?: boolean, prepareDataFunction?: (rawData: any) => any }, + callbackHandler: ((rawData: any) => void) | string, updateHandler?: ((rawData: any) => void) | string): void; + getAxisFormat(format: object): string; + getPointXFormat(format: object): string; + getPointYFormat(format: object): string; + getPointZFormat(format: object): string; + }; + } + + interface Report { + dataSource?: DataSource; + slice?: Slice; + options?: Options; + conditions?: ConditionalFormat[]; + formats?: Format[]; + tableSizes?: { + columns?: ColumnSize[]; + rows?: RowSize[]; + }; + localization?: object | string; + } + + interface DataSource { + browseForFile?: boolean; + catalog?: string; + cube?: string; + data?: object[]; + dataSourceInfo?: string; + dataSourceType?: string; + fieldSeparator?: string; + thousandSeparator?: string; + filename?: string; + ignoreQuotedLineBreaks?: boolean; + proxyUrl?: string; + recordsetDelimiter?: string; + binary?: boolean; + roles?: string; + localeIdentifier?: string; + effectiveUserName?: string; + customData?: string; + hash?: string; + username?: string; + password?: string; + requestHeader?: object; + subquery?: string; + } + + interface Slice { + columns?: Hierarchy[]; + measures?: Measure[]; + reportFilters?: Hierarchy[]; + rows?: Hierarchy[]; + drills?: { + drillAll?: boolean; + columns?: Array<{ tuple: string[]; measure?: MeasureObject; }>; + rows?: Array<{ tuple: string[]; measure?: MeasureObject; }>; + }; + expands?: { + expandAll?: boolean; + columns?: Array<{ tuple: string[]; measure?: MeasureObject; }>; + rows?: Array<{ tuple: string[]; measure?: MeasureObject; }>; + }; + sorting?: { + column?: Array<{ type: string; tuple: string[]; measure: MeasureObject; }>; + row?: Array<{ type: string; tuple: string[]; measure: MeasureObject; }>; + }; + drillThrough?: string[]; + } + + interface Options { + chart?: { + activeMeasure?: MeasureObject; + activeTupleIndex?: number; + autoRange?: boolean; + labelsHierarchy?: string; + multipleMeasures?: boolean; + oneLevel?: boolean; + showFilter?: boolean; + showLegend?: boolean; + showLegendButton?: boolean; + showMeasures?: boolean; + showWarning?: boolean; + title?: string; + type?: string; + showDataLabels?: boolean; + reversedAxes?: boolean; + showAllLabels?: boolean; + showOneMeasureSelection?: boolean; + position?: string; + pieDataIndex?: string; + }; + grid?: { + showFilter?: boolean; + showGrandTotals?: string; + showHeaders?: boolean; + showHierarchies?: boolean; + showHierarchyCaptions?: boolean; + showReportFiltersArea?: boolean; + showTotals?: boolean; + title?: string; + type?: string; + showAutoCalculationBar?: boolean; + dragging?: boolean; + grandTotalsPosition?: string; + drillThroughMaxRows?: number; + }; + configuratorActive?: boolean; + configuratorButton?: boolean; + dateTimezoneOffset?: number; + datePattern?: string; + dateTimePattern?: string; + defaultHierarchySortName?: string; + drillThrough?: boolean; + editing?: boolean; + selectEmptyCells?: boolean; + showAggregations?: boolean; + showCalculatedValuesButton?: boolean; + showDefaultSlice?: boolean; + showMemberProperties?: boolean; + sorting?: string; + viewType?: string; + showAggregationLabels?: boolean; + useOlapFormatting?: boolean; + defaultDateType?: string; + timePattern?: string; + showOutdatedDataAlert?: boolean; + showEmptyData?: boolean; + saveAllFormats?: boolean; + showDrillThroughConfigurator?: boolean; + grouping?: boolean; + showAllFieldsDrillThrough?: boolean; + } + + interface PrintOptions { + header?: string; + footer?: string; + } + + interface Member { + caption?: string; + uniqueName?: string; + hierarchyName?: string; + children?: Member[]; + isLeaf?: boolean; + parentMember?: string; + } + + interface FilterProperties { + type: string; + members?: FilterItem[]; + quantity?: number; + measure?: MeasureObject; + } + + interface FilterItem { + caption?: string; + uniqueName?: string; + hierarchyName?: string; + } + + interface CellData { + columnIndex?: number; + columns?: object[]; + escapedLabel?: string; + height?: number; + hierarchy?: Hierarchy; + isClassicTotalRow?: boolean; + isDrillThrough?: boolean; + isGrandTotal?: boolean; + isGrandTotalColumn?: boolean; + isGrandTotalRow?: boolean; + isTotal?: boolean; + isTotalColumn?: boolean; + isTotalRow?: boolean; + member?: Member; + width?: number; + x?: number; + y?: number; + label?: string; + measure?: MeasureObject; + rowIndex?: number; + rows?: object[]; + type?: string; + value?: number; + } + + interface ExportOptions { + filename?: string; + destinationType?: string; + excelSheetName?: string; + footer?: string; + header?: string; + pageOrientation?: string; + showFilters?: boolean; + url?: string; + useOlapFormattingInExcel?: boolean; + useCustomizeCellForData?: boolean; + excelExportAll?: boolean; + requestHeader?: object; + } + + interface Hierarchy { + caption?: string; + dimensionName?: string; + filter?: { + members?: string[]; + negation?: boolean; + measure?: MeasureObject; + quantity?: number; + type?: string; + }; + sortName?: string; + sortOrder?: string[]; + uniqueName?: string; + } + + interface Measure { + uniqueName?: string; + active?: boolean; + aggregation?: string; + availableAggregations?: string[]; + caption?: string; + formula?: string; + format?: string; + grandTotalCaption?: string; + } + + interface MeasureObject { + uniqueName: string; + aggregation?: string; + } + + interface ConditionalFormat { + formula?: string; + format?: Style; + formatCSS?: string; + row?: number; + column?: number; + measureName?: string; + hierarchy?: string; + member?: string; + isTotal?: number; + } + + interface Style { + color?: string; + backgroundColor?: string; + backgroundImage?: string; + borderColor?: string; + fontSize?: string; + fontWeight?: string; + fill?: string; + textAlign?: string; + fontFamily?: string; + width?: number; + maxWidth?: number; + height?: number; + maxHeight?: number; + } + + interface Format { + name?: string; + thousandsSeparator?: string; + decimalSeparator?: string; + decimalPlaces?: number; + maxDecimalPlaces?: number; + maxSymbols?: number; + currencySymbol?: string; + currencySymbolAlign?: string; + nullValue?: string; + infinityValue?: string; + divideByZeroValue?: string; + textAlign?: string; + isPercent?: boolean; + beautifyFloatingPoint?: boolean; + } + + interface ColumnSize { + width?: number; + idx?: number; + tuple?: string[]; + measure?: MeasureObject; + } + + interface RowSize { + height?: number; + idx?: number; + tuple?: string[]; + measure?: MeasureObject; + } + + interface CellBuilder { + attr?: object; + classes?: string[]; + style?: object; + tag?: string; + text?: string; + addClass(value?: string): void; + toHtml(): string; + } + + interface ContextMenuItem { + label?: string; + handler?: (() => void) | string; + submenu?: ContextMenuItem[]; + isSelected?: boolean; + } + + interface ChartData { + columnTuple?: number[]; + id?: string; + label?: string; + measure?: MeasureObject; + rawTuple?: number[]; + value?: number; + } + + interface Toolbar { + getTabs: () => ToolbarTab[]; + // Connect tab + connectLocalCSVHandler: () => void; + connectLocalJSONHandler: () => void; + connectRemoteCSV: () => void; + connectRemoteJSON: () => void; + connectOLAP: () => void; + // Open tab + openLocalReport: () => void; + openRemoteReport: () => void; + // Save tab + saveHandler: () => void; + // Export tab + printHandler: () => void; + exportHandler: (type: string) => void; + // Grid tab + gridHandler: () => void; + // Charts tab + chartsHandler: (type: string) => void; + chartsMultipleHandler: () => void; + // Format tab + formatCellsHandler: () => void; + conditionalFormattingHandler: () => void; + // Options tab + optionsHandler: () => void; + // Fields tab + fieldsHandler: () => void; + // Fullscreen tab + fullscreenHandler: () => void; + } + + interface ToolbarTab { + android: boolean; + args: any; + handler: (() => void) | string; + icon: string; + id: string; + ios: boolean; + mobile: boolean; + menu: ToolbarTab[]; + title: string; + } +} diff --git a/types/flexmonster/v2.6/tsconfig.json b/types/flexmonster/v2.6/tsconfig.json new file mode 100644 index 0000000000..fd6a531526 --- /dev/null +++ b/types/flexmonster/v2.6/tsconfig.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "flexmonster": [ + "flexmonster/v2.6" + ], + "flexmonster/*": [ + "flexmonster/v2.6/*" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "flexmonster-tests.ts" + ] +} \ No newline at end of file diff --git a/types/flexmonster/v2.6/tslint.json b/types/flexmonster/v2.6/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/flexmonster/v2.6/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From 566da0ba32abccebc591d2d3d074c7c49f8101da Mon Sep 17 00:00:00 2001 From: Flexmonster Pivot Table Date: Tue, 12 Mar 2019 19:17:42 +0200 Subject: [PATCH 035/710] 2.7 version tests update --- types/flexmonster/flexmonster-tests.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/types/flexmonster/flexmonster-tests.ts b/types/flexmonster/flexmonster-tests.ts index fb9840c6cb..2deb24ccfc 100644 --- a/types/flexmonster/flexmonster-tests.ts +++ b/types/flexmonster/flexmonster-tests.ts @@ -1,7 +1,11 @@ import Flexmonster = require('flexmonster'); new Flexmonster({ + componentFolder: '', container: 'pivot-container', + global: {}, height: '550px', - width: '100%' + width: '100%', + report: {}, + toolbar: true }); From de0525fe631bd57394c2ccc1d52afccf9d78f794 Mon Sep 17 00:00:00 2001 From: Flexmonster Pivot Table Date: Tue, 12 Mar 2019 19:32:54 +0200 Subject: [PATCH 036/710] 2.6 tsconfig update --- types/flexmonster/v2.6/tsconfig.json | 3 --- 1 file changed, 3 deletions(-) diff --git a/types/flexmonster/v2.6/tsconfig.json b/types/flexmonster/v2.6/tsconfig.json index fd6a531526..700754b991 100644 --- a/types/flexmonster/v2.6/tsconfig.json +++ b/types/flexmonster/v2.6/tsconfig.json @@ -15,9 +15,6 @@ "paths": { "flexmonster": [ "flexmonster/v2.6" - ], - "flexmonster/*": [ - "flexmonster/v2.6/*" ] }, "types": [], From 041c529d61858d3d955449ee472c512301c999f6 Mon Sep 17 00:00:00 2001 From: Flexmonster Pivot Table Date: Tue, 12 Mar 2019 19:42:33 +0200 Subject: [PATCH 037/710] package update --- types/flexmonster/v2.6/flexmonster-tests.ts | 7 - types/flexmonster/v2.6/index.d.ts | 513 -------------------- types/flexmonster/v2.6/tsconfig.json | 28 -- types/flexmonster/v2.6/tslint.json | 3 - 4 files changed, 551 deletions(-) delete mode 100644 types/flexmonster/v2.6/flexmonster-tests.ts delete mode 100644 types/flexmonster/v2.6/index.d.ts delete mode 100644 types/flexmonster/v2.6/tsconfig.json delete mode 100644 types/flexmonster/v2.6/tslint.json diff --git a/types/flexmonster/v2.6/flexmonster-tests.ts b/types/flexmonster/v2.6/flexmonster-tests.ts deleted file mode 100644 index fb9840c6cb..0000000000 --- a/types/flexmonster/v2.6/flexmonster-tests.ts +++ /dev/null @@ -1,7 +0,0 @@ -import Flexmonster = require('flexmonster'); - -new Flexmonster({ - container: 'pivot-container', - height: '550px', - width: '100%' -}); diff --git a/types/flexmonster/v2.6/index.d.ts b/types/flexmonster/v2.6/index.d.ts deleted file mode 100644 index fad76ca64d..0000000000 --- a/types/flexmonster/v2.6/index.d.ts +++ /dev/null @@ -1,513 +0,0 @@ -// Type definitions for flexmonster 2.6 -// Project: https://flexmonster.com/ -// Definitions by: Flexmonster -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 - -export as namespace Flexmonster; - -declare const Flexmonster: FlexmonsterConstructor; -export = Flexmonster; - -interface FlexmonsterConstructor { - new (params: Flexmonster.Params): Flexmonster.Pivot; - (params: Flexmonster.Params): Flexmonster.Pivot; -} - -declare namespace Flexmonster { - interface Params { - // params - toolbar?: boolean; - licenseKey?: string; - width?: string | number; - height?: string | number; - componentFolder?: string; - report?: Report | string; - global?: Report; - customizeCell?: (cell: CellBuilder, data: CellData) => void; - customizeContextMenu?: (items: ContextMenuItem[], data: CellData | ChartData, viewType: string) => ContextMenuItem[]; - // events - afterchartdraw?: () => void; - aftergriddraw?: (param: object) => void; - beforegriddraw?: (param: object) => void; - beforetoolbarcreated?: (toolbar: Toolbar) => void; - cellclick?: (cell: CellData) => void; - celldoubleclick?: (cell: CellData) => void; - datachanged?: (param: object) => void; - dataerror?: (param: object) => void; - datafilecancelled?: () => void; - dataloaded?: () => void; - exportcomplete?: () => void; - exportstart?: () => void; - fieldslistclose?: () => void; - fieldslistopen?: () => void; - filterclose?: () => void; - filteropen?: () => void; - loadingdata?: () => void; - loadinglocalization?: () => void; - loadingolapstructure?: () => void; - loadingreportfile?: () => void; - localizationerror?: () => void; - localizationloaded?: () => void; - olapstructureerror?: () => void; - olapstructureloaded?: () => void; - openingreportfile?: () => void; - printcomplete?: () => void; - printstart?: () => void; - querycomplete?: () => void; - queryerror?: () => void; - ready?: () => void; - reportchange?: () => void; - reportcomplete?: () => void; - reportfilecancelled?: () => void; - reportfileerror?: () => void; - runningquery?: () => void; - update?: () => void; - // other - container?: string; - } - - interface Pivot { - addCalculatedMeasure(measure: Measure): void; - addCondition(condition: ConditionalFormat): void; - addJSON(json: object[]): void; - alert(options: { title?: string; message?: string; type?: string; buttons?: Array<{ label: string; handler?: () => void; }>; blocking?: boolean; }): void; - clear(): void; - clearFilter(hierarchyName: string): void; - clearXMLACache(proxyUrl: string, databaseId: string, callbackHandler: ((reponse: object) => void) | string, cubeId: string, measuresGroupId: string, - username?: string, password?: string): void; - closeFieldsList(): void; - collapseAllData(): void; - collapseData(hierarchyName: string): void; - connectTo(object: DataSource): void; - customizeCell(customizeCellFunction: (cell: CellBuilder, data: CellData) => void): void; - customizeContextMenu(customizeFunction: (items: ContextMenuItem[], data: CellData | ChartData, viewType: string) => ContextMenuItem[]): void; - dispose(): void; - expandAllData(withAllChildren?: boolean): void; - expandData(hierarchyName: string): void; - exportTo(type: string, exportOptions?: ExportOptions, callbackHandler?: ((result: object) => void) | string): void; - getAllConditions(): ConditionalFormat[]; - getAllHierarchies(): Hierarchy[]; - getAllMeasures(): Measure[]; - getCell(rowIdx: number, colIdx: number): CellData; - getColumns(): Hierarchy[]; - getCondition(id: string): ConditionalFormat; - getData(options: { slice?: Slice }, callbackHandler: ((rawData: any) => void) | string, updateHandler?: ((rawData: any) => void) | string): void; - getFilter(hierarchyName: string): FilterItem[]; - getFilterProperties(hierarchyName: string): FilterProperties; - getFormat(measureName: string): Format; - getMeasures(): Measure[]; - getMembers(hierarchyName: string, memberName: string, callbackHandler: ((members: Member[]) => void) | string): Member[]; - getOptions(): Options; - getReport(format?: string): Report | string; - getReportFilters(): Hierarchy[]; - getRows(): Hierarchy[]; - getSelectedCell(): CellData | CellData[]; - getSort(hierarchyName: string): string; - getXMLACatalogs(proxyURL: string, dataSource: string, callbackHandler: ((response: any) => void) | string, username?: string, password?: string): void; - getXMLACubes(proxyURL: string, dataSource: string, catalog: string, callbackHandler: ((response: any) => void) | string, username?: string, password?: string): void; - getXMLADataSources(proxyURL: string, callbackHandler: ((response: any) => void) | string, username?: string, password?: string): void; - getXMLAProviderName(proxyURL: string, callbackHandler: ((response: any) => void) | string, username?: string, password?: string): string; - load(url: string, componentFolder?: string): void; - off(eventType: string, handler?: ((...args: any[]) => any) | string): void; - on(eventType: string, handler: ((...args: any[]) => any) | string): void; - open(): void; - openFieldsList(): void; - openFilter(hierarchyName: string): void; - print(options?: PrintOptions): void; - refresh(): void; - removeAllCalculatedMeasures(): void; - removeAllConditions(): void; - removeCalculatedMeasure(uniqueName: string): void; - removeCondition(id: string): void; - removeSelection(): void; - runQuery(slice: Slice): void; - save(filename: string, destination: string, callbackHandler?: (() => void) | string, url?: string, embedData?: boolean): string; - setBottomX(hierarchyName: string, num: number, measure: MeasureObject): void; - setFilter(hierarchyName: string, items: string[], negation?: boolean): void; - setFormat(format: Format, measureName: string): void; - setOptions(options: Options): void; - setReport(report: Report): void; - setSort(hierarchyName: string, sortName: string, customSorting?: string[]): void; - setTopX(hierarchyName: string, num: number, measure: MeasureObject): void; - showCharts(type?: string, multiple?: boolean): void; - showGrid(): void; - showGridAndCharts(type?: string, position?: string, multiple?: boolean): void; - sortingMethod(hierarchyName: string, compareFunction: (a: string, b: string) => boolean): void; - sortValues(axisName: string, type: string, tuple: number[], measure: MeasureObject): void; - toolbar: Toolbar; - updateData(object: DataSource | object[]): void; - version: string; - fusioncharts?: { - getData(options: { type: string; slice?: Slice; prepareDataFunction?: (rawData: any) => any }, callbackHandler: ((rawData: any) => void) | string, - updateHandler?: ((rawData: any) => void) | string): void; - getNumberFormat(format: object): object; - }; - googlecharts?: { - getData(options: { type?: string; slice?: Slice; prepareDataFunction?: (rawData: any) => any }, callbackHandler: ((rawData: any) => void) | string, - updateHandler?: ((rawData: any) => void) | string): void; - getNumberFormat(format: object): object; - getNumberFormatPattern(format: object): string; - }; - highcharts?: { - getData(options: { type?: string; slice?: Slice; xAxisType?: string; valuesOnly?: boolean, withDrilldown?: boolean, prepareDataFunction?: (rawData: any) => any }, - callbackHandler: ((rawData: any) => void) | string, updateHandler?: ((rawData: any) => void) | string): void; - getAxisFormat(format: object): string; - getPointXFormat(format: object): string; - getPointYFormat(format: object): string; - getPointZFormat(format: object): string; - }; - } - - interface Report { - dataSource?: DataSource; - slice?: Slice; - options?: Options; - conditions?: ConditionalFormat[]; - formats?: Format[]; - tableSizes?: { - columns?: ColumnSize[]; - rows?: RowSize[]; - }; - localization?: object | string; - } - - interface DataSource { - browseForFile?: boolean; - catalog?: string; - cube?: string; - data?: object[]; - dataSourceInfo?: string; - dataSourceType?: string; - fieldSeparator?: string; - thousandSeparator?: string; - filename?: string; - ignoreQuotedLineBreaks?: boolean; - proxyUrl?: string; - recordsetDelimiter?: string; - binary?: boolean; - roles?: string; - localeIdentifier?: string; - effectiveUserName?: string; - customData?: string; - hash?: string; - username?: string; - password?: string; - requestHeader?: object; - subquery?: string; - } - - interface Slice { - columns?: Hierarchy[]; - measures?: Measure[]; - reportFilters?: Hierarchy[]; - rows?: Hierarchy[]; - drills?: { - drillAll?: boolean; - columns?: Array<{ tuple: string[]; measure?: MeasureObject; }>; - rows?: Array<{ tuple: string[]; measure?: MeasureObject; }>; - }; - expands?: { - expandAll?: boolean; - columns?: Array<{ tuple: string[]; measure?: MeasureObject; }>; - rows?: Array<{ tuple: string[]; measure?: MeasureObject; }>; - }; - sorting?: { - column?: Array<{ type: string; tuple: string[]; measure: MeasureObject; }>; - row?: Array<{ type: string; tuple: string[]; measure: MeasureObject; }>; - }; - drillThrough?: string[]; - } - - interface Options { - chart?: { - activeMeasure?: MeasureObject; - activeTupleIndex?: number; - autoRange?: boolean; - labelsHierarchy?: string; - multipleMeasures?: boolean; - oneLevel?: boolean; - showFilter?: boolean; - showLegend?: boolean; - showLegendButton?: boolean; - showMeasures?: boolean; - showWarning?: boolean; - title?: string; - type?: string; - showDataLabels?: boolean; - reversedAxes?: boolean; - showAllLabels?: boolean; - showOneMeasureSelection?: boolean; - position?: string; - pieDataIndex?: string; - }; - grid?: { - showFilter?: boolean; - showGrandTotals?: string; - showHeaders?: boolean; - showHierarchies?: boolean; - showHierarchyCaptions?: boolean; - showReportFiltersArea?: boolean; - showTotals?: boolean; - title?: string; - type?: string; - showAutoCalculationBar?: boolean; - dragging?: boolean; - grandTotalsPosition?: string; - drillThroughMaxRows?: number; - }; - configuratorActive?: boolean; - configuratorButton?: boolean; - dateTimezoneOffset?: number; - datePattern?: string; - dateTimePattern?: string; - defaultHierarchySortName?: string; - drillThrough?: boolean; - editing?: boolean; - selectEmptyCells?: boolean; - showAggregations?: boolean; - showCalculatedValuesButton?: boolean; - showDefaultSlice?: boolean; - showMemberProperties?: boolean; - sorting?: string; - viewType?: string; - showAggregationLabels?: boolean; - useOlapFormatting?: boolean; - defaultDateType?: string; - timePattern?: string; - showOutdatedDataAlert?: boolean; - showEmptyData?: boolean; - saveAllFormats?: boolean; - showDrillThroughConfigurator?: boolean; - grouping?: boolean; - showAllFieldsDrillThrough?: boolean; - } - - interface PrintOptions { - header?: string; - footer?: string; - } - - interface Member { - caption?: string; - uniqueName?: string; - hierarchyName?: string; - children?: Member[]; - isLeaf?: boolean; - parentMember?: string; - } - - interface FilterProperties { - type: string; - members?: FilterItem[]; - quantity?: number; - measure?: MeasureObject; - } - - interface FilterItem { - caption?: string; - uniqueName?: string; - hierarchyName?: string; - } - - interface CellData { - columnIndex?: number; - columns?: object[]; - escapedLabel?: string; - height?: number; - hierarchy?: Hierarchy; - isClassicTotalRow?: boolean; - isDrillThrough?: boolean; - isGrandTotal?: boolean; - isGrandTotalColumn?: boolean; - isGrandTotalRow?: boolean; - isTotal?: boolean; - isTotalColumn?: boolean; - isTotalRow?: boolean; - member?: Member; - width?: number; - x?: number; - y?: number; - label?: string; - measure?: MeasureObject; - rowIndex?: number; - rows?: object[]; - type?: string; - value?: number; - } - - interface ExportOptions { - filename?: string; - destinationType?: string; - excelSheetName?: string; - footer?: string; - header?: string; - pageOrientation?: string; - showFilters?: boolean; - url?: string; - useOlapFormattingInExcel?: boolean; - useCustomizeCellForData?: boolean; - excelExportAll?: boolean; - requestHeader?: object; - } - - interface Hierarchy { - caption?: string; - dimensionName?: string; - filter?: { - members?: string[]; - negation?: boolean; - measure?: MeasureObject; - quantity?: number; - type?: string; - }; - sortName?: string; - sortOrder?: string[]; - uniqueName?: string; - } - - interface Measure { - uniqueName?: string; - active?: boolean; - aggregation?: string; - availableAggregations?: string[]; - caption?: string; - formula?: string; - format?: string; - grandTotalCaption?: string; - } - - interface MeasureObject { - uniqueName: string; - aggregation?: string; - } - - interface ConditionalFormat { - formula?: string; - format?: Style; - formatCSS?: string; - row?: number; - column?: number; - measureName?: string; - hierarchy?: string; - member?: string; - isTotal?: number; - } - - interface Style { - color?: string; - backgroundColor?: string; - backgroundImage?: string; - borderColor?: string; - fontSize?: string; - fontWeight?: string; - fill?: string; - textAlign?: string; - fontFamily?: string; - width?: number; - maxWidth?: number; - height?: number; - maxHeight?: number; - } - - interface Format { - name?: string; - thousandsSeparator?: string; - decimalSeparator?: string; - decimalPlaces?: number; - maxDecimalPlaces?: number; - maxSymbols?: number; - currencySymbol?: string; - currencySymbolAlign?: string; - nullValue?: string; - infinityValue?: string; - divideByZeroValue?: string; - textAlign?: string; - isPercent?: boolean; - beautifyFloatingPoint?: boolean; - } - - interface ColumnSize { - width?: number; - idx?: number; - tuple?: string[]; - measure?: MeasureObject; - } - - interface RowSize { - height?: number; - idx?: number; - tuple?: string[]; - measure?: MeasureObject; - } - - interface CellBuilder { - attr?: object; - classes?: string[]; - style?: object; - tag?: string; - text?: string; - addClass(value?: string): void; - toHtml(): string; - } - - interface ContextMenuItem { - label?: string; - handler?: (() => void) | string; - submenu?: ContextMenuItem[]; - isSelected?: boolean; - } - - interface ChartData { - columnTuple?: number[]; - id?: string; - label?: string; - measure?: MeasureObject; - rawTuple?: number[]; - value?: number; - } - - interface Toolbar { - getTabs: () => ToolbarTab[]; - // Connect tab - connectLocalCSVHandler: () => void; - connectLocalJSONHandler: () => void; - connectRemoteCSV: () => void; - connectRemoteJSON: () => void; - connectOLAP: () => void; - // Open tab - openLocalReport: () => void; - openRemoteReport: () => void; - // Save tab - saveHandler: () => void; - // Export tab - printHandler: () => void; - exportHandler: (type: string) => void; - // Grid tab - gridHandler: () => void; - // Charts tab - chartsHandler: (type: string) => void; - chartsMultipleHandler: () => void; - // Format tab - formatCellsHandler: () => void; - conditionalFormattingHandler: () => void; - // Options tab - optionsHandler: () => void; - // Fields tab - fieldsHandler: () => void; - // Fullscreen tab - fullscreenHandler: () => void; - } - - interface ToolbarTab { - android: boolean; - args: any; - handler: (() => void) | string; - icon: string; - id: string; - ios: boolean; - mobile: boolean; - menu: ToolbarTab[]; - title: string; - } -} diff --git a/types/flexmonster/v2.6/tsconfig.json b/types/flexmonster/v2.6/tsconfig.json deleted file mode 100644 index 700754b991..0000000000 --- a/types/flexmonster/v2.6/tsconfig.json +++ /dev/null @@ -1,28 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../../", - "typeRoots": [ - "../../" - ], - "paths": { - "flexmonster": [ - "flexmonster/v2.6" - ] - }, - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "flexmonster-tests.ts" - ] -} \ No newline at end of file diff --git a/types/flexmonster/v2.6/tslint.json b/types/flexmonster/v2.6/tslint.json deleted file mode 100644 index f93cf8562a..0000000000 --- a/types/flexmonster/v2.6/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "dtslint/dt.json" -} From 85326c89aecba8f79d334cd1f7038f3dc74dd3d6 Mon Sep 17 00:00:00 2001 From: Bryan Krol Date: Wed, 13 Mar 2019 20:21:29 -0400 Subject: [PATCH 038/710] Added some more definitions for use. --- types/fabric/fabric-impl.d.ts | 59 ++++++++++++++++++++++++++++++++++- 1 file changed, 58 insertions(+), 1 deletion(-) diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 8e973de1ab..2b384347aa 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -865,7 +865,7 @@ interface IShadowOptions { /** * Whether the shadow should affect stroke operations */ - affectStrike?: boolean; + affectStroke?: boolean; /** * Indicates whether toObject should include default values */ @@ -3529,6 +3529,40 @@ export class Object { * @return {fabric.Point} */ translateToGivenOrigin(pointL: Point, fromOriginX: string, fromOriginY: string, toOriginX: string, toOriginY: string): Point; + /* + * Calculate object dimensions from its properties + * @private + * @return {Object} .x width dimension + * @return {Object} .y height dimension + */ + _getNonTransformedDimensions(): {x: number, y: number}; + /** + * + * @param ctx + * @private + */ + _renderStroke(ctx: CanvasRenderingContext2D): void; + /** + * @private + * @param {CanvasRenderingContext2D} ctx Context to render on + */ + _removeShadow(ctx: CanvasRenderingContext2D): void; + /** + * @private + * Sets line dash + * @param {CanvasRenderingContext2D} ctx Context to set the dash line on + * @param {Array} dashArray array representing dashes + * @param {Function} alternative function to call if browser does not support lineDash + */ + _setLineDash(ctx: CanvasRenderingContext2D, dashArray: number[], alternative: Function): void; + /** + * @private + * @param {CanvasRenderingContext2D} ctx Context to render on + * @param {Object} filler fabric.Pattern or fabric.Gradient + * @return {Object} offset.offsetX offset for text rendering + * @return {Object} offset.offsetY offset for text rendering + */ + _applyPatternGradientTransform(ctx: CanvasRenderingContext2D, filler: string | Pattern | Gradient): void; } interface IPathOptions extends IObjectOptions { @@ -3940,6 +3974,20 @@ export class Text extends Object { * @return {Boolean} */ styleHas(property: string, lineIndex?: number): boolean; + /** + * Measure a single line given its index. Used to calculate the initial + * text bounding box. The values are calculated and stored in __lineWidths cache. + * @private + * @param {Number} lineIndex line number + * @return {Number} Line width + */ + getLineWidth(lineIndex: number): number; + /** + * @private + * @param {Number} lineIndex index text line + * @return {Number} Line left offset + */ + _getLineLeftOffset(lineIndex: number): number } interface ITextOptions extends TextOptions { /** @@ -4372,6 +4420,15 @@ export class IText extends Text { * @param {Event} e Event object */ setCursorByClick(e: Event): void; + /** + * @private + */ + _getNewSelectionStartFromOffset(mouseOffset: {x: number, y: number}, prevWidth: number, width: number, index: number, jlen: number): number; + /** + * @private + * @param {CanvasRenderingContext2D} ctx Context to render on + */ + _render(ctx: CanvasRenderingContext2D): void; } interface ITextboxOptions extends ITextOptions { /** From dce8d5bba1fcfd2875ac8bddcbc316db38c5774e Mon Sep 17 00:00:00 2001 From: Bryan Krol Date: Wed, 13 Mar 2019 20:33:01 -0400 Subject: [PATCH 039/710] Updated type for vptCoords so they are correct and also added a few more type defs --- types/fabric/fabric-impl.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 2b384347aa..4e7fec0258 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -1038,7 +1038,7 @@ interface IStaticCanvasOptions { * The coordinates get updated with @method calcViewportBoundaries. * @memberOf fabric.StaticCanvas.prototype */ - vptCoords?: {tl: number, tr: number, bl: number, br: number} + vptCoords?: {tl: {x: number, y: number}, tr: {x: number, y: number}, bl: {x: number, y: number}, br: {x: number, y: number}} /** * Based on vptCoords and object.aCoords, skip rendering of objects that * are not included in current viewport. From bf27bf7455ea59a5ea89a37d366a540edbfed426 Mon Sep 17 00:00:00 2001 From: Erin Noe-Payne Date: Fri, 15 Mar 2019 15:28:13 -0600 Subject: [PATCH 040/710] Adds support for @rebass/grid/emotion --- types/rebass__grid/emotion.d.ts | 1 + types/rebass__grid/index.d.ts | 1 + types/rebass__grid/rebass__grid-tests.tsx | 9 +++++++++ types/rebass__grid/tsconfig.json | 4 +++- 4 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 types/rebass__grid/emotion.d.ts diff --git a/types/rebass__grid/emotion.d.ts b/types/rebass__grid/emotion.d.ts new file mode 100644 index 0000000000..34c6161062 --- /dev/null +++ b/types/rebass__grid/emotion.d.ts @@ -0,0 +1 @@ +export * from './index' \ No newline at end of file diff --git a/types/rebass__grid/index.d.ts b/types/rebass__grid/index.d.ts index 3f5012851f..918004bfca 100644 --- a/types/rebass__grid/index.d.ts +++ b/types/rebass__grid/index.d.ts @@ -4,6 +4,7 @@ // Victor Orlov // Louis Hache // Adam Lavin +// Erin Noe-Payne // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 diff --git a/types/rebass__grid/rebass__grid-tests.tsx b/types/rebass__grid/rebass__grid-tests.tsx index 147f3ff084..562091952b 100644 --- a/types/rebass__grid/rebass__grid-tests.tsx +++ b/types/rebass__grid/rebass__grid-tests.tsx @@ -1,6 +1,7 @@ import * as React from "react"; import { Flex, Box } from "@rebass/grid"; import { css } from "styled-components"; +import * as Emotion from "@rebass/grid/emotion"; const Layout = () => ( @@ -9,3 +10,11 @@ const Layout = () => ( ); const cssTest = ; + +const EmotionLayout = () => ( + + + +); + +const emotionCssTest = ; diff --git a/types/rebass__grid/tsconfig.json b/types/rebass__grid/tsconfig.json index 419413e066..b2c3ecb0e5 100644 --- a/types/rebass__grid/tsconfig.json +++ b/types/rebass__grid/tsconfig.json @@ -14,7 +14,8 @@ "../" ], "paths": { - "@rebass/grid": ["rebass__grid"] + "@rebass/grid": ["rebass__grid"], + "@rebass/grid/emotion": ["rebass__grid/emotion"] }, "types": [], "noEmit": true, @@ -23,6 +24,7 @@ }, "files": [ "index.d.ts", + "emotion.d.ts", "rebass__grid-tests.tsx" ] } \ No newline at end of file From e060dd0398d5aedf8d01330749bbd05366c849e8 Mon Sep 17 00:00:00 2001 From: Eric Hwang Date: Fri, 22 Mar 2019 18:28:50 -0700 Subject: [PATCH 041/710] [sharedb] Update type signatures for Backend #use and #addProjection Backend#use(action, listener) now gets rich type information on listener params, by using the same pattern as addEventListener in TypeScript's built-in DOM type definitions. This also tweaks some method param types on the base sharedb Backend class, to better match the JS. --- types/sharedb/index.d.ts | 128 +++++++++++++++++++++++++++++++-- types/sharedb/lib/sharedb.d.ts | 14 +++- types/sharedb/sharedb-tests.ts | 87 ++++++++++++++++++++++ 3 files changed, 221 insertions(+), 8 deletions(-) diff --git a/types/sharedb/index.d.ts b/types/sharedb/index.d.ts index 0f0f5575fd..7657075f8e 100644 --- a/types/sharedb/index.d.ts +++ b/types/sharedb/index.d.ts @@ -1,7 +1,9 @@ // Type definitions for sharedb 1.0 // Project: https://github.com/share/sharedb // Definitions by: Steve Oney +// Eric Hwang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /// @@ -18,20 +20,33 @@ export = sharedb; declare class sharedb { constructor(options?: {db?: any, pubsub?: sharedb.PubSub, disableDocAction?: boolean, disableSpaceDelimitedActions?: boolean}); - connect: () => sharedb.Connection; - addProjection(name: string, collection: string, fields: {}): any; + connect: (connection?: any, req?: any) => sharedb.Connection; + /** + * Registers a projection that can be used from clients just like a normal collection. + * + * @param name name of the projection + * @param collection name of the backing collection + * @param fields field whitelist for the projection + */ + addProjection(name: string, collection: string, fields: ProjectionFields): void; listen(stream: any): void; - close(callback?: (err: Error) => any): void; - use(action: sharedb.UseAction, fn: sharedb.UseCallback): void; + close(callback?: (err?: Error) => any): void; + /** + * Registers a server middleware function. + * + * @param action name of an action from https://github.com/share/sharedb#middlewares + * @param fn listener invoked when the specified action occurs + */ + use( + action: A, + fn: (context: middleware.ActionContextMap[A], callback: (err?: any) => void) => void, + ): void; static types: { register: (type: { name?: string, uri?: string, [key: string]: any}) => void; }; } declare namespace sharedb { - type UseAction = 'connect' | 'op' | 'doc' | 'query' | 'submit' | 'apply' | 'commit' | 'after submit' | 'receive'; - type UseCallback = ((request: {action: UseAction, agent: any, req: any, collection: string, id: string, query: any, op: ShareDB.RawOp}, callback: () => void) => void); - abstract class DB { projectsSnapshots: boolean; disableSubscribe: boolean; @@ -100,3 +115,102 @@ declare namespace sharedb { type Path = ShareDB.Path; type ShareDBSourceOptions = ShareDB.ShareDBSourceOptions; } + +declare namespace middleware { + interface ActionContextMap { + afterSubmit: SubmitContext; + apply: ApplyContext; + commit: CommitContext; + connect: ConnectContext; + doc: DocContext; // Deprecated, use 'readSnapshots' instead. + op: OpContext; + query: QueryContext; + receive: ReceiveContext; + readSnapshots: ReadSnapshotsContext; + submit: SubmitContext; + } + + interface BaseContext { + action: keyof ActionContextMap; + agent: any; + backend: sharedb; + } + + interface ApplyContext extends BaseContext, SubmitRequest { + } + + interface CommitContext extends BaseContext, SubmitRequest { + } + + interface ConnectContext extends BaseContext { + stream: any; + req: any; // Property always exists, value may be undefined + } + + interface DocContext extends BaseContext { + collection: string; + id: string; + snapshot: ShareDB.Snapshot; + } + + interface OpContext extends BaseContext { + collection: string; + id: string; + op: ShareDB.Op; + } + + interface QueryContext extends BaseContext { + index: string; + collection: string; + projection: Projection | undefined; + fields: ProjectionFields | undefined; + channel: string; + query: any; + options: any; + db: sharedb.DB | null; + snapshotProjection: Projection | null; + } + + interface ReceiveContext extends BaseContext { + data: any; + } + + interface ReadSnapshotsContext extends BaseContext { + collection: string; + snapshots: ShareDB.Snapshot[]; + snapshotType: SnapshotType; + } + + type SnapshotType = 'current' | 'byVersion' | 'byTimestamp'; + + interface SubmitContext extends BaseContext, SubmitRequest { + } +} + +interface Projection { + target: string; + fields: ProjectionFields; +} + +interface ProjectionFields { + [propertyName: string]: true; +} + +interface SubmitRequest { + index: string; + projection: Projection | undefined; + collection: string; + id: string; + op: sharedb.Op; + options: any; + start: number; + + saveMilestoneSnapshot: boolean | null; + suppressPublish: boolean | null; + maxRetries: number | null; + retries: number; + + snapshot: ShareDB.Snapshot | null; + ops: ShareDB.Op[]; + channels: string[] | null; +} diff --git a/types/sharedb/lib/sharedb.d.ts b/types/sharedb/lib/sharedb.d.ts index 426eac5a0e..169b7e6674 100644 --- a/types/sharedb/lib/sharedb.d.ts +++ b/types/sharedb/lib/sharedb.d.ts @@ -1,7 +1,19 @@ import { EventEmitter } from 'events'; export type Path = ReadonlyArray; -export type Snapshot = number; +export interface Snapshot { + id: string; + v: number; + type: string | null; + data: any; // JSON object, could be undefined + m: SnapshotMeta | null; +} + +export interface SnapshotMeta { + ctime: number; + mtime: number; + [key: string]: any; +} export interface AddNumOp { p: Path; na: number; } diff --git a/types/sharedb/sharedb-tests.ts b/types/sharedb/sharedb-tests.ts index 55c3dc797d..a4e35d3507 100644 --- a/types/sharedb/sharedb-tests.ts +++ b/types/sharedb/sharedb-tests.ts @@ -30,7 +30,94 @@ class WebSocketJSONStream extends Duplex { } const backend = new ShareDB(); + +backend.addProjection('notes_minimal', 'notes', {title: true, creator: true, lastUpdateTime: true}); + +// Exercise middleware (backend.use) +type SubmitRelatedActions = 'afterSubmit' | 'apply' | 'commit' | 'submit'; +const submitRelatedActions: SubmitRelatedActions[] = ['afterSubmit', 'apply', 'commit', 'submit']; +for (const action of submitRelatedActions) { + backend.use(action, (request, callback) => { + console.log( + request.action, + request.agent, + request.backend, + request.index, + request.collection, + request.projection, + request.id, + request.op, + request.options, + request.snapshot, + request.ops, + request.channels, + ); + callback(); + }); +} +backend.use('connect', (context, callback) => { + console.log( + context.action, + context.agent, + context.backend, + context.stream, + context.req, + ); + callback(); +}); +backend.use('op', (context, callback) => { + console.log( + context.action, + context.agent, + context.backend, + context.collection, + context.id, + context.op, + ); + callback(); +}); +backend.use('query', (context, callback) => { + console.log( + context.action, + context.agent, + context.backend, + context.index, + context.collection, + context.projection, + context.fields, + context.channel, + context.query, + context.options, + context.snapshotProjection, + ); + callback(); +}); +backend.use('receive', (context, callback) => { + console.log( + context.action, + context.agent, + context.backend, + context.data, + ); + callback(); +}); +backend.use('readSnapshots', (context, callback) => { + console.log( + context.action, + context.agent, + context.backend, + context.collection, + context.snapshots, + context.snapshotType, + ); + callback(); +}); + const connection = backend.connect(); +const netRequest = {}; // Passed through to 'connect' middleware, not used by sharedb itself +const connectionWithReq = backend.connect(null, netRequest); +const reboundConnection = backend.connect(backend.connect(), netRequest); + const doc = connection.get('examples', 'counter'); doc.fetch((err) => { From f6b15715e2b7131bb84105f50d114549d8ff244a Mon Sep 17 00:00:00 2001 From: breeze9527 Date: Sat, 23 Mar 2019 12:28:03 +0800 Subject: [PATCH 042/710] Added type definition for non-npm package amap-js-api-place-search --- .../amap-js-api-place-search-tests.ts | 435 +++++++++++ types/amap-js-api-place-search/index.d.ts | 737 ++++++++++++++++++ types/amap-js-api-place-search/tsconfig.json | 24 + types/amap-js-api-place-search/tslint.json | 3 + 4 files changed, 1199 insertions(+) create mode 100644 types/amap-js-api-place-search/amap-js-api-place-search-tests.ts create mode 100644 types/amap-js-api-place-search/index.d.ts create mode 100644 types/amap-js-api-place-search/tsconfig.json create mode 100644 types/amap-js-api-place-search/tslint.json diff --git a/types/amap-js-api-place-search/amap-js-api-place-search-tests.ts b/types/amap-js-api-place-search/amap-js-api-place-search-tests.ts new file mode 100644 index 0000000000..b4c787c301 --- /dev/null +++ b/types/amap-js-api-place-search/amap-js-api-place-search-tests.ts @@ -0,0 +1,435 @@ +declare const map: AMap.Map; +declare const div: HTMLElement; +declare const lnglat: AMap.LngLat; +declare const lnglatTuple: [number, number]; +declare const bounds: AMap.Bounds; +declare const polygon: AMap.Polygon; +declare const lang: AMap.Lang; + +// $ExpectType PlaceSearch +const placeSearch = new AMap.PlaceSearch(); +// $ExpectType PlaceSearch +new AMap.PlaceSearch({}); +// $ExpectType PlaceSearch +new AMap.PlaceSearch({ + city: '深圳', + citylimit: true, + children: 1, + type: 'é¤é¥®æœåŠ¡', + lang: 'zh_cn', + pageSize: 10, + pageIndex: 10, + extensions: 'all', + map, + panel: div, + showCover: true, + renderStyle: 'newpc', + autoFitView: true +}); + +// $ExpectType void +placeSearch.search('keyword', (status, result) => { + const temp: 'error' | 'complete' | 'no_data' = status; + // $ExpectType string | SearchResult + result; + if (typeof result !== 'string') { + // $ExpectType string + result.info; + // $ExpectType PoiList + result.poiList; + // $ExpectType string[] | undefined + result.keywordList; + // $ExpectType CityInfo[] | undefined + result.cityList; + + const poiList = result.poiList; + // $ExpectType number + poiList.pageIndex; + // $ExpectType number + poiList.pageSize; + // $ExpectType number + poiList.count; + + const poi = poiList.pois[0]; + // $ExpectType string + poi.address; + // $ExpectType number + poi.distance; + // $ExpectType string + poi.id; + // $ExpectType LngLat | null + poi.location; + // $ExpectType string + poi.name; + // $ExpectType string + poi.shopinfo; + // $ExpectType string + poi.tel; + // $ExpectType string + poi.type; + if ('website' in poi) { + // $ExpectType string + poi.adcode; + // $ExpectType string + poi.adname; + // $ExpectType string + poi.citycode; + // $ExpectType string + poi.cityname; + // $ExpectType boolean + poi.discount; + // $ExpectType string + poi.email; + // $ExpectType LngLat | null + poi.entr_location; + // $ExpectType LngLat | null + poi.exit_location; + // $ExpectType boolean + poi.groupbuy; + if (poi.indoor_map) { + const indoorData = poi.indoor_data; + // $ExpectType string + indoorData.cpid; + // $ExpectType string + indoorData.floor; + // $ExpectType string + indoorData.truefloor; + } + poi.pcode; + // $ExpectType PoiPhoto[] + poi.photos; + // $ExpectType string + poi.pname; + // $ExpectType string + poi.postcode; + // $ExpectType string + poi.website; + + const photo = poi.photos[0]; + // $ExpectType string + photo.title; + // $ExpectType string + photo.url; + // $ExpectType Groupbuy[] | undefined + poi.groupbuys; + if (poi.groupbuys) { + const groupbuy = poi.groupbuys[0]; + // $ExpectType string + groupbuy.title; + // $ExpectType string + groupbuy.type_code; + // $ExpectType string + groupbuy.type; + // $ExpectType string + groupbuy.detail; + // $ExpectType string + groupbuy.stime; + // $ExpectType string + groupbuy.etime; + // $ExpectType number + groupbuy.count; + // $ExpectType number + groupbuy.sold_num; + // $ExpectType number + groupbuy.original_price; + // $ExpectType number + groupbuy.groupbuy_price; + // $ExpectType number + groupbuy.discount; + // $ExpectType string + groupbuy.ticket_address; + // $ExpectType string + groupbuy.ticket_tel; + // $ExpectType PoiPhoto[] + groupbuy.photos; + // $ExpectType string + groupbuy.url; + // $ExpectType string + groupbuy.provider; + } + // $ExpectType Discount[] | undefined + poi.discounts; + if (poi.discounts) { + const discount = poi.discounts[0]; + // $ExpectType string + discount.title; + // $ExpectType string + discount.detail; + // $ExpectType string + discount.start_time; + // $ExpectType string + discount.end_time; + // $ExpectType number + discount.sold_num; + // $ExpectType PoiPhoto[] + discount.photos; + // $ExpectType string + discount.url; + // $ExpectType string + discount.provider; + } + if (poi.deep_type === 'CINEMA') { + // $ExpectType Cinema + const cinema = poi.cinema; + // $ExpectType string + cinema.intro; + // $ExpectType string + cinema.rating; + // $ExpectType string + cinema.deep_src; + // $ExpectType string + cinema.parking; + // $ExpectType string + cinema.opentime_GDF; + // $ExpectType string + cinema.opentime; + // $ExpectType PoiPhoto[] + cinema.photos; + } + if (poi.deep_type === 'DINING') { + // $ExpectType Dining + const dining = poi.dining; + // $ExpectType string + dining.cuisines; + // $ExpectType string + dining.tag; + // $ExpectType string + dining.intro; + // $ExpectType string + dining.rating; + // $ExpectType string + dining.cp_rating; + // $ExpectType string + dining.deep_src; + // $ExpectType string + dining.taste_rating; + // $ExpectType string + dining.environment_rating; + // $ExpectType string + dining.service_rating; + // $ExpectType string + dining.cost; + // $ExpectType string + dining.recommend; + // $ExpectType string + dining.atmosphere; + // $ExpectType string + dining.ordering_wap_url; + // $ExpectType string + dining.ordering_web_url; + // $ExpectType string + dining.ordering_app_url; + // $ExpectType string + dining.opentime_GDF; + // $ExpectType string + dining.opentime; + // $ExpectType string + dining.addition; + // $ExpectType PoiPhoto[] + dining.photos; + } + if (poi.deep_type === 'SCENIC') { + // $ExpectType Scenic + const scenic = poi.scenic; + // $ExpectType string + scenic.intro; + // $ExpectType string + scenic.rating; + // $ExpectType string + scenic.deep_src; + // $ExpectType string + scenic.level; + // $ExpectType string + scenic.price; + // $ExpectType string + scenic.season; + // $ExpectType string + scenic.recommend; + // $ExpectType string + scenic.theme; + // $ExpectType string + scenic.ordering_wap_url; + // $ExpectType string + scenic.ordering_web_url; + // $ExpectType string + scenic.opentime_GDF; + // $ExpectType string + scenic.opentime; + // $ExpectType PoiPhoto[] + scenic.photos; + } + if (poi.deep_type === 'HOTEL') { + // $ExpectType Hotel + const hotel = poi.hotel; + // $ExpectType string + hotel.rating; + // $ExpectType string + hotel.star; + // $ExpectType string + hotel.intro; + // $ExpectType string + hotel.lowest_price; + // $ExpectType string + hotel.faci_rating; + // $ExpectType string + hotel.health_rating; + // $ExpectType string + hotel.environment_rating; + // $ExpectType string + hotel.service_rating; + // $ExpectType string + hotel.traffic; + // $ExpectType string + hotel.addition; + // $ExpectType string + hotel.deep_src; + // $ExpectType PoiPhoto[] + hotel.photos; + } + } + + if (result.cityList) { + const city = result.cityList[0]; + // $ExpectType string + city.adcode; + // $ExpectType string + city.citycode; + // $ExpectType number + city.count; + // $ExpectType string + city.name; + } + } else { + // $ExpectType string + result; + } +}); + +// $ExpectType void +placeSearch.searchNearBy('keyword', lnglat, 10, (status, result) => { + const temp: 'error' | 'complete' | 'no_data' = status; + // $ExpectType string | SearchResult + result; +}); +// $ExpectType void +placeSearch.searchNearBy('keyword', lnglatTuple, 10, () => { }); + +// $ExpectType void +placeSearch.searchInBounds('keyword', bounds, (status, result) => { + const temp: 'error' | 'complete' | 'no_data' = status; + // $ExpectType string | SearchResult + result; +}); +// $ExpectType void +placeSearch.searchInBounds('keyword', polygon, () => { }); + +// $ExpectType void +placeSearch.getDetails('id', (status, result) => { + const temp: 'error' | 'complete' | 'no_data' = status; + // $ExpectType string | SearchResult + result; +}); + +// $ExpectType void +placeSearch.setType('type'); +// $ExpectType void +placeSearch.setType(); + +// $ExpectType void +placeSearch.setCityLimit(true); +// $ExpectType void +placeSearch.setCityLimit(); + +// $ExpectType void +placeSearch.setPageIndex(1); +// $ExpectType void +placeSearch.setPageIndex(); + +// $ExpectType void +placeSearch.setPageSize(1); +// $ExpectType void +placeSearch.setPageSize(); + +// $ExpectType void +placeSearch.setCity('city'); +// $ExpectType void +placeSearch.setCity(); + +// $ExpectType void +placeSearch.setLang(lang); +// $ExpectType void +placeSearch.setLang(); + +// $ExpectType "zh_cn" | "en" | "zh_en" | undefined +placeSearch.getLang(); + +// $ExpectType void +placeSearch.clear(); + +// $ExpectType void +placeSearch.poiOnAMAP({ + id: 'id', +}); +// $ExpectType void +placeSearch.poiOnAMAP({ + location: lnglat, + id: 'id', + name: 'name' +}); + +// $ExpectType void +placeSearch.detailOnAMAP({ + id: 'id', +}); +// $ExpectType void +placeSearch.detailOnAMAP({ + location: lnglat, + id: 'id', + name: 'name' +}); + +// $ExpectType void +placeSearch.open(); + +// $ExpectType void +placeSearch.close(); + +placeSearch.on('complete', (event: AMap.PlaceSearch.EventMap['complete']) => { + // $ExpectType "complete" + event.type; + // $ExpectType string + event.info; + // $ExpectType PoiList + event.poiList; + // $ExpectType string[] | undefined + event.keywordList; + // $ExpectType CityInfo[] | undefined + event.cityList; +}); + +placeSearch.on('listElementClick', (event: AMap.PlaceSearch.EventMap['listElementClick']) => { + // $ExpectType MouseEvent + event.event; + // $ExpectType string + event.id; + // $ExpectType number + event.index; + // $ExpectType Marker + event.marker; + // $ExpectType HTMLLIElement + event.listElement; +}); + +placeSearch.on('markerClick', (event: AMap.PlaceSearch.EventMap['markerClick']) => { + const markerEvent = event.event; + // $ExpectType Marker + markerEvent.target; + // $ExpectType string + event.id; + // $ExpectType number + event.index; + // $ExpectType Marker + event.marker; + // $ExpectType HTMLLIElement + event.listElement; +}); diff --git a/types/amap-js-api-place-search/index.d.ts b/types/amap-js-api-place-search/index.d.ts new file mode 100644 index 0000000000..4a333f3b2b --- /dev/null +++ b/types/amap-js-api-place-search/index.d.ts @@ -0,0 +1,737 @@ +// Type definitions for non-npm package amap-js-api-place-search 1.4 +// Project: https://lbs.amap.com/api/javascript-api/reference/search#m_AMap.PlaceSearch +// Definitions by: breeze9527 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +declare namespace AMap { + namespace PlaceSearch { + interface EventMap { + complete: Event<'complete', SearchResult>; + error: Event<'error', { info: string }>; + selectChanged: Event<'selectChanged', { + selected: SelectChangeEventData | EventMap['markerClick'] | EventMap['listElementClick']; + lastSelected: SelectChangeEventData | EventMap['markerClick'] | EventMap['listElementClick'] | null; + }>; + listElementClick: SelectChangeEvent<'listElementClick', MouseEvent>; + markerClick: SelectChangeEvent<'markerClick', Marker.EventMap['click']>; + // internal + renderComplete: Event<'renderComplete', { + result: SelectChangeEventData[]; + markers: Marker[]; + listElements: HTMLElement[]; + }>; + infoWindowClick: Event<'infoWindowClick', SelectChangeEventData & { + event: MouseEvent; + infoWindow: InfoWindow; + infoWindowContentDom: HTMLDivElement; + }>; + willClear: Event<'willClear', { + id: string; + index: number; + data: Poi[]; + }>; + markerDestoryed: Event<'markerDestoryed', SelectChangeEventData>; // typo in source code + listElementDetroyed: Event<'listElementDetroyed', SelectChangeEventData>; // typo too + } + + interface SelectChangeEventData { + /** + * 当å‰é€‰ä¸­çš„POIçš„ID + */ + id: string; + /** + * 索引 + */ + index: number; + /** + * 当å‰é€‰ä¸­çš„POI对应的在地图中的Marker对象 + */ + marker: Marker; + /** + * 当å‰é€‰ä¸­çš„POIåœ¨ç»“æžœé¢æ¿ä¸­å¯¹åº”的列表项 + */ + listElement: HTMLLIElement; + /** + * 当å‰é€‰ä¸­çš„POIçš„ä¿¡æ¯ + */ + data: Poi[]; + } + type SelectChangeEvent = Event; + interface PoiPhoto { + /** + * 图片åç§° + */ + title: string; + /** + * 图片url + */ + url: string; + } + interface PoiBase { + /** + * 全局唯一ID + */ + id: string; + /** + * åç§° + */ + name: string; + /** + * 兴趣点类型 + */ + type: string; + /** + * 兴趣点ç»çº¬åº¦ + */ + location: LngLat | null; + /** + * åœ°å€ + */ + address: string; + /** + * 离中心点è·ç¦» + */ + distance: number; + /** + * ç”µè¯ + */ + tel: string; + shopinfo: string; + children?: any[]; // TODO Array<{location: LngLat | null}> + } + interface Groupbuy { + /** + * 团购标题 + */ + title: string; + /** + * å›¢è´­åˆ†ç±»ä»£ç  + */ + type_code: string; + /** + * 团购分类 + */ + type: string; + /** + * 团购详情 + */ + detail: string; + /** + * 团购开始时间 + */ + stime: string; + /** + * å›¢è´­ç»“æŸæ—¶é—´ + */ + etime: string; + /** + * å›¢è´­æ€»é‡ + */ + count: number; + /** + * å·²å–å‡ºæ•°é‡ + */ + sold_num: number; + /** + * 原价 + */ + original_price: number; + /** + * 折扣价 + */ + groupbuy_price: number; + /** + * 折扣 + */ + discount: number; + /** + * å–ç¥¨åœ°å€ + */ + ticket_address: string; + /** + * å–ç¥¨ç”µè¯ + */ + ticket_tel: string; + /** + * å›¾ç‰‡ä¿¡æ¯ + */ + photos: PoiPhoto[]; + /** + * æ¥æºurl + */ + url: string; + /** + * æ¥æºæ ‡è¯† + */ + provider: string; + } + interface Discount { + /** + * 优惠标题 + */ + title: string; + /** + * 优惠详情 + */ + detail: string; + /** + * 开始时间 + */ + start_time: string; + /** + * ç»“æŸæ—¶é—´ + */ + end_time: string; + /** + * å·²å–å‡ºæ•°é‡ + */ + sold_num: number; + /** + * 图片信æ¯åˆ—表 + */ + photos: PoiPhoto[]; + /** + * æ¥æºurl + */ + url: string; + /** + * æ¥æºæ ‡è¯† + */ + provider: string; + } + interface Cinema { + /** + * 简介 + */ + intro: string; + /** + * 综åˆè¯„分 + */ + rating: string; + /** + * ä¿¡æ¯æ¥æº + */ + deep_src: string; + /** + * åœè½¦åœºè®¾æ–½ + */ + parking: string; + /** + * 规范格å¼çš„è¥ä¸šæ—¶é—´ + */ + opentime_GDF: string; + /** + * éžè§„范格å¼çš„è¥ä¸šæ—¶é—´ + */ + opentime: string; + /** + * 图片信æ¯åˆ—表 + */ + photos: PoiPhoto[]; + } + interface Dining { + /** + * èœç³» + */ + cuisines: string; + /** + * 标签 + */ + tag: string; + /** + * 简介 + */ + intro: string; + /** + * 综åˆè¯„分 + */ + rating: string; + /** + * 啿•°æ®æºçš„评分 + */ + cp_rating: string; + /** + * ä¿¡æ¯æ¥æº + */ + deep_src: string; + /** + * å£å‘³è¯„分 + */ + taste_rating: string; + /** + * 环境评分 + */ + environment_rating: string; + /** + * æœåŠ¡è¯„åˆ† + */ + service_rating: string; + /** + * äººå‡æ¶ˆè´¹ + */ + cost: string; + /** + * ç‰¹è‰²èœ + */ + recommend: string; + /** + * 氛围 + */ + atmosphere: string; + /** + * 订é¤wap链接 + */ + ordering_wap_url: string; + /** + * 订é¤web链接 + */ + ordering_web_url: string; + /** + * 订é¤APP URL + */ + ordering_app_url: string; + /** + * 规范格å¼çš„è¥ä¸šæ—¶é—´ + */ + opentime_GDF: string; + /** + * éžè§„范格å¼çš„è¥ä¸šæ—¶é—´ + */ + opentime: string; + /** + * é¤åŽ…ç‰¹è‰² + */ + addition: string; + /** + * 图片信æ¯åˆ—表 + */ + photos: PoiPhoto[]; + } + interface Scenic { + /** + * 简介 + */ + intro: string; + /** + * 综åˆè¯„分 + */ + rating: string; + /** + * ä¿¡æ¯æ¥æº + */ + deep_src: string; + /** + * 景区国标级别 + */ + level: string; + /** + * 门票价格 + */ + price: string; + /** + * é€‚åˆæ¸¸çŽ©çš„å­£èŠ‚ + */ + season: string; + /** + * æŽ¨èæ™¯ç‚¹ + */ + recommend: string; + /** + * 景区主题 + */ + theme: string; + /** + * wap购票链接 + */ + ordering_wap_url: string; + /** + * web购票链接 + */ + ordering_web_url: string; + /** + * 规范格å¼çš„è¥ä¸šæ—¶é—´ + */ + opentime_GDF: string; + /** + * éžè§„范格å¼çš„è¥ä¸šæ—¶é—´ + */ + opentime: string; + /** + * 图片信æ¯åˆ—表 + */ + photos: PoiPhoto[]; + } + interface Hotel { + /** + * 综åˆè¯„分 + */ + rating: string; + /** + * 星级 + */ + star: string; + /** + * 简介 + */ + intro: string; + /** + * 最低房价 + */ + lowest_price: string; + /** + * 设施评分 + */ + faci_rating: string; + /** + * å«ç”Ÿè¯„分 + */ + health_rating: string; + /** + * 环境评分 + */ + environment_rating: string; + /** + * æœåŠ¡è¯„åˆ† + */ + service_rating: string; + /** + * 交通æç¤º + */ + traffic: string; + /** + * 特色æœåŠ¡ + */ + addition: string; + /** + * ä¿¡æ¯æ¥æº + */ + deep_src: string; + /** + * 图片信æ¯åˆ—表 + */ + photos: PoiPhoto[]; + } + type PoiExt = PoiBase & { + /** + * ç½‘å€ + */ + website: string; + /** + * 所在çœä»½ç¼–ç  + */ + pcode: string; + /** + * æ‰€åœ¨åŸŽå¸‚ç¼–ç  + */ + citycode: string; + /** + * æ‰€åœ¨åŒºåŸŸç¼–ç  + */ + adcode: string; + /** + * 邮编 + */ + postcode: string; + /** + * 所在çœä»½ + */ + pname: string; + /** + * 所在城市åç§° + */ + cityname: string; + /** + * 所在行政区åç§° + */ + adname: string; + /** + * 电å­é‚®ç®± + */ + email: string; + /** + * 照片 + */ + photos: PoiPhoto[]; + /** + * å…¥å£ç»çº¬åº¦ + */ + entr_location: LngLat | null; + /** + * 出å£ç»çº¬åº¦ + */ + exit_location: LngLat | null; + /** + * @deprecated æ˜¯å¦æœ‰å›¢è´­ä¿¡æ¯ + */ + groupbuy: boolean; + /** + * @deprecated æ˜¯å¦æœ‰ä¼˜æƒ ä¿¡æ¯ + */ + discount: boolean; + } & ({ + indoor_map: true; + indoor_data: { + cpid: string; + floor: string; + truefloor: string; + }; + } | { + indoor_map: false; + }) & { + /** + * @deprecated å›¢è´­ä¿¡æ¯ + */ + groupbuys?: Groupbuy[]; + /** + * @deprecated ä¼˜æƒ ä¿¡æ¯ + */ + discounts?: Discount[]; + } & ({ + deep_type: 'CINEMA'; + /** + * @deprecated å½±é™¢ç±»æ·±åº¦ä¿¡æ¯ + */ + cinema: Cinema; + } | { + deep_type: 'DINING'; + /** + * @deprecated é¤é¥®ç±»æ·±åº¦ä¿¡æ¯ + */ + dining: Dining; + } | { + deep_type: 'SCENIC'; + /** + * @deprecated æ™¯ç‚¹ç±»æ·±åº¦ä¿¡æ¯ + */ + scenic: Scenic; + } | { + deep_type: 'HOTEL'; + /** + * @deprecated é…’åº—ç±»æ·±åº¦ä¿¡æ¯ + */ + hotel: Hotel; + }); + interface Options { + /** + * 兴趣点城市 + */ + city?: string; + /** + * 是å¦å¼ºåˆ¶é™åˆ¶åœ¨è®¾ç½®çš„城市内æœç´¢ + */ + citylimit?: boolean; + /** + * æ˜¯å¦æŒ‰ç…§å±‚级展示å­POIæ•°æ® + * children=1,展示å­èŠ‚ç‚¹POIæ•°æ®ï¼Œchildren=0,ä¸å±•示å­èŠ‚ç‚¹æ•°æ® + */ + children?: number; + /** + * 兴趣点类别,多个类别用“|â€åˆ†å‰² + */ + type?: string; + /** + * 检索语言类型 + */ + lang?: Lang; + /** + * å•é¡µæ˜¾ç¤ºç»“æžœæ¡æ•° + */ + pageSize?: number; + /** + * é¡µç  + */ + pageIndex?: number; + /** + * 是å¦è¿”å›žè¯¦ç»†ä¿¡æ¯ + * base返回基本地å€ä¿¡æ¯ï¼›all返回基本+è¯¦ç»†ä¿¡æ¯ + */ + extensions?: 'base' | 'all'; + /** + * Map对象 + */ + map?: Map; + /** + * 结果列表的HTML容器id或容器元素 + */ + panel?: string | HTMLElement; + /** + * 是å¦åœ¨åœ°å›¾ä¸Šæ˜¾ç¤ºå‘¨è¾¹æœç´¢çš„圆或者范围æœç´¢çš„多边形 + */ + showCover?: boolean; + /** + * 绘制的UI风格 + */ + renderStyle?: 'newpc' | 'default'; + /** + * 是å¦è‡ªåŠ¨è°ƒæ•´åœ°å›¾è§†é‡Žä½¿ç»˜åˆ¶çš„Marker点都处于视å£çš„å¯è§èŒƒå›´ + */ + autoFitView?: boolean; + + // internal + renderEngine?: string; + rankBy?: string; + } + interface PoiList { + /** + * Poi列表 + */ + pois: Poi[]; // PlaceSearchPoiBase[] | PlaceSearchPoiExt[]; + /** + * é¡µç  + */ + pageIndex: number; + /** + * å•页结果数 + */ + pageSize: number; + /** + * 查询结果总数 + */ + count: number; + } + interface CityInfo { + /** + * 建议城市åç§° + */ + name: string; + /** + * åŸŽå¸‚ç¼–ç  + */ + citycode: string; + /** + * è¡Œæ”¿åŒºç¼–ç  + */ + adcode: string; + /** + * 该城市的建议结果数目 + */ + count: number; + } + interface SearchResult { + /** + * æˆåŠŸçŠ¶æ€è¯´æ˜Ž + */ + info: string; + /** + * 兴趣点列表 + */ + poiList: PoiList; + /** + * 建议关键字列表 + */ + keywordList?: string[]; + /** + * 城市建议列表 + */ + cityList?: CityInfo[]; + } + type Poi = PoiBase | PoiExt; + type SearchStatus = 'complete' | 'error' | 'no_data'; + } + class PlaceSearch extends EventEmitter { + /** + * 地点æœç´¢æœåŠ¡ + * @param options 选项 + */ + constructor(options?: PlaceSearch.Options); + /** + * æ ¹æ®å…³é”®å­—æœç´¢ + * @param keyword æ ¹æ®å…³é”®å­—æœç´¢ + * @param callback 回调 + */ + search( + keyword: string, + callback: (status: PlaceSearch.SearchStatus, result: string | PlaceSearch.SearchResult) => void + ): void; + /** + * 周边查询 + * @param keyword 关键字 + * @param center æœç´¢ä¸­å¿ƒ + * @param radius æœç´¢åŠå¾„ + * @param callback 回调 + */ + searchNearBy( + keyword: string, + center: LocationValue, + radius: number, + callback: (status: PlaceSearch.SearchStatus, result: string | PlaceSearch.SearchResult) => void + ): void; + /** + * æ ¹æ®èŒƒå›´å’Œå…³é”®è¯è¿›è¡ŒèŒƒå›´æŸ¥è¯¢ + * @param keyword 关键字 + * @param bounds æœç´¢èŒƒå›´ + * @param callback 回调 + */ + searchInBounds( + keyword: string, + bounds: Bounds | Polygon, + callback: (status: PlaceSearch.SearchStatus, result: string | PlaceSearch.SearchResult) => void + ): void; + /** + * æ ¹æ®POIID 查询POI è¯¦ç»†ä¿¡æ¯ + * @param POIID POIID + * @param callback æœç´¢å›žè°ƒ + */ + getDetails( + POIID: string, + callback: (status: PlaceSearch.SearchStatus, result: string | PlaceSearch.SearchResult) => void + ): void; + /** + * 设置查询类别 + * @param type 查询类别 + */ + setType(type?: string): void; + /** + * 设置是å¦å¼ºåˆ¶é™åˆ¶åŸŽå¸‚ + * @param limit 是å¦å¼ºåˆ¶é™åˆ¶åŸŽå¸‚ + */ + setCityLimit(limit?: boolean): void; + /** + * 设置查询结果特定页数 + * @param pageIndex é¡µç  + */ + setPageIndex(pageIndex?: number): void; + /** + * 设置查询å•页结果数 + * @param pageSize 结果数 + */ + setPageSize(pageSize?: number): void; + /** + * 设置查询城市 + * @param city 城市 + */ + setCity(city?: string): void; + /** + * 设置检索语言类型 + * @param lang 语言类型 + */ + setLang(lang?: Lang): void; + /** + * èŽ·å–æ£€ç´¢è¯­è¨€ç±»åž‹ + */ + getLang(): Lang | undefined; + /** + * 清除æœç´¢ç»“æžœ + */ + clear(): void; + /** + * 唤起高德地图客户端marker页 + * @param obj å”¤èµ·å‚æ•° + */ + poiOnAMAP(obj: { location?: LocationValue; id: string; name?: string; }): void; + /** + * 唤起高德地图客户端POI详情页 + * @param obj å”¤èµ·å‚æ•° + */ + detailOnAMAP(obj: { location?: LocationValue; id: string; name?: string; }): void; + + // internal + open(): void; + close(): void; + } +} diff --git a/types/amap-js-api-place-search/tsconfig.json b/types/amap-js-api-place-search/tsconfig.json new file mode 100644 index 0000000000..e3259e1b01 --- /dev/null +++ b/types/amap-js-api-place-search/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noEmit": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "amap-js-api-place-search-tests.ts" + ] +} diff --git a/types/amap-js-api-place-search/tslint.json b/types/amap-js-api-place-search/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/amap-js-api-place-search/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From 81e531f9ad95adaaf59fbd6d5e9d6be775bb5d2e Mon Sep 17 00:00:00 2001 From: Ivan Ha Date: Sat, 16 Mar 2019 19:08:45 +0800 Subject: [PATCH 043/710] ramda: support R.__ in R.propOr --- types/ramda/index.d.ts | 2 ++ types/ramda/ramda-tests.ts | 2 ++ 2 files changed, 4 insertions(+) diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index 1078d9a51a..f3dd54dbb5 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -2332,6 +2332,8 @@ declare namespace R { * If the given, non-null object has an own property with the specified name, returns the value of that property. * Otherwise returns the provided default value. */ + propOr(val: T, __: Placeholder, obj: U): (p: string) => V; + propOr(__: Placeholder, p: string, obj: U): (val: T) => V; propOr(val: T, p: string, obj: U): V; propOr(val: T, p: string): (obj: U) => V; propOr(val: T): (p: string, obj: U) => V; diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 6f88d82200..782a85a90b 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -1967,6 +1967,8 @@ class Rectangle { const favoriteWithDefault = R.propOr("Ramda", "favoriteLibrary"); const s2 = favoriteWithDefault(alice); // => 'Ramda' + R.propOr('Ramda', R.__, alice)('name'); // => 'ALICE' + R.propOr(R.__, 'foo', alice)('default'); // => 'default' }; () => { From 26ee14fa13ecf40bdc52cdc962bdd858dfd5c4c6 Mon Sep 17 00:00:00 2001 From: Anton Bortnikov <6088046+ntnbrtnkv@users.noreply.github.com> Date: Sat, 23 Mar 2019 16:49:51 +0500 Subject: [PATCH 044/710] feat: add react-tabs-redux types --- types/react-tabs-redux/TabContent.d.ts | 15 +++++++ types/react-tabs-redux/TabLink.d.ts | 19 ++++++++ types/react-tabs-redux/Tabs.d.ts | 14 ++++++ types/react-tabs-redux/index.d.ts | 8 ++++ .../react-tabs-redux-tests.tsx | 44 +++++++++++++++++++ types/react-tabs-redux/tsconfig.json | 28 ++++++++++++ types/react-tabs-redux/tslint.json | 6 +++ 7 files changed, 134 insertions(+) create mode 100644 types/react-tabs-redux/TabContent.d.ts create mode 100644 types/react-tabs-redux/TabLink.d.ts create mode 100644 types/react-tabs-redux/Tabs.d.ts create mode 100644 types/react-tabs-redux/index.d.ts create mode 100644 types/react-tabs-redux/react-tabs-redux-tests.tsx create mode 100644 types/react-tabs-redux/tsconfig.json create mode 100644 types/react-tabs-redux/tslint.json diff --git a/types/react-tabs-redux/TabContent.d.ts b/types/react-tabs-redux/TabContent.d.ts new file mode 100644 index 0000000000..9c3d5c24a6 --- /dev/null +++ b/types/react-tabs-redux/TabContent.d.ts @@ -0,0 +1,15 @@ +import * as React from 'react'; + +export interface TabContentProps { + children?: React.ReactNode; + for: string | number; + visibleStyle?: object; + isVisible?: boolean; + renderActiveTabContentOnly?: boolean; + disableInlineStyles?: boolean; + className?: string; + visibleClassName?: string; + style?: object; +} + +export declare class TabContent extends React.Component {} diff --git a/types/react-tabs-redux/TabLink.d.ts b/types/react-tabs-redux/TabLink.d.ts new file mode 100644 index 0000000000..392fec2d73 --- /dev/null +++ b/types/react-tabs-redux/TabLink.d.ts @@ -0,0 +1,19 @@ +import * as React from 'react'; + +export interface TabLinkProps { + to: number | string; + component?: string; + handleSelect?: (tab: string, name: string) => void; + onClick?: (event: Event) => void; + children?: React.ReactNode; + isActive?: boolean; + namespace?: string; + activeStyle?: object; + disableInlineStyles?: boolean; + className?: string; + activeClassName?: string; + style?: object; + default?: boolean; +} + +export declare class TabLink extends React.Component {} diff --git a/types/react-tabs-redux/Tabs.d.ts b/types/react-tabs-redux/Tabs.d.ts new file mode 100644 index 0000000000..8f0599c0f5 --- /dev/null +++ b/types/react-tabs-redux/Tabs.d.ts @@ -0,0 +1,14 @@ +import * as React from 'react'; + +export interface TabsProps { + name?: string; + onChange?: (selectedTab: string, name: string) => void; + handleSelect?: (tab: string, name: string) => void; + selectedTab?: string; + activeLinkStyle?: object; + visibleTabStyle?: object; + disableInlineStyles?: boolean; + renderActiveTabContentOnly?: boolean; +} + +export declare class Tabs extends React.Component {} diff --git a/types/react-tabs-redux/index.d.ts b/types/react-tabs-redux/index.d.ts new file mode 100644 index 0000000000..62ee5cc5d1 --- /dev/null +++ b/types/react-tabs-redux/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for react-tabs-redux 4.0 +// Project: https://github.com/patrik-piskay/react-tabs-redux#readme +// Definitions by: Anton Bortnikov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export {Tabs, TabsProps} from './Tabs'; +export {TabLink, TabLinkProps} from './TabLink'; +export {TabContent, TabContentProps} from './TabContent'; diff --git a/types/react-tabs-redux/react-tabs-redux-tests.tsx b/types/react-tabs-redux/react-tabs-redux-tests.tsx new file mode 100644 index 0000000000..758ba7b5c9 --- /dev/null +++ b/types/react-tabs-redux/react-tabs-redux-tests.tsx @@ -0,0 +1,44 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import { + Tabs, + TabLink, + TabContent, + TabsProps, + TabLinkProps, + TabContentProps +} from 'react-tabs-redux'; + +interface TestTabsProps extends TabsProps {} +interface TestTabLinkProps extends TabLinkProps {} +interface TestTabContentProps extends TabContentProps {} + +class TestApp extends React.Component { + onChange = (selectedTab: string, name: string) => { + console.log(`selectedTab: ${selectedTab}`); + console.log(`namespace: ${name}`); + } + + onClick = (event: Event) => { + console.log(`event: ${event.type}`); + } + + render() { + return ( + + Tab1 + Tab2 + Tab3 + + Content1 + Content2 + Content3 + + ); + } +} + +ReactDOM.render( + , + document.getElementById("test-app") +); diff --git a/types/react-tabs-redux/tsconfig.json b/types/react-tabs-redux/tsconfig.json new file mode 100644 index 0000000000..8872a8cb4f --- /dev/null +++ b/types/react-tabs-redux/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "Tabs.d.ts", + "TabLink.d.ts", + "TabContent.d.ts", + "react-tabs-redux-tests.tsx" + ] +} diff --git a/types/react-tabs-redux/tslint.json b/types/react-tabs-redux/tslint.json new file mode 100644 index 0000000000..4f44991c3c --- /dev/null +++ b/types/react-tabs-redux/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-empty-interface": false + } +} From f5f06bf3dec952e9d6b679b7faa1fbf9de87c6ed Mon Sep 17 00:00:00 2001 From: Anton Bortnikov <6088046+ntnbrtnkv@users.noreply.github.com> Date: Sat, 23 Mar 2019 17:04:46 +0500 Subject: [PATCH 045/710] set ts version --- types/react-tabs-redux/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/react-tabs-redux/index.d.ts b/types/react-tabs-redux/index.d.ts index 62ee5cc5d1..38c563f22c 100644 --- a/types/react-tabs-redux/index.d.ts +++ b/types/react-tabs-redux/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/patrik-piskay/react-tabs-redux#readme // Definitions by: Anton Bortnikov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 export {Tabs, TabsProps} from './Tabs'; export {TabLink, TabLinkProps} from './TabLink'; From 4edec4dfad5da8cb8d10deb8df4ded113f66c8b8 Mon Sep 17 00:00:00 2001 From: Anton Bortnikov <6088046+ntnbrtnkv@users.noreply.github.com> Date: Sat, 23 Mar 2019 17:42:23 +0500 Subject: [PATCH 046/710] style: fix lint --- types/react-tabs-redux/TabContent.d.ts | 2 +- types/react-tabs-redux/TabLink.d.ts | 2 +- types/react-tabs-redux/Tabs.d.ts | 2 +- types/react-tabs-redux/index.d.ts | 6 +++--- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/types/react-tabs-redux/TabContent.d.ts b/types/react-tabs-redux/TabContent.d.ts index 9c3d5c24a6..d2a1f68926 100644 --- a/types/react-tabs-redux/TabContent.d.ts +++ b/types/react-tabs-redux/TabContent.d.ts @@ -12,4 +12,4 @@ export interface TabContentProps { style?: object; } -export declare class TabContent extends React.Component {} +export class TabContent extends React.Component {} diff --git a/types/react-tabs-redux/TabLink.d.ts b/types/react-tabs-redux/TabLink.d.ts index 392fec2d73..dc1dd2f91b 100644 --- a/types/react-tabs-redux/TabLink.d.ts +++ b/types/react-tabs-redux/TabLink.d.ts @@ -16,4 +16,4 @@ export interface TabLinkProps { default?: boolean; } -export declare class TabLink extends React.Component {} +export class TabLink extends React.Component {} diff --git a/types/react-tabs-redux/Tabs.d.ts b/types/react-tabs-redux/Tabs.d.ts index 8f0599c0f5..a8be4dacfc 100644 --- a/types/react-tabs-redux/Tabs.d.ts +++ b/types/react-tabs-redux/Tabs.d.ts @@ -11,4 +11,4 @@ export interface TabsProps { renderActiveTabContentOnly?: boolean; } -export declare class Tabs extends React.Component {} +export class Tabs extends React.Component {} diff --git a/types/react-tabs-redux/index.d.ts b/types/react-tabs-redux/index.d.ts index 38c563f22c..c6f2f5181a 100644 --- a/types/react-tabs-redux/index.d.ts +++ b/types/react-tabs-redux/index.d.ts @@ -4,6 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -export {Tabs, TabsProps} from './Tabs'; -export {TabLink, TabLinkProps} from './TabLink'; -export {TabContent, TabContentProps} from './TabContent'; +export { Tabs, TabsProps } from './Tabs'; +export { TabLink, TabLinkProps } from './TabLink'; +export { TabContent, TabContentProps } from './TabContent'; From f3b55d58de4a33a1b39ac17bcf7e8d20be0f5320 Mon Sep 17 00:00:00 2001 From: Aleksey Klimenko Date: Sun, 24 Mar 2019 02:37:18 +0300 Subject: [PATCH 047/710] [musicmatch] added basic definitions and tests --- types/musicmatch/index.d.ts | 204 +++++++++++++++++++++++++++ types/musicmatch/musicmatch-tests.ts | 65 +++++++++ types/musicmatch/tsconfig.json | 23 +++ types/musicmatch/tslint.json | 79 +++++++++++ 4 files changed, 371 insertions(+) create mode 100644 types/musicmatch/index.d.ts create mode 100644 types/musicmatch/musicmatch-tests.ts create mode 100644 types/musicmatch/tsconfig.json create mode 100644 types/musicmatch/tslint.json diff --git a/types/musicmatch/index.d.ts b/types/musicmatch/index.d.ts new file mode 100644 index 0000000000..6bc88b1983 --- /dev/null +++ b/types/musicmatch/index.d.ts @@ -0,0 +1,204 @@ +// Type definitions for musicmatch 0.3.2 +// Project: https://www.npmjs.com/package/musicmatch +// Definitions by: Aleksei Klimenko +// Definitions: https://github.com/DefinitelyTyped/ + +declare module 'musicmatch'; + +type TFormat = 'json' | 'xml'; +type TSort = 'asc' | 'desc'; +type TBoolean = 0 | 1; + +export interface IPageable { + page?: number; + page_size?: number; +} + +export interface IAlbumParams { + album_id: number; +} + +export interface IAlbumTracksParams { + album_id?: number; + album_mbid?: number; + format?: TFormat; +} + +export interface IArtistParams { + artist_id?: number; + artist_mbid?: number; +} + +export interface IArtistRelatedParams extends IArtistParams, IPageable { +} + +export interface IArtistAlbumsParams extends IArtistParams, IPageable { + g_album_name?: TBoolean; + s_release_date?: TSort; +} + +export interface IArtistSearchParams extends IPageable { + q_artist?: string; + f_artist_id?: number; + f_artist_mbid?: number; +} + +export interface IMatcherLyricsParams { + q_track?: string; + q_artist?: string; +} + +export interface IMatcherSubtitleParams extends IMatcherLyricsParams { + f_subtitle_length?: number; + f_subtitle_length_max_deviation?: number; +} + +export interface IMatcherTrackParams extends IMatcherLyricsParams { + f_has_lyrics?: TBoolean; + f_has_subtitle?: TBoolean; +} + +export interface ITrackLyricsFeedbackParams { + lyrics_id?: number; + track_id?: number; + feedback?: 'wrong_lyrics' | 'wrong_attribution' | 'bad_characters' | 'lines_too_long' | 'wrong_verses' | 'wrong_formatting'; +} + +export interface ITrackLyricsAddParams { + lyrics_id?: number; + lyrics_body?: string; +} + +export interface ITrackSnippetParams { + track_id: number; +} + +export interface ITrackLyricsParams { + track_id?: number; + track_mbid?: number; +} + +export interface ITrackSubtitleParams { + track_id?: number; + track_mbid?: number; + subtitle_format?: 'lrc' | 'dfxp' | 'stledu'; + f_subtitle_length?: number; + f_subtitle_length_max_deviation?: number; +} + +export interface ITrackParams { + track_id?: number; + track_mbid?: number; +} + +export interface ITrackSearchParams extends IPageable { + q?: string; + q_lyrics?: string; + f_has_lyrics?: TBoolean; + f_artist_id?: number; + f_music_genre_id?: number; + f_artist_mbid?: number; + f_lyrics_language?: string; + s_track_rating?: TSort; + s_artist_rating?: TSort; + quorum_factor?: number; +} + +export interface ITrackSearchResult { + message: { + body: { + track_list: ITrackResult[]; + }, + header: { + available: number; + execute_time: number; + status_code: number; + } + }; +} + +export interface IMusicGenre { + music_genre_id: number; + music_genre_parent_id: number; + music_genre_name: string; + music_genre_name_extended: string; + music_genre_vanity: string; +} + +export interface PrimaryGenres { + music_genre_list: Array<{ music_genre: IMusicGenre }>; +} + +export interface ITrackResult { + track: { + track_id: number; + track_name: string; + track_name_translation_list: any[]; + track_rating: number; + commontrack_id: number; + instrumental: TBoolean; + explicit: TBoolean; + has_lyrics: TBoolean; + has_subtitles: TBoolean; + has_richsync: TBoolean; + num_favourite: number; + album_id: number; + album_name: string; + artist_id: number; + artist_name: string; + track_share_url: string; + track_edit_url: string; + restricted: TBoolean; + updated_time: string; + primary_genres: PrimaryGenres; + }; +} + +export interface IChartTracksParams extends IPageable { + country?: string; + f_has_lyrics?: TBoolean; +} + +export interface IChartArtistsParams extends IPageable { + country?: string; +} + +export default class Musicmatch { + constructor(obj?: { apikey?: string, format?: string }); + + album(params: IAlbumParams): Promise; + + albumTracks(params: IAlbumTracksParams): Promise; + + artist(params: IArtistParams): Promise; + + artistAlbums(params: IArtistAlbumsParams): Promise; + + artistRelated(params: IArtistRelatedParams): Promise; + + artistSearch(params: IArtistSearchParams): Promise; + + chartArtists(params: IChartArtistsParams): Promise; + + chartTracks(params: IChartTracksParams): Promise; + + matcherLyrics(params: IMatcherLyricsParams): Promise; + + matcherSubtitle(params: IMatcherSubtitleParams): Promise; + + matcherTrack(params: IMatcherTrackParams): Promise; + + track(params: ITrackParams): Promise; + + trackLyrics(params: ITrackLyricsParams): Promise; + + trackLyricsAdd(params: ITrackLyricsAddParams): Promise; + + trackLyricsFeedback(params: ITrackLyricsFeedbackParams): Promise; + + trackSearch(params: ITrackSearchParams): Promise; + + trackSnippet(params: ITrackSnippetParams): Promise; + + trackSubtitle(params: ITrackSubtitleParams): Promise; +} diff --git a/types/musicmatch/musicmatch-tests.ts b/types/musicmatch/musicmatch-tests.ts new file mode 100644 index 0000000000..5cab791bb6 --- /dev/null +++ b/types/musicmatch/musicmatch-tests.ts @@ -0,0 +1,65 @@ +// Type definitions for musicmatch 0.3.2 +// Project: https://www.npmjs.com/package/musicmatch +// Definitions by: Aleksei Klimenko +// Definitions: https://github.com/DefinitelyTyped/ + +import Musicmatch, { ITrackSearchParams, ITrackSearchResult } from 'musicmatch'; + +const musicmatch = new Musicmatch({ apikey: 'api_key', format: '' }); + +const trackSearchParams: ITrackSearchParams = { + f_music_genre_id: 18, + page_size: 100, + page: 1, + s_track_rating: 'desc', + f_lyrics_language: 'en', +}; + +musicmatch.trackSearch(trackSearchParams); + +/** + * Search for a track + * + * GET ws/1.1/track.search + * + */ +const trackSearchResult: ITrackSearchResult = { + 'message': { + 'header': { 'status_code': 200, 'execute_time': 0.27148103713989, 'available': 10000 }, 'body': { + 'track_list': [{ + 'track': { + 'track_id': 164289228, + 'track_name': '7 rings', + 'track_name_translation_list': [], + 'track_rating': 100, + 'commontrack_id': 91473047, + 'instrumental': 0, + 'explicit': 1, + 'has_lyrics': 1, + 'has_subtitles': 1, + 'has_richsync': 1, + 'num_favourite': 2130, + 'album_id': 31234760, + 'album_name': 'thank u, next', + 'artist_id': 13958599, + 'artist_name': 'Ariana Grande', + 'track_share_url': 'https:\/\/www.musixmatch.com\/lyrics\/Ariana-Grande\/7-rings?utm_source=application&utm_campaign=api&utm_medium=FruitSarcop%3A1409618278546', + 'track_edit_url': 'https:\/\/www.musixmatch.com\/lyrics\/Ariana-Grande\/7-rings\/edit?utm_source=application&utm_campaign=api&utm_medium=FruitSarcop%3A1409618278546', + 'restricted': 0, + 'updated_time': '2019-03-22T15:28:01Z', + 'primary_genres': { + 'music_genre_list': [{ + 'music_genre': { + 'music_genre_id': 14, + 'music_genre_parent_id': 34, + 'music_genre_name': 'Pop', + 'music_genre_name_extended': 'Pop', + 'music_genre_vanity': 'Pop' + } + }] + } + } + }] + } + } +}; diff --git a/types/musicmatch/tsconfig.json b/types/musicmatch/tsconfig.json new file mode 100644 index 0000000000..800f5abd46 --- /dev/null +++ b/types/musicmatch/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "musicmatch-tests.ts" + ] +} diff --git a/types/musicmatch/tslint.json b/types/musicmatch/tslint.json new file mode 100644 index 0000000000..a41bf5d19a --- /dev/null +++ b/types/musicmatch/tslint.json @@ -0,0 +1,79 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "adjacent-overload-signatures": false, + "array-type": false, + "arrow-return-shorthand": false, + "ban-types": false, + "callable-types": false, + "comment-format": false, + "dt-header": false, + "eofline": false, + "export-just-namespace": false, + "import-spacing": false, + "interface-name": false, + "interface-over-type-literal": false, + "jsdoc-format": false, + "max-line-length": false, + "member-access": false, + "new-parens": false, + "no-any-union": false, + "no-boolean-literal-compare": false, + "no-conditional-assignment": false, + "no-consecutive-blank-lines": false, + "no-construct": false, + "no-declare-current-package": false, + "no-duplicate-imports": false, + "no-duplicate-variable": false, + "no-empty-interface": false, + "no-for-in-array": false, + "no-inferrable-types": false, + "no-internal-module": false, + "no-irregular-whitespace": false, + "no-mergeable-namespace": false, + "no-misused-new": false, + "no-namespace": false, + "no-object-literal-type-assertion": false, + "no-padding": false, + "no-redundant-jsdoc": false, + "no-redundant-jsdoc-2": false, + "no-redundant-undefined": false, + "no-reference-import": false, + "no-relative-import-in-test": false, + "no-self-import": false, + "no-single-declare-module": false, + "no-string-throw": false, + "no-unnecessary-callback-wrapper": false, + "no-unnecessary-class": false, + "no-unnecessary-generics": false, + "no-unnecessary-qualifier": false, + "no-unnecessary-type-assertion": false, + "no-useless-files": false, + "no-var-keyword": false, + "no-var-requires": false, + "no-void-expression": false, + "no-trailing-whitespace": false, + "object-literal-key-quotes": false, + "object-literal-shorthand": false, + "one-line": false, + "one-variable-per-declaration": false, + "only-arrow-functions": false, + "prefer-conditional-expression": false, + "prefer-const": false, + "prefer-declare-function": false, + "prefer-for-of": false, + "prefer-method-signature": false, + "prefer-template": false, + "radix": false, + "semicolon": false, + "space-before-function-paren": false, + "space-within-parens": false, + "strict-export-declare-modifiers": false, + "trim-file": false, + "triple-equals": false, + "typedef-whitespace": false, + "unified-signatures": false, + "void-return": false, + "whitespace": false + } +} From 15f39a5afe86b7037c7d7cd3e11cf845f2b9798d Mon Sep 17 00:00:00 2001 From: Aleksey Klimenko Date: Sun, 24 Mar 2019 03:02:57 +0300 Subject: [PATCH 048/710] [musicmatch] added github url --- types/musicmatch/index.d.ts | 2 +- types/musicmatch/musicmatch-tests.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/musicmatch/index.d.ts b/types/musicmatch/index.d.ts index 6bc88b1983..c22bbc6424 100644 --- a/types/musicmatch/index.d.ts +++ b/types/musicmatch/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for musicmatch 0.3.2 -// Project: https://www.npmjs.com/package/musicmatch +// Project: https://github.com/c0b41/musixmatch, https://www.npmjs.com/package/musicmatch // Definitions by: Aleksei Klimenko // Definitions: https://github.com/DefinitelyTyped/ diff --git a/types/musicmatch/musicmatch-tests.ts b/types/musicmatch/musicmatch-tests.ts index 5cab791bb6..6511920854 100644 --- a/types/musicmatch/musicmatch-tests.ts +++ b/types/musicmatch/musicmatch-tests.ts @@ -1,5 +1,5 @@ // Type definitions for musicmatch 0.3.2 -// Project: https://www.npmjs.com/package/musicmatch +// Project: https://github.com/c0b41/musixmatch, https://www.npmjs.com/package/musicmatch // Definitions by: Aleksei Klimenko // Definitions: https://github.com/DefinitelyTyped/ From 468a3b55178aedb632fdb411cdd161a9399e5de8 Mon Sep 17 00:00:00 2001 From: Joel Spadin Date: Sun, 24 Mar 2019 00:34:49 -0500 Subject: [PATCH 049/710] Add types for license-checker-webpack-plugin --- .../license-checker-webpack-plugin/index.d.ts | 73 +++++++++++++++++++ .../license-checker-webpack-plugin-tests.ts | 24 ++++++ .../tsconfig.json | 23 ++++++ .../tslint.json | 1 + 4 files changed, 121 insertions(+) create mode 100644 types/license-checker-webpack-plugin/index.d.ts create mode 100644 types/license-checker-webpack-plugin/license-checker-webpack-plugin-tests.ts create mode 100644 types/license-checker-webpack-plugin/tsconfig.json create mode 100644 types/license-checker-webpack-plugin/tslint.json diff --git a/types/license-checker-webpack-plugin/index.d.ts b/types/license-checker-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..ff131df767 --- /dev/null +++ b/types/license-checker-webpack-plugin/index.d.ts @@ -0,0 +1,73 @@ +// Type definitions for license-checker-webpack-plugin 0.0 +// Project: https://github.com/Microsoft/license-checker-webpack-plugin#readme +// Definitions by: Joel Spadin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Plugin } from 'webpack'; + +declare class LicenseCheckerWebpackPlugin extends Plugin { + constructor(options: LicenseCheckerWebpackPlugin.Options); +} + +declare namespace LicenseCheckerWebpackPlugin { + interface Dependency { + name: string; + version: string; + repository: string; + licenseName: string; + licenseText: string; + } + + interface Options { + /** + * Regular expression that matches the file paths of dependencies to check. + */ + filter?: RegExp; + + /** + * SPDX expression with allowed licenses. + * + * Default: `"(Apache-2.0 OR BSD-2-Clause OR BSD-3-Clause OR MIT)"` + */ + allow?: string; + + /** + * Array of dependencies to ignore, in the format `["@"]`. + * For example, `["assignment@^2.0.0"]`. + * + * Default: `[]` + */ + ignore?: string[]; + + /** + * Object of dependencies to override, in the format `{"@": { ... }}`. + * For example, `{"assignment@^2.0.0": { licenseName: "MIT" }}`. + * + * Default: `{}` + */ + override?: Record>; + + /** + * Whether to emit errors instead of warnings. + * + * Default: `false` + */ + emitError?: boolean; + + /** + * Path to a `.ejs` template, or function that will generate the contents + * of the third-party notices file. + */ + outputWriter?: string | ((dependencies: Dependency[]) => string); + + /** + * Name of the third-party notices file with all licensing information. + * + * Default: `"ThirdPartyNotices.txt"` + */ + outputFilename?: string; + } +} + +export = LicenseCheckerWebpackPlugin; diff --git a/types/license-checker-webpack-plugin/license-checker-webpack-plugin-tests.ts b/types/license-checker-webpack-plugin/license-checker-webpack-plugin-tests.ts new file mode 100644 index 0000000000..f476b515f5 --- /dev/null +++ b/types/license-checker-webpack-plugin/license-checker-webpack-plugin-tests.ts @@ -0,0 +1,24 @@ +import * as path from 'path'; +import LicenseCheckerWebpackPlugin = require('license-checker-webpack-plugin'); + +// $ExpectType LicenseCheckerWebpackPlugin +new LicenseCheckerWebpackPlugin({ + allow: "(Apache-2.0 OR BSD-2-Clause OR BSD-3-Clause OR MIT)", + ignore: ["@microsoft/*"], + override: { + "assignment@2.0.0": { licenseName: "MIT" }, + "intersection-observer@0.5.0": { licenseName: "MIT" }, + "querystring-es3@0.2.1": { licenseName: "MIT" } + }, + emitError: true, + outputWriter: path.resolve(__dirname, "customTemplate.ejs"), + outputFilename: "ThirdPartyNotices.txt" +}); + +// $ExpectType LicenseCheckerWebpackPlugin +new LicenseCheckerWebpackPlugin({ + filter: /.*/, + outputWriter: (dependencies) => { + return dependencies.map(d => `${d.name} ${d.licenseName}`).join('\n'); + }, +}); diff --git a/types/license-checker-webpack-plugin/tsconfig.json b/types/license-checker-webpack-plugin/tsconfig.json new file mode 100644 index 0000000000..2e9aebac73 --- /dev/null +++ b/types/license-checker-webpack-plugin/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "license-checker-webpack-plugin-tests.ts" + ] +} diff --git a/types/license-checker-webpack-plugin/tslint.json b/types/license-checker-webpack-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/license-checker-webpack-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From b1cf17e7969f20a792a443c2205e73ee9fae3d7a Mon Sep 17 00:00:00 2001 From: John Caruso Date: Sun, 24 Mar 2019 16:13:36 -0500 Subject: [PATCH 050/710] Add ServiceNow London type definitions --- types/servicenow-london/Class.d.ts | 8 + .../GlideDBFunctionBuilder.d.ts | 189 ++++ types/servicenow-london/GlideDate.d.ts | 154 +++ types/servicenow-london/GlideDateTime.d.ts | 833 ++++++++++++++++ types/servicenow-london/GlideDuration.d.ts | 160 ++++ .../servicenow-london/GlideEmailOutbound.d.ts | 90 ++ types/servicenow-london/GlideFilter.d.ts | 3 + types/servicenow-london/GlideLocale.d.ts | 5 + .../servicenow-london/GlidePluginManager.d.ts | 3 + .../GlideRecordOperation.d.ts | 1 + types/servicenow-london/GlideSchedule.d.ts | 167 ++++ .../GlideScopedEvaluator.d.ts | 95 ++ .../GlideScriptedProcessor.d.ts | 5 + .../GlideSecureRandomUtil.d.ts | 6 + .../GlideServletRequest.d.ts | 11 + .../GlideServletResponse.d.ts | 5 + types/servicenow-london/GlideSession.d.ts | 13 + types/servicenow-london/GlideStringUtil.d.ts | 16 + .../servicenow-london/GlideSysAttachment.d.ts | 26 + types/servicenow-london/GlideSystem.d.ts | 90 ++ types/servicenow-london/GlideTime.d.ts | 171 ++++ types/servicenow-london/GlideUser.d.ts | 16 + types/servicenow-london/QueryOperator.d.ts | 15 + types/servicenow-london/RESTAPIRequest.d.ts | 13 + .../servicenow-london/RESTAPIRequestBody.d.ts | 9 + types/servicenow-london/RESTAPIResponse.d.ts | 12 + .../RESTAPIResponseStream.d.ts | 6 + types/servicenow-london/RESTMessageV2.d.ts | 581 +++++++++++ types/servicenow-london/RESTResponseV2.d.ts | 188 ++++ types/servicenow-london/RenderProperties.d.ts | 13 + types/servicenow-london/SOAPMessageV2.d.ts | 31 + types/servicenow-london/SOAPResponseV2.d.ts | 14 + .../ScopedElementDescriptor.d.ts | 227 +++++ .../servicenow-london/ScopedGlideElement.d.ts | 447 +++++++++ .../servicenow-london/ScopedGlideRecord.d.ts | 898 ++++++++++++++++++ .../ScopedQueryCondition.d.ts | 72 ++ types/servicenow-london/Workflow.d.ts | 97 ++ types/servicenow-london/XMLDocument2.d.ts | 13 + types/servicenow-london/XMLNode.d.ts | 11 + types/servicenow-london/XMLNodeIterator.d.ts | 4 + types/servicenow-london/index.d.ts | 62 ++ types/servicenow-london/test/Class.ts | 11 + .../test/GlideDBFunctionBuilder.ts | 75 ++ types/servicenow-london/test/GlideDate.ts | 18 + types/servicenow-london/test/GlideDateTime.ts | 100 ++ types/servicenow-london/test/GlideDuration.ts | 46 + .../test/GlideEmailOutbound.ts | 21 + types/servicenow-london/test/GlideFilter.ts | 10 + types/servicenow-london/test/GlideLocale.ts | 15 + .../test/GlidePluginManager.ts | 18 + types/servicenow-london/test/GlideSchedule.ts | 62 ++ .../test/GlideScopedEvaluator.ts | 34 + .../test/GlideScriptedProcessor.ts | 16 + .../test/GlideSecureRandomUtil.ts | 12 + .../test/GlideServletRequest.ts | 26 + .../test/GlideServletResponse.ts | 10 + types/servicenow-london/test/GlideSession.ts | 64 ++ .../servicenow-london/test/GlideStringUtil.ts | 85 ++ .../test/GlideSysAttachment.ts | 1 + types/servicenow-london/test/GlideSystem.ts | 211 ++++ types/servicenow-london/test/GlideTime.ts | 46 + types/servicenow-london/test/GlideUser.ts | 59 ++ .../servicenow-london/test/RESTAPIRequest.ts | 22 + .../test/RESTAPIRequestBody.ts | 33 + .../servicenow-london/test/RESTAPIResponse.ts | 28 + .../test/RESTAPIResponseStream.ts | 17 + types/servicenow-london/test/RESTMessageV2.ts | 106 +++ .../servicenow-london/test/RESTResponseV2.ts | 22 + types/servicenow-london/test/SOAPMessageV2.ts | 28 + .../servicenow-london/test/SOAPResponseV2.ts | 20 + .../test/ScopedElementDescriptor.ts | 19 + .../test/ScopedGlideElement.ts | 13 + .../test/ScopedGlideRecord.ts | 400 ++++++++ .../test/ScopedQueryCondition.ts | 26 + types/servicenow-london/test/Workflow.ts | 134 +++ types/servicenow-london/test/XMLDocument2.ts | 153 +++ types/servicenow-london/test/XMLNode.ts | 137 +++ .../servicenow-london/test/XMLNodeIterator.ts | 36 + types/servicenow-london/tsconfig.json | 97 ++ types/servicenow-london/tslint.json | 12 + 80 files changed, 7023 insertions(+) create mode 100644 types/servicenow-london/Class.d.ts create mode 100644 types/servicenow-london/GlideDBFunctionBuilder.d.ts create mode 100644 types/servicenow-london/GlideDate.d.ts create mode 100644 types/servicenow-london/GlideDateTime.d.ts create mode 100644 types/servicenow-london/GlideDuration.d.ts create mode 100644 types/servicenow-london/GlideEmailOutbound.d.ts create mode 100644 types/servicenow-london/GlideFilter.d.ts create mode 100644 types/servicenow-london/GlideLocale.d.ts create mode 100644 types/servicenow-london/GlidePluginManager.d.ts create mode 100644 types/servicenow-london/GlideRecordOperation.d.ts create mode 100644 types/servicenow-london/GlideSchedule.d.ts create mode 100644 types/servicenow-london/GlideScopedEvaluator.d.ts create mode 100644 types/servicenow-london/GlideScriptedProcessor.d.ts create mode 100644 types/servicenow-london/GlideSecureRandomUtil.d.ts create mode 100644 types/servicenow-london/GlideServletRequest.d.ts create mode 100644 types/servicenow-london/GlideServletResponse.d.ts create mode 100644 types/servicenow-london/GlideSession.d.ts create mode 100644 types/servicenow-london/GlideStringUtil.d.ts create mode 100644 types/servicenow-london/GlideSysAttachment.d.ts create mode 100644 types/servicenow-london/GlideSystem.d.ts create mode 100644 types/servicenow-london/GlideTime.d.ts create mode 100644 types/servicenow-london/GlideUser.d.ts create mode 100644 types/servicenow-london/QueryOperator.d.ts create mode 100644 types/servicenow-london/RESTAPIRequest.d.ts create mode 100644 types/servicenow-london/RESTAPIRequestBody.d.ts create mode 100644 types/servicenow-london/RESTAPIResponse.d.ts create mode 100644 types/servicenow-london/RESTAPIResponseStream.d.ts create mode 100644 types/servicenow-london/RESTMessageV2.d.ts create mode 100644 types/servicenow-london/RESTResponseV2.d.ts create mode 100644 types/servicenow-london/RenderProperties.d.ts create mode 100644 types/servicenow-london/SOAPMessageV2.d.ts create mode 100644 types/servicenow-london/SOAPResponseV2.d.ts create mode 100644 types/servicenow-london/ScopedElementDescriptor.d.ts create mode 100644 types/servicenow-london/ScopedGlideElement.d.ts create mode 100644 types/servicenow-london/ScopedGlideRecord.d.ts create mode 100644 types/servicenow-london/ScopedQueryCondition.d.ts create mode 100644 types/servicenow-london/Workflow.d.ts create mode 100644 types/servicenow-london/XMLDocument2.d.ts create mode 100644 types/servicenow-london/XMLNode.d.ts create mode 100644 types/servicenow-london/XMLNodeIterator.d.ts create mode 100644 types/servicenow-london/index.d.ts create mode 100644 types/servicenow-london/test/Class.ts create mode 100644 types/servicenow-london/test/GlideDBFunctionBuilder.ts create mode 100644 types/servicenow-london/test/GlideDate.ts create mode 100644 types/servicenow-london/test/GlideDateTime.ts create mode 100644 types/servicenow-london/test/GlideDuration.ts create mode 100644 types/servicenow-london/test/GlideEmailOutbound.ts create mode 100644 types/servicenow-london/test/GlideFilter.ts create mode 100644 types/servicenow-london/test/GlideLocale.ts create mode 100644 types/servicenow-london/test/GlidePluginManager.ts create mode 100644 types/servicenow-london/test/GlideSchedule.ts create mode 100644 types/servicenow-london/test/GlideScopedEvaluator.ts create mode 100644 types/servicenow-london/test/GlideScriptedProcessor.ts create mode 100644 types/servicenow-london/test/GlideSecureRandomUtil.ts create mode 100644 types/servicenow-london/test/GlideServletRequest.ts create mode 100644 types/servicenow-london/test/GlideServletResponse.ts create mode 100644 types/servicenow-london/test/GlideSession.ts create mode 100644 types/servicenow-london/test/GlideStringUtil.ts create mode 100644 types/servicenow-london/test/GlideSysAttachment.ts create mode 100644 types/servicenow-london/test/GlideSystem.ts create mode 100644 types/servicenow-london/test/GlideTime.ts create mode 100644 types/servicenow-london/test/GlideUser.ts create mode 100644 types/servicenow-london/test/RESTAPIRequest.ts create mode 100644 types/servicenow-london/test/RESTAPIRequestBody.ts create mode 100644 types/servicenow-london/test/RESTAPIResponse.ts create mode 100644 types/servicenow-london/test/RESTAPIResponseStream.ts create mode 100644 types/servicenow-london/test/RESTMessageV2.ts create mode 100644 types/servicenow-london/test/RESTResponseV2.ts create mode 100644 types/servicenow-london/test/SOAPMessageV2.ts create mode 100644 types/servicenow-london/test/SOAPResponseV2.ts create mode 100644 types/servicenow-london/test/ScopedElementDescriptor.ts create mode 100644 types/servicenow-london/test/ScopedGlideElement.ts create mode 100644 types/servicenow-london/test/ScopedGlideRecord.ts create mode 100644 types/servicenow-london/test/ScopedQueryCondition.ts create mode 100644 types/servicenow-london/test/Workflow.ts create mode 100644 types/servicenow-london/test/XMLDocument2.ts create mode 100644 types/servicenow-london/test/XMLNode.ts create mode 100644 types/servicenow-london/test/XMLNodeIterator.ts create mode 100644 types/servicenow-london/tsconfig.json create mode 100644 types/servicenow-london/tslint.json diff --git a/types/servicenow-london/Class.d.ts b/types/servicenow-london/Class.d.ts new file mode 100644 index 0000000000..085f14edb8 --- /dev/null +++ b/types/servicenow-london/Class.d.ts @@ -0,0 +1,8 @@ +declare const Class: { + /** + * `Class.create` creates a class and returns a constructor function for instances of the class. + * Calling the constructor function (typically as part of a `new` statement) will invoke the + * class's `initialize` method. + */ + create: () => () => void; +}; diff --git a/types/servicenow-london/GlideDBFunctionBuilder.d.ts b/types/servicenow-london/GlideDBFunctionBuilder.d.ts new file mode 100644 index 0000000000..c2c561b60c --- /dev/null +++ b/types/servicenow-london/GlideDBFunctionBuilder.d.ts @@ -0,0 +1,189 @@ +declare class GlideDBFunctionBuilder { + /** + * Instantiates a GlideDBFunctionBuilder object. + * + * @example + * + * var builder = new GlideDBFunctionBuilder(); + */ + constructor(); + + /** + * Adds the values of two or more integer fields. + * + * @example + * + * var functionBuilder = new GlideDBFunctionBuilder(); + * var myAddingFunction = functionBuilder.add(); + * myAddingFunction = functionBuilder.field('order'); + * myAddingFunction = functionBuilder.field('priority'); + * myAddingFunction = functionBuilder.build(); + */ + add(): GlideDBFunctionBuilder; + + /** + * Builds the database function defined by the GlideDBFunctionBuilder object. + * + * @example + * + * var functionBuilder = new GlideDBFunctionBuilder(); + * var myAddingFunction = functionBuilder.add(); + * myAddingFunction = functionBuilder.field('order'); + * myAddingFunction = functionBuilder.field('priority'); + * myAddingFunction = functionBuilder.build(); + * gs.print(myAddingFunction); + */ + build(): string; + + /** + * Concatenates the values of two or more fields. + * Use the `field(String field)` method to define fields on which the operation is performed. + * + * @example + * + * var functionBuilder = new GlideDBFunctionBuilder(); + * var myConcatFunction = functionBuilder.concat(); + * myConcatFunction = functionBuilder.field('short_description'); + * myConcatFunction = functionBuilder.field('caller_id.name'); + * myConcatFunction = functionBuilder.build(); + */ + concat(): GlideDBFunctionBuilder; + + /** + * Defines a constant value to use in the function. If used with the `dayofweek()` method, the + * string defines whether to use Sunday or Monday as the first day of the week. + * + * @param constant A constant value used in a function. + * + * When used with the `dayofweek()` method, the value defines whether the week starts on a Sunday or + * Monday. + * + * - 1: Week begins on Sunday. + * - 2: Week begins on Monday. + * + * This definition enables the `dayofweek()` method to return the correct day of the week from a + * given date. If a value other than 1 or 2 is provided, the `dayofweek()` method uses Sunday as + * the first day of the week. + */ + constant(constant: string): GlideDBFunctionBuilder; + + /** + * Determines the duration using a given start date/time and end date/time. + * Use the `field(String field)` method to define start and end date/time fields. + */ + datediff(): GlideDBFunctionBuilder; + + /** + * Returns an integer representing the day of the week for a given date. + * + * @returns If the first day of the week is set to Sunday in the constant(String + * constant) method, return values are associated with the following days + * of the week: + * + * - 1: Sunday + * - 2: Monday + * - 3: Tuesday + * - 4: Wednesday + * - 5: Thursday + * - 6: Friday + * - 7: Saturday + * + * If the first day of the week is set to Monday: + * + * - 1: Monday + * - 2: Tuesday + * - 3: Wednesday + * - 4: Thursday + * - 5: Friday + * - 6: Saturday + * - 7: Sunday + * + * If a value other than 1 or 2 is provided in the `constant(String constant)` method, the + * `dayofweek()` method uses Sunday as the first day of the week. + * @example + * + * var functionBuilder = new GlideDBFunctionBuilder(); + * var dayOfWeekFunction = functionBuilder.dayofweek(); + * dayOfWeekFunction = functionBuilder.field('opened_at'); + * dayOfWeekFunction = functionBuilder.constant('2'); + * dayOfWeekFunction = functionBuilder.build(); + * + * var gr = new GlideRecord('incident'); + * gr.addFunction(dayOfWeekFunction); + * gr.query(); + * while(gr.next()) + * gs.log(gr.getValue(dayOfWeekFunction)); + * + */ + dayofweek(): GlideDBFunctionBuilder; + + /** + * Divides the value of one integer field by another. + * Use the `field(String field)` method to define fields on which the operation is performed. + * + * @example + * + * var functionBuilder = new GlideDBFunctionBuilder(); + * var myDivideFunction = functionBuilder.divide(); + * myDivideFunction = functionBuilder.field('order'); + * myDivideFunction = functionBuilder.field('priority'); + * myDivideFunction = functionBuilder.build(); + */ + divide(): GlideDBFunctionBuilder; + + /** + * Defines a field on which a SQL operation is performed. + * + * @param field The field on which you are performing the SQL operation. + * @example + * + * var functionBuilder = new GlideDBFunctionBuilder(); + * var myAddingFunction = functionBuilder.add(); + * myAddingFunction = functionBuilder.field('order'); + * myAddingFunction = functionBuilder.field('priority'); + * myAddingFunction = functionBuilder.build(); + */ + field(field: string): GlideDBFunctionBuilder; + + /** + * Determines the number of code units in a field. + * Use the `field(String field)` method to define fields on which the operation is performed. + * + * @example + * + * var functionBuilder = new GlideDBFunctionBuilder(); + * var myLengthFunction = functionBuilder.length(); + * myLengthFunction = functionBuilder.field('short_description'); + * myLengthFunction = functionBuilder.build(); + * + */ + length(): GlideDBFunctionBuilder; + + /** + * Multiplies the values of two integer fields. + * Use the `field(String field)` method to define fields on which the operation is performed. + * + * @example + * + * var functionBuilder = new GlideDBFunctionBuilder(); + * var myMultiplyFunction = functionBuilder.multiply(); + * myMultiplyFunction = functionBuilder.field('order'); + * myMultiplyFunction = functionBuilder.field('priority'); + * myMultiplyFunction = functionBuilder.build(); + */ + multiply(): GlideDBFunctionBuilder; + + /** + * Subtracts the value of one integer field from another. + * Use the `field(String field)` method to define fields on which the operation is performed. + * + * @example + * + * var functionBuilder = new GlideDBFunctionBuilder(); + * var mySubtractFunction = functionBuilder.subtract(); + * mySubtractFunction = functionBuilder.field('order'); + * mySubtractFunction = functionBuilder.field('priority'); + * mySubtractFunction = functionBuilder.build(); + */ + subtract(): GlideDBFunctionBuilder; +} diff --git a/types/servicenow-london/GlideDate.d.ts b/types/servicenow-london/GlideDate.d.ts new file mode 100644 index 0000000000..828128657d --- /dev/null +++ b/types/servicenow-london/GlideDate.d.ts @@ -0,0 +1,154 @@ +/** + * The scoped GlideDate class provides methods for performing operations on GlideDate + * objects, such as instantiating GlideDate objects or working with GlideDate fields. + */ +declare class GlideDate { + /** + * Creates a GlideDate object with the current date time. + */ + constructor(); + + /** + * Gets the date in the specified date format. + * + * @param format the desired date format + * @returns the date in the specified format + * @example + * + * var gd = new GlideDate(); + * gd.setValue('2015-01-01'); + * gs.info(gd.getByFormat('dd-MM-yyyy')); + * // 01-01-2015 + */ + getByFormat(format: string): string; + + /** + * Gets the day of the month stored by the GlideDate object, expressed in the UTC time + * zone. + * + * @returns The day of the month in the UTC time zone, from 1 to 31. + * @example + * + * // Today's date is 2016-05-13 + * var gd = new GlideDate('2016-05-13'); + * gs.info(gd.getDayOfMonthNoTZ()); + * // 13 + */ + getDayOfMonthNoTZ(): number; + + /** + * Gets the date in the current user's display format and time zone. + * + * @returns The date in the user's format and time zone. Keep in mind when designing + * business rules or script includes that this method may return values in different + * formats for different users. + * @example + * + * var gd = new GlideDate(); + * gd.setValue('2015-01-01'); + * gs.info(gd.getDisplayValue()); + * // 2015-01-01 + */ + + getDisplayValue(): string; + + /** + * Gets the display value in the internal format (yyyy-MM-dd). + * + * @returns The date values for the GlideDate object in the current user's time zone and + * the internal time format of yyyy-MM-dd. + * @example + * + * var gd = new GlideDate(); + * gs.info(gd.getDisplayValueInternal()); + * // 2014-10-22 + */ + getDisplayValueInternal(): string; + + /** + * Gets the month stored by the GlideDate object, expressed in the UTC time zone. + * @returns The numerical value of the month from 1 to 12. + * + * @example + * + * // Today's date is 2016-05-13 + * var gd = new GlideDate(); + * gs.info(gd.getMonthNoTZ()); + * // 5 + */ + getMonthNoTZ(): number; + + /** + * Gets the date value stored in the database by the GlideDate object in the internal + * format, yyyy-MM-dd, and the system time zone, UTC by default. + * + * @returns The date value in the internal format and system time zone. + * @example + * + * var gd = new GlideDate(); + * gd.setValue('2015-01-01'); + * gs.info(gd.getValue()); + * // 2015-01-01 + */ + getValue(): string; + + /** + * Gets the year stored by the GlideDate object, expressed in the UTC time zone. + * + * @returns The numerical value of the year. + * @example + * + * // Today's date is 2016-05-13 + * var gd = new GlideDate(); + * gs.info(gd.getYearNoTZ()); + * // 5 + */ + getYearNoTZ(): number; + + /** + * Sets a date value using the current user's display format and time zone. + * + * @param asDisplayed The date in the current user's display format and time zone. The parameter must + * be formatted using the current user's preferred display format, such as yyyy-MM-dd. + * @returns Method does not return a value + * @example + * + * var gd = new GlideDate(); + * gd.setDisplayValue('2011-01-01'); + * gs.info(gd.getValue()); + * // 2011-01-01 + */ + setDisplayValue(asDisplayed: string): void; + + /** + * Sets the date of the GlideDate object. + * + * @param o The date and time to use. + * @returns Method does not return a value + * @example + * + * var gd = new GlideDate(); + * gd.setValue('2015-01-01'); + * gs.info(gd.getValue()); + * // 2015-01-01 + */ + setValue(o: string): void; + + /** + * Gets the duration difference between two GlideDate values. + * + * @param start The start value. + * @param end The end value. + * @returns The duration between the two values. + * @example + * + * var sgd1 = new GlideDate(); + * sgd1.setDisplayValue('2014-07-18'); + * var sgd2 = new GlideDate(); + * sgd2.setDisplayValue('2014-07-19'); + * var duration = GlideDate.subtract(sgd1, sgd2); + * gs.info(duration.getDisplayValue()); + * // 1 Day + */ + static subtract(start: GlideDate | GlideTime, end: GlideDate | GlideTime): GlideDuration; +} diff --git a/types/servicenow-london/GlideDateTime.d.ts b/types/servicenow-london/GlideDateTime.d.ts new file mode 100644 index 0000000000..ad4ef1210b --- /dev/null +++ b/types/servicenow-london/GlideDateTime.d.ts @@ -0,0 +1,833 @@ +/** + * The scoped GlideDateTime class provides methods for performing operations on GlideDateTime + * objects, such as instantiating GlideDateTime objects or working with glide_date_time fields. + */ +declare class GlideDateTime { + /** + * Instantiates a new GlideDateTime object with the current date and time in Greenwich Mean Time + * (GMT). + */ + constructor(); + + /** + * Instantiates a new GlideDateTime object with the current date and time in Greenwich Mean Time + * (GMT). + * + * @param value A UTC date and time using the internal format yyyy-MM-dd HH:mm:ss. + */ + constructor(value: string); + + /** + * Instantiates a new GlideDateTime object with the current date and time in Greenwich Mean Time + * (GMT). + * + * @param g The GlideDateTime object to use for setting the time of the new object. + */ + constructor(g: GlideDateTime); + + /** + * Adds a GlideTime object to the current GlideDateTime object. + * + * @param gd The GlideTime object to add. + * @example + * + * var gdt = new GlideDateTime('2011-08-31 08:00:00'); + * var gtime1 = new GlideTime(); + * gtime1.setValue('00:00:20'); + * gdt.add(gtime1); + * var gtime2 = gdt.getTime(); + * gs.info(gtime2.getByFormat('hh:mm:ss')); + */ + add(gd: GlideTime): void; + + /** + * Adds the specified number of milliseconds to the current GlideDateTime object. + * + * @param milliseconds The number of milliseconds to add. + * @example + * + * var gdt = new GlideDateTime('2011-08-31 08:00:00'); + * gs.info(gdt.getNumericValue()); + * gdt.add(10); + * gs.info(gdt.getNumericValue()); + */ + add(milliseconds: number): void; + + /** + * Adds a specified number of days to the current GlideDateTime object. A negative parameter + * subtracts days. The method determines the local date and time equivalent to the value stored by + * the GlideDateTime object, then adds or subtracts days using the local date and time values. + * + * @param days The number of days to add. Use a negative value to subtract. + * @example + * + * var gdt = new GlideDateTime('2011-08-31 08:00:00'); + * gdt.addDaysLocalTime(-1); + * gs.info(gdt.getLocalDate()); + */ + addDaysLocalTime(days: number): void; + + /** + * Adds a specified number of days to the current GlideDateTime object. A negative parameter + * subtracts days. The method determines the UTC date and time equivalent to the value stored by + * the GlideDateTime object, then adds or subtracts days using the UTC date and time values. + * + * @param days The number of days to add. Use a negative number to subtract. + * @example + * + * var gdt = new GlideDateTime('2011-08-31 08:00:00'); + * gdt.addDaysUTC(-1); + * gs.info(gdt.getDate()); + */ + addDaysUTC(amount: number): void; + + /** + * Adds a specified number of months to the current GlideDateTime object. A negative parameter + * subtracts months. The method determines the local date and time equivalent to the value stored + * by the GlideDateTime object, then adds or subtracts months using the local date and time + * values. + * + * @param months The number of months to add. use a negative value to subtract. + * @example + * + * var gdt = new GlideDateTime('2011-08-31 08:00:00'); + * gdt.addMonthsLocalTime(2); + * gs.info(gdt.getDate()); + */ + addMonthsLocalTime(amount: number): void; + + /** + * Adds a specified number of months to the current GlideDateTime object. A negative parameter + * subtracts months. The method determines the UTC date and time equivalent to the value stored by + * the GlideDateTime object, then adds or subtracts months using the UTC date and time values. + * + * @param months The number of months to add. Use a negative value to subtract. + * @example + * + * var gdt = new GlideDateTime('2011-08-31 08:00:00'); + * gdt.addMonthsUTC(2); + * gs.info(gdt.getDate()); + */ + addMonthsUTC(amount: number): void; + + /** + * Adds the specified number of seconds to the current GlideDateTime object. + * + * @param seconds The number of seconds to add. + * @example + * + * var gdt = new GlideDateTime('2011-12-07 08:00:00'); + * gdt.addSeconds(1000); + * gs.info(gdt.getValue()); + */ + addSeconds(value: number): void; + + /** + * Adds a specified number of weeks to the current GlideDateTime object. A negative parameter + * subtracts weeks. The method determines the local date and time equivalent to the value stored + * by the GlideDateTime object, then adds or subtracts weeks using the local date and time values. + * + * @param weeks The number of weeks to add. Use a negative value to subtract. + * @example + * + * var gdt = new GlideDateTime('2011-08-31 08:00:00'); + * gdt.addWeeksLocalTime(-1); + * gs.info(gdt.getDate()); + */ + addWeeksLocalTime(amount: number): void; + + /** + * Adds a specified number of weeks to the current GlideDateTime object. A negative parameter + * subtracts weeks. The method determines the UTC date and time equivalent to the value stored by + * the GlideDateTime object, then adds or subtracts weeks using the UTC date and time values. + * + * @param weeks The number of weeks to add. Use a negative value to subtract. + * @example + * + * var gdt = new GlideDateTime('2011-08-31 08:00:00'); + * gdt.addWeeksUTC(-1); + * gs.info(gdt.getDate()); + */ + addWeeksUTC(amount: number): void; + + /** + * Adds a specified number of years to the current GlideDateTime object. A negative parameter + * subtracts years. The method determines the local date and time equivalent to the value stored + * by the GlideDateTime object, then adds or subtracts years using the local date and time values. + * + * @param years The number of years to add. Use a negative value to subtract. + * @example + * + * var gdt = new GlideDateTime('2011-08-31 08:00:00'); + * gdt.addYearsLocalTime(1); + * gs.info(gdt.getDate()); + */ + addYearsLocalTime(amount: number): void; + + /** + * Adds a specified number of years to the current GlideDateTime object. A negative parameter + * subtracts years. The date and time value stored by GlideDateTime object is interpreted as being + * in the UTC time zone. + * + * @param years The number of years to add. Use a negative value to subtract. + * @example + * + * var gdt = new GlideDateTime('2011-08-31 08:00:00'); + * gdt.addYearsUTC(1); + * gs.info(gdt.getDate()); + */ + addYearsUTC(amount: number): void; + + /** + * Determines if the GlideDateTime object occurs after the specified GlideDateTime. + * + * @param gdt The time to check against. + * @returns Returns true if the GlideDateTime object's time is after the time specified by + * the parameter. + * @example + * + * var gdt1 = new GlideDateTime('2016-05-09 10:11:12'); + * var gdt2 = new GlideDateTime('2017-06-12 15:11:12'); + * gs.info(gdt1.after(gdt2)); + */ + after(gdt: GlideDateTime): boolean; + + /** + * Determines if the GlideDateTime object occurs before the specified GlideDateTime. + * + * @param gdt The time to check against. + * @returns Returns true if the GlideDateTime object's time is before the time specified by + * the parameter. + * @example + * + * var gdt1 = new GlideDateTime('2016-05-09 10:11:12'); + * var gdt2 = new GlideDateTime('2017-06-12 15:11:12'); + * gs.info(gdt1.before(gdt2)); + */ + + before(gdt: GlideDateTime): boolean; + + /** + * Compares two date and time objects to determine whether they are equivalent or one occurs + * before or after the other. + * + * @param o Date and time object in GlideDateTime format + * @returns + * 0 = Dates are equal + * 1 = The object's date is after the date specified in the parameter + * -1 = The object's date is before the date specified in the parameter + * + * @example + * + * var initDate = new GlideDateTime('2011-08-01 12:00:00'); + * var compDate1 = new GlideDateTime('2011-08-01 12:00:00'); + * var compDate2 = new GlideDateTime('2011-07-31 12:00:00'); + * var compDate3 = new GlideDateTime('2011-08-04 16:00:00'); + * gs.info(initDate.compareTo(compDate1)); // Equals (0) + * gs.info(initDate.compareTo(compDate2)); // initDate is after compDate2 (1) + * gs.info(initDate.compareTo(compDate3)); // initDate is before compDate3 (-1) + */ + compareTo(o: object): number; + + /** + * Compares a datetime with an existing value for equality. + * + * @param dateTime The datetime to compare. + * @returns Returns true if they are equal; otherwise, false. + * @example + * + * var gdt = new GlideDateTime('2011-08-31 00:00:00'); + * gs.info(gdt.equals('2011-09-30 00:12:01')); + */ + equals(dateTime: GlideDateTime | string): boolean; + + /** + * Gets the date stored by the GlideDateTime object, expressed in the standard format, yyyy-MM-dd, + * and the system time zone, UTC by default. + * + * @returns The date in the system time zone. + * @example + * + * var gdt = new GlideDateTime('2011-08-31 00:00:00'); + * gs.info(gdt.getDate()); + */ + getDate(): GlideTime; + + /** + * Gets the day of the month stored by the GlideDateTime object, expressed in the current user's + * time zone. + * + * @returns The day of the month in the user's time zone, from 1 to 31. + * @example + * + * var gdt = new GlideDateTime('2011-12-02 12:00:00'); + * gs.info(gdt.getDayOfMonthLocalTime()); + */ + getDayOfMonthLocalTime(): number; + + /** + * Gets the day of the month stored by the GlideDateTime object, expressed in the UTC time zone. + * + * @returns The day of the month in the UTC time zone, from 1 to 31. + * @example + * + * var gdt = new GlideDateTime('2011-12-02 12:00:00'); + * gs.info(gdt.getDayOfMonthUTC()); + */ + getDayOfMonthUTC(): number; + + /** + * Gets the day of the week stored by the GlideDateTime object, expressed in the user's time zone. + * + * @returns The day of week value, in the user's time zone, from 1 to 7. Monday equals 1, Sunday + * equals 7. + * @example + * + * var gdt = new GlideDateTime('2011-12-01 12:00:00');//Thursday + * gs.info(gdt.getDayOfWeekLocalTime()); + */ + getDayOfWeekLocalTime(): number; + + /** + * Gets the day of the week stored by the GlideDateTime object, expressed in the UTC time zone. + * + * @returns The day of week value from 1 to 7. Monday equals 1, Sunday equals 7. + * @example + * + * var gdt = new GlideDateTime('2011-12-01 12:00:00');//Thursday + * gs.info(gdt.getDayOfWeekLocalTime()); + */ + getDayOfWeekUTC(): number; + + /** + * Gets the number of days in the month stored by the GlideDateTime object, expressed in the + * current user's time zone. + * + * @returns The number of days in the current month in the user's time zone. + * @example + * + * var gdt = new GlideDateTime('2011-12-02 12:00:00'); //December + * gs.info(gdt.getDaysInMonthLocalTime()); + */ + getDaysInMonthLocalTime(): number; + + /** + * Gets the number of days in the month stored by the GlideDateTime object, expressed in the UTC + * time zone. + * + * @returns The number of days in the month stored by the GlideDateTime object, expressed in the + * UTC time zone. + * @example + * + * var gdt = new GlideDateTime('2011-11-02 12:00:00'); //November + * gs.info(gdt.getDaysInMonthUTC()); + */ + getDaysInMonthUTC(): number; + + /** + * Gets the date and time value in the current user's display format and time zone. + * + * @returns The date and time in the user's format and time zone. Keep in mind when designing + * business rules or script includes that this method may return values in different formats for + * different users. + * @example + * + * var gdt = new GlideDateTime('2011-08-31 08:00:00'); + * gs.info(gdt.getDisplayValue()); //uses current user session time zone (US/Pacific) + */ + getDisplayValue(): string; + + /** + * Gets the display value in the internal format (yyyy-MM-dd HH:mm:ss). + * + * @returns The date and time values for the GlideDateTime object in the current user's time zone + * and the internal date and time format of yyyy-MM-dd HH:mm:ss. + * @example + * + * var gdt = new GlideDateTime('2011-08-31 08:00:00'); + * gs.info(gdt.getDisplayValueInternal()); //uses current user session time zone (US/Pacific) + */ + getDisplayValueInternal(): string; + + /** + * Gets the amount of time that daylight saving time is offset. + * + * @returns Amount of time, in milliseconds, that daylight saving is offset. Returns 0 if there is + * no offset or if the time is not during daylight saving time. + * @example + * + * var gdt = new GlideDateTime('2014-08-31 08:00:00'); + * gs.info(gdt.getDSTOffset()); //uses current user session time zone (US/Pacific) + */ + getDSTOffset(): number; + + /** + * Gets the current error message. + * + * @returns The error message. + * @example + * + * var gdt = new GlideDateTime(); + * gdt.setDisplayValue('2011-aa-01 00:00:00'); + * gs.info(gdt.getErrorMsg()); + */ + getErrorMsg(): string; + + /** + * Returns the object's time in the local time zone and in the internal format. + * + * @returns The object's time in the local time zone and the internal format. + */ + getInternalFormattedLocalTime(): string; + + /** + * Gets the date stored by the GlideDateTime object, expressed in the standard format, yyyy-MM-dd, + * and the current user's time zone. + * + * @returns The date in the user's time zone. + * @example + * + * var gdt = new GlideDateTime('2011-08-31 08:00:00'); + * gs.info(gdt.getLocalDate()); + */ + getLocalDate(): GlideTime; + + /** + * Returns a GlideTime object that represents the time portion of the GlideDateTime object in the + * user's time zone. + * + * @returns The time in the user's time zone. + * @example + * + * var gdt = new GlideDateTime('2014-08-31 08:00:00'); + * gt = gdt.getLocalTime(); + * gs.info("local time is " + gt.getByFormat('hh:mm:ss')); + */ + getLocalTime(): GlideTime; + + /** + * Gets the month stored by the GlideDateTime object, expressed in the current user's time zone. + * + * @returns The numerical value of the month. + * @example + * + * var gdt = new GlideDateTime('2011-11-02 12:00:00'); //November + * gs.info(gdt.getMonthLocalTime()); + */ + getMonthLocalTime(): number; + + /** + * Gets the month stored by the GlideDateTime object, expressed in the UTC time zone. + * + * @returns The numerical value of the month. + * @example + * + * var gdt = new GlideDateTime('2011-11-02 12:00:00'); //November + * gs.info(gdt.getMonthUTC()); + */ + getMonthUTC(): number; + + /** + * Gets the number of milliseconds since January 1, 1970, 00:00:00 GMT. + * + * @returns The number of milliseconds since January 1, 1970, 00:00:00 GMT. + * @example + * + * var gdt = new GlideDateTime('2011-08-31 08:00:00'); + * gs.info(gdt.getNumericValue()); + */ + getNumericValue(): number; + + /** + * Returns a GlideTime object that represents the time portion of the GlideDateTime object. + * + * @returns The Unix duration stamp in system format based on GMT time. + * @example + * + * var gdt = new GlideDateTime('2014-08-31 08:00:00'); + * gt = gdt.getTime(); + * gs.info(gt.getByFormat('hh:mm:ss')); + */ + getTime(): GlideTime; + + /** + * Gets the time zone offset in milliseconds. + * + * @returns The number of milliseconds of time zone offset. + * @example + * + * var gdt = new GlideDateTime(); + * gdt.getLocalTime(); // PST local time + * gs.info(gdt.getTZOffset()); + */ + getTZOffset(): number; + + /** + * Returns the object's time in the local time zone and in the user's format. + * + * @returns The object's time in the local time zone and in the user's format. + */ + getUserFormattedLocalTime(): string; + + /** + * Gets the date and time value stored by the GlideDateTime object in the internal format, + * yyyy-MM-dd HH:mm:ss, and the system time zone, UTC by default. + * + * @returns The date and time value in the internal format and system time zone. + * @example + * + * var gdt = new GlideDateTime('2014-08-31 08:00:00'); + * gs.info(gdt.getValue()); + */ + getValue(): string; + + /** + * Gets the number of the week stored by the GlideDateTime object, expressed in the current user's + * time zone. All weeks begin on Sunday. The first week of the year is the week that contains at + * least one day of the new year. The week beginning Sunday 2015-12-27 is considered the first + * week of 2016 as that week contains January 1 and 2. + * + * @returns The number of the current week in local time. The highest week number in a year is + * either 52 or 53. + * @example + * + * var gdt = new GlideDateTime('2011-12-01 12:00:00');//49th week, 1st week in december + * gs.info(gdt.getWeekOfYearLocalTime()); + */ + getWeekOfYearLocalTime(): number; + + /** + * Gets the number of the week stored by the GlideDateTime object, expressed in the UTC time zone. + * All weeks begin on Sunday. The first week of the year is the week that contains at least one + * day of the new year. The week beginning Sunday 2015-12-27 is considered the first week of 2016 + * as that week contains January 1 and 2. + * + * @returns The number of the current week in UTC time. The highest week number in a year is + * either 52 or 53. + * @example + * + * var gdt = new GlideDateTime('2011-12-01 12:00:00');//49th week, 1st week in december + * gs.info(gdt.getWeekOfYearUTC()); + */ + getWeekOfYearUTC(): number; + + /** + * Gets the year stored by the GlideDateTime object, expressed in the current user's time zone. + * + * @returns Four-digit year value in the user's time zone. + * @example + * + * var gdt = new GlideDateTime('2011-11-02 12:00:00'); + * gs.info(gdt.getYearLocalTime()); + */ + getYearLocalTime(): number; + + /** + * Gets the year stored by the GlideDateTime object, expressed in the UTC time zone. + * + * @returns 4-digit year value in the UTC time zone. + * @example + * + * var gdt = new GlideDateTime('2011-11-02 12:00:00'); + * gs.info(gdt.getYearUTC()); + */ + getYearUTC(): number; + + /** + * Determines if an object's date is set. + * + * @returns True if the object date is set; otherwise, returns false. + * @example + * + * var gdt = new GlideDateTime('2011-08-31 08:00:00'); + * gs.info(gdt.hasDate()); + */ + hasDate(): boolean; + + /** + * Determines if an object's time uses a daylight saving offset. + * + * @returns True if the time is daylight saving; otherwise, returns false. + * @example + * + * var gdt = new GlideDateTime('2014-08-31 00:00:00'); + * gs.info(gdt.isDST()); //true + */ + isDST(): boolean; + + /** + * Determines if a value is a valid date and time. + * + * @returns True if value is valid; otherwise, returns false. + * @example + * + * var gdt = new GlideDateTime(); + * gdt.setDisplayValue('2011-aa-01 00:00:00'); + * gs.info(gdt.isValid()); + */ + isValid(): boolean; + + /** + * Determines if the GlideDateTime object occurs on or after the specified GlideDateTime. + * + * @param gdt The time to check against. + * @returns Returns true if the GlideDateTime object's time is on or after the time specified by + * the parameter. + * @example + * + * var gdt1 = new GlideDateTime('2016-05-09 10:11:12'); + * var gdt2 = new GlideDateTime('2017-06-12 15:11:12'); + * gs.info(gdt1.onOrAfter(gdt2)); + */ + onOrAfter(gdt: GlideDateTime): boolean; + + /** + * Determines if the GlideDateTime object occurs on or before the specified GlideDateTime. + * + * @param gdt The time to check against. + * @returns Returns true if the GlideDateTime object's time is on or before the time specified by + * the parameter. + * @example + * + * var gdt1 = new GlideDateTime('2016-05-09 10:11:12'); + * var gdt2 = new GlideDateTime('2017-06-12 15:11:12'); + * gs.info(gdt1.onOrBefore(gdt2)); + */ + onOrBefore(gdt: GlideDateTime): boolean; + + /** + * Sets the day of the month to a specified value in the current user's time zone. + * + * @param day The day of month to change to, from 1 to 31. If this value is greater than the + * maximum number of days in the month, the value is set to the last day of the month. + * @example + * + * var gdt = new GlideDateTime(); + * gdt.setDayOfMonthLocalTime(9); + * gs.info(gdt.getDayOfMonthLocalTime()); + */ + setDayOfMonthLocalTime(day: number): void; + + /** + * Sets the day of the month to a specified value in the UTC time zone. + * + * @param day The day of month to change to, from 1 to 31. If this value is greater than the + * maximum number of days in the month, the value is set to the last day of the month. + * @example + * + * var gdt = new GlideDateTime(); + * gdt.setDayOfMonthUTC(9); + * gs.info(gdt.getDayOfMonthUTC()); + */ + setDayOfMonthUTC(day: number): void; + + /** + * Sets a date and time value using the current user's display format and time zone. + * + * @param asDisplayed The date and time in the current user's display format and time zone. The + * parameter must be formatted using the current user's preferred display format, such as + * MM-dd-yyyy HH:mm:ss. To assign the current date and time to a variable in a workflow script, + * use variable.setDisplayValue(gs.nowDateTime);. + * @example + * + * var gdt = new GlideDateTime('2014-02-02 12:00:00'); + * gdt.setDisplayValue('2014-01-01 12:00:00');//uses current user session time zone (US/Pacific) + * gs.info(gdt.getValue()); + */ + setDisplayValue(asDisplayed: string): void; + + /** + * Sets a date and time value using the current user's time zone and the specified date and time + * format. This method throws a runtime exception if the date and time format used in the value + * parameter does not match the format parameter. + * + * You can retrieve the error message by calling getErrorMsg() on the GlideDateTime object after + * the exception is caught. + * + * @param value The date and time in the current user's time zone. + * @param format The date and time format to use to parse the value + * parameter. + * @example + * + * var gdt = new GlideDateTime('2011-02-02 12:00:00'); + * gdt.setDisplayValue('20-5-2011 12:00:00', 'dd-MM-yyyy HH:mm:ss'); //uses current user session time zone (US/Pacific) + * gs.info(gdt.getValue()); + */ + setDisplayValue(value: string, format?: string): void; + + /** + * Sets a date and time value using the internal format (yyyy-MM-dd HH:mm:ss) and the current + * user's time zone. + * + * @param value The date and time in internal format. + * @example + * + * var gdt = new GlideDateTime('2014-02-02 12:00:00'); + * //uses current user session time zone (US/Pacific) + * gdt.setDisplayValueInternal('2014-01-01 12:00:00'); + * gs.info(gdt.getValue()); + */ + setDisplayValueInternal(value: string): void; + + /** + * Sets the date and time of the current object using an existing GlideDateTime object. This + * method is equivalent to instantiating a new object with a GlideDateTime parameter. + * + * @param g The object to use for setting the datetime value. + * @example + * + * var dt1 = new GlideDateTime('2011-01-01 12:00:00'); + * var dt2 = new GlideDateTime('2011-02-02 08:00:00'); + * dt1.setGlideDateTime(dt2); + * gs.info(dt1.getValue()); + */ + setGlideDateTime(g: GlideDateTime): void; + + /** + * Sets the month stored by the GlideDateTime object to the specified value using the current + * user's time zone. + * + * @param month The month to change to. + * @example + * + * var gdt = new GlideDateTime(); + * gdt.setMonthLocalTime(1); + * gs.info(gdt.getMonthLocalTime()); + */ + setMonthLocalTime(month: number): void; + + /** + * Sets the month stored by the GlideDateTime object to the specified value using the UTC time + * zone. + * + * @param month The month to change to. + * @example + * + * var gdt = new GlideDateTime(); + * gdt.setMonthUTC(1); + * gs.info(gdt.getMonthUTC()); + */ + setMonthUTC(month: number): void; + + /** + * Sets the date and time of the GlideDateTime object. + * + * @param o The date and time to use. This parameter may be one of several types: + * + * - A string in the UTC time zone and the internal format of yyyy-MM-dd HH:mm:ss. Sets the value + * of the object to the specified date and time. Using the method this way is equivalent to + * instantiating a new GlideDateTime object using the GlideDateTime(String value) constructor. If + * the date and time format used does not match the internal format, the method attempts to set + * the date and time using other available formats. Resolving the date and time this way can lead + * to inaccurate data due to ambiguity in the day and month values. When using a non-standard date + * and time format, use setValueUTC(String dt, String format) instead. + * - A GlideDateTime object. Sets the value of the object to the date and time stored by the + * GlideDateTime passed in the parameter. Using the method this way is equivalent to instantiating + * a new GlideDateTime object using the GlideDateTime(GlideDateTime g) constructor. + * - A JavaScript Number. Sets the value of the object using the Number value as milliseconds past + * January 1, 1970 00:00:00 GMT. + * @example + * + * var gdt = new GlideDateTime('2011-01-01 12:00:00'); + * gdt.setValue('2011-02-02 08:00:00'); // value set = 2011-02-02 08:00:00 + * gs.info(gdt.getValue()); + */ + setValue(o: string | number | GlideDateTime): void; + + /** + * Sets a date and time value using the UTC time zone and the specified date and time format. This + * method throws a runtime exception if the date and time format used in the `dt` parameter does + * not match the `format` parameter. You can retrieve the error message by calling `getErrorMsg()` + * on the GlideDateTime object after the exception is caught. + * + * @param dt The date and time to use. + * @param format The date and time format to use. + * @example + * + * var gdt = new GlideDateTime('2011-01-01 12:00:00'); + * gdt.setValueUTC('15-02-2011 08:00:00', 'dd-MM-yyyy HH:mm:ss'); + * gs.info(gdt.getValue()); + */ + setValueUTC(dt: string, format: string): void; + + /** + * Sets the year stored by the GlideDateTime object to the specified value using the current + * user's time zone. + * + * @param year The year to change to. + * @example var gdt = new GlideDateTime(); + * gdt.setYearLocalTime(2013); + * gs.info(gdt.getYearLocalTime()); + */ + setYearLocalTime(year: number): void; + + /** + * Sets the year stored by the GlideDateTime object to the specified value using the UTC time + * zone. + * + * @param year The year to change to. + * @example + * + * var gdt = new GlideDateTime(); + * gdt.setYearUTC(2013); + * gs.info(gdt.getYearUTC()); + */ + setYearUTC(year: number): void; + + /** + * Gets the duration difference between two GlideDateTime values. + * + * @param Start The start value. + * @param End The end value. + * @returns The duration between the two values. + * @example + * + * var gdt1 = new GlideDateTime('2011-08-28 09:00:00'); + * var gdt2 = new GlideDateTime('2011-08-31 08:00:00'); + * var dur = GlideDateTime.subtract(gdt1, gdt2); //the difference between gdt1 and gdt2 + * gs.info(dur.getDisplayValue()); + */ + static subtract(start: GlideDateTime, end?: GlideDateTime): GlideDuration; + + /** + * Subtracts a specified amount of time from the current GlideDateTime object. + * + * @param time The time value to subtract. + * @example + * + * var gdt = new GlideDateTime('2011-08-31 08:00:00'); + * var gtime1 = new GlideTime(); + * gtime1.setValue('00:00:20'); + * gdt.subtract(gtime1); + * var gtime2 = gdt.getTime(); + * gs.info(gtime2.getByFormat('hh:mm:ss')); + */ + + subtract(time: GlideTime): void; + + /** + * Subtracts the specified number of milliseconds from the GlideDateTime object. + * + * @param milliseconds The number of milliseconds to subtract. + * @example + * + * var gdt = new GlideDateTime('2011-12-07 08:00:00'); + * gdt.subtract(1000); + * gs.info(gdt.getValue()); + */ + subtract(milliseconds: number): void; + + /** + * Gets the date and time value stored by the GlideDateTime object in the internal format, + * yyyy-MM-dd HH:mm:ss, and the system time zone, UTC by default. This method is equivalent to + * getValue(). + * + * @returns The date and time stored by the GlideDateTime object in the system time zone + * and format. + * @example + * + * var gdt = new GlideDateTime('2011-08-31 08:00:00'); + * gs.info(gdt.toString()); + */ + toString(): string; +} diff --git a/types/servicenow-london/GlideDuration.d.ts b/types/servicenow-london/GlideDuration.d.ts new file mode 100644 index 0000000000..b616be5000 --- /dev/null +++ b/types/servicenow-london/GlideDuration.d.ts @@ -0,0 +1,160 @@ +/** + * The scoped GlideDuration class provides methods for working with spans of time or durations. + * + * GlideDuration objects store the duration as a date and time from January 1, 1970, 00:00:00. + * As a result, setValue() and getValue() use the scoped GlideDateTime object for parameters and + * return values. + */ +declare class GlideDuration { + /** + * Instantiates a GlideDuration object. + */ + constructor(); + + /** + * Instantiates a GlideDuration object by cloning the value of another GlideDuration object. + * + * @param another Another scoped GlideDuration object. + */ + constructor(another: GlideDuration); + + /** + * Instantiates a GlideDuration object with the specified duration. + * + * @param milliseconds The duration value in milliseconds. + */ + constructor(milliseconds: number); + + /** + * Instantiates a GlideDuration object with the specified display value. + * + * @param displayValue The display value. + */ + constructor(displayValue: string); + + /** + * Add the specified duration to the object. + * + * @param duration The value to add to the object. + * @returns The sum of the current and the added duration. + * @example + * + * var duration = new GlideDuration('3 12:00:00'); + * var duration2 = new GlideDuration('3:00:00'); + * var answer = duration.add(duration2); + * gs.info(answer.getDisplayValue()); + */ + add(value: GlideDuration): GlideDuration; + + /** + * Gets the duration in the specified format. + * + * @param format The duration format. + * @returns The current duration in the specified format. + * @example + * + * var dur = new GlideDuration('3 22:00:00'); + * gs.info(dur.getByFormat('HH:mm')); + */ + getByFormat(format: string): string; + + /** + * Gets the number of days. + * + * @returns The number of days. + * @example + * + * var dur = new GlideDuration('3 12:00:00'); + * gs.info(dur.getDayPart()); + */ + getDayPart(): number; + + /** + * Gets the display value of the duration in number of days, hours, and + * minutes. + * + * @returns The number of days, hours, and minutes. + * @example + * + * var dur = new GlideDuration('3 12:00:00'); + * gs.info(dur.getDisplayValue()); + */ + getDisplayValue(): string; + + /** + * Gets the duration value in "d HH:mm:ss" format. + * + * @returns The duration value. + * @example + * + * var dur = new GlideDuration('3 12:00:00'); + * gs.info(dur.getDurationValue()); + */ + getDurationValue(): string; + + /** + * Gets the rounded number of days. If the time part is more than 12 hours, the return value is + * rounded up. Otherwise, it is rounded down. + * + * @returns The day part, rounded. + * @example + * + * var dur = new GlideDuration('3 11:00:00'); + * gs.info(dur.getRoundedDayPart()); + */ + getRoundedDayPart(): number; + + /** + * Gets the internal value of the GlideDuration object. + * + * @returns The duration in the object's internal format, which is the date and time from + * January 1, 1970, 00:00:00. + * @example + * + * var dur = new GlideDuration('3 12:00:00'); + * gs.info(dur.getValue()); + */ + getValue(): string; + + /** + * Sets the display value. + * + * @param asDisplayed The duration in "d HH:mm:ss" format. + * @returns Method does not return a value + * @example + * + * var dur = new GlideDuration(); + * dur.setDisplayValue('3 08:00:00'); + * gs.info(dur.getDisplayValue()); + */ + + setDisplayValue(asDisplayed: string): void; + + /** + * Sets the internal value of the GlideDuration object. + * + * @param value The duration in the object's internal format, which is the date and time from + * January 1, 1970, 00:00:00. + * @example + * + * var dur = new GlideDuration(); + * // Sets internal DateTime value. The String will be parsed into a GlideDateTime object. + * dur.setValue('1970-01-05 08:00:00'); + * gs.info(dur.getDisplayValue()); + */ + setValue(value: string): void; + + /** + * Subtracts the specified duration from the current duration. + * + * @param duration The duration to subtract. + * @returns GlideDuration of the difference. + * @example + * + * var duration = new GlideDuration('3 12:00:00'); + * var duration2 = new GlideDuration('3:00:00'); + * var answer = duration.subtract(duration2); + * gs.info(answer.getDisplayValue()); + */ + subtract(value: GlideDuration): GlideDuration; +} diff --git a/types/servicenow-london/GlideEmailOutbound.d.ts b/types/servicenow-london/GlideEmailOutbound.d.ts new file mode 100644 index 0000000000..c9589efb71 --- /dev/null +++ b/types/servicenow-london/GlideEmailOutbound.d.ts @@ -0,0 +1,90 @@ +/** + * The scoped GlideEmailOutbound class implements the email object for scoped applications. + * You can use the GlideEmailOutbound methods with the email global object available in mail + * scripts. The email object behaves identically for global and scoped applications. + */ +declare class GlideEmailOutbound { + /** + * Instantiates a scoped GlideEmailOutbound object. + */ + constructor(); + + /** + * Adds the address to either the cc or bcc list. + * + * @param type Either cc or bcc, determines the list to which the address is added. + * @param address The recipient's email address. + * @example + * + * email.addAddress('cc', 'joe.employee@something.com'); + */ + addAddress(type: string, address: string): void; + + /** + * Adds the recipient to either the cc or bcc list, but uses the display name instead of the + * address when showing the recipient. + * + * @param type Either cc or bcc, determines the list to which the address is added. + * @param address The recipient's email address. + * @param displayName The name to be shown instead of the email address. + * @example + * + * email.addAddress('bcc', 'joe.employee@something.com', 'dudley rocks'); + */ + addAddress(type: string, address: string, displayName: string): void; + + /** + * Returns the email's subject line. + * + * @returns The email's subject line. + * @example + * + * var subject = email.getSubject(); + */ + getSubject(): string; + + /** + * Returns the email's watermark. + */ + getWatermark(): string; + + /** + * Sets the body of the email. + * + * @param bodyText The body of the email. + * @example + * + * email.setBody('Dear Sir, ...'); + */ + setBody(bodyText: string): void; + + /** + * Sets the sender's address. + * + * @param address The sender's email address. + * @example + * + * email.setFrom('joe.employee@something.com'); + */ + setFrom(address: string): void; + + /** + * Sets the reply to address. + * + * @param address The reply to email address. + * @example + * + * email.setReplyTo('joe.employee@something.com'); + */ + setReplyTo(address: string): void; + + /** + * Sets the email's subject line. + * + * @param subject Text for the subject line. + * @example + * + * email.setSubject('Important Issues to discuss'); + */ + setSubject(subject: string): void; +} diff --git a/types/servicenow-london/GlideFilter.d.ts b/types/servicenow-london/GlideFilter.d.ts new file mode 100644 index 0000000000..31694e19b7 --- /dev/null +++ b/types/servicenow-london/GlideFilter.d.ts @@ -0,0 +1,3 @@ +declare const GlideFilter: { + checkRecord(gr: ScopedGlideRecord, filter: string, matchAll?: object): boolean; +}; diff --git a/types/servicenow-london/GlideLocale.d.ts b/types/servicenow-london/GlideLocale.d.ts new file mode 100644 index 0000000000..841d3d47a2 --- /dev/null +++ b/types/servicenow-london/GlideLocale.d.ts @@ -0,0 +1,5 @@ +declare class GlideLocale { + static get(): GlideLocale; + getGroupingSeparator(): string; + getDecimalSeparator(): string; +} diff --git a/types/servicenow-london/GlidePluginManager.d.ts b/types/servicenow-london/GlidePluginManager.d.ts new file mode 100644 index 0000000000..f60dfe1433 --- /dev/null +++ b/types/servicenow-london/GlidePluginManager.d.ts @@ -0,0 +1,3 @@ +declare class GlidePluginManager { + isActive(pluginId: string): boolean; +} diff --git a/types/servicenow-london/GlideRecordOperation.d.ts b/types/servicenow-london/GlideRecordOperation.d.ts new file mode 100644 index 0000000000..06ad6eb255 --- /dev/null +++ b/types/servicenow-london/GlideRecordOperation.d.ts @@ -0,0 +1 @@ +type GlideRecordOperation = 'insert' | 'update' | 'delete'; diff --git a/types/servicenow-london/GlideSchedule.d.ts b/types/servicenow-london/GlideSchedule.d.ts new file mode 100644 index 0000000000..435b7c8506 --- /dev/null +++ b/types/servicenow-london/GlideSchedule.d.ts @@ -0,0 +1,167 @@ +/** + * The scoped GlideSchedule API provides methods for performing operations on GlideSchedule + * objects, such as adding new schedule segments to a schedule, determining if a datetime is within + * the schedule, or setting the schedule timezone. + */ +declare class GlideSchedule { + /** + * Instantiates an empty GlideSchedule object. + */ + constructor(); + + /** + * Instantiates a GlideSchedule object and loads the schedule information. If a timezone is not + * specified or is nil, the current session timezone is used. + * + * @param sysId The system ID for the schedule. + * @param timeZone The time zone. (Optional) + * @example + * + * var schedule = new GlideSchedule('090eecae0a0a0b260077e1dfa71da828', 'US/Pacific'); + */ + constructor(sysId: string, timeZone?: string); + + /** + * Adds a new schedule segment to the current schedule. + * + * @param startDate The starting date of the new schedule segment. + * @param offSet The time offset of the new schedule segment. + * @returns The schedule updated with the new schedule segment. + * + * @example + * + * var startDate = new GlideDateTime('2014-01-02'); + * var days = 2; + * var dur = new GlideDuration(60 * 60 * 24 * 1000 * days); + * var schedule = new GlideSchedule(); + * var end = schedule.add(startDate, dur); + * gs.info(end); + */ + add(startDate: GlideDateTime, offset: GlideDuration): GlideDateTime; + + /** + * Determines the elapsed time in the schedule between two date time values using the + * timezone of the schedule or, if that is not specified, the timezone of the session. + * + * @param startDate The starting datetime. + * @param endDate The ending datetime. + * @returns The difference between the starting and ending datetime. + * + * @example + * + * var startDate = new GlideDateTime('2014-10-16 02:00:00'); + * var endDate = new GlideDateTime('2014-10-18 04:00:00'); + * var schedule = new GlideSchedule(); + * // loads "8-5 weekdays excluding holidays" schedule + * schedule.load('090eecae0a0a0b260077e1dfa71da828'); + * var duration = schedule.duration(startDate, endDate); + * gs.info(duration.getDurationValue()); // gets the elapsed time in schedule + */ + duration(startDate: GlideDateTime, endDate: GlideDateTime): GlideDuration; + + /** + * Retrieves the schedule name. + * + * @returns The name of the current schedule. + * + * @example + * + * sys_id ='04e664654a36232701a2247dcd8fc4cf'; // sys_id for "Application" schedule record + * var sched = new GlideSchedule(sys_id); + * gs.info(sched.getName()); + */ + getName(): string; + + /** + * Determines if the given datetime is within the current schedule. + * + * @param time The datetime value to check. + * @returns True if the specified datetime is within the schedule; otherwise, + * false. + * + * @example + * + * var g = new GlideRecord('cmn_schedule'); + * g.addQuery('type', 'blackout'); + * g.query(); + * if (g.next()) { + * var sched = new GlideSchedule(g.sys_id); + * var d = new GlideDateTime(); + * d.setDisplayValue("2007-09-18 12:00:00"); + * if (sched.isInSchedule(d)) + * gs.info("Is in the schedule"); + * else + * gs.info("Is NOT in the schedule"); + * } + */ + isInSchedule(time: GlideDateTime): string; + + /** + * Determines if the current schedule is valid. A schedule is valid if it has at least one + * schedule span. + * + * @returns True if the schedule is valid. + * + * @example + * + * var g = new GlideRecord('cmn_schedule'); + * g.addQuery('type', 'blackout'); + * g.query(); + * if (g.next()) { + * var sched = new GlideSchedule(g.sys_id); + * var d = new GlideDateTime(); + * d.setDisplayValue("2007-09-18 12:00:00"); + * if (sched.isValid()) + * gs.info("Is valid"); + * else + * gs.info("Is not valid"); + * } + */ + isValid(): boolean; + + /** + * Loads a schedule with the schedule information. + * + * @param sysID The system ID of the schedule. + * @param [timeZone] (Optional) The timezone. If a timezone is not specified, or is nil, the + * current session timezone is used for the schedule. + * @param [excludeSpanID] Any span to exclude. + * @returns Method does not return a value + * + * @example + * + * var x = new GlideSchedule(); + * x.load('08fcd0830a0a0b2600079f56b1adb9ae'); + */ + load(sysId: string, timeZone?: string, excludeSpanId?: string): void; + + /** + * Sets the timezone for the current schedule. + * + * @param timeZone The timezone. + * @returns Method does not return a value + * + * @example + * + * var schedule = new GlideSchedule(); + * schedule.setTimeZone('US/Pacific'); + */ + setTimeZone(tz: string): void; + + /** + * Determines how much time (in milliseconds) until start time of the next schedule + * item. + * + * @param time The time to be evaluated. + * @param [timeZone] The timezone. + * @returns The number of milliseconds until the start time of the next schedule item. + * Returns -1 if never. + * + * @example + * + * var startDate = new GlideDateTime('2014-10-25 08:00:00'); + * var glideSchedule = new GlideSchedule('08fcd0830a0a0b2600079f56b1adb9ae', 'UTC'); + * gs.info(glideSchedule.whenNext(startDate)); + */ + whenNext(time: GlideDateTime, timeZone?: string): number; +} diff --git a/types/servicenow-london/GlideScopedEvaluator.d.ts b/types/servicenow-london/GlideScopedEvaluator.d.ts new file mode 100644 index 0000000000..bb84e99329 --- /dev/null +++ b/types/servicenow-london/GlideScopedEvaluator.d.ts @@ -0,0 +1,95 @@ +/** + * The GlideScopedEvaluator API allows you to evaluate scripts in a GlideRecord field from + * both scoped and global server scripts. + */ +declare class GlideScopedEvaluator { + /** + * Instantiates a GlideScopedEvaluator object. + */ + constructor(); + + /** + * Evaluates a script from a GlideRecord field. + * + * @param grObj The GlideRecord containing a script expression. + * @param [scriptField] (Optional) The name of the field containing the script expression. + * @param [variables] (Optional) A map of variables with name-value pairs. These variables are + * available to the script during execution of this method. + * @returns The result of the script execution. + * @example + * + * // For this example, we created a table: "x_app_table" with two columns: + * // "short_description", "test_script" + * // "test_script" will store the script to be evaluated by GlideScopedEvaluator. + * gr = new GlideRecord('x_app_table'); + * gr.short_description = 'Testing GlideScopedEvaluator'; + * gr.test_script = "gs.getUser().getName() + ' says ' + greeting; "; + * gr.insert(); + * // setup variables to be used by the script + * var vars = {'greeting' : 'hello'}; + * //Evaluate the script from the field + * var evaluator = new GlideScopedEvaluator(); + * gr = new GlideRecord('x_app_table'); + * gr.addQuery('short_description','Testing GlideScopedEvaluator'); + * gr.query(); + * if (gr.next()) { + * gs.info(evaluator.evaluateScript(gr, 'test_script', vars)); + * } + */ + evaluateScript(grObj: ScopedGlideRecord, scriptField?: string, variables?: object | null): any; + + /** + * Returns a variable from a GlideScopedEvaluator object. + * + * @param name The name of the variable. + * @returns The value of the specified variable. + * @example + * + * //setting up a record that contains the script to be executed. + * gr = new GlideRecord('x_app_table'); + * gr.short_description = 'Calculate Addition'; + * gr.calculate = "result = x + y"; + * gr.insert(); + * var evaluator = new GlideScopedEvaluator(); + * evaluator.putVariable('x', 100); + * evaluator.putVariable('y', 200); + * evaluator.putVariable('result', null); + * // Now retrieve the result + * gr = new GlideRecord('x_app_table'); + * gr.addQuery('short_description','Calculate Addition'); + * gr.query(); + * if (gr.next()) { + * evaluator.evaluateScript(gr, 'calculate', null); + * gs.info(evaluator.getVariable('result')); + * } + */ + getVariable(name: string): any; + + /** + * Puts a variable into the GlideScopedEvaluator object. These variables are available to + * the script that this GlideScopedEvaluator object runs. + * + * @param name The name of the variable. + * @param value The value of the variable. + * @example + * + * //setting up a record that contains the script to be executed. + * gr = new GlideRecord('x_app_table'); + * gr.short_description = 'Calculate Addition'; + * gr.calculate = "result = x + y"; + * gr.insert(); + * var evaluator = new GlideScopedEvaluator(); + * evaluator.putVariable('x', 100); + * evaluator.putVariable('y', 200); + * evaluator.putVariable('result', null); + * // Now retrieve the result + * gr = new GlideRecord('x_app_table'); + * gr.addQuery('short_description','Calculate Addition'); + * gr.query(); + * if (gr.next()) { + * evaluator.evaluateScript(gr, 'calculate', null); + * gs.info(evaluator.getVariable('result')); + * } + */ + putVariable(name: string, value: any): void; +} diff --git a/types/servicenow-london/GlideScriptedProcessor.d.ts b/types/servicenow-london/GlideScriptedProcessor.d.ts new file mode 100644 index 0000000000..3ad2a72c97 --- /dev/null +++ b/types/servicenow-london/GlideScriptedProcessor.d.ts @@ -0,0 +1,5 @@ +interface GlideScriptedProcessor { + redirect(url: string): void; + writeOutput(contentType: string, s?: string): void; + writeJSON(o: object): void; +} diff --git a/types/servicenow-london/GlideSecureRandomUtil.d.ts b/types/servicenow-london/GlideSecureRandomUtil.d.ts new file mode 100644 index 0000000000..545354d30a --- /dev/null +++ b/types/servicenow-london/GlideSecureRandomUtil.d.ts @@ -0,0 +1,6 @@ +declare const GlideSecureRandomUtil: { + getSecureRandomInt(): number; + getSecureRandomIntBound(bound: number): number; + getSecureRandomLong(): number; + getSecureRandomString(length: number): string; +}; diff --git a/types/servicenow-london/GlideServletRequest.d.ts b/types/servicenow-london/GlideServletRequest.d.ts new file mode 100644 index 0000000000..027d81413f --- /dev/null +++ b/types/servicenow-london/GlideServletRequest.d.ts @@ -0,0 +1,11 @@ +interface GlideServletRequest { + getContentType(): string; + getHeader(name: string): string; + getHeaderNames(): string; + getHeaders(name: string): string; + getParameter(name: string): string; + getParameterNames(): string; + getQueryString(): string; + writeOutput(mimeType: string, output: string): void; + toString(): string; +} diff --git a/types/servicenow-london/GlideServletResponse.d.ts b/types/servicenow-london/GlideServletResponse.d.ts new file mode 100644 index 0000000000..1e2c4af3ed --- /dev/null +++ b/types/servicenow-london/GlideServletResponse.d.ts @@ -0,0 +1,5 @@ +interface GlideServletResponse { + setContentType(type: string): void; + setHeader(name: string, value: string): void; + setStatus(value: number): void; +} diff --git a/types/servicenow-london/GlideSession.d.ts b/types/servicenow-london/GlideSession.d.ts new file mode 100644 index 0000000000..ccf9a61c5d --- /dev/null +++ b/types/servicenow-london/GlideSession.d.ts @@ -0,0 +1,13 @@ +interface GlideSession { + isInteractive(): boolean; + isLoggedIn(): boolean; + getClientData(paramName: string): string; + getClientIP(): string; + getCurrentApplicationId(): string; + getLanguage(): string; + getTimeZoneName(): string; + getSessionToken(): string; + getUrlOnStack(): string; + isImpersonating(): boolean; + putClientData(paramName: string, paramValue: string): void; +} diff --git a/types/servicenow-london/GlideStringUtil.d.ts b/types/servicenow-london/GlideStringUtil.d.ts new file mode 100644 index 0000000000..326296d12d --- /dev/null +++ b/types/servicenow-london/GlideStringUtil.d.ts @@ -0,0 +1,16 @@ +declare const GlideStringUtil: { + dotToUnderBar(sourceString: string): string; + escapeAllQuotes(sourceString: string): string; + escapeForHomePage(sourceString: string): string; + escapeHTML(htmlString: string): string; + escapeNonPrintable(sourceString: string): string; + escapeQueryTermSeparator(sourceString: string): string; + escapeTicks(sourceString: string): string; + getHTMLValue(sourceString: string): string; + getNumeric(sourceString: string): string; + isBase64(sourceString: string): boolean; + isEligibleSysID(sourceString: string): boolean; + newLinesToBreaks(sourceString: string): string; + normalizeWhitespace(sourceString: string): string; + unescapeHTML(htmlString: string): string; +}; diff --git a/types/servicenow-london/GlideSysAttachment.d.ts b/types/servicenow-london/GlideSysAttachment.d.ts new file mode 100644 index 0000000000..8878cf877f --- /dev/null +++ b/types/servicenow-london/GlideSysAttachment.d.ts @@ -0,0 +1,26 @@ +declare class GlideSysAttachment { + constructor(); + copy( + sourceTable: string, + sourceSysId: string, + destinationTable: string, + destinationSysId: string + ): void; + deleteAttachment(sysId: string): void; + getContent(record: ScopedGlideRecord): any; + getContentBase64(record: ScopedGlideRecord): string; + getContentStream(sysId: string): object; + write(record: ScopedGlideRecord, fileName: string, contentType: string, data: any): string; + writeBase64( + record: ScopedGlideRecord, + fileName: string, + contentType: string, + base64Content: string + ): string; + writeContentStream( + record: ScopedGlideRecord, + fileName: string, + contentType: string, + inputStream: object + ): string; +} diff --git a/types/servicenow-london/GlideSystem.d.ts b/types/servicenow-london/GlideSystem.d.ts new file mode 100644 index 0000000000..77dee48d8f --- /dev/null +++ b/types/servicenow-london/GlideSystem.d.ts @@ -0,0 +1,90 @@ +interface GlideSystem { + addErrorMessage(message: string): void; + addInfoMessage(message: string): void; + base64Decode(source: string): string; + base64Encode(source: string): string; + beginningOfLastMonth(): string; + beginningOfLastWeek(): string; + beginningOfNextWeek(): string; + beginningOfNextMonth(): string; + beginningOfNextYear(): string; + beginningOfThisMonth(): string; + beginningOfThisQuarter(): string; + beginningOfThisWeek(): string; + beginningOfThisYear(): string; + dateGenerate(date: string): string; + daysAgo(days: number): string; + daysAgoEnd(days: number): string; + daysAgoStart(days: number): string; + debug(message: string, parm1?: any, parm2?: any, parm3?: any, parm4?: any, parm5?: any): void; + endOfLastMonth(): string; + endOfLastWeek(): string; + endOfLastYear(): string; + endOfNextMonth(): string; + endOfNextWeek(): string; + endOfNextYear(): string; + endOfThisMonth(): string; + endOfThisQuarter(): string; + endOfThisWeek(): string; + endOfThisYear(): string; + error(message: string, parm1?: any, parm2?: any, parm3?: any, parm4?: any, parm5?: any): void; + eventQueue( + eventName: string, + gr: ScopedGlideRecord, + optionalParam1: string, + optionalParam2: string, + eventQueue?: string + ): void; + eventQueueScheduled( + name: string, + instance: ScopedGlideRecord, + parm1: string, + parm2: string, + expiration: object + ): void; + executeNow(job: ScopedGlideRecord): string; + generateGUID(): string; + getCallerScopeName(): string; + getCssCacheVersionString(): string; + getCurrentApplicationId(): string; + getCurrentScopeName(): string; + getErrorMessages(id: string, args?: string[]): string; + getEscapedMessage(id: string, object?: any): string; + getMessage(id: string, object?: any): string; + getProperty(key: string, altobject?: {}): {}; + getSession(): GlideSession; + getSessionID(): string; + getSessionToken(): string; + getTimeZoneName(): string; + getUrlOnStack(): string; + getUser(): GlideUser; + getUserDisplayName(): string; + getUserID(): string; + getUserName(): string; + getUserNameByUserID(id: string): string; + hasRole(roleName: string): boolean; + hoursAgo(hours: number): string; + hoursAgoEnd(hours: number): string; + hoursAgoStart(hours: number): string; + include(include: string): void; + info(message: any, parm1?: any, parm2?: any, parm3?: any, parm4?: any, parm5?: any): void; + isDebugging(): boolean; + isInteractive(): boolean; + isLoggedIn(): boolean; + isMobile(): boolean; + minutesAgoEnd(num: number): string; + minutesAgoStart(num: number): string; + monthsAgo(num: number): string; + monthsAgoEnd(num: number): string; + monthsAgoStart(num: number): string; + nil(object: any): boolean; + quartersAgoEnd(num: number): string; + quartersAgoStart(num: number): string; + setProperty(key: string, value: string, description: string): void; + setRedirect(uri: string): void; + tableExists(table: string): boolean; + warn(message: string, parm1?: any, parm2?: any, parm3?: any, parm4?: any, parm5?: any): void; + xmlToJSON(xml: string): any; + yearsAgo(years: number): string; + yesterday(): string; +} diff --git a/types/servicenow-london/GlideTime.d.ts b/types/servicenow-london/GlideTime.d.ts new file mode 100644 index 0000000000..d51854e7a6 --- /dev/null +++ b/types/servicenow-london/GlideTime.d.ts @@ -0,0 +1,171 @@ +/** + * The scoped GlideTime class provides methods for performing operations on GlideTime + * objects, such as instantiating GlideTime objects or working with GlideTime fields. + */ +declare class GlideTime { + /** + * Instantiates a GlideTime object with the current time. + * + * @example + * + * var gt = new GlideTime(); + * gs.info(gt.getDisplayValue()); + */ + constructor(); + + /** + * Instantiates a GlideTime object with the specified time. + * + * @example + * + * var gt = new GlideTime(10000); + * gs.info(gt.getDisplayValue()); + */ + constructor(milliseconds: number); + + /** + * Gets the time in the specified format. + * + * @param format The time format. + * @returns The time in the specified format. + * @example + * + * var gt = new GlideTime(); + * gt.setValue('12:00:00'); + * gs.info(gt.getByFormat("HH:mm")); + */ + getByFormat(format: string): string; + + /** + * Gets the time in the current user's display format and time zone. + * + * @returns The time in the user's format and time zone. + * @example + * + * var gt = new GlideTime(); + * gt.setDisplayValue("12:00:00"); // User Time Zone + * gs.info(gt.getDisplayValue()); // User Time Zone + */ + getDisplayValue(): string; + + /** + * Gets the display value in the current user's time zone and the internal format + * (HH:mm:ss). + * + * @returns The time value for the GlideTime object in the current user's time zone and the + * internal time format of HH:mm:ss. + * @example + * + * var gt = new GlideTime(); + * gt.setValue("01:00:00"); //Internal Time Zone , UTC + * gs.info(gt.getDisplayValueInternal()); //User Time Zone + */ + getDisplayValueInternal(): string; + + /** + * Returns the hours part of the time using the local time zone. + * + * @returns The hours using the local time zone. + */ + + getHourLocalTime(): number; + + /** + * Returns the hours part of the time using the local time zone. The number of hours is + * based on a 24 hour clock. + * + * @returns The hours using the local time zone. The number of hours is based on a 24 hour + * clock. + */ + getHourOfDayLocalTime(): number; + + /** + * Returns the hours part of the time using the UTC time zone. The number of hours is + * based on a 24 hour clock. + * + * @returns The hours using the UTC time zone. The number of hours is based on a 24 hour + * clock. + */ + getHourOfDayUTC(): number; + /** + * Returns the hours part of the time using the UTC time zone. The number of hours is + * based on a 12 hour clock. Noon and midnight are represented by 0, not 12. + * + * @returns The hours using the UTC time zone. The number of hours is based on a 12 hour + * clock. Noon and midnight are represented by 0, not 12. + */ + getHourUTC(): number; + /** + * Returns the number of minutes using the local time zone. + * + * @returns The number of minutes using the local time zone. + */ + getMinutesLocalTime(): number; + /** + * Returns the number of minutes in the hour based on the UTC time zone. + * + * @returns The number of minutes in the hour using the UTC time zone. + */ + getMinutesUTC(): number; + /** + * Returns the number of seconds in the current minute. + * + * @returns The number of seconds in the minute. + */ + getSeconds(): number; + /** + * Gets the time value stored in the database by the GlideTime object in the internal + * format, HH:mm:ss, and the system time zone. + * + * @returns The time value in the internal fomat and system time zone. + * @example + * + * var gt = new GlideTime(); + * gs.info(gt.getValue()); // Internal Time Zone, UTC + */ + getValue(): string; + + /** + * Sets a time value using the current user's display format and time zone. + * + * @param asDisplayed The time in the current user's display format and time zone. The parameter + * must be formatted using the current user's preferred display format, such as HH:mm:ss. + * @returns Method does not return a value + * @example + * + * var gt = new GlideTime(); + * gt.setDisplayValue('01:00:00'); // User Time Zone + * gs.info(gt.getDisplayValueInternal()); // User Time Zone + */ + setDisplayValue(asDisplayed: string): void; + + /** + * Sets the time of the GlideTime object in the internal time zone. + * + * @param o The time in hh:mm:ss format. + * @returns Method does not return a value + * @example + * + * var gt = new GlideTime(); + * gt.setValue('01:00:00'); //Internal Time Zone, UTC + * gs.info("time is "+ gt.getByFormat('hh:mm:ss')); + */ + setValue(o: string): void; + + /** + * Gets the duration difference between two GlideTime object values. + * + * @param startTime The start value. + * @param endTime The end value. + * @returns The duration between the two values. + * @example + * + * var gd1 = new GlideTime(); + * gd1.setDisplayValue("09:00:00"); + * var gd2 = new GlideTime(); + * gd2.setDisplayValue("09:10:00"); + * var dur = GlideDate.subtract(gd1, gd2); //the difference between gdt1 and gdt2 + * gs.info(dur.getDisplayValue()); + */ + subtract(start: GlideTime, end: GlideTime): GlideDuration; +} diff --git a/types/servicenow-london/GlideUser.d.ts b/types/servicenow-london/GlideUser.d.ts new file mode 100644 index 0000000000..f3aeddc83d --- /dev/null +++ b/types/servicenow-london/GlideUser.d.ts @@ -0,0 +1,16 @@ +interface GlideUser { + getCompanyID(): string; + getDisplayName(): string; + getDomainID(): string; + getEmail(): string; + getFirstName(): string; + getID(): string; + getLastName(): string; + getName(): string; + getPreference(name: string): string; + getRoles(): string[]; + getUserRoles(): string[]; + hasRole(role: string): boolean; + isMemberOf(group: string): boolean; + savePreference(name: string, value: string): void; +} diff --git a/types/servicenow-london/QueryOperator.d.ts b/types/servicenow-london/QueryOperator.d.ts new file mode 100644 index 0000000000..a378e98f18 --- /dev/null +++ b/types/servicenow-london/QueryOperator.d.ts @@ -0,0 +1,15 @@ +type QueryOperator = + | '=' + | '!=' + | '>' + | '>=' + | '<' + | '<=' + | 'IN' + | 'NOT IN' + | 'STARTSWITH' + | 'ENDSWITH' + | 'CONTAINS' + | 'DOES NOT CONTAIN' + | 'INSTANCEOF' + | 'SAMEAS'; diff --git a/types/servicenow-london/RESTAPIRequest.d.ts b/types/servicenow-london/RESTAPIRequest.d.ts new file mode 100644 index 0000000000..536123baae --- /dev/null +++ b/types/servicenow-london/RESTAPIRequest.d.ts @@ -0,0 +1,13 @@ +declare namespace sn_ws { + interface RESTAPIRequest { + readonly body: RESTAPIRequestBody; + readonly pathParams: { [paramName: string]: string }; + readonly queryParams: { [paramName: string]: string[] }; + readonly queryString: string; + readonly uri: string; + readonly url: string; + readonly headers: { [paramName: string]: string }; + getHeader(header: string): string; + getSupportedResponseContentTypes(): string[]; + } +} diff --git a/types/servicenow-london/RESTAPIRequestBody.d.ts b/types/servicenow-london/RESTAPIRequestBody.d.ts new file mode 100644 index 0000000000..76e24c38dc --- /dev/null +++ b/types/servicenow-london/RESTAPIRequestBody.d.ts @@ -0,0 +1,9 @@ +declare namespace sn_ws { + interface RESTAPIRequestBody { + readonly data: any; + readonly dataStream: object; + readonly dataString: string; + hasNext(): boolean; + nextEntry(): any; + } +} diff --git a/types/servicenow-london/RESTAPIResponse.d.ts b/types/servicenow-london/RESTAPIResponse.d.ts new file mode 100644 index 0000000000..430d56048a --- /dev/null +++ b/types/servicenow-london/RESTAPIResponse.d.ts @@ -0,0 +1,12 @@ +declare namespace sn_ws { + interface RESTAPIResponse { + getStreamWriter(): RESTAPIResponseStream; + setBody(body: any): void; + setHeaders(headers: any): void; + setLocation(location: string): void; + setStatus(status: number): void; + setHeader(header: string, value: string): void; + setContentType(contentType: string): void; + setError(error: any): void; + } +} diff --git a/types/servicenow-london/RESTAPIResponseStream.d.ts b/types/servicenow-london/RESTAPIResponseStream.d.ts new file mode 100644 index 0000000000..c98d0eecfd --- /dev/null +++ b/types/servicenow-london/RESTAPIResponseStream.d.ts @@ -0,0 +1,6 @@ +declare namespace sn_ws { + interface RESTAPIResponseStream { + writeStream(stream: object): void; + writeString(data: string): void; + } +} diff --git a/types/servicenow-london/RESTMessageV2.d.ts b/types/servicenow-london/RESTMessageV2.d.ts new file mode 100644 index 0000000000..fadac635aa --- /dev/null +++ b/types/servicenow-london/RESTMessageV2.d.ts @@ -0,0 +1,581 @@ +declare namespace sn_ws { + /** + * The RESTMessageV2 API allows you to send outbound REST messages using JavaScript. + * Use the RESTResponseV2 API to manage the response returned by the REST provider. + * + * You can use this API in scoped applications, or within the global scope. + */ + class RESTMessageV2 { + /** + * Instantiates an empty RESTMessageV2 object. + * + * When using an object instantiated this way, you must manually specify an HTTP method an + * endpoint. + * @example + * + * var sm = new sn_ws.RESTMessageV2(); + */ + constructor(); + + /** + * Instantiates a RESTMessageV2 object using information from a REST message record. + * + * You must have a REST message record defined before you can use this constructor. + * + * In the following example, replace `REST_message_record` with the name of the REST message + * record from your instance. + * + * @param name The name of the REST message record. + * @param methodName The name of the HTTP method to use, such as GET or PUT. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2("","get"); + */ + constructor(name: string, methodName: RestHTTPMethods); + + /** + * Send the REST message to the endpoint. + * + * In the following example, replace REST_message_record with the name of the REST message + * record from your instance. + * + * @returns The response returned by the REST provider. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2("","get"); + * // Might throw exception if http connection timed out or some issue with sending request + * // itself because of encryption/decryption of password. + * var response = sm.execute(); + */ + execute(): RESTResponseV2; + + /** + * Send the REST message to the endpoint asynchronously. The instance does not wait for a + * response from the web service provider when making asynchronous calls. + * + * In the following example, replace REST_message_record with the name of the REST message + * record from your instance. + * + * @returns The response returned by the REST provider. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2("","get"); + * // Might throw exception if http connection timed out or some issue with sending request + * // itself because of encryption/decryption of password. + * var response = sm.executeAsync(); + * // In seconds. Wait at most 60 seconds to get response from ECC Queue/Mid Server + * // Might throw exception timing out waiting for response in ECC queue. + * response.waitForResponse(60); + */ + executeAsync(): RESTResponseV2; + + /** + * Get the URL of the endpoint for the REST message. + * + * In the following example, replace REST_message_record with the name of the REST message + * record from your instance. + * + * @returns The URL of the REST web service provider. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2("","get"); + * var endpoint = sm.getEndpoint(); + */ + getEndpoint(): string; + + /** + * Get the content of the REST message body. + * + * In the following example, replace REST_message_record with the name of the REST message + * record from your instance. + * + * @returns The REST message body. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2("","get"); + * var body = sm.getRequestBody(); + */ + getRequestBody(): string; + + /** + * Get the value for an HTTP header specified in the REST message. + * + * By default, this method cannot return the value for a header set automatically by the system. + * To grant this method access to all headers, set the property glide.http.log_debug to true. + * + * In the following example, replace REST_message_record with the name of the REST message + * record from your instance. + * + * @param headerName The request header you want to get the value for. + * @returns The value of the specified header. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2("","get"); + * var header = sm.getRequestHeader("Accept"); + */ + getRequestHeader(headerName: string): string; + + /** + * Get HTTP headers that were set by the REST client and the associated values. + * + * This method does not return headers set automatically by the system. To configure this + * method to return all headers, set the property glide.http.log_debug to true. + * + * In the following example, replace REST_message_record with the name of the REST message + * record from your instance. + * + * @returns An Object that maps the name of each header to the associated value. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2("","get"); + * var headers = sm.getRequestHeaders(); + */ + getRequestHeaders(): object; + + /** + * Configures the REST message to save the returned response body as an attachment record. + * + * When you use this function with a REST message that is sent through a MID server, the MID + * server user must have any roles required to read and write attachment records, as well as + * any roles required to read and write records on the table specified in the tableName + * parameter. + * + * The response body does not need to be a binary file to be saved as an attachment. Response + * bodies using text formats, such as JSON or XML can also be saved. If the instance fails + * to save the attachment, call getErrorMessage() on the related RESTResponseV2 object + * for error details. + * + * @param tableName Specify the table that contains the record you want to attach the saved file + * to. + * @param recordSysId Specify the sys_id of the record you want to attach the saved file to. + * @param fileName Specify the file name to give to the saved file. + * @example + * + * (function sampleRESTMessageV2() { + * try { + * var request = new sn_ws.RESTMessageV2(); + * request.setHttpMethod('get'); + * + * var attachment_sys_id = '', + * tablename = 'incident', + * recordSysId = '', + * response, + * httpResponseStatus, + * filename = ''; + * + * // endpoint - ServiceNow REST Attachment API + * request.setEndpoint('https://.service-now.com/api/now/attachment/' + + * attachment_sys_id + '/file'); + * request.setBasicAuth('', ''); + * + * // RESTMessageV2 - saveResponseBodyAsAttachment(String tableName, String recordSysId, + * // String fileName) + * request.saveResponseBodyAsAttachment(tablename, recordSysId, filename); + * + * response = request.execute(); + * httpResponseStatus = response.getStatusCode(); + * + * gs.print(" http response status_code: " + httpResponseStatus); + * } + * catch (ex) { + * var message = ex.getMessage(); + * gs.print(message); + * } + * })(); + */ + saveResponseBodyAsAttachment( + tableName: string, + recordSysId: string, + fileName: string + ): void; + + /** + * Configure the REST message to save the returned response body as an encrypted + * attachment record. + * + * When you use this function with a REST message that is sent through a MID server, the MID + * server user must have any roles required to read and write attachment records, as well as any + * roles required to read and write records on the table specified in the `tableName` parameter. + * + * The response body does not need to be a binary file to be saved as an attachment. Response + * bodies using text formats, such as JSON or XML can also be saved. If the instance fails to + * save the attachment, call `getErrorMessage()` on the related RESTResponseV2 object for error + * details. + * + * @param tableName Specify the table that contains the record you want to attach the saved file + * to. + * @param recordSysId Specify the sys_id of the record you want to attach the saved file to. + * @param fileName Specify the file name to give to the saved file. + * @param encryptContext Specify the sys_id of an encryption context. The saved file is + * encrypted using this context. + */ + + saveResponseBodyAsAttachment( + tableName: string, + recordSysId: string, + fileName: string, + encryptContext: string + ): void; + + /** + * Set the credentials for the REST message using an existing basic auth or OAuth 2.0 profile. + * + * In the following example, replace REST_message_record with the name of the REST message + * record from your instance. + * + * @param type The type of authentication profile to use. Valid values are 'basic' to use basic + * authentication, or 'oauth2' to use OAuth 2.0. + * @param profileId The sys_id of an authentication profile record. When using basic auth, + * specify the sys_id of a Basic Auth Configuration [sys_auth_profile_basic] record. When using + * OAuth 2.0, specify the sys_id of a OAuth Entity Profile [oauth_entity_profile] record. + * @example + * + * var requestBody; + * var responseBody; + * var status; + * var sm; + * try { + * // Might throw exception if message doesn't exist or not visible due to scope. + * sm = new sn_ws.RESTMessageV2("", "get"); + * + * // set auth profile to an OAuth 2.0 profile record. + * sm.setAuthenticationProfile('oauth2', '1234adsf123212131123qasdsf'); + * + * sm.setStringParameter("symbol", "NOW"); + * sm.setStringParameterNoEscape("xml_data", "test"); + * + * // In milliseconds. Wait at most 10 seconds for response from http request. + * sm.setHttpTimeout(10000); + * // Might throw exception if http connection timed out or some issue + * // with sending request itself because of encryption/decryption of password. + * response = sm.execute(); + * responseBody = response.haveError() ? response.getErrorMessage() : response.getBody(); + * status = response.getStatusCode(); + * } catch (ex) { + * responseBody = ex.getMessage(); + * status = '500'; + * } finally { + * requestBody = sm ? sm.getRequestBody() : null; + * } + */ + setAuthenticationProfile(type: string, profileId: string): void; + + /** + * Sets basic authentication headers for the REST message. + * + * Setting security values using this method overrides basic authentication values defined for + * the REST message record. + * + * In the following example, replace REST_message_record with the name of the REST message + * record from your instance. + * + * @param userName The username you want to use to authenticate the REST message. + * @param userPass The password for the specified user. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2("","get"); + * sm.setBasicAuth("username","password"); + */ + setBasicAuth(userName: string, userPass: string): void; + + /** + * Associate outbound requests and the resulting response record in the ECC queue. This method + * only applies to REST messages sent through a MID Server. + * + * The correlator provided populates the Agent correlator field on the ECC queue record for the + * response. Provide a unique correlator for each outbound request to associate the correct + * results in the ECC queue with the request when designing asynchronous automation through a + * MID Server. + * + * In the following example, replace REST_message_record with the name of the REST message record + * from your instance. + * + * @param correlator A unique identifier + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2("","get"); + * sm.setEccCorrelator("unique_identifier"); + */ + setEccCorrelator(correlator: string): void; + + /** + * Override a value from the database by writing to the REST message payload. This method only + * applies to REST messages sent through a MID Server. + * + * Use this method when a value from the REST message in the database is invalid, such as when + * the endpoint URL is longer than the maximum REST endpoint field length. You can set only the + * endpoint URL using this method by passing source as the name parameter. + * + * In the following example, replace REST_message_record with the name of the REST message + * record from your instance. + * + * @param name The name of the parameter, such as source. + * @param value The value to assign to the specified parameter. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2("","get"); + * sm.setEccParameter("source","http://very.long.endpoint.url"); + */ + setEccParameter(name: string, value: string): void; + + /** + * Set the endpoint for the REST message. + * + * By default, the REST message uses the endpoint specified in the REST message record. Use this + * method to override this default. You must call this method when using the RESTMessageV2 - + * + * RESTMessageV2() constructor with no parameters. + * + * @param endpoint The URL of the REST provider you want to interface with. + * @example + * + * var sm = new sn_ws.RESTMessageV2(); + * sm.setEndpoint("http://web.service.endpoint"); + */ + setEndpoint(endpoint: string): void; + + /** + * The HTTP method this REST message performs, such as GET or PUT. + * + * You must set an HTTP method when using the RESTMessageV2 - RESTMessageV2() constructor with + * no parameters. + * @param method The HTTP method to perform. + * @example + * + * var sm = new sn_ws.RESTMessageV2(); + * sm.setHttpMethod("post"); + */ + setHttpMethod(method: RestHTTPMethods): void; + + /** + * Set the amount of time the REST message waits for a response from the web service provider + * before the request times out. + * + * In the following example, replace REST_message_record with the name of the REST message + * record from your instance. + * + * @param timeoutMs The amount of time, in milliseconds, before the call to the REST provider + * times out. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2("","get"); + * sm.setHttpTimeout(6000); + */ + setHttpTimeout(timeoutMs: number): void; + + /** + * Set the log level for this message and the corresponding response. + * + * Setting a log level using the RESTMessageV2 API overrides the log level configured on the + * REST message record. This log level may not apply if the endpoint domain is blacklisted, or + * if the property glide.outbound_http_log.override is true. To view outbound web service logs, + * navigate to System Logs > Outbound HTTP Requests. + * + * @param level The log level. Valid values are basic, elevated, and all. + * @example + * + * var rm = new sn_ws.RESTMessageV2(); + * rm.setLogLevel('all'); + */ + setLogLevel(level: 'basic' | 'elevated' | 'all'): void; + + /** + * Configure the REST message to communicate through a MID Server. + * + * In the following example, replace REST_message_record with the name of the REST message + * record from your instance. + * + * @param midServer The name of the MID Server to use. Your instance must have an active MID + * Server with the specified name. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2("","get"); + * sm.setMIDServer("mid_server_name"); + */ + setMIDServer(midServer: string): void; + + /** + * Set the mutual authentication protocol profile for the REST message. + * + * Setting a protocol profile using this method overrides the protocol profile selected for the + * REST message record. + * + * In the following example, replace REST_message_record with the name of the REST message + * record from your instance. + * + * @param profileName The Name of the protocol profile to use for mutual authentication. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2("","get"); + * sm.setMutualAuth("mutual_auth_profile_name"); + */ + setMutualAuth(profileName: string): void; + + /** + * Append a parameter to the end of the request URL with the form name=value. + * + * For example, the code setQueryParameter("sysparm_query", + * "active=true^ORDERBYnumber^ORDERBYDESCcategory"); appends the text + * + * sysparm_query=active=true^ORDERBYnumber^ORDERBYDESCcategory to the request URL. + * + * @param name The name of the URL parameter to pass. + * @param value The value to assign the URL parameter. + * @example + * + * var sm = new sn_ws.RESTMessageV2(); + * // Set up message, including endpoint and authentication + * sm.setQueryParameter("sysparm_query","active=true^ORDERBYnumber^ORDERBYDESCcategory"); + */ + setQueryParameter(name: string, value: string): void; + + /** + * Set the body content to send to the web service provider when using PUT or POST HTTP methods. + * + * When you set the body content using this method, variables in the body are not substituted + * for parameters from the REST message function record. You must explicitly define all values + * within the REST message body. + * + * @param body The request body to send. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2("Update user","post"); + * var body = ""; + * sm.setRequestBody(body); + */ + setRequestBody(body: string): void; + + /** + * Sets the request body using an existing attachment record. + * + * When you use this function with a REST message that is sent through a MID server, the MID + * server user must have any roles required to read attachment records. + * + * @param attachmentSysId The sys_id of the Attachment [sys_attachment] record you want to send + * in this REST message. + * @example + * + * (function sampleRESTMessageV2() { + * try { + * var request = new sn_ws.RESTMessageV2(); + * request.setHttpMethod('post'); + * request.setEndpoint(''); + * request.setRequestBodyFromAttachment(''); + * + * var response = request.execute(); + * var httpResponseStatus = response.getStatusCode(); + * + * gs.print("http response status_code: " + httpResponseStatus); + * } + * catch (ex) { + * var message = ex.getMessage(); + * gs.print(message); + * } + * })(); + */ + setRequestBodyFromAttachment(attachmentSysId: string): void; + + /** + * Set the body content of a PUT or POST message using a binary stream. + * + * You can use this method to send binary files such as images or archives using REST messages. + * If the request is not a PUT or POST request, the request body is ignored. + * + * @param stream The binary data to send, such as an attachment or a stream from a 3rd-party + * service. + */ + setRequestBodyFromStream(stream: object): void; + + /** + * Set an HTTP header in the REST message to the specified value. + * + * In the following example, replace REST_message_record with the name of the REST message + * record from your instance. + * + * @param name The name of the header. + * @param value The value to assign to the specified header. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2("","get"); + * sm.setRequestHeader("Accept","Application/json"); + */ + setRequestHeader(name: string, value: string): void; + + /** + * Override the default requestor profile for the REST message in order to retrieve an OAuth + * access token associated with a different requestor. + * + * This method applies only to REST messages configured to use OAuth 2.0 authentication. This + * method is optional and is unnecessary in most configurations. + * + * @param requestorContext + * @param requestorId + */ + setRequestorProfile(requestorContext: string, requestorId: string): void; + + /** + * Set a REST message function variable with the specified name from the REST message record + * to the specified value. + * + * XML reserved characters in the value are converted to the equivalent escaped characters. Use + * setStringParameterNoEscape to set a variable without escaping XML reserved characters. + * + * In the following example, replace REST_message_record with the name of the REST message + * record from your instance. + * + * @param name The name of the REST message variable. This parameter must be defined in the + * REST message record before you can assign a value to it. + * @param value The value to assign the variable. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2("","get"); + * sm.setStringParameter("s","NOW"); + */ + setStringParameter(name: string, value: string): void; + + /** + * Set a REST message function variable with the specified name from the REST message record to + * the specified value. + * + * This method is equivalent to setStringParameter but does not escape XML reserved characters. + * In the following example, replace REST_message_record with the name of the REST message + * record from your instance. + * + * @param name The name of the REST message variable. This parameter must be defined in the + * REST message record before you can assign a value to it. + * @param value The value to assign the variable. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2("","get"); + * sm.setStringParameterNoEscape("s","NOW"); + */ + setStringParameterNoEscape(name: string, value: string): void; + } + + type RestHTTPMethods = + | 'get' + | 'post' + | 'delete' + | 'patch' + | 'put' + | 'head' + | 'delete' + | 'options'; +} diff --git a/types/servicenow-london/RESTResponseV2.d.ts b/types/servicenow-london/RESTResponseV2.d.ts new file mode 100644 index 0000000000..76f42acf71 --- /dev/null +++ b/types/servicenow-london/RESTResponseV2.d.ts @@ -0,0 +1,188 @@ +declare namespace sn_ws { + /** + * The RESTResponseV2 API allows you to use the data returned by an outbound REST message + * in JavaScript code. + */ + class RESTResponseV2 { + /** + * Returns all headers contained in the response, including any duplicate headers. + * + * @returns The list of headers contained in the response. Each header is represented as a + * GlideHTTPHeader object which contains the header `name` and `value`. + * @example + * + * var r = new sn_ws.RESTMessageV2('', 'get'); + * var response = r.execute(); + * var headers = response.getAllHeaders(); + * for(var i in headers){ + * gs.info(headers[i].name + ': ' + headers[i].value); + * } + */ + getAllHeaders(): [{ name: string; value: string }]; + + /** + * Get the content of the REST response body. + * + * Use this function when you want to get the request body as text content. Do not use this + * method when saving the response as a binary attachment. If a RESTMessageV2 object called + * the `saveResponseBodyAsAttachment(...)` function, using `getBody()` on the associated + * RESTResponseV2 object will cause an error. When saving the response as an attachment, + * if the outbound REST message fails, call `getErrorMessage()` on the response to retrieve + * the body content. + * + * @returns The REST response body. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2('Yahoo Finance', 'get'); + * var response = sm.execute(); + * var responseBody = response.getBody(); + */ + getBody(): string; + + /** + * Returns all cookies included in the response. + * + * @returns The list of cookies. Iterate through the list to perform operations on each cookie. + * @example + * + * var cookies = response.getCookies(); + * var i; + * for (var i = 0; i < cookies.size(); i++) { + * gs.info('cookie: ' + cookies.get(i)); + * } + */ + getCookies(): { size: () => number; get: (index: number) => string }; + + /** + * Get the numeric error code if there was an error during the REST transaction. + * + * This error code is specific to the Now Platform, it is not an HTTP error code. Provide this + * error code if you require assistance from ServiceNow Customer Support. + * + * @returns The numeric error code, such as 1 for socket timeout. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2('Yahoo Finance', 'get'); + * var response = sm.execute(); + * var errorCode = response.getErrorCode(); + */ + getErrorCode(): number; + + /** + * Get the error message if there was an error during the REST transaction. + * + * @returns The error message. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2('Yahoo Finance', 'get'); + * var response = sm.execute(); + * var errorMsg = response.getErrorMessage(); + */ + getErrorMessage(): string; + + /** + * Get the value for a specified header. + * + * @param name The name of the header that you want the value for, such as Set-Cookie. + * @returns The value of the specified header. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2('Yahoo Finance', 'get'); + * var response = sm.execute(); + * var headerVal = response.getHeader('Content-Type'); + */ + getHeader(name: string): string; + + /** + * Get all headers returned in the REST response and the associated values. + * + * **Note:** If a header is present more than once in the response, such as a Set-Cookie header, + * this function returns only the last of the duplicate headers. To return all headers + * including duplicates, use the `getAllHeaders()` function. + * + * @returns An Object that maps the name of each header to the associated value. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2('Yahoo Finance', 'get'); + * var response = sm.execute(); + * var headers = response.getHeaders(); + */ + getHeaders(): object; + + /** + * Get the fully-resolved query sent to the REST endpoint. + * + * This query contains the endpoint URL as well as any values assigned to variables in the + * REST message. Use this method only with responses to direct requests. This method is not + * supported for requests sent asynchronously, or requests sent using a MID server. + * + * @returns The fully-resolved query. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2('Yahoo Finance', 'get'); + * var response = sm.execute(); + * var queryString = response.getQueryString(); + */ + getQueryString(): string; + + /** + * Get the sys_id value of the attachment created from the response body content. + * + * If the RESTMessageV2 object associated with this response called the + * `saveResponseBodyAsAttachment(...)` function, use `getResponseAttachmentSysid()` to get the + * sys_id of the created attachment record. Use this function when you want to perform + * additional operations with the new attachment record. + * + * @returns The sys_id of the new attachment record. + */ + getResponseAttachmentSysid(): string; + + /** + * Get the numeric HTTP status code returned by the REST provider. + * + * @returns The numeric status code returned by the REST provider, such as 200 for a + * successful response. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2('Yahoo Finance', 'get'); + * var response = sm.execute(); + * var statusCode = response.getStatusCode(); + */ + getStatusCode(): number; + + /** + * Indicate if there was an error during the REST transaction. + * + * @returns Returns true if there was an error, false if there was no error. + * @example + * + * // Might throw exception if message doesn't exist or not visible due to scope. + * var sm = new sn_ws.RESTMessageV2('Yahoo Finance', 'get'); + * var response = sm.execute(); + * var error = response.haveError(); + */ + haveError(): boolean; + + /** + * Set the amount of time the instance waits for a response from the web service provider. + * + * This method overrides the property glide.rest.outbound.ecc_response.timeout for this REST + * response. + * + * @param timeoutSecs The amount of time, in seconds, to wait for this response. + * @example + * + * var sm = new sn_ws.RESTMessageV2("Yahoo Finance","get"); //Might throw exception if message doesn't exist or not visible due to scope. + * var response = sm.executeAsync(); + * response.waitForResponse(60); + */ + waitForResponse(timeoutSecs: number): void; + } +} diff --git a/types/servicenow-london/RenderProperties.d.ts b/types/servicenow-london/RenderProperties.d.ts new file mode 100644 index 0000000000..ade2ebe4a5 --- /dev/null +++ b/types/servicenow-london/RenderProperties.d.ts @@ -0,0 +1,13 @@ +interface RenderProperties { + getEncodedQuery(): string; + getListControl(): any; + getParameters(): string[]; + getParameterValue(value: string): string; + getReferringURL(): string; + getViewName(): string; + getWindowProperties(): any; + isInDevStudio(): boolean; + isInteractive(): boolean; + isManyToMany(): boolean; + isRelatedList(): boolean; +} diff --git a/types/servicenow-london/SOAPMessageV2.d.ts b/types/servicenow-london/SOAPMessageV2.d.ts new file mode 100644 index 0000000000..0b935f5406 --- /dev/null +++ b/types/servicenow-london/SOAPMessageV2.d.ts @@ -0,0 +1,31 @@ +declare namespace sn_ws { + class SOAPMessageV2 { + constructor(); + constructor(soapMessage: string, soapFunction: string); + execute(): SOAPResponseV2; + executeAsync(): SOAPResponseV2; + setHttpMethod(method: string): void; + setHttpTimeout(timeoutMs: number): void; + setBasicAuth(userName: string, userPass: string): void; + setMutualAuth(profileName: string): void; + setEccCorrelator(correlator: string): void; + setEccParameter(name: string, value: string): void; + setEndpoint(endpoint: string): void; + setMIDServer(midServer: string): void; + setRequestBody(body: string): void; + setRequestHeader(name: string, value: string): void; + setSOAPAction(soapAction: string): void; + setStringParameter(name: string, value: string): void; + setStringParameterNoEscape(name: string, value: string): void; + setWSSecurity( + keystoreId: string, + keystoreAlias: string, + keystorePassword: string, + certificateId: string + ): void; + getRequestBody(): string; + getEndpoint(): string; + getRequestHeader(headerName: string): string; + getRequestHeaders(): object; + } +} diff --git a/types/servicenow-london/SOAPResponseV2.d.ts b/types/servicenow-london/SOAPResponseV2.d.ts new file mode 100644 index 0000000000..4d8020c918 --- /dev/null +++ b/types/servicenow-london/SOAPResponseV2.d.ts @@ -0,0 +1,14 @@ +declare namespace sn_ws { + interface SOAPResponseV2 { + getAllHeaders(): [{ name: string; value: string }]; + getBody(): string; + getCookies(): { size: () => number; get: (index: number) => string }; + getErrorCode(): number; + getErrorMessage(): string; + getHeader(name: string): string; + getHeaders(): object; + getStatusCode(): number; + haveError(): boolean; + waitForResponse(timeoutSecs: number): void; + } +} diff --git a/types/servicenow-london/ScopedElementDescriptor.d.ts b/types/servicenow-london/ScopedElementDescriptor.d.ts new file mode 100644 index 0000000000..da5de57c32 --- /dev/null +++ b/types/servicenow-london/ScopedElementDescriptor.d.ts @@ -0,0 +1,227 @@ +/** + * The scoped GlideElementDescriptor API provides information about individual fields. + * + * There is no constructor for this class. Use the GlideElement `getED()` method to obtain a + * GlideElementDescriptor object. + * + * Actual type com.glide.db.ElementDescriptor (JavaObject). + */ +interface ScopedElementDescriptor { + /** + * Returns the encryption type used for attachments on the element's table. + * + * @returns The encryption type used on attachments. Returns null if attachments on the element's + * table are not being encrypted. + * @example + * + * var grInc = new GlideRecord('incident'); + * grInc.query('priority', '1'); + * + * var field = grInc.getElement('priority'); + * var ed = field.getED(); + * + * var isEdge = ed.getAttachmentEncryptionType(); + * gs.info(isEdge); + * // null + */ + getAttachmentEncryptionType(): string; + + /** + * Returns the element's encryption type. + * + * @returns The element's encryption type. Returns null if the element is not + * encrypted. + * @example + * + * var grInc = new GlideRecord('incident'); + * grInc.query('priority', '1'); + * + * var field = grInc.getElement('priority'); + * var ed = field.getED(); + * + * sEdge = ed.getEncryptionType(); + * gs.info(isEdge); + * // null + */ + getEncryptionType(): string; + + /** + * Returns the element's internal data type. + * + * @returns The element's internal data type. + * @example + * + * var grInc = new GlideRecord('incident'); + * grInc.query('priority', '1'); + * + * var field = grInc.getElement('priority'); + * var ed = field.getED(); + * + * var isEdge = ed.getInternalType(); + * gs.info(isEdge); + */ + getInternalType(): string; + + /** + * Returns the element's label. + * + * @returns The element's label. + * @example + * + * var grInc = new GlideRecord('incident'); + * grInc.query('priority', '1'); + * + * var field = grInc.getElement('priority'); + * var ed = field.getED(); + * + * var isEdge = ed.getLabel(); + * gs.info(isEdge); + * // Priority + */ + getLabel(): string; + + /** + * Returns the element's length. + * + * @returns The element's size. + * @example + * + * var grInc = new GlideRecord('incident'); + * grInc.query('priority', '1'); + * + * var field = grInc.getElement('priority'); + * var ed = field.getED(); + * + * var isEdge = ed.getLength(); + * gs.info(isEdge); + * // 40 + */ + getLength(): number; + + /** + * Returns the element's name. + * + * @returns The element's name. + * @example + * + * var grInc = new GlideRecord('incident'); + * grInc.query('priority', '1'); + * + * var field = grInc.getElement('priority'); + * var ed = field.getED(); + * + * var isEdge = ed.getName(); + * gs.info(isEdge); + * // priority + */ + getName(): string; + + /** + * Returns the element's plural label. + * + * @returns The element's plural label. + * @example + * + * var gr = new GlideRecord('incident'); + * gr.query(); + * var ed = gr.getED(); + * gs.info(ed.getPlural()); + * // Incidents + */ + getPlural(): string; + + /** + * Returns true if an encrypted attachment has been added to the table. + * + * @returns Returns true if an encrypted attachment has been added to the table. + * @example + * + * var grInc = new GlideRecord('incident'); + * grInc.query('priority', '1'); + * + * var field = grInc.getElement('priority'); + * var ed = field.getED(); + * + * var isEdge = ed.hasAttachmentsEncrypted(); + * gs.info(isEdge); + * // false + */ + hasAttachmentsEncrypted(): boolean; + + /** + * Returns true if the element is an automatically generated or system field. + * + * @returns True if the element is automatically generated or a system field. + * @example + * + * var grInc = new GlideRecord('incident'); + * grInc.query('priority', '1'); + * var field = grInc.getElement('priority'); + * var ed = field.getED(); + * + * isEdge = ed.isAutoOrSysID(); + * gs.info(isEdge); + * // false + */ + isAutoOrSysID(): boolean; + + /** + * Returns true if the element is defined as a dropdown choice in its dictionary + * definition. + * + * @returns Returns true if the element is defined as a dropdown choice. Returns true even + * if there are no entries defined in the choice table. The last choice type, + * suggestion, does not return true. + * @example + * + * var grInc = new GlideRecord('incident'); + * grInc.query('priority', '1'); + * + * var field = grInc.getElement('priority'); + * var ed = field.getED(); + * + * var isChoiceTable = ed.isChoiceTable(); + * gs.info(isChoiceTable); + * // true + */ + isChoiceTable(): boolean; + + /** + * Returns true if an element is encrypted. + * + * @returns Returns true if the element is encrypted, false otherwise. + * @example + * + * var grInc = new GlideRecord('incident'); + * grInc.query('priority', '1'); + * + * var field = grInc.getElement('priority'); + * var ed = field.getED(); + * + * var isEdge = ed.isEdgeEncrypted(); + * gs.info(isEdge) + * // false + */ + isEdgeEncrypted(): boolean; + + /** + * Returns true if the element is a virtual element. + * + * A virtual element is a calculated field as set by the dictionary definition of the field. + * Virtual fields cannot be encrypted. + * + * @returns Returns true if the element is a virtual element. + * @example + * + * var grInc = new GlideRecord('incident'); + * grInc.query('priority', '1'); + * + * var field = grInc.getElement('priority'); + * var ed = field.getED(); + * + * var isVirtual = ed.isVirtual(); + * gs.info(isVirtual); + * // false + */ + isVirtual(): boolean; +} diff --git a/types/servicenow-london/ScopedGlideElement.d.ts b/types/servicenow-london/ScopedGlideElement.d.ts new file mode 100644 index 0000000000..729aa5748d --- /dev/null +++ b/types/servicenow-london/ScopedGlideElement.d.ts @@ -0,0 +1,447 @@ +/** + * The Scoped GlideElement API provides a number of convenient script methods for dealing + * with fields and their values. Scoped GlideElement methods are available for the fields of the + * current GlideRecord. + */ +interface ScopedGlideElement { + /** + * Determines if the user's role permits the creation of new records in this field. + * + * @returns True if the field can be created, false otherwise. + */ + canCreate(): boolean; + + /** + * Indicates whether the user's role permits them to read the associated GlideRecord. + * + * @returns True if the field can be read, false otherwise. + */ + canRead(): boolean; + + /** + * Determines whether the user's role permits them to write to the associated GlideRecord. + * + * @returns True if the user can write to the field, false otherwise. + */ + canWrite(): boolean; + + /** + * Determines if the current field has been modified. This functionality is available for all + * available data types, except Journal fields. + * + * **Note:** The `changes()` method is not supported within ACL scripts. + * + * @returns True if the fields have been changed, false if the field has not. + * @example + * + * // This method is often used in business rules. The following example shown is from a business + * // rule, if "assigned_to" field value is changed, create a event in the EventQueue. + * if (!current.assigned_to.nil() && current.assigned_to.changes()) { + * gs.eventQueue( + * 'incident.assigned', + * current, + * current.assigned_to.getDisplayValue(), + * previous.assigned_to.getDisplayValue() + * ); + * } + */ + changes(): boolean; + + /** + * Determines if the previous value of the current field matches the specified object. + * + * **Note:** If the GlideRecord on which you are performing this method has only been initialized + * and read, and has not been written, the underlying before-and-after values are the same. In + * this case, the method returns `false`, as there has been no change to the data store. + * + * @param o An object value to check against the previous value of the current field. + * @returns True if the previous value matches, false if it does not. + * @example + * + * // The following example shows that in a business rule, if "active" field is changed from true, + * // insert a event in the EventQueue. + * if (current.active.changesFrom(true)) { + * gs.eventQueue('incident.inactive', current, current.incident_state, previous.incident_state); + * } + */ + changesFrom(o: any): boolean; + + /** + * Determines if the new value of a field, after a change, matches the specified object. + * + * **Note:** The changesTo() method is not supported within ACL scripts. + * + * @param o An object value to check against the new value of the current field. + * @returns True if the previous value matches, false if it does not. + * @example + * + * // The following example shows that in a business rule, if "active" field is changed to false, + * // insert a event in the EventQueue. + * if (current.active.changesTo(false)) { + * gs.eventQueue('incident.inactive', current, current.incident_state, previous.incident_state); + * } + */ + changesTo(o: any): boolean; + + /** + * Returns the value of the specified attribute from the dictionary. + * + * If the attribute is a boolean attribute, use `getBooleanAttribute(String)` to get the value as + * a boolean rather than as a string. + * + * @param attributeName Attribute name + * @returns Attribute value + * @example + * + * doit(); + * function doit() { + * var gr = new GlideRecord('sys_user'); + * gr.query('user_name', 'admin'); + * if (gr.next()) { + * gs.print('we got one'); + * gs.print(gr.location.getAttribute('tree_picker')); + * } + * } + */ + getAttribute(attributeName: string): string; + + /** + * Returns the Boolean value of the specified attribute from the dictionary. + * + * To get the value as a string, use `getAttribute(string)`. + * + * @param attributeName Attribute name + * @returns Boolean value of the attribute. Returns false if the attribute does not exist. + */ + getBooleanAttribute(attributeName: string): boolean; + + /** + * Generates a choice list for a field. + * + * @param [dependent] Optional: a dependent value + * @returns An array list of choices. + * @example + * + * var glideRecord = new GlideRecord('incident'); + * glideRecord.query('priority', '1'); + * glideRecord.next(); + * + * // urgency has choice list: 1 - High, 2 - Medium, 3 - Low, with value: 1, 2, 3 + * var choices = glideRecord.urgency.getChoices(); + * gs.info(choices); + */ + getChoices(dependent?: string): any[]; + + /** + * Returns the choice label for the current choice. + * + * @returns The selected choice's label. + * @example + * + * var glideRecord = new GlideRecord('incident'); + * glideRecord.query('priority', '1'); + * glideRecord.next(); + * + * // urgency has choice list: 1 - High, 2 - Medium, 3 - Low, with value: 1, 2, 3 + * var choiceLabel = glideRecord.urgency.getChoiceValue(); + * gs.info(choiceLabel); + * // 1 - High + */ + getChoiceValue(): string; + + /** + * Returns the clear text value for Password (2 way encrypted) fields in scoped + * applications. + * + * @returns The clear text password. + * @example + * + * var tablename = 'x_scoped_app_table' + * var CI = new GlideRecord(tablename); + * CI.addQuery('number', '0001002'); + * CI.query(); + * CI.next(); + * + * var password = CI.password_field + * var decrypted = password.getDecryptedValue(); + * gs.info(decrypted); + */ + getDecryptedValue(): string; + + /** + * Gets the formatted display value of the field. + * + * @param [maxCharacters] Optional: Maximum characters desired + * @returns The display value of the field + * @example + * + * var glideRecord = new GlideRecord('incident'); + * glideRecord.query('priority', '1'); + * glideRecord.next(); + * gs.info(glideRecord.priority.getDisplayValue()); + */ + getDisplayValue(maxCharacters?: number): string; + + /** + * Returns the field's element descriptor. + * + * @returns The field's element descriptor. + * @example + * + * var grInc = new GlideRecord('incident'); + * grInc.query('priority', '1'); + * + * var field = grInc.getElement('priority'); + * var ed = field.getED(); + */ + getED(): ScopedElementDescriptor; + + /** + * Returns the phone number in international format. + * + * @returns The phone number in international format. + */ + getGlobalDisplayValue(): any; + + /** + * Returns the HTML value of a field. + * + * @param [maxChars] Optional. Maximum number of characters to return. + * @returns HTML value for the field. + * @example + * + * var inccause = new GlideRecord('incident'); + * inccause.short_description = current.short_description; + * inccause.comments = current.comments.getHTMLValue(); + * inccause.insert(); + */ + getHTMLValue(maxChars?: number): string; + + /** + * Returns either the most recent journal entry or all journal entries. + * + * @param mostRecent If 1, returns the most recent entry. If -1, returns all journal + * entries. + * @returns For the most recent entry, returns a string that contains the field label, + * timestamp, and user display name of the journal entry. + * + * For all journal entries, returns the same information for all journal entries + * ever entered as a single string with each entry delimited by "\n\n". + * @example + * + * //gets all journal entries as a string where each entry is delimited by '\n\n' + * var notes = current.work_notes.getJournalEntry(-1); + * //stores each entry into an array of strings + * var na = notes.split('\n\n'); + * + * for (var i = 0; i < na.length; i++) + * gs.print(na[i]); + */ + getJournalEntry(mostRecent: number): string; + + /** + * Returns the object label. + * + * @returns Object label + * @example + * + * var gr = new GlideRecord('sc_req_item'); + * gr.addQuery('request', current.sysapproval); + * gr.query(); + * while (gr.next()) { + * var nicePrice = gr.price.toString(); + * if (nicePrice != '') { + * nicePrice = parseFloat(nicePrice); + * nicePrice = nicePrice.toFixed(2); + * } + * template.print( + * gr.number + ': ' + gr.quantity + ' X ' + gr.cat_item.getDisplayValue() + + * ' at $' + nicePrice + ' each \n' + * ); + * template.print(' Options:\n'); + * for (var key in gr.variables) { + * var v = gr.variables[key]; + * if (v.getGlideObject().getQuestion().getLabel() != '' ) { + * template.space(4); + * template.print( + * ' ' + v.getGlideObject().getQuestion().getLabel() + ' = ' + + * v.getDisplayValue() + '\n' + * ); + * } + * } + * } + */ + getLabel(): string; + + /** + * Returns the name of the field. + * + * @returns Field name + */ + getName(): string; + + /** + * Gets the table name for a reference element. + * + * @returns The table name of the reference + * @example + * + * var grINC = new GlideRecord('incident'); + * grINC.query('number', 'INC0010041'); // record assignment group assigned to "CAB Approval" + * if (grINC.next()) { + * // Get the table name + * var tableName = grINC.assignment_group.getReferenceTable(); + * gs.info(tableName); + * } + */ + getReferenceTable(): string; + + /** + * Returns a GlideRecord object for a given reference element. + * + * @returns A GlideRecord object + * @example + * + * var grINC = new GlideRecord('incident'); + * grINC.notNullQuery('caller_id'); + * grINC.query(); + * if (grINC.next()) { + * + * // Get a GlideRecord object for the referenced sys_user record + * var grUSER = grINC.caller_id.getRefRecord(); + * if (grUSER.isValidRecord()) + * gs.print( grUSER.getValue('name') ); + * } + */ + getRefRecord(): ScopedGlideRecord; + + /** + * Returns the name of the table on which the field resides. + * + * @returns Name of the table. The returned value may be different from the table Class + * that the record is in. See Tables and Classes in the product documentation. + * @example + * + * if (current.approver.getTableName() == 'sysapproval_approver') { + * if (current.approver == email.from_sys_id) { + * current.comments = 'reply from: ' + email.from + '\n\n' + email.body_text; + * + * // if it's been cancelled, it's cancelled. + * var doit = true; + * if (current.state == 'cancelled') doit = false; + * + * if (email.body.state != undefined) current.state = email.body.state; + * + * if (doit) current.update(); + * } else { + * gs.log( + * 'Approval for task (' + + * current.sysapproval.getDisplayValue() + + * ') rejected because user sending email (' + + * email.from + + * ') does not match the approver (' + + * current.approver.getDisplayValue() + + * ')' + * ); + * } + * } + */ + getTableName(): string; + + /** + * Determines if a field is null. + * + * @returns True if the field is null or an empty string, false if not. + * @example + * + * var glideRecord = new GlideRecord('incident'); + * glideRecord.query('priority', '1'); + * glideRecord.next(); + * gs.info(glideRecord.state.nil()); + */ + nil(): boolean; + + /** + * Sets the value of a date/time element to the specified number of milliseconds since + * January 1, 1970 00:00:00 GMT. + * + * @param milliseconds Number of milliseconds since 1/1/1970 + * @example + * + * var gr = new GlideRecord('incident'); + * gr.initialize(); + * gr.opened_at.setDateNumericValue(10000); + */ + setDateNumericValue(milliseconds: number): void; + + /** + * Sets the display value of the field. + * + * @param value The value to set for the field. + * @example + * + * var glideRecord = new GlideRecord('incident'); + * glideRecord.query('priority', '1'); + * glideRecord.next(); + * + * //change the urgency to 3 + * glideRecord.urgency.setDisplayValue('3 - Low'); + * gs.info(glideRecord.urgency); + */ + setDisplayValue(value: object): void; + + /** + * Adds an error message. Available in Fuji patch 3. + * + * @param errorMessage The error message. + * @returns Method does not return a value + * @example + * + * var glideRecord = new GlideRecord('incident'); + * glideRecord.query('priority', '1'); + * glideRecord.next(); + * glideRecord.short_description.setError('Error text'); + */ + setError(errorMessage: string): void; + + /** + * Sets the field to the specified phone number. + * + * @param phoneNumber The phone number to set. This can be in either the international or local + * format. + * @param strict When true, specifies that the number specified must match the correct format. + * When false, the system attempts to correct an improperly formatted phone + * number. + * @returns True if the value was set. + */ + setPhoneNumber(phoneNumber: any, strict: boolean): boolean; + + /** + * Sets the value of a field. + * + * @param value Object value to set the field to. + * @returns Method does not return a value + * @example + * + * var glideRecord = new GlideRecord('incident'); + * glideRecord.query('priority', '1'); + * glideRecord.next(); + * glideRecord.short_description.setValue('Network failure'); + * gs.info(glideRecord.short_description); + */ + setValue(value: any): void; + + /** + * Converts the value to a string. + * + * @param value Object value to set the field to. + * @returns The value as a string + * @example + * + * var glideRecord = new GlideRecord('incident'); + * glideRecord.query('priority', '1'); + * glideRecord.next(); + * gs.info(glideRecord.opened_at.toString()); + */ + toString(): string; +} diff --git a/types/servicenow-london/ScopedGlideRecord.d.ts b/types/servicenow-london/ScopedGlideRecord.d.ts new file mode 100644 index 0000000000..3e3dfb7bc5 --- /dev/null +++ b/types/servicenow-london/ScopedGlideRecord.d.ts @@ -0,0 +1,898 @@ +/** + * Scoped GlideRecord is used for database operations. + */ +interface ScopedGlideRecord { + readonly sys_created_by: string & ScopedGlideElement; + readonly sys_created_on: GlideDateTime & ScopedGlideElement; + readonly sys_id: string & ScopedGlideElement; + readonly sys_mod_count: number & ScopedGlideElement; + readonly sys_updated_by: string & ScopedGlideElement; + readonly sys_updated_on: GlideDateTime & ScopedGlideElement; + variables: { [name: string]: any }; + [fieldName: string]: any; + + /** + * Creates an instance of the GlideRecord class for the specified table. + * + * @param tableName The table to be used. + * @example + * + * var gr = new GlideRecord('incident'); + */ + new (tableName: string): ScopedGlideRecord; + + /** + * Adds a filter to return active records. + * + * @returns Filter to return active records. + * @example + * + * var inc = new GlideRecord('incident'); + * inc.addActiveQuery(); + * inc.query(); + */ + addActiveQuery(): ScopedQueryCondition; + + /** + * Adds an encoded query to other queries that may have been set. + * + * @param query An encoded query string + * @example + * + * var queryString = "priority=1^ORpriority=2"; + * var gr = new GlideRecord('incident'); + * gr.addEncodedQuery(queryString); + * gr.query(); + * while (gr.next()) { + * gs.addInfoMessage(gr.number); + * } + */ + addEncodedQuery(query: string): void; + + /** + * Applies a pre-defined GlideDBFunctionBuilder object to a record. + * + * @param fun A GlideDBFunctionBuilder object that defines a SQL operation. + * @returns Method does not return a value + * @example + * + * var functionBuilder = new GlideDBFunctionBuilder(); + * var myAddingFunction = functionBuilder.add(); + * myAddingFunction = functionBuilder.field('order'); + * myAddingFunction = functionBuilder.field('priority'); + * myAddingFunction = functionBuilder.build(); + * + * var gr = new GlideRecord('incident'); + * gr.addFunction(myAddingFunction); + * gr.addQuery(myAddingFunction, '<', 5); + * gr.query(); + * while(gr.next()) + * gs.log(gr.getValue(myAddingFunction)); + * + */ + addFunction(fun: string): void; + + /** + * Adds a filter to return records based on a relationship in a related table. + * + * @param joinTable Table name + * @param primaryField (Optional) If other than sys_id, the primary field + * @param joinTableField (Optional) If other than sys_id, the field that joins the tables. + * @returns A filter that lists records where the relationships match. + * @example + * + * var prob = new GlideRecord('problem'); + * prob.addJoinQuery('incident'); + * prob.query(); + * + * @example + * + * // Look for Problem records that have associated Incident records + * var gr = new GlideRecord('problem'); + * var grSQ = gr.addJoinQuery('incident'); + * // Where the Problem records are "active=false" + * gr.addQuery('active', 'false'); + * // And the Incident records are "active=true" + * grSQ.addCondition('active', 'true'); + * // Query + * gr.query(); + * // Iterate and output results + * while (gr.next()) { + * gs.info(gr.getValue('number')); + * } + * + * @example + * + * var gr = new GlideRecord('problem'); + * gr.addJoinQuery('incident', 'opened_by', 'caller_id'); + * gr.query(); + */ + addJoinQuery( + joinTable: string, + primaryField?: string, + joinTableField?: string + ): ScopedQueryCondition; + + /** + * A filter that specifies records where the value of the field passed in the parameter is not + * null. + * + * @param fieldName The name of the field to be checked. + * @returns A filter that specifies records where the value of the field passed in the + * parameter is not null. + * @example + * + * var target = new GlideRecord('incident'); + * target.addNotNullQuery('short_description'); + * // Issue the query to the database to get all records where short_description is not null + * target.query(); + * while (target.next()) { + * // add code here to process the incident record + * } + */ + addNotNullQuery(fieldName: string): ScopedQueryCondition; + + /** + * Adds a filter to return records where the value of the specified field is null. + * + * @param fieldName The name of the field to be checked. + * @returns The query condition added to the GlideRecord. + * @example + * + * var target = new GlideRecord('incident'); + * target.addNullQuery('short_description'); + * // Issue the query to the database to get all records where short_description is null + * target.query(); + * while (target.next()) { + * // add code here to process the incident record + * } + */ + addNullQuery(fieldName: string): ScopedQueryCondition; + + /** + * Provides the ability to build a request, which when executed, returns the rows from the + * specified table, that match the request. + * + * @param name Table field name. + * @param value Value on which to query (not case-sensitive). + * @returns The query condition added to the GlideRecord. + * @example + * + * var rec = new GlideRecord('incident'); + * rec.addQuery('active', true); + * rec.query(); + * while (rec.next()) { + * rec.active = false; + * gs.info('Active incident ' + rec.number + ' closed'); + * rec.update(); + * } + */ + addQuery(name: string, value: any): ScopedQueryCondition; + + /** + * Provides the ability to build a request, which when executed, returns the rows from the + * specified table, that match the request. + * + * @param name Table field name. + * @param operator Query operator. The available values are dependent on the data type of the + * value parameter. + * + * Numbers: + * - = + * - != + * - > + * - >= + * - < + * - <= + * + * Strings (must be in upper case): + * - = + * - != + * - IN + * - NOT IN + * - STARTSWITH + * - ENDSWITH + * - CONTAINS + * - DOES NOT CONTAIN + * - INSTANCEOF + * + * @param value Value on which to query (not case-sensitive). + * @returns The query condition that was added to the GlideRecord. + * @example + * + * var rec = new GlideRecord('incident'); + * rec.addQuery('active', true); + * rec.addQuery('sys_created_on', '>', '2010-01-19 04:05:00'); + * rec.query(); + * while (rec.next()) { + * rec.active = false; + * gs.info('Active incident ' + rec.number + ' closed'); + * rec.update(); + * } + * + * @example Using the IN operator. + * + * var gr = new GlideRecord('incident'); + * gr.addQuery('number','IN','INC00001,INC00002'); + * gr.query(); + * while (gr.next()) { + * //do something.... + * } + */ + addQuery(name: string, operator: QueryOperator, value: any): ScopedQueryCondition; + + /** + * Adds a filter to return records using an encoded query string. + * + * @param query An encoded query string + * @returns The query condition added to the GlideRecord. + * @example + * + * var rec = new GlideRecord('incident'); + * rec.addQuery('active=true'); + * rec.query(); + * while (rec.next()) { + * rec.active = false; + * gs.info('Active incident ' + rec.number + ' closed'); + * rec.update(); + * } + */ + addQuery(query: string): ScopedQueryCondition; + + /** + * Determines if the Access Control Rules, which include the user's roles, permit + * inserting new records in this table. + * + * @returns True if the user's roles permit creation of new records in this + * table. + * @example + * + * var gr = new GlideRecord('incident'); + * gs.info(gr.canCreate()); + */ + canCreate(): boolean; + + /** + * Determines if the Access Control Rules, which include the user's roles, permit deleting + * records in this table. + * + * @returns True if the user's roles permit deletions of records in this table. + * @example + * + * var att = new GlideRecord('sys_attachment'); + * gs.info(att.canDelete()); + */ + canDelete(): boolean; + + /** + * Determines if the Access Control Rules, which include the user's roles, permit reading + * records in this table. + * + * @returns True if the user's roles permit reading records from this table. + * @example + * + * var gr = new GlideRecord('incident'); + * gs.info(gr.canRead()); + */ + canRead(): boolean; + + /** + * Determines if the Access Control Rules, which include the user's roles, permit editing + * records in this table. + * + * @returns True if the user's roles permit writing to records from this table. + * @example + * + * var gr = new GlideRecord('incident'); + * gs.info(gr.canWrite()); + */ + canWrite(): boolean; + + /** + * Sets a range of rows to be returned by subsequent queries. + * + * @param firstRow The first row to include. + * @param lastRow The last row to include. + * @param forceCount If true, the getRowCount() method will return all possible records. + * @returns Method does not return a value + * @example + * + * var gr = new GlideRecord('incident'); + * gr.orderBy('number'); + * gr.chooseWindow(2, 4); + * gr.query(); + * if (gr.next()) { + * gs.info(gr.number + ' is within window'); + * } + */ + chooseWindow(firstRow: number, lastRow: number, forceCount?: boolean): void; + + /** + * Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT for a duration field. + * Does not require the creation of a GlideDateTime object because the duration field is already a + * GlideDateTime object. + * + * @returns Number of milliseconds since January 1, 1970, 00:00:00 GMT. + * @example + * + * var inc = new GlideRecord('incident'); + * inc.get('17c90efb13418700cc36b1422244b05d'); + * gs.info(inc.calendar_duration.dateNumericValue()); + */ + dateNumericValue(): number; + + /** + * Deletes multiple records that satisfy the query condition. + * + * @example + * + * var gr = new GlideRecord('incident') + * gr.addQuery('active','false'); //to delete all inactive incidents + * gr.deleteMultiple(); + */ + deleteMultiple(): void; + + /** + * Deletes the current record. + * + * @returns True if the record was deleted; false if no record was found to delete. + * @example + * + * var gr = new GlideRecord('incident') + * gr.addQuery('sys_id','99ebb4156fa831005be8883e6b3ee4b9'); //to delete one record + * gr.query(); + * gr.next(); + * gr.deleteRecord(); + */ + deleteRecord(): boolean; + + /** + * Defines a GlideRecord based on the specified expression of 'name = value'. + * + * @param name Column name to match (if two arguments are specified), or sys_id (if one is + * specified) + * @param [value] Value to match. If value is not specified, then the expression used is + * 'sys_id = name'. + * @returns True if one or more matching records was found. False if no matches + * found. + * @example + * + * var gr = new GlideRecord('incident'); + * gr.get('99ebb4156fa831005be8883e6b3ee4b9'); + * gs.info(gr.number); + */ + get(name: string, value?: string): boolean; + + /** + * Returns the dictionary attributes for the specified field. + * + * @param fieldName Field name for which to return the dictionary attributes + * @returns Dictionary attributes + * @example + * + * doit(); + * function doit() { + * var gr = new GlideRecord('sys_user'); + * gr.query("user_name","admin"); + * if (gr.next()) { + * gs.print("we got one"); + * gs.print(gr.location.getAttribute("tree_picker")); + * } + * } + */ + getAttribute(fieldName: string): string; + + /** + * Returns the table's label. + * + * @returns Table's label + */ + getClassDisplayValue(): string; + + /** + * Retrieves the display value for the current record. + * + * @returns The display value for the current record. + * @example + * + * var gr = new GlideRecord('incident'); + * gr.get('sys_id','ef43c6d40a0a0b5700c77f9bf387afe3'); + * gs.info(gr.getDisplayValue()); + */ + getDisplayValue(field?: string): string; + + /** + * Returns the element's descriptor. + * + * @returns Element's descriptor + * @example + * + * var gr = new GlideRecord('incident'); + * var ed = gr.getED(); + * gs.info(ed.getLabel()); + * // Incident + */ + getED(): ScopedElementDescriptor; + + /** + * Retrieves the GlideElement object for the specified field. + * + * @param columnName Name of the column to get the element from. + * @returns The GlideElement for the specified column of the current record. + * @example + * + * var elementName = 'short_description'; + * var gr = new GlideRecord('incident'); + * gr.initialize(); + * gr.setValue(elementName, "My DB is not working"); + * gr.insert(); + * gs.info(gr.getElement('short_description')); + */ + getElement(columnName: string): ScopedGlideElement; + + /** + * Returns an array of GlideElements for the current record. + * + * @returns The array of GlideElements for the current record. + */ + getElements(): [ScopedGlideElement]; + + /** + * Retrieves the query condition of the current result set as an encoded query string. + * + * @returns The encoded query as a string. + * @example + * + * var gr = new GlideRecord('incident'); + * gr.addQuery('active', true); + * gr.addQuery('priority', 1); + * gr.query(); + * var encodedQuery = gr.getEncodedQuery(); + * gs.info(encodedQuery); + */ + getEncodedQuery(): string; + + /** + * Returns the field's label. + * + * @returns Field's label + * @example + * + * var gr = new GlideRecord('incident'); + * gs.info(gr.getLabel()); + * // Incident + */ + getLabel(): string; + + /** + * Retrieves the last error message. If there is no last error message, null is returned. + * + * @returns The last error message as a string. + * @example + * + * // Setup a data policy where short_description field in incident is mandatory + * var gr = new GlideRecord('incident'); + * gr.insert(); // insert without data in mandatory field + * var errormessage = gr.getLastErrorMessage(); + * gs.info(errormessage); + */ + getLastErrorMessage(): string; + + /** + * Retrieves a link to the current record. + * + * @param noStack If true, the sysparm_stack parameter is not appended to the link. + * The parameter sysparm_stack specifies the page to visit after closing the current link. + * @returns A link to the current record as a string. + * @example + * + * gr = new GlideRecord('incident'); + * gr.addActiveQuery(); + * gr.addQuery("priority", 1); + * gr.query(); + * gr.next() + * gs.info(gs.getProperty('glide.servlet.uri') + gr.getLink(false)); + */ + getLink(noStack: boolean): string; + + /** + * Retrieves the class name for the current record. + * + * @returns The class name. + * @example + * + * var gr = new GlideRecord('incident'); + * var recordClassName = gr.getRecordClassName(); + * gs.info(recordClassName); + */ + getRecordClassName(): string; + + /** + * Retrieves the number of rows in the query result. + * + * @returns The number of rows. + * @example + * + * var gr = new GlideRecord('incident') + * gr.query(); + * gs.info("Records in incident table: " + gr.getRowCount()); + */ + getRowCount(): number; + + /** + * Retrieves the name of the table associated with the GlideRecord. + * + * @returns The table name + * @example + * + * var gr = new GlideRecord('incident'); + * gs.info(gr.getTableName()); + */ + getTableName(): string; + + /** + * Gets the primary key of the record, which is usually the sys_id unless otherwise + * specified. + * + * @returns The unique primary key as a String, or null if the key is null. + * @example + * + * var gr = new GlideRecord('kb_knowledge'); + * gr.query(); + * gr.next(); + * var uniqueid = gr.getUniqueValue(); + * gs.info(uniqueid); + */ + getUniqueValue(): string; + + /** + * Retrieves the string value of an underlying element in a field. + * + * @param name The name of the field to get the value from. + * @returns The value of the field. + * @example + * + * var gr = new GlideRecord('incident'); + * gr.orderBy('number'); + * gr.query('active','true'); + * gr.next() ; + * gs.info(gr.getValue('number')); + */ + getValue(name: string): string; + + /** + * Determines if there are any more records in the GlideRecord object. + * + * @returns True if there are more records in the query result set. + * @example + * + * var rec = new GlideRecord('incident'); + * rec.query(); + * if (rec.hasNext()) { + * gs.info("Table is not empty"); + * } + */ + hasNext(): boolean; + + /** + * Creates an empty record suitable for population before an insert. + * + * @example + * + * var gr = new GlideRecord('incident'); + * gr.initialize(); + * gr.name='New Incident'; + * gr.description='Incident description'; + * gr.insert(); + */ + initialize(): void; + + /** + * Inserts a new record using the field values that have been set for the current record. + * + * @returns Unique ID of the inserted record, or null if the record is not inserted. + * @example + * + * var gr = new GlideRecord('incident'); + * gr.initialize(); + * gr.name = 'New Incident'; + * gr.description = 'Incident description'; + * gr.insert(); + */ + insert(): string; + + /** + * Checks to see if the current database action is to be aborted. + * + * @returns True if the current database action is to be aborted + * @example + * + * var gr = new GlideRecord('incident'); + * gs.info(gr.isActionAborted()); + */ + isActionAborted(): boolean; + + /** + * Checks if the current record is a new record that has not yet been inserted into the database. + * + * @returns True if the record is new and has not been inserted into the database. + * @example + * + * var gr = new GlideRecord("x_app_table"); + * gr.newRecord(); // create a new record and populate it with default values + * gs.info(gr.isNewRecord()); + */ + isNewRecord(): boolean; + + /** + * Determines if the table exists. + * + * @returns True if table is valid or if record was successfully retrieved. False if table is + * invalid or record was not successfully retrieved. + * @example + * + * var gr = new GlideRecord('incident'); + * gs.info(gr.isValid()); + * var anotherGr = new GlideRecord('wrong_table_name'); + * gs.info(anotherGr.isValid()); + */ + isValid(): boolean; + + /** + * Determines if the specified field is defined in the current table. + * + * @param columnName The name of the the field. + * @returns True if the field is defined for the current table. + * @example + * + * var gr = new GlideRecord('incident'); + * gr.initialize(); + * gs.info(gr.isValidField("short_description")); + */ + isValidField(columnName: string): boolean; + + /** + * Determines if current record is a valid record. + * + * @returns True if the current record is valid. False if past the end of the record set. + * @example + * + * var rec = new GlideRecord('incident'); + * rec.query(); + * while (rec.next()) { + * gs.info(rec.number + ' exists'); + * } + * gs.info(rec.isValidRecord()); + */ + isValidRecord(): boolean; + + /** + * Creates a new GlideRecord record, sets the default values for the fields, and assigns a unique + * ID to the record. + * + * @example + * + * var gr = new GlideRecord("x_app_table"); + * gr.newRecord(); + * gs.info(gr.isNewRecord()); + */ + newRecord(): void; + + /** + * Moves to the next record in the GlideRecord object. + * + * @returns True if moving to the next record is successful. False if there are no more records in + * the result set. + * @example + * + * var rec = new GlideRecord('incident'); + * rec.query(); + * while (rec.next()) { + * gs.info(rec.number + ' exists'); + * } + */ + next(): boolean; + + /** + * Retrieves the current operation being performed, such as insert, update, or delete. + * + * @returns The current operation. + * @example + * + * // Commonly used in a business rule, returns insert if the current operation is insert + * gs.info("current operation " + current.operation()); + */ + operation(): GlideRecordOperation; + + /** + * Specifies an orderBy column. + * + * @param name The column name used to order the records in this GlideRecord object. + * @example + * + * var queryString = "priority=2"; + * var gr = new GlideRecord('incident'); + * gr.orderBy('short_description'); // Ascending Order + * gr.addEncodedQuery(queryString); + * gr.query(); + * while (gr.next()) { + * gs.info(gr.short_description); + * } + */ + orderBy(name: string): void; + + /** + * Specifies a decending orderBy column. + * + * @param name The column name to be used to order the records in a GlideRecord object. + * @example + * + * var queryString = "priority=2"; + * var gr = new GlideRecord('incident'); + * gr.orderByDesc('short_description'); //Descending Order + * gr.addEncodedQuery(queryString); + * gr.query(); + * while (gr.next()) { + * gs.info(gr.short_description); + * } + */ + orderByDesc(name: string): void; + + /** + * Runs the query against the table based on the filters specified by addQuery, addEncodedQuery, + * etc. + * + * This queries the GlideRecord table as well as any references of the table. Usually this is + * performed without arguments. If name/value pair is specified, "name=value" condition is added + * to the query. + * + * @param field The column name to query on. + * @param value The value to query for. + * @example + * + * var rec = new GlideRecord('incident'); + * rec.query(); + * while (rec.next()) { + * gs.info(rec.number + ' exists'); + * } + */ + query(field?: string, value?: any): void; + + /** + * Sets a flag to indicate if the next database action (insert, update, delete) is to be aborted. + * This is often used in business rules. + * + * @param b True to abort the next action. False if the action is to be allowed. + * @example + * + * // Often used in business rule to check whether the current operation should be aborted. + * if (current.size > 16) { + * current.setAbortAction(true); + * } + */ + setAbortAction(b: boolean): void; + + /** + * Scoped API docs include `setDateNumericValue` but it is not a valid method. + * When called, it throws: + * org.mozilla.javascript.EcmaError: Cannot find function setDateNumericValue in object + * [object GlideRecord]. + */ + // setDateNumericValue(milliseconds: number): void; + + /** + * Sets the limit for number of records are fetched by the GlideRecord query. + * + * @param maxNumRecords The maximum number of records to fetch. + * @example + * + * var gr = new GlideRecord('incident'); + * gr.orderByDesc('sys_created_on'); + * gr.setLimit(10); + * gr.query(); // this retrieves latest 10 incident records created + */ + setLimit(maxNumRecords: number): void; + + /** + * Sets sys_id value for the current record. + * + * @param guid The GUID to be assigned to the current record. + * @example + * + * var gr = new GlideRecord('incident'); + * gr.short_description='The third floor printer is broken'; + * gr.setNewGuidValue('eb4636ca6f6d31005be8883e6b3ee333'); + * gr.insert(); + * gs.info(gr.sys_id); + */ + setNewGuidValue(guid: string): void; + + /** + * Sets the value of the field with the specified name to the specified value. + * + * @param name Name of the field. + * @param value The value to assign to the field. + * @example + * + * var elementName = 'short_description'; + * var gr = new GlideRecord('incident'); + * gr.initialize(); + * gr.setValue(elementName, "My DB is not working"); + * gr.insert(); + */ + setValue(name: string, value: any): void; + + /** + * Enables or disables the running of business rules, script engines, and audit. + * + * @param enable If true (default), enables business rules. If false, disables business + * rules. + * @example + * + * //Enable business rules, scripts engines for x_app_table + * var gr = new GlideRecord("x_app_table"); + * gr.setWorkflow(true); + */ + setWorkflow(enable: boolean): void; + + /** + * Updates the GlideRecord with any changes that have been made. If the record does not already + * exist, it is inserted. + * + * @param [reason] The reason for the update. The reason is displayed in the audit record. + * @returns Unique ID of the new or updated record. Returns null if the update fails. + * @example + * + * var gr = new GlideRecord('incident') + * gr.get('99ebb4156fa831005be8883e6b3ee4b9'); + * gr.short_description='Update the short description'; + * gr.update(); + * gs.info(gr.getElement('short_description')); + */ + update(reason?: string): string; + + /** + * Updates each GlideRecord in the list with any changes that have been made. + * + * @example + * + * // update the state of all active incidents to 4 - "Awaiting User Info" + * var gr = new GlideRecord('incident') + * gr.addQuery('active', true); + * gr.query(); + * gr.setValue('state', 4); + * gr.updateMultiple(); + */ + updateMultiple(): void; + + /** + * Moves to the next record in the GlideRecord. Provides the same functionality as next(), it is + * intended to be used in cases where the GlideRecord has a column named next. + * + * @returns True if there are more records in the query set. + * @example + * + * var rec = new GlideRecord('sys_template'); + * rec.query(); + * while (rec._next()) { + * gs.print(rec.number + ' exists'); + * } + */ + _next(): boolean; + + /** + * Identical to query(). This method is intended to be used on tables where there is a column + * named query, which would interfere with using the query() method. + * + * @param name Column name on which to query + * @param value Value for which to query + * @example + * + * var rec = new GlideRecord('sys_app_module'); + * rec._query(); + * while (rec.next()) { + * gs.print(rec.number + ' exists'); + * } + */ + _query(name?: string, value?: any): void; +} diff --git a/types/servicenow-london/ScopedQueryCondition.d.ts b/types/servicenow-london/ScopedQueryCondition.d.ts new file mode 100644 index 0000000000..2cffd17769 --- /dev/null +++ b/types/servicenow-london/ScopedQueryCondition.d.ts @@ -0,0 +1,72 @@ +interface ScopedQueryCondition { + /** + * Adds an AND condition to the current condition. + * + * @param name The name of a field. + * @param value The value to query on. + * @returns A reference to a GlideQueryConditon that was added to the GlideRecord. + * @example + * var gr = new GlideRecord('incident'); + * var qc = gr.addQuery('category', 'Hardware'); + * qc.addCondition('category', 'Network'); + * gr.addQuery('number','INC0000003'); + * gr.next(); + * gr.number; + * gs.info(gr.getEncodedQuery()); + */ + addCondition(name: string, value: object | string | number): ScopedQueryCondition; + + /** + * Adds an AND condition to the current condition. + * + * @param name The name of a field. + * @param oper The operator for the query. + * If you do not specify an operator, the condition uses an equals operator. + * @param value The value to query on. + * @returns A reference to a GlideQueryConditon that was added to the GlideRecord. + */ + addCondition( + name: string, + oper: QueryOperator, + value: object | string | number + ): ScopedQueryCondition; + + /** + * Appends a 2-or-3 parameter OR condition to an existing GlideQueryCondition. + * + * @param name Field name + * @param value The value to query on. + * @returns A reference to a GlideQueryConditon that was added to the GlideRecord. + */ + addOrCondition(name: string, value: object | string | number): ScopedQueryCondition; + + /** + * Appends a 2-or-3 parameter OR condition to an existing GlideQueryCondition. + * + * @param name Field name + * @param oper Query operator. + * The available values are dependent on the data type of the value parameter. + * + * Numbers: + * - = + * - != + * - > + * - >= + * - < + * - <= + * + * Strings (must be in upper case): + * - = + * - != + * - IN + * - NOT IN + * - STARTSWITH + * - ENDSWITH + * - CONTAINS + * - DOES NOT CONTAIN + * - INSTANCEOF + * @param value The value to query on. + * @returns A reference to a GlideQueryConditon that was added to the GlideRecord. + */ + addOrCondition(name: string, oper: QueryOperator, value: any): ScopedQueryCondition; +} diff --git a/types/servicenow-london/Workflow.d.ts b/types/servicenow-london/Workflow.d.ts new file mode 100644 index 0000000000..05b1f9e3dd --- /dev/null +++ b/types/servicenow-london/Workflow.d.ts @@ -0,0 +1,97 @@ +declare namespace global { + class Workflow { + constructor(); + broadcastEvent(contextId: string, eventName: string): void; + cancel(record: ScopedGlideRecord): void; + cancelContext(context: ScopedGlideRecord): void; + deleteWorkflow(current: ScopedGlideRecord): void; + fireEvent(eventRecord: ScopedGlideRecord, eventName: string): void; + fireEventById(eventRecordId: string, eventName: string): void; + getContexts(record: ScopedGlideRecord): ScopedGlideRecord; + getEstimatedDeliveryTime(workflowId: string): string; + getEstimatedDeliveryTimeFromWFVersion(wfVersion: ScopedGlideRecord): string; + + /** + * Get the return value set by activity "Return Value" + * + * @param context wf_context GlideRecord of the context from which you want the return value + * @return The value set by activity "Return Value" in the workflow + */ + getReturnValue(context: ScopedGlideRecord): any; + getRunningFlows(record: ScopedGlideRecord): ScopedGlideRecord; + getVersion(workflowId: string): ScopedGlideRecord; + getVersionFromName(workflowName: string): ScopedGlideElement; + getWorkflowFromName(workflowName: string): string; + hasWorkflow(record: ScopedGlideRecord): boolean; + restartWorkflow(record: ScopedGlideRecord, maintainStateFlag?: boolean): void; + + /** + * Run all flows attached to a current GlideRecord. + * + * Calling this method on a current will not implicitly update the current. If the workflow + * modifies the input current to this method, it is up to the caller to call + * current.update() to persist these changes. + * + * @param record A GlideRecord that holds the current record + * @param operation A String that holds the operation such as "update", "insert", or perhaps + * "timer" or some other user defined value. + */ + runFlows(record: ScopedGlideRecord, operation: GlideRecordOperation): void; + + /** + * Start a workflow. Internal logic will determine which workflow version should be run. The + * workflow version to run is either the one checked out to the current user, or the + * published workflow version. Calling this method on a current will not implicitly update + * the current. If the workflow modifies the input current to this method, it is up to the + * caller to call current.update() to persist these changes. + * + * @param workflowId The sys_id of the workflow from the wf_workflow table + * @param current The GlideRecord of the current record to be operated on by the workflow + * @param operation The String operation for this workflow - not used + * @param vars JavaScript object of workflow inputs. The key is the variable name, the value + * is the variable value. + * @returns The GlideRecord of the wf_context of the running workflow. Do not modify this + * returned GlideRecord. + */ + startFlow( + workflowId: string, + current: ScopedGlideRecord | null, + operation: GlideRecordOperation, + vars?: object + ): string; + + /** + * An intermediate method used to start a workflow from the green "run" button on the + * Graphical Workflow Editor. This should not be used by SNC script writers. + * + * @param context GlideRecord on wf_context of the context to start the Workflow engine on + * @param operation The String event for processing + */ + startFlowFromContextInsert( + context: ScopedGlideRecord, + operation: GlideRecordOperation + ): void; + + /** + * An intermediate method used to start a workflow with preloaded values for SLA Timer + * activity. This should not be used by SNC script writers + * + * @param workflowId The sys_id of a record in table wf_workflow for the workflow to run + * @param retroactiveMSecs Integer value of seconds to start the workflow on. This is used + * by SLA Timer activity + * @param current The GlideRecord of the current record + * @param operation The String event for processing - not used. + * @param vars JavaScript object or Java HashMap of workflow inputs. The key is the variable + * name, the value is the variable value + * @param withSchedule Boolean value to indicate if a schedule should be used + */ + startFlowRetroactive( + workflowID: string, + retroactiveMSecs: number, + current: ScopedGlideRecord, + operation: GlideRecordOperation, + vars?: object, + withSchedule?: any + ): ScopedGlideRecord; + } +} diff --git a/types/servicenow-london/XMLDocument2.d.ts b/types/servicenow-london/XMLDocument2.d.ts new file mode 100644 index 0000000000..d52b057a72 --- /dev/null +++ b/types/servicenow-london/XMLDocument2.d.ts @@ -0,0 +1,13 @@ +declare class XMLDocument2 { + constructor(); + createElement(name: string): XMLNode; + createElementWithTextValue(name: string, value: string): XMLNode; + getDocumentElement(): XMLNode; + getFirstNode(xpath: string): XMLNode; + getNextNode(prev: object): XMLNode; + getNode(xpath: string): XMLNode; + getNodeText(xpath: string): string; + parseXML(xmlDoc: string): void; + setCurrentElement(element: XMLNode): void; + toString(): string; +} diff --git a/types/servicenow-london/XMLNode.d.ts b/types/servicenow-london/XMLNode.d.ts new file mode 100644 index 0000000000..2ad525b49b --- /dev/null +++ b/types/servicenow-london/XMLNode.d.ts @@ -0,0 +1,11 @@ +interface XMLNode { + getLastChild(): XMLNode; + getFirstChild(): XMLNode; + getNodeValue(): string; + getNodeName(): string; + hasAttribute(name: string): boolean; + getAttribute(attribute: string): string; + getChildNodeIterator(): XMLNodeIterator; + getTextContent(): string; + toString(): string; +} diff --git a/types/servicenow-london/XMLNodeIterator.d.ts b/types/servicenow-london/XMLNodeIterator.d.ts new file mode 100644 index 0000000000..4e404ec199 --- /dev/null +++ b/types/servicenow-london/XMLNodeIterator.d.ts @@ -0,0 +1,4 @@ +interface XMLNodeIterator { + hasNext(): boolean; + next(): XMLNode; +} diff --git a/types/servicenow-london/index.d.ts b/types/servicenow-london/index.d.ts new file mode 100644 index 0000000000..1a236a1708 --- /dev/null +++ b/types/servicenow-london/index.d.ts @@ -0,0 +1,62 @@ +// Type definitions for non-npm package servicenow-london 1.0 +// Project: https://developer.servicenow.com/app.do#!/api_doc?v=london +// Definitions by: John Caruso +// Bryce Godfrey +// Garrett Griffin +// Erik Myrold +// Tim Woodruff +// Anim Yeboah +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +declare const GlideRecord: ScopedGlideRecord; +declare const GlideRecordSecure: ScopedGlideRecord; +declare const RP: RenderProperties; +declare const current: ScopedGlideRecord; +declare const email: GlideEmailOutbound; +declare const g_processor: GlideScriptedProcessor; +declare const g_request: GlideServletRequest; +declare const g_response: GlideServletResponse; +declare const gs: GlideSystem; +declare const previous: ScopedGlideRecord; diff --git a/types/servicenow-london/test/Class.ts b/types/servicenow-london/test/Class.ts new file mode 100644 index 0000000000..f6d1c9f2b7 --- /dev/null +++ b/types/servicenow-london/test/Class.ts @@ -0,0 +1,11 @@ +var NewInclude = Class.create(); + +NewInclude.prototype = { + initialize: function() {}, + + myFunction: function() { + //Put function code here + }, + + type: 'NewInclude' +}; diff --git a/types/servicenow-london/test/GlideDBFunctionBuilder.ts b/types/servicenow-london/test/GlideDBFunctionBuilder.ts new file mode 100644 index 0000000000..0fc4b980e1 --- /dev/null +++ b/types/servicenow-london/test/GlideDBFunctionBuilder.ts @@ -0,0 +1,75 @@ +(function() { + var functionBuilder = new GlideDBFunctionBuilder(); + var myAddingFunction = functionBuilder.add(); + myAddingFunction = functionBuilder.field('order'); + myAddingFunction = functionBuilder.field('priority'); + var func = functionBuilder.build(); +})(); +(function() { + var functionBuilder = new GlideDBFunctionBuilder(); + var myAddingFunction = functionBuilder.add(); + myAddingFunction = functionBuilder.field('order'); + myAddingFunction = functionBuilder.field('priority'); + var func = functionBuilder.build(); + gs.info(func); +})(); +(function() { + var functionBuilder = new GlideDBFunctionBuilder(); + var myConcatFunction = functionBuilder.concat(); + myConcatFunction = functionBuilder.field('short_description'); + myConcatFunction = functionBuilder.field('caller_id.name'); + var func = functionBuilder.build(); +})(); +(function() { + var functionBuilder = new GlideDBFunctionBuilder(); + var myDateDiffFunction = functionBuilder.datediff(); + myDateDiffFunction = functionBuilder.field('sys_updated_on'); + myDateDiffFunction = functionBuilder.field('opened_at'); + var func = functionBuilder.build(); +})(); +(function() { + var functionBuilder = new GlideDBFunctionBuilder(); + var dayOfWeekFunction = functionBuilder.dayofweek(); + dayOfWeekFunction = functionBuilder.field('opened_at'); + dayOfWeekFunction = functionBuilder.constant('2'); + var func = functionBuilder.build(); + + var gr = new GlideRecord('incident'); + gr.addFunction(func); + gr.query(); + while (gr.next()) gs.info(gr.getValue(func)); +})(); +(function() { + var functionBuilder = new GlideDBFunctionBuilder(); + var myDivideFunction = functionBuilder.divide(); + myDivideFunction = functionBuilder.field('order'); + myDivideFunction = functionBuilder.field('priority'); + var func = functionBuilder.build(); +})(); +(function() { + var functionBuilder = new GlideDBFunctionBuilder(); + var myAddingFunction = functionBuilder.add(); + myAddingFunction = functionBuilder.field('order'); + myAddingFunction = functionBuilder.field('priority'); + var func = functionBuilder.build(); +})(); +(function() { + var functionBuilder = new GlideDBFunctionBuilder(); + var myLengthFunction = functionBuilder.length(); + myLengthFunction = functionBuilder.field('short_description'); + var func = functionBuilder.build(); +})(); +(function() { + var functionBuilder = new GlideDBFunctionBuilder(); + var myMultiplyFunction = functionBuilder.multiply(); + myMultiplyFunction = functionBuilder.field('order'); + myMultiplyFunction = functionBuilder.field('priority'); + var func = functionBuilder.build(); +})(); +(function() { + var functionBuilder = new GlideDBFunctionBuilder(); + var mySubtractFunction = functionBuilder.subtract(); + mySubtractFunction = functionBuilder.field('order'); + mySubtractFunction = functionBuilder.field('priority'); + var func = functionBuilder.build(); +})(); diff --git a/types/servicenow-london/test/GlideDate.ts b/types/servicenow-london/test/GlideDate.ts new file mode 100644 index 0000000000..1a4c2fd086 --- /dev/null +++ b/types/servicenow-london/test/GlideDate.ts @@ -0,0 +1,18 @@ +(function() { + var gd = new GlideDate(); + gs.info(gd.getByFormat('dd-MM-yyyy')); + gs.info(gd.getDayOfMonthNoTZ()); + gs.info(gd.getDisplayValue()); + gs.info(gd.getDisplayValueInternal()); + gs.info(gd.getMonthNoTZ()); + gs.info(gd.getValue()); + gs.info(gd.getYearNoTZ()); + gd.setDisplayValue('2011-01-01'); + gd.setValue('2015-01-01'); + var sgd1 = new GlideDate(); + sgd1.setDisplayValue('2014-07-18'); + var sgd2 = new GlideDate(); + sgd2.setDisplayValue('2014-07-19'); + var duration = GlideDate.subtract(sgd1, sgd2); + gs.info(duration.getDisplayValue()); +})(); diff --git a/types/servicenow-london/test/GlideDateTime.ts b/types/servicenow-london/test/GlideDateTime.ts new file mode 100644 index 0000000000..e3396f268d --- /dev/null +++ b/types/servicenow-london/test/GlideDateTime.ts @@ -0,0 +1,100 @@ +(function() { + var gdt = new GlideDateTime('2011-08-31 08:00:00'); + var gtime1 = new GlideTime(); + gtime1.setValue('00:00:20'); + gdt.add(gtime1); + var gtime2 = gdt.getTime(); + gs.info(gtime2.getByFormat('hh:mm:ss')); + gdt.add(10); + var start = new GlideDateTime('2011-01-01 12:00:00'); + var end = new GlideDateTime(start); + gdt.addDaysLocalTime(-1); + gdt.addDaysUTC(-1); + gdt.addMonthsLocalTime(2); + gdt.addMonthsUTC(2); + gdt.addSeconds(1000); + gdt.addWeeksLocalTime(-1); + gdt.addWeeksUTC(-1); + gdt.addYearsLocalTime(1); + gdt.addYearsUTC(1); + var gdt1 = new GlideDateTime('2016-05-09 10:11:12'); + var gdt2 = new GlideDateTime('2017-06-12 15:11:12'); + gs.info(gdt1.after(gdt2)); + gs.info(gdt1.before(gdt2)); + var initDate = new GlideDateTime('2011-08-01 12:00:00'); + var compDate1 = new GlideDateTime('2011-08-01 12:00:00'); + var compDate2 = new GlideDateTime('2011-07-31 12:00:00'); + var compDate3 = new GlideDateTime('2011-08-04 16:00:00'); + gs.info(initDate.compareTo(compDate1)); // Equals (0) + gs.info(initDate.compareTo(compDate2)); // initDate is after compDate2 (1) + gs.info(initDate.compareTo(compDate3)); // initDate is before compDate3 (-1) + gs.info(gdt.equals('2011-09-30 00:12:01')); + gs.info(gdt.getDate()); + gs.info(gdt.getValue()); + gs.info(gdt.getDayOfMonthLocalTime()); + gs.info(gdt.getDayOfMonthUTC()); + gs.info(gdt.getDayOfWeekLocalTime()); + gs.info(gdt.getDayOfWeekLocalTime()); + gs.info(gdt.getDaysInMonthLocalTime()); + gs.info(gdt.getDaysInMonthUTC()); + gs.info(gdt.getDisplayValue()); + gs.info(gdt.getDisplayValueInternal()); //uses current user session time zone (US/Pacific) + gs.info(gdt.getDSTOffset()); //uses current user session time zone (US/Pacific) + gdt.setDisplayValue('2011-aa-01 00:00:00'); + gs.info(gdt.getErrorMsg()); // Could not parse DateTime: 2011-aa-01 00:00:00 + gs.info(gdt.getLocalDate()); + var gt = gdt.getLocalTime(); + gs.info('local time is ' + gt.getByFormat('hh:mm:ss')); + gs.info(gdt.getMonthLocalTime()); + gs.info(gdt.getMonthUTC()); + gs.info(gdt.getNumericValue()); + var gt = gdt.getTime(); + gs.info(gt.getByFormat('hh:mm:ss')); + gdt.getLocalTime(); // PST local time + gs.info(gdt.getTZOffset()); + gs.info(gdt.getValue()); + gs.info(gdt.getWeekOfYearLocalTime()); + gs.info(gdt.getWeekOfYearUTC()); + gs.info(gdt.getYearLocalTime()); + gs.info(gdt.getYearUTC()); + gs.info(gdt.hasDate()); + gs.info(gdt.isDST()); //true + gdt.setDisplayValue('2011-aa-01 00:00:00'); + gs.info(gdt.isValid()); + var gdt1 = new GlideDateTime('2016-05-09 10:11:12'); + var gdt2 = new GlideDateTime('2017-06-12 15:11:12'); + gs.info(gdt1.onOrAfter(gdt2)); + gs.info(gdt1.onOrBefore(gdt2)); + gdt.setDayOfMonthLocalTime(9); + gs.info(gdt.getDayOfMonthLocalTime()); + gdt.setDayOfMonthUTC(9); + gs.info(gdt.getDayOfMonthUTC()); + gdt.setDisplayValue('2014-01-01 12:00:00'); + gdt.setDisplayValue('20-5-2011 12:00:00', 'dd-MM-yyyy HH:mm:ss'); + gdt.setDisplayValueInternal('2014-01-01 12:00:00'); + var dt1 = new GlideDateTime('2011-01-01 12:00:00'); + var dt2 = new GlideDateTime('2011-02-02 08:00:00'); + dt1.setGlideDateTime(dt2); + gdt.setMonthLocalTime(1); + gs.info(gdt.getMonthLocalTime()); + gdt.setMonthUTC(1); + gs.info(gdt.getMonthUTC()); + gdt.setValue('2011-02-02 08:00:00'); // value set = 2011-02-02 08:00:00 + gdt.setValueUTC('15-02-2011 08:00:00', 'dd-MM-yyyy HH:mm:ss'); + gdt.setYearLocalTime(2013); + gs.info(gdt.getYearLocalTime()); + gdt.setYearUTC(2013); + gs.info(gdt.getYearUTC()); + var gdt1 = new GlideDateTime('2011-08-28 09:00:00'); + var gdt2 = new GlideDateTime('2011-08-31 08:00:00'); + var dur = GlideDateTime.subtract(gdt1, gdt2); //the difference between gdt1 and gdt2 + gs.info(dur.getDisplayValue()); + var gtime1 = new GlideTime(); + gtime1.setValue('00:00:20'); + gdt.subtract(gtime1); + var gtime2 = gdt.getTime(); + gs.info(gtime2.getByFormat('hh:mm:ss')); + var gdt = new GlideDateTime('2011-12-07 08:00:00'); + gdt.subtract(1000); + gs.info(gdt.toString()); +})(); diff --git a/types/servicenow-london/test/GlideDuration.ts b/types/servicenow-london/test/GlideDuration.ts new file mode 100644 index 0000000000..f217d74e74 --- /dev/null +++ b/types/servicenow-london/test/GlideDuration.ts @@ -0,0 +1,46 @@ +(function() { + var duration = new GlideDuration('3 12:00:00'); + var duration2 = new GlideDuration('3:00:00'); + var answer = duration.add(duration2); + gs.info(answer.getDisplayValue()); +})(); +(function() { + var dur = new GlideDuration('3 22:00:00'); + gs.info(dur.getByFormat('HH:mm')); +})(); +(function() { + var dur = new GlideDuration('3 12:00:00'); + gs.info(dur.getDayPart()); +})(); +(function() { + var dur = new GlideDuration('3 12:00:00'); + gs.info(dur.getDisplayValue()); +})(); +(function() { + var dur = new GlideDuration('3 12:00:00'); + gs.info(dur.getDurationValue()); +})(); +(function() { + var dur = new GlideDuration('3 11:00:00'); + gs.info(dur.getRoundedDayPart()); +})(); +(function() { + var dur = new GlideDuration('3 12:00:00'); + gs.info(dur.getValue()); +})(); +(function() { + var dur = new GlideDuration(); + dur.setDisplayValue('3 08:00:00'); + gs.info(dur.getDisplayValue()); +})(); +(function() { + var dur = new GlideDuration(); + dur.setValue('1970-01-05 08:00:00'); // sets internal DateTime value. The String will be parsed into a GlideDateTime object. + gs.info(dur.getDisplayValue()); +})(); +(function() { + var duration = new GlideDuration('3 12:00:00'); + var duration2 = new GlideDuration('3:00:00'); + var answer = duration.subtract(duration2); + gs.info(answer.getDisplayValue()); +})(); diff --git a/types/servicenow-london/test/GlideEmailOutbound.ts b/types/servicenow-london/test/GlideEmailOutbound.ts new file mode 100644 index 0000000000..969e16255f --- /dev/null +++ b/types/servicenow-london/test/GlideEmailOutbound.ts @@ -0,0 +1,21 @@ +(function() { + email.addAddress('cc', 'joe.employee@something.com'); +})(); +(function() { + email.addAddress('bcc', 'joe.employee@something.com', 'dudley rocks'); +})(); +(function() { + var watermark = email.getWatermark(); +})(); +(function() { + email.setBody('Dear Sir, ...'); +})(); +(function() { + email.setFrom('joe.employee@something.com'); +})(); +(function() { + email.setReplyTo('joe.employee@something.com'); +})(); +(function() { + email.setSubject('Important Issues to discuss'); +})(); diff --git a/types/servicenow-london/test/GlideFilter.ts b/types/servicenow-london/test/GlideFilter.ts new file mode 100644 index 0000000000..ff0348c71e --- /dev/null +++ b/types/servicenow-london/test/GlideFilter.ts @@ -0,0 +1,10 @@ +(function() { + var rec = new GlideRecord('incident'); + rec.query(); + var bool = true; + + while (rec.next()) { + bool = GlideFilter.checkRecord(rec, 'active=true'); + gs.info('number ' + rec.number + ' is ' + bool); + } +})(); diff --git a/types/servicenow-london/test/GlideLocale.ts b/types/servicenow-london/test/GlideLocale.ts new file mode 100644 index 0000000000..831d035919 --- /dev/null +++ b/types/servicenow-london/test/GlideLocale.ts @@ -0,0 +1,15 @@ +(function() { + var locale = GlideLocale.get(); +})(); +(function() { + var locale = GlideLocale.get(); + var decimalSeparator = locale.getDecimalSeparator(); + gs.info('The decimal separator is ' + decimalSeparator); + // The decimal separator is . +})(); +(function() { + var locale = GlideLocale.get(); + var groupingSeparator = locale.getGroupingSeparator(); + gs.info('The grouping separator is ' + groupingSeparator); + // The grouping separator is , +})(); diff --git a/types/servicenow-london/test/GlidePluginManager.ts b/types/servicenow-london/test/GlidePluginManager.ts new file mode 100644 index 0000000000..ca040d31b2 --- /dev/null +++ b/types/servicenow-london/test/GlidePluginManager.ts @@ -0,0 +1,18 @@ +(function() { + var gr = new GlideRecord('sys_plugins'); + var queryString = 'active=0^ORactive=1'; + gr.addEncodedQuery(queryString); + gr.query(); + var pMgr = new GlidePluginManager(); + + while (gr.next()) { + var name = gr.getValue('name'); + var pID = gr.getValue('source'); + var isActive = pMgr.isActive(pID); + if (isActive) gs.info('The plugin ' + name + ' is active'); + } + // The plugin Country Lookup Data is active + // The plugin Database Replication is active + // The plugin REST API Provider is active + // The plugin Ten Cool Things is active ... +})(); diff --git a/types/servicenow-london/test/GlideSchedule.ts b/types/servicenow-london/test/GlideSchedule.ts new file mode 100644 index 0000000000..ada8aeaf6d --- /dev/null +++ b/types/servicenow-london/test/GlideSchedule.ts @@ -0,0 +1,62 @@ +(function() { + var startDate = new GlideDateTime('2014-01-02'); + var days = 2; + var dur = new GlideDuration(60 * 60 * 24 * 1000 * days); + var schedule = new GlideSchedule(); + var end = schedule.add(startDate, dur); + gs.info(end); +})(); +(function() { + var schedule = new GlideSchedule('090eecae0a0a0b260077e1dfa71da828', 'US/Pacific'); +})(); +(function() { + var startDate = new GlideDateTime('2014-10-16 02:00:00'); + var endDate = new GlideDateTime('2014-10-18 04:00:00'); + var schedule = new GlideSchedule(); + + schedule.load('090eecae0a0a0b260077e1dfa71da828'); // loads "8-5 weekdays excluding holidays" schedule + var duration = schedule.duration(startDate, endDate); + gs.info(duration.getDurationValue()); // gets the elapsed time in schedule +})(); +(function() { + var sys_id = '04e664654a36232701a2247dcd8fc4cf'; // sys_id for "Application" schedule record + var sched = new GlideSchedule(sys_id); + gs.info(sched.getName()); +})(); +(function() { + var g = new GlideRecord('cmn_schedule'); + g.addQuery('type', 'blackout'); + g.query(); + if (g.next()) { + var sched = new GlideSchedule(g.sys_id); + var d = new GlideDateTime(); + d.setDisplayValue('2007-09-18 12:00:00'); + if (sched.isInSchedule(d)) gs.info('Is in the schedule'); + else gs.info('Is NOT in the schedule'); + } +})(); +(function() { + var g = new GlideRecord('cmn_schedule'); + g.addQuery('type', 'blackout'); + g.query(); + if (g.next()) { + var sched = new GlideSchedule(g.sys_id); + var d = new GlideDateTime(); + d.setDisplayValue('2007-09-18 12:00:00'); + if (sched.isValid()) gs.info('Is valid'); + else gs.info('Is not valid'); + } +})(); +(function() { + var x = new GlideSchedule(); + x.load('08fcd0830a0a0b2600079f56b1adb9ae'); +})(); +(function() { + var schedule = new GlideSchedule(); + schedule.setTimeZone('US/Pacific'); +})(); +(function() { + var startDate = new GlideDateTime('2014-10-25 08:00:00'); + var glideSchedule = new GlideSchedule('08fcd0830a0a0b2600079f56b1adb9ae', 'UTC'); + gs.info(glideSchedule.whenNext(startDate)); +})(); diff --git a/types/servicenow-london/test/GlideScopedEvaluator.ts b/types/servicenow-london/test/GlideScopedEvaluator.ts new file mode 100644 index 0000000000..4a3745ee11 --- /dev/null +++ b/types/servicenow-london/test/GlideScopedEvaluator.ts @@ -0,0 +1,34 @@ +(function() { + // For this example, we created a table: "x_app_table" + // with two columns: "short_description", "test_script" + // "test_script" will store the script to be evaluated by GlideScopedEvaluator. + var gr = new GlideRecord('x_app_table'); + gr.short_description = 'Testing GlideScopedEvaluator'; + gr.test_script = "gs.getUser().getName() + ' says ' + greeting; "; + gr.insert(); + + // setup variables to be used by the script + var vars = { greeting: 'hello' }; + + //Evaluate the script from the field + var evaluator = new GlideScopedEvaluator(); + gs.info(evaluator.evaluateScript(gr, 'test_script', vars)); + // ${user_name} says hello +})(); +(function() { + //setting up a record that contains the script to be executed. + var gr = new GlideRecord('x_app_table'); + gr.short_description = 'Calculate Addition'; + gr.test_script = 'result = x + y'; + gr.insert(); + + var evaluator = new GlideScopedEvaluator(); + evaluator.putVariable('x', 100); + evaluator.putVariable('y', 200); + evaluator.putVariable('result', null); + + // Now retrieve the result + evaluator.evaluateScript(gr, 'test_script', null); + gs.info(evaluator.getVariable('result')); + // 300 +})(); diff --git a/types/servicenow-london/test/GlideScriptedProcessor.ts b/types/servicenow-london/test/GlideScriptedProcessor.ts new file mode 100644 index 0000000000..470458074c --- /dev/null +++ b/types/servicenow-london/test/GlideScriptedProcessor.ts @@ -0,0 +1,16 @@ +(function() { + //Do whatever processing you need and redirect to the homepage + g_processor.redirect('/navpage.do'); +})(); +(function() { + var map = { key1: 'value1', key2: 'value2' }; + g_processor.writeJSON(map); +})(); +(function() { + var name = g_request.getParameter('name'); + g_processor.writeOutput('text/plain', 'Hello ' + name); +})(); +(function() { + var name = g_request.getParameter('name'); + g_processor.writeOutput('Hello ' + name); +})(); diff --git a/types/servicenow-london/test/GlideSecureRandomUtil.ts b/types/servicenow-london/test/GlideSecureRandomUtil.ts new file mode 100644 index 0000000000..249f502af7 --- /dev/null +++ b/types/servicenow-london/test/GlideSecureRandomUtil.ts @@ -0,0 +1,12 @@ +(function() { + gs.info(GlideSecureRandomUtil.getSecureRandomInt()); +})(); +(function() { + gs.info(GlideSecureRandomUtil.getSecureRandomIntBound(100)); +})(); +(function() { + gs.info(GlideSecureRandomUtil.getSecureRandomLong()); +})(); +(function() { + gs.info(GlideSecureRandomUtil.getSecureRandomString(12)); +})(); diff --git a/types/servicenow-london/test/GlideServletRequest.ts b/types/servicenow-london/test/GlideServletRequest.ts new file mode 100644 index 0000000000..0eae56fd0c --- /dev/null +++ b/types/servicenow-london/test/GlideServletRequest.ts @@ -0,0 +1,26 @@ +(function() { + var contentType = g_request.getContentType(); +})(); +(function() { + var headerValue = g_request.getHeader('host'); + // demonightlyus.service-now.com +})(); +(function() { + var headerList = g_request.getHeaderNames(); + // host,connection,cache-control,authorization,accept,user-agent,accept-encoding, + // accept-language, cookie,x-forwarded-proto,x-forwarded-host,x-forwarded-for +})(); +(function() { + var headerValue = g_request.getHeaders('host'); + // demonightlyus.service-now.com +})(); +(function() { + var name = g_request.getParameter('x_snc_custom_x_snc_name'); +})(); +(function() { + var paramList = g_request.getParameterNames(); +})(); +(function() { + var daString = g_request.getQueryString(); + g_processor.writeOutput('The query string is: ' + daString); +})(); diff --git a/types/servicenow-london/test/GlideServletResponse.ts b/types/servicenow-london/test/GlideServletResponse.ts new file mode 100644 index 0000000000..c0cfc5a082 --- /dev/null +++ b/types/servicenow-london/test/GlideServletResponse.ts @@ -0,0 +1,10 @@ +(function() { + g_response.setContentType('text/html;charset=UTF-8'); +})(); +(function() { + g_response.setHeader('host', 'demonightlyus.service-now.com'); +})(); +(function() { + // set the status to okay + g_response.setStatus(200); +})(); diff --git a/types/servicenow-london/test/GlideSession.ts b/types/servicenow-london/test/GlideSession.ts new file mode 100644 index 0000000000..fd702606b3 --- /dev/null +++ b/types/servicenow-london/test/GlideSession.ts @@ -0,0 +1,64 @@ +(function() { + var session = gs.getSession(); + session.putClientData('test1', 'Harry'); + var clientData = session.getClientData('test1'); + gs.info(clientData); + // Harry +})(); +(function() { + var session = gs.getSession(); + var addr = session.getClientIP(); + gs.info(addr); +})(); +(function() { + var session = gs.getSession(); + var appID = session.getCurrentApplicationId(); + gs.info(appID); + // ce05b9f32b840200c5244f74b4da1501 +})(); +(function() { + var session = gs.getSession(); + var language = session.getLanguage(); + gs.info(language); + // en +})(); +(function() { + var session = gs.getSession(); + var token = session.getSessionToken(); + gs.info(token); + // 4284b5372b840200c5244f74b4da15f2c3476cf7fcb6572afa4ef9d5e6d307a5fd9e1da7 +})(); +(function() { + var session = gs.getSession(); + var zoneName = session.getTimeZoneName(); + gs.info(zoneName); + // US/Pacific +})(); +(function() { + var session = gs.getSession(); + var URL = session.getUrlOnStack(); + gs.info(URL); + // sys_app.do?sys_id=ce05b9f32b840200c5244f74b4da1501&sysparm_goto_url=sys_app.do + // %3Fsys_id%3Dce05b9f32b840200c5244f74b4da1501 +})(); +(function() { + var isImpersonator = gs.getSession().isImpersonating(); + gs.info(isImpersonator); +})(); +(function() { + var interActive = gs.getSession().isInteractive(); + gs.info(interActive); +})(); +(function() { + var session = gs.getSession(); + var loggedIn = session.isLoggedIn(); + gs.info(loggedIn); + // true +})(); +(function() { + var session = gs.getSession(); + session.putClientData('test1', 'Harry'); + var clientData = session.getClientData('test1'); + gs.info(clientData); + // Harry +})(); diff --git a/types/servicenow-london/test/GlideStringUtil.ts b/types/servicenow-london/test/GlideStringUtil.ts new file mode 100644 index 0000000000..1cf7a3ab6b --- /dev/null +++ b/types/servicenow-london/test/GlideStringUtil.ts @@ -0,0 +1,85 @@ +(function() { + var filename = '../../../../../../etc/passwd'; + var cleanFilename = GlideStringUtil.dotToUnderBar(filename); + gs.info(cleanFilename); + // __/__/__/__/__/__/etc/passwd +})(); +(function() { + var mystring = "let's escape some quotes"; + var escapeQuote = GlideStringUtil.escapeAllQuotes(mystring); + gs.info(escapeQuote); + // lets escape some quotes +})(); +(function() { + var mystring = ' string \n to escape'; + var escapedString = GlideStringUtil.escapeForHomePage(mystring); + gs.info(escapedString); + // %3ctest%3e string \n to escape +})(); +(function() { + var mydata = '"<>&'; + mydata = GlideStringUtil.escapeHTML(mydata); + gs.info(mydata); + // "<>& +})(); +(function() { + var mystring = 'test \x09 non \x00 printable \x07 chars'; + var escapedString = GlideStringUtil.escapeNonPrintable(mystring); + gs.info(escapedString); + // test \t non \u0000 printable \u0007 chars +})(); +(function() { + var myquery = 'test^Test'; + var escapedQuery = GlideStringUtil.escapeQueryTermSeparator(myquery); + gs.info(escapedQuery); + // test^^Test +})(); +(function() { + var mystring = "let's try escapeTicks"; + var escaped = GlideStringUtil.escapeTicks(mystring); + gs.info(escaped); + // let\'s try escapeTicks +})(); +(function() { + var mydata = '&'; + var htmlvalue = GlideStringUtil.getHTMLValue(mydata); + gs.info(htmlvalue); + // & +})(); +(function() { + var mystring = '123 test 456 String 789 cleaning'; + var onlyNumeric = GlideStringUtil.getNumeric(mystring); + gs.info(onlyNumeric); + // 123456789 +})(); +(function() { + // (adding a "*" to corrupt the base64 format) + var base64 = 'GethdTYehdtshetB*'; + var isValid = GlideStringUtil.isBase64(base64); + gs.info(isValid); + // false +})(); +(function() { + var sysID = '62826bf03710200044e0bfc8bcbe5df1'; + var isElig = GlideStringUtil.isEligibleSysID(sysID); + gs.info(isElig); + // true +})(); +(function() { + var mystring = 'new line break \n, this is after the break'; + var replaceNewLine = GlideStringUtil.newLinesToBreaks(mystring); + gs.info(replaceNewLine); + // new line break
, this is after the break +})(); +(function() { + var mystring = 'test with \n (new line) and \t (tabulation)'; + var normalizedString = GlideStringUtil.normalizeWhitespace(mystring); + gs.info(normalizedString); + // test with (new line) and (tabulation) +})(); +(function() { + var mydata = '"<>&'; + var unescaped = GlideStringUtil.unescapeHTML(mydata); + gs.info(unescaped); + // "<>& +})(); diff --git a/types/servicenow-london/test/GlideSysAttachment.ts b/types/servicenow-london/test/GlideSysAttachment.ts new file mode 100644 index 0000000000..0ffdd02fcb --- /dev/null +++ b/types/servicenow-london/test/GlideSysAttachment.ts @@ -0,0 +1 @@ +// TODO \ No newline at end of file diff --git a/types/servicenow-london/test/GlideSystem.ts b/types/servicenow-london/test/GlideSystem.ts new file mode 100644 index 0000000000..0458978982 --- /dev/null +++ b/types/servicenow-london/test/GlideSystem.ts @@ -0,0 +1,211 @@ +(function() { + gs.addErrorMessage('Invalid account'); +})(); +(function() { + if (!current.u_date1.nil() && !current.u_date2.nil()) { + var start = current.u_date1.getGlideObject().getNumericValue(); + var end = current.u_date2.getGlideObject().getNumericValue(); + if (start > end) { + gs.addInfoMessage('start must be before end'); + current.u_date1.setError('start must be before end'); + current.setAbortAction(true); + } + } +})(); +(function() { + function contractNoticeDue() { + var gr = new GlideRecord('contract'); + gr.addQuery('u_contract_status', 'Active'); + gr.query(); + while (gr.next()) { + if (gr.u_termination_date <= gs.daysAgo(-90) && gr.u_contract_duration == 'Long') { + gr.u_contract_status = 'In review'; + } else if ( + gr.u_termination_date <= gs.daysAgo(-50) && + gr.u_contract_duration == 'Medium' + ) { + gr.u_contract_status = 'In review'; + } else if ( + gr.u_termination_date <= gs.daysAgo(-10) && + gr.u_contract_duration == 'Short' + ) { + gr.u_contract_status = 'In review'; + } + } + gr.update(); + } +})(); +(function() { + var gr = new GlideRecord('sysapproval_approver'); + gr.addQuery('state', 'requested'); + gr.addQuery('sys_updated_on', '<', gs.daysAgoStart(5)); + gr.query(); +})(); +(function() { + gs.debug('This is a debug message'); + var myFirstName = 'Abel'; + var myLastName = 'Tuter'; + gs.debug('This is a debug message from {0}.{1}', myFirstName, myLastName); +})(); +(function() { + gs.error('This is an error message'); + var myFirstName = 'Abel'; + var myLastName = 'Tuter'; + gs.error('This is an error message from {0}.{1}', myFirstName, myLastName); +})(); +(function() { + if (current.operation() != 'insert' && current.comments.changes()) { + gs.eventQueue('incident.commented', current, gs.getUserID(), gs.getUserName()); + } +})(); +(function() { + var personalId = gs.generateGUID(); + gs.info(personalId); + // af770511ff013100e04bfffffffffff6 +})(); +(function() { + return gs.getCallerScopeName(); +})(); +(function() { + var verStr = gs.getCssCacheVersionString(); + gs.info(verStr); + // _d82979516f0171005be8883e6b3ee4cf&theme= +})(); +(function() { + var currentId = gs.getCurrentApplicationId(); + gs.info(currentId); + // 04936cb16f30b1005be8883e6b3ee4e0 +})(); +(function() { + var currentScope = gs.getCurrentScopeName(); + gs.info(currentScope); +})(); +(function() { + var myMessage = gs.getEscapedMessage('Hello {0}', ['mom']); +})(); +(function() { + var attachment_link = gs.getProperty('glide.servlet.uri'); + gs.info(attachment_link); + // https://instance.service-now.com/ +})(); +(function() { + if (!gs.hasRole('admin') && !gs.hasRole('user_admin') && gs.getSession().isInteractive()) { + current.addQuery('active', 'true'); + } +})(); +(function() { + var myUserObject = gs.getSessionID(); + gs.info(myUserObject); +})(); +(function() { + gs.info(gs.getTimeZoneName()); +})(); +(function() { + gs.info(gs.getUrlOnStack()); +})(); +(function() { + var myUserObject = gs.getUser(); +})(); +(function() { + gs.info(gs.getUserDisplayName()); +})(); +(function() { + gs.info(gs.getUserID()); +})(); +(function() { + gs.info(gs.getUserName()); +})(); +(function() { + if (!gs.hasRole('admin') && !gs.hasRole('groups_admin') && gs.getSession().isInteractive()) { + var qc = current.addQuery('u_hidden', '!=', 'true'); //cannot see hidden groups... + qc.addOrCondition('sys_id', 'javascript:getMyGroups()'); //...unless in the hidden group + gs.info('User has admin and groups admin roles'); + } else { + gs.info('User does not have both admin and groups admin roles'); + } +})(); +(function() { + if (current.operation() == 'insert') { + // If no due date was specified, calculate a default + if (current.due_date == '') { + if (current.urgency == '1') { + // Set due date to 4 hours ahead of current time + current.due_date = gs.hoursAgo(-4); + } + + if (current.urgency == '2') { + // Set due date to 2 days ahead of current time + current.due_date = gs.daysAgo(-2); + } + + if (current.urgency == '3') { + // Set due date to 7 days ahead of current time + current.due_date = gs.daysAgo(-7); + } + } + } +})(); +(function() { + gs.include('PrototypeServer'); +})(); +(function() { + gs.info('This is an info message'); + var myFirstName = 'Abel'; + var myLastName = 'Tuter'; + gs.info('This is an info message from {0}.{1}', myFirstName, myLastName); +})(); +(function() { + gs.debug('This is a log message'); + var myFirstName = 'Abel'; + var myLastName = 'Tuter'; + gs.debug('This is a log message from {0}.{1}', myFirstName, myLastName); + gs.info(gs.isDebugging()); +})(); +(function() { + if (!gs.hasRole('admin') && gs.getSession().isInteractive()) { + var qc1 = current.addQuery('u_group', ''); + var gra = new GlideRecord('sys_user_grmember'); + gra.addQuery('user', gs.getUserID()); + gra.query(); + while (gra.next()) { + qc1.addOrCondition('u_group', gra.group); + } + } +})(); +(function() { + gs.info(gs.isLoggedIn()); +})(); +(function() { + if (gs.isMobile()) gs.info('submitted from mobile UI'); + else gs.info('NOT submitted from mobile UI'); +})(); +(function() { + var gr = new GlideRecord('incident'); + gs.info(gs.nil(gr)); +})(); +(function() { + gs.setProperty('glide.foo', 'bar', 'foo'); + gs.info(gs.getProperty('glide.foo')); +})(); +(function() { + gs.setRedirect( + 'com.glideapp.servicecatalog_cat_item_view.do?sysparm_id=d41ce5bac611227a0167f4bf8109bf70&sysparm_user=' + + current.sys_id + + '&sysparm_email=' + + current.email + ); +})(); +(function() { + gs.info(gs.tableExists('incident')); +})(); +(function() { + gs.warn('This is a warning'); + var myFirstName = 'Abel'; + var myLastName = 'Tuter'; + gs.warn('This is a warning from {0}.{1}', myFirstName, myLastName); +})(); +(function() { + var xmlString = 'value'; + var jsonObject = gs.xmlToJSON(xmlString); + gs.info(jsonObject); +})(); diff --git a/types/servicenow-london/test/GlideTime.ts b/types/servicenow-london/test/GlideTime.ts new file mode 100644 index 0000000000..805e4da23a --- /dev/null +++ b/types/servicenow-london/test/GlideTime.ts @@ -0,0 +1,46 @@ +(function() { + var gt = new GlideTime(); + gs.info(gt.getDisplayValue()); +})(); +(function() { + var gt = new GlideTime(10000); + gs.info(gt.getDisplayValue()); +})(); +(function() { + var gt = new GlideTime(); + gt.setValue('12:00:00'); + gs.info(gt.getByFormat('HH:mm')); +})(); +(function() { + var gt = new GlideTime(); + gt.setDisplayValue('12:00:00'); // User Time Zone + gs.info(gt.getDisplayValue()); // User Time Zone +})(); +(function() { + var gt = new GlideTime(); + gt.setValue('01:00:00'); //Internal Time Zone , UTC + gs.info(gt.getDisplayValueInternal()); //User Time Zone +})(); +(function() { + var gt = new GlideTime(); + gs.info(gt.getValue()); // Internal Time Zone, UTC +})(); +(function() { + var gt = new GlideTime(); + gt.setDisplayValue('01:00:00'); // User Time Zone + gs.info(gt.getDisplayValueInternal()); // User Time Zone +})(); +(function() { + var gt = new GlideTime(); + gt.setValue('01:00:00'); //Internal Time Zone, UTC + gs.info('time is ' + gt.getByFormat('hh:mm:ss')); +})(); +(function() { + var gd1 = new GlideTime(); + gd1.setDisplayValue('09:00:00'); + var gd2 = new GlideTime(); + gd2.setDisplayValue('09:10:00'); + + var dur = GlideDate.subtract(gd1, gd2); //the difference between gdt1 and gdt2 + gs.info(dur.getDisplayValue()); +})(); diff --git a/types/servicenow-london/test/GlideUser.ts b/types/servicenow-london/test/GlideUser.ts new file mode 100644 index 0000000000..c554843db3 --- /dev/null +++ b/types/servicenow-london/test/GlideUser.ts @@ -0,0 +1,59 @@ +(function() { + var currentUser = gs.getUser(); + gs.info(currentUser.getCompanyID()); +})(); +(function() { + var currentUser = gs.getUser(); + gs.info(currentUser.getDisplayName()); +})(); +(function() { + var domain = new GlideRecord('domain'); + domain.get(gs.getUser().getDomainID()); + gs.info(domain.name); +})(); +(function() { + var currentUser = gs.getUser(); + gs.info(currentUser.getEmail()); +})(); +(function() { + var currentUser = gs.getUser(); + gs.info(currentUser.getFirstName()); +})(); +(function() { + var currentUser = gs.getUser(); + gs.info(currentUser.getID()); +})(); +(function() { + var currentUser = gs.getUser(); + gs.info(currentUser.getLastName()); +})(); +(function() { + var currentUser = gs.getUser(); + gs.info(currentUser.getName()); +})(); +(function() { + var currentUser = gs.getUser(); + currentUser.savePreference('myPref', 'red'); + gs.info(currentUser.getPreference('myPref')); +})(); +(function() { + var currentUser = gs.getUser(); + gs.info(currentUser.getRoles()); +})(); +(function() { + var currentUser = gs.getUser(); + gs.info(currentUser.getUserRoles()); +})(); +(function() { + var currentUser = gs.getUser(); + gs.info(currentUser.hasRole('admin')); +})(); +(function() { + var currentUser = gs.getUser(); + gs.info(currentUser.isMemberOf('Capacity Mgmt')); +})(); +(function() { + var currentUser = gs.getUser(); + currentUser.savePreference('myPref', 'red'); + gs.info(currentUser.getPreference('myPref')); +})(); diff --git a/types/servicenow-london/test/RESTAPIRequest.ts b/types/servicenow-london/test/RESTAPIRequest.ts new file mode 100644 index 0000000000..14ec7ef8e3 --- /dev/null +++ b/types/servicenow-london/test/RESTAPIRequest.ts @@ -0,0 +1,22 @@ +function testRESTAPIRequest(request: sn_ws.RESTAPIRequest) { + var entry; + var id; + var requestBody = request.body; + var requestData = requestBody.data; + if (requestData instanceof Array) { + entry = requestData[0].name; + id = requestData[0].id; + } else { + entry = requestData.name; + id = requestData.id; + } + + var requestStream = requestBody.dataStream; + var requestString = requestBody.dataString; + requestBody.hasNext(); + requestBody.hasNext(); + var requestEntry = requestBody.nextEntry(); + + var name = requestEntry.name; + requestEntry = requestBody.nextEntry(); +} diff --git a/types/servicenow-london/test/RESTAPIRequestBody.ts b/types/servicenow-london/test/RESTAPIRequestBody.ts new file mode 100644 index 0000000000..6f4120d55f --- /dev/null +++ b/types/servicenow-london/test/RESTAPIRequestBody.ts @@ -0,0 +1,33 @@ +function testRESTAPIRequestBody(request: sn_ws.RESTAPIRequest) { + var requestBody = request.body; + // Returns instance of RESTAPIRequestBody + + var headers = request.headers; + var acceptHeader = headers.Accept; + var myCustomHeader = headers.myCustom; + var specialHeader = headers['special - header']; + var pathParams = request.pathParams; + var tableName = pathParams.tableName; + // "myApp_table" + + var id = pathParams.id; + // "1234" + + var queryParams = request.queryParams; + var isActiveQuery = queryParams.active; + // false + + var nameQueryVal = queryParams.name; + // "now" + + var query = request.queryString; + // "active=false&name=now" + + var query2 = request.uri; + // "api/now/table/myTable" + + var query3 = request.url; + // "https://instance.service-now.com/api/now/table/myTable?active=false&name=now" + + var acceptHeader = request.getHeader('accept'); +} diff --git a/types/servicenow-london/test/RESTAPIResponse.ts b/types/servicenow-london/test/RESTAPIResponse.ts new file mode 100644 index 0000000000..9938141393 --- /dev/null +++ b/types/servicenow-london/test/RESTAPIResponse.ts @@ -0,0 +1,28 @@ +function testRESTAPIResponse(response: sn_ws.RESTAPIResponse) { + response.setContentType('application/json'); + response.setStatus(200); + var writer = response.getStreamWriter(); + + var body: any = {}; + body.name = 'incident'; + body.number = '1234'; + body.caller = { id: 'user1' }; + response.setBody(body); + + var bodyArray = []; + body = {}; + body.name = 'incident'; + body.number = '1234'; + body.caller = { id: 'user1' }; + bodyArray.push(body); + response.setBody(bodyArray); + + response.setHeader('Location', ''); + + var headers: any = {}; + headers['X-Total-Count'] = 100; + headers.Location = 'https://instance.service-now.com/'; + response.setHeaders(headers); + + response.setStatus(200); +} diff --git a/types/servicenow-london/test/RESTAPIResponseStream.ts b/types/servicenow-london/test/RESTAPIResponseStream.ts new file mode 100644 index 0000000000..75f30d88d3 --- /dev/null +++ b/types/servicenow-london/test/RESTAPIResponseStream.ts @@ -0,0 +1,17 @@ +function testRESTAPIResponseStream(response: sn_ws.RESTAPIResponse, attachmentStream: any) { + response.setContentType('application/json'); + response.setStatus(200); + var writer = response.getStreamWriter(); + writer.writeStream(attachmentStream); + + response.setContentType('application/json'); + response.setStatus(200); + var writer = response.getStreamWriter(); + var body: any = { + name: 'user1', + id: 1234, + roles: [{ name: 'admin' }, { name: 'itil' }] + }; + writer.writeString("{'name':'user','id':'1234'}"); + writer.writeString(JSON.stringify(body)); +} diff --git a/types/servicenow-london/test/RESTMessageV2.ts b/types/servicenow-london/test/RESTMessageV2.ts new file mode 100644 index 0000000000..4368c70293 --- /dev/null +++ b/types/servicenow-london/test/RESTMessageV2.ts @@ -0,0 +1,106 @@ +(function() { + var sm = new sn_ws.RESTMessageV2('', 'get'); + var response = sm.execute(); + var response = sm.executeAsync(); + response.waitForResponse(60); + + var endpoint = sm.getEndpoint(); + var body = sm.getRequestBody(); + var header = sm.getRequestHeader('Accept'); + var headers = sm.getRequestHeaders(); + + sm.setBasicAuth('username', 'password'); + sm.setEccCorrelator('unique_identifier'); + sm.setEccParameter('source', 'http://very.long.endpoint.url'); + sm.setEndpoint('http://web.service.endpoint'); + sm.setHttpMethod('post'); + sm.setHttpTimeout(6000); + sm.setLogLevel('all'); + sm.setMIDServer('mid_server_name'); + sm.setMutualAuth('mutual_auth_profile_name'); + sm.setQueryParameter('sysparm_query', 'active=true^ORDERBYnumber^ORDERBYDESCcategory'); + sm.setRequestHeader('Accept', 'Application/json'); + sm.setStringParameter('s', 'NOW'); + sm.setStringParameterNoEscape('s', 'NOW'); + + var body = ''; + sm.setRequestBody(body); +})(); +(function sampleRESTMessageV2() { + try { + var request = new sn_ws.RESTMessageV2(); + request.setHttpMethod('get'); + + var attachment_sys_id = '', + tablename = 'incident', + recordSysId = '', + response, + httpResponseStatus, + filename = ''; + + //endpoint - ServiceNow REST Attachment API + request.setEndpoint( + 'https://.service-now.com/api/now/attachment/' + + attachment_sys_id + + '/file' + ); + request.setBasicAuth('', ''); + + //RESTMessageV2 - saveResponseBodyAsAttachment(String tableName, String recordSysId, String fileName) + request.saveResponseBodyAsAttachment(tablename, recordSysId, filename); + + response = request.execute(); + httpResponseStatus = response.getStatusCode(); + + gs.info(' http response status_code: ' + httpResponseStatus); + } catch (ex) { + var message = ex.getMessage(); + gs.info(message); + } +})(); +(function() { + var requestBody; + var response; + var responseBody; + var status; + var sm; + try { + // Might throw exception if message doesn't exist or not visible due to scope. + sm = new sn_ws.RESTMessageV2('', 'get'); + + //set auth profile to an OAuth 2.0 profile record. + sm.setAuthenticationProfile('oauth2', '1234adsf123212131123qasdsf'); + + sm.setStringParameter('symbol', 'NOW'); + sm.setStringParameterNoEscape('xml_data', 'test'); + + //In milliseconds. Wait at most 10 seconds for response from http request. + sm.setHttpTimeout(10000); + //Might throw exception if http connection timed out or some issue + //with sending request itself because of encryption/decryption of password. + response = sm.execute(); + responseBody = response.haveError() ? response.getErrorMessage() : response.getBody(); + status = response.getStatusCode(); + } catch (ex) { + responseBody = ex.getMessage(); + status = '500'; + } finally { + requestBody = sm ? sm.getRequestBody() : null; + } +})(); +(function sampleRESTMessageV2() { + try { + var request = new sn_ws.RESTMessageV2(); + request.setHttpMethod('post'); + request.setEndpoint(''); + request.setRequestBodyFromAttachment(''); + + var response = request.execute(); + var httpResponseStatus = response.getStatusCode(); + + gs.info('http response status_code: ' + httpResponseStatus); + } catch (ex) { + var message = ex.getMessage(); + gs.info(message); + } +})(); diff --git a/types/servicenow-london/test/RESTResponseV2.ts b/types/servicenow-london/test/RESTResponseV2.ts new file mode 100644 index 0000000000..79ede22cc4 --- /dev/null +++ b/types/servicenow-london/test/RESTResponseV2.ts @@ -0,0 +1,22 @@ +(function() { + var sm = new sn_ws.RESTMessageV2('
', 'get'); + var response = sm.execute(); + var allHeaders = response.getAllHeaders(); + for (var header in allHeaders) { + gs.info(allHeaders[header].name + ': ' + allHeaders[header].value); + } + var cookies = response.getCookies(); + for (var i = 0; i < cookies.size(); i++) { + gs.info('cookie: ' + cookies.get(i)); + } + var responseBody = response.getBody(); + var errorCode = response.getErrorCode(); + var errorMsg = response.getErrorMessage(); + var headerVal = response.getHeader('Content-Type'); + var headers = response.getHeaders(); + var queryString = response.getQueryString(); + var statusCode = response.getStatusCode(); + var error = response.haveError(); + var response = sm.executeAsync(); + response.waitForResponse(60); +})(); diff --git a/types/servicenow-london/test/SOAPMessageV2.ts b/types/servicenow-london/test/SOAPMessageV2.ts new file mode 100644 index 0000000000..5181a9be3b --- /dev/null +++ b/types/servicenow-london/test/SOAPMessageV2.ts @@ -0,0 +1,28 @@ +(function() { + var sm = new sn_ws.SOAPMessageV2(); + sm = new sn_ws.SOAPMessageV2('StockQuote', 'GetQuote'); + var response = sm.execute(); + response = sm.executeAsync(); + var endpoint = sm.getEndpoint(); + var requestBody = sm.getRequestBody(); + var header = sm.getRequestHeader('Accept'); + var requestHeaders = sm.getRequestHeaders(); + sm.setBasicAuth('username', 'password'); + sm.setEccCorrelator('unique_id'); + sm.setEccParameter('source', 'http://very.long.endpoint'); + sm.setEndpoint('http://web.service.endpoint'); + sm.setHttpTimeout(6000); + sm.setMutualAuth('auth_profile_name'); + var body = ''; + sm.setRequestBody(body); + sm.setRequestHeader('Accept', 'Application/json'); + sm.setSOAPAction('GetQuote'); + sm.setStringParameter('symbol', 'NOW'); + sm.setStringParameterNoEscape('symbol', 'NOW'); + sm.setWSSecurity( + '70d65e074f3812001f6eac118110c71a', + 'Quote keys', + 'UXr82cqX75Z7MaSa+EyjGA==', + 'ba969a074f3812001f6eac118110c76d' + ); +})(); diff --git a/types/servicenow-london/test/SOAPResponseV2.ts b/types/servicenow-london/test/SOAPResponseV2.ts new file mode 100644 index 0000000000..c7a4c181a3 --- /dev/null +++ b/types/servicenow-london/test/SOAPResponseV2.ts @@ -0,0 +1,20 @@ +(function() { + var r = new sn_ws.SOAPMessageV2('', 'get'); + var response = r.execute(); + var allHeaders = response.getAllHeaders(); + for (var h in allHeaders) { + gs.info(allHeaders[h].name + ': ' + allHeaders[h].value); + } + var body = response.getBody(); + var cookies = response.getCookies(); + for (var i = 0; i < cookies.size(); i++) { + gs.info('cookie: ' + cookies.get(i)); + } + var errorCode = response.getErrorCode(); + var errorMsg = response.getErrorMessage(); + var headerVal = response.getHeader("Accept"); + var headers = response.getHeaders(); + var statusCode = response.getStatusCode(); + var error = response.haveError(); + response.waitForResponse(60); +})(); diff --git a/types/servicenow-london/test/ScopedElementDescriptor.ts b/types/servicenow-london/test/ScopedElementDescriptor.ts new file mode 100644 index 0000000000..a0da98ba85 --- /dev/null +++ b/types/servicenow-london/test/ScopedElementDescriptor.ts @@ -0,0 +1,19 @@ +(function() { + var gr = new GlideRecord('incident'); + gr.query('priority', '1'); + var field = gr.getElement('priority'); + var ed = field.getED(); + + var s = ed.getAttachmentEncryptionType(); + s = ed.getEncryptionType(); + s = ed.getInternalType(); + s = ed.getLabel(); + var n = ed.getLength(); + s = ed.getName(); + s = ed.getPlural(); + var b = ed.hasAttachmentsEncrypted(); + b = ed.isAutoOrSysID(); + b = ed.isChoiceTable(); + b = ed.isEdgeEncrypted(); + b = ed.isVirtual(); +})(); diff --git a/types/servicenow-london/test/ScopedGlideElement.ts b/types/servicenow-london/test/ScopedGlideElement.ts new file mode 100644 index 0000000000..8d749d848e --- /dev/null +++ b/types/servicenow-london/test/ScopedGlideElement.ts @@ -0,0 +1,13 @@ +(function() { + var gr = new GlideRecord('incident'); + var el = gr.getElement('active'); + var b = el.changes(); + b = el.changesFrom(true); + b = el.changesTo(false); + var s = el.getAttribute('tree_picker'); + var sa = el.getChoices(); + s = el.getChoiceValue(); + s = el.getDecryptedValue(); + s = el.getDisplayValue(); + var ed = el.getED(); +})(); diff --git a/types/servicenow-london/test/ScopedGlideRecord.ts b/types/servicenow-london/test/ScopedGlideRecord.ts new file mode 100644 index 0000000000..d2a2ed715a --- /dev/null +++ b/types/servicenow-london/test/ScopedGlideRecord.ts @@ -0,0 +1,400 @@ +interface ScopedGlideRecord { + new (tableName: 'othertype'): OtherType; +} +interface OtherType extends ScopedGlideRecord { + someproperty: string; +} +(function testMerging() { + var gr = new GlideRecord('othertype'); + gr.someproperty = 'foo'; +})(); +(function() { + var inc = new GlideRecord('incident'); + inc.addActiveQuery(); + inc.query(); +})(); +(function() { + var queryString = 'priority=1^ORpriority=2'; + var gr = new GlideRecord('incident'); + gr.addEncodedQuery(queryString); + gr.query(); + while (gr.next()) { + gs.addInfoMessage(gr.number); + } +})(); +(function() { + var functionBuilder = new GlideDBFunctionBuilder(); + var myAddingFunction = functionBuilder.add(); + myAddingFunction = functionBuilder.field('order'); + myAddingFunction = functionBuilder.field('priority'); + var func = functionBuilder.build(); + + var gr = new GlideRecord('incident'); + gr.addFunction(func); + gr.addQuery(func, '<', 5); + gr.query(); + while (gr.next()) gs.info(gr.getValue(func)); +})(); +(function() { + var prob = new GlideRecord('problem'); + prob.addJoinQuery('incident'); + prob.query(); +})(); +(function() { + // Look for Problem records that have associated Incident records + var gr = new GlideRecord('problem'); + var grSQ = gr.addJoinQuery('incident'); + + // Where the Problem records are "active=false" + gr.addQuery('active', 'false'); + + // And the Incident records are "active=true" + grSQ.addCondition('active', 'true'); + + // Query + gr.query(); + + // Iterate and output results + while (gr.next()) { + gs.info(gr.getValue('number')); + } +})(); +(function() { + var gr = new GlideRecord('problem'); + gr.addJoinQuery('incident', 'opened_by', 'caller_id'); + gr.query(); +})(); +(function() { + var target = new GlideRecord('incident'); + target.addNotNullQuery('short_description'); + target.query(); // Issue the query to the database to get all records where short_description is not null + while (target.next()) { + // add code here to process the incident record + } +})(); +(function() { + var target = new GlideRecord('incident'); + target.addNullQuery('short_description'); + target.query(); // Issue the query to the database to get all records where short_description is null + while (target.next()) { + // add code here to process the incident record + } +})(); +(function() { + var rec = new GlideRecord('incident'); + rec.addQuery('active', true); + rec.query(); + while (rec.next()) { + rec.active = false; + gs.info('Active incident ' + rec.number + ' closed'); + rec.update(); + } +})(); +(function() { + var rec = new GlideRecord('incident'); + rec.addQuery('active', true); + rec.addQuery('sys_created_on', '>', '2010-01-19 04:05:00'); + rec.query(); + while (rec.next()) { + rec.active = false; + gs.info('Active incident ' + rec.number + ' closed'); + rec.update(); + } +})(); +(function() { + var gr = new GlideRecord('incident'); + gr.addQuery('number', 'IN', 'INC00001,INC00002'); + gr.query(); + while (gr.next()) { + //do something.... + } +})(); +(function() { + var rec = new GlideRecord('incident'); + rec.addQuery('active=true'); + rec.query(); + while (rec.next()) { + rec.active = false; + gs.info('Active incident ' + rec.number + ' closed'); + rec.update(); + } +})(); +(function() { + var gr = new GlideRecord('incident'); + gs.info(gr.canCreate()); + gs.info(gr.canDelete()); + gs.info(gr.canRead()); + gs.info(gr.canWrite()); +})(); +(function() { + var gr = new GlideRecord('incident'); + gr.orderBy('number'); + gr.chooseWindow(2, 4); + gr.query(); + if (gr.next()) { + gs.info(gr.number + ' is within window'); + } +})(); +(function() { + var inc = new GlideRecord('incident'); + inc.get('17c90efb13418700cc36b1422244b05d'); + gs.info(inc.calendar_duration.dateNumericValue()); +})(); +(function() { + var gr = new GlideRecord('incident'); + gr.addQuery('active', 'false'); //to delete all inactive incidents + gr.deleteMultiple(); +})(); +(function() { + var gr = new GlideRecord('incident'); + //to delete one record + if (gr.get('99ebb4156fa831005be8883e6b3ee4b9')) { + gr.deleteRecord(); + } +})(); +(function() { + var grIncident = new GlideRecord('incident'); + var returnValue = grIncident.get('99ebb4156fa831005be8883e6b3ee4b9'); + gs.info(returnValue); // logs true or false + gs.info(grIncident.number); // logs Incident Number +})(); +(function() { + var grIncident = new GlideRecord('incident'); + var returnValue = grIncident.get('caller_id.name', 'Sylivia Wayland'); + gs.info(returnValue); // logs true or false + gs.info(grIncident.number); // logs Incident Number +})(); +doit(); +function doit() { + var gr = new GlideRecord('sys_user'); + gr.query('user_name', 'admin'); + if (gr.next()) { + gs.info('we got one'); + gs.info(gr.location.getAttribute('tree_picker')); + } +} +(function() { + var gr = new GlideRecord('incident'); + gr.get('sys_id', 'ef43c6d40a0a0b5700c77f9bf387afe3'); + gs.info(gr.getDisplayValue()); +})(); +(function() { + var gr = new GlideRecord('incident'); + var ed = gr.getED(); + gs.info(ed.getLabel()); +})(); +(function() { + var elementName = 'short_description'; + var gr = new GlideRecord('incident'); + gr.initialize(); + gr.setValue(elementName, 'My DB is not working'); + gr.insert(); + gs.info(gr.getElement('short_description')); +})(); +(function() { + var gr = new GlideRecord('incident'); + gr.addQuery('active', true); + gr.addQuery('priority', 1); + gr.query(); + var encodedQuery = gr.getEncodedQuery(); + gs.info(encodedQuery); +})(); +(function() { + var gr = new GlideRecord('incident'); + gs.info(gr.getLabel()); +})(); +(function() { + // Setup a data policy where short_description field in incident is mandatory + var gr = new GlideRecord('incident'); + gr.insert(); // insert without data in mandatory field + var errormessage = gr.getLastErrorMessage(); + gs.info(errormessage); +})(); +(function() { + var gr = new GlideRecord('incident'); + gr.addActiveQuery(); + gr.addQuery('priority', 1); + gr.query(); + gr.next(); + gs.info(gs.getProperty('glide.servlet.uri') + gr.getLink(false)); +})(); +(function() { + var gr = new GlideRecord('incident'); + var recordClassName = gr.getRecordClassName(); + gs.info(recordClassName); +})(); +(function() { + var gr = new GlideRecord('incident'); + gr.query(); + gs.info('Records in incident table: ' + gr.getRowCount()); +})(); +(function() { + var gr = new GlideRecord('incident'); + gs.info(gr.getTableName()); +})(); +(function() { + var gr = new GlideRecord('kb_knowledge'); + gr.query(); + gr.next(); + var uniqueid = gr.getUniqueValue(); + gs.info(uniqueid); +})(); +(function() { + var gr = new GlideRecord('incident'); + gr.orderBy('number'); + gr.query('active', 'true'); + gr.next(); + gs.info(gr.getValue('number')); +})(); +(function() { + var rec = new GlideRecord('incident'); + rec.query(); + if (rec.hasNext()) { + gs.info('Table is not empty'); + } +})(); +(function() { + var gr = new GlideRecord('incident'); + gr.initialize(); + gr.name = 'New Incident'; + gr.description = 'Incident description'; + gr.insert(); +})(); +(function() { + var gr = new GlideRecord('incident'); + gr.initialize(); + gr.name = 'New Incident'; + gr.description = 'Incident description'; + gr.insert(); +})(); +(function() { + var gr = new GlideRecord('incident'); + gs.info(gr.isActionAborted()); +})(); +(function() { + var gr = new GlideRecord('x_app_table'); + gr.newRecord(); // create a new record and populate it with default values + gs.info(gr.isNewRecord()); +})(); +(function() { + var gr = new GlideRecord('incident'); + gs.info(gr.isValid()); + var anotherGr = new GlideRecord('wrong_table_name'); + gs.info(anotherGr.isValid()); +})(); +(function() { + var gr = new GlideRecord('incident'); + gr.initialize(); + gs.info(gr.isValidField('short_description')); +})(); +(function() { + var rec = new GlideRecord('incident'); + rec.query(); + while (rec.next()) { + gs.info(rec.number + ' exists'); + } + gs.info(rec.isValidRecord()); +})(); +(function() { + var gr = new GlideRecord('x_app_table'); + gr.newRecord(); + gs.info(gr.isNewRecord()); +})(); +(function() { + var rec = new GlideRecord('incident'); + rec.query(); + while (rec.next()) { + gs.info(rec.number + ' exists'); + } +})(); +(function() { + //Commonly used in a business rule, returns insert if the current operation is insert + gs.info('current operation ' + current.operation()); +})(); +(function() { + var queryString = 'priority=2'; + var gr = new GlideRecord('incident'); + gr.orderBy('short_description'); // Ascending Order + gr.addEncodedQuery(queryString); + gr.query(); + while (gr.next()) { + gs.info(gr.short_description); + } +})(); +(function() { + var queryString = 'priority=2'; + var gr = new GlideRecord('incident'); + gr.orderByDesc('short_description'); //Descending Order + gr.addEncodedQuery(queryString); + gr.query(); + while (gr.next()) { + gs.info(gr.short_description); + } +})(); +(function() { + var rec = new GlideRecord('incident'); + rec.query(); + while (rec.next()) { + gs.info(rec.number + ' exists'); + } +})(); +(function() { + // Often used in business rule to check whether the current operation should be aborted. + if (current.size > 16) { + current.setAbortAction(true); + } +})(); +(function() { + var gr = new GlideRecord('incident'); + gr.orderByDesc('sys_created_on'); + gr.setLimit(10); + gr.query(); // this retrieves latest 10 incident records created +})(); +(function() { + var gr = new GlideRecord('incident'); + gr.short_description = 'The third floor printer is broken'; + gr.setNewGuidValue('eb4636ca6f6d31005be8883e6b3ee333'); + gr.insert(); + gs.info(gr.sys_id); +})(); +(function() { + var elementName = 'short_description'; + var gr = new GlideRecord('incident'); + gr.initialize(); + gr.setValue(elementName, 'My DB is not working'); + gr.insert(); +})(); +(function() { + //Enable business rules, scripts engines for x_app_table + var gr = new GlideRecord('x_app_table'); + gr.setWorkflow(true); +})(); +(function() { + var gr = new GlideRecord('incident'); + gr.get('99ebb4156fa831005be8883e6b3ee4b9'); + gr.short_description = 'Update the short description'; + gr.update(); + gs.info(gr.getElement('short_description')); +})(); +(function() { + // update the state of all active incidents to 4 - "Awaiting User Info" + var gr = new GlideRecord('incident'); + gr.addQuery('active', true); + gr.query(); + gr.setValue('state', 4); + gr.updateMultiple(); +})(); +(function() { + var rec = new GlideRecord('sys_template'); + rec.query(); + while (rec._next()) { + gs.info(rec.number + ' exists'); + } +})(); +(function() { + var rec = new GlideRecord('sys_app_module'); + rec._query(); + while (rec.next()) { + gs.info(rec.number + ' exists'); + } +})(); diff --git a/types/servicenow-london/test/ScopedQueryCondition.ts b/types/servicenow-london/test/ScopedQueryCondition.ts new file mode 100644 index 0000000000..3a818b966a --- /dev/null +++ b/types/servicenow-london/test/ScopedQueryCondition.ts @@ -0,0 +1,26 @@ +(function() { + var gr = new GlideRecord('incident'); + var qc = gr.addQuery('category', 'Hardware'); + qc.addCondition('category', 'Network'); + gr.addQuery('number', 'INC0000003'); + gr.next(); + gr.number; + gs.info(gr.getEncodedQuery()); +})(); +(function() { + var gr = new GlideRecord('incident'); + var qc = gr.addQuery('category', 'Hardware'); + qc.addOrCondition('category', 'Network'); + gr.addQuery('number', 'INC0000003'); + gr.next(); + gr.number; + gs.info(gr.getEncodedQuery()); +})(); +(function() { + var myObj = new GlideRecord('incident'); + var q1 = myObj.addQuery('state', '<', 3); + q1.addOrCondition('state', '>', 5); + var q2 = myObj.addQuery('priority', 1); + q2.addOrCondition('priority', 5); + myObj.query(); +})(); diff --git a/types/servicenow-london/test/Workflow.ts b/types/servicenow-london/test/Workflow.ts new file mode 100644 index 0000000000..bbe5710899 --- /dev/null +++ b/types/servicenow-london/test/Workflow.ts @@ -0,0 +1,134 @@ +(function() { + var gr = new GlideRecord('change_request'); + gr.get('8ecd7552db252200a6a2b31be0b8f581'); + + var wf = new global.Workflow(); + var grFlows = wf.getRunningFlows(gr); + while (grFlows.next()) { + wf.broadcastEvent(grFlows.sys_id, 'resume'); + } +})(); +(function() { + var gr = new GlideRecord('change_request'); + gr.get('8ecd7552db252200a6a2b31be0b8f581'); + + var wf = new global.Workflow(); + wf.cancel(gr); +})(); +(function() { + // If a workflow has started for this item, cancel it, where current is a task record with a workflow context + if (current.stage == 'Request Cancelled' && current.context && !current.context.nil()) { + var w = new global.Workflow(); + var gr = new GlideRecord('wf_context'); + + if (gr.get(current.context)) w.cancelContext(gr); + } +})(); +(function() { + var wkfw = new global.Workflow(); + wkfw.deleteWorkflow(current); +})(); +(function() { + // where current is a task record with a workflow context + var w = new global.Workflow(); + w.fireEvent(current, 'execute'); +})(); +(function() { + var wkfw = new global.Workflow(); + wkfw.fireEventById('f2400ec10b0a3c1c00ca5bb5c6fae427', 'Timer'); +})(); +(function() { + //where current is a task record with a workflow context + var wkfw = new global.Workflow(); + gs.info(wkfw.getContexts(current).started); +})(); +(function() { + var wkfw = new global.Workflow(); + gs.info(wkfw.getEstimatedDeliveryTime('b99a866a4a3623120074c033e005418f')); +})(); +(function() { + //where current is a task record with a workflow context + var wkfw = new global.Workflow(); + var context = wkfw.getContexts(current); + gs.info(wkfw.getEstimatedDeliveryTimeFromWFVersion(context.wf_version)); +})(); +(function() { + var gr = new GlideRecord('wf_context'); + gr.get('08a90c3adba52200a6a2b31be0b8f565'); + var wkfw = new global.Workflow(); + wkfw.getReturnValue(gr); +})(); +(function() { + //where current is a task record with a workflow context + var wf = new global.Workflow().getRunningFlows(current); + while (wf.next()) { + new global.Workflow().broadcastEvent(wf.sys_id, 'pause'); + } +})(); +(function() { + var wkfw = new global.Workflow(); + var gr = wkfw.getVersion('b99a866a4a3623120074c033e005418f'); +})(); +(function() { + var wkfw = new global.Workflow(); + var ge = wkfw.getVersionFromName('Emergency Change'); +})(); +(function() { + var wkfw = new global.Workflow(); + var s = wkfw.getWorkflowFromName('Emergency Change'); +})(); +(function() { + var gr = new GlideRecord('change_request'); + gr.get('cecdb552db252200a6a2b31be0b8f50b'); + var wkfw = new global.Workflow(); + gs.info(wkfw.hasWorkflow(gr)); +})(); +(function() { + var gr = new GlideRecord('change_request'); + gr.get('cecdb552db252200a6a2b31be0b8f50b'); + new global.Workflow().restartWorkflow(gr); +})(); +(function() { + var gr = new GlideRecord('change_request'); + gr.get('cecdb552db252200a6a2b31be0b8f50b'); + var wkfw = new global.Workflow(); + wkfw.runFlows(gr, 'update'); +})(); +(function() { + ////where current is a task record with a workflow context + var w = new global.Workflow(); + var context = w.startFlow('sys_id', current, current.operation(), {}); +})(); +(function() { + //where current is a task record with a workflow context + current.name = current.workflow_version.name; + current.started_by.setValue(gs.getUserID()); + + if (gs.nil(current.id)) { + var gr = new GlideRecord('wf_workflow_execution'); + gr.name = current.name; + gr.insert(); + + current.table = 'wf_workflow_execution'; + current.id = gr.sys_id; + } + + var wf = new global.Workflow(); + wf.startFlowFromContextInsert(current, current.operation()); +})(); +(function() { + var id = 'sys_id'; + // is this a retroactive start? + ////where current is a task record with a workflow context + var msecs = + new GlideDateTime().getNumericValue() - + current.start_time.getGlideObject().getNumericValue(); + + // treat this as a retroactive workflow start if the SLA started more than 5 seconds ago + var w = new global.Workflow(); + if (msecs <= 5000) w.startFlow(id, current, current.operation()); + else w.startFlowRetroactive(id, msecs, current, current.operation()); + + // update the record in case the workflow changed some values + current.update(); +})(); diff --git a/types/servicenow-london/test/XMLDocument2.ts b/types/servicenow-london/test/XMLDocument2.ts new file mode 100644 index 0000000000..5ef77cc906 --- /dev/null +++ b/types/servicenow-london/test/XMLDocument2.ts @@ -0,0 +1,153 @@ +(function() { + var xmlString = + '' + + ' ' + + ' abcd1234' + + ' 1234abcd' + + ' another' + + ' ' + + ' 1234' + + ''; + var xmlDoc = new XMLDocument2(); + xmlDoc.parseXML(xmlString); + xmlDoc.createElement('new2'); + + gs.info(xmlDoc); +})(); +(function() { + var xmlString = + '' + + ' ' + + ' abcd1234' + + ' 1234abcd' + + ' another' + + ' ' + + ' 1234' + + ''; + var xmlDoc = new XMLDocument2(); + xmlDoc.parseXML(xmlString); + xmlDoc.createElementWithTextValue('new', 'test'); + gs.info(xmlDoc); +})(); +(function() { + var xmlString = + '' + + ' ' + + ' abcd1234' + + ' 1234abcd' + + ' another' + + ' ' + + ' 1234' + + ''; + var xmlDoc = new XMLDocument2(); + xmlDoc.parseXML(xmlString); + //returns the root node of the document tree. + var rootNode = xmlDoc.getDocumentElement(); + gs.info(rootNode.getTextContent()); +})(); +(function() { + var xmlString = + '' + + ' ' + + ' abcd1234' + + ' 1234abcd' + + ' another' + + ' ' + + ' 1234' + + ''; + var xmlDoc = new XMLDocument2(); + xmlDoc.parseXML(xmlString); + var foo = xmlDoc.getFirstNode('/test/one/two'); + gs.info(foo.getTextContent()); +})(); +(function() { + var xmlString = + '' + + ' ' + + ' abcd1234' + + ' 1234abcd' + + ' another' + + ' ' + + ' 1234' + + ''; + var xmlDoc = new XMLDocument2(); + xmlDoc.parseXML(xmlString); + var foo = xmlDoc.getFirstNode('/test/one/two'); + var foo2 = xmlDoc.getNextNode(foo); + gs.info(foo.getTextContent()); + gs.info(foo2.getTextContent()); +})(); +(function() { + var xmlString = + '' + + ' ' + + ' abcd1234' + + ' 1234abcd' + + ' another' + + ' ' + + ' 1234' + + ''; + var xmlDoc = new XMLDocument2(); + xmlDoc.parseXML(xmlString); + var node = xmlDoc.getNode('/test/one/two'); + gs.info(node); +})(); +(function() { + var xmlString = + '' + + ' ' + + ' abcd1234' + + ' 1234abcd' + + ' another' + + ' ' + + ' 1234' + + ''; + var xmlDoc = new XMLDocument2(); + xmlDoc.parseXML(xmlString); + gs.info(xmlDoc.getNodeText('//two')); +})(); +(function() { + var xmlString = + '' + + ' ' + + ' abcd1234' + + ' 1234abcd' + + ' another' + + ' ' + + ' 1234' + + ''; + var xmlDoc = new XMLDocument2(); + xmlDoc.parseXML(xmlString); + var rootNode = xmlDoc.getDocumentElement(); +})(); +(function() { + var xmlString = + '' + + ' ' + + ' abcd1234' + + ' 1234abcd' + + ' another' + + ' ' + + ' 1234' + + ''; + var xmlDoc = new XMLDocument2(); + xmlDoc.parseXML(xmlString); + //returns the root node of the document tree. + var rootNode = xmlDoc.getDocumentElement(); //returns org.w3c.dom.Element + // sets the root node as the current element + xmlDoc.setCurrentElement(rootNode); +})(); +(function() { + var xmlString = + '' + + ' ' + + ' abcd1234' + + ' 1234abcd' + + ' another' + + ' ' + + ' 1234' + + ''; + var xmlDoc = new XMLDocument2(); + xmlDoc.parseXML(xmlString); + gs.info(xmlDoc.toString()); +})(); diff --git a/types/servicenow-london/test/XMLNode.ts b/types/servicenow-london/test/XMLNode.ts new file mode 100644 index 0000000000..a5db5cd6ed --- /dev/null +++ b/types/servicenow-london/test/XMLNode.ts @@ -0,0 +1,137 @@ +(function() { + var xmlString = + '' + + ' ' + + ' abcd1234' + + ' 1234abcd' + + ' another' + + ' ' + + ' 1234' + + ''; + var xmlDoc = new XMLDocument2(); + xmlDoc.parseXML(xmlString); + var node = xmlDoc.getNode('//two'); + gs.info(node.getAttribute('att')); +})(); +(function() { + var xmlString = + '' + + ' ' + + ' abcd1234' + + ' 1234abcd' + + ' another' + + ' ' + + ' 1234' + + ''; + var xmlDoc = new XMLDocument2(); + xmlDoc.parseXML(xmlString); + var node = xmlDoc.getNode('//one'); + var iter = node.getChildNodeIterator(); + gs.info(iter.hasNext()); +})(); +(function() { + var xmlString = + '' + + '' + + 'abcd1234' + + '1234abcd' + + 'another' + + '' + + '1234' + + ''; + var xmlDoc = new XMLDocument2(); + xmlDoc.parseXML(xmlString); + var node = xmlDoc.getNode('//one'); + gs.info(node.getFirstChild()); +})(); +(function() { + var xmlString = + '' + + '' + + 'abcd1234' + + '1234abcd' + + 'another' + + '' + + '1234' + + ''; + var xmlDoc = new XMLDocument2(); + xmlDoc.parseXML(xmlString); + var node = xmlDoc.getNode('//one'); + + gs.info(node.getLastChild()); +})(); +(function() { + var xmlString = + '' + + ' ' + + ' abcd1234' + + ' 1234abcd' + + ' another' + + ' ' + + ' 1234' + + ''; + var xmlDoc = new XMLDocument2(); + xmlDoc.parseXML(xmlString); + var node = xmlDoc.getNode('//two'); + gs.info(node.getNodeName()); +})(); +(function() { + var xmlString = + '' + + ' ' + + ' abcd1234' + + ' 1234abcd' + + ' another' + + ' ' + + ' 1234' + + ''; + var xmlDoc = new XMLDocument2(); + xmlDoc.parseXML(xmlString); + var node = xmlDoc.getNode('//two'); + gs.info(node.getNodeValue()); +})(); +(function() { + var xmlString = + '' + + ' ' + + ' abcd1234' + + ' 1234abcd' + + ' another' + + ' ' + + ' 1234' + + ''; + var xmldoc = new XMLDocument2(); + xmldoc.parseXML(xmlString); + var node = xmldoc.getNode('//one/two'); + gs.info(node.getTextContent()); +})(); +(function() { + var xmlString = + '' + + ' ' + + ' abcd1234' + + ' 1234abcd' + + ' another' + + ' ' + + ' 1234' + + ''; + var xmlDoc = new XMLDocument2(); + xmlDoc.parseXML(xmlString); + var node = xmlDoc.getNode('//two'); + gs.info(node.hasAttribute('att')); +})(); +(function() { + var xmlString = + '' + + ' ' + + ' abcd1234' + + ' 1234abcd' + + ' another' + + ' ' + + ' 1234' + + ''; + var xmlDoc = new XMLDocument2(); + xmlDoc.parseXML(xmlString); + var node = xmlDoc.getNode('//one'); + gs.info(node.toString()); +})(); diff --git a/types/servicenow-london/test/XMLNodeIterator.ts b/types/servicenow-london/test/XMLNodeIterator.ts new file mode 100644 index 0000000000..50e58e8f83 --- /dev/null +++ b/types/servicenow-london/test/XMLNodeIterator.ts @@ -0,0 +1,36 @@ +(function() { + var xmlString = + '' + + ' ' + + ' abcd1234' + + ' 1234abcd' + + ' another' + + ' ' + + ' 1234' + + ''; + var xmlDoc = new XMLDocument2(); + xmlDoc.parseXML(xmlString); + var node = xmlDoc.getNode('//one'); + var iter = node.getChildNodeIterator(); + gs.info(iter.hasNext()); +})(); +(function() { + var xmlString = + '' + + ' ' + + ' abcd1234' + + ' 1234abcd' + + ' another' + + ' ' + + ' 1234' + + ''; + var xmlDoc = new XMLDocument2(); + xmlDoc.parseXML(xmlString); + var node = xmlDoc.getNode('//one'); + var iter = node.getChildNodeIterator(); + while (iter.hasNext()) { + var n = iter.next(); + gs.info('Node name: ' + n.getNodeName()); + gs.info('Node value: ' + n.getNodeValue()); + } +})(); diff --git a/types/servicenow-london/tsconfig.json b/types/servicenow-london/tsconfig.json new file mode 100644 index 0000000000..53dd1d713d --- /dev/null +++ b/types/servicenow-london/tsconfig.json @@ -0,0 +1,97 @@ +{ + "compilerOptions": { + "lib": ["es5"], + "module": "commonjs", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + + "Class.d.ts", + "GlideDate.d.ts", + "GlideDateTime.d.ts", + "GlideDBFunctionBuilder.d.ts", + "GlideDuration.d.ts", + "GlideEmailOutbound.d.ts", + "GlideFilter.d.ts", + "GlideLocale.d.ts", + "GlidePluginManager.d.ts", + "GlideRecordOperation.d.ts", + "GlideSchedule.d.ts", + "GlideScopedEvaluator.d.ts", + "GlideScriptedProcessor.d.ts", + "GlideSecureRandomUtil.d.ts", + "GlideServletRequest.d.ts", + "GlideServletResponse.d.ts", + "GlideSession.d.ts", + "GlideStringUtil.d.ts", + "GlideSysAttachment.d.ts", + "GlideSystem.d.ts", + "GlideTime.d.ts", + "GlideUser.d.ts", + "QueryOperator.d.ts", + "RenderProperties.d.ts", + "RESTAPIRequest.d.ts", + "RESTAPIRequestBody.d.ts", + "RESTAPIResponse.d.ts", + "RESTAPIResponseStream.d.ts", + "RESTMessageV2.d.ts", + "RESTResponseV2.d.ts", + "ScopedElementDescriptor.d.ts", + "ScopedGlideElement.d.ts", + "ScopedGlideRecord.d.ts", + "ScopedQueryCondition.d.ts", + "SOAPMessageV2.d.ts", + "SOAPResponseV2.d.ts", + "Workflow.d.ts", + "XMLDocument2.d.ts", + "XMLNode.d.ts", + "XMLNodeIterator.d.ts", + + "test/Class.ts", + "test/GlideDate.ts", + "test/GlideDateTime.ts", + "test/GlideDBFunctionBuilder.ts", + "test/GlideDuration.ts", + "test/GlideEmailOutbound.ts", + "test/GlideFilter.ts", + "test/GlideLocale.ts", + "test/GlidePluginManager.ts", + "test/GlideSchedule.ts", + "test/GlideScopedEvaluator.ts", + "test/GlideScriptedProcessor.ts", + "test/GlideSecureRandomUtil.ts", + "test/GlideServletRequest.ts", + "test/GlideServletResponse.ts", + "test/GlideSession.ts", + "test/GlideStringUtil.ts", + "test/GlideSysAttachment.ts", + "test/GlideSystem.ts", + "test/GlideTime.ts", + "test/GlideUser.ts", + "test/RESTAPIRequest.ts", + "test/RESTAPIRequestBody.ts", + "test/RESTAPIResponse.ts", + "test/RESTAPIResponseStream.ts", + "test/RESTMessageV2.ts", + "test/RESTResponseV2.ts", + "test/ScopedElementDescriptor.ts", + "test/ScopedGlideElement.ts", + "test/ScopedGlideRecord.ts", + "test/ScopedQueryCondition.ts", + "test/SOAPMessageV2.ts", + "test/SOAPResponseV2.ts", + "test/Workflow.ts", + "test/XMLDocument2.ts", + "test/XMLNode.ts", + "test/XMLNodeIterator.ts" + ] +} diff --git a/types/servicenow-london/tslint.json b/types/servicenow-london/tslint.json new file mode 100644 index 0000000000..1e1f71979b --- /dev/null +++ b/types/servicenow-london/tslint.json @@ -0,0 +1,12 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // Interface is needed for merging GlideRecord types + "no-misused-new": false, + // Disabling to all separate JSDoc per signature to correspond with ServiceNow API docs + "unified-signatures": false + }, + "linterOptions": { + "exclude": ["test/*.ts"] + } +} From 6e9e2d4eaa2e2650e79a3dbeae6fb4c37b9a4812 Mon Sep 17 00:00:00 2001 From: codert Date: Mon, 25 Mar 2019 13:56:37 +0800 Subject: [PATCH 051/710] fix: setElement type definition --- types/fabric/fabric-impl.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 96034c0b5f..cd52bd54e5 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -2212,10 +2212,10 @@ export class Image { * Sets image element for this instance to a specified one. * If filters defined they are applied to new image. * You might need to call `canvas.renderAll` and `object.setCoords` after replacing, to render new image and update controls area. - * @param [callback] Callback is invoked when all filters have been applied and new image is generated + * @param element image element * @param [options] Options object */ - setElement(element: HTMLImageElement, callback: Function, options: IImageOptions): Image; + setElement(element: HTMLImageElement, options?: IImageOptions): Image; /** * Delete a single texture if in webgl mode */ From d698a46d37bb59a8747160e717e375d1ab61e0a9 Mon Sep 17 00:00:00 2001 From: codert Date: Mon, 25 Mar 2019 14:11:46 +0800 Subject: [PATCH 052/710] chore: add definitions by --- types/fabric/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/fabric/index.d.ts b/types/fabric/index.d.ts index 3897987589..7444f481b8 100644 --- a/types/fabric/index.d.ts +++ b/types/fabric/index.d.ts @@ -9,6 +9,7 @@ // Bradley Hill // Bryan Krol // Glenn Gartner +// Codertx // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 export import fabric = require("./fabric-impl"); From 0ff72beea9b70a7fa54b247e22d1846be12f7792 Mon Sep 17 00:00:00 2001 From: Flexmonster Date: Mon, 25 Mar 2019 10:45:07 +0200 Subject: [PATCH 053/710] Fix customData & sortingMethod --- types/flexmonster/index.d.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/flexmonster/index.d.ts b/types/flexmonster/index.d.ts index 6d92a20ddc..dbf42871dd 100644 --- a/types/flexmonster/index.d.ts +++ b/types/flexmonster/index.d.ts @@ -130,7 +130,7 @@ declare namespace Flexmonster { showCharts(type?: string, multiple?: boolean): void; showGrid(): void; showGridAndCharts(type?: string, position?: string, multiple?: boolean): void; - sortingMethod(hierarchyName: string, compareFunction: (a: string, b: string) => boolean): void; + sortingMethod(hierarchyName: string, compareFunction: (a: string, b: string) => number): void; sortValues(axisName: string, type: string, tuple: number[], measure: MeasureObject): void; toolbar: Toolbar; updateData(object: DataSource | object[]): void; @@ -186,7 +186,7 @@ declare namespace Flexmonster { roles?: string; localeIdentifier?: string; effectiveUserName?: string; - customData?: string; + customData?: object; hash?: string; username?: string; password?: string; From 1dfa3d1eaae1bc71b413f7bf62196232bc6159e6 Mon Sep 17 00:00:00 2001 From: Flexmonster Date: Mon, 25 Mar 2019 11:05:35 +0200 Subject: [PATCH 054/710] Revert customData --- types/flexmonster/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/flexmonster/index.d.ts b/types/flexmonster/index.d.ts index 9c43b0a57d..2854b19a81 100644 --- a/types/flexmonster/index.d.ts +++ b/types/flexmonster/index.d.ts @@ -186,7 +186,7 @@ declare namespace Flexmonster { roles?: string; localeIdentifier?: string; effectiveUserName?: string; - customData?: object; + customData?: string; hash?: string; username?: string; password?: string; From 40caec87f13272f32169ea35f1addd1372ccd831 Mon Sep 17 00:00:00 2001 From: Leo Chen Date: Mon, 25 Mar 2019 21:41:36 +1100 Subject: [PATCH 055/710] Set parameters to optional on filter.applyTo() --- types/ckeditor/ckeditor-tests.ts | 1 + types/ckeditor/index.d.ts | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/types/ckeditor/ckeditor-tests.ts b/types/ckeditor/ckeditor-tests.ts index 1321d5b83d..13f6268d9d 100644 --- a/types/ckeditor/ckeditor-tests.ts +++ b/types/ckeditor/ckeditor-tests.ts @@ -620,6 +620,7 @@ function test_filter() { allowed = filter.allow('rule', 'name', false); var apply: boolean = filter.applyTo(CKEDITOR.htmlParser.fragment.fromHtml('string'), true, false, 1); + apply = filter.applyTo(new CKEDITOR.htmlParser.element('name', null)); apply = filter.applyTo(new CKEDITOR.htmlParser.element('name', null), true, false, 1); var checked: boolean = filter.check(style); diff --git a/types/ckeditor/index.d.ts b/types/ckeditor/index.d.ts index 3d35877b9d..bf2d51b3db 100644 --- a/types/ckeditor/index.d.ts +++ b/types/ckeditor/index.d.ts @@ -1436,7 +1436,7 @@ declare namespace CKEDITOR { addFeature(feature: feature): boolean; addTransformations(transformations: Array>): void; allow(newRules: filter.allowedContentRules, featureName?: string, overrideCustom?: boolean): boolean; - applyTo(fragment: htmlParser.fragment | htmlParser.element, toHrml: boolean, transformOnly: boolean, enterMode: number): boolean; + applyTo(fragment: htmlParser.fragment | htmlParser.element, toHtml?: boolean, transformOnly?: boolean, enterMode?: number): boolean; check(test: filter.contentRule, applyTransformations?: boolean, strictCheck?: boolean): boolean; checkFeature(feature: feature): boolean; clone(): filter; From 242fc8cb640db948cbae0ecb4c7df3b5c4181554 Mon Sep 17 00:00:00 2001 From: Ryo Ota Date: Tue, 26 Mar 2019 00:02:23 +0900 Subject: [PATCH 056/710] Add a description about asOfVersion in "Removing a package" --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b50272dbf4..9c52808682 100644 --- a/README.md +++ b/README.md @@ -169,7 +169,7 @@ When a package [bundles](http://www.typescriptlang.org/docs/handbook/declaration You can remove it by running `npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [libraryName]`. - `typingsPackageName`: This is the name of the directory to delete. -- `asOfVersion`: A stub will be published to `@types/foo` with this version. Should be higher than any currently published version. +- `asOfVersion`: A stub will be published to `@types/foo` with this version. Should be higher than any currently published version, and should be a version of `foo` on npm. - `sourceRepoURL`: This should point to the repository that contains the typings. - `libraryName`: Name of npm package that replaces the Definitely Typed types. Usually this is identical to "typingsPackageName", in which case you can omit it. From ca0bad23e6aecd259c924ed728772c932197af71 Mon Sep 17 00:00:00 2001 From: Bert Verhelst Date: Mon, 25 Mar 2019 16:15:17 +0100 Subject: [PATCH 057/710] Attempts are passed to onRetry function https://github.com/zeit/async-retry/blob/master/lib/index.js#L33 --- types/async-retry/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/async-retry/index.d.ts b/types/async-retry/index.d.ts index 6b50c71b63..992b78ddcc 100644 --- a/types/async-retry/index.d.ts +++ b/types/async-retry/index.d.ts @@ -16,7 +16,7 @@ declare namespace AsyncRetry { minTimeout?: number; maxTimeout?: number; randomize?: boolean; - onRetry?: (e: Error) => any; + onRetry?: (e: Error, attempt: number) => any; } type RetryFunction = (bail: (e: Error) => void, attempt: number) => A|Promise; From 54bc43d1d82ac9487d88816c949be69b798a2f7a Mon Sep 17 00:00:00 2001 From: Bert Verhelst Date: Mon, 25 Mar 2019 16:16:29 +0100 Subject: [PATCH 058/710] Update version number --- types/async-retry/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/async-retry/index.d.ts b/types/async-retry/index.d.ts index 992b78ddcc..8c66a2f370 100644 --- a/types/async-retry/index.d.ts +++ b/types/async-retry/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for async-retry 1.2 +// Type definitions for async-retry 1.2.1 // Project: https://github.com/zeit/async-retry#readme // Definitions by: Albert Wu // Pablo Rodríguez From 0c90b7a9afad60d9f6b0b0e1edba8c5a7c389301 Mon Sep 17 00:00:00 2001 From: Matthias Kunnen Date: Mon, 25 Mar 2019 17:51:25 +0100 Subject: [PATCH 059/710] [stripe] Updated create and update invoice --- types/stripe/index.d.ts | 115 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 112 insertions(+), 3 deletions(-) diff --git a/types/stripe/index.d.ts b/types/stripe/index.d.ts index 2a93740f3f..53298c1eb4 100644 --- a/types/stripe/index.d.ts +++ b/types/stripe/index.d.ts @@ -2223,16 +2223,74 @@ declare namespace Stripe { */ application_fee?: number; + /** + * Controls whether Stripe will perform + * [automatic collection](https://stripe.com/docs/billing/invoices/workflow/#auto_advance) + * of the invoice. When `false`, the invoice’s state will not automatically advance + * without an explicit action. + */ + auto_advance?: boolean; + + /** + * Either `charge_automatically`, or `send_invoice`. When charging automatically, Stripe + * will attempt to pay this invoice using the default source attached to the customer. + * When sending an invoice, Stripe will email this invoice to the customer with payment + * instructions. Defaults to charge_automatically. + */ + billing?: 'charge_automatically' | 'send_invoice'; + + /** + * A list of up to 4 custom fields to be displayed on the invoice. + */ + custom_fields?: Array<{ + /** + * The name of the custom field. This may be up to 30 characters. + */ + name: string; + + /** + * The value of the custom field. This may be up to 30 characters. + */ + value: string; + }>; + + /** + * The number of days from when the invoice is created until it is due. Valid only for + * invoices where `billing=send_invoice`. + */ + days_until_due?: number; + + /** + * ID of the default payment source for the invoice. It must belong to the customer + * associated with the invoice and be in a chargeable state. If not set, defaults to the + * subscription’s default source, if any, or to the customer’s default source. + */ + default_source?: string; + description?: string; + /** + * The date on which payment for this invoice is due. Valid only for invoices where + * `billing=send_invoice`; + */ + due_date?: Date | number; + + /** + * Footer to be displayed on the invoice. This can be unset by updating the value to + * `null` and then saving. + */ + footer?: string | null; + /** * Extra information about a charge for the customer’s credit card statement. */ statement_descriptor?: string; /** - * The ID of the subscription to invoice. If not set, the created invoice will include all pending invoice items for - * the customer. If set, the created invoice will exclude pending invoice items that pertain to other subscriptions. + * The ID of the subscription to invoice, if any. If not set, the created invoice will + * include all pending invoice items for the customer. If set, the created invoice will + * exclude pending invoice items that pertain to other subscriptions. The subscription’s + * billing cycle and regular subscription events won’t be affected. */ subscription?: string; @@ -2250,13 +2308,61 @@ declare namespace Stripe { */ application_fee?: number; + /** + * Controls whether Stripe will perform + * [automatic collection](https://stripe.com/docs/billing/invoices/workflow/#auto_advance) + * of the invoice. + */ + auto_advance?: boolean; + /** * Boolean representing whether an invoice is closed or not. To close an invoice, pass true. */ closed?: boolean; + /** + * A list of up to 4 custom fields to be displayed on the invoice. + */ + custom_fields?: Array<{ + /** + * The name of the custom field. This may be up to 30 characters. + */ + name: string; + + /** + * The value of the custom field. This may be up to 30 characters. + */ + value: string; + }>; + + /** + * The number of days from which the invoice is created until it is due. Only valid for + * invoices where billing=send_invoice. This field can only be updated on draft + * invoices. + */ + days_until_due?: number; + + /** + * ID of the default payment source for the invoice. It must belong to the customer + * associated with the invoice and be in a chargeable state. If not set, defaults to the + * subscription’s default source, if any, or to the customer’s default source. + */ + default_source?: string; + description?: string; + /** + * The date on which payment for this invoice is due. Only valid for invoices where + * `billing=send_invoice`. This field can only be updated on draft invoices. + */ + due_date?: Date | number; + + /** + * Footer to be displayed on the invoice. This can be unset by updating the value to + * `null` and then saving. + */ + footer?: string | null; + /** * Boolean representing whether an invoice is forgiven or not. To forgive an invoice, pass true. Forgiving an invoice * instructs us to update the subscription status as if the invoice were successfully paid. Once an invoice has been @@ -2270,7 +2376,10 @@ declare namespace Stripe { statement_descriptor?: string; /** - * The percent tax rate applied to the invoice, represented as a decimal number. + * The percent tax rate applied to the invoice, represented as a non-negative decimal + * number (with at most four decimal places) between 0 and 100. To unset a + * previously-set value, pass an empty string. This field can be updated only on draft + * invoices. */ tax_percent?: number; } From 85eaa2e401bd34e399deb3ac996a3524ede2953f Mon Sep 17 00:00:00 2001 From: Matthias Dailey Date: Mon, 25 Mar 2019 14:15:09 -0400 Subject: [PATCH 060/710] [toastr] support strictNullChecks and optional parameters as undefined. --- types/toastr/index.d.ts | 31 ++--------- types/toastr/toastr-tests.ts | 100 +++++++++++++++++++++++++++++++---- types/toastr/tsconfig.json | 4 +- 3 files changed, 95 insertions(+), 40 deletions(-) diff --git a/types/toastr/index.d.ts b/types/toastr/index.d.ts index 8d5d163f7b..255fda0277 100644 --- a/types/toastr/index.d.ts +++ b/types/toastr/index.d.ts @@ -221,19 +221,6 @@ interface ToastrOptions { } interface ToastrDisplayMethod { - /** - * Create a toast - * - * @param message Message to display in toast - */ - (message: string): JQuery; - /** - * Create a toast - * - * @param message Message to display in toast - * @param title Title to display on toast - */ - (message: string, title: string): JQuery; /** * Create a toast * @@ -241,7 +228,7 @@ interface ToastrDisplayMethod { * @param title Title to display on toast * @param overrides Option values for toast */ - (message: string, title: string, overrides: ToastrOptions): JQuery; + (message: string, title?: string, overrides?: ToastrOptions): JQuery; } type ToastrType = 'error'|'info'|'success'|'warning'; @@ -301,23 +288,13 @@ interface Toastr { * Clear toasts */ clear: { - /** - * Clear all toasts - */ - (): void; - /** - * Clear specific toast - * - * @param toast Toast to clear - */ - (toast: JQuery): void; /** * Clear specific toast * * @param toast Toast to clear * @param clearOptions force clearing a toast, ignoring focus */ - (toast: JQuery, clearOptions: {force: boolean}): void; + (toast?: JQuery, clearOptions?: {force: boolean}): void; }; /** * Removes all toasts (without animation) @@ -373,9 +350,7 @@ interface Toastr { * * @param callback The function which will be passed the event details. */ - subscribe: (callback: (response: ToastrResponse) => any) => void; - - [key: string]: any; + subscribe: (callback: (response: ToastrResponse) => void) => void; } declare var toastr: Toastr; diff --git a/types/toastr/toastr-tests.ts b/types/toastr/toastr-tests.ts index 1f9abe7164..3d4d0bc2a3 100644 --- a/types/toastr/toastr-tests.ts +++ b/types/toastr/toastr-tests.ts @@ -1,7 +1,19 @@ +declare let displayMethodStr: 'success' | 'info' | 'warning' | 'error'; +declare let undefinedVal: undefined; +declare let booleanVal: boolean; +declare let booleanOrUndefinedVal: boolean | undefined; +declare let stringVal: string; +declare let stringOrUndefinedVal: string | undefined; +declare let toastrOptionsVal: ToastrOptions; +declare let toastrOptionsOrUndefinedVal: ToastrOptions | undefined; +declare let jQueryVal: JQuery; +declare let jQueryOrUndefinedVal: JQuery | undefined; +declare let clearOptionsVal: {force: boolean}; +declare let clearOptionsOrUndefinedVal: typeof clearOptionsVal | undefined; function test_basic() { - var t: any[] = []; + var t: JQuery[] = []; t.push(toastr.info('Are you the 6 fingered man?')); t.push(toastr.warning('My name is Inigo Montoya. You Killed my father, prepare to die!')); t.push(toastr.success('Have fun storming the castle!', 'Miracle Max Says')); @@ -15,12 +27,52 @@ function test_basic() { var overrides = { timeOut: 250 }; toastr.warning(msg, title, overrides); toastr.options.onclick = function () { } + + // Override global options + toastr.success('We do have the Kapua suite available.', 'Turtle Bay Resort', {timeOut: 5000}) + + // Options from Readme + // Escape HTML characters + toastr.options.escapeHtml = true; + // Close Button + toastr.options.closeButton = true; + toastr.options.closeHtml = ''; + toastr.options.closeMethod = 'fadeOut'; + toastr.options.closeDuration = 300; + toastr.options.closeEasing = 'swing'; + // Display Sequence + toastr.options.newestOnTop = false; + // Callbacks + toastr.options.onShown = function() { console.log('hello'); } + toastr.options.onHidden = function() { console.log('goodbye'); } + toastr.options.onclick = function() { console.log('clicked'); } + toastr.options.onCloseClick = function() { console.log('close button clicked'); } + // Animation Options + // Easings + toastr.options.showEasing = 'swing'; + toastr.options.hideEasing = 'linear'; + toastr.options.closeEasing = 'linear'; + // Animation method + toastr.options.showMethod = 'slideDown'; + toastr.options.hideMethod = 'slideUp'; + toastr.options.closeMethod = 'slideUp'; + // Prevent Duplicates + toastr.options.preventDuplicates = true; + // Timeouts + toastr.options.timeOut = 30; // How long the toast will display without user interaction + toastr.options.extendedTimeOut = 60; // How long the toast will display after a user hovers over it + // Prevent from Auto Hiding + toastr.options.timeOut = 0; + toastr.options.extendedTimeOut = 0; + // Progress Bar + toastr.options.progressBar = true; + // rtl + toastr.options.rtl = true; } function test_fromdemo() { var i = -1, - toastCount = 0, - $toastlast: any, + $toastlast: JQuery, getMessage = function () { var msgs = ['My name is Inigo Montoya. You killed my father. Prepare to die!', '
', @@ -37,9 +89,9 @@ function test_fromdemo() { return msgs[i]; }; $('#showtoast').click(function () { - var shortCutFunction = $("#toastTypeGroup input:radio:checked").val() as string, - msg = $('#message').val(), - title = $('#title').val() || '', + var shortCutFunction = $("#toastTypeGroup input:radio:checked").val() as 'success' | 'info' | 'warning' | 'error', + msg = $('#message').val() as string, + title = $('#title').val() as string || '', $fadeIn = $('#fadeIn'), $fadeOut = $('#fadeOut'), $timeOut = $('#timeOut'), @@ -53,16 +105,16 @@ function test_fromdemo() { progressBar: true } if (( $fadeIn.val()).length) { - toastr.options.showDuration = +$fadeIn.val() + toastr.options.showDuration = +$fadeIn.val()! } if (( $fadeOut.val()).length) { - toastr.options.hideDuration = +$fadeOut.val() + toastr.options.hideDuration = +$fadeOut.val()! } if (( $timeOut.val()).length) { - toastr.options.timeOut = +$timeOut.val() + toastr.options.timeOut = +$timeOut.val()! } if (( $extendedTimeOut.val()).length) { - toastr.options.extendedTimeOut = +$extendedTimeOut.val() + toastr.options.extendedTimeOut = +$extendedTimeOut.val()! } var $toast = toastr[shortCutFunction](msg, title) if ($toast.find('#okBtn').length) { @@ -84,3 +136,31 @@ function test_fromdemo() { toastr.clear(); }); } + +function test_displayOptions() { + // 1st parameter + jQueryVal = toastr[displayMethodStr](stringVal); + + // 2nd parameter + jQueryVal = toastr[displayMethodStr](stringVal, undefinedVal); + jQueryVal = toastr[displayMethodStr](stringVal, stringVal); + jQueryVal = toastr[displayMethodStr](stringVal, stringOrUndefinedVal); + + // 3rd parameter + jQueryVal = toastr[displayMethodStr](stringVal, stringOrUndefinedVal, undefinedVal); + jQueryVal = toastr[displayMethodStr](stringVal, stringOrUndefinedVal, toastrOptionsVal); + jQueryVal = toastr[displayMethodStr](stringVal, stringOrUndefinedVal, toastrOptionsOrUndefinedVal); +} + +function test_clearOptions() { + // 1st parameter + toastr.clear(); + toastr.clear(undefinedVal); + toastr.clear(jQueryVal); + toastr.clear(jQueryOrUndefinedVal); + + // 2nd parameter + toastr.clear(jQueryOrUndefinedVal, clearOptionsVal); + toastr.clear(jQueryOrUndefinedVal, undefinedVal); + toastr.clear(jQueryOrUndefinedVal, clearOptionsOrUndefinedVal); +} diff --git a/types/toastr/tsconfig.json b/types/toastr/tsconfig.json index 6714a59824..11bee31103 100644 --- a/types/toastr/tsconfig.json +++ b/types/toastr/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -21,4 +21,4 @@ "index.d.ts", "toastr-tests.ts" ] -} \ No newline at end of file +} From 459a900e81a662283ef4aa9fc156df3ba96527e1 Mon Sep 17 00:00:00 2001 From: Matthias Dailey Date: Mon, 25 Mar 2019 14:51:05 -0400 Subject: [PATCH 061/710] Omit generic type parameter since it's the default --- types/toastr/toastr-tests.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/types/toastr/toastr-tests.ts b/types/toastr/toastr-tests.ts index 3d4d0bc2a3..38f17dd0fb 100644 --- a/types/toastr/toastr-tests.ts +++ b/types/toastr/toastr-tests.ts @@ -7,8 +7,8 @@ declare let stringVal: string; declare let stringOrUndefinedVal: string | undefined; declare let toastrOptionsVal: ToastrOptions; declare let toastrOptionsOrUndefinedVal: ToastrOptions | undefined; -declare let jQueryVal: JQuery; -declare let jQueryOrUndefinedVal: JQuery | undefined; +declare let jQueryVal: JQuery; +declare let jQueryOrUndefinedVal: JQuery | undefined; declare let clearOptionsVal: {force: boolean}; declare let clearOptionsOrUndefinedVal: typeof clearOptionsVal | undefined; From 4ff4c3e5cb2dee32bee9421b490926e566dea10d Mon Sep 17 00:00:00 2001 From: Aleksey Klimenko Date: Tue, 26 Mar 2019 01:16:30 +0300 Subject: [PATCH 062/710] [musicmatch] removed additional tslint rules, updated typings and tests --- types/musicmatch/index.d.ts | 94 ++++++----- types/musicmatch/musicmatch-tests.ts | 227 ++++++++++++++++++++++----- types/musicmatch/tsconfig.json | 3 +- types/musicmatch/tslint.json | 78 +-------- 4 files changed, 236 insertions(+), 166 deletions(-) diff --git a/types/musicmatch/index.d.ts b/types/musicmatch/index.d.ts index c22bbc6424..35e2937564 100644 --- a/types/musicmatch/index.d.ts +++ b/types/musicmatch/index.d.ts @@ -1,84 +1,82 @@ -// Type definitions for musicmatch 0.3.2 +// Type definitions for musicmatch 0.3 // Project: https://github.com/c0b41/musixmatch, https://www.npmjs.com/package/musicmatch // Definitions by: Aleksei Klimenko // Definitions: https://github.com/DefinitelyTyped/ -declare module 'musicmatch'; +export type TFormat = 'json' | 'xml'; +export type TSort = 'asc' | 'desc'; +export type TBoolean = 0 | 1; -type TFormat = 'json' | 'xml'; -type TSort = 'asc' | 'desc'; -type TBoolean = 0 | 1; - -export interface IPageable { +export interface Pageable { page?: number; page_size?: number; } -export interface IAlbumParams { +export interface AlbumParams { album_id: number; } -export interface IAlbumTracksParams { +export interface AlbumTracksParams { album_id?: number; album_mbid?: number; format?: TFormat; } -export interface IArtistParams { +export interface ArtistParams { artist_id?: number; artist_mbid?: number; } -export interface IArtistRelatedParams extends IArtistParams, IPageable { +export interface ArtistRelatedParams extends ArtistParams, Pageable { } -export interface IArtistAlbumsParams extends IArtistParams, IPageable { +export interface ArtistAlbumsParams extends ArtistParams, Pageable { g_album_name?: TBoolean; s_release_date?: TSort; } -export interface IArtistSearchParams extends IPageable { +export interface ArtistSearchParams extends Pageable { q_artist?: string; f_artist_id?: number; f_artist_mbid?: number; } -export interface IMatcherLyricsParams { +export interface MatcherLyricsParams { q_track?: string; q_artist?: string; } -export interface IMatcherSubtitleParams extends IMatcherLyricsParams { +export interface MatcherSubtitleParams extends MatcherLyricsParams { f_subtitle_length?: number; f_subtitle_length_max_deviation?: number; } -export interface IMatcherTrackParams extends IMatcherLyricsParams { +export interface MatcherTrackParams extends MatcherLyricsParams { f_has_lyrics?: TBoolean; f_has_subtitle?: TBoolean; } -export interface ITrackLyricsFeedbackParams { +export interface TrackLyricsFeedbackParams { lyrics_id?: number; track_id?: number; feedback?: 'wrong_lyrics' | 'wrong_attribution' | 'bad_characters' | 'lines_too_long' | 'wrong_verses' | 'wrong_formatting'; } -export interface ITrackLyricsAddParams { +export interface TrackLyricsAddParams { lyrics_id?: number; lyrics_body?: string; } -export interface ITrackSnippetParams { +export interface TrackSnippetParams { track_id: number; } -export interface ITrackLyricsParams { +export interface TrackLyricsParams { track_id?: number; track_mbid?: number; } -export interface ITrackSubtitleParams { +export interface TrackSubtitleParams { track_id?: number; track_mbid?: number; subtitle_format?: 'lrc' | 'dfxp' | 'stledu'; @@ -86,12 +84,12 @@ export interface ITrackSubtitleParams { f_subtitle_length_max_deviation?: number; } -export interface ITrackParams { +export interface TrackParams { track_id?: number; track_mbid?: number; } -export interface ITrackSearchParams extends IPageable { +export interface TrackSearchParams extends Pageable { q?: string; q_lyrics?: string; f_has_lyrics?: TBoolean; @@ -104,10 +102,10 @@ export interface ITrackSearchParams extends IPageable { quorum_factor?: number; } -export interface ITrackSearchResult { +export interface TrackSearchResult { message: { body: { - track_list: ITrackResult[]; + track_list: TrackResult[]; }, header: { available: number; @@ -117,7 +115,7 @@ export interface ITrackSearchResult { }; } -export interface IMusicGenre { +export interface MusicGenre { music_genre_id: number; music_genre_parent_id: number; music_genre_name: string; @@ -126,10 +124,10 @@ export interface IMusicGenre { } export interface PrimaryGenres { - music_genre_list: Array<{ music_genre: IMusicGenre }>; + music_genre_list: Array<{ music_genre: MusicGenre }>; } -export interface ITrackResult { +export interface TrackResult { track: { track_id: number; track_name: string; @@ -154,51 +152,51 @@ export interface ITrackResult { }; } -export interface IChartTracksParams extends IPageable { +export interface ChartTracksParams extends Pageable { country?: string; f_has_lyrics?: TBoolean; } -export interface IChartArtistsParams extends IPageable { +export interface ChartArtistsParams extends Pageable { country?: string; } export default class Musicmatch { constructor(obj?: { apikey?: string, format?: string }); - album(params: IAlbumParams): Promise; + album(params: AlbumParams): Promise; - albumTracks(params: IAlbumTracksParams): Promise; + albumTracks(params: AlbumTracksParams): Promise; - artist(params: IArtistParams): Promise; + artist(params: ArtistParams): Promise; - artistAlbums(params: IArtistAlbumsParams): Promise; + artistAlbums(params: ArtistAlbumsParams): Promise; - artistRelated(params: IArtistRelatedParams): Promise; + artistRelated(params: ArtistRelatedParams): Promise; - artistSearch(params: IArtistSearchParams): Promise; + artistSearch(params: ArtistSearchParams): Promise; - chartArtists(params: IChartArtistsParams): Promise; + chartArtists(params: ChartArtistsParams): Promise; - chartTracks(params: IChartTracksParams): Promise; + chartTracks(params: ChartTracksParams): Promise; - matcherLyrics(params: IMatcherLyricsParams): Promise; + matcherLyrics(params: MatcherLyricsParams): Promise; - matcherSubtitle(params: IMatcherSubtitleParams): Promise; + matcherSubtitle(params: MatcherSubtitleParams): Promise; - matcherTrack(params: IMatcherTrackParams): Promise; + matcherTrack(params: MatcherTrackParams): Promise; - track(params: ITrackParams): Promise; + track(params: TrackParams): Promise; - trackLyrics(params: ITrackLyricsParams): Promise; + trackLyrics(params: TrackLyricsParams): Promise; - trackLyricsAdd(params: ITrackLyricsAddParams): Promise; + trackLyricsAdd(params: TrackLyricsAddParams): Promise; - trackLyricsFeedback(params: ITrackLyricsFeedbackParams): Promise; + trackLyricsFeedback(params: TrackLyricsFeedbackParams): Promise; - trackSearch(params: ITrackSearchParams): Promise; + trackSearch(params: TrackSearchParams): Promise; - trackSnippet(params: ITrackSnippetParams): Promise; + trackSnippet(params: TrackSnippetParams): Promise; - trackSubtitle(params: ITrackSubtitleParams): Promise; + trackSubtitle(params: TrackSubtitleParams): Promise; } diff --git a/types/musicmatch/musicmatch-tests.ts b/types/musicmatch/musicmatch-tests.ts index 6511920854..cc9d516d92 100644 --- a/types/musicmatch/musicmatch-tests.ts +++ b/types/musicmatch/musicmatch-tests.ts @@ -1,13 +1,35 @@ -// Type definitions for musicmatch 0.3.2 // Project: https://github.com/c0b41/musixmatch, https://www.npmjs.com/package/musicmatch // Definitions by: Aleksei Klimenko // Definitions: https://github.com/DefinitelyTyped/ -import Musicmatch, { ITrackSearchParams, ITrackSearchResult } from 'musicmatch'; +import Musicmatch, { + AlbumParams, + AlbumTracksParams, + ArtistAlbumsParams, + ArtistParams, + ArtistRelatedParams, + ArtistSearchParams, + ChartArtistsParams, + MatcherLyricsParams, + MatcherSubtitleParams, + MatcherTrackParams, + TrackLyricsAddParams, + TrackLyricsFeedbackParams, + TrackLyricsParams, + TrackParams, + TrackSearchParams, + TrackSearchResult, + TrackSnippetParams, + TrackSubtitleParams +} from 'musicmatch'; const musicmatch = new Musicmatch({ apikey: 'api_key', format: '' }); -const trackSearchParams: ITrackSearchParams = { +const COUNTRY = 'USA'; +const Q_ARTIST = 'artist name'; +const Q_TRACK = 'track title'; + +const trackSearchParams: TrackSearchParams = { f_music_genre_id: 18, page_size: 100, page: 1, @@ -15,46 +37,144 @@ const trackSearchParams: ITrackSearchParams = { f_lyrics_language: 'en', }; -musicmatch.trackSearch(trackSearchParams); +const albumParams: AlbumParams = { + album_id: 1, +}; + +const albumTrackParams: AlbumTracksParams = { + album_id: 1, + album_mbid: 1, + format: 'json', +}; + +const artisParams: ArtistParams = { + artist_id: 1, + artist_mbid: 1, +}; + +const artistAlbumsParams: ArtistAlbumsParams = { + artist_mbid: 1, + artist_id: 1, + g_album_name: 1, + page: 1, + page_size: 10, + s_release_date: 'desc', +}; + +const artistRelatedParams: ArtistRelatedParams = { + page_size: 10, + page: 1, + artist_id: 1, + artist_mbid: 1, +}; + +const artistSearchParams: ArtistSearchParams = { + page: 1, + page_size: 10, + f_artist_id: 1, + f_artist_mbid: 1, + q_artist: Q_ARTIST +}; + +const chartArtistsParams: ChartArtistsParams = { + page: 1, + page_size: 10, + country: COUNTRY +}; + +const chartTracksParams: ChartArtistsParams = { + page: 1, + page_size: 10, + country: COUNTRY, +}; + +const matcherLyricsParams: MatcherLyricsParams = { + q_artist: Q_ARTIST, + q_track: Q_TRACK, +}; + +const matcherSubtitleParams: MatcherSubtitleParams = { + q_artist: Q_ARTIST, + q_track: Q_TRACK, + f_subtitle_length: 100, + f_subtitle_length_max_deviation: 10, +}; + +const matcherTrackParams: MatcherTrackParams = { + q_artist: Q_ARTIST, + q_track: Q_TRACK, + f_has_lyrics: 1, + f_has_subtitle: 1, +}; + +const trackParams: TrackParams = { + track_id: 1, + track_mbid: 1, +}; + +const trackLyricsParams: TrackLyricsParams = { + track_id: 1, + track_mbid: 1, +}; + +const trackLyricsAddParams: TrackLyricsAddParams = { + lyrics_body: 'Lyrics', + lyrics_id: 1, +}; + +const trackLyricsFeedbackParams: TrackLyricsFeedbackParams = { + feedback: 'bad_characters', + lyrics_id: 1, + track_id: 1, +}; + +const trackSnippetParams: TrackSnippetParams = { + track_id: 1, +}; + +const trackSubtitleParams: TrackSubtitleParams = { + f_subtitle_length: 100, + f_subtitle_length_max_deviation: 10, + subtitle_format: 'dfxp', + track_id: 1, + track_mbid: 1, +}; /** - * Search for a track - * - * GET ws/1.1/track.search - * + * Example of track search result */ -const trackSearchResult: ITrackSearchResult = { - 'message': { - 'header': { 'status_code': 200, 'execute_time': 0.27148103713989, 'available': 10000 }, 'body': { - 'track_list': [{ - 'track': { - 'track_id': 164289228, - 'track_name': '7 rings', - 'track_name_translation_list': [], - 'track_rating': 100, - 'commontrack_id': 91473047, - 'instrumental': 0, - 'explicit': 1, - 'has_lyrics': 1, - 'has_subtitles': 1, - 'has_richsync': 1, - 'num_favourite': 2130, - 'album_id': 31234760, - 'album_name': 'thank u, next', - 'artist_id': 13958599, - 'artist_name': 'Ariana Grande', - 'track_share_url': 'https:\/\/www.musixmatch.com\/lyrics\/Ariana-Grande\/7-rings?utm_source=application&utm_campaign=api&utm_medium=FruitSarcop%3A1409618278546', - 'track_edit_url': 'https:\/\/www.musixmatch.com\/lyrics\/Ariana-Grande\/7-rings\/edit?utm_source=application&utm_campaign=api&utm_medium=FruitSarcop%3A1409618278546', - 'restricted': 0, - 'updated_time': '2019-03-22T15:28:01Z', - 'primary_genres': { - 'music_genre_list': [{ - 'music_genre': { - 'music_genre_id': 14, - 'music_genre_parent_id': 34, - 'music_genre_name': 'Pop', - 'music_genre_name_extended': 'Pop', - 'music_genre_vanity': 'Pop' +const trackSearchResult: TrackSearchResult = { + message: { + header: { status_code: 200, execute_time: 0.27148103713989, available: 10000 }, body: { + track_list: [{ + track: { + track_id: 164289228, + track_name: '7 rings', + track_name_translation_list: [], + track_rating: 100, + commontrack_id: 91473047, + instrumental: 0, + explicit: 1, + has_lyrics: 1, + has_subtitles: 1, + has_richsync: 1, + num_favourite: 2130, + album_id: 31234760, + album_name: 'thank u, next', + artist_id: 13958599, + artist_name: 'Ariana Grande', + track_share_url: 'https:\/\/www.musixmatch.com\/lyrics\/Ariana-Grande\/7-rings?utm_source=application&utm_campaign=api&utm_medium=FruitSarcop%3A1409618278546', + track_edit_url: 'https:\/\/www.musixmatch.com\/lyrics\/Ariana-Grande\/7-rings\/edit?utm_source=application&utm_campaign=api&utm_medium=FruitSarcop%3A1409618278546', + restricted: 0, + updated_time: '2019-03-22T15:28:01Z', + primary_genres: { + music_genre_list: [{ + music_genre: { + music_genre_id: 14, + music_genre_parent_id: 34, + music_genre_name: 'Pop', + music_genre_name_extended: 'Pop', + music_genre_vanity: 'Pop' } }] } @@ -63,3 +183,30 @@ const trackSearchResult: ITrackSearchResult = { } } }; + +Promise + .all([ + musicmatch.album(albumParams), // 0 + musicmatch.albumTracks(albumTrackParams), // 1 + musicmatch.artist(artisParams), // 2 + musicmatch.artistAlbums(artistAlbumsParams), // 3 + musicmatch.artistRelated(artistRelatedParams), // 4 + musicmatch.artistSearch(artistSearchParams), // 5 + musicmatch.chartArtists(chartArtistsParams), // 6 + musicmatch.chartTracks(chartTracksParams), // 7 + musicmatch.matcherLyrics(matcherLyricsParams), // 8 + musicmatch.matcherSubtitle(matcherSubtitleParams), // 9 + musicmatch.matcherTrack(matcherTrackParams), // 10 + musicmatch.track(trackParams), // 11 + musicmatch.trackLyrics(trackLyricsParams), // 12 + musicmatch.trackLyricsAdd(trackLyricsAddParams), // 13 + musicmatch.trackLyricsFeedback(trackLyricsFeedbackParams), // 14 + musicmatch.trackSearch(trackSearchParams), // 15 + musicmatch.trackSnippet(trackSnippetParams), // 16 + musicmatch.trackSubtitle(trackSubtitleParams), // 17 + ]) + .then((results) => { + const trackSearchResult: TrackSearchResult = results[15]; + + console.log('No. of tracks found by search:', trackSearchResult.message.body.track_list.length); + }); diff --git a/types/musicmatch/tsconfig.json b/types/musicmatch/tsconfig.json index 800f5abd46..035d6f98aa 100644 --- a/types/musicmatch/tsconfig.json +++ b/types/musicmatch/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/musicmatch/tslint.json b/types/musicmatch/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/musicmatch/tslint.json +++ b/types/musicmatch/tslint.json @@ -1,79 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "adjacent-overload-signatures": false, - "array-type": false, - "arrow-return-shorthand": false, - "ban-types": false, - "callable-types": false, - "comment-format": false, - "dt-header": false, - "eofline": false, - "export-just-namespace": false, - "import-spacing": false, - "interface-name": false, - "interface-over-type-literal": false, - "jsdoc-format": false, - "max-line-length": false, - "member-access": false, - "new-parens": false, - "no-any-union": false, - "no-boolean-literal-compare": false, - "no-conditional-assignment": false, - "no-consecutive-blank-lines": false, - "no-construct": false, - "no-declare-current-package": false, - "no-duplicate-imports": false, - "no-duplicate-variable": false, - "no-empty-interface": false, - "no-for-in-array": false, - "no-inferrable-types": false, - "no-internal-module": false, - "no-irregular-whitespace": false, - "no-mergeable-namespace": false, - "no-misused-new": false, - "no-namespace": false, - "no-object-literal-type-assertion": false, - "no-padding": false, - "no-redundant-jsdoc": false, - "no-redundant-jsdoc-2": false, - "no-redundant-undefined": false, - "no-reference-import": false, - "no-relative-import-in-test": false, - "no-self-import": false, - "no-single-declare-module": false, - "no-string-throw": false, - "no-unnecessary-callback-wrapper": false, - "no-unnecessary-class": false, - "no-unnecessary-generics": false, - "no-unnecessary-qualifier": false, - "no-unnecessary-type-assertion": false, - "no-useless-files": false, - "no-var-keyword": false, - "no-var-requires": false, - "no-void-expression": false, - "no-trailing-whitespace": false, - "object-literal-key-quotes": false, - "object-literal-shorthand": false, - "one-line": false, - "one-variable-per-declaration": false, - "only-arrow-functions": false, - "prefer-conditional-expression": false, - "prefer-const": false, - "prefer-declare-function": false, - "prefer-for-of": false, - "prefer-method-signature": false, - "prefer-template": false, - "radix": false, - "semicolon": false, - "space-before-function-paren": false, - "space-within-parens": false, - "strict-export-declare-modifiers": false, - "trim-file": false, - "triple-equals": false, - "typedef-whitespace": false, - "unified-signatures": false, - "void-return": false, - "whitespace": false - } + "extends": "dtslint/dt.json" } From e594fe950d17e9e08619c35b46b8414df0333bc3 Mon Sep 17 00:00:00 2001 From: John Caruso Date: Mon, 25 Mar 2019 17:20:58 -0500 Subject: [PATCH 063/710] Remove non-lintable tests --- .../servicenow-london-tests.ts | 24 ++ types/servicenow-london/test/Class.ts | 11 - .../test/GlideDBFunctionBuilder.ts | 75 ---- types/servicenow-london/test/GlideDate.ts | 18 - types/servicenow-london/test/GlideDateTime.ts | 100 ----- types/servicenow-london/test/GlideDuration.ts | 46 -- .../test/GlideEmailOutbound.ts | 21 - types/servicenow-london/test/GlideFilter.ts | 10 - types/servicenow-london/test/GlideLocale.ts | 15 - .../test/GlidePluginManager.ts | 18 - types/servicenow-london/test/GlideSchedule.ts | 62 --- .../test/GlideScopedEvaluator.ts | 34 -- .../test/GlideScriptedProcessor.ts | 16 - .../test/GlideSecureRandomUtil.ts | 12 - .../test/GlideServletRequest.ts | 26 -- .../test/GlideServletResponse.ts | 10 - types/servicenow-london/test/GlideSession.ts | 64 --- .../servicenow-london/test/GlideStringUtil.ts | 85 ---- .../test/GlideSysAttachment.ts | 1 - types/servicenow-london/test/GlideSystem.ts | 211 --------- types/servicenow-london/test/GlideTime.ts | 46 -- types/servicenow-london/test/GlideUser.ts | 59 --- .../servicenow-london/test/RESTAPIRequest.ts | 22 - .../test/RESTAPIRequestBody.ts | 33 -- .../servicenow-london/test/RESTAPIResponse.ts | 28 -- .../test/RESTAPIResponseStream.ts | 17 - types/servicenow-london/test/RESTMessageV2.ts | 106 ----- .../servicenow-london/test/RESTResponseV2.ts | 22 - types/servicenow-london/test/SOAPMessageV2.ts | 28 -- .../servicenow-london/test/SOAPResponseV2.ts | 20 - .../test/ScopedElementDescriptor.ts | 19 - .../test/ScopedGlideElement.ts | 13 - .../test/ScopedGlideRecord.ts | 400 ------------------ .../test/ScopedQueryCondition.ts | 26 -- types/servicenow-london/test/Workflow.ts | 134 ------ types/servicenow-london/test/XMLDocument2.ts | 153 ------- types/servicenow-london/test/XMLNode.ts | 137 ------ .../servicenow-london/test/XMLNodeIterator.ts | 36 -- types/servicenow-london/tsconfig.json | 38 +- types/servicenow-london/tslint.json | 9 - 40 files changed, 25 insertions(+), 2180 deletions(-) create mode 100644 types/servicenow-london/servicenow-london-tests.ts delete mode 100644 types/servicenow-london/test/Class.ts delete mode 100644 types/servicenow-london/test/GlideDBFunctionBuilder.ts delete mode 100644 types/servicenow-london/test/GlideDate.ts delete mode 100644 types/servicenow-london/test/GlideDateTime.ts delete mode 100644 types/servicenow-london/test/GlideDuration.ts delete mode 100644 types/servicenow-london/test/GlideEmailOutbound.ts delete mode 100644 types/servicenow-london/test/GlideFilter.ts delete mode 100644 types/servicenow-london/test/GlideLocale.ts delete mode 100644 types/servicenow-london/test/GlidePluginManager.ts delete mode 100644 types/servicenow-london/test/GlideSchedule.ts delete mode 100644 types/servicenow-london/test/GlideScopedEvaluator.ts delete mode 100644 types/servicenow-london/test/GlideScriptedProcessor.ts delete mode 100644 types/servicenow-london/test/GlideSecureRandomUtil.ts delete mode 100644 types/servicenow-london/test/GlideServletRequest.ts delete mode 100644 types/servicenow-london/test/GlideServletResponse.ts delete mode 100644 types/servicenow-london/test/GlideSession.ts delete mode 100644 types/servicenow-london/test/GlideStringUtil.ts delete mode 100644 types/servicenow-london/test/GlideSysAttachment.ts delete mode 100644 types/servicenow-london/test/GlideSystem.ts delete mode 100644 types/servicenow-london/test/GlideTime.ts delete mode 100644 types/servicenow-london/test/GlideUser.ts delete mode 100644 types/servicenow-london/test/RESTAPIRequest.ts delete mode 100644 types/servicenow-london/test/RESTAPIRequestBody.ts delete mode 100644 types/servicenow-london/test/RESTAPIResponse.ts delete mode 100644 types/servicenow-london/test/RESTAPIResponseStream.ts delete mode 100644 types/servicenow-london/test/RESTMessageV2.ts delete mode 100644 types/servicenow-london/test/RESTResponseV2.ts delete mode 100644 types/servicenow-london/test/SOAPMessageV2.ts delete mode 100644 types/servicenow-london/test/SOAPResponseV2.ts delete mode 100644 types/servicenow-london/test/ScopedElementDescriptor.ts delete mode 100644 types/servicenow-london/test/ScopedGlideElement.ts delete mode 100644 types/servicenow-london/test/ScopedGlideRecord.ts delete mode 100644 types/servicenow-london/test/ScopedQueryCondition.ts delete mode 100644 types/servicenow-london/test/Workflow.ts delete mode 100644 types/servicenow-london/test/XMLDocument2.ts delete mode 100644 types/servicenow-london/test/XMLNode.ts delete mode 100644 types/servicenow-london/test/XMLNodeIterator.ts diff --git a/types/servicenow-london/servicenow-london-tests.ts b/types/servicenow-london/servicenow-london-tests.ts new file mode 100644 index 0000000000..a976b80bf0 --- /dev/null +++ b/types/servicenow-london/servicenow-london-tests.ts @@ -0,0 +1,24 @@ +const NewInclude = Class.create(); + +const grFirst = new GlideRecord('core_company'); + +const grSecond = new GlideRecord('core_company'); +grSecond.addQuery('property', '=', grFirst.sys_id); +grSecond.addQuery('property2', '!=', 'somevalue'); +if (grSecond.get('somesysid')) { + gs.info('got it'); +} + +const wf = new global.Workflow(); + +const rest = new sn_ws.RESTMessageV2(); + +interface ScopedGlideRecord { + new (tableName: 'othertype'): OtherType; +} +interface OtherType extends ScopedGlideRecord { + someproperty: string; +} + +const grOther = new GlideRecord('othertype'); +grOther.someproperty = 'foo'; diff --git a/types/servicenow-london/test/Class.ts b/types/servicenow-london/test/Class.ts deleted file mode 100644 index f6d1c9f2b7..0000000000 --- a/types/servicenow-london/test/Class.ts +++ /dev/null @@ -1,11 +0,0 @@ -var NewInclude = Class.create(); - -NewInclude.prototype = { - initialize: function() {}, - - myFunction: function() { - //Put function code here - }, - - type: 'NewInclude' -}; diff --git a/types/servicenow-london/test/GlideDBFunctionBuilder.ts b/types/servicenow-london/test/GlideDBFunctionBuilder.ts deleted file mode 100644 index 0fc4b980e1..0000000000 --- a/types/servicenow-london/test/GlideDBFunctionBuilder.ts +++ /dev/null @@ -1,75 +0,0 @@ -(function() { - var functionBuilder = new GlideDBFunctionBuilder(); - var myAddingFunction = functionBuilder.add(); - myAddingFunction = functionBuilder.field('order'); - myAddingFunction = functionBuilder.field('priority'); - var func = functionBuilder.build(); -})(); -(function() { - var functionBuilder = new GlideDBFunctionBuilder(); - var myAddingFunction = functionBuilder.add(); - myAddingFunction = functionBuilder.field('order'); - myAddingFunction = functionBuilder.field('priority'); - var func = functionBuilder.build(); - gs.info(func); -})(); -(function() { - var functionBuilder = new GlideDBFunctionBuilder(); - var myConcatFunction = functionBuilder.concat(); - myConcatFunction = functionBuilder.field('short_description'); - myConcatFunction = functionBuilder.field('caller_id.name'); - var func = functionBuilder.build(); -})(); -(function() { - var functionBuilder = new GlideDBFunctionBuilder(); - var myDateDiffFunction = functionBuilder.datediff(); - myDateDiffFunction = functionBuilder.field('sys_updated_on'); - myDateDiffFunction = functionBuilder.field('opened_at'); - var func = functionBuilder.build(); -})(); -(function() { - var functionBuilder = new GlideDBFunctionBuilder(); - var dayOfWeekFunction = functionBuilder.dayofweek(); - dayOfWeekFunction = functionBuilder.field('opened_at'); - dayOfWeekFunction = functionBuilder.constant('2'); - var func = functionBuilder.build(); - - var gr = new GlideRecord('incident'); - gr.addFunction(func); - gr.query(); - while (gr.next()) gs.info(gr.getValue(func)); -})(); -(function() { - var functionBuilder = new GlideDBFunctionBuilder(); - var myDivideFunction = functionBuilder.divide(); - myDivideFunction = functionBuilder.field('order'); - myDivideFunction = functionBuilder.field('priority'); - var func = functionBuilder.build(); -})(); -(function() { - var functionBuilder = new GlideDBFunctionBuilder(); - var myAddingFunction = functionBuilder.add(); - myAddingFunction = functionBuilder.field('order'); - myAddingFunction = functionBuilder.field('priority'); - var func = functionBuilder.build(); -})(); -(function() { - var functionBuilder = new GlideDBFunctionBuilder(); - var myLengthFunction = functionBuilder.length(); - myLengthFunction = functionBuilder.field('short_description'); - var func = functionBuilder.build(); -})(); -(function() { - var functionBuilder = new GlideDBFunctionBuilder(); - var myMultiplyFunction = functionBuilder.multiply(); - myMultiplyFunction = functionBuilder.field('order'); - myMultiplyFunction = functionBuilder.field('priority'); - var func = functionBuilder.build(); -})(); -(function() { - var functionBuilder = new GlideDBFunctionBuilder(); - var mySubtractFunction = functionBuilder.subtract(); - mySubtractFunction = functionBuilder.field('order'); - mySubtractFunction = functionBuilder.field('priority'); - var func = functionBuilder.build(); -})(); diff --git a/types/servicenow-london/test/GlideDate.ts b/types/servicenow-london/test/GlideDate.ts deleted file mode 100644 index 1a4c2fd086..0000000000 --- a/types/servicenow-london/test/GlideDate.ts +++ /dev/null @@ -1,18 +0,0 @@ -(function() { - var gd = new GlideDate(); - gs.info(gd.getByFormat('dd-MM-yyyy')); - gs.info(gd.getDayOfMonthNoTZ()); - gs.info(gd.getDisplayValue()); - gs.info(gd.getDisplayValueInternal()); - gs.info(gd.getMonthNoTZ()); - gs.info(gd.getValue()); - gs.info(gd.getYearNoTZ()); - gd.setDisplayValue('2011-01-01'); - gd.setValue('2015-01-01'); - var sgd1 = new GlideDate(); - sgd1.setDisplayValue('2014-07-18'); - var sgd2 = new GlideDate(); - sgd2.setDisplayValue('2014-07-19'); - var duration = GlideDate.subtract(sgd1, sgd2); - gs.info(duration.getDisplayValue()); -})(); diff --git a/types/servicenow-london/test/GlideDateTime.ts b/types/servicenow-london/test/GlideDateTime.ts deleted file mode 100644 index e3396f268d..0000000000 --- a/types/servicenow-london/test/GlideDateTime.ts +++ /dev/null @@ -1,100 +0,0 @@ -(function() { - var gdt = new GlideDateTime('2011-08-31 08:00:00'); - var gtime1 = new GlideTime(); - gtime1.setValue('00:00:20'); - gdt.add(gtime1); - var gtime2 = gdt.getTime(); - gs.info(gtime2.getByFormat('hh:mm:ss')); - gdt.add(10); - var start = new GlideDateTime('2011-01-01 12:00:00'); - var end = new GlideDateTime(start); - gdt.addDaysLocalTime(-1); - gdt.addDaysUTC(-1); - gdt.addMonthsLocalTime(2); - gdt.addMonthsUTC(2); - gdt.addSeconds(1000); - gdt.addWeeksLocalTime(-1); - gdt.addWeeksUTC(-1); - gdt.addYearsLocalTime(1); - gdt.addYearsUTC(1); - var gdt1 = new GlideDateTime('2016-05-09 10:11:12'); - var gdt2 = new GlideDateTime('2017-06-12 15:11:12'); - gs.info(gdt1.after(gdt2)); - gs.info(gdt1.before(gdt2)); - var initDate = new GlideDateTime('2011-08-01 12:00:00'); - var compDate1 = new GlideDateTime('2011-08-01 12:00:00'); - var compDate2 = new GlideDateTime('2011-07-31 12:00:00'); - var compDate3 = new GlideDateTime('2011-08-04 16:00:00'); - gs.info(initDate.compareTo(compDate1)); // Equals (0) - gs.info(initDate.compareTo(compDate2)); // initDate is after compDate2 (1) - gs.info(initDate.compareTo(compDate3)); // initDate is before compDate3 (-1) - gs.info(gdt.equals('2011-09-30 00:12:01')); - gs.info(gdt.getDate()); - gs.info(gdt.getValue()); - gs.info(gdt.getDayOfMonthLocalTime()); - gs.info(gdt.getDayOfMonthUTC()); - gs.info(gdt.getDayOfWeekLocalTime()); - gs.info(gdt.getDayOfWeekLocalTime()); - gs.info(gdt.getDaysInMonthLocalTime()); - gs.info(gdt.getDaysInMonthUTC()); - gs.info(gdt.getDisplayValue()); - gs.info(gdt.getDisplayValueInternal()); //uses current user session time zone (US/Pacific) - gs.info(gdt.getDSTOffset()); //uses current user session time zone (US/Pacific) - gdt.setDisplayValue('2011-aa-01 00:00:00'); - gs.info(gdt.getErrorMsg()); // Could not parse DateTime: 2011-aa-01 00:00:00 - gs.info(gdt.getLocalDate()); - var gt = gdt.getLocalTime(); - gs.info('local time is ' + gt.getByFormat('hh:mm:ss')); - gs.info(gdt.getMonthLocalTime()); - gs.info(gdt.getMonthUTC()); - gs.info(gdt.getNumericValue()); - var gt = gdt.getTime(); - gs.info(gt.getByFormat('hh:mm:ss')); - gdt.getLocalTime(); // PST local time - gs.info(gdt.getTZOffset()); - gs.info(gdt.getValue()); - gs.info(gdt.getWeekOfYearLocalTime()); - gs.info(gdt.getWeekOfYearUTC()); - gs.info(gdt.getYearLocalTime()); - gs.info(gdt.getYearUTC()); - gs.info(gdt.hasDate()); - gs.info(gdt.isDST()); //true - gdt.setDisplayValue('2011-aa-01 00:00:00'); - gs.info(gdt.isValid()); - var gdt1 = new GlideDateTime('2016-05-09 10:11:12'); - var gdt2 = new GlideDateTime('2017-06-12 15:11:12'); - gs.info(gdt1.onOrAfter(gdt2)); - gs.info(gdt1.onOrBefore(gdt2)); - gdt.setDayOfMonthLocalTime(9); - gs.info(gdt.getDayOfMonthLocalTime()); - gdt.setDayOfMonthUTC(9); - gs.info(gdt.getDayOfMonthUTC()); - gdt.setDisplayValue('2014-01-01 12:00:00'); - gdt.setDisplayValue('20-5-2011 12:00:00', 'dd-MM-yyyy HH:mm:ss'); - gdt.setDisplayValueInternal('2014-01-01 12:00:00'); - var dt1 = new GlideDateTime('2011-01-01 12:00:00'); - var dt2 = new GlideDateTime('2011-02-02 08:00:00'); - dt1.setGlideDateTime(dt2); - gdt.setMonthLocalTime(1); - gs.info(gdt.getMonthLocalTime()); - gdt.setMonthUTC(1); - gs.info(gdt.getMonthUTC()); - gdt.setValue('2011-02-02 08:00:00'); // value set = 2011-02-02 08:00:00 - gdt.setValueUTC('15-02-2011 08:00:00', 'dd-MM-yyyy HH:mm:ss'); - gdt.setYearLocalTime(2013); - gs.info(gdt.getYearLocalTime()); - gdt.setYearUTC(2013); - gs.info(gdt.getYearUTC()); - var gdt1 = new GlideDateTime('2011-08-28 09:00:00'); - var gdt2 = new GlideDateTime('2011-08-31 08:00:00'); - var dur = GlideDateTime.subtract(gdt1, gdt2); //the difference between gdt1 and gdt2 - gs.info(dur.getDisplayValue()); - var gtime1 = new GlideTime(); - gtime1.setValue('00:00:20'); - gdt.subtract(gtime1); - var gtime2 = gdt.getTime(); - gs.info(gtime2.getByFormat('hh:mm:ss')); - var gdt = new GlideDateTime('2011-12-07 08:00:00'); - gdt.subtract(1000); - gs.info(gdt.toString()); -})(); diff --git a/types/servicenow-london/test/GlideDuration.ts b/types/servicenow-london/test/GlideDuration.ts deleted file mode 100644 index f217d74e74..0000000000 --- a/types/servicenow-london/test/GlideDuration.ts +++ /dev/null @@ -1,46 +0,0 @@ -(function() { - var duration = new GlideDuration('3 12:00:00'); - var duration2 = new GlideDuration('3:00:00'); - var answer = duration.add(duration2); - gs.info(answer.getDisplayValue()); -})(); -(function() { - var dur = new GlideDuration('3 22:00:00'); - gs.info(dur.getByFormat('HH:mm')); -})(); -(function() { - var dur = new GlideDuration('3 12:00:00'); - gs.info(dur.getDayPart()); -})(); -(function() { - var dur = new GlideDuration('3 12:00:00'); - gs.info(dur.getDisplayValue()); -})(); -(function() { - var dur = new GlideDuration('3 12:00:00'); - gs.info(dur.getDurationValue()); -})(); -(function() { - var dur = new GlideDuration('3 11:00:00'); - gs.info(dur.getRoundedDayPart()); -})(); -(function() { - var dur = new GlideDuration('3 12:00:00'); - gs.info(dur.getValue()); -})(); -(function() { - var dur = new GlideDuration(); - dur.setDisplayValue('3 08:00:00'); - gs.info(dur.getDisplayValue()); -})(); -(function() { - var dur = new GlideDuration(); - dur.setValue('1970-01-05 08:00:00'); // sets internal DateTime value. The String will be parsed into a GlideDateTime object. - gs.info(dur.getDisplayValue()); -})(); -(function() { - var duration = new GlideDuration('3 12:00:00'); - var duration2 = new GlideDuration('3:00:00'); - var answer = duration.subtract(duration2); - gs.info(answer.getDisplayValue()); -})(); diff --git a/types/servicenow-london/test/GlideEmailOutbound.ts b/types/servicenow-london/test/GlideEmailOutbound.ts deleted file mode 100644 index 969e16255f..0000000000 --- a/types/servicenow-london/test/GlideEmailOutbound.ts +++ /dev/null @@ -1,21 +0,0 @@ -(function() { - email.addAddress('cc', 'joe.employee@something.com'); -})(); -(function() { - email.addAddress('bcc', 'joe.employee@something.com', 'dudley rocks'); -})(); -(function() { - var watermark = email.getWatermark(); -})(); -(function() { - email.setBody('Dear Sir, ...'); -})(); -(function() { - email.setFrom('joe.employee@something.com'); -})(); -(function() { - email.setReplyTo('joe.employee@something.com'); -})(); -(function() { - email.setSubject('Important Issues to discuss'); -})(); diff --git a/types/servicenow-london/test/GlideFilter.ts b/types/servicenow-london/test/GlideFilter.ts deleted file mode 100644 index ff0348c71e..0000000000 --- a/types/servicenow-london/test/GlideFilter.ts +++ /dev/null @@ -1,10 +0,0 @@ -(function() { - var rec = new GlideRecord('incident'); - rec.query(); - var bool = true; - - while (rec.next()) { - bool = GlideFilter.checkRecord(rec, 'active=true'); - gs.info('number ' + rec.number + ' is ' + bool); - } -})(); diff --git a/types/servicenow-london/test/GlideLocale.ts b/types/servicenow-london/test/GlideLocale.ts deleted file mode 100644 index 831d035919..0000000000 --- a/types/servicenow-london/test/GlideLocale.ts +++ /dev/null @@ -1,15 +0,0 @@ -(function() { - var locale = GlideLocale.get(); -})(); -(function() { - var locale = GlideLocale.get(); - var decimalSeparator = locale.getDecimalSeparator(); - gs.info('The decimal separator is ' + decimalSeparator); - // The decimal separator is . -})(); -(function() { - var locale = GlideLocale.get(); - var groupingSeparator = locale.getGroupingSeparator(); - gs.info('The grouping separator is ' + groupingSeparator); - // The grouping separator is , -})(); diff --git a/types/servicenow-london/test/GlidePluginManager.ts b/types/servicenow-london/test/GlidePluginManager.ts deleted file mode 100644 index ca040d31b2..0000000000 --- a/types/servicenow-london/test/GlidePluginManager.ts +++ /dev/null @@ -1,18 +0,0 @@ -(function() { - var gr = new GlideRecord('sys_plugins'); - var queryString = 'active=0^ORactive=1'; - gr.addEncodedQuery(queryString); - gr.query(); - var pMgr = new GlidePluginManager(); - - while (gr.next()) { - var name = gr.getValue('name'); - var pID = gr.getValue('source'); - var isActive = pMgr.isActive(pID); - if (isActive) gs.info('The plugin ' + name + ' is active'); - } - // The plugin Country Lookup Data is active - // The plugin Database Replication is active - // The plugin REST API Provider is active - // The plugin Ten Cool Things is active ... -})(); diff --git a/types/servicenow-london/test/GlideSchedule.ts b/types/servicenow-london/test/GlideSchedule.ts deleted file mode 100644 index ada8aeaf6d..0000000000 --- a/types/servicenow-london/test/GlideSchedule.ts +++ /dev/null @@ -1,62 +0,0 @@ -(function() { - var startDate = new GlideDateTime('2014-01-02'); - var days = 2; - var dur = new GlideDuration(60 * 60 * 24 * 1000 * days); - var schedule = new GlideSchedule(); - var end = schedule.add(startDate, dur); - gs.info(end); -})(); -(function() { - var schedule = new GlideSchedule('090eecae0a0a0b260077e1dfa71da828', 'US/Pacific'); -})(); -(function() { - var startDate = new GlideDateTime('2014-10-16 02:00:00'); - var endDate = new GlideDateTime('2014-10-18 04:00:00'); - var schedule = new GlideSchedule(); - - schedule.load('090eecae0a0a0b260077e1dfa71da828'); // loads "8-5 weekdays excluding holidays" schedule - var duration = schedule.duration(startDate, endDate); - gs.info(duration.getDurationValue()); // gets the elapsed time in schedule -})(); -(function() { - var sys_id = '04e664654a36232701a2247dcd8fc4cf'; // sys_id for "Application" schedule record - var sched = new GlideSchedule(sys_id); - gs.info(sched.getName()); -})(); -(function() { - var g = new GlideRecord('cmn_schedule'); - g.addQuery('type', 'blackout'); - g.query(); - if (g.next()) { - var sched = new GlideSchedule(g.sys_id); - var d = new GlideDateTime(); - d.setDisplayValue('2007-09-18 12:00:00'); - if (sched.isInSchedule(d)) gs.info('Is in the schedule'); - else gs.info('Is NOT in the schedule'); - } -})(); -(function() { - var g = new GlideRecord('cmn_schedule'); - g.addQuery('type', 'blackout'); - g.query(); - if (g.next()) { - var sched = new GlideSchedule(g.sys_id); - var d = new GlideDateTime(); - d.setDisplayValue('2007-09-18 12:00:00'); - if (sched.isValid()) gs.info('Is valid'); - else gs.info('Is not valid'); - } -})(); -(function() { - var x = new GlideSchedule(); - x.load('08fcd0830a0a0b2600079f56b1adb9ae'); -})(); -(function() { - var schedule = new GlideSchedule(); - schedule.setTimeZone('US/Pacific'); -})(); -(function() { - var startDate = new GlideDateTime('2014-10-25 08:00:00'); - var glideSchedule = new GlideSchedule('08fcd0830a0a0b2600079f56b1adb9ae', 'UTC'); - gs.info(glideSchedule.whenNext(startDate)); -})(); diff --git a/types/servicenow-london/test/GlideScopedEvaluator.ts b/types/servicenow-london/test/GlideScopedEvaluator.ts deleted file mode 100644 index 4a3745ee11..0000000000 --- a/types/servicenow-london/test/GlideScopedEvaluator.ts +++ /dev/null @@ -1,34 +0,0 @@ -(function() { - // For this example, we created a table: "x_app_table" - // with two columns: "short_description", "test_script" - // "test_script" will store the script to be evaluated by GlideScopedEvaluator. - var gr = new GlideRecord('x_app_table'); - gr.short_description = 'Testing GlideScopedEvaluator'; - gr.test_script = "gs.getUser().getName() + ' says ' + greeting; "; - gr.insert(); - - // setup variables to be used by the script - var vars = { greeting: 'hello' }; - - //Evaluate the script from the field - var evaluator = new GlideScopedEvaluator(); - gs.info(evaluator.evaluateScript(gr, 'test_script', vars)); - // ${user_name} says hello -})(); -(function() { - //setting up a record that contains the script to be executed. - var gr = new GlideRecord('x_app_table'); - gr.short_description = 'Calculate Addition'; - gr.test_script = 'result = x + y'; - gr.insert(); - - var evaluator = new GlideScopedEvaluator(); - evaluator.putVariable('x', 100); - evaluator.putVariable('y', 200); - evaluator.putVariable('result', null); - - // Now retrieve the result - evaluator.evaluateScript(gr, 'test_script', null); - gs.info(evaluator.getVariable('result')); - // 300 -})(); diff --git a/types/servicenow-london/test/GlideScriptedProcessor.ts b/types/servicenow-london/test/GlideScriptedProcessor.ts deleted file mode 100644 index 470458074c..0000000000 --- a/types/servicenow-london/test/GlideScriptedProcessor.ts +++ /dev/null @@ -1,16 +0,0 @@ -(function() { - //Do whatever processing you need and redirect to the homepage - g_processor.redirect('/navpage.do'); -})(); -(function() { - var map = { key1: 'value1', key2: 'value2' }; - g_processor.writeJSON(map); -})(); -(function() { - var name = g_request.getParameter('name'); - g_processor.writeOutput('text/plain', 'Hello ' + name); -})(); -(function() { - var name = g_request.getParameter('name'); - g_processor.writeOutput('Hello ' + name); -})(); diff --git a/types/servicenow-london/test/GlideSecureRandomUtil.ts b/types/servicenow-london/test/GlideSecureRandomUtil.ts deleted file mode 100644 index 249f502af7..0000000000 --- a/types/servicenow-london/test/GlideSecureRandomUtil.ts +++ /dev/null @@ -1,12 +0,0 @@ -(function() { - gs.info(GlideSecureRandomUtil.getSecureRandomInt()); -})(); -(function() { - gs.info(GlideSecureRandomUtil.getSecureRandomIntBound(100)); -})(); -(function() { - gs.info(GlideSecureRandomUtil.getSecureRandomLong()); -})(); -(function() { - gs.info(GlideSecureRandomUtil.getSecureRandomString(12)); -})(); diff --git a/types/servicenow-london/test/GlideServletRequest.ts b/types/servicenow-london/test/GlideServletRequest.ts deleted file mode 100644 index 0eae56fd0c..0000000000 --- a/types/servicenow-london/test/GlideServletRequest.ts +++ /dev/null @@ -1,26 +0,0 @@ -(function() { - var contentType = g_request.getContentType(); -})(); -(function() { - var headerValue = g_request.getHeader('host'); - // demonightlyus.service-now.com -})(); -(function() { - var headerList = g_request.getHeaderNames(); - // host,connection,cache-control,authorization,accept,user-agent,accept-encoding, - // accept-language, cookie,x-forwarded-proto,x-forwarded-host,x-forwarded-for -})(); -(function() { - var headerValue = g_request.getHeaders('host'); - // demonightlyus.service-now.com -})(); -(function() { - var name = g_request.getParameter('x_snc_custom_x_snc_name'); -})(); -(function() { - var paramList = g_request.getParameterNames(); -})(); -(function() { - var daString = g_request.getQueryString(); - g_processor.writeOutput('The query string is: ' + daString); -})(); diff --git a/types/servicenow-london/test/GlideServletResponse.ts b/types/servicenow-london/test/GlideServletResponse.ts deleted file mode 100644 index c0cfc5a082..0000000000 --- a/types/servicenow-london/test/GlideServletResponse.ts +++ /dev/null @@ -1,10 +0,0 @@ -(function() { - g_response.setContentType('text/html;charset=UTF-8'); -})(); -(function() { - g_response.setHeader('host', 'demonightlyus.service-now.com'); -})(); -(function() { - // set the status to okay - g_response.setStatus(200); -})(); diff --git a/types/servicenow-london/test/GlideSession.ts b/types/servicenow-london/test/GlideSession.ts deleted file mode 100644 index fd702606b3..0000000000 --- a/types/servicenow-london/test/GlideSession.ts +++ /dev/null @@ -1,64 +0,0 @@ -(function() { - var session = gs.getSession(); - session.putClientData('test1', 'Harry'); - var clientData = session.getClientData('test1'); - gs.info(clientData); - // Harry -})(); -(function() { - var session = gs.getSession(); - var addr = session.getClientIP(); - gs.info(addr); -})(); -(function() { - var session = gs.getSession(); - var appID = session.getCurrentApplicationId(); - gs.info(appID); - // ce05b9f32b840200c5244f74b4da1501 -})(); -(function() { - var session = gs.getSession(); - var language = session.getLanguage(); - gs.info(language); - // en -})(); -(function() { - var session = gs.getSession(); - var token = session.getSessionToken(); - gs.info(token); - // 4284b5372b840200c5244f74b4da15f2c3476cf7fcb6572afa4ef9d5e6d307a5fd9e1da7 -})(); -(function() { - var session = gs.getSession(); - var zoneName = session.getTimeZoneName(); - gs.info(zoneName); - // US/Pacific -})(); -(function() { - var session = gs.getSession(); - var URL = session.getUrlOnStack(); - gs.info(URL); - // sys_app.do?sys_id=ce05b9f32b840200c5244f74b4da1501&sysparm_goto_url=sys_app.do - // %3Fsys_id%3Dce05b9f32b840200c5244f74b4da1501 -})(); -(function() { - var isImpersonator = gs.getSession().isImpersonating(); - gs.info(isImpersonator); -})(); -(function() { - var interActive = gs.getSession().isInteractive(); - gs.info(interActive); -})(); -(function() { - var session = gs.getSession(); - var loggedIn = session.isLoggedIn(); - gs.info(loggedIn); - // true -})(); -(function() { - var session = gs.getSession(); - session.putClientData('test1', 'Harry'); - var clientData = session.getClientData('test1'); - gs.info(clientData); - // Harry -})(); diff --git a/types/servicenow-london/test/GlideStringUtil.ts b/types/servicenow-london/test/GlideStringUtil.ts deleted file mode 100644 index 1cf7a3ab6b..0000000000 --- a/types/servicenow-london/test/GlideStringUtil.ts +++ /dev/null @@ -1,85 +0,0 @@ -(function() { - var filename = '../../../../../../etc/passwd'; - var cleanFilename = GlideStringUtil.dotToUnderBar(filename); - gs.info(cleanFilename); - // __/__/__/__/__/__/etc/passwd -})(); -(function() { - var mystring = "let's escape some quotes"; - var escapeQuote = GlideStringUtil.escapeAllQuotes(mystring); - gs.info(escapeQuote); - // lets escape some quotes -})(); -(function() { - var mystring = ' string \n to escape'; - var escapedString = GlideStringUtil.escapeForHomePage(mystring); - gs.info(escapedString); - // %3ctest%3e string \n to escape -})(); -(function() { - var mydata = '"<>&'; - mydata = GlideStringUtil.escapeHTML(mydata); - gs.info(mydata); - // "<>& -})(); -(function() { - var mystring = 'test \x09 non \x00 printable \x07 chars'; - var escapedString = GlideStringUtil.escapeNonPrintable(mystring); - gs.info(escapedString); - // test \t non \u0000 printable \u0007 chars -})(); -(function() { - var myquery = 'test^Test'; - var escapedQuery = GlideStringUtil.escapeQueryTermSeparator(myquery); - gs.info(escapedQuery); - // test^^Test -})(); -(function() { - var mystring = "let's try escapeTicks"; - var escaped = GlideStringUtil.escapeTicks(mystring); - gs.info(escaped); - // let\'s try escapeTicks -})(); -(function() { - var mydata = '&'; - var htmlvalue = GlideStringUtil.getHTMLValue(mydata); - gs.info(htmlvalue); - // & -})(); -(function() { - var mystring = '123 test 456 String 789 cleaning'; - var onlyNumeric = GlideStringUtil.getNumeric(mystring); - gs.info(onlyNumeric); - // 123456789 -})(); -(function() { - // (adding a "*" to corrupt the base64 format) - var base64 = 'GethdTYehdtshetB*'; - var isValid = GlideStringUtil.isBase64(base64); - gs.info(isValid); - // false -})(); -(function() { - var sysID = '62826bf03710200044e0bfc8bcbe5df1'; - var isElig = GlideStringUtil.isEligibleSysID(sysID); - gs.info(isElig); - // true -})(); -(function() { - var mystring = 'new line break \n, this is after the break'; - var replaceNewLine = GlideStringUtil.newLinesToBreaks(mystring); - gs.info(replaceNewLine); - // new line break
, this is after the break -})(); -(function() { - var mystring = 'test with \n (new line) and \t (tabulation)'; - var normalizedString = GlideStringUtil.normalizeWhitespace(mystring); - gs.info(normalizedString); - // test with (new line) and (tabulation) -})(); -(function() { - var mydata = '"<>&'; - var unescaped = GlideStringUtil.unescapeHTML(mydata); - gs.info(unescaped); - // "<>& -})(); diff --git a/types/servicenow-london/test/GlideSysAttachment.ts b/types/servicenow-london/test/GlideSysAttachment.ts deleted file mode 100644 index 0ffdd02fcb..0000000000 --- a/types/servicenow-london/test/GlideSysAttachment.ts +++ /dev/null @@ -1 +0,0 @@ -// TODO \ No newline at end of file diff --git a/types/servicenow-london/test/GlideSystem.ts b/types/servicenow-london/test/GlideSystem.ts deleted file mode 100644 index 0458978982..0000000000 --- a/types/servicenow-london/test/GlideSystem.ts +++ /dev/null @@ -1,211 +0,0 @@ -(function() { - gs.addErrorMessage('Invalid account'); -})(); -(function() { - if (!current.u_date1.nil() && !current.u_date2.nil()) { - var start = current.u_date1.getGlideObject().getNumericValue(); - var end = current.u_date2.getGlideObject().getNumericValue(); - if (start > end) { - gs.addInfoMessage('start must be before end'); - current.u_date1.setError('start must be before end'); - current.setAbortAction(true); - } - } -})(); -(function() { - function contractNoticeDue() { - var gr = new GlideRecord('contract'); - gr.addQuery('u_contract_status', 'Active'); - gr.query(); - while (gr.next()) { - if (gr.u_termination_date <= gs.daysAgo(-90) && gr.u_contract_duration == 'Long') { - gr.u_contract_status = 'In review'; - } else if ( - gr.u_termination_date <= gs.daysAgo(-50) && - gr.u_contract_duration == 'Medium' - ) { - gr.u_contract_status = 'In review'; - } else if ( - gr.u_termination_date <= gs.daysAgo(-10) && - gr.u_contract_duration == 'Short' - ) { - gr.u_contract_status = 'In review'; - } - } - gr.update(); - } -})(); -(function() { - var gr = new GlideRecord('sysapproval_approver'); - gr.addQuery('state', 'requested'); - gr.addQuery('sys_updated_on', '<', gs.daysAgoStart(5)); - gr.query(); -})(); -(function() { - gs.debug('This is a debug message'); - var myFirstName = 'Abel'; - var myLastName = 'Tuter'; - gs.debug('This is a debug message from {0}.{1}', myFirstName, myLastName); -})(); -(function() { - gs.error('This is an error message'); - var myFirstName = 'Abel'; - var myLastName = 'Tuter'; - gs.error('This is an error message from {0}.{1}', myFirstName, myLastName); -})(); -(function() { - if (current.operation() != 'insert' && current.comments.changes()) { - gs.eventQueue('incident.commented', current, gs.getUserID(), gs.getUserName()); - } -})(); -(function() { - var personalId = gs.generateGUID(); - gs.info(personalId); - // af770511ff013100e04bfffffffffff6 -})(); -(function() { - return gs.getCallerScopeName(); -})(); -(function() { - var verStr = gs.getCssCacheVersionString(); - gs.info(verStr); - // _d82979516f0171005be8883e6b3ee4cf&theme= -})(); -(function() { - var currentId = gs.getCurrentApplicationId(); - gs.info(currentId); - // 04936cb16f30b1005be8883e6b3ee4e0 -})(); -(function() { - var currentScope = gs.getCurrentScopeName(); - gs.info(currentScope); -})(); -(function() { - var myMessage = gs.getEscapedMessage('Hello {0}', ['mom']); -})(); -(function() { - var attachment_link = gs.getProperty('glide.servlet.uri'); - gs.info(attachment_link); - // https://instance.service-now.com/ -})(); -(function() { - if (!gs.hasRole('admin') && !gs.hasRole('user_admin') && gs.getSession().isInteractive()) { - current.addQuery('active', 'true'); - } -})(); -(function() { - var myUserObject = gs.getSessionID(); - gs.info(myUserObject); -})(); -(function() { - gs.info(gs.getTimeZoneName()); -})(); -(function() { - gs.info(gs.getUrlOnStack()); -})(); -(function() { - var myUserObject = gs.getUser(); -})(); -(function() { - gs.info(gs.getUserDisplayName()); -})(); -(function() { - gs.info(gs.getUserID()); -})(); -(function() { - gs.info(gs.getUserName()); -})(); -(function() { - if (!gs.hasRole('admin') && !gs.hasRole('groups_admin') && gs.getSession().isInteractive()) { - var qc = current.addQuery('u_hidden', '!=', 'true'); //cannot see hidden groups... - qc.addOrCondition('sys_id', 'javascript:getMyGroups()'); //...unless in the hidden group - gs.info('User has admin and groups admin roles'); - } else { - gs.info('User does not have both admin and groups admin roles'); - } -})(); -(function() { - if (current.operation() == 'insert') { - // If no due date was specified, calculate a default - if (current.due_date == '') { - if (current.urgency == '1') { - // Set due date to 4 hours ahead of current time - current.due_date = gs.hoursAgo(-4); - } - - if (current.urgency == '2') { - // Set due date to 2 days ahead of current time - current.due_date = gs.daysAgo(-2); - } - - if (current.urgency == '3') { - // Set due date to 7 days ahead of current time - current.due_date = gs.daysAgo(-7); - } - } - } -})(); -(function() { - gs.include('PrototypeServer'); -})(); -(function() { - gs.info('This is an info message'); - var myFirstName = 'Abel'; - var myLastName = 'Tuter'; - gs.info('This is an info message from {0}.{1}', myFirstName, myLastName); -})(); -(function() { - gs.debug('This is a log message'); - var myFirstName = 'Abel'; - var myLastName = 'Tuter'; - gs.debug('This is a log message from {0}.{1}', myFirstName, myLastName); - gs.info(gs.isDebugging()); -})(); -(function() { - if (!gs.hasRole('admin') && gs.getSession().isInteractive()) { - var qc1 = current.addQuery('u_group', ''); - var gra = new GlideRecord('sys_user_grmember'); - gra.addQuery('user', gs.getUserID()); - gra.query(); - while (gra.next()) { - qc1.addOrCondition('u_group', gra.group); - } - } -})(); -(function() { - gs.info(gs.isLoggedIn()); -})(); -(function() { - if (gs.isMobile()) gs.info('submitted from mobile UI'); - else gs.info('NOT submitted from mobile UI'); -})(); -(function() { - var gr = new GlideRecord('incident'); - gs.info(gs.nil(gr)); -})(); -(function() { - gs.setProperty('glide.foo', 'bar', 'foo'); - gs.info(gs.getProperty('glide.foo')); -})(); -(function() { - gs.setRedirect( - 'com.glideapp.servicecatalog_cat_item_view.do?sysparm_id=d41ce5bac611227a0167f4bf8109bf70&sysparm_user=' + - current.sys_id + - '&sysparm_email=' + - current.email - ); -})(); -(function() { - gs.info(gs.tableExists('incident')); -})(); -(function() { - gs.warn('This is a warning'); - var myFirstName = 'Abel'; - var myLastName = 'Tuter'; - gs.warn('This is a warning from {0}.{1}', myFirstName, myLastName); -})(); -(function() { - var xmlString = 'value'; - var jsonObject = gs.xmlToJSON(xmlString); - gs.info(jsonObject); -})(); diff --git a/types/servicenow-london/test/GlideTime.ts b/types/servicenow-london/test/GlideTime.ts deleted file mode 100644 index 805e4da23a..0000000000 --- a/types/servicenow-london/test/GlideTime.ts +++ /dev/null @@ -1,46 +0,0 @@ -(function() { - var gt = new GlideTime(); - gs.info(gt.getDisplayValue()); -})(); -(function() { - var gt = new GlideTime(10000); - gs.info(gt.getDisplayValue()); -})(); -(function() { - var gt = new GlideTime(); - gt.setValue('12:00:00'); - gs.info(gt.getByFormat('HH:mm')); -})(); -(function() { - var gt = new GlideTime(); - gt.setDisplayValue('12:00:00'); // User Time Zone - gs.info(gt.getDisplayValue()); // User Time Zone -})(); -(function() { - var gt = new GlideTime(); - gt.setValue('01:00:00'); //Internal Time Zone , UTC - gs.info(gt.getDisplayValueInternal()); //User Time Zone -})(); -(function() { - var gt = new GlideTime(); - gs.info(gt.getValue()); // Internal Time Zone, UTC -})(); -(function() { - var gt = new GlideTime(); - gt.setDisplayValue('01:00:00'); // User Time Zone - gs.info(gt.getDisplayValueInternal()); // User Time Zone -})(); -(function() { - var gt = new GlideTime(); - gt.setValue('01:00:00'); //Internal Time Zone, UTC - gs.info('time is ' + gt.getByFormat('hh:mm:ss')); -})(); -(function() { - var gd1 = new GlideTime(); - gd1.setDisplayValue('09:00:00'); - var gd2 = new GlideTime(); - gd2.setDisplayValue('09:10:00'); - - var dur = GlideDate.subtract(gd1, gd2); //the difference between gdt1 and gdt2 - gs.info(dur.getDisplayValue()); -})(); diff --git a/types/servicenow-london/test/GlideUser.ts b/types/servicenow-london/test/GlideUser.ts deleted file mode 100644 index c554843db3..0000000000 --- a/types/servicenow-london/test/GlideUser.ts +++ /dev/null @@ -1,59 +0,0 @@ -(function() { - var currentUser = gs.getUser(); - gs.info(currentUser.getCompanyID()); -})(); -(function() { - var currentUser = gs.getUser(); - gs.info(currentUser.getDisplayName()); -})(); -(function() { - var domain = new GlideRecord('domain'); - domain.get(gs.getUser().getDomainID()); - gs.info(domain.name); -})(); -(function() { - var currentUser = gs.getUser(); - gs.info(currentUser.getEmail()); -})(); -(function() { - var currentUser = gs.getUser(); - gs.info(currentUser.getFirstName()); -})(); -(function() { - var currentUser = gs.getUser(); - gs.info(currentUser.getID()); -})(); -(function() { - var currentUser = gs.getUser(); - gs.info(currentUser.getLastName()); -})(); -(function() { - var currentUser = gs.getUser(); - gs.info(currentUser.getName()); -})(); -(function() { - var currentUser = gs.getUser(); - currentUser.savePreference('myPref', 'red'); - gs.info(currentUser.getPreference('myPref')); -})(); -(function() { - var currentUser = gs.getUser(); - gs.info(currentUser.getRoles()); -})(); -(function() { - var currentUser = gs.getUser(); - gs.info(currentUser.getUserRoles()); -})(); -(function() { - var currentUser = gs.getUser(); - gs.info(currentUser.hasRole('admin')); -})(); -(function() { - var currentUser = gs.getUser(); - gs.info(currentUser.isMemberOf('Capacity Mgmt')); -})(); -(function() { - var currentUser = gs.getUser(); - currentUser.savePreference('myPref', 'red'); - gs.info(currentUser.getPreference('myPref')); -})(); diff --git a/types/servicenow-london/test/RESTAPIRequest.ts b/types/servicenow-london/test/RESTAPIRequest.ts deleted file mode 100644 index 14ec7ef8e3..0000000000 --- a/types/servicenow-london/test/RESTAPIRequest.ts +++ /dev/null @@ -1,22 +0,0 @@ -function testRESTAPIRequest(request: sn_ws.RESTAPIRequest) { - var entry; - var id; - var requestBody = request.body; - var requestData = requestBody.data; - if (requestData instanceof Array) { - entry = requestData[0].name; - id = requestData[0].id; - } else { - entry = requestData.name; - id = requestData.id; - } - - var requestStream = requestBody.dataStream; - var requestString = requestBody.dataString; - requestBody.hasNext(); - requestBody.hasNext(); - var requestEntry = requestBody.nextEntry(); - - var name = requestEntry.name; - requestEntry = requestBody.nextEntry(); -} diff --git a/types/servicenow-london/test/RESTAPIRequestBody.ts b/types/servicenow-london/test/RESTAPIRequestBody.ts deleted file mode 100644 index 6f4120d55f..0000000000 --- a/types/servicenow-london/test/RESTAPIRequestBody.ts +++ /dev/null @@ -1,33 +0,0 @@ -function testRESTAPIRequestBody(request: sn_ws.RESTAPIRequest) { - var requestBody = request.body; - // Returns instance of RESTAPIRequestBody - - var headers = request.headers; - var acceptHeader = headers.Accept; - var myCustomHeader = headers.myCustom; - var specialHeader = headers['special - header']; - var pathParams = request.pathParams; - var tableName = pathParams.tableName; - // "myApp_table" - - var id = pathParams.id; - // "1234" - - var queryParams = request.queryParams; - var isActiveQuery = queryParams.active; - // false - - var nameQueryVal = queryParams.name; - // "now" - - var query = request.queryString; - // "active=false&name=now" - - var query2 = request.uri; - // "api/now/table/myTable" - - var query3 = request.url; - // "https://instance.service-now.com/api/now/table/myTable?active=false&name=now" - - var acceptHeader = request.getHeader('accept'); -} diff --git a/types/servicenow-london/test/RESTAPIResponse.ts b/types/servicenow-london/test/RESTAPIResponse.ts deleted file mode 100644 index 9938141393..0000000000 --- a/types/servicenow-london/test/RESTAPIResponse.ts +++ /dev/null @@ -1,28 +0,0 @@ -function testRESTAPIResponse(response: sn_ws.RESTAPIResponse) { - response.setContentType('application/json'); - response.setStatus(200); - var writer = response.getStreamWriter(); - - var body: any = {}; - body.name = 'incident'; - body.number = '1234'; - body.caller = { id: 'user1' }; - response.setBody(body); - - var bodyArray = []; - body = {}; - body.name = 'incident'; - body.number = '1234'; - body.caller = { id: 'user1' }; - bodyArray.push(body); - response.setBody(bodyArray); - - response.setHeader('Location', ''); - - var headers: any = {}; - headers['X-Total-Count'] = 100; - headers.Location = 'https://instance.service-now.com/'; - response.setHeaders(headers); - - response.setStatus(200); -} diff --git a/types/servicenow-london/test/RESTAPIResponseStream.ts b/types/servicenow-london/test/RESTAPIResponseStream.ts deleted file mode 100644 index 75f30d88d3..0000000000 --- a/types/servicenow-london/test/RESTAPIResponseStream.ts +++ /dev/null @@ -1,17 +0,0 @@ -function testRESTAPIResponseStream(response: sn_ws.RESTAPIResponse, attachmentStream: any) { - response.setContentType('application/json'); - response.setStatus(200); - var writer = response.getStreamWriter(); - writer.writeStream(attachmentStream); - - response.setContentType('application/json'); - response.setStatus(200); - var writer = response.getStreamWriter(); - var body: any = { - name: 'user1', - id: 1234, - roles: [{ name: 'admin' }, { name: 'itil' }] - }; - writer.writeString("{'name':'user','id':'1234'}"); - writer.writeString(JSON.stringify(body)); -} diff --git a/types/servicenow-london/test/RESTMessageV2.ts b/types/servicenow-london/test/RESTMessageV2.ts deleted file mode 100644 index 4368c70293..0000000000 --- a/types/servicenow-london/test/RESTMessageV2.ts +++ /dev/null @@ -1,106 +0,0 @@ -(function() { - var sm = new sn_ws.RESTMessageV2('', 'get'); - var response = sm.execute(); - var response = sm.executeAsync(); - response.waitForResponse(60); - - var endpoint = sm.getEndpoint(); - var body = sm.getRequestBody(); - var header = sm.getRequestHeader('Accept'); - var headers = sm.getRequestHeaders(); - - sm.setBasicAuth('username', 'password'); - sm.setEccCorrelator('unique_identifier'); - sm.setEccParameter('source', 'http://very.long.endpoint.url'); - sm.setEndpoint('http://web.service.endpoint'); - sm.setHttpMethod('post'); - sm.setHttpTimeout(6000); - sm.setLogLevel('all'); - sm.setMIDServer('mid_server_name'); - sm.setMutualAuth('mutual_auth_profile_name'); - sm.setQueryParameter('sysparm_query', 'active=true^ORDERBYnumber^ORDERBYDESCcategory'); - sm.setRequestHeader('Accept', 'Application/json'); - sm.setStringParameter('s', 'NOW'); - sm.setStringParameterNoEscape('s', 'NOW'); - - var body = ''; - sm.setRequestBody(body); -})(); -(function sampleRESTMessageV2() { - try { - var request = new sn_ws.RESTMessageV2(); - request.setHttpMethod('get'); - - var attachment_sys_id = '', - tablename = 'incident', - recordSysId = '', - response, - httpResponseStatus, - filename = ''; - - //endpoint - ServiceNow REST Attachment API - request.setEndpoint( - 'https://.service-now.com/api/now/attachment/' + - attachment_sys_id + - '/file' - ); - request.setBasicAuth('', ''); - - //RESTMessageV2 - saveResponseBodyAsAttachment(String tableName, String recordSysId, String fileName) - request.saveResponseBodyAsAttachment(tablename, recordSysId, filename); - - response = request.execute(); - httpResponseStatus = response.getStatusCode(); - - gs.info(' http response status_code: ' + httpResponseStatus); - } catch (ex) { - var message = ex.getMessage(); - gs.info(message); - } -})(); -(function() { - var requestBody; - var response; - var responseBody; - var status; - var sm; - try { - // Might throw exception if message doesn't exist or not visible due to scope. - sm = new sn_ws.RESTMessageV2('', 'get'); - - //set auth profile to an OAuth 2.0 profile record. - sm.setAuthenticationProfile('oauth2', '1234adsf123212131123qasdsf'); - - sm.setStringParameter('symbol', 'NOW'); - sm.setStringParameterNoEscape('xml_data', 'test'); - - //In milliseconds. Wait at most 10 seconds for response from http request. - sm.setHttpTimeout(10000); - //Might throw exception if http connection timed out or some issue - //with sending request itself because of encryption/decryption of password. - response = sm.execute(); - responseBody = response.haveError() ? response.getErrorMessage() : response.getBody(); - status = response.getStatusCode(); - } catch (ex) { - responseBody = ex.getMessage(); - status = '500'; - } finally { - requestBody = sm ? sm.getRequestBody() : null; - } -})(); -(function sampleRESTMessageV2() { - try { - var request = new sn_ws.RESTMessageV2(); - request.setHttpMethod('post'); - request.setEndpoint(''); - request.setRequestBodyFromAttachment(''); - - var response = request.execute(); - var httpResponseStatus = response.getStatusCode(); - - gs.info('http response status_code: ' + httpResponseStatus); - } catch (ex) { - var message = ex.getMessage(); - gs.info(message); - } -})(); diff --git a/types/servicenow-london/test/RESTResponseV2.ts b/types/servicenow-london/test/RESTResponseV2.ts deleted file mode 100644 index 79ede22cc4..0000000000 --- a/types/servicenow-london/test/RESTResponseV2.ts +++ /dev/null @@ -1,22 +0,0 @@ -(function() { - var sm = new sn_ws.RESTMessageV2('', 'get'); - var response = sm.execute(); - var allHeaders = response.getAllHeaders(); - for (var header in allHeaders) { - gs.info(allHeaders[header].name + ': ' + allHeaders[header].value); - } - var cookies = response.getCookies(); - for (var i = 0; i < cookies.size(); i++) { - gs.info('cookie: ' + cookies.get(i)); - } - var responseBody = response.getBody(); - var errorCode = response.getErrorCode(); - var errorMsg = response.getErrorMessage(); - var headerVal = response.getHeader('Content-Type'); - var headers = response.getHeaders(); - var queryString = response.getQueryString(); - var statusCode = response.getStatusCode(); - var error = response.haveError(); - var response = sm.executeAsync(); - response.waitForResponse(60); -})(); diff --git a/types/servicenow-london/test/SOAPMessageV2.ts b/types/servicenow-london/test/SOAPMessageV2.ts deleted file mode 100644 index 5181a9be3b..0000000000 --- a/types/servicenow-london/test/SOAPMessageV2.ts +++ /dev/null @@ -1,28 +0,0 @@ -(function() { - var sm = new sn_ws.SOAPMessageV2(); - sm = new sn_ws.SOAPMessageV2('StockQuote', 'GetQuote'); - var response = sm.execute(); - response = sm.executeAsync(); - var endpoint = sm.getEndpoint(); - var requestBody = sm.getRequestBody(); - var header = sm.getRequestHeader('Accept'); - var requestHeaders = sm.getRequestHeaders(); - sm.setBasicAuth('username', 'password'); - sm.setEccCorrelator('unique_id'); - sm.setEccParameter('source', 'http://very.long.endpoint'); - sm.setEndpoint('http://web.service.endpoint'); - sm.setHttpTimeout(6000); - sm.setMutualAuth('auth_profile_name'); - var body = ''; - sm.setRequestBody(body); - sm.setRequestHeader('Accept', 'Application/json'); - sm.setSOAPAction('GetQuote'); - sm.setStringParameter('symbol', 'NOW'); - sm.setStringParameterNoEscape('symbol', 'NOW'); - sm.setWSSecurity( - '70d65e074f3812001f6eac118110c71a', - 'Quote keys', - 'UXr82cqX75Z7MaSa+EyjGA==', - 'ba969a074f3812001f6eac118110c76d' - ); -})(); diff --git a/types/servicenow-london/test/SOAPResponseV2.ts b/types/servicenow-london/test/SOAPResponseV2.ts deleted file mode 100644 index c7a4c181a3..0000000000 --- a/types/servicenow-london/test/SOAPResponseV2.ts +++ /dev/null @@ -1,20 +0,0 @@ -(function() { - var r = new sn_ws.SOAPMessageV2('', 'get'); - var response = r.execute(); - var allHeaders = response.getAllHeaders(); - for (var h in allHeaders) { - gs.info(allHeaders[h].name + ': ' + allHeaders[h].value); - } - var body = response.getBody(); - var cookies = response.getCookies(); - for (var i = 0; i < cookies.size(); i++) { - gs.info('cookie: ' + cookies.get(i)); - } - var errorCode = response.getErrorCode(); - var errorMsg = response.getErrorMessage(); - var headerVal = response.getHeader("Accept"); - var headers = response.getHeaders(); - var statusCode = response.getStatusCode(); - var error = response.haveError(); - response.waitForResponse(60); -})(); diff --git a/types/servicenow-london/test/ScopedElementDescriptor.ts b/types/servicenow-london/test/ScopedElementDescriptor.ts deleted file mode 100644 index a0da98ba85..0000000000 --- a/types/servicenow-london/test/ScopedElementDescriptor.ts +++ /dev/null @@ -1,19 +0,0 @@ -(function() { - var gr = new GlideRecord('incident'); - gr.query('priority', '1'); - var field = gr.getElement('priority'); - var ed = field.getED(); - - var s = ed.getAttachmentEncryptionType(); - s = ed.getEncryptionType(); - s = ed.getInternalType(); - s = ed.getLabel(); - var n = ed.getLength(); - s = ed.getName(); - s = ed.getPlural(); - var b = ed.hasAttachmentsEncrypted(); - b = ed.isAutoOrSysID(); - b = ed.isChoiceTable(); - b = ed.isEdgeEncrypted(); - b = ed.isVirtual(); -})(); diff --git a/types/servicenow-london/test/ScopedGlideElement.ts b/types/servicenow-london/test/ScopedGlideElement.ts deleted file mode 100644 index 8d749d848e..0000000000 --- a/types/servicenow-london/test/ScopedGlideElement.ts +++ /dev/null @@ -1,13 +0,0 @@ -(function() { - var gr = new GlideRecord('incident'); - var el = gr.getElement('active'); - var b = el.changes(); - b = el.changesFrom(true); - b = el.changesTo(false); - var s = el.getAttribute('tree_picker'); - var sa = el.getChoices(); - s = el.getChoiceValue(); - s = el.getDecryptedValue(); - s = el.getDisplayValue(); - var ed = el.getED(); -})(); diff --git a/types/servicenow-london/test/ScopedGlideRecord.ts b/types/servicenow-london/test/ScopedGlideRecord.ts deleted file mode 100644 index d2a2ed715a..0000000000 --- a/types/servicenow-london/test/ScopedGlideRecord.ts +++ /dev/null @@ -1,400 +0,0 @@ -interface ScopedGlideRecord { - new (tableName: 'othertype'): OtherType; -} -interface OtherType extends ScopedGlideRecord { - someproperty: string; -} -(function testMerging() { - var gr = new GlideRecord('othertype'); - gr.someproperty = 'foo'; -})(); -(function() { - var inc = new GlideRecord('incident'); - inc.addActiveQuery(); - inc.query(); -})(); -(function() { - var queryString = 'priority=1^ORpriority=2'; - var gr = new GlideRecord('incident'); - gr.addEncodedQuery(queryString); - gr.query(); - while (gr.next()) { - gs.addInfoMessage(gr.number); - } -})(); -(function() { - var functionBuilder = new GlideDBFunctionBuilder(); - var myAddingFunction = functionBuilder.add(); - myAddingFunction = functionBuilder.field('order'); - myAddingFunction = functionBuilder.field('priority'); - var func = functionBuilder.build(); - - var gr = new GlideRecord('incident'); - gr.addFunction(func); - gr.addQuery(func, '<', 5); - gr.query(); - while (gr.next()) gs.info(gr.getValue(func)); -})(); -(function() { - var prob = new GlideRecord('problem'); - prob.addJoinQuery('incident'); - prob.query(); -})(); -(function() { - // Look for Problem records that have associated Incident records - var gr = new GlideRecord('problem'); - var grSQ = gr.addJoinQuery('incident'); - - // Where the Problem records are "active=false" - gr.addQuery('active', 'false'); - - // And the Incident records are "active=true" - grSQ.addCondition('active', 'true'); - - // Query - gr.query(); - - // Iterate and output results - while (gr.next()) { - gs.info(gr.getValue('number')); - } -})(); -(function() { - var gr = new GlideRecord('problem'); - gr.addJoinQuery('incident', 'opened_by', 'caller_id'); - gr.query(); -})(); -(function() { - var target = new GlideRecord('incident'); - target.addNotNullQuery('short_description'); - target.query(); // Issue the query to the database to get all records where short_description is not null - while (target.next()) { - // add code here to process the incident record - } -})(); -(function() { - var target = new GlideRecord('incident'); - target.addNullQuery('short_description'); - target.query(); // Issue the query to the database to get all records where short_description is null - while (target.next()) { - // add code here to process the incident record - } -})(); -(function() { - var rec = new GlideRecord('incident'); - rec.addQuery('active', true); - rec.query(); - while (rec.next()) { - rec.active = false; - gs.info('Active incident ' + rec.number + ' closed'); - rec.update(); - } -})(); -(function() { - var rec = new GlideRecord('incident'); - rec.addQuery('active', true); - rec.addQuery('sys_created_on', '>', '2010-01-19 04:05:00'); - rec.query(); - while (rec.next()) { - rec.active = false; - gs.info('Active incident ' + rec.number + ' closed'); - rec.update(); - } -})(); -(function() { - var gr = new GlideRecord('incident'); - gr.addQuery('number', 'IN', 'INC00001,INC00002'); - gr.query(); - while (gr.next()) { - //do something.... - } -})(); -(function() { - var rec = new GlideRecord('incident'); - rec.addQuery('active=true'); - rec.query(); - while (rec.next()) { - rec.active = false; - gs.info('Active incident ' + rec.number + ' closed'); - rec.update(); - } -})(); -(function() { - var gr = new GlideRecord('incident'); - gs.info(gr.canCreate()); - gs.info(gr.canDelete()); - gs.info(gr.canRead()); - gs.info(gr.canWrite()); -})(); -(function() { - var gr = new GlideRecord('incident'); - gr.orderBy('number'); - gr.chooseWindow(2, 4); - gr.query(); - if (gr.next()) { - gs.info(gr.number + ' is within window'); - } -})(); -(function() { - var inc = new GlideRecord('incident'); - inc.get('17c90efb13418700cc36b1422244b05d'); - gs.info(inc.calendar_duration.dateNumericValue()); -})(); -(function() { - var gr = new GlideRecord('incident'); - gr.addQuery('active', 'false'); //to delete all inactive incidents - gr.deleteMultiple(); -})(); -(function() { - var gr = new GlideRecord('incident'); - //to delete one record - if (gr.get('99ebb4156fa831005be8883e6b3ee4b9')) { - gr.deleteRecord(); - } -})(); -(function() { - var grIncident = new GlideRecord('incident'); - var returnValue = grIncident.get('99ebb4156fa831005be8883e6b3ee4b9'); - gs.info(returnValue); // logs true or false - gs.info(grIncident.number); // logs Incident Number -})(); -(function() { - var grIncident = new GlideRecord('incident'); - var returnValue = grIncident.get('caller_id.name', 'Sylivia Wayland'); - gs.info(returnValue); // logs true or false - gs.info(grIncident.number); // logs Incident Number -})(); -doit(); -function doit() { - var gr = new GlideRecord('sys_user'); - gr.query('user_name', 'admin'); - if (gr.next()) { - gs.info('we got one'); - gs.info(gr.location.getAttribute('tree_picker')); - } -} -(function() { - var gr = new GlideRecord('incident'); - gr.get('sys_id', 'ef43c6d40a0a0b5700c77f9bf387afe3'); - gs.info(gr.getDisplayValue()); -})(); -(function() { - var gr = new GlideRecord('incident'); - var ed = gr.getED(); - gs.info(ed.getLabel()); -})(); -(function() { - var elementName = 'short_description'; - var gr = new GlideRecord('incident'); - gr.initialize(); - gr.setValue(elementName, 'My DB is not working'); - gr.insert(); - gs.info(gr.getElement('short_description')); -})(); -(function() { - var gr = new GlideRecord('incident'); - gr.addQuery('active', true); - gr.addQuery('priority', 1); - gr.query(); - var encodedQuery = gr.getEncodedQuery(); - gs.info(encodedQuery); -})(); -(function() { - var gr = new GlideRecord('incident'); - gs.info(gr.getLabel()); -})(); -(function() { - // Setup a data policy where short_description field in incident is mandatory - var gr = new GlideRecord('incident'); - gr.insert(); // insert without data in mandatory field - var errormessage = gr.getLastErrorMessage(); - gs.info(errormessage); -})(); -(function() { - var gr = new GlideRecord('incident'); - gr.addActiveQuery(); - gr.addQuery('priority', 1); - gr.query(); - gr.next(); - gs.info(gs.getProperty('glide.servlet.uri') + gr.getLink(false)); -})(); -(function() { - var gr = new GlideRecord('incident'); - var recordClassName = gr.getRecordClassName(); - gs.info(recordClassName); -})(); -(function() { - var gr = new GlideRecord('incident'); - gr.query(); - gs.info('Records in incident table: ' + gr.getRowCount()); -})(); -(function() { - var gr = new GlideRecord('incident'); - gs.info(gr.getTableName()); -})(); -(function() { - var gr = new GlideRecord('kb_knowledge'); - gr.query(); - gr.next(); - var uniqueid = gr.getUniqueValue(); - gs.info(uniqueid); -})(); -(function() { - var gr = new GlideRecord('incident'); - gr.orderBy('number'); - gr.query('active', 'true'); - gr.next(); - gs.info(gr.getValue('number')); -})(); -(function() { - var rec = new GlideRecord('incident'); - rec.query(); - if (rec.hasNext()) { - gs.info('Table is not empty'); - } -})(); -(function() { - var gr = new GlideRecord('incident'); - gr.initialize(); - gr.name = 'New Incident'; - gr.description = 'Incident description'; - gr.insert(); -})(); -(function() { - var gr = new GlideRecord('incident'); - gr.initialize(); - gr.name = 'New Incident'; - gr.description = 'Incident description'; - gr.insert(); -})(); -(function() { - var gr = new GlideRecord('incident'); - gs.info(gr.isActionAborted()); -})(); -(function() { - var gr = new GlideRecord('x_app_table'); - gr.newRecord(); // create a new record and populate it with default values - gs.info(gr.isNewRecord()); -})(); -(function() { - var gr = new GlideRecord('incident'); - gs.info(gr.isValid()); - var anotherGr = new GlideRecord('wrong_table_name'); - gs.info(anotherGr.isValid()); -})(); -(function() { - var gr = new GlideRecord('incident'); - gr.initialize(); - gs.info(gr.isValidField('short_description')); -})(); -(function() { - var rec = new GlideRecord('incident'); - rec.query(); - while (rec.next()) { - gs.info(rec.number + ' exists'); - } - gs.info(rec.isValidRecord()); -})(); -(function() { - var gr = new GlideRecord('x_app_table'); - gr.newRecord(); - gs.info(gr.isNewRecord()); -})(); -(function() { - var rec = new GlideRecord('incident'); - rec.query(); - while (rec.next()) { - gs.info(rec.number + ' exists'); - } -})(); -(function() { - //Commonly used in a business rule, returns insert if the current operation is insert - gs.info('current operation ' + current.operation()); -})(); -(function() { - var queryString = 'priority=2'; - var gr = new GlideRecord('incident'); - gr.orderBy('short_description'); // Ascending Order - gr.addEncodedQuery(queryString); - gr.query(); - while (gr.next()) { - gs.info(gr.short_description); - } -})(); -(function() { - var queryString = 'priority=2'; - var gr = new GlideRecord('incident'); - gr.orderByDesc('short_description'); //Descending Order - gr.addEncodedQuery(queryString); - gr.query(); - while (gr.next()) { - gs.info(gr.short_description); - } -})(); -(function() { - var rec = new GlideRecord('incident'); - rec.query(); - while (rec.next()) { - gs.info(rec.number + ' exists'); - } -})(); -(function() { - // Often used in business rule to check whether the current operation should be aborted. - if (current.size > 16) { - current.setAbortAction(true); - } -})(); -(function() { - var gr = new GlideRecord('incident'); - gr.orderByDesc('sys_created_on'); - gr.setLimit(10); - gr.query(); // this retrieves latest 10 incident records created -})(); -(function() { - var gr = new GlideRecord('incident'); - gr.short_description = 'The third floor printer is broken'; - gr.setNewGuidValue('eb4636ca6f6d31005be8883e6b3ee333'); - gr.insert(); - gs.info(gr.sys_id); -})(); -(function() { - var elementName = 'short_description'; - var gr = new GlideRecord('incident'); - gr.initialize(); - gr.setValue(elementName, 'My DB is not working'); - gr.insert(); -})(); -(function() { - //Enable business rules, scripts engines for x_app_table - var gr = new GlideRecord('x_app_table'); - gr.setWorkflow(true); -})(); -(function() { - var gr = new GlideRecord('incident'); - gr.get('99ebb4156fa831005be8883e6b3ee4b9'); - gr.short_description = 'Update the short description'; - gr.update(); - gs.info(gr.getElement('short_description')); -})(); -(function() { - // update the state of all active incidents to 4 - "Awaiting User Info" - var gr = new GlideRecord('incident'); - gr.addQuery('active', true); - gr.query(); - gr.setValue('state', 4); - gr.updateMultiple(); -})(); -(function() { - var rec = new GlideRecord('sys_template'); - rec.query(); - while (rec._next()) { - gs.info(rec.number + ' exists'); - } -})(); -(function() { - var rec = new GlideRecord('sys_app_module'); - rec._query(); - while (rec.next()) { - gs.info(rec.number + ' exists'); - } -})(); diff --git a/types/servicenow-london/test/ScopedQueryCondition.ts b/types/servicenow-london/test/ScopedQueryCondition.ts deleted file mode 100644 index 3a818b966a..0000000000 --- a/types/servicenow-london/test/ScopedQueryCondition.ts +++ /dev/null @@ -1,26 +0,0 @@ -(function() { - var gr = new GlideRecord('incident'); - var qc = gr.addQuery('category', 'Hardware'); - qc.addCondition('category', 'Network'); - gr.addQuery('number', 'INC0000003'); - gr.next(); - gr.number; - gs.info(gr.getEncodedQuery()); -})(); -(function() { - var gr = new GlideRecord('incident'); - var qc = gr.addQuery('category', 'Hardware'); - qc.addOrCondition('category', 'Network'); - gr.addQuery('number', 'INC0000003'); - gr.next(); - gr.number; - gs.info(gr.getEncodedQuery()); -})(); -(function() { - var myObj = new GlideRecord('incident'); - var q1 = myObj.addQuery('state', '<', 3); - q1.addOrCondition('state', '>', 5); - var q2 = myObj.addQuery('priority', 1); - q2.addOrCondition('priority', 5); - myObj.query(); -})(); diff --git a/types/servicenow-london/test/Workflow.ts b/types/servicenow-london/test/Workflow.ts deleted file mode 100644 index bbe5710899..0000000000 --- a/types/servicenow-london/test/Workflow.ts +++ /dev/null @@ -1,134 +0,0 @@ -(function() { - var gr = new GlideRecord('change_request'); - gr.get('8ecd7552db252200a6a2b31be0b8f581'); - - var wf = new global.Workflow(); - var grFlows = wf.getRunningFlows(gr); - while (grFlows.next()) { - wf.broadcastEvent(grFlows.sys_id, 'resume'); - } -})(); -(function() { - var gr = new GlideRecord('change_request'); - gr.get('8ecd7552db252200a6a2b31be0b8f581'); - - var wf = new global.Workflow(); - wf.cancel(gr); -})(); -(function() { - // If a workflow has started for this item, cancel it, where current is a task record with a workflow context - if (current.stage == 'Request Cancelled' && current.context && !current.context.nil()) { - var w = new global.Workflow(); - var gr = new GlideRecord('wf_context'); - - if (gr.get(current.context)) w.cancelContext(gr); - } -})(); -(function() { - var wkfw = new global.Workflow(); - wkfw.deleteWorkflow(current); -})(); -(function() { - // where current is a task record with a workflow context - var w = new global.Workflow(); - w.fireEvent(current, 'execute'); -})(); -(function() { - var wkfw = new global.Workflow(); - wkfw.fireEventById('f2400ec10b0a3c1c00ca5bb5c6fae427', 'Timer'); -})(); -(function() { - //where current is a task record with a workflow context - var wkfw = new global.Workflow(); - gs.info(wkfw.getContexts(current).started); -})(); -(function() { - var wkfw = new global.Workflow(); - gs.info(wkfw.getEstimatedDeliveryTime('b99a866a4a3623120074c033e005418f')); -})(); -(function() { - //where current is a task record with a workflow context - var wkfw = new global.Workflow(); - var context = wkfw.getContexts(current); - gs.info(wkfw.getEstimatedDeliveryTimeFromWFVersion(context.wf_version)); -})(); -(function() { - var gr = new GlideRecord('wf_context'); - gr.get('08a90c3adba52200a6a2b31be0b8f565'); - var wkfw = new global.Workflow(); - wkfw.getReturnValue(gr); -})(); -(function() { - //where current is a task record with a workflow context - var wf = new global.Workflow().getRunningFlows(current); - while (wf.next()) { - new global.Workflow().broadcastEvent(wf.sys_id, 'pause'); - } -})(); -(function() { - var wkfw = new global.Workflow(); - var gr = wkfw.getVersion('b99a866a4a3623120074c033e005418f'); -})(); -(function() { - var wkfw = new global.Workflow(); - var ge = wkfw.getVersionFromName('Emergency Change'); -})(); -(function() { - var wkfw = new global.Workflow(); - var s = wkfw.getWorkflowFromName('Emergency Change'); -})(); -(function() { - var gr = new GlideRecord('change_request'); - gr.get('cecdb552db252200a6a2b31be0b8f50b'); - var wkfw = new global.Workflow(); - gs.info(wkfw.hasWorkflow(gr)); -})(); -(function() { - var gr = new GlideRecord('change_request'); - gr.get('cecdb552db252200a6a2b31be0b8f50b'); - new global.Workflow().restartWorkflow(gr); -})(); -(function() { - var gr = new GlideRecord('change_request'); - gr.get('cecdb552db252200a6a2b31be0b8f50b'); - var wkfw = new global.Workflow(); - wkfw.runFlows(gr, 'update'); -})(); -(function() { - ////where current is a task record with a workflow context - var w = new global.Workflow(); - var context = w.startFlow('sys_id', current, current.operation(), {}); -})(); -(function() { - //where current is a task record with a workflow context - current.name = current.workflow_version.name; - current.started_by.setValue(gs.getUserID()); - - if (gs.nil(current.id)) { - var gr = new GlideRecord('wf_workflow_execution'); - gr.name = current.name; - gr.insert(); - - current.table = 'wf_workflow_execution'; - current.id = gr.sys_id; - } - - var wf = new global.Workflow(); - wf.startFlowFromContextInsert(current, current.operation()); -})(); -(function() { - var id = 'sys_id'; - // is this a retroactive start? - ////where current is a task record with a workflow context - var msecs = - new GlideDateTime().getNumericValue() - - current.start_time.getGlideObject().getNumericValue(); - - // treat this as a retroactive workflow start if the SLA started more than 5 seconds ago - var w = new global.Workflow(); - if (msecs <= 5000) w.startFlow(id, current, current.operation()); - else w.startFlowRetroactive(id, msecs, current, current.operation()); - - // update the record in case the workflow changed some values - current.update(); -})(); diff --git a/types/servicenow-london/test/XMLDocument2.ts b/types/servicenow-london/test/XMLDocument2.ts deleted file mode 100644 index 5ef77cc906..0000000000 --- a/types/servicenow-london/test/XMLDocument2.ts +++ /dev/null @@ -1,153 +0,0 @@ -(function() { - var xmlString = - '' + - ' ' + - ' abcd1234' + - ' 1234abcd' + - ' another' + - ' ' + - ' 1234' + - ''; - var xmlDoc = new XMLDocument2(); - xmlDoc.parseXML(xmlString); - xmlDoc.createElement('new2'); - - gs.info(xmlDoc); -})(); -(function() { - var xmlString = - '' + - ' ' + - ' abcd1234' + - ' 1234abcd' + - ' another' + - ' ' + - ' 1234' + - ''; - var xmlDoc = new XMLDocument2(); - xmlDoc.parseXML(xmlString); - xmlDoc.createElementWithTextValue('new', 'test'); - gs.info(xmlDoc); -})(); -(function() { - var xmlString = - '' + - ' ' + - ' abcd1234' + - ' 1234abcd' + - ' another' + - ' ' + - ' 1234' + - ''; - var xmlDoc = new XMLDocument2(); - xmlDoc.parseXML(xmlString); - //returns the root node of the document tree. - var rootNode = xmlDoc.getDocumentElement(); - gs.info(rootNode.getTextContent()); -})(); -(function() { - var xmlString = - '' + - ' ' + - ' abcd1234' + - ' 1234abcd' + - ' another' + - ' ' + - ' 1234' + - ''; - var xmlDoc = new XMLDocument2(); - xmlDoc.parseXML(xmlString); - var foo = xmlDoc.getFirstNode('/test/one/two'); - gs.info(foo.getTextContent()); -})(); -(function() { - var xmlString = - '' + - ' ' + - ' abcd1234' + - ' 1234abcd' + - ' another' + - ' ' + - ' 1234' + - ''; - var xmlDoc = new XMLDocument2(); - xmlDoc.parseXML(xmlString); - var foo = xmlDoc.getFirstNode('/test/one/two'); - var foo2 = xmlDoc.getNextNode(foo); - gs.info(foo.getTextContent()); - gs.info(foo2.getTextContent()); -})(); -(function() { - var xmlString = - '' + - ' ' + - ' abcd1234' + - ' 1234abcd' + - ' another' + - ' ' + - ' 1234' + - ''; - var xmlDoc = new XMLDocument2(); - xmlDoc.parseXML(xmlString); - var node = xmlDoc.getNode('/test/one/two'); - gs.info(node); -})(); -(function() { - var xmlString = - '' + - ' ' + - ' abcd1234' + - ' 1234abcd' + - ' another' + - ' ' + - ' 1234' + - ''; - var xmlDoc = new XMLDocument2(); - xmlDoc.parseXML(xmlString); - gs.info(xmlDoc.getNodeText('//two')); -})(); -(function() { - var xmlString = - '' + - ' ' + - ' abcd1234' + - ' 1234abcd' + - ' another' + - ' ' + - ' 1234' + - ''; - var xmlDoc = new XMLDocument2(); - xmlDoc.parseXML(xmlString); - var rootNode = xmlDoc.getDocumentElement(); -})(); -(function() { - var xmlString = - '' + - ' ' + - ' abcd1234' + - ' 1234abcd' + - ' another' + - ' ' + - ' 1234' + - ''; - var xmlDoc = new XMLDocument2(); - xmlDoc.parseXML(xmlString); - //returns the root node of the document tree. - var rootNode = xmlDoc.getDocumentElement(); //returns org.w3c.dom.Element - // sets the root node as the current element - xmlDoc.setCurrentElement(rootNode); -})(); -(function() { - var xmlString = - '' + - ' ' + - ' abcd1234' + - ' 1234abcd' + - ' another' + - ' ' + - ' 1234' + - ''; - var xmlDoc = new XMLDocument2(); - xmlDoc.parseXML(xmlString); - gs.info(xmlDoc.toString()); -})(); diff --git a/types/servicenow-london/test/XMLNode.ts b/types/servicenow-london/test/XMLNode.ts deleted file mode 100644 index a5db5cd6ed..0000000000 --- a/types/servicenow-london/test/XMLNode.ts +++ /dev/null @@ -1,137 +0,0 @@ -(function() { - var xmlString = - '' + - ' ' + - ' abcd1234' + - ' 1234abcd' + - ' another' + - ' ' + - ' 1234' + - ''; - var xmlDoc = new XMLDocument2(); - xmlDoc.parseXML(xmlString); - var node = xmlDoc.getNode('//two'); - gs.info(node.getAttribute('att')); -})(); -(function() { - var xmlString = - '' + - ' ' + - ' abcd1234' + - ' 1234abcd' + - ' another' + - ' ' + - ' 1234' + - ''; - var xmlDoc = new XMLDocument2(); - xmlDoc.parseXML(xmlString); - var node = xmlDoc.getNode('//one'); - var iter = node.getChildNodeIterator(); - gs.info(iter.hasNext()); -})(); -(function() { - var xmlString = - '' + - '' + - 'abcd1234' + - '1234abcd' + - 'another' + - '' + - '1234' + - ''; - var xmlDoc = new XMLDocument2(); - xmlDoc.parseXML(xmlString); - var node = xmlDoc.getNode('//one'); - gs.info(node.getFirstChild()); -})(); -(function() { - var xmlString = - '' + - '' + - 'abcd1234' + - '1234abcd' + - 'another' + - '' + - '1234' + - ''; - var xmlDoc = new XMLDocument2(); - xmlDoc.parseXML(xmlString); - var node = xmlDoc.getNode('//one'); - - gs.info(node.getLastChild()); -})(); -(function() { - var xmlString = - '' + - ' ' + - ' abcd1234' + - ' 1234abcd' + - ' another' + - ' ' + - ' 1234' + - ''; - var xmlDoc = new XMLDocument2(); - xmlDoc.parseXML(xmlString); - var node = xmlDoc.getNode('//two'); - gs.info(node.getNodeName()); -})(); -(function() { - var xmlString = - '' + - ' ' + - ' abcd1234' + - ' 1234abcd' + - ' another' + - ' ' + - ' 1234' + - ''; - var xmlDoc = new XMLDocument2(); - xmlDoc.parseXML(xmlString); - var node = xmlDoc.getNode('//two'); - gs.info(node.getNodeValue()); -})(); -(function() { - var xmlString = - '' + - ' ' + - ' abcd1234' + - ' 1234abcd' + - ' another' + - ' ' + - ' 1234' + - ''; - var xmldoc = new XMLDocument2(); - xmldoc.parseXML(xmlString); - var node = xmldoc.getNode('//one/two'); - gs.info(node.getTextContent()); -})(); -(function() { - var xmlString = - '' + - ' ' + - ' abcd1234' + - ' 1234abcd' + - ' another' + - ' ' + - ' 1234' + - ''; - var xmlDoc = new XMLDocument2(); - xmlDoc.parseXML(xmlString); - var node = xmlDoc.getNode('//two'); - gs.info(node.hasAttribute('att')); -})(); -(function() { - var xmlString = - '' + - ' ' + - ' abcd1234' + - ' 1234abcd' + - ' another' + - ' ' + - ' 1234' + - ''; - var xmlDoc = new XMLDocument2(); - xmlDoc.parseXML(xmlString); - var node = xmlDoc.getNode('//one'); - gs.info(node.toString()); -})(); diff --git a/types/servicenow-london/test/XMLNodeIterator.ts b/types/servicenow-london/test/XMLNodeIterator.ts deleted file mode 100644 index 50e58e8f83..0000000000 --- a/types/servicenow-london/test/XMLNodeIterator.ts +++ /dev/null @@ -1,36 +0,0 @@ -(function() { - var xmlString = - '' + - ' ' + - ' abcd1234' + - ' 1234abcd' + - ' another' + - ' ' + - ' 1234' + - ''; - var xmlDoc = new XMLDocument2(); - xmlDoc.parseXML(xmlString); - var node = xmlDoc.getNode('//one'); - var iter = node.getChildNodeIterator(); - gs.info(iter.hasNext()); -})(); -(function() { - var xmlString = - '' + - ' ' + - ' abcd1234' + - ' 1234abcd' + - ' another' + - ' ' + - ' 1234' + - ''; - var xmlDoc = new XMLDocument2(); - xmlDoc.parseXML(xmlString); - var node = xmlDoc.getNode('//one'); - var iter = node.getChildNodeIterator(); - while (iter.hasNext()) { - var n = iter.next(); - gs.info('Node name: ' + n.getNodeName()); - gs.info('Node value: ' + n.getNodeValue()); - } -})(); diff --git a/types/servicenow-london/tsconfig.json b/types/servicenow-london/tsconfig.json index 53dd1d713d..3302148bc7 100644 --- a/types/servicenow-london/tsconfig.json +++ b/types/servicenow-london/tsconfig.json @@ -56,42 +56,6 @@ "XMLNode.d.ts", "XMLNodeIterator.d.ts", - "test/Class.ts", - "test/GlideDate.ts", - "test/GlideDateTime.ts", - "test/GlideDBFunctionBuilder.ts", - "test/GlideDuration.ts", - "test/GlideEmailOutbound.ts", - "test/GlideFilter.ts", - "test/GlideLocale.ts", - "test/GlidePluginManager.ts", - "test/GlideSchedule.ts", - "test/GlideScopedEvaluator.ts", - "test/GlideScriptedProcessor.ts", - "test/GlideSecureRandomUtil.ts", - "test/GlideServletRequest.ts", - "test/GlideServletResponse.ts", - "test/GlideSession.ts", - "test/GlideStringUtil.ts", - "test/GlideSysAttachment.ts", - "test/GlideSystem.ts", - "test/GlideTime.ts", - "test/GlideUser.ts", - "test/RESTAPIRequest.ts", - "test/RESTAPIRequestBody.ts", - "test/RESTAPIResponse.ts", - "test/RESTAPIResponseStream.ts", - "test/RESTMessageV2.ts", - "test/RESTResponseV2.ts", - "test/ScopedElementDescriptor.ts", - "test/ScopedGlideElement.ts", - "test/ScopedGlideRecord.ts", - "test/ScopedQueryCondition.ts", - "test/SOAPMessageV2.ts", - "test/SOAPResponseV2.ts", - "test/Workflow.ts", - "test/XMLDocument2.ts", - "test/XMLNode.ts", - "test/XMLNodeIterator.ts" + "servicenow-london-tests.ts" ] } diff --git a/types/servicenow-london/tslint.json b/types/servicenow-london/tslint.json index 1e1f71979b..e595b70d63 100644 --- a/types/servicenow-london/tslint.json +++ b/types/servicenow-london/tslint.json @@ -1,12 +1,3 @@ { "extends": "dtslint/dt.json", - "rules": { - // Interface is needed for merging GlideRecord types - "no-misused-new": false, - // Disabling to all separate JSDoc per signature to correspond with ServiceNow API docs - "unified-signatures": false - }, - "linterOptions": { - "exclude": ["test/*.ts"] - } } From ebb1d54175602aadab6da28e93b7380bad4c2706 Mon Sep 17 00:00:00 2001 From: John Caruso Date: Mon, 25 Mar 2019 17:24:16 -0500 Subject: [PATCH 064/710] Fix tslint.json --- types/servicenow-london/tslint.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/servicenow-london/tslint.json b/types/servicenow-london/tslint.json index e595b70d63..f93cf8562a 100644 --- a/types/servicenow-london/tslint.json +++ b/types/servicenow-london/tslint.json @@ -1,3 +1,3 @@ { - "extends": "dtslint/dt.json", + "extends": "dtslint/dt.json" } From 5e4ad116c462700a5261bf4a2c6efe0fd10428bc Mon Sep 17 00:00:00 2001 From: John Caruso Date: Mon, 25 Mar 2019 17:33:37 -0500 Subject: [PATCH 065/710] Fix lint issues --- types/servicenow-london/GlideDateTime.d.ts | 2 ++ types/servicenow-london/GlideDuration.d.ts | 2 ++ types/servicenow-london/GlideEmailOutbound.d.ts | 2 ++ types/servicenow-london/GlideSchedule.d.ts | 2 ++ types/servicenow-london/GlideTime.d.ts | 2 ++ types/servicenow-london/RESTMessageV2.d.ts | 2 ++ types/servicenow-london/ScopedGlideRecord.d.ts | 2 ++ 7 files changed, 14 insertions(+) diff --git a/types/servicenow-london/GlideDateTime.d.ts b/types/servicenow-london/GlideDateTime.d.ts index ad4ef1210b..abaacc1049 100644 --- a/types/servicenow-london/GlideDateTime.d.ts +++ b/types/servicenow-london/GlideDateTime.d.ts @@ -1,3 +1,5 @@ +/* tslint:disable:unified-signatures */ + /** * The scoped GlideDateTime class provides methods for performing operations on GlideDateTime * objects, such as instantiating GlideDateTime objects or working with glide_date_time fields. diff --git a/types/servicenow-london/GlideDuration.d.ts b/types/servicenow-london/GlideDuration.d.ts index b616be5000..fe8fdb94f9 100644 --- a/types/servicenow-london/GlideDuration.d.ts +++ b/types/servicenow-london/GlideDuration.d.ts @@ -1,3 +1,5 @@ +/* tslint:disable:unified-signatures */ + /** * The scoped GlideDuration class provides methods for working with spans of time or durations. * diff --git a/types/servicenow-london/GlideEmailOutbound.d.ts b/types/servicenow-london/GlideEmailOutbound.d.ts index c9589efb71..5e0c19e817 100644 --- a/types/servicenow-london/GlideEmailOutbound.d.ts +++ b/types/servicenow-london/GlideEmailOutbound.d.ts @@ -1,3 +1,5 @@ +/* tslint:disable:unified-signatures */ + /** * The scoped GlideEmailOutbound class implements the email object for scoped applications. * You can use the GlideEmailOutbound methods with the email global object available in mail diff --git a/types/servicenow-london/GlideSchedule.d.ts b/types/servicenow-london/GlideSchedule.d.ts index 435b7c8506..f530954ddb 100644 --- a/types/servicenow-london/GlideSchedule.d.ts +++ b/types/servicenow-london/GlideSchedule.d.ts @@ -1,3 +1,5 @@ +/* tslint:disable:unified-signatures */ + /** * The scoped GlideSchedule API provides methods for performing operations on GlideSchedule * objects, such as adding new schedule segments to a schedule, determining if a datetime is within diff --git a/types/servicenow-london/GlideTime.d.ts b/types/servicenow-london/GlideTime.d.ts index d51854e7a6..e34760970f 100644 --- a/types/servicenow-london/GlideTime.d.ts +++ b/types/servicenow-london/GlideTime.d.ts @@ -1,3 +1,5 @@ +/* tslint:disable:unified-signatures */ + /** * The scoped GlideTime class provides methods for performing operations on GlideTime * objects, such as instantiating GlideTime objects or working with GlideTime fields. diff --git a/types/servicenow-london/RESTMessageV2.d.ts b/types/servicenow-london/RESTMessageV2.d.ts index fadac635aa..02401a531c 100644 --- a/types/servicenow-london/RESTMessageV2.d.ts +++ b/types/servicenow-london/RESTMessageV2.d.ts @@ -1,3 +1,5 @@ +/* tslint:disable:unified-signatures */ + declare namespace sn_ws { /** * The RESTMessageV2 API allows you to send outbound REST messages using JavaScript. diff --git a/types/servicenow-london/ScopedGlideRecord.d.ts b/types/servicenow-london/ScopedGlideRecord.d.ts index 3e3dfb7bc5..9c6583acda 100644 --- a/types/servicenow-london/ScopedGlideRecord.d.ts +++ b/types/servicenow-london/ScopedGlideRecord.d.ts @@ -1,3 +1,5 @@ +/* tslint:disable:unified-signatures no-misused-new */ + /** * Scoped GlideRecord is used for database operations. */ From 0db7ca6551be043ccf7302fa82bf101692dfadd9 Mon Sep 17 00:00:00 2001 From: Andrew <0coming.soon@gmail.com> Date: Tue, 26 Mar 2019 15:46:08 +0500 Subject: [PATCH 066/710] Allow to pass _.List to OOP wrapper --- types/underscore/index.d.ts | 1 + types/underscore/underscore-tests.ts | 4 ++++ 2 files changed, 5 insertions(+) diff --git a/types/underscore/index.d.ts b/types/underscore/index.d.ts index 209f660277..e3973187c8 100644 --- a/types/underscore/index.d.ts +++ b/types/underscore/index.d.ts @@ -105,6 +105,7 @@ declare module _ { * @param key First argument to Underscore object functions. **/ (value: _.Dictionary): Underscore; + (value: _.List): Underscore; (value: Array): Underscore; (value: T): Underscore; diff --git a/types/underscore/underscore-tests.ts b/types/underscore/underscore-tests.ts index bd5a871545..4396ce5c35 100644 --- a/types/underscore/underscore-tests.ts +++ b/types/underscore/underscore-tests.ts @@ -147,6 +147,10 @@ namespace TestFind { result = _('abc').chain().detect(iterator).value(); result = _('abc').chain().detect(iterator, context).value(); } + + { + _(list).map(x => x.a); + } } var evens = _.filter([1, 2, 3, 4, 5, 6], (num) => num % 2 == 0); From 71031b5611a9d7564ab113b8a9aaf79560b3613c Mon Sep 17 00:00:00 2001 From: chensara Date: Tue, 26 Mar 2019 16:31:40 +0200 Subject: [PATCH 067/710] Add react-image-crop `renderSelectionAddon(state)` --- types/react-image-crop/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/react-image-crop/index.d.ts b/types/react-image-crop/index.d.ts index 877966b00e..97471841ff 100644 --- a/types/react-image-crop/index.d.ts +++ b/types/react-image-crop/index.d.ts @@ -47,6 +47,7 @@ declare namespace ReactCrop { onImageError?: (event: React.SyntheticEvent) => void; className?: string; locked?: boolean; + renderSelectionAddon?: (state: any) => ReactNode; } function getPixelCrop(image: HTMLImageElement, percentCrop: Crop): Crop; From 50f6ccdb2b6f4e862eb65657c150420c641c2ddb Mon Sep 17 00:00:00 2001 From: Anton Bortnikov <6088046+ntnbrtnkv@users.noreply.github.com> Date: Tue, 26 Mar 2019 20:54:39 +0500 Subject: [PATCH 068/710] refactor: remove tslint rule --- types/react-tabs-redux/react-tabs-redux-tests.tsx | 12 +++++++++--- types/react-tabs-redux/tslint.json | 7 +------ 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/types/react-tabs-redux/react-tabs-redux-tests.tsx b/types/react-tabs-redux/react-tabs-redux-tests.tsx index 758ba7b5c9..6a91eb0ecd 100644 --- a/types/react-tabs-redux/react-tabs-redux-tests.tsx +++ b/types/react-tabs-redux/react-tabs-redux-tests.tsx @@ -9,9 +9,15 @@ import { TabContentProps } from 'react-tabs-redux'; -interface TestTabsProps extends TabsProps {} -interface TestTabLinkProps extends TabLinkProps {} -interface TestTabContentProps extends TabContentProps {} +interface TestTabsProps extends TabsProps { + handleSomething: () => void; +} +interface TestTabLinkProps extends TabLinkProps { + link: string; +} +interface TestTabContentProps extends TabContentProps { + tabIndex: number; +} class TestApp extends React.Component { onChange = (selectedTab: string, name: string) => { diff --git a/types/react-tabs-redux/tslint.json b/types/react-tabs-redux/tslint.json index 4f44991c3c..3db14f85ea 100644 --- a/types/react-tabs-redux/tslint.json +++ b/types/react-tabs-redux/tslint.json @@ -1,6 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "no-empty-interface": false - } -} +{ "extends": "dtslint/dt.json" } From 2474134ef0622cbea90ccd4d8a02d4276a1fc4cd Mon Sep 17 00:00:00 2001 From: timolinn Date: Tue, 26 Mar 2019 17:02:08 +0100 Subject: [PATCH 069/710] new package: burns --- types/burns/burns-tests.ts | 29 +++++++++++++++++++++++++++++ types/burns/index.d.ts | 26 ++++++++++++++++++++++++++ types/burns/tsconfig.json | 24 ++++++++++++++++++++++++ types/burns/tslint.json | 1 + 4 files changed, 80 insertions(+) create mode 100644 types/burns/burns-tests.ts create mode 100644 types/burns/index.d.ts create mode 100644 types/burns/tsconfig.json create mode 100644 types/burns/tslint.json diff --git a/types/burns/burns-tests.ts b/types/burns/burns-tests.ts new file mode 100644 index 0000000000..e1fd41ad09 --- /dev/null +++ b/types/burns/burns-tests.ts @@ -0,0 +1,29 @@ +import burns from 'burns'; + +interface OrderData { + userName: string; + orderId: string; +} + +function handleEverything() { + console.log('Do absolutely nothing! 😄'); +} + +function sendEmail(message: string) { + console.log(message); +} + +function sendOrderShippedEmail(data: OrderData) { + sendEmail(`Hi ${data.userName}, Your order ${data.orderId} has been shipped`); +} + +burns.configure({ + defaultHandler: handleEverything +}); +burns.registerEvents({ + newPurchase: sendOrderShippedEmail +}); +burns.dispatch('newPurchase', { + userName: 'Johnny', + orderId: 'rand' +}); diff --git a/types/burns/index.d.ts b/types/burns/index.d.ts new file mode 100644 index 0000000000..af1d86c9e6 --- /dev/null +++ b/types/burns/index.d.ts @@ -0,0 +1,26 @@ +// Type definitions for burns version 2.0.1 +// Project: https://github.com/shalvah/burns +// Definitions by: Timothy Onyiuke +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare const _Burns: Burns; + +export interface Config { + defaultHandler?: any; + broadcaster?: any; + pusher?: any; +} + +export interface ObjectLiteral { + [key: string]: any +} + +declare class Burns { + configure(config?: Config): this; + + registerEvents(newEvents: ObjectLiteral): this; + + dispatch(eventName: string, eventData?: ObjectLiteral, exclude?: { exclude?: any }): this; +} + +export default _Burns; \ No newline at end of file diff --git a/types/burns/tsconfig.json b/types/burns/tsconfig.json new file mode 100644 index 0000000000..45af42852b --- /dev/null +++ b/types/burns/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "burns-tests.ts" + ] +} \ No newline at end of file diff --git a/types/burns/tslint.json b/types/burns/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/burns/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From e46fcb1f401bd9c17cc7fb2237c3c477f4663162 Mon Sep 17 00:00:00 2001 From: Alexander Tesfamichael Date: Mon, 25 Mar 2019 17:25:30 +0100 Subject: [PATCH 070/710] Add instance methods to React Native Material Textfield (#34175) * Add methods * Add examples of method use --- .../index.d.ts | 27 ++++++++++++- .../react-native-material-textfield-tests.tsx | 39 +++++++++++++------ 2 files changed, 54 insertions(+), 12 deletions(-) diff --git a/types/react-native-material-textfield/index.d.ts b/types/react-native-material-textfield/index.d.ts index c21caa15b4..1aed9e03aa 100644 --- a/types/react-native-material-textfield/index.d.ts +++ b/types/react-native-material-textfield/index.d.ts @@ -66,4 +66,29 @@ export interface TextFieldProps extends TextInputProps { * Material Style Text Field * @see https://github.com/n4kz/react-native-material-textfield/blob/master/src/components/field/index.js */ -export class TextField extends React.Component {} +export class TextField extends React.Component { + /* + * Acquire focus + */ + focus(): void; + /* + * Release focus + */ + blur(): void; + /* + * Clear text field + */ + clear(): void; + /* + * Get current value + */ + value(): string; + /* + * Get current focus state + */ + isFocused(): boolean; + /* + * Get current restriction state + */ + isRestricted(): boolean; +} diff --git a/types/react-native-material-textfield/react-native-material-textfield-tests.tsx b/types/react-native-material-textfield/react-native-material-textfield-tests.tsx index 50fb2b166b..7219dd9a3f 100644 --- a/types/react-native-material-textfield/react-native-material-textfield-tests.tsx +++ b/types/react-native-material-textfield/react-native-material-textfield-tests.tsx @@ -2,14 +2,31 @@ import * as React from 'react'; import { View } from 'react-native'; import { TextField } from 'react-native-material-textfield'; -const Example = () => ( - - - -); +export class Example extends React.Component { + textFieldRef = React.createRef(); + + componentDidMount() { + if (this.textFieldRef.current) { + this.textFieldRef.current.focus(); + this.textFieldRef.current.blur(); + this.textFieldRef.current.clear(); + this.textFieldRef.current.value(); + this.textFieldRef.current.isFocused(); + this.textFieldRef.current.isRestricted(); + } + } + + render() { + return ( + + + + ); + } +} From 259db5c3aa13a350754f3023d5960ae1d9ec9656 Mon Sep 17 00:00:00 2001 From: codert Date: Tue, 26 Mar 2019 00:26:02 +0800 Subject: [PATCH 071/710] fabric.Image.setElement method has no callback argument (#34173) * fix: setElement type definition * chore: add definitions by --- types/fabric/fabric-impl.d.ts | 4 ++-- types/fabric/index.d.ts | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 96034c0b5f..cd52bd54e5 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -2212,10 +2212,10 @@ export class Image { * Sets image element for this instance to a specified one. * If filters defined they are applied to new image. * You might need to call `canvas.renderAll` and `object.setCoords` after replacing, to render new image and update controls area. - * @param [callback] Callback is invoked when all filters have been applied and new image is generated + * @param element image element * @param [options] Options object */ - setElement(element: HTMLImageElement, callback: Function, options: IImageOptions): Image; + setElement(element: HTMLImageElement, options?: IImageOptions): Image; /** * Delete a single texture if in webgl mode */ diff --git a/types/fabric/index.d.ts b/types/fabric/index.d.ts index 3897987589..7444f481b8 100644 --- a/types/fabric/index.d.ts +++ b/types/fabric/index.d.ts @@ -9,6 +9,7 @@ // Bradley Hill // Bryan Krol // Glenn Gartner +// Codertx // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 export import fabric = require("./fabric-impl"); From d9ad8e536345e264b7ee219d515dad5350946b51 Mon Sep 17 00:00:00 2001 From: Ryo Ota Date: Tue, 26 Mar 2019 01:27:33 +0900 Subject: [PATCH 072/710] Remove the type definition of get-port (#34165) --- notNeededPackages.json | 6 ++++++ types/get-port/get-port-tests.ts | 10 ---------- types/get-port/index.d.ts | 12 ------------ types/get-port/tsconfig.json | 23 ----------------------- types/get-port/tslint.json | 3 --- 5 files changed, 6 insertions(+), 48 deletions(-) delete mode 100644 types/get-port/get-port-tests.ts delete mode 100644 types/get-port/index.d.ts delete mode 100644 types/get-port/tsconfig.json delete mode 100644 types/get-port/tslint.json diff --git a/notNeededPackages.json b/notNeededPackages.json index cf61daf58d..33ac19b762 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -786,6 +786,12 @@ "sourceRepoURL": "https://github.com/manuelbieh/Geolib", "asOfVersion": "2.0.23" }, + { + "libraryName": "get-port", + "typingsPackageName": "get-port", + "sourceRepoURL": "https://github.com/sindresorhus/get-port", + "asOfVersion": "4.2.0" + }, { "libraryName": "get-stream", "typingsPackageName": "get-stream", diff --git a/types/get-port/get-port-tests.ts b/types/get-port/get-port-tests.ts deleted file mode 100644 index 5e47c33c1a..0000000000 --- a/types/get-port/get-port-tests.ts +++ /dev/null @@ -1,10 +0,0 @@ -import getPort = require('get-port'); - -// $ExpectType Promise -getPort(); -// $ExpectType Promise -getPort({ port: 3000 }); -// $ExpectType Promise -getPort({ port: [3000, 3001] }); -// $ExpectType Promise -getPort({ host: 'foo.local' }); diff --git a/types/get-port/index.d.ts b/types/get-port/index.d.ts deleted file mode 100644 index 9af3b311fc..0000000000 --- a/types/get-port/index.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -// Type definitions for get-port 4.0 -// Project: https://github.com/sindresorhus/get-port -// Definitions by: York Yao -// BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare function getPort(options?: { - port?: number | ReadonlyArray; - host?: string; -}): Promise; - -export = getPort; diff --git a/types/get-port/tsconfig.json b/types/get-port/tsconfig.json deleted file mode 100644 index 0d9f3a8975..0000000000 --- a/types/get-port/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "get-port-tests.ts" - ] -} diff --git a/types/get-port/tslint.json b/types/get-port/tslint.json deleted file mode 100644 index f93cf8562a..0000000000 --- a/types/get-port/tslint.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "extends": "dtslint/dt.json" -} From 2987a599bb83a915f375486905ea298162e5da85 Mon Sep 17 00:00:00 2001 From: Paul Melnikow Date: Mon, 25 Mar 2019 12:28:10 -0400 Subject: [PATCH 073/710] [cacheable-request] Include type alias for cache adapter (#34155) * [cacheable-request] Include type alias for cache adapter This allows easily declaring a parameter that will be passed into the constructor. Ref https://github.com/sindresorhus/got/pull/760#discussion_r268277506 * Fix missing semicolon * Move StorageAdapter into namespace --- types/cacheable-request/index.d.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/types/cacheable-request/index.d.ts b/types/cacheable-request/index.d.ts index 98d858d3f6..16e778274a 100644 --- a/types/cacheable-request/index.d.ts +++ b/types/cacheable-request/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for cacheable-request 6.0 // Project: https://github.com/lukechilds/cacheable-request#readme // Definitions by: BendingBender +// Paul Melnikow // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -20,7 +21,7 @@ declare const CacheableRequest: CacheableRequest; type RequestFn = typeof request; interface CacheableRequest { - new (requestFn: RequestFn, storageAdapter?: string | Store): ( + new (requestFn: RequestFn, storageAdapter?: string | CacheableRequest.StorageAdapter): ( opts: string | URL | (RequestOptions & CacheSemanticsOptions), cb?: (response: ServerResponse | ResponseLike) => void ) => CacheableRequest.Emitter; @@ -30,6 +31,8 @@ interface CacheableRequest { } declare namespace CacheableRequest { + type StorageAdapter = Store; + interface Options { /** * If the cache should be used. Setting this to `false` will completely bypass the cache for the current request. From 79108a1ef22492c7bee825bd60d24fa91d545e7d Mon Sep 17 00:00:00 2001 From: Silas Rech Date: Mon, 25 Mar 2019 17:29:06 +0100 Subject: [PATCH 074/710] [bull] allow supplying of the queue type when creating a new instance (#34154) --- types/bull/index.d.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index 07de38e05d..648e2ba360 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -26,10 +26,12 @@ import { EventEmitter } from "events"; * Everytime the same queue is instantiated it tries to process all the old jobs that may exist from a previous unfinished session. */ declare const Bull: { - (queueName: string, opts?: Bull.QueueOptions): Bull.Queue; - (queueName: string, url: string, opts?: Bull.QueueOptions): Bull.Queue; // tslint:disable-line unified-signatures - new (queueName: string, opts?: Bull.QueueOptions): Bull.Queue; - new (queueName: string, url: string, opts?: Bull.QueueOptions): Bull.Queue; // tslint:disable-line unified-signatures + /* tslint:disable:no-unnecessary-generics unified-signatures */ + (queueName: string, opts?: Bull.QueueOptions): Bull.Queue; + (queueName: string, url: string, opts?: Bull.QueueOptions): Bull.Queue; + new (queueName: string, opts?: Bull.QueueOptions): Bull.Queue; + new (queueName: string, url: string, opts?: Bull.QueueOptions): Bull.Queue; + /* tslint:enable:no-unnecessary-generics unified-signatures */ }; declare namespace Bull { From 239748d8be7f308682ff3bfcbf41b84daefe8efe Mon Sep 17 00:00:00 2001 From: TokugawaT_YD <41653501+TokugawaTakesi@users.noreply.github.com> Date: Tue, 26 Mar 2019 01:31:33 +0900 Subject: [PATCH 075/710] Types for gulp-tap (#31917) * Types for "gulp-tap" added * Types for "gulp-tap" added * Requested changes applied * Requested changes applied --- types/gulp-tap/gulp-tap-tests.ts | 11 +++++++++++ types/gulp-tap/index.d.ts | 22 ++++++++++++++++++++++ types/gulp-tap/tsconfig.json | 23 +++++++++++++++++++++++ types/gulp-tap/tslint.json | 3 +++ 4 files changed, 59 insertions(+) create mode 100644 types/gulp-tap/gulp-tap-tests.ts create mode 100644 types/gulp-tap/index.d.ts create mode 100644 types/gulp-tap/tsconfig.json create mode 100644 types/gulp-tap/tslint.json diff --git a/types/gulp-tap/gulp-tap-tests.ts b/types/gulp-tap/gulp-tap-tests.ts new file mode 100644 index 0000000000..7d89c50ba0 --- /dev/null +++ b/types/gulp-tap/gulp-tap-tests.ts @@ -0,0 +1,11 @@ +import gulpTap = require('gulp-tap'); +import gulp = require('gulp'); +import Vinyl = require('vinyl'); + +gulp.task('testTask', () => { + return gulp.src(['src/*.html']) + .pipe(gulpTap((sourceFile: Vinyl) => { + console.log(sourceFile.path); + })) + .pipe(gulp.dest('dist/')); +}); diff --git a/types/gulp-tap/index.d.ts b/types/gulp-tap/index.d.ts new file mode 100644 index 0000000000..30af7663f8 --- /dev/null +++ b/types/gulp-tap/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for gulp-tap 1.0 +// Project: https://github.com/geejs/gulp-tap +// Definitions by: Takesi Tokugawa +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import Vinyl = require('vinyl'); + +declare namespace tap { + interface Tap { + (tapFunction: TapFunction, t?: any): NodeJS.ReadWriteStream; + } + + interface TapFunction { + (file: Vinyl): any; + } +} + +declare function tap(tapFunction: (file: Vinyl, t?: {}) => void): NodeJS.ReadWriteStream; + +export = tap; diff --git a/types/gulp-tap/tsconfig.json b/types/gulp-tap/tsconfig.json new file mode 100644 index 0000000000..d48ac90475 --- /dev/null +++ b/types/gulp-tap/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "gulp-tap-tests.ts" + ] +} diff --git a/types/gulp-tap/tslint.json b/types/gulp-tap/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/gulp-tap/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From b2e5f15e64138403872418200ee4ace21cd95b9a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matheus=20Gon=C3=A7alves=20da=20Silva?= Date: Mon, 25 Mar 2019 13:34:48 -0300 Subject: [PATCH 076/710] Add type definitions to webpack-plugin-serve (#33948) * feat(wps): add webpack-plugin-serve types * fix export method * fix declaration * add strictFunctionTypes * fix declaration problems * remove redundant declare * add correct level types * export history api interfaces * reuse koa-compress and koa-static * fix padding --- types/connect-history-api-fallback/index.d.ts | 38 +++++----- types/koa-compress/index.d.ts | 22 +++--- types/webpack-plugin-serve/index.d.ts | 69 +++++++++++++++++++ types/webpack-plugin-serve/tsconfig.json | 23 +++++++ types/webpack-plugin-serve/tslint.json | 1 + .../webpack-plugin-serve-tests.ts | 39 +++++++++++ 6 files changed, 162 insertions(+), 30 deletions(-) create mode 100644 types/webpack-plugin-serve/index.d.ts create mode 100644 types/webpack-plugin-serve/tsconfig.json create mode 100644 types/webpack-plugin-serve/tslint.json create mode 100644 types/webpack-plugin-serve/webpack-plugin-serve-tests.ts diff --git a/types/connect-history-api-fallback/index.d.ts b/types/connect-history-api-fallback/index.d.ts index a39fbfdbd6..b32e61e147 100644 --- a/types/connect-history-api-fallback/index.d.ts +++ b/types/connect-history-api-fallback/index.d.ts @@ -10,26 +10,28 @@ import { Url } from 'url'; import * as core from "express-serve-static-core"; -declare function historyApiFallback(options?: Options): core.RequestHandler; -declare namespace historyApiFallback {} export = historyApiFallback; -interface Options { - disableDotRule?: true; - htmlAcceptHeaders?: string[]; - index?: string; - logger?: typeof console.log; - rewrites?: Rewrite[]; - verbose?: boolean; -} +declare function historyApiFallback(options?: historyApiFallback.Options): core.RequestHandler; -interface Context { - match: RegExpMatchArray; - parsedUrl: Url; -} -type RewriteTo = (context: Context) => string; +declare namespace historyApiFallback { + interface Options { + disableDotRule?: true; + htmlAcceptHeaders?: string[]; + index?: string; + logger?: typeof console.log; + rewrites?: Rewrite[]; + verbose?: boolean; + } -interface Rewrite { - from: RegExp; - to: string | RegExp | RewriteTo; + interface Context { + match: RegExpMatchArray; + parsedUrl: Url; + } + type RewriteTo = (context: Context) => string; + + interface Rewrite { + from: RegExp; + to: string | RegExp | RewriteTo; + } } diff --git a/types/koa-compress/index.d.ts b/types/koa-compress/index.d.ts index 24b7a1e1af..9b0a4415be 100644 --- a/types/koa-compress/index.d.ts +++ b/types/koa-compress/index.d.ts @@ -16,12 +16,18 @@ /// /// -declare module "koa-compress" { +import * as Koa from "koa"; +import * as zlib from "zlib"; - import * as Koa from "koa"; - import * as zlib from "zlib"; +/** + * Compress middleware for Koa + */ +declare function koaCompress(options?: koaCompress.CompressOptions): Koa.Middleware; - interface CompressOptions extends zlib.ZlibOptions { +export = koaCompress; + +declare namespace koaCompress { + export interface CompressOptions extends zlib.ZlibOptions { /** * An optional function that checks the response content type to decide whether to compress. By default, it uses compressible. */ @@ -32,12 +38,4 @@ declare module "koa-compress" { */ threshold?: number } - - /** - * Compress middleware for Koa - */ - function compress(options?: CompressOptions): Koa.Middleware; - - namespace compress {} - export = compress; } diff --git a/types/webpack-plugin-serve/index.d.ts b/types/webpack-plugin-serve/index.d.ts new file mode 100644 index 0000000000..1233333ebc --- /dev/null +++ b/types/webpack-plugin-serve/index.d.ts @@ -0,0 +1,69 @@ +// Type definitions for webpack-plugin-serve 0.7 +// Project: https://github.com/shellscape/webpack-plugin-serve +// Definitions by: Matheus Gonçalves da Silva +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 +/// + +import { Url } from 'url'; +import { Config as HttpProxyMiddlewareConfig, Proxy } from 'http-proxy-middleware'; +import * as Koa from 'koa'; +import { + ServerOptions as Http2ServerOptions, + SecureServerOptions as Http2SecureServerOptions, +} from 'http2'; +import { ServerOptions as HttpsServerOptions } from 'https'; +import { ZlibOptions } from 'zlib'; +import { Compiler } from 'webpack'; +import { Options as HistoryApiFallbackOptions } from 'connect-history-api-fallback'; +import { CompressOptions } from 'koa-compress'; +import { Options as KoaStaticOptions } from 'koa-static'; + +export interface Builtins { + proxy: (args: HttpProxyMiddlewareConfig) => Proxy; + compress: (opts: CompressOptions) => void; + static: (paths: string[], opts?: KoaStaticOptions) => void; + historyFallback: (opts: HistoryApiFallbackOptions) => void; + websocket: () => void; + four0four: (fn?: (ctx: Koa.Context) => void) => void; +} + +export interface WebpackPluginServeOptions { + client?: { + address?: string; + retry?: boolean; + silent?: boolean; + }; + compress?: boolean; + historyFallback?: boolean | HistoryApiFallbackOptions; + hmr?: boolean; + host?: string | Promise; + http2?: boolean | Http2ServerOptions | Http2SecureServerOptions; + https?: HttpsServerOptions; + liveReload?: boolean; + log?: { + level: 'trace' | 'debug' | 'info' | 'warn' | 'error'; + timestamp?: boolean; + }; + middleware?: (app: Koa, builtins: Builtins) => void; + open?: + | boolean + | { + wait?: boolean; + app?: string | ReadonlyArray; + }; + port?: number | Promise; + progress?: boolean | 'minimal'; + static?: string | string[]; + status?: boolean; + waitForBuild?: boolean; +} + +export class WebpackPluginServe { + constructor(opts?: WebpackPluginServeOptions); + attach(): { + apply(compiler: Compiler): void; + }; + hook(compiler: Compiler): void; + apply(compiler: Compiler): void; +} diff --git a/types/webpack-plugin-serve/tsconfig.json b/types/webpack-plugin-serve/tsconfig.json new file mode 100644 index 0000000000..8b70e1d1d4 --- /dev/null +++ b/types/webpack-plugin-serve/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "strictFunctionTypes": true, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "webpack-plugin-serve-tests.ts" + ] +} diff --git a/types/webpack-plugin-serve/tslint.json b/types/webpack-plugin-serve/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/webpack-plugin-serve/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/webpack-plugin-serve/webpack-plugin-serve-tests.ts b/types/webpack-plugin-serve/webpack-plugin-serve-tests.ts new file mode 100644 index 0000000000..7abddcc600 --- /dev/null +++ b/types/webpack-plugin-serve/webpack-plugin-serve-tests.ts @@ -0,0 +1,39 @@ +import { WebpackPluginServe } from 'webpack-plugin-serve'; +import { Configuration } from 'webpack'; + +const usage = (config: Configuration) => { + (config.entry as string[]).push('webpack-plugin-serve/client'); + + config.watch = true; + + config.plugins!.push( + new WebpackPluginServe({ + compress: true, + historyFallback: true, + host: '0.0.0.0', + port: 3808, + liveReload: true, + middleware: (app: any, builtins: any) => + app.use(async (ctx: any, next: any) => { + await next(); + ctx.set('Access-Control-Allow-Headers', '*'); + ctx.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); + ctx.set('Access-Control-Allow-Origin', '*'); + }), + static: '/', + + status: true, + progress: true, + }), + ); + + config.output!.publicPath = '/'; + + return config; +}; + +const baseConfig = { + entry: 'index.js' +}; + +const configWithServer = usage(baseConfig); From 277ae76f590b5e5d1a52f33ee886d619a4b32a45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20F=C3=BCrst?= Date: Mon, 25 Mar 2019 17:36:43 +0100 Subject: [PATCH 077/710] [@types/react-color] Fix wrong color type on swatch hover (#33984) * Fix wrong type on swatch hover * Change variable name for consistency * Add user as definitions author * Change major version due to breaking changes --- types/react-color/index.d.ts | 5 +++-- types/react-color/lib/components/block/Block.d.ts | 4 ++-- types/react-color/lib/components/circle/Circle.d.ts | 2 +- types/react-color/lib/components/compact/Compact.d.ts | 4 ++-- types/react-color/lib/components/github/Github.d.ts | 4 ++-- types/react-color/lib/components/sketch/Sketch.d.ts | 4 ++-- types/react-color/lib/components/swatches/Swatches.d.ts | 4 ++-- types/react-color/lib/components/twitter/Twitter.d.ts | 4 ++-- 8 files changed, 16 insertions(+), 15 deletions(-) diff --git a/types/react-color/index.d.ts b/types/react-color/index.d.ts index 9935814feb..3e0b0f3989 100644 --- a/types/react-color/index.d.ts +++ b/types/react-color/index.d.ts @@ -1,10 +1,11 @@ -// Type definitions for react-color 2.17 +// Type definitions for react-color 3.0 // Project: https://github.com/casesandberg/react-color/, http://casesandberg.github.io/react-color // Definitions by: Karol Janyst , // Marks Polakovs , // Matthieu Montaudouin , // Nokogiri , -// 0815Strohhut +// 0815Strohhut , +// Daniel Fürst // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 diff --git a/types/react-color/lib/components/block/Block.d.ts b/types/react-color/lib/components/block/Block.d.ts index 20ea123eed..6761cf3f90 100644 --- a/types/react-color/lib/components/block/Block.d.ts +++ b/types/react-color/lib/components/block/Block.d.ts @@ -1,11 +1,11 @@ import { Component } from "react"; -import { ColorPickerProps, Color } from "../../.."; +import { ColorPickerProps, ColorResult } from "../../.."; export interface BlockPickerProps extends ColorPickerProps { colors?: string[]; width?: string; triangle?: 'hide' | 'top'; - onSwatchHover?(color: Color, event: MouseEvent): void; + onSwatchHover?(color: ColorResult, event: MouseEvent): void; } export default class BlockPicker extends Component {} diff --git a/types/react-color/lib/components/circle/Circle.d.ts b/types/react-color/lib/components/circle/Circle.d.ts index 98eec039a0..df230cf71d 100644 --- a/types/react-color/lib/components/circle/Circle.d.ts +++ b/types/react-color/lib/components/circle/Circle.d.ts @@ -6,7 +6,7 @@ export interface CirclePickerProps extends ColorPickerProps { width?: string; circleSize?: number; circleSpacing?: number; - onSwatchHover?(colorResult: ColorResult, event: MouseEvent): void; + onSwatchHover?(color: ColorResult, event: MouseEvent): void; } export default class CirclePicker extends Component {} diff --git a/types/react-color/lib/components/compact/Compact.d.ts b/types/react-color/lib/components/compact/Compact.d.ts index 5609899128..c79e331a33 100644 --- a/types/react-color/lib/components/compact/Compact.d.ts +++ b/types/react-color/lib/components/compact/Compact.d.ts @@ -1,9 +1,9 @@ import { Component } from "react"; -import { ColorPickerProps, Color } from "../../.."; +import { ColorPickerProps, ColorResult } from "../../.."; export interface CompactPickerProps extends ColorPickerProps { colors?: string[]; - onSwatchHover?(color: Color, event: MouseEvent): void; + onSwatchHover?(color: ColorResult, event: MouseEvent): void; } export default class CompactPicker extends Component {} diff --git a/types/react-color/lib/components/github/Github.d.ts b/types/react-color/lib/components/github/Github.d.ts index 18b6a21121..8155152f28 100644 --- a/types/react-color/lib/components/github/Github.d.ts +++ b/types/react-color/lib/components/github/Github.d.ts @@ -1,11 +1,11 @@ import { Component } from "react"; -import { ColorPickerProps, Color } from "../../.."; +import { ColorPickerProps, ColorResult } from "../../.."; export interface GithubPickerProps extends ColorPickerProps { colors?: string[]; width?: string; triangle?: 'hide' | 'top-left' | 'top-right'; - onSwatchHover?(color: Color, event: MouseEvent): void; + onSwatchHover?(color: ColorResult, event: MouseEvent): void; } export default class GithubPicker extends Component {} diff --git a/types/react-color/lib/components/sketch/Sketch.d.ts b/types/react-color/lib/components/sketch/Sketch.d.ts index 7aec9fb82f..bf11556a98 100644 --- a/types/react-color/lib/components/sketch/Sketch.d.ts +++ b/types/react-color/lib/components/sketch/Sketch.d.ts @@ -1,11 +1,11 @@ import { Component } from "react"; -import { ColorPickerProps, Color } from "../../.."; +import { ColorPickerProps, ColorResult } from "../../.."; export interface SketchPickerProps extends ColorPickerProps { disableAlpha?: boolean; presetColors?: string[]; width?: string; - onSwatchHover?(color: Color, event: MouseEvent): void; + onSwatchHover?(color: ColorResult, event: MouseEvent): void; } export default class SketchPicker extends Component {} diff --git a/types/react-color/lib/components/swatches/Swatches.d.ts b/types/react-color/lib/components/swatches/Swatches.d.ts index b2a7f72dc2..bf0b9dbd4a 100644 --- a/types/react-color/lib/components/swatches/Swatches.d.ts +++ b/types/react-color/lib/components/swatches/Swatches.d.ts @@ -1,11 +1,11 @@ import { Component } from "react"; -import { ColorPickerProps, Color } from "../../.."; +import { ColorPickerProps, ColorResult } from "../../.."; export interface SwatchesPickerProps extends ColorPickerProps { colors?: string[][]; height?: number; width?: number; - onSwatchHover?(color: Color, event: MouseEvent): void; + onSwatchHover?(color: ColorResult, event: MouseEvent): void; } export default class SwatchesPicker extends Component {} diff --git a/types/react-color/lib/components/twitter/Twitter.d.ts b/types/react-color/lib/components/twitter/Twitter.d.ts index 8d5eb2e6dd..73fbd6f984 100644 --- a/types/react-color/lib/components/twitter/Twitter.d.ts +++ b/types/react-color/lib/components/twitter/Twitter.d.ts @@ -1,11 +1,11 @@ import { Component } from "react"; -import { ColorPickerProps, Color } from "../../.."; +import { ColorPickerProps, ColorResult } from "../../.."; export interface TwitterPickerProps extends ColorPickerProps { colors?: string[]; width?: string; triangle?: 'hide' | 'top-left' | 'top-right'; - onSwatchHover?(color: Color, event: MouseEvent): void; + onSwatchHover?(color: ColorResult, event: MouseEvent): void; } export default class TwitterPicker extends Component {} From 486030d264c099ef84f68ebe45cd975c30c2b149 Mon Sep 17 00:00:00 2001 From: James Nimlos Date: Mon, 25 Mar 2019 09:38:31 -0700 Subject: [PATCH 078/710] Update fluent definitions for v0.11 (#33859) * update fluent definitions for v0.11 * remove circular reference * add typescript version requiring fix * downgrade ts version definitelytyped-header-parser errors on prereleases versions but TS v3.4 is not actually released so it also errors --- types/fluent-react/index.d.ts | 4 ++-- types/fluent/fluent-tests.ts | 6 ++++++ types/fluent/index.d.ts | 6 ++++-- types/fluent/tsconfig.json | 1 + 4 files changed, 13 insertions(+), 4 deletions(-) diff --git a/types/fluent-react/index.d.ts b/types/fluent-react/index.d.ts index 5ffc93d874..b3fa7c9dec 100644 --- a/types/fluent-react/index.d.ts +++ b/types/fluent-react/index.d.ts @@ -2,7 +2,7 @@ // Project: http://projectfluent.org // Definitions by: Huy Nguyen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.3 import * as React from 'react'; import { @@ -76,7 +76,7 @@ export type Matching = { */ export type Shared< InjectedProps, - DecorationTargetProps extends Shared + DecorationTargetProps > = { [P in Extract]?: InjectedProps[P] extends DecorationTargetProps[P] ? DecorationTargetProps[P] : never; }; diff --git a/types/fluent/fluent-tests.ts b/types/fluent/fluent-tests.ts index d2fcd4a6c4..90b4bffa61 100644 --- a/types/fluent/fluent-tests.ts +++ b/types/fluent/fluent-tests.ts @@ -29,6 +29,7 @@ const bundle4 = new FluentBundle(['en-US'], { // FluentBundle addMessages examples: bundle1.addMessages('foo = Foo'); +bundle2.hasMessage('foo'); bundle2.getMessage('foo'); // FluentBundle addResource examples: @@ -42,3 +43,8 @@ bundle1.addMessages('hello = Hello, { $name }!'); const hello = bundle2.getMessage('hello'); bundle3.format(hello, { name: 'Jane' }, errors2); bundle3.format(hello, undefined, errors2); + +for (const [id, message] of bundle1.messages) { + bundle1.getMessage(id); + bundle1.format(message); +} diff --git a/types/fluent/index.d.ts b/types/fluent/index.d.ts index 56014044ab..8520443354 100644 --- a/types/fluent/index.d.ts +++ b/types/fluent/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for fluent 0.10 +// Type definitions for fluent 0.11 // Project: http://projectfluent.org -// Definitions by: Huy Nguyen +// Definitions by: Huy Nguyen , James Nimlos // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -28,6 +28,8 @@ export class FluentResource extends Map { export class FluentBundle { constructor(locales: string | string[], options?: FluentBundleContructorOptions); + messages: IterableIterator<[string, FluentNode[]]>; + hasMessage(source: string): boolean; addMessages(source: string): string[]; getMessage(id: string): FluentNode[]; format(message: FluentNode[], args?: object, errors?: string[]): string; diff --git a/types/fluent/tsconfig.json b/types/fluent/tsconfig.json index 64e2460dcd..c08fe97570 100644 --- a/types/fluent/tsconfig.json +++ b/types/fluent/tsconfig.json @@ -4,6 +4,7 @@ "lib": [ "es6" ], + "target": "es6", "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, From 58e4f00832fa8ffd2fb060a710eecb52ba858e5b Mon Sep 17 00:00:00 2001 From: Johan Davidsson Date: Mon, 25 Mar 2019 17:39:20 +0100 Subject: [PATCH 079/710] [@types/htmlparser2] Update typings for Htmlparser2 (and related modules) to match updates (#33921) * Added new types for domelementtype * Modify existing types for htmlparser2 * Updating PULL_REQUEST_TEMPLATE.md * Revert changes to .github/PULL_REQUEST_TEMPLATE.md * Fixed missing optional * Adding DomUtils * Update dependencies * Removed requirement for TypeScript 2.1 and updated test * Updated test to include DomUtils and DomHandlerOptions. * Updated domhandler tests * Remove incorrect constructor in Parser * Remove incorrect constructor in WritableStream * Change way of importing in tests * Adding deprecated fallback to Options * Add deprecated Options as a fallback to sanitize-html * Add ParserOptions * Use the deprecated Options --- types/domhandler/domhandler-tests.ts | 8 +-- types/domhandler/index.d.ts | 1 - types/domutils/index.d.ts | 1 - types/htmlparser2/htmlparser2-tests.ts | 37 ++++++++------ types/htmlparser2/index.d.ts | 68 ++++++++++++++++++-------- types/sanitize-html/index.d.ts | 1 + 6 files changed, 74 insertions(+), 42 deletions(-) diff --git a/types/domhandler/domhandler-tests.ts b/types/domhandler/domhandler-tests.ts index eea6441ad7..4b1c5406ec 100644 --- a/types/domhandler/domhandler-tests.ts +++ b/types/domhandler/domhandler-tests.ts @@ -1,6 +1,6 @@ -import { DomHandler, DomHandlerOptions, Node } from "domhandler"; +import { DomHandler, DomHandlerOptions, Node, DomElement } from "domhandler"; -const handler = new DomHandler((error: Error, dom: any) => { +const handler = new DomHandler((error: Error, dom: DomElement[]) => { if (error) console.error('There has been an error...'); else @@ -8,7 +8,7 @@ const handler = new DomHandler((error: Error, dom: any) => { }); handler.ontext = (data: string) => { console.log(data); }; handler.onreset = () => { console.log('We have a reset.'); }; -handler.onerror = (error: Error) => { console.error(Error); }; -handler.onopentag = (name: string, attribs) => { console.log(name, attribs); }; +handler.onerror = (error: Error) => { console.error(error); }; +handler.onopentag = (name: string, attribs: { [s: string]: string }) => { console.log(name, attribs); }; const dho: DomHandlerOptions = { normalizeWhitespace: true, withDomLvl1: true, withEndIndices: true, withStartIndices: true }; diff --git a/types/domhandler/index.d.ts b/types/domhandler/index.d.ts index 9d33055bbd..49dcd6325f 100644 --- a/types/domhandler/index.d.ts +++ b/types/domhandler/index.d.ts @@ -2,7 +2,6 @@ // Project: https://github.com/fb55/DomHandler#readme // Definitions by: Johan Davidsson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 export interface DomHandlerOptions { /*** diff --git a/types/domutils/index.d.ts b/types/domutils/index.d.ts index 5300a68a8c..6790f9bf82 100644 --- a/types/domutils/index.d.ts +++ b/types/domutils/index.d.ts @@ -2,7 +2,6 @@ // Project: https://github.com/FB55/domutils#readme // Definitions by: Johan Davidsson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 import { DomElement } from "domhandler"; /*** diff --git a/types/htmlparser2/htmlparser2-tests.ts b/types/htmlparser2/htmlparser2-tests.ts index 21289b96f5..807f2fe904 100644 --- a/types/htmlparser2/htmlparser2-tests.ts +++ b/types/htmlparser2/htmlparser2-tests.ts @@ -1,23 +1,30 @@ /** * Created by staticfunction on 8/4/14. */ -import htmlparser = require("htmlparser2"); +import htmlparser = require('htmlparser2'); -var parser = new htmlparser.Parser({ - onopentag: (name:string, attribs:{[s:string]:string}) => { - if(name === "script" && attribs['type'] === "text/javascript"){ - console.log("JS! Hooray!"); - } - }, - ontext: (text: string) => { - console.log("-->", text); - }, - onclosetag: (tagname:string) => { - if(tagname === "script"){ - console.log("That's it?!"); - } +const options: htmlparser.DomHandlerOptions = { withEndIndices: false, withDomLvl1: true } +const dh = new htmlparser.DomHandler((err: Error, dom: htmlparser.DomElement[]) => { + if(err) { + throw err; } -}); + + // Use DomUtils to get name of first element in dom + console.log(htmlparser.DomUtils.getName(dom[0])); +}, options); +dh.onopentag = (name:string, attribs:{[s:string]:string}) => { + if(name === "script" && attribs['type'] === "text/javascript"){ + console.log("JS! Hooray!"); + } +}; +dh.ontext = (text: string) => { + console.log("-->", text); +}; +dh.onclosetag = () => { + console.log("That's it?!"); +}; + +var parser = new htmlparser.Parser(dh); parser.write("Xyz "); parser.end(); diff --git a/types/htmlparser2/index.d.ts b/types/htmlparser2/index.d.ts index 313ff56a96..c10dea047e 100644 --- a/types/htmlparser2/index.d.ts +++ b/types/htmlparser2/index.d.ts @@ -1,30 +1,20 @@ -// Type definitions for htmlparser2 v3.7.x +// Type definitions for htmlparser2 v3.10.x // Project: https://github.com/fb55/htmlparser2/ // Definitions by: James Roland Cabresos // Linus Unnebäck +// Johan Davidsson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// +/// +/// import { Writable } from 'stream' +import { DomHandler } from 'domhandler'; +import * as DomUtils from 'domutils'; +export { DomElement, DomHandlerOptions, DomHandler, Element, Node } from 'domhandler'; -export interface Handler { - onopentag?: (name: string, attribs: { [type: string]: string }) => void; - onopentagname?: (name: string) => void; - onattribute?: (name: string, value: string) => void; - ontext?: (text: string) => void; - onclosetag?: (text: string) => void; - onprocessinginstruction?: (name: string, data: string) => void; - oncomment?: (data: string) => void; - oncommentend?: () => void; - oncdatastart?: () => void; - oncdataend?: () => void; - onerror?: (error: Error) => void; - onreset?: () => void; - onend?: () => void; -} - -export interface Options { +export interface ParserOptions { /*** * Indicates whether special tags (