From 5b018e667bec1b1fcca6ad83822a9acc47c41f24 Mon Sep 17 00:00:00 2001 From: ChenX Date: Mon, 18 Sep 2017 10:32:21 +0800 Subject: [PATCH 001/201] Clean code --- types/three/three-core.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index b2fa482639..cf45c757ca 100644 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -4820,8 +4820,7 @@ export class LineSegments extends Line { } export class Mesh extends Object3D { - constructor(geometry?: Geometry, material?: Material | Material []); - constructor(geometry?: BufferGeometry, material?: Material | Material []); + constructor(geometry?: Geometry | BufferGeometry, material?: Material | Material []); geometry: Geometry|BufferGeometry; material: Material | Material[]; From 9e0c0e74fbe721ee379aedf8cddcb17c5f266872 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jozef=20B=C3=ADro=C5=A1?= Date: Sat, 28 Oct 2017 11:38:09 +0200 Subject: [PATCH 002/201] Actualized FieldArrayMetaProps and FieldProps according to flow types from redux-form v7.1.2 --- types/redux-form/v6/lib/FieldArray.d.ts | 38 +++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/types/redux-form/v6/lib/FieldArray.d.ts b/types/redux-form/v6/lib/FieldArray.d.ts index 9629eecb27..42308c4f76 100644 --- a/types/redux-form/v6/lib/FieldArray.d.ts +++ b/types/redux-form/v6/lib/FieldArray.d.ts @@ -103,6 +103,10 @@ interface WrappedFieldArrayProps { } interface FieldsProps { + /** + * true if field is field array + */ + _isFieldArray: boolean /** * A method to iterate over each value of the array. */ @@ -134,6 +138,15 @@ interface FieldsProps { */ map(callback: (name: string, index: number, fields: FieldsProps) => any): any; + /** + * A method to move value in array on on different index in the field array + */ + move(from: number, to: number): void; + + /** + * Name of field array + */ + name: string; /** * Removes an item from the end of the array. Returns the item removed. */ @@ -144,16 +157,32 @@ interface FieldsProps { */ push(value: T): void; + /** + * TODO: Need to figure out what does this do, its taken + * directly form redux-form repo and flow types + */ + reduce(callback: Function): any + /** * Removes an item from the array at an arbitrary index. */ remove(index: number): void; + /** + * It will remove all fields in field array + */ + removeAll(): void + /** * Removes an item from beginning of the array. Returns the item removed. */ shift(): T; + /** + * TODO: Need to figure out what does this do, its taken + * directly form redux-form repo and flow types + */ + some(callback: Function): void /** * Swaps two items in the array at the given indexes. */ @@ -197,6 +226,15 @@ interface FieldArrayMetaProps { */ pristine: boolean; + /** + * true if field array is being submitted + */ + submitting: boolean; + + /** + * true if some field value in the field array fails validation on submit + */ + submitFailed: boolean; /** * true if any of the fields have been touched. */ From 58232d354e2af1e9dc4d5303b088d66eca037047 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Radek=20Mat=C4=9Bj?= Date: Tue, 31 Oct 2017 11:55:38 +0100 Subject: [PATCH 003/201] Declare property on window object --- types/cordova-plugin-device/index.d.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/types/cordova-plugin-device/index.d.ts b/types/cordova-plugin-device/index.d.ts index cb75703d1a..0ca54cf34a 100644 --- a/types/cordova-plugin-device/index.d.ts +++ b/types/cordova-plugin-device/index.d.ts @@ -2,14 +2,18 @@ // Project: https://github.com/apache/cordova-plugin-device // Definitions by: Microsoft Open Technologies Inc // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// +// // Copyright (c) Microsoft Open Technologies Inc -// Licensed under the MIT license +// Licensed under the MIT license /** * This plugin defines a global device object, which describes the device's hardware and software. * Although the object is in the global scope, it is not available until after the deviceready event. */ + interface Window { + device: Device; +} + interface Device { /** Get the version of Cordova running on the device. */ cordova: string; From bc20b02f4ce24e255f8fdd1bcf5799d3b8477f89 Mon Sep 17 00:00:00 2001 From: ZheyangSong Date: Mon, 6 Nov 2017 16:16:55 -0800 Subject: [PATCH 004/201] Recharts Typing Update + Many interfaces are partially shaped or wrongly shaped. + Replace tab with 4-spaces --- types/recharts/index.d.ts | 1393 +++++++++++++++-------------- types/recharts/recharts-tests.tsx | 1 + 2 files changed, 743 insertions(+), 651 deletions(-) diff --git a/types/recharts/index.d.ts b/types/recharts/index.d.ts index c9bf71283d..81fa7aee98 100644 --- a/types/recharts/index.d.ts +++ b/types/recharts/index.d.ts @@ -3,843 +3,934 @@ // Definitions by: Maarten Mulders // Raphael Mueller // Roy Xue +// Zheyang Song // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import * as React from 'react'; +import { CurveFactory } from 'd3-shape'; export type Percentage = string; export type RechartsFunction = () => void; export type TickFormatterFunction = (value: any) => any; +export type TickGeneratorFunction = (noTicksProps: object) => any[]; export type LabelFormatter = (label: string | number) => React.ReactNode; export type TooltipFormatter = (value: string | number | Array, name: string, entry: TooltipPayload, index: number) => React.ReactNode; export type ItemSorter = (a: T, b: T) => number; export type ContentRenderer

= (props: P) => React.ReactNode; +export type DataKey = string | number | ((dataObject: any) => number | [number, number]); -export type LegendType = 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | 'none'; +export type IconType = 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye'; +export type LegendType = IconType | 'none'; export type LayoutType = 'horizontal' | 'vertical'; export type AnimationEasingType = 'ease' | 'ease-in' | 'ease-out' | 'ease-in-out' | 'linear'; -export type ScaleType = 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | 'ordinal' | 'quantile' | 'quantize' | 'utcTime' | 'sequential' | 'threshold'; -export type PositionType = 'top' | 'left' | 'right' | 'bottom' | 'inside' | 'outside'| 'insideLeft' | 'insideRight' | - 'insideTop' | 'insideBottom' | 'insideTopLeft' | 'insideBottomLeft' | 'insideTopRight' | 'insideBottomRight' | 'insideStart' | 'insideEnd' | 'end' | 'center'; +export type ScaleType = + 'auto' | 'linear' | 'pow' | 'sqrt' | 'log' | 'identity' | 'time' | 'band' | 'point' | + 'ordinal' | 'quantile' | 'quantize' | 'utcTime' | 'sequential' | 'threshold'; +export type PositionType = + 'top' | 'left' | 'right' | 'bottom' | 'inside' | 'outside'| 'insideLeft' | 'insideRight' | + 'insideTop' | 'insideBottom' | 'insideTopLeft' | 'insideBottomLeft' | 'insideTopRight' | + 'insideBottomRight' | 'insideStart' | 'insideEnd' | 'end' | 'center'; +export type StackOffsetType = 'sign' | 'expand' | 'none' | 'wiggle' | 'silhouette'; +export type LineType = + 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | + 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | CurveFactory; +export type AxisInterval = number | 'preserveStart' | 'preserveEnd' | 'preserveStartEnd'; -export type PartialAndNumber = { - [P in keyof T]?: number | T[P]; -}; +export type PickedCSSStyleDeclarationKeys = + 'alignmentBaseline' | 'baselineShift' | 'clip' | 'clipPath' | 'clipRule' | 'color' | + 'colorInterpolationFilters' | 'cursor' | 'direction' | 'display' | 'dominantBaseline' | + 'enableBackground' | 'fill' | 'fillRule' | 'filter' | 'floodColor' | + 'floodOpacity' | 'font' | 'fontFamily' | 'fontStretch' | 'fontStyle' | 'fontVariant' | + 'glyphOrientationHorizontal' | 'glyphOrientationVertical' | 'letterSpacing' | 'lightingColor' | + 'markerEnd' | 'markerMid' | 'markerStart' | 'mask' | 'overflow' | 'pointerEvents' | + 'stopColor' | 'strokeDasharray' | 'strokeLinecap' | 'strokeLinejoin' | 'textAnchor' | + 'textDecoration' | 'unicodeBidi' | 'visibility' | 'writingMode' | 'transform'; -export interface Margin { - top: number; - right: number; - bottom: number; - left: number; +export interface Point { + x: number; + y: number; + value: number | any[]; } -export interface AreaProps extends Partial { - type?: 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | RechartsFunction; - dataKey?: string | number; - xAxisId?: string | number; - yAxisId?: string | number; - legendType?: LegendType; - dot?: boolean | any | React.ReactElement | RechartsFunction; - activeDot?: boolean | any | React.ReactElement | RechartsFunction; - label?: boolean | any | React.ReactElement | RechartsFunction; - stroke?: string; - layout?: LayoutType; - baseLine?: number | any[]; - points?: any[]; - stackId?: string | number; - connectNulls?: boolean; - unit?: string | number; - name?: string | number; - isAnimationActive?: boolean; - animationBegin?: number; - animationEasing?: AnimationEasingType; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface Margin { + top: number; + right: number; + bottom: number; + left: number; +} + +export interface Animatable { + onAnimationStart?: RechartsFunction; + onAnimationEnd?: RechartsFunction; + animationId?: number; + isAnimationActive?: boolean; + isUpdateAnimationActive?: boolean; + animationBegin?: number; + animationDuration?: number; + animationEasing?: AnimationEasingType; +} + +export interface CategoricalChartWrapper { + syncId?: string | number; + compact?: boolean; + width?: number; + height?: number; + data?: object[]; + layout?: L; + stackOffset?: StackOffsetType; + throttleDelay?: number; + margin?: Partial; + barCategoryGap?: number | string; + barGap?: number | string; + barSize?: number | string; + maxBarSize?: number; + style?: object; + className?: string; + children?: React.ReactNode | React.ReactNode[]; + onClick?: RechartsFunction; + onMouseLeave?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + reverseStackOrder?: boolean; +} + +export interface EventAttributes { + onClick?: RechartsFunction; + onMouseDown?: RechartsFunction; + onMouseUp?: RechartsFunction; + onMouseOver?: RechartsFunction; + onMouseMove?: RechartsFunction; + onMouseOut?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + onTouchEnd?: RechartsFunction; + onTouchMove?: RechartsFunction; + onTouchStart?: RechartsFunction; + onTouchCancel?: RechartsFunction; +} + +export interface PresentationAttributes extends Pick { + angle: number; + colorInterpolation: string; + colorProfile: string; + colorRendering: string; + fillOpacity: number | string; + fontSize: number | string; + fontSizeAdjust: number | string; + fontWeight: 'normal' | 'bold' | 'bolder' | 'lighter' | + 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | 'inherit'; + imageRendering: 'auto' | 'optimizeSpeed' | 'optimizeQuality' | 'inherit'; + kerning: number | string; + opacity: number | string; + shapeRendering: 'auto' | 'optimizeSpeed' | 'crispEdges' | 'geometricPrecision' | 'inherit'; + stopOpacity: number | string; + stroke: number | string; + strokeDashoffset: number | string; + strokeMiterlimit: number | string; + strokeOpacity: number | string; + strokeWidth: number | string; + textRendering: 'auto' | 'optimizeSpeed' | 'optimizeLegibility' | 'geometricPrecision' | 'inherit'; + wordSpacing: number | string; + style: object; + width: number; + height: number; + dx: number; + dy: number; + x: X; + y: Y; + r: number; +} + +export interface AreaProps extends EventAttributes, Partial, Animatable { + dataKey: DataKey; // As the source code states, dataKey will replace valueKey in 1.1.0 and it'll be required (it's already required in current implementation). + className?: string; + type?: LineType; + unit?: string | number; + name?: string | number; + xAxisId?: string | number; + yAxisId?: string | number; + xAxis?: object; + yAxis?: object; + stackId?: string | number; + legendType?: LegendType; + connectNulls?: boolean; + activeDot?: boolean | object | React.ReactElement | ContentRenderer; + dot?: boolean | object | React.ReactElement | ContentRenderer; + label?: boolean | object | React.ReactElement | Label['content']; + hide?: boolean; + layout?: LayoutType; + baseLine?: number | any[]; + isRange?: boolean; + points?: Point[]; } export class Area extends React.Component { } -export interface AreaChartProps { - layout?: LayoutType; - syncId?: string; - width: number; - height: number; - data: any[]; - margin?: Margin; - stackOffset?: 'expand' | 'none' | 'wiggle' | 'silhouette'; - baseValue?: number | 'dataMin' | 'dataMax' | 'auto'; - onClick?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseLeave?: RechartsFunction; -} +// NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it). +export type AreaChartProps = CategoricalChartWrapper & EventAttributes; export class AreaChart extends React.Component { } -export interface BarProps extends Partial { - layout?: LayoutType; - dataKey?: string | number; - xAxisId?: string | number; - yAxisId?: string | number; - legendType?: LegendType; - label?: boolean | any | React.ReactElement | RechartsFunction; - data?: any[]; - barSize?: number; - maxBarSize?: number; - minPointSize?: number; - shape?: React.ReactElement | RechartsFunction; - stackId?: string | number; - unit?: string | number; - name?: string | number; - isAnimationActive?: boolean; - animationBegin?: number; - animationEasing?: AnimationEasingType; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface BarData { + x: number; + y: number; + width: number; + height: number; + radius: number | any[]; + value: number | string | any[]; +} + +export interface BarProps extends EventAttributes, Partial, Animatable { + dataKey: DataKey; // As the source code states, dataKey will replace valueKey in 1.1.0 and it'll be required (it's already required in current implementation). + className?: string; + layout?: LayoutType; + xAxisId?: string | number; + yAxisId?: string | number; + yAxis?: object; + xAxis?: object; + stackId?: string | number; + barSize?: number; + unit?: string | number; + name?: string | number; + legendType?: LegendType; + minPointSize?: number; + maxBarSize?: number; + hide?: boolean; + shape?: React.ReactElement | ContentRenderer; + data?: BarData[]; } export class Bar extends React.Component { } -export interface BarChartProps { - layout?: LayoutType; - syncId?: string; - width?: number; - height?: number; - data?: any[]; - margin?: Margin; - barCategoryGap?: Percentage | number; - barGap?: Percentage | number; - barSize?: number; - maxBarSize?: number; - stackOffset?: 'expand' | 'none' | 'wiggle' | 'silhouette' | 'sign'; - onClick?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseLeave?: RechartsFunction; -} +// NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it). +export type BarChartProps = CategoricalChartWrapper & EventAttributes; export class BarChart extends React.Component { } export interface BrushProps { - dataKey: number | string; - x?: number; - y?: number; - width?: number; - height?: number; - data: any[]; - travellerWidth?: number; - startIndex?: number; - endIndex?: number; - tickFormatter?: TickFormatterFunction; - onChange?: RechartsFunction; + className?: string; + fill?: string; + stroke?: string; + x: number; + y: number; + width: number; + height: number; + travellerWidth?: number; + padding?: Partial; + dataKey?: DataKey; + data?: any[]; + startIndex?: number; + endIndex?: number; + tickFormatter?: TickFormatterFunction; + children?: React.ReactNode; + onChange?: (newIndex: { + startIndex: number; + endIndex: number; + }) => void; + updateId?: string | number; } export class Brush extends React.Component { } -export interface CartesianAxisProps { - x?: number; - y?: number; - width?: number; - height?: number; - orientation?: 'top' | 'bottom' | 'left' | 'right'; - viewBox?: ViewBox; - axisLine?: boolean | any; - tickLine?: boolean | any; - minTickGap?: number; - tickSize?: number; - interval?: "preserveStart" | "preserveEnd" | "preserveStartEnd" | number; - tick?: boolean | any | React.ReactElement | RechartsFunction; - label?: string | number | React.ReactElement | ContentRenderer; - mirror?: boolean; +export interface CartesianAxisProps extends EventAttributes, Partial { + className?: string; + x?: number; + y?: number; + width?: number; + height?: number; + orientation?: 'top' | 'bottom' | 'left' | 'right'; + viewBox?: ViewBox; + tick?: boolean | ContentRenderer | object | React.ReactElement; + axisLine?: boolean | object; + tickLine?: boolean | object; + mirror?: boolean; + minTickGap?: number; + ticks?: any[]; + tickSize?: number; + stroke?: string; + tickFormatter?: TickFormatterFunction; + ticksGenerator?: TickGeneratorFunction; + interval?: AxisInterval; } export class CartesianAxis extends React.Component { } -export interface CartesianGridProps extends Partial { - x?: number; - y?: number; - horizontal?: boolean; - vertical?: boolean; - horizontalPoints?: any[]; - verticalPoints?: any[]; +export interface CartesianGridProps extends Partial { + y?: number; + width?: number; + height?: number; + horizontal?: object | React.ReactElement | ContentRenderer | boolean; + vertical?: object | React.ReactElement | ContentRenderer | boolean; + horizontalPoints?: number[]; + verticalPoints?: number[]; + horizontalCoordinatesGenerator?: (arg: { + yAxis: CartesianGridProps['yAxis']; + width: CartesianGridProps['chartWidth']; + height: CartesianGridProps['chartHeight']; + offset: CartesianGridProps['offset']; + }) => number[]; + verticalCoordinatesGenerator?: (arg: { + yAxis: CartesianGridProps['xAxis']; + width: CartesianGridProps['chartWidth']; + height: CartesianGridProps['chartHeight']; + offset: CartesianGridProps['offset']; + }) => number[]; + xAxis?: object; + yAxis?: object; + offset?: object; + chartWidth?: number; + chartHeight?: number; } export class CartesianGrid extends React.Component { } -export interface CellProps { - fill?: string; - stroke?: string; -} +// NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it). +export type CellProps = Partial; export class Cell extends React.Component { } -export interface ComposedChartProps { - layout?: LayoutType; - syncId?: string; - width?: number; - height?: number; - data?: any[]; - margin?: Margin; - barCategoryGap?: Percentage | number; - barGap?: number; - barSize?: number; - onClick?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseLeave?: RechartsFunction; -} +// NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it). +export type ComposedChartProps = CategoricalChartWrapper & EventAttributes; export class ComposedChart extends React.Component { } -export interface CrossProps { - x?: number; - y?: number; - top?: number; - left?: number; - width?: number; - height?: number; +export interface CrossProps extends Partial { + className?: string; + x?: number; + y?: number; + width?: number; + height?: number; + top?: number; + left?: number; } export class Cross extends React.Component { } -export interface CurveProps extends Partial { - type?: 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | RechartsFunction; - points: any[]; - layout?: LayoutType; - baseLine?: number | any[]; - connectNulls?: boolean; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +// NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it). +export interface CurveProps extends EventAttributes, Partial { + className?: string; + type?: LineType; + layout?: LayoutType; + baseLine?: number | any[]; + points?: object[]; + connectNulls?: boolean; + path?: string; + pathRef?: React.Ref; } export class Curve extends React.Component { } -export interface DotProps { - cx: number; - cy: number; - r: number; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseLeave?: RechartsFunction; +// NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it). +export interface DotProps extends EventAttributes { + className?: string; + cx?: number; + cy?: number; + r?: number; } export class Dot extends React.Component { } -export interface ErrorBarProps extends Partial { - dataKey?: string | number; - strokeWidth?: string; - stroke?: string; - direction?: string; +export interface ErrorBarProps { + dataKey: DataKey; // As the source code states, dataKey will replace valueKey in 1.1.0 and it'll be required (it's already required in current implementation). + data?: any[]; + xAxis?: object; + yAxis?: object; + layout?: string; + dataPointFormatter?: (entry: any, dataKey: DataKey) => { x: number; y: number, value: any; errorVal: any; }; + stroke?: string; + strokeWidth?: number; + width?: number; + offset?: number; } export class ErrorBar extends React.Component { } +export interface LegendPayload { + value: any; + id: any; + type: LegendType; +} + export interface LegendProps { - width?: number; - height?: number; - layout?: LayoutType; - align?: 'left' | 'center' | 'right'; - verticalAlign?: 'top' | 'middle' | 'bottom'; - iconSize?: number; - iconType?: 'line' | 'square' | 'rect' | 'circle' | 'cross' | 'diamond' | 'star' | 'triangle' | 'wye'; - payload?: any[]; - chartWidth?: number; - chartHeight?: number; - margin?: Margin; - content?: React.ReactElement | ContentRenderer; - wrapperStyle?: any; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; + content?: React.ReactElement | ContentRenderer; + wrapperStyle?: object; + chartWidth?: number; + chartHeight?: number; + width?: number; + height?: number; + iconSize?: number; + iconType?: IconType; + layout?: LayoutType; + align?: 'left' | 'center' | 'right'; + verticalAlign?: 'top' | 'middle' | 'bottom'; + margin?: Partial; + payload?: LegendPayload[]; + formatter?: RechartsFunction; + onClick?: RechartsFunction; + onMouseEnter?: RechartsFunction; + onMouseLeave?: RechartsFunction; + onBBoxUpdate?: (box: { width: number; height: number; }) => void; } export class Legend extends React.Component { } -export interface LineProps extends Partial { - type?: 'basis' | 'basisClosed' | 'basisOpen' | 'linear' | 'linearClosed' | 'natural' | 'monotoneX' | 'monotoneY' | 'monotone' | 'step' | 'stepBefore' | 'stepAfter' | RechartsFunction; - dataKey: string | number; - xAxisId?: string | number; - yAxisId?: string | number; - legendType?: LegendType; - dot?: boolean | any | React.ReactElement | RechartsFunction; - activeDot?: boolean | any | React.ReactElement | RechartsFunction; - label?: boolean | any | React.ReactElement | RechartsFunction; - points?: any[]; // made this points property partial, since in every example they don't use this property. But their definition says not optional. - layout?: LayoutType; - connectNulls?: boolean; - unit?: string | number; - name?: string | number; - isAnimationActive?: boolean; - animationBegin?: number; - animationEasing?: AnimationEasingType; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface LineProps extends EventAttributes, Partial, Animatable { + className?: string; + type?: LineType; + unit?: string | number; + name?: string | number; + xAxisId?: string | number; + yAxisId?: string | number; + yAxis?: object; + xAxis?: object; + legendType?: LegendType; + layout?: LayoutType; + connectNulls?: boolean; + hide?: boolean; + activeDot?: object | React.ReactElement | ContentRenderer | boolean; + dot?: object | React.ReactElement | ContentRenderer | boolean; + top?: number; + left?: number; + width?: number; + height?: number; + dataKey: string | number; // As the source code states, dataKey will replace valueKey in 1.1.0 and it'll be required (it's already required in current implementation). + label?: boolean | object | React.ReactElement | Label['content']; + points?: Point[]; } export class Line extends React.Component { } -export interface LineChartProps { - layout?: LayoutType; - syncId?: string; - width?: number; - height?: number; - data?: any[]; - margin?: Margin; - onClick?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseLeave?: RechartsFunction; -} +// NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it). +export type LineChartProps = CategoricalChartWrapper & EventAttributes; export class LineChart extends React.Component { } -export interface PieProps extends Partial { - cx?: Percentage | number; - cy?: Percentage | number; - innerRadius?: Percentage | number; - outerRadius?: Percentage | number; - startAngle?: number; - endAngle?: number; - minAngle?: number; - paddingAngle?: number; - nameKey?: string; - dataKey?: string; - valueKey?: string; - legendType?: LegendType; - label?: boolean | any | React.ReactElement | RechartsFunction; - labelLine?: boolean | any | React.ReactElement | RechartsFunction; - data: any[]; - activeIndex?: number | number[]; - activeShape?: any | React.ReactElement | RechartsFunction; - isAnimationActive?: boolean; - animationBegin?: number; - animationEasing?: AnimationEasingType | RechartsFunction; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface PieProps extends EventAttributes, Partial, Animatable { + className?: string; + dataKey: DataKey; // As the source code states, dataKey will replace valueKey in 1.1.0 and it'll be required (it's already required in current implementation). + cx?: number | string; + cy?: number | string; + startAngle?: number; + endAngle?: number; + paddingAngle?: number; + innerRadius?: number | string; + outerRadius?: number | string; + cornerRadius?: number | string; + nameKey?: string | number | ((dataObject: any) => number); + valueKey?: string | number | ((dataObject: any) => number); + data?: object[]; + minAngle?: number; + legendType?: LegendType; + maxRadius?: number; + sectors?: object[]; + hide?: boolean; + labelLine?: object | ContentRenderer | React.ReactElement | boolean; + label?: { + offsetRadius: number; + } | Label['content'] | React.ReactElement | boolean; + activeShape?: object |ContentRenderer | React.ReactElement; + activeIndex?: number | number[]; } export class Pie extends React.Component { } -export interface PieChartProps { - width: number; - height: number; - margin?: Margin; - onClick?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +// NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it). +export interface PieChartProps extends EventAttributes, CategoricalChartWrapper<'centric'> { + startAngle?: number; + endAngle?: number; + cx?: number | string; + cy?: number | string; + innerRadius?: number | string; + outerRadius?: number | string; } export class PieChart extends React.Component { } -export interface PolarAngleAxisProps { - dataKey: string | number; - cx: number; - cy: number; - radius: Percentage | number; - axisLine?: boolean | any; - axisLineType?: string; - tickLine?: boolean | any; - tick?: boolean | any | React.ReactElement | RechartsFunction; - ticks: any[]; - orient?: string; - tickFormatter: TickFormatterFunction; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface PolarAngleAxisTick { + value: any; + coordinate: number; +} + +export interface PolarAngleAxisProps extends EventAttributes, Partial { + type?: 'number' | 'category'; + angleAxisId?: string | number; + dataKey?: DataKey; // As the source code states, dataKey will replace valueKey in 1.1.0 and it'll be required (it's already required in current implementation). + cx?: number; + cy?: number; + radius?: Percentage | number; + hide?: boolean; + scale?: ScaleType | RechartsFunction; // this seems not being used by the lib. + axisLine?: boolean | object; + axisLineType?: 'polygon' | 'circle'; + tickLine?: boolean | object; + tick?: boolean | ContentRenderer | object | React.ReactElement; + ticks?: PolarAngleAxisTick[]; + stroke?: string; + orientation?: 'inner' | 'outer'; + tickFormatter: TickFormatterFunction; } export class PolarAngleAxis extends React.Component { } -export interface PolarGridProps extends Partial { - cx: number; - cy: number; - innerRadius: number; - outerRadius: number; - polarAngles: any[]; - polarRadius: any[]; - gridType?: 'polygon' | 'circle'; +export interface PolarGridProps extends Partial { + cx?: number; + cy?: number; + innerRadius?: number; + outerRadius?: number; + polarAngles?: number[]; + polarRadius?: number[]; + gridType?: 'polygon' | 'circle'; } export class PolarGrid extends React.Component { } -export interface PolarRadiusAxisProps { - angle?: number; - cx: number; - cy: number; - domain?: any[]; - label?: string | number | React.ReactElement | RechartsFunction; - orientation?: "left" | "right" | "middle"; - axisLine?: boolean | any; - tick?: boolean | any | Element | RechartsFunction; - tickFormatter: TickFormatterFunction; - tickCount?: number; - scale?: ScaleType | RechartsFunction; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface PolarRadiusAxisTick { + value: any; + coordinate: number; +} + +export type PolarRadiusAxisDomain = number | 'auto' | 'dataMin' | 'dataMax'; + +export interface PolarRadiusAxisProps extends EventAttributes, Partial { + type?: 'number' | 'category'; + cx?: number; + cy?: number; + hide?: boolean; + radiusAxisId?: string | number; + angle?: number; + tickCount?: number; + ticks?: PolarRadiusAxisTick[]; + orientation?: "left" | "right" | "middle"; + axisLine?: boolean | object; + tick?: boolean | object | React.ReactElement | ContentRenderer; + stroke?: string; + tickFormatter: TickFormatterFunction; + domain?: PolarRadiusAxisDomain[]; + scale?: ScaleType | RechartsFunction; + allowDataOverflow?: boolean; } export class PolarRadiusAxis extends React.Component { } -export interface PolygonProps { - points: any[]; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface PolygonPoint { + x: number; + y: number; +} + +export interface PolygonProps extends EventAttributes, Partial { + className?: string; + points?: PolygonPoint[]; } export class Polygon extends React.Component { } -export interface RadarProps extends Partial { - dataKey: string | number; - points: any[]; - shape: Element | RechartsFunction; - dot?: boolean | any | Element | RechartsFunction; - legendType?: LegendType; - label?: boolean | any | Element | RechartsFunction; - isAnimationActive?: boolean; - animationBegin?: number; - animationEasing?: AnimationEasingType; +export interface RadarPoint { + x: number; + y: number; + cx: number; + cy: number; + angle: number; + radius: number; + value: number; + payload: object; +} + +export interface RadarProps extends EventAttributes, Partial, Animatable { + className?: string; + dataKey: DataKey; // As the source code states, dataKey will replace valueKey in 1.1.0 and it'll be required (it's already required in current implementation). + points?: RadarPoint[]; + shape?: React.ReactElement | ContentRenderer; + activeDot?: object | React.ReactElement | ContentRenderer | boolean; + dot?: object | React.ReactElement | ContentRenderer | boolean; + label?: object | React.ReactElement | Label['content'] | boolean; + legendType?: LegendType; + hide?: boolean; } export class Radar extends React.Component { } -export interface RadarChartProps { - width: number; - height: number; - cx?: Percentage | number; - cy?: Percentage | number; - startAngle?: number; - innerRadius?: Percentage | number; - outerRadius?: Percentage | number; - margin?: Margin; - clockWise?: boolean; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - onClick?: RechartsFunction; +// NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it). +export interface RadarChartProps extends EventAttributes, CategoricalChartWrapper<'centric'> { + startAngle?: number; + endAngle?: number; + cx?: number | string; + cy?: number | string; + innerRadius?: number | string; + outerRadius?: number | string; } export class RadarChart extends React.Component { } -export interface RadialBarProps extends Partial { - cx?: number; - cy?: number; - startAngle?: number; - endAngle?: number; - maxAngle?: number; - minAngle?: number; - legendType?: LegendType; - label?: boolean | any | React.ReactElement | RechartsFunction; - background?: boolean | any | React.ReactElement | RechartsFunction; - data: any[]; - isAnimationActive?: boolean; - animationBegin?: number; - animationEasing?: AnimationEasingType; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface RadialBarData { + cx: number; + cy: number; + innerRadius: number; + outerRadius: number; + value: any; +} + +export interface RadialBarProps extends EventAttributes, Partial, Animatable { + className?: string; + dataKey: DataKey; // As the source code states, dataKey will replace valueKey in 1.1.0 and it'll be required (it's already required in current implementation). + angleAxisId?: string | number; + radiusAxisId?: string | number; + shape?: ContentRenderer | React.ReactElement; + activeShape?: object | ContentRenderer | React.ReactElement; + cornerRadius?: number | string; + minPointSize?: number; + maxBarSize?: number; + data?: RadialBarData[]; + legendType?: LegendType; + label?: boolean | React.ReactElement | Label['content'] | object; + background?: boolean | React.ReactElement | ContentRenderer | object; + hide?: boolean; } export class RadialBar extends React.Component { } -export interface RadialBarChartProps { - width?: number; - height?: number; - data?: any[]; - margin?: Margin; - barCategoryGap?: Percentage | number; - barGap?: number; - cx?: Percentage | number; - cy?: Percentage | number; - innerRadius?: Percentage | number; - outerRadius?: Percentage | number; - barSize?: number; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; - onClick?: RechartsFunction; +export interface RadialBarChartProps extends CategoricalChartWrapper<'radial'> { + startAngle?: number; + endAngle?: number; + cx?: string | number; + cy?: string | number; + innerRadius?: string | number; + outerRadius?: string | number; } export class RadialBarChart extends React.Component { } -export interface RectangleProps extends Partial { - x?: number; - y?: number; - radius?: number; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface RectangleProps extends EventAttributes, Partial, Animatable { + className?: string; + x?: number; + y?: number; + width?: number; + height?: number; + radius?: number | any[]; } export class Rectangle extends React.Component { } -export interface ReferenceAreaProps extends PartialAndNumber { - xAxisId?: string | number; - yAxisId?: string | number; - x1?: number | string; - x2?: number | string; - y1?: number | string; - y2?: number | string; - alwaysShow?: boolean; - viewBox?: ViewBox; - xAxis?: any; - yAxis?: any; - label?: string | number | React.ReactElement | ContentRenderer; - isFront?: boolean; +export interface ReferenceAreaProps extends Partial { + className?: number | string; + viewBox?: ViewBox; + xAxis?: object; + yAxis?: object; + isFront?: boolean; + alwaysShow?: boolean; + x1?: number | string; + x2?: number | string; + y1?: number | string; + y2?: number | string; + xAxisId?: string | number; + yAxisId?: string | number; + shape?: ContentRenderer | React.ReactElement; } export class ReferenceArea extends React.Component { } -export interface ReferenceDotProps { - xAxisId?: string | number; - yAxisId?: string | number; - x: number | string; - y: number | string; - r: number; - alwaysShow?: boolean; - xAxis: any; - yAxis: any; - label?: string | number | React.ReactElement | ContentRenderer; - isFront?: boolean; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface ReferenceDotProps extends EventAttributes, Partial> { + className?: number | string; + r?: number; + xAxis?: { scale: (x: ReferenceDotProps['x']) => number }; + yAxis?: { scale: (y: ReferenceDotProps['y']) => number }; + isFront?: boolean; + alwaysShow?: boolean; + x?: number | string; + y?: number | string; + xAxisId?: string | number; + yAxisId?: string | number; + shape?: ContentRenderer< + EventAttributes + & Partial> + & { cx: number; cy: number; } + > | React.ReactElement; } export class ReferenceDot extends React.Component { } -export interface ReferenceLineProps extends PartialAndNumber { - xAxisId?: string | number; - yAxisId?: string | number; - x?: number | string; - y?: number | string; - alwaysShow?: boolean; - viewBox?: ViewBox; - xAxis?: any; - yAxis?: any; - label?: string | number | React.ReactElement | ContentRenderer; - isFront?: boolean; +export interface ReferenceLineProps extends Partial> { + className?: number | string; + viewBox?: ViewBox; + xAxis?: object; + yAxis?: object; + isFront?: boolean; + alwaysShow?: boolean; + x?: number | string; + y?: number | string; + xAxisId?: string | number; + yAxisId?: string | number; + shape?: ContentRenderer< + EventAttributes + & Partial> + & { x1: number; y1: number; x2: number; y2: number; } + > | React.ReactElement; } export class ReferenceLine extends React.Component { } export interface ResponsiveContainerProps { - aspect?: number; - width?: Percentage | number; - height?: Percentage | number; - minWidth?: number; - minHeight?: number; - maxHeight?: Percentage | number; - debounce?: number; + aspect?: number; + width?: string | number; + height?: string | number; + minHeight?: string | number; + minWidth?: string | number; + maxHeight?: string | number; + children: React.ReactNode; + debounce?: number; + id?: string | number; } export class ResponsiveContainer extends React.Component { } -export interface ScatterProps extends Partial { - legendType?: LegendType; - xAxisId?: string | number; - yAxisId?: string | number; - zAxisId?: string | number; - line?: boolean | any | React.ReactElement | RechartsFunction; - shape?: 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | React.ReactElement | RechartsFunction; - lineType?: 'joint' | 'fitting'; - points: any[]; - isAnimationActive?: boolean; - animationBegin?: number; - animationEasing?: AnimationEasingType; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface ScatterPoint { + cx?: number; + cy?: number; + size?: number; + node?: { + x?: number | string; + y?: number | string; + z?: number | string; + }; + payload?: any; +} + +export interface ScatterProps extends EventAttributes, Partial, Animatable { + xAxisId?: string | number; + yAxisId?: string | number; + zAxisId?: string | number; + line?: boolean | object | RechartsFunction | React.ReactElement; + lineType?: 'joint' | 'fitting'; + lineJointType?: LineType; + legendType?: LegendType; + activeIndex?: number; + activeShape?: object | RechartsFunction | React.ReactElement; + shape?: 'circle' | 'cross' | 'diamond' | 'square' | 'star' | 'triangle' | 'wye' | React.ReactElement | ContentRenderer; + points?: ScatterPoint[]; + hide?: boolean; } export class Scatter extends React.Component { } -export interface ScatterChartProps { - width: number; - height: number; - margin?: Margin; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; -} +// NOTE: the lib's implementation doesn't inherits the event props (it's kept in this definition due to the previous typing definition has it). +export type ScatterChartProps = CategoricalChartWrapper & EventAttributes; export class ScatterChart extends React.Component { } -export interface SectorProps { - cx?: number; - cy?: number; - innerRadius?: number; - outerRadius?: number; - startAngle?: number; - endAngle?: number; - cornerRadius?: number; - fill?: string; - onClick?: RechartsFunction; - onMouseDown?: RechartsFunction; - onMouseUp?: RechartsFunction; - onMouseMove?: RechartsFunction; - onMouseOver?: RechartsFunction; - onMouseOut?: RechartsFunction; - onMouseEnter?: RechartsFunction; - onMouseLeave?: RechartsFunction; +export interface SectorProps extends EventAttributes, Partial { + className?: string; + cx?: number; + cy?: number; + innerRadius?: number; + outerRadius?: number; + startAngle?: number; + endAngle?: number; + cornerRadius?: number | string; } export class Sector extends React.Component { } -export interface TextProps extends Partial { - scaleToFit?: boolean; - angle?: number; - textAnchor?: 'start' | 'middle' | 'end' | 'inherit'; - verticalAnchor?: 'start' | 'middle' | 'end'; +export interface TextProps extends Partial { + scaleToFit?: boolean; + angle?: number; + textAnchor?: 'start' | 'middle' | 'end' | 'inherit'; + verticalAnchor?: 'start' | 'middle' | 'end'; + style?: object; } export class Text extends React.Component { } export interface ViewBox { - x?: number; - y?: number; - width?: number; - height?: number; + x?: number; + y?: number; + width?: number; + height?: number; } + export interface PolarViewBox { - cx?: number; - cy?: number; - innerRadius?: number; - outerRadius?: number; - startAngle?: number; - endAngle?: number; + cx?: number; + cy?: number; + innerRadius?: number; + outerRadius?: number; + startAngle?: number; + endAngle?: number; } + export interface Coordinate { - x: number; - y: number; + x: number; + y: number; } + export interface TooltipPayload { - name: string; - value: string | number | Array; - unit: string; + name: string; + value: string | number | Array; + unit: string; } -export interface TooltipProps { - separator?: string; - offset?: number; - itemStyle?: any; - wrapperStyle?: any; - labelStyle?: any; - cursor?: boolean | any | React.ReactElement | React.StatelessComponent; - viewBox?: ViewBox; - active?: boolean; - coordinate?: Coordinate; - payload?: TooltipPayload[]; - label?: string | number; - content?: React.ReactElement | React.StatelessComponent | ContentRenderer; - formatter?: TooltipFormatter; - labelFormatter?: LabelFormatter; - itemSorter?: ItemSorter; - isAnimationActive?: boolean; - animationBegin?: number; - animationEasing?: AnimationEasingType; - filterNull?: boolean; + +export interface TooltipProps extends Animatable { + content?: React.ReactElement | React.StatelessComponent | ContentRenderer; + viewBox?: ViewBox; + active?: boolean; + separator?: string; + formatter?: TooltipFormatter; + offset?: number; + itemStyle?: object; + labelStyle?: object; + wrapperStyle?: object; + cursor?: boolean | object | React.ReactElement | React.StatelessComponent; + coordinate?: Coordinate; + position?: Coordinate; + label?: any; + payload?: TooltipPayload[]; + itemSorter?: ItemSorter; + filterNull?: boolean; } export class Tooltip extends React.Component { } -export interface TreemapProps { - data: any[]; - width?: number; - height?: number; - dataKey?: string; - aspectRatio: number; - isAnimationActive?: boolean; - animationBegin?: number; - animationEasing?: AnimationEasingType; -} - -export interface Label { - viewBox?: ViewBox | PolarViewBox; - formatter?: LabelFormatter; - value: string | number; - position?: PositionType; - offset?: number; - content?: React.ReactElement | ContentRenderer

{INLINE_STYLES.map(type => , document.getElementById('target') ); + +const editorState = EditorState.createEmpty(); +const contentState = editorState.getCurrentContent(); +const rawContentState: RawDraftContentState = convertToRaw(contentState); + +rawContentState.blocks.forEach((block: RawDraftContentBlock) => { + block.entityRanges.forEach((entityRange: RawDraftEntityRange) => { + const { key, offset, length } = entityRange; + const entity: RawDraftEntity = rawContentState.entityMap[key]; + const entityType: DraftEntityType = entity.type; + const entityMutability: DraftEntityMutability = entity.mutability; + console.log(entityType, entityMutability, offset, length); + }); + + block.inlineStyleRanges.forEach((inlineStyleRange: RawDraftInlineStyleRange) => { + const { offset, length } = inlineStyleRange + const inlineStyle: DraftInlineStyleType = inlineStyleRange.style; + console.log(inlineStyle, offset, length); + }); +}); diff --git a/types/draft-js/index.d.ts b/types/draft-js/index.d.ts index 088d083a7f..0897fb72f9 100644 --- a/types/draft-js/index.d.ts +++ b/types/draft-js/index.d.ts @@ -260,9 +260,10 @@ declare namespace Draft { * or block types. */ "bold" | - "italic" | - "underline" | "code" | + "italic" | + "strikethrough" | + "underline" | /** * Split a block in two. @@ -326,6 +327,60 @@ declare namespace Draft { * another fragment or if the selected fragment shall be replaced */ type DraftInsertionType = "replace" | "before" | "after"; + + /** + * Valid inline styles. + */ + type DraftInlineStyleType = ( + "BOLD" | + "CODE" | + "ITALIC" | + "STRIKETHROUGH" | + "UNDERLINE" + ) + + /** + * Default entity types. + */ + type ComposedEntityType = ( + "LINK" | + "TOKEN" | + "PHOTO" | + "IMAGE" + ) + + /** + * Possible entity types. + */ + type DraftEntityType = string | ComposedEntityType; + + /** + * Possible "mutability" options for an entity. This refers to the behavior + * that should occur when inserting or removing characters in a text range + * with an entity applied to it. + * + * `MUTABLE`: + * The text range can be modified freely. Generally used in cases where + * the text content and the entity do not necessarily have a direct + * relationship. For instance, the text and URI for a link may be completely + * different. The user is allowed to edit the text as needed, and the entity + * is preserved and applied to any characters added within the range. + * + * `IMMUTABLE`: + * Not to be confused with immutable data structures used to represent the + * state of the editor. Immutable entity ranges cannot be modified in any + * way. Adding characters within the range will remove the entity from the + * entire range. Deleting characters will delete the entire range. Example: + * Facebook Page mentions. + * + * `SEGMENTED`: + * Segmented entities allow the removal of partial ranges of text, as + * separated by a delimiter. Adding characters wihin the range will remove + * the entity from the entire range. Deleting characters within a segmented + * entity will delete only the segments affected by the deletion. Example: + * Facebook User mentions. + */ + type DraftEntityMutability = "MUTABLE" | "IMMUTABLE" | "SEGMENTED"; } namespace Decorators { @@ -406,14 +461,24 @@ declare namespace Draft { } namespace Encoding { + import DraftInlineStyleType = Draft.Model.Constants.DraftInlineStyleType; + import DraftBlockType = Draft.Model.Constants.DraftBlockType; + import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; + import DraftEntityType = Draft.Model.Constants.DraftEntityType; + import ContentBlock = Draft.Model.ImmutableData.ContentBlock; import ContentState = Draft.Model.ImmutableData.ContentState; import DraftBlockRenderMap = Draft.Component.Base.DraftBlockRenderMap; - import DraftBlockType = Draft.Model.Constants.DraftBlockType; - import DraftEntityType = Draft.Model.Entity.DraftEntityType; - import DraftEntityMutability = Draft.Model.Entity.DraftEntityMutability; + /** + * A plain object representation of an inline style range. + */ + interface RawDraftInlineStyleRange { + style: DraftInlineStyleType; + offset: number; + length: number; + } /** * A plain object representation of an entity attribution. @@ -421,21 +486,12 @@ declare namespace Draft { * The `key` value corresponds to the key of the entity in the `entityMap` of * a `ComposedText` object, not for use with `DraftEntity.get()`. */ - interface EntityRange { + interface RawDraftEntityRange { key: number, offset: number, length: number, } - /** - * A plain object representation of an inline style range. - */ - interface InlineStyleRange { - style: string; - offset: number; - length: number; - } - /** * A plain object representation of an EntityInstance. */ @@ -454,8 +510,8 @@ declare namespace Draft { type: DraftBlockType; text: string; depth: number; - inlineStyleRanges: Array; - entityRanges: Array; + inlineStyleRanges: Array; + entityRanges: Array; data?: Object; } @@ -479,36 +535,8 @@ declare namespace Draft { } namespace Entity { - type ComposedEntityType = "LINK" | "TOKEN" | "PHOTO"; - type DraftEntityType = string | ComposedEntityType; - - /** - * An enum representing the possible "mutability" options for an entity. - * This refers to the behavior that should occur when inserting or removing - * characters in a text range with an entity applied to it. - * - * `MUTABLE`: - * The text range can be modified freely. Generally used in cases where - * the text content and the entity do not necessarily have a direct - * relationship. For instance, the text and URI for a link may be completely - * different. The user is allowed to edit the text as needed, and the entity - * is preserved and applied to any characters added within the range. - * - * `IMMUTABLE`: - * Not to be confused with immutable data structures used to represent the - * state of the editor. Immutable entity ranges cannot be modified in any - * way. Adding characters within the range will remove the entity from the - * entire range. Deleting characters will delete the entire range. Example: - * Facebook Page mentions. - * - * `SEGMENTED`: - * Segmented entities allow the removal of partial ranges of text, as - * separated by a delimiter. Adding characters wihin the range will remove - * the entity from the entire range. Deleting characters within a segmented - * entity will delete only the segments affected by the deletion. Example: - * Facebook User mentions. - */ - type DraftEntityMutability = "MUTABLE" | "IMMUTABLE" | "SEGMENTED"; + import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; + import DraftEntityType = Draft.Model.Constants.DraftEntityType; /** * A "document entity" is an object containing metadata associated with a @@ -577,10 +605,10 @@ declare namespace Draft { namespace ImmutableData { import DraftBlockType = Draft.Model.Constants.DraftBlockType; - import DraftDecoratorType = Draft.Model.Decorators.DraftDecoratorType; + import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; + import DraftEntityType = Draft.Model.Constants.DraftEntityType; - import DraftEntityType = Draft.Model.Entity.DraftEntityType; - import DraftEntityMutability = Draft.Model.Entity.DraftEntityMutability; + import DraftDecoratorType = Draft.Model.Decorators.DraftDecoratorType; type DraftInlineStyle = Immutable.OrderedSet; type BlockMap = Immutable.OrderedMap; @@ -936,6 +964,10 @@ import RichUtils = Draft.Model.Modifier.RichTextEditorUtil; import DefaultDraftBlockRenderMap = Draft.Model.ImmutableData.DefaultDraftBlockRenderMap; import DefaultDraftInlineStyle = Draft.Model.ImmutableData.DefaultDraftInlineStyle; +import RawDraftInlineStyleRange = Draft.Model.Encoding.RawDraftInlineStyleRange; +import RawDraftEntityRange = Draft.Model.Encoding.RawDraftEntityRange; +import RawDraftEntity = Draft.Model.Encoding.RawDraftEntity; +import RawDraftContentBlock = Draft.Model.Encoding.RawDraftContentBlock; import RawDraftContentState = Draft.Model.Encoding.RawDraftContentState; import convertFromRaw = Draft.Model.Encoding.convertFromRawToDraftState; import convertToRaw = Draft.Model.Encoding.convertFromDraftStateToRaw; @@ -948,6 +980,9 @@ import getVisibleSelectionRect = Draft.Component.Selection.getVisibleSelectionRe import DraftEditorCommand = Draft.Model.Constants.DraftEditorCommand; import DraftDragType = Draft.Model.Constants.DraftDragType; import DraftBlockType = Draft.Model.Constants.DraftBlockType; +import DraftInlineStyleType = Draft.Model.Constants.DraftInlineStyleType; +import DraftEntityMutability = Draft.Model.Constants.DraftEntityMutability; +import DraftEntityType = Draft.Model.Constants.DraftEntityType; import DraftRemovalDirection = Draft.Model.Constants.DraftRemovalDirection; import DraftHandleValue = Draft.Model.Constants.DraftHandleValue; import DraftInsertionType = Draft.Model.Constants.DraftInsertionType; @@ -977,6 +1012,10 @@ export { DefaultDraftBlockRenderMap, DefaultDraftInlineStyle, + RawDraftInlineStyleRange, + RawDraftEntityRange, + RawDraftEntity, + RawDraftContentBlock, RawDraftContentState, convertFromRaw, convertToRaw, @@ -989,6 +1028,9 @@ export { DraftEditorCommand, DraftDragType, DraftBlockType, + DraftInlineStyleType, + DraftEntityType, + DraftEntityMutability, DraftRemovalDirection, DraftHandleValue, DraftInsertionType, From 80ba4dd2650bb3c841c3123ee9f49f345c29f6b4 Mon Sep 17 00:00:00 2001 From: Kewei Li Date: Fri, 10 Nov 2017 16:21:08 -0800 Subject: [PATCH 006/201] forgot a static method --- types/winrt-uwp/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/winrt-uwp/index.d.ts b/types/winrt-uwp/index.d.ts index 348ca65c55..2e1eb9391d 100644 --- a/types/winrt-uwp/index.d.ts +++ b/types/winrt-uwp/index.d.ts @@ -49396,7 +49396,7 @@ declare namespace Windows { * @param parametersAsJson A JSON-formatted string that contains the arguments to pass to the request. * @return An asynchronous operation that, on successful completion, returns a StoreSendRequestResult object that provides status and error info about the request. */ - sendRequestAsync(context: StoreContext, requestKind: number, parametersAsJson: string): Windows.Foundation.IPromiseWithIAsyncOperation; + static sendRequestAsync(context: StoreContext, requestKind: number, parametersAsJson: string): Windows.Foundation.IPromiseWithIAsyncOperation; } /** Provides response data for a request that is sent to the Windows Store. */ From effa795f85687dc303b3787b32e65f447dd938f1 Mon Sep 17 00:00:00 2001 From: Kewei Li Date: Fri, 10 Nov 2017 16:46:38 -0800 Subject: [PATCH 007/201] making IPromise compatible with ES6 PromiseLike --- types/winrt-uwp/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/winrt-uwp/index.d.ts b/types/winrt-uwp/index.d.ts index 2e1eb9391d..6e0a460e33 100644 --- a/types/winrt-uwp/index.d.ts +++ b/types/winrt-uwp/index.d.ts @@ -20,7 +20,7 @@ declare namespace Windows { } declare namespace Windows.Foundation { - interface IPromise { + interface IPromise extends PromiseLike { then(success?: (value: TResult) => IPromise, error?: (error: any) => IPromise, progress?: (progress: any) => void): IPromise; then(success?: (value: TResult) => IPromise, error?: (error: any) => U, progress?: (progress: any) => void): IPromise; then(success?: (value: TResult) => U, error?: (error: any) => IPromise, progress?: (progress: any) => void): IPromise; From 49f2d7ce15bcbda133440a1687569a80328aa44f Mon Sep 17 00:00:00 2001 From: AJ Richardson Date: Sat, 11 Nov 2017 21:18:26 -0500 Subject: [PATCH 008/201] Trying to make strictFunctionTypes work (#21206). Wrapper assignability is fixed, but tests are failing due to GC error. --- types/lodash/index.d.ts | 12 ++++++++---- types/lodash/tsconfig.json | 2 +- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/types/lodash/index.d.ts b/types/lodash/index.d.ts index f038846d22..fafa7f6b5c 100644 --- a/types/lodash/index.d.ts +++ b/types/lodash/index.d.ts @@ -10723,7 +10723,7 @@ declare namespace _ { /** * @see _.toArray */ - toArray(): LoDashImplicitWrapper>; + //toArray(): LoDashImplicitWrapper>; } interface LoDashExplicitWrapper { @@ -10735,7 +10735,7 @@ declare namespace _ { /** * @see _.toArray */ - toArray(): LoDashExplicitWrapper>; + //toArray(): LoDashExplicitWrapper>; } //_.toPlainObject @@ -16078,14 +16078,18 @@ declare namespace _ { /** * @see _.constant */ - constant(): LoDashImplicitWrapper<() => TValue>; + constant(this: LoDashImplicitWrapper): LoDashImplicitWrapper<() => T>; + // Note: we can't use TValue here because of an issue with dtslint. Using T as a workaround; change back to TValue once dtsLint is working. + // constant(): LoDashImplicitWrapper<() => TValue>; } interface LoDashExplicitWrapper { /** * @see _.constant */ - constant(): LoDashExplicitWrapper<() => TValue>; + constant(this: LoDashExplicitWrapper): LoDashExplicitWrapper<() => T>; + // Note: we can't use TValue here because of an issue with dtslint. Using T as a workaround; change back to TValue once dtsLint is working. + // constant(): LoDashExplicitWrapper<() => TValue>; } //_.defaultTo diff --git a/types/lodash/tsconfig.json b/types/lodash/tsconfig.json index 2c4aa57c54..8bd56c0b87 100644 --- a/types/lodash/tsconfig.json +++ b/types/lodash/tsconfig.json @@ -7,7 +7,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, - "strictFunctionTypes": false, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" From fb8ae6d498cddca68ffc5191a9483eb3c1e355cf Mon Sep 17 00:00:00 2001 From: segayuu Date: Mon, 13 Nov 2017 11:44:26 +0900 Subject: [PATCH 009/201] Activate unnecessarily disabled Rules --- types/js-yaml/tslint.json | 64 +-------------------------------------- 1 file changed, 1 insertion(+), 63 deletions(-) diff --git a/types/js-yaml/tslint.json b/types/js-yaml/tslint.json index a41bf5d19a..1aa46ce6dd 100644 --- a/types/js-yaml/tslint.json +++ b/types/js-yaml/tslint.json @@ -1,79 +1,17 @@ { "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 + "trim-file": false } } From 7d82d7faa0b89a85376cf5286f4879c080cff8d1 Mon Sep 17 00:00:00 2001 From: segayuu Date: Mon, 13 Nov 2017 11:48:19 +0900 Subject: [PATCH 010/201] Activate ignore lint error(not default): max-lile-length --- types/js-yaml/tslint.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/js-yaml/tslint.json b/types/js-yaml/tslint.json index 1aa46ce6dd..a9925ae946 100644 --- a/types/js-yaml/tslint.json +++ b/types/js-yaml/tslint.json @@ -4,7 +4,7 @@ "ban-types": false, "dt-header": false, "export-just-namespace": false, - "max-line-length": false, + "max-line-length": [true, 240], "member-access": false, "no-consecutive-blank-lines": false, "no-empty-interface": false, From 4d4b4c5c083968e49b430561c7ef74fb68ac2b95 Mon Sep 17 00:00:00 2001 From: segayuu Date: Mon, 13 Nov 2017 11:50:10 +0900 Subject: [PATCH 011/201] cleanup ignore lint errors: no-consecutive-blank-lines, trim-file --- types/js-yaml/js-yaml-tests.ts | 2 -- types/js-yaml/tslint.json | 4 +--- 2 files changed, 1 insertion(+), 5 deletions(-) diff --git a/types/js-yaml/js-yaml-tests.ts b/types/js-yaml/js-yaml-tests.ts index aff53acd3c..3a9a8b8d68 100644 --- a/types/js-yaml/js-yaml-tests.ts +++ b/types/js-yaml/js-yaml-tests.ts @@ -1,5 +1,3 @@ - - import yaml = require('js-yaml'); import LoadOptions = yaml.LoadOptions; import DumpOptions = yaml.DumpOptions; diff --git a/types/js-yaml/tslint.json b/types/js-yaml/tslint.json index a9925ae946..1c982d31bf 100644 --- a/types/js-yaml/tslint.json +++ b/types/js-yaml/tslint.json @@ -6,12 +6,10 @@ "export-just-namespace": false, "max-line-length": [true, 240], "member-access": false, - "no-consecutive-blank-lines": false, "no-empty-interface": false, "no-unnecessary-class": false, "no-var-keyword": false, "prefer-const": false, - "strict-export-declare-modifiers": false, - "trim-file": false + "strict-export-declare-modifiers": false } } From 42f80db4cbf64c77f753ff4d8080eb71f5181140 Mon Sep 17 00:00:00 2001 From: segayuu Date: Mon, 13 Nov 2017 11:52:43 +0900 Subject: [PATCH 012/201] cleanup ignore lint error: no-var-keyword --- types/js-yaml/index.d.ts | 14 +++++++------- types/js-yaml/js-yaml-tests.ts | 22 +++++++++++----------- types/js-yaml/tslint.json | 1 - 3 files changed, 18 insertions(+), 19 deletions(-) diff --git a/types/js-yaml/index.d.ts b/types/js-yaml/index.d.ts index 8f7c0a346d..77212bea02 100644 --- a/types/js-yaml/index.d.ts +++ b/types/js-yaml/index.d.ts @@ -74,17 +74,17 @@ declare namespace jsyaml { } // only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 - export var FAILSAFE_SCHEMA: any; + export let FAILSAFE_SCHEMA: any; // only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 - export var JSON_SCHEMA: any; + export let JSON_SCHEMA: any; // same as JSON_SCHEMA: http://www.yaml.org/spec/1.2/spec.html#id2804923 - export var CORE_SCHEMA: any; + export let CORE_SCHEMA: any; // all supported YAML types, without unsafe ones (!!js/undefined, !!js/regexp and !!js/function): http://yaml.org/type/ - export var DEFAULT_SAFE_SCHEMA: any; + export let DEFAULT_SAFE_SCHEMA: any; // all supported YAML types. - export var DEFAULT_FULL_SCHEMA: any; - export var MINIMAL_SCHEMA: any; - export var SAFE_SCHEMA: any; + export let DEFAULT_FULL_SCHEMA: any; + export let MINIMAL_SCHEMA: any; + export let SAFE_SCHEMA: any; export class YAMLException extends Error { constructor(reason?: any, mark?: any); diff --git a/types/js-yaml/js-yaml-tests.ts b/types/js-yaml/js-yaml-tests.ts index 3a9a8b8d68..b7014a0ba8 100644 --- a/types/js-yaml/js-yaml-tests.ts +++ b/types/js-yaml/js-yaml-tests.ts @@ -4,19 +4,19 @@ import DumpOptions = yaml.DumpOptions; import TypeConstructorOptions = yaml.TypeConstructorOptions; import SchemaDefinition = yaml.SchemaDefinition; -var bool: boolean; -var num: number; -var str: string; -var obj: Object; -var value: any; -var array: any[]; -var fn: Function; -var schemaDefinition: SchemaDefinition = { +let bool: boolean; +let num: number; +let str: string; +let obj: Object; +let value: any; +let array: any[]; +let fn: Function; +let schemaDefinition: SchemaDefinition = { implicit: array, explicit: array, include: array }; -var typeConstructorOptions: TypeConstructorOptions = { +let typeConstructorOptions: TypeConstructorOptions = { kind: str, resolve: fn, construct: fn, @@ -27,8 +27,8 @@ var typeConstructorOptions: TypeConstructorOptions = { styleAliases: obj }; -var loadOpts: LoadOptions; -var dumpOpts: DumpOptions; +let loadOpts: LoadOptions; +let dumpOpts: DumpOptions; // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- diff --git a/types/js-yaml/tslint.json b/types/js-yaml/tslint.json index 1c982d31bf..83911cae02 100644 --- a/types/js-yaml/tslint.json +++ b/types/js-yaml/tslint.json @@ -8,7 +8,6 @@ "member-access": false, "no-empty-interface": false, "no-unnecessary-class": false, - "no-var-keyword": false, "prefer-const": false, "strict-export-declare-modifiers": false } From acb66323ee8deb11105f9fd359eb2a5c397b769d Mon Sep 17 00:00:00 2001 From: segayuu Date: Mon, 13 Nov 2017 12:01:48 +0900 Subject: [PATCH 013/201] cleanup ignore lint error: dt-header --- types/js-yaml/index.d.ts | 2 +- types/js-yaml/tslint.json | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/types/js-yaml/index.d.ts b/types/js-yaml/index.d.ts index 77212bea02..d32d7eeeb7 100644 --- a/types/js-yaml/index.d.ts +++ b/types/js-yaml/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for js-yaml 3.9.1 +// Type definitions for js-yaml 3.9 // Project: https://github.com/nodeca/js-yaml // Definitions by: Bart van der Schoor , Sebastian Clausen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/js-yaml/tslint.json b/types/js-yaml/tslint.json index 83911cae02..11bb42dd95 100644 --- a/types/js-yaml/tslint.json +++ b/types/js-yaml/tslint.json @@ -2,7 +2,6 @@ "extends": "dtslint/dt.json", "rules": { "ban-types": false, - "dt-header": false, "export-just-namespace": false, "max-line-length": [true, 240], "member-access": false, From ba6f0675d130091d4c3b9e8c9c46dce80dc0f112 Mon Sep 17 00:00:00 2001 From: segayuu Date: Mon, 13 Nov 2017 13:14:24 +0900 Subject: [PATCH 014/201] cleanup ignore lint errors: export-just-namespace, strict-export-declare-modifiers --- types/js-yaml/index.d.ts | 171 ++++++++++++++++++-------------------- types/js-yaml/tslint.json | 4 +- 2 files changed, 84 insertions(+), 91 deletions(-) diff --git a/types/js-yaml/index.d.ts b/types/js-yaml/index.d.ts index d32d7eeeb7..a74857bbdf 100644 --- a/types/js-yaml/index.d.ts +++ b/types/js-yaml/index.d.ts @@ -3,94 +3,89 @@ // Definitions by: Bart van der Schoor , Sebastian Clausen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -declare namespace jsyaml { - export function safeLoad(str: string, opts?: LoadOptions): any; - export function load(str: string, opts?: LoadOptions): any; +export function safeLoad(str: string, opts?: LoadOptions): any; +export function load(str: string, opts?: LoadOptions): any; - export interface Type extends TypeConstructorOptions { } - export class Type { - constructor(tag: string, opts?: TypeConstructorOptions); - tag: string; - } - export class Schema { - constructor(definition: SchemaDefinition); - public static create(types: Type[] | Type): Schema; - public static create(schemas: Schema[] | Schema, types: Type[] | Type): Schema; - } - - export function safeLoadAll(str: string, iterator: (doc: any) => void, opts?: LoadOptions): any; - export function loadAll(str: string, iterator: (doc: any) => void, opts?: LoadOptions): any; - - export function safeDump(obj: any, opts?: DumpOptions): string; - export function dump(obj: any, opts?: DumpOptions): string; - - export interface LoadOptions { - // string to be used as a file path in error/warning messages. - filename?: string; - // makes the loader to throw errors instead of warnings. - strict?: boolean; - // specifies a schema to use. - schema?: any; - } - - export interface DumpOptions { - // indentation width to use (in spaces). - indent?: number; - // do not throw on invalid types (like function in the safe schema) and skip pairs and single values with such types. - skipInvalid?: boolean; - // specifies level of nesting, when to switch from block to flow style for collections. -1 means block style everwhere - flowLevel?: number; - // Each tag may have own set of styles. - "tag" => "style" map. - styles?: Object; - // specifies a schema to use. - schema?: any; - // if true, sort keys when dumping YAML. If a function, use the function to sort the keys. (default: false) - sortKeys?: boolean | ((a: any, b: any) => number); - // set max line width. (default: 80) - lineWidth?: number; - // if true, don't convert duplicate objects into references (default: false) - noRefs?: boolean; - // if true don't try to be compatible with older yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 (default: false) - noCompatMode?: boolean; - // if true flow sequences will be condensed, omitting the space between `key: value` or `a, b`. Eg. `'[a,b]'` or `{a:{b:c}}`. Can be useful when using yaml for pretty URL query params as spaces are %-encoded. (default: false) - condenseFlow?: boolean; - } - - export interface TypeConstructorOptions { - kind?: string; - resolve?: Function; - construct?: Function; - instanceOf?: Object; - predicate?: string; - represent?: Function; - defaultStyle?: string; - styleAliases?: Object; - } - - export interface SchemaDefinition { - implicit?: any[]; - explicit?: any[]; - include?: any[]; - } - - // only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 - export let FAILSAFE_SCHEMA: any; - // only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 - export let JSON_SCHEMA: any; - // same as JSON_SCHEMA: http://www.yaml.org/spec/1.2/spec.html#id2804923 - export let CORE_SCHEMA: any; - // all supported YAML types, without unsafe ones (!!js/undefined, !!js/regexp and !!js/function): http://yaml.org/type/ - export let DEFAULT_SAFE_SCHEMA: any; - // all supported YAML types. - export let DEFAULT_FULL_SCHEMA: any; - export let MINIMAL_SCHEMA: any; - export let SAFE_SCHEMA: any; - - export class YAMLException extends Error { - constructor(reason?: any, mark?: any); - toString(compact?: boolean): string; - } +export interface Type extends TypeConstructorOptions { } +export class Type { + constructor(tag: string, opts?: TypeConstructorOptions); + tag: string; +} +export class Schema { + constructor(definition: SchemaDefinition); + public static create(types: Type[] | Type): Schema; + public static create(schemas: Schema[] | Schema, types: Type[] | Type): Schema; } -export = jsyaml; -export as namespace jsyaml; +export function safeLoadAll(str: string, iterator: (doc: any) => void, opts?: LoadOptions): any; +export function loadAll(str: string, iterator: (doc: any) => void, opts?: LoadOptions): any; + +export function safeDump(obj: any, opts?: DumpOptions): string; +export function dump(obj: any, opts?: DumpOptions): string; + +export interface LoadOptions { + // string to be used as a file path in error/warning messages. + filename?: string; + // makes the loader to throw errors instead of warnings. + strict?: boolean; + // specifies a schema to use. + schema?: any; +} + +export interface DumpOptions { + // indentation width to use (in spaces). + indent?: number; + // do not throw on invalid types (like function in the safe schema) and skip pairs and single values with such types. + skipInvalid?: boolean; + // specifies level of nesting, when to switch from block to flow style for collections. -1 means block style everwhere + flowLevel?: number; + // Each tag may have own set of styles. - "tag" => "style" map. + styles?: Object; + // specifies a schema to use. + schema?: any; + // if true, sort keys when dumping YAML. If a function, use the function to sort the keys. (default: false) + sortKeys?: boolean | ((a: any, b: any) => number); + // set max line width. (default: 80) + lineWidth?: number; + // if true, don't convert duplicate objects into references (default: false) + noRefs?: boolean; + // if true don't try to be compatible with older yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 (default: false) + noCompatMode?: boolean; + // if true flow sequences will be condensed, omitting the space between `key: value` or `a, b`. Eg. `'[a,b]'` or `{a:{b:c}}`. Can be useful when using yaml for pretty URL query params as spaces are %-encoded. (default: false) + condenseFlow?: boolean; +} + +export interface TypeConstructorOptions { + kind?: string; + resolve?: Function; + construct?: Function; + instanceOf?: Object; + predicate?: string; + represent?: Function; + defaultStyle?: string; + styleAliases?: Object; +} + +export interface SchemaDefinition { + implicit?: any[]; + explicit?: any[]; + include?: any[]; +} + +// only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 +export let FAILSAFE_SCHEMA: any; +// only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 +export let JSON_SCHEMA: any; +// same as JSON_SCHEMA: http://www.yaml.org/spec/1.2/spec.html#id2804923 +export let CORE_SCHEMA: any; +// all supported YAML types, without unsafe ones (!!js/undefined, !!js/regexp and !!js/function): http://yaml.org/type/ +export let DEFAULT_SAFE_SCHEMA: any; +// all supported YAML types. +export let DEFAULT_FULL_SCHEMA: any; +export let MINIMAL_SCHEMA: any; +export let SAFE_SCHEMA: any; + +export class YAMLException extends Error { + constructor(reason?: any, mark?: any); + toString(compact?: boolean): string; +} diff --git a/types/js-yaml/tslint.json b/types/js-yaml/tslint.json index 11bb42dd95..7bc6a914d7 100644 --- a/types/js-yaml/tslint.json +++ b/types/js-yaml/tslint.json @@ -2,12 +2,10 @@ "extends": "dtslint/dt.json", "rules": { "ban-types": false, - "export-just-namespace": false, "max-line-length": [true, 240], "member-access": false, "no-empty-interface": false, "no-unnecessary-class": false, - "prefer-const": false, - "strict-export-declare-modifiers": false + "prefer-const": false } } From 5f72051df1b8e8e95e79d62c72933efb883984bb Mon Sep 17 00:00:00 2001 From: segayuu Date: Mon, 13 Nov 2017 13:29:01 +0900 Subject: [PATCH 015/201] cleanup ignore lint errors: member-access --- types/js-yaml/index.d.ts | 4 ++-- types/js-yaml/tslint.json | 1 - 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/types/js-yaml/index.d.ts b/types/js-yaml/index.d.ts index a74857bbdf..c2793bd8aa 100644 --- a/types/js-yaml/index.d.ts +++ b/types/js-yaml/index.d.ts @@ -13,8 +13,8 @@ export class Type { } export class Schema { constructor(definition: SchemaDefinition); - public static create(types: Type[] | Type): Schema; - public static create(schemas: Schema[] | Schema, types: Type[] | Type): Schema; + static create(types: Type[] | Type): Schema; + static create(schemas: Schema[] | Schema, types: Type[] | Type): Schema; } export function safeLoadAll(str: string, iterator: (doc: any) => void, opts?: LoadOptions): any; diff --git a/types/js-yaml/tslint.json b/types/js-yaml/tslint.json index 7bc6a914d7..4498d831ad 100644 --- a/types/js-yaml/tslint.json +++ b/types/js-yaml/tslint.json @@ -3,7 +3,6 @@ "rules": { "ban-types": false, "max-line-length": [true, 240], - "member-access": false, "no-empty-interface": false, "no-unnecessary-class": false, "prefer-const": false From 6699f716e73304e4d1f649def02c47d7dda8bd9c Mon Sep 17 00:00:00 2001 From: segayuu Date: Mon, 13 Nov 2017 14:01:31 +0900 Subject: [PATCH 016/201] cleanup lint error: ban-types --- types/js-yaml/index.d.ts | 17 +++++++++-------- types/js-yaml/js-yaml-tests.ts | 4 ++-- types/js-yaml/tslint.json | 1 - 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/types/js-yaml/index.d.ts b/types/js-yaml/index.d.ts index c2793bd8aa..c1fcfef107 100644 --- a/types/js-yaml/index.d.ts +++ b/types/js-yaml/index.d.ts @@ -2,14 +2,15 @@ // Project: https://github.com/nodeca/js-yaml // Definitions by: Bart van der Schoor , Sebastian Clausen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 export function safeLoad(str: string, opts?: LoadOptions): any; export function load(str: string, opts?: LoadOptions): any; export interface Type extends TypeConstructorOptions { } export class Type { - constructor(tag: string, opts?: TypeConstructorOptions); - tag: string; + constructor(tag: string, opts?: TypeConstructorOptions); + tag: string; } export class Schema { constructor(definition: SchemaDefinition); @@ -40,7 +41,7 @@ export interface DumpOptions { // specifies level of nesting, when to switch from block to flow style for collections. -1 means block style everwhere flowLevel?: number; // Each tag may have own set of styles. - "tag" => "style" map. - styles?: Object; + styles?: { [x: string]: any; }; // specifies a schema to use. schema?: any; // if true, sort keys when dumping YAML. If a function, use the function to sort the keys. (default: false) @@ -57,13 +58,13 @@ export interface DumpOptions { export interface TypeConstructorOptions { kind?: string; - resolve?: Function; - construct?: Function; - instanceOf?: Object; + resolve?: (data: any) => boolean; + construct?: (data: any) => any; + instanceOf?: object; predicate?: string; - represent?: Function; + represent?: ((data: object) => any) | { [x: string]: (data: object) => any }; defaultStyle?: string; - styleAliases?: Object; + styleAliases?: { [x: string]: any; }; } export interface SchemaDefinition { diff --git a/types/js-yaml/js-yaml-tests.ts b/types/js-yaml/js-yaml-tests.ts index b7014a0ba8..91229e487a 100644 --- a/types/js-yaml/js-yaml-tests.ts +++ b/types/js-yaml/js-yaml-tests.ts @@ -7,10 +7,10 @@ import SchemaDefinition = yaml.SchemaDefinition; let bool: boolean; let num: number; let str: string; -let obj: Object; +let obj: { [x: string]: any; }; let value: any; let array: any[]; -let fn: Function; +let fn: (...args: any[]) => any; let schemaDefinition: SchemaDefinition = { implicit: array, explicit: array, diff --git a/types/js-yaml/tslint.json b/types/js-yaml/tslint.json index 4498d831ad..e874572520 100644 --- a/types/js-yaml/tslint.json +++ b/types/js-yaml/tslint.json @@ -1,7 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "ban-types": false, "max-line-length": [true, 240], "no-empty-interface": false, "no-unnecessary-class": false, From a5e802d7d321609fa8af7e8b4b02178ee033f286 Mon Sep 17 00:00:00 2001 From: segayuu Date: Mon, 13 Nov 2017 14:08:13 +0900 Subject: [PATCH 017/201] cleanup ignore lint errors: no-empty-interface, no-unnecessary-class --- types/js-yaml/index.d.ts | 21 ++++++++++++--------- types/js-yaml/tslint.json | 2 -- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/types/js-yaml/index.d.ts b/types/js-yaml/index.d.ts index c1fcfef107..5529906deb 100644 --- a/types/js-yaml/index.d.ts +++ b/types/js-yaml/index.d.ts @@ -7,12 +7,15 @@ export function safeLoad(str: string, opts?: LoadOptions): any; export function load(str: string, opts?: LoadOptions): any; -export interface Type extends TypeConstructorOptions { } export class Type { constructor(tag: string, opts?: TypeConstructorOptions); tag: string; } -export class Schema { +/* tslint:disable-next-line:no-empty-interface */ +export interface Type extends TypeConstructorOptions { } + +/* tslint:disable-next-line:no-unnecessary-class */ +export class Schema implements SchemaDefinition { constructor(definition: SchemaDefinition); static create(types: Type[] | Type): Schema; static create(schemas: Schema[] | Schema, types: Type[] | Type): Schema; @@ -74,17 +77,17 @@ export interface SchemaDefinition { } // only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 -export let FAILSAFE_SCHEMA: any; +export let FAILSAFE_SCHEMA: Schema; // only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 -export let JSON_SCHEMA: any; +export let JSON_SCHEMA: Schema; // same as JSON_SCHEMA: http://www.yaml.org/spec/1.2/spec.html#id2804923 -export let CORE_SCHEMA: any; +export let CORE_SCHEMA: Schema; // all supported YAML types, without unsafe ones (!!js/undefined, !!js/regexp and !!js/function): http://yaml.org/type/ -export let DEFAULT_SAFE_SCHEMA: any; +export let DEFAULT_SAFE_SCHEMA: Schema; // all supported YAML types. -export let DEFAULT_FULL_SCHEMA: any; -export let MINIMAL_SCHEMA: any; -export let SAFE_SCHEMA: any; +export let DEFAULT_FULL_SCHEMA: Schema; +export let MINIMAL_SCHEMA: Schema; +export let SAFE_SCHEMA: Schema; export class YAMLException extends Error { constructor(reason?: any, mark?: any); diff --git a/types/js-yaml/tslint.json b/types/js-yaml/tslint.json index e874572520..90f22f083b 100644 --- a/types/js-yaml/tslint.json +++ b/types/js-yaml/tslint.json @@ -2,8 +2,6 @@ "extends": "dtslint/dt.json", "rules": { "max-line-length": [true, 240], - "no-empty-interface": false, - "no-unnecessary-class": false, "prefer-const": false } } From 5fb500e9bcae139156b7ec0e56add5465fef30bc Mon Sep 17 00:00:00 2001 From: segayuu Date: Mon, 13 Nov 2017 14:11:35 +0900 Subject: [PATCH 018/201] cleanup lint error: max-line-length(240->default) --- types/js-yaml/index.d.ts | 3 ++- types/js-yaml/tslint.json | 1 - 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/types/js-yaml/index.d.ts b/types/js-yaml/index.d.ts index 5529906deb..98354d26ba 100644 --- a/types/js-yaml/index.d.ts +++ b/types/js-yaml/index.d.ts @@ -55,7 +55,8 @@ export interface DumpOptions { noRefs?: boolean; // if true don't try to be compatible with older yaml versions. Currently: don't quote "yes", "no" and so on, as required for YAML 1.1 (default: false) noCompatMode?: boolean; - // if true flow sequences will be condensed, omitting the space between `key: value` or `a, b`. Eg. `'[a,b]'` or `{a:{b:c}}`. Can be useful when using yaml for pretty URL query params as spaces are %-encoded. (default: false) + // if true flow sequences will be condensed, omitting the space between `key: value` or `a, b`. Eg. `'[a,b]'` or `{a:{b:c}}`. + // Can be useful when using yaml for pretty URL query params as spaces are %-encoded. (default: false) condenseFlow?: boolean; } diff --git a/types/js-yaml/tslint.json b/types/js-yaml/tslint.json index 90f22f083b..a6a9bab5f0 100644 --- a/types/js-yaml/tslint.json +++ b/types/js-yaml/tslint.json @@ -1,7 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "max-line-length": [true, 240], "prefer-const": false } } From 886cf03960f125e6248f8fbf093f5e10c8311b96 Mon Sep 17 00:00:00 2001 From: Manduro Date: Mon, 13 Nov 2017 09:53:53 +0100 Subject: [PATCH 019/201] mixpanel: 2.14 with new method --- types/mixpanel/index.d.ts | 17 ++++++++++++++++- types/mixpanel/mixpanel-tests.ts | 5 +++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/types/mixpanel/index.d.ts b/types/mixpanel/index.d.ts index 4964a55c79..08bbe26720 100644 --- a/types/mixpanel/index.d.ts +++ b/types/mixpanel/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mixpanel 2.13 +// Type definitions for Mixpanel 2.14 // Project: https://mixpanel.com/ // https://github.com/mixpanel/mixpanel-js // Definitions by: Knut Eirik Leira Hjelle @@ -348,6 +348,21 @@ declare namespace Mixpanel { set_once(prop: string, value: any, callback?: () => void): void; set_once(keys: { [index: string]: any }, callback?: () => void): void; + /** + * Unset properties on a user record (permanently removes the properties and their values from a profile). + * + * ### Usage: + * + * mixpanel.people.unset('gender'); + * + * // or unset multiple properties at once + * mixpanel.people.unset(['gender', 'Company']); + * + * @param prop If a string, this is the name of the property. If an array, this is a list of property names. + * @param callback If provided, the callback will be called after the tracking event + */ + unset(prop: string | string[], callback?: () => void): void; + /** * Increment/decrement numeric people analytics properties. * diff --git a/types/mixpanel/mixpanel-tests.ts b/types/mixpanel/mixpanel-tests.ts index b1d735c22e..a48cd4065a 100644 --- a/types/mixpanel/mixpanel-tests.ts +++ b/types/mixpanel/mixpanel-tests.ts @@ -95,6 +95,11 @@ function mixpanel_people() { 'Starting Plan': 'Premium' }, () => {}); + mixpanel.people.unset('Company'); + mixpanel.people.unset('Company', () => {}); + mixpanel.people.unset(['Company', 'Plan']); + mixpanel.people.unset(['Company', 'Plan'], () => {}); + mixpanel.people.increment('page_views'); mixpanel.people.increment('page_views', 1); mixpanel.people.increment('credits_left', -1); From b41cd804d86518060d6878411a6b8266baa4f191 Mon Sep 17 00:00:00 2001 From: Aleksey Levenstein Date: Mon, 13 Nov 2017 11:25:10 +0200 Subject: [PATCH 020/201] ace: added new Document's methods + added deprecation tag for old --- types/ace/index.d.ts | 66 ++++++++++++++++++++++++++++++++++---------- 1 file changed, 51 insertions(+), 15 deletions(-) diff --git a/types/ace/index.d.ts b/types/ace/index.d.ts index 456727756c..822c394a32 100644 --- a/types/ace/index.d.ts +++ b/types/ace/index.d.ts @@ -345,18 +345,47 @@ declare namespace AceAjax { insert(position: Position, text: string): any; /** - * Inserts the elements in `lines` into the document, starting at the row index given by `row`. This method also triggers the `'change'` event. - * @param row The index of the row to insert at - * @param lines An array of strings - **/ + * @deprecated Use the insertFullLines method instead. + */ insertLines(row: number, lines: string[]): any; /** - * Inserts a new line into the document at the current row's `position`. This method also triggers the `'change'` event. - * @param position The position to insert at - **/ + * Inserts the elements in `lines` into the document as full lines (does not merge with existing line), starting at the row index given by `row`. This method also triggers the `"change"` event. + * @param {Number} row The index of the row to insert at + * @param {Array} lines An array of strings + * @returns {Object} Contains the final row and column, like this: + * ``` + * {row: endRow, column: 0} + * ``` + * If `lines` is empty, this function returns an object containing the current row, and column, like this: + * ``` + * {row: row, column: 0} + * ``` + * + **/ + insertFullLines(row: number, lines: string[]): any; + + /** + * @deprecated Use insertMergedLines(position, ['', '']) instead. + */ insertNewLine(position: Position): any; + /** + * Inserts the elements in `lines` into the document, starting at the position index given by `row`. This method also triggers the `"change"` event. + * @param {Number} row The index of the row to insert at + * @param {Array} lines An array of strings + * @returns {Object} Contains the final row and column, like this: + * ``` + * {row: endRow, column: 0} + * ``` + * If `lines` is empty, this function returns an object containing the current row, and column, like this: + * ``` + * {row: row, column: 0} + * ``` + * + **/ + insertMergedLines(row: number, lines: string[]): any; + /** * Inserts `text` into the `position` at the current row. This method also triggers the `'change'` event. * @param position The position to insert at @@ -379,12 +408,19 @@ declare namespace AceAjax { removeInLine(row: number, startColumn: number, endColumn: number): any; /** - * Removes a range of full lines. This method also triggers the `'change'` event. - * @param firstRow The first row to be removed - * @param lastRow The last row to be removed - **/ + * @deprecated Use the removeFullLines method instead. + */ removeLines(firstRow: number, lastRow: number): string[]; + /** + * Removes a range of full lines. This method also triggers the `"change"` event. + * @param {Number} firstRow The first row to be removed + * @param {Number} lastRow The last row to be removed + * @returns {[String]} Returns all the removed lines. + * + **/ + removeFullLines(firstRow: number, lastRow: number): string[]; + /** * Removes the new line between `row` and the row immediately following it. This method also triggers the `'change'` event. * @param row The row to check @@ -474,9 +510,9 @@ declare namespace AceAjax { removeFold(arg: any): void; expandFold(arg: any): void; - + foldAll(startRow?: number, endRow?: number, depth?: number): void - + unfold(arg1: any, arg2: boolean): void; screenToDocumentColumn(row: number, column: number): void; @@ -2659,9 +2695,9 @@ declare namespace AceAjax { characterWidth: number; lineHeight: number; - + setScrollMargin(top:number, bottom:number, left: number, right: number): void; - + screenToTextCoordinates(left: number, top: number): void; /** From 17514234313c5163369e7e40c53250f24acfc311 Mon Sep 17 00:00:00 2001 From: Knut Huehne and Richard Sylvester Date: Mon, 13 Nov 2017 11:27:44 +0100 Subject: [PATCH 021/201] Update AmGraph documentation - these changes add all properties defined at https://docs.amcharts.com/3/javascriptcharts/AmGraph - the documentation was scraped and then manually cleaned --- types/amcharts/index.d.ts | 253 +++++++++++++++++++++++++++++++------- 1 file changed, 208 insertions(+), 45 deletions(-) diff --git a/types/amcharts/index.d.ts b/types/amcharts/index.d.ts index 85abd11f5c..0dae492a76 100644 --- a/types/amcharts/index.d.ts +++ b/types/amcharts/index.d.ts @@ -2191,27 +2191,45 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val chart.addGraph(graph); */ class AmGraph { + /** Text which screen readers will read if user rolls-over the bullet/column or sets focus using tab key (this is possible only if tabIndex property of AmGraph is set to some number). Text is added as aria-label tag. Note - not all screen readers and browsers support this. + @default "[[title]] [[category]] [[value]]" + */ + accessibleLabel: string; /** Name of the alpha field in your dataProvider. */ alphaField: string; + /** If you set this to true before chart is drawn, the animation of this graph won't be played. + @default false + */ + animationPlayed: boolean; + /** Allows customizing graphs balloons individually (only when ChartCursor is used). Note: the balloon object is not created automatically, you should create it before setting properties */ + balloon: AmBalloon; /** Value balloon color. Will use graph or data item color if not set. */ balloonColor: string; - /** If you set some function, the graph will call it and pass GraphDataItem and AmGraph object to it. This function should return a string which will be displayed in a balloon. */ + /** If you set some function, the graph will call it and pass GraphDataItem and AmGraph objects to it. This function should return a string which will be displayed in a balloon. */ balloonFunction(graphDataItem: GraphDataItem, amGraph: AmGraph): string; - /** Balloon text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]] [[value]] */ + /** Balloon text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]] or any other field name from your data provider. HTML tags can also be used. + @default [[value]] + */ balloonText: string; - /** Specifies if the line graph should be placed behind column graphs */ + /** Specifies if the line graph should be placed behind column graphs + @default false + */ behindColumns: boolean; - /** Type of the bullets. Possible values are: "none", "round", "square", "triangleUp", "triangleDown", "bubble", "custom". none */ + /** Type of the bullets. Possible values are: "none", "round", "square", "triangleUp", "triangleDown", "triangleLeft", "triangleRight", "bubble", "diamond", "xError", "yError" and "custom". + @default "none" + */ bullet: string; /** Opacity of bullets. Value range is 0 - 1. @default 1 */ bulletAlpha: number; + /** bulletAxis value is used when you are building error chart. Error chart is a regular serial or XY chart with bullet type set to "xError" or "yError". The graph should know which axis should be used to determine the size of this bullet - that's when bulletAxis should be set. Besides that, you should also set graph.errorField. You can also use other bullet types with this feature too. For example, if you set bulletAxis for XY chart, the size of a bullet will change as you zoom the chart. */ + bulletAxis: ValueAxis; /** Bullet border opacity. - @default 1 + @default 0 */ bulletBorderAlpha: number; - /** Bullet border color. Will use lineColor if not set. */ + /** Bullet border color. Will use lineColor if not set. */ bulletBorderColor: string; /** Bullet border thickness. @default 2 @@ -2221,7 +2239,11 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val bulletColor: string; /** Name of the bullet field in your dataProvider. */ bulletField: string; - /** Bullet offset. Distance from the actual data point to the bullet. Can be used to place custom bullets above the columns. */ + /** Useful for touch devices - if you set it to 20 or so, the bullets of a graph will have invisible circle around the actual bullet (bullets should still be enabled), which will be easier to touch (bullets usually are smaller and hard to hit). */ + bulletHitAreaSize: number; + /** Bullet offset. Distance from the actual data point to the bullet. Can be used to place custom bullets above the columns. + @default 0 + */ bulletOffset: number; /** Bullet size. @default 8 @@ -2229,17 +2251,31 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val bulletSize: number; /** Name of the bullet size field in your dataProvider. */ bulletSizeField: string; + /** If this field is set and addClassNames is enabled, the chart will look for a class name string in data using this setting and apply additional class names to elements of the particular data points, such as bullets. */ + classNameField: string; /** Name of the close field (used by candlesticks and ohlc) in your dataProvider. */ closeField: string; + /** In case you want to place this graph's columns in front of other columns, set this to false. In case "true", the columns will be clustered next to each other. + + NOTE: clustering works only for graphs of type "column". + @default true + */ + clustered: boolean; /** Color of value labels. Will use chart's color if not set. */ color: string; /** Name of the color field in your dataProvider. */ colorField: string; - /** Specifies whether to connect data points if data is missing. The default value is true. + /** You can use this property with non-stacked column graphs and specify order of columns of each category (starting from 0). Important: this feature does not work in stacked columns scenarios as well as with graph toggling enabled in legend. */ + columnIndexField: string; + /** You can specify custom column width for each graph individually. Value range is 0 - 1 (we set relative width, not pixel width here). */ + columnWidth: number; + /** Specifies whether to connect data points if data is missing. The default value is true. This feature does not work with XY chart. @default true */ connect: boolean; - /** Corner radius of column. It can be set both in pixels or in percents. The chart's depth and angle styles must be set to 0. The default value is 0. Note, cornerRadiusTop will be applied for all corners of the column, JavaScript charts do not have a possibility to set separate corner radius for top and bottom. As we want all the property names to be the same both on JS and Flex, we didn't change this too. */ + /** Corner radius of column. It can be set both in pixels or in percents. The chart's depth and angle styles must be set to 0. The default value is 0. Note, cornerRadiusTop will be applied for all corners of the column, JavaScript charts do not have a possibility to set separate corner radius for top and bottom. As we want all the property names to be the same both on JS and Flex, we didn't change this too. + @default 0 + */ cornerRadiusTop: number; /** If bulletsEnabled of ChartCurosor is true, a bullet on each graph follows the cursor. You can set opacity of each graphs bullet. In case you want to disable these bullets for a certain graph, set opacity to 0. @default 1 @@ -2249,55 +2285,108 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val customBullet: string; /** Name of the custom bullet field in your dataProvider. */ customBulletField: string; - /** Dash length. If you set it to a value greater than 0, the graph line will be dashed. */ + /** Path to the image for legend marker. */ + customMarker: string; + /** Dash length. If you set it to a value greater than 0, the graph line (or columns border) will be dashed. + @default 0 + */ dashLength: number; + /** Name of the dash length field in your dataProvider. This property adds a possibility to change graphs’ line from solid to dashed on any data point. You can also make columns border dashed using this setting. Note, this won't work with smoothedLineGraph. */ + dashLengthField: string; + /** Used to format balloons if value axis is date-based. + @default "MMM DD, YYYY" + */ + dateFormat: string; /** Name of the description field in your dataProvider. */ descriptionField: string; - /** Opacity of fill. Plural form is used to keep the same property names as our Flex charts'. Flex charts can accept array of numbers to generate gradients. Although you can set array here, only first value of this array will be used. */ + /** Name of error value field in your data provider. */ + errorField: string; + /** Opacity of fill. Plural form is used to keep the same property names as our Flex charts'. Flex charts can accept array of numbers to generate gradients. Although you can set array here, only first value of this array will be used. + @default 0 + */ fillAlphas: number; - /** Fill color. Will use lineColor if not set. */ - fillColors: any; - /** Name of the fill colors field in your dataProvider. */ + /** Fill color. Will use lineColor if not set. You can also set array of colors here. */ + fillColors: string; + /** Name of the fill colors field in your dataProvider. This property adds a possibility to change line graphs’ fill color on any data point to create highlighted sections of the graph. Works only with AmSerialChart. */ fillColorsField: string; - /** You can set another graph here and if fillAlpha is >0, the area from this graph to fillToGraph will be filled (instead of filling the area to the X axis). */ + /** XY chart only. If you set this property to id or reference of your X or Y axis, and the fillAlphas is > 0, the area between graph and axis will be filled with color, like in this demo. */ + fillToAxis: ValueAxis; + /** You can set another graph here and if fillAlpha is >0, the area from this graph to fillToGraph will be filled (instead of filling the area to the X axis). This feature is not supported by smoothedLine graphs and Radar chart. */ fillToGraph: AmGraph; + /** Column width in pixels. If you set this property, columns will be of a fixed width and won't adjust to the available space. */ + fixedColumnWidth: number; /** Size of value labels text. Will use chart's fontSize if not set. */ - fontSize: string; - /** Orientation of the gradient fills (only for "column" graph type). Possible values are "vertical" and "horizontal". vertical */ + fontSize: number; + /** If this is set `true`, the graph will always break the line if the distance in time between two adjacent data points is bigger than `gapPeriod x minPeriod`, even if `connect` is set to `true`. + @default false + */ + forceGap: boolean; + /** Name of the gap field in your dataProvider. You can force graph to show gap at a desired data point using this feature. This feature does not work with XY chart. */ + gapField: string; + /** Using this property you can specify when graph should display gap - if the time difference between data points is bigger than duration of minPeriod * gapPeriod, and connect property of a graph is set to false, graph will display gap. + @default 1.1 + */ + gapPeriod: number; + /** Orientation of the gradient fills (only for "column" graph type). Possible values are "vertical" and "horizontal". + @default "vertical" + */ gradientOrientation: string; - /** Specifies whether the graph is hidden. Do not use this to show/hide the graph, use hideGraph(graph) and showGraph(graph) methods instead. */ + /** Specifies whether the graph is hidden. Do not use this to show/hide the graph, use hideGraph(graph) and showGraph(graph) methods instead. + @default false + */ hidden: boolean; - /** If there are more data points than hideBulletsCount, the bullets will not be shown. 0 means the bullets will always be visible. */ + /** If there are more data points than hideBulletsCount, the bullets will not be shown. 0 means the bullets will always be visible. + @default 0 + */ hideBulletsCount: number; /** Name of the high field (used by candlesticks and ohlc) in your dataProvider. */ highField: string; - - /** Unique id of a graph. It is not required to set one, unless you want to use this graph for as your scrollbar's graph and need to indicate which graph should be used.*/ - id?: string; - + /** Unique id of a graph. It is not required to set one, unless you want to use this graph for as your scrollbar's graph and need to indicate which graph should be used. */ + id: string; /** Whether to include this graph when calculating min and max value of the axis. @default true */ includeInMinMax: boolean; + /** Data label text anchor. + @default "auto" + */ + labelAnchor: string; /** Name of label color field in data provider. */ labelColorField: string; - /** Position of value label. Possible values are: "bottom", "top", "right", "left", "inside", "middle". Sometimes position is changed by the chart, depending on a graph type, rotation, etc. top */ + /** You can use it to format labels of data items in any way you want. Graph will call this function and pass reference to GraphDataItem and formatted text as attributes. This function should return string which will be displayed as label. */ + labelFunction(value: number, valueText: string, valueAxis: ValueAxis): string; + labelFunction(valueText: string, data: Date, valueAxis: ValueAxis): string; + /** Offset of data label. + @default 0 + */ + labelOffset: number; + /** Position of value label. Possible values are: "bottom", "top", "right", "left", "inside", "middle". Sometimes position is changed by the chart, depending on a graph type, rotation, etc. + @default "top" + */ labelPosition: string; + /** Rotation of a data label. + @default 0 + */ + labelRotation: number; /** Value label text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]]. */ labelText: string; /** Legend marker opacity. Will use lineAlpha if not set. Value range is 0 - 1. */ legendAlpha: number; /** Legend marker color. Will use lineColor if not set. */ legendColor: string; + /** It is called and the following attributes are passed: dataItem, formattedText, periodValues, periodPercentValues. It should return hex color code which will be used for legend marker. */ + legendColorFunction: Object; + /** The text which will be displayed in the value portion of the legend when user is not hovering above any data point. The tags should be made out of two parts - the name of a field (value / open / close / high / low) and the value of the period you want to be show - open / close / high / low / sum / average / count. For example: [[value.sum]] means that sum of all data points of value field in the selected period will be displayed. */ + legendPeriodValueText: string; /** Legend value text. You can use tags like [[value]], [[description]], [[percents]], [[open]], [[category]] You can also use custom fields from your dataProvider. If not set, uses Legend's valueText. */ legendValueText: string; /** Opacity of the line (or column border). Value range is 0 - 1. @default 1 */ lineAlpha: number; - /** Color of the line (or column border). If you do not set any, the color from [[AmCoordinateChart */ + /** Color of the line (or column border). If you do not set any, the color from AmCoordinateChart.colors array will be used for each subsequent graph. */ lineColor: string; - /** Name of the line color field (used by columns and candlesticks only) in your dataProvider. */ + /** Name of the line color field in your dataProvider. This property adds a possibility to change graphs’ line color on any data point to create highlighted sections of the graph. Works only with AmSerialChart. */ lineColorField: string; /** Specifies thickness of the graph line (or column border). @default 1 @@ -2305,55 +2394,125 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val lineThickness: number; /** Name of the low field (used by candlesticks and ohlc) in your dataProvider. */ lowField: string; - /** Legend marker type. You can set legend marker (key) type for individual graphs. Possible values are: "square", "circle", "line", "dashedLine", "triangleUp", "triangleDown", "bubble". */ + /** Legend marker type. You can set legend marker (key) type for individual graphs. Possible values are: square, circle, diamond, triangleUp, triangleDown, triangleLeft, triangleDown, bubble, line, none. */ markerType: string; /** Specifies size of the bullet which value is the biggest (XY chart). @default 50 */ maxBulletSize: number; - /** Specifies minimum size of the bullet (XY chart). */ + /** Specifies minimum size of the bullet (XY chart). + @default 4 + */ minBulletSize: number; - /** If you use different colors for your negative values, a graph below zero line is filled with negativeColor. With this property you can define a different base value at which colors should be changed to negative colors. */ + /** It is useful if you have really lots of data points. Based on this property the graph will omit some of the lines (if the distance between points is less that minDistance, in pixels). This will not affect the bullets or indicator in anyway, so the user will not see any difference (unless you set minValue to a bigger value, let say 5), but will increase performance as less lines will be drawn. By setting value to a bigger number you can also make your lines look less jagged. + @default 1 + */ + minDistance: number; + /** If you use different colors for your negative values, a graph below zero line is filled with negativeColor. With this property you can define a different base value at which colors should be changed to negative colors. + @default 0 + */ negativeBase: number; /** Fill opacity of negative part of the graph. Will use fillAlphas if not set. */ negativeFillAlphas: number; /** Fill color of negative part of the graph. Will use fillColors if not set. */ - negativeFillColors: any; //String /Array; + negativeFillColors: string; + /** Opacity of the negative portion of the line (or column border). Value range is 0 - 1. + @default 1 + */ + negativeLineAlpha: number; /** Color of the line (or column) when the values are negative. In case the graph type is candlestick or ohlc, negativeLineColor is used when close value is less then open value. */ negativeLineColor: string; - /** Example: {precision:-1, decimalSeparator:'.', thousandsSeparator:','}. The graph uses this object's values to format the numbers. Uses chart's numberFormatter if not defined. */ - numberFormatter: Object; - /** If you set it to true, column chart will begin new stack. This allows having Clustered and Stacked column/bar chart. */ - newStack: boolean; - /** Name of the open field (used by floating columns, candlesticks and ohlc) in your dataProvider. - @default 50 + /** If you set it to true, column chart will begin new stack. This allows having Clustered and Stacked column/bar chart. + @default false */ + newStack: boolean; + /** In case you want to have a step line graph without risers, you should set this to true. + @default false + */ + noStepRisers: boolean; + /** Name of the open field (used by floating columns, candlesticks and ohlc) in your dataProvider. */ openField: string; - /**Precision of values. Will use chart's precision if not set any.*/ - precision: number; - /** Specifies where data points should be placed - on the beginning of the period (day, hour, etc) or in the middle (only when parseDates property of categoryAxis is set to true). This setting affects Serial chart only. Possible values are "start" and "middle". middle */ + /** Value of pattern should be object with url, width, height of an image, optionally it might have x, y, randomX and randomY values. For example: {"url":"../amcharts/patterns/black/pattern1.png", "width":4, "height":4}. If you want to have individual patterns for each column, define patterns in data provider and set graph.patternField property. Check amcharts/patterns folder for some patterns. You can create your own patterns and use them. Note, x, y, randomX and randomY properties won't work with IE8 and older. 3D bar/Pie charts won't work properly with patterns. */ + pattern: Object; + /** Field name in your data provider which holds pattern information. Value of pattern should be object with url, width, height of an image, optionally it might have x, y, randomX and randomY values. For example: {"url":"../amcharts/patterns/black/pattern1.png", "width":4, "height":4}. Check amcharts/patterns folder for some patterns. You can create your own patterns and use them. Note, x, y, randomX and randomY properties won't work with IE8 and older. 3D bar/Pie charts won't work properly with patterns. */ + patternField: string; + /** This property can be used by step graphs - you can set how many periods one horizontal line should span. + @default 1 + */ + periodSpan: number; + /** Specifies where data points should be placed - on the beginning of the period (day, hour, etc) or in the middle (only when parseDates property of categoryAxis is set to true). This setting affects Serial chart only. Possible values are "start", "middle" and "end" + @default "middle" + */ pointPosition: string; - /** If graph's type is column and labelText is set, graph hides labels which do not fit into the column's space. If you don't want these labels to be hidden, set this to true. */ + /** Precision of values. Will use chart's precision if not set any. */ + precision: number; + /** If this is set to true, candlesticks will be colored in a different manner - if current close is less than current open, the candlestick will be empty, otherwise - filled with color. If previous close is less than current close, the candlestick will use positive color, otherwise - negative color. + @default false + */ + proCandlesticks: boolean; + /** Gantt chart only. Contains unmodified segment object from data provider. */ + segmentData: Object; + /** If graph's type is column and labelText is set, graph hides labels which do not fit into the column's space or go outside plot area. If you don't want these labels to be hidden, set this to true. + @default false + */ showAllValueLabels: boolean; /** Specifies whether the value balloon of this graph is shown when mouse is over data item or chart's indicator is over some series. @default true */ showBalloon: boolean; - /** Specifies graphs value at which cursor is showed. This is only important for candlestick and ohlc charts, also if column chart has "open" value. Possible values are: "open", "close", "high", "low". close */ + /** Specifies graphs value at which cursor is showed. This is only important for candlestick and ohlc charts, also if column chart has "open" value. Possible values are: "open", "close", "high", "low". "top" and "bottom" values will glue the balloon to top/bottom of the plot area. + @default "close" + */ showBalloonAt: string; + /** Works with candlestick graph type, you can set it to open, close, high, low. If you set it to high, the events will be shown at the tip of the high line. + @default "close" + */ + showBulletsAt: string; + /** If you want mouse pointer to change to hand when hovering the graph, set this property to true. + @default false + */ + showHandOnHover: boolean; + /** It can only be used together with topRadius (when columns look like cylinders). If you set it to true, the cylinder will be lowered down so that the center of it's bottom circle would be right on category axis. + @default false + */ + showOnAxis: boolean; /** If the value axis of this graph has stack types like "regular" or "100%" You can exclude this graph from stacking. @default true */ stackable: boolean; + /** Step graph only. Specifies to which direction step should be drawn. + @default "right" + */ + stepDirection: string; + /** If you set it to false, the graph will not be hidden when user clicks on legend entry. + @default true + */ + switchable: boolean; + /** In case you set it to some number, the chart will set focus on bullet/column (starting from first) when user clicks tab key. When a focus is set, screen readers like NVDA Screen reader will read label which is set using accessibleLabel property of AmGraph. Note, not all browsers and readers support this. */ + tabIndex: number; /** Graph title. */ title: string; - /** Type of the graph. Possible values are: "line", "column", "step", "smoothedLine", "candlestick", "ohlc". XY and Radar charts can only display "line" type graphs. line */ + /** If you set this to 1, columns will become cylinders (must set depth3D and angle properties of a chart to >0 values in order this to be visible). you can make columns look like cones (set topRadius to 0) or even like some glasses (set to bigger than 1). We strongly recommend setting grid opacity to 0 in order this to look good. */ + topRadius: number; + /** Type of the graph. Possible values are: "line", "column", "step", "smoothedLine", "candlestick", "ohlc". XY and Radar charts can only display "line" type graphs. + @default "line" + */ type: string; /** Name of the url field in your dataProvider. */ urlField: string; /** Target to open URLs in, i.e. _blank, _top, etc. */ urlTarget: string; - /** Specifies which value axis the graph will use. Will use the first value axis if not set. */ + /** If set to true, the bullet border will take the same color as graph line. + @default false + */ + useLineColorForBulletBorder: boolean; + /** If negativeLineColor and/or negativeFillColors are set and useNegativeColorIfDown is set to true (default is false), the line, step and column graphs will use these colors for lines, bullets or columns if previous value is bigger than current value. In case you set openField for the graph, the graph will compare current value with openField value instead of comparing to previous value. Here is a demo. + @default false + */ + useNegativeColorIfDown: boolean; + /** Specifies which value axis the graph will use. Will use the first value axis if not set. You can use reference to the real ValueAxis object or set value axis id. + @default ValueAxis + */ valueAxis: ValueAxis; /** Name of the value field in your dataProvider. */ valueField: string; @@ -2361,11 +2520,15 @@ If you do not set properties such as dashLength, lineAlpha, lineColor, etc - val @default true */ visibleInLegend: boolean; - /** XY chart only. A horizontal value axis object to attach graph to. */ + /** XY chart only. A horizontal value axis object to attach graph to. + @default ValueAxis + */ xAxis: ValueAxis; /** XY chart only. Name of the x field in your dataProvider. */ xField: string; - /** XY chart only. A vertical value axis object to attach graph to. */ + /** XY chart only. A vertical value axis object to attach graph to. + @default ValueAxis + */ yAxis: ValueAxis; /** XY chart only. Name of the y field in your dataProvider. */ yField: string; From c8196d8e753f9e8d9bce2bfac827ef4519bd1327 Mon Sep 17 00:00:00 2001 From: Yu-Hsin Lu Date: Mon, 13 Nov 2017 18:49:02 +0800 Subject: [PATCH 022/201] Add data field to CheerioElement --- types/cheerio/index.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/cheerio/index.d.ts b/types/cheerio/index.d.ts index 511fce354d..7ea8360849 100644 --- a/types/cheerio/index.d.ts +++ b/types/cheerio/index.d.ts @@ -263,6 +263,7 @@ interface CheerioElement { parent: CheerioElement; parentNode: CheerioElement; nodeValue: string; + data: string; } interface CheerioAPI extends CheerioSelector, CheerioStatic { From 58cf30d21eb55c3cd1dc0c245261ebeac63964c5 Mon Sep 17 00:00:00 2001 From: bonimba Date: Mon, 13 Nov 2017 11:40:04 +0000 Subject: [PATCH 023/201] fix typo 'bottom-ceter' to 'bottom-center' in type positionType --- types/react-redux-toastr/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/react-redux-toastr/index.d.ts b/types/react-redux-toastr/index.d.ts index 74346d2c29..a7ca79c5b1 100644 --- a/types/react-redux-toastr/index.d.ts +++ b/types/react-redux-toastr/index.d.ts @@ -10,7 +10,7 @@ import { Component } from 'react'; import { Action, ActionCreator, Reducer } from 'redux'; export type iconType = 'success' | 'info' | 'warning' | 'error'; -export type positionType = 'top-left' | 'top-center' | 'top-right' | 'bottom-left' | 'bottom-ceter' | 'bottom-right'; +export type positionType = 'top-left' | 'top-center' | 'top-right' | 'bottom-left' | 'bottom-center' | 'bottom-right'; export type toastType = 'success' | 'info' | 'warning' | 'light' | 'error' | 'confirm' | 'message'; export type transitionInType = 'bounceIn' | 'bounceInDown' | 'fadeIn'; export type transitionOutType = 'bounceOut' | 'bounceOutUp' | 'fadeOut'; From 6b6db76b81dcbd2da7366f8e056a0793183c53e7 Mon Sep 17 00:00:00 2001 From: "Mariano A. Cortesi" Date: Mon, 13 Nov 2017 13:19:54 -0300 Subject: [PATCH 024/201] [mongodb] Include `bufferMaxEntries` as a MongoClientOption --- types/mongodb/index.d.ts | 4 ++++ types/mongodb/mongodb-tests.ts | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 19cf0136e2..32bc523d38 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -5,6 +5,7 @@ // Gady Piazza // Jason Dreyzehner // Gaurav Lahoti +// Mariano Cortesi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -146,6 +147,9 @@ export interface DbCreateOptions { promiseLibrary?: Object; // https://docs.mongodb.com/manual/reference/read-concern/#read-concern readConcern?: { level?: Object }; + // Sets a cap on how many operations the driver will buffer up before giving up on getting a + // working connection, default is -1 which is unlimited. + bufferMaxEntries?: number; } // http://mongodb.github.io/node-mongodb-native/2.2/api/Server.html diff --git a/types/mongodb/mongodb-tests.ts b/types/mongodb/mongodb-tests.ts index 2b8c49d186..52f2d6e4f8 100644 --- a/types/mongodb/mongodb-tests.ts +++ b/types/mongodb/mongodb-tests.ts @@ -3,7 +3,7 @@ import mongodb = require('mongodb'); var MongoClient = mongodb.MongoClient; var format = require('util').format; -let options = { +let options: mongodb.MongoClientOptions = { authSource : ' ', w : 1, wtimeout : 300, From 74871d99d2c4d90396de1a8140a005e5ab191147 Mon Sep 17 00:00:00 2001 From: Kirk Thompson Date: Mon, 13 Nov 2017 15:09:52 -0500 Subject: [PATCH 025/201] Fix angular-sanitize ILinky typing. The second argument to the ILinky filter should be optional, per documentat ion. See https://docs.angularjs.org/api/ngSanitize/filter/linky --- types/angular-sanitize/angular-sanitize-tests.ts | 1 + types/angular-sanitize/index.d.ts | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/types/angular-sanitize/angular-sanitize-tests.ts b/types/angular-sanitize/angular-sanitize-tests.ts index b093f2bbb0..51d48db90d 100644 --- a/types/angular-sanitize/angular-sanitize-tests.ts +++ b/types/angular-sanitize/angular-sanitize-tests.ts @@ -4,5 +4,6 @@ declare var $sanitizeService: ng.sanitize.ISanitizeService; shouldBeString = $sanitizeService(shouldBeString); declare var $linky: ng.sanitize.filter.ILinky; +shouldBeString = $linky(shouldBeString); shouldBeString = $linky(shouldBeString, "target"); shouldBeString = $linky(shouldBeString, shouldBeString); diff --git a/types/angular-sanitize/index.d.ts b/types/angular-sanitize/index.d.ts index ad42ec362e..b9d16aaeb2 100644 --- a/types/angular-sanitize/index.d.ts +++ b/types/angular-sanitize/index.d.ts @@ -36,7 +36,7 @@ declare module 'angular' { * see https://docs.angularjs.org/api/ngSanitize/filter/linky */ interface ILinky { - (text: string, target: string, attributes?: { [attribute: string]: string } | ((url: string) => { [attribute: string]: string })): string; + (text: string, target?: string, attributes?: { [attribute: string]: string } | ((url: string) => { [attribute: string]: string })): string; } } From f72c47652e57827bb8906ad13f7a1c7379017210 Mon Sep 17 00:00:00 2001 From: Luke Sanwick Date: Mon, 13 Nov 2017 15:23:13 -0800 Subject: [PATCH 026/201] [redux-actions] Update definition to support nested reducer maps --- types/redux-actions/index.d.ts | 4 +++- types/redux-actions/redux-actions-tests.ts | 9 +++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/types/redux-actions/index.d.ts b/types/redux-actions/index.d.ts index 45ecf21933..6051ab7afe 100644 --- a/types/redux-actions/index.d.ts +++ b/types/redux-actions/index.d.ts @@ -22,8 +22,10 @@ export interface ActionMeta extends Action { meta: Meta; } +export type ReducerMapValue = Reducer | ReducerNextThrow | ReducerMap; + export interface ReducerMap { - [actionType: string]: Reducer | ReducerNextThrow; + [actionType: string]: ReducerMapValue; } export interface ReducerMapMeta { diff --git a/types/redux-actions/redux-actions-tests.ts b/types/redux-actions/redux-actions-tests.ts index b7eeb2e62f..7fa5744f22 100644 --- a/types/redux-actions/redux-actions-tests.ts +++ b/types/redux-actions/redux-actions-tests.ts @@ -51,6 +51,15 @@ const actionsHandlerWithInitialState = ReduxActions.handleActions({ state = actionsHandlerWithInitialState(0, { type: 'INCREMENT' }); +const actionsHandlerWithRecursiveReducerMap = ReduxActions.handleActions({ + ADJUST: { + UP: (state: number, action: ReduxActions.Action) => state + action.payload, + DOWN: (state: number, action: ReduxActions.Action) => state - action.payload, + } +}, 0); + +state = actionsHandlerWithRecursiveReducerMap(0, { type: 'ADJUST/UP', payload: 1 }); + // ---------------------------------------------------------------------------------------------------- interface TypedState { From a70ad3ce5d4affd8e3fe0c545361d8f01c7c3137 Mon Sep 17 00:00:00 2001 From: segayuu Date: Tue, 14 Nov 2017 10:14:36 +0900 Subject: [PATCH 027/201] Fix to explicitly set Type Class field --- types/js-yaml/index.d.ts | 17 +++++++++++------ types/js-yaml/js-yaml-tests.ts | 16 +++++++++++++++- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/types/js-yaml/index.d.ts b/types/js-yaml/index.d.ts index 98354d26ba..51f3ae95cf 100644 --- a/types/js-yaml/index.d.ts +++ b/types/js-yaml/index.d.ts @@ -7,12 +7,17 @@ export function safeLoad(str: string, opts?: LoadOptions): any; export function load(str: string, opts?: LoadOptions): any; -export class Type { +export class Type implements TypeConstructorOptions { constructor(tag: string, opts?: TypeConstructorOptions); - tag: string; + kind: string | null; + resolve(data: any): boolean; + construct(data: any): any; + instanceOf: object | null; + predicate: string | null; + represent: ((data: object) => any) | { [x: string]: (data: object) => any; } | null; + defaultStyle: string | null; + styleAliases: { [x: string]: any; }; } -/* tslint:disable-next-line:no-empty-interface */ -export interface Type extends TypeConstructorOptions { } /* tslint:disable-next-line:no-unnecessary-class */ export class Schema implements SchemaDefinition { @@ -73,8 +78,8 @@ export interface TypeConstructorOptions { export interface SchemaDefinition { implicit?: any[]; - explicit?: any[]; - include?: any[]; + explicit?: Type[]; + include?: Schema[]; } // only strings, arrays and plain objects: http://www.yaml.org/spec/1.2/spec.html#id2802346 diff --git a/types/js-yaml/js-yaml-tests.ts b/types/js-yaml/js-yaml-tests.ts index 91229e487a..6799deafd8 100644 --- a/types/js-yaml/js-yaml-tests.ts +++ b/types/js-yaml/js-yaml-tests.ts @@ -7,10 +7,13 @@ import SchemaDefinition = yaml.SchemaDefinition; let bool: boolean; let num: number; let str: string; -let obj: { [x: string]: any; }; +let obj: object; +let map: { [x: string]: any; }; let value: any; let array: any[]; let fn: (...args: any[]) => any; +let fnOrFnMap: ((...args: any[]) => any) | { [x: string]: (...args: any[]) => any; }; +let type: yaml.Type; let schemaDefinition: SchemaDefinition = { implicit: array, explicit: array, @@ -72,6 +75,17 @@ dumpOpts = { // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +str = type.kind; +fn = type.resolve; +fn = type.construct; +obj = type.instanceOf; +str = type.predicate; +fnOrFnMap = type.represent; +str = type.defaultStyle; +map = type.styleAliases; + +// -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- + value = yaml.safeLoad(str); value = yaml.safeLoad(str, loadOpts); From dfa80c44edbed7e944f031e7cc9b6b465e923460 Mon Sep 17 00:00:00 2001 From: segayuu Date: Tue, 14 Nov 2017 11:16:05 +0900 Subject: [PATCH 028/201] Only one of 'sequence', 'scalar' and 'mapping' can be used for kind. --- types/js-yaml/index.d.ts | 4 ++-- types/js-yaml/js-yaml-tests.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/types/js-yaml/index.d.ts b/types/js-yaml/index.d.ts index 51f3ae95cf..d01f272661 100644 --- a/types/js-yaml/index.d.ts +++ b/types/js-yaml/index.d.ts @@ -9,7 +9,7 @@ export function load(str: string, opts?: LoadOptions): any; export class Type implements TypeConstructorOptions { constructor(tag: string, opts?: TypeConstructorOptions); - kind: string | null; + kind: 'sequence' | 'scalar' | 'mapping' | null; resolve(data: any): boolean; construct(data: any): any; instanceOf: object | null; @@ -66,7 +66,7 @@ export interface DumpOptions { } export interface TypeConstructorOptions { - kind?: string; + kind?: 'sequence' | 'scalar' | 'mapping'; resolve?: (data: any) => boolean; construct?: (data: any) => any; instanceOf?: object; diff --git a/types/js-yaml/js-yaml-tests.ts b/types/js-yaml/js-yaml-tests.ts index 6799deafd8..f6d1da58f0 100644 --- a/types/js-yaml/js-yaml-tests.ts +++ b/types/js-yaml/js-yaml-tests.ts @@ -20,7 +20,7 @@ let schemaDefinition: SchemaDefinition = { include: array }; let typeConstructorOptions: TypeConstructorOptions = { - kind: str, + kind: "scalar", resolve: fn, construct: fn, instanceOf: obj, From f5c566a7fd1f291b0b58cf74fe12fafddd8b187a Mon Sep 17 00:00:00 2001 From: segayuu Date: Tue, 14 Nov 2017 11:44:12 +0900 Subject: [PATCH 029/201] cleanup ignore lint error: prefer-const --- types/js-yaml/js-yaml-tests.ts | 121 +++++++++++++++++++++------------ types/js-yaml/tslint.json | 7 +- 2 files changed, 80 insertions(+), 48 deletions(-) diff --git a/types/js-yaml/js-yaml-tests.ts b/types/js-yaml/js-yaml-tests.ts index f6d1da58f0..9cb457b98e 100644 --- a/types/js-yaml/js-yaml-tests.ts +++ b/types/js-yaml/js-yaml-tests.ts @@ -4,22 +4,21 @@ import DumpOptions = yaml.DumpOptions; import TypeConstructorOptions = yaml.TypeConstructorOptions; import SchemaDefinition = yaml.SchemaDefinition; -let bool: boolean; -let num: number; -let str: string; -let obj: object; -let map: { [x: string]: any; }; -let value: any; -let array: any[]; -let fn: (...args: any[]) => any; -let fnOrFnMap: ((...args: any[]) => any) | { [x: string]: (...args: any[]) => any; }; -let type: yaml.Type; -let schemaDefinition: SchemaDefinition = { +const bool = true; +const num = 0; +const str = ""; +const obj: object = {}; +const map: { [x: string]: any; } = {}; +const array: any[] = []; +const fn: (...args: any[]) => any = () => {}; +const type = new yaml.Type(str); + +const schemaDefinition: SchemaDefinition = { implicit: array, explicit: array, include: array }; -let typeConstructorOptions: TypeConstructorOptions = { +const typeConstructorOptions: TypeConstructorOptions = { kind: "scalar", resolve: fn, construct: fn, @@ -27,20 +26,30 @@ let typeConstructorOptions: TypeConstructorOptions = { predicate: str, represent: fn, defaultStyle: str, - styleAliases: obj + styleAliases: map }; +const schema: yaml.Schema = new yaml.Schema(schemaDefinition); + +let value: any; let loadOpts: LoadOptions; let dumpOpts: DumpOptions; // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- +// $ExpectType Schema yaml.FAILSAFE_SCHEMA; +// $ExpectType Schema yaml.JSON_SCHEMA; +// $ExpectType Schema yaml.CORE_SCHEMA; +// $ExpectType Schema yaml.DEFAULT_SAFE_SCHEMA; +// $ExpectType Schema yaml.DEFAULT_FULL_SCHEMA; +// $ExpectType Schema yaml.MINIMAL_SCHEMA; +// $ExpectType Schema yaml.SAFE_SCHEMA; // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- @@ -75,53 +84,81 @@ dumpOpts = { // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -str = type.kind; -fn = type.resolve; -fn = type.construct; -obj = type.instanceOf; -str = type.predicate; -fnOrFnMap = type.represent; -str = type.defaultStyle; -map = type.styleAliases; +// $ExpectType Type +new yaml.Type(str, typeConstructorOptions); + +// $ExpectType "sequence" | "scalar" | "mapping" +type.kind; +// $ExpectType (data: any) => boolean +type.resolve; +// $ExpectType (data: any) => any +type.construct; +// $ExpectType object +type.instanceOf; +// $ExpectType string +type.predicate; +// $ExpectType ((data: object) => any) | { [x: string]: (data: object) => any; } +type.represent; +// $ExpectType string +type.defaultStyle; +// $ExpectType { [x: string]: any; } +type.styleAliases; // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -value = yaml.safeLoad(str); -value = yaml.safeLoad(str, loadOpts); +// $ExpectType any +yaml.safeLoad(str); +// $ExpectType any +yaml.safeLoad(str, loadOpts); -value = yaml.load(str); -value = yaml.load(str, loadOpts); +// $ExpectType any +yaml.load(str); +// $ExpectType any +yaml.load(str, loadOpts); // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -value = yaml.safeLoadAll(str, (doc) => { +// $ExpectType any +yaml.safeLoadAll(str, (doc) => { value = doc; }); -value = yaml.safeLoadAll(str, (doc) => { +// $ExpectType any +yaml.safeLoadAll(str, (doc) => { value = doc; }, loadOpts); -value = yaml.loadAll(str, (doc) => { +// $ExpectType any +yaml.loadAll(str, (doc) => { value = doc; }); -value = yaml.loadAll(str, (doc) => { +// $ExpectType any +yaml.loadAll(str, (doc) => { value = doc; }, loadOpts); // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -value = yaml.safeDump(str); -value = yaml.safeDump(str, dumpOpts); +// $ExpectType string +yaml.safeDump(str); +// $ExpectType string +yaml.safeDump(str, dumpOpts); -value = yaml.dump(str); -value = yaml.dump(str, dumpOpts); +// $ExpectType string +yaml.dump(str); +// $ExpectType string +yaml.dump(str, dumpOpts); -value = new yaml.YAMLException(); -value = new yaml.Type(str, typeConstructorOptions); -value = new yaml.Schema(schemaDefinition); -value = yaml.Schema.create([new yaml.Type(str)]); -value = yaml.Schema.create(new yaml.Type(str)); -value = yaml.Schema.create(new yaml.Schema(schemaDefinition), [new yaml.Type(str)]); -value = yaml.Schema.create([new yaml.Schema(schemaDefinition)], [new yaml.Type(str)]); -value = yaml.Schema.create(new yaml.Schema(schemaDefinition), new yaml.Type(str)); -value = yaml.Schema.create([new yaml.Schema(schemaDefinition)], new yaml.Type(str)); +new yaml.YAMLException(); + +// $ExpectType Schema +yaml.Schema.create([type]); +// $ExpectType Schema +yaml.Schema.create(type); +// $ExpectType Schema +yaml.Schema.create(schema, [type]); +// $ExpectType Schema +yaml.Schema.create([schema], [type]); +// $ExpectType Schema +yaml.Schema.create(schema, type); +// $ExpectType Schema +yaml.Schema.create([schema], type); diff --git a/types/js-yaml/tslint.json b/types/js-yaml/tslint.json index a6a9bab5f0..3db14f85ea 100644 --- a/types/js-yaml/tslint.json +++ b/types/js-yaml/tslint.json @@ -1,6 +1 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "prefer-const": false - } -} +{ "extends": "dtslint/dt.json" } From 3860b64345b459ee76d985e10969321ac55a87a7 Mon Sep 17 00:00:00 2001 From: segayuu Date: Tue, 14 Nov 2017 11:49:52 +0900 Subject: [PATCH 030/201] Enable strictNullChecks --- types/js-yaml/index.d.ts | 2 +- types/js-yaml/js-yaml-tests.ts | 10 +++++----- types/js-yaml/tsconfig.json | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/types/js-yaml/index.d.ts b/types/js-yaml/index.d.ts index d01f272661..70e43b5067 100644 --- a/types/js-yaml/index.d.ts +++ b/types/js-yaml/index.d.ts @@ -7,7 +7,7 @@ export function safeLoad(str: string, opts?: LoadOptions): any; export function load(str: string, opts?: LoadOptions): any; -export class Type implements TypeConstructorOptions { +export class Type { constructor(tag: string, opts?: TypeConstructorOptions); kind: 'sequence' | 'scalar' | 'mapping' | null; resolve(data: any): boolean; diff --git a/types/js-yaml/js-yaml-tests.ts b/types/js-yaml/js-yaml-tests.ts index 9cb457b98e..13931a81df 100644 --- a/types/js-yaml/js-yaml-tests.ts +++ b/types/js-yaml/js-yaml-tests.ts @@ -87,19 +87,19 @@ dumpOpts = { // $ExpectType Type new yaml.Type(str, typeConstructorOptions); -// $ExpectType "sequence" | "scalar" | "mapping" +// $ExpectType "sequence" | "scalar" | "mapping" | null type.kind; // $ExpectType (data: any) => boolean type.resolve; // $ExpectType (data: any) => any type.construct; -// $ExpectType object +// $ExpectType object | null type.instanceOf; -// $ExpectType string +// $ExpectType string | null type.predicate; -// $ExpectType ((data: object) => any) | { [x: string]: (data: object) => any; } +// $ExpectType ((data: object) => any) | { [x: string]: (data: object) => any; } | null type.represent; -// $ExpectType string +// $ExpectType string | null type.defaultStyle; // $ExpectType { [x: string]: any; } type.styleAliases; diff --git a/types/js-yaml/tsconfig.json b/types/js-yaml/tsconfig.json index b1e787d1b3..c36931fa61 100644 --- a/types/js-yaml/tsconfig.json +++ b/types/js-yaml/tsconfig.json @@ -6,7 +6,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ @@ -20,4 +20,4 @@ "index.d.ts", "js-yaml-tests.ts" ] -} \ No newline at end of file +} From 81001434b1dc8446be72ec72a4fb0bcf2788ea0b Mon Sep 17 00:00:00 2001 From: segayuu Date: Tue, 14 Nov 2017 11:50:35 +0900 Subject: [PATCH 031/201] js-yaml miner version up --- types/js-yaml/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/js-yaml/index.d.ts b/types/js-yaml/index.d.ts index 70e43b5067..2ef8eea676 100644 --- a/types/js-yaml/index.d.ts +++ b/types/js-yaml/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for js-yaml 3.9 +// Type definitions for js-yaml 3.10 // Project: https://github.com/nodeca/js-yaml // Definitions by: Bart van der Schoor , Sebastian Clausen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From a704c482e491350a1f35352b8b009e065dbd362c Mon Sep 17 00:00:00 2001 From: segayuu Date: Tue, 14 Nov 2017 13:21:31 +0900 Subject: [PATCH 032/201] Add LoadOptions.json https://github.com/nodeca/js-yaml#safeload-string---options- --- types/js-yaml/index.d.ts | 2 ++ types/js-yaml/js-yaml-tests.ts | 3 +++ 2 files changed, 5 insertions(+) diff --git a/types/js-yaml/index.d.ts b/types/js-yaml/index.d.ts index eff4fd51b0..2fa264cbd9 100644 --- a/types/js-yaml/index.d.ts +++ b/types/js-yaml/index.d.ts @@ -39,6 +39,8 @@ export interface LoadOptions { strict?: boolean; // specifies a schema to use. schema?: any; + // compatibility with JSON.parse behaviour. + json?: boolean; } export interface DumpOptions { diff --git a/types/js-yaml/js-yaml-tests.ts b/types/js-yaml/js-yaml-tests.ts index 4e7e9c834e..3d5ecc17bf 100644 --- a/types/js-yaml/js-yaml-tests.ts +++ b/types/js-yaml/js-yaml-tests.ts @@ -63,6 +63,9 @@ loadOpts = { loadOpts = { schema: bool }; +loadOpts = { + json: bool +}; // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- From 2a5a4ff2fdf8fcefb23865ee84689d017b89311e Mon Sep 17 00:00:00 2001 From: simonxca Date: Mon, 13 Nov 2017 21:06:28 -0800 Subject: [PATCH 033/201] Add tests for mongoose child schema Fixes #20331 --- types/mongoose/mongoose-tests.ts | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index d6f262ebf6..1416d12332 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -385,8 +385,14 @@ Animal['findByName']('fido', function(err: any, animals: any) { animalSchema.virtual('name.full').get(function () { return this.name.first + ' ' + this.name.last; }); -new mongoose.Schema({ - child: { name: String } +var childSchema = new mongoose.Schema({ name: String }); +var parentSchema = new mongoose.Schema({ + children: [childSchema], + child: childSchema, + name: { + index: true, + required: true + } }); new mongoose.Schema({ eggs: { From ea1c4c37641de38ee3818626d7276ffb4d5328b6 Mon Sep 17 00:00:00 2001 From: Scott Thompson Date: Tue, 14 Nov 2017 12:22:08 -0500 Subject: [PATCH 034/201] add heatmap to layer types (added in 0.41.0) --- types/mapbox-gl/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 6be9a465ef..672ebfd89a 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -901,7 +901,7 @@ declare namespace mapboxgl { export interface Layer { id: string; - type?: "fill" | "line" | "symbol" | "circle" | "fill-extrusion" | "raster" | "background"; + type?: "fill" | "line" | "symbol" | "circle" | "fill-extrusion" | "raster" | "background" | "heatmap"; metadata?: any; ref?: string; From 0d5ef0aa4dca6451e43e7d5b02f5222ebbda09dc Mon Sep 17 00:00:00 2001 From: sthomp Date: Tue, 14 Nov 2017 12:46:58 -0500 Subject: [PATCH 035/201] version bump --- types/mapbox-gl/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 672ebfd89a..ddaafced3d 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mapbox GL JS v0.40.1 +// Type definitions for Mapbox GL JS v0.41.0 // Project: https://github.com/mapbox/mapbox-gl-js // Definitions by: Dominik Bruderer , Patrick Reames // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped From 48f796b42f4f660a7eaae76cb88a67f975f5fb88 Mon Sep 17 00:00:00 2001 From: Walter Zalazar Date: Tue, 14 Nov 2017 17:49:54 -0300 Subject: [PATCH 036/201] use string array for path parameter --- types/koa-router/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/koa-router/index.d.ts b/types/koa-router/index.d.ts index ba7815ef54..206ce70a3d 100644 --- a/types/koa-router/index.d.ts +++ b/types/koa-router/index.d.ts @@ -140,7 +140,7 @@ declare class Router { * "down" the middleware stack. */ use(...middleware: Array): Router; - use(path: string | RegExp, ...middleware: Array): Router; + use(path: string | string[] | RegExp, ...middleware: Array): Router; /** * HTTP get method From b2692d72c12afe3a6618ab2285edb6cea18bb75b Mon Sep 17 00:00:00 2001 From: Pavel Birukov Date: Tue, 14 Nov 2017 23:35:22 +0200 Subject: [PATCH 037/201] Add disableLifecycleMethods option to configure() and shallow() --- types/enzyme/enzyme-tests.tsx | 26 ++++++++++++++++++++++++-- types/enzyme/index.d.ts | 18 +++++++++++++++++- 2 files changed, 41 insertions(+), 3 deletions(-) diff --git a/types/enzyme/enzyme-tests.tsx b/types/enzyme/enzyme-tests.tsx index 63e716c50b..c48c050357 100644 --- a/types/enzyme/enzyme-tests.tsx +++ b/types/enzyme/enzyme-tests.tsx @@ -1,5 +1,14 @@ import * as React from "react"; -import { shallow, mount, render, ShallowWrapper, ReactWrapper } from "enzyme"; +import { + shallow, + mount, + render, + ShallowWrapper, + ReactWrapper, + configure, + EnzymeAdapter, + ShallowRendererProps, +} from "enzyme"; import { Component, ReactElement, HTMLAttributes, ComponentClass, StatelessComponent } from "react"; // Help classes/interfaces @@ -24,6 +33,18 @@ class MyComponent extends Component { const MyStatelessComponent = (props: StatelessProps) => ; +// Enzyme.configure +function configureTest() { + const configureAdapter: { adapter: EnzymeAdapter } = { adapter: {} }; + configure(configureAdapter); + + const configureAdapterAndDisableLifecycle: typeof configureAdapter & Pick = { + adapter: {}, + disableLifecycleMethods: true, + }; + configure(configureAdapterAndDisableLifecycle); +} + // ShallowWrapper function ShallowWrapperTest() { let shallowWrapper: ShallowWrapper = @@ -50,7 +71,8 @@ function ShallowWrapperTest() { context: { test: "a", }, - lifecycleExperimental: true + lifecycleExperimental: true, + disableLifecycleMethods: true }); } diff --git a/types/enzyme/index.d.ts b/types/enzyme/index.d.ts index bfd714fd22..3a8ea149f9 100644 --- a/types/enzyme/index.d.ts +++ b/types/enzyme/index.d.ts @@ -551,6 +551,12 @@ export class ReactWrapper

{ } export interface ShallowRendererProps { + // See https://github.com/airbnb/enzyme/blob/enzyme@3.1.1/docs/api/shallow.md#arguments + /** + * If set to true, componentDidMount is not called on the component, and componentDidUpdate is not called after + * setProps and setContext. Default to false. + */ + disableLifecycleMethods?: boolean; /** * Enable experimental support for full react lifecycle methods */ @@ -602,4 +608,14 @@ export class EnzymeAdapter { * Configure enzyme to use the correct adapter for the react verstion * This is enabling the Enzyme configuration with adapters in TS */ -export function configure(options: { adapter: EnzymeAdapter }): void; +export function configure(options: { + adapter: EnzymeAdapter, + // See https://github.com/airbnb/enzyme/blob/enzyme@3.1.1/docs/guides/migration-from-2-to-3.md#lifecycle-methods + // Actually, `{adapter:} & Pick` is more precise. However, + // in that case jsdoc won't be shown + /** + * If set to true, componentDidMount is not called on the component, and componentDidUpdate is not called after + * setProps and setContext. Default to false. + */ + disableLifecycleMethods?: boolean; +}): void; From 778e97bc8af28573ee21a38171fcfe77175940c3 Mon Sep 17 00:00:00 2001 From: Asuka Ito Date: Wed, 15 Nov 2017 10:30:51 +0900 Subject: [PATCH 038/201] moxios: Add some properties. --- types/moxios/index.d.ts | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/types/moxios/index.d.ts b/types/moxios/index.d.ts index b4ca5580fd..b0cc379fef 100644 --- a/types/moxios/index.d.ts +++ b/types/moxios/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Asuka Ito // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -import { AxiosInstance } from "axios"; +import { AxiosInstance, AxiosRequestConfig } from "axios"; interface Item { response?: any; @@ -75,7 +75,14 @@ declare class Request { * @param reject The function to call when Promise is rejected * @param config The config object to be used for the request */ - constructor(resolve: (arg: any) => void, reject: (arg: any) => void, config: any); + constructor(resolve: (arg: any) => void, reject: (arg: any) => void, config: AxiosRequestConfig); + + config: AxiosRequestConfig; + headers: any; + url: string; + timeout: number; + withCredentials: boolean; + responseType: string; /** * Respond to this request with a timeout result @@ -102,12 +109,13 @@ declare class Response { */ constructor(req: Request, res: any); - config: any; + config: AxiosRequestConfig; data?: any; status?: number; statusText?: string; headers: any; request: Request; + code?: string; } declare let moxios: { From ed60772e25027bc02e322f3a417532a4f6aab707 Mon Sep 17 00:00:00 2001 From: Roelof Date: Wed, 15 Nov 2017 12:06:31 +0200 Subject: [PATCH 039/201] Added the BufferGeometry.setFromPoints method with the return type of BufferGeometry. Also added the return type of BufferGeometry to the existing BufferGeometry.setFromObject method. --- types/three/index.d.ts | 2 +- types/three/three-core.d.ts | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/types/three/index.d.ts b/types/three/index.d.ts index f9dcc7a762..5819d326de 100644 --- a/types/three/index.d.ts +++ b/types/three/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for three.js 0.84 // Project: http://mrdoob.github.com/three.js/ -// Definitions by: Kon , Satoru Kimura , Florent Poujol , SereznoKot , HouChunlei , Ivo , David Asmuth , Brandon Roberge, Qinsi ZHU , Toshiya Nakakura , Poul Kjeldager Sørensen , Stefan Profanter , Edmund Fokschaner +// Definitions by: Kon , Satoru Kimura , Florent Poujol , SereznoKot , HouChunlei , Ivo , David Asmuth , Brandon Roberge, Qinsi ZHU , Toshiya Nakakura , Poul Kjeldager Sørensen , Stefan Profanter , Edmund Fokschaner , Roelof Jooste // Definitions: https://github.com//DefinitelyTyped export * from "./three-core"; diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index 3252661b75..88babf5ed2 100644 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -862,7 +862,8 @@ export class BufferGeometry extends EventDispatcher { center(): Vector3; - setFromObject(object: Object3D): void; + setFromObject(object: Object3D): BufferGeometry; + setFromPoints(points: Vector3[]): BufferGeometry; updateFromObject(object: Object3D): void; fromGeometry(geometry: Geometry, settings?: any): BufferGeometry; From 16dd87cb3f93438a3a980ec8e936bfd1e5ba0801 Mon Sep 17 00:00:00 2001 From: Joni Salmi Date: Wed, 15 Nov 2017 13:49:17 +0200 Subject: [PATCH 040/201] Supertest@2.0.1: Add missing options argument for Agent --- types/supertest/index.d.ts | 5 ++++- types/supertest/supertest-tests.ts | 5 +++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/types/supertest/index.d.ts b/types/supertest/index.d.ts index 6da2f54206..0716f9e1b5 100644 --- a/types/supertest/index.d.ts +++ b/types/supertest/index.d.ts @@ -32,7 +32,10 @@ declare namespace supertest { end(callback?: CallbackHandler): this; } - function agent(app?: any): SuperTest; + interface AgentOptions { + ca?: any; + } + function agent(app?: any, options?: AgentOptions): SuperTest; interface SuperTest extends superagent.SuperAgent { } diff --git a/types/supertest/supertest-tests.ts b/types/supertest/supertest-tests.ts index 7241aac5c3..868aa8fdce 100644 --- a/types/supertest/supertest-tests.ts +++ b/types/supertest/supertest-tests.ts @@ -42,6 +42,11 @@ client }); }); +// allow passing trusted CA as option to TestAgent +supertest.agent(app, { + ca: 'test ca', +}); + // functional expect (request .get('/') as supertest.Test) From ef2b897324f6db46e162c676481683d9f9437a78 Mon Sep 17 00:00:00 2001 From: Gregor Yushinov Date: Wed, 15 Nov 2017 17:48:25 +0100 Subject: [PATCH 041/201] Accept a connection object instead of a URL --- types/amqplib/index.d.ts | 2 +- types/amqplib/properties.d.ts | 60 ++++++++++++++++++++++++++++++++++- 2 files changed, 60 insertions(+), 2 deletions(-) diff --git a/types/amqplib/index.d.ts b/types/amqplib/index.d.ts index 91060d23b0..2d5cb3ba99 100644 --- a/types/amqplib/index.d.ts +++ b/types/amqplib/index.d.ts @@ -63,4 +63,4 @@ export interface ConfirmChannel extends Channel { waitForConfirms(): Promise; } -export function connect(url: string, socketOptions?: any): Promise; +export function connect(url: string | Options.Connect, socketOptions?: any): Promise; diff --git a/types/amqplib/properties.d.ts b/types/amqplib/properties.d.ts index 12514d7810..af90909d8c 100644 --- a/types/amqplib/properties.d.ts +++ b/types/amqplib/properties.d.ts @@ -21,6 +21,64 @@ export namespace Replies { } export namespace Options { + interface Connect { + /** + * The to be used protocol + * + * Default value: 'amqp' + */ + protocol?: string; + /** + * Hostname used for connecting to the server. + * + * Default value: 'localhost' + */ + hostname?: string; + /** + * Port used for connecting to the server. + * + * Default value: 5672 + */ + port?: number; + /** + * Username used for authenticating against the server. + * + * Default value: 'guest' + */ + username?: string; + /** + * Password used for authenticating against the server. + * + * Default value: 'guest' + */ + password?: string; + /** + * The desired locale for error messages. RabbitMQ only ever uses en_US + * + * Default value: 'en_US' + */ + locale?: string; + /** + * The size in bytes of the maximum frame allowed over the connection. 0 means + * no limit (but since frames have a size field which is an unsigned 32 bit integer, it’s perforce 2^32 - 1). + * + * Default value: 0x1000 (4kb) - That's the allowed minimum, it will fit many purposes + */ + frameMax?: number; + /** + * The period of the connection heartbeat in seconds. + * + * Default value: 0 + */ + heartbeat?: number; + /** + * What VHost shall be used. + * + * Default value: '/' + */ + vhost?: string; + } + interface AssertQueue { exclusive?: boolean; durable?: boolean; @@ -85,4 +143,4 @@ export interface Message { content: Buffer; fields: any; properties: any; -} \ No newline at end of file +} From e4fd38e983451f4829dc4110f93d23e040d7193a Mon Sep 17 00:00:00 2001 From: mnlegend Date: Wed, 15 Nov 2017 10:31:15 -0800 Subject: [PATCH 042/201] Update Backbone.sync to use a union Updating file to use union to better follow the typescript Do's and Don'ts under the 'Use Union Types' section found in the link below. https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html This will help prevent issues where a line of code such as 'let proxiedSync = Backbone.sync;' will use the wrong sync function. --- types/backbone/index.d.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/types/backbone/index.d.ts b/types/backbone/index.d.ts index 607f6413fc..1a186d9924 100644 --- a/types/backbone/index.d.ts +++ b/types/backbone/index.d.ts @@ -460,8 +460,7 @@ declare namespace Backbone { } // SYNC - function sync(method: string, model: Model, options?: JQueryAjaxSettings): any; - function sync(method: string, collection: Collection, options?: JQueryAjaxSettings): any; + function sync(method: string, model: Model | Collection, options?: JQueryAjaxSettings): any; function ajax(options?: JQueryAjaxSettings): JQueryXHR; var emulateHTTP: boolean; var emulateJSON: boolean; From 003471fd3cd1a7a4e3d847e24bb6c5d5ad681f6c Mon Sep 17 00:00:00 2001 From: Joel Hegg Date: Wed, 15 Nov 2017 16:11:51 -0500 Subject: [PATCH 043/201] [actions-on-google] Upgrade to 1.6 --- types/actions-on-google/actions-sdk-app.d.ts | 25 ++ types/actions-on-google/assistant-app.d.ts | 265 ++++++++++++++---- types/actions-on-google/index.d.ts | 2 +- types/actions-on-google/response-builder.d.ts | 20 +- types/actions-on-google/transactions.d.ts | 174 +++++++++--- 5 files changed, 389 insertions(+), 97 deletions(-) diff --git a/types/actions-on-google/actions-sdk-app.d.ts b/types/actions-on-google/actions-sdk-app.d.ts index 8de0de0cfb..09a4fbe0ad 100644 --- a/types/actions-on-google/actions-sdk-app.d.ts +++ b/types/actions-on-google/actions-sdk-app.d.ts @@ -35,6 +35,7 @@ export class ActionsSdkApp extends AssistantApp { constructor(options: ActionsSdkAppOptions); /** + * @deprecated * Validates whether request is from Assistant through signature verification. * Uses Google-Auth-Library to verify authorization token against given * Google Cloud Project ID. Auth token is given in request header with key, @@ -58,6 +59,30 @@ export class ActionsSdkApp extends AssistantApp { */ isRequestFromAssistant(projectId: string): Promise; + /** + * Validates whether request is from Google through signature verification. + * Uses Google-Auth-Library to verify authorization token against given + * Google Cloud Project ID. Auth token is given in request header with key, + * "Authorization". + * + * @example + * const app = new ActionsSdkApp({request, response}); + * app.isRequestFromGoogle('nodejs-cloud-test-project-1234') + * .then(() => { + * app.ask('Hey there, thanks for stopping by!'); + * }) + * .catch(err => { + * response.status(400).send(); + * }); + * + * @param projectId Google Cloud Project ID for the Assistant app. + * @return Promise resolving with google-auth-library LoginTicket + * if request is from a valid source, otherwise rejects with the error reason + * for an invalid token. + * @actionssdk + */ + isRequestFromGoogle(projectId: string): Promise; + /** * Gets the request Conversation API version. * diff --git a/types/actions-on-google/assistant-app.d.ts b/types/actions-on-google/assistant-app.d.ts index d33f447a2e..caed5cf6cb 100644 --- a/types/actions-on-google/assistant-app.d.ts +++ b/types/actions-on-google/assistant-app.d.ts @@ -10,58 +10,36 @@ import { ActionPaymentTransactionConfig, Cart, GooglePaymentTransactionConfig, L * @dialogflow */ export enum StandardIntents { - /** - * App fires MAIN intent for queries like [talk to $app]. - */ + /** App fires MAIN intent for queries like [talk to $app]. */ MAIN, - /** - * App fires TEXT intent when action issues ask intent. - */ + /** App fires TEXT intent when action issues ask intent. */ TEXT, - /** - * App fires PERMISSION intent when action invokes askForPermission. - */ + /** App fires PERMISSION intent when action invokes askForPermission. */ PERMISSION, - /** - * App fires OPTION intent when user chooses from options provided. - */ + /** App fires OPTION intent when user chooses from options provided. */ OPTION, - /** - * App fires TRANSACTION_REQUIREMENTS_CHECK intent when action sets up transaction. - */ + /** App fires TRANSACTION_REQUIREMENTS_CHECK intent when action sets up transaction. */ TRANSACTION_REQUIREMENTS_CHECK, - /** - * App fires DELIVERY_ADDRESS intent when action asks for delivery address. - */ + /** App fires DELIVERY_ADDRESS intent when action asks for delivery address. */ DELIVERY_ADDRESS, - /** - * App fires TRANSACTION_DECISION intent when action asks for transaction decision. - */ + /** App fires TRANSACTION_DECISION intent when action asks for transaction decision. */ TRANSACTION_DECISION, - /** - * App fires CONFIRMATION intent when requesting affirmation from user. - */ + /** App fires CONFIRMATION intent when requesting affirmation from user. */ CONFIRMATION, - /** - * App fires DATETIME intent when requesting date/time from user. - */ + /** App fires DATETIME intent when requesting date/time from user. */ DATETIME, - /** - * App fires SIGN_IN intent when requesting sign-in from user. - */ + /** App fires SIGN_IN intent when requesting sign-in from user. */ SIGN_IN, - /** - * App fires NO_INPUT intent when user doesn't provide input. - */ + /** App fires NO_INPUT intent when user doesn't provide input. */ NO_INPUT, - /** - * App fires CANCEL intent when user exits app mid-dialog. - */ + /** App fires CANCEL intent when user exits app mid-dialog. */ CANCEL, - /** - * App fires NEW_SURFACE intent when requesting handoff to a new surface from user. - */ + /** App fires NEW_SURFACE intent when requesting handoff to a new surface from user. */ NEW_SURFACE, + /** App fires REGISTER_UPDATE intent when requesting the user to register for proactive updates. */ + REGISTER_UPDATE, + /** App receives CONFIGURE_UPDATES intent to indicate a custom REGISTER_UPDATE intent should be sent. */ + CONFIGURE_UPDATES } /** @@ -85,6 +63,10 @@ export enum SupportedPermissions { * {@link https://developers.google.com/actions/reference/conversation#Location|Location object}. */ DEVICE_COARSE_LOCATION, + /** + * Confirmation to receive proactive content at any time from the app. + */ + UPDATE } /** @@ -137,6 +119,8 @@ export enum BuiltInArgNames { * New surface value argument. */ NEW_SURFACE, + /** Update registration value argument. */ + REGISTER_UPDATE } /** @@ -144,8 +128,17 @@ export enum BuiltInArgNames { * {@link https://developers.google.com/actions/reference/conversation#Conversation|Conversation object}. * @actionssdk * @dialogflow + * @deprecated Use {@link ConversationTypes} instead. */ -export enum ConversationStages { +export type ConversationStages = ConversationTypes; + +/** + * List of possible conversation types, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Conversation|Conversation object}. + * @actionssdk + * @dialogflow + */ +export enum ConversationTypes { /** * Unspecified conversation state. */ @@ -224,6 +217,13 @@ export enum SignInStatus { ERROR } +/** + * Possible update trigger time context frequencies. + */ +export enum TimeContextFrequency { + DAILY +} + /** * User provided date/time info. */ @@ -277,6 +277,17 @@ export interface User { userName: UserName; /** Unique Oauth2 token. Only available with account linking. */ accessToken: string; + /** + * Timestamp for the last access from the user. + * Retrieve using app.getLastSeen() to get a Date object or null if never seen. + */ + lastSeen: string; + /** + * A string persistent across sessions. + * Retrieved and set using app.userStorage which allows you to store it like an JSON object + * which is abstracted for convenience by the client library. + */ + userStorage: string; } /** @@ -295,6 +306,17 @@ export interface Capability { name: string; } +/** + * Intent Argument. For incoming intents, the argument value can be retrieved + * using {@link AssistantApp#getArgument}. + */ +export interface IntentArgument { + /** Name of the argument. */ + name: string; + /** Text value of the argument. */ + textValue: string; +} + /** * The Actions on Google client library AssistantApp base class. * @@ -313,6 +335,20 @@ export class AssistantApp { */ data: object; + /** + * The data persistent across sessions in JSON format. + * It exists in the same context as getUser().userId + * + * @example + * // Actions SDK + * const app = new ActionsSdkApp({request: request, response: response}); + * app.userStorage.someProperty = 'someValue'; + * // Dialogflow + * const app = new DialogflowApp({request: request, response: response}); + * app.userStorage.someProperty = 'someValue'; + */ + userStorage: object; + /** * List of standard intents that the app provides. * @actionssdk @@ -339,8 +375,17 @@ export class AssistantApp { * {@link https://developers.google.com/actions/reference/conversation#Conversation|Conversation object}. * @actionssdk * @dialogflow + * @deprecated Use {@link ConversationTypes} instead. */ - readonly ConversationStages: typeof ConversationStages; + readonly ConversationStages: typeof ConversationTypes; + + /** + * List of possible conversation types, as defined in the + * {@link https://developers.google.com/actions/reference/conversation#Conversation|Conversation object}. + * @actionssdk + * @dialogflow + */ + readonly ConversationTypes: typeof ConversationTypes; /** * List of surface capabilities supported by the app. @@ -368,6 +413,11 @@ export class AssistantApp { */ readonly Transactions: typeof TransactionValues; + /** + * Possible update trigger time context frequencies. + */ + readonly TimeContextFrequency: typeof TimeContextFrequency; + // --------------------------------------------------------------------------- // Public APIs // --------------------------------------------------------------------------- @@ -477,7 +527,7 @@ export class AssistantApp { * @param permissions Array of permissions App supports, each of * which comes from AssistantApp.SupportedPermissions. * @param dialogState JSON object the app uses to hold dialog state that - * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. * @return A response is sent to Assistant to ask for the user's permission; for any * invalid input, we return null. * @actionssdk @@ -485,6 +535,58 @@ export class AssistantApp { */ askForPermissions(context: string, permissions: string[], dialogState?: object): express.Response | null; + /** + * Prompts the user for permission to send proactive updates at any time. + * + * @example + * const app = new DialogflowApp({request, response}); + * const REQUEST_PERMISSION_ACTION = 'request.permission'; + * const PERMISSION_REQUESTED = 'permission.requested'; + * const SHOW_IMAGE = 'show.image'; + * + * function requestPermission (app) { + * app.askForUpdatePermission('show.image', [ + * { + * name: 'image_to_show', + * textValue: 'image_type_1' + * } + * ]); + * } + * + * function checkPermission (app) { + * if (app.isPermissionGranted()) { + * app.tell(`Great, I'll send an update whenever I notice a change`); + * } else { + * // Response shows that user did not grant permission + * app.tell('Alright, just let me know whenever you need the weather!'); + * } + * } + * + * function showImage (app) { + * showPicture(app.getArgument('image_to_show')); + * } + * + * const actionMap = new Map(); + * actionMap.set(REQUEST_PERMISSION_ACTION, requestPermission); + * actionMap.set(PERMISSION_REQUESTED, checkPermission); + * actionMap.set(SHOW_IMAGE, showImage); + * app.handleRequest(actionMap); + * + * @param intent If using Dialogflow, the action name of the intent + * to be triggered when the update is received. If using Actions SDK, the + * intent name to be triggered when the update is received. + * @param intentArguments The necessary arguments + * to fulfill the intent triggered on update. These can be retrieved using + * {@link AssistantApp#getArgument}. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. + * @return A response is sent to Assistant to ask for the user's permission; for any + * invalid input, we return null. + * @actionssdk + * @dialogflow + */ + askForUpdatePermission(intent: string, intentArguments: IntentArgument[], dialogState?: object): express.Response | null; + /** * Checks whether user is in transactable state. * @@ -520,7 +622,7 @@ export class AssistantApp { * options and order options. Optional if order has no payment or * delivery. * @param dialogState JSON object the app uses to hold dialog state that - * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. * @return HTTP response. * @actionssdk * @dialogflow @@ -562,7 +664,7 @@ export class AssistantApp { * transactionConfig Configuration for the transaction. Includes payment * options and order options. * @param dialogState JSON object the app uses to hold dialog state that - * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. * @return HTTP response * @dialogflow */ @@ -737,7 +839,7 @@ export class AssistantApp { * query for an affirmative or negative response. If undefined or null, * Google will use a generic yes/no prompt. * @param dialogState JSON object the app uses to hold dialog state that - * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. * @return HTTP response. * @actionssdk * @dialogflow @@ -782,7 +884,7 @@ export class AssistantApp { * time if not provided by user. If undefined or null, Google will use a * generic prompt. * @param dialogState JSON object the app uses to hold dialog state that - * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. * @return HTTP response. * @actionssdk * @dialogflow @@ -795,11 +897,6 @@ export class AssistantApp { * Retrieve the access token in subsequent intents using * app.getUser().accessToken. * - * Note: Currently this API requires enabling the app for Transactions APIs. - * To do this, fill out the App Info section of the Actions Console project - * and check the box indicating the use of Transactions under "Privacy and - * consent". - * * @example * const app = new DialogflowApp({ request, response }); * const WELCOME_INTENT = 'input.welcome'; @@ -824,7 +921,7 @@ export class AssistantApp { * app.handleRequest(actionMap); * * @param dialogState JSON object the app uses to hold dialog state that - * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. * @return HTTP response. * @actionssdk * @dialogflow @@ -872,13 +969,53 @@ export class AssistantApp { * @param capabilities The list of capabilities required in * the surface. * @param dialogState JSON object the app uses to hold dialog state that - * will be circulated back by Assistant. Used in {@link ActionsSdkAssistant}. + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. * @return HTTP response. * @dialogflow * @actionssdk */ askForNewSurface(context: string, notificationTitle: string, capabilities: SurfaceCapabilities[], dialogState?: object): express.Response | null; + /** + * Requests the user to register for daily updates. + * + * @example + * const app = new DialogflowApp({ request, response }); + * const WELCOME_INTENT = 'input.welcome'; + * const SHOW_IMAGE = 'show.image'; + * + * function welcomeIntent (app) { + * app.askToRegisterDailyUpdate('show.image', [ + * { + * name: 'image_to_show', + * textValue: 'image_type_1' + * } + * ]); + * } + * + * function showImage (app) { + * showPicture(app.getArgument('image_to_show')); + * } + * + * const actionMap = new Map(); + * actionMap.set(WELCOME_INTENT, welcomeIntent); + * actionMap.set(SHOW_IMAGE, showImage); + * app.handleRequest(actionMap); + * + * @param intent If using Dialogflow, the action name of the intent + * to be triggered when the update is received. If using Actions SDK, the + * intent name to be triggered when the update is received. + * @param intentArguments The necessary arguments + * to fulfill the intent triggered on update. These can be retrieved using + * {@link AssistantApp#getArgument}. + * @param dialogState JSON object the app uses to hold dialog state that + * will be circulated back by Assistant. Used in {@link ActionsSdkApp}. + * @return HTTP response. + * @dialogflow + * @actionssdk + */ + askToRegisterDailyUpdate(intent: string, intentArguments: IntentArgument[], dialogState?: object): express.Response | null; + /** * Gets the {@link User} object. * The user object contains information about the user, including @@ -945,6 +1082,18 @@ export class AssistantApp { */ getUserLocale(): string; + /** + * Get the user's last seen time as a Date object. + * Not supported in V1. + * + * @example + * const app = new DialogflowApp({request, response}); + * const lastSeen = app.getLastSeen(); + * + * @return User's last seen date or null if never seen + */ + getLastSeen(): Date | null; + /** * If granted permission to device's location in previous intent, returns device's * location (see {@link AssistantApp#askForPermissions|askForPermissions}). @@ -1225,6 +1374,16 @@ export class AssistantApp { */ isFinalReprompt(): boolean; + /** + * Returns true if user accepted update registration request. Used with + * {@link AssistantApp#askToRegisterDailyUpdate} + * + * @return True if user accepted update registration request. + * @dialogflow + * @actionssdk + */ + isUpdateRegistered(): boolean; + // --------------------------------------------------------------------------- // Response Builders // --------------------------------------------------------------------------- diff --git a/types/actions-on-google/index.d.ts b/types/actions-on-google/index.d.ts index 5f7baba3b8..378604411f 100644 --- a/types/actions-on-google/index.d.ts +++ b/types/actions-on-google/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for actions-on-google 1.5 +// Type definitions for actions-on-google 1.6 // Project: https://github.com/actions-on-google/actions-on-google-nodejs // Definitions by: Joel Hegg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped diff --git a/types/actions-on-google/response-builder.d.ts b/types/actions-on-google/response-builder.d.ts index 1e11984551..5b6e3d7522 100644 --- a/types/actions-on-google/response-builder.d.ts +++ b/types/actions-on-google/response-builder.d.ts @@ -70,6 +70,24 @@ export interface OptionInfo { synonyms: string[]; } +export interface StructuredResponse { + orderUpdate: OrderUpdate; +} + +export interface RichResponseItemBasicCard { + basicCard: BasicCard; +} + +export interface RichResponseItemSimpleResponse { + simpleResponse: SimpleResponse; +} + +export interface RichResponseItemStructuredResponse { + structuredResponse: StructuredResponse; +} + +export type RichResponseItem = RichResponseItemBasicCard | RichResponseItemSimpleResponse | RichResponseItemStructuredResponse; + /** * Class for initializing and constructing Rich Responses with chainable interface. */ @@ -85,7 +103,7 @@ export class RichResponse { * Ordered list of either SimpleResponse objects or BasicCard objects. * First item must be SimpleResponse. There can be at most one card. */ - items: Array; + items: RichResponseItem[]; /** * Ordered list of text suggestions to display. Optional. diff --git a/types/actions-on-google/transactions.d.ts b/types/actions-on-google/transactions.d.ts index 8cc26165db..b4a4285fe9 100644 --- a/types/actions-on-google/transactions.d.ts +++ b/types/actions-on-google/transactions.d.ts @@ -25,8 +25,8 @@ export interface Price { * Order rejection info. */ export interface RejectionInfo { - /** One of Transaction.RejectionType. */ - type: RejectionType; + /** One of Transaction.ReasonType. */ + type: ReasonType; /** Reason for the order rejection. */ reason: string; } @@ -51,26 +51,16 @@ export interface CancellationInfo { * Order transit info. */ export interface TransitInfo { - /** UTC timestamp of the transit update. */ - updatedTime: { - /** Seconds since Unix epoch. */ - seconds: number; - /** Partial seconds since Unix epoch. */ - nanos?: number; - }; + /** UTC timestamp of the transit update as an RFC 3339 string. */ + updatedTime: string; } /** * Order fulfillment info. */ export interface FulfillmentInfo { - /** UTC timestamp of the fulfillment update. */ - deliveryTime: { - /** Seconds since Unix epoch. */ - seconds: number; - /** Partial seconds since Unix epoch. */ - nanos?: number; - }; + /** UTC timestamp of the fulfillment update as an RFC 3339 string. */ + deliveryTime: string; } /** @@ -140,7 +130,7 @@ export interface Location { */ export interface TransactionDecision { /** One of Transactions.ConfirmationDecision. */ - userDecision: ConfirmationDecision; + userDecision: TransactionUserDecision; checkResult: { /** One of Transactions.ResultType. */ resultType: ResultType; @@ -175,32 +165,61 @@ export interface TransactionDecision { export const TransactionValues: { /** List of transaction card networks available when paying with Google. */ readonly CardNetwork: typeof CardNetwork; + /** + * List of possible item types. + * @deprecated Use {@link TransactionValues.LineItemType} instead. + */ + readonly ItemType: typeof LineItemType; /** List of possible item types. */ - readonly ItemType: typeof ItemType; + readonly LineItemType: typeof LineItemType; /** List of price types. */ readonly PriceType: typeof PriceType; /** List of possible item types. */ readonly PaymentType: typeof PaymentType; /** List of customer information properties that can be requested. */ readonly CustomerInfoProperties: typeof CustomerInfoProperties; + /** + * List of possible order confirmation user decisions + * @deprecated Use {@link TransactionValues.TransactionUserDecision} instead. + */ + readonly ConfirmationDecision: typeof TransactionUserDecision; /** List of possible order confirmation user decisions */ - readonly ConfirmationDecision: typeof ConfirmationDecision; + readonly TransactionUserDecision: typeof TransactionUserDecision; /** List of possible order states. */ readonly OrderState: typeof OrderState; + /** + * List of possible actions to take on the order. + * @deprecated Use {@link TransactionValues.ActionType} instead. + */ + readonly OrderAction: typeof ActionType; /** List of possible actions to take on the order. */ - readonly OrderAction: typeof OrderAction; + readonly ActionType: typeof ActionType; + /** + * List of possible types of order rejection. + * @deprecated Use {@link TransactionValues.ReasonType} instead. + */ + readonly RejectionType: typeof ReasonType; /** List of possible types of order rejection. */ - readonly RejectionType: typeof RejectionType; + readonly ReasonType: typeof ReasonType; /** List of possible order state objects. */ readonly OrderStateInfo: typeof OrderStateInfo; /** List of possible order transaction requirements check result types. */ readonly ResultType: typeof ResultType; /** List of possible user decisions to give delivery address. */ - readonly DeliveryAddressDecision: typeof DeliveryAddressDecision; + readonly DeliveryAddressDecision: typeof DeliveryAddressUserDecision; + /** List of possible user decisions to give delivery address. */ + readonly DeliveryAddressUserDecision: typeof DeliveryAddressUserDecision; + /** + * List of possible order location types. + * @deprecated Use {@link TransactionValues.OrderLocationType} instead. + */ + readonly LocationType: typeof OrderLocationType; /** List of possible order location types. */ - readonly LocationType: typeof LocationType; + readonly OrderLocationType: typeof OrderLocationType; /** List of possible order time types. */ readonly TimeType: typeof TimeType; + /** List of possible tokenization types for the payment method */ + readonly PaymentMethodTokenizationType: typeof PaymentMethodTokenizationType; }; /** @@ -235,8 +254,14 @@ export enum CardNetwork { /** * List of possible item types. + * @deprecated Use {@link TransactionValues.LineItemType} instead. */ -export enum ItemType { +export type ItemType = LineItemType; + +/** + * List of possible item types. + */ +export enum LineItemType { /** * Unspecified. */ @@ -323,13 +348,24 @@ export enum PaymentType { * List of customer information properties that can be requested. */ export enum CustomerInfoProperties { + CUSTOMER_INFO_PROPERTY_UNSPECIFIED, EMAIL } /** * List of possible order confirmation user decisions + * @deprecated Use {@link TransactionValues.TransactionUserDecision} instead. */ -export enum ConfirmationDecision { +export type ConfirmationDecision = TransactionUserDecision; + +/** + * List of possible order confirmation user decisions + */ +export enum TransactionUserDecision { + /** + * Unspecified user decision. + */ + UNKNOWN_USER_DECISION, /** * Order was approved by user. */ @@ -353,6 +389,10 @@ export enum ConfirmationDecision { * List of possible order states. */ export enum OrderState { + /** + * Order was created at the integrator's system. + */ + CREATED, /** * Order was rejected. */ @@ -381,8 +421,18 @@ export enum OrderState { /** * List of possible actions to take on the order. + * @deprecated Use {@link TransactionValues.ActionType} instead. */ -export enum OrderAction { +export type OrderAction = ActionType; + +/** + * List of possible actions to take on the order. + */ +export enum ActionType { + /** + * Unknown action. + */ + UNKNOWN, /** * View details. */ @@ -418,13 +468,23 @@ export enum OrderAction { /** * Review. */ - REVIEW + REVIEW, + /** + * Customer Service. + */ + CUSTOMER_SERVICE } /** * List of possible types of order rejection. + * @deprecated Use {@link TransactionValues.ReasonType} instead. */ -export enum RejectionType { +export type RejectionType = ReasonType; + +/** + * List of possible types of order rejection. + */ +export enum ReasonType { /** * Unknown */ @@ -494,8 +554,14 @@ export enum ResultType { /** * List of possible user decisions to give delivery address. + * @deprecated Use {@link TransactionValues.DeliveryAddressUserDecision} instead. */ -export enum DeliveryAddressDecision { +export type DeliveryAddressDecision = DeliveryAddressUserDecision; + +/** + * List of possible user decisions to give delivery address. + */ +export enum DeliveryAddressUserDecision { /** * Unknown. */ @@ -512,8 +578,14 @@ export enum DeliveryAddressDecision { /** * List of possible order location types. + * @deprecated Use {@link TransactionValues.OrderLocationType} instead. */ -export enum LocationType { +export type LocationType = OrderLocationType; + +/** + * List of possible order location types. + */ +export enum OrderLocationType { /** * Unknown. */ @@ -533,7 +605,11 @@ export enum LocationType { /** * Destination of the order. */ - DESTINATION + DESTINATION, + /** + * Pick up location of the order. + */ + PICK_UP } /** @@ -558,6 +634,20 @@ export enum TimeType { RESERVATION_SLOT } +/** + * List of possible tokenization types for the payment method + */ +export enum PaymentMethodTokenizationType { + /** + * Unspecified tokenization type. + */ + UNSPECIFIED_TOKENIZATION_TYPE, + /** + * Use external payment gateway tokenization API to tokenize selected payment method. + */ + PAYMENT_GATEWAY +} + /** * Class for initializing and constructing Order with chainable interface. */ @@ -655,11 +745,11 @@ export class Order { /** * Adds an associated location to the order. Up to 2 locations can be added. * - * @param type One of TransactionValues.LocationType. + * @param type One of TransactionValues.OrderLocationType. * @param location Location to add. * @return Returns current constructed Order. */ - addLocation(type: LocationType, location: Location): Order; + addLocation(type: OrderLocationType, location: Location): Order; /** * Sets an associated time to the order. @@ -780,9 +870,9 @@ export class LineItem { image?: Image; /** - * Type of the item. One of TransactionValues.ItemType. + * Type of the item. One of TransactionValues.LineItemType. */ - type?: ItemType; + type?: LineItemType; /** * Quantity of the item. @@ -834,10 +924,10 @@ export class LineItem { /** * Set the type of the item. * - * @param type Type of the item. One of TransactionValues.ItemType. + * @param type Type of the item. One of TransactionValues.LineItemType. * @return Returns current constructed LineItem. */ - setType(type: ItemType): LineItem; + setType(type: LineItemType): LineItem; /** * Set the quantity of the item. @@ -898,9 +988,9 @@ export class OrderUpdate { lineItemUpdates: object; /** - * UTC timestamp of the order update. + * UTC timestamp of the order update as an RFC 3339 string. */ - updateTime?: object; + updateTime?: string; /** * Actionable items presented to the user to manage the order. @@ -946,7 +1036,7 @@ export class OrderUpdate { * Set the update time of the order. * * @param seconds Seconds since Unix epoch. - * @param nanos Partial time units. + * @param nanos Partial time units. It is rounded to the nearest millisecond. * @return Returns current constructed OrderUpdate. */ setUpdateTime(seconds: number, nanos?: number): OrderUpdate; @@ -974,12 +1064,12 @@ export class OrderUpdate { /** * Adds an actionable item for the user to manage the order. * - * @param type One of TransactionValues.OrderActions. + * @param type One of TransactionValues.ActionType. * @param label Button label. * @param url URL to open when button is clicked. * @return Returns current constructed OrderUpdate. */ - addOrderManagementAction(type: OrderAction, label: string, url: string): OrderUpdate; + addOrderManagementAction(type: ActionType, label: string, url: string): OrderUpdate; /** * Adds a single price update for a particular line item in the order. From b1fbf97b328ce5b0287801fada96907ccabb87f7 Mon Sep 17 00:00:00 2001 From: Matt Bishop Date: Wed, 15 Nov 2017 16:01:05 -0800 Subject: [PATCH 044/201] Expand parameter types to match js.spec library. Remove un-exported spec.finite --- types/js.spec/index.d.ts | 12 ++++++------ types/js.spec/js.spec-tests.ts | 8 ++++++++ 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/types/js.spec/index.d.ts b/types/js.spec/index.d.ts index 735de40976..764bfa845e 100644 --- a/types/js.spec/index.d.ts +++ b/types/js.spec/index.d.ts @@ -71,7 +71,7 @@ export interface Problem { * @param value the value to test * @returns true if valid */ -export function valid(spec: Spec, value: any): boolean; +export function valid(spec: spec.SpecInput, value: any): boolean; /** * Returns the conformed value to this spec. @@ -79,7 +79,7 @@ export function valid(spec: Spec, value: any): boolean; * @param value the value to test * @returns if the value does not conform to the spec, or the conformed value if it does. */ -export function conform(spec: Spec, value: any): any; +export function conform(spec: spec.SpecInput, value: any): any; /** * Like explain(), but returns Problems array. @@ -87,28 +87,28 @@ export function conform(spec: Spec, value: any): any; * @param value the value to test * @returns list of problems or null if none */ -export function explainData(spec: Spec, value: any): Problem[]; +export function explainData(spec: spec.SpecInput, value: any): Problem[]; /** * Prints, to the console, reasons why the value did not conform to this spec. * @param spec the spec to test with * @param value the value to test */ -export function explain(spec: Spec, value: any): void; +export function explain(spec: spec.SpecInput, value: any): void; /** * Returns a multiline string with reasons why the value did not conform to this spec. * @param spec the spec to test with * @param value the value to test */ -export function explainStr(spec: Spec, value: any): string; +export function explainStr(spec: spec.SpecInput, value: any): string; /** * Tests if a value conforms to a spec, and if not, throws an Error. * @param spec the spec to test with * @param value the value to test */ -export function assert(spec: Spec, value: any): void; +export function assert(spec: spec.SpecInput, value: any): void; export namespace symbol { /** diff --git a/types/js.spec/js.spec-tests.ts b/types/js.spec/js.spec-tests.ts index 8bb9611e87..e1d7703f76 100644 --- a/types/js.spec/js.spec-tests.ts +++ b/types/js.spec/js.spec-tests.ts @@ -7,20 +7,28 @@ const name: string = spec.name; const options: object = spec.options; const isValid: boolean = S.valid(S.spec.boolean, true); +S.valid((value) => true, "a value"); const result = S.conform(S.spec.map("dancing", {field: S.spec.string}), "not a map"); +S.conform((value) => true, "a value"); const problems: S.Problem[] = S.explainData(S.spec.int, "not a number"); +S.explainData((value) => true, "a value"); const {path, via, value, predicate}: {path: string[], via: string[], value: any, predicate: S.Predicate} = problems[0]; const problemStr: string = S.explainStr(S.spec.even, 3); +S.explainStr((value) => true, "a value"); // $ExpectType void S.explain(S.spec.positive, true); +// $ExpectType void +S.explain((value) => true, "a value"); // $ExpectType void S.assert(S.spec.string, "things"); +// $ExpectType void +S.assert((value) => true, "a value"); const symbols: symbol[] = [S.symbol.count, S.symbol.invalid, S.symbol.maxCount, S.symbol.minCount, S.symbol.optional]; From b9eb2feb3d63edd08969005a93c88e15944868b3 Mon Sep 17 00:00:00 2001 From: Roberto Ritger Date: Wed, 15 Nov 2017 15:46:37 -0800 Subject: [PATCH 045/201] A-Frame register custom geometry fix --- types/aframe/aframe-tests.ts | 12 ++++++++++-- types/aframe/index.d.ts | 13 +++++++++---- 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/types/aframe/aframe-tests.ts b/types/aframe/aframe-tests.ts index 439d314f4a..5af66a09d1 100644 --- a/types/aframe/aframe-tests.ts +++ b/types/aframe/aframe-tests.ts @@ -1,5 +1,4 @@ // Global - const threeCamera = new AFRAME.THREE.Camera(); AFRAME.TWEEN.Easing; @@ -42,9 +41,18 @@ entity.addEventListener('child-detached', (event) => { const Component = AFRAME.registerComponent('test', {}); // Scene - const scene = document.querySelector('a-scene'); scene.hasLoaded; // System const system = scene.systems['systemName']; + +// Register Custom Geometry +AFRAME.registerGeometry('a-test-geometry', { + schema: { + groupIndex: { default: 0 } + }, + init(data) { + this.geometry = new THREE.Geometry(); + } +}); diff --git a/types/aframe/index.d.ts b/types/aframe/index.d.ts index f1f5cd7a20..803318a754 100644 --- a/types/aframe/index.d.ts +++ b/types/aframe/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for AFRAME 0.5 +// Type definitions for AFRAME 0.7 // Project: https://aframe.io/ // Definitions by: Paul Shannon +// Roberto Ritger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -40,7 +41,7 @@ declare namespace AFrame { primitives: { [ key: string ]: Entity }; registerComponent(name: string, component: ComponentDefinition): ComponentConstructor; registerElement(name: string, element: ANode): void; - registerGeometry(name: string, geometery: THREE.Geometry): Geometry; + registerGeometry(name: string, geometry: GeometryDefinition): Geometry; registerPrimitive(name: string, primitive: PrimitiveDefinition): void; registerShader(name: string, shader: any): void; registerSystem(name: string, definition: SystemDefinition): void; @@ -101,7 +102,7 @@ declare namespace AFrame { name: string; schema: Schema; - init(): void; + init(data?: any): void; pause(): void; play(): void; remove(): void; @@ -124,7 +125,7 @@ declare namespace AFrame { multiple?: boolean; schema?: Schema; - init?(): void; + init?(data?: any): void; pause?(): void; play?(): void; remove?(): void; @@ -222,6 +223,10 @@ declare namespace AFrame { [ key: string ]: any; } + interface GeometryDefinition extends ComponentDefinition { + geometry?: THREE.Geometry; + } + interface GeometryDescriptor { Geometry: Geometry; schema: Schema; From 3bb5a9fc5fc60fd6fb2c989b8f22fd1c51eb12ff Mon Sep 17 00:00:00 2001 From: takuya hatadani Date: Thu, 16 Nov 2017 15:59:29 +0900 Subject: [PATCH 046/201] fix CKEDITOR.config add: clipboard_notificationDuration colorButton_colorsPerRow colorButton_enableAutomatic colorButton_normalizeBackground --- types/ckeditor/index.d.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/types/ckeditor/index.d.ts b/types/ckeditor/index.d.ts index f26a08a725..20882269fd 100644 --- a/types/ckeditor/index.d.ts +++ b/types/ckeditor/index.d.ts @@ -602,13 +602,17 @@ declare namespace CKEDITOR { browserContextMenuOnCtrl?: boolean; clipboard_defaultContentType?: string; // html | text + clipboard_notificationDuration?: number; codeSnippet_codeClass?: string; codeSnippet_languages?: Object; coceSnippet_theme?: string; colorButton_backStyle?: config.styleObject; colorButton_colors?: string; + colorButton_colorsPerRow?: number; + colorButton_enableAutomatic?: boolean; colorButton_enableMore?: boolean; colorButton_foreStyle?: config.styleObject; + colorButton_normalizeBackground?: boolean; contentsCss?: string | string[]; contentsLangDirection?: string; contentsLanguage?: string; From 3fc0f813fa608f791bd751bb511646b990e665d8 Mon Sep 17 00:00:00 2001 From: Jiaren Liu Date: Thu, 16 Nov 2017 15:17:45 +0800 Subject: [PATCH 047/201] add `request.ip` --- types/koa/index.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/types/koa/index.d.ts b/types/koa/index.d.ts index d46920bf07..d4f339aa32 100644 --- a/types/koa/index.d.ts +++ b/types/koa/index.d.ts @@ -136,6 +136,11 @@ declare interface ContextDelegatedRequest { */ secure: boolean; + /** + * Request remote address. Supports X-Forwarded-For when app.proxy is true. + */ + ip: string; + /** * When `app.proxy` is `true`, parse * the "X-Forwarded-For" ip address list. From ae48e5684b31a05782cfa0dad44287cc83d896f0 Mon Sep 17 00:00:00 2001 From: Zhao Lei Date: Thu, 16 Nov 2017 16:16:12 +0800 Subject: [PATCH 048/201] Add files via upload @types/websocket interfaces updated. --- types/websocket/index.d.ts | 11 ++--- types/websocket/websocket-tests.ts | 64 +++++++++++++++++++++++++++++- 2 files changed, 68 insertions(+), 7 deletions(-) diff --git a/types/websocket/index.d.ts b/types/websocket/index.d.ts index 3b41a5f6da..ab4e453e80 100644 --- a/types/websocket/index.d.ts +++ b/types/websocket/index.d.ts @@ -1,7 +1,8 @@ // Type definitions for websocket // Project: https://github.com/theturtle32/WebSocket-Node // Definitions by: Paul Loyd , -// Kay Schecker +// Kay Schecker , +// Zhao Lei // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -563,10 +564,10 @@ declare class client extends events.EventEmitter { * any scripting content that caused the connection to be requested. * @param requestUrl should be a standard websocket url */ - connect(requestUrl: url.Url, protocols?: string[], origin?: string, headers?: any[]): void; - connect(requestUrl: string, protocols?: string[], origin?: string, headers?: any[]): void; - connect(requestUrl: url.Url, protocols?: string, origin?: string, headers?: any[]): void; - connect(requestUrl: string, protocols?: string, origin?: string, headers?: any[]): void; + connect(requestUrl: url.Url, protocols?: string[], origin?: string, headers?: any[], extraRequestOptions?: http.RequestOptions): void; + connect(requestUrl: string, protocols?: string[], origin?: string, headers?: any[], extraRequestOptions?: http.RequestOptions): void; + connect(requestUrl: url.Url, protocols?: string, origin?: string, headers?: any[], extraRequestOptions?: http.RequestOptions): void; + connect(requestUrl: string, protocols?: string, origin?: string, headers?: any[], extraRequestOptions?: http.RequestOptions): void; // Events on(event: string, listener: () => void): this; diff --git a/types/websocket/websocket-tests.ts b/types/websocket/websocket-tests.ts index 5ecee0080d..3044f9bf7d 100644 --- a/types/websocket/websocket-tests.ts +++ b/types/websocket/websocket-tests.ts @@ -1,8 +1,10 @@ import websocket = require('websocket'); import http = require('http'); +import os = require('os'); -{ +/* +function serverTest() { var server = http.createServer((req, res) => { console.log((new Date()) + ' Received request for ' + req.url); res.writeHead(404); @@ -88,7 +90,7 @@ import http = require('http'); wsRouter.unmount(/^route\/[a-zA-Z]+$/, 'protocol'); } -{ +function clientTest() { var WebSocketClient = require('websocket').client; var client = new WebSocketClient(); @@ -124,4 +126,62 @@ import http = require('http'); }); client.connect('ws://localhost:8080/', 'echo-protocol'); +}*/ + +function getLocalIpArray(): Array { + var interfaces: any = os.networkInterfaces(); + var ipArray: Array = []; + for (var dev in interfaces) { + for (var i = 0; i < interfaces[dev].length; i++) { + if (interfaces[dev][i].family == "IPv4" && interfaces[dev][i].internal == false) { + ipArray.push(interfaces[dev][i].address); + } + } + } + return ipArray; +} + +function serverTest2() { + var server = http.createServer((req, rsp) => { + rsp.writeHead(200); + rsp.end("Hello, world!"); + }); + server.listen(8888); + + var wsServer = new websocket.server({ + httpServer: server, + autoAcceptConnections: true + }); + + wsServer.on("connect", (conn) => { + conn.sendUTF(`Your IP Address is - ${conn.remoteAddress}`) + }); +} + +function clientTest2() { + var ipArray = getLocalIpArray(); + + var client = new websocket.client(); + client.on("connect", (conn) => { + console.log(`on connect`); + conn.on("frame", (frame) => { + console.log(`on frame - ${frame.binaryPayload.toString()}`); + }); + conn.on("message", (data) => { + console.log(`on message - ${data.utf8Data}`); + }); + }); + client.on("connectFailed", (err) => { + console.log(`on failed: ${err}`); + }); + client.connect(`ws://${ipArray[0]}:8888`, undefined, undefined, undefined, { + localAddress: ipArray[0] + }); + +} + +{ + console.log(`websocket test start.`); + serverTest2(); + clientTest2(); } From adc1ffa1a163ebc866f8431e2324dcd69ee87f20 Mon Sep 17 00:00:00 2001 From: Marius Agur Pedersen Date: Thu, 16 Nov 2017 14:20:51 +0100 Subject: [PATCH 049/201] Added getFormContext to v8 as it should be available there as well. --- types/xrm/v8/index.d.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/types/xrm/v8/index.d.ts b/types/xrm/v8/index.d.ts index b46b92ffa1..1145838256 100644 --- a/types/xrm/v8/index.d.ts +++ b/types/xrm/v8/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Microsoft Dynamics xRM API 8.2 // Project: http://www.microsoft.com/en-us/download/details.aspx?id=44567 -// Definitions by: David Berry , Matt Ngan , Markus Mauch , Daryl LaBar , Tully H +// Definitions by: David Berry , Matt Ngan , Markus Mauch , Daryl LaBar , Tully H , Marius Agur // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 @@ -1101,6 +1101,18 @@ declare namespace Xrm { * * @remarks Used to pass values between handlers of an event. */ + getFormContext(): Page; + + /** + * Gets the shared variable with the specified key. + * + * @param T Generic type parameter. + * @param key The key. + * + * @return The shared variable. + * + * @remarks Used to pass values between handlers of an event. + */ getSharedVariable(key: string): T; /** From 43c84d9bc391ed51f92f1c3792ed37dad924b641 Mon Sep 17 00:00:00 2001 From: Marius Agur Pedersen Date: Thu, 16 Nov 2017 14:37:56 +0100 Subject: [PATCH 050/201] Changed contributers formatting to stay compliant with max line length and improve readability --- types/xrm/v8/index.d.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/types/xrm/v8/index.d.ts b/types/xrm/v8/index.d.ts index 1145838256..65d1904a8c 100644 --- a/types/xrm/v8/index.d.ts +++ b/types/xrm/v8/index.d.ts @@ -1,6 +1,11 @@ // Type definitions for Microsoft Dynamics xRM API 8.2 // Project: http://www.microsoft.com/en-us/download/details.aspx?id=44567 -// Definitions by: David Berry , Matt Ngan , Markus Mauch , Daryl LaBar , Tully H , Marius Agur +// Definitions by: David Berry +// Matt Ngan +// Markus Mauch +// Daryl LaBar +// Tully H +// Marius Agur // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 From cf1b88c2d368ee93cb1a121436c2bc3c79c31745 Mon Sep 17 00:00:00 2001 From: Michael Randolph Date: Thu, 16 Nov 2017 11:17:50 -0500 Subject: [PATCH 051/201] Update passport-facebook-token types * Duplicate imports are no longer necessary with this change --- types/passport-facebook-token/index.d.ts | 19 +++++++++++-------- .../passport-facebook-token-tests.ts | 18 +++++++++--------- 2 files changed, 20 insertions(+), 17 deletions(-) diff --git a/types/passport-facebook-token/index.d.ts b/types/passport-facebook-token/index.d.ts index 9013910ee1..9877b84527 100644 --- a/types/passport-facebook-token/index.d.ts +++ b/types/passport-facebook-token/index.d.ts @@ -7,15 +7,17 @@ import * as passport from 'passport'; import * as express from 'express'; -declare class Strategy implements passport.Strategy { - constructor(options: Strategy.StrategyOptionsWithRequest, verify: Strategy.VerifyFunctionWithRequest) - constructor(options: Strategy.StrategyOptions, verify: Strategy.VerifyFunction); +declare namespace PassportFacebookToken { + interface StrategyStatic { + new(options: StrategyOptionsWithRequest, verify: VerifyFunctionWithRequest): StrategyInstance; + new(options: StrategyOptions, verify: VerifyFunction): StrategyInstance; + } - name: string; - authenticate: (req: express.Request, options?: any) => void; -} + interface StrategyInstance { + name: string; + authenticate: (req: express.Request, options?: any) => void; + } -declare namespace Strategy { interface ValueObject { value: string; } @@ -55,4 +57,5 @@ declare namespace Strategy { type VerifyFunctionWithRequest = (req: express.Request, accessToken: string, refreshToken: string, profile: Profile, done: (error: any, user?: any, info?: any) => void) => void; } -export = Strategy; +declare const PassportFacebookToken: PassportFacebookToken.StrategyStatic; +export = PassportFacebookToken; diff --git a/types/passport-facebook-token/passport-facebook-token-tests.ts b/types/passport-facebook-token/passport-facebook-token-tests.ts index cb2f078e88..c926748286 100644 --- a/types/passport-facebook-token/passport-facebook-token-tests.ts +++ b/types/passport-facebook-token/passport-facebook-token-tests.ts @@ -1,8 +1,6 @@ import * as express from 'express'; import * as passport from 'passport'; -import * as FacebookStrategy from 'passport-facebook-token'; -// tslint:disable-next-line:no-duplicate-imports -import { StrategyOptions, StrategyOptionsWithRequest, VerifyFunction, VerifyFunctionWithRequest, Profile } from 'passport-facebook-token'; +import * as PassportFacebookToken from 'passport-facebook-token'; const User = { findOrCreate(id: string, provider: string, callback: (err: any, user: any) => void): void { @@ -10,18 +8,19 @@ const User = { } }; -const options: StrategyOptions = { +const options: PassportFacebookToken.StrategyOptions = { clientID: 'TEST_CLIENT_ID', clientSecret: 'TEST_CLIENT_SECRET' }; -const optionsWithRequest: StrategyOptionsWithRequest = { +const optionsWithRequest: PassportFacebookToken.StrategyOptionsWithRequest = { clientID: 'TEST_CLIENT_ID', clientSecret: 'TEST_CLIENT_SECRET', passReqToCallback: true }; -const verify: VerifyFunction = (accessToken: string, refreshToken: string, profile: Profile, done: (err: any, user?: any, info?: any) => void) => { +const verify: PassportFacebookToken.VerifyFunction = + (accessToken: string, refreshToken: string, profile: PassportFacebookToken.Profile, done: (err: any, user?: any, info?: any) => void) => { User.findOrCreate(profile.id, profile.provider, (err, user) => { if (err) { done(err); @@ -30,7 +29,8 @@ const verify: VerifyFunction = (accessToken: string, refreshToken: string, profi }); }; -const verifyWithRequest: VerifyFunctionWithRequest = (req: express.Request, accessToken: string, refreshToken: string, profile: Profile, done: (err: any, user?: any, info?: any) => void) => { +const verifyWithRequest: PassportFacebookToken.VerifyFunctionWithRequest = + (req: express.Request, accessToken: string, refreshToken: string, profile: PassportFacebookToken.Profile, done: (err: any, user?: any, info?: any) => void) => { User.findOrCreate(profile.id, profile.provider, (err, user) => { if (err) { done(err); @@ -39,5 +39,5 @@ const verifyWithRequest: VerifyFunctionWithRequest = (req: express.Request, acce }); }; -passport.use(new FacebookStrategy(options, verify)); -passport.use(new FacebookStrategy(optionsWithRequest, verifyWithRequest)); +passport.use(new PassportFacebookToken(options, verify)); +passport.use(new PassportFacebookToken(optionsWithRequest, verifyWithRequest)); From 4a668e8310779350b10f2af5f65d9fb9fcfdc8c0 Mon Sep 17 00:00:00 2001 From: Marius Agur Pedersen Date: Thu, 16 Nov 2017 19:22:56 +0100 Subject: [PATCH 052/201] Fixed trailing white space --- types/xrm/v8/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/xrm/v8/index.d.ts b/types/xrm/v8/index.d.ts index 65d1904a8c..472fbfdca6 100644 --- a/types/xrm/v8/index.d.ts +++ b/types/xrm/v8/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Microsoft Dynamics xRM API 8.2 // Project: http://www.microsoft.com/en-us/download/details.aspx?id=44567 -// Definitions by: David Berry +// Definitions by: David Berry // Matt Ngan // Markus Mauch // Daryl LaBar From 13d444d6d1062677b0be2ee1d6a0ac821d850f4f Mon Sep 17 00:00:00 2001 From: simonxca Date: Thu, 16 Nov 2017 11:22:14 -0800 Subject: [PATCH 053/201] Add generic type for lean method Fixes #20874 --- types/mongoose/index.d.ts | 1 + types/mongoose/mongoose-tests.ts | 10 ++++++++++ 2 files changed, 11 insertions(+) diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index b819e37ad9..3c11000c64 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -1623,6 +1623,7 @@ declare module "mongoose" { * @param bool defaults to true */ lean(bool?: boolean): Query; + lean(bool?: boolean): Query; /** Specifies the maximum number of documents the query will return. Cannot be used with distinct() */ limit(val: number): this; diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index 1416d12332..aad019c021 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -1355,6 +1355,16 @@ MongoModel.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {} MongoModel.findOne({ type: 'iphone' }, 'name', { lean: true }, cb); MongoModel.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(cb); MongoModel.findOne({ type: 'iphone' }).select('name').lean().exec(cb); +interface ModelUser { + _id: any; + name: string; + abctest: string; +} +MongoModel.findOne({ type: 'iphone' }).select('name').lean().exec().then(function(doc) { + doc._id; + doc.name; + doc.abctest; +}); MongoModel.findOneAndRemove({}, {}, cb); MongoModel.findOneAndRemove({}, {}); MongoModel.findOneAndRemove({}, cb); From c7bd1c3ebf4371f3d911b59d50a26f0ea4fd813b Mon Sep 17 00:00:00 2001 From: Marius Agur Pedersen Date: Thu, 16 Nov 2017 20:28:09 +0100 Subject: [PATCH 054/201] Added getEventArgs() to EventContext base interface. Returns null for non-save events according to Microsoft Documentation https://msdn.microsoft.com/en-us/library/gg328130.aspx#BKMK_getEventArgs --- types/xrm/index.d.ts | 6 ++++++ types/xrm/v8/index.d.ts | 7 +++++++ 2 files changed, 13 insertions(+) diff --git a/types/xrm/index.d.ts b/types/xrm/index.d.ts index 2362daf1b7..88910547f4 100644 --- a/types/xrm/index.d.ts +++ b/types/xrm/index.d.ts @@ -1397,6 +1397,12 @@ declare namespace Xrm { */ getDepth(): number; + /** + * Get event args returns null for non-save operations + * + * @return null + */ + getEventArgs(): null; /** * Gets a reference to the object for which event occurred. * diff --git a/types/xrm/v8/index.d.ts b/types/xrm/v8/index.d.ts index 472fbfdca6..cb3ca35d50 100644 --- a/types/xrm/v8/index.d.ts +++ b/types/xrm/v8/index.d.ts @@ -1089,6 +1089,13 @@ declare namespace Xrm { */ getDepth(): number; + /** + * Get event args returns null for non-save operations + * + * @return null + */ + getEventArgs(): null; + /** * Gets a reference to the object for which event occurred. * From f313a73ba3fda0f78d4a497c3601fe66127045f5 Mon Sep 17 00:00:00 2001 From: Paul Selden Date: Thu, 16 Nov 2017 15:22:28 -0500 Subject: [PATCH 055/201] add definition for mobx-apollo --- types/mobx-apollo/index.d.ts | 29 +++++++++++++++++++ types/mobx-apollo/mobx-apollo-tests.ts | 40 ++++++++++++++++++++++++++ types/mobx-apollo/tsconfig.json | 18 ++++++++++++ types/mobx-apollo/tslint.json | 1 + 4 files changed, 88 insertions(+) create mode 100644 types/mobx-apollo/index.d.ts create mode 100644 types/mobx-apollo/mobx-apollo-tests.ts create mode 100644 types/mobx-apollo/tsconfig.json create mode 100644 types/mobx-apollo/tslint.json diff --git a/types/mobx-apollo/index.d.ts b/types/mobx-apollo/index.d.ts new file mode 100644 index 0000000000..4054601717 --- /dev/null +++ b/types/mobx-apollo/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for mobx-apollo 0.0 +// Project: https://github.com/sonaye/mobx-apollo#readme +// Definitions by: Paul Selden +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { + ApolloClient, + ObservableQuery, + WatchQueryOptions, + ApolloError +} from 'apollo-client'; + +export interface MobxApolloQueryOptions extends WatchQueryOptions { + client: ApolloClient; + onFetch?: (result: T) => void; + onError?: (error: ApolloError) => void; +} + +export interface MobxApolloQuery { + loading: boolean; + data: T; + error?: ApolloError; + ref: ObservableQuery; +} + +export default function graphql( + options: MobxApolloQueryOptions +): MobxApolloQuery; diff --git a/types/mobx-apollo/mobx-apollo-tests.ts b/types/mobx-apollo/mobx-apollo-tests.ts new file mode 100644 index 0000000000..cc17916a5a --- /dev/null +++ b/types/mobx-apollo/mobx-apollo-tests.ts @@ -0,0 +1,40 @@ +import * as React from 'react'; +import { computed } from 'mobx'; +import { ApolloClient } from 'apollo-client'; +import gql from 'graphql-tag'; + +import query from 'mobx-apollo'; + +const PostsQuery = gql` + { + posts { + id + title + } + } +`; + +interface Post { + id: string; + title: string; +} + +class PostStore { + @computed + private get postsQuery() { + return query<{ posts: Post[] }>({ + client: new ApolloClient({ + link: {} as any, + cache: {} as any + }), + query: PostsQuery + }); + } + + @computed + get posts() { + return this.postsQuery.data.posts; + } +} + +new PostStore(); diff --git a/types/mobx-apollo/tsconfig.json b/types/mobx-apollo/tsconfig.json new file mode 100644 index 0000000000..c18e0f5512 --- /dev/null +++ b/types/mobx-apollo/tsconfig.json @@ -0,0 +1,18 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "target": "es5", + "experimentalDecorators": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "mobx-apollo-tests.ts"] +} diff --git a/types/mobx-apollo/tslint.json b/types/mobx-apollo/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mobx-apollo/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 6cf5cfa6195e475b9f1c62bd050f0a7e4018096e Mon Sep 17 00:00:00 2001 From: Jose Berrocal Date: Thu, 16 Nov 2017 14:32:21 -0600 Subject: [PATCH 056/201] Add missing property and constructor This attemp to add: - Property **disableTextLayer** - Constructor function for **PDFSinglePageViewer** --- types/pdfjs-dist/index.d.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/types/pdfjs-dist/index.d.ts b/types/pdfjs-dist/index.d.ts index a40c612d5a..f72d70f44e 100644 --- a/types/pdfjs-dist/index.d.ts +++ b/types/pdfjs-dist/index.d.ts @@ -407,6 +407,12 @@ declare namespace PDF { * in browsers which support the fullscreen API. */ disableFullscreen: boolean; + + /** + * Disable the text layer of PDF when used PDF.js renders a canvas instead of div elements + * + */ + disableTextLayer: boolean; /** * Enables CSS only zooming. @@ -475,5 +481,11 @@ declare namespace PDF { : PDFPromise; PDFViewer(params: PDFViewerParams): void; + /** + * yet another viewer, this will render only one page at the time, reducing rendering time + * very important for mobile development + * @params {PDFViewerParams} + */ + PDFSinglePageViewer(params: PDFViewerParams): void; } } From 3bb17cd6db2b4624bbb1493f3822346c1fc28bed Mon Sep 17 00:00:00 2001 From: David Newell Date: Thu, 16 Nov 2017 15:43:40 -0500 Subject: [PATCH 057/201] Updating the test --- types/dagre/dagre-tests.ts | 33 ++++++++++++++++++++++++++++++++- types/dagre/index.d.ts | 2 +- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/types/dagre/dagre-tests.ts b/types/dagre/dagre-tests.ts index ae81c2c896..a29cf0128a 100644 --- a/types/dagre/dagre-tests.ts +++ b/types/dagre/dagre-tests.ts @@ -1,8 +1,39 @@ -const gDagre = new dagre.graphlib.Graph(); +const gDagre = new dagre.graphlib.Graph({compound: true, multigraph: false}); gDagre.setGraph({}) .setDefaultEdgeLabel(() => ({})) + .setDefaultNodeLabel(() => ({})) .setNode("a", {}) .setEdge("b", "c") .setEdge("c", "d", {class: "class"}); dagre.layout(gDagre); + +gDagre.edge({v: 'b', w: 'c'}); +gDagre.hasEdge({v: 'b', w: 'c'}); +gDagre.inEdges('c'); +gDagre.outEdges('c'); + +gDagre.setParent('a', 'b'); +gDagre.children('b'); +gDagre.hasNode('d'); +gDagre.neighbors('c'); +gDagre.node({}); +gDagre.parent('a'); +gDagre.predecessors('d'); +gDagre.successors('b'); + +gDagre.removeEdge('c', 'd').removeNode('d'); + +dagre.graphlib.json.read(dagre.graphlib.json.write(gDagre)); + +dagre.graphlib.alg.components(gDagre); +dagre.graphlib.alg.dijkstra(gDagre, 'a', (edge) => 5); +dagre.graphlib.alg.dijkstraAll(gDagre); +dagre.graphlib.alg.findCycles(gDagre); +dagre.graphlib.alg.floydWarchall(gDagre); +dagre.graphlib.alg.isAcyclic(gDagre); +dagre.graphlib.alg.postorder(gDagre, 'a'); +dagre.graphlib.alg.preorder(gDagre, ['b', 'c']); +dagre.graphlib.alg.prim(gDagre); +dagre.graphlib.alg.tarjam(gDagre); +dagre.graphlib.alg.topsort(gDagre); diff --git a/types/dagre/index.d.ts b/types/dagre/index.d.ts index 852fe33973..6c5e5e00ec 100644 --- a/types/dagre/index.d.ts +++ b/types/dagre/index.d.ts @@ -41,7 +41,7 @@ export namespace graphlib { predecessors(name: string): Node[]|undefined; removeNode(name: string): Graph; setDefaultNodeLabel(callback: string|((nodeId: string) => string|Label)): Graph; - setNode(id: string, node: NodeConfig): Graph; + setNode(name: string, label: string|Label): Graph; setParent(childName: string, parentName: string): void; sinks(): Node[]; sources(): Node[]; From 71d0268f5cb01ac218cdbd8a0f46918db93ae1f9 Mon Sep 17 00:00:00 2001 From: Paul Selden Date: Thu, 16 Nov 2017 17:54:59 -0500 Subject: [PATCH 058/201] Add package.json with dependencies --- types/mobx-apollo/mobx-apollo-tests.ts | 1 - types/mobx-apollo/package.json | 8 ++++++++ 2 files changed, 8 insertions(+), 1 deletion(-) create mode 100644 types/mobx-apollo/package.json diff --git a/types/mobx-apollo/mobx-apollo-tests.ts b/types/mobx-apollo/mobx-apollo-tests.ts index cc17916a5a..d90ff873f2 100644 --- a/types/mobx-apollo/mobx-apollo-tests.ts +++ b/types/mobx-apollo/mobx-apollo-tests.ts @@ -1,4 +1,3 @@ -import * as React from 'react'; import { computed } from 'mobx'; import { ApolloClient } from 'apollo-client'; import gql from 'graphql-tag'; diff --git a/types/mobx-apollo/package.json b/types/mobx-apollo/package.json new file mode 100644 index 0000000000..197ba27ae8 --- /dev/null +++ b/types/mobx-apollo/package.json @@ -0,0 +1,8 @@ +{ + "private": true, + "dependencies": { + "apollo-client": "^2.0.0", + "graphql-tag": "^2.0.0", + "mobx": "^3.0.0" + } +} From 89667eb5cbee013f697ef1adef6582caa62385f3 Mon Sep 17 00:00:00 2001 From: Jeff Jacobson Date: Thu, 16 Nov 2017 14:50:49 -0800 Subject: [PATCH 059/201] Updated GeoJSON type definitions Updated to match RFC 7946 (https://tools.ietf.org/html/rfc7946). * Removed coordinate reference system types due to their removal from the standard. (https://tools.ietf.org/html/rfc7946#appendix-B.1) * Position arrays are now restricted to either two or three positions. (https://tools.ietf.org/html/rfc7946#section-3.1.1) * Feature and feature collection types are no longer generic. * Added support for foreign members. (https://tools.ietf.org/html/rfc7946#section-6.1) --- types/geojson/geojson-tests.ts | 93 ++++++++++-------- types/geojson/index.d.ts | 166 ++++++++++++++++++++------------- 2 files changed, 154 insertions(+), 105 deletions(-) diff --git a/types/geojson/geojson-tests.ts b/types/geojson/geojson-tests.ts index 4adb7f88f2..c9042c9da2 100644 --- a/types/geojson/geojson-tests.ts +++ b/types/geojson/geojson-tests.ts @@ -1,4 +1,9 @@ -let featureCollection: GeoJSON.FeatureCollection = { +import { + Feature, FeatureCollection, GeometryCollection, LineString, + MultiLineString, MultiPoint, MultiPolygon, Point, Polygon +} from "geojson"; + +let featureCollection: FeatureCollection = { type: "FeatureCollection", features: [ { @@ -34,7 +39,7 @@ let featureCollection: GeoJSON.FeatureCollection = { geometry: { type: "Polygon", coordinates: [ - [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] + [[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]] ] }, properties: { @@ -45,6 +50,9 @@ let featureCollection: GeoJSON.FeatureCollection = { } } ], + // Coordinate Systems no longer supported in GeoJSON as of RFC 7946. + // This will still work due to the standard's allowance for + // "foregin members", however. crs: { type: "link", properties: { @@ -54,7 +62,7 @@ let featureCollection: GeoJSON.FeatureCollection = { } }; -let featureWithPolygon: GeoJSON.Feature = { +const featureWithPolygon: Feature = { type: "Feature", bbox: [-180.0, -90.0, 180.0, 90.0], geometry: { @@ -66,57 +74,57 @@ let featureWithPolygon: GeoJSON.Feature = { properties: null }; -let point: GeoJSON.Point = { +const point: Point = { type: "Point", coordinates: [100.0, 0.0] }; // This type is commonly used in the turf package -let pointCoordinates: number[] = point.coordinates; +const pointCoordinates: number[] = point.coordinates; -let lineString: GeoJSON.LineString = { +const lineString: LineString = { type: "LineString", - coordinates: [ [100.0, 0.0], [101.0, 1.0] ] + coordinates: [[100.0, 0.0], [101.0, 1.0]] }; -let polygon: GeoJSON.Polygon = { +const polygon: Polygon = { type: "Polygon", coordinates: [ - [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] + [[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]] ] }; -let polygonWithHole: GeoJSON.Polygon = { +const polygonWithHole: Polygon = { type: "Polygon", coordinates: [ - [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ], - [ [100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2] ] + [[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]], + [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]] ] }; -let multiPoint: GeoJSON.MultiPoint = { +const multiPoint: MultiPoint = { type: "MultiPoint", - coordinates: [ [100.0, 0.0], [101.0, 1.0] ] + coordinates: [[100.0, 0.0], [101.0, 1.0]] }; -let multiLineString: GeoJSON.MultiLineString = { +const multiLineString: MultiLineString = { type: "MultiLineString", coordinates: [ - [ [100.0, 0.0], [101.0, 1.0] ], - [ [102.0, 2.0], [103.0, 3.0] ] + [[100.0, 0.0], [101.0, 1.0]], + [[102.0, 2.0], [103.0, 3.0]] ] }; -let multiPolygon: GeoJSON.MultiPolygon = { +const multiPolygon: MultiPolygon = { type: "MultiPolygon", coordinates: [ [[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]], [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]], - [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]] + [[100.2, 0.2], [100.8, 0.2], [100.8, 0.8], [100.2, 0.8], [100.2, 0.2]]] ] }; -let geometryCollection: GeoJSON.GeometryCollection = { +const geometryCollection: GeometryCollection = { type: "GeometryCollection", geometries: [ { @@ -125,12 +133,12 @@ let geometryCollection: GeoJSON.GeometryCollection = { }, { type: "LineString", - coordinates: [ [101.0, 0.0], [102.0, 1.0] ] + coordinates: [[101.0, 0.0], [102.0, 1.0]] } ] }; -let feature: GeoJSON.Feature = { +let feature: Feature = { type: "Feature", geometry: lineString, properties: null @@ -172,31 +180,31 @@ featureCollection = { { type: "Feature", geometry: lineString, - properties: {test: "OK"} + properties: { test: "OK" } }, { type: "Feature", geometry: polygon, - properties: {test: "OK"} + properties: { test: "OK" } }, { type: "Feature", geometry: polygonWithHole, - properties: {test: "OK"} + properties: { test: "OK" } }, { type: "Feature", geometry: multiPoint, - properties: {test: "OK"} + properties: { test: "OK" } }, { type: "Feature", geometry: multiLineString, - properties: {test: "OK"} + properties: { test: "OK" } }, { type: "Feature", geometry: multiPolygon, - properties: {test: "OK"} + properties: { test: "OK" } }, { type: "Feature", geometry: geometryCollection, - properties: {test: "OK"} + properties: { test: "OK" } } ], crs: { @@ -209,7 +217,7 @@ featureCollection = { }; // Allow access to custom properties -const pt: GeoJSON.Feature = { +const pt: Feature = { type: "Feature", properties: { foo: "bar", @@ -221,9 +229,14 @@ const pt: GeoJSON.Feature = { coordinates: [0, 0] } }; -pt.properties.foo; -pt.properties.hello; -pt.properties[1]; + +if (pt.properties) { + if (pt.properties.foo == null || pt.properties.hello == null || pt.properties[1] == null) { + throw TypeError("Properties should not be null or undefined."); + } +} else { + throw TypeError("Feature should have a 'properties' property."); +} // Optional generic for properties @@ -232,19 +245,21 @@ interface TestProperty { hello: string; } -const typedPropertiesFeature: GeoJSON.Feature = { +const testProps: TestProperty = { + foo: "bar", + hello: "world" +}; + +const typedPropertiesFeature: Feature = { type: "Feature", - properties: { - foo: "bar", - hello: "world", - }, + properties: testProps, geometry: { type: "Point", coordinates: [0, 0] } }; -const typedPropertiesFeatureCollection: GeoJSON.FeatureCollection = { +const typedPropertiesFeatureCollection: FeatureCollection = { type: "FeatureCollection", features: [typedPropertiesFeature] }; diff --git a/types/geojson/index.d.ts b/types/geojson/index.d.ts index b916179fac..2b086bc382 100644 --- a/types/geojson/index.d.ts +++ b/types/geojson/index.d.ts @@ -1,123 +1,157 @@ -// Type definitions for GeoJSON Format Specification Revision 1.0 -// Project: http://geojson.org/ +// Type definitions for geojson 7946.0 +// Project: https://geojson.org/ // Definitions by: Jacob Bruun // Arne Schubert +// Jeff Jacobson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 +// Note: as of the RFC 7946 version of GeoJSON, Coordinate Reference Systems +// are no longer supported. (See https://tools.ietf.org/html/rfc7946#appendix-B)} + export as namespace GeoJSON; -/*** - * http://geojson.org/geojson-spec.html#geojson-objects +/** + * The valid values for the "type" property of GeoJSON geometry objects. + * https://tools.ietf.org/html/rfc7946#section-1.4 + */ +export type GeoJsonGeometryTypeNames = "Point" | "LineString" | "MultiPoint" | "Polygon" | "MultiLineString" | + "MultiPolygon" | "GeometryCollection"; + +/** + * The value values for the "type" property of GeoJSON Objects. + * https://tools.ietf.org/html/rfc7946#section-1.4 + */ +export type GeoJsonTypeNames = "FeatureCollection" | "Feature" | GeoJsonGeometryTypeNames; + +/** + * Bounding box + * https://tools.ietf.org/html/rfc7946#section-5 + */ +export type BoundingBox = [number, number, number, number] | [number, number, number, number, number]; + +/** + * A Position is an array of coordinates. + * https://tools.ietf.org/html/rfc7946#section-3.1.1 + */ +export type Position = [number, number] | [number, number, number]; + +/** + * The base GeoJSON object. + * https://tools.ietf.org/html/rfc7946#section-3 */ export interface GeoJsonObject { - type: string; - bbox?: number[]; - crs?: CoordinateReferenceSystem; + /** + * Allow foreign members as specified in https://tools.ietf.org/html/rfc7946#section-6.1 + */ + [key: string]: any; + /** + * Specifies the type of GeoJSON object. + */ + type: GeoJsonTypeNames; + /** + * Bounding box of the coordinate range of the object's Geometries, Features, or Feature Collections. + * https://tools.ietf.org/html/rfc7946#section-5 + */ + bbox?: BoundingBox; } -/*** - * http://geojson.org/geojson-spec.html#positions - */ -export type Position = number[]; - -/*** - * http://geojson.org/geojson-spec.html#geometry-objects - */ -export interface DirectGeometryObject extends GeoJsonObject { - coordinates: Position[][][] | Position[][] | Position[] | Position; -} /** - * GeometryObject supports geometry collection as well + * A geometry object. + * https://tools.ietf.org/html/rfc7946#section-3 */ -export type GeometryObject = DirectGeometryObject | GeometryCollection; +export interface GeometryObject extends GeoJsonObject { + type: GeoJsonGeometryTypeNames; +} -/*** - * http://geojson.org/geojson-spec.html#point +/** + * Point geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.2 */ -export interface Point extends DirectGeometryObject { +export interface Point extends GeometryObject { type: "Point"; coordinates: Position; } -/*** - * http://geojson.org/geojson-spec.html#multipoint +/** + * MultiPoint geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.3 */ -export interface MultiPoint extends DirectGeometryObject { +export interface MultiPoint extends GeometryObject { type: "MultiPoint"; coordinates: Position[]; } -/*** - * http://geojson.org/geojson-spec.html#linestring +/** + * LineString geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.4 */ -export interface LineString extends DirectGeometryObject { +export interface LineString extends GeometryObject { type: "LineString"; coordinates: Position[]; } -/*** - * http://geojson.org/geojson-spec.html#multilinestring +/** + * MultiLineString geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.5 */ -export interface MultiLineString extends DirectGeometryObject { +export interface MultiLineString extends GeometryObject { type: "MultiLineString"; coordinates: Position[][]; } -/*** - * http://geojson.org/geojson-spec.html#polygon +/** + * Polygon geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.6 */ -export interface Polygon extends DirectGeometryObject { +export interface Polygon extends GeometryObject { type: "Polygon"; coordinates: Position[][]; } -/*** - * http://geojson.org/geojson-spec.html#multipolygon +/** + * MultiPolygon geometry object. + * https://tools.ietf.org/html/rfc7946#section-3.1.7 */ -export interface MultiPolygon extends DirectGeometryObject { +export interface MultiPolygon extends GeometryObject { type: "MultiPolygon"; coordinates: Position[][][]; } -/*** - * http://geojson.org/geojson-spec.html#geometry-collection +/** + * Geometry Collection + * https://tools.ietf.org/html/rfc7946#section-3.1.8 */ -export interface GeometryCollection extends GeoJsonObject { +export interface GeometryCollection extends GeometryObject { type: "GeometryCollection"; geometries: GeometryObject[]; } -/*** +/** + * A feature object which contains a geometry and associated properties. * https://tools.ietf.org/html/rfc7946#section-3.2 */ -export interface Feature extends GeoJsonObject { +export interface Feature extends GeoJsonObject { type: "Feature"; - geometry: G; - properties: P; + /** + * The feature's geometry + */ + geometry: GeometryObject | null; + /** + * A value that uniquely identifies this feature in a + * https://tools.ietf.org/html/rfc7946#section-3.2. + */ id?: string | number; + /** + * Properties associated with this feature. + */ + properties: { [name: string]: any; } | null; } -/*** - * http://geojson.org/geojson-spec.html#feature-collection-objects +/** + * A collection of feature objects. + * https://tools.ietf.org/html/rfc7946#section-3.3 */ -export interface FeatureCollection extends GeoJsonObject { - type: "FeatureCollection"; - features: Array>; -} - -/*** - * http://geojson.org/geojson-spec.html#coordinate-reference-system-objects - */ -export interface CoordinateReferenceSystem { - type: string; - properties: any; -} - -export interface NamedCoordinateReferenceSystem extends CoordinateReferenceSystem { - properties: { name: string }; -} - -export interface LinkedCoordinateReferenceSystem extends CoordinateReferenceSystem { - properties: { href: string; type: string }; +export interface FeatureCollection extends GeoJsonObject { + features: Feature[]; } From 335d12a4ee9af8e7f0c25dc6fe93a059e3ee9fa9 Mon Sep 17 00:00:00 2001 From: Jeff Jacobson Date: Thu, 16 Nov 2017 15:40:04 -0800 Subject: [PATCH 060/201] Modified typedefs dependent on "geojson" to accommodate changes. --- types/d3-geo/d3-geo-tests.ts | 4 ++-- types/d3-geo/index.d.ts | 4 +++- types/geojson2osm/geojson2osm-tests.ts | 2 +- types/geojson2osm/index.d.ts | 2 +- types/leaflet/index.d.ts | 28 +++++++++++++------------- types/leaflet/v0/index.d.ts | 12 +++++------ types/mapbox-gl/index.d.ts | 8 ++++---- types/polyline/index.d.ts | 2 +- types/shapefile/index.d.ts | 4 ++-- types/supercluster/index.d.ts | 2 +- types/tilebelt/index.d.ts | 4 ++-- 11 files changed, 37 insertions(+), 35 deletions(-) diff --git a/types/d3-geo/d3-geo-tests.ts b/types/d3-geo/d3-geo-tests.ts index 876461e3e9..e6014837a7 100644 --- a/types/d3-geo/d3-geo-tests.ts +++ b/types/d3-geo/d3-geo-tests.ts @@ -49,7 +49,7 @@ const sampleExtendedGeometryCollection: d3Geo.ExtendedGeometryCollection = { +const sampleFeature: GeoJSON.Feature = { type: 'Feature', geometry: samplePolygon, properties: { @@ -74,7 +74,7 @@ const sampleExtendedFeature2: d3Geo.ExtendedFeature = { +const sampleFeatureCollection: GeoJSON.FeatureCollection = { type: 'FeatureCollection', features: [ sampleFeature, diff --git a/types/d3-geo/index.d.ts b/types/d3-geo/index.d.ts index 4093b696e9..1d1d36fe91 100644 --- a/types/d3-geo/index.d.ts +++ b/types/d3-geo/index.d.ts @@ -36,7 +36,9 @@ export type GeoGeometryObjects = GeoJSON.GeometryObject | GeoSphere; export interface ExtendedGeometryCollection { type: string; bbox?: number[]; - crs?: GeoJSON.CoordinateReferenceSystem; + // GeoJSON removed the Coordinate System objects from the spec, but does allow + // "foreign members". + crs?: GeoJSON.GeoJsonObject; geometries: GeometryType[]; } diff --git a/types/geojson2osm/geojson2osm-tests.ts b/types/geojson2osm/geojson2osm-tests.ts index 887f10a83c..9d95de64c4 100644 --- a/types/geojson2osm/geojson2osm-tests.ts +++ b/types/geojson2osm/geojson2osm-tests.ts @@ -1,6 +1,6 @@ import { geojson2osm } from 'geojson2osm' -const features: GeoJSON.FeatureCollection = { +const features: GeoJSON.FeatureCollection = { type: 'FeatureCollection', features: [{ type: 'Feature', diff --git a/types/geojson2osm/index.d.ts b/types/geojson2osm/index.d.ts index 39b03de5bf..513348eeae 100644 --- a/types/geojson2osm/index.d.ts +++ b/types/geojson2osm/index.d.ts @@ -11,4 +11,4 @@ * @param features Input features * @returns OpenStreetMap XML */ -export function geojson2osm(features: GeoJSON.Feature | GeoJSON.FeatureCollection): any +export function geojson2osm(features: GeoJSON.Feature | GeoJSON.FeatureCollection): any diff --git a/types/leaflet/index.d.ts b/types/leaflet/index.d.ts index b1e7ead796..727478864a 100644 --- a/types/leaflet/index.d.ts +++ b/types/leaflet/index.d.ts @@ -583,7 +583,7 @@ export interface PolylineOptions extends PathOptions { export class Polyline extends Path { constructor(latlngs: LatLngExpression[], options?: PolylineOptions); - toGeoJSON(): geojson.Feature; + toGeoJSON(): geojson.Feature; getLatLngs(): LatLng[]; setLatLngs(latlngs: LatLngExpression[]): this; isEmpty(): boolean; @@ -591,7 +591,7 @@ export class Polyline; + feature?: geojson.Feature; options: PolylineOptions; } @@ -616,14 +616,14 @@ export interface CircleMarkerOptions extends PathOptions { export class CircleMarker

extends Path { constructor(latlng: LatLngExpression, options?: CircleMarkerOptions); - toGeoJSON(): geojson.Feature; + toGeoJSON(): geojson.Feature; setLatLng(latLng: LatLngExpression): this; getLatLng(): LatLng; setRadius(radius: number): this; getRadius(): number; options: CircleMarkerOptions; - feature?: geojson.Feature; + feature?: geojson.Feature; } export function circleMarker(latlng: LatLngExpression, options?: CircleMarkerOptions): CircleMarker; @@ -671,7 +671,7 @@ export class LayerGroup

extends Layer { /** * Returns a GeoJSON representation of the layer group (as a GeoJSON GeometryCollection, GeoJSONFeatureCollection or Multipoint). */ - toGeoJSON(): geojson.FeatureCollection | geojson.Feature | geojson.GeometryCollection; + toGeoJSON(): geojson.FeatureCollection | geojson.Feature | geojson.GeometryCollection; /** * Adds the given layer to the group. @@ -725,7 +725,7 @@ export class LayerGroup

extends Layer { */ getLayerId(layer: Layer): number; - feature?: geojson.FeatureCollection | geojson.Feature | geojson.GeometryCollection; + feature?: geojson.FeatureCollection | geojson.Feature | geojson.GeometryCollection; } /** @@ -765,7 +765,7 @@ export class FeatureGroup

extends LayerGroup

{ */ export function featureGroup(layers?: Layer[]): FeatureGroup; -export type StyleFunction

= (feature?: geojson.Feature) => PathOptions; +export type StyleFunction

= (feature?: geojson.Feature) => PathOptions; export interface GeoJSONOptions

extends LayerOptions { /** @@ -781,7 +781,7 @@ export interface GeoJSONOptions

extends LayerOptions { * } * ``` */ - pointToLayer?(geoJsonPoint: geojson.Feature, latlng: LatLng): Layer; // should import GeoJSON typings + pointToLayer?(geoJsonPoint: geojson.Feature, latlng: LatLng): Layer; // should import GeoJSON typings /** * A Function defining the Path options for styling GeoJSON lines and polygons, @@ -807,7 +807,7 @@ export interface GeoJSONOptions

extends LayerOptions { * function (feature, layer) {} * ``` */ - onEachFeature?(feature: geojson.Feature, layer: Layer): void; + onEachFeature?(feature: geojson.Feature, layer: Layer): void; /** * A Function that will be used to decide whether to show a feature or not. @@ -820,7 +820,7 @@ export interface GeoJSONOptions

extends LayerOptions { * } * ``` */ - filter?(geoJsonFeature: geojson.Feature): boolean; + filter?(geoJsonFeature: geojson.Feature): boolean; /** * A Function that will be used for converting GeoJSON coordinates to LatLngs. @@ -838,7 +838,7 @@ export class GeoJSON

extends FeatureGroup

{ * Creates a Layer from a given GeoJSON feature. Can use a custom pointToLayer * and/or coordsToLatLng functions if provided as options. */ - static geometryToLayer

(featureData: geojson.Feature, options?: GeoJSONOptions

): Layer; + static geometryToLayer(featureData: geojson.Feature, options?: GeoJSONOptions): Layer; /** * Creates a LatLng object from an array of 2 numbers (longitude, latitude) or @@ -872,7 +872,7 @@ export class GeoJSON

extends FeatureGroup

{ /** * Normalize GeoJSON geometries/features into GeoJSON features. */ - static asFeature

(geojson: geojson.Feature | geojson.GeometryObject): geojson.Feature; + static asFeature(geojson: geojson.Feature | geojson.GeometryObject): geojson.Feature; constructor(geojson?: geojson.GeoJsonObject, options?: GeoJSONOptions

) /** @@ -1454,7 +1454,7 @@ export interface MarkerOptions extends InteractiveLayerOptions { export class Marker

extends Layer { constructor(latlng: LatLngExpression, options?: MarkerOptions); - toGeoJSON(): geojson.Feature; + toGeoJSON(): geojson.Feature; getLatLng(): LatLng; setLatLng(latlng: LatLngExpression): this; setZIndexOffset(offset: number): this; @@ -1465,7 +1465,7 @@ export class Marker

extends Layer { // Properties options: MarkerOptions; dragging?: Handler; - feature?: geojson.Feature; + feature?: geojson.Feature; } export function marker(latlng: LatLngExpression, options?: MarkerOptions): Marker; diff --git a/types/leaflet/v0/index.d.ts b/types/leaflet/v0/index.d.ts index efadd88e8f..d841a45133 100644 --- a/types/leaflet/v0/index.d.ts +++ b/types/leaflet/v0/index.d.ts @@ -223,7 +223,7 @@ declare namespace L { /** * Returns a GeoJSON representation of the circle (GeoJSON Point Feature). */ - toGeoJSON(): GeoJSON.Feature; + toGeoJSON(): GeoJSON.Feature; } } @@ -1716,7 +1716,7 @@ declare namespace L { * Returns a GeoJSON representation of the layer group (GeoJSON FeatureCollection). * Note: Descendent classes MultiPolygon & MultiPolyLine return `Feature`s, not `FeatureCollection`s */ - toGeoJSON(): GeoJSON.FeatureCollection|GeoJSON.Feature; + toGeoJSON(): GeoJSON.FeatureCollection|GeoJSON.Feature; //////////// //////////// @@ -2943,7 +2943,7 @@ declare namespace L { /** * Returns a GeoJSON representation of the marker (GeoJSON Point Feature). */ - toGeoJSON(): GeoJSON.Feature; + toGeoJSON(): GeoJSON.Feature; /** * Marker dragging handler (by both mouse and touch). @@ -3103,7 +3103,7 @@ declare namespace L { /** * Returns a GeoJSON representation of the multipolygon (GeoJSON MultiPolygon Feature). */ - toGeoJSON(): GeoJSON.Feature; + toGeoJSON(): GeoJSON.Feature; } } @@ -3144,7 +3144,7 @@ declare namespace L { /** * Returns a GeoJSON representation of the multipolyline (GeoJSON MultiLineString Feature). */ - toGeoJSON(): GeoJSON.Feature; + toGeoJSON(): GeoJSON.Feature; } } @@ -3565,7 +3565,7 @@ declare namespace L { /** * Returns a GeoJSON representation of the polyline (GeoJSON LineString Feature). */ - toGeoJSON(): GeoJSON.Feature; + toGeoJSON(): GeoJSON.Feature; } } diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 6be9a465ef..6e61c90c70 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -54,9 +54,9 @@ declare namespace mapboxgl { unproject(point: PointLike): mapboxgl.LngLat; - queryRenderedFeatures(pointOrBox?: PointLike | PointLike[], parameters?: {layers?: string[], filter?: any[]}): GeoJSON.Feature[]; + queryRenderedFeatures(pointOrBox?: PointLike | PointLike[], parameters?: {layers?: string[], filter?: any[]}): GeoJSON.Feature[]; - querySourceFeatures(sourceID: string, parameters?: {sourceLayer?: string, filter?: any[]}): GeoJSON.Feature[]; + querySourceFeatures(sourceID: string, parameters?: {sourceLayer?: string, filter?: any[]}): GeoJSON.Feature[]; setStyle(style: mapboxgl.Style | string): this; @@ -507,11 +507,11 @@ declare namespace mapboxgl { constructor(options?: mapboxgl.GeoJSONSourceOptions); - setData(data: GeoJSON.Feature | GeoJSON.FeatureCollection | String): this; + setData(data: GeoJSON.Feature | GeoJSON.FeatureCollection | String): this; } export interface GeoJSONSourceOptions { - data?: GeoJSON.Feature | GeoJSON.FeatureCollection | string; + data?: GeoJSON.Feature | GeoJSON.FeatureCollection | string; maxzoom?: number; diff --git a/types/polyline/index.d.ts b/types/polyline/index.d.ts index 7a8b7eeb19..6961205212 100644 --- a/types/polyline/index.d.ts +++ b/types/polyline/index.d.ts @@ -9,7 +9,7 @@ interface Polyline { decode(string: string, precision?: number): number[][]; encode(coordinate: number[][], precision?: number): string; - fromGeoJSON(geojson: GeoJSON.LineString | GeoJSON.Feature, precision?: number): string; + fromGeoJSON(geojson: GeoJSON.LineString | GeoJSON.Feature, precision?: number): string; } declare var polyline: Polyline; diff --git a/types/shapefile/index.d.ts b/types/shapefile/index.d.ts index 54a18a2503..83852507e1 100644 --- a/types/shapefile/index.d.ts +++ b/types/shapefile/index.d.ts @@ -15,7 +15,7 @@ declare namespace shapefile { } interface Feature { done: boolean - value: GeoJSON.Feature + value: GeoJSON.Feature } interface Shapefile { bbox: Array @@ -23,7 +23,7 @@ declare namespace shapefile { } interface ShapefileStatic { open(shp: any, dbf?: any, options?: Options): Promise; - read(shp: any, dbf?: any, options?: Options): Promise>; + read(shp: any, dbf?: any, options?: Options): Promise; } } diff --git a/types/supercluster/index.d.ts b/types/supercluster/index.d.ts index 7fd487ae09..7463b4a43a 100644 --- a/types/supercluster/index.d.ts +++ b/types/supercluster/index.d.ts @@ -94,7 +94,7 @@ export class Supercluster { */ export default function supercluster(options: Options): Supercluster; -export type Point = GeoJSON.Feature; +export type Point = GeoJSON.Feature; export type Points = Point[]; export type Clusters = Cluster[]; export type TileFeatures = TileFeature[]; diff --git a/types/tilebelt/index.d.ts b/types/tilebelt/index.d.ts index f8d3adae1c..eed92f915b 100644 --- a/types/tilebelt/index.d.ts +++ b/types/tilebelt/index.d.ts @@ -14,12 +14,12 @@ declare namespace tilebelt { * * @name tileToGeoJSON * @param {Array} tile - * @returns {Feature} + * @returns {Feature} * @example * var poly = tileToGeoJSON([5, 10, 10]) * //=poly */ - tileToGeoJSON(tile: Array): GeoJSON.Feature + tileToGeoJSON(tile: Array): GeoJSON.Feature /** * Get the bbox of a tile From 79e1c170a8c9cfa1247ad19ffd447c285542935e Mon Sep 17 00:00:00 2001 From: ChenX Date: Fri, 17 Nov 2017 17:08:46 +0800 Subject: [PATCH 061/201] update new function --- types/three/three-core.d.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index 3252661b75..c0468fdecd 100644 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -463,6 +463,8 @@ export class CubeCamera extends Object3D { renderTarget: WebGLRenderTargetCube; updateCubeMap(renderer: Renderer, scene: Scene): void; + + update(renderer: Renderer, scene: Scene): void; } /** @@ -2757,7 +2759,7 @@ export interface MeshStandardMaterialParameters extends MaterialParameters { lightMapIntensity?: number; aoMap?: Texture; aoMapIntensity?: number; - emissive?: Color; + emissive?: number|string|Color; emissiveIntensity?: number; emissiveMap?: Texture; bumpMap?: Texture; From f0417239882a1643f6af66cda1ab193a42ae8525 Mon Sep 17 00:00:00 2001 From: ChenX Date: Fri, 17 Nov 2017 17:15:30 +0800 Subject: [PATCH 062/201] add OutLinePass and SMAAPass --- types/three/index.d.ts | 2 ++ types/three/three-OutlinePass.d.ts | 20 ++++++++++++++++++++ types/three/three-SMAAPass.d.ts | 19 +++++++++++++++++++ 3 files changed, 41 insertions(+) create mode 100644 types/three/three-OutlinePass.d.ts create mode 100644 types/three/three-SMAAPass.d.ts diff --git a/types/three/index.d.ts b/types/three/index.d.ts index f9dcc7a762..da9bc5f452 100644 --- a/types/three/index.d.ts +++ b/types/three/index.d.ts @@ -29,5 +29,7 @@ export * from "./three-trackballcontrols"; export * from "./three-transformcontrols"; export * from "./three-vrcontrols"; export * from "./three-vreffect"; +export * from "./three-OutlinePass"; +export * from "./three-SMAAPass.d"; export as namespace THREE; diff --git a/types/three/three-OutlinePass.d.ts b/types/three/three-OutlinePass.d.ts new file mode 100644 index 0000000000..1dfef0fbd9 --- /dev/null +++ b/types/three/three-OutlinePass.d.ts @@ -0,0 +1,20 @@ +import +{ + Camera, + Color, + Face3, + Light, + Material, + Object3D, + Scene, + Vector2, + Vector3, + Vector4 +} from "./three-core"; +export class OutlinePass +{ + constructor(size: Vector2, scene: Scene, camer: Camera); + selectedObjects: Array; + renderCamera: Camera; +} + diff --git a/types/three/three-SMAAPass.d.ts b/types/three/three-SMAAPass.d.ts new file mode 100644 index 0000000000..76d5f14a7d --- /dev/null +++ b/types/three/three-SMAAPass.d.ts @@ -0,0 +1,19 @@ +import +{ + Camera, + Color, + Face3, + Light, + Material, + Object3D, + Scene, + Vector2, + Vector3, + Vector4 +} from "./three-core"; +export class SMAAPass +{ + constructor(width: number, height: number); + renderToScreen: boolean; +} + From d66780309a2963cf26098b7ee32fcd762d1c6a0d Mon Sep 17 00:00:00 2001 From: ChenX Date: Fri, 17 Nov 2017 17:23:44 +0800 Subject: [PATCH 063/201] clear code. --- types/three/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/three/index.d.ts b/types/three/index.d.ts index da9bc5f452..58c72301c0 100644 --- a/types/three/index.d.ts +++ b/types/three/index.d.ts @@ -30,6 +30,6 @@ export * from "./three-transformcontrols"; export * from "./three-vrcontrols"; export * from "./three-vreffect"; export * from "./three-OutlinePass"; -export * from "./three-SMAAPass.d"; +export * from "./three-SMAAPass"; export as namespace THREE; From 45111d599cef8aafa21c7099720188faee875668 Mon Sep 17 00:00:00 2001 From: Loic CAOUEN Date: Fri, 17 Nov 2017 10:42:46 +0100 Subject: [PATCH 064/201] types\applicationinsights-js\index.d.ts : update setAuthenticatedUserContext definition according to last version of applicationinsights-js --- types/applicationinsights-js/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/applicationinsights-js/index.d.ts b/types/applicationinsights-js/index.d.ts index 17137d67dd..4214837ddf 100644 --- a/types/applicationinsights-js/index.d.ts +++ b/types/applicationinsights-js/index.d.ts @@ -777,7 +777,7 @@ declare module Microsoft.ApplicationInsights { * @param authenticatedUserId {string} - The authenticated user id. A unique and persistent string that represents each authenticated user in the service. * @param accountId {string} - An optional string to represent the account associated with the authenticated user. */ - setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string): any; + setAuthenticatedUserContext(authenticatedUserId: string, accountId?: string, storeInCookie?: boolean): any; /** * Clears the authenticated user id and the account id from the user context. */ From f3dc15c020ceb2eac7718c307b75a963d60fcb4e Mon Sep 17 00:00:00 2001 From: Alex Brick Date: Thu, 16 Nov 2017 16:39:53 +0100 Subject: [PATCH 065/201] [swagger-tools] Fixing type of req.swagger field I managed to find some tests in the `swagger-tools` codebase for this field, so I was able to verify the typing. I found a number of mistakes I had made. I've also changed a few fields to `any` where I had no good structure to give them. --- types/swagger-tools/index.d.ts | 56 +++-- types/swagger-tools/swagger-tools-tests.ts | 247 +++++++++++++++++++-- 2 files changed, 270 insertions(+), 33 deletions(-) diff --git a/types/swagger-tools/index.d.ts b/types/swagger-tools/index.d.ts index 4f39031477..0fc0c91969 100644 --- a/types/swagger-tools/index.d.ts +++ b/types/swagger-tools/index.d.ts @@ -8,32 +8,42 @@ import { NextHandleFunction } from 'connect'; import { IncomingMessage, ServerResponse } from 'http'; export interface SwaggerParameterSchema { + allowMultiple?: boolean; + description?: string; + format?: string; + in?: string; + maximum?: string; + minimum?: string; name: string; - in: string; + paramType?: string; + required?: boolean; + type: string; } -export interface SwaggerRequestParameter { - path: string; +export interface SwaggerRequestParameter { + path: string[]; schema: SwaggerParameterSchema; originalValue: any; - value: any; + value: T; } export interface SwaggerRequestParameters { - [paramName: string]: SwaggerRequestParameter; + [paramName: string]: SwaggerRequestParameter; } export interface Swagger12Request extends IncomingMessage { swagger: { - api: string; + api: any; apiDeclaration: any; apiIndex: number; - authorizations?: any[]; - operation?: string; - operationPath?: string; + authorizations?: any; + operation?: any; + operationPath?: string[]; params: SwaggerRequestParameters; resourceIndex: number; resourceListing: any; + swaggerVersion: string; + useStubs?: boolean; }; } @@ -50,20 +60,40 @@ export interface SwaggerRouter12Options { } export interface OperationParameter { - path: string; + path: string[]; schema: SwaggerParameterSchema; } +export interface Swagger20Security { + [name: string]: any; +} + +export interface Swagger20Response { + description?: string; + schema?: any; +} + +export interface Swagger20Operation { + operationId?: string; + parameters?: SwaggerParameterSchema[]; + responses: { [code: string]: Swagger20Response }; + security?: Swagger20Security[]; + summary?: string; + tags?: string[]; +} + export interface Swagger20Request extends IncomingMessage { swagger: { apiPath: string; - operation?: string; - operationPath?: string; + operation?: Swagger20Operation; + operationPath?: string[]; operationParameters?: OperationParameter[]; - path: string; + path: any; params: SwaggerRequestParameters; security: any[]; swaggerObject: any; + swaggerVersion: string; + useStubs?: boolean; }; } diff --git a/types/swagger-tools/swagger-tools-tests.ts b/types/swagger-tools/swagger-tools-tests.ts index 12a7993819..8bf1b94800 100644 --- a/types/swagger-tools/swagger-tools-tests.ts +++ b/types/swagger-tools/swagger-tools-tests.ts @@ -37,17 +37,102 @@ swaggerTools.initializeMiddleware(swaggerDoc20, middleware => { // Test passing in the handlers directly app.use(middleware.swaggerRouter({ controllers: { - foo_bar: (req, res, next) => { - console.log(req.swagger.apiPath); - console.log(req.swagger.operation); - console.log(req.swagger.operationParameters); - console.log(req.swagger.operationPath); - console.log(req.swagger.path); - console.log(req.swagger.security); - console.log(req.swagger.swaggerObject); + // These tests are based on tests here: + // https://github.com/apigee-127/swagger-tools/blob/0cea535b122265c6d01546e199e2e8fda4c0f5da/test/2.0/test-middleware-swagger-metadata.js#L102-L138 - console.log(req.swagger.params.location.value); - console.log(req.swagger.params.unit.value); + foo_bar: (req, res, next) => { + req.swagger.swaggerVersion = '2.0'; + req.swagger.apiPath = '/pets/{id}'; + req.swagger.operation = { + security: [ + { + oauth2: ["read"] + } + ], + tags: [ "Pet Operations" ], + operationId: "getPetById", + summary: "Finds the pet by id", + responses: { + 200: { + description: "Pet response", + schema: { + $ref: "#/definitions/Pet" + } + }, + default: { + description: "Unexpected error", + schema: { + $ref: "#/definitions/Error" + } + } + }, + parameters: [ + { + in: 'query', + name: 'mock', + description: 'Mock mode', + required: false, + type: 'boolean' + } + ] + }; + + req.swagger.operationParameters = [ + { + path: ['paths', '/pets/{id}', 'get', 'parameters', '0'], + schema: { + in: 'query', + name: 'mock', + description: 'Mock mode', + required: false, + type: 'boolean' + }, + }, + { + path: ['paths', '/pets/{id}', 'parameters', '0'], + schema: { + name: "id", + in: "path", + description: "ID of pet", + required: true, + type: "integer", + format: "int64" + } + } + ]; + req.swagger.operationPath = ['paths', '/pets/{id}', 'get']; + req.swagger.security = [ + { + oauth2: [ 'read' ] + } + ]; + req.swagger.params = { + id: { + path: ['paths', '/pets/{id}', 'parameters', '0'], + schema: { + name: "id", + in: "path", + description: "ID of pet", + required: true, + type: "integer", + format: "int64" + }, + originalValue: '1', + value: 1 + }, + mock: { + path: ['paths', '/pets/{id}', 'get', 'parameters', '0'], + schema: { + in: 'query', + name: 'mock', + description: 'Mock mode', + required: false, + type: 'boolean' + }, + originalValue: 'false', + value: false + } + }; res.setHeader('Content-Type', 'application/json'); res.end([ 'foo', 0 ]); @@ -90,17 +175,139 @@ swaggerTools.initializeMiddleware(apiDoc12, apiDeclarations, middleware => { // Test passing in the handlers directly app.use(middleware.swaggerRouter({ controllers: { - foo_bar: (req, res, next) => { - console.log(req.swagger.api); - console.log(req.swagger.apiDeclaration); - console.log(req.swagger.apiIndex); - console.log(req.swagger.operation); - console.log(req.swagger.operationPath); - console.log(req.swagger.resourceIndex); - console.log(req.swagger.resourceListing); + // These tests are based on tests here: + // https://github.com/apigee-127/swagger-tools/blob/0cea535b122265c6d01546e199e2e8fda4c0f5da/test/1.2/test-middleware-swagger-metadata.js#L72-L89 - console.log(req.swagger.params.location.value); - console.log(req.swagger.params.unit.value); + foo_bar: (req, res, next) => { + req.swagger.swaggerVersion = '1.2'; + req.swagger.api = { + operations: [ + { + authorizations: {}, + method: "GET", + nickname: "getPetById", + notes: "Returns a pet based on ID", + parameters: [ + { + allowMultiple: false, + description: "ID of pet that needs to be fetched", + format: "int64", + maximum: "100000.0", + minimum: "1.0", + name: "petId", + paramType: "path", + required: true, + type: "integer" + } + ], + responseMessages: [ + { + code: 400, + message: "Invalid ID supplied" + }, + { + code: 404, + message: "Pet not found" + } + ], + summary: "Find pet by ID", + type: "Pet" + }, + { + authorizations: { + oauth2: [ + { + description: "modify pets in your account", + scope: "write:pets" + } + ] + }, + method: "DELETE", + nickname: "deletePet", + notes: "", + parameters: [ + { + allowMultiple: false, + description: "Pet id to delete", + name: "petId", + paramType: "path", + required: true, + type: "string" + } + ], + responseMessages: [ + { + code: 400, + message: "Invalid pet value" + } + ], + summary: "Deletes a pet", + type: "void" + }, + ], + path: "/pet/{petId}" + }; + + req.swagger.apiDeclaration = {}; + req.swagger.apiIndex = 0; + req.swagger.authorizations = { + oauth2: [ + { + description: "modify pets in your account", + scope: "write:pets" + } + ] + }; + req.swagger.operation = { + authorizations: {}, + method: "GET", + nickname: "getPetById", + notes: "Returns a pet based on ID", + parameters: [ + { + allowMultiple: false, + description: "ID of pet that needs to be fetched", + format: "int64", + maximum: "100000.0", + minimum: "1.0", + name: "petId", + paramType: "path", + required: true, + type: "integer" + } + ], + responseMessages: [ + { + code: 400, + message: "Invalid ID supplied" + }, + { + code: 404, + message: "Pet not found" + } + ], + summary: "Find pet by ID", + type: "Pet" + }; + req.swagger.operationPath = ['apis', '0', 'operations', '0']; + req.swagger.params = { + petId: { + path: ['apis', '0', 'operations', '0', 'parameters', '0'], + schema: { + allowMultiple: false, + description: "ID of pet that needs to be fetched", + format: "int64", + maximum: "100000.0", + minimum: "1.0", + name: "petId", + paramType: "path", + required: true, + type: "integer" + }, + originalValue: '1', + value: 1 + } + }; res.setHeader('Content-Type', 'application/json'); res.end([ 'foo', 0 ]); From 00877f7d99cf529622a8d9fac52c728e17e3a341 Mon Sep 17 00:00:00 2001 From: Marius Agur Pedersen Date: Fri, 17 Nov 2017 13:57:19 +0100 Subject: [PATCH 066/201] Changed getEventArgs implementation to remediate errors introduced in last commit --- types/xrm/index.d.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/types/xrm/index.d.ts b/types/xrm/index.d.ts index 88910547f4..915df1fa62 100644 --- a/types/xrm/index.d.ts +++ b/types/xrm/index.d.ts @@ -1398,11 +1398,12 @@ declare namespace Xrm { getDepth(): number; /** - * Get event args returns null for non-save operations + * Returns the event arguments for the event context + * Get event args returns null for read operations * - * @return null + * @return The event arguments or null */ - getEventArgs(): null; + getEventArgs(): SaveEventArguments | StageChangeEventArguments | StageSelectedEventArguments; /** * Gets a reference to the object for which event occurred. * From 60742eeb8ca8a67f535509a781d2a06468db6fbb Mon Sep 17 00:00:00 2001 From: Marius Agur Pedersen Date: Fri, 17 Nov 2017 13:58:33 +0100 Subject: [PATCH 067/201] Updated getEventArgs function for v8 and formatted code --- types/xrm/index.d.ts | 1 + types/xrm/v8/index.d.ts | 7 ++++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/types/xrm/index.d.ts b/types/xrm/index.d.ts index 915df1fa62..31bdd6776a 100644 --- a/types/xrm/index.d.ts +++ b/types/xrm/index.d.ts @@ -1404,6 +1404,7 @@ declare namespace Xrm { * @return The event arguments or null */ getEventArgs(): SaveEventArguments | StageChangeEventArguments | StageSelectedEventArguments; + /** * Gets a reference to the object for which event occurred. * diff --git a/types/xrm/v8/index.d.ts b/types/xrm/v8/index.d.ts index cb3ca35d50..810d461033 100644 --- a/types/xrm/v8/index.d.ts +++ b/types/xrm/v8/index.d.ts @@ -1090,11 +1090,12 @@ declare namespace Xrm { getDepth(): number; /** - * Get event args returns null for non-save operations + * Returns the event arguments for the event context + * Get event args returns null for read operations * - * @return null + * @return The event arguments or null */ - getEventArgs(): null; + getEventArgs(): SaveEventArguments | StageChangeEventArguments | StageSelectedEventArguments; /** * Gets a reference to the object for which event occurred. From c8df900a5318fd9a0ed61bfe8fb4c4d21c48aca9 Mon Sep 17 00:00:00 2001 From: Christopher Deutsch Date: Fri, 17 Nov 2017 11:43:20 -0600 Subject: [PATCH 068/201] Fix bug with `waitForSelector`. Option params should all be optional. Add new `LaunchOptions` Used https://github.com/GoogleChrome/puppeteer/blob/90ca0073679830bb39b4ce549ff8ed513c8a36ed/docs/api.md as reference for these changes. --- types/puppeteer/index.d.ts | 6 +++++- types/puppeteer/puppeteer-tests.ts | 7 +++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index f92bedd135..19e4162071 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -723,7 +723,7 @@ export interface FrameBase { ): Promise; waitForSelector( selector: string, - options?: { visible: boolean; timeout: number } + options?: { visible?: boolean; hidden?: boolean; timeout?: number } ): Promise; } @@ -1110,6 +1110,10 @@ export interface LaunchOptions { args?: string[]; /** Close chrome process on Ctrl-C. Defaults to true. */ handleSIGINT?: boolean; + /** Close chrome process on SIGTERM. Defaults to true. */ + handleSIGTERM?: boolean; + /** Close chrome process on SIGHUP. Defaults to true. */ + handleSIGHUP?: boolean; /** * Maximum time in milliseconds to wait for the Chrome instance to start. * Defaults to 30000 (30 seconds). Pass 0 to disable timeout. diff --git a/types/puppeteer/puppeteer-tests.ts b/types/puppeteer/puppeteer-tests.ts index 709afc87d0..d8bb2b4229 100644 --- a/types/puppeteer/puppeteer-tests.ts +++ b/types/puppeteer/puppeteer-tests.ts @@ -118,7 +118,7 @@ puppeteer.launch().then(async browser => { let currentURL: string; page - .waitForSelector("img") + .waitForSelector("img", { visible: true }) .then(() => console.log("First URL with image: " + currentURL)); for (currentURL of [ "https://example.com", @@ -160,7 +160,10 @@ puppeteer.launch().then(async browser => { args: [ '--no-sandbox', '--disable-setuid-sandbox', - ] + ], + handleSIGINT: true, + handleSIGHUP: true, + handleSIGTERM: true, }); const page = await browser.newPage(); await page.goto("https://example.com"); From d8652bb065c07f84fdd63bb5770680f98f3e6285 Mon Sep 17 00:00:00 2001 From: Josh Goldberg Date: Fri, 17 Nov 2017 12:06:42 -0800 Subject: [PATCH 069/201] Made name optional in jest::jasmine::createSpy See https://github.com/jasmine/jasmine/issues/1438 and https://github.com/DefinitelyTyped/DefinitelyTyped/pull/21159. --- types/jest/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/jest/index.d.ts b/types/jest/index.d.ts index 1b8d137094..0a5c595cfa 100644 --- a/types/jest/index.d.ts +++ b/types/jest/index.d.ts @@ -555,7 +555,7 @@ declare namespace jasmine { function anything(): Any; function arrayContaining(sample: any[]): ArrayContaining; function objectContaining(sample: any): ObjectContaining; - function createSpy(name: string, originalFn?: (...args: any[]) => any): Spy; + function createSpy(name?: string, originalFn?: (...args: any[]) => any): Spy; function createSpyObj(baseName: string, methodNames: any[]): any; function createSpyObj(baseName: string, methodNames: any[]): T; function pp(value: any): string; From 78bf7ac1d61c97cdd83db2a1b47feadbc21f00dc Mon Sep 17 00:00:00 2001 From: Christian Svensson Date: Fri, 17 Nov 2017 22:13:07 +0100 Subject: [PATCH 070/201] importer is undefined for entry modules https://github.com/rollup/rollup/blob/master/src/Bundle.js#L116 --- types/rollup/index.d.ts | 2 +- types/rollup/rollup-tests.ts | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/types/rollup/index.d.ts b/types/rollup/index.d.ts index 946b4f6786..b1a67c9fdc 100644 --- a/types/rollup/index.d.ts +++ b/types/rollup/index.d.ts @@ -135,7 +135,7 @@ export interface Plugin { * Returning null or undefined defers to other resolveId functions (and eventually the default resolution behavior); * returning any other falsy value signals that importee should be treated as an external module and not included in the bundle. */ - resolveId?(importee: string, importer: string): string | null | undefined | false | 0 | '' + resolveId?(importee: string, importer: string | undefined): string | null | undefined | false | 0 | '' /** A module transformer function */ transform?(this: TransformContext, source: string, id: string): string | { code: string, map: SourceMap } /** A bundle transformer function */ diff --git a/types/rollup/rollup-tests.ts b/types/rollup/rollup-tests.ts index 924e675373..078cdf5450 100644 --- a/types/rollup/rollup-tests.ts +++ b/types/rollup/rollup-tests.ts @@ -5,6 +5,12 @@ declare const console: { log(...messages: any[]): void, warn(message: string): v let cache: Bundle | undefined const plugin: Plugin = { name: 'test-plugin', + resolveId(importee, importer) { + if (importer === undefined) { + return 'custom/entry/point.js' + } + return importer.trim() + }, transform(source, id) { if (id === 'rxjs') { this.error(new Error(`Don't import this directly`)) From 3be84fe1aa0228beb184c4c24ea67271e6d3ba76 Mon Sep 17 00:00:00 2001 From: Christian Svensson Date: Sat, 18 Nov 2017 02:54:58 +0100 Subject: [PATCH 071/201] transform/transformBundle can return null/undefined I did not find it explicitly in documentation, but here is the code: https://github.com/rollup/rollup/blob/master/src/utils/transform.js#L78 https://github.com/rollup/rollup/blob/master/src/utils/transformBundle.js#L12 --- types/rollup/index.d.ts | 4 ++-- types/rollup/rollup-tests.ts | 11 +++++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/types/rollup/index.d.ts b/types/rollup/index.d.ts index b1a67c9fdc..05fb4e9319 100644 --- a/types/rollup/index.d.ts +++ b/types/rollup/index.d.ts @@ -137,9 +137,9 @@ export interface Plugin { */ resolveId?(importee: string, importer: string | undefined): string | null | undefined | false | 0 | '' /** A module transformer function */ - transform?(this: TransformContext, source: string, id: string): string | { code: string, map: SourceMap } + transform?(this: TransformContext, source: string, id: string): string | null | undefined | { code: string, map: SourceMap } /** A bundle transformer function */ - transformBundle?(source: string, options: { format: Format }): string | { code: string, map: SourceMap } + transformBundle?(source: string, options: { format: Format }): string | null | undefined | { code: string, map: SourceMap } /** Function hook called when bundle.generate() is being executed. */ ongenerate?(options: GenerateOptions, bundle: Bundle): void /** Function hook called when bundle.write() is being executed, after the file has been written to disk. */ diff --git a/types/rollup/rollup-tests.ts b/types/rollup/rollup-tests.ts index 078cdf5450..04908c52bb 100644 --- a/types/rollup/rollup-tests.ts +++ b/types/rollup/rollup-tests.ts @@ -14,12 +14,23 @@ const plugin: Plugin = { transform(source, id) { if (id === 'rxjs') { this.error(new Error(`Don't import this directly`)) + return null } const indexOfQuote = source.indexOf('"') if (indexOfQuote >= 0) { this.warn(`Prefer ' over " for strings`, indexOfQuote) + return undefined } return source + }, + transformBundle(source, options) { + if (options.format === 'iife') { + return `window.nonModule = true\n${source}` + } else if (options.format === 'cjs') { + return null + } + + return undefined } } From 71be23ef73b7297de309dd1fc42ed5d660feb8ce Mon Sep 17 00:00:00 2001 From: Christian Svensson Date: Sat, 18 Nov 2017 06:01:23 +0100 Subject: [PATCH 072/201] added watch api typings See documentation: for details https://rollupjs.org/#rollup-watch Source code has more details on event data: https://github.com/rollup/rollup/blob/e11a2fdf7e6f619cc66d28cfc1edc2f54aab4cce/src/watch/index.js --- types/rollup/index.d.ts | 51 ++++++++++++++++++++++++++++++++++++ types/rollup/rollup-tests.ts | 42 ++++++++++++++++++++++++++++- 2 files changed, 92 insertions(+), 1 deletion(-) diff --git a/types/rollup/index.d.ts b/types/rollup/index.d.ts index 946b4f6786..921dca7d21 100644 --- a/types/rollup/index.d.ts +++ b/types/rollup/index.d.ts @@ -164,3 +164,54 @@ export interface TransformContext { /** Returns a Promise that resolves with a bundle */ export function rollup(options: Options): Promise + +export interface WatchOptions extends ConfigFileOptions { + watch?: { + /** + * If set to true, will use chokidar for file watching (requires installation). + * If set to object, the settings are passed on to chokidar + */ + chokidar?: boolean | { [key: string]: any }; + /** Limit the file-watching to certain files, e.g. 'src/**' */ + include?: string; + /** Prevent files from being watched, e.g. 'node_modules/**' */ + exclude?: string; + } +} + +export interface StartEvent { + code: 'START' +} +export interface EndEvent { + code: 'END' +} +export interface ErrorEvent { + code: 'ERROR' + error: Error +} +export interface FatalEvent { + code: 'FATAL' + error: Error +} +export interface BundleStartEvent { + code: 'BUNDLE_START' + input: string + output: string[] +} +export interface BundleEndEvent { + code: 'BUNDLE_END' + input: string + output: string[] + duration: number +} +export type WatchEvent = StartEvent | EndEvent | ErrorEvent | FatalEvent | BundleStartEvent | BundleEndEvent + +export class Watcher { + /** Listen to the events that are emitted by rollup during watching */ + on(type: 'event', callback: (e: WatchEvent) => void): void + /** Stop watching for file changes */ + close(): void +} + +/** Starts rollup in watch mode. Returns a watcher instance for closing or listening to events */ +export function watch(options: WatchOptions): Watcher diff --git a/types/rollup/rollup-tests.ts b/types/rollup/rollup-tests.ts index 924e675373..7fa0c32330 100644 --- a/types/rollup/rollup-tests.ts +++ b/types/rollup/rollup-tests.ts @@ -1,4 +1,4 @@ -import { rollup, Bundle, Plugin, ConfigFileOptions } from 'rollup' +import { rollup, watch, Bundle, Plugin, ConfigFileOptions } from 'rollup' declare const console: { log(...messages: any[]): void, warn(message: string): void } @@ -69,6 +69,42 @@ async function main() { sourcemapFile: 'bundle.js.map', strict: true, }) + + const watcher = watch({ + input: 'main.js', + output: { + file: 'bundle.js', + format: 'es' + }, + watch: { + chokidar: true + } + }) + + watcher.on('event', e => { + switch (e.code) { + case 'START': + console.log(`We're rolling!`) + return + case 'END': + console.log(`We're all rolled up!`) + return + case 'ERROR': + case 'FATAL': + console.log(e.error.message) + return + case 'BUNDLE_START': + console.log(`Bundling: ${e.input}`) + return + case 'BUNDLE_END': + console.log(`Bundling: ${e.input}`) + return + } + + assertNever(e) + }) + + watcher.close() } main() @@ -94,3 +130,7 @@ export const multiConfig: ConfigFileOptions = { } ] } + +function assertNever(nope: never) { + throw new Error('Oh no!') +} From f24864cbffc0cae2bdc1e4bd1e6746f7da7fe287 Mon Sep 17 00:00:00 2001 From: Denis Malinochkin Date: Sat, 18 Nov 2017 12:20:10 +0300 Subject: [PATCH 073/201] feat(types): Add typings for "http-proxy-agent" package --- .../http-proxy-agent-tests.ts | 12 ++++++++++ types/http-proxy-agent/index.d.ts | 15 ++++++++++++ types/http-proxy-agent/tsconfig.json | 23 +++++++++++++++++++ types/http-proxy-agent/tslint.json | 1 + 4 files changed, 51 insertions(+) create mode 100644 types/http-proxy-agent/http-proxy-agent-tests.ts create mode 100644 types/http-proxy-agent/index.d.ts create mode 100644 types/http-proxy-agent/tsconfig.json create mode 100644 types/http-proxy-agent/tslint.json diff --git a/types/http-proxy-agent/http-proxy-agent-tests.ts b/types/http-proxy-agent/http-proxy-agent-tests.ts new file mode 100644 index 0000000000..f730cd1bde --- /dev/null +++ b/types/http-proxy-agent/http-proxy-agent-tests.ts @@ -0,0 +1,12 @@ +import Agent = require('http-proxy-agent'); + +// $ExpectType HttpProxyAgent +new Agent('url'); +new Agent({}); +new Agent({ host: 'url' }); + +// $ExpectError +new Agent(); + +// $ExpectError +new Agent({ a: 1 }); diff --git a/types/http-proxy-agent/index.d.ts b/types/http-proxy-agent/index.d.ts new file mode 100644 index 0000000000..015508b5d1 --- /dev/null +++ b/types/http-proxy-agent/index.d.ts @@ -0,0 +1,15 @@ +// Type definitions for http-proxy-agent 2.0 +// Project: https://github.com/TooTallNate/node-http-proxy-agent +// Definitions by: mrmlnc +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Agent } from 'http'; +import { Url } from 'url'; + +declare class HttpProxyAgent extends Agent { + constructor(options: string | Url); +} + +export = HttpProxyAgent; diff --git a/types/http-proxy-agent/tsconfig.json b/types/http-proxy-agent/tsconfig.json new file mode 100644 index 0000000000..626d4eaa4c --- /dev/null +++ b/types/http-proxy-agent/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", + "http-proxy-agent-tests.ts" + ] +} diff --git a/types/http-proxy-agent/tslint.json b/types/http-proxy-agent/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/http-proxy-agent/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From aa823497f02b9c030fe0a88fc888f1d1c16639ed Mon Sep 17 00:00:00 2001 From: cx Date: Sat, 18 Nov 2017 23:10:09 +0800 Subject: [PATCH 074/201] #three.js update new function name --- types/three/three-core.d.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index c0468fdecd..21df7b3b01 100644 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -4489,6 +4489,7 @@ export class Vector3 implements Vector { * http://en.wikipedia.org/wiki/Taxicab_geometry */ lengthManhattan(): number; + manhattanDistanceTo():number; /** * Normalizes this vector. From f9886d4f27a4fd9912b777e7708cacf61bbd59e5 Mon Sep 17 00:00:00 2001 From: cx Date: Sat, 18 Nov 2017 23:12:37 +0800 Subject: [PATCH 075/201] update --- types/three/three-core.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index 21df7b3b01..f054fca360 100644 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -4489,7 +4489,7 @@ export class Vector3 implements Vector { * http://en.wikipedia.org/wiki/Taxicab_geometry */ lengthManhattan(): number; - manhattanDistanceTo():number; + manhattanDistanceTo(v:Vector3):number; /** * Normalizes this vector. From 10e05d7aa22d48fdef923483120749d1fb168e65 Mon Sep 17 00:00:00 2001 From: Peter Bartha Date: Sat, 18 Nov 2017 20:07:33 +0100 Subject: [PATCH 076/201] Add 'setSelections' to CodeMirror --- types/codemirror/index.d.ts | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/types/codemirror/index.d.ts b/types/codemirror/index.d.ts index 126eafe013..45e503e068 100644 --- a/types/codemirror/index.d.ts +++ b/types/codemirror/index.d.ts @@ -105,9 +105,9 @@ declare namespace CodeMirror { function signal(target: any, name: string, ...args: any[]): void; type DOMEvent = 'mousedown' | 'dblclick' | 'touchstart' | 'contextmenu' | 'keydown' | 'keypress' | 'keyup' | 'cut' | 'copy' | 'paste' | 'dragstart' | 'dragenter' | 'dragover' | 'dragleave' | 'drop'; - + type CoordsMode = 'window' | 'page' | 'local'; - + interface Token { /** The character(on the given line) at which the token starts. */ start: number; @@ -202,10 +202,10 @@ declare namespace CodeMirror { /** Compute the line at the given pixel height. mode is the relative element to use to compute this line, it may be "window", "page" (the default), or "local" */ lineAtHeight(height: number, mode?: CoordsMode): number; - - /** Computes the height of the top of a line, in the coordinate system specified by mode, it may be "window", - "page" (the default), or "local". When a line below the bottom of the document is specified, the returned value - is the bottom of the last line in the document. By default, the position of the actual text is returned. + + /** Computes the height of the top of a line, in the coordinate system specified by mode, it may be "window", + "page" (the default), or "local". When a line below the bottom of the document is specified, the returned value + is the bottom of the last line in the document. By default, the position of the actual text is returned. If includeWidgets is true and the line has line widgets, the position above the first line widget is returned. */ heightAtLine(line: any, mode?: CoordsMode, includeWidgets?: boolean): number; @@ -292,7 +292,7 @@ declare namespace CodeMirror { charCoords(pos: CodeMirror.Position, mode?: CoordsMode): { left: number; right: number; top: number; bottom: number; }; /** Given an { left , top } object , returns the { line , ch } position that corresponds to it. - The optional mode parameter determines relative to what the coordinates are interpreted. + The optional mode parameter determines relative to what the coordinates are interpreted. It may be "window", "page" (the default), or "local". */ coordsChar(object: { left: number; top: number; }, mode?: CoordsMode): CodeMirror.Position; @@ -512,7 +512,7 @@ declare namespace CodeMirror { /** Get the currently selected code. */ getSelection(): string; - + /** Returns an array containing a string for each selection, representing the content of the selections. */ getSelections(lineSep?: string): Array; @@ -538,6 +538,9 @@ declare namespace CodeMirror { /** Set the selection range.anchor and head should be { line , ch } objects.head defaults to anchor when not given. */ setSelection(anchor: CodeMirror.Position, head: CodeMirror.Position): void; + /** Set and normalize selection ranges and range should be { anchor, head } objects. primary determines which selection is the primary one. */ + setSelections(ranges: Array<{ anchor: CodeMirror.Position, head: CodeMirror.Position }>, primary?: number): void; + /** Similar to setSelection , but will, if shift is held or the extending flag is set, move the head of the selection while leaving the anchor at its current place. pos2 is optional , and can be passed to ensure a region (for example a word or paragraph) will end up selected @@ -779,7 +782,7 @@ declare namespace CodeMirror { /** Determines whether the gutter scrolls along with the content horizontally (false) or whether it stays fixed during horizontal scrolling (true, the default). */ fixedGutter?: boolean; - + /** * Chooses a scrollbar implementation. The default is "native", showing native scrollbars. The core library also * provides the "null" style, which completely hides the scrollbars. Addons can implement additional scrollbar models. From e007354a791761439ddccbe7edac8d0493e1ed18 Mon Sep 17 00:00:00 2001 From: Joshua Goldberg Date: Sat, 18 Nov 2017 15:26:21 -0800 Subject: [PATCH 077/201] Fixed camelCasing for webpack-manifest-plugin fileName It's listed as fileName in the docs. I think this was just a typo. --- types/webpack-manifest-plugin/index.d.ts | 2 +- .../webpack-manifest-plugin/webpack-manifest-plugin-tests.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/types/webpack-manifest-plugin/index.d.ts b/types/webpack-manifest-plugin/index.d.ts index 6c90731424..cb61e42c18 100644 --- a/types/webpack-manifest-plugin/index.d.ts +++ b/types/webpack-manifest-plugin/index.d.ts @@ -34,7 +34,7 @@ declare namespace WebpackManifestPlugin { * The manifest filename in your output directory. * Default: manifest.json */ - filename?: string; + fileName?: string; /** * A path prefix for all file references. Useful for including your output path in the manifest. diff --git a/types/webpack-manifest-plugin/webpack-manifest-plugin-tests.ts b/types/webpack-manifest-plugin/webpack-manifest-plugin-tests.ts index 134e6825e6..3c34f052fa 100644 --- a/types/webpack-manifest-plugin/webpack-manifest-plugin-tests.ts +++ b/types/webpack-manifest-plugin/webpack-manifest-plugin-tests.ts @@ -3,7 +3,7 @@ import path = require('path'); import WebpackManifestPlugin = require('webpack-manifest-plugin'); const options: WebpackManifestPlugin.Options = { - filename: 'manifest.json', + fileName: 'manifest.json', basePath: '/src/', seed: { name: 'Hello world', @@ -28,7 +28,7 @@ const c: Configuration = { plugins: [ new WebpackManifestPlugin(), new WebpackManifestPlugin({ - filename: 'my-manifest.json', + fileName: 'my-manifest.json', basePath: '/app/', seed: { name: 'My Manifest', From e701d8560935de88129c2bbd4a71f35deec2ed52 Mon Sep 17 00:00:00 2001 From: Arturas Molcanovas Date: Sun, 19 Nov 2017 00:34:46 +0000 Subject: [PATCH 078/201] iltorb tests --- types/iltorb/iltorb-tests.ts | 36 ++++++++++++++++++++++++++++++++++++ types/iltorb/index.d.ts | 30 ++++++++++++++++++++++++++++++ types/iltorb/tsconfig.json | 23 +++++++++++++++++++++++ types/iltorb/tslint.json | 3 +++ 4 files changed, 92 insertions(+) create mode 100644 types/iltorb/iltorb-tests.ts create mode 100644 types/iltorb/index.d.ts create mode 100644 types/iltorb/tsconfig.json create mode 100644 types/iltorb/tslint.json diff --git a/types/iltorb/iltorb-tests.ts b/types/iltorb/iltorb-tests.ts new file mode 100644 index 0000000000..4e425b36f6 --- /dev/null +++ b/types/iltorb/iltorb-tests.ts @@ -0,0 +1,36 @@ +import {createReadStream, createWriteStream} from 'fs'; +import * as br from 'iltorb'; + +const opts: br.BrotliEncodeParams = { + disable_literal_context_modeling: false, + lgblock: 0, + lgwin: 22, + mode: 0, + quality: 11, + size_hint: 0 +}; + +const onCompress = (err1: Error | null | undefined, compressed: Buffer) => { + br.decompress(compressed, (err2: Error | null | undefined, decompressed: Buffer) => { + console.log(decompressed.toString()); + }); +}; + +br.compress(Buffer.from('foo', 'utf8'), onCompress); + +br.compress(Buffer.from('foo', 'utf8'), opts, onCompress); + +createReadStream(__filename) + .pipe(br.compressStream()) + .pipe(createWriteStream('foo.ts')); + +createReadStream(__dirname) + .pipe(br.compressStream(opts)) + .pipe(createWriteStream('bar.ts')); + +createReadStream('bar.ts') + .pipe(br.decompressStream()) + .pipe(createWriteStream('qux.ts')); + +br.decompressSync(br.compressSync(Buffer.from('foo', 'utf8'))); +br.decompressSync(br.compressSync(Buffer.from('foo', 'utf8'), opts)); diff --git a/types/iltorb/index.d.ts b/types/iltorb/index.d.ts new file mode 100644 index 0000000000..ffec8bc6a6 --- /dev/null +++ b/types/iltorb/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for iltorb 2.0 +// Project: https://github.com/MayhemYDG/iltorb +// Definitions by: Arturas Molcanovas +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import { Transform } from 'stream'; + +export interface BrotliEncodeParams { + disable_literal_context_modeling?: boolean; + lgblock?: number; + lgwin?: number; + mode?: number; + quality?: number; + size_hint?: number; +} + +export type IltorbCallback = (err: Error | null | undefined, output: Buffer) => any; + +export function compress(buffer: Buffer, options: BrotliEncodeParams, callback: IltorbCallback): void; +export function compress(buffer: Buffer, callback: IltorbCallback): void; + +export function decompress(buffer: Buffer, callback: IltorbCallback): void; + +export function compressSync(buffer: Buffer, options?: BrotliEncodeParams): Buffer; +export function decompressSync(buffer: Buffer): Buffer; + +export function compressStream(options?: BrotliEncodeParams): Transform; +export function decompressStream(): Transform; diff --git a/types/iltorb/tsconfig.json b/types/iltorb/tsconfig.json new file mode 100644 index 0000000000..c12ff988ba --- /dev/null +++ b/types/iltorb/tsconfig.json @@ -0,0 +1,23 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es5" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "iltorb-tests.ts" + ] +} diff --git a/types/iltorb/tslint.json b/types/iltorb/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/iltorb/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} From f26b4401fea3bcb02404c64d7520dafef71305ef Mon Sep 17 00:00:00 2001 From: Arturas Molcanovas Date: Sun, 19 Nov 2017 00:36:31 +0000 Subject: [PATCH 079/201] fix iltorb lint --- types/iltorb/iltorb-tests.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/iltorb/iltorb-tests.ts b/types/iltorb/iltorb-tests.ts index 4e425b36f6..5c30fcd3b5 100644 --- a/types/iltorb/iltorb-tests.ts +++ b/types/iltorb/iltorb-tests.ts @@ -1,4 +1,4 @@ -import {createReadStream, createWriteStream} from 'fs'; +import { createReadStream, createWriteStream } from 'fs'; import * as br from 'iltorb'; const opts: br.BrotliEncodeParams = { From 63b3d353cd0983ccaf5f5d1610e7be9803045f4f Mon Sep 17 00:00:00 2001 From: Arturas Molcanovas Date: Sun, 19 Nov 2017 00:40:30 +0000 Subject: [PATCH 080/201] iltorb callback return type set to void --- types/iltorb/index.d.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/iltorb/index.d.ts b/types/iltorb/index.d.ts index ffec8bc6a6..bd6cd88fb7 100644 --- a/types/iltorb/index.d.ts +++ b/types/iltorb/index.d.ts @@ -16,7 +16,7 @@ export interface BrotliEncodeParams { size_hint?: number; } -export type IltorbCallback = (err: Error | null | undefined, output: Buffer) => any; +export type IltorbCallback = (err: Error | null | undefined, output: Buffer) => void; export function compress(buffer: Buffer, options: BrotliEncodeParams, callback: IltorbCallback): void; export function compress(buffer: Buffer, callback: IltorbCallback): void; From efcfa2916364b838ebfbedf6bd16fecf926c3780 Mon Sep 17 00:00:00 2001 From: AJ Richardson Date: Sat, 18 Nov 2017 22:49:43 -0500 Subject: [PATCH 081/201] Fix the remaining strictFunctionTypes issues --- types/lodash/index.d.ts | 178 ++++++++++++++++++++++------------- types/lodash/lodash-tests.ts | 103 ++++---------------- 2 files changed, 131 insertions(+), 150 deletions(-) diff --git a/types/lodash/index.d.ts b/types/lodash/index.d.ts index fafa7f6b5c..5be5358b4b 100644 --- a/types/lodash/index.d.ts +++ b/types/lodash/index.d.ts @@ -1234,7 +1234,7 @@ declare namespace _ { */ findIndex( array: List | null | undefined, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): number; } @@ -1245,7 +1245,7 @@ declare namespace _ { */ findIndex( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): number; } @@ -1256,7 +1256,7 @@ declare namespace _ { */ findIndex( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; } @@ -1282,7 +1282,7 @@ declare namespace _ { */ findLastIndex( array: List | null | undefined, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): number; } @@ -1293,7 +1293,7 @@ declare namespace _ { */ findLastIndex( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): number; } @@ -1304,7 +1304,7 @@ declare namespace _ { */ findLastIndex( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; } @@ -4315,6 +4315,14 @@ declare namespace _ { * @param thisArg The this binding of iteratee. * @return Returns the composed aggregate object. */ + countBy( + collection: string | null | undefined, + iteratee?: StringIterator + ): Dictionary; + + /** + * @see _.countBy + */ countBy( collection: List | null | undefined, iteratee?: ListIteratee @@ -4338,6 +4346,14 @@ declare namespace _ { } interface LoDashImplicitWrapper { + /** + * @see _.countBy + */ + countBy( + this: LoDashImplicitWrapper, + iteratee?: StringIterator + ): LoDashImplicitWrapper>; + /** * @see _.countBy */ @@ -4364,6 +4380,14 @@ declare namespace _ { } interface LoDashExplicitWrapper { + /** + * @see _.countBy + */ + countBy( + this: LoDashExplicitWrapper, + iteratee?: StringIterator + ): LoDashExplicitWrapper>; + /** * @see _.countBy */ @@ -4479,7 +4503,7 @@ declare namespace _ { */ every( collection: List | null | undefined, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): boolean; /** @@ -4487,7 +4511,7 @@ declare namespace _ { */ every( collection: NumericDictionary | null | undefined, - predicate?: NumericDictionaryIterateeBoolean + predicate?: NumericDictionaryIterateeCustom ): boolean; /** @@ -4495,7 +4519,7 @@ declare namespace _ { */ every( collection: T | null | undefined, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): boolean; } @@ -4505,7 +4529,7 @@ declare namespace _ { */ every( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): boolean; /** @@ -4513,7 +4537,7 @@ declare namespace _ { */ every( this: LoDashImplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): boolean; /** @@ -4521,7 +4545,7 @@ declare namespace _ { */ every( this: LoDashImplicitWrapper | null | undefined>, - predicate?: NumericDictionaryIterateeBoolean + predicate?: NumericDictionaryIterateeCustom ): boolean; } @@ -4531,7 +4555,7 @@ declare namespace _ { */ every( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): LoDashExplicitWrapper; /** @@ -4539,7 +4563,7 @@ declare namespace _ { */ every( this: LoDashExplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): LoDashExplicitWrapper; /** @@ -4547,7 +4571,7 @@ declare namespace _ { */ every( this: LoDashExplicitWrapper | null | undefined>, - predicate?: NumericDictionaryIterateeBoolean + predicate?: NumericDictionaryIterateeCustom ): LoDashExplicitWrapper; } @@ -4589,7 +4613,7 @@ declare namespace _ { */ filter( collection: List | null | undefined, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): T[]; /** @@ -4605,7 +4629,7 @@ declare namespace _ { */ filter( collection: T | null | undefined, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): Array; } @@ -4631,7 +4655,7 @@ declare namespace _ { */ filter( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): LoDashImplicitWrapper; /** @@ -4647,7 +4671,7 @@ declare namespace _ { */ filter( this: LoDashImplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): LoDashImplicitWrapper>; } @@ -4673,7 +4697,7 @@ declare namespace _ { */ filter( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): LoDashExplicitWrapper; /** @@ -4689,7 +4713,7 @@ declare namespace _ { */ filter( this: LoDashExplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): LoDashExplicitWrapper>; } @@ -4724,7 +4748,7 @@ declare namespace _ { */ find( collection: List | null | undefined, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): T|undefined; @@ -4742,7 +4766,7 @@ declare namespace _ { */ find( collection: T | null | undefined, - predicate?: ObjectIterateeBoolean, + predicate?: ObjectIterateeCustom, fromIndex?: number ): T[keyof T]|undefined; } @@ -4762,7 +4786,7 @@ declare namespace _ { */ find( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): T|undefined; @@ -4780,7 +4804,7 @@ declare namespace _ { */ find( this: LoDashImplicitWrapper, - predicate?: ObjectIterateeBoolean, + predicate?: ObjectIterateeCustom, fromIndex?: number ): T[keyof T]|undefined; } @@ -4800,7 +4824,7 @@ declare namespace _ { */ find( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; @@ -4818,7 +4842,7 @@ declare namespace _ { */ find( this: LoDashExplicitWrapper, - predicate?: ObjectIterateeBoolean, + predicate?: ObjectIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; } @@ -4844,7 +4868,7 @@ declare namespace _ { */ findLast( collection: List | null | undefined, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): T|undefined; @@ -4862,7 +4886,7 @@ declare namespace _ { */ findLast( collection: T | null | undefined, - predicate?: ObjectIterateeBoolean, + predicate?: ObjectIterateeCustom, fromIndex?: number ): T[keyof T]|undefined; } @@ -4882,7 +4906,7 @@ declare namespace _ { */ findLast( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): T | undefined; @@ -4900,7 +4924,7 @@ declare namespace _ { */ findLast( this: LoDashImplicitWrapper, - predicate?: ObjectIterateeBoolean, + predicate?: ObjectIterateeCustom, fromIndex?: number ): T[keyof T]|undefined; } @@ -4920,7 +4944,7 @@ declare namespace _ { */ findLast( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean, + predicate?: ListIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; @@ -4938,7 +4962,7 @@ declare namespace _ { */ findLast( this: LoDashExplicitWrapper, - predicate?: ObjectIterateeBoolean, + predicate?: ObjectIterateeCustom, fromIndex?: number ): LoDashExplicitWrapper; } @@ -5849,9 +5873,17 @@ declare namespace _ { * @param thisArg The this binding of iteratee. * @return Returns the composed aggregate object. */ + keyBy( + collection: string | null | undefined, + iteratee?: StringIterator + ): Dictionary; + + /** + * @see _.keyBy + */ keyBy( collection: List | null | undefined, - iteratee?: ListIteratee + iteratee?: ListIterateeCustom ): Dictionary; /** @@ -5859,7 +5891,7 @@ declare namespace _ { */ keyBy( collection: T | null | undefined, - iteratee?: ObjectIteratee + iteratee?: ObjectIterateeCustom ): Dictionary; /** @@ -5867,17 +5899,25 @@ declare namespace _ { */ keyBy( collection: NumericDictionary | null | undefined, - iteratee?: NumericDictionaryIteratee + iteratee?: NumericDictionaryIterateeCustom ): Dictionary; } interface LoDashImplicitWrapper { + /** + * @see _.keyBy + */ + keyBy( + this: LoDashImplicitWrapper, + iteratee?: StringIterator + ): LoDashImplicitWrapper>; + /** * @see _.keyBy */ keyBy( this: LoDashImplicitWrapper | null | undefined>, - iteratee?: ListIteratee + iteratee?: ListIterateeCustom ): LoDashImplicitWrapper>; /** @@ -5885,7 +5925,7 @@ declare namespace _ { */ keyBy( this: LoDashImplicitWrapper, - iteratee?: ObjectIteratee + iteratee?: ObjectIterateeCustom ): LoDashImplicitWrapper>; /** @@ -5893,17 +5933,25 @@ declare namespace _ { */ keyBy( this: LoDashImplicitWrapper | null | undefined>, - iteratee?: NumericDictionaryIteratee + iteratee?: NumericDictionaryIterateeCustom ): LoDashImplicitWrapper>; } interface LoDashExplicitWrapper { + /** + * @see _.keyBy + */ + keyBy( + this: LoDashExplicitWrapper, + iteratee?: StringIterator + ): LoDashExplicitWrapper>; + /** * @see _.keyBy */ keyBy( this: LoDashExplicitWrapper | null | undefined>, - iteratee?: ListIteratee + iteratee?: ListIterateeCustom ): LoDashExplicitWrapper>; /** @@ -5911,7 +5959,7 @@ declare namespace _ { */ keyBy( this: LoDashExplicitWrapper, - iteratee?: ObjectIteratee + iteratee?: ObjectIterateeCustom ): LoDashExplicitWrapper>; /** @@ -5919,7 +5967,7 @@ declare namespace _ { */ keyBy( this: LoDashExplicitWrapper | null | undefined>, - iteratee?: NumericDictionaryIteratee + iteratee?: NumericDictionaryIterateeCustom ): LoDashExplicitWrapper>; } @@ -6718,7 +6766,7 @@ declare namespace _ { */ reject( collection: List | null | undefined, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): T[]; /** @@ -6726,7 +6774,7 @@ declare namespace _ { */ reject( collection: T | null | undefined, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): Array; } @@ -6744,7 +6792,7 @@ declare namespace _ { */ reject( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): LoDashImplicitWrapper; /** @@ -6752,7 +6800,7 @@ declare namespace _ { */ reject( this: LoDashImplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): LoDashImplicitWrapper>; } @@ -6770,7 +6818,7 @@ declare namespace _ { */ reject( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): LoDashExplicitWrapper; /** @@ -6778,7 +6826,7 @@ declare namespace _ { */ reject( this: LoDashExplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): LoDashExplicitWrapper>; } @@ -6992,7 +7040,7 @@ declare namespace _ { */ some( collection: List | null | undefined, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): boolean; /** @@ -7000,7 +7048,7 @@ declare namespace _ { */ some( collection: T | null | undefined, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): boolean; /** @@ -7008,7 +7056,7 @@ declare namespace _ { */ some( collection: NumericDictionary | null | undefined, - predicate?: NumericDictionaryIterateeBoolean + predicate?: NumericDictionaryIterateeCustom ): boolean; } @@ -7018,7 +7066,7 @@ declare namespace _ { */ some( this: LoDashImplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): boolean; /** @@ -7026,7 +7074,7 @@ declare namespace _ { */ some( this: LoDashImplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): boolean; /** @@ -7034,7 +7082,7 @@ declare namespace _ { */ some( this: LoDashImplicitWrapper | null | undefined>, - predicate?: NumericDictionaryIterateeBoolean + predicate?: NumericDictionaryIterateeCustom ): boolean; } @@ -7044,7 +7092,7 @@ declare namespace _ { */ some( this: LoDashExplicitWrapper | null | undefined>, - predicate?: ListIterateeBoolean + predicate?: ListIterateeCustom ): LoDashExplicitWrapper; /** @@ -7052,7 +7100,7 @@ declare namespace _ { */ some( this: LoDashExplicitWrapper, - predicate?: ObjectIterateeBoolean + predicate?: ObjectIterateeCustom ): LoDashExplicitWrapper; /** @@ -7060,7 +7108,7 @@ declare namespace _ { */ some( this: LoDashExplicitWrapper | null | undefined>, - predicate?: NumericDictionaryIterateeBoolean + predicate?: NumericDictionaryIterateeCustom ): LoDashExplicitWrapper; } @@ -9315,14 +9363,16 @@ declare namespace _ { /** * @see _.conformsTo */ - conformsTo(source: ConformsPredicateObject): boolean; + conformsTo(this: LoDashImplicitWrapper, source: ConformsPredicateObject): boolean; + // Note: we can't use TValue here, because it generates a typescript error when strictFunctionTypes is enabled. } interface LoDashExplicitWrapper { /** * @see _.conformsTo */ - conformsTo(source: ConformsPredicateObject): LoDashExplicitWrapper; + conformsTo(this: LoDashImplicitWrapper, source: ConformsPredicateObject): LoDashExplicitWrapper; + // Note: we can't use TValue here, because it generates a typescript error when strictFunctionTypes is enabled. } type CondPair = [(val: T) => boolean, (val: T) => R] @@ -10723,7 +10773,7 @@ declare namespace _ { /** * @see _.toArray */ - //toArray(): LoDashImplicitWrapper>; + toArray(this: LoDashImplicitWrapper): LoDashImplicitWrapper>; } interface LoDashExplicitWrapper { @@ -10735,7 +10785,7 @@ declare namespace _ { /** * @see _.toArray */ - //toArray(): LoDashExplicitWrapper>; + toArray(this: LoDashImplicitWrapper): LoDashExplicitWrapper>; } //_.toPlainObject @@ -17019,13 +17069,13 @@ declare namespace _ { type ArrayIterator = (value: T, index: number, collection: T[]) => TResult; type ListIterator = (value: T, index: number, collection: List) => TResult; type ListIteratee = ListIterator | string | [string, any] | PartialDeep; - type ListIterateeBoolean = ListIterator | string | [string, any] | PartialDeep; + type ListIterateeCustom = ListIterator | string | [string, any] | PartialDeep; type ListIteratorTypeGuard = (value: T, index: number, collection: List) => value is S; // Note: key should be string, not keyof T, because the actual object may contain extra properties that were not specified in the type. type ObjectIterator = (value: TObject[keyof TObject], key: string, collection: TObject) => TResult; type ObjectIteratee = ObjectIterator | string | [string, any] | PartialDeep; - type ObjectIterateeBoolean = ObjectIterator | string | [string, any] | PartialDeep; + type ObjectIterateeCustom = ObjectIterator | string | [string, any] | PartialDeep; type ObjectIteratorTypeGuard = (value: TObject[keyof TObject], key: string, collection: TObject) => value is S; type DictionaryIterator = ObjectIterator, TResult>; @@ -17034,7 +17084,7 @@ declare namespace _ { type NumericDictionaryIterator = (value: T, key: number, collection: NumericDictionary) => TResult; type NumericDictionaryIteratee = NumericDictionaryIterator | string | [string, any] | PartialDeep; - type NumericDictionaryIterateeBoolean = NumericDictionaryIterator | string | [string, any] | PartialDeep; + type NumericDictionaryIterateeCustom = NumericDictionaryIterator | string | [string, any] | PartialDeep; type StringIterator = (char: string, index: number, string: string) => TResult; diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index e40569204d..cca7c239c7 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -4,86 +4,19 @@ interface IFoodOrganic { name: string; organic: boolean; } - -interface IFoodType { - name: string; - type: string; -} - -interface IFoodCombined { - name: string; - organic: boolean; - type: string; -} - -interface IStoogesQuote { - name: string; - quotes: string[]; -} - interface IStoogesAge { name: string; age: number; } -interface IStoogesCombined { - name: string; - age: number; - quotes: string[]; -} - -interface IKey { - dir: string; - code: number; -} - -interface IDictionary { - [index: string]: T; -} - const foodsOrganic: IFoodOrganic[] = [ { name: 'banana', organic: true }, { name: 'beet', organic: false }, ]; -const foodsType: IFoodType[] = [ - { name: 'apple', type: 'fruit' }, - { name: 'banana', type: 'fruit' }, - { name: 'beet', type: 'vegetable' } -]; -const foodsCombined: IFoodCombined[] = [ - { 'name': 'apple', 'organic': false, 'type': 'fruit' }, - { 'name': 'carrot', 'organic': true, 'type': 'vegetable' } -]; - -const stoogesQuotes: IStoogesQuote[] = [ - { 'name': 'curly', 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }, - { 'name': 'moe', 'quotes': ['Spread out!', 'You knucklehead!'] } -]; const stoogesAges: IStoogesAge[] = [ { 'name': 'moe', 'age': 40 }, { 'name': 'larry', 'age': 50 } ]; -const stoogesAgesDict: IDictionary = { - first: { 'name': 'moe', 'age': 40 }, - second: { 'name': 'larry', 'age': 50 } -}; -const stoogesCombined: IStoogesCombined[] = [ - { 'name': 'curly', 'age': 30, 'quotes': ['Oh, a wise guy, eh?', 'Poifect!'] }, - { 'name': 'moe', 'age': 40, 'quotes': ['Spread out!', 'You knucklehead!'] } -]; - -const keys: IKey[] = [ - { 'dir': 'left', 'code': 97 }, - { 'dir': 'right', 'code': 100 } -]; - -class Dog { - constructor(public name: string) { } - - bark() { - // Woof - } -} let result: any; @@ -4591,9 +4524,9 @@ namespace TestFilter { let obj: any = {}; let dictionary: _.Dictionary | null | undefined = obj; - let stringIterator: (char: string, index: number, string: string) => any = (char: string, index: number, string: string) => 1; - let listIterator: (value: TResult, index: number, collection: _.List) => any = (value: TResult, index: number, collection: _.List) => 1; - let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any = (value: TResult, key: string, collection: _.Dictionary) => 1; + let stringIterator = (char: string, index: number, string: string) => true; + let listIterator = (value: TResult, index: number, collection: _.List) => true; + let dictionaryIterator = (value: TResult, key: string, collection: _.Dictionary) => true; { let result: string[]; @@ -5207,7 +5140,7 @@ namespace TestFlatMapDepth { let listIterator: (value: number|number[], index: number, collection: _.List) => _.ListOfRecursiveArraysOrValues = (a, b, c) =>[ 1]; - let dictionaryIterator: (value: number|number[], key: number, collection: _.Dictionary) => _.ListOfRecursiveArraysOrValues = (a, b, c) => [1]; + let dictionaryIterator: (value: number|number[], key: string, collection: _.Dictionary) => _.ListOfRecursiveArraysOrValues = (a, b, c) => [1]; let numericDictionaryIterator: (value: number|number[], key: number, collection: _.NumericDictionary) => _.ListOfRecursiveArraysOrValues = (a, b, c) => [1]; @@ -5776,8 +5709,8 @@ namespace TestGroupBy { { let result: _.Dictionary; - result = _.groupBy(''); - result = _.groupBy('', stringIterator); + result = _.groupBy(''); + result = _.groupBy('', stringIterator); } { @@ -5909,16 +5842,16 @@ namespace TestKeyBy { let dictionary: _.Dictionary | null | undefined = obj; let numericDictionary: _.NumericDictionary | null | undefined = obj; - let stringIterator: (value: string, index: number, collection: string) => any = (value: string, index: number, collection: string) => 1; - let listIterator: (value: SampleObject, index: number, collection: _.List) => any = (value: SampleObject, index: number, collection: _.List) => 1; - let dictionaryIterator: (value: SampleObject, key: string, collection: _.Dictionary) => any = (value: SampleObject, key: string, collection: _.Dictionary) => 1; - let numericDictionaryIterator: (value: SampleObject, key: number, collection: _.NumericDictionary) => any = (value: SampleObject, key: number, collection: _.NumericDictionary) => 1; + let stringIterator = (value: string, index: number, collection: string) => "a"; + let listIterator = (value: SampleObject, index: number, collection: _.List) => 1; + let dictionaryIterator = (value: SampleObject, key: string, collection: _.Dictionary) => Symbol.name; + let numericDictionaryIterator = (value: SampleObject, key: number, collection: _.NumericDictionary) => "a"; { let result: _.Dictionary; - result = _.keyBy('abcd'); - result = _.keyBy('abcd', stringIterator); + result = _.keyBy('abcd'); + result = _.keyBy('abcd', stringIterator); } { @@ -6464,9 +6397,9 @@ namespace TestReject { let obj: any = {}; let dictionary: _.Dictionary | null | undefined = obj; - let stringIterator: (char: string, index: number, string: string) => any = (char: string, index: number, string: string) => 1; - let listIterator: (value: TResult, index: number, collection: _.List) => any = (value: TResult, index: number, collection: _.List) => 1; - let dictionaryIterator: (value: TResult, key: string, collection: _.Dictionary) => any = (value: TResult, key: string, collection: _.Dictionary) => 1; + let stringIterator = (char: string, index: number, string: string) => true; + let listIterator = (value: TResult, index: number, collection: _.List) => true; + let dictionaryIterator = (value: TResult, key: string, collection: _.Dictionary) => true; { let result: string[]; @@ -8667,9 +8600,7 @@ namespace TestIsEqual { // _.isEqualWith namespace TestIsEqualWith { - let customizer = (value: any, other: any, indexOrKey: number|string|undefined, parent: any, otherParent: any, stack: any) => { - return value ? undefined : true; - }; + let customizer = (value: any, other: any, indexOrKey: number|string|symbol|undefined, parent: any, otherParent: any, stack: any) => true; { let result: boolean; @@ -8873,7 +8804,7 @@ namespace TestIsMatch { // _.isMatchWith namespace TestIsMatchWith { - let testIsMatchCustiomizerFn = (value: any, other: any, indexOrKey: number|string) => true; + let testIsMatchCustiomizerFn = (value: any, other: any, indexOrKey: number|string|symbol) => true; let result: boolean; From a8408bce17669bd6bb0516890347dea6cf0c1578 Mon Sep 17 00:00:00 2001 From: AJ Richardson Date: Sat, 18 Nov 2017 22:57:55 -0500 Subject: [PATCH 082/201] lodash: revert back to old constant types. The old types seem to work again, so no need to use the workaround. --- types/lodash/index.d.ts | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/types/lodash/index.d.ts b/types/lodash/index.d.ts index 5be5358b4b..a19f4aa4a1 100644 --- a/types/lodash/index.d.ts +++ b/types/lodash/index.d.ts @@ -16128,18 +16128,14 @@ declare namespace _ { /** * @see _.constant */ - constant(this: LoDashImplicitWrapper): LoDashImplicitWrapper<() => T>; - // Note: we can't use TValue here because of an issue with dtslint. Using T as a workaround; change back to TValue once dtsLint is working. - // constant(): LoDashImplicitWrapper<() => TValue>; + constant(): LoDashImplicitWrapper<() => TValue>; } interface LoDashExplicitWrapper { /** * @see _.constant */ - constant(this: LoDashExplicitWrapper): LoDashExplicitWrapper<() => T>; - // Note: we can't use TValue here because of an issue with dtslint. Using T as a workaround; change back to TValue once dtsLint is working. - // constant(): LoDashExplicitWrapper<() => TValue>; + constant(): LoDashExplicitWrapper<() => TValue>; } //_.defaultTo From 0a4a4f34397feedfcfdacf8884b94910790016f4 Mon Sep 17 00:00:00 2001 From: Nico Jansen Date: Sun, 19 Nov 2017 10:31:08 +0100 Subject: [PATCH 083/201] feat(download): Add download types --- types/download/download-tests.ts | 30 +++++++++++++++++++++++ types/download/index.d.ts | 41 ++++++++++++++++++++++++++++++++ types/download/tsconfig.json | 23 ++++++++++++++++++ types/download/tslint.json | 1 + 4 files changed, 95 insertions(+) create mode 100644 types/download/download-tests.ts create mode 100644 types/download/index.d.ts create mode 100644 types/download/tsconfig.json create mode 100644 types/download/tslint.json diff --git a/types/download/download-tests.ts b/types/download/download-tests.ts new file mode 100644 index 0000000000..7a498ef0dd --- /dev/null +++ b/types/download/download-tests.ts @@ -0,0 +1,30 @@ +import * as fs from 'fs'; +import download = require('download'); + +download('http://unicorn.com/foo.jpg', 'dist').then(() => { + console.log('done!'); +}); + +download('http://unicorn.com/foo.jpg').then(data => { + fs.writeFileSync('dist/foo.jpg', data); +}); + +download('unicorn.com/foo.jpg').pipe(fs.createWriteStream('dist/foo.jpg')); + +download('unicorn.com/foo.jpg', 'dest', { + body: '', + decompress: true, + encoding: 'utf8', + extract: true, + filename: 'filename', + followRedirect: true, + proxy: '', + query: '', + retries: (retry: number, error: any) => 4, + timeout: { + connect: 20, + request: 20, + socket: 20 + }, + useElectronNet: true +}); diff --git a/types/download/index.d.ts b/types/download/index.d.ts new file mode 100644 index 0000000000..f3af9778bf --- /dev/null +++ b/types/download/index.d.ts @@ -0,0 +1,41 @@ +// Type definitions for download 6.2 +// Project: https://github.com/kevva/download +// Definitions by: Nico Jansen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// + +interface TimeoutOptions { + connect?: number; + socket?: number; + request?: number; +} +type RetryFunction = (retry: number, error: any) => number; + +interface DownloadOptions { + body?: string | Buffer | NodeJS.ReadableStream; + encoding?: string | null; + query?: string | object; + timeout?: number | TimeoutOptions; + retries?: number | RetryFunction; + followRedirect?: boolean; + decompress?: boolean; + useElectronNet?: boolean; + /** + * If set to true, try extracting the file using decompress. + */ + extract?: boolean; + /** + * Name of the saved file. + */ + filename?: string; + /** + * Proxy endpoint + */ + proxy?: string; +} + +declare function download(url: string, destination?: string, options?: DownloadOptions): Promise & NodeJS.WritableStream & NodeJS.ReadableStream; + +export = download; diff --git a/types/download/tsconfig.json b/types/download/tsconfig.json new file mode 100644 index 0000000000..634ae5ab32 --- /dev/null +++ b/types/download/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", + "download-tests.ts" + ] +} diff --git a/types/download/tslint.json b/types/download/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/download/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From 934892c37d7ba758cd3f3f09d8a7fff1bcc807c0 Mon Sep 17 00:00:00 2001 From: johanblumenberg Date: Sun, 19 Nov 2017 12:44:22 +0100 Subject: [PATCH 084/201] Update css types Make all of the AtRule interfaces inherit from Node. Break out StyleRules from Stylesheet, as it's own type. This is useful when using rework, which is only given the Stylesheet.stylesheet object. Change StyleRules proeprty rules to be mandatory. It is always set. --- types/css/index.d.ts | 41 +++++++++++++++++++++++------------------ 1 file changed, 23 insertions(+), 18 deletions(-) diff --git a/types/css/index.d.ts b/types/css/index.d.ts index c892d5c3a2..be8f1323a0 100644 --- a/types/css/index.d.ts +++ b/types/css/index.d.ts @@ -112,7 +112,7 @@ export interface Comment extends Node { /** * The @charset at-rule. */ -export interface Charset { +export interface Charset extends Node { /** The part following @charset. */ charset?: string; } @@ -120,7 +120,7 @@ export interface Charset { /** * The @custom-media at-rule */ -export interface CustomMedia { +export interface CustomMedia extends Node { /** The ---prefixed name. */ name?: string; /** The part following the name. */ @@ -130,7 +130,7 @@ export interface CustomMedia { /** * The @document at-rule. */ -export interface Document { +export interface Document extends Node { /** The part following @document. */ document?: string; /** The vendor prefix in @document, or undefined if there is none. */ @@ -142,7 +142,7 @@ export interface Document { /** * The @font-face at-rule. */ -export interface FontFace { +export interface FontFace extends Node { /** Array of nodes with the types declaration and comment. */ declarations?: Array; } @@ -150,7 +150,7 @@ export interface FontFace { /** * The @host at-rule. */ -export interface Host { +export interface Host extends Node { /** Array of nodes with the types rule, comment and any of the at-rule types. */ rules?: Array; } @@ -158,7 +158,7 @@ export interface Host { /** * The @import at-rule. */ -export interface Import { +export interface Import extends Node { /** The part following @import. */ import?: string; } @@ -166,7 +166,7 @@ export interface Import { /** * The @keyframes at-rule. */ -export interface KeyFrames { +export interface KeyFrames extends Node { /** The name of the keyframes rule. */ name?: string; /** The vendor prefix in @keyframes, or undefined if there is none. */ @@ -175,7 +175,7 @@ export interface KeyFrames { keyframes?: Array; } -export interface KeyFrame { +export interface KeyFrame extends Node { /** The list of "selectors" of the keyframe rule, split on commas. Each “selector” is trimmed from whitespace. */ values?: Array; /** Array of nodes with the types declaration and comment. */ @@ -185,7 +185,7 @@ export interface KeyFrame { /** * The @media at-rule. */ -export interface Media { +export interface Media extends Node { /** The part following @media. */ media?: string; /** Array of nodes with the types rule, comment and any of the at-rule types. */ @@ -195,7 +195,7 @@ export interface Media { /** * The @namespace at-rule. */ -export interface Namespace { +export interface Namespace extends Node { /** The part following @namespace. */ namespace?: string; } @@ -203,7 +203,7 @@ export interface Namespace { /** * The @page at-rule. */ -export interface Page { +export interface Page extends Node { /** The list of selectors of the rule, split on commas. Each selector is trimmed from whitespace and comments. */ selectors?: Array; /** Array of nodes with the types declaration and comment. */ @@ -213,7 +213,7 @@ export interface Page { /** * The @supports at-rule. */ -export interface Supports { +export interface Supports extends Node { /** The part following @supports. */ supports?: string; /** Array of nodes with the types rule, comment and any of the at-rule types. */ @@ -223,16 +223,21 @@ export interface Supports { /** All at-rules. */ export type AtRule = Charset | CustomMedia | Document | FontFace | Host | Import | KeyFrames | Media | Namespace | Page | Supports; +/** + * A collection of rules + */ +export interface StyleRules { + /** Array of nodes with the types rule, comment and any of the at-rule types. */ + rules: Array; + /** Array of Errors. Errors collected during parsing when option silent is true. */ + parsingErrors?: Array +} + /** * The root node returned by css.parse. */ export interface Stylesheet extends Node { - stylesheet?: { - /** Array of nodes with the types rule, comment and any of the at-rule types. */ - rules?: Array; - /** Array of Errors. Errors collected during parsing when option silent is true. */ - parsingErrors?: Array - }; + stylesheet?: StyleRules; } // --------------------------------------------------------------------------------- From 42832414db8785c30d82c3dc3772bd986cbd27d4 Mon Sep 17 00:00:00 2001 From: Uri Shaked Date: Sun, 19 Nov 2017 13:54:11 +0200 Subject: [PATCH 085/201] [beats] Add typings --- types/beats/beats-tests.ts | 11 +++++++++++ types/beats/index.d.ts | 19 +++++++++++++++++++ types/beats/tsconfig.json | 23 +++++++++++++++++++++++ types/beats/tslint.json | 1 + 4 files changed, 54 insertions(+) create mode 100644 types/beats/beats-tests.ts create mode 100644 types/beats/index.d.ts create mode 100644 types/beats/tsconfig.json create mode 100644 types/beats/tslint.json diff --git a/types/beats/beats-tests.ts b/types/beats/beats-tests.ts new file mode 100644 index 0000000000..32acdf0da5 --- /dev/null +++ b/types/beats/beats-tests.ts @@ -0,0 +1,11 @@ +import * as beats from 'beats'; + +const bins: beats.Bin[] = [ + { lo: 0, hi: 512, threshold: 0, decay: 0.005 }, + { lo: 512, hi: 1024, threshold: 0, decay: 0.005 }, +]; + +const detect = beats(bins, 1); + +const frequencies = new Uint8Array(1024); +const result = detect(frequencies); diff --git a/types/beats/index.d.ts b/types/beats/index.d.ts new file mode 100644 index 0000000000..f63530311e --- /dev/null +++ b/types/beats/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for beats 0.0 +// Project: https://github.com/hughsk/beats/ +// Definitions by: Uri Shaked +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = beats; + +type DetectFunction = (frequencies: Uint8Array | Float32Array | ReadonlyArray, dt?: number) => Float32Array; + +declare function beats(bins: ReadonlyArray, minSeparation?: number): DetectFunction; + +declare namespace beats { + interface Bin { + lo: number; + hi: number; + threshold: number; + decay: number; + } +} diff --git a/types/beats/tsconfig.json b/types/beats/tsconfig.json new file mode 100644 index 0000000000..89bd0b5995 --- /dev/null +++ b/types/beats/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", + "beats-tests.ts" + ] +} diff --git a/types/beats/tslint.json b/types/beats/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/beats/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From c49ab1c37bf43923cf784c6ce1db584ccaffad9a Mon Sep 17 00:00:00 2001 From: AJ Richardson Date: Sun, 19 Nov 2017 08:19:44 -0500 Subject: [PATCH 086/201] lodash: fix compile error with _.pick --- types/lodash/index.d.ts | 19 +++++++++++++++++++ types/lodash/lodash-tests.ts | 16 +++++++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/types/lodash/index.d.ts b/types/lodash/index.d.ts index a19f4aa4a1..a0eaef941c 100644 --- a/types/lodash/index.d.ts +++ b/types/lodash/index.d.ts @@ -14398,6 +14398,9 @@ declare namespace _ { ...props: Array> ): Pick; + /** + * @see _.pick + */ pick( object: T | null | undefined, ...props: PropertyPath[] @@ -14405,6 +14408,14 @@ declare namespace _ { } interface LoDashImplicitWrapper { + /** + * @see _.pick + */ + pick( + this: LoDashImplicitWrapper, + ...props: Array> + ): LoDashImplicitWrapper>; + /** * @see _.pick */ @@ -14415,6 +14426,14 @@ declare namespace _ { } interface LoDashExplicitWrapper { + /** + * @see _.pick + */ + pick( + this: LoDashExplicitWrapper, + ...props: Array> + ): LoDashExplicitWrapper>; + /** * @see _.pick */ diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index cca7c239c7..dbefb1abaa 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -11821,7 +11821,7 @@ namespace TestPick { { let result: Pick; result = _.pick(obj, 'a', 'b'); - result = _.pick(obj, ['a', 'b']); + result = _.pick(obj, ['a' as 'a', 'b' as 'b']); } { @@ -11832,6 +11832,13 @@ namespace TestPick { result = _(obj).pick(['b', 1], 0, 'a'); } + { + let result: _.LoDashImplicitWrapper>; + + result = _(obj).pick('a', 'b'); + result = _(obj).pick(['a' as 'a', 'b' as 'b']); + } + { let result: _.LoDashExplicitWrapper>; @@ -11839,6 +11846,13 @@ namespace TestPick { result = _(obj).chain().pick(0, 'a'); result = _(obj).chain().pick(['b', 1], 0, 'a'); } + + { + let result: _.LoDashExplicitWrapper>; + + result = _(obj).chain().pick('a', 'b'); + result = _(obj).chain().pick(['a' as 'a', 'b' as 'b']); + } } // _.pickBy From d17a9bb82368c403b5f456014dd4a16d3b259ee7 Mon Sep 17 00:00:00 2001 From: Derek Wickern Date: Sun, 19 Nov 2017 09:46:14 -0800 Subject: [PATCH 087/201] update ember typings --- types/ember/index.d.ts | 4 +++- types/ember/test/array-proxy.ts | 7 +++---- 2 files changed, 6 insertions(+), 5 deletions(-) mode change 100755 => 100644 types/ember/test/array-proxy.ts diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index bb6cce8b36..adef4e70c2 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -558,6 +558,8 @@ declare module 'ember' { **/ interface ArrayProxy extends MutableArray {} class ArrayProxy extends Object.extend(MutableArray as {}) { + content: NativeArray; + /** * Should actually retrieve the object at the specified index from the * content. You can override this method in subclasses to transform the @@ -1837,7 +1839,7 @@ declare module 'ember' { * A hook you can implement to convert the URL into the model for * this route. */ - model(params: {}, transition: Transition): T | Rsvp.Promise; + model(params: {}, transition: Transition): any; /** * Returns the model of a parent (or any ancestor) route diff --git a/types/ember/test/array-proxy.ts b/types/ember/test/array-proxy.ts old mode 100755 new mode 100644 index 763034bbd0..dceea7b847 --- a/types/ember/test/array-proxy.ts +++ b/types/ember/test/array-proxy.ts @@ -21,7 +21,6 @@ class MyNewProxy extends Ember.ArrayProxy { isNew = true; } -let x = MyNewProxy.create({ content: Ember.A([1, 2, 3]) }); -// TODO: type inference can't infer 'number', just '{}' -// x.get('firstObject'); // $ExpectType number | undefined -x.isNew; // $ExpectType boolean +let x = MyNewProxy.create({ content: Ember.A([1, 2, 3]) }) as MyNewProxy; +assertType(x.get('firstObject')); +assertType(x.isNew); From e133846d157bd8bc0809964d5fca54faf41026c6 Mon Sep 17 00:00:00 2001 From: Derek Wickern Date: Sun, 19 Nov 2017 10:18:17 -0800 Subject: [PATCH 088/201] add ember-data typings --- types/ember-data/index.d.ts | 1684 +++++++++++++++++++++ types/ember-data/test/adapter.ts | 25 + types/ember-data/test/belongs-to.ts | 16 + types/ember-data/test/has-many.ts | 43 + types/ember-data/test/injections.ts | 22 + types/ember-data/test/lib/assert.ts | 2 + types/ember-data/test/model.ts | 29 + types/ember-data/test/record-reference.ts | 38 + types/ember-data/test/relationships.ts | 30 + types/ember-data/test/serializer.ts | 38 + types/ember-data/test/store.ts | 119 ++ types/ember-data/test/transform.ts | 16 + types/ember-data/tsconfig.json | 32 + types/ember-data/tslint.json | 16 + 14 files changed, 2110 insertions(+) create mode 100644 types/ember-data/index.d.ts create mode 100644 types/ember-data/test/adapter.ts create mode 100644 types/ember-data/test/belongs-to.ts create mode 100644 types/ember-data/test/has-many.ts create mode 100644 types/ember-data/test/injections.ts create mode 100644 types/ember-data/test/lib/assert.ts create mode 100644 types/ember-data/test/model.ts create mode 100644 types/ember-data/test/record-reference.ts create mode 100644 types/ember-data/test/relationships.ts create mode 100644 types/ember-data/test/serializer.ts create mode 100644 types/ember-data/test/store.ts create mode 100644 types/ember-data/test/transform.ts create mode 100644 types/ember-data/tsconfig.json create mode 100644 types/ember-data/tslint.json diff --git a/types/ember-data/index.d.ts b/types/ember-data/index.d.ts new file mode 100644 index 0000000000..bf273f2f20 --- /dev/null +++ b/types/ember-data/index.d.ts @@ -0,0 +1,1684 @@ +// Type definitions for ember-data 2.14 +// Project: https://github.com/emberjs/data +// Definitions by: Derek Wickern +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +import Ember from 'ember'; + +declare namespace DS { + /** + * Convert an hash of errors into an array with errors in JSON-API format. + */ + function errorsHashToArray(errors: {}): any[]; + /** + * Convert an array of errors in JSON-API format into an object. + */ + function errorsArrayToHash(errors: any[]): {}; + /** + * `DS.belongsTo` is used to define One-To-One and One-To-Many + * relationships on a [DS.Model](/api/data/classes/DS.Model.html). + */ + function belongsTo(modelName: string, options: { + async: false, + inverse?: string | null, + polymorphic?: boolean + }): Ember.ComputedProperty; + function belongsTo(modelName: string, options?: { + async?: true, + inverse?: string | null, + polymorphic?: boolean + }): Ember.ComputedProperty>; + /** + * `DS.hasMany` is used to define One-To-Many and Many-To-Many + * relationships on a [DS.Model](/api/data/classes/DS.Model.html). + */ + function hasMany(type: string, options: { + async: false, + inverse?: string | null, + polymorphic?: boolean + }): Ember.ComputedProperty>; + function hasMany(type: string, options?: { + async?: true, + inverse?: string | null, + polymorphic?: boolean + }): Ember.ComputedProperty>; + /** + * This method normalizes a modelName into the format Ember Data uses + * internally. + */ + function normalizeModelName(modelName: string): string; + const VERSION: string; + + interface AttrOptions { + defaultValue?: T | (() => T); + } + + /** + * `DS.attr` defines an attribute on a [DS.Model](/api/data/classes/DS.Model.html). + * By default, attributes are passed through as-is, however you can specify an + * optional type to have the value automatically transformed. + * Ember Data ships with four basic transform types: `string`, `number`, + * `boolean` and `date`. You can define your own transforms by subclassing + * [DS.Transform](/api/data/classes/DS.Transform.html). + */ + function attr(type: 'string', options?: AttrOptions): Ember.ComputedProperty; + function attr(type: 'boolean', options?: AttrOptions): Ember.ComputedProperty; + function attr(type: 'number', options?: AttrOptions): Ember.ComputedProperty; + function attr(type: 'date', options?: AttrOptions): Ember.ComputedProperty; + function attr(type: string, options?: AttrOptions): Ember.ComputedProperty; + function attr(options?: AttrOptions): Ember.ComputedProperty; + /** + * WARNING: This interface is likely to change in order to accomodate https://github.com/emberjs/rfcs/pull/4 + * ## Using BuildURLMixin + * To use url building, include the mixin when extending an adapter, and call `buildURL` where needed. + * The default behaviour is designed for RESTAdapter. + * ### Example + * ```javascript + * export default DS.Adapter.extend(BuildURLMixin, { + * findRecord: function(store, type, id, snapshot) { + * var url = this.buildURL(type.modelName, id, snapshot, 'findRecord'); + * return this.ajax(url, 'GET'); + * } + * }); + * ``` + * ### Attributes + * The `host` and `namespace` attributes will be used if defined, and are optional. + */ + class BuildURLMixin { + /** + * Builds a URL for a given type and optional ID. + */ + buildURL(modelName: string, id: string|any[]|{}, snapshot: Snapshot|any[], requestType: string, query: {}): string; + /** + * Builds a URL for a `store.findRecord(type, id)` call. + */ + urlForFindRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `store.findAll(type)` call. + */ + urlForFindAll(modelName: string, snapshot: SnapshotRecordArray): string; + /** + * Builds a URL for a `store.query(type, query)` call. + */ + urlForQuery(query: {}, modelName: string): string; + /** + * Builds a URL for a `store.queryRecord(type, query)` call. + */ + urlForQueryRecord(query: {}, modelName: string): string; + /** + * Builds a URL for coalesceing multiple `store.findRecord(type, id)` + * records into 1 request when the adapter's `coalesceFindRequests` + * property is true. + */ + urlForFindMany(ids: any[], modelName: string, snapshots: any[]): string; + /** + * Builds a URL for fetching a async hasMany relationship when a url + * is not provided by the server. + */ + urlForFindHasMany(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for fetching a async belongsTo relationship when a url + * is not provided by the server. + */ + urlForFindBelongsTo(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record was created + * locally using `store.createRecord()`. + */ + urlForCreateRecord(modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record has been update locally. + */ + urlForUpdateRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record has been deleted locally. + */ + urlForDeleteRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Determines the pathname for a given type. + */ + pathForType(modelName: string): string; + } + /** + * A `DS.AdapterError` is used by an adapter to signal that an error occurred + * during a request to an external API. It indicates a generic error, and + * subclasses are used to indicate specific error states. The following + * subclasses are provided: + */ + class AdapterError { + } + /** + * A `DS.InvalidError` is used by an adapter to signal the external API + * was unable to process a request because the content was not + * semantically correct or meaningful per the API. Usually this means a + * record failed some form of server side validation. When a promise + * from an adapter is rejected with a `DS.InvalidError` the record will + * transition to the `invalid` state and the errors will be set to the + * `errors` property on the record. + */ + class InvalidError { + } + /** + * A `DS.TimeoutError` is used by an adapter to signal that a request + * to the external API has timed out. I.e. no response was received from + * the external API within an allowed time period. + */ + class TimeoutError { + } + /** + * A `DS.AbortError` is used by an adapter to signal that a request to + * the external API was aborted. For example, this can occur if the user + * navigates away from the current page after a request to the external API + * has been initiated but before a response has been received. + */ + class AbortError { + } + /** + * A `DS.UnauthorizedError` equates to a HTTP `401 Unauthorized` response + * status. It is used by an adapter to signal that a request to the external + * API was rejected because authorization is required and has failed or has not + * yet been provided. + */ + class UnauthorizedError { + } + /** + * A `DS.ForbiddenError` equates to a HTTP `403 Forbidden` response status. + * It is used by an adapter to signal that a request to the external API was + * valid but the server is refusing to respond to it. If authorization was + * provided and is valid, then the authenticated user does not have the + * necessary permissions for the request. + */ + class ForbiddenError { + } + /** + * A `DS.NotFoundError` equates to a HTTP `404 Not Found` response status. + * It is used by an adapter to signal that a request to the external API + * was rejected because the resource could not be found on the API. + */ + class NotFoundError { + } + /** + * A `DS.ConflictError` equates to a HTTP `409 Conflict` response status. + * It is used by an adapter to indicate that the request could not be processed + * because of a conflict in the request. An example scenario would be when + * creating a record with a client generated id but that id is already known + * to the external API. + */ + class ConflictError { + } + /** + * A `DS.ServerError` equates to a HTTP `500 Internal Server Error` response + * status. It is used by the adapter to indicate that a request has failed + * because of an error in the external API. + */ + class ServerError { + } + /** + * Holds validation errors for a given record, organized by attribute names. + */ + interface Errors extends Ember.Enumerable, Ember.Evented {} + class Errors extends Ember.Object { + /** + * DEPRECATED: + * Register with target handler + */ + registerHandlers(target: {}, becameInvalid: Function, becameValid: Function): any; + /** + * Returns errors for a given attribute + */ + errorsFor(attribute: string): any[]; + /** + * An array containing all of the error messages for this + * record. This is useful for displaying all errors to the user. + */ + messages: Ember.ComputedProperty; + /** + * Total number of errors. + */ + length: Ember.ComputedProperty; + isEmpty: Ember.ComputedProperty; + /** + * DEPRECATED: + * Adds error messages to a given attribute and sends + * `becameInvalid` event to the record. + */ + add(attribute: string, messages: any[]|string): any; + /** + * DEPRECATED: + * Removes all error messages from the given attribute and sends + * `becameValid` event to the record if there no more errors left. + */ + remove(attribute: string): any; + /** + * DEPRECATED: + * Removes all error messages and sends `becameValid` event + * to the record. + */ + clear(): any; + /** + * Checks if there is error messages for the given attribute. + */ + has(attribute: string): boolean; + } + /** + * The model class that all Ember Data records descend from. + * This is the public API of Ember Data models. If you are using Ember Data + * in your application, this is the class you should use. + * If you are working on Ember Data internals, you most likely want to be dealing + * with `InternalModel` + */ + class Model extends Ember.Object { + /** + * If this property is `true` the record is in the `empty` + * state. Empty is the first state all records enter after they have + * been created. Most records created by the store will quickly + * transition to the `loading` state if data needs to be fetched from + * the server or the `created` state if the record is created on the + * client. A record can also enter the empty state if the adapter is + * unable to locate the record. + */ + isEmpty: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `loading` state. A + * record enters this state when the store asks the adapter for its + * data. It remains in this state until the adapter provides the + * requested data. + */ + isLoading: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `loaded` state. A + * record enters this state when its data is populated. Most of a + * record's lifecycle is spent inside substates of the `loaded` + * state. + */ + isLoaded: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `dirty` state. The + * record has local changes that have not yet been saved by the + * adapter. This includes records that have been created (but not yet + * saved) or deleted. + */ + hasDirtyAttributes: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `saving` state. A + * record enters the saving state when `save` is called, but the + * adapter has not yet acknowledged that the changes have been + * persisted to the backend. + */ + isSaving: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `deleted` state + * and has been marked for deletion. When `isDeleted` is true and + * `hasDirtyAttributes` is true, the record is deleted locally but the deletion + * was not yet persisted. When `isSaving` is true, the change is + * in-flight. When both `hasDirtyAttributes` and `isSaving` are false, the + * change has persisted. + */ + isDeleted: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `new` state. A + * record will be in the `new` state when it has been created on the + * client and the adapter has not yet report that it was successfully + * saved. + */ + isNew: Ember.ComputedProperty; + /** + * If this property is `true` the record is in the `valid` state. + */ + isValid: Ember.ComputedProperty; + /** + * If the record is in the dirty state this property will report what + * kind of change has caused it to move into the dirty + * state. Possible values are: + */ + dirtyType: Ember.ComputedProperty; + /** + * If `true` the adapter reported that it was unable to save local + * changes to the backend for any reason other than a server-side + * validation error. + */ + isError: boolean; + /** + * If `true` the store is attempting to reload the record from the adapter. + */ + isReloading: boolean; + /** + * All ember models have an id property. This is an identifier + * managed by an external source. These are always coerced to be + * strings before being used internally. Note when declaring the + * attributes for a model it is an error to declare an id + * attribute. + */ + id: string; + /** + * When the record is in the `invalid` state this object will contain + * any errors returned by the adapter. When present the errors hash + * contains keys corresponding to the invalid property names + * and values which are arrays of Javascript objects with two keys: + */ + errors: Ember.ComputedProperty; + /** + * This property holds the `DS.AdapterError` object with which + * last adapter operation was rejected. + */ + adapterError: AdapterError; + /** + * Create a JSON representation of the record, using the serialization + * strategy of the store's adapter. + */ + serialize(options: {}): {}; + /** + * Use [DS.JSONSerializer](DS.JSONSerializer.html) to + * get the JSON representation of a record. + */ + toJSON(options: {}): {}; + /** + * Fired when the record is ready to be interacted with, + * that is either loaded from the server or created locally. + */ + ready(): void; + /** + * Fired when the record is loaded from the server. + */ + didLoad(): void; + /** + * Fired when the record is updated. + */ + didUpdate(): void; + /** + * Fired when a new record is commited to the server. + */ + didCreate(): void; + /** + * Fired when the record is deleted. + */ + didDelete(): void; + /** + * Fired when the record becomes invalid. + */ + becameInvalid(): void; + /** + * Fired when the record enters the error state. + */ + becameError(): void; + /** + * Fired when the record is rolled back. + */ + rolledBack(): void; + /** + * Marks the record as deleted but does not save it. You must call + * `save` afterwards if you want to persist it. You might use this + * method if you want to allow the user to still `rollbackAttributes()` + * after a delete was made. + */ + deleteRecord(): any; + /** + * Same as `deleteRecord`, but saves the record immediately. + */ + destroyRecord(options: {}): Promise; + /** + * Unloads the record from the store. This will cause the record to be destroyed and freed up for garbage collection. + */ + unloadRecord(): any; + /** + * Returns an object, whose keys are changed properties, and value is + * an [oldProp, newProp] array. + */ + changedAttributes(): {}; + /** + * If the model `hasDirtyAttributes` this function will discard any unsaved + * changes. If the model `isNew` it will be removed from the store. + */ + rollbackAttributes(): any; + /** + * Save the record and persist any changes to the record to an + * external source via the adapter. + */ + save(options?: {}): Promise; + /** + * Reload the record from the adapter. + */ + reload(): Promise; + /** + * Get the reference for the specified belongsTo relationship. + */ + belongsTo(name: string): BelongsToReference; + /** + * Get the reference for the specified hasMany relationship. + */ + hasMany(name: string): HasManyReference; + /** + * Given a callback, iterates over each of the relationships in the model, + * invoking the callback with the name of each relationship and its relationship + * descriptor. + */ + eachRelationship(callback: Function, binding: any): any; + /** + * Represents the model's class name as a string. This can be used to look up the model's class name through + * `DS.Store`'s modelFor method. + */ + static modelName: string; + /** + * For a given relationship name, returns the model type of the relationship. + */ + static typeForRelationship(name: string, store: Store): Model; + /** + * Find the relationship which is the inverse of the one asked for. + */ + static inverseFor(name: string, store: Store): {}; + /** + * The model's relationships as a map, keyed on the type of the + * relationship. The value of each entry is an array containing a descriptor + * for each relationship with that type, describing the name of the relationship + * as well as the type. + */ + static relationships: Ember.ComputedProperty; + /** + * A hash containing lists of the model's relationships, grouped + * by the relationship kind. For example, given a model with this + * definition: + */ + static relationshipNames: Ember.ComputedProperty<{}>; + /** + * An array of types directly related to a model. Each type will be + * included once, regardless of the number of relationships it has with + * the model. + */ + static relatedTypes: Ember.ComputedProperty>; + /** + * A map whose keys are the relationships of a model and whose values are + * relationship descriptors. + */ + static relationshipsByName: Ember.ComputedProperty; + /** + * A map whose keys are the fields of the model and whose values are strings + * describing the kind of the field. A model's fields are the union of all of its + * attributes and relationships. + */ + static fields: Ember.ComputedProperty; + /** + * Given a callback, iterates over each of the relationships in the model, + * invoking the callback with the name of each relationship and its relationship + * descriptor. + */ + static eachRelationship(callback: Function, binding: any): any; + /** + * Given a callback, iterates over each of the types related to a model, + * invoking the callback with the related type's class. Each type will be + * returned just once, regardless of how many different relationships it has + * with a model. + */ + static eachRelatedType(callback: Function, binding: any): any; + /** + * A map whose keys are the attributes of the model (properties + * described by DS.attr) and whose values are the meta object for the + * property. + */ + static attributes: Ember.ComputedProperty; + /** + * A map whose keys are the attributes of the model (properties + * described by DS.attr) and whose values are type of transformation + * applied to each attribute. This map does not include any + * attributes that do not have an transformation type. + */ + static transformedAttributes: Ember.ComputedProperty; + /** + * Iterates through the attributes of the model, calling the passed function on each + * attribute. + */ + static eachAttribute(callback: Function, binding: {}): any; + /** + * Iterates through the transformedAttributes of the model, calling + * the passed function on each attribute. Note the callback will not be + * called for any attributes that do not have an transformation type. + */ + static eachTransformedAttribute(callback: Function, binding: {}): any; + /** + * Discards any unsaved changes to the given attribute. This feature is not enabled by default. You must enable `ds-rollback-attribute` and be running a canary build. + */ + rollbackAttribute(): any; + /** + * This Ember.js hook allows an object to be notified when a property + * is defined. + */ + didDefineProperty(proto: {}, key: string, value: Ember.ComputedProperty): any; + } + /** + * ### State + */ + class RootState { + } + /** + * Represents an ordered list of records whose order and membership is + * determined by the adapter. For example, a query sent to the adapter + * may trigger a search on the server, whose results would be loaded + * into an instance of the `AdapterPopulatedRecordArray`. + */ + class AdapterPopulatedRecordArray extends RecordArray { + } + /** + * Represents a list of records whose membership is determined by the + * store. As records are created, loaded, or modified, the store + * evaluates them to determine if they should be part of the record + * array. + */ + class FilteredRecordArray extends RecordArray { + /** + * The filterFunction is a function used to test records from the store to + * determine if they should be part of the record array. + */ + filterFunction(record: Model): boolean; + } + /** + * A record array is an array that contains records of a certain modelName. The record + * array materializes records as needed when they are retrieved for the first + * time. You should not create record arrays yourself. Instead, an instance of + * `DS.RecordArray` or its subclasses will be returned by your application's store + * in response to queries. + */ + interface RecordArray extends Ember.ArrayProxy, Ember.Evented {} + class RecordArray { + /** + * The flag to signal a `RecordArray` is finished loading data. + */ + isLoaded: boolean; + /** + * The flag to signal a `RecordArray` is currently loading data. + */ + isUpdating: boolean; + /** + * The modelClass represented by this record array. + */ + type: Ember.ComputedProperty; + /** + * Used to get the latest version of all of the records in this array + * from the adapter. + */ + update(): any; + /** + * Saves all of the records in the `RecordArray`. + */ + save(): PromiseArray; + } + /** + * A BelongsToReference is a low level API that allows users and + * addon author to perform meta-operations on a belongs-to + * relationship. + */ + class BelongsToReference { + /** + * This returns a string that represents how the reference will be + * looked up when it is loaded. If the relationship has a link it will + * use the "link" otherwise it defaults to "id". + */ + remoteType(): string; + /** + * The `id` of the record that this reference refers to. Together, the + * `type()` and `id()` methods form a composite key for the identity + * map. This can be used to access the id of an async relationship + * without triggering a fetch that would normally happen if you + * attempted to use `record.get('relationship.id')`. + */ + id(): string; + /** + * The link Ember Data will use to fetch or reload this belongs-to + * relationship. + */ + link(): string; + /** + * The meta data for the belongs-to relationship. + */ + meta(): {}; + /** + * `push` can be used to update the data in the relationship and Ember + * Data will treat the new data as the conanical value of this + * relationship on the backend. + */ + push(objectOrPromise: {}|Promise): Promise; + /** + * `value()` synchronously returns the current value of the belongs-to + * relationship. Unlike `record.get('relationshipName')`, calling + * `value()` on a reference does not trigger a fetch if the async + * relationship is not yet loaded. If the relationship is not loaded + * it will always return `null`. + */ + value(objectOrPromise: {}|Promise): Model; + /** + * Loads a record in a belongs to relationship if it is not already + * loaded. If the relationship is already loaded this method does not + * trigger a new load. + */ + load(): Promise; + /** + * Triggers a reload of the value in this relationship. If the + * remoteType is `"link"` Ember Data will use the relationship link to + * reload the relationship. Otherwise it will reload the record by its + * id. + */ + reload(): Promise; + } + /** + * A HasManyReference is a low level API that allows users and addon + * author to perform meta-operations on a has-many relationship. + */ + class HasManyReference { + /** + * This returns a string that represents how the reference will be + * looked up when it is loaded. If the relationship has a link it will + * use the "link" otherwise it defaults to "id". + */ + remoteType(): string; + /** + * The link Ember Data will use to fetch or reload this has-many + * relationship. + */ + link(): string; + /** + * `ids()` returns an array of the record ids in this relationship. + */ + ids(): any[]; + /** + * The meta data for the has-many relationship. + */ + meta(): {}; + /** + * `push` can be used to update the data in the relationship and Ember + * Data will treat the new data as the canonical value of this + * relationship on the backend. + */ + push(objectOrPromise: T[] | Promise): ManyArray; + /** + * `value()` synchronously returns the current value of the has-many + * relationship. Unlike `record.get('relationshipName')`, calling + * `value()` on a reference does not trigger a fetch if the async + * relationship is not yet loaded. If the relationship is not loaded + * it will always return `null`. + */ + value(): ManyArray; + /** + * Loads the relationship if it is not already loaded. If the + * relationship is already loaded this method does not trigger a new + * load. + */ + load(): Promise; + /** + * Reloads this has-many relationship. + */ + reload(): Promise; + } + /** + * An RecordReference is a low level API that allows users and + * addon author to perform meta-operations on a record. + */ + class RecordReference { + /** + * The `id` of the record that this reference refers to. + */ + id(): string; + /** + * How the reference will be looked up when it is loaded: Currently + * this always return `identity` to signifying that a record will be + * loaded by the `type` and `id`. + */ + remoteType(): string; + /** + * This API allows you to provide a reference with new data. The + * simplest usage of this API is similar to `store.push`: you provide a + * normalized hash of data and the object represented by the reference + * will update. + */ + push(payload: Promise|{}): PromiseObject & T; + /** + * If the entity referred to by the reference is already loaded, it is + * present as `reference.value`. Otherwise the value returned by this function + * is `null`. + */ + value(): T | null; + /** + * Triggers a fetch for the backing entity based on its `remoteType` + * (see `remoteType` definitions per reference type). + */ + load(): PromiseObject & T; + /** + * Reloads the record if it is already loaded. If the record is not + * loaded it will load the record via `store.findRecord` + */ + reload(): PromiseObject & T; + } + /** + * A `ManyArray` is a `MutableArray` that represents the contents of a has-many + * relationship. + */ + interface ManyArray extends Ember.MutableArray {} + class ManyArray extends Ember.Object.extend(Ember.MutableArray as {}, Ember.Evented) { + /** + * The loading state of this array + */ + isLoaded: boolean; + /** + * Metadata associated with the request for async hasMany relationships. + */ + meta: {}; + /** + * Reloads all of the records in the manyArray. If the manyArray + * holds a relationship that was originally fetched using a links url + * Ember Data will revisit the original links url to repopulate the + * relationship. + */ + reload(): PromiseArray; + /** + * Saves all of the records in the `ManyArray`. + */ + save(): PromiseArray; + /** + * Create a child record within the owner + */ + createRecord(inputProperties?: {}): T; + } + /** + * A `PromiseArray` is an object that acts like both an `Ember.Array` + * and a promise. When the promise is resolved the resulting value + * will be set to the `PromiseArray`'s `content` property. This makes + * it easy to create data bindings with the `PromiseArray` that will be + * updated when the promise resolves. + */ + interface PromiseArray extends Ember.ArrayProxy, Ember.PromiseProxyMixin> {} + class PromiseArray { + } + /** + * A `PromiseObject` is an object that acts like both an `Ember.Object` + * and a promise. When the promise is resolved, then the resulting value + * will be set to the `PromiseObject`'s `content` property. This makes + * it easy to create data bindings with the `PromiseObject` that will + * be updated when the promise resolves. + */ + interface PromiseObject extends Ember.ObjectProxy, Ember.PromiseProxyMixin> {} + class PromiseObject { + } + /** + * A PromiseManyArray is a PromiseArray that also proxies certain method calls + * to the underlying manyArray. + * Right now we proxy: + */ + class PromiseManyArray extends PromiseArray { + /** + * Reloads all of the records in the manyArray. If the manyArray + * holds a relationship that was originally fetched using a links url + * Ember Data will revisit the original links url to repopulate the + * relationship. + */ + reload(): PromiseManyArray; + /** + * Create a child record within the owner + */ + createRecord(inputProperties?: {}): T; + } + class SnapshotRecordArray { + /** + * Number of records in the array + */ + length: number; + /** + * Meta objects for the record array. + */ + meta: {}; + /** + * A hash of adapter options passed into the store method for this request. + */ + adapterOptions: {}; + /** + * The relationships to include for this request. + */ + include: string|any[]; + /** + * The type of the underlying records for the snapshots in the array, as a DS.Model + */ + type: Model; + /** + * Get snapshots of the underlying record array + */ + snapshots(): any[]; + } + class Snapshot { + /** + * The underlying record for this snapshot. Can be used to access methods and + * properties defined on the record. + */ + record: Model; + /** + * The id of the snapshot's underlying record + */ + id: string; + /** + * A hash of adapter options + */ + adapterOptions: {}; + /** + * The name of the type of the underlying record for this snapshot, as a string. + */ + modelName: string; + /** + * The type of the underlying record for this snapshot, as a DS.Model. + */ + type: Model; + /** + * Returns the value of an attribute. + */ + attr(keyName: string): {}; + /** + * Returns all attributes and their corresponding values. + */ + attributes(): {}; + /** + * Returns all changed attributes and their old and new values. + */ + changedAttributes(): {}; + /** + * Returns the current value of a belongsTo relationship. + */ + belongsTo(keyName: string, options: {}): Snapshot|string|null|undefined; + /** + * Returns the current value of a hasMany relationship. + */ + hasMany(keyName: string, options: {}): any[]|undefined; + /** + * Iterates through all the attributes of the model, calling the passed + * function on each attribute. + */ + eachAttribute(callback: Function, binding: {}): any; + /** + * Iterates through all the relationships of the model, calling the passed + * function on each relationship. + */ + eachRelationship(callback: Function, binding: {}): any; + /** + * Serializes the snapshot using the serializer for the model. + */ + serialize(options: {}): {}; + } + /** + * The store contains all of the data for records loaded from the server. + * It is also responsible for creating instances of `DS.Model` that wrap + * the individual data for a record, so that they can be bound to in your + * Handlebars templates. + */ + class Store { + /** + * The default adapter to use to communicate to a backend server or + * other persistence layer. This will be overridden by an application + * adapter if present. + */ + adapter: string; + /** + * Create a new record in the current store. The properties passed + * to this method are set on the newly created record. + */ + createRecord(modelName: string, inputProperties?: {}): T; + /** + * For symmetry, a record can be deleted via the store. + */ + deleteRecord(record: Model): void; + /** + * For symmetry, a record can be unloaded via the store. + * This will cause the record to be destroyed and freed up for garbage collection. + */ + unloadRecord(record: Model): void; + /** + * This method returns a record for a given type and id combination. + */ + findRecord(modelName: string, id: string|number, options?: {}): PromiseObject & T; + /** + * Get the reference for the specified record. + */ + getReference(modelName: string, id: string|number): RecordReference; + /** + * Get a record by a given type and ID without triggering a fetch. + */ + peekRecord(modelName: string, id: string|number): T|null; + /** + * This method returns true if a record for a given modelName and id is already + * loaded in the store. Use this function to know beforehand if a findRecord() + * will result in a request or that it will be a cache hit. + */ + hasRecordForId(modelName: string, id: string|number): boolean; + /** + * This method delegates a query to the adapter. This is the one place where + * adapter-level semantics are exposed to the application. + */ + query(modelName: string, query: any): AdapterPopulatedRecordArray & PromiseArray; + /** + * This method makes a request for one record, where the `id` is not known + * beforehand (if the `id` is known, use [`findRecord`](#method_findRecord) + * instead). + */ + queryRecord(modelName: string, query: any): Promise; + /** + * `findAll` asks the adapter's `findAll` method to find the records for the + * given type, and returns a promise which will resolve with all records of + * this type present in the store, even if the adapter only returns a subset + * of them. + */ + findAll(modelName: string, options?: { + reload?: boolean, + backgroundReload?: boolean, + include?: string, + adapterOptions?: any + }): PromiseArray; + /** + * This method returns a filtered array that contains all of the + * known records for a given type in the store. + */ + peekAll(modelName: string): RecordArray; + /** + * This method unloads all records in the store. + * It schedules unloading to happen during the next run loop. + */ + unloadAll(modelName: string): void; + /** + * DEPRECATED: + * This method has been deprecated and is an alias for store.hasRecordForId, which should + * be used instead. + */ + recordIsLoaded(modelName: string, id: string): boolean; + /** + * Returns the model class for the particular `modelName`. + */ + modelFor(modelName: string): Model; + /** + * Push some data for a given type into the store. + */ + push(data: {}): Model|any[]; + /** + * Push some raw data into the store. + */ + pushPayload(modelName: string, inputPayload: {}): any; + /** + * `normalize` converts a json payload into the normalized form that + * [push](#method_push) expects. + */ + normalize(modelName: string, payload: {}): {}; + /** + * Returns an instance of the adapter for a given type. For + * example, `adapterFor('person')` will return an instance of + * `App.PersonAdapter`. + */ + adapterFor(modelName: string): Adapter; + /** + * Returns an instance of the serializer for a given type. For + * example, `serializerFor('person')` will return an instance of + * `App.PersonSerializer`. + */ + serializerFor(modelName: string): Serializer; + } + /** + * The `JSONAPIAdapter` is the default adapter used by Ember Data. It + * is responsible for transforming the store's requests into HTTP + * requests that follow the [JSON API](http://jsonapi.org/format/) + * format. + */ + class JSONAPIAdapter extends RESTAdapter { + /** + * By default the JSONAPIAdapter will send each find request coming from a `store.find` + * or from accessing a relationship separately to the server. If your server supports passing + * ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests + * within a single runloop. + */ + coalesceFindRequests: boolean; + } + /** + * The REST adapter allows your store to communicate with an HTTP server by + * transmitting JSON via XHR. Most Ember.js apps that consume a JSON API + * should use the REST adapter. + */ + class RESTAdapter extends Adapter implements BuildURLMixin { + /** + * By default, the RESTAdapter will send the query params sorted alphabetically to the + * server. + */ + sortQueryParams(obj: {}): {}; + /** + * By default the RESTAdapter will send each find request coming from a `store.find` + * or from accessing a relationship separately to the server. If your server supports passing + * ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests + * within a single runloop. + */ + coalesceFindRequests: boolean; + /** + * Endpoint paths can be prefixed with a `namespace` by setting the namespace + * property on the adapter: + */ + namespace: string; + /** + * An adapter can target other hosts by setting the `host` property. + */ + host: string; + /** + * Some APIs require HTTP headers, e.g. to provide an API + * key. Arbitrary headers can be set as key/value pairs on the + * `RESTAdapter`'s `headers` object and Ember Data will send them + * along with each ajax request. For dynamic headers see [headers + * customization](/api/data/classes/DS.RESTAdapter.html#toc_headers-customization). + */ + headers: {}; + /** + * Called by the store in order to fetch the JSON for a given + * type and ID. + */ + findRecord(store: Store, type: Model, id: string, snapshot: Snapshot): Promise; + /** + * Called by the store in order to fetch a JSON array for all + * of the records for a given type. + */ + findAll(store: Store, type: Model, sinceToken: string, snapshotRecordArray: SnapshotRecordArray): Promise; + /** + * Called by the store in order to fetch a JSON array for + * the records that match a particular query. + */ + query(store: Store, type: Model, query: {}): Promise; + /** + * Called by the store in order to fetch a JSON object for + * the record that matches a particular query. + */ + queryRecord(store: Store, type: Model, query: {}): Promise; + /** + * Called by the store in order to fetch several records together if `coalesceFindRequests` is true + */ + findMany(store: Store, type: Model, ids: any[], snapshots: any[]): Promise; + /** + * Called by the store in order to fetch a JSON array for + * the unloaded records in a has-many relationship that were originally + * specified as a URL (inside of `links`). + */ + findHasMany(store: Store, snapshot: Snapshot, url: string, relationship: {}): Promise; + /** + * Called by the store in order to fetch the JSON for the unloaded record in a + * belongs-to relationship that was originally specified as a URL (inside of + * `links`). + */ + findBelongsTo(store: Store, snapshot: Snapshot, url: string): Promise; + /** + * Called by the store when a newly created record is + * saved via the `save` method on a model record instance. + */ + createRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * Called by the store when an existing record is saved + * via the `save` method on a model record instance. + */ + updateRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * Called by the store when a record is deleted. + */ + deleteRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * Organize records into groups, each of which is to be passed to separate + * calls to `findMany`. + */ + groupRecordsForFindMany(store: Store, snapshots: any[]): any[]; + /** + * Takes an ajax response, and returns the json payload or an error. + */ + handleResponse(status: number, headers: {}, payload: {}, requestData: {}): {}; + /** + * Default `handleResponse` implementation uses this hook to decide if the + * response is a success. + */ + isSuccess(status: number, headers: {}, payload: {}): boolean; + /** + * Default `handleResponse` implementation uses this hook to decide if the + * response is an invalid error. + */ + isInvalid(status: number, headers: {}, payload: {}): boolean; + /** + * Get the data (body or query params) for a request. + */ + dataForRequest(params: {}): {}; + /** + * Get the HTTP method for a request. + */ + methodForRequest(params: {}): string; + /** + * Get the URL for a request. + */ + urlForRequest(params: {}): string; + /** + * Get the headers for a request. + */ + headersForRequest(params: {}): {}; + /** + * Builds a URL for a given type and optional ID. + */ + buildURL(modelName: string, id: string|any[]|{}, snapshot: Snapshot|any[], requestType: string, query: {}): string; + /** + * Builds a URL for a `store.findRecord(type, id)` call. + */ + urlForFindRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `store.findAll(type)` call. + */ + urlForFindAll(modelName: string, snapshot: SnapshotRecordArray): string; + /** + * Builds a URL for a `store.query(type, query)` call. + */ + urlForQuery(query: {}, modelName: string): string; + /** + * Builds a URL for a `store.queryRecord(type, query)` call. + */ + urlForQueryRecord(query: {}, modelName: string): string; + /** + * Builds a URL for coalesceing multiple `store.findRecord(type, id)` + * records into 1 request when the adapter's `coalesceFindRequests` + * property is true. + */ + urlForFindMany(ids: any[], modelName: string, snapshots: any[]): string; + /** + * Builds a URL for fetching a async hasMany relationship when a url + * is not provided by the server. + */ + urlForFindHasMany(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for fetching a async belongsTo relationship when a url + * is not provided by the server. + */ + urlForFindBelongsTo(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record was created + * locally using `store.createRecord()`. + */ + urlForCreateRecord(modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record has been update locally. + */ + urlForUpdateRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Builds a URL for a `record.save()` call when the record has been deleted locally. + */ + urlForDeleteRecord(id: string, modelName: string, snapshot: Snapshot): string; + /** + * Determines the pathname for a given type. + */ + pathForType(modelName: string): string; + } + /** + * ## Using Embedded Records + */ + class EmbeddedRecordsMixin { + /** + * Normalize the record and recursively normalize/extract all the embedded records + * while pushing them into the store as they are encountered + */ + normalize(typeClass: Model, hash: {}, prop: string): {}; + /** + * Serialize `belongsTo` relationship when it is configured as an embedded object. + */ + serializeBelongsTo(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * Serializes `hasMany` relationships when it is configured as embedded objects. + */ + serializeHasMany(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * When serializing an embedded record, modify the property (in the json payload) + * that refers to the parent record (foreign key for relationship). + */ + removeEmbeddedForeignKey(snapshot: Snapshot, embeddedSnapshot: Snapshot, relationship: {}, json: {}): any; + } + /** + * Ember Data 2.0 Serializer: + */ + class JSONAPISerializer extends JSONSerializer { + pushPayload(store: Store, payload: {}): any; + /** + * Dasherizes and singularizes the model name in the payload to match + * the format Ember Data uses internally for the model name. + */ + modelNameFromPayloadKey(key: string): string; + /** + * Converts the model name to a pluralized version of the model name. + */ + payloadKeyFromModelName(modelName: string): string; + /** + * `keyForAttribute` can be used to define rules for how to convert an + * attribute name in your model to a key in your JSON. + * By default `JSONAPISerializer` follows the format used on the examples of + * http://jsonapi.org/format and uses dashes as the word separator in the JSON + * attribute keys. + */ + keyForAttribute(key: string, method: string): string; + /** + * `keyForRelationship` can be used to define a custom key when + * serializing and deserializing relationship properties. + * By default `JSONAPISerializer` follows the format used on the examples of + * http://jsonapi.org/format and uses dashes as word separators in + * relationship properties. + */ + keyForRelationship(key: string, typeClass: string, method: string): string; + /** + * `modelNameFromPayloadType` can be used to change the mapping for a DS model + * name, taken from the value in the payload. + */ + modelNameFromPayloadType(payloadType: string): string; + /** + * `payloadTypeFromModelName` can be used to change the mapping for the type in + * the payload, taken from the model name. + */ + payloadTypeFromModelName(modelname: string): string; + } + /** + * Ember Data 2.0 Serializer: + */ + class JSONSerializer extends Serializer { + /** + * The `primaryKey` is used when serializing and deserializing + * data. Ember Data always uses the `id` property to store the id of + * the record. The external source may not always follow this + * convention. In these cases it is useful to override the + * `primaryKey` property to match the `primaryKey` of your external + * store. + */ + primaryKey: string; + /** + * The `attrs` object can be used to declare a simple mapping between + * property names on `DS.Model` records and payload keys in the + * serialized JSON object representing the record. An object with the + * property `key` can also be used to designate the attribute's key on + * the response payload. + */ + attrs: {}; + /** + * The `normalizeResponse` method is used to normalize a payload from the + * server to a JSON-API Document. + */ + normalizeResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeFindRecordResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeQueryRecordResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeFindAllResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeFindBelongsToResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeFindHasManyResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeFindManyResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeQueryResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeCreateRecordResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeDeleteRecordResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeUpdateRecordResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeSaveResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeSingleResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + normalizeArrayResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + /** + * Normalizes a part of the JSON payload returned by + * the server. You should override this method, munge the hash + * and call super if you have generic normalization to do. + */ + normalize(typeClass: Model, hash: {}): {}; + /** + * Returns the resource's ID. + */ + extractId(modelClass: {}, resourceHash: {}): string; + /** + * Returns the resource's attributes formatted as a JSON-API "attributes object". + */ + extractAttributes(modelClass: {}, resourceHash: {}): {}; + /** + * Returns a relationship formatted as a JSON-API "relationship object". + */ + extractRelationship(relationshipModelName: {}, relationshipHash: {}): {}; + /** + * Returns a polymorphic relationship formatted as a JSON-API "relationship object". + */ + extractPolymorphicRelationship(relationshipModelName: {}, relationshipHash: {}, relationshipOptions: {}): {}; + /** + * Returns the resource's relationships formatted as a JSON-API "relationships object". + */ + extractRelationships(modelClass: {}, resourceHash: {}): {}; + modelNameFromPayloadKey(key: string): string; + /** + * Check if the given hasMany relationship should be serialized + */ + shouldSerializeHasMany(snapshot: Snapshot, key: string, relationshipType: string): boolean; + /** + * Called when a record is saved in order to convert the + * record into JSON. + */ + serialize(snapshot: Snapshot, options: {}): {}; + /** + * You can use this method to customize how a serialized record is added to the complete + * JSON hash to be sent to the server. By default the JSON Serializer does not namespace + * the payload and just sends the raw serialized JSON object. + * If your server expects namespaced keys, you should consider using the RESTSerializer. + * Otherwise you can override this method to customize how the record is added to the hash. + * The hash property should be modified by reference. + */ + serializeIntoHash(hash: {}, typeClass: Model, snapshot: Snapshot, options: {}): any; + /** + * `serializeAttribute` can be used to customize how `DS.attr` + * properties are serialized + */ + serializeAttribute(snapshot: Snapshot, json: {}, key: string, attribute: {}): any; + /** + * `serializeBelongsTo` can be used to customize how `DS.belongsTo` + * properties are serialized. + */ + serializeBelongsTo(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * `serializeHasMany` can be used to customize how `DS.hasMany` + * properties are serialized. + */ + serializeHasMany(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * You can use this method to customize how polymorphic objects are + * serialized. Objects are considered to be polymorphic if + * `{ polymorphic: true }` is pass as the second argument to the + * `DS.belongsTo` function. + */ + serializePolymorphicType(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * `extractMeta` is used to deserialize any meta information in the + * adapter payload. By default Ember Data expects meta information to + * be located on the `meta` property of the payload object. + */ + extractMeta(store: Store, modelClass: Model, payload: {}): any; + /** + * `extractErrors` is used to extract model errors when a call + * to `DS.Model#save` fails with an `InvalidError`. By default + * Ember Data expects error information to be located on the `errors` + * property of the payload object. + */ + extractErrors(store: Store, typeClass: Model, payload: {}, id: string|number): {}; + /** + * `keyForAttribute` can be used to define rules for how to convert an + * attribute name in your model to a key in your JSON. + */ + keyForAttribute(key: string, method: string): string; + /** + * `keyForRelationship` can be used to define a custom key when + * serializing and deserializing relationship properties. By default + * `JSONSerializer` does not provide an implementation of this method. + */ + keyForRelationship(key: string, typeClass: string, method: string): string; + /** + * `keyForLink` can be used to define a custom key when deserializing link + * properties. + */ + keyForLink(key: string, kind: string): string; + modelNameFromPayloadType(type: string): string; + /** + * serializeId can be used to customize how id is serialized + * For example, your server may expect integer datatype of id + */ + serializeId(snapshot: Snapshot, json: {}, primaryKey: string): any; + } + /** + * Normally, applications will use the `RESTSerializer` by implementing + * the `normalize` method. + */ + class RESTSerializer extends JSONSerializer { + /** + * `keyForPolymorphicType` can be used to define a custom key when + * serializing and deserializing a polymorphic type. By default, the + * returned key is `${key}Type`. + */ + keyForPolymorphicType(key: string, typeClass: string, method: string): string; + /** + * Normalizes a part of the JSON payload returned by + * the server. You should override this method, munge the hash + * and call super if you have generic normalization to do. + */ + normalize(modelClass: Model, resourceHash: {}, prop?: string): {}; + /** + * This method allows you to push a payload containing top-level + * collections of records organized per type. + */ + pushPayload(store: Store, payload: {}): any; + /** + * This method is used to convert each JSON root key in the payload + * into a modelName that it can use to look up the appropriate model for + * that part of the payload. + */ + modelNameFromPayloadKey(key: string): string; + /** + * Called when a record is saved in order to convert the + * record into JSON. + */ + serialize(snapshot: Snapshot, options: {}): {}; + /** + * You can use this method to customize the root keys serialized into the JSON. + * The hash property should be modified by reference (possibly using something like _.extend) + * By default the REST Serializer sends the modelName of a model, which is a camelized + * version of the name. + */ + serializeIntoHash(hash: {}, typeClass: Model, snapshot: Snapshot, options: {}): any; + /** + * You can use `payloadKeyFromModelName` to override the root key for an outgoing + * request. By default, the RESTSerializer returns a camelized version of the + * model's name. + */ + payloadKeyFromModelName(modelName: string): string; + /** + * You can use this method to customize how polymorphic objects are serialized. + * By default the REST Serializer creates the key by appending `Type` to + * the attribute and value from the model's camelcased model name. + */ + serializePolymorphicType(snapshot: Snapshot, json: {}, relationship: {}): any; + /** + * You can use this method to customize how a polymorphic relationship should + * be extracted. + */ + extractPolymorphicRelationship(relationshipType: {}, relationshipHash: {}, relationshipOptions: {}): {}; + /** + * `modelNameFromPayloadType` can be used to change the mapping for a DS model + * name, taken from the value in the payload. + */ + modelNameFromPayloadType(payloadType: string): string; + /** + * `payloadTypeFromModelName` can be used to change the mapping for the type in + * the payload, taken from the model name. + */ + payloadTypeFromModelName(modelName: string): string; + } + /** + * The `DS.BooleanTransform` class is used to serialize and deserialize + * boolean attributes on Ember Data record objects. This transform is + * used when `boolean` is passed as the type parameter to the + * [DS.attr](../../data#method_attr) function. + */ + class BooleanTransform extends Transform { + } + /** + * The `DS.DateTransform` class is used to serialize and deserialize + * date attributes on Ember Data record objects. This transform is used + * when `date` is passed as the type parameter to the + * [DS.attr](../../data#method_attr) function. It uses the [`ISO 8601`](https://en.wikipedia.org/wiki/ISO_8601) + * standard. + */ + class DateTransform extends Transform { + } + /** + * The `DS.NumberTransform` class is used to serialize and deserialize + * numeric attributes on Ember Data record objects. This transform is + * used when `number` is passed as the type parameter to the + * [DS.attr](../../data#method_attr) function. + */ + class NumberTransform extends Transform { + } + /** + * The `DS.StringTransform` class is used to serialize and deserialize + * string attributes on Ember Data record objects. This transform is + * used when `string` is passed as the type parameter to the + * [DS.attr](../../data#method_attr) function. + */ + class StringTransform extends Transform { + } + /** + * The `DS.Transform` class is used to serialize and deserialize model + * attributes when they are saved or loaded from an + * adapter. Subclassing `DS.Transform` is useful for creating custom + * attributes. All subclasses of `DS.Transform` must implement a + * `serialize` and a `deserialize` method. + */ + class Transform extends Ember.Object { + /** + * When given a deserialized value from a record attribute this + * method must return the serialized value. + */ + serialize(deserialized: any, options: AttrOptions): any; + /** + * When given a serialize value from a JSON object this method must + * return the deserialized value for the record attribute. + */ + deserialize(serialized: any, options: AttrOptions): any; + } + /** + * An adapter is an object that receives requests from a store and + * translates them into the appropriate action to take against your + * persistence layer. The persistence layer is usually an HTTP API, but + * may be anything, such as the browser's local storage. Typically the + * adapter is not invoked directly instead its functionality is accessed + * through the `store`. + */ + class Adapter extends Ember.Object { + /** + * If you would like your adapter to use a custom serializer you can + * set the `defaultSerializer` property to be the name of the custom + * serializer. + */ + defaultSerializer: string; + /** + * The `findRecord()` method is invoked when the store is asked for a record that + * has not previously been loaded. In response to `findRecord()` being called, you + * should query your persistence layer for a record with the given ID. The `findRecord` + * method should return a promise that will resolve to a JavaScript object that will be + * normalized by the serializer. + */ + findRecord(store: Store, type: Model, id: string, snapshot: Snapshot): Promise; + /** + * The `findAll()` method is used to retrieve all records for a given type. + */ + findAll(store: Store, type: Model, sinceToken: string, snapshotRecordArray: SnapshotRecordArray): Promise; + /** + * This method is called when you call `query` on the store. + */ + query(store: Store, type: Model, query: {}, recordArray: AdapterPopulatedRecordArray): Promise; + /** + * The `queryRecord()` method is invoked when the store is asked for a single + * record through a query object. + */ + queryRecord(store: Store, type: Model, query: {}): Promise; + /** + * If the globally unique IDs for your records should be generated on the client, + * implement the `generateIdForRecord()` method. This method will be invoked + * each time you create a new record, and the value returned from it will be + * assigned to the record's `primaryKey`. + */ + generateIdForRecord(store: Store, type: Model, inputProperties: {}): string|number; + /** + * Proxies to the serializer's `serialize` method. + */ + serialize(snapshot: Snapshot, options: {}): {}; + /** + * Implement this method in a subclass to handle the creation of + * new records. + */ + createRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * Implement this method in a subclass to handle the updating of + * a record. + */ + updateRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * Implement this method in a subclass to handle the deletion of + * a record. + */ + deleteRecord(store: Store, type: Model, snapshot: Snapshot): Promise; + /** + * By default the store will try to coalesce all `fetchRecord` calls within the same runloop + * into as few requests as possible by calling groupRecordsForFindMany and passing it into a findMany call. + * You can opt out of this behaviour by either not implementing the findMany hook or by setting + * coalesceFindRequests to false. + */ + coalesceFindRequests: boolean; + /** + * The store will call `findMany` instead of multiple `findRecord` + * requests to find multiple records at once if coalesceFindRequests + * is true. + */ + findMany(store: Store, type: Model, ids: any[], snapshots: any[]): Promise; + /** + * Organize records into groups, each of which is to be passed to separate + * calls to `findMany`. + */ + groupRecordsForFindMany(store: Store, snapshots: any[]): any[]; + /** + * This method is used by the store to determine if the store should + * reload a record from the adapter when a record is requested by + * `store.findRecord`. + */ + shouldReloadRecord(store: Store, snapshot: Snapshot): boolean; + /** + * This method is used by the store to determine if the store should + * reload all records from the adapter when records are requested by + * `store.findAll`. + */ + shouldReloadAll(store: Store, snapshotRecordArray: SnapshotRecordArray): boolean; + /** + * This method is used by the store to determine if the store should + * reload a record after the `store.findRecord` method resolves a + * cached record. + */ + shouldBackgroundReloadRecord(store: Store, snapshot: Snapshot): boolean; + /** + * This method is used by the store to determine if the store should + * reload a record array after the `store.findAll` method resolves + * with a cached record array. + */ + shouldBackgroundReloadAll(store: Store, snapshotRecordArray: SnapshotRecordArray): boolean; + } + /** + * `DS.Serializer` is an abstract base class that you should override in your + * application to customize it for your backend. The minimum set of methods + * that you should implement is: + */ + class Serializer extends Ember.Object { + /** + * The `store` property is the application's `store` that contains + * all records. It can be used to look up serializers for other model + * types that may be nested inside the payload response. + */ + store: Store; + /** + * The `normalizeResponse` method is used to normalize a payload from the + * server to a JSON-API Document. + */ + normalizeResponse(store: Store, primaryModelClass: Model, payload: {}, id: string|number, requestType: string): {}; + /** + * The `serialize` method is used when a record is saved in order to convert + * the record into the form that your external data source expects. + */ + serialize(snapshot: Snapshot, options: {}): {}; + /** + * The `normalize` method is used to convert a payload received from your + * external data source into the normalized form `store.push()` expects. You + * should override this method, munge the hash and return the normalized + * payload. + */ + normalize(typeClass: Model, hash: {}): {}; + } +} +export default DS; + +declare module 'ember' { + namespace Ember { + /* + * The store is automatically injected into these objects + * + * https://github.com/emberjs/data/blob/05e95280e11c411177f2fbcb65fd83488d6a9d89/addon/setup-container.js#L71-L78 + */ + interface Route { + store: DS.Store; + } + interface Controller { + store: DS.Store; + } + interface DataAdapter { + store: DS.Store; + } + } +} diff --git a/types/ember-data/test/adapter.ts b/types/ember-data/test/adapter.ts new file mode 100644 index 0000000000..d648f73310 --- /dev/null +++ b/types/ember-data/test/adapter.ts @@ -0,0 +1,25 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +const JsonApi = DS.JSONAPIAdapter.extend({ + // Application specific overrides go here +}); + +const Customized = DS.JSONAPIAdapter.extend({ + host: 'https://api.example.com', + namespace: 'api/v1', + headers: { + 'API_KEY': 'secret key', + 'ANOTHER_HEADER': 'Some header value' + } +}); + +const AuthTokenHeader = DS.JSONAPIAdapter.extend({ + session: Ember.inject.service('session'), + headers: Ember.computed('session.authToken', function() { + return { + 'API_KEY': this.get('session.authToken'), + 'ANOTHER_HEADER': 'Some header value' + }; + }) +}); diff --git a/types/ember-data/test/belongs-to.ts b/types/ember-data/test/belongs-to.ts new file mode 100644 index 0000000000..9e59aa6128 --- /dev/null +++ b/types/ember-data/test/belongs-to.ts @@ -0,0 +1,16 @@ +import DS from 'ember-data'; +import { assertType } from './lib/assert'; + +class Folder extends DS.Model { + name = DS.attr('string'); + children = DS.hasMany('folder', { inverse: 'parent' }); + parent = DS.belongsTo('folder', { inverse: 'children' }); +} + +const folder = Folder.create(); +assertType(folder.get('parent')); +assertType(folder.get('parent').get('name')); +folder.get('parent').then(parent => { + assertType(parent); + assertType(parent.get('name')); +}); diff --git a/types/ember-data/test/has-many.ts b/types/ember-data/test/has-many.ts new file mode 100644 index 0000000000..7fb586ff4a --- /dev/null +++ b/types/ember-data/test/has-many.ts @@ -0,0 +1,43 @@ +import DS from 'ember-data'; +import { assertType } from './lib/assert'; + +class Comment extends DS.Model { + text = DS.attr('string'); +} + +class BlogPost extends DS.Model { + title = DS.attr('string'); + commentsAsync = DS.hasMany('comment'); + commentsSync = DS.hasMany('comment', { async: false }); +} + +const post = BlogPost.create(); + +assertType>(post.get('commentsSync').reload()); +assertType(post.get('commentsSync').createRecord()); + +const comment = post.get('commentsSync').get('firstObject'); +assertType(comment); +if (comment) { + assertType(comment.get('text')); +} + +assertType>(post.get('commentsAsync').reload()); +assertType(post.get('commentsAsync').createRecord()); +assertType(post.get('commentsAsync').get('firstObject')); + +const commentAsync = post.get('commentsAsync').get('firstObject'); +assertType(commentAsync); +if (commentAsync) { + assertType(commentAsync.get('text')); +} +assertType(post.get('commentsAsync').get('isFulfilled')); + +post.get('commentsAsync').then(comments => { + assertType(comments.get('firstObject')); + assertType(comments.get('firstObject')!.get('text')); +}); + +class Polymorphic extends DS.Model { + paymentMethods = DS.hasMany('payment-method', { polymorphic: true }); +} diff --git a/types/ember-data/test/injections.ts b/types/ember-data/test/injections.ts new file mode 100644 index 0000000000..4c0a6e4e6b --- /dev/null +++ b/types/ember-data/test/injections.ts @@ -0,0 +1,22 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +Ember.Route.extend({ + model(): any { + return this.store.findAll('my-model'); + } +}); + +Ember.Controller.extend({ + actions: { + create(): any { + return this.store.createRecord('my-model'); + } + } +}); + +Ember.DataAdapter.extend({ + test() { + this.store.findRecord('my-model', 123); + } +}); diff --git a/types/ember-data/test/lib/assert.ts b/types/ember-data/test/lib/assert.ts new file mode 100644 index 0000000000..10094b9616 --- /dev/null +++ b/types/ember-data/test/lib/assert.ts @@ -0,0 +1,2 @@ +/** Static assertion that `value` has type `T` */ +export declare function assertType(value: T): void; diff --git a/types/ember-data/test/model.ts b/types/ember-data/test/model.ts new file mode 100644 index 0000000000..b3fa04e086 --- /dev/null +++ b/types/ember-data/test/model.ts @@ -0,0 +1,29 @@ +import Ember from 'ember'; +import DS from 'ember-data'; +import { assertType } from "./lib/assert"; + +const Person = DS.Model.extend({ + firstName: DS.attr(), + lastName: DS.attr(), + title: DS.attr({ defaultValue: "The default" }), + title2: DS.attr({ defaultValue: () => "The default" }), + + fullName: Ember.computed('firstName', 'lastName', function() { + return `${this.get('firstName')} ${this.get('lastName')}`; + }) +}); + +const User = DS.Model.extend({ + username: DS.attr('string'), + email: DS.attr('string'), + verified: DS.attr('boolean', { defaultValue: false }), + createdAt: DS.attr('date', { + defaultValue() { return new Date(); } + }) +}); + +const user = User.create({ username: 'dwickern' }); +assertType(user.get('id')); +assertType(user.get('username')); +assertType(user.get('verified')); +assertType(user.get('createdAt')); diff --git a/types/ember-data/test/record-reference.ts b/types/ember-data/test/record-reference.ts new file mode 100644 index 0000000000..bb4fda42d4 --- /dev/null +++ b/types/ember-data/test/record-reference.ts @@ -0,0 +1,38 @@ +import DS from 'ember-data'; +import { assertType } from "./lib/assert"; + +declare const store: DS.Store; + +class User extends DS.Model { + username = DS.attr('string'); +} + +let userRef = store.getReference('user', 1); + +// get the record of the reference (null if not yet available) +let user = userRef.value(); +if (user !== null) { + assertType(user); +} + +// get the identifier of the reference +if (userRef.remoteType() === 'id') { + let id = userRef.id(); + assertType(id); +} + +// load user (via store.find) +userRef.load().then(user => { + assertType(user); +}); + +// or trigger a reload +userRef.reload().then(user => { + assertType(user); +}); + +// provide data for reference +userRef.push({ id: 1, username: '@user' }).then(function(user) { + assertType(user); + userRef.value() === user; +}); diff --git a/types/ember-data/test/relationships.ts b/types/ember-data/test/relationships.ts new file mode 100644 index 0000000000..a878428bc4 --- /dev/null +++ b/types/ember-data/test/relationships.ts @@ -0,0 +1,30 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +declare const store: DS.Store; + +const Person = DS.Model.extend({ + children: DS.hasMany('folder', { inverse: 'parent' }), + parent: DS.belongsTo('folder', { inverse: 'children' }) +}); + +const Polymorphic = DS.Model.extend({ + paymentMethods: DS.hasMany('payment-method', { polymorphic: true }) +}); + +class Comment extends DS.Model { + author = DS.attr('string'); +} + +class BlogPost extends DS.Model { + title = DS.attr('string'); + tag = DS.attr('string'); + comments = DS.hasMany('comment', { async: true }); + relatedPosts = DS.hasMany('post'); +} + +let blogPost = store.peekRecord('blog-post', 1); +blogPost!.get('comments').then((comments) => { + // now we can work with the comments + let author: string = comments.get('firstObject')!.get('author'); +}); diff --git a/types/ember-data/test/serializer.ts b/types/ember-data/test/serializer.ts new file mode 100644 index 0000000000..986020144f --- /dev/null +++ b/types/ember-data/test/serializer.ts @@ -0,0 +1,38 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +const JsonApi = DS.JSONAPISerializer.extend({}); + +const Customized = DS.JSONAPISerializer.extend({ + serialize(snapshot: DS.Snapshot, options: {}) { + let json: any = this._super(...Array.from(arguments)); + + json.data.attributes.cost = { + amount: json.data.attributes.amount, + currency: json.data.attributes.currency + }; + + return json; + }, + normalizeResponse(store: DS.Store, primaryModelClass: DS.Model, payload: any, id: string|number, requestType: string) { + payload.data.attributes.amount = payload.data.attributes.cost.amount; + payload.data.attributes.currency = payload.data.attributes.cost.currency; + + delete payload.data.attributes.cost; + + return this._super(...Array.from(arguments)); + } +}); + +const EmbeddedRecordMixin = DS.JSONSerializer.extend(DS.EmbeddedRecordsMixin, { + attrs: { + author: { + serialize: false, + deserialize: 'records' + }, + comments: { + deserialize: 'records', + serialize: 'ids' + } + } +}); diff --git a/types/ember-data/test/store.ts b/types/ember-data/test/store.ts new file mode 100644 index 0000000000..f7560a231f --- /dev/null +++ b/types/ember-data/test/store.ts @@ -0,0 +1,119 @@ +import Ember from 'ember'; +import DS from 'ember-data'; +import { assertType } from "./lib/assert"; + +declare const store: DS.Store; + +class Post extends DS.Model { + title = DS.attr('string'); +} + +let post = store.createRecord('post', { + title: 'Rails is Omakase', + body: 'Lorem ipsum' +}); + +post.save(); // => POST to '/posts' +post.save().then((saved) => { + assertType(saved); +}); + +store.findRecord('post', 1).then(function(post) { + post.get('title'); // => "Rails is Omakase" + post.set('title', 'A new post'); + post.save(); // => PATCH to '/posts/1' +}); + +class User extends DS.Model { + username = DS.attr('string'); +} + +store.queryRecord('user', {}).then(function(user) { + let username = user.get('username'); + console.log(`Currently logged in as ${username}`); +}); + +store.findAll('blog-post'); // => GET /blog-posts +store.findAll('author', { reload: true }).then(function(authors) { + authors.getEach('id'); // ['first', 'second'] +}); +store.findAll('post', { + adapterOptions: { subscribe: false } +}); +store.findAll('post', { include: 'comments,comments.author' }); + +store.peekAll('blog-post'); // => no network request + +if (store.hasRecordForId('post', 1)) { + let maybePost = store.peekRecord('post', 1); + if (maybePost) { + maybePost.get('id'); // 1 + } +} + +class Message extends DS.Model { + hasBeenSeen = DS.attr('boolean'); +} + +const messages = store.peekAll('message'); +messages.forEach(function(message) { + message.set('hasBeenSeen', true); +}); +messages.save(); + +const people = store.peekAll('person'); +people.get('isUpdating'); // false +people.update().then(function() { + people.get('isUpdating'); // false +}); +people.get('isUpdating'); // true + +const MyRoute = Ember.Route.extend({ + model(params: any): any { + return this.store.findRecord('post', params.post_id, {include: 'comments,comments.author'}); + } +}); + +// GET to /users?filter[email]=tomster@example.com +const tom = store.query('user', { + filter: { + email: 'tomster@example.com' + } +}).then(function(users) { + return users.get("firstObject"); +}); + +// GET /users?isAdmin=true +const admins = store.query('user', { isAdmin: true }); +admins.then(function() { + console.log(admins.get("length")); // 42 +}); +admins.update().then(function() { + admins.get('isUpdating'); // false + console.log(admins.get("length")); // 123 +}); + +store.push({ + data: [{ + id: 1, + type: 'album', + attributes: { + title: 'Fewer Moving Parts', + artist: 'David Bazan', + songCount: 10 + }, + relationships: {} + }, { + id: 2, + type: 'album', + attributes: { + title: 'Calgary b/w I Can\'t Make You Love Me/Nick Of Time', + artist: 'Bon Iver', + songCount: 2 + }, + relationships: {} + }] +}); + +assertType(store.adapterFor('person')); +assertType(store.serializerFor('person')); diff --git a/types/ember-data/test/transform.ts b/types/ember-data/test/transform.ts new file mode 100644 index 0000000000..b76d40a73f --- /dev/null +++ b/types/ember-data/test/transform.ts @@ -0,0 +1,16 @@ +import Ember from 'ember'; +import DS from 'ember-data'; + +class Point extends Ember.Object { + x: number; + y: number; +} + +const PointTransform = DS.Transform.extend({ + serialize(value: Point): number[] { + return [value.get('x'), value.get('y')]; + }, + deserialize(value: [ number, number ]): Point { + return Point.create({ x: value[0], y: value[1] }); + } +}); diff --git a/types/ember-data/tsconfig.json b/types/ember-data/tsconfig.json new file mode 100644 index 0000000000..155515ac6b --- /dev/null +++ b/types/ember-data/tsconfig.json @@ -0,0 +1,32 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": false, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "test/lib/assert.ts", + "test/model.ts", + "test/adapter.ts", + "test/serializer.ts", + "test/transform.ts", + "test/relationships.ts", + "test/store.ts", + "test/has-many.ts", + "test/belongs-to.ts", + "test/record-reference.ts", + "test/injections.ts" + ] +} diff --git a/types/ember-data/tslint.json b/types/ember-data/tslint.json new file mode 100644 index 0000000000..dd3a7f529c --- /dev/null +++ b/types/ember-data/tslint.json @@ -0,0 +1,16 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // Heavy use of Function type in this older package. + "ban-types": false, + "jsdoc-format": false, + "no-misused-new": false, + // not sure what this means + "no-single-declare-module": false, + "object-literal-key-quotes": false, + "only-arrow-functions": false, + "no-empty-interface": false, + "prefer-const": false, + "no-unnecessary-generics": false + } +} From 0112196cb92be4009d35907ec0519728cb7dd7a7 Mon Sep 17 00:00:00 2001 From: Knuppe Date: Sun, 19 Nov 2017 22:36:06 -0200 Subject: [PATCH 089/201] This fixes the definitions of classes that extend the EventEmitter (Browser and Page). Signed-off-by: Knuppe --- types/puppeteer/index.d.ts | 50 +++++++++++++++++++++++++++++++++----- 1 file changed, 44 insertions(+), 6 deletions(-) diff --git a/types/puppeteer/index.d.ts b/types/puppeteer/index.d.ts index f92bedd135..991d568a8a 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -7,6 +7,8 @@ /// +import { EventEmitter } from "events"; + /** Keyboard provides an api for managing a virtual keyboard. */ export interface Keyboard { /** @@ -781,11 +783,29 @@ export interface PageEventObj { } /** Page provides methods to interact with a single tab in Chromium. One Browser instance might have multiple Page instances. */ -export interface Page extends FrameBase { +export interface Page extends EventEmitter, FrameBase { + /** + * Adds the listener function to the end of the listeners array for the event named `eventName`. + * No checks are made to see if the listener has already been added. Multiple calls passing the same combination of + * `eventName` and listener will result in the listener being added, and called, multiple times. + * @param event The name of the event. + * @param handler The callback function. + */ on( - event: K, + eventName: K, handler: (e: PageEventObj[K], ...args: any[]) => void - ): void; + ): this; + + /** + * Adds a one time listener function for the event named `eventName`. + * The next time `eventName` is triggered, this listener is removed and then invoked. + * @param event The name of the event. + * @param handler The callback function. + */ + once( + eventName: K, + handler: (e: PageEventObj[K], ...args: any[]) => void + ): this; /** * Provide credentials for http authentication. @@ -1028,11 +1048,29 @@ export interface Page extends FrameBase { } /** A Browser is created when Puppeteer connects to a Chromium instance, either through puppeteer.launch or puppeteer.connect. */ -export interface Browser { +export interface Browser extends EventEmitter { + /** + * Adds the listener function to the end of the listeners array for the event named `eventName`. + * No checks are made to see if the listener has already been added. Multiple calls passing the same combination of + * `eventName` and listener will result in the listener being added, and called, multiple times. + * @param event The name of the event. + * @param handler The callback function. + */ on( - event: K, + eventName: K, handler: (e: BrowserEventObj[K], ...args: any[]) => void - ): void; + ): this; + + /** + * Adds a one time listener function for the event named `eventName`. + * The next time `eventName` is triggered, this listener is removed and then invoked. + * @param event The name of the event. + * @param handler The callback function. + */ + once( + eventName: K, + handler: (e: BrowserEventObj[K], ...args: any[]) => void + ): this; /** * Closes browser with all the pages (if any were opened). From 71bb4d4a87c058cc9f9c7e73397df388453ae637 Mon Sep 17 00:00:00 2001 From: Rico Kahler Date: Sun, 19 Nov 2017 21:11:02 -0500 Subject: [PATCH 090/201] add typings for react-sketchapp --- types/react-sketchapp/index.d.ts | 288 ++++++++++++++++++ .../react-sketchapp/react-sketchapp-tests.tsx | 41 +++ types/react-sketchapp/tsconfig.json | 11 + types/react-sketchapp/tslint.json | 1 + 4 files changed, 341 insertions(+) create mode 100644 types/react-sketchapp/index.d.ts create mode 100644 types/react-sketchapp/react-sketchapp-tests.tsx create mode 100644 types/react-sketchapp/tsconfig.json create mode 100644 types/react-sketchapp/tslint.json diff --git a/types/react-sketchapp/index.d.ts b/types/react-sketchapp/index.d.ts new file mode 100644 index 0000000000..38573eac89 --- /dev/null +++ b/types/react-sketchapp/index.d.ts @@ -0,0 +1,288 @@ + +// Type definitions for react-sketchapp 0.12 +// Project: https://github.com/airbnb/react-sketchapp +// Definitions by: Rico Kahler +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +import * as React from "../react/index"; + +declare global { + export const context: SketchContext; +} + +// sketch interfaces taken from +// https://github.com/airbnb/react-sketchapp/blob/v0.12.1/src/types.js +export interface SketchPage { name: () => any } +export interface SketchAssetCollection { + colors: () => any[], + gradients: () => any[], +} +export interface SketchSharedStyleContainer { + setObjects: (objects: any[]) => void, + addSharedStyleWithName_firstInstance: (name: string, ins: any) => void, +} +export interface SketchDocumentData { + layerStyles: () => void, + layerTextStyles: () => SketchSharedStyleContainer, + layerSymbols: () => void, + assets: () => SketchAssetCollection, +} +export interface SketchDocument { + documentData: () => SketchDocumentData, + pages: () => SketchPage[], + addBlankPage: () => SketchPage, + currentPage: SketchPage, +} +export interface SketchContext { document: SketchDocument } + +/** + * Returns the top-level rendered Sketch object or an array of Sketch objects if you use + * components. + * @param element Top-level React component that defines your Sketch document. + * @param container The element to render into - will be replaced. Should either be a Sketch Group + * or Page Object. + * @return The top-most rendered native Sketch layer. + */ +export function render(element: JSX.Element, container?: any): any; + +/** + * Returns a Sketch JSON object for further consumption - doesn't add to the page. + * @param element + * @return The top-most Sketch layer as JSON. + */ +export function renderToJSON(element: JSX.Element): any; + +// https://github.com/airbnb/react-sketchapp/blob/v0.12.1/src/types.js#L59 +export type Color = string | number; + +/** + * The [`StyleSheet` api uses numbers as IDs][0] to pull registered styles. The component props + * can actually take either a `Style` or a `StyleReference` (where the `StyleReference` is given + * by a `StyleSheet` obj created with `StyleSheet.create`) + * [0]: https://github.com/airbnb/react-sketchapp/blob/v0.12.1/src/stylesheet/index.js#L34 + */ +export type StyleReference = number; + +/** + * Represents the base styles that can be applied to a component. + */ +export interface Style { + shadowColor?: Color, + shadowOffset?: { width?: number, height?: number }, + shadowOpacity?: number, + shadowRadius?: number, + width?: number, + height?: number, + top?: number, + left?: number, + right?: number, + bottom?: number, + minWidth?: number, + maxWidth?: number, + minHeight?: number, + maxHeight?: number, + margin?: number, + marginVertical?: number, + marginHorizontal?: number, + marginTop?: number, + marginBottom?: number, + marginLeft?: number, + marginRight?: number, + padding?: number, + paddingVertical?: number, + paddingHorizontal?: number, + paddingTop?: number, + paddingBottom?: number, + paddingLeft?: number, + paddingRight?: number, + borderWidth?: number, + borderTopWidth?: number, + borderRightWidth?: number, + borderBottomWidth?: number, + borderLeftWidth?: number, + position?: 'absolute' | 'relative', + flexDirection?: 'row' | 'row-reverse' | 'column' | 'column-reverse', + flexWrap?: 'wrap' | 'nowrap', + justifyContent?: 'flex-start' | 'flex-end' | 'center' | 'space-between' | 'space-around', + alignItems?: 'flex-start' | 'flex-end' | 'center' | 'stretch', + alignSelf?: 'auto' | 'flex-start' | 'flex-end' | 'center' | 'stretch', + overflow?: 'visible' | 'hidden' | 'scroll', + flex?: number, + flexGrow?: number, + flexShrink?: number, + flexBasis?: number, + aspectRatio?: number, + zIndex?: number, + backfaceVisibility?: 'visible' | 'hidden', + backgroundColor?: Color, + borderColor?: Color, + borderTopColor?: Color, + borderRightColor?: Color, + borderBottomColor?: Color, + borderLeftColor?: Color, + borderRadius?: number, + borderTopLeftRadius?: number, + borderTopRightRadius?: number, + borderBottomLeftRadius?: number, + borderBottomRightRadius?: number, + borderStyle?: 'solid' | 'dotted' | 'dashed', + opacity?: number, +} + +/** + * Represents all the Styles that can be applied to a `` component. The this interface + * extends the `Style` interface + */ +export interface TextStyle extends Style { + color?: Color, + fontFamily?: string, + fontSize?: number, + fontStyle?: 'normal' | 'italic', + fontWeight?: string, + textDecorationLine?: 'none' | 'underline' | 'double' | 'line-through', + textShadowOffset?: { width: number, height: number }, + textShadowRadius?: number, + textShadowColor?: Color, + letterSpacing?: number, + lineHeight?: number, + textAlign?: 'auto' | 'left' | 'right' | 'center' | 'justify', + writingDirection?: 'auto' | 'ltr' | 'rtl', +} + +// wanted to type these as classes because they are implemented as classes and typing them this +// way gives you typings like `Artboard.prototype` + + +// Artboard +export interface ArtboardProps { + /** + * The name to be displayed in the Sketch Layer List + */ + name?: string, + children?: any, + style?: Style | StyleReference, +} +/** + * Wrapper for Sketch's Artboards. + */ +export class Artboard extends React.Component { } + + +// Image +type ImageSource = string | { src: string }; +type ResizeMode = 'contain' | 'cover' | 'stretch' | 'center' | 'repeat' | 'none'; +interface ImageProps { + children?: any, + source?: ImageSource, + style?: Style | StyleReference, + resizeMode: ResizeMode, +} +export class Image extends React.Component { } + + +// RedBox +export interface RedBoxProps { + /** A JavaScript Error object */ + error: Error, +} +/** + * A red box / 'red screen of death' error handler. Thanks to [commissure/redbox-react.][0] + * --SUGGESTION: can you give a screenshot of what this looks like? + * + * [0]: https://github.com/commissure/redbox-react + */ +export class RedBox extends React.Component { } + + +// Text +export interface TextProps { + name?: string, + children?: string, + style?: TextStyle | StyleReference, +} +/** Text primitives */ +export class Text extends React.Component { } + + +// View +export interface ViewProps { + name?: string, + children?: any, + style?: Style | StyleReference, +} +/** View primitives */ +export class View extends React.Component { } + + +export const StyleSheet: { + hairlineWidth: 1, + absoluteFill: StyleReference, + /** + * Create an optimized `StyleSheet` reference from a style object. + */ + create: (t: T) => { + [P in keyof T]: StyleReference + }, + /** + * Flatten an array of style objects into one aggregated object, or look up the definition for a + * registered stylesheet. + */ + flatten: ( + input: (Style | TextStyle | StyleReference)[] | StyleReference | undefined | Style + ) => Style | TextStyle, // returns the expanded style or expanded style reference which conforms + // to the `Style | TextStyle` interface + /** + * resolve one style + */ + resolve: (style: Style | TextStyle) => { style: Style | TextStyle } +}; + +/** + * An interface to Sketch's shared text styles. Create styles with or without rendering them to + * the document canvas. + */ +export const TextStyles: { + /** + * The primary interface to TextStyles. Call this before rendering. + */ + create: ( + options: { context: SketchContext, clearExistingStyle?: boolean }, + styles: { [key: string]: TextStyle } + ) => any, + /** + * Find a stored native Sketch style object for a given JavaScript style object. You probably + * don't need to use this. + */ + resolve: (style: TextStyle) => any, + /** + * Find a stored style by name. + */ + get: (name: string) => TextStyle | undefined, + /** + * Find all of the registered styles. You probably don't need to use this. + */ + styles: { [key: string]: TextStyle | undefined }, + /** + * Reset the registered styles. + */ + clear: () => void, +}; + + +// Symbols +/** + * Returns a Sketch symbol given a node and an optional name. + * @param node The node object that will be rendered as a symbol + * @param name Optional name for the symbol, string can include backslashes to organize these + * symbols with Sketch. For example squares/blue + */ +export function makeSymbol

( + node: React.ComponentClass

| ((props: P) => JSX.Element), + name?: string +): React.ComponentClass

; + +/** + * Injects the symbols into Sketch's symbol page. **Call this before rendering.** + * @param context + */ +export function injectSymbols(context: SketchContext): void; \ No newline at end of file diff --git a/types/react-sketchapp/react-sketchapp-tests.tsx b/types/react-sketchapp/react-sketchapp-tests.tsx new file mode 100644 index 0000000000..e769df93b3 --- /dev/null +++ b/types/react-sketchapp/react-sketchapp-tests.tsx @@ -0,0 +1,41 @@ +import { Artboard, View, Text, StyleSheet, TextStyles, render, renderToJSON } from './index'; + +// the styles object should be a mapped typed mapping the keys of the object literal to numbers +const styles = StyleSheet.create({ + red: { + backgroundColor: '#FF00000' + }, + flexRow: { + flexDirection: 'row' + } +}); + +// style references are numbers +const styleReference = styles.red; + +const Document = () => + + text must be a string + + + + + +render(); +renderToJSON(); + +// Artboard is typed with a class so the prototype should be typed too (not very useful though) +Artboard.prototype.componentDidMount + +// context is a global but conflicts with others in this library +// TODO: currently this interface returns any but it looks like this method produces a side-affect +// and the return type isn't used anyway +TextStyles.create(context as any, { + normal: { + fontSize: 16, + }, + heading: { + fontSize: 16 * 1.618, + fontWeight: 'bold', + } +}); \ No newline at end of file diff --git a/types/react-sketchapp/tsconfig.json b/types/react-sketchapp/tsconfig.json new file mode 100644 index 0000000000..796c91f46b --- /dev/null +++ b/types/react-sketchapp/tsconfig.json @@ -0,0 +1,11 @@ +{ + "compilerOptions": { + "target": "es2017", + "module": "es2015", + "jsx": "preserve", + "strict": true, + "typeRoots": [ + "../" + ] + } +} \ No newline at end of file diff --git a/types/react-sketchapp/tslint.json b/types/react-sketchapp/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-sketchapp/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } From f14380642aac27f70b028887a6745209da8107fe Mon Sep 17 00:00:00 2001 From: Rico Kahler Date: Sun, 19 Nov 2017 21:31:17 -0500 Subject: [PATCH 091/201] run through linter --- types/react-sketchapp/index.d.ts | 241 +++++++++--------- .../react-sketchapp/react-sketchapp-tests.tsx | 8 +- types/react-sketchapp/tsconfig.json | 16 +- 3 files changed, 132 insertions(+), 133 deletions(-) diff --git a/types/react-sketchapp/index.d.ts b/types/react-sketchapp/index.d.ts index 38573eac89..055e5aadc3 100644 --- a/types/react-sketchapp/index.d.ts +++ b/types/react-sketchapp/index.d.ts @@ -1,39 +1,39 @@ - // Type definitions for react-sketchapp 0.12 // Project: https://github.com/airbnb/react-sketchapp // Definitions by: Rico Kahler // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as React from "../react/index"; declare global { - export const context: SketchContext; + const context: SketchContext; } // sketch interfaces taken from // https://github.com/airbnb/react-sketchapp/blob/v0.12.1/src/types.js -export interface SketchPage { name: () => any } +export interface SketchPage { name: () => any; } export interface SketchAssetCollection { - colors: () => any[], - gradients: () => any[], + colors: () => any[]; + gradients: () => any[]; } export interface SketchSharedStyleContainer { - setObjects: (objects: any[]) => void, - addSharedStyleWithName_firstInstance: (name: string, ins: any) => void, + setObjects: (objects: any[]) => void; + addSharedStyleWithName_firstInstance: (name: string, ins: any) => void; } export interface SketchDocumentData { - layerStyles: () => void, - layerTextStyles: () => SketchSharedStyleContainer, - layerSymbols: () => void, - assets: () => SketchAssetCollection, + layerStyles: () => void; + layerTextStyles: () => SketchSharedStyleContainer; + layerSymbols: () => void; + assets: () => SketchAssetCollection; } export interface SketchDocument { - documentData: () => SketchDocumentData, - pages: () => SketchPage[], - addBlankPage: () => SketchPage, - currentPage: SketchPage, + documentData: () => SketchDocumentData; + pages: () => SketchPage[]; + addBlankPage: () => SketchPage; + currentPage: SketchPage; } -export interface SketchContext { document: SketchDocument } +export interface SketchContext { document: SketchDocument; } /** * Returns the top-level rendered Sketch object or an array of Sketch objects if you use @@ -47,7 +47,6 @@ export function render(element: JSX.Element, container?: any): any; /** * Returns a Sketch JSON object for further consumption - doesn't add to the page. - * @param element * @return The top-most Sketch layer as JSON. */ export function renderToJSON(element: JSX.Element): any; @@ -67,66 +66,66 @@ export type StyleReference = number; * Represents the base styles that can be applied to a component. */ export interface Style { - shadowColor?: Color, - shadowOffset?: { width?: number, height?: number }, - shadowOpacity?: number, - shadowRadius?: number, - width?: number, - height?: number, - top?: number, - left?: number, - right?: number, - bottom?: number, - minWidth?: number, - maxWidth?: number, - minHeight?: number, - maxHeight?: number, - margin?: number, - marginVertical?: number, - marginHorizontal?: number, - marginTop?: number, - marginBottom?: number, - marginLeft?: number, - marginRight?: number, - padding?: number, - paddingVertical?: number, - paddingHorizontal?: number, - paddingTop?: number, - paddingBottom?: number, - paddingLeft?: number, - paddingRight?: number, - borderWidth?: number, - borderTopWidth?: number, - borderRightWidth?: number, - borderBottomWidth?: number, - borderLeftWidth?: number, - position?: 'absolute' | 'relative', - flexDirection?: 'row' | 'row-reverse' | 'column' | 'column-reverse', - flexWrap?: 'wrap' | 'nowrap', - justifyContent?: 'flex-start' | 'flex-end' | 'center' | 'space-between' | 'space-around', - alignItems?: 'flex-start' | 'flex-end' | 'center' | 'stretch', - alignSelf?: 'auto' | 'flex-start' | 'flex-end' | 'center' | 'stretch', - overflow?: 'visible' | 'hidden' | 'scroll', - flex?: number, - flexGrow?: number, - flexShrink?: number, - flexBasis?: number, - aspectRatio?: number, - zIndex?: number, - backfaceVisibility?: 'visible' | 'hidden', - backgroundColor?: Color, - borderColor?: Color, - borderTopColor?: Color, - borderRightColor?: Color, - borderBottomColor?: Color, - borderLeftColor?: Color, - borderRadius?: number, - borderTopLeftRadius?: number, - borderTopRightRadius?: number, - borderBottomLeftRadius?: number, - borderBottomRightRadius?: number, - borderStyle?: 'solid' | 'dotted' | 'dashed', - opacity?: number, + shadowColor?: Color; + shadowOffset?: { width?: number, height?: number }; + shadowOpacity?: number; + shadowRadius?: number; + width?: number; + height?: number; + top?: number; + left?: number; + right?: number; + bottom?: number; + minWidth?: number; + maxWidth?: number; + minHeight?: number; + maxHeight?: number; + margin?: number; + marginVertical?: number; + marginHorizontal?: number; + marginTop?: number; + marginBottom?: number; + marginLeft?: number; + marginRight?: number; + padding?: number; + paddingVertical?: number; + paddingHorizontal?: number; + paddingTop?: number; + paddingBottom?: number; + paddingLeft?: number; + paddingRight?: number; + borderWidth?: number; + borderTopWidth?: number; + borderRightWidth?: number; + borderBottomWidth?: number; + borderLeftWidth?: number; + position?: 'absolute' | 'relative'; + flexDirection?: 'row' | 'row-reverse' | 'column' | 'column-reverse'; + flexWrap?: 'wrap' | 'nowrap'; + justifyContent?: 'flex-start' | 'flex-end' | 'center' | 'space-between' | 'space-around'; + alignItems?: 'flex-start' | 'flex-end' | 'center' | 'stretch'; + alignSelf?: 'auto' | 'flex-start' | 'flex-end' | 'center' | 'stretch'; + overflow?: 'visible' | 'hidden' | 'scroll'; + flex?: number; + flexGrow?: number; + flexShrink?: number; + flexBasis?: number; + aspectRatio?: number; + zIndex?: number; + backfaceVisibility?: 'visible' | 'hidden'; + backgroundColor?: Color; + borderColor?: Color; + borderTopColor?: Color; + borderRightColor?: Color; + borderBottomColor?: Color; + borderLeftColor?: Color; + borderRadius?: number; + borderTopLeftRadius?: number; + borderTopRightRadius?: number; + borderBottomLeftRadius?: number; + borderBottomRightRadius?: number; + borderStyle?: 'solid' | 'dotted' | 'dashed'; + opacity?: number; } /** @@ -134,101 +133,93 @@ export interface Style { * extends the `Style` interface */ export interface TextStyle extends Style { - color?: Color, - fontFamily?: string, - fontSize?: number, - fontStyle?: 'normal' | 'italic', - fontWeight?: string, - textDecorationLine?: 'none' | 'underline' | 'double' | 'line-through', - textShadowOffset?: { width: number, height: number }, - textShadowRadius?: number, - textShadowColor?: Color, - letterSpacing?: number, - lineHeight?: number, - textAlign?: 'auto' | 'left' | 'right' | 'center' | 'justify', - writingDirection?: 'auto' | 'ltr' | 'rtl', + color?: Color; + fontFamily?: string; + fontSize?: number; + fontStyle?: 'normal' | 'italic'; + fontWeight?: string; + textDecorationLine?: 'none' | 'underline' | 'double' | 'line-through'; + textShadowOffset?: { width: number, height: number }; + textShadowRadius?: number; + textShadowColor?: Color; + letterSpacing?: number; + lineHeight?: number; + textAlign?: 'auto' | 'left' | 'right' | 'center' | 'justify'; + writingDirection?: 'auto' | 'ltr' | 'rtl'; } // wanted to type these as classes because they are implemented as classes and typing them this // way gives you typings like `Artboard.prototype` - // Artboard export interface ArtboardProps { /** * The name to be displayed in the Sketch Layer List */ - name?: string, - children?: any, - style?: Style | StyleReference, + name?: string; + children?: any; + style?: Style | StyleReference; } /** * Wrapper for Sketch's Artboards. */ export class Artboard extends React.Component { } - // Image -type ImageSource = string | { src: string }; -type ResizeMode = 'contain' | 'cover' | 'stretch' | 'center' | 'repeat' | 'none'; -interface ImageProps { - children?: any, - source?: ImageSource, - style?: Style | StyleReference, - resizeMode: ResizeMode, +export type ImageSource = string | { src: string }; +export type ResizeMode = 'contain' | 'cover' | 'stretch' | 'center' | 'repeat' | 'none'; +export interface ImageProps { + children?: any; + source?: ImageSource; + style?: Style | StyleReference; + resizeMode: ResizeMode; } export class Image extends React.Component { } - // RedBox export interface RedBoxProps { /** A JavaScript Error object */ - error: Error, + error: Error; } /** - * A red box / 'red screen of death' error handler. Thanks to [commissure/redbox-react.][0] - * --SUGGESTION: can you give a screenshot of what this looks like? - * - * [0]: https://github.com/commissure/redbox-react + * A red box / 'red screen of death' error handler. Thanks to + * [commissure/redbox-react.](https://github.com/commissure/redbox-react) */ export class RedBox extends React.Component { } - // Text export interface TextProps { - name?: string, - children?: string, - style?: TextStyle | StyleReference, + name?: string; + children?: string; + style?: TextStyle | StyleReference; } /** Text primitives */ export class Text extends React.Component { } - // View export interface ViewProps { - name?: string, - children?: any, - style?: Style | StyleReference, + name?: string; + children?: any; + style?: Style | StyleReference; } /** View primitives */ export class View extends React.Component { } - export const StyleSheet: { - hairlineWidth: 1, - absoluteFill: StyleReference, + hairlineWidth: 1; + absoluteFill: StyleReference; /** * Create an optimized `StyleSheet` reference from a style object. */ create: (t: T) => { [P in keyof T]: StyleReference - }, - /** + }; + /** * Flatten an array of style objects into one aggregated object, or look up the definition for a * registered stylesheet. */ flatten: ( - input: (Style | TextStyle | StyleReference)[] | StyleReference | undefined | Style + input: Array