From 97d40ab4329b4b0ef7083987762dc576c712198b Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Thu, 13 Oct 2016 17:08:58 -0700 Subject: [PATCH] Update LKG --- lib/lib.d.ts | 406 +- lib/lib.dom.d.ts | 381 +- lib/lib.es2015.core.d.ts | 2 +- lib/lib.es5.d.ts | 24 + lib/lib.es6.d.ts | 405 +- lib/lib.webworker.d.ts | 12 +- lib/protocol.d.ts | 1848 +++++++ lib/tsc.js | 3575 ++++++------ lib/tsserver.js | 10126 +++++++++++++++++++++------------- lib/tsserverlibrary.d.ts | 2356 ++++++-- lib/tsserverlibrary.js | 9961 ++++++++++++++++++++------------- lib/typescript.d.ts | 480 +- lib/typescript.js | 4929 ++++++++++------- lib/typescriptServices.d.ts | 480 +- lib/typescriptServices.js | 4929 ++++++++++------- lib/typingsInstaller.js | 377 +- 16 files changed, 25228 insertions(+), 15063 deletions(-) create mode 100644 lib/protocol.d.ts diff --git a/lib/lib.d.ts b/lib/lib.d.ts index d8be920dc0a..87280fedba4 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -260,9 +260,6 @@ interface Function { */ bind(this: Function, thisArg: any, ...argArray: any[]): any; - /** Returns a string representation of an object. */ - toString(): string; - prototype: any; readonly length: number; @@ -1219,6 +1216,30 @@ interface Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U]; /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. @@ -11663,11 +11684,12 @@ declare var HashChangeEvent: { interface History { readonly length: number; readonly state: any; - back(distance?: any): void; - forward(distance?: any): void; - go(delta?: any): void; - pushState(statedata: any, title?: string, url?: string): void; - replaceState(statedata: any, title?: string, url?: string): void; + scrollRestoration: ScrollRestoration; + back(): void; + forward(): void; + go(delta?: number): void; + pushState(data: any, title: string, url?: string | null): void; + replaceState(data: any, title: string, url?: string | null): void; } declare var History: { @@ -17239,7 +17261,6 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; - [index: number]: Window; } declare var Window: { @@ -17270,7 +17291,7 @@ declare var XMLDocument: { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - onreadystatechange: (this: this, ev: ProgressEvent) => any; + onreadystatechange: (this: this, ev: Event) => any; readonly readyState: number; readonly response: any; readonly responseText: string; @@ -17297,13 +17318,13 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -17644,183 +17665,183 @@ interface NavigatorUserMedia { } interface NodeSelector { - querySelector(selectors: "a"): HTMLAnchorElement; - querySelector(selectors: "abbr"): HTMLElement; - querySelector(selectors: "acronym"): HTMLElement; - querySelector(selectors: "address"): HTMLElement; - querySelector(selectors: "applet"): HTMLAppletElement; - querySelector(selectors: "area"): HTMLAreaElement; - querySelector(selectors: "article"): HTMLElement; - querySelector(selectors: "aside"): HTMLElement; - querySelector(selectors: "audio"): HTMLAudioElement; - querySelector(selectors: "b"): HTMLElement; - querySelector(selectors: "base"): HTMLBaseElement; - querySelector(selectors: "basefont"): HTMLBaseFontElement; - querySelector(selectors: "bdo"): HTMLElement; - querySelector(selectors: "big"): HTMLElement; - querySelector(selectors: "blockquote"): HTMLQuoteElement; - querySelector(selectors: "body"): HTMLBodyElement; - querySelector(selectors: "br"): HTMLBRElement; - querySelector(selectors: "button"): HTMLButtonElement; - querySelector(selectors: "canvas"): HTMLCanvasElement; - querySelector(selectors: "caption"): HTMLTableCaptionElement; - querySelector(selectors: "center"): HTMLElement; - querySelector(selectors: "circle"): SVGCircleElement; - querySelector(selectors: "cite"): HTMLElement; - querySelector(selectors: "clippath"): SVGClipPathElement; - querySelector(selectors: "code"): HTMLElement; - querySelector(selectors: "col"): HTMLTableColElement; - querySelector(selectors: "colgroup"): HTMLTableColElement; - querySelector(selectors: "datalist"): HTMLDataListElement; - querySelector(selectors: "dd"): HTMLElement; - querySelector(selectors: "defs"): SVGDefsElement; - querySelector(selectors: "del"): HTMLModElement; - querySelector(selectors: "desc"): SVGDescElement; - querySelector(selectors: "dfn"): HTMLElement; - querySelector(selectors: "dir"): HTMLDirectoryElement; - querySelector(selectors: "div"): HTMLDivElement; - querySelector(selectors: "dl"): HTMLDListElement; - querySelector(selectors: "dt"): HTMLElement; - querySelector(selectors: "ellipse"): SVGEllipseElement; - querySelector(selectors: "em"): HTMLElement; - querySelector(selectors: "embed"): HTMLEmbedElement; - querySelector(selectors: "feblend"): SVGFEBlendElement; - querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement; - querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement; - querySelector(selectors: "fecomposite"): SVGFECompositeElement; - querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement; - querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement; - querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement; - querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement; - querySelector(selectors: "feflood"): SVGFEFloodElement; - querySelector(selectors: "fefunca"): SVGFEFuncAElement; - querySelector(selectors: "fefuncb"): SVGFEFuncBElement; - querySelector(selectors: "fefuncg"): SVGFEFuncGElement; - querySelector(selectors: "fefuncr"): SVGFEFuncRElement; - querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement; - querySelector(selectors: "feimage"): SVGFEImageElement; - querySelector(selectors: "femerge"): SVGFEMergeElement; - querySelector(selectors: "femergenode"): SVGFEMergeNodeElement; - querySelector(selectors: "femorphology"): SVGFEMorphologyElement; - querySelector(selectors: "feoffset"): SVGFEOffsetElement; - querySelector(selectors: "fepointlight"): SVGFEPointLightElement; - querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement; - querySelector(selectors: "fespotlight"): SVGFESpotLightElement; - querySelector(selectors: "fetile"): SVGFETileElement; - querySelector(selectors: "feturbulence"): SVGFETurbulenceElement; - querySelector(selectors: "fieldset"): HTMLFieldSetElement; - querySelector(selectors: "figcaption"): HTMLElement; - querySelector(selectors: "figure"): HTMLElement; - querySelector(selectors: "filter"): SVGFilterElement; - querySelector(selectors: "font"): HTMLFontElement; - querySelector(selectors: "footer"): HTMLElement; - querySelector(selectors: "foreignobject"): SVGForeignObjectElement; - querySelector(selectors: "form"): HTMLFormElement; - querySelector(selectors: "frame"): HTMLFrameElement; - querySelector(selectors: "frameset"): HTMLFrameSetElement; - querySelector(selectors: "g"): SVGGElement; - querySelector(selectors: "h1"): HTMLHeadingElement; - querySelector(selectors: "h2"): HTMLHeadingElement; - querySelector(selectors: "h3"): HTMLHeadingElement; - querySelector(selectors: "h4"): HTMLHeadingElement; - querySelector(selectors: "h5"): HTMLHeadingElement; - querySelector(selectors: "h6"): HTMLHeadingElement; - querySelector(selectors: "head"): HTMLHeadElement; - querySelector(selectors: "header"): HTMLElement; - querySelector(selectors: "hgroup"): HTMLElement; - querySelector(selectors: "hr"): HTMLHRElement; - querySelector(selectors: "html"): HTMLHtmlElement; - querySelector(selectors: "i"): HTMLElement; - querySelector(selectors: "iframe"): HTMLIFrameElement; - querySelector(selectors: "image"): SVGImageElement; - querySelector(selectors: "img"): HTMLImageElement; - querySelector(selectors: "input"): HTMLInputElement; - querySelector(selectors: "ins"): HTMLModElement; - querySelector(selectors: "isindex"): HTMLUnknownElement; - querySelector(selectors: "kbd"): HTMLElement; - querySelector(selectors: "keygen"): HTMLElement; - querySelector(selectors: "label"): HTMLLabelElement; - querySelector(selectors: "legend"): HTMLLegendElement; - querySelector(selectors: "li"): HTMLLIElement; - querySelector(selectors: "line"): SVGLineElement; - querySelector(selectors: "lineargradient"): SVGLinearGradientElement; - querySelector(selectors: "link"): HTMLLinkElement; - querySelector(selectors: "listing"): HTMLPreElement; - querySelector(selectors: "map"): HTMLMapElement; - querySelector(selectors: "mark"): HTMLElement; - querySelector(selectors: "marker"): SVGMarkerElement; - querySelector(selectors: "marquee"): HTMLMarqueeElement; - querySelector(selectors: "mask"): SVGMaskElement; - querySelector(selectors: "menu"): HTMLMenuElement; - querySelector(selectors: "meta"): HTMLMetaElement; - querySelector(selectors: "metadata"): SVGMetadataElement; - querySelector(selectors: "meter"): HTMLMeterElement; - querySelector(selectors: "nav"): HTMLElement; - querySelector(selectors: "nextid"): HTMLUnknownElement; - querySelector(selectors: "nobr"): HTMLElement; - querySelector(selectors: "noframes"): HTMLElement; - querySelector(selectors: "noscript"): HTMLElement; - querySelector(selectors: "object"): HTMLObjectElement; - querySelector(selectors: "ol"): HTMLOListElement; - querySelector(selectors: "optgroup"): HTMLOptGroupElement; - querySelector(selectors: "option"): HTMLOptionElement; - querySelector(selectors: "p"): HTMLParagraphElement; - querySelector(selectors: "param"): HTMLParamElement; - querySelector(selectors: "path"): SVGPathElement; - querySelector(selectors: "pattern"): SVGPatternElement; - querySelector(selectors: "picture"): HTMLPictureElement; - querySelector(selectors: "plaintext"): HTMLElement; - querySelector(selectors: "polygon"): SVGPolygonElement; - querySelector(selectors: "polyline"): SVGPolylineElement; - querySelector(selectors: "pre"): HTMLPreElement; - querySelector(selectors: "progress"): HTMLProgressElement; - querySelector(selectors: "q"): HTMLQuoteElement; - querySelector(selectors: "radialgradient"): SVGRadialGradientElement; - querySelector(selectors: "rect"): SVGRectElement; - querySelector(selectors: "rt"): HTMLElement; - querySelector(selectors: "ruby"): HTMLElement; - querySelector(selectors: "s"): HTMLElement; - querySelector(selectors: "samp"): HTMLElement; - querySelector(selectors: "script"): HTMLScriptElement; - querySelector(selectors: "section"): HTMLElement; - querySelector(selectors: "select"): HTMLSelectElement; - querySelector(selectors: "small"): HTMLElement; - querySelector(selectors: "source"): HTMLSourceElement; - querySelector(selectors: "span"): HTMLSpanElement; - querySelector(selectors: "stop"): SVGStopElement; - querySelector(selectors: "strike"): HTMLElement; - querySelector(selectors: "strong"): HTMLElement; - querySelector(selectors: "style"): HTMLStyleElement; - querySelector(selectors: "sub"): HTMLElement; - querySelector(selectors: "sup"): HTMLElement; - querySelector(selectors: "svg"): SVGSVGElement; - querySelector(selectors: "switch"): SVGSwitchElement; - querySelector(selectors: "symbol"): SVGSymbolElement; - querySelector(selectors: "table"): HTMLTableElement; - querySelector(selectors: "tbody"): HTMLTableSectionElement; - querySelector(selectors: "td"): HTMLTableDataCellElement; - querySelector(selectors: "template"): HTMLTemplateElement; - querySelector(selectors: "text"): SVGTextElement; - querySelector(selectors: "textpath"): SVGTextPathElement; - querySelector(selectors: "textarea"): HTMLTextAreaElement; - querySelector(selectors: "tfoot"): HTMLTableSectionElement; - querySelector(selectors: "th"): HTMLTableHeaderCellElement; - querySelector(selectors: "thead"): HTMLTableSectionElement; - querySelector(selectors: "title"): HTMLTitleElement; - querySelector(selectors: "tr"): HTMLTableRowElement; - querySelector(selectors: "track"): HTMLTrackElement; - querySelector(selectors: "tspan"): SVGTSpanElement; - querySelector(selectors: "tt"): HTMLElement; - querySelector(selectors: "u"): HTMLElement; - querySelector(selectors: "ul"): HTMLUListElement; - querySelector(selectors: "use"): SVGUseElement; - querySelector(selectors: "var"): HTMLElement; - querySelector(selectors: "video"): HTMLVideoElement; - querySelector(selectors: "view"): SVGViewElement; - querySelector(selectors: "wbr"): HTMLElement; - querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement; - querySelector(selectors: "xmp"): HTMLPreElement; - querySelector(selectors: string): Element; + querySelector(selectors: "a"): HTMLAnchorElement | null; + querySelector(selectors: "abbr"): HTMLElement | null; + querySelector(selectors: "acronym"): HTMLElement | null; + querySelector(selectors: "address"): HTMLElement | null; + querySelector(selectors: "applet"): HTMLAppletElement | null; + querySelector(selectors: "area"): HTMLAreaElement | null; + querySelector(selectors: "article"): HTMLElement | null; + querySelector(selectors: "aside"): HTMLElement | null; + querySelector(selectors: "audio"): HTMLAudioElement | null; + querySelector(selectors: "b"): HTMLElement | null; + querySelector(selectors: "base"): HTMLBaseElement | null; + querySelector(selectors: "basefont"): HTMLBaseFontElement | null; + querySelector(selectors: "bdo"): HTMLElement | null; + querySelector(selectors: "big"): HTMLElement | null; + querySelector(selectors: "blockquote"): HTMLQuoteElement | null; + querySelector(selectors: "body"): HTMLBodyElement | null; + querySelector(selectors: "br"): HTMLBRElement | null; + querySelector(selectors: "button"): HTMLButtonElement | null; + querySelector(selectors: "canvas"): HTMLCanvasElement | null; + querySelector(selectors: "caption"): HTMLTableCaptionElement | null; + querySelector(selectors: "center"): HTMLElement | null; + querySelector(selectors: "circle"): SVGCircleElement | null; + querySelector(selectors: "cite"): HTMLElement | null; + querySelector(selectors: "clippath"): SVGClipPathElement | null; + querySelector(selectors: "code"): HTMLElement | null; + querySelector(selectors: "col"): HTMLTableColElement | null; + querySelector(selectors: "colgroup"): HTMLTableColElement | null; + querySelector(selectors: "datalist"): HTMLDataListElement | null; + querySelector(selectors: "dd"): HTMLElement | null; + querySelector(selectors: "defs"): SVGDefsElement | null; + querySelector(selectors: "del"): HTMLModElement | null; + querySelector(selectors: "desc"): SVGDescElement | null; + querySelector(selectors: "dfn"): HTMLElement | null; + querySelector(selectors: "dir"): HTMLDirectoryElement | null; + querySelector(selectors: "div"): HTMLDivElement | null; + querySelector(selectors: "dl"): HTMLDListElement | null; + querySelector(selectors: "dt"): HTMLElement | null; + querySelector(selectors: "ellipse"): SVGEllipseElement | null; + querySelector(selectors: "em"): HTMLElement | null; + querySelector(selectors: "embed"): HTMLEmbedElement | null; + querySelector(selectors: "feblend"): SVGFEBlendElement | null; + querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement | null; + querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement | null; + querySelector(selectors: "fecomposite"): SVGFECompositeElement | null; + querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement | null; + querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement | null; + querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement | null; + querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement | null; + querySelector(selectors: "feflood"): SVGFEFloodElement | null; + querySelector(selectors: "fefunca"): SVGFEFuncAElement | null; + querySelector(selectors: "fefuncb"): SVGFEFuncBElement | null; + querySelector(selectors: "fefuncg"): SVGFEFuncGElement | null; + querySelector(selectors: "fefuncr"): SVGFEFuncRElement | null; + querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement | null; + querySelector(selectors: "feimage"): SVGFEImageElement | null; + querySelector(selectors: "femerge"): SVGFEMergeElement | null; + querySelector(selectors: "femergenode"): SVGFEMergeNodeElement | null; + querySelector(selectors: "femorphology"): SVGFEMorphologyElement | null; + querySelector(selectors: "feoffset"): SVGFEOffsetElement | null; + querySelector(selectors: "fepointlight"): SVGFEPointLightElement | null; + querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement | null; + querySelector(selectors: "fespotlight"): SVGFESpotLightElement | null; + querySelector(selectors: "fetile"): SVGFETileElement | null; + querySelector(selectors: "feturbulence"): SVGFETurbulenceElement | null; + querySelector(selectors: "fieldset"): HTMLFieldSetElement | null; + querySelector(selectors: "figcaption"): HTMLElement | null; + querySelector(selectors: "figure"): HTMLElement | null; + querySelector(selectors: "filter"): SVGFilterElement | null; + querySelector(selectors: "font"): HTMLFontElement | null; + querySelector(selectors: "footer"): HTMLElement | null; + querySelector(selectors: "foreignobject"): SVGForeignObjectElement | null; + querySelector(selectors: "form"): HTMLFormElement | null; + querySelector(selectors: "frame"): HTMLFrameElement | null; + querySelector(selectors: "frameset"): HTMLFrameSetElement | null; + querySelector(selectors: "g"): SVGGElement | null; + querySelector(selectors: "h1"): HTMLHeadingElement | null; + querySelector(selectors: "h2"): HTMLHeadingElement | null; + querySelector(selectors: "h3"): HTMLHeadingElement | null; + querySelector(selectors: "h4"): HTMLHeadingElement | null; + querySelector(selectors: "h5"): HTMLHeadingElement | null; + querySelector(selectors: "h6"): HTMLHeadingElement | null; + querySelector(selectors: "head"): HTMLHeadElement | null; + querySelector(selectors: "header"): HTMLElement | null; + querySelector(selectors: "hgroup"): HTMLElement | null; + querySelector(selectors: "hr"): HTMLHRElement | null; + querySelector(selectors: "html"): HTMLHtmlElement | null; + querySelector(selectors: "i"): HTMLElement | null; + querySelector(selectors: "iframe"): HTMLIFrameElement | null; + querySelector(selectors: "image"): SVGImageElement | null; + querySelector(selectors: "img"): HTMLImageElement | null; + querySelector(selectors: "input"): HTMLInputElement | null; + querySelector(selectors: "ins"): HTMLModElement | null; + querySelector(selectors: "isindex"): HTMLUnknownElement | null; + querySelector(selectors: "kbd"): HTMLElement | null; + querySelector(selectors: "keygen"): HTMLElement | null; + querySelector(selectors: "label"): HTMLLabelElement | null; + querySelector(selectors: "legend"): HTMLLegendElement | null; + querySelector(selectors: "li"): HTMLLIElement | null; + querySelector(selectors: "line"): SVGLineElement | null; + querySelector(selectors: "lineargradient"): SVGLinearGradientElement | null; + querySelector(selectors: "link"): HTMLLinkElement | null; + querySelector(selectors: "listing"): HTMLPreElement | null; + querySelector(selectors: "map"): HTMLMapElement | null; + querySelector(selectors: "mark"): HTMLElement | null; + querySelector(selectors: "marker"): SVGMarkerElement | null; + querySelector(selectors: "marquee"): HTMLMarqueeElement | null; + querySelector(selectors: "mask"): SVGMaskElement | null; + querySelector(selectors: "menu"): HTMLMenuElement | null; + querySelector(selectors: "meta"): HTMLMetaElement | null; + querySelector(selectors: "metadata"): SVGMetadataElement | null; + querySelector(selectors: "meter"): HTMLMeterElement | null; + querySelector(selectors: "nav"): HTMLElement | null; + querySelector(selectors: "nextid"): HTMLUnknownElement | null; + querySelector(selectors: "nobr"): HTMLElement | null; + querySelector(selectors: "noframes"): HTMLElement | null; + querySelector(selectors: "noscript"): HTMLElement | null; + querySelector(selectors: "object"): HTMLObjectElement | null; + querySelector(selectors: "ol"): HTMLOListElement | null; + querySelector(selectors: "optgroup"): HTMLOptGroupElement | null; + querySelector(selectors: "option"): HTMLOptionElement | null; + querySelector(selectors: "p"): HTMLParagraphElement | null; + querySelector(selectors: "param"): HTMLParamElement | null; + querySelector(selectors: "path"): SVGPathElement | null; + querySelector(selectors: "pattern"): SVGPatternElement | null; + querySelector(selectors: "picture"): HTMLPictureElement | null; + querySelector(selectors: "plaintext"): HTMLElement | null; + querySelector(selectors: "polygon"): SVGPolygonElement | null; + querySelector(selectors: "polyline"): SVGPolylineElement | null; + querySelector(selectors: "pre"): HTMLPreElement | null; + querySelector(selectors: "progress"): HTMLProgressElement | null; + querySelector(selectors: "q"): HTMLQuoteElement | null; + querySelector(selectors: "radialgradient"): SVGRadialGradientElement | null; + querySelector(selectors: "rect"): SVGRectElement | null; + querySelector(selectors: "rt"): HTMLElement | null; + querySelector(selectors: "ruby"): HTMLElement | null; + querySelector(selectors: "s"): HTMLElement | null; + querySelector(selectors: "samp"): HTMLElement | null; + querySelector(selectors: "script"): HTMLScriptElement | null; + querySelector(selectors: "section"): HTMLElement | null; + querySelector(selectors: "select"): HTMLSelectElement | null; + querySelector(selectors: "small"): HTMLElement | null; + querySelector(selectors: "source"): HTMLSourceElement | null; + querySelector(selectors: "span"): HTMLSpanElement | null; + querySelector(selectors: "stop"): SVGStopElement | null; + querySelector(selectors: "strike"): HTMLElement | null; + querySelector(selectors: "strong"): HTMLElement | null; + querySelector(selectors: "style"): HTMLStyleElement | null; + querySelector(selectors: "sub"): HTMLElement | null; + querySelector(selectors: "sup"): HTMLElement | null; + querySelector(selectors: "svg"): SVGSVGElement | null; + querySelector(selectors: "switch"): SVGSwitchElement | null; + querySelector(selectors: "symbol"): SVGSymbolElement | null; + querySelector(selectors: "table"): HTMLTableElement | null; + querySelector(selectors: "tbody"): HTMLTableSectionElement | null; + querySelector(selectors: "td"): HTMLTableDataCellElement | null; + querySelector(selectors: "template"): HTMLTemplateElement | null; + querySelector(selectors: "text"): SVGTextElement | null; + querySelector(selectors: "textpath"): SVGTextPathElement | null; + querySelector(selectors: "textarea"): HTMLTextAreaElement | null; + querySelector(selectors: "tfoot"): HTMLTableSectionElement | null; + querySelector(selectors: "th"): HTMLTableHeaderCellElement | null; + querySelector(selectors: "thead"): HTMLTableSectionElement | null; + querySelector(selectors: "title"): HTMLTitleElement | null; + querySelector(selectors: "tr"): HTMLTableRowElement | null; + querySelector(selectors: "track"): HTMLTrackElement | null; + querySelector(selectors: "tspan"): SVGTSpanElement | null; + querySelector(selectors: "tt"): HTMLElement | null; + querySelector(selectors: "u"): HTMLElement | null; + querySelector(selectors: "ul"): HTMLUListElement | null; + querySelector(selectors: "use"): SVGUseElement | null; + querySelector(selectors: "var"): HTMLElement | null; + querySelector(selectors: "video"): HTMLVideoElement | null; + querySelector(selectors: "view"): SVGViewElement | null; + querySelector(selectors: "wbr"): HTMLElement | null; + querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement | null; + querySelector(selectors: "xmp"): HTMLPreElement | null; + querySelector(selectors: string): Element | null; querySelectorAll(selectors: "a"): NodeListOf; querySelectorAll(selectors: "abbr"): NodeListOf; querySelectorAll(selectors: "acronym"): NodeListOf; @@ -18750,6 +18771,7 @@ type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; type IDBValidKey = number | string | Date | IDBArrayKey; type BufferSource = ArrayBuffer | ArrayBufferView; type MouseWheelEvent = WheelEvent; +type ScrollRestoration = "auto" | "manual"; ///////////////////////////// /// WorkerGlobalScope APIs ///////////////////////////// diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index 4e45a38c17e..4c19c878064 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -7552,11 +7552,12 @@ declare var HashChangeEvent: { interface History { readonly length: number; readonly state: any; - back(distance?: any): void; - forward(distance?: any): void; - go(delta?: any): void; - pushState(statedata: any, title?: string, url?: string): void; - replaceState(statedata: any, title?: string, url?: string): void; + scrollRestoration: ScrollRestoration; + back(): void; + forward(): void; + go(delta?: number): void; + pushState(data: any, title: string, url?: string | null): void; + replaceState(data: any, title: string, url?: string | null): void; } declare var History: { @@ -13128,7 +13129,6 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; - [index: number]: Window; } declare var Window: { @@ -13159,7 +13159,7 @@ declare var XMLDocument: { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - onreadystatechange: (this: this, ev: ProgressEvent) => any; + onreadystatechange: (this: this, ev: Event) => any; readonly readyState: number; readonly response: any; readonly responseText: string; @@ -13186,13 +13186,13 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -13533,183 +13533,183 @@ interface NavigatorUserMedia { } interface NodeSelector { - querySelector(selectors: "a"): HTMLAnchorElement; - querySelector(selectors: "abbr"): HTMLElement; - querySelector(selectors: "acronym"): HTMLElement; - querySelector(selectors: "address"): HTMLElement; - querySelector(selectors: "applet"): HTMLAppletElement; - querySelector(selectors: "area"): HTMLAreaElement; - querySelector(selectors: "article"): HTMLElement; - querySelector(selectors: "aside"): HTMLElement; - querySelector(selectors: "audio"): HTMLAudioElement; - querySelector(selectors: "b"): HTMLElement; - querySelector(selectors: "base"): HTMLBaseElement; - querySelector(selectors: "basefont"): HTMLBaseFontElement; - querySelector(selectors: "bdo"): HTMLElement; - querySelector(selectors: "big"): HTMLElement; - querySelector(selectors: "blockquote"): HTMLQuoteElement; - querySelector(selectors: "body"): HTMLBodyElement; - querySelector(selectors: "br"): HTMLBRElement; - querySelector(selectors: "button"): HTMLButtonElement; - querySelector(selectors: "canvas"): HTMLCanvasElement; - querySelector(selectors: "caption"): HTMLTableCaptionElement; - querySelector(selectors: "center"): HTMLElement; - querySelector(selectors: "circle"): SVGCircleElement; - querySelector(selectors: "cite"): HTMLElement; - querySelector(selectors: "clippath"): SVGClipPathElement; - querySelector(selectors: "code"): HTMLElement; - querySelector(selectors: "col"): HTMLTableColElement; - querySelector(selectors: "colgroup"): HTMLTableColElement; - querySelector(selectors: "datalist"): HTMLDataListElement; - querySelector(selectors: "dd"): HTMLElement; - querySelector(selectors: "defs"): SVGDefsElement; - querySelector(selectors: "del"): HTMLModElement; - querySelector(selectors: "desc"): SVGDescElement; - querySelector(selectors: "dfn"): HTMLElement; - querySelector(selectors: "dir"): HTMLDirectoryElement; - querySelector(selectors: "div"): HTMLDivElement; - querySelector(selectors: "dl"): HTMLDListElement; - querySelector(selectors: "dt"): HTMLElement; - querySelector(selectors: "ellipse"): SVGEllipseElement; - querySelector(selectors: "em"): HTMLElement; - querySelector(selectors: "embed"): HTMLEmbedElement; - querySelector(selectors: "feblend"): SVGFEBlendElement; - querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement; - querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement; - querySelector(selectors: "fecomposite"): SVGFECompositeElement; - querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement; - querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement; - querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement; - querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement; - querySelector(selectors: "feflood"): SVGFEFloodElement; - querySelector(selectors: "fefunca"): SVGFEFuncAElement; - querySelector(selectors: "fefuncb"): SVGFEFuncBElement; - querySelector(selectors: "fefuncg"): SVGFEFuncGElement; - querySelector(selectors: "fefuncr"): SVGFEFuncRElement; - querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement; - querySelector(selectors: "feimage"): SVGFEImageElement; - querySelector(selectors: "femerge"): SVGFEMergeElement; - querySelector(selectors: "femergenode"): SVGFEMergeNodeElement; - querySelector(selectors: "femorphology"): SVGFEMorphologyElement; - querySelector(selectors: "feoffset"): SVGFEOffsetElement; - querySelector(selectors: "fepointlight"): SVGFEPointLightElement; - querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement; - querySelector(selectors: "fespotlight"): SVGFESpotLightElement; - querySelector(selectors: "fetile"): SVGFETileElement; - querySelector(selectors: "feturbulence"): SVGFETurbulenceElement; - querySelector(selectors: "fieldset"): HTMLFieldSetElement; - querySelector(selectors: "figcaption"): HTMLElement; - querySelector(selectors: "figure"): HTMLElement; - querySelector(selectors: "filter"): SVGFilterElement; - querySelector(selectors: "font"): HTMLFontElement; - querySelector(selectors: "footer"): HTMLElement; - querySelector(selectors: "foreignobject"): SVGForeignObjectElement; - querySelector(selectors: "form"): HTMLFormElement; - querySelector(selectors: "frame"): HTMLFrameElement; - querySelector(selectors: "frameset"): HTMLFrameSetElement; - querySelector(selectors: "g"): SVGGElement; - querySelector(selectors: "h1"): HTMLHeadingElement; - querySelector(selectors: "h2"): HTMLHeadingElement; - querySelector(selectors: "h3"): HTMLHeadingElement; - querySelector(selectors: "h4"): HTMLHeadingElement; - querySelector(selectors: "h5"): HTMLHeadingElement; - querySelector(selectors: "h6"): HTMLHeadingElement; - querySelector(selectors: "head"): HTMLHeadElement; - querySelector(selectors: "header"): HTMLElement; - querySelector(selectors: "hgroup"): HTMLElement; - querySelector(selectors: "hr"): HTMLHRElement; - querySelector(selectors: "html"): HTMLHtmlElement; - querySelector(selectors: "i"): HTMLElement; - querySelector(selectors: "iframe"): HTMLIFrameElement; - querySelector(selectors: "image"): SVGImageElement; - querySelector(selectors: "img"): HTMLImageElement; - querySelector(selectors: "input"): HTMLInputElement; - querySelector(selectors: "ins"): HTMLModElement; - querySelector(selectors: "isindex"): HTMLUnknownElement; - querySelector(selectors: "kbd"): HTMLElement; - querySelector(selectors: "keygen"): HTMLElement; - querySelector(selectors: "label"): HTMLLabelElement; - querySelector(selectors: "legend"): HTMLLegendElement; - querySelector(selectors: "li"): HTMLLIElement; - querySelector(selectors: "line"): SVGLineElement; - querySelector(selectors: "lineargradient"): SVGLinearGradientElement; - querySelector(selectors: "link"): HTMLLinkElement; - querySelector(selectors: "listing"): HTMLPreElement; - querySelector(selectors: "map"): HTMLMapElement; - querySelector(selectors: "mark"): HTMLElement; - querySelector(selectors: "marker"): SVGMarkerElement; - querySelector(selectors: "marquee"): HTMLMarqueeElement; - querySelector(selectors: "mask"): SVGMaskElement; - querySelector(selectors: "menu"): HTMLMenuElement; - querySelector(selectors: "meta"): HTMLMetaElement; - querySelector(selectors: "metadata"): SVGMetadataElement; - querySelector(selectors: "meter"): HTMLMeterElement; - querySelector(selectors: "nav"): HTMLElement; - querySelector(selectors: "nextid"): HTMLUnknownElement; - querySelector(selectors: "nobr"): HTMLElement; - querySelector(selectors: "noframes"): HTMLElement; - querySelector(selectors: "noscript"): HTMLElement; - querySelector(selectors: "object"): HTMLObjectElement; - querySelector(selectors: "ol"): HTMLOListElement; - querySelector(selectors: "optgroup"): HTMLOptGroupElement; - querySelector(selectors: "option"): HTMLOptionElement; - querySelector(selectors: "p"): HTMLParagraphElement; - querySelector(selectors: "param"): HTMLParamElement; - querySelector(selectors: "path"): SVGPathElement; - querySelector(selectors: "pattern"): SVGPatternElement; - querySelector(selectors: "picture"): HTMLPictureElement; - querySelector(selectors: "plaintext"): HTMLElement; - querySelector(selectors: "polygon"): SVGPolygonElement; - querySelector(selectors: "polyline"): SVGPolylineElement; - querySelector(selectors: "pre"): HTMLPreElement; - querySelector(selectors: "progress"): HTMLProgressElement; - querySelector(selectors: "q"): HTMLQuoteElement; - querySelector(selectors: "radialgradient"): SVGRadialGradientElement; - querySelector(selectors: "rect"): SVGRectElement; - querySelector(selectors: "rt"): HTMLElement; - querySelector(selectors: "ruby"): HTMLElement; - querySelector(selectors: "s"): HTMLElement; - querySelector(selectors: "samp"): HTMLElement; - querySelector(selectors: "script"): HTMLScriptElement; - querySelector(selectors: "section"): HTMLElement; - querySelector(selectors: "select"): HTMLSelectElement; - querySelector(selectors: "small"): HTMLElement; - querySelector(selectors: "source"): HTMLSourceElement; - querySelector(selectors: "span"): HTMLSpanElement; - querySelector(selectors: "stop"): SVGStopElement; - querySelector(selectors: "strike"): HTMLElement; - querySelector(selectors: "strong"): HTMLElement; - querySelector(selectors: "style"): HTMLStyleElement; - querySelector(selectors: "sub"): HTMLElement; - querySelector(selectors: "sup"): HTMLElement; - querySelector(selectors: "svg"): SVGSVGElement; - querySelector(selectors: "switch"): SVGSwitchElement; - querySelector(selectors: "symbol"): SVGSymbolElement; - querySelector(selectors: "table"): HTMLTableElement; - querySelector(selectors: "tbody"): HTMLTableSectionElement; - querySelector(selectors: "td"): HTMLTableDataCellElement; - querySelector(selectors: "template"): HTMLTemplateElement; - querySelector(selectors: "text"): SVGTextElement; - querySelector(selectors: "textpath"): SVGTextPathElement; - querySelector(selectors: "textarea"): HTMLTextAreaElement; - querySelector(selectors: "tfoot"): HTMLTableSectionElement; - querySelector(selectors: "th"): HTMLTableHeaderCellElement; - querySelector(selectors: "thead"): HTMLTableSectionElement; - querySelector(selectors: "title"): HTMLTitleElement; - querySelector(selectors: "tr"): HTMLTableRowElement; - querySelector(selectors: "track"): HTMLTrackElement; - querySelector(selectors: "tspan"): SVGTSpanElement; - querySelector(selectors: "tt"): HTMLElement; - querySelector(selectors: "u"): HTMLElement; - querySelector(selectors: "ul"): HTMLUListElement; - querySelector(selectors: "use"): SVGUseElement; - querySelector(selectors: "var"): HTMLElement; - querySelector(selectors: "video"): HTMLVideoElement; - querySelector(selectors: "view"): SVGViewElement; - querySelector(selectors: "wbr"): HTMLElement; - querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement; - querySelector(selectors: "xmp"): HTMLPreElement; - querySelector(selectors: string): Element; + querySelector(selectors: "a"): HTMLAnchorElement | null; + querySelector(selectors: "abbr"): HTMLElement | null; + querySelector(selectors: "acronym"): HTMLElement | null; + querySelector(selectors: "address"): HTMLElement | null; + querySelector(selectors: "applet"): HTMLAppletElement | null; + querySelector(selectors: "area"): HTMLAreaElement | null; + querySelector(selectors: "article"): HTMLElement | null; + querySelector(selectors: "aside"): HTMLElement | null; + querySelector(selectors: "audio"): HTMLAudioElement | null; + querySelector(selectors: "b"): HTMLElement | null; + querySelector(selectors: "base"): HTMLBaseElement | null; + querySelector(selectors: "basefont"): HTMLBaseFontElement | null; + querySelector(selectors: "bdo"): HTMLElement | null; + querySelector(selectors: "big"): HTMLElement | null; + querySelector(selectors: "blockquote"): HTMLQuoteElement | null; + querySelector(selectors: "body"): HTMLBodyElement | null; + querySelector(selectors: "br"): HTMLBRElement | null; + querySelector(selectors: "button"): HTMLButtonElement | null; + querySelector(selectors: "canvas"): HTMLCanvasElement | null; + querySelector(selectors: "caption"): HTMLTableCaptionElement | null; + querySelector(selectors: "center"): HTMLElement | null; + querySelector(selectors: "circle"): SVGCircleElement | null; + querySelector(selectors: "cite"): HTMLElement | null; + querySelector(selectors: "clippath"): SVGClipPathElement | null; + querySelector(selectors: "code"): HTMLElement | null; + querySelector(selectors: "col"): HTMLTableColElement | null; + querySelector(selectors: "colgroup"): HTMLTableColElement | null; + querySelector(selectors: "datalist"): HTMLDataListElement | null; + querySelector(selectors: "dd"): HTMLElement | null; + querySelector(selectors: "defs"): SVGDefsElement | null; + querySelector(selectors: "del"): HTMLModElement | null; + querySelector(selectors: "desc"): SVGDescElement | null; + querySelector(selectors: "dfn"): HTMLElement | null; + querySelector(selectors: "dir"): HTMLDirectoryElement | null; + querySelector(selectors: "div"): HTMLDivElement | null; + querySelector(selectors: "dl"): HTMLDListElement | null; + querySelector(selectors: "dt"): HTMLElement | null; + querySelector(selectors: "ellipse"): SVGEllipseElement | null; + querySelector(selectors: "em"): HTMLElement | null; + querySelector(selectors: "embed"): HTMLEmbedElement | null; + querySelector(selectors: "feblend"): SVGFEBlendElement | null; + querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement | null; + querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement | null; + querySelector(selectors: "fecomposite"): SVGFECompositeElement | null; + querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement | null; + querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement | null; + querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement | null; + querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement | null; + querySelector(selectors: "feflood"): SVGFEFloodElement | null; + querySelector(selectors: "fefunca"): SVGFEFuncAElement | null; + querySelector(selectors: "fefuncb"): SVGFEFuncBElement | null; + querySelector(selectors: "fefuncg"): SVGFEFuncGElement | null; + querySelector(selectors: "fefuncr"): SVGFEFuncRElement | null; + querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement | null; + querySelector(selectors: "feimage"): SVGFEImageElement | null; + querySelector(selectors: "femerge"): SVGFEMergeElement | null; + querySelector(selectors: "femergenode"): SVGFEMergeNodeElement | null; + querySelector(selectors: "femorphology"): SVGFEMorphologyElement | null; + querySelector(selectors: "feoffset"): SVGFEOffsetElement | null; + querySelector(selectors: "fepointlight"): SVGFEPointLightElement | null; + querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement | null; + querySelector(selectors: "fespotlight"): SVGFESpotLightElement | null; + querySelector(selectors: "fetile"): SVGFETileElement | null; + querySelector(selectors: "feturbulence"): SVGFETurbulenceElement | null; + querySelector(selectors: "fieldset"): HTMLFieldSetElement | null; + querySelector(selectors: "figcaption"): HTMLElement | null; + querySelector(selectors: "figure"): HTMLElement | null; + querySelector(selectors: "filter"): SVGFilterElement | null; + querySelector(selectors: "font"): HTMLFontElement | null; + querySelector(selectors: "footer"): HTMLElement | null; + querySelector(selectors: "foreignobject"): SVGForeignObjectElement | null; + querySelector(selectors: "form"): HTMLFormElement | null; + querySelector(selectors: "frame"): HTMLFrameElement | null; + querySelector(selectors: "frameset"): HTMLFrameSetElement | null; + querySelector(selectors: "g"): SVGGElement | null; + querySelector(selectors: "h1"): HTMLHeadingElement | null; + querySelector(selectors: "h2"): HTMLHeadingElement | null; + querySelector(selectors: "h3"): HTMLHeadingElement | null; + querySelector(selectors: "h4"): HTMLHeadingElement | null; + querySelector(selectors: "h5"): HTMLHeadingElement | null; + querySelector(selectors: "h6"): HTMLHeadingElement | null; + querySelector(selectors: "head"): HTMLHeadElement | null; + querySelector(selectors: "header"): HTMLElement | null; + querySelector(selectors: "hgroup"): HTMLElement | null; + querySelector(selectors: "hr"): HTMLHRElement | null; + querySelector(selectors: "html"): HTMLHtmlElement | null; + querySelector(selectors: "i"): HTMLElement | null; + querySelector(selectors: "iframe"): HTMLIFrameElement | null; + querySelector(selectors: "image"): SVGImageElement | null; + querySelector(selectors: "img"): HTMLImageElement | null; + querySelector(selectors: "input"): HTMLInputElement | null; + querySelector(selectors: "ins"): HTMLModElement | null; + querySelector(selectors: "isindex"): HTMLUnknownElement | null; + querySelector(selectors: "kbd"): HTMLElement | null; + querySelector(selectors: "keygen"): HTMLElement | null; + querySelector(selectors: "label"): HTMLLabelElement | null; + querySelector(selectors: "legend"): HTMLLegendElement | null; + querySelector(selectors: "li"): HTMLLIElement | null; + querySelector(selectors: "line"): SVGLineElement | null; + querySelector(selectors: "lineargradient"): SVGLinearGradientElement | null; + querySelector(selectors: "link"): HTMLLinkElement | null; + querySelector(selectors: "listing"): HTMLPreElement | null; + querySelector(selectors: "map"): HTMLMapElement | null; + querySelector(selectors: "mark"): HTMLElement | null; + querySelector(selectors: "marker"): SVGMarkerElement | null; + querySelector(selectors: "marquee"): HTMLMarqueeElement | null; + querySelector(selectors: "mask"): SVGMaskElement | null; + querySelector(selectors: "menu"): HTMLMenuElement | null; + querySelector(selectors: "meta"): HTMLMetaElement | null; + querySelector(selectors: "metadata"): SVGMetadataElement | null; + querySelector(selectors: "meter"): HTMLMeterElement | null; + querySelector(selectors: "nav"): HTMLElement | null; + querySelector(selectors: "nextid"): HTMLUnknownElement | null; + querySelector(selectors: "nobr"): HTMLElement | null; + querySelector(selectors: "noframes"): HTMLElement | null; + querySelector(selectors: "noscript"): HTMLElement | null; + querySelector(selectors: "object"): HTMLObjectElement | null; + querySelector(selectors: "ol"): HTMLOListElement | null; + querySelector(selectors: "optgroup"): HTMLOptGroupElement | null; + querySelector(selectors: "option"): HTMLOptionElement | null; + querySelector(selectors: "p"): HTMLParagraphElement | null; + querySelector(selectors: "param"): HTMLParamElement | null; + querySelector(selectors: "path"): SVGPathElement | null; + querySelector(selectors: "pattern"): SVGPatternElement | null; + querySelector(selectors: "picture"): HTMLPictureElement | null; + querySelector(selectors: "plaintext"): HTMLElement | null; + querySelector(selectors: "polygon"): SVGPolygonElement | null; + querySelector(selectors: "polyline"): SVGPolylineElement | null; + querySelector(selectors: "pre"): HTMLPreElement | null; + querySelector(selectors: "progress"): HTMLProgressElement | null; + querySelector(selectors: "q"): HTMLQuoteElement | null; + querySelector(selectors: "radialgradient"): SVGRadialGradientElement | null; + querySelector(selectors: "rect"): SVGRectElement | null; + querySelector(selectors: "rt"): HTMLElement | null; + querySelector(selectors: "ruby"): HTMLElement | null; + querySelector(selectors: "s"): HTMLElement | null; + querySelector(selectors: "samp"): HTMLElement | null; + querySelector(selectors: "script"): HTMLScriptElement | null; + querySelector(selectors: "section"): HTMLElement | null; + querySelector(selectors: "select"): HTMLSelectElement | null; + querySelector(selectors: "small"): HTMLElement | null; + querySelector(selectors: "source"): HTMLSourceElement | null; + querySelector(selectors: "span"): HTMLSpanElement | null; + querySelector(selectors: "stop"): SVGStopElement | null; + querySelector(selectors: "strike"): HTMLElement | null; + querySelector(selectors: "strong"): HTMLElement | null; + querySelector(selectors: "style"): HTMLStyleElement | null; + querySelector(selectors: "sub"): HTMLElement | null; + querySelector(selectors: "sup"): HTMLElement | null; + querySelector(selectors: "svg"): SVGSVGElement | null; + querySelector(selectors: "switch"): SVGSwitchElement | null; + querySelector(selectors: "symbol"): SVGSymbolElement | null; + querySelector(selectors: "table"): HTMLTableElement | null; + querySelector(selectors: "tbody"): HTMLTableSectionElement | null; + querySelector(selectors: "td"): HTMLTableDataCellElement | null; + querySelector(selectors: "template"): HTMLTemplateElement | null; + querySelector(selectors: "text"): SVGTextElement | null; + querySelector(selectors: "textpath"): SVGTextPathElement | null; + querySelector(selectors: "textarea"): HTMLTextAreaElement | null; + querySelector(selectors: "tfoot"): HTMLTableSectionElement | null; + querySelector(selectors: "th"): HTMLTableHeaderCellElement | null; + querySelector(selectors: "thead"): HTMLTableSectionElement | null; + querySelector(selectors: "title"): HTMLTitleElement | null; + querySelector(selectors: "tr"): HTMLTableRowElement | null; + querySelector(selectors: "track"): HTMLTrackElement | null; + querySelector(selectors: "tspan"): SVGTSpanElement | null; + querySelector(selectors: "tt"): HTMLElement | null; + querySelector(selectors: "u"): HTMLElement | null; + querySelector(selectors: "ul"): HTMLUListElement | null; + querySelector(selectors: "use"): SVGUseElement | null; + querySelector(selectors: "var"): HTMLElement | null; + querySelector(selectors: "video"): HTMLVideoElement | null; + querySelector(selectors: "view"): SVGViewElement | null; + querySelector(selectors: "wbr"): HTMLElement | null; + querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement | null; + querySelector(selectors: "xmp"): HTMLPreElement | null; + querySelector(selectors: string): Element | null; querySelectorAll(selectors: "a"): NodeListOf; querySelectorAll(selectors: "abbr"): NodeListOf; querySelectorAll(selectors: "acronym"): NodeListOf; @@ -14638,4 +14638,5 @@ type ScrollBehavior = "auto" | "instant" | "smooth"; type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; type IDBValidKey = number | string | Date | IDBArrayKey; type BufferSource = ArrayBuffer | ArrayBufferView; -type MouseWheelEvent = WheelEvent; \ No newline at end of file +type MouseWheelEvent = WheelEvent; +type ScrollRestoration = "auto" | "manual"; \ No newline at end of file diff --git a/lib/lib.es2015.core.d.ts b/lib/lib.es2015.core.d.ts index 49a81a220ce..669c80944ec 100644 --- a/lib/lib.es2015.core.d.ts +++ b/lib/lib.es2015.core.d.ts @@ -217,7 +217,7 @@ interface NumberConstructor { /** * Returns true if passed value is finite. - * Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a + * Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a * number. Only finite values of the type number, result in true. * @param number A numeric value. */ diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 5df0d7d4068..d20c7d1e3a7 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -1216,6 +1216,30 @@ interface Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U]; /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index f6c7766ea9f..6067d810b44 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -1216,6 +1216,30 @@ interface Array { * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. */ forEach(callbackfn: (value: T, index: number, array: T[]) => void, thisArg?: any): void; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U, U]; + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map(this: [T, T], callbackfn: (value: T, index: number, array: T[]) => U, thisArg?: any): [U, U]; /** * Calls a defined callback function on each element of an array, and returns an array that contains the results. * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. @@ -4325,7 +4349,7 @@ interface NumberConstructor { /** * Returns true if passed value is finite. - * Unlike the global isFininte, Number.isFinite doesn't forcibly convert the parameter to a + * Unlike the global isFinite, Number.isFinite doesn't forcibly convert the parameter to a * number. Only finite values of the type number, result in true. * @param number A numeric value. */ @@ -13361,11 +13385,12 @@ declare var HashChangeEvent: { interface History { readonly length: number; readonly state: any; - back(distance?: any): void; - forward(distance?: any): void; - go(delta?: any): void; - pushState(statedata: any, title?: string, url?: string): void; - replaceState(statedata: any, title?: string, url?: string): void; + scrollRestoration: ScrollRestoration; + back(): void; + forward(): void; + go(delta?: number): void; + pushState(data: any, title: string, url?: string | null): void; + replaceState(data: any, title: string, url?: string | null): void; } declare var History: { @@ -18937,7 +18962,6 @@ interface Window extends EventTarget, WindowTimers, WindowSessionStorage, Window addEventListener(type: "waiting", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "wheel", listener: (this: this, ev: WheelEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; - [index: number]: Window; } declare var Window: { @@ -18968,7 +18992,7 @@ declare var XMLDocument: { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - onreadystatechange: (this: this, ev: ProgressEvent) => any; + onreadystatechange: (this: this, ev: Event) => any; readonly readyState: number; readonly response: any; readonly responseText: string; @@ -18995,13 +19019,13 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } @@ -19342,183 +19366,183 @@ interface NavigatorUserMedia { } interface NodeSelector { - querySelector(selectors: "a"): HTMLAnchorElement; - querySelector(selectors: "abbr"): HTMLElement; - querySelector(selectors: "acronym"): HTMLElement; - querySelector(selectors: "address"): HTMLElement; - querySelector(selectors: "applet"): HTMLAppletElement; - querySelector(selectors: "area"): HTMLAreaElement; - querySelector(selectors: "article"): HTMLElement; - querySelector(selectors: "aside"): HTMLElement; - querySelector(selectors: "audio"): HTMLAudioElement; - querySelector(selectors: "b"): HTMLElement; - querySelector(selectors: "base"): HTMLBaseElement; - querySelector(selectors: "basefont"): HTMLBaseFontElement; - querySelector(selectors: "bdo"): HTMLElement; - querySelector(selectors: "big"): HTMLElement; - querySelector(selectors: "blockquote"): HTMLQuoteElement; - querySelector(selectors: "body"): HTMLBodyElement; - querySelector(selectors: "br"): HTMLBRElement; - querySelector(selectors: "button"): HTMLButtonElement; - querySelector(selectors: "canvas"): HTMLCanvasElement; - querySelector(selectors: "caption"): HTMLTableCaptionElement; - querySelector(selectors: "center"): HTMLElement; - querySelector(selectors: "circle"): SVGCircleElement; - querySelector(selectors: "cite"): HTMLElement; - querySelector(selectors: "clippath"): SVGClipPathElement; - querySelector(selectors: "code"): HTMLElement; - querySelector(selectors: "col"): HTMLTableColElement; - querySelector(selectors: "colgroup"): HTMLTableColElement; - querySelector(selectors: "datalist"): HTMLDataListElement; - querySelector(selectors: "dd"): HTMLElement; - querySelector(selectors: "defs"): SVGDefsElement; - querySelector(selectors: "del"): HTMLModElement; - querySelector(selectors: "desc"): SVGDescElement; - querySelector(selectors: "dfn"): HTMLElement; - querySelector(selectors: "dir"): HTMLDirectoryElement; - querySelector(selectors: "div"): HTMLDivElement; - querySelector(selectors: "dl"): HTMLDListElement; - querySelector(selectors: "dt"): HTMLElement; - querySelector(selectors: "ellipse"): SVGEllipseElement; - querySelector(selectors: "em"): HTMLElement; - querySelector(selectors: "embed"): HTMLEmbedElement; - querySelector(selectors: "feblend"): SVGFEBlendElement; - querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement; - querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement; - querySelector(selectors: "fecomposite"): SVGFECompositeElement; - querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement; - querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement; - querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement; - querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement; - querySelector(selectors: "feflood"): SVGFEFloodElement; - querySelector(selectors: "fefunca"): SVGFEFuncAElement; - querySelector(selectors: "fefuncb"): SVGFEFuncBElement; - querySelector(selectors: "fefuncg"): SVGFEFuncGElement; - querySelector(selectors: "fefuncr"): SVGFEFuncRElement; - querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement; - querySelector(selectors: "feimage"): SVGFEImageElement; - querySelector(selectors: "femerge"): SVGFEMergeElement; - querySelector(selectors: "femergenode"): SVGFEMergeNodeElement; - querySelector(selectors: "femorphology"): SVGFEMorphologyElement; - querySelector(selectors: "feoffset"): SVGFEOffsetElement; - querySelector(selectors: "fepointlight"): SVGFEPointLightElement; - querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement; - querySelector(selectors: "fespotlight"): SVGFESpotLightElement; - querySelector(selectors: "fetile"): SVGFETileElement; - querySelector(selectors: "feturbulence"): SVGFETurbulenceElement; - querySelector(selectors: "fieldset"): HTMLFieldSetElement; - querySelector(selectors: "figcaption"): HTMLElement; - querySelector(selectors: "figure"): HTMLElement; - querySelector(selectors: "filter"): SVGFilterElement; - querySelector(selectors: "font"): HTMLFontElement; - querySelector(selectors: "footer"): HTMLElement; - querySelector(selectors: "foreignobject"): SVGForeignObjectElement; - querySelector(selectors: "form"): HTMLFormElement; - querySelector(selectors: "frame"): HTMLFrameElement; - querySelector(selectors: "frameset"): HTMLFrameSetElement; - querySelector(selectors: "g"): SVGGElement; - querySelector(selectors: "h1"): HTMLHeadingElement; - querySelector(selectors: "h2"): HTMLHeadingElement; - querySelector(selectors: "h3"): HTMLHeadingElement; - querySelector(selectors: "h4"): HTMLHeadingElement; - querySelector(selectors: "h5"): HTMLHeadingElement; - querySelector(selectors: "h6"): HTMLHeadingElement; - querySelector(selectors: "head"): HTMLHeadElement; - querySelector(selectors: "header"): HTMLElement; - querySelector(selectors: "hgroup"): HTMLElement; - querySelector(selectors: "hr"): HTMLHRElement; - querySelector(selectors: "html"): HTMLHtmlElement; - querySelector(selectors: "i"): HTMLElement; - querySelector(selectors: "iframe"): HTMLIFrameElement; - querySelector(selectors: "image"): SVGImageElement; - querySelector(selectors: "img"): HTMLImageElement; - querySelector(selectors: "input"): HTMLInputElement; - querySelector(selectors: "ins"): HTMLModElement; - querySelector(selectors: "isindex"): HTMLUnknownElement; - querySelector(selectors: "kbd"): HTMLElement; - querySelector(selectors: "keygen"): HTMLElement; - querySelector(selectors: "label"): HTMLLabelElement; - querySelector(selectors: "legend"): HTMLLegendElement; - querySelector(selectors: "li"): HTMLLIElement; - querySelector(selectors: "line"): SVGLineElement; - querySelector(selectors: "lineargradient"): SVGLinearGradientElement; - querySelector(selectors: "link"): HTMLLinkElement; - querySelector(selectors: "listing"): HTMLPreElement; - querySelector(selectors: "map"): HTMLMapElement; - querySelector(selectors: "mark"): HTMLElement; - querySelector(selectors: "marker"): SVGMarkerElement; - querySelector(selectors: "marquee"): HTMLMarqueeElement; - querySelector(selectors: "mask"): SVGMaskElement; - querySelector(selectors: "menu"): HTMLMenuElement; - querySelector(selectors: "meta"): HTMLMetaElement; - querySelector(selectors: "metadata"): SVGMetadataElement; - querySelector(selectors: "meter"): HTMLMeterElement; - querySelector(selectors: "nav"): HTMLElement; - querySelector(selectors: "nextid"): HTMLUnknownElement; - querySelector(selectors: "nobr"): HTMLElement; - querySelector(selectors: "noframes"): HTMLElement; - querySelector(selectors: "noscript"): HTMLElement; - querySelector(selectors: "object"): HTMLObjectElement; - querySelector(selectors: "ol"): HTMLOListElement; - querySelector(selectors: "optgroup"): HTMLOptGroupElement; - querySelector(selectors: "option"): HTMLOptionElement; - querySelector(selectors: "p"): HTMLParagraphElement; - querySelector(selectors: "param"): HTMLParamElement; - querySelector(selectors: "path"): SVGPathElement; - querySelector(selectors: "pattern"): SVGPatternElement; - querySelector(selectors: "picture"): HTMLPictureElement; - querySelector(selectors: "plaintext"): HTMLElement; - querySelector(selectors: "polygon"): SVGPolygonElement; - querySelector(selectors: "polyline"): SVGPolylineElement; - querySelector(selectors: "pre"): HTMLPreElement; - querySelector(selectors: "progress"): HTMLProgressElement; - querySelector(selectors: "q"): HTMLQuoteElement; - querySelector(selectors: "radialgradient"): SVGRadialGradientElement; - querySelector(selectors: "rect"): SVGRectElement; - querySelector(selectors: "rt"): HTMLElement; - querySelector(selectors: "ruby"): HTMLElement; - querySelector(selectors: "s"): HTMLElement; - querySelector(selectors: "samp"): HTMLElement; - querySelector(selectors: "script"): HTMLScriptElement; - querySelector(selectors: "section"): HTMLElement; - querySelector(selectors: "select"): HTMLSelectElement; - querySelector(selectors: "small"): HTMLElement; - querySelector(selectors: "source"): HTMLSourceElement; - querySelector(selectors: "span"): HTMLSpanElement; - querySelector(selectors: "stop"): SVGStopElement; - querySelector(selectors: "strike"): HTMLElement; - querySelector(selectors: "strong"): HTMLElement; - querySelector(selectors: "style"): HTMLStyleElement; - querySelector(selectors: "sub"): HTMLElement; - querySelector(selectors: "sup"): HTMLElement; - querySelector(selectors: "svg"): SVGSVGElement; - querySelector(selectors: "switch"): SVGSwitchElement; - querySelector(selectors: "symbol"): SVGSymbolElement; - querySelector(selectors: "table"): HTMLTableElement; - querySelector(selectors: "tbody"): HTMLTableSectionElement; - querySelector(selectors: "td"): HTMLTableDataCellElement; - querySelector(selectors: "template"): HTMLTemplateElement; - querySelector(selectors: "text"): SVGTextElement; - querySelector(selectors: "textpath"): SVGTextPathElement; - querySelector(selectors: "textarea"): HTMLTextAreaElement; - querySelector(selectors: "tfoot"): HTMLTableSectionElement; - querySelector(selectors: "th"): HTMLTableHeaderCellElement; - querySelector(selectors: "thead"): HTMLTableSectionElement; - querySelector(selectors: "title"): HTMLTitleElement; - querySelector(selectors: "tr"): HTMLTableRowElement; - querySelector(selectors: "track"): HTMLTrackElement; - querySelector(selectors: "tspan"): SVGTSpanElement; - querySelector(selectors: "tt"): HTMLElement; - querySelector(selectors: "u"): HTMLElement; - querySelector(selectors: "ul"): HTMLUListElement; - querySelector(selectors: "use"): SVGUseElement; - querySelector(selectors: "var"): HTMLElement; - querySelector(selectors: "video"): HTMLVideoElement; - querySelector(selectors: "view"): SVGViewElement; - querySelector(selectors: "wbr"): HTMLElement; - querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement; - querySelector(selectors: "xmp"): HTMLPreElement; - querySelector(selectors: string): Element; + querySelector(selectors: "a"): HTMLAnchorElement | null; + querySelector(selectors: "abbr"): HTMLElement | null; + querySelector(selectors: "acronym"): HTMLElement | null; + querySelector(selectors: "address"): HTMLElement | null; + querySelector(selectors: "applet"): HTMLAppletElement | null; + querySelector(selectors: "area"): HTMLAreaElement | null; + querySelector(selectors: "article"): HTMLElement | null; + querySelector(selectors: "aside"): HTMLElement | null; + querySelector(selectors: "audio"): HTMLAudioElement | null; + querySelector(selectors: "b"): HTMLElement | null; + querySelector(selectors: "base"): HTMLBaseElement | null; + querySelector(selectors: "basefont"): HTMLBaseFontElement | null; + querySelector(selectors: "bdo"): HTMLElement | null; + querySelector(selectors: "big"): HTMLElement | null; + querySelector(selectors: "blockquote"): HTMLQuoteElement | null; + querySelector(selectors: "body"): HTMLBodyElement | null; + querySelector(selectors: "br"): HTMLBRElement | null; + querySelector(selectors: "button"): HTMLButtonElement | null; + querySelector(selectors: "canvas"): HTMLCanvasElement | null; + querySelector(selectors: "caption"): HTMLTableCaptionElement | null; + querySelector(selectors: "center"): HTMLElement | null; + querySelector(selectors: "circle"): SVGCircleElement | null; + querySelector(selectors: "cite"): HTMLElement | null; + querySelector(selectors: "clippath"): SVGClipPathElement | null; + querySelector(selectors: "code"): HTMLElement | null; + querySelector(selectors: "col"): HTMLTableColElement | null; + querySelector(selectors: "colgroup"): HTMLTableColElement | null; + querySelector(selectors: "datalist"): HTMLDataListElement | null; + querySelector(selectors: "dd"): HTMLElement | null; + querySelector(selectors: "defs"): SVGDefsElement | null; + querySelector(selectors: "del"): HTMLModElement | null; + querySelector(selectors: "desc"): SVGDescElement | null; + querySelector(selectors: "dfn"): HTMLElement | null; + querySelector(selectors: "dir"): HTMLDirectoryElement | null; + querySelector(selectors: "div"): HTMLDivElement | null; + querySelector(selectors: "dl"): HTMLDListElement | null; + querySelector(selectors: "dt"): HTMLElement | null; + querySelector(selectors: "ellipse"): SVGEllipseElement | null; + querySelector(selectors: "em"): HTMLElement | null; + querySelector(selectors: "embed"): HTMLEmbedElement | null; + querySelector(selectors: "feblend"): SVGFEBlendElement | null; + querySelector(selectors: "fecolormatrix"): SVGFEColorMatrixElement | null; + querySelector(selectors: "fecomponenttransfer"): SVGFEComponentTransferElement | null; + querySelector(selectors: "fecomposite"): SVGFECompositeElement | null; + querySelector(selectors: "feconvolvematrix"): SVGFEConvolveMatrixElement | null; + querySelector(selectors: "fediffuselighting"): SVGFEDiffuseLightingElement | null; + querySelector(selectors: "fedisplacementmap"): SVGFEDisplacementMapElement | null; + querySelector(selectors: "fedistantlight"): SVGFEDistantLightElement | null; + querySelector(selectors: "feflood"): SVGFEFloodElement | null; + querySelector(selectors: "fefunca"): SVGFEFuncAElement | null; + querySelector(selectors: "fefuncb"): SVGFEFuncBElement | null; + querySelector(selectors: "fefuncg"): SVGFEFuncGElement | null; + querySelector(selectors: "fefuncr"): SVGFEFuncRElement | null; + querySelector(selectors: "fegaussianblur"): SVGFEGaussianBlurElement | null; + querySelector(selectors: "feimage"): SVGFEImageElement | null; + querySelector(selectors: "femerge"): SVGFEMergeElement | null; + querySelector(selectors: "femergenode"): SVGFEMergeNodeElement | null; + querySelector(selectors: "femorphology"): SVGFEMorphologyElement | null; + querySelector(selectors: "feoffset"): SVGFEOffsetElement | null; + querySelector(selectors: "fepointlight"): SVGFEPointLightElement | null; + querySelector(selectors: "fespecularlighting"): SVGFESpecularLightingElement | null; + querySelector(selectors: "fespotlight"): SVGFESpotLightElement | null; + querySelector(selectors: "fetile"): SVGFETileElement | null; + querySelector(selectors: "feturbulence"): SVGFETurbulenceElement | null; + querySelector(selectors: "fieldset"): HTMLFieldSetElement | null; + querySelector(selectors: "figcaption"): HTMLElement | null; + querySelector(selectors: "figure"): HTMLElement | null; + querySelector(selectors: "filter"): SVGFilterElement | null; + querySelector(selectors: "font"): HTMLFontElement | null; + querySelector(selectors: "footer"): HTMLElement | null; + querySelector(selectors: "foreignobject"): SVGForeignObjectElement | null; + querySelector(selectors: "form"): HTMLFormElement | null; + querySelector(selectors: "frame"): HTMLFrameElement | null; + querySelector(selectors: "frameset"): HTMLFrameSetElement | null; + querySelector(selectors: "g"): SVGGElement | null; + querySelector(selectors: "h1"): HTMLHeadingElement | null; + querySelector(selectors: "h2"): HTMLHeadingElement | null; + querySelector(selectors: "h3"): HTMLHeadingElement | null; + querySelector(selectors: "h4"): HTMLHeadingElement | null; + querySelector(selectors: "h5"): HTMLHeadingElement | null; + querySelector(selectors: "h6"): HTMLHeadingElement | null; + querySelector(selectors: "head"): HTMLHeadElement | null; + querySelector(selectors: "header"): HTMLElement | null; + querySelector(selectors: "hgroup"): HTMLElement | null; + querySelector(selectors: "hr"): HTMLHRElement | null; + querySelector(selectors: "html"): HTMLHtmlElement | null; + querySelector(selectors: "i"): HTMLElement | null; + querySelector(selectors: "iframe"): HTMLIFrameElement | null; + querySelector(selectors: "image"): SVGImageElement | null; + querySelector(selectors: "img"): HTMLImageElement | null; + querySelector(selectors: "input"): HTMLInputElement | null; + querySelector(selectors: "ins"): HTMLModElement | null; + querySelector(selectors: "isindex"): HTMLUnknownElement | null; + querySelector(selectors: "kbd"): HTMLElement | null; + querySelector(selectors: "keygen"): HTMLElement | null; + querySelector(selectors: "label"): HTMLLabelElement | null; + querySelector(selectors: "legend"): HTMLLegendElement | null; + querySelector(selectors: "li"): HTMLLIElement | null; + querySelector(selectors: "line"): SVGLineElement | null; + querySelector(selectors: "lineargradient"): SVGLinearGradientElement | null; + querySelector(selectors: "link"): HTMLLinkElement | null; + querySelector(selectors: "listing"): HTMLPreElement | null; + querySelector(selectors: "map"): HTMLMapElement | null; + querySelector(selectors: "mark"): HTMLElement | null; + querySelector(selectors: "marker"): SVGMarkerElement | null; + querySelector(selectors: "marquee"): HTMLMarqueeElement | null; + querySelector(selectors: "mask"): SVGMaskElement | null; + querySelector(selectors: "menu"): HTMLMenuElement | null; + querySelector(selectors: "meta"): HTMLMetaElement | null; + querySelector(selectors: "metadata"): SVGMetadataElement | null; + querySelector(selectors: "meter"): HTMLMeterElement | null; + querySelector(selectors: "nav"): HTMLElement | null; + querySelector(selectors: "nextid"): HTMLUnknownElement | null; + querySelector(selectors: "nobr"): HTMLElement | null; + querySelector(selectors: "noframes"): HTMLElement | null; + querySelector(selectors: "noscript"): HTMLElement | null; + querySelector(selectors: "object"): HTMLObjectElement | null; + querySelector(selectors: "ol"): HTMLOListElement | null; + querySelector(selectors: "optgroup"): HTMLOptGroupElement | null; + querySelector(selectors: "option"): HTMLOptionElement | null; + querySelector(selectors: "p"): HTMLParagraphElement | null; + querySelector(selectors: "param"): HTMLParamElement | null; + querySelector(selectors: "path"): SVGPathElement | null; + querySelector(selectors: "pattern"): SVGPatternElement | null; + querySelector(selectors: "picture"): HTMLPictureElement | null; + querySelector(selectors: "plaintext"): HTMLElement | null; + querySelector(selectors: "polygon"): SVGPolygonElement | null; + querySelector(selectors: "polyline"): SVGPolylineElement | null; + querySelector(selectors: "pre"): HTMLPreElement | null; + querySelector(selectors: "progress"): HTMLProgressElement | null; + querySelector(selectors: "q"): HTMLQuoteElement | null; + querySelector(selectors: "radialgradient"): SVGRadialGradientElement | null; + querySelector(selectors: "rect"): SVGRectElement | null; + querySelector(selectors: "rt"): HTMLElement | null; + querySelector(selectors: "ruby"): HTMLElement | null; + querySelector(selectors: "s"): HTMLElement | null; + querySelector(selectors: "samp"): HTMLElement | null; + querySelector(selectors: "script"): HTMLScriptElement | null; + querySelector(selectors: "section"): HTMLElement | null; + querySelector(selectors: "select"): HTMLSelectElement | null; + querySelector(selectors: "small"): HTMLElement | null; + querySelector(selectors: "source"): HTMLSourceElement | null; + querySelector(selectors: "span"): HTMLSpanElement | null; + querySelector(selectors: "stop"): SVGStopElement | null; + querySelector(selectors: "strike"): HTMLElement | null; + querySelector(selectors: "strong"): HTMLElement | null; + querySelector(selectors: "style"): HTMLStyleElement | null; + querySelector(selectors: "sub"): HTMLElement | null; + querySelector(selectors: "sup"): HTMLElement | null; + querySelector(selectors: "svg"): SVGSVGElement | null; + querySelector(selectors: "switch"): SVGSwitchElement | null; + querySelector(selectors: "symbol"): SVGSymbolElement | null; + querySelector(selectors: "table"): HTMLTableElement | null; + querySelector(selectors: "tbody"): HTMLTableSectionElement | null; + querySelector(selectors: "td"): HTMLTableDataCellElement | null; + querySelector(selectors: "template"): HTMLTemplateElement | null; + querySelector(selectors: "text"): SVGTextElement | null; + querySelector(selectors: "textpath"): SVGTextPathElement | null; + querySelector(selectors: "textarea"): HTMLTextAreaElement | null; + querySelector(selectors: "tfoot"): HTMLTableSectionElement | null; + querySelector(selectors: "th"): HTMLTableHeaderCellElement | null; + querySelector(selectors: "thead"): HTMLTableSectionElement | null; + querySelector(selectors: "title"): HTMLTitleElement | null; + querySelector(selectors: "tr"): HTMLTableRowElement | null; + querySelector(selectors: "track"): HTMLTrackElement | null; + querySelector(selectors: "tspan"): SVGTSpanElement | null; + querySelector(selectors: "tt"): HTMLElement | null; + querySelector(selectors: "u"): HTMLElement | null; + querySelector(selectors: "ul"): HTMLUListElement | null; + querySelector(selectors: "use"): SVGUseElement | null; + querySelector(selectors: "var"): HTMLElement | null; + querySelector(selectors: "video"): HTMLVideoElement | null; + querySelector(selectors: "view"): SVGViewElement | null; + querySelector(selectors: "wbr"): HTMLElement | null; + querySelector(selectors: "x-ms-webview"): MSHTMLWebViewElement | null; + querySelector(selectors: "xmp"): HTMLPreElement | null; + querySelector(selectors: string): Element | null; querySelectorAll(selectors: "a"): NodeListOf; querySelectorAll(selectors: "abbr"): NodeListOf; querySelectorAll(selectors: "acronym"): NodeListOf; @@ -20448,6 +20472,7 @@ type ScrollLogicalPosition = "start" | "center" | "end" | "nearest"; type IDBValidKey = number | string | Date | IDBArrayKey; type BufferSource = ArrayBuffer | ArrayBufferView; type MouseWheelEvent = WheelEvent; +type ScrollRestoration = "auto" | "manual"; ///////////////////////////// /// WorkerGlobalScope APIs ///////////////////////////// diff --git a/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index 5b35d820dfe..6cb14c5b184 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -744,7 +744,7 @@ declare var Worker: { } interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { - onreadystatechange: (this: this, ev: ProgressEvent) => any; + onreadystatechange: (this: this, ev: Event) => any; readonly readyState: number; readonly response: any; readonly responseText: string; @@ -770,13 +770,13 @@ interface XMLHttpRequest extends EventTarget, XMLHttpRequestEventTarget { readonly LOADING: number; readonly OPENED: number; readonly UNSENT: number; - addEventListener(type: "abort", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; - addEventListener(type: "error", listener: (this: this, ev: ErrorEvent) => any, useCapture?: boolean): void; - addEventListener(type: "load", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "abort", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "error", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "load", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "loadend", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "loadstart", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; + addEventListener(type: "loadstart", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: "progress", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; - addEventListener(type: "readystatechange", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; + addEventListener(type: "readystatechange", listener: (this: this, ev: Event) => any, useCapture?: boolean): void; addEventListener(type: "timeout", listener: (this: this, ev: ProgressEvent) => any, useCapture?: boolean): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, useCapture?: boolean): void; } diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts new file mode 100644 index 00000000000..2b57b5de644 --- /dev/null +++ b/lib/protocol.d.ts @@ -0,0 +1,1848 @@ +/** + * Declaration module describing the TypeScript Server protocol + */ +declare namespace ts.server.protocol { + namespace CommandTypes { + type Brace = "brace"; + type BraceCompletion = "braceCompletion"; + type Change = "change"; + type Close = "close"; + type Completions = "completions"; + type CompletionDetails = "completionEntryDetails"; + type CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; + type CompileOnSaveEmitFile = "compileOnSaveEmitFile"; + type Configure = "configure"; + type Definition = "definition"; + type Implementation = "implementation"; + type Exit = "exit"; + type Format = "format"; + type Formatonkey = "formatonkey"; + type Geterr = "geterr"; + type GeterrForProject = "geterrForProject"; + type SemanticDiagnosticsSync = "semanticDiagnosticsSync"; + type SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; + type NavBar = "navbar"; + type Navto = "navto"; + type NavTree = "navtree"; + type NavTreeFull = "navtree-full"; + type Occurrences = "occurrences"; + type DocumentHighlights = "documentHighlights"; + type Open = "open"; + type Quickinfo = "quickinfo"; + type References = "references"; + type Reload = "reload"; + type Rename = "rename"; + type Saveto = "saveto"; + type SignatureHelp = "signatureHelp"; + type TypeDefinition = "typeDefinition"; + type ProjectInfo = "projectInfo"; + type ReloadProjects = "reloadProjects"; + type Unknown = "unknown"; + type OpenExternalProject = "openExternalProject"; + type OpenExternalProjects = "openExternalProjects"; + type CloseExternalProject = "closeExternalProject"; + type TodoComments = "todoComments"; + type Indentation = "indentation"; + type DocCommentTemplate = "docCommentTemplate"; + type CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; + type GetCodeFixes = "getCodeFixes"; + type GetSupportedCodeFixes = "getSupportedCodeFixes"; + } + /** + * A TypeScript Server message + */ + interface Message { + /** + * Sequence number of the message + */ + seq: number; + /** + * One of "request", "response", or "event" + */ + type: string; + } + /** + * Client-initiated request message + */ + interface Request extends Message { + /** + * The command to execute + */ + command: string; + /** + * Object containing arguments for the command + */ + arguments?: any; + } + /** + * Request to reload the project structure for all the opened files + */ + interface ReloadProjectsRequest extends Message { + command: CommandTypes.ReloadProjects; + } + /** + * Server-initiated event message + */ + interface Event extends Message { + /** + * Name of event + */ + event: string; + /** + * Event-specific information + */ + body?: any; + } + /** + * Response by server to client request message. + */ + interface Response extends Message { + /** + * Sequence number of the request message. + */ + request_seq: number; + /** + * Outcome of the request. + */ + success: boolean; + /** + * The command requested. + */ + command: string; + /** + * Contains error message if success === false. + */ + message?: string; + /** + * Contains message body if success === true. + */ + body?: any; + } + /** + * Arguments for FileRequest messages. + */ + interface FileRequestArgs { + /** + * The file for the request (absolute pathname required). + */ + file: string; + projectFileName?: string; + } + /** + * Requests a JS Doc comment template for a given position + */ + interface DocCommentTemplateRequest extends FileLocationRequest { + command: CommandTypes.DocCommentTemplate; + } + /** + * Response to DocCommentTemplateRequest + */ + interface DocCommandTemplateResponse extends Response { + body?: TextInsertion; + } + /** + * A request to get TODO comments from the file + */ + interface TodoCommentRequest extends FileRequest { + command: CommandTypes.TodoComments; + arguments: TodoCommentRequestArgs; + } + /** + * Arguments for TodoCommentRequest request. + */ + interface TodoCommentRequestArgs extends FileRequestArgs { + /** + * Array of target TodoCommentDescriptors that describes TODO comments to be found + */ + descriptors: TodoCommentDescriptor[]; + } + /** + * Response for TodoCommentRequest request. + */ + interface TodoCommentsResponse extends Response { + body?: TodoComment[]; + } + /** + * A request to get indentation for a location in file + */ + interface IndentationRequest extends FileLocationRequest { + command: CommandTypes.Indentation; + arguments: IndentationRequestArgs; + } + /** + * Response for IndentationRequest request. + */ + interface IndentationResponse extends Response { + body?: IndentationResult; + } + /** + * Indentation result representing where indentation should be placed + */ + interface IndentationResult { + /** + * The base position in the document that the indent should be relative to + */ + position: number; + /** + * The number of columns the indent should be at relative to the position's column. + */ + indentation: number; + } + /** + * Arguments for IndentationRequest request. + */ + interface IndentationRequestArgs extends FileLocationRequestArgs { + /** + * An optional set of settings to be used when computing indentation. + * If argument is omitted - then it will use settings for file that were previously set via 'configure' request or global settings. + */ + options?: EditorSettings; + } + /** + * Arguments for ProjectInfoRequest request. + */ + interface ProjectInfoRequestArgs extends FileRequestArgs { + /** + * Indicate if the file name list of the project is needed + */ + needFileNameList: boolean; + } + /** + * A request to get the project information of the current file. + */ + interface ProjectInfoRequest extends Request { + command: CommandTypes.ProjectInfo; + arguments: ProjectInfoRequestArgs; + } + /** + * A request to retrieve compiler options diagnostics for a project + */ + interface CompilerOptionsDiagnosticsRequest extends Request { + arguments: CompilerOptionsDiagnosticsRequestArgs; + } + /** + * Arguments for CompilerOptionsDiagnosticsRequest request. + */ + interface CompilerOptionsDiagnosticsRequestArgs { + /** + * Name of the project to retrieve compiler options diagnostics. + */ + projectFileName: string; + } + /** + * Response message body for "projectInfo" request + */ + interface ProjectInfo { + /** + * For configured project, this is the normalized path of the 'tsconfig.json' file + * For inferred project, this is undefined + */ + configFileName: string; + /** + * The list of normalized file name in the project, including 'lib.d.ts' + */ + fileNames?: string[]; + /** + * Indicates if the project has a active language service instance + */ + languageServiceDisabled?: boolean; + } + /** + * Represents diagnostic info that includes location of diagnostic in two forms + * - start position and length of the error span + * - startLocation and endLocation - a pair of Location objects that store start/end line and offset of the error span. + */ + interface DiagnosticWithLinePosition { + message: string; + start: number; + length: number; + startLocation: Location; + endLocation: Location; + category: string; + code: number; + } + /** + * Response message for "projectInfo" request + */ + interface ProjectInfoResponse extends Response { + body?: ProjectInfo; + } + /** + * Request whose sole parameter is a file name. + */ + interface FileRequest extends Request { + arguments: FileRequestArgs; + } + /** + * Instances of this interface specify a location in a source file: + * (file, line, character offset), where line and character offset are 1-based. + */ + interface FileLocationRequestArgs extends FileRequestArgs { + /** + * The line number for the request (1-based). + */ + line: number; + /** + * The character offset (on the line) for the request (1-based). + */ + offset: number; + } + /** + * Request for the available codefixes at a specific position. + */ + interface CodeFixRequest extends Request { + command: CommandTypes.GetCodeFixes; + arguments: CodeFixRequestArgs; + } + /** + * Instances of this interface specify errorcodes on a specific location in a sourcefile. + */ + interface CodeFixRequestArgs extends FileRequestArgs { + /** + * The line number for the request (1-based). + */ + startLine: number; + /** + * The character offset (on the line) for the request (1-based). + */ + startOffset: number; + /** + * The line number for the request (1-based). + */ + endLine: number; + /** + * The character offset (on the line) for the request (1-based). + */ + endOffset: number; + /** + * Errorcodes we want to get the fixes for. + */ + errorCodes?: number[]; + } + /** + * Response for GetCodeFixes request. + */ + interface GetCodeFixesResponse extends Response { + body?: CodeAction[]; + } + /** + * A request whose arguments specify a file location (file, line, col). + */ + interface FileLocationRequest extends FileRequest { + arguments: FileLocationRequestArgs; + } + /** + * A request to get codes of supported code fixes. + */ + interface GetSupportedCodeFixesRequest extends Request { + command: CommandTypes.GetSupportedCodeFixes; + } + /** + * A response for GetSupportedCodeFixesRequest request. + */ + interface GetSupportedCodeFixesResponse extends Response { + /** + * List of error codes supported by the server. + */ + body?: string[]; + } + /** + * Arguments for EncodedSemanticClassificationsRequest request. + */ + interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { + /** + * Start position of the span. + */ + start: number; + /** + * Length of the span. + */ + length: number; + } + /** + * Arguments in document highlight request; include: filesToSearch, file, + * line, offset. + */ + interface DocumentHighlightsRequestArgs extends FileLocationRequestArgs { + /** + * List of files to search for document highlights. + */ + filesToSearch: string[]; + } + /** + * Go to definition request; value of command field is + * "definition". Return response giving the file locations that + * define the symbol found in file at location line, col. + */ + interface DefinitionRequest extends FileLocationRequest { + command: CommandTypes.Definition; + } + /** + * Go to type request; value of command field is + * "typeDefinition". Return response giving the file locations that + * define the type for the symbol found in file at location line, col. + */ + interface TypeDefinitionRequest extends FileLocationRequest { + command: CommandTypes.TypeDefinition; + } + /** + * Go to implementation request; value of command field is + * "implementation". Return response giving the file locations that + * implement the symbol found in file at location line, col. + */ + interface ImplementationRequest extends FileLocationRequest { + command: CommandTypes.Implementation; + } + /** + * Location in source code expressed as (one-based) line and character offset. + */ + interface Location { + line: number; + offset: number; + } + /** + * Object found in response messages defining a span of text in source code. + */ + interface TextSpan { + /** + * First character of the definition. + */ + start: Location; + /** + * One character past last character of the definition. + */ + end: Location; + } + /** + * Object found in response messages defining a span of text in a specific source file. + */ + interface FileSpan extends TextSpan { + /** + * File containing text span. + */ + file: string; + } + /** + * Definition response message. Gives text range for definition. + */ + interface DefinitionResponse extends Response { + body?: FileSpan[]; + } + /** + * Definition response message. Gives text range for definition. + */ + interface TypeDefinitionResponse extends Response { + body?: FileSpan[]; + } + /** + * Implementation response message. Gives text range for implementations. + */ + interface ImplementationResponse extends Response { + body?: FileSpan[]; + } + /** + * Request to get brace completion for a location in the file. + */ + interface BraceCompletionRequest extends FileLocationRequest { + command: CommandTypes.BraceCompletion; + arguments: BraceCompletionRequestArgs; + } + /** + * Argument for BraceCompletionRequest request. + */ + interface BraceCompletionRequestArgs extends FileLocationRequestArgs { + /** + * Kind of opening brace + */ + openingBrace: string; + } + /** + * Get occurrences request; value of command field is + * "occurrences". Return response giving spans that are relevant + * in the file at a given line and column. + */ + interface OccurrencesRequest extends FileLocationRequest { + command: CommandTypes.Occurrences; + } + interface OccurrencesResponseItem extends FileSpan { + /** + * True if the occurrence is a write location, false otherwise. + */ + isWriteAccess: boolean; + } + interface OccurrencesResponse extends Response { + body?: OccurrencesResponseItem[]; + } + /** + * Get document highlights request; value of command field is + * "documentHighlights". Return response giving spans that are relevant + * in the file at a given line and column. + */ + interface DocumentHighlightsRequest extends FileLocationRequest { + command: CommandTypes.DocumentHighlights; + arguments: DocumentHighlightsRequestArgs; + } + /** + * Span augmented with extra information that denotes the kind of the highlighting to be used for span. + * Kind is taken from HighlightSpanKind type. + */ + interface HighlightSpan extends TextSpan { + kind: string; + } + /** + * Represents a set of highligh spans for a give name + */ + interface DocumentHighlightsItem { + /** + * File containing highlight spans. + */ + file: string; + /** + * Spans to highlight in file. + */ + highlightSpans: HighlightSpan[]; + } + /** + * Response for a DocumentHighlightsRequest request. + */ + interface DocumentHighlightsResponse extends Response { + body?: DocumentHighlightsItem[]; + } + /** + * Find references request; value of command field is + * "references". Return response giving the file locations that + * reference the symbol found in file at location line, col. + */ + interface ReferencesRequest extends FileLocationRequest { + command: CommandTypes.References; + } + interface ReferencesResponseItem extends FileSpan { + /** Text of line containing the reference. Including this + * with the response avoids latency of editor loading files + * to show text of reference line (the server already has + * loaded the referencing files). + */ + lineText: string; + /** + * True if reference is a write location, false otherwise. + */ + isWriteAccess: boolean; + /** + * True if reference is a definition, false otherwise. + */ + isDefinition: boolean; + } + /** + * The body of a "references" response message. + */ + interface ReferencesResponseBody { + /** + * The file locations referencing the symbol. + */ + refs: ReferencesResponseItem[]; + /** + * The name of the symbol. + */ + symbolName: string; + /** + * The start character offset of the symbol (on the line provided by the references request). + */ + symbolStartOffset: number; + /** + * The full display name of the symbol. + */ + symbolDisplayString: string; + } + /** + * Response to "references" request. + */ + interface ReferencesResponse extends Response { + body?: ReferencesResponseBody; + } + /** + * Argument for RenameRequest request. + */ + interface RenameRequestArgs extends FileLocationRequestArgs { + /** + * Should text at specified location be found/changed in comments? + */ + findInComments?: boolean; + /** + * Should text at specified location be found/changed in strings? + */ + findInStrings?: boolean; + } + /** + * Rename request; value of command field is "rename". Return + * response giving the file locations that reference the symbol + * found in file at location line, col. Also return full display + * name of the symbol so that client can print it unambiguously. + */ + interface RenameRequest extends FileLocationRequest { + command: CommandTypes.Rename; + arguments: RenameRequestArgs; + } + /** + * Information about the item to be renamed. + */ + interface RenameInfo { + /** + * True if item can be renamed. + */ + canRename: boolean; + /** + * Error message if item can not be renamed. + */ + localizedErrorMessage?: string; + /** + * Display name of the item to be renamed. + */ + displayName: string; + /** + * Full display name of item to be renamed. + */ + fullDisplayName: string; + /** + * The items's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + } + /** + * A group of text spans, all in 'file'. + */ + interface SpanGroup { + /** The file to which the spans apply */ + file: string; + /** The text spans in this group */ + locs: TextSpan[]; + } + interface RenameResponseBody { + /** + * Information about the item to be renamed. + */ + info: RenameInfo; + /** + * An array of span groups (one per file) that refer to the item to be renamed. + */ + locs: SpanGroup[]; + } + /** + * Rename response message. + */ + interface RenameResponse extends Response { + body?: RenameResponseBody; + } + /** + * Represents a file in external project. + * External project is project whose set of files, compilation options and open\close state + * is maintained by the client (i.e. if all this data come from .csproj file in Visual Studio). + * External project will exist even if all files in it are closed and should be closed explicity. + * If external project includes one or more tsconfig.json/jsconfig.json files then tsserver will + * create configured project for every config file but will maintain a link that these projects were created + * as a result of opening external project so they should be removed once external project is closed. + */ + interface ExternalFile { + /** + * Name of file file + */ + fileName: string; + /** + * Script kind of the file + */ + scriptKind?: ScriptKind; + /** + * Whether file has mixed content (i.e. .cshtml file that combines html markup with C#/JavaScript) + */ + hasMixedContent?: boolean; + /** + * Content of the file + */ + content?: string; + } + /** + * Represent an external project + */ + interface ExternalProject { + /** + * Project name + */ + projectFileName: string; + /** + * List of root files in project + */ + rootFiles: ExternalFile[]; + /** + * Compiler options for the project + */ + options: ExternalProjectCompilerOptions; + /** + * Explicitly specified typing options for the project + */ + typingOptions?: TypingOptions; + } + /** + * For external projects, some of the project settings are sent together with + * compiler settings. + */ + interface ExternalProjectCompilerOptions extends CompilerOptions { + /** + * If compile on save is enabled for the project + */ + compileOnSave?: boolean; + } + /** + * Contains information about current project version + */ + interface ProjectVersionInfo { + /** + * Project name + */ + projectName: string; + /** + * true if project is inferred or false if project is external or configured + */ + isInferred: boolean; + /** + * Project version + */ + version: number; + /** + * Current set of compiler options for project + */ + options: CompilerOptions; + } + /** + * Represents a set of changes that happen in project + */ + interface ProjectChanges { + /** + * List of added files + */ + added: string[]; + /** + * List of removed files + */ + removed: string[]; + } + /** + * Describes set of files in the project. + * info might be omitted in case of inferred projects + * if files is set - then this is the entire set of files in the project + * if changes is set - then this is the set of changes that should be applied to existing project + * otherwise - assume that nothing is changed + */ + interface ProjectFiles { + /** + * Information abount project verison + */ + info?: ProjectVersionInfo; + /** + * List of files in project (might be omitted if current state of project can be computed using only information from 'changes') + */ + files?: string[]; + /** + * Set of changes in project (omitted if the entire set of files in project should be replaced) + */ + changes?: ProjectChanges; + } + /** + * Combines project information with project level errors. + */ + interface ProjectFilesWithDiagnostics extends ProjectFiles { + /** + * List of errors in project + */ + projectErrors: DiagnosticWithLinePosition[]; + } + /** + * Information found in a configure request. + */ + interface ConfigureRequestArguments { + /** + * Information about the host, for example 'Emacs 24.4' or + * 'Sublime Text version 3075' + */ + hostInfo?: string; + /** + * If present, tab settings apply only to this file. + */ + file?: string; + /** + * The format options to use during formatting and other code editing features. + */ + formatOptions?: FormatCodeSettings; + } + /** + * Configure request; value of command field is "configure". Specifies + * host information, such as host type, tab size, and indent size. + */ + interface ConfigureRequest extends Request { + command: CommandTypes.Configure; + arguments: ConfigureRequestArguments; + } + /** + * Response to "configure" request. This is just an acknowledgement, so + * no body field is required. + */ + interface ConfigureResponse extends Response { + } + /** + * Information found in an "open" request. + */ + interface OpenRequestArgs extends FileRequestArgs { + /** + * Used when a version of the file content is known to be more up to date than the one on disk. + * Then the known content will be used upon opening instead of the disk copy + */ + fileContent?: string; + /** + * Used to specify the script kind of the file explicitly. It could be one of the following: + * "TS", "JS", "TSX", "JSX" + */ + scriptKindName?: "TS" | "JS" | "TSX" | "JSX"; + } + /** + * Open request; value of command field is "open". Notify the + * server that the client has file open. The server will not + * monitor the filesystem for changes in this file and will assume + * that the client is updating the server (using the change and/or + * reload messages) when the file changes. Server does not currently + * send a response to an open request. + */ + interface OpenRequest extends Request { + command: CommandTypes.Open; + arguments: OpenRequestArgs; + } + /** + * Request to open or update external project + */ + interface OpenExternalProjectRequest extends Request { + command: CommandTypes.OpenExternalProject; + arguments: OpenExternalProjectArgs; + } + /** + * Arguments to OpenExternalProjectRequest request + */ + type OpenExternalProjectArgs = ExternalProject; + /** + * Request to open multiple external projects + */ + interface OpenExternalProjectsRequest extends Request { + command: CommandTypes.OpenExternalProjects; + arguments: OpenExternalProjectsArgs; + } + /** + * Arguments to OpenExternalProjectsRequest + */ + interface OpenExternalProjectsArgs { + /** + * List of external projects to open or update + */ + projects: ExternalProject[]; + } + /** + * Response to OpenExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface OpenExternalProjectResponse extends Response { + } + /** + * Response to OpenExternalProjectsRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface OpenExternalProjectsResponse extends Response { + } + /** + * Request to close external project. + */ + interface CloseExternalProjectRequest extends Request { + command: CommandTypes.CloseExternalProject; + arguments: CloseExternalProjectRequestArgs; + } + /** + * Arguments to CloseExternalProjectRequest request + */ + interface CloseExternalProjectRequestArgs { + /** + * Name of the project to close + */ + projectFileName: string; + } + /** + * Response to CloseExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface CloseExternalProjectResponse extends Response { + } + /** + * Arguments to SynchronizeProjectListRequest + */ + interface SynchronizeProjectListRequestArgs { + /** + * List of last known projects + */ + knownProjects: protocol.ProjectVersionInfo[]; + } + /** + * Request to set compiler options for inferred projects. + * External projects are opened / closed explicitly. + * Configured projects are opened when user opens loose file that has 'tsconfig.json' or 'jsconfig.json' anywhere in one of containing folders. + * This configuration file will be used to obtain a list of files and configuration settings for the project. + * Inferred projects are created when user opens a loose file that is not the part of external project + * or configured project and will contain only open file and transitive closure of referenced files if 'useOneInferredProject' is false, + * or all open loose files and its transitive closure of referenced files if 'useOneInferredProject' is true. + */ + interface SetCompilerOptionsForInferredProjectsRequest extends Request { + command: CommandTypes.CompilerOptionsForInferredProjects; + arguments: SetCompilerOptionsForInferredProjectsArgs; + } + /** + * Argument for SetCompilerOptionsForInferredProjectsRequest request. + */ + interface SetCompilerOptionsForInferredProjectsArgs { + /** + * Compiler options to be used with inferred projects. + */ + options: ExternalProjectCompilerOptions; + } + /** + * Response to SetCompilerOptionsForInferredProjectsResponse request. This is just an acknowledgement, so + * no body field is required. + */ + interface SetCompilerOptionsForInferredProjectsResponse extends Response { + } + /** + * Exit request; value of command field is "exit". Ask the server process + * to exit. + */ + interface ExitRequest extends Request { + command: CommandTypes.Exit; + } + /** + * Close request; value of command field is "close". Notify the + * server that the client has closed a previously open file. If + * file is still referenced by open files, the server will resume + * monitoring the filesystem for changes to file. Server does not + * currently send a response to a close request. + */ + interface CloseRequest extends FileRequest { + command: CommandTypes.Close; + } + /** + * Request to obtain the list of files that should be regenerated if target file is recompiled. + * NOTE: this us query-only operation and does not generate any output on disk. + */ + interface CompileOnSaveAffectedFileListRequest extends FileRequest { + command: CommandTypes.CompileOnSaveAffectedFileList; + } + /** + * Contains a list of files that should be regenerated in a project + */ + interface CompileOnSaveAffectedFileListSingleProject { + /** + * Project name + */ + projectFileName: string; + /** + * List of files names that should be recompiled + */ + fileNames: string[]; + } + /** + * Response for CompileOnSaveAffectedFileListRequest request; + */ + interface CompileOnSaveAffectedFileListResponse extends Response { + body: CompileOnSaveAffectedFileListSingleProject[]; + } + /** + * Request to recompile the file. All generated outputs (.js, .d.ts or .js.map files) is written on disk. + */ + interface CompileOnSaveEmitFileRequest extends FileRequest { + command: CommandTypes.CompileOnSaveEmitFile; + arguments: CompileOnSaveEmitFileRequestArgs; + } + /** + * Arguments for CompileOnSaveEmitFileRequest + */ + interface CompileOnSaveEmitFileRequestArgs extends FileRequestArgs { + /** + * if true - then file should be recompiled even if it does not have any changes. + */ + forced?: boolean; + } + /** + * Quickinfo request; value of command field is + * "quickinfo". Return response giving a quick type and + * documentation string for the symbol found in file at location + * line, col. + */ + interface QuickInfoRequest extends FileLocationRequest { + command: CommandTypes.Quickinfo; + } + /** + * Body of QuickInfoResponse. + */ + interface QuickInfoResponseBody { + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * Starting file location of symbol. + */ + start: Location; + /** + * One past last character of symbol. + */ + end: Location; + /** + * Type and kind of symbol. + */ + displayString: string; + /** + * Documentation associated with symbol. + */ + documentation: string; + } + /** + * Quickinfo response message. + */ + interface QuickInfoResponse extends Response { + body?: QuickInfoResponseBody; + } + /** + * Arguments for format messages. + */ + interface FormatRequestArgs extends FileLocationRequestArgs { + /** + * Last line of range for which to format text in file. + */ + endLine: number; + /** + * Character offset on last line of range for which to format text in file. + */ + endOffset: number; + /** + * Format options to be used. + */ + options?: FormatCodeSettings; + } + /** + * Format request; value of command field is "format". Return + * response giving zero or more edit instructions. The edit + * instructions will be sorted in file order. Applying the edit + * instructions in reverse to file will result in correctly + * reformatted text. + */ + interface FormatRequest extends FileLocationRequest { + command: CommandTypes.Format; + arguments: FormatRequestArgs; + } + /** + * Object found in response messages defining an editing + * instruction for a span of text in source code. The effect of + * this instruction is to replace the text starting at start and + * ending one character before end with newText. For an insertion, + * the text span is empty. For a deletion, newText is empty. + */ + interface CodeEdit { + /** + * First character of the text span to edit. + */ + start: Location; + /** + * One character past last character of the text span to edit. + */ + end: Location; + /** + * Replace the span defined above with this string (may be + * the empty string). + */ + newText: string; + } + interface FileCodeEdits { + fileName: string; + textChanges: CodeEdit[]; + } + interface CodeFixResponse extends Response { + /** The code actions that are available */ + body?: CodeAction[]; + } + interface CodeAction { + /** Description of the code action to display in the UI of the editor */ + description: string; + /** Text changes to apply to each file as part of the code action */ + changes: FileCodeEdits[]; + } + /** + * Format and format on key response message. + */ + interface FormatResponse extends Response { + body?: CodeEdit[]; + } + /** + * Arguments for format on key messages. + */ + interface FormatOnKeyRequestArgs extends FileLocationRequestArgs { + /** + * Key pressed (';', '\n', or '}'). + */ + key: string; + options?: FormatCodeSettings; + } + /** + * Format on key request; value of command field is + * "formatonkey". Given file location and key typed (as string), + * return response giving zero or more edit instructions. The + * edit instructions will be sorted in file order. Applying the + * edit instructions in reverse to file will result in correctly + * reformatted text. + */ + interface FormatOnKeyRequest extends FileLocationRequest { + command: CommandTypes.Formatonkey; + arguments: FormatOnKeyRequestArgs; + } + /** + * Arguments for completions messages. + */ + interface CompletionsRequestArgs extends FileLocationRequestArgs { + /** + * Optional prefix to apply to possible completions. + */ + prefix?: string; + } + /** + * Completions request; value of command field is "completions". + * Given a file location (file, line, col) and a prefix (which may + * be the empty string), return the possible completions that + * begin with prefix. + */ + interface CompletionsRequest extends FileLocationRequest { + command: CommandTypes.Completions; + arguments: CompletionsRequestArgs; + } + /** + * Arguments for completion details request. + */ + interface CompletionDetailsRequestArgs extends FileLocationRequestArgs { + /** + * Names of one or more entries for which to obtain details. + */ + entryNames: string[]; + } + /** + * Completion entry details request; value of command field is + * "completionEntryDetails". Given a file location (file, line, + * col) and an array of completion entry names return more + * detailed information for each completion entry. + */ + interface CompletionDetailsRequest extends FileLocationRequest { + command: CommandTypes.CompletionDetails; + arguments: CompletionDetailsRequestArgs; + } + /** + * Part of a symbol description. + */ + interface SymbolDisplayPart { + /** + * Text of an item describing the symbol. + */ + text: string; + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: string; + } + /** + * An item found in a completion response. + */ + interface CompletionEntry { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * A string that is used for comparing completion items so that they can be ordered. This + * is often the same as the name but may be different in certain circumstances. + */ + sortText: string; + /** + * An optional span that indicates the text to be replaced by this completion item. If present, + * this span should be used instead of the default one. + */ + replacementSpan?: TextSpan; + } + /** + * Additional completion entry details, available on demand + */ + interface CompletionEntryDetails { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * Display parts of the symbol (similar to quick info). + */ + displayParts: SymbolDisplayPart[]; + /** + * Documentation strings for the symbol. + */ + documentation: SymbolDisplayPart[]; + } + interface CompletionsResponse extends Response { + body?: CompletionEntry[]; + } + interface CompletionDetailsResponse extends Response { + body?: CompletionEntryDetails[]; + } + /** + * Signature help information for a single parameter + */ + interface SignatureHelpParameter { + /** + * The parameter's name + */ + name: string; + /** + * Documentation of the parameter. + */ + documentation: SymbolDisplayPart[]; + /** + * Display parts of the parameter. + */ + displayParts: SymbolDisplayPart[]; + /** + * Whether the parameter is optional or not. + */ + isOptional: boolean; + } + /** + * Represents a single signature to show in signature help. + */ + interface SignatureHelpItem { + /** + * Whether the signature accepts a variable number of arguments. + */ + isVariadic: boolean; + /** + * The prefix display parts. + */ + prefixDisplayParts: SymbolDisplayPart[]; + /** + * The suffix display parts. + */ + suffixDisplayParts: SymbolDisplayPart[]; + /** + * The separator display parts. + */ + separatorDisplayParts: SymbolDisplayPart[]; + /** + * The signature helps items for the parameters. + */ + parameters: SignatureHelpParameter[]; + /** + * The signature's documentation + */ + documentation: SymbolDisplayPart[]; + } + /** + * Signature help items found in the response of a signature help request. + */ + interface SignatureHelpItems { + /** + * The signature help items. + */ + items: SignatureHelpItem[]; + /** + * The span for which signature help should appear on a signature + */ + applicableSpan: TextSpan; + /** + * The item selected in the set of available help items. + */ + selectedItemIndex: number; + /** + * The argument selected in the set of parameters. + */ + argumentIndex: number; + /** + * The argument count + */ + argumentCount: number; + } + /** + * Arguments of a signature help request. + */ + interface SignatureHelpRequestArgs extends FileLocationRequestArgs { + } + /** + * Signature help request; value of command field is "signatureHelp". + * Given a file location (file, line, col), return the signature + * help. + */ + interface SignatureHelpRequest extends FileLocationRequest { + command: CommandTypes.SignatureHelp; + arguments: SignatureHelpRequestArgs; + } + /** + * Response object for a SignatureHelpRequest. + */ + interface SignatureHelpResponse extends Response { + body?: SignatureHelpItems; + } + /** + * Synchronous request for semantic diagnostics of one file. + */ + interface SemanticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SemanticDiagnosticsSync; + arguments: SemanticDiagnosticsSyncRequestArgs; + } + interface SemanticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + /** + * Response object for synchronous sematic diagnostics request. + */ + interface SemanticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + /** + * Synchronous request for syntactic diagnostics of one file. + */ + interface SyntacticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SyntacticDiagnosticsSync; + arguments: SyntacticDiagnosticsSyncRequestArgs; + } + interface SyntacticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + /** + * Response object for synchronous syntactic diagnostics request. + */ + interface SyntacticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + /** + * Arguments for GeterrForProject request. + */ + interface GeterrForProjectRequestArgs { + /** + * the file requesting project error list + */ + file: string; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ + delay: number; + } + /** + * GeterrForProjectRequest request; value of command field is + * "geterrForProject". It works similarly with 'Geterr', only + * it request for every file in this project. + */ + interface GeterrForProjectRequest extends Request { + command: CommandTypes.GeterrForProject; + arguments: GeterrForProjectRequestArgs; + } + /** + * Arguments for geterr messages. + */ + interface GeterrRequestArgs { + /** + * List of file names for which to compute compiler errors. + * The files will be checked in list order. + */ + files: string[]; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ + delay: number; + } + /** + * Geterr request; value of command field is "geterr". Wait for + * delay milliseconds and then, if during the wait no change or + * reload messages have arrived for the first file in the files + * list, get the syntactic errors for the file, field requests, + * and then get the semantic errors for the file. Repeat with a + * smaller delay for each subsequent file on the files list. Best + * practice for an editor is to send a file list containing each + * file that is currently visible, in most-recently-used order. + */ + interface GeterrRequest extends Request { + command: CommandTypes.Geterr; + arguments: GeterrRequestArgs; + } + /** + * Item of diagnostic information found in a DiagnosticEvent message. + */ + interface Diagnostic { + /** + * Starting file location at which text applies. + */ + start: Location; + /** + * The last file location at which the text applies. + */ + end: Location; + /** + * Text of diagnostic message. + */ + text: string; + /** + * The error code of the diagnostic message. + */ + code?: number; + } + interface DiagnosticEventBody { + /** + * The file for which diagnostic information is reported. + */ + file: string; + /** + * An array of diagnostic information items. + */ + diagnostics: Diagnostic[]; + } + /** + * Event message for "syntaxDiag" and "semanticDiag" event types. + * These events provide syntactic and semantic errors for a file. + */ + interface DiagnosticEvent extends Event { + body?: DiagnosticEventBody; + } + interface ConfigFileDiagnosticEventBody { + /** + * The file which trigged the searching and error-checking of the config file + */ + triggerFile: string; + /** + * The name of the found config file. + */ + configFile: string; + /** + * An arry of diagnostic information items for the found config file. + */ + diagnostics: Diagnostic[]; + } + /** + * Event message for "configFileDiag" event type. + * This event provides errors for a found config file. + */ + interface ConfigFileDiagnosticEvent extends Event { + body?: ConfigFileDiagnosticEventBody; + event: "configFileDiag"; + } + /** + * Arguments for reload request. + */ + interface ReloadRequestArgs extends FileRequestArgs { + /** + * Name of temporary file from which to reload file + * contents. May be same as file. + */ + tmpfile: string; + } + /** + * Reload request message; value of command field is "reload". + * Reload contents of file with name given by the 'file' argument + * from temporary file with name given by the 'tmpfile' argument. + * The two names can be identical. + */ + interface ReloadRequest extends FileRequest { + command: CommandTypes.Reload; + arguments: ReloadRequestArgs; + } + /** + * Response to "reload" request. This is just an acknowledgement, so + * no body field is required. + */ + interface ReloadResponse extends Response { + } + /** + * Arguments for saveto request. + */ + interface SavetoRequestArgs extends FileRequestArgs { + /** + * Name of temporary file into which to save server's view of + * file contents. + */ + tmpfile: string; + } + /** + * Saveto request message; value of command field is "saveto". + * For debugging purposes, save to a temporaryfile (named by + * argument 'tmpfile') the contents of file named by argument + * 'file'. The server does not currently send a response to a + * "saveto" request. + */ + interface SavetoRequest extends FileRequest { + command: CommandTypes.Saveto; + arguments: SavetoRequestArgs; + } + /** + * Arguments for navto request message. + */ + interface NavtoRequestArgs extends FileRequestArgs { + /** + * Search term to navigate to from current location; term can + * be '.*' or an identifier prefix. + */ + searchValue: string; + /** + * Optional limit on the number of items to return. + */ + maxResultCount?: number; + /** + * Optional flag to indicate we want results for just the current file + * or the entire project. + */ + currentFileOnly?: boolean; + projectFileName?: string; + } + /** + * Navto request message; value of command field is "navto". + * Return list of objects giving file locations and symbols that + * match the search term given in argument 'searchTerm'. The + * context for the search is given by the named file. + */ + interface NavtoRequest extends FileRequest { + command: CommandTypes.Navto; + arguments: NavtoRequestArgs; + } + /** + * An item found in a navto response. + */ + interface NavtoItem { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: string; + /** + * exact, substring, or prefix. + */ + matchKind?: string; + /** + * If this was a case sensitive or insensitive match. + */ + isCaseSensitive?: boolean; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + /** + * The file in which the symbol is found. + */ + file: string; + /** + * The location within file at which the symbol is found. + */ + start: Location; + /** + * One past the last character of the symbol. + */ + end: Location; + /** + * Name of symbol's container symbol (if any); for example, + * the class name if symbol is a class member. + */ + containerName?: string; + /** + * Kind of symbol's container symbol (if any). + */ + containerKind?: string; + } + /** + * Navto response message. Body is an array of navto items. Each + * item gives a symbol that matched the search term. + */ + interface NavtoResponse extends Response { + body?: NavtoItem[]; + } + /** + * Arguments for change request message. + */ + interface ChangeRequestArgs extends FormatRequestArgs { + /** + * Optional string to insert at location (file, line, offset). + */ + insertString?: string; + } + /** + * Change request message; value of command field is "change". + * Update the server's view of the file named by argument 'file'. + * Server does not currently send a response to a change request. + */ + interface ChangeRequest extends FileLocationRequest { + command: CommandTypes.Change; + arguments: ChangeRequestArgs; + } + /** + * Response to "brace" request. + */ + interface BraceResponse extends Response { + body?: TextSpan[]; + } + /** + * Brace matching request; value of command field is "brace". + * Return response giving the file locations of matching braces + * found in file at location line, offset. + */ + interface BraceRequest extends FileLocationRequest { + command: CommandTypes.Brace; + } + /** + * NavBar items request; value of command field is "navbar". + * Return response giving the list of navigation bar entries + * extracted from the requested file. + */ + interface NavBarRequest extends FileRequest { + command: CommandTypes.NavBar; + } + /** + * NavTree request; value of command field is "navtree". + * Return response giving the navigation tree of the requested file. + */ + interface NavTreeRequest extends FileRequest { + command: CommandTypes.NavTree; + } + interface NavigationBarItem { + /** + * The item's display text. + */ + text: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + /** + * The definition locations of the item. + */ + spans: TextSpan[]; + /** + * Optional children. + */ + childItems?: NavigationBarItem[]; + /** + * Number of levels deep this item should appear. + */ + indent: number; + } + /** protocol.NavigationTree is identical to ts.NavigationTree, except using protocol.TextSpan instead of ts.TextSpan */ + interface NavigationTree { + text: string; + kind: string; + kindModifiers: string; + spans: TextSpan[]; + childItems?: NavigationTree[]; + } + interface NavBarResponse extends Response { + body?: NavigationBarItem[]; + } + interface NavTreeResponse extends Response { + body?: NavigationTree; + } +} +declare namespace ts.server.protocol { + + interface TextInsertion { + newText: string; + /** The position in newText the caret should point to after the insertion. */ + caretOffset: number; + } + + interface TodoCommentDescriptor { + text: string; + priority: number; + } + + interface TodoComment { + descriptor: TodoCommentDescriptor; + message: string; + position: number; + } + + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle; + } + + enum IndentStyle { + None = 0, + Block = 1, + Smart = 2, + } + + enum ScriptKind { + Unknown = 0, + JS = 1, + JSX = 2, + TS = 3, + TSX = 4, + } + + interface TypingOptions { + enableAutoDiscovery?: boolean; + include?: string[]; + exclude?: string[]; + [option: string]: string[] | boolean | undefined; + } + + interface CompilerOptions { + allowJs?: boolean; + allowSyntheticDefaultImports?: boolean; + allowUnreachableCode?: boolean; + allowUnusedLabels?: boolean; + alwaysStrict?: boolean; + baseUrl?: string; + charset?: string; + declaration?: boolean; + declarationDir?: string; + disableSizeLimit?: boolean; + emitBOM?: boolean; + emitDecoratorMetadata?: boolean; + experimentalDecorators?: boolean; + forceConsistentCasingInFileNames?: boolean; + importHelpers?: boolean; + inlineSourceMap?: boolean; + inlineSources?: boolean; + isolatedModules?: boolean; + jsx?: JsxEmit; + lib?: string[]; + locale?: string; + mapRoot?: string; + maxNodeModuleJsDepth?: number; + module?: ModuleKind; + moduleResolution?: ModuleResolutionKind; + newLine?: NewLineKind; + noEmit?: boolean; + noEmitHelpers?: boolean; + noEmitOnError?: boolean; + noErrorTruncation?: boolean; + noFallthroughCasesInSwitch?: boolean; + noImplicitAny?: boolean; + noImplicitReturns?: boolean; + noImplicitThis?: boolean; + noUnusedLocals?: boolean; + noUnusedParameters?: boolean; + noImplicitUseStrict?: boolean; + noLib?: boolean; + noResolve?: boolean; + out?: string; + outDir?: string; + outFile?: string; + paths?: MapLike; + preserveConstEnums?: boolean; + project?: string; + reactNamespace?: string; + removeComments?: boolean; + rootDir?: string; + rootDirs?: string[]; + skipLibCheck?: boolean; + skipDefaultLibCheck?: boolean; + sourceMap?: boolean; + sourceRoot?: string; + strictNullChecks?: boolean; + suppressExcessPropertyErrors?: boolean; + suppressImplicitAnyIndexErrors?: boolean; + target?: ScriptTarget; + traceResolution?: boolean; + types?: string[]; + /** Paths used to used to compute primary types search locations */ + typeRoots?: string[]; + [option: string]: CompilerOptionsValue | undefined; + } + + enum JsxEmit { + None = 0, + Preserve = 1, + React = 2, + } + + enum ModuleKind { + None = 0, + CommonJS = 1, + AMD = 2, + UMD = 3, + System = 4, + ES6 = 5, + ES2015 = 5, + } + + enum ModuleResolutionKind { + Classic = 1, + NodeJs = 2, + } + + enum NewLineKind { + CarriageReturnLineFeed = 0, + LineFeed = 1, + } + + interface MapLike { + [index: string]: T; + } + + enum ScriptTarget { + ES3 = 0, + ES5 = 1, + ES6 = 2, + ES2015 = 2, + Latest = 2, + } + + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike; + + interface FormatCodeSettings extends EditorSettings { + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; + } +} \ No newline at end of file diff --git a/lib/tsc.js b/lib/tsc.js index aef54c957e6..7f46b1dddb4 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -145,6 +145,7 @@ var ts; contains: contains, remove: remove, forEachValue: forEachValueInMap, + getKeys: getKeys, clear: clear }; function forEachValueInMap(f) { @@ -152,6 +153,13 @@ var ts; f(key, files[key]); } } + function getKeys() { + var keys = []; + for (var key in files) { + keys.push(key); + } + return keys; + } function get(path) { return files[toKey(path)]; } @@ -528,16 +536,22 @@ var ts; : undefined; } ts.lastOrUndefined = lastOrUndefined; - function binarySearch(array, value) { + function binarySearch(array, value, comparer) { + if (!array || array.length === 0) { + return -1; + } var low = 0; var high = array.length - 1; + comparer = comparer !== undefined + ? comparer + : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; - if (midValue === value) { + if (comparer(midValue, value) === 0) { return middle; } - else if (midValue > value) { + else if (comparer(midValue, value) > 0) { high = middle - 1; } else { @@ -771,6 +785,56 @@ var ts; }; } ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (t) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { baseIndex = baseIndex || 0; return text.replace(/{(\d+)}/g, function (match, index) { return args[+index + baseIndex]; }); @@ -1007,10 +1071,45 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; + function isExternalModuleNameRelative(moduleName) { + return /^\.\.?($|[\\/])/.test(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; function isRootedDiskPath(path) { return getRootLength(path) !== 0; } ts.isRootedDiskPath = isRootedDiskPath; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); + } + ts.convertToRelativePath = convertToRelativePath; function normalizedPathComponents(path, rootLength) { var normalizedParts = getNormalizedParts(path, rootLength); return [path.substr(0, rootLength)].concat(normalizedParts); @@ -1384,6 +1483,14 @@ var ts; return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } ts.getSupportedExtensions = getSupportedExtensions; + function hasJavaScriptFileExtension(fileName) { + return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; @@ -1475,7 +1582,6 @@ var ts; this.transformFlags = 0; this.parent = undefined; this.original = undefined; - this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, @@ -1488,9 +1594,9 @@ var ts; }; var Debug; (function (Debug) { - var currentAssertionLevel; + Debug.currentAssertionLevel = 0; function shouldAssert(level) { - return getCurrentAssertionLevel() >= level; + return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -1508,30 +1614,7 @@ var ts; Debug.assert(false, message); } Debug.fail = fail; - function getCurrentAssertionLevel() { - if (currentAssertionLevel !== undefined) { - return currentAssertionLevel; - } - if (ts.sys === undefined) { - return 0; - } - var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); - currentAssertionLevel = developmentMode - ? 1 - : 0; - return currentAssertionLevel; - } })(Debug = ts.Debug || (ts.Debug = {})); - function getEnvironmentVariable(name, host) { - if (host && host.getEnvironmentVariable) { - return host.getEnvironmentVariable(name); - } - if (ts.sys && ts.sys.getEnvironmentVariable) { - return ts.sys.getEnvironmentVariable(name); - } - return ""; - } - ts.getEnvironmentVariable = getEnvironmentVariable; function orderedRemoveItemAt(array, index) { for (var i = index; i < array.length - 1; i++) { array[i] = array[i + 1]; @@ -1562,6 +1645,64 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + function tryParsePattern(pattern) { + Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; })(ts || (ts = {})); var ts; (function (ts) { @@ -1755,8 +1896,14 @@ var ts; function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; } + function isFileSystemCaseSensitive() { + if (platform === "win32" || platform === "win64") { + return false; + } + return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + } var platform = _os.platform(); - var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); function readFile(fileName, encoding) { if (!fileExists(fileName)) { return undefined; @@ -1881,6 +2028,9 @@ var ts; }, watchDirectory: function (directoryName, callback, recursive) { var options; + if (!directoryExists(directoryName)) { + return; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -1992,19 +2142,43 @@ var ts; realpath: realpath }; } + function recursiveCreateDirectory(directoryPath, sys) { + var basePath = ts.getDirectoryPath(directoryPath); + var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + if (shouldCreateParent) { + recursiveCreateDirectory(basePath, sys); + } + if (shouldCreateParent || !sys.directoryExists(directoryPath)) { + sys.createDirectory(directoryPath); + } + } + var sys; if (typeof ChakraHost !== "undefined") { - return getChakraSystem(); + sys = getChakraSystem(); } else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { - return getWScriptSystem(); + sys = getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { - return getNodeSystem(); + sys = getNodeSystem(); } - else { - return undefined; + if (sys) { + var originalWriteFile_1 = sys.writeFile; + sys.writeFile = function (path, data, writeBom) { + var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); + if (directoryPath && !sys.directoryExists(directoryPath)) { + recursiveCreateDirectory(directoryPath, sys); + } + originalWriteFile_1.call(sys, path, data, writeBom); + }; } + return sys; })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 + : 0; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -2329,7 +2503,7 @@ var ts; The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class" }, - All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "All_symbols_within_a_with_block_will_be_resolved_to_any_2410", message: "All symbols within a 'with' block will be resolved to 'any'." }, + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, @@ -2490,7 +2664,7 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, - Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, @@ -2723,6 +2897,8 @@ var ts; No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file" }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -2747,6 +2923,7 @@ var ts; Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, + Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type 'any' in some locations where its type cannot be determined." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -2776,7 +2953,14 @@ var ts; super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } + The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." }, + Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, + Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, + Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'" }, + Remove_unused_identifiers: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_unused_identifiers_90004", message: "Remove unused identifiers" }, + Implement_interface_on_reference: { code: 90005, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_reference_90005", message: "Implement interface on reference" }, + Implement_interface_on_class: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_class_90006", message: "Implement interface on class" }, + Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class" } }; })(ts || (ts = {})); var ts; @@ -3686,7 +3870,7 @@ var ts; return token = 69; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8"); + ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); var value = 0; var numberOfDigits = 0; while (true) { @@ -4810,10 +4994,10 @@ var ts; return !!(ts.getCombinedNodeFlags(node) & 1); } ts.isLet = isLet; - function isSuperCallExpression(n) { + function isSuperCall(n) { return n.kind === 174 && n.expression.kind === 95; } - ts.isSuperCallExpression = isSuperCallExpression; + ts.isSuperCall = isSuperCall; function isPrologueDirective(node) { return node.kind === 202 && node.expression.kind === 9; } @@ -5061,6 +5245,12 @@ var ts; return node && node.kind === 147 && node.parent.kind === 171; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 147 && + (node.parent.kind === 171 || + node.parent.kind === 192); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { return predicate && predicate.kind === 1; } @@ -5376,10 +5566,6 @@ var ts; return false; } ts.isPartOfExpression = isPartOfExpression; - function isExternalModuleNameRelative(moduleName) { - return /^\.\.?($|[\\/])/.test(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { var moduleState = ts.getModuleInstanceState(node); return moduleState === 1 || @@ -5977,14 +6163,10 @@ var ts; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(node) { - return positionIsSynthesized(node.pos) - || positionIsSynthesized(node.end); + return ts.positionIsSynthesized(node.pos) + || ts.positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function positionIsSynthesized(pos) { - return !(pos >= 0); - } - ts.positionIsSynthesized = positionIsSynthesized; function getOriginalNode(node) { if (node) { while (node.original !== undefined) { @@ -6420,28 +6602,16 @@ var ts; function getDeclarationEmitOutputFilePath(sourceFile, host) { var options = host.getCompilerOptions(); var outputDir = options.declarationDir || options.outDir; - if (options.declaration) { - var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; - } + var path = outputDir + ? getSourceFilePathInNewDir(sourceFile, host, outputDir) + : sourceFile.fileName; + return ts.removeFileExtension(path) + ".d.ts"; } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; - function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0; - } - ts.getEmitScriptTarget = getEmitScriptTarget; - function getEmitModuleKind(compilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; - } - ts.getEmitModuleKind = getEmitModuleKind; function getSourceFilesToEmit(host, targetSourceFile) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { - var moduleKind = getEmitModuleKind(options); + var moduleKind = ts.getEmitModuleKind(options); var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; var sourceFiles = host.getSourceFiles(); return ts.filter(sourceFiles, moduleEmitEnabled ? isNonDeclarationFile : isBundleEmitNonExternalModule); @@ -6458,7 +6628,7 @@ var ts; function isBundleEmitNonExternalModule(sourceFile) { return !isDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile); } - function forEachTransformedEmitFile(host, sourceFiles, action) { + function forEachTransformedEmitFile(host, sourceFiles, action, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { onBundledEmit(host, sourceFiles); @@ -6485,7 +6655,7 @@ var ts; } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (options.declaration || emitOnlyDtsFiles) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], false); } function onBundledEmit(host, sourceFiles) { @@ -6501,7 +6671,7 @@ var ts; function getSourceMapFilePath(jsFilePath, options) { return options.sourceMap ? jsFilePath + ".map" : undefined; } - function forEachExpectedEmitFile(host, action, targetSourceFile) { + function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { onBundledEmit(host); @@ -6528,18 +6698,19 @@ var ts; } } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var emitFileNames = { jsFilePath: jsFilePath, sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), - declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined + declarationFilePath: declarationFilePath }; - action(emitFileNames, [sourceFile], false); + action(emitFileNames, [sourceFile], false, emitOnlyDtsFiles); } function onBundledEmit(host) { var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile) && (!ts.isExternalModule(sourceFile) || - !!getEmitModuleKind(options)); }); + !!ts.getEmitModuleKind(options)); }); if (bundledSources.length) { var jsFilePath = options.outFile || options.out; var emitFileNames = { @@ -6547,7 +6718,7 @@ var ts; sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined }; - action(emitFileNames, bundledSources, true); + action(emitFileNames, bundledSources, true, emitOnlyDtsFiles); } } } @@ -6584,13 +6755,32 @@ var ts; ts.getFirstConstructorWithBody = getFirstConstructorWithBody; function getSetAccessorTypeAnnotationNode(accessor) { if (accessor && accessor.parameters.length > 0) { - var hasThis = accessor.parameters.length === 2 && - accessor.parameters[0].name.kind === 69 && - accessor.parameters[0].name.originalKeywordKind === 97; + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); return accessor.parameters[hasThis ? 1 : 0].type; } } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + if (signature.parameters.length) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return node && node.kind === 69 && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 97; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -6904,14 +7094,6 @@ var ts; return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function hasJavaScriptFileExtension(fileName) { - return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function tryExtractTypeScriptExtension(fileName) { return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } @@ -7002,12 +7184,6 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !ts.isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); - } - ts.convertToRelativePath = convertToRelativePath; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { @@ -7108,7 +7284,7 @@ var ts; } ts.formatSyntaxKind = formatSyntaxKind; function movePos(pos, value) { - return positionIsSynthesized(pos) ? -1 : pos + value; + return ts.positionIsSynthesized(pos) ? -1 : pos + value; } ts.movePos = movePos; function createRange(pos, end) { @@ -7177,7 +7353,7 @@ var ts; } ts.positionsAreOnSameLine = positionsAreOnSameLine; function getStartPositionOfRange(range, sourceFile) { - return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); } ts.getStartPositionOfRange = getStartPositionOfRange; function collectExternalModuleInfo(sourceFile, resolver) { @@ -7277,15 +7453,16 @@ var ts; return 11 <= kind && kind <= 14; } ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isTemplateLiteralFragmentKind(kind) { - return kind === 12 - || kind === 13 + function isTemplateHead(node) { + return node.kind === 12; + } + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 13 || kind === 14; } - function isTemplateLiteralFragment(node) { - return isTemplateLiteralFragmentKind(node.kind); - } - ts.isTemplateLiteralFragment = isTemplateLiteralFragment; + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; function isIdentifier(node) { return node.kind === 69; } @@ -7424,12 +7601,12 @@ var ts; return node.kind === 174; } ts.isCallExpression = isCallExpression; - function isTemplate(node) { + function isTemplateLiteral(node) { var kind = node.kind; return kind === 189 || kind === 11; } - ts.isTemplate = isTemplate; + ts.isTemplateLiteral = isTemplateLiteral; function isSpreadElementExpression(node) { return node.kind === 191; } @@ -7995,7 +8172,7 @@ var ts; ts.createSynthesizedNodeArray = createSynthesizedNodeArray; function getSynthesizedClone(node) { var clone = createNode(node.kind, undefined, node.flags); - clone.original = node; + setOriginalNode(clone, node); for (var key in node) { if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { continue; @@ -8027,7 +8204,7 @@ var ts; node.text = value; return node; } - else { + else if (value) { var node = createNode(9, location, undefined); node.textSourceNode = value; node.text = value.text; @@ -8314,7 +8491,7 @@ var ts; function createPropertyAccess(expression, name, location, flags) { var node = createNode(172, location, flags); node.expression = parenthesizeForAccess(expression); - node.emitFlags = 1048576; + (node.emitNode || (node.emitNode = {})).flags |= 1048576; node.name = typeof name === "string" ? createIdentifier(name) : name; return node; } @@ -8322,7 +8499,7 @@ var ts; function updatePropertyAccess(node, expression, name) { if (node.expression !== expression || node.name !== name) { var propertyAccess = createPropertyAccess(expression, name, node, node.flags); - propertyAccess.emitFlags = node.emitFlags; + (propertyAccess.emitNode || (propertyAccess.emitNode = {})).flags = getEmitFlags(node); return updateNode(propertyAccess, node); } return node; @@ -8426,7 +8603,7 @@ var ts; node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken || createNode(34); + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(34); node.body = parenthesizeConciseBody(body); return node; } @@ -8519,7 +8696,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right, location) { - var operatorToken = typeof operator === "number" ? createSynthesizedNode(operator) : operator; + var operatorToken = typeof operator === "number" ? createToken(operator) : operator; var operatorKind = operatorToken.kind; var node = createNode(187, location); node.left = parenthesizeBinaryOperand(operatorKind, left, true, undefined); @@ -9419,13 +9596,13 @@ var ts; } else { var expression = ts.isIdentifier(memberName) ? createPropertyAccess(target, memberName, location) : createElementAccess(target, memberName, location); - expression.emitFlags |= 2048; + (expression.emitNode || (expression.emitNode = {})).flags |= 2048; return expression; } } ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; function createRestParameter(name) { - return createParameterDeclaration(undefined, undefined, createSynthesizedNode(22), name, undefined, undefined, undefined); + return createParameterDeclaration(undefined, undefined, createToken(22), name, undefined, undefined, undefined); } ts.createRestParameter = createRestParameter; function createFunctionCall(func, thisArg, argumentsList, location) { @@ -9539,8 +9716,8 @@ var ts; } ts.createDecorateHelper = createDecorateHelper; function createAwaiterHelper(externalHelpersModuleName, hasLexicalArguments, promiseConstructor, body) { - var generatorFunc = createFunctionExpression(createNode(37), undefined, undefined, [], undefined, body); - generatorFunc.emitFlags |= 2097152; + var generatorFunc = createFunctionExpression(createToken(37), undefined, undefined, [], undefined, body); + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 2097152; return createCall(createHelperName(externalHelpersModuleName, "__awaiter"), undefined, [ createThis(), hasLexicalArguments ? createIdentifier("arguments") : createVoidZero(), @@ -9767,7 +9944,7 @@ var ts; target.push(startOnNewLine(createStatement(createLiteral("use strict")))); foundUseStrict = true; } - if (statement.emitFlags & 8388608) { + if (getEmitFlags(statement) & 8388608) { target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { @@ -9779,6 +9956,28 @@ var ts; return statementOffset; } ts.addPrologueDirectives = addPrologueDirectives; + function ensureUseStrict(node) { + var foundUseStrict = false; + for (var _i = 0, _a = node.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + break; + } + } + else { + break; + } + } + if (!foundUseStrict) { + var statements = []; + statements.push(startOnNewLine(createStatement(createLiteral("use strict")))); + return updateSourceFileNode(node, statements.concat(node.statements)); + } + return node; + } + ts.ensureUseStrict = ensureUseStrict; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = skipPartiallyEmittedExpressions(operand); if (skipped.kind === 178) { @@ -10018,17 +10217,112 @@ var ts; function setOriginalNode(node, original) { node.original = original; if (original) { - var emitFlags = original.emitFlags, commentRange = original.commentRange, sourceMapRange = original.sourceMapRange; - if (emitFlags) - node.emitFlags = emitFlags; - if (commentRange) - node.commentRange = commentRange; - if (sourceMapRange) - node.sourceMapRange = sourceMapRange; + var emitNode = original.emitNode; + if (emitNode) + node.emitNode = mergeEmitNode(emitNode, node.emitNode); } return node; } ts.setOriginalNode = setOriginalNode; + function mergeEmitNode(sourceEmitNode, destEmitNode) { + var flags = sourceEmitNode.flags, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges; + if (!destEmitNode && (flags || commentRange || sourceMapRange || tokenSourceMapRanges)) + destEmitNode = {}; + if (flags) + destEmitNode.flags = flags; + if (commentRange) + destEmitNode.commentRange = commentRange; + if (sourceMapRange) + destEmitNode.sourceMapRange = sourceMapRange; + if (tokenSourceMapRanges) + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + return destEmitNode; + } + function mergeTokenSourceMapRanges(sourceRanges, destRanges) { + if (!destRanges) + destRanges = ts.createMap(); + ts.copyProperties(sourceRanges, destRanges); + return destRanges; + } + function disposeEmitNodes(sourceFile) { + sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile)); + var emitNode = sourceFile && sourceFile.emitNode; + var annotatedNodes = emitNode && emitNode.annotatedNodes; + if (annotatedNodes) { + for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) { + var node = annotatedNodes_1[_i]; + node.emitNode = undefined; + } + } + } + ts.disposeEmitNodes = disposeEmitNodes; + function getOrCreateEmitNode(node) { + if (!node.emitNode) { + if (ts.isParseTreeNode(node)) { + if (node.kind === 256) { + return node.emitNode = { annotatedNodes: [node] }; + } + var sourceFile = ts.getSourceFileOfNode(node); + getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); + } + node.emitNode = {}; + } + return node.emitNode; + } + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags; + } + ts.getEmitFlags = getEmitFlags; + function setEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).flags = emitFlags; + return node; + } + ts.setEmitFlags = setEmitFlags; + function setSourceMapRange(node, range) { + getOrCreateEmitNode(node).sourceMapRange = range; + return node; + } + ts.setSourceMapRange = setSourceMapRange; + function setTokenSourceMapRange(node, token, range) { + var emitNode = getOrCreateEmitNode(node); + var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = ts.createMap()); + tokenSourceMapRanges[token] = range; + return node; + } + ts.setTokenSourceMapRange = setTokenSourceMapRange; + function setCommentRange(node, range) { + getOrCreateEmitNode(node).commentRange = range; + return node; + } + ts.setCommentRange = setCommentRange; + function getCommentRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.commentRange) || node; + } + ts.getCommentRange = getCommentRange; + function getSourceMapRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.sourceMapRange) || node; + } + ts.getSourceMapRange = getSourceMapRange; + function getTokenSourceMapRange(node, token) { + var emitNode = node.emitNode; + var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; + return tokenSourceMapRanges && tokenSourceMapRanges[token]; + } + ts.getTokenSourceMapRange = getTokenSourceMapRange; + function getConstantValue(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.constantValue; + } + ts.getConstantValue = getConstantValue; + function setConstantValue(node, value) { + var emitNode = getOrCreateEmitNode(node); + emitNode.constantValue = value; + return node; + } + ts.setConstantValue = setConstantValue; function setTextRange(node, location) { if (location) { node.pos = location.pos; @@ -11138,7 +11432,7 @@ var ts; case 16: return token() === 18 || token() === 20; case 18: - return token() === 27 || token() === 17; + return token() !== 24; case 20: return token() === 15 || token() === 16; case 13: @@ -11466,7 +11760,7 @@ var ts; } function parseTemplateExpression() { var template = createNode(189); - template.head = parseTemplateLiteralFragment(); + template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 12, "Template head has wrong token kind"); var templateSpans = createNodeArray(); do { @@ -11482,7 +11776,7 @@ var ts; var literal; if (token() === 16) { reScanTemplateToken(); - literal = parseTemplateLiteralFragment(); + literal = parseTemplateMiddleOrTemplateTail(); } else { literal = parseExpectedToken(14, false, ts.Diagnostics._0_expected, ts.tokenToString(16)); @@ -11493,8 +11787,15 @@ var ts; function parseLiteralNode(internName) { return parseLiteralLikeNode(token(), internName); } - function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token(), false); + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token(), false); + ts.Debug.assert(fragment.kind === 12, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token(), false); + ts.Debug.assert(fragment.kind === 13 || fragment.kind === 14, "Template fragment has wrong token kind"); + return fragment; } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -13842,7 +14143,7 @@ var ts; parseExpected(56); node.type = parseType(); parseSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseEnumMember() { var node = createNode(255, scanner.getStartPos()); @@ -15277,7 +15578,7 @@ var ts; file = f; options = opts; languageVersion = ts.getEmitScriptTarget(options); - inStrictMode = !!file.externalModuleIndicator; + inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; skipTransformFlagAggregation = ts.isDeclarationFile(file); @@ -15307,6 +15608,14 @@ var ts; subtreeTransformFlags = 0; } return bindSourceFile; + function bindInStrictMode(file, opts) { + if (opts.alwaysStrict && !ts.isDeclarationFile(file)) { + return true; + } + else { + return !!file.externalModuleIndicator; + } + } function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); @@ -15425,11 +15734,17 @@ var ts; var message_1 = symbol.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (ts.hasModifier(declaration, 512)) { + if (symbol.declarations && symbol.declarations.length) { + if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } - }); + else { + if (symbol.declarations && symbol.declarations.length && + (isDefaultExport || (node.kind === 235 && !node.isExportEquals))) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + } + } ts.forEach(symbol.declarations, function (declaration) { file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); }); @@ -15494,7 +15809,7 @@ var ts; } else { currentFlow = { flags: 2 }; - if (containerFlags & 16) { + if (containerFlags & (16 | 128)) { currentFlow.container = node; } currentReturnTarget = undefined; @@ -15949,7 +16264,9 @@ var ts; currentFlow = preTryFlow; bind(node.finallyBlock); } - currentFlow = finishFlowLabel(postFinallyLabel); + if (!node.finallyBlock || !(currentFlow.flags & 1)) { + currentFlow = finishFlowLabel(postFinallyLabel); + } } function bindSwitchStatement(node) { var postSwitchLabel = createBranchLabel(); @@ -16082,7 +16399,7 @@ var ts; } else { ts.forEachChild(node, bind); - if (node.operator === 57 || node.operator === 42) { + if (node.operator === 41 || node.operator === 42) { bindAssignmentTargetFlow(node.operand); } } @@ -16181,9 +16498,12 @@ var ts; return 1 | 32; case 256: return 1 | 4 | 32; + case 147: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 | 4 | 32 | 8 | 128; + } case 148: case 220: - case 147: case 146: case 149: case 150: @@ -16715,7 +17035,7 @@ var ts; var flags = node.kind === 235 && ts.exportAssignmentIsAlias(node) ? 8388608 : 4; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 | 8388608); + declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 | 8388608 | 32 | 16); } } function bindNamespaceExportDeclaration(node) { @@ -16912,6 +17232,9 @@ var ts; emitFlags |= 2048; } } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } return ts.hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); @@ -17050,8 +17373,7 @@ var ts; if (node.questionToken) { transformFlags |= 3; } - if (subtreeFlags & 2048 - || (name && ts.isIdentifier(name) && name.originalKeywordKind === 97)) { + if (subtreeFlags & 2048 || ts.isThisIdentifier(name)) { transformFlags |= 3; } if (modifierFlags & 92) { @@ -17153,7 +17475,7 @@ var ts; || (subtreeFlags & 2048)) { transformFlags |= 3; } - if (asteriskToken && node.emitFlags & 2097152) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152) { transformFlags |= 1536; } node.transformFlags = transformFlags | 536870912; @@ -17198,7 +17520,7 @@ var ts; if (subtreeFlags & 81920) { transformFlags |= 192; } - if (asteriskToken && node.emitFlags & 2097152) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152) { transformFlags |= 1536; } } @@ -17215,7 +17537,7 @@ var ts; if (subtreeFlags & 81920) { transformFlags |= 192; } - if (asteriskToken && node.emitFlags & 2097152) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152) { transformFlags |= 1536; } node.transformFlags = transformFlags | 536870912; @@ -17456,6 +17778,560 @@ var ts; } })(ts || (ts = {})); var ts; +(function (ts) { + function trace(host, message) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; + } + ts.createResolvedModule = createResolvedModule; + function moduleHasNonRelativeName(moduleName) { + return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); + } + function tryReadTypesSection(packageJsonPath, baseDirectory, state) { + var jsonContent = readJson(packageJsonPath, state.host); + function tryReadFromField(fieldName) { + if (ts.hasProperty(jsonContent, fieldName)) { + var typesFile = jsonContent[fieldName]; + if (typeof typesFile === "string") { + var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); + } + return typesFilePath_1; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); + } + } + } + } + var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); + if (typesFilePath) { + return typesFilePath; + } + if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); + } + var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); + return mainFilePath; + } + return undefined; + } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + return {}; + } + } + var typeReferenceExtensions = [".d.ts"]; + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + return currentDirectory !== undefined && getDefaultTypeRoots(currentDirectory, host); + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + } + var typeRoots; + while (true) { + var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + var parent_7 = ts.getDirectoryPath(currentDirectory); + if (parent_7 === currentDirectory) { + break; + } + currentDirectory = parent_7; + } + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + var traceEnabled = isTraceEnabled(options, host); + var moduleResolutionState = { + compilerOptions: options, + host: host, + skipTsx: true, + traceEnabled: traceEnabled + }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === undefined) { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + } + } + else { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + } + } + } + var failedLookupLocations = []; + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + var primarySearchPaths = typeRoots; + for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { + var typeRoot = primarySearchPaths_1[_i]; + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); + if (resolvedFile_1) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); + } + return { + resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, + failedLookupLocations: failedLookupLocations + }; + } + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + var resolvedFile; + var initialLocationForSecondaryLookup; + if (containingFile) { + initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); + } + if (initialLocationForSecondaryLookup !== undefined) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, false); + if (traceEnabled) { + if (resolvedFile) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); + } + else { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + return { + resolvedTypeReferenceDirective: resolvedFile + ? { primary: false, resolvedFileName: resolvedFile } + : undefined, + failedLookupLocations: failedLookupLocations + }; + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + function getAutomaticTypeDirectiveNames(options, host) { + if (options.types) { + return options.types; + } + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + result.push(ts.getBaseFileName(normalized)); + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); + } + else { + return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); + } + } + function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { + var subst = _a[_i]; + var path = matchedStar ? subst.replace("*", matchedStar) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + } + return undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); + var isExternalLibraryImport = false; + if (!resolvedFileName) { + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state, false); + isExternalLibraryImport = resolvedFileName !== undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); + } + } + if (resolvedFileName && host.realpath) { + var originalFileName = resolvedFileName; + resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); + } + } + return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + if (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); + } + } + function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + return ts.forEach(extensions, function (ext) { + return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); + }); + } + function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + failedLookupLocation.push(fileName); + return undefined; + } + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { + var packageJsonPath = pathToPackageJson(candidate); + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); + if (typesFile) { + var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); + var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || + tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); + if (result) { + return result; + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); + } + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + failedLookupLocation.push(packageJsonPath); + } + return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); + } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } + function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); + var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + } + function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, false); + } + ts.loadModuleFromNodeModules = loadModuleFromNodeModules; + function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, false, true); + } + function loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, typesOnly) { + directory = ts.normalizeSlashes(directory); + while (true) { + var baseName = ts.getBaseFileName(directory); + if (baseName !== "node_modules") { + var packageResult = void 0; + if (!typesOnly) { + packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); + if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { + return packageResult; + } + } + var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); + if (typesResult || packageResult) { + return typesResult || packageResult; + } + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory || checkOneLevel) { + break; + } + directory = parentPath; + } + return undefined; + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; + var failedLookupLocations = []; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, false, failedLookupLocations); + } + var referencedSourceFile; + if (moduleHasNonRelativeName(moduleName)) { + referencedSourceFile = referencedSourceFile = loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) || + loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); + } + return referencedSourceFile + ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } + : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + } + ts.classicNameResolver = classicNameResolver; + function loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) { + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); + if (referencedSourceFile) { + return referencedSourceFile; + } + var parentPath = ts.getDirectoryPath(containingDirectory); + if (parentPath === containingDirectory) { + return undefined; + } + containingDirectory = parentPath; + } + } +})(ts || (ts = {})); +var ts; (function (ts) { var ambientModuleSymbolRegex = /^".+"$/; var nextSymbolId = 1; @@ -17551,6 +18427,7 @@ var ts; var unknownSymbol = createSymbol(4 | 67108864, "unknown"); var resolvingSymbol = createSymbol(67108864, "__resolving__"); var anyType = createIntrinsicType(1, "any"); + var autoType = createIntrinsicType(1, "any"); var unknownType = createIntrinsicType(1, "unknown"); var undefinedType = createIntrinsicType(2048, "undefined"); var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 33554432, "undefined"); @@ -18108,7 +18985,7 @@ var ts; if (result && isInExternalModule && (meaning & 107455) === 107455) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 228) { - error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name); } } } @@ -18526,6 +19403,7 @@ var ts; } function getExportsForModule(moduleSymbol) { var visitedSymbols = []; + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || moduleSymbol.exports; function visit(symbol) { if (!(symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol))) { @@ -19010,9 +19888,9 @@ var ts; var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent_7) { - walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), false); + var parent_8 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_8) { + walkSymbol(parent_8, getQualifiedLeftMeaning(meaning), false); } } if (accessibleSymbolChain) { @@ -19047,7 +19925,7 @@ var ts; ? "any" : type.intrinsicName); } - else if (type.flags & 268435456) { + else if (type.flags & 16384 && type.isThisType) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } @@ -19064,7 +19942,7 @@ var ts; else if (type.flags & (32768 | 65536 | 16 | 16384)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } - else if (!(flags & 512) && type.flags & (2097152 | 1572864) && type.aliasSymbol && + else if (!(flags & 512) && ((type.flags & 2097152 && !type.target) || type.flags & 1572864) && type.aliasSymbol && isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); @@ -19134,12 +20012,12 @@ var ts; var length_1 = outerTypeParameters.length; while (i < length_1) { var start = i; - var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_9 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_9); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_8, typeArguments, start, i, flags); + writeSymbolTypeReference(parent_9, typeArguments, start, i, flags); writePunctuation(writer, 21); } } @@ -19528,12 +20406,12 @@ var ts; if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_9 = getDeclarationContainer(node); + var parent_10 = getDeclarationContainer(node); if (!(ts.getCombinedModifierFlags(node) & 1) && - !(node.kind !== 229 && parent_9.kind !== 256 && ts.isInAmbientContext(parent_9))) { - return isGlobalSourceFile(parent_9); + !(node.kind !== 229 && parent_10.kind !== 256 && ts.isInAmbientContext(parent_10))) { + return isGlobalSourceFile(parent_10); } - return isDeclarationVisible(parent_9); + return isDeclarationVisible(parent_10); case 145: case 144: case 149: @@ -19791,6 +20669,10 @@ var ts; } return undefined; } + function isAutoVariableInitializer(initializer) { + var expr = initializer && ts.skipParentheses(initializer); + return !expr || expr.kind === 93 || expr.kind === 69 && getResolvedSymbol(expr) === undefinedSymbol; + } function addOptionality(type, optional) { return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; } @@ -19813,6 +20695,11 @@ var ts; if (declaration.type) { return addOptionality(getTypeFromTypeNode(declaration.type), declaration.questionToken && includeOptionality); } + if (declaration.kind === 218 && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedNodeFlags(declaration) & 2) && !(ts.getCombinedModifierFlags(declaration) & 1) && + !ts.isInAmbientContext(declaration) && isAutoVariableInitializer(declaration.initializer)) { + return autoType; + } if (declaration.kind === 142) { var func = declaration.parent; if (func.kind === 150 && !ts.hasDynamicName(func)) { @@ -19884,7 +20771,7 @@ var ts; result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 536870912; + result.isObjectLiteralPatternWithComputedProperties = true; } return result; } @@ -20353,7 +21240,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); + type.thisType = createType(16384); + type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -20886,13 +21774,24 @@ var ts; var current = _a[_i]; for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { var prop = _c[_b]; - getPropertyOfUnionOrIntersectionType(type, prop.name); + getUnionOrIntersectionProperty(type, prop.name); } if (type.flags & 524288) { break; } } - return type.resolvedProperties ? symbolsToArray(type.resolvedProperties) : emptyArray; + var props = type.resolvedProperties; + if (props) { + var result = []; + for (var key in props) { + var prop = props[key]; + if (!(prop.flags & 268435456 && prop.isPartial)) { + result.push(prop); + } + } + return result; + } + return emptyArray; } function getPropertiesOfType(type) { type = getApparentType(type); @@ -20931,6 +21830,7 @@ var ts; var props; var commonFlags = (containingType.flags & 1048576) ? 536870912 : 0; var isReadonly = false; + var isPartial = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); @@ -20949,20 +21849,20 @@ var ts; } } else if (containingType.flags & 524288) { - return undefined; + isPartial = true; } } } if (!props) { return undefined; } - if (props.length === 1) { + if (props.length === 1 && !isPartial) { return props[0]; } var propTypes = []; var declarations = []; var commonType = undefined; - var hasCommonType = true; + var hasNonUniformType = false; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { @@ -20973,22 +21873,20 @@ var ts; commonType = type; } else if (type !== commonType) { - hasCommonType = false; + hasNonUniformType = true; } - propTypes.push(getTypeOfSymbol(prop)); + propTypes.push(type); } - var result = createSymbol(4 | - 67108864 | - 268435456 | - commonFlags, name); + var result = createSymbol(4 | 67108864 | 268435456 | commonFlags, name); result.containingType = containingType; - result.hasCommonType = hasCommonType; + result.hasNonUniformType = hasNonUniformType; + result.isPartial = isPartial; result.declarations = declarations; result.isReadonly = isReadonly; result.type = containingType.flags & 524288 ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } - function getPropertyOfUnionOrIntersectionType(type, name) { + function getUnionOrIntersectionProperty(type, name) { var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); var property = properties[name]; if (!property) { @@ -20999,6 +21897,10 @@ var ts; } return property; } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + return property && !(property.flags & 268435456 && property.isPartial) ? property : undefined; + } function getPropertyOfType(type, name) { type = getApparentType(type); if (type.flags & 2588672) { @@ -21371,7 +22273,7 @@ var ts; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 268435456) && type.flags & 16384 && !ts.contains(checked, type)) { + while (type && type.flags & 16384 && !(type.isThisType) && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -21655,7 +22557,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); + type.thisType = createType(16384); + type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; type.declaredCallSignatures = emptyArray; @@ -21754,7 +22657,24 @@ var ts; } return false; } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 256) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 256) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } var i = types.length; while (i > 0) { i--; @@ -22729,7 +23649,8 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 536870912) && maybeTypeOfKind(target, 2588672)) { + if (maybeTypeOfKind(target, 2588672) && + (!(target.flags & 2588672) || !target.isObjectLiteralPatternWithComputedProperties)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -23934,17 +24855,10 @@ var ts; } function isDiscriminantProperty(type, name) { if (type && type.flags & 524288) { - var prop = getPropertyOfType(type, name); - if (!prop) { - var filteredType = getTypeWithFacts(type, 4194304); - if (filteredType !== type && filteredType.flags & 524288) { - prop = getPropertyOfType(filteredType, name); - } - } + var prop = getUnionOrIntersectionProperty(type, name); if (prop && prop.flags & 268435456) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !prop.hasCommonType && - isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = prop.hasNonUniformType && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -24221,6 +25135,23 @@ var ts; } return f(type) ? type : neverType; } + function mapType(type, f) { + return type.flags & 524288 ? getUnionType(ts.map(type.types, f)) : f(type); + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 2 ? extractTypesOfKind(typeWithLiterals, 2 | 32) : + t.flags & 4 ? extractTypesOfKind(typeWithLiterals, 4 | 64) : + t; + }); + } + return typeWithPrimitives; + } function isIncomplete(flowType) { return flowType.flags === 0; } @@ -24235,7 +25166,9 @@ var ts; if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048); + var initialType = assumeInitialized ? declaredType : + declaredType === autoType ? undefinedType : + includeFalsyTypes(declaredType, 2048); var visitedFlowStart = visitedFlowCount; var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; @@ -24297,10 +25230,13 @@ var ts; function getTypeAtFlowAssignment(flow) { var node = flow.node; if (isMatchingReference(reference, node)) { - var isIncrementOrDecrement = node.parent.kind === 185 || node.parent.kind === 186; - return declaredType.flags & 524288 && !isIncrementOrDecrement ? - getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : - declaredType; + if (node.parent.kind === 185 || node.parent.kind === 186) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + return declaredType === autoType ? getBaseTypeOfLiteralType(getInitialOrAssignedType(node)) : + declaredType.flags & 524288 ? getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : + declaredType; } if (containsMatchingReference(reference, node)) { return declaredType; @@ -24486,12 +25422,12 @@ var ts; assumeTrue ? 16384 : 131072; return getTypeWithFacts(type, facts); } - if (type.flags & 2589191) { + if (type.flags & 2589185) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 ? type : narrowedType; + return narrowedType.flags & 8192 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -24529,7 +25465,8 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); + var caseType = discriminantType.flags & 8192 ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -24656,7 +25593,7 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpression(location) && !ts.isAssignmentTarget(location)) { + if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { var type = checkExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; @@ -24779,14 +25716,26 @@ var ts; var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; while (flowContainer !== declarationContainer && - (flowContainer.kind === 179 || flowContainer.kind === 180) && + (flowContainer.kind === 179 || + flowContainer.kind === 180 || + ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } - var assumeInitialized = !strictNullChecks || (type.flags & 1) !== 0 || isParameter || - isOuterVariable || ts.isInAmbientContext(declaration); + var assumeInitialized = isParameter || isOuterVariable || + type !== autoType && (!strictNullChecks || (type.flags & 1) !== 0) || + ts.isInAmbientContext(declaration); var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); - if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { + if (type === autoType) { + if (flowType === autoType) { + if (compilerOptions.noImplicitAny) { + error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol)); + error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(anyType)); + } + return anyType; + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); return type; } @@ -24871,7 +25820,7 @@ var ts; } } function findFirstSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return n; } else if (ts.isFunctionLike(n)) { @@ -24936,7 +25885,7 @@ var ts; captureLexicalThis(node, container); } if (ts.isFunctionLike(container) && - (!isInParameterInitializerBeforeContainingFunction(node) || getFunctionLikeThisParameter(container))) { + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { if (container.kind === 179 && ts.isInJavaScriptFile(container.parent) && ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { @@ -25596,7 +26545,8 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 536870912)) { + else if (contextualTypeHasPattern && + !(contextualType.flags & 2588672 && contextualType.isObjectLiteralPatternWithComputedProperties)) { var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { prop.flags |= impliedProp.flags & 536870912; @@ -25647,7 +26597,10 @@ var ts; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216; - result.flags |= 8388608 | 67108864 | freshObjectLiteralFlag | (typeFlags & 234881024) | (patternWithComputedProperties ? 536870912 : 0); + result.flags |= 8388608 | 67108864 | freshObjectLiteralFlag | (typeFlags & 234881024); + if (patternWithComputedProperties) { + result.isObjectLiteralPatternWithComputedProperties = true; + } if (inDestructuringPattern) { result.pattern = node; } @@ -26042,7 +26995,7 @@ var ts; if (flags & 32) { return true; } - if (type.flags & 268435456) { + if (type.flags & 16384 && type.isThisType) { type = getConstraintOfTypeParameter(type); } if (!(getTargetType(type).flags & (32768 | 65536) && hasBaseType(type, enclosingClass))) { @@ -26083,7 +27036,7 @@ var ts; var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 268435456 ? apparentType : type); + reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); } return unknownType; } @@ -26308,19 +27261,19 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_10 = signature.declaration && signature.declaration.parent; + var parent_11 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_10 === lastParent) { + if (lastParent && parent_11 === lastParent) { index++; } else { - lastParent = parent_10; + lastParent = parent_11; index = cutoffIndex; } } else { index = cutoffIndex = result.length; - lastParent = parent_10; + lastParent = parent_11; } lastSymbol = symbol; if (signature.hasLiteralTypes) { @@ -27223,7 +28176,9 @@ var ts; if (!contextualSignature) { reportErrorsFromWidening(func, type); } - if (isUnitType(type) && !(contextualSignature && isLiteralContextualType(getReturnTypeOfSignature(contextualSignature)))) { + if (isUnitType(type) && + !(contextualSignature && + isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { type = getWidenedLiteralType(type); } var widenedType = getWidenedType(type); @@ -27373,7 +28328,7 @@ var ts; } } } - if (produceDiagnostics && node.kind !== 147 && node.kind !== 146) { + if (produceDiagnostics && node.kind !== 147) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } @@ -28316,9 +29271,9 @@ var ts; case 156: case 147: case 146: - var parent_11 = node.parent; - if (node === parent_11.type) { - return parent_11; + var parent_12 = node.parent; + if (node === parent_12.type) { + return parent_12; } } } @@ -28529,7 +29484,7 @@ var ts; return n.name && containsSuperCall(n.name); } function containsSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return true; } else if (ts.isFunctionLike(n)) { @@ -28555,6 +29510,7 @@ var ts; } var containingClassDecl = node.parent; if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); if (superCall) { @@ -28568,7 +29524,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 202 && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 202 && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -29271,14 +30227,14 @@ var ts; } function checkUnusedLocalsAndParameters(node) { if (node.parent.kind !== 222 && noUnusedIdentifiers && !ts.isInAmbientContext(node)) { - var _loop_1 = function(key) { + var _loop_1 = function (key) { var local = node.locals[key]; if (!local.isReferenced) { if (local.valueDeclaration && local.valueDeclaration.kind === 142) { var parameter = local.valueDeclaration; if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && - !parameterIsThisKeyword(parameter) && + !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(parameter)) { error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } @@ -29293,9 +30249,6 @@ var ts; } } } - function parameterIsThisKeyword(parameter) { - return parameter.name && parameter.name.originalKeywordKind === 97; - } function parameterNameStartsWithUnderscore(parameter) { return parameter.name && parameter.name.kind === 69 && parameter.name.text.charCodeAt(0) === 95; } @@ -29433,6 +30386,9 @@ var ts; } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + if (modulekind >= ts.ModuleKind.ES6) { + return; + } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } @@ -29536,6 +30492,9 @@ var ts; } } } + function convertAutoToAny(type) { + return type === autoType ? anyType : type; + } function checkVariableLikeDeclaration(node) { checkDecorators(node); checkSourceElement(node.type); @@ -29549,12 +30508,12 @@ var ts; if (node.propertyName && node.propertyName.kind === 140) { checkComputedPropertyName(node.propertyName); } - var parent_12 = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent_12); + var parent_13 = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent_13); var name_21 = node.propertyName || node.name; var property = getPropertyOfType(parentType, getTextOfPropertyName(name_21)); - if (parent_12.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property); + if (parent_13.initializer && property && getParentOfSymbol(property)) { + checkClassPropertyAccess(parent_13, parent_13.initializer, parentType, property); } } if (ts.isBindingPattern(node.name)) { @@ -29572,7 +30531,7 @@ var ts; return; } var symbol = getSymbolOfNode(node); - var type = getTypeOfVariableOrParameterOrProperty(symbol); + var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); if (node === symbol.valueDeclaration) { if (node.initializer && node.parent.parent.kind !== 207) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); @@ -29580,7 +30539,7 @@ var ts; } } else { - var declarationType = getWidenedTypeForVariableLikeDeclaration(node); + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); } @@ -29955,7 +30914,12 @@ var ts; } } checkExpression(node.expression); - error(node.expression, ts.Diagnostics.All_symbols_within_a_with_block_will_be_resolved_to_any); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } } function checkSwitchStatement(node) { checkGrammarStatementInAmbientContext(node); @@ -30674,9 +31638,11 @@ var ts; grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (ts.isIdentifier(node.name)) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); if (symbol.flags & 512 @@ -30915,9 +31881,11 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 256 && node.parent.kind !== 226 && node.parent.kind !== 225) { - return grammarErrorOnFirstToken(node, errorMessage); + var isInAppropriateContext = node.parent.kind === 256 || node.parent.kind === 226 || node.parent.kind === 225; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); } + return !isInAppropriateContext; } function checkExportSpecifier(node) { checkAliasSymbol(node); @@ -31004,7 +31972,8 @@ var ts; links.exportsChecked = true; } function isNotOverload(declaration) { - return declaration.kind !== 220 || !!declaration.body; + return (declaration.kind !== 220 && declaration.kind !== 147) || + !!declaration.body; } } function checkSourceElement(node) { @@ -31489,6 +32458,9 @@ var ts; node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } + if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) { + return resolveExternalModuleName(node, node); + } case 8: if (node.parent.kind === 173 && node.parent.argumentExpression === node) { var objectType = checkExpression(node.parent.expression); @@ -31912,9 +32884,9 @@ var ts; } var location = reference; if (startInDeclarationContainer) { - var parent_13 = reference.parent; - if (ts.isDeclaration(parent_13) && reference === parent_13.name) { - location = getDeclarationContainer(parent_13); + var parent_14 = reference.parent; + if (ts.isDeclaration(parent_14) && reference === parent_14.name) { + location = getDeclarationContainer(parent_14); } } return resolveName(location, reference.text, 107455 | 1048576 | 8388608, undefined, undefined); @@ -32023,9 +32995,9 @@ var ts; } var current = symbol; while (true) { - var parent_14 = getParentOfSymbol(current); - if (parent_14) { - current = parent_14; + var parent_15 = getParentOfSymbol(current); + if (parent_15) { + current = parent_15; } else { break; @@ -32585,8 +33557,8 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_2 = args; _i < args_2.length; _i++) { - var arg = args_2[_i]; + for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { + var arg = args_4[_i]; if (arg.kind === 193) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } @@ -32695,8 +33667,7 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; var name_24 = prop.name; - if (prop.kind === 193 || - name_24.kind === 140) { + if (name_24.kind === 140) { checkGrammarComputedPropertyName(name_24); } if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) { @@ -32852,17 +33823,8 @@ var ts; return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 149 ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 149 ? 1 : 2) && - accessor.parameters[0].name.kind === 69 && - accessor.parameters[0].name.originalKeywordKind === 97) { - return accessor.parameters[0]; - } - } - function getFunctionLikeThisParameter(func) { - if (func.parameters.length && - func.parameters[0].name.kind === 69 && - func.parameters[0].name.originalKeywordKind === 97) { - return func.parameters[0]; + if (accessor.parameters.length === (accessor.kind === 149 ? 1 : 2)) { + return ts.getThisParameter(accessor); } } function checkGrammarForNonSymbolComputedProperty(node, message) { @@ -33222,8 +34184,7 @@ var ts; { name: "name", test: ts.isPropertyName }, { name: "initializer", test: ts.isExpression, optional: true, parenthesize: ts.parenthesizeExpressionForList } ], - _a - )); + _a)); function reduceNode(node, f, initial) { return node ? f(initial, node) : initial; } @@ -33697,7 +34658,7 @@ var ts; case 175: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); case 176: - return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplate)); + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); case 178: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); case 179: @@ -33721,7 +34682,7 @@ var ts; case 188: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 189: - return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateLiteralFragment), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); case 190: return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); case 191: @@ -33731,7 +34692,7 @@ var ts; case 194: return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); case 197: - return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateLiteralFragment)); + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); case 199: return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); case 200: @@ -33955,10 +34916,10 @@ var ts; ? function (message) { return Debug.assert(false, message || "Node not optional."); } : function (message) { }; Debug.failBadSyntaxKind = Debug.shouldAssert(1) - ? function (node, message) { return Debug.assert(false, message || "Unexpected node.", function () { return ("Node " + ts.formatSyntaxKind(node.kind) + " was unexpected."); }); } + ? function (node, message) { return Debug.assert(false, message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " was unexpected."; }); } : function (node, message) { }; Debug.assertNode = Debug.shouldAssert(1) - ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return ("Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."); }); } + ? function (node, test, message) { return Debug.assert(test === undefined || test(node), message || "Unexpected node.", function () { return "Node " + ts.formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }); } : function (node, test, message) { }; function getFunctionName(func) { if (typeof func !== "function") { @@ -34006,7 +34967,7 @@ var ts; return expression; function emitAssignment(name, value, location) { var expression = ts.createAssignment(name, value, location); - context.setNodeEmitFlags(expression, 2048); + ts.setEmitFlags(expression, 2048); ts.aggregateTransformFlags(expression); expressions.push(expression); } @@ -34023,7 +34984,7 @@ var ts; return declarations; function emitAssignment(name, value, location) { var declaration = ts.createVariableDeclaration(name, undefined, value, location); - context.setNodeEmitFlags(declaration, 2048); + ts.setEmitFlags(declaration, 2048); ts.aggregateTransformFlags(declaration); declarations.push(declaration); } @@ -34047,7 +35008,7 @@ var ts; } var declaration = ts.createVariableDeclaration(name, undefined, value, location); declaration.original = original; - context.setNodeEmitFlags(declaration, 2048); + ts.setEmitFlags(declaration, 2048); declarations.push(declaration); ts.aggregateTransformFlags(declaration); } @@ -34087,7 +35048,7 @@ var ts; function emitPendingAssignment(name, value, location, original) { var expression = ts.createAssignment(name, value, location); expression.original = original; - context.setNodeEmitFlags(expression, 2048); + ts.setEmitFlags(expression, 2048); pendingAssignments.push(expression); return expression; } @@ -34132,8 +35093,8 @@ var ts; } else { var name_26 = ts.getMutableClone(target); - context.setSourceMapRange(name_26, target); - context.setCommentRange(name_26, target); + ts.setSourceMapRange(name_26, target); + ts.setCommentRange(name_26, target); emitAssignment(name_26, value, location, undefined); } } @@ -34248,7 +35209,7 @@ var ts; (function (ts) { var USE_NEW_TYPE_METADATA_FORMAT = false; function transformTypeScript(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, setCommentRange = context.setCommentRange, setSourceMapRange = context.setSourceMapRange, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -34257,10 +35218,13 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; + context.enableSubstitution(172); + context.enableSubstitution(173); var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; var currentScope; + var currentScopeFirstDeclarationsOfName; var currentSourceFileExternalHelpersModuleName; var enabledSubstitutions; var classAliases; @@ -34268,12 +35232,19 @@ var ts; var currentSuperContainer; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitNode(node, visitor, ts.isSourceFile); } function saveStateAndInvoke(node, f) { var savedCurrentScope = currentScope; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; onBeforeVisitNode(node); var visited = f(node); + if (currentScope !== savedCurrentScope) { + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + } currentScope = savedCurrentScope; return visited; } @@ -34427,11 +35398,22 @@ var ts; case 226: case 199: currentScope = node; + currentScopeFirstDeclarationsOfName = undefined; + break; + case 221: + case 220: + if (ts.hasModifier(node, 2)) { + break; + } + recordEmittedDeclarationInScope(node); break; } } function visitSourceFile(node) { currentSourceFile = node; + if (compilerOptions.alwaysStrict) { + node = ts.ensureUseStrict(node); + } if (node.flags & 31744 && compilerOptions.importHelpers && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { @@ -34453,7 +35435,7 @@ var ts; else { node = ts.visitEachChild(node, visitor, context); } - setNodeEmitFlags(node, 1 | node.emitFlags); + ts.setEmitFlags(node, 1 | ts.getEmitFlags(node)); return node; } function shouldEmitDecorateCallForClass(node) { @@ -34483,7 +35465,7 @@ var ts; var classDeclaration = ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), node); ts.setOriginalNode(classDeclaration, node); if (staticProperties.length > 0) { - setNodeEmitFlags(classDeclaration, 1024 | getNodeEmitFlags(classDeclaration)); + ts.setEmitFlags(classDeclaration, 1024 | ts.getEmitFlags(classDeclaration)); } statements.push(classDeclaration); } @@ -34525,7 +35507,7 @@ var ts; var transformedClassExpression = ts.createVariableStatement(undefined, ts.createLetDeclarationList([ ts.createVariableDeclaration(classAlias || declaredName, undefined, classExpression) ]), location); - setCommentRange(transformedClassExpression, node); + ts.setCommentRange(transformedClassExpression, node); statements.push(ts.setOriginalNode(transformedClassExpression, node)); if (classAlias) { statements.push(ts.setOriginalNode(ts.createVariableStatement(undefined, ts.createLetDeclarationList([ @@ -34546,7 +35528,7 @@ var ts; enableSubstitutionForClassAliases(); classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); } - setNodeEmitFlags(classExpression, 524288 | getNodeEmitFlags(classExpression)); + ts.setEmitFlags(classExpression, 524288 | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); ts.addRange(expressions, generateInitializedPropertyExpressions(node, staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); @@ -34607,7 +35589,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 202 && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 202 && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -34626,9 +35608,9 @@ var ts; ts.Debug.assert(ts.isIdentifier(node.name)); var name = node.name; var propertyName = ts.getMutableClone(name); - setNodeEmitFlags(propertyName, 49152 | 1536); + ts.setEmitFlags(propertyName, 49152 | 1536); var localName = ts.getMutableClone(name); - setNodeEmitFlags(localName, 49152); + ts.setEmitFlags(localName, 49152); return ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), propertyName, node.name), localName), ts.moveRangePos(node, -1))); } function getInitializedProperties(node, isStatic) { @@ -34649,8 +35631,8 @@ var ts; for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var property = properties_7[_i]; var statement = ts.createStatement(transformInitializedProperty(node, property, receiver)); - setSourceMapRange(statement, ts.moveRangePastModifiers(property)); - setCommentRange(statement, property); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); statements.push(statement); } } @@ -34660,8 +35642,8 @@ var ts; var property = properties_8[_i]; var expression = transformInitializedProperty(node, property, receiver); expression.startsOnNewLine = true; - setSourceMapRange(expression, ts.moveRangePastModifiers(property)); - setCommentRange(expression, property); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + ts.setCommentRange(expression, property); expressions.push(expression); } return expressions; @@ -34802,7 +35784,7 @@ var ts; : ts.createNull() : undefined; var helper = ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); - setNodeEmitFlags(helper, 49152); + ts.setEmitFlags(helper, 49152); return helper; } function addConstructorDecorationStatement(statements, node, decoratedClassAlias) { @@ -34820,12 +35802,12 @@ var ts; if (decoratedClassAlias) { var expression = ts.createAssignment(decoratedClassAlias, ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node))); var result = ts.createAssignment(getDeclarationName(node), expression, ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152); + ts.setEmitFlags(result, 49152); return result; } else { var result = ts.createAssignment(getDeclarationName(node), ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node)), ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152); + ts.setEmitFlags(result, 49152); return result; } } @@ -34839,7 +35821,7 @@ var ts; for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { var decorator = decorators_1[_i]; var helper = ts.createParamHelper(currentSourceFileExternalHelpersModuleName, transformDecorator(decorator), parameterOffset, decorator.expression); - setNodeEmitFlags(helper, 49152); + ts.setEmitFlags(helper, 49152); expressions.push(helper); } } @@ -35004,10 +35986,33 @@ var ts; : ts.createIdentifier("Symbol"); case 155: return serializeTypeReferenceNode(node); + case 163: + case 162: + { + var unionOrIntersection = node; + var serializedUnion = void 0; + for (var _i = 0, _a = unionOrIntersection.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var serializedIndividual = serializeTypeNode(typeNode); + if (serializedIndividual.kind !== 69) { + serializedUnion = undefined; + break; + } + if (serializedIndividual.text === "Object") { + return serializedIndividual; + } + if (serializedUnion && serializedUnion.text !== serializedIndividual.text) { + serializedUnion = undefined; + break; + } + serializedUnion = serializedIndividual; + } + if (serializedUnion) { + return serializedUnion; + } + } case 158: case 159: - case 162: - case 163: case 117: case 165: break; @@ -35128,8 +36133,8 @@ var ts; return undefined; } var method = ts.createMethod(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); - setCommentRange(method, node); - setSourceMapRange(method, ts.moveRangePastDecorators(node)); + ts.setCommentRange(method, node); + ts.setSourceMapRange(method, ts.moveRangePastDecorators(node)); ts.setOriginalNode(method, node); return method; } @@ -35141,8 +36146,8 @@ var ts; return undefined; } var accessor = ts.createGetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setCommentRange(accessor, node); + ts.setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); ts.setOriginalNode(accessor, node); return accessor; } @@ -35151,8 +36156,8 @@ var ts; return undefined; } var accessor = ts.createSetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setCommentRange(accessor, node); + ts.setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); ts.setOriginalNode(accessor, node); return accessor; } @@ -35247,11 +36252,11 @@ var ts; if (languageVersion >= 2) { if (resolver.getNodeCheckFlags(node) & 4096) { enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 8); + ts.setEmitFlags(block, 8); } else if (resolver.getNodeCheckFlags(node) & 2048) { enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 4); + ts.setEmitFlags(block, 4); } } return block; @@ -35261,14 +36266,14 @@ var ts; } } function visitParameter(node) { - if (node.name && ts.isIdentifier(node.name) && node.name.originalKeywordKind === 97) { + if (ts.parameterIsThisKeyword(node)) { return undefined; } var parameter = ts.createParameterDeclaration(undefined, undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression), ts.moveRangePastModifiers(node)); ts.setOriginalNode(parameter, node); - setCommentRange(parameter, node); - setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - setNodeEmitFlags(parameter.name, 1024); + ts.setCommentRange(parameter, node); + ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(parameter.name, 1024); return parameter; } function visitVariableStatement(node) { @@ -35317,12 +36322,13 @@ var ts; || compilerOptions.isolatedModules; } function shouldEmitVarForEnumDeclaration(node) { - return !ts.hasModifier(node, 1) - || (isES6ExportedDeclaration(node) && ts.isFirstDeclarationOfKind(node, node.kind)); + return isFirstEmittedDeclarationInScope(node) + && (!ts.hasModifier(node, 1) + || isES6ExportedDeclaration(node)); } function addVarForEnumExportedFromNamespace(statements, node) { var statement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, getExportName(node))]); - setSourceMapRange(statement, node); + ts.setSourceMapRange(statement, node); statements.push(statement); } function visitEnumDeclaration(node) { @@ -35331,6 +36337,7 @@ var ts; } var statements = []; var emitFlags = 64; + recordEmittedDeclarationInScope(node); if (shouldEmitVarForEnumDeclaration(node)) { addVarForEnumOrModuleDeclaration(statements, node); if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { @@ -35342,7 +36349,7 @@ var ts; var exportName = getExportName(node); var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformEnumBody(node, containerName)), undefined, [ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()))]), node); ts.setOriginalNode(enumStatement, node); - setNodeEmitFlags(enumStatement, emitFlags); + ts.setEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); if (isNamespaceExport(node)) { addVarForEnumExportedFromNamespace(statements, node); @@ -35381,18 +36388,32 @@ var ts; function shouldEmitModuleDeclaration(node) { return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } - function isModuleMergedWithES6Class(node) { - return languageVersion === 2 - && ts.isMergedWithClass(node); - } function isES6ExportedDeclaration(node) { return isExternalModuleExport(node) && moduleKind === ts.ModuleKind.ES6; } + function recordEmittedDeclarationInScope(node) { + var name = node.symbol && node.symbol.name; + if (name) { + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createMap(); + } + if (!(name in currentScopeFirstDeclarationsOfName)) { + currentScopeFirstDeclarationsOfName[name] = node; + } + } + } + function isFirstEmittedDeclarationInScope(node) { + if (currentScopeFirstDeclarationsOfName) { + var name_28 = node.symbol && node.symbol.name; + if (name_28) { + return currentScopeFirstDeclarationsOfName[name_28] === node; + } + } + return false; + } function shouldEmitVarForModuleDeclaration(node) { - return !isModuleMergedWithES6Class(node) - && (!isES6ExportedDeclaration(node) - || ts.isFirstDeclarationOfKind(node, node.kind)); + return isFirstEmittedDeclarationInScope(node); } function addVarForEnumOrModuleDeclaration(statements, node) { var statement = ts.createVariableStatement(isES6ExportedDeclaration(node) @@ -35402,13 +36423,13 @@ var ts; ]); ts.setOriginalNode(statement, node); if (node.kind === 224) { - setSourceMapRange(statement.declarationList, node); + ts.setSourceMapRange(statement.declarationList, node); } else { - setSourceMapRange(statement, node); + ts.setSourceMapRange(statement, node); } - setCommentRange(statement, node); - setNodeEmitFlags(statement, 32768); + ts.setCommentRange(statement, node); + ts.setEmitFlags(statement, 32768); statements.push(statement); } function visitModuleDeclaration(node) { @@ -35419,6 +36440,7 @@ var ts; enableSubstitutionForNamespaceExports(); var statements = []; var emitFlags = 64; + recordEmittedDeclarationInScope(node); if (shouldEmitVarForModuleDeclaration(node)) { addVarForEnumOrModuleDeclaration(statements, node); if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { @@ -35435,15 +36457,17 @@ var ts; } var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformModuleBody(node, containerName)), undefined, [moduleArg]), node); ts.setOriginalNode(moduleStatement, node); - setNodeEmitFlags(moduleStatement, emitFlags); + ts.setEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); return statements; } function transformModuleBody(node, namespaceLocalName) { var savedCurrentNamespaceContainerName = currentNamespaceContainerName; var savedCurrentNamespace = currentNamespace; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; currentNamespaceContainerName = namespaceLocalName; currentNamespace = node; + currentScopeFirstDeclarationsOfName = undefined; var statements = []; startLexicalEnvironment(); var statementsLocation; @@ -35470,9 +36494,10 @@ var ts; ts.addRange(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), blockLocation, true); if (body.kind !== 226) { - setNodeEmitFlags(block, block.emitFlags | 49152); + ts.setEmitFlags(block, ts.getEmitFlags(block) | 49152); } return block; } @@ -35495,7 +36520,7 @@ var ts; return undefined; } var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); - setNodeEmitFlags(moduleReference, 49152 | 65536); + ts.setEmitFlags(moduleReference, 49152 | 65536); if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { return ts.setOriginalNode(ts.createVariableStatement(ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(node.name, undefined, moduleReference) @@ -35524,9 +36549,9 @@ var ts; } function addExportMemberAssignment(statements, node) { var expression = ts.createAssignment(getExportName(node), getLocalName(node, true)); - setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + ts.setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); var statement = ts.createStatement(expression); - setSourceMapRange(statement, ts.createRange(-1, node.end)); + ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); } function createNamespaceExport(exportName, exportValue, location) { @@ -35547,7 +36572,7 @@ var ts; emitFlags |= 1536; } if (emitFlags) { - setNodeEmitFlags(qualifiedName, emitFlags); + ts.setEmitFlags(qualifiedName, emitFlags); } return qualifiedName; } @@ -35556,7 +36581,7 @@ var ts; } function getNamespaceParameterName(node) { var name = ts.getGeneratedNameForNode(node); - setSourceMapRange(name, node.name); + ts.setSourceMapRange(name, node.name); return name; } function getNamespaceContainerName(node) { @@ -35573,8 +36598,8 @@ var ts; } function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { if (node.name) { - var name_28 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); + var name_29 = ts.getMutableClone(node.name); + emitFlags |= ts.getEmitFlags(node.name); if (!allowSourceMaps) { emitFlags |= 1536; } @@ -35582,9 +36607,9 @@ var ts; emitFlags |= 49152; } if (emitFlags) { - setNodeEmitFlags(name_28, emitFlags); + ts.setEmitFlags(name_29, emitFlags); } - return name_28; + return name_29; } else { return ts.getGeneratedNameForNode(node); @@ -35646,7 +36671,7 @@ var ts; function isTransformedEnumDeclaration(node) { return ts.getOriginalNode(node).kind === 224; } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedApplicableSubstitutions = applicableSubstitutions; var savedCurrentSuperContainer = currentSuperContainer; if (enabledSubstitutions & 4 && isSuperContainer(node)) { @@ -35658,13 +36683,13 @@ var ts; if (enabledSubstitutions & 8 && isTransformedEnumDeclaration(node)) { applicableSubstitutions |= 8; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); applicableSubstitutions = savedApplicableSubstitutions; currentSuperContainer = savedCurrentSuperContainer; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -35674,14 +36699,14 @@ var ts; } function substituteShorthandPropertyAssignment(node) { if (enabledSubstitutions & 2) { - var name_29 = node.name; - var exportedName = trySubstituteNamespaceExportedName(name_29); + var name_30 = node.name; + var exportedName = trySubstituteNamespaceExportedName(name_30); if (exportedName) { if (node.objectAssignmentInitializer) { var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); - return ts.createPropertyAssignment(name_29, initializer, node); + return ts.createPropertyAssignment(name_30, initializer, node); } - return ts.createPropertyAssignment(name_29, exportedName, node); + return ts.createPropertyAssignment(name_30, exportedName, node); } } return node; @@ -35690,16 +36715,15 @@ var ts; switch (node.kind) { case 69: return substituteExpressionIdentifier(node); - } - if (enabledSubstitutions & 4) { - switch (node.kind) { - case 174: + case 172: + return substitutePropertyAccessExpression(node); + case 173: + return substituteElementAccessExpression(node); + case 174: + if (enabledSubstitutions & 4) { return substituteCallExpression(node); - case 172: - return substitutePropertyAccessExpression(node); - case 173: - return substituteElementAccessExpression(node); - } + } + break; } return node; } @@ -35716,8 +36740,8 @@ var ts; var classAlias = classAliases[declaration.id]; if (classAlias) { var clone_4 = ts.getSynthesizedClone(classAlias); - setSourceMapRange(clone_4, node); - setCommentRange(clone_4, node); + ts.setSourceMapRange(clone_4, node); + ts.setCommentRange(clone_4, node); return clone_4; } } @@ -35726,7 +36750,7 @@ var ts; return undefined; } function trySubstituteNamespaceExportedName(node) { - if (enabledSubstitutions & applicableSubstitutions && (getNodeEmitFlags(node) & 262144) === 0) { + if (enabledSubstitutions & applicableSubstitutions && (ts.getEmitFlags(node) & 262144) === 0) { var container = resolver.getReferencedExportContainer(node, false); if (container) { var substitute = (applicableSubstitutions & 2 && container.kind === 225) || @@ -35754,23 +36778,48 @@ var ts; return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 95) { + if (enabledSubstitutions & 4 && node.expression.kind === 95) { var flags = getSuperContainerAsyncMethodFlags(); if (flags) { return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); } } - return node; + return substituteConstantValue(node); } function substituteElementAccessExpression(node) { - if (node.expression.kind === 95) { + if (enabledSubstitutions & 4 && node.expression.kind === 95) { var flags = getSuperContainerAsyncMethodFlags(); if (flags) { return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); } } + return substituteConstantValue(node); + } + function substituteConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + var substitute = ts.createLiteral(constantValue); + ts.setSourceMapRange(substitute, node); + ts.setCommentRange(substitute, node); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : ts.getTextOfNode(node.argumentExpression); + substitute.trailingComment = " " + propertyName + " "; + } + ts.setConstantValue(node, constantValue); + return substitute; + } return node; } + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; + } + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) + ? resolver.getConstantValue(node) + : undefined; + } function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { if (flags & 4096) { return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), "value", location); @@ -35794,6 +36843,9 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; return ts.visitEachChild(node, visitor, context); @@ -35905,7 +36957,7 @@ var ts; var ts; (function (ts) { function transformSystemModule(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -35934,6 +36986,9 @@ var ts; var currentNode; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; currentNode = node; @@ -35966,12 +37021,12 @@ var ts; var body = ts.createFunctionExpression(undefined, undefined, undefined, [ ts.createParameter(exportFunctionForFile), ts.createParameter(contextObjectForFile) - ], undefined, setNodeEmitFlags(ts.createBlock(statements, undefined, true), 1)); + ], undefined, ts.setEmitFlags(ts.createBlock(statements, undefined, true), 1)); return updateSourceFile(node, [ ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), undefined, moduleName ? [moduleName, dependencies, body] : [dependencies, body])) - ], ~1 & getNodeEmitFlags(node)); + ], ~1 & ts.getEmitFlags(node)); var _a; } function addSystemModuleBody(statements, node, dependencyGroups) { @@ -36215,11 +37270,11 @@ var ts; } function visitFunctionDeclaration(node) { if (ts.hasModifier(node, 1)) { - var name_30 = node.name || ts.getGeneratedNameForNode(node); - var newNode = ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name_30, undefined, node.parameters, undefined, node.body, node); + var name_31 = node.name || ts.getGeneratedNameForNode(node); + var newNode = ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name_31, undefined, node.parameters, undefined, node.body, node); recordExportedFunctionDeclaration(node); if (!ts.hasModifier(node, 512)) { - recordExportName(name_30); + recordExportName(name_31); } ts.setOriginalNode(newNode, node); node = newNode; @@ -36230,13 +37285,13 @@ var ts; function visitExpressionStatement(node) { var originalNode = ts.getOriginalNode(node); if ((originalNode.kind === 225 || originalNode.kind === 224) && ts.hasModifier(originalNode, 1)) { - var name_31 = getDeclarationName(originalNode); + var name_32 = getDeclarationName(originalNode); if (originalNode.kind === 224) { - hoistVariableDeclaration(name_31); + hoistVariableDeclaration(name_32); } return [ node, - createExportStatement(name_31, name_31) + createExportStatement(name_32, name_32) ]; } return node; @@ -36390,19 +37445,19 @@ var ts; function visitBlock(node) { return ts.visitEachChild(node, visitNestedNode, context); } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { if (node.kind === 256) { exportFunctionForFile = exportFunctionForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); exportFunctionForFile = undefined; } else { - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); } } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } return node; @@ -36436,7 +37491,7 @@ var ts; return node; } function substituteAssignmentExpression(node) { - setNodeEmitFlags(node, 128); + ts.setEmitFlags(node, 128); var left = node.left; switch (left.kind) { case 69: @@ -36541,7 +37596,7 @@ var ts; var exportDeclaration = resolver.getReferencedExportContainer(operand); if (exportDeclaration) { var expr = ts.createPrefix(node.operator, operand, node); - setNodeEmitFlags(expr, 128); + ts.setEmitFlags(expr, 128); var call = createExportExpression(operand, expr); if (node.kind === 185) { return call; @@ -36574,7 +37629,7 @@ var ts; ts.createForIn(ts.createVariableDeclarationList([ ts.createVariableDeclaration(n, undefined) ]), m, ts.createBlock([ - setNodeEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32) + ts.setEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32) ])), ts.createStatement(ts.createCall(exportFunctionForFile, undefined, [exports])) ], undefined, true))); @@ -36674,7 +37729,7 @@ var ts; function updateSourceFile(node, statements, nodeEmitFlags) { var updated = ts.getMutableClone(node); updated.statements = ts.createNodeArray(statements, node.statements); - setNodeEmitFlags(updated, nodeEmitFlags); + ts.setEmitFlags(updated, nodeEmitFlags); return updated; } } @@ -36688,9 +37743,8 @@ var ts; _a[ts.ModuleKind.CommonJS] = transformCommonJSModule, _a[ts.ModuleKind.AMD] = transformAMDModule, _a[ts.ModuleKind.UMD] = transformUMDModule, - _a - )); - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, setNodeEmitFlags = context.setNodeEmitFlags, getNodeEmitFlags = context.getNodeEmitFlags, setSourceMapRange = context.setSourceMapRange; + _a)); + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -36715,6 +37769,9 @@ var ts; var hasExportStarsToExportValues; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); @@ -36740,7 +37797,7 @@ var ts; addExportEqualsIfNeeded(statements, false); var updated = updateSourceFile(node, statements); if (hasExportStarsToExportValues) { - setNodeEmitFlags(updated, 2 | getNodeEmitFlags(node)); + ts.setEmitFlags(updated, 2 | ts.getEmitFlags(node)); } return updated; } @@ -36751,7 +37808,7 @@ var ts; } function transformUMDModule(node) { var define = ts.createIdentifier("define"); - setNodeEmitFlags(define, 16); + ts.setEmitFlags(define, 16); return transformAsynchronousModule(node, define, undefined, false); } function transformAsynchronousModule(node, define, moduleName, includeNonAmdDependencies) { @@ -36778,7 +37835,7 @@ var ts; addExportEqualsIfNeeded(statements, true); var body = ts.createBlock(statements, undefined, true); if (hasExportStarsToExportValues) { - setNodeEmitFlags(body, 2); + ts.setEmitFlags(body, 2); } return body; } @@ -36786,12 +37843,12 @@ var ts; if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { if (emitAsReturn) { var statement = ts.createReturn(exportEquals.expression, exportEquals); - setNodeEmitFlags(statement, 12288 | 49152); + ts.setEmitFlags(statement, 12288 | 49152); statements.push(statement); } else { var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), exportEquals.expression), exportEquals); - setNodeEmitFlags(statement, 49152); + ts.setEmitFlags(statement, 49152); statements.push(statement); } } @@ -36854,7 +37911,7 @@ var ts; if (!ts.contains(externalImports, node)) { return undefined; } - setNodeEmitFlags(node.name, 128); + ts.setEmitFlags(node.name, 128); var statements = []; if (moduleKind !== ts.ModuleKind.AMD) { if (ts.hasModifier(node, 1)) { @@ -36942,16 +37999,16 @@ var ts; else { var names = ts.reduceEachChild(node, collectExportMembers, []); for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_32 = names_1[_i]; - addExportMemberAssignments(statements, name_32); + var name_33 = names_1[_i]; + addExportMemberAssignments(statements, name_33); } } } function collectExportMembers(names, node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && ts.isDeclaration(node)) { - var name_33 = node.name; - if (ts.isIdentifier(name_33)) { - names.push(name_33); + var name_34 = node.name; + if (ts.isIdentifier(name_34)) { + names.push(name_34); } } return ts.reduceEachChild(node, collectExportMembers, names); @@ -36969,7 +38026,7 @@ var ts; addExportDefault(statements, getDeclarationName(node), node); } else { - statements.push(createExportStatement(node.name, setNodeEmitFlags(ts.getSynthesizedClone(node.name), 262144), node)); + statements.push(createExportStatement(node.name, ts.setEmitFlags(ts.getSynthesizedClone(node.name), 262144), node)); } } function visitVariableStatement(node) { @@ -37086,25 +38143,25 @@ var ts; } function addVarForExportedEnumOrNamespaceDeclaration(statements, node) { var transformedStatement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, ts.createPropertyAccess(ts.createIdentifier("exports"), getDeclarationName(node)))], node); - setNodeEmitFlags(transformedStatement, 49152); + ts.setEmitFlags(transformedStatement, 49152); statements.push(transformedStatement); } function getDeclarationName(node) { return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { if (node.kind === 256) { bindingNameExportSpecifiersMap = bindingNameExportSpecifiersForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); bindingNameExportSpecifiersMap = undefined; } else { - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); } } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -37145,7 +38202,7 @@ var ts; var left = node.left; if (ts.isIdentifier(left) && ts.isAssignmentOperator(node.operatorToken.kind)) { if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, left.text)) { - setNodeEmitFlags(node, 128); + ts.setEmitFlags(node, 128); var nestedExportAssignment = void 0; for (var _i = 0, _a = bindingNameExportSpecifiersMap[left.text]; _i < _a.length; _i++) { var specifier = _a[_i]; @@ -37163,11 +38220,11 @@ var ts; var operand = node.operand; if (ts.isIdentifier(operand) && bindingNameExportSpecifiersForFileMap) { if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, operand.text)) { - setNodeEmitFlags(node, 128); + ts.setEmitFlags(node, 128); var transformedUnaryExpression = void 0; if (node.kind === 186) { - transformedUnaryExpression = ts.createBinary(operand, ts.createNode(operator === 41 ? 57 : 58), ts.createLiteral(1), node); - setNodeEmitFlags(transformedUnaryExpression, 128); + transformedUnaryExpression = ts.createBinary(operand, ts.createToken(operator === 41 ? 57 : 58), ts.createLiteral(1), node); + ts.setEmitFlags(transformedUnaryExpression, 128); } var nestedExportAssignment = void 0; for (var _i = 0, _a = bindingNameExportSpecifiersMap[operand.text]; _i < _a.length; _i++) { @@ -37182,7 +38239,7 @@ var ts; return node; } function trySubstituteExportedName(node) { - var emitFlags = getNodeEmitFlags(node); + var emitFlags = ts.getEmitFlags(node); if ((emitFlags & 262144) === 0) { var container = resolver.getReferencedExportContainer(node, (emitFlags & 131072) !== 0); if (container) { @@ -37194,7 +38251,7 @@ var ts; return undefined; } function trySubstituteImportedName(node) { - if ((getNodeEmitFlags(node) & 262144) === 0) { + if ((ts.getEmitFlags(node) & 262144) === 0) { var declaration = resolver.getReferencedImportDeclaration(node); if (declaration) { if (ts.isImportClause(declaration)) { @@ -37206,12 +38263,12 @@ var ts; } } else if (ts.isImportSpecifier(declaration)) { - var name_34 = declaration.propertyName || declaration.name; - if (name_34.originalKeywordKind === 77 && languageVersion <= 0) { - return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_34.text), node); + var name_35 = declaration.propertyName || declaration.name; + if (name_35.originalKeywordKind === 77 && languageVersion <= 0) { + return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_35.text), node); } else { - return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_34), node); + return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_35), node); } } } @@ -37233,7 +38290,7 @@ var ts; var statement = ts.createStatement(createExportAssignment(name, value)); statement.startsOnNewLine = true; if (location) { - setSourceMapRange(statement, location); + ts.setSourceMapRange(statement, location); } return statement; } @@ -37261,7 +38318,7 @@ var ts; var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); if (includeNonAmdDependencies && importAliasName) { - setNodeEmitFlags(importAliasName, 128); + ts.setEmitFlags(importAliasName, 128); aliasedModuleNames.push(externalModuleName); importAliasNames.push(ts.createParameter(importAliasName)); } @@ -37288,6 +38345,9 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; node = ts.visitEachChild(node, visitor, context); currentSourceFile = undefined; @@ -37446,12 +38506,12 @@ var ts; return getTagName(node.openingElement); } else { - var name_35 = node.tagName; - if (ts.isIdentifier(name_35) && ts.isIntrinsicJsxName(name_35.text)) { - return ts.createLiteral(name_35.text); + var name_36 = node.tagName; + if (ts.isIdentifier(name_36) && ts.isIntrinsicJsxName(name_36.text)) { + return ts.createLiteral(name_36.text); } else { - return ts.createExpressionFromEntityName(name_35); + return ts.createExpressionFromEntityName(name_36); } } } @@ -37733,6 +38793,9 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitEachChild(node, visitor, context); } function visitor(node) { @@ -37797,10 +38860,9 @@ var ts; _a[4] = "yield", _a[5] = "yield*", _a[7] = "endfinally", - _a - )); + _a)); function transformGenerators(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration, setSourceMapRange = context.setSourceMapRange, setCommentRange = context.setCommentRange, setNodeEmitFlags = context.setNodeEmitFlags; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var resolver = context.getEmitResolver(); @@ -37834,6 +38896,9 @@ var ts; var withBlockStack; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (node.transformFlags & 1024) { currentSourceFile = node; node = ts.visitEachChild(node, visitor, context); @@ -37940,7 +39005,7 @@ var ts; } } function visitFunctionDeclaration(node) { - if (node.asteriskToken && node.emitFlags & 2097152) { + if (node.asteriskToken && ts.getEmitFlags(node) & 2097152) { node = ts.setOriginalNode(ts.createFunctionDeclaration(undefined, undefined, undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); } else { @@ -37961,7 +39026,7 @@ var ts; } } function visitFunctionExpression(node) { - if (node.asteriskToken && node.emitFlags & 2097152) { + if (node.asteriskToken && ts.getEmitFlags(node) & 2097152) { node = ts.setOriginalNode(ts.createFunctionExpression(undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); } else { @@ -37992,6 +39057,7 @@ var ts; var savedBlocks = blocks; var savedBlockOffsets = blockOffsets; var savedBlockActions = blockActions; + var savedBlockStack = blockStack; var savedLabelOffsets = labelOffsets; var savedLabelExpressions = labelExpressions; var savedNextLabelId = nextLabelId; @@ -38004,6 +39070,7 @@ var ts; blocks = undefined; blockOffsets = undefined; blockActions = undefined; + blockStack = undefined; labelOffsets = undefined; labelExpressions = undefined; nextLabelId = 1; @@ -38022,6 +39089,7 @@ var ts; blocks = savedBlocks; blockOffsets = savedBlockOffsets; blockActions = savedBlockActions; + blockStack = savedBlockStack; labelOffsets = savedLabelOffsets; labelExpressions = savedLabelExpressions; nextLabelId = savedNextLabelId; @@ -38037,7 +39105,7 @@ var ts; return undefined; } else { - if (node.emitFlags & 8388608) { + if (ts.getEmitFlags(node) & 8388608) { return node; } for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { @@ -38705,9 +39773,9 @@ var ts; } return -1; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } return node; @@ -38724,11 +39792,11 @@ var ts; if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { - var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); - if (name_36) { - var clone_7 = ts.getMutableClone(name_36); - setSourceMapRange(clone_7, node); - setCommentRange(clone_7, node); + var name_37 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); + if (name_37) { + var clone_7 = ts.getMutableClone(name_37); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); return clone_7; } } @@ -39122,7 +40190,7 @@ var ts; var buildResult = buildStatements(); return ts.createCall(ts.createHelperName(currentSourceFile.externalHelpersModuleName, "__generator"), undefined, [ ts.createThis(), - setNodeEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(state)], undefined, ts.createBlock(buildResult, undefined, buildResult.length > 0)), 4194304) + ts.setEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(state)], undefined, ts.createBlock(buildResult, undefined, buildResult.length > 0)), 4194304) ]); } function buildStatements() { @@ -39391,7 +40459,7 @@ var ts; var ts; (function (ts) { function transformES6(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, getCommentRange = context.getCommentRange, setCommentRange = context.setCommentRange, getSourceMapRange = context.getSourceMapRange, setSourceMapRange = context.setSourceMapRange, setTokenSourceMapRange = context.setTokenSourceMapRange; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var previousOnSubstituteNode = context.onSubstituteNode; var previousOnEmitNode = context.onEmitNode; @@ -39411,6 +40479,9 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; currentText = node.text; return ts.visitNode(node, visitor, ts.isSourceFile); @@ -39580,7 +40651,7 @@ var ts; enclosingFunction = currentNode; if (currentNode.kind !== 180) { enclosingNonArrowFunction = currentNode; - if (!(currentNode.emitFlags & 2097152)) { + if (!(ts.getEmitFlags(currentNode) & 2097152)) { enclosingNonAsyncFunctionBody = currentNode; } } @@ -39717,15 +40788,15 @@ var ts; } var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter("_super")] : [], undefined, transformClassBody(node, extendsClauseElement)); - if (getNodeEmitFlags(node) & 524288) { - setNodeEmitFlags(classFunction, 524288); + if (ts.getEmitFlags(node) & 524288) { + ts.setEmitFlags(classFunction, 524288); } var inner = ts.createPartiallyEmittedExpression(classFunction); inner.end = node.end; - setNodeEmitFlags(inner, 49152); + ts.setEmitFlags(inner, 49152); var outer = ts.createPartiallyEmittedExpression(inner); outer.end = ts.skipTrivia(currentText, node.pos); - setNodeEmitFlags(outer, 49152); + ts.setEmitFlags(outer, 49152); return ts.createParen(ts.createCall(outer, undefined, extendsClauseElement ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] : [])); @@ -39740,14 +40811,14 @@ var ts; var localName = getLocalName(node); var outer = ts.createPartiallyEmittedExpression(localName); outer.end = closingBraceLocation.end; - setNodeEmitFlags(outer, 49152); + ts.setEmitFlags(outer, 49152); var statement = ts.createReturn(outer); statement.pos = closingBraceLocation.pos; - setNodeEmitFlags(statement, 49152 | 12288); + ts.setEmitFlags(statement, 49152 | 12288); statements.push(statement); ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, node.members), undefined, true); - setNodeEmitFlags(block, 49152); + ts.setEmitFlags(block, 49152); return block; } function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { @@ -39758,7 +40829,11 @@ var ts; function addConstructor(statements, node, extendsClauseElement) { var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); - statements.push(ts.createFunctionDeclaration(undefined, undefined, undefined, getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), constructor || node)); + var constructorFunction = ts.createFunctionDeclaration(undefined, undefined, undefined, getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), constructor || node); + if (extendsClauseElement) { + ts.setEmitFlags(constructorFunction, 256); + } + statements.push(constructorFunction); } function transformConstructorParameters(constructor, hasSynthesizedSuper) { if (constructor && !hasSynthesizedSuper) { @@ -39769,33 +40844,98 @@ var ts; function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { var statements = []; startLexicalEnvironment(); + var statementOffset = -1; + if (hasSynthesizedSuper) { + statementOffset = 1; + } + else if (constructor) { + statementOffset = ts.addPrologueDirectives(statements, constructor.body.statements, false, visitor); + } if (constructor) { - addCaptureThisForNodeIfNeeded(statements, constructor); addDefaultValueAssignmentsIfNeeded(statements, constructor); addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); + } + var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, !!extendsClauseElement, hasSynthesizedSuper, statementOffset); + if (superCaptureStatus === 1 || superCaptureStatus === 2) { + statementOffset++; } - addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper); if (constructor) { - var body = saveStateAndInvoke(constructor, hasSynthesizedSuper ? transformConstructorBodyWithSynthesizedSuper : transformConstructorBodyWithoutSynthesizedSuper); + var body = saveStateAndInvoke(constructor, function (constructor) { return ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, statementOffset); }); ts.addRange(statements, body); } + if (extendsClauseElement + && superCaptureStatus !== 2 + && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { + statements.push(ts.createReturn(ts.createIdentifier("_this"))); + } ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, constructor ? constructor.body.statements : node.members), constructor ? constructor.body : node, true); if (!constructor) { - setNodeEmitFlags(block, 49152); + ts.setEmitFlags(block, 49152); } return block; } - function transformConstructorBodyWithSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 1); - } - function transformConstructorBodyWithoutSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 0); - } - function addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper) { - if (constructor ? hasSynthesizedSuper : extendsClauseElement) { - statements.push(ts.createStatement(ts.createFunctionApply(ts.createIdentifier("_super"), ts.createThis(), ts.createIdentifier("arguments")), extendsClauseElement)); + function isSufficientlyCoveredByReturnStatements(statement) { + if (statement.kind === 211) { + return true; } + else if (statement.kind === 203) { + var ifStatement = statement; + if (ifStatement.elseStatement) { + return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && + isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); + } + } + else if (statement.kind === 199) { + var lastStatement = ts.lastOrUndefined(statement.statements); + if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { + return true; + } + } + return false; + } + function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, hasExtendsClause, hasSynthesizedSuper, statementOffset) { + if (!hasExtendsClause) { + if (ctor) { + addCaptureThisForNodeIfNeeded(statements, ctor); + } + return 0; + } + if (!ctor) { + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + return 2; + } + if (hasSynthesizedSuper) { + captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); + enableSubstitutionsForCapturedThis(); + return 1; + } + var firstStatement; + var superCallExpression; + var ctorStatements = ctor.body.statements; + if (statementOffset < ctorStatements.length) { + firstStatement = ctorStatements[statementOffset]; + if (firstStatement.kind === 202 && ts.isSuperCall(firstStatement.expression)) { + var superCall = firstStatement.expression; + superCallExpression = ts.setOriginalNode(saveStateAndInvoke(superCall, visitImmediateSuperCallInBody), superCall); + } + } + if (superCallExpression && statementOffset === ctorStatements.length - 1) { + statements.push(ts.createReturn(superCallExpression)); + return 2; + } + captureThisForNode(statements, ctor, superCallExpression, firstStatement); + if (superCallExpression) { + return 1; + } + return 0; + } + function createDefaultSuperCallOrThis() { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 128); + var superCall = ts.createFunctionApply(ts.createIdentifier("_super"), actualThis, ts.createIdentifier("arguments")); + return ts.createLogicalOr(superCall, actualThis); } function visitParameter(node) { if (node.dotDotDotToken) { @@ -39820,34 +40960,34 @@ var ts; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - var name_37 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + var name_38 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; if (dotDotDotToken) { continue; } - if (ts.isBindingPattern(name_37)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name_37, initializer); + if (ts.isBindingPattern(name_38)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name_38, initializer); } else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name_37, initializer); + addDefaultValueAssignmentForInitializer(statements, parameter, name_38, initializer); } } } function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { var temp = ts.getGeneratedNameForNode(parameter); if (name.elements.length > 0) { - statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608)); + statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608)); } else if (initializer) { - statements.push(setNodeEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608)); + statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608)); } } function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); - var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), setNodeEmitFlags(ts.createBlock([ - ts.createStatement(ts.createAssignment(setNodeEmitFlags(ts.getMutableClone(name), 1536), setNodeEmitFlags(initializer, 1536 | getNodeEmitFlags(initializer)), parameter)) + var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), ts.setEmitFlags(ts.createBlock([ + ts.createStatement(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 1536), ts.setEmitFlags(initializer, 1536 | ts.getEmitFlags(initializer)), parameter)) ], parameter), 32 | 1024 | 12288), undefined, parameter); statement.startsOnNewLine = true; - setNodeEmitFlags(statement, 12288 | 1024 | 8388608); + ts.setEmitFlags(statement, 12288 | 1024 | 8388608); statements.push(statement); } function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { @@ -39859,11 +40999,11 @@ var ts; return; } var declarationName = ts.getMutableClone(parameter.name); - setNodeEmitFlags(declarationName, 1536); + ts.setEmitFlags(declarationName, 1536); var expressionName = ts.getSynthesizedClone(parameter.name); var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); - statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(declarationName, undefined, ts.createArrayLiteral([])) ]), parameter), 8388608)); var forStatement = ts.createFor(ts.createVariableDeclarationList([ @@ -39871,21 +41011,24 @@ var ts; ], parameter), ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length"), parameter), ts.createPostfixIncrement(temp, parameter), ts.createBlock([ ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), parameter)) ])); - setNodeEmitFlags(forStatement, 8388608); + ts.setEmitFlags(forStatement, 8388608); ts.startOnNewLine(forStatement); statements.push(forStatement); } function addCaptureThisForNodeIfNeeded(statements, node) { if (node.transformFlags & 16384 && node.kind !== 180) { - enableSubstitutionsForCapturedThis(); - var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("_this", undefined, ts.createThis()) - ])); - setNodeEmitFlags(captureThisStatement, 49152 | 8388608); - setSourceMapRange(captureThisStatement, node); - statements.push(captureThisStatement); + captureThisForNode(statements, node, ts.createThis()); } } + function captureThisForNode(statements, node, initializer, originalStatement) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("_this", undefined, initializer) + ]), originalStatement); + ts.setEmitFlags(captureThisStatement, 49152 | 8388608); + ts.setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } function addClassMembers(statements, node) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -39915,43 +41058,43 @@ var ts; return ts.createEmptyStatement(member); } function transformClassMethodDeclarationToStatement(receiver, member) { - var commentRange = getCommentRange(member); - var sourceMapRange = getSourceMapRange(member); + var commentRange = ts.getCommentRange(member); + var sourceMapRange = ts.getSourceMapRange(member); var func = transformFunctionLikeToExpression(member, member, undefined); - setNodeEmitFlags(func, 49152); - setSourceMapRange(func, sourceMapRange); + ts.setEmitFlags(func, 49152); + ts.setSourceMapRange(func, sourceMapRange); var statement = ts.createStatement(ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), member.name), func), member); ts.setOriginalNode(statement, member); - setCommentRange(statement, commentRange); - setNodeEmitFlags(statement, 1536); + ts.setCommentRange(statement, commentRange); + ts.setEmitFlags(statement, 1536); return statement; } function transformAccessorsToStatement(receiver, accessors) { - var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, false), getSourceMapRange(accessors.firstAccessor)); - setNodeEmitFlags(statement, 49152); + var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, false), ts.getSourceMapRange(accessors.firstAccessor)); + ts.setEmitFlags(statement, 49152); return statement; } function transformAccessorsToExpression(receiver, _a, startsOnNewLine) { var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; var target = ts.getMutableClone(receiver); - setNodeEmitFlags(target, 49152 | 1024); - setSourceMapRange(target, firstAccessor.name); + ts.setEmitFlags(target, 49152 | 1024); + ts.setSourceMapRange(target, firstAccessor.name); var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); - setNodeEmitFlags(propertyName, 49152 | 512); - setSourceMapRange(propertyName, firstAccessor.name); + ts.setEmitFlags(propertyName, 49152 | 512); + ts.setSourceMapRange(propertyName, firstAccessor.name); var properties = []; if (getAccessor) { var getterFunction = transformFunctionLikeToExpression(getAccessor, undefined, undefined); - setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); + ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor)); var getter = ts.createPropertyAssignment("get", getterFunction); - setCommentRange(getter, getCommentRange(getAccessor)); + ts.setCommentRange(getter, ts.getCommentRange(getAccessor)); properties.push(getter); } if (setAccessor) { var setterFunction = transformFunctionLikeToExpression(setAccessor, undefined, undefined); - setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); + ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor)); var setter = ts.createPropertyAssignment("set", setterFunction); - setCommentRange(setter, getCommentRange(setAccessor)); + ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); properties.push(setter); } properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); @@ -39970,7 +41113,7 @@ var ts; enableSubstitutionsForCapturedThis(); } var func = transformFunctionLikeToExpression(node, node, undefined); - setNodeEmitFlags(func, 256); + ts.setEmitFlags(func, 256); return func; } function visitFunctionExpression(node) { @@ -40027,7 +41170,7 @@ var ts; } var expression = ts.visitNode(body, visitor, ts.isExpression); var returnStatement = ts.createReturn(expression, body); - setNodeEmitFlags(returnStatement, 12288 | 1024 | 32768); + ts.setEmitFlags(returnStatement, 12288 | 1024 | 32768); statements.push(returnStatement); closeBraceLocation = body; } @@ -40038,10 +41181,10 @@ var ts; } var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); if (!multiLine && singleLine) { - setNodeEmitFlags(block, 32); + ts.setEmitFlags(block, 32); } if (closeBraceLocation) { - setTokenSourceMapRange(block, 16, closeBraceLocation); + ts.setTokenSourceMapRange(block, 16, closeBraceLocation); } ts.setOriginalNode(block, node.body); return block; @@ -40082,7 +41225,7 @@ var ts; assignment = ts.flattenVariableDestructuringToExpression(context, decl, hoistVariableDeclaration, undefined, visitor); } else { - assignment = ts.createBinary(decl.name, 56, decl.initializer); + assignment = ts.createBinary(decl.name, 56, ts.visitNode(decl.initializer, visitor, ts.isExpression)); } (assignments || (assignments = [])).push(assignment); } @@ -40105,13 +41248,13 @@ var ts; : visitVariableDeclaration)); var declarationList = ts.createVariableDeclarationList(declarations, node); ts.setOriginalNode(declarationList, node); - setCommentRange(declarationList, node); + ts.setCommentRange(declarationList, node); if (node.transformFlags & 2097152 && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { var firstDeclaration = ts.firstOrUndefined(declarations); var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); } return declarationList; } @@ -40206,7 +41349,7 @@ var ts; ts.setOriginalNode(declarationList, initializer); var firstDeclaration = declarations[0]; var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); statements.push(ts.createVariableStatement(undefined, declarationList)); } else { @@ -40241,14 +41384,14 @@ var ts; statements.push(statement); } } - setNodeEmitFlags(expression, 1536 | getNodeEmitFlags(expression)); + ts.setEmitFlags(expression, 1536 | ts.getEmitFlags(expression)); var body = ts.createBlock(ts.createNodeArray(statements, statementsLocation), bodyLocation); - setNodeEmitFlags(body, 1536 | 12288); + ts.setEmitFlags(body, 1536 | 12288); var forStatement = ts.createFor(ts.createVariableDeclarationList([ ts.createVariableDeclaration(counter, undefined, ts.createLiteral(0), ts.moveRangePos(node.expression, -1)), ts.createVariableDeclaration(rhsReference, undefined, expression, node.expression) ], node.expression), ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length"), node.expression), ts.createPostfixIncrement(counter, node.expression), body, node); - setNodeEmitFlags(forStatement, 8192); + ts.setEmitFlags(forStatement, 8192); return forStatement; } function visitObjectLiteralExpression(node) { @@ -40266,7 +41409,7 @@ var ts; ts.Debug.assert(numInitialProperties !== numProperties); var temp = ts.createTempVariable(hoistVariableDeclaration); var expressions = []; - var assignment = ts.createAssignment(temp, setNodeEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, node.multiLine), 524288)); + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, node.multiLine), 524288)); if (node.multiLine) { assignment.startsOnNewLine = true; } @@ -40355,7 +41498,7 @@ var ts; loopBody = ts.createBlock([loopBody], undefined, true); } var isAsyncBlockContainingAwait = enclosingNonArrowFunction - && (enclosingNonArrowFunction.emitFlags & 2097152) !== 0 + && (ts.getEmitFlags(enclosingNonArrowFunction) & 2097152) !== 0 && (node.statement.transformFlags & 4194304) !== 0; var loopBodyFlags = 0; if (currentState.containsLexicalThis) { @@ -40365,7 +41508,7 @@ var ts; loopBodyFlags |= 2097152; } var convertedLoopVariable = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, undefined, setNodeEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) + ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) ])); var statements = [convertedLoopVariable]; var extraVariableDeclarations; @@ -40393,8 +41536,8 @@ var ts; if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var name_38 in currentState.hoistedLocalVariables) { - var identifier = currentState.hoistedLocalVariables[name_38]; + for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { + var identifier = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } @@ -40403,8 +41546,8 @@ var ts; if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _b = 0, loopOutParameters_1 = loopOutParameters; _b < loopOutParameters_1.length; _b++) { - var outParam = loopOutParameters_1[_b]; + for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { + var outParam = loopOutParameters_1[_d]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } @@ -40582,7 +41725,7 @@ var ts; function visitMethodDeclaration(node) { ts.Debug.assert(!ts.isComputedPropertyName(node.name)); var functionExpression = transformFunctionLikeToExpression(node, ts.moveRangePos(node, -1), undefined); - setNodeEmitFlags(functionExpression, 16384 | getNodeEmitFlags(functionExpression)); + ts.setEmitFlags(functionExpression, 16384 | ts.getEmitFlags(functionExpression)); return ts.createPropertyAssignment(node.name, functionExpression, node); } function visitShorthandPropertyAssignment(node) { @@ -40595,13 +41738,32 @@ var ts; return transformAndSpreadElements(node.elements, true, node.multiLine, node.elements.hasTrailingComma); } function visitCallExpression(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, true); + } + function visitImmediateSuperCallInBody(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, false); + } + function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 95) { + ts.setEmitFlags(thisArg, 128); + } + var resultingCall; if (node.transformFlags & 262144) { - return ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); + resultingCall = ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); } else { - return ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); + resultingCall = ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); } + if (node.expression.kind === 95) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 128); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + return assignToCapturedThis + ? ts.createAssignment(ts.createIdentifier("_this"), initializer) + : initializer; + } + return resultingCall; } function visitNewExpression(node) { ts.Debug.assert((node.transformFlags & 262144) !== 0); @@ -40721,12 +41883,12 @@ var ts; clone.statements = ts.createNodeArray(statements, node.statements); return clone; } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedEnclosingFunction = enclosingFunction; if (enabledSubstitutions & 1 && ts.isFunctionLike(node)) { enclosingFunction = node; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); enclosingFunction = savedEnclosingFunction; } function enableSubstitutionsForBlockScopedBindings() { @@ -40748,9 +41910,9 @@ var ts; context.enableEmitNotification(220); } } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } if (ts.isIdentifier(node)) { @@ -40800,7 +41962,7 @@ var ts; function substituteThisKeyword(node) { if (enabledSubstitutions & 1 && enclosingFunction - && enclosingFunction.emitFlags & 256) { + && ts.getEmitFlags(enclosingFunction) & 256) { return ts.createIdentifier("_this", node); } return node; @@ -40811,7 +41973,7 @@ var ts; function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { if (node.name && !ts.isGeneratedIdentifier(node.name)) { var name_39 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); + emitFlags |= ts.getEmitFlags(node.name); if (!allowSourceMaps) { emitFlags |= 1536; } @@ -40819,7 +41981,7 @@ var ts; emitFlags |= 49152; } if (emitFlags) { - setNodeEmitFlags(name_39, emitFlags); + ts.setEmitFlags(name_39, emitFlags); } return name_39; } @@ -40868,8 +42030,7 @@ var ts; _a[ts.ModuleKind.CommonJS] = ts.transformModule, _a[ts.ModuleKind.UMD] = ts.transformModule, _a[ts.ModuleKind.None] = ts.transformModule, - _a - )); + _a)); function getTransformers(compilerOptions) { var jsx = compilerOptions.jsx; var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -40888,18 +42049,10 @@ var ts; return transformers; } ts.getTransformers = getTransformers; - var nextTransformId = 1; function transformFiles(resolver, host, sourceFiles, transformers) { - var transformId = nextTransformId; - nextTransformId++; - var tokenSourceMapRanges = ts.createMap(); var lexicalEnvironmentVariableDeclarationsStack = []; var lexicalEnvironmentFunctionDeclarationsStack = []; var enabledSyntaxKindFeatures = new Array(289); - var parseTreeNodesWithAnnotations = []; - var lastTokenSourceMapRangeNode; - var lastTokenSourceMapRangeToken; - var lastTokenSourceMapRange; var lexicalEnvironmentStackOffset = 0; var hoistedVariableDeclarations; var hoistedFunctionDeclarations; @@ -40908,47 +42061,24 @@ var ts; getCompilerOptions: function () { return host.getCompilerOptions(); }, getEmitResolver: function () { return resolver; }, getEmitHost: function () { return host; }, - getNodeEmitFlags: getNodeEmitFlags, - setNodeEmitFlags: setNodeEmitFlags, - getSourceMapRange: getSourceMapRange, - setSourceMapRange: setSourceMapRange, - getTokenSourceMapRange: getTokenSourceMapRange, - setTokenSourceMapRange: setTokenSourceMapRange, - getCommentRange: getCommentRange, - setCommentRange: setCommentRange, hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, startLexicalEnvironment: startLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, - onSubstituteNode: onSubstituteNode, + onSubstituteNode: function (emitContext, node) { return node; }, enableSubstitution: enableSubstitution, isSubstitutionEnabled: isSubstitutionEnabled, - onEmitNode: onEmitNode, + onEmitNode: function (node, emitContext, emitCallback) { return emitCallback(node, emitContext); }, enableEmitNotification: enableEmitNotification, isEmitNotificationEnabled: isEmitNotificationEnabled }; - var transformation = chain.apply(void 0, transformers)(context); + var transformation = ts.chain.apply(void 0, transformers)(context); var transformed = ts.map(sourceFiles, transformSourceFile); lexicalEnvironmentDisabled = true; return { - getSourceFiles: function () { return transformed; }, - getTokenSourceMapRange: getTokenSourceMapRange, - isSubstitutionEnabled: isSubstitutionEnabled, - isEmitNotificationEnabled: isEmitNotificationEnabled, - onSubstituteNode: context.onSubstituteNode, - onEmitNode: context.onEmitNode, - dispose: function () { - for (var _i = 0, parseTreeNodesWithAnnotations_1 = parseTreeNodesWithAnnotations; _i < parseTreeNodesWithAnnotations_1.length; _i++) { - var node = parseTreeNodesWithAnnotations_1[_i]; - if (node.transformId === transformId) { - node.transformId = 0; - node.emitFlags = 0; - node.commentRange = undefined; - node.sourceMapRange = undefined; - } - } - parseTreeNodesWithAnnotations.length = 0; - } + transformed: transformed, + emitNodeWithSubstitution: emitNodeWithSubstitution, + emitNodeWithNotification: emitNodeWithNotification }; function transformSourceFile(sourceFile) { if (ts.isDeclarationFile(sourceFile)) { @@ -40960,75 +42090,37 @@ var ts; enabledSyntaxKindFeatures[kind] |= 1; } function isSubstitutionEnabled(node) { - return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0; + return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0 + && (ts.getEmitFlags(node) & 128) === 0; } - function onSubstituteNode(node, isExpression) { - return node; + function emitNodeWithSubstitution(emitContext, node, emitCallback) { + if (node) { + if (isSubstitutionEnabled(node)) { + var substitute = context.onSubstituteNode(emitContext, node); + if (substitute && substitute !== node) { + emitCallback(emitContext, substitute); + return; + } + } + emitCallback(emitContext, node); + } } function enableEmitNotification(kind) { enabledSyntaxKindFeatures[kind] |= 2; } function isEmitNotificationEnabled(node) { return (enabledSyntaxKindFeatures[node.kind] & 2) !== 0 - || (getNodeEmitFlags(node) & 64) !== 0; + || (ts.getEmitFlags(node) & 64) !== 0; } - function onEmitNode(node, emit) { - emit(node); - } - function beforeSetAnnotation(node) { - if ((node.flags & 8) === 0 && node.transformId !== transformId) { - parseTreeNodesWithAnnotations.push(node); - node.transformId = transformId; - } - } - function getNodeEmitFlags(node) { - return node.emitFlags; - } - function setNodeEmitFlags(node, emitFlags) { - beforeSetAnnotation(node); - node.emitFlags = emitFlags; - return node; - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - function setSourceMapRange(node, range) { - beforeSetAnnotation(node); - node.sourceMapRange = range; - return node; - } - function getTokenSourceMapRange(node, token) { - if (lastTokenSourceMapRangeNode === node && lastTokenSourceMapRangeToken === token) { - return lastTokenSourceMapRange; - } - var range; - var current = node; - while (current) { - range = current.id ? tokenSourceMapRanges[current.id + "-" + token] : undefined; - if (range !== undefined) { - break; + function emitNodeWithNotification(emitContext, node, emitCallback) { + if (node) { + if (isEmitNotificationEnabled(node)) { + context.onEmitNode(emitContext, node, emitCallback); + } + else { + emitCallback(emitContext, node); } - current = current.original; } - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - return range; - } - function setTokenSourceMapRange(node, token, range) { - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - tokenSourceMapRanges[ts.getNodeId(node) + "-" + token] = range; - return node; - } - function getCommentRange(node) { - return node.commentRange || node; - } - function setCommentRange(node, range) { - beforeSetAnnotation(node); - node.commentRange = range; - return node; } function hoistVariableDeclaration(name) { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); @@ -41081,93 +42173,10 @@ var ts; } } ts.transformFiles = transformFiles; - function chain(a, b, c, d, e) { - if (e) { - var args_3 = []; - for (var i = 0; i < arguments.length; i++) { - args_3[i] = arguments[i]; - } - return function (t) { return compose.apply(void 0, ts.map(args_3, function (f) { return f(t); })); }; - } - else if (d) { - return function (t) { return compose(a(t), b(t), c(t), d(t)); }; - } - else if (c) { - return function (t) { return compose(a(t), b(t), c(t)); }; - } - else if (b) { - return function (t) { return compose(a(t), b(t)); }; - } - else if (a) { - return function (t) { return compose(a(t)); }; - } - else { - return function (t) { return function (u) { return u; }; }; - } - } - function compose(a, b, c, d, e) { - if (e) { - var args_4 = []; - for (var i = 0; i < arguments.length; i++) { - args_4[i] = arguments[i]; - } - return function (t) { return ts.reduceLeft(args_4, function (u, f) { return f(u); }, t); }; - } - else if (d) { - return function (t) { return d(c(b(a(t)))); }; - } - else if (c) { - return function (t) { return c(b(a(t))); }; - } - else if (b) { - return function (t) { return b(a(t)); }; - } - else if (a) { - return function (t) { return a(t); }; - } - else { - return function (t) { return t; }; - } - } var _a; })(ts || (ts = {})); var ts; (function (ts) { - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - if (compilerOptions.extendedDiagnostics) { - return createSourceMapWriterWithExtendedDiagnostics(host, writer); - } - return createSourceMapWriterWorker(host, writer); - } - else { - return getNullSourceMapWriter(); - } - } - ts.createSourceMapWriter = createSourceMapWriter; - var nullSourceMapWriter; - function getNullSourceMapWriter() { - if (nullSourceMapWriter === undefined) { - nullSourceMapWriter = { - initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, - reset: function () { }, - getSourceMapData: function () { return undefined; }, - setSourceFile: function (sourceFile) { }, - emitPos: function (pos) { }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitTokenStart: function (token, pos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - emitTokenEnd: function (token, end, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - changeEmitSourcePos: function () { }, - stopOverridingSpan: function () { }, - getText: function () { return undefined; }, - getSourceMappingURL: function () { return undefined; } - }; - } - return nullSourceMapWriter; - } - ts.getNullSourceMapWriter = getNullSourceMapWriter; var defaultLastEncodedSourceMapSpan = { emittedLine: 1, emittedColumn: 1, @@ -41175,42 +42184,38 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function createSourceMapWriterWorker(host, writer) { + function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var currentSourceText; var sourceMapDir; - var stopOverridingSpan = false; - var modifyLastSourcePos = false; var sourceMapSourceIndex; var lastRecordedSourceMapSpan; var lastEncodedSourceMapSpan; var lastEncodedNameIndex; var sourceMapData; - var disableDepth; + var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { initialize: initialize, reset: reset, getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, - emitStart: emitStart, - emitEnd: emitEnd, - emitTokenStart: emitTokenStart, - emitTokenEnd: emitTokenEnd, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: function () { return stopOverridingSpan = true; }, + emitNodeWithSourceMap: emitNodeWithSourceMap, + emitTokenWithSourceMap: emitTokenWithSourceMap, getText: getText, getSourceMappingURL: getSourceMappingURL }; function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (disabled) { + return; + } if (sourceMapData) { reset(); } currentSourceFile = undefined; currentSourceText = undefined; - disableDepth = 0; sourceMapSourceIndex = -1; lastRecordedSourceMapSpan = undefined; lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan; @@ -41250,6 +42255,9 @@ var ts; } } function reset() { + if (disabled) { + return; + } currentSourceFile = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; @@ -41257,38 +42265,6 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; - disableDepth = 0; - } - function enable() { - if (disableDepth > 0) { - disableDepth--; - } - } - function disable() { - disableDepth++; - } - function updateLastEncodedAndRecordedSpans() { - if (modifyLastSourcePos) { - modifyLastSourcePos = false; - lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; - lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; - sourceMapData.sourceMapDecodedMappings.pop(); - lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? - sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : - defaultLastEncodedSourceMapSpan; - var sourceMapMappings = sourceMapData.sourceMapMappings; - var lenthToSet = sourceMapMappings.length - 1; - for (; lenthToSet >= 0; lenthToSet--) { - var currentChar = sourceMapMappings.charAt(lenthToSet); - if (currentChar === ",") { - break; - } - if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { - break; - } - } - sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); - } } function encodeLastRecordedSourceMapSpan() { if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { @@ -41319,7 +42295,7 @@ var ts; sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); } function emitPos(pos) { - if (ts.positionIsSynthesized(pos) || disableDepth > 0) { + if (disabled || ts.positionIsSynthesized(pos)) { return; } if (extendedDiagnostics) { @@ -41344,84 +42320,68 @@ var ts; sourceColumn: sourceLinePos.character, sourceIndex: sourceMapSourceIndex }; - stopOverridingSpan = false; } - else if (!stopOverridingSpan) { + else { lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } - updateLastEncodedAndRecordedSpans(); if (extendedDiagnostics) { ts.performance.mark("afterSourcemap"); ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); } } - function getStartPosPastDecorators(range) { - var rangeHasDecorators = !!range.decorators; - return ts.skipTrivia(currentSourceText, rangeHasDecorators ? range.decorators.end : range.pos); - } - function emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(getStartPosPastDecorators(range)); - } - if (ignoreChildrenCallback(contextNode)) { - disable(); - } + function emitNodeWithSourceMap(emitContext, node, emitCallback) { + if (disabled) { + return emitCallback(emitContext, node); } - else { - emitPos(getStartPosPastDecorators(range)); + if (node) { + var emitNode = node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var _a = emitNode && emitNode.sourceMapRange || node, pos = _a.pos, end = _a.end; + if (node.kind !== 287 + && (emitFlags & 512) === 0 + && pos >= 0) { + emitPos(ts.skipTrivia(currentSourceText, pos)); + } + if (emitFlags & 2048) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; + } + else { + emitCallback(emitContext, node); + } + if (node.kind !== 287 + && (emitFlags & 1024) === 0 + && end >= 0) { + emitPos(end); + } } } - function emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (ignoreChildrenCallback(contextNode)) { - enable(); - } - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(range.end); - } + function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + if (disabled) { + return emitCallback(token, tokenPos); } - else { - emitPos(range.end); + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + tokenPos = ts.skipTrivia(currentSourceText, range ? range.pos : tokenPos); + if ((emitFlags & 4096) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - stopOverridingSpan = false; - } - function emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return ts.skipTrivia(currentSourceText, tokenStartPos); - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenStartPos = range.pos; - } + tokenPos = emitCallback(token, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 8192) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - tokenStartPos = ts.skipTrivia(currentSourceText, tokenStartPos); - emitPos(tokenStartPos); - return tokenStartPos; - } - function emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return tokenEndPos; - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenEndPos = range.end; - } - } - emitPos(tokenEndPos); - return tokenEndPos; - } - function changeEmitSourcePos() { - ts.Debug.assert(!modifyLastSourcePos); - modifyLastSourcePos = true; + return tokenPos; } function setSourceFile(sourceFile) { + if (disabled) { + return; + } currentSourceFile = sourceFile; currentSourceText = currentSourceFile.text; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; @@ -41437,6 +42397,9 @@ var ts; } } function getText() { + if (disabled) { + return; + } encodeLastRecordedSourceMapSpan(); return ts.stringify({ version: 3, @@ -41449,6 +42412,9 @@ var ts; }); } function getSourceMappingURL() { + if (disabled) { + return; + } if (compilerOptions.inlineSourceMap) { var base64SourceMapText = ts.convertToBase64(getText()); return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; @@ -41458,46 +42424,7 @@ var ts; } } } - function createSourceMapWriterWithExtendedDiagnostics(host, writer) { - var _a = createSourceMapWriterWorker(host, writer), initialize = _a.initialize, reset = _a.reset, getSourceMapData = _a.getSourceMapData, setSourceFile = _a.setSourceFile, emitPos = _a.emitPos, emitStart = _a.emitStart, emitEnd = _a.emitEnd, emitTokenStart = _a.emitTokenStart, emitTokenEnd = _a.emitTokenEnd, changeEmitSourcePos = _a.changeEmitSourcePos, stopOverridingSpan = _a.stopOverridingSpan, getText = _a.getText, getSourceMappingURL = _a.getSourceMappingURL; - return { - initialize: initialize, - reset: reset, - getSourceMapData: getSourceMapData, - setSourceFile: setSourceFile, - emitPos: function (pos) { - ts.performance.mark("sourcemapStart"); - emitPos(pos); - ts.performance.measure("sourceMapTime", "sourcemapStart"); - }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitStart"); - emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitStart"); - }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitEnd"); - emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitEnd"); - }, - emitTokenStart: function (token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenStart"); - tokenStartPos = emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenStart"); - return tokenStartPos; - }, - emitTokenEnd: function (token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenEnd"); - tokenEndPos = emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenEnd"); - return tokenEndPos; - }, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: stopOverridingSpan, - getText: getText, - getSourceMappingURL: getSourceMappingURL - }; - } + ts.createSourceMapWriter = createSourceMapWriter; var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64FormatEncode(inValue) { if (inValue < 64) { @@ -41547,20 +42474,22 @@ var ts; emitBodyWithDetachedComments: emitBodyWithDetachedComments, emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition }; - function emitNodeWithComments(node, emitCallback) { + function emitNodeWithComments(emitContext, node, emitCallback) { if (disabled) { - emitCallback(node); + emitCallback(emitContext, node); return; } if (node) { - var _a = node.commentRange || node, pos = _a.pos, end = _a.end; - var emitFlags = node.emitFlags; + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var emitFlags = ts.getEmitFlags(node); if ((pos < 0 && end < 0) || (pos === end)) { if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } } else { @@ -41589,10 +42518,12 @@ var ts; ts.performance.measure("commentTime", "preEmitNodeWithComment"); } if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } if (extendedDiagnostics) { ts.performance.mark("beginEmitNodeWithComment"); @@ -41614,7 +42545,7 @@ var ts; ts.performance.mark("preEmitBodyWithDetachedComments"); } var pos = detachedRange.pos, end = detachedRange.end; - var emitFlags = node.emitFlags; + var emitFlags = ts.getEmitFlags(node); var skipLeadingComments = pos < 0 || (emitFlags & 16384) !== 0; var skipTrailingComments = disabled || end < 0 || (emitFlags & 32768) !== 0; if (!skipLeadingComments) { @@ -41623,8 +42554,10 @@ var ts; if (extendedDiagnostics) { ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); } - if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 65536 && !disabled) { + disabled = true; + emitCallback(node); + disabled = false; } else { emitCallback(node); @@ -41732,16 +42665,6 @@ var ts; currentLineMap = ts.getLineStarts(currentSourceFile); detachedCommentsInfo = undefined; } - function disableCommentsAndEmit(node, emitCallback) { - if (disabled) { - emitCallback(node); - } - else { - disabled = true; - emitCallback(node); - disabled = false; - } - } function hasDetachedComments(pos) { return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; } @@ -41793,11 +42716,11 @@ var ts; return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, false); } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -41833,7 +42756,7 @@ var ts; ts.forEach(sourceFile.referencedFiles, function (fileReference) { var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { addedGlobalFileReference = true; } emittedReferencedFiles.push(referencedFile); @@ -42018,7 +42941,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 | 1024, writer); errorNameNode = undefined; } } @@ -42030,7 +42953,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 | 1024, writer); errorNameNode = undefined; } } @@ -42223,7 +43146,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -42629,7 +43552,7 @@ var ts; } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); } function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; @@ -43197,14 +44120,14 @@ var ts; return emitSourceFile(node); } } - function writeReferencePath(referencedFile, addBundledFileReference) { + function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; if (ts.isDeclarationFile(referencedFile)) { declFileName = referencedFile.fileName; } else { - ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); } if (declFileName) { declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); @@ -43221,8 +44144,8 @@ var ts; } } } - function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencesOutput @@ -43248,7 +44171,9 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function emitFiles(resolver, host, targetSourceFile) { + var id = function (s) { return s; }; + var nullTransformers = [function (ctx) { return id; }]; + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) { var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; @@ -43256,7 +44181,7 @@ var ts; var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};"; var metadataHelper = "\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};"; var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; - var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; + var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; var generatorHelper = "\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;\n return { next: verb(0), \"throw\": verb(1), \"return\": verb(2) };\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};"; var exportStarHelper = "\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}"; var umdHelper = "\n(function (dependencies, factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define(dependencies, factory);\n }\n})"; @@ -43269,11 +44194,11 @@ var ts; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); var newLine = host.getNewLine(); - var transformers = ts.getTransformers(compilerOptions); + var transformers = emitOnlyDtsFiles ? nullTransformers : ts.getTransformers(compilerOptions); var writer = ts.createTextWriter(newLine); var write = writer.write, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; var sourceMap = ts.createSourceMapWriter(host, writer); - var emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitTokenStart = sourceMap.emitTokenStart, emitTokenEnd = sourceMap.emitTokenEnd; + var emitNodeWithSourceMap = sourceMap.emitNodeWithSourceMap, emitTokenWithSourceMap = sourceMap.emitTokenWithSourceMap; var comments = ts.createCommentWriter(host, writer, sourceMap); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; var nodeIdToGeneratedName; @@ -43290,14 +44215,17 @@ var ts; var awaiterEmitted; var isOwnFileEmit; var emitSkipped = false; + var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); ts.performance.mark("beforeTransform"); - var transformed = ts.transformFiles(resolver, host, ts.getSourceFilesToEmit(host, targetSourceFile), transformers); + var _a = ts.transformFiles(resolver, host, sourceFiles, transformers), transformed = _a.transformed, emitNodeWithSubstitution = _a.emitNodeWithSubstitution, emitNodeWithNotification = _a.emitNodeWithNotification; ts.performance.measure("transformTime", "beforeTransform"); - var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode; ts.performance.mark("beforePrint"); - ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile); - transformed.dispose(); + ts.forEachTransformedEmitFile(host, transformed, emitFile, emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); + for (var _b = 0, sourceFiles_4 = sourceFiles; _b < sourceFiles_4.length; _b++) { + var sourceFile = sourceFiles_4[_b]; + ts.disposeEmitNodes(sourceFile); + } return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -43306,16 +44234,20 @@ var ts; }; function emitFile(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, isBundledEmit) { if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + if (!emitOnlyDtsFiles) { + printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } } else { emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; } if (!emitSkipped && emittedFilesList) { - emittedFilesList.push(jsFilePath); + if (!emitOnlyDtsFiles) { + emittedFilesList.push(jsFilePath); + } if (sourceMapFilePath) { emittedFilesList.push(sourceMapFilePath); } @@ -43331,8 +44263,8 @@ var ts; generatedNameSet = ts.createMap(); isOwnFileEmit = !isBundledEmit; if (isBundledEmit && moduleKind) { - for (var _a = 0, sourceFiles_4 = sourceFiles; _a < sourceFiles_4.length; _a++) { - var sourceFile = sourceFiles_4[_a]; + for (var _a = 0, sourceFiles_5 = sourceFiles; _a < sourceFiles_5.length; _a++) { + var sourceFile = sourceFiles_5[_a]; emitEmitHelpers(sourceFile); } } @@ -43368,73 +44300,61 @@ var ts; currentFileIdentifiers = node.identifiers; sourceMap.setSourceFile(node); comments.setSourceFile(node); - emitNodeWithNotification(node, emitWorker); + pipelineEmitWithNotification(0, node); } function emit(node) { - emitNodeWithNotification(node, emitWithComments); - } - function emitWithComments(node) { - emitNodeWithComments(node, emitWithSourceMap); - } - function emitWithSourceMap(node) { - emitNodeWithSourceMap(node, emitWorker); + pipelineEmitWithNotification(3, node); } function emitIdentifierName(node) { - if (node) { - emitNodeWithNotification(node, emitIdentifierNameWithComments); - } - } - function emitIdentifierNameWithComments(node) { - emitNodeWithComments(node, emitWorker); + pipelineEmitWithNotification(2, node); } function emitExpression(node) { - emitNodeWithNotification(node, emitExpressionWithComments); + pipelineEmitWithNotification(1, node); } - function emitExpressionWithComments(node) { - emitNodeWithComments(node, emitExpressionWithSourceMap); + function pipelineEmitWithNotification(emitContext, node) { + emitNodeWithNotification(emitContext, node, pipelineEmitWithComments); } - function emitExpressionWithSourceMap(node) { - emitNodeWithSourceMap(node, emitExpressionWorker); - } - function emitNodeWithNotification(node, emitCallback) { - if (node) { - if (isEmitNotificationEnabled(node)) { - onEmitNode(node, emitCallback); - } - else { - emitCallback(node); - } - } - } - function emitNodeWithSourceMap(node, emitCallback) { - if (node) { - emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - emitCallback(node); - emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - function shouldSkipLeadingCommentsForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 16384) !== 0; - } - function shouldSkipLeadingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 512) !== 0; - } - function shouldSkipTrailingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 1024) !== 0; - } - function shouldSkipSourceMapForChildren(node) { - return (node.emitFlags & 2048) !== 0; - } - function emitWorker(node) { - if (tryEmitSubstitute(node, emitWorker, false)) { + function pipelineEmitWithComments(emitContext, node) { + if (emitContext === 0) { + pipelineEmitWithSourceMap(emitContext, node); return; } + emitNodeWithComments(emitContext, node, pipelineEmitWithSourceMap); + } + function pipelineEmitWithSourceMap(emitContext, node) { + if (emitContext === 0 + || emitContext === 2) { + pipelineEmitWithSubstitution(emitContext, node); + return; + } + emitNodeWithSourceMap(emitContext, node, pipelineEmitWithSubstitution); + } + function pipelineEmitWithSubstitution(emitContext, node) { + emitNodeWithSubstitution(emitContext, node, pipelineEmitForContext); + } + function pipelineEmitForContext(emitContext, node) { + switch (emitContext) { + case 0: return pipelineEmitInSourceFileContext(node); + case 2: return pipelineEmitInIdentifierNameContext(node); + case 3: return pipelineEmitInUnspecifiedContext(node); + case 1: return pipelineEmitInExpressionContext(node); + } + } + function pipelineEmitInSourceFileContext(node) { + var kind = node.kind; + switch (kind) { + case 256: + return emitSourceFile(node); + } + } + function pipelineEmitInIdentifierNameContext(node) { + var kind = node.kind; + switch (kind) { + case 69: + return emitIdentifier(node); + } + } + function pipelineEmitInUnspecifiedContext(node) { var kind = node.kind; switch (kind) { case 12: @@ -43461,7 +44381,8 @@ var ts; case 132: case 133: case 137: - return writeTokenNode(node); + writeTokenText(kind); + return; case 139: return emitQualifiedName(node); case 140: @@ -43637,17 +44558,12 @@ var ts; return emitShorthandPropertyAssignment(node); case 255: return emitEnumMember(node); - case 256: - return emitSourceFile(node); } if (ts.isExpression(node)) { - return emitExpressionWorker(node); + return pipelineEmitWithSubstitution(1, node); } } - function emitExpressionWorker(node) { - if (tryEmitSubstitute(node, emitExpressionWorker, true)) { - return; - } + function pipelineEmitInExpressionContext(node) { var kind = node.kind; switch (kind) { case 8: @@ -43663,7 +44579,8 @@ var ts; case 95: case 99: case 97: - return writeTokenNode(node); + writeTokenText(kind); + return; case 170: return emitArrayLiteralExpression(node); case 171: @@ -43741,7 +44658,7 @@ var ts; } } function emitIdentifier(node) { - if (node.emitFlags & 16) { + if (ts.getEmitFlags(node) & 16) { writeLines(umdHelper); } else { @@ -43956,7 +44873,7 @@ var ts; write("{}"); } else { - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 524288; if (indentedFlag) { increaseIndent(); } @@ -43969,21 +44886,18 @@ var ts; } } function emitPropertyAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } var indentBeforeDot = false; var indentAfterDot = false; - if (!(node.emitFlags & 1048576)) { + if (!(ts.getEmitFlags(node) & 1048576)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentText, node.expression.end) + 1; var dotToken = { kind: 21, pos: dotRangeStart, end: dotRangeEnd }; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } - var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); emitExpression(node.expression); increaseIndentIf(indentBeforeDot); + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); write(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); @@ -43994,15 +44908,14 @@ var ts; var text = getLiteralTextOfNode(expression); return text.indexOf(ts.tokenToString(21)) < 0; } - else { - var constantValue = tryGetConstEnumValue(expression); - return isFinite(constantValue) && Math.floor(constantValue) === constantValue; + else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { + var constantValue = ts.getConstantValue(expression); + return isFinite(constantValue) + && Math.floor(constantValue) === constantValue + && compilerOptions.removeComments; } } function emitElementAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } emitExpression(node.expression); write("["); emitExpression(node.argumentExpression); @@ -44157,7 +45070,7 @@ var ts; } } function emitBlockStatements(node) { - if (node.emitFlags & 32) { + if (ts.getEmitFlags(node) & 32) { emitList(node, node.statements, 384); } else { @@ -44332,11 +45245,11 @@ var ts; var body = node.body; if (body) { if (ts.isBlock(body)) { - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 524288; if (indentedFlag) { increaseIndent(); } - if (node.emitFlags & 4194304) { + if (ts.getEmitFlags(node) & 4194304) { emitSignatureHead(node); emitBlockFunctionBody(node, body); } @@ -44368,7 +45281,7 @@ var ts; emitWithPrefix(": ", node.type); } function shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) { - if (body.emitFlags & 32) { + if (ts.getEmitFlags(body) & 32) { return true; } if (body.multiLine) { @@ -44423,7 +45336,7 @@ var ts; emitModifiers(node, node.modifiers); write("class"); emitNodeWithPrefix(" ", node.name, emitIdentifierName); - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 524288; if (indentedFlag) { increaseIndent(); } @@ -44485,7 +45398,7 @@ var ts; emit(body); } function emitModuleBlock(node) { - if (isSingleLineEmptyBlock(node)) { + if (isEmptyBlock(node)) { write("{ }"); } else { @@ -44682,8 +45595,8 @@ var ts; emit(node.name); write(": "); var initializer = node.initializer; - if (!shouldSkipLeadingCommentsForNode(initializer)) { - var commentRange = initializer.commentRange || initializer; + if ((ts.getEmitFlags(initializer) & 16384) === 0) { + var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } emitExpression(initializer); @@ -44731,7 +45644,7 @@ var ts; return statements.length; } function emitHelpers(node) { - var emitFlags = node.emitFlags; + var emitFlags = ts.getEmitFlags(node); var helpersEmitted = false; if (emitFlags & 1) { helpersEmitted = emitEmitHelpers(currentSourceFile); @@ -44837,31 +45750,6 @@ var ts; write(suffix); } } - function tryEmitSubstitute(node, emitNode, isExpression) { - if (isSubstitutionEnabled(node) && (node.emitFlags & 128) === 0) { - var substitute = onSubstituteNode(node, isExpression); - if (substitute !== node) { - substitute.emitFlags |= 128; - emitNode(substitute); - return true; - } - } - return false; - } - function tryEmitConstantValue(node) { - var constantValue = tryGetConstEnumValue(node); - if (constantValue !== undefined) { - write(String(constantValue)); - if (!compilerOptions.removeComments) { - var propertyName = ts.isPropertyAccessExpression(node) - ? ts.declarationNameToString(node.name) - : getTextOfNode(node.argumentExpression); - write(" /* " + propertyName + " */"); - } - return true; - } - return false; - } function emitEmbeddedStatement(node) { if (ts.isBlock(node)) { write(" "); @@ -44961,7 +45849,7 @@ var ts; } } if (shouldEmitInterveningComments) { - var commentRange = child.commentRange || child; + var commentRange = ts.getCommentRange(child); emitTrailingCommentsOfPosition(commentRange.pos); } else { @@ -45003,27 +45891,12 @@ var ts; } } function writeToken(token, pos, contextNode) { - var tokenStartPos = emitTokenStart(token, pos, contextNode, shouldSkipLeadingSourceMapForToken, getTokenSourceMapRange); - var tokenEndPos = writeTokenText(token, tokenStartPos); - return emitTokenEnd(token, tokenEndPos, contextNode, shouldSkipTrailingSourceMapForToken, getTokenSourceMapRange); - } - function shouldSkipLeadingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 4096) !== 0; - } - function shouldSkipTrailingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 8192) !== 0; + return emitTokenWithSourceMap(contextNode, token, pos, writeTokenText); } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); - return ts.positionIsSynthesized(pos) ? -1 : pos + tokenString.length; - } - function writeTokenNode(node) { - if (node) { - emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - writeTokenText(node.kind); - emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } + return pos < 0 ? pos : pos + tokenString.length; } function increaseIndentIf(value, valueToWriteWhenNotIndenting) { if (value) { @@ -45162,17 +46035,12 @@ var ts; } return ts.getLiteralText(node, currentSourceFile, languageVersion); } - function tryGetConstEnumValue(node) { - if (compilerOptions.isolatedModules) { - return undefined; - } - return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) - ? resolver.getConstantValue(node) - : undefined; - } function isSingleLineEmptyBlock(block) { return !block.multiLine - && block.statements.length === 0 + && isEmptyBlock(block); + } + function isEmptyBlock(block) { + return block.statements.length === 0 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function isUniqueName(name) { @@ -45382,581 +46250,6 @@ var ts; return ts.getNormalizedPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; - function trace(host, message) { - host.trace(ts.formatMessage.apply(undefined, arguments)); - } - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - function hasZeroOrOneAsteriskCharacter(str) { - var seenAsterisk = false; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - return false; - } - } - } - return true; - } - ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; - } - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); - function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); - } - return typesFilePath_1; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } - } - } - } - var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); - if (typesFilePath) { - return typesFilePath; - } - if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); - } - var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - return mainFilePath; - } - return undefined; - } - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - return {}; - } - } - var typeReferenceExtensions = [".d.ts"]; - function getEffectiveTypeRoots(options, host) { - if (options.typeRoots) { - return options.typeRoots; - } - var currentDirectory; - if (options.configFilePath) { - currentDirectory = ts.getDirectoryPath(options.configFilePath); - } - else if (host.getCurrentDirectory) { - currentDirectory = host.getCurrentDirectory(); - } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; - } - var typeRoots; - while (true) { - var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - var parent_15 = ts.getDirectoryPath(currentDirectory); - if (parent_15 === currentDirectory) { - break; - } - currentDirectory = parent_15; - } - return typeRoots; - } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { - compilerOptions: options, - host: host, - skipTsx: true, - traceEnabled: traceEnabled - }; - var typeRoots = getEffectiveTypeRoots(options, host); - if (traceEnabled) { - if (containingFile === undefined) { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); - } - } - else { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); - } - } - } - var failedLookupLocations = []; - if (typeRoots && typeRoots.length) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); - } - var primarySearchPaths = typeRoots; - for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { - var typeRoot = primarySearchPaths_1[_i]; - var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); - var candidateDirectory = ts.getDirectoryPath(candidate); - var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); - if (resolvedFile_1) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); - } - return { - resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, - failedLookupLocations: failedLookupLocations - }; - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); - } - } - var resolvedFile; - var initialLocationForSecondaryLookup; - if (containingFile) { - initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); - } - if (initialLocationForSecondaryLookup !== undefined) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); - } - resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState); - if (traceEnabled) { - if (resolvedFile) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); - } - } - return { - resolvedTypeReferenceDirective: resolvedFile - ? { primary: false, resolvedFileName: resolvedFile } - : undefined, - failedLookupLocations: failedLookupLocations - }; - } - ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - var result; - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); - break; - case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host); - break; - } - if (traceEnabled) { - if (result.resolvedModule) { - trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); - } - else { - return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); - } - } - function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { - var subst = _a[_i]; - var path = matchedStar ? subst.replace("*", matchedStar) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - } - return undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - function tryParsePattern(pattern) { - ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var traceEnabled = isTraceEnabled(compilerOptions, host); - var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); - var isExternalLibraryImport = false; - if (!resolvedFileName) { - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); - } - resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); - isExternalLibraryImport = resolvedFileName !== undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); - } - } - if (resolvedFileName && host.realpath) { - var originalFileName = resolvedFileName; - resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); - } - } - return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); - } - var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); - return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); - } - function directoryProbablyExists(directoryName, host) { - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - if (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); - } - } - function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - return ts.forEach(extensions, function (ext) { - return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); - }); - } - function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; - } - } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); - if (typesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); - var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || - tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); - if (result) { - return result; - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); - } - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - failedLookupLocation.push(packageJsonPath); - } - return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); - } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); - var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - } - function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { - directory = ts.normalizeSlashes(directory); - while (true) { - var baseName = ts.getBaseFileName(directory); - if (baseName !== "node_modules") { - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - return packageResult; - } - else { - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; - } - } - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - break; - } - directory = parentPath; - } - return undefined; - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; - var failedLookupLocations = []; - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); - if (resolvedFileName) { - return createResolvedModule(resolvedFileName, false, failedLookupLocations); - } - var referencedSourceFile; - if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); - } - return referencedSourceFile - ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - ts.classicNameResolver = classicNameResolver; function createCompilerHost(options, setParentNodes) { var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { @@ -46058,7 +46351,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.getEnvironmentVariable(name, undefined); }, + getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; @@ -46126,33 +46419,6 @@ var ts; } return resolutions; } - function getAutomaticTypeDirectiveNames(options, host) { - if (options.types) { - return options.types; - } - var result = []; - if (host.directoryExists && host.getDirectories) { - var typeRoots = getEffectiveTypeRoots(options, host); - if (typeRoots) { - for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { - var root = typeRoots_1[_i]; - if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - result.push(ts.getBaseFileName(normalized)); - } - } - } - } - } - } - return result; - } - ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -46178,7 +46444,7 @@ var ts; resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; } else { - var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -46186,15 +46452,15 @@ var ts; resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; } else { - var loader_2 = function (typesRef, containingFile) { return resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; + var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); }; } var filesByName = ts.createFileMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - var typeReferences = getAutomaticTypeDirectiveNames(options, host); - if (typeReferences) { + var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + if (typeReferences.length) { var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { @@ -46236,7 +46502,8 @@ var ts; getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, - getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -46283,6 +46550,7 @@ var ts; (oldOptions.configFilePath !== options.configFilePath) || (oldOptions.baseUrl !== options.baseUrl) || (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || + !ts.arrayIsEqualTo(oldOptions.lib, options.lib) || !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || !ts.equalOwnProperties(oldOptions.paths, options.paths)) { @@ -46383,16 +46651,19 @@ var ts; function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false)); } - function emit(sourceFile, writeFileCallback, cancellationToken) { - return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); }); + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); } - function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { var declarationDiagnostics = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; @@ -46413,7 +46684,7 @@ var ts; } var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); ts.performance.mark("beforeEmit"); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -46928,7 +47199,6 @@ var ts; for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); - var resolvedPath = resolution ? ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName) : undefined; var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport; var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName); if (isFromNodeModulesSearch) { @@ -46940,7 +47210,7 @@ var ts; modulesWithElidedImports[file.path] = true; } else if (shouldAddFile) { - findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); + findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } if (isFromNodeModulesSearch) { currentNodeModulesDepth--; @@ -46954,8 +47224,8 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var file = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var file = sourceFiles_6[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -46966,8 +47236,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -47010,7 +47280,7 @@ var ts; if (!ts.hasProperty(options.paths, key)) { continue; } - if (!hasZeroOrOneAsteriskCharacter(key)) { + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { @@ -47021,7 +47291,7 @@ var ts; var subst = _a[_i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { - if (!hasZeroOrOneAsteriskCharacter(subst)) { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } @@ -47060,6 +47330,9 @@ var ts; if (options.lib && options.noLib) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")); } + if (options.noImplicitUseStrict && options.alwaysStrict) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict")); + } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); @@ -47136,11 +47409,13 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; ts.optionDeclarations = [ { name: "charset", type: "string" }, + ts.compileOnSaveCommandLineOption, { name: "declaration", shortName: "d", @@ -47563,6 +47838,11 @@ var ts; name: "importHelpers", type: "boolean", description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "alwaysStrict", + type: "boolean", + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file } ]; ts.typingOptionDeclarations = [ @@ -47764,10 +48044,11 @@ var ts; return parseConfigFileTextToJson(fileName, text); } ts.readConfigFile = readConfigFile; - function parseConfigFileTextToJson(fileName, jsonText) { + function parseConfigFileTextToJson(fileName, jsonText, stripComments) { + if (stripComments === void 0) { stripComments = true; } try { - var jsonTextWithoutComments = removeComments(jsonText); - return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; + var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; + return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; @@ -47901,13 +48182,15 @@ var ts; options = ts.extend(existingOptions, options); options.configFilePath = configFileName; var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, errors: errors, - wildcardDirectories: wildcardDirectories + wildcardDirectories: wildcardDirectories, + compileOnSave: compileOnSave }; function tryExtendsName(extendedConfig) { if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { @@ -47916,7 +48199,7 @@ var ts; } var extendedConfigPath = ts.toPath(extendedConfig, basePath, getCanonicalFileName); if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json")) { - extendedConfigPath = (extendedConfigPath + ".json"); + extendedConfigPath = extendedConfigPath + ".json"; if (!host.fileExists(extendedConfigPath)) { errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_does_not_exist, extendedConfig)); return; @@ -47985,6 +48268,17 @@ var ts; var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + if (typeof result === "boolean" && result) { + return result; + } + return false; + } + ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); @@ -47998,7 +48292,9 @@ var ts; } ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } + : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } @@ -48294,8 +48590,7 @@ var ts; _a[ts.DiagnosticCategory.Warning] = yellowForegroundEscapeSequence, _a[ts.DiagnosticCategory.Error] = redForegroundEscapeSequence, _a[ts.DiagnosticCategory.Message] = blueForegroundEscapeSequence, - _a - )); + _a)); function formatAndReset(text, formatStyle) { return formatStyle + text + resetEscapeSequence; } diff --git a/lib/tsserver.js b/lib/tsserver.js index 8bb071cf4a1..f5437988c1a 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -72,7 +72,6 @@ var ts; (function (ts) { ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; })(ts || (ts = {})); -var ts; (function (ts) { var performance; (function (performance) { @@ -150,6 +149,7 @@ var ts; contains: contains, remove: remove, forEachValue: forEachValueInMap, + getKeys: getKeys, clear: clear }; function forEachValueInMap(f) { @@ -157,6 +157,13 @@ var ts; f(key, files[key]); } } + function getKeys() { + var keys = []; + for (var key in files) { + keys.push(key); + } + return keys; + } function get(path) { return files[toKey(path)]; } @@ -533,16 +540,22 @@ var ts; : undefined; } ts.lastOrUndefined = lastOrUndefined; - function binarySearch(array, value) { + function binarySearch(array, value, comparer) { + if (!array || array.length === 0) { + return -1; + } var low = 0; var high = array.length - 1; + comparer = comparer !== undefined + ? comparer + : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; - if (midValue === value) { + if (comparer(midValue, value) === 0) { return middle; } - else if (midValue > value) { + else if (comparer(midValue, value) > 0) { high = middle - 1; } else { @@ -776,6 +789,56 @@ var ts; }; } ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (t) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { baseIndex = baseIndex || 0; return text.replace(/{(\d+)}/g, function (match, index) { return args[+index + baseIndex]; }); @@ -1012,10 +1075,45 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; + function isExternalModuleNameRelative(moduleName) { + return /^\.\.?($|[\\/])/.test(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; function isRootedDiskPath(path) { return getRootLength(path) !== 0; } ts.isRootedDiskPath = isRootedDiskPath; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); + } + ts.convertToRelativePath = convertToRelativePath; function normalizedPathComponents(path, rootLength) { var normalizedParts = getNormalizedParts(path, rootLength); return [path.substr(0, rootLength)].concat(normalizedParts); @@ -1389,6 +1487,14 @@ var ts; return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } ts.getSupportedExtensions = getSupportedExtensions; + function hasJavaScriptFileExtension(fileName) { + return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; @@ -1480,7 +1586,6 @@ var ts; this.transformFlags = 0; this.parent = undefined; this.original = undefined; - this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, @@ -1493,9 +1598,9 @@ var ts; }; var Debug; (function (Debug) { - var currentAssertionLevel; + Debug.currentAssertionLevel = 0; function shouldAssert(level) { - return getCurrentAssertionLevel() >= level; + return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -1513,30 +1618,7 @@ var ts; Debug.assert(false, message); } Debug.fail = fail; - function getCurrentAssertionLevel() { - if (currentAssertionLevel !== undefined) { - return currentAssertionLevel; - } - if (ts.sys === undefined) { - return 0; - } - var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); - currentAssertionLevel = developmentMode - ? 1 - : 0; - return currentAssertionLevel; - } })(Debug = ts.Debug || (ts.Debug = {})); - function getEnvironmentVariable(name, host) { - if (host && host.getEnvironmentVariable) { - return host.getEnvironmentVariable(name); - } - if (ts.sys && ts.sys.getEnvironmentVariable) { - return ts.sys.getEnvironmentVariable(name); - } - return ""; - } - ts.getEnvironmentVariable = getEnvironmentVariable; function orderedRemoveItemAt(array, index) { for (var i = index; i < array.length - 1; i++) { array[i] = array[i + 1]; @@ -1567,6 +1649,64 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + function tryParsePattern(pattern) { + Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; })(ts || (ts = {})); var ts; (function (ts) { @@ -1760,8 +1900,14 @@ var ts; function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; } + function isFileSystemCaseSensitive() { + if (platform === "win32" || platform === "win64") { + return false; + } + return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + } var platform = _os.platform(); - var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); function readFile(fileName, encoding) { if (!fileExists(fileName)) { return undefined; @@ -1886,6 +2032,9 @@ var ts; }, watchDirectory: function (directoryName, callback, recursive) { var options; + if (!directoryExists(directoryName)) { + return; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -1997,19 +2146,43 @@ var ts; realpath: realpath }; } + function recursiveCreateDirectory(directoryPath, sys) { + var basePath = ts.getDirectoryPath(directoryPath); + var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + if (shouldCreateParent) { + recursiveCreateDirectory(basePath, sys); + } + if (shouldCreateParent || !sys.directoryExists(directoryPath)) { + sys.createDirectory(directoryPath); + } + } + var sys; if (typeof ChakraHost !== "undefined") { - return getChakraSystem(); + sys = getChakraSystem(); } else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { - return getWScriptSystem(); + sys = getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { - return getNodeSystem(); + sys = getNodeSystem(); } - else { - return undefined; + if (sys) { + var originalWriteFile_1 = sys.writeFile; + sys.writeFile = function (path, data, writeBom) { + var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); + if (directoryPath && !sys.directoryExists(directoryPath)) { + recursiveCreateDirectory(directoryPath, sys); + } + originalWriteFile_1.call(sys, path, data, writeBom); + }; } + return sys; })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 + : 0; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -2334,7 +2507,7 @@ var ts; The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class" }, - All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "All_symbols_within_a_with_block_will_be_resolved_to_any_2410", message: "All symbols within a 'with' block will be resolved to 'any'." }, + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, @@ -2495,7 +2668,7 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, - Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, @@ -2728,6 +2901,8 @@ var ts; No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file" }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -2752,6 +2927,7 @@ var ts; Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, + Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type 'any' in some locations where its type cannot be determined." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -2781,7 +2957,14 @@ var ts; super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } + The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." }, + Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, + Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, + Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'" }, + Remove_unused_identifiers: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_unused_identifiers_90004", message: "Remove unused identifiers" }, + Implement_interface_on_reference: { code: 90005, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_reference_90005", message: "Implement interface on reference" }, + Implement_interface_on_class: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_class_90006", message: "Implement interface on class" }, + Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class" } }; })(ts || (ts = {})); var ts; @@ -3691,7 +3874,7 @@ var ts; return token = 69; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8"); + ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); var value = 0; var numberOfDigits = 0; while (true) { @@ -4334,11 +4517,13 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; ts.optionDeclarations = [ { name: "charset", type: "string" }, + ts.compileOnSaveCommandLineOption, { name: "declaration", shortName: "d", @@ -4761,6 +4946,11 @@ var ts; name: "importHelpers", type: "boolean", description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "alwaysStrict", + type: "boolean", + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file } ]; ts.typingOptionDeclarations = [ @@ -4962,10 +5152,11 @@ var ts; return parseConfigFileTextToJson(fileName, text); } ts.readConfigFile = readConfigFile; - function parseConfigFileTextToJson(fileName, jsonText) { + function parseConfigFileTextToJson(fileName, jsonText, stripComments) { + if (stripComments === void 0) { stripComments = true; } try { - var jsonTextWithoutComments = removeComments(jsonText); - return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; + var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; + return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; @@ -5099,13 +5290,15 @@ var ts; options = ts.extend(existingOptions, options); options.configFilePath = configFileName; var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, errors: errors, - wildcardDirectories: wildcardDirectories + wildcardDirectories: wildcardDirectories, + compileOnSave: compileOnSave }; function tryExtendsName(extendedConfig) { if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { @@ -5183,6 +5376,17 @@ var ts; var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + if (typeof result === "boolean" && result) { + return result; + } + return false; + } + ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); @@ -5196,7 +5400,9 @@ var ts; } ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } + : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } @@ -5395,6 +5601,937 @@ var ts; } })(ts || (ts = {})); var ts; +(function (ts) { + var JsTyping; + (function (JsTyping) { + ; + ; + var safeList; + var EmptySafeList = ts.createMap(); + function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { + var inferredTypings = ts.createMap(); + if (!typingOptions || !typingOptions.enableAutoDiscovery) { + return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; + } + fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { + var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)); + return kind === 1 || kind === 2; + }); + if (!safeList) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + safeList = result.config ? ts.createMap(result.config) : EmptySafeList; + } + var filesToWatch = []; + var searchDirs = []; + var exclude = []; + mergeTypings(typingOptions.include); + exclude = typingOptions.exclude || []; + var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); + if (projectRootPath !== undefined) { + possibleSearchDirs.push(projectRootPath); + } + searchDirs = ts.deduplicate(possibleSearchDirs); + for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { + var searchDir = searchDirs_1[_i]; + var packageJsonPath = ts.combinePaths(searchDir, "package.json"); + getTypingNamesFromJson(packageJsonPath, filesToWatch); + var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); + getTypingNamesFromJson(bowerJsonPath, filesToWatch); + var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); + getTypingNamesFromNodeModuleFolder(nodeModulesPath); + } + getTypingNamesFromSourceFileNames(fileNames); + for (var name_7 in packageNameToTypingLocation) { + if (name_7 in inferredTypings && !inferredTypings[name_7]) { + inferredTypings[name_7] = packageNameToTypingLocation[name_7]; + } + } + for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { + var excludeTypingName = exclude_1[_a]; + delete inferredTypings[excludeTypingName]; + } + var newTypingNames = []; + var cachedTypingPaths = []; + for (var typing in inferredTypings) { + if (inferredTypings[typing] !== undefined) { + cachedTypingPaths.push(inferredTypings[typing]); + } + else { + newTypingNames.push(typing); + } + } + return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + function mergeTypings(typingNames) { + if (!typingNames) { + return; + } + for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { + var typing = typingNames_1[_i]; + if (!(typing in inferredTypings)) { + inferredTypings[typing] = undefined; + } + } + } + function getTypingNamesFromJson(jsonPath, filesToWatch) { + var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); + if (result.config) { + var jsonConfig = result.config; + filesToWatch.push(jsonPath); + if (jsonConfig.dependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); + } + if (jsonConfig.devDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); + } + if (jsonConfig.optionalDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); + } + if (jsonConfig.peerDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); + } + } + } + function getTypingNamesFromSourceFileNames(fileNames) { + var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); + var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); + var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); + if (safeList !== EmptySafeList) { + mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); + } + var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2; }); + if (hasJsxFile) { + mergeTypings(["react"]); + } + } + function getTypingNamesFromNodeModuleFolder(nodeModulesPath) { + if (!host.directoryExists(nodeModulesPath)) { + return; + } + var typingNames = []; + var fileNames = host.readDirectory(nodeModulesPath, [".json"], undefined, undefined, 2); + for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { + var fileName = fileNames_2[_i]; + var normalizedFileName = ts.normalizePath(fileName); + if (ts.getBaseFileName(normalizedFileName) !== "package.json") { + continue; + } + var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + if (!result.config) { + continue; + } + var packageJson = result.config; + if (packageJson._requiredBy && + ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { + continue; + } + if (!packageJson.name) { + continue; + } + if (packageJson.typings) { + var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); + inferredTypings[packageJson.name] = absolutePath; + } + else { + typingNames.push(packageJson.name); + } + } + mergeTypings(typingNames); + } + } + JsTyping.discoverTypings = discoverTypings; + })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + (function (LogLevel) { + LogLevel[LogLevel["terse"] = 0] = "terse"; + LogLevel[LogLevel["normal"] = 1] = "normal"; + LogLevel[LogLevel["requestTime"] = 2] = "requestTime"; + LogLevel[LogLevel["verbose"] = 3] = "verbose"; + })(server.LogLevel || (server.LogLevel = {})); + var LogLevel = server.LogLevel; + server.emptyArray = []; + var Msg; + (function (Msg) { + Msg.Err = "Err"; + Msg.Info = "Info"; + Msg.Perf = "Perf"; + })(Msg = server.Msg || (server.Msg = {})); + function getProjectRootPath(project) { + switch (project.projectKind) { + case server.ProjectKind.Configured: + return ts.getDirectoryPath(project.getProjectName()); + case server.ProjectKind.Inferred: + return ""; + case server.ProjectKind.External: + var projectName = ts.normalizeSlashes(project.getProjectName()); + return project.projectService.host.fileExists(projectName) ? ts.getDirectoryPath(projectName) : projectName; + } + } + function createInstallTypingsRequest(project, typingOptions, cachePath) { + return { + projectName: project.getProjectName(), + fileNames: project.getFileNames(), + compilerOptions: project.getCompilerOptions(), + typingOptions: typingOptions, + projectRootPath: getProjectRootPath(project), + cachePath: cachePath, + kind: "discover" + }; + } + server.createInstallTypingsRequest = createInstallTypingsRequest; + var Errors; + (function (Errors) { + function ThrowNoProject() { + throw new Error("No Project."); + } + Errors.ThrowNoProject = ThrowNoProject; + function ThrowProjectLanguageServiceDisabled() { + throw new Error("The project's language service is disabled."); + } + Errors.ThrowProjectLanguageServiceDisabled = ThrowProjectLanguageServiceDisabled; + function ThrowProjectDoesNotContainDocument(fileName, project) { + throw new Error("Project '" + project.getProjectName() + "' does not contain document '" + fileName + "'"); + } + Errors.ThrowProjectDoesNotContainDocument = ThrowProjectDoesNotContainDocument; + })(Errors = server.Errors || (server.Errors = {})); + function getDefaultFormatCodeSettings(host) { + return { + indentSize: 4, + tabSize: 4, + newLineCharacter: host.newLine || "\n", + convertTabsToSpaces: true, + indentStyle: ts.IndentStyle.Smart, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false + }; + } + server.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings; + function mergeMaps(target, source) { + for (var key in source) { + if (ts.hasProperty(source, key)) { + target[key] = source[key]; + } + } + } + server.mergeMaps = mergeMaps; + function removeItemFromSet(items, itemToRemove) { + if (items.length === 0) { + return; + } + var index = items.indexOf(itemToRemove); + if (index < 0) { + return; + } + if (index === items.length - 1) { + items.pop(); + } + else { + items[index] = items.pop(); + } + } + server.removeItemFromSet = removeItemFromSet; + function toNormalizedPath(fileName) { + return ts.normalizePath(fileName); + } + server.toNormalizedPath = toNormalizedPath; + function normalizedPathToPath(normalizedPath, currentDirectory, getCanonicalFileName) { + var f = ts.isRootedDiskPath(normalizedPath) ? normalizedPath : ts.getNormalizedAbsolutePath(normalizedPath, currentDirectory); + return getCanonicalFileName(f); + } + server.normalizedPathToPath = normalizedPathToPath; + function asNormalizedPath(fileName) { + return fileName; + } + server.asNormalizedPath = asNormalizedPath; + function createNormalizedPathMap() { + var map = Object.create(null); + return { + get: function (path) { + return map[path]; + }, + set: function (path, value) { + map[path] = value; + }, + contains: function (path) { + return ts.hasProperty(map, path); + }, + remove: function (path) { + delete map[path]; + } + }; + } + server.createNormalizedPathMap = createNormalizedPathMap; + function throwLanguageServiceIsDisabledError() { + throw new Error("LanguageService is disabled"); + } + server.nullLanguageService = { + cleanupSemanticCache: throwLanguageServiceIsDisabledError, + getSyntacticDiagnostics: throwLanguageServiceIsDisabledError, + getSemanticDiagnostics: throwLanguageServiceIsDisabledError, + getCompilerOptionsDiagnostics: throwLanguageServiceIsDisabledError, + getSyntacticClassifications: throwLanguageServiceIsDisabledError, + getEncodedSyntacticClassifications: throwLanguageServiceIsDisabledError, + getSemanticClassifications: throwLanguageServiceIsDisabledError, + getEncodedSemanticClassifications: throwLanguageServiceIsDisabledError, + getCompletionsAtPosition: throwLanguageServiceIsDisabledError, + findReferences: throwLanguageServiceIsDisabledError, + getCompletionEntryDetails: throwLanguageServiceIsDisabledError, + getQuickInfoAtPosition: throwLanguageServiceIsDisabledError, + findRenameLocations: throwLanguageServiceIsDisabledError, + getNameOrDottedNameSpan: throwLanguageServiceIsDisabledError, + getBreakpointStatementAtPosition: throwLanguageServiceIsDisabledError, + getBraceMatchingAtPosition: throwLanguageServiceIsDisabledError, + getSignatureHelpItems: throwLanguageServiceIsDisabledError, + getDefinitionAtPosition: throwLanguageServiceIsDisabledError, + getRenameInfo: throwLanguageServiceIsDisabledError, + getTypeDefinitionAtPosition: throwLanguageServiceIsDisabledError, + getReferencesAtPosition: throwLanguageServiceIsDisabledError, + getDocumentHighlights: throwLanguageServiceIsDisabledError, + getOccurrencesAtPosition: throwLanguageServiceIsDisabledError, + getNavigateToItems: throwLanguageServiceIsDisabledError, + getNavigationBarItems: throwLanguageServiceIsDisabledError, + getNavigationTree: throwLanguageServiceIsDisabledError, + getOutliningSpans: throwLanguageServiceIsDisabledError, + getTodoComments: throwLanguageServiceIsDisabledError, + getIndentationAtPosition: throwLanguageServiceIsDisabledError, + getFormattingEditsForRange: throwLanguageServiceIsDisabledError, + getFormattingEditsForDocument: throwLanguageServiceIsDisabledError, + getFormattingEditsAfterKeystroke: throwLanguageServiceIsDisabledError, + getDocCommentTemplateAtPosition: throwLanguageServiceIsDisabledError, + isValidBraceCompletionAtPosition: throwLanguageServiceIsDisabledError, + getEmitOutput: throwLanguageServiceIsDisabledError, + getProgram: throwLanguageServiceIsDisabledError, + getNonBoundSourceFile: throwLanguageServiceIsDisabledError, + dispose: throwLanguageServiceIsDisabledError, + getCompletionEntrySymbol: throwLanguageServiceIsDisabledError, + getImplementationAtPosition: throwLanguageServiceIsDisabledError, + getSourceFile: throwLanguageServiceIsDisabledError, + getCodeFixesAtPosition: throwLanguageServiceIsDisabledError + }; + server.nullLanguageServiceHost = { + setCompilationSettings: function () { return undefined; }, + notifyFileRemoved: function () { return undefined; } + }; + function isInferredProjectName(name) { + return /dev\/null\/inferredProject\d+\*/.test(name); + } + server.isInferredProjectName = isInferredProjectName; + function makeInferredProjectName(counter) { + return "/dev/null/inferredProject" + counter + "*"; + } + server.makeInferredProjectName = makeInferredProjectName; + var ThrottledOperations = (function () { + function ThrottledOperations(host) { + this.host = host; + this.pendingTimeouts = ts.createMap(); + } + ThrottledOperations.prototype.schedule = function (operationId, delay, cb) { + if (ts.hasProperty(this.pendingTimeouts, operationId)) { + this.host.clearTimeout(this.pendingTimeouts[operationId]); + } + this.pendingTimeouts[operationId] = this.host.setTimeout(ThrottledOperations.run, delay, this, operationId, cb); + }; + ThrottledOperations.run = function (self, operationId, cb) { + delete self.pendingTimeouts[operationId]; + cb(); + }; + return ThrottledOperations; + }()); + server.ThrottledOperations = ThrottledOperations; + var GcTimer = (function () { + function GcTimer(host, delay, logger) { + this.host = host; + this.delay = delay; + this.logger = logger; + } + GcTimer.prototype.scheduleCollect = function () { + if (!this.host.gc || this.timerId != undefined) { + return; + } + this.timerId = this.host.setTimeout(GcTimer.run, this.delay, this); + }; + GcTimer.run = function (self) { + self.timerId = undefined; + var log = self.logger.hasLevel(LogLevel.requestTime); + var before = log && self.host.getMemoryUsage(); + self.host.gc(); + if (log) { + var after = self.host.getMemoryUsage(); + self.logger.perftrc("GC::before " + before + ", after " + after); + } + }; + return GcTimer; + }()); + server.GcTimer = GcTimer; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function trace(host, message) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; + } + ts.createResolvedModule = createResolvedModule; + function moduleHasNonRelativeName(moduleName) { + return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); + } + function tryReadTypesSection(packageJsonPath, baseDirectory, state) { + var jsonContent = readJson(packageJsonPath, state.host); + function tryReadFromField(fieldName) { + if (ts.hasProperty(jsonContent, fieldName)) { + var typesFile = jsonContent[fieldName]; + if (typeof typesFile === "string") { + var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); + } + return typesFilePath_1; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); + } + } + } + } + var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); + if (typesFilePath) { + return typesFilePath; + } + if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); + } + var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); + return mainFilePath; + } + return undefined; + } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + return {}; + } + } + var typeReferenceExtensions = [".d.ts"]; + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + return currentDirectory !== undefined && getDefaultTypeRoots(currentDirectory, host); + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + } + var typeRoots; + while (true) { + var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + var parent_1 = ts.getDirectoryPath(currentDirectory); + if (parent_1 === currentDirectory) { + break; + } + currentDirectory = parent_1; + } + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + var traceEnabled = isTraceEnabled(options, host); + var moduleResolutionState = { + compilerOptions: options, + host: host, + skipTsx: true, + traceEnabled: traceEnabled + }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === undefined) { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + } + } + else { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + } + } + } + var failedLookupLocations = []; + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + var primarySearchPaths = typeRoots; + for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { + var typeRoot = primarySearchPaths_1[_i]; + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); + if (resolvedFile_1) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); + } + return { + resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, + failedLookupLocations: failedLookupLocations + }; + } + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + var resolvedFile; + var initialLocationForSecondaryLookup; + if (containingFile) { + initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); + } + if (initialLocationForSecondaryLookup !== undefined) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, false); + if (traceEnabled) { + if (resolvedFile) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); + } + else { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + return { + resolvedTypeReferenceDirective: resolvedFile + ? { primary: false, resolvedFileName: resolvedFile } + : undefined, + failedLookupLocations: failedLookupLocations + }; + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + function getAutomaticTypeDirectiveNames(options, host) { + if (options.types) { + return options.types; + } + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + result.push(ts.getBaseFileName(normalized)); + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); + } + else { + return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); + } + } + function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { + var subst = _a[_i]; + var path = matchedStar ? subst.replace("*", matchedStar) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + } + return undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); + var isExternalLibraryImport = false; + if (!resolvedFileName) { + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state, false); + isExternalLibraryImport = resolvedFileName !== undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); + } + } + if (resolvedFileName && host.realpath) { + var originalFileName = resolvedFileName; + resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); + } + } + return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + if (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); + } + } + function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + return ts.forEach(extensions, function (ext) { + return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); + }); + } + function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + failedLookupLocation.push(fileName); + return undefined; + } + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { + var packageJsonPath = pathToPackageJson(candidate); + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); + if (typesFile) { + var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); + var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || + tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); + if (result) { + return result; + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); + } + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + failedLookupLocation.push(packageJsonPath); + } + return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); + } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } + function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); + var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + } + function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, false); + } + ts.loadModuleFromNodeModules = loadModuleFromNodeModules; + function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, false, true); + } + function loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, typesOnly) { + directory = ts.normalizeSlashes(directory); + while (true) { + var baseName = ts.getBaseFileName(directory); + if (baseName !== "node_modules") { + var packageResult = void 0; + if (!typesOnly) { + packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); + if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { + return packageResult; + } + } + var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); + if (typesResult || packageResult) { + return typesResult || packageResult; + } + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory || checkOneLevel) { + break; + } + directory = parentPath; + } + return undefined; + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; + var failedLookupLocations = []; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, false, failedLookupLocations); + } + var referencedSourceFile; + if (moduleHasNonRelativeName(moduleName)) { + referencedSourceFile = referencedSourceFile = loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) || + loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); + } + return referencedSourceFile + ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } + : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + } + ts.classicNameResolver = classicNameResolver; + function loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) { + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); + if (referencedSourceFile) { + return referencedSourceFile; + } + var parentPath = ts.getDirectoryPath(containingDirectory); + if (parentPath === containingDirectory) { + return undefined; + } + containingDirectory = parentPath; + } + } +})(ts || (ts = {})); +var ts; (function (ts) { ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { @@ -5877,10 +7014,10 @@ var ts; return !!(ts.getCombinedNodeFlags(node) & 1); } ts.isLet = isLet; - function isSuperCallExpression(n) { + function isSuperCall(n) { return n.kind === 174 && n.expression.kind === 95; } - ts.isSuperCallExpression = isSuperCallExpression; + ts.isSuperCall = isSuperCall; function isPrologueDirective(node) { return node.kind === 202 && node.expression.kind === 9; } @@ -5943,23 +7080,23 @@ var ts; case 139: case 172: case 97: - var parent_1 = node.parent; - if (parent_1.kind === 158) { + var parent_2 = node.parent; + if (parent_2.kind === 158) { return false; } - if (154 <= parent_1.kind && parent_1.kind <= 166) { + if (154 <= parent_2.kind && parent_2.kind <= 166) { return true; } - switch (parent_1.kind) { + switch (parent_2.kind) { case 194: - return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); + return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_2); case 141: - return node === parent_1.constraint; + return node === parent_2.constraint; case 145: case 144: case 142: case 218: - return node === parent_1.type; + return node === parent_2.type; case 220: case 179: case 180: @@ -5968,16 +7105,16 @@ var ts; case 146: case 149: case 150: - return node === parent_1.type; + return node === parent_2.type; case 151: case 152: case 153: - return node === parent_1.type; + return node === parent_2.type; case 177: - return node === parent_1.type; + return node === parent_2.type; case 174: case 175: - return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; + return parent_2.typeArguments && ts.indexOf(parent_2.typeArguments, node) >= 0; case 176: return false; } @@ -6030,9 +7167,9 @@ var ts; return; default: if (isFunctionLike(node)) { - var name_7 = node.name; - if (name_7 && name_7.kind === 140) { - traverse(name_7.expression); + var name_8 = node.name; + if (name_8 && name_8.kind === 140) { + traverse(name_8.expression); return; } } @@ -6128,6 +7265,12 @@ var ts; return node && node.kind === 147 && node.parent.kind === 171; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 147 && + (node.parent.kind === 171 || + node.parent.kind === 192); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { return predicate && predicate.kind === 1; } @@ -6238,13 +7381,13 @@ var ts; function getImmediatelyInvokedFunctionExpression(func) { if (func.kind === 179 || func.kind === 180) { var prev = func; - var parent_2 = func.parent; - while (parent_2.kind === 178) { - prev = parent_2; - parent_2 = parent_2.parent; + var parent_3 = func.parent; + while (parent_3.kind === 178) { + prev = parent_3; + parent_3 = parent_3.parent; } - if (parent_2.kind === 174 && parent_2.expression === prev) { - return parent_2; + if (parent_3.kind === 174 && parent_3.expression === prev) { + return parent_3; } } } @@ -6390,8 +7533,8 @@ var ts; case 8: case 9: case 97: - var parent_3 = node.parent; - switch (parent_3.kind) { + var parent_4 = node.parent; + switch (parent_4.kind) { case 218: case 142: case 145: @@ -6399,7 +7542,7 @@ var ts; case 255: case 253: case 169: - return parent_3.initializer === node; + return parent_4.initializer === node; case 202: case 203: case 204: @@ -6410,32 +7553,32 @@ var ts; case 249: case 215: case 213: - return parent_3.expression === node; + return parent_4.expression === node; case 206: - var forStatement = parent_3; + var forStatement = parent_4; return (forStatement.initializer === node && forStatement.initializer.kind !== 219) || forStatement.condition === node || forStatement.incrementor === node; case 207: case 208: - var forInStatement = parent_3; + var forInStatement = parent_4; return (forInStatement.initializer === node && forInStatement.initializer.kind !== 219) || forInStatement.expression === node; case 177: case 195: - return node === parent_3.expression; + return node === parent_4.expression; case 197: - return node === parent_3.expression; + return node === parent_4.expression; case 140: - return node === parent_3.expression; + return node === parent_4.expression; case 143: case 248: case 247: return true; case 194: - return parent_3.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_3); + return parent_4.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_4); default: - if (isPartOfExpression(parent_3)) { + if (isPartOfExpression(parent_4)) { return true; } } @@ -6443,10 +7586,6 @@ var ts; return false; } ts.isPartOfExpression = isPartOfExpression; - function isExternalModuleNameRelative(moduleName) { - return /^\.\.?($|[\\/])/.test(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { var moduleState = ts.getModuleInstanceState(node); return moduleState === 1 || @@ -6650,17 +7789,17 @@ var ts; node.parent && node.parent.kind === 225) { result = append(result, getJSDocs(node.parent, checkParentVariableStatement, getDocs, getTags)); } - var parent_4 = node.parent; - var isSourceOfAssignmentExpressionStatement = parent_4 && parent_4.parent && - parent_4.kind === 187 && - parent_4.operatorToken.kind === 56 && - parent_4.parent.kind === 202; + var parent_5 = node.parent; + var isSourceOfAssignmentExpressionStatement = parent_5 && parent_5.parent && + parent_5.kind === 187 && + parent_5.operatorToken.kind === 56 && + parent_5.parent.kind === 202; if (isSourceOfAssignmentExpressionStatement) { - result = append(result, getJSDocs(parent_4.parent, checkParentVariableStatement, getDocs, getTags)); + result = append(result, getJSDocs(parent_5.parent, checkParentVariableStatement, getDocs, getTags)); } - var isPropertyAssignmentExpression = parent_4 && parent_4.kind === 253; + var isPropertyAssignmentExpression = parent_5 && parent_5.kind === 253; if (isPropertyAssignmentExpression) { - result = append(result, getJSDocs(parent_4, checkParentVariableStatement, getDocs, getTags)); + result = append(result, getJSDocs(parent_5, checkParentVariableStatement, getDocs, getTags)); } if (node.kind === 142) { var paramTags = getJSDocParameterTag(node, checkParentVariableStatement); @@ -6693,8 +7832,8 @@ var ts; } } else if (param.name.kind === 69) { - var name_8 = param.name.text; - var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 && tag.parameterName.text === name_8; }); + var name_9 = param.name.text; + var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 && tag.parameterName.text === name_9; }); if (paramTags) { return paramTags; } @@ -6765,20 +7904,20 @@ var ts; node = node.parent; } while (true) { - var parent_5 = node.parent; - if (parent_5.kind === 170 || parent_5.kind === 191) { - node = parent_5; + var parent_6 = node.parent; + if (parent_6.kind === 170 || parent_6.kind === 191) { + node = parent_6; continue; } - if (parent_5.kind === 253 || parent_5.kind === 254) { - node = parent_5.parent; + if (parent_6.kind === 253 || parent_6.kind === 254) { + node = parent_6.parent; continue; } - return parent_5.kind === 187 && - isAssignmentOperator(parent_5.operatorToken.kind) && - parent_5.left === node || - (parent_5.kind === 207 || parent_5.kind === 208) && - parent_5.initializer === node; + return parent_6.kind === 187 && + isAssignmentOperator(parent_6.operatorToken.kind) && + parent_6.left === node || + (parent_6.kind === 207 || parent_6.kind === 208) && + parent_6.initializer === node; } } ts.isAssignmentTarget = isAssignmentTarget; @@ -7044,14 +8183,10 @@ var ts; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(node) { - return positionIsSynthesized(node.pos) - || positionIsSynthesized(node.end); + return ts.positionIsSynthesized(node.pos) + || ts.positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function positionIsSynthesized(pos) { - return !(pos >= 0); - } - ts.positionIsSynthesized = positionIsSynthesized; function getOriginalNode(node) { if (node) { while (node.original !== undefined) { @@ -7487,28 +8622,16 @@ var ts; function getDeclarationEmitOutputFilePath(sourceFile, host) { var options = host.getCompilerOptions(); var outputDir = options.declarationDir || options.outDir; - if (options.declaration) { - var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; - } + var path = outputDir + ? getSourceFilePathInNewDir(sourceFile, host, outputDir) + : sourceFile.fileName; + return ts.removeFileExtension(path) + ".d.ts"; } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; - function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0; - } - ts.getEmitScriptTarget = getEmitScriptTarget; - function getEmitModuleKind(compilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; - } - ts.getEmitModuleKind = getEmitModuleKind; function getSourceFilesToEmit(host, targetSourceFile) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { - var moduleKind = getEmitModuleKind(options); + var moduleKind = ts.getEmitModuleKind(options); var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; var sourceFiles = host.getSourceFiles(); return ts.filter(sourceFiles, moduleEmitEnabled ? isNonDeclarationFile : isBundleEmitNonExternalModule); @@ -7525,7 +8648,7 @@ var ts; function isBundleEmitNonExternalModule(sourceFile) { return !isDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile); } - function forEachTransformedEmitFile(host, sourceFiles, action) { + function forEachTransformedEmitFile(host, sourceFiles, action, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { onBundledEmit(host, sourceFiles); @@ -7552,7 +8675,7 @@ var ts; } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (options.declaration || emitOnlyDtsFiles) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], false); } function onBundledEmit(host, sourceFiles) { @@ -7568,7 +8691,7 @@ var ts; function getSourceMapFilePath(jsFilePath, options) { return options.sourceMap ? jsFilePath + ".map" : undefined; } - function forEachExpectedEmitFile(host, action, targetSourceFile) { + function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { onBundledEmit(host); @@ -7595,18 +8718,19 @@ var ts; } } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var emitFileNames = { jsFilePath: jsFilePath, sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), - declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined + declarationFilePath: declarationFilePath }; - action(emitFileNames, [sourceFile], false); + action(emitFileNames, [sourceFile], false, emitOnlyDtsFiles); } function onBundledEmit(host) { var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile) && (!ts.isExternalModule(sourceFile) || - !!getEmitModuleKind(options)); }); + !!ts.getEmitModuleKind(options)); }); if (bundledSources.length) { var jsFilePath = options.outFile || options.out; var emitFileNames = { @@ -7614,7 +8738,7 @@ var ts; sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined }; - action(emitFileNames, bundledSources, true); + action(emitFileNames, bundledSources, true, emitOnlyDtsFiles); } } } @@ -7651,13 +8775,32 @@ var ts; ts.getFirstConstructorWithBody = getFirstConstructorWithBody; function getSetAccessorTypeAnnotationNode(accessor) { if (accessor && accessor.parameters.length > 0) { - var hasThis = accessor.parameters.length === 2 && - accessor.parameters[0].name.kind === 69 && - accessor.parameters[0].name.originalKeywordKind === 97; + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); return accessor.parameters[hasThis ? 1 : 0].type; } } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + if (signature.parameters.length) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return node && node.kind === 69 && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 97; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -7971,14 +9114,6 @@ var ts; return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function hasJavaScriptFileExtension(fileName) { - return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function tryExtractTypeScriptExtension(fileName) { return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } @@ -8069,12 +9204,6 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !ts.isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); - } - ts.convertToRelativePath = convertToRelativePath; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { @@ -8163,9 +9292,9 @@ var ts; if (syntaxKindCache[kind]) { return syntaxKindCache[kind]; } - for (var name_9 in syntaxKindEnum) { - if (syntaxKindEnum[name_9] === kind) { - return syntaxKindCache[kind] = kind.toString() + " (" + name_9 + ")"; + for (var name_10 in syntaxKindEnum) { + if (syntaxKindEnum[name_10] === kind) { + return syntaxKindCache[kind] = kind.toString() + " (" + name_10 + ")"; } } } @@ -8175,7 +9304,7 @@ var ts; } ts.formatSyntaxKind = formatSyntaxKind; function movePos(pos, value) { - return positionIsSynthesized(pos) ? -1 : pos + value; + return ts.positionIsSynthesized(pos) ? -1 : pos + value; } ts.movePos = movePos; function createRange(pos, end) { @@ -8244,7 +9373,7 @@ var ts; } ts.positionsAreOnSameLine = positionsAreOnSameLine; function getStartPositionOfRange(range, sourceFile) { - return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); } ts.getStartPositionOfRange = getStartPositionOfRange; function collectExternalModuleInfo(sourceFile, resolver) { @@ -8281,8 +9410,8 @@ var ts; else { for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { var specifier = _c[_b]; - var name_10 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_10] || (exportSpecifiers[name_10] = [])).push(specifier); + var name_11 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_11] || (exportSpecifiers[name_11] = [])).push(specifier); } } break; @@ -8344,15 +9473,16 @@ var ts; return 11 <= kind && kind <= 14; } ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isTemplateLiteralFragmentKind(kind) { - return kind === 12 - || kind === 13 + function isTemplateHead(node) { + return node.kind === 12; + } + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 13 || kind === 14; } - function isTemplateLiteralFragment(node) { - return isTemplateLiteralFragmentKind(node.kind); - } - ts.isTemplateLiteralFragment = isTemplateLiteralFragment; + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; function isIdentifier(node) { return node.kind === 69; } @@ -8491,12 +9621,12 @@ var ts; return node.kind === 174; } ts.isCallExpression = isCallExpression; - function isTemplate(node) { + function isTemplateLiteral(node) { var kind = node.kind; return kind === 189 || kind === 11; } - ts.isTemplate = isTemplate; + ts.isTemplateLiteral = isTemplateLiteral; function isSpreadElementExpression(node) { return node.kind === 191; } @@ -8827,7 +9957,6 @@ var ts; } ts.isWatchSet = isWatchSet; })(ts || (ts = {})); -var ts; (function (ts) { function getDefaultLibFileName(options) { return options.target === 2 ? "lib.es6.d.ts" : "lib.d.ts"; @@ -9062,7 +10191,7 @@ var ts; ts.createSynthesizedNodeArray = createSynthesizedNodeArray; function getSynthesizedClone(node) { var clone = createNode(node.kind, undefined, node.flags); - clone.original = node; + setOriginalNode(clone, node); for (var key in node) { if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { continue; @@ -9094,7 +10223,7 @@ var ts; node.text = value; return node; } - else { + else if (value) { var node = createNode(9, location, undefined); node.textSourceNode = value; node.text = value.text; @@ -9381,7 +10510,7 @@ var ts; function createPropertyAccess(expression, name, location, flags) { var node = createNode(172, location, flags); node.expression = parenthesizeForAccess(expression); - node.emitFlags = 1048576; + (node.emitNode || (node.emitNode = {})).flags |= 1048576; node.name = typeof name === "string" ? createIdentifier(name) : name; return node; } @@ -9389,7 +10518,7 @@ var ts; function updatePropertyAccess(node, expression, name) { if (node.expression !== expression || node.name !== name) { var propertyAccess = createPropertyAccess(expression, name, node, node.flags); - propertyAccess.emitFlags = node.emitFlags; + (propertyAccess.emitNode || (propertyAccess.emitNode = {})).flags = getEmitFlags(node); return updateNode(propertyAccess, node); } return node; @@ -9493,7 +10622,7 @@ var ts; node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken || createNode(34); + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(34); node.body = parenthesizeConciseBody(body); return node; } @@ -9586,7 +10715,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right, location) { - var operatorToken = typeof operator === "number" ? createSynthesizedNode(operator) : operator; + var operatorToken = typeof operator === "number" ? createToken(operator) : operator; var operatorKind = operatorToken.kind; var node = createNode(187, location); node.left = parenthesizeBinaryOperand(operatorKind, left, true, undefined); @@ -10486,13 +11615,13 @@ var ts; } else { var expression = ts.isIdentifier(memberName) ? createPropertyAccess(target, memberName, location) : createElementAccess(target, memberName, location); - expression.emitFlags |= 2048; + (expression.emitNode || (expression.emitNode = {})).flags |= 2048; return expression; } } ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; function createRestParameter(name) { - return createParameterDeclaration(undefined, undefined, createSynthesizedNode(22), name, undefined, undefined, undefined); + return createParameterDeclaration(undefined, undefined, createToken(22), name, undefined, undefined, undefined); } ts.createRestParameter = createRestParameter; function createFunctionCall(func, thisArg, argumentsList, location) { @@ -10606,8 +11735,8 @@ var ts; } ts.createDecorateHelper = createDecorateHelper; function createAwaiterHelper(externalHelpersModuleName, hasLexicalArguments, promiseConstructor, body) { - var generatorFunc = createFunctionExpression(createNode(37), undefined, undefined, [], undefined, body); - generatorFunc.emitFlags |= 2097152; + var generatorFunc = createFunctionExpression(createToken(37), undefined, undefined, [], undefined, body); + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 2097152; return createCall(createHelperName(externalHelpersModuleName, "__awaiter"), undefined, [ createThis(), hasLexicalArguments ? createIdentifier("arguments") : createVoidZero(), @@ -10834,7 +11963,7 @@ var ts; target.push(startOnNewLine(createStatement(createLiteral("use strict")))); foundUseStrict = true; } - if (statement.emitFlags & 8388608) { + if (getEmitFlags(statement) & 8388608) { target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { @@ -10846,6 +11975,28 @@ var ts; return statementOffset; } ts.addPrologueDirectives = addPrologueDirectives; + function ensureUseStrict(node) { + var foundUseStrict = false; + for (var _i = 0, _a = node.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + break; + } + } + else { + break; + } + } + if (!foundUseStrict) { + var statements = []; + statements.push(startOnNewLine(createStatement(createLiteral("use strict")))); + return updateSourceFileNode(node, statements.concat(node.statements)); + } + return node; + } + ts.ensureUseStrict = ensureUseStrict; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = skipPartiallyEmittedExpressions(operand); if (skipped.kind === 178) { @@ -11085,17 +12236,112 @@ var ts; function setOriginalNode(node, original) { node.original = original; if (original) { - var emitFlags = original.emitFlags, commentRange = original.commentRange, sourceMapRange = original.sourceMapRange; - if (emitFlags) - node.emitFlags = emitFlags; - if (commentRange) - node.commentRange = commentRange; - if (sourceMapRange) - node.sourceMapRange = sourceMapRange; + var emitNode = original.emitNode; + if (emitNode) + node.emitNode = mergeEmitNode(emitNode, node.emitNode); } return node; } ts.setOriginalNode = setOriginalNode; + function mergeEmitNode(sourceEmitNode, destEmitNode) { + var flags = sourceEmitNode.flags, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges; + if (!destEmitNode && (flags || commentRange || sourceMapRange || tokenSourceMapRanges)) + destEmitNode = {}; + if (flags) + destEmitNode.flags = flags; + if (commentRange) + destEmitNode.commentRange = commentRange; + if (sourceMapRange) + destEmitNode.sourceMapRange = sourceMapRange; + if (tokenSourceMapRanges) + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + return destEmitNode; + } + function mergeTokenSourceMapRanges(sourceRanges, destRanges) { + if (!destRanges) + destRanges = ts.createMap(); + ts.copyProperties(sourceRanges, destRanges); + return destRanges; + } + function disposeEmitNodes(sourceFile) { + sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile)); + var emitNode = sourceFile && sourceFile.emitNode; + var annotatedNodes = emitNode && emitNode.annotatedNodes; + if (annotatedNodes) { + for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) { + var node = annotatedNodes_1[_i]; + node.emitNode = undefined; + } + } + } + ts.disposeEmitNodes = disposeEmitNodes; + function getOrCreateEmitNode(node) { + if (!node.emitNode) { + if (ts.isParseTreeNode(node)) { + if (node.kind === 256) { + return node.emitNode = { annotatedNodes: [node] }; + } + var sourceFile = ts.getSourceFileOfNode(node); + getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); + } + node.emitNode = {}; + } + return node.emitNode; + } + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags; + } + ts.getEmitFlags = getEmitFlags; + function setEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).flags = emitFlags; + return node; + } + ts.setEmitFlags = setEmitFlags; + function setSourceMapRange(node, range) { + getOrCreateEmitNode(node).sourceMapRange = range; + return node; + } + ts.setSourceMapRange = setSourceMapRange; + function setTokenSourceMapRange(node, token, range) { + var emitNode = getOrCreateEmitNode(node); + var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = ts.createMap()); + tokenSourceMapRanges[token] = range; + return node; + } + ts.setTokenSourceMapRange = setTokenSourceMapRange; + function setCommentRange(node, range) { + getOrCreateEmitNode(node).commentRange = range; + return node; + } + ts.setCommentRange = setCommentRange; + function getCommentRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.commentRange) || node; + } + ts.getCommentRange = getCommentRange; + function getSourceMapRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.sourceMapRange) || node; + } + ts.getSourceMapRange = getSourceMapRange; + function getTokenSourceMapRange(node, token) { + var emitNode = node.emitNode; + var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; + return tokenSourceMapRanges && tokenSourceMapRanges[token]; + } + ts.getTokenSourceMapRange = getTokenSourceMapRange; + function getConstantValue(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.constantValue; + } + ts.getConstantValue = getConstantValue; + function setConstantValue(node, value) { + var emitNode = getOrCreateEmitNode(node); + emitNode.constantValue = value; + return node; + } + ts.setConstantValue = setConstantValue; function setTextRange(node, location) { if (location) { node.pos = location.pos; @@ -11122,8 +12368,8 @@ var ts; function getLocalNameForExternalImport(node, sourceFile) { var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); if (namespaceDeclaration && !ts.isDefaultImport(node)) { - var name_11 = namespaceDeclaration.name; - return ts.isGeneratedIdentifier(name_11) ? name_11 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); + var name_12 = namespaceDeclaration.name; + return ts.isGeneratedIdentifier(name_12) ? name_12 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); } if (node.kind === 230 && node.importClause) { return getGeneratedNameForNode(node); @@ -12205,7 +13451,7 @@ var ts; case 16: return token() === 18 || token() === 20; case 18: - return token() === 27 || token() === 17; + return token() !== 24; case 20: return token() === 15 || token() === 16; case 13: @@ -12533,7 +13779,7 @@ var ts; } function parseTemplateExpression() { var template = createNode(189); - template.head = parseTemplateLiteralFragment(); + template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 12, "Template head has wrong token kind"); var templateSpans = createNodeArray(); do { @@ -12549,7 +13795,7 @@ var ts; var literal; if (token() === 16) { reScanTemplateToken(); - literal = parseTemplateLiteralFragment(); + literal = parseTemplateMiddleOrTemplateTail(); } else { literal = parseExpectedToken(14, false, ts.Diagnostics._0_expected, ts.tokenToString(16)); @@ -12560,8 +13806,15 @@ var ts; function parseLiteralNode(internName) { return parseLiteralLikeNode(token(), internName); } - function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token(), false); + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token(), false); + ts.Debug.assert(fragment.kind === 12, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token(), false); + ts.Debug.assert(fragment.kind === 13 || fragment.kind === 14, "Template fragment has wrong token kind"); + return fragment; } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -14822,8 +16075,8 @@ var ts; return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { - var name_12 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_12, undefined); + var name_13 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_13, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } @@ -14909,7 +16162,7 @@ var ts; parseExpected(56); node.type = parseType(); parseSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseEnumMember() { var node = createNode(255, scanner.getStartPos()); @@ -15847,8 +17100,8 @@ var ts; if (typeExpression.type.kind === 267) { var jsDocTypeReference = typeExpression.type; if (jsDocTypeReference.name.kind === 69) { - var name_13 = jsDocTypeReference.name; - if (name_13.text === "Object") { + var name_14 = jsDocTypeReference.name; + if (name_14.text === "Object") { typedefTag.jsDocTypeLiteral = scanChildTags(); } } @@ -15934,14 +17187,14 @@ var ts; } var typeParameters = createNodeArray(); while (true) { - var name_14 = parseJSDocIdentifierName(); + var name_15 = parseJSDocIdentifierName(); skipWhitespace(); - if (!name_14) { + if (!name_15) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(141, name_14.pos); - typeParameter.name = name_14; + var typeParameter = createNode(141, name_15.pos); + typeParameter.name = name_15; finishNode(typeParameter); typeParameters.push(typeParameter); if (token() === 24) { @@ -16344,7 +17597,7 @@ var ts; file = f; options = opts; languageVersion = ts.getEmitScriptTarget(options); - inStrictMode = !!file.externalModuleIndicator; + inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; skipTransformFlagAggregation = ts.isDeclarationFile(file); @@ -16374,6 +17627,14 @@ var ts; subtreeTransformFlags = 0; } return bindSourceFile; + function bindInStrictMode(file, opts) { + if (opts.alwaysStrict && !ts.isDeclarationFile(file)) { + return true; + } + else { + return !!file.externalModuleIndicator; + } + } function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); @@ -16492,11 +17753,17 @@ var ts; var message_1 = symbol.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (ts.hasModifier(declaration, 512)) { + if (symbol.declarations && symbol.declarations.length) { + if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } - }); + else { + if (symbol.declarations && symbol.declarations.length && + (isDefaultExport || (node.kind === 235 && !node.isExportEquals))) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + } + } ts.forEach(symbol.declarations, function (declaration) { file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); }); @@ -16561,7 +17828,7 @@ var ts; } else { currentFlow = { flags: 2 }; - if (containerFlags & 16) { + if (containerFlags & (16 | 128)) { currentFlow.container = node; } currentReturnTarget = undefined; @@ -17016,7 +18283,9 @@ var ts; currentFlow = preTryFlow; bind(node.finallyBlock); } - currentFlow = finishFlowLabel(postFinallyLabel); + if (!node.finallyBlock || !(currentFlow.flags & 1)) { + currentFlow = finishFlowLabel(postFinallyLabel); + } } function bindSwitchStatement(node) { var postSwitchLabel = createBranchLabel(); @@ -17149,7 +18418,7 @@ var ts; } else { ts.forEachChild(node, bind); - if (node.operator === 57 || node.operator === 42) { + if (node.operator === 41 || node.operator === 42) { bindAssignmentTargetFlow(node.operand); } } @@ -17248,9 +18517,12 @@ var ts; return 1 | 32; case 256: return 1 | 4 | 32; + case 147: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 | 4 | 32 | 8 | 128; + } case 148: case 220: - case 147: case 146: case 149: case 150: @@ -17782,7 +19054,7 @@ var ts; var flags = node.kind === 235 && ts.exportAssignmentIsAlias(node) ? 8388608 : 4; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 | 8388608); + declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 | 8388608 | 32 | 16); } } function bindNamespaceExportDeclaration(node) { @@ -17794,12 +19066,12 @@ var ts; return; } else { - var parent_6 = node.parent; - if (!ts.isExternalModule(parent_6)) { + var parent_7 = node.parent; + if (!ts.isExternalModule(parent_7)) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); return; } - if (!parent_6.isDeclarationFile) { + if (!parent_7.isDeclarationFile) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); return; } @@ -17979,6 +19251,9 @@ var ts; emitFlags |= 2048; } } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } return ts.hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); @@ -18117,8 +19392,7 @@ var ts; if (node.questionToken) { transformFlags |= 3; } - if (subtreeFlags & 2048 - || (name && ts.isIdentifier(name) && name.originalKeywordKind === 97)) { + if (subtreeFlags & 2048 || ts.isThisIdentifier(name)) { transformFlags |= 3; } if (modifierFlags & 92) { @@ -18220,7 +19494,7 @@ var ts; || (subtreeFlags & 2048)) { transformFlags |= 3; } - if (asteriskToken && node.emitFlags & 2097152) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152) { transformFlags |= 1536; } node.transformFlags = transformFlags | 536870912; @@ -18265,7 +19539,7 @@ var ts; if (subtreeFlags & 81920) { transformFlags |= 192; } - if (asteriskToken && node.emitFlags & 2097152) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152) { transformFlags |= 1536; } } @@ -18282,7 +19556,7 @@ var ts; if (subtreeFlags & 81920) { transformFlags |= 192; } - if (asteriskToken && node.emitFlags & 2097152) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152) { transformFlags |= 1536; } node.transformFlags = transformFlags | 536870912; @@ -18618,6 +19892,7 @@ var ts; var unknownSymbol = createSymbol(4 | 67108864, "unknown"); var resolvingSymbol = createSymbol(67108864, "__resolving__"); var anyType = createIntrinsicType(1, "any"); + var autoType = createIntrinsicType(1, "any"); var unknownType = createIntrinsicType(1, "unknown"); var undefinedType = createIntrinsicType(2048, "undefined"); var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 33554432, "undefined"); @@ -19175,7 +20450,7 @@ var ts; if (result && isInExternalModule && (meaning & 107455) === 107455) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 228) { - error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name); } } } @@ -19335,28 +20610,28 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_15 = specifier.propertyName || specifier.name; - if (name_15.text) { + var name_16 = specifier.propertyName || specifier.name; + if (name_16.text) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { return moduleSymbol; } var symbolFromVariable = void 0; if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_15.text); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_16.text); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_15.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_16.text); } symbolFromVariable = resolveSymbol(symbolFromVariable); - var symbolFromModule = getExportOfModule(targetSymbol, name_15.text); - if (!symbolFromModule && allowSyntheticDefaultImports && name_15.text === "default") { + var symbolFromModule = getExportOfModule(targetSymbol, name_16.text); + if (!symbolFromModule && allowSyntheticDefaultImports && name_16.text === "default") { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_15, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_15)); + error(name_16, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_16)); } return symbol; } @@ -19593,6 +20868,7 @@ var ts; } function getExportsForModule(moduleSymbol) { var visitedSymbols = []; + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || moduleSymbol.exports; function visit(symbol) { if (!(symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol))) { @@ -20077,9 +21353,9 @@ var ts; var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent_7) { - walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), false); + var parent_8 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_8) { + walkSymbol(parent_8, getQualifiedLeftMeaning(meaning), false); } } if (accessibleSymbolChain) { @@ -20114,7 +21390,7 @@ var ts; ? "any" : type.intrinsicName); } - else if (type.flags & 268435456) { + else if (type.flags & 16384 && type.isThisType) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } @@ -20131,7 +21407,7 @@ var ts; else if (type.flags & (32768 | 65536 | 16 | 16384)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } - else if (!(flags & 512) && type.flags & (2097152 | 1572864) && type.aliasSymbol && + else if (!(flags & 512) && ((type.flags & 2097152 && !type.target) || type.flags & 1572864) && type.aliasSymbol && isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); @@ -20201,12 +21477,12 @@ var ts; var length_1 = outerTypeParameters.length; while (i < length_1) { var start = i; - var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_9 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_9); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_8, typeArguments, start, i, flags); + writeSymbolTypeReference(parent_9, typeArguments, start, i, flags); writePunctuation(writer, 21); } } @@ -20595,12 +21871,12 @@ var ts; if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_9 = getDeclarationContainer(node); + var parent_10 = getDeclarationContainer(node); if (!(ts.getCombinedModifierFlags(node) & 1) && - !(node.kind !== 229 && parent_9.kind !== 256 && ts.isInAmbientContext(parent_9))) { - return isGlobalSourceFile(parent_9); + !(node.kind !== 229 && parent_10.kind !== 256 && ts.isInAmbientContext(parent_10))) { + return isGlobalSourceFile(parent_10); } - return isDeclarationVisible(parent_9); + return isDeclarationVisible(parent_10); case 145: case 144: case 149: @@ -20787,19 +22063,19 @@ var ts; } var type; if (pattern.kind === 167) { - var name_16 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_16)) { + var name_17 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_17)) { return anyType; } if (declaration.initializer) { getContextualType(declaration.initializer); } - var text = getTextOfPropertyName(name_16); + var text = getTextOfPropertyName(name_17); type = getTypeOfPropertyOfType(parentType, text) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); if (!type) { - error(name_16, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_16)); + error(name_17, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_17)); return unknownType; } } @@ -20858,6 +22134,10 @@ var ts; } return undefined; } + function isAutoVariableInitializer(initializer) { + var expr = initializer && ts.skipParentheses(initializer); + return !expr || expr.kind === 93 || expr.kind === 69 && getResolvedSymbol(expr) === undefinedSymbol; + } function addOptionality(type, optional) { return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; } @@ -20880,6 +22160,11 @@ var ts; if (declaration.type) { return addOptionality(getTypeFromTypeNode(declaration.type), declaration.questionToken && includeOptionality); } + if (declaration.kind === 218 && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedNodeFlags(declaration) & 2) && !(ts.getCombinedModifierFlags(declaration) & 1) && + !ts.isInAmbientContext(declaration) && isAutoVariableInitializer(declaration.initializer)) { + return autoType; + } if (declaration.kind === 142) { var func = declaration.parent; if (func.kind === 150 && !ts.hasDynamicName(func)) { @@ -20951,7 +22236,7 @@ var ts; result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 536870912; + result.isObjectLiteralPatternWithComputedProperties = true; } return result; } @@ -21420,7 +22705,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); + type.thisType = createType(16384); + type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -21953,13 +23239,24 @@ var ts; var current = _a[_i]; for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { var prop = _c[_b]; - getPropertyOfUnionOrIntersectionType(type, prop.name); + getUnionOrIntersectionProperty(type, prop.name); } if (type.flags & 524288) { break; } } - return type.resolvedProperties ? symbolsToArray(type.resolvedProperties) : emptyArray; + var props = type.resolvedProperties; + if (props) { + var result = []; + for (var key in props) { + var prop = props[key]; + if (!(prop.flags & 268435456 && prop.isPartial)) { + result.push(prop); + } + } + return result; + } + return emptyArray; } function getPropertiesOfType(type) { type = getApparentType(type); @@ -21998,6 +23295,7 @@ var ts; var props; var commonFlags = (containingType.flags & 1048576) ? 536870912 : 0; var isReadonly = false; + var isPartial = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); @@ -22016,20 +23314,20 @@ var ts; } } else if (containingType.flags & 524288) { - return undefined; + isPartial = true; } } } if (!props) { return undefined; } - if (props.length === 1) { + if (props.length === 1 && !isPartial) { return props[0]; } var propTypes = []; var declarations = []; var commonType = undefined; - var hasCommonType = true; + var hasNonUniformType = false; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { @@ -22040,22 +23338,20 @@ var ts; commonType = type; } else if (type !== commonType) { - hasCommonType = false; + hasNonUniformType = true; } - propTypes.push(getTypeOfSymbol(prop)); + propTypes.push(type); } - var result = createSymbol(4 | - 67108864 | - 268435456 | - commonFlags, name); + var result = createSymbol(4 | 67108864 | 268435456 | commonFlags, name); result.containingType = containingType; - result.hasCommonType = hasCommonType; + result.hasNonUniformType = hasNonUniformType; + result.isPartial = isPartial; result.declarations = declarations; result.isReadonly = isReadonly; result.type = containingType.flags & 524288 ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } - function getPropertyOfUnionOrIntersectionType(type, name) { + function getUnionOrIntersectionProperty(type, name) { var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); var property = properties[name]; if (!property) { @@ -22066,6 +23362,10 @@ var ts; } return property; } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + return property && !(property.flags & 268435456 && property.isPartial) ? property : undefined; + } function getPropertyOfType(type, name) { type = getApparentType(type); if (type.flags & 2588672) { @@ -22438,7 +23738,7 @@ var ts; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 268435456) && type.flags & 16384 && !ts.contains(checked, type)) { + while (type && type.flags & 16384 && !(type.isThisType) && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -22722,7 +24022,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); + type.thisType = createType(16384); + type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; type.declaredCallSignatures = emptyArray; @@ -22821,7 +24122,24 @@ var ts; } return false; } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 256) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 256) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } var i = types.length; while (i > 0) { i--; @@ -23796,7 +25114,8 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 536870912) && maybeTypeOfKind(target, 2588672)) { + if (maybeTypeOfKind(target, 2588672) && + (!(target.flags & 2588672) || !target.isObjectLiteralPatternWithComputedProperties)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -25001,17 +26320,10 @@ var ts; } function isDiscriminantProperty(type, name) { if (type && type.flags & 524288) { - var prop = getPropertyOfType(type, name); - if (!prop) { - var filteredType = getTypeWithFacts(type, 4194304); - if (filteredType !== type && filteredType.flags & 524288) { - prop = getPropertyOfType(filteredType, name); - } - } + var prop = getUnionOrIntersectionProperty(type, name); if (prop && prop.flags & 268435456) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !prop.hasCommonType && - isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = prop.hasNonUniformType && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -25288,6 +26600,23 @@ var ts; } return f(type) ? type : neverType; } + function mapType(type, f) { + return type.flags & 524288 ? getUnionType(ts.map(type.types, f)) : f(type); + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 2 ? extractTypesOfKind(typeWithLiterals, 2 | 32) : + t.flags & 4 ? extractTypesOfKind(typeWithLiterals, 4 | 64) : + t; + }); + } + return typeWithPrimitives; + } function isIncomplete(flowType) { return flowType.flags === 0; } @@ -25302,7 +26631,9 @@ var ts; if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048); + var initialType = assumeInitialized ? declaredType : + declaredType === autoType ? undefinedType : + includeFalsyTypes(declaredType, 2048); var visitedFlowStart = visitedFlowCount; var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; @@ -25364,10 +26695,13 @@ var ts; function getTypeAtFlowAssignment(flow) { var node = flow.node; if (isMatchingReference(reference, node)) { - var isIncrementOrDecrement = node.parent.kind === 185 || node.parent.kind === 186; - return declaredType.flags & 524288 && !isIncrementOrDecrement ? - getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : - declaredType; + if (node.parent.kind === 185 || node.parent.kind === 186) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + return declaredType === autoType ? getBaseTypeOfLiteralType(getInitialOrAssignedType(node)) : + declaredType.flags & 524288 ? getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : + declaredType; } if (containsMatchingReference(reference, node)) { return declaredType; @@ -25553,12 +26887,12 @@ var ts; assumeTrue ? 16384 : 131072; return getTypeWithFacts(type, facts); } - if (type.flags & 2589191) { + if (type.flags & 2589185) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 ? type : narrowedType; + return narrowedType.flags & 8192 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -25596,7 +26930,8 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); + var caseType = discriminantType.flags & 8192 ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -25723,7 +27058,7 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpression(location) && !ts.isAssignmentTarget(location)) { + if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { var type = checkExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; @@ -25846,14 +27181,26 @@ var ts; var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; while (flowContainer !== declarationContainer && - (flowContainer.kind === 179 || flowContainer.kind === 180) && + (flowContainer.kind === 179 || + flowContainer.kind === 180 || + ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } - var assumeInitialized = !strictNullChecks || (type.flags & 1) !== 0 || isParameter || - isOuterVariable || ts.isInAmbientContext(declaration); + var assumeInitialized = isParameter || isOuterVariable || + type !== autoType && (!strictNullChecks || (type.flags & 1) !== 0) || + ts.isInAmbientContext(declaration); var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); - if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { + if (type === autoType) { + if (flowType === autoType) { + if (compilerOptions.noImplicitAny) { + error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol)); + error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(anyType)); + } + return anyType; + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); return type; } @@ -25938,7 +27285,7 @@ var ts; } } function findFirstSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return n; } else if (ts.isFunctionLike(n)) { @@ -26003,7 +27350,7 @@ var ts; captureLexicalThis(node, container); } if (ts.isFunctionLike(container) && - (!isInParameterInitializerBeforeContainingFunction(node) || getFunctionLikeThisParameter(container))) { + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { if (container.kind === 179 && ts.isInJavaScriptFile(container.parent) && ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { @@ -26222,11 +27569,11 @@ var ts; } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name_17 = declaration.propertyName || declaration.name; + var name_18 = declaration.propertyName || declaration.name; if (ts.isVariableLike(parentDeclaration) && parentDeclaration.type && - !ts.isBindingPattern(name_17)) { - var text = getTextOfPropertyName(name_17); + !ts.isBindingPattern(name_18)) { + var text = getTextOfPropertyName(name_18); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); } @@ -26663,7 +28010,8 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 536870912)) { + else if (contextualTypeHasPattern && + !(contextualType.flags & 2588672 && contextualType.isObjectLiteralPatternWithComputedProperties)) { var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { prop.flags |= impliedProp.flags & 536870912; @@ -26714,7 +28062,10 @@ var ts; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216; - result.flags |= 8388608 | 67108864 | freshObjectLiteralFlag | (typeFlags & 234881024) | (patternWithComputedProperties ? 536870912 : 0); + result.flags |= 8388608 | 67108864 | freshObjectLiteralFlag | (typeFlags & 234881024); + if (patternWithComputedProperties) { + result.isObjectLiteralPatternWithComputedProperties = true; + } if (inDestructuringPattern) { result.pattern = node; } @@ -27109,7 +28460,7 @@ var ts; if (flags & 32) { return true; } - if (type.flags & 268435456) { + if (type.flags & 16384 && type.isThisType) { type = getConstraintOfTypeParameter(type); } if (!(getTargetType(type).flags & (32768 | 65536) && hasBaseType(type, enclosingClass))) { @@ -27150,7 +28501,7 @@ var ts; var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 268435456 ? apparentType : type); + reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); } return unknownType; } @@ -27266,15 +28617,15 @@ var ts; return unknownType; } if (node.argumentExpression) { - var name_18 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_18 !== undefined) { - var prop = getPropertyOfType(objectType, name_18); + var name_19 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_19 !== undefined) { + var prop = getPropertyOfType(objectType, name_19); if (prop) { getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); } else if (isConstEnum) { - error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_18, symbolToString(objectType.symbol)); + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_19, symbolToString(objectType.symbol)); return unknownType; } } @@ -27375,19 +28726,19 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_10 = signature.declaration && signature.declaration.parent; + var parent_11 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_10 === lastParent) { + if (lastParent && parent_11 === lastParent) { index++; } else { - lastParent = parent_10; + lastParent = parent_11; index = cutoffIndex; } } else { index = cutoffIndex = result.length; - lastParent = parent_10; + lastParent = parent_11; } lastSymbol = symbol; if (signature.hasLiteralTypes) { @@ -28290,7 +29641,9 @@ var ts; if (!contextualSignature) { reportErrorsFromWidening(func, type); } - if (isUnitType(type) && !(contextualSignature && isLiteralContextualType(getReturnTypeOfSignature(contextualSignature)))) { + if (isUnitType(type) && + !(contextualSignature && + isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { type = getWidenedLiteralType(type); } var widenedType = getWidenedType(type); @@ -28440,7 +29793,7 @@ var ts; } } } - if (produceDiagnostics && node.kind !== 147 && node.kind !== 146) { + if (produceDiagnostics && node.kind !== 147) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } @@ -28690,14 +30043,14 @@ var ts; } function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, contextualMapper) { if (property.kind === 253 || property.kind === 254) { - var name_19 = property.name; - if (name_19.kind === 140) { - checkComputedPropertyName(name_19); + var name_20 = property.name; + if (name_20.kind === 140) { + checkComputedPropertyName(name_20); } - if (isComputedNonLiteralName(name_19)) { + if (isComputedNonLiteralName(name_20)) { return undefined; } - var text = getTextOfPropertyName(name_19); + var text = getTextOfPropertyName(name_20); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || @@ -28712,7 +30065,7 @@ var ts; } } else { - error(name_19, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_19)); + error(name_20, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_20)); } } else { @@ -29361,9 +30714,9 @@ var ts; else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name_20 = _a[_i].name; - if (ts.isBindingPattern(name_20) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_20, parameterName, typePredicate.parameterName)) { + var name_21 = _a[_i].name; + if (ts.isBindingPattern(name_21) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_21, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -29383,9 +30736,9 @@ var ts; case 156: case 147: case 146: - var parent_11 = node.parent; - if (node === parent_11.type) { - return parent_11; + var parent_12 = node.parent; + if (node === parent_12.type) { + return parent_12; } } } @@ -29395,15 +30748,15 @@ var ts; if (ts.isOmittedExpression(element)) { continue; } - var name_21 = element.name; - if (name_21.kind === 69 && - name_21.text === predicateVariableName) { + var name_22 = element.name; + if (name_22.kind === 69 && + name_22.text === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name_21.kind === 168 || - name_21.kind === 167) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_21, predicateVariableNode, predicateVariableName)) { + else if (name_22.kind === 168 || + name_22.kind === 167) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_22, predicateVariableNode, predicateVariableName)) { return true; } } @@ -29596,7 +30949,7 @@ var ts; return n.name && containsSuperCall(n.name); } function containsSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return true; } else if (ts.isFunctionLike(n)) { @@ -29622,6 +30975,7 @@ var ts; } var containingClassDecl = node.parent; if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); if (superCall) { @@ -29635,7 +30989,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 202 && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 202 && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -30345,7 +31699,7 @@ var ts; var parameter = local.valueDeclaration; if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && - !parameterIsThisKeyword(parameter) && + !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(parameter)) { error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } @@ -30360,9 +31714,6 @@ var ts; } } } - function parameterIsThisKeyword(parameter) { - return parameter.name && parameter.name.originalKeywordKind === 97; - } function parameterNameStartsWithUnderscore(parameter) { return parameter.name && parameter.name.kind === 69 && parameter.name.text.charCodeAt(0) === 95; } @@ -30500,6 +31851,9 @@ var ts; } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + if (modulekind >= ts.ModuleKind.ES6) { + return; + } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } @@ -30547,8 +31901,8 @@ var ts; container.kind === 225 || container.kind === 256); if (!namesShareScope) { - var name_22 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_22, name_22); + var name_23 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_23, name_23); } } } @@ -30603,6 +31957,9 @@ var ts; } } } + function convertAutoToAny(type) { + return type === autoType ? anyType : type; + } function checkVariableLikeDeclaration(node) { checkDecorators(node); checkSourceElement(node.type); @@ -30616,12 +31973,12 @@ var ts; if (node.propertyName && node.propertyName.kind === 140) { checkComputedPropertyName(node.propertyName); } - var parent_12 = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent_12); - var name_23 = node.propertyName || node.name; - var property = getPropertyOfType(parentType, getTextOfPropertyName(name_23)); - if (parent_12.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property); + var parent_13 = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent_13); + var name_24 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, getTextOfPropertyName(name_24)); + if (parent_13.initializer && property && getParentOfSymbol(property)) { + checkClassPropertyAccess(parent_13, parent_13.initializer, parentType, property); } } if (ts.isBindingPattern(node.name)) { @@ -30639,7 +31996,7 @@ var ts; return; } var symbol = getSymbolOfNode(node); - var type = getTypeOfVariableOrParameterOrProperty(symbol); + var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); if (node === symbol.valueDeclaration) { if (node.initializer && node.parent.parent.kind !== 207) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); @@ -30647,7 +32004,7 @@ var ts; } } else { - var declarationType = getWidenedTypeForVariableLikeDeclaration(node); + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); } @@ -31022,7 +32379,12 @@ var ts; } } checkExpression(node.expression); - error(node.expression, ts.Diagnostics.All_symbols_within_a_with_block_will_be_resolved_to_any); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } } function checkSwitchStatement(node) { checkGrammarStatementInAmbientContext(node); @@ -31741,9 +33103,11 @@ var ts; grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (ts.isIdentifier(node.name)) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); if (symbol.flags & 512 @@ -31818,9 +33182,9 @@ var ts; break; case 169: case 218: - var name_24 = node.name; - if (ts.isBindingPattern(name_24)) { - for (var _b = 0, _c = name_24.elements; _b < _c.length; _b++) { + var name_25 = node.name; + if (ts.isBindingPattern(name_25)) { + for (var _b = 0, _c = name_25.elements; _b < _c.length; _b++) { var el = _c[_b]; checkModuleAugmentationElement(el, isGlobalAugmentation); } @@ -31982,9 +33346,11 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 256 && node.parent.kind !== 226 && node.parent.kind !== 225) { - return grammarErrorOnFirstToken(node, errorMessage); + var isInAppropriateContext = node.parent.kind === 256 || node.parent.kind === 226 || node.parent.kind === 225; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); } + return !isInAppropriateContext; } function checkExportSpecifier(node) { checkAliasSymbol(node); @@ -32071,7 +33437,8 @@ var ts; links.exportsChecked = true; } function isNotOverload(declaration) { - return declaration.kind !== 220 || !!declaration.body; + return (declaration.kind !== 220 && declaration.kind !== 147) || + !!declaration.body; } } function checkSourceElement(node) { @@ -32556,6 +33923,9 @@ var ts; node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } + if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) { + return resolveExternalModuleName(node, node); + } case 8: if (node.parent.kind === 173 && node.parent.argumentExpression === node) { var objectType = checkExpression(node.parent.expression); @@ -32670,9 +34040,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456) { var symbols_3 = []; - var name_25 = symbol.name; + var name_26 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_25); + var symbol = getPropertyOfType(t, name_26); if (symbol) { symbols_3.push(symbol); } @@ -32979,9 +34349,9 @@ var ts; } var location = reference; if (startInDeclarationContainer) { - var parent_13 = reference.parent; - if (ts.isDeclaration(parent_13) && reference === parent_13.name) { - location = getDeclarationContainer(parent_13); + var parent_14 = reference.parent; + if (ts.isDeclaration(parent_14) && reference === parent_14.name) { + location = getDeclarationContainer(parent_14); } } return resolveName(location, reference.text, 107455 | 1048576 | 8388608, undefined, undefined); @@ -33090,9 +34460,9 @@ var ts; } var current = symbol; while (true) { - var parent_14 = getParentOfSymbol(current); - if (parent_14) { - current = parent_14; + var parent_15 = getParentOfSymbol(current); + if (parent_15) { + current = parent_15; } else { break; @@ -33652,8 +35022,8 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_2 = args; _i < args_2.length; _i++) { - var arg = args_2[_i]; + for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { + var arg = args_4[_i]; if (arg.kind === 193) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } @@ -33761,10 +35131,9 @@ var ts; var GetOrSetAccessor = GetAccessor | SetAccessor; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - var name_26 = prop.name; - if (prop.kind === 193 || - name_26.kind === 140) { - checkGrammarComputedPropertyName(name_26); + var name_27 = prop.name; + if (name_27.kind === 140) { + checkGrammarComputedPropertyName(name_27); } if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) { return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); @@ -33780,8 +35149,8 @@ var ts; var currentKind = void 0; if (prop.kind === 253 || prop.kind === 254) { checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_26.kind === 8) { - checkGrammarNumericLiteral(name_26); + if (name_27.kind === 8) { + checkGrammarNumericLiteral(name_27); } currentKind = Property; } @@ -33797,7 +35166,7 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_26); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_27); if (effectiveName === undefined) { continue; } @@ -33807,18 +35176,18 @@ var ts; else { var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name_26, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_26)); + grammarErrorOnNode(name_27, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_27)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[effectiveName] = currentKind | existingKind; } else { - return grammarErrorOnNode(name_26, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return grammarErrorOnNode(name_27, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); } } else { - return grammarErrorOnNode(name_26, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return grammarErrorOnNode(name_27, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); } } } @@ -33831,12 +35200,12 @@ var ts; continue; } var jsxAttr = attr; - var name_27 = jsxAttr.name; - if (!seen[name_27.text]) { - seen[name_27.text] = true; + var name_28 = jsxAttr.name; + if (!seen[name_28.text]) { + seen[name_28.text] = true; } else { - return grammarErrorOnNode(name_27, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_28, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; if (initializer && initializer.kind === 248 && !initializer.expression) { @@ -33919,17 +35288,8 @@ var ts; return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 149 ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 149 ? 1 : 2) && - accessor.parameters[0].name.kind === 69 && - accessor.parameters[0].name.originalKeywordKind === 97) { - return accessor.parameters[0]; - } - } - function getFunctionLikeThisParameter(func) { - if (func.parameters.length && - func.parameters[0].name.kind === 69 && - func.parameters[0].name.originalKeywordKind === 97) { - return func.parameters[0]; + if (accessor.parameters.length === (accessor.kind === 149 ? 1 : 2)) { + return ts.getThisParameter(accessor); } } function checkGrammarForNonSymbolComputedProperty(node, message) { @@ -34763,7 +36123,7 @@ var ts; case 175: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); case 176: - return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplate)); + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); case 178: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); case 179: @@ -34787,7 +36147,7 @@ var ts; case 188: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 189: - return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateLiteralFragment), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); case 190: return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); case 191: @@ -34797,7 +36157,7 @@ var ts; case 194: return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); case 197: - return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateLiteralFragment)); + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); case 199: return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); case 200: @@ -35072,7 +36432,7 @@ var ts; return expression; function emitAssignment(name, value, location) { var expression = ts.createAssignment(name, value, location); - context.setNodeEmitFlags(expression, 2048); + ts.setEmitFlags(expression, 2048); ts.aggregateTransformFlags(expression); expressions.push(expression); } @@ -35089,7 +36449,7 @@ var ts; return declarations; function emitAssignment(name, value, location) { var declaration = ts.createVariableDeclaration(name, undefined, value, location); - context.setNodeEmitFlags(declaration, 2048); + ts.setEmitFlags(declaration, 2048); ts.aggregateTransformFlags(declaration); declarations.push(declaration); } @@ -35113,7 +36473,7 @@ var ts; } var declaration = ts.createVariableDeclaration(name, undefined, value, location); declaration.original = original; - context.setNodeEmitFlags(declaration, 2048); + ts.setEmitFlags(declaration, 2048); declarations.push(declaration); ts.aggregateTransformFlags(declaration); } @@ -35153,7 +36513,7 @@ var ts; function emitPendingAssignment(name, value, location, original) { var expression = ts.createAssignment(name, value, location); expression.original = original; - context.setNodeEmitFlags(expression, 2048); + ts.setEmitFlags(expression, 2048); pendingAssignments.push(expression); return expression; } @@ -35197,10 +36557,10 @@ var ts; emitArrayLiteralAssignment(target, value, location); } else { - var name_28 = ts.getMutableClone(target); - context.setSourceMapRange(name_28, target); - context.setCommentRange(name_28, target); - emitAssignment(name_28, value, location, undefined); + var name_29 = ts.getMutableClone(target); + ts.setSourceMapRange(name_29, target); + ts.setCommentRange(name_29, target); + emitAssignment(name_29, value, location, undefined); } } function emitObjectLiteralAssignment(target, value, location) { @@ -35314,7 +36674,7 @@ var ts; (function (ts) { var USE_NEW_TYPE_METADATA_FORMAT = false; function transformTypeScript(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, setCommentRange = context.setCommentRange, setSourceMapRange = context.setSourceMapRange, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -35323,10 +36683,13 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; + context.enableSubstitution(172); + context.enableSubstitution(173); var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; var currentScope; + var currentScopeFirstDeclarationsOfName; var currentSourceFileExternalHelpersModuleName; var enabledSubstitutions; var classAliases; @@ -35334,12 +36697,19 @@ var ts; var currentSuperContainer; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitNode(node, visitor, ts.isSourceFile); } function saveStateAndInvoke(node, f) { var savedCurrentScope = currentScope; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; onBeforeVisitNode(node); var visited = f(node); + if (currentScope !== savedCurrentScope) { + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + } currentScope = savedCurrentScope; return visited; } @@ -35493,11 +36863,22 @@ var ts; case 226: case 199: currentScope = node; + currentScopeFirstDeclarationsOfName = undefined; + break; + case 221: + case 220: + if (ts.hasModifier(node, 2)) { + break; + } + recordEmittedDeclarationInScope(node); break; } } function visitSourceFile(node) { currentSourceFile = node; + if (compilerOptions.alwaysStrict) { + node = ts.ensureUseStrict(node); + } if (node.flags & 31744 && compilerOptions.importHelpers && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { @@ -35519,7 +36900,7 @@ var ts; else { node = ts.visitEachChild(node, visitor, context); } - setNodeEmitFlags(node, 1 | node.emitFlags); + ts.setEmitFlags(node, 1 | ts.getEmitFlags(node)); return node; } function shouldEmitDecorateCallForClass(node) { @@ -35549,7 +36930,7 @@ var ts; var classDeclaration = ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), node); ts.setOriginalNode(classDeclaration, node); if (staticProperties.length > 0) { - setNodeEmitFlags(classDeclaration, 1024 | getNodeEmitFlags(classDeclaration)); + ts.setEmitFlags(classDeclaration, 1024 | ts.getEmitFlags(classDeclaration)); } statements.push(classDeclaration); } @@ -35591,7 +36972,7 @@ var ts; var transformedClassExpression = ts.createVariableStatement(undefined, ts.createLetDeclarationList([ ts.createVariableDeclaration(classAlias || declaredName, undefined, classExpression) ]), location); - setCommentRange(transformedClassExpression, node); + ts.setCommentRange(transformedClassExpression, node); statements.push(ts.setOriginalNode(transformedClassExpression, node)); if (classAlias) { statements.push(ts.setOriginalNode(ts.createVariableStatement(undefined, ts.createLetDeclarationList([ @@ -35612,7 +36993,7 @@ var ts; enableSubstitutionForClassAliases(); classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); } - setNodeEmitFlags(classExpression, 524288 | getNodeEmitFlags(classExpression)); + ts.setEmitFlags(classExpression, 524288 | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); ts.addRange(expressions, generateInitializedPropertyExpressions(node, staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); @@ -35673,7 +37054,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 202 && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 202 && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -35692,9 +37073,9 @@ var ts; ts.Debug.assert(ts.isIdentifier(node.name)); var name = node.name; var propertyName = ts.getMutableClone(name); - setNodeEmitFlags(propertyName, 49152 | 1536); + ts.setEmitFlags(propertyName, 49152 | 1536); var localName = ts.getMutableClone(name); - setNodeEmitFlags(localName, 49152); + ts.setEmitFlags(localName, 49152); return ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), propertyName, node.name), localName), ts.moveRangePos(node, -1))); } function getInitializedProperties(node, isStatic) { @@ -35715,8 +37096,8 @@ var ts; for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var property = properties_7[_i]; var statement = ts.createStatement(transformInitializedProperty(node, property, receiver)); - setSourceMapRange(statement, ts.moveRangePastModifiers(property)); - setCommentRange(statement, property); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); statements.push(statement); } } @@ -35726,8 +37107,8 @@ var ts; var property = properties_8[_i]; var expression = transformInitializedProperty(node, property, receiver); expression.startsOnNewLine = true; - setSourceMapRange(expression, ts.moveRangePastModifiers(property)); - setCommentRange(expression, property); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + ts.setCommentRange(expression, property); expressions.push(expression); } return expressions; @@ -35868,7 +37249,7 @@ var ts; : ts.createNull() : undefined; var helper = ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); - setNodeEmitFlags(helper, 49152); + ts.setEmitFlags(helper, 49152); return helper; } function addConstructorDecorationStatement(statements, node, decoratedClassAlias) { @@ -35886,12 +37267,12 @@ var ts; if (decoratedClassAlias) { var expression = ts.createAssignment(decoratedClassAlias, ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node))); var result = ts.createAssignment(getDeclarationName(node), expression, ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152); + ts.setEmitFlags(result, 49152); return result; } else { var result = ts.createAssignment(getDeclarationName(node), ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node)), ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152); + ts.setEmitFlags(result, 49152); return result; } } @@ -35905,7 +37286,7 @@ var ts; for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { var decorator = decorators_1[_i]; var helper = ts.createParamHelper(currentSourceFileExternalHelpersModuleName, transformDecorator(decorator), parameterOffset, decorator.expression); - setNodeEmitFlags(helper, 49152); + ts.setEmitFlags(helper, 49152); expressions.push(helper); } } @@ -36070,10 +37451,33 @@ var ts; : ts.createIdentifier("Symbol"); case 155: return serializeTypeReferenceNode(node); + case 163: + case 162: + { + var unionOrIntersection = node; + var serializedUnion = void 0; + for (var _i = 0, _a = unionOrIntersection.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var serializedIndividual = serializeTypeNode(typeNode); + if (serializedIndividual.kind !== 69) { + serializedUnion = undefined; + break; + } + if (serializedIndividual.text === "Object") { + return serializedIndividual; + } + if (serializedUnion && serializedUnion.text !== serializedIndividual.text) { + serializedUnion = undefined; + break; + } + serializedUnion = serializedIndividual; + } + if (serializedUnion) { + return serializedUnion; + } + } case 158: case 159: - case 162: - case 163: case 117: case 165: break; @@ -36117,14 +37521,14 @@ var ts; function serializeEntityNameAsExpression(node, useFallback) { switch (node.kind) { case 69: - var name_29 = ts.getMutableClone(node); - name_29.flags &= ~8; - name_29.original = undefined; - name_29.parent = currentScope; + var name_30 = ts.getMutableClone(node); + name_30.flags &= ~8; + name_30.original = undefined; + name_30.parent = currentScope; if (useFallback) { - return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_29), ts.createLiteral("undefined")), name_29); + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_30), ts.createLiteral("undefined")), name_30); } - return name_29; + return name_30; case 139: return serializeQualifiedNameAsExpression(node, useFallback); } @@ -36194,8 +37598,8 @@ var ts; return undefined; } var method = ts.createMethod(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); - setCommentRange(method, node); - setSourceMapRange(method, ts.moveRangePastDecorators(node)); + ts.setCommentRange(method, node); + ts.setSourceMapRange(method, ts.moveRangePastDecorators(node)); ts.setOriginalNode(method, node); return method; } @@ -36207,8 +37611,8 @@ var ts; return undefined; } var accessor = ts.createGetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setCommentRange(accessor, node); + ts.setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); ts.setOriginalNode(accessor, node); return accessor; } @@ -36217,8 +37621,8 @@ var ts; return undefined; } var accessor = ts.createSetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setCommentRange(accessor, node); + ts.setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); ts.setOriginalNode(accessor, node); return accessor; } @@ -36313,11 +37717,11 @@ var ts; if (languageVersion >= 2) { if (resolver.getNodeCheckFlags(node) & 4096) { enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 8); + ts.setEmitFlags(block, 8); } else if (resolver.getNodeCheckFlags(node) & 2048) { enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 4); + ts.setEmitFlags(block, 4); } } return block; @@ -36327,14 +37731,14 @@ var ts; } } function visitParameter(node) { - if (node.name && ts.isIdentifier(node.name) && node.name.originalKeywordKind === 97) { + if (ts.parameterIsThisKeyword(node)) { return undefined; } var parameter = ts.createParameterDeclaration(undefined, undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression), ts.moveRangePastModifiers(node)); ts.setOriginalNode(parameter, node); - setCommentRange(parameter, node); - setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - setNodeEmitFlags(parameter.name, 1024); + ts.setCommentRange(parameter, node); + ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(parameter.name, 1024); return parameter; } function visitVariableStatement(node) { @@ -36383,12 +37787,13 @@ var ts; || compilerOptions.isolatedModules; } function shouldEmitVarForEnumDeclaration(node) { - return !ts.hasModifier(node, 1) - || (isES6ExportedDeclaration(node) && ts.isFirstDeclarationOfKind(node, node.kind)); + return isFirstEmittedDeclarationInScope(node) + && (!ts.hasModifier(node, 1) + || isES6ExportedDeclaration(node)); } function addVarForEnumExportedFromNamespace(statements, node) { var statement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, getExportName(node))]); - setSourceMapRange(statement, node); + ts.setSourceMapRange(statement, node); statements.push(statement); } function visitEnumDeclaration(node) { @@ -36397,6 +37802,7 @@ var ts; } var statements = []; var emitFlags = 64; + recordEmittedDeclarationInScope(node); if (shouldEmitVarForEnumDeclaration(node)) { addVarForEnumOrModuleDeclaration(statements, node); if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { @@ -36408,7 +37814,7 @@ var ts; var exportName = getExportName(node); var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformEnumBody(node, containerName)), undefined, [ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()))]), node); ts.setOriginalNode(enumStatement, node); - setNodeEmitFlags(enumStatement, emitFlags); + ts.setEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); if (isNamespaceExport(node)) { addVarForEnumExportedFromNamespace(statements, node); @@ -36447,18 +37853,32 @@ var ts; function shouldEmitModuleDeclaration(node) { return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } - function isModuleMergedWithES6Class(node) { - return languageVersion === 2 - && ts.isMergedWithClass(node); - } function isES6ExportedDeclaration(node) { return isExternalModuleExport(node) && moduleKind === ts.ModuleKind.ES6; } + function recordEmittedDeclarationInScope(node) { + var name = node.symbol && node.symbol.name; + if (name) { + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createMap(); + } + if (!(name in currentScopeFirstDeclarationsOfName)) { + currentScopeFirstDeclarationsOfName[name] = node; + } + } + } + function isFirstEmittedDeclarationInScope(node) { + if (currentScopeFirstDeclarationsOfName) { + var name_31 = node.symbol && node.symbol.name; + if (name_31) { + return currentScopeFirstDeclarationsOfName[name_31] === node; + } + } + return false; + } function shouldEmitVarForModuleDeclaration(node) { - return !isModuleMergedWithES6Class(node) - && (!isES6ExportedDeclaration(node) - || ts.isFirstDeclarationOfKind(node, node.kind)); + return isFirstEmittedDeclarationInScope(node); } function addVarForEnumOrModuleDeclaration(statements, node) { var statement = ts.createVariableStatement(isES6ExportedDeclaration(node) @@ -36468,13 +37888,13 @@ var ts; ]); ts.setOriginalNode(statement, node); if (node.kind === 224) { - setSourceMapRange(statement.declarationList, node); + ts.setSourceMapRange(statement.declarationList, node); } else { - setSourceMapRange(statement, node); + ts.setSourceMapRange(statement, node); } - setCommentRange(statement, node); - setNodeEmitFlags(statement, 32768); + ts.setCommentRange(statement, node); + ts.setEmitFlags(statement, 32768); statements.push(statement); } function visitModuleDeclaration(node) { @@ -36485,6 +37905,7 @@ var ts; enableSubstitutionForNamespaceExports(); var statements = []; var emitFlags = 64; + recordEmittedDeclarationInScope(node); if (shouldEmitVarForModuleDeclaration(node)) { addVarForEnumOrModuleDeclaration(statements, node); if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { @@ -36501,15 +37922,17 @@ var ts; } var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformModuleBody(node, containerName)), undefined, [moduleArg]), node); ts.setOriginalNode(moduleStatement, node); - setNodeEmitFlags(moduleStatement, emitFlags); + ts.setEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); return statements; } function transformModuleBody(node, namespaceLocalName) { var savedCurrentNamespaceContainerName = currentNamespaceContainerName; var savedCurrentNamespace = currentNamespace; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; currentNamespaceContainerName = namespaceLocalName; currentNamespace = node; + currentScopeFirstDeclarationsOfName = undefined; var statements = []; startLexicalEnvironment(); var statementsLocation; @@ -36536,9 +37959,10 @@ var ts; ts.addRange(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), blockLocation, true); if (body.kind !== 226) { - setNodeEmitFlags(block, block.emitFlags | 49152); + ts.setEmitFlags(block, ts.getEmitFlags(block) | 49152); } return block; } @@ -36561,7 +37985,7 @@ var ts; return undefined; } var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); - setNodeEmitFlags(moduleReference, 49152 | 65536); + ts.setEmitFlags(moduleReference, 49152 | 65536); if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { return ts.setOriginalNode(ts.createVariableStatement(ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(node.name, undefined, moduleReference) @@ -36590,9 +38014,9 @@ var ts; } function addExportMemberAssignment(statements, node) { var expression = ts.createAssignment(getExportName(node), getLocalName(node, true)); - setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + ts.setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); var statement = ts.createStatement(expression); - setSourceMapRange(statement, ts.createRange(-1, node.end)); + ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); } function createNamespaceExport(exportName, exportValue, location) { @@ -36613,7 +38037,7 @@ var ts; emitFlags |= 1536; } if (emitFlags) { - setNodeEmitFlags(qualifiedName, emitFlags); + ts.setEmitFlags(qualifiedName, emitFlags); } return qualifiedName; } @@ -36622,7 +38046,7 @@ var ts; } function getNamespaceParameterName(node) { var name = ts.getGeneratedNameForNode(node); - setSourceMapRange(name, node.name); + ts.setSourceMapRange(name, node.name); return name; } function getNamespaceContainerName(node) { @@ -36639,8 +38063,8 @@ var ts; } function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { if (node.name) { - var name_30 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); + var name_32 = ts.getMutableClone(node.name); + emitFlags |= ts.getEmitFlags(node.name); if (!allowSourceMaps) { emitFlags |= 1536; } @@ -36648,9 +38072,9 @@ var ts; emitFlags |= 49152; } if (emitFlags) { - setNodeEmitFlags(name_30, emitFlags); + ts.setEmitFlags(name_32, emitFlags); } - return name_30; + return name_32; } else { return ts.getGeneratedNameForNode(node); @@ -36712,7 +38136,7 @@ var ts; function isTransformedEnumDeclaration(node) { return ts.getOriginalNode(node).kind === 224; } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedApplicableSubstitutions = applicableSubstitutions; var savedCurrentSuperContainer = currentSuperContainer; if (enabledSubstitutions & 4 && isSuperContainer(node)) { @@ -36724,13 +38148,13 @@ var ts; if (enabledSubstitutions & 8 && isTransformedEnumDeclaration(node)) { applicableSubstitutions |= 8; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); applicableSubstitutions = savedApplicableSubstitutions; currentSuperContainer = savedCurrentSuperContainer; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -36740,14 +38164,14 @@ var ts; } function substituteShorthandPropertyAssignment(node) { if (enabledSubstitutions & 2) { - var name_31 = node.name; - var exportedName = trySubstituteNamespaceExportedName(name_31); + var name_33 = node.name; + var exportedName = trySubstituteNamespaceExportedName(name_33); if (exportedName) { if (node.objectAssignmentInitializer) { var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); - return ts.createPropertyAssignment(name_31, initializer, node); + return ts.createPropertyAssignment(name_33, initializer, node); } - return ts.createPropertyAssignment(name_31, exportedName, node); + return ts.createPropertyAssignment(name_33, exportedName, node); } } return node; @@ -36756,16 +38180,15 @@ var ts; switch (node.kind) { case 69: return substituteExpressionIdentifier(node); - } - if (enabledSubstitutions & 4) { - switch (node.kind) { - case 174: + case 172: + return substitutePropertyAccessExpression(node); + case 173: + return substituteElementAccessExpression(node); + case 174: + if (enabledSubstitutions & 4) { return substituteCallExpression(node); - case 172: - return substitutePropertyAccessExpression(node); - case 173: - return substituteElementAccessExpression(node); - } + } + break; } return node; } @@ -36782,8 +38205,8 @@ var ts; var classAlias = classAliases[declaration.id]; if (classAlias) { var clone_4 = ts.getSynthesizedClone(classAlias); - setSourceMapRange(clone_4, node); - setCommentRange(clone_4, node); + ts.setSourceMapRange(clone_4, node); + ts.setCommentRange(clone_4, node); return clone_4; } } @@ -36792,7 +38215,7 @@ var ts; return undefined; } function trySubstituteNamespaceExportedName(node) { - if (enabledSubstitutions & applicableSubstitutions && (getNodeEmitFlags(node) & 262144) === 0) { + if (enabledSubstitutions & applicableSubstitutions && (ts.getEmitFlags(node) & 262144) === 0) { var container = resolver.getReferencedExportContainer(node, false); if (container) { var substitute = (applicableSubstitutions & 2 && container.kind === 225) || @@ -36820,23 +38243,48 @@ var ts; return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 95) { + if (enabledSubstitutions & 4 && node.expression.kind === 95) { var flags = getSuperContainerAsyncMethodFlags(); if (flags) { return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); } } - return node; + return substituteConstantValue(node); } function substituteElementAccessExpression(node) { - if (node.expression.kind === 95) { + if (enabledSubstitutions & 4 && node.expression.kind === 95) { var flags = getSuperContainerAsyncMethodFlags(); if (flags) { return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); } } + return substituteConstantValue(node); + } + function substituteConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + var substitute = ts.createLiteral(constantValue); + ts.setSourceMapRange(substitute, node); + ts.setCommentRange(substitute, node); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : ts.getTextOfNode(node.argumentExpression); + substitute.trailingComment = " " + propertyName + " "; + } + ts.setConstantValue(node, constantValue); + return substitute; + } return node; } + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; + } + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) + ? resolver.getConstantValue(node) + : undefined; + } function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { if (flags & 4096) { return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), "value", location); @@ -36860,6 +38308,9 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; node = ts.visitEachChild(node, visitor, context); currentSourceFile = undefined; @@ -37018,12 +38469,12 @@ var ts; return getTagName(node.openingElement); } else { - var name_32 = node.tagName; - if (ts.isIdentifier(name_32) && ts.isIntrinsicJsxName(name_32.text)) { - return ts.createLiteral(name_32.text); + var name_34 = node.tagName; + if (ts.isIdentifier(name_34) && ts.isIntrinsicJsxName(name_34.text)) { + return ts.createLiteral(name_34.text); } else { - return ts.createExpressionFromEntityName(name_32); + return ts.createExpressionFromEntityName(name_34); } } } @@ -37305,6 +38756,9 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitEachChild(node, visitor, context); } function visitor(node) { @@ -37364,7 +38818,7 @@ var ts; var ts; (function (ts) { function transformES6(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, getCommentRange = context.getCommentRange, setCommentRange = context.setCommentRange, getSourceMapRange = context.getSourceMapRange, setSourceMapRange = context.setSourceMapRange, setTokenSourceMapRange = context.setTokenSourceMapRange; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var previousOnSubstituteNode = context.onSubstituteNode; var previousOnEmitNode = context.onEmitNode; @@ -37384,6 +38838,9 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; currentText = node.text; return ts.visitNode(node, visitor, ts.isSourceFile); @@ -37553,7 +39010,7 @@ var ts; enclosingFunction = currentNode; if (currentNode.kind !== 180) { enclosingNonArrowFunction = currentNode; - if (!(currentNode.emitFlags & 2097152)) { + if (!(ts.getEmitFlags(currentNode) & 2097152)) { enclosingNonAsyncFunctionBody = currentNode; } } @@ -37690,15 +39147,15 @@ var ts; } var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter("_super")] : [], undefined, transformClassBody(node, extendsClauseElement)); - if (getNodeEmitFlags(node) & 524288) { - setNodeEmitFlags(classFunction, 524288); + if (ts.getEmitFlags(node) & 524288) { + ts.setEmitFlags(classFunction, 524288); } var inner = ts.createPartiallyEmittedExpression(classFunction); inner.end = node.end; - setNodeEmitFlags(inner, 49152); + ts.setEmitFlags(inner, 49152); var outer = ts.createPartiallyEmittedExpression(inner); outer.end = ts.skipTrivia(currentText, node.pos); - setNodeEmitFlags(outer, 49152); + ts.setEmitFlags(outer, 49152); return ts.createParen(ts.createCall(outer, undefined, extendsClauseElement ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] : [])); @@ -37713,14 +39170,14 @@ var ts; var localName = getLocalName(node); var outer = ts.createPartiallyEmittedExpression(localName); outer.end = closingBraceLocation.end; - setNodeEmitFlags(outer, 49152); + ts.setEmitFlags(outer, 49152); var statement = ts.createReturn(outer); statement.pos = closingBraceLocation.pos; - setNodeEmitFlags(statement, 49152 | 12288); + ts.setEmitFlags(statement, 49152 | 12288); statements.push(statement); ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, node.members), undefined, true); - setNodeEmitFlags(block, 49152); + ts.setEmitFlags(block, 49152); return block; } function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { @@ -37731,7 +39188,11 @@ var ts; function addConstructor(statements, node, extendsClauseElement) { var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); - statements.push(ts.createFunctionDeclaration(undefined, undefined, undefined, getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), constructor || node)); + var constructorFunction = ts.createFunctionDeclaration(undefined, undefined, undefined, getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), constructor || node); + if (extendsClauseElement) { + ts.setEmitFlags(constructorFunction, 256); + } + statements.push(constructorFunction); } function transformConstructorParameters(constructor, hasSynthesizedSuper) { if (constructor && !hasSynthesizedSuper) { @@ -37742,33 +39203,98 @@ var ts; function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { var statements = []; startLexicalEnvironment(); + var statementOffset = -1; + if (hasSynthesizedSuper) { + statementOffset = 1; + } + else if (constructor) { + statementOffset = ts.addPrologueDirectives(statements, constructor.body.statements, false, visitor); + } if (constructor) { - addCaptureThisForNodeIfNeeded(statements, constructor); addDefaultValueAssignmentsIfNeeded(statements, constructor); addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); + } + var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, !!extendsClauseElement, hasSynthesizedSuper, statementOffset); + if (superCaptureStatus === 1 || superCaptureStatus === 2) { + statementOffset++; } - addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper); if (constructor) { - var body = saveStateAndInvoke(constructor, hasSynthesizedSuper ? transformConstructorBodyWithSynthesizedSuper : transformConstructorBodyWithoutSynthesizedSuper); + var body = saveStateAndInvoke(constructor, function (constructor) { return ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, statementOffset); }); ts.addRange(statements, body); } + if (extendsClauseElement + && superCaptureStatus !== 2 + && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { + statements.push(ts.createReturn(ts.createIdentifier("_this"))); + } ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, constructor ? constructor.body.statements : node.members), constructor ? constructor.body : node, true); if (!constructor) { - setNodeEmitFlags(block, 49152); + ts.setEmitFlags(block, 49152); } return block; } - function transformConstructorBodyWithSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 1); - } - function transformConstructorBodyWithoutSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 0); - } - function addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper) { - if (constructor ? hasSynthesizedSuper : extendsClauseElement) { - statements.push(ts.createStatement(ts.createFunctionApply(ts.createIdentifier("_super"), ts.createThis(), ts.createIdentifier("arguments")), extendsClauseElement)); + function isSufficientlyCoveredByReturnStatements(statement) { + if (statement.kind === 211) { + return true; } + else if (statement.kind === 203) { + var ifStatement = statement; + if (ifStatement.elseStatement) { + return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && + isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); + } + } + else if (statement.kind === 199) { + var lastStatement = ts.lastOrUndefined(statement.statements); + if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { + return true; + } + } + return false; + } + function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, hasExtendsClause, hasSynthesizedSuper, statementOffset) { + if (!hasExtendsClause) { + if (ctor) { + addCaptureThisForNodeIfNeeded(statements, ctor); + } + return 0; + } + if (!ctor) { + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + return 2; + } + if (hasSynthesizedSuper) { + captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); + enableSubstitutionsForCapturedThis(); + return 1; + } + var firstStatement; + var superCallExpression; + var ctorStatements = ctor.body.statements; + if (statementOffset < ctorStatements.length) { + firstStatement = ctorStatements[statementOffset]; + if (firstStatement.kind === 202 && ts.isSuperCall(firstStatement.expression)) { + var superCall = firstStatement.expression; + superCallExpression = ts.setOriginalNode(saveStateAndInvoke(superCall, visitImmediateSuperCallInBody), superCall); + } + } + if (superCallExpression && statementOffset === ctorStatements.length - 1) { + statements.push(ts.createReturn(superCallExpression)); + return 2; + } + captureThisForNode(statements, ctor, superCallExpression, firstStatement); + if (superCallExpression) { + return 1; + } + return 0; + } + function createDefaultSuperCallOrThis() { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 128); + var superCall = ts.createFunctionApply(ts.createIdentifier("_super"), actualThis, ts.createIdentifier("arguments")); + return ts.createLogicalOr(superCall, actualThis); } function visitParameter(node) { if (node.dotDotDotToken) { @@ -37793,34 +39319,34 @@ var ts; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - var name_33 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + var name_35 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; if (dotDotDotToken) { continue; } - if (ts.isBindingPattern(name_33)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name_33, initializer); + if (ts.isBindingPattern(name_35)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name_35, initializer); } else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name_33, initializer); + addDefaultValueAssignmentForInitializer(statements, parameter, name_35, initializer); } } } function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { var temp = ts.getGeneratedNameForNode(parameter); if (name.elements.length > 0) { - statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608)); + statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608)); } else if (initializer) { - statements.push(setNodeEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608)); + statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608)); } } function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); - var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), setNodeEmitFlags(ts.createBlock([ - ts.createStatement(ts.createAssignment(setNodeEmitFlags(ts.getMutableClone(name), 1536), setNodeEmitFlags(initializer, 1536 | getNodeEmitFlags(initializer)), parameter)) + var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), ts.setEmitFlags(ts.createBlock([ + ts.createStatement(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 1536), ts.setEmitFlags(initializer, 1536 | ts.getEmitFlags(initializer)), parameter)) ], parameter), 32 | 1024 | 12288), undefined, parameter); statement.startsOnNewLine = true; - setNodeEmitFlags(statement, 12288 | 1024 | 8388608); + ts.setEmitFlags(statement, 12288 | 1024 | 8388608); statements.push(statement); } function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { @@ -37832,11 +39358,11 @@ var ts; return; } var declarationName = ts.getMutableClone(parameter.name); - setNodeEmitFlags(declarationName, 1536); + ts.setEmitFlags(declarationName, 1536); var expressionName = ts.getSynthesizedClone(parameter.name); var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); - statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(declarationName, undefined, ts.createArrayLiteral([])) ]), parameter), 8388608)); var forStatement = ts.createFor(ts.createVariableDeclarationList([ @@ -37844,21 +39370,24 @@ var ts; ], parameter), ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length"), parameter), ts.createPostfixIncrement(temp, parameter), ts.createBlock([ ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), parameter)) ])); - setNodeEmitFlags(forStatement, 8388608); + ts.setEmitFlags(forStatement, 8388608); ts.startOnNewLine(forStatement); statements.push(forStatement); } function addCaptureThisForNodeIfNeeded(statements, node) { if (node.transformFlags & 16384 && node.kind !== 180) { - enableSubstitutionsForCapturedThis(); - var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("_this", undefined, ts.createThis()) - ])); - setNodeEmitFlags(captureThisStatement, 49152 | 8388608); - setSourceMapRange(captureThisStatement, node); - statements.push(captureThisStatement); + captureThisForNode(statements, node, ts.createThis()); } } + function captureThisForNode(statements, node, initializer, originalStatement) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("_this", undefined, initializer) + ]), originalStatement); + ts.setEmitFlags(captureThisStatement, 49152 | 8388608); + ts.setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } function addClassMembers(statements, node) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -37888,43 +39417,43 @@ var ts; return ts.createEmptyStatement(member); } function transformClassMethodDeclarationToStatement(receiver, member) { - var commentRange = getCommentRange(member); - var sourceMapRange = getSourceMapRange(member); + var commentRange = ts.getCommentRange(member); + var sourceMapRange = ts.getSourceMapRange(member); var func = transformFunctionLikeToExpression(member, member, undefined); - setNodeEmitFlags(func, 49152); - setSourceMapRange(func, sourceMapRange); + ts.setEmitFlags(func, 49152); + ts.setSourceMapRange(func, sourceMapRange); var statement = ts.createStatement(ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), member.name), func), member); ts.setOriginalNode(statement, member); - setCommentRange(statement, commentRange); - setNodeEmitFlags(statement, 1536); + ts.setCommentRange(statement, commentRange); + ts.setEmitFlags(statement, 1536); return statement; } function transformAccessorsToStatement(receiver, accessors) { - var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, false), getSourceMapRange(accessors.firstAccessor)); - setNodeEmitFlags(statement, 49152); + var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, false), ts.getSourceMapRange(accessors.firstAccessor)); + ts.setEmitFlags(statement, 49152); return statement; } function transformAccessorsToExpression(receiver, _a, startsOnNewLine) { var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; var target = ts.getMutableClone(receiver); - setNodeEmitFlags(target, 49152 | 1024); - setSourceMapRange(target, firstAccessor.name); + ts.setEmitFlags(target, 49152 | 1024); + ts.setSourceMapRange(target, firstAccessor.name); var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); - setNodeEmitFlags(propertyName, 49152 | 512); - setSourceMapRange(propertyName, firstAccessor.name); + ts.setEmitFlags(propertyName, 49152 | 512); + ts.setSourceMapRange(propertyName, firstAccessor.name); var properties = []; if (getAccessor) { var getterFunction = transformFunctionLikeToExpression(getAccessor, undefined, undefined); - setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); + ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor)); var getter = ts.createPropertyAssignment("get", getterFunction); - setCommentRange(getter, getCommentRange(getAccessor)); + ts.setCommentRange(getter, ts.getCommentRange(getAccessor)); properties.push(getter); } if (setAccessor) { var setterFunction = transformFunctionLikeToExpression(setAccessor, undefined, undefined); - setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); + ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor)); var setter = ts.createPropertyAssignment("set", setterFunction); - setCommentRange(setter, getCommentRange(setAccessor)); + ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); properties.push(setter); } properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); @@ -37943,7 +39472,7 @@ var ts; enableSubstitutionsForCapturedThis(); } var func = transformFunctionLikeToExpression(node, node, undefined); - setNodeEmitFlags(func, 256); + ts.setEmitFlags(func, 256); return func; } function visitFunctionExpression(node) { @@ -38000,7 +39529,7 @@ var ts; } var expression = ts.visitNode(body, visitor, ts.isExpression); var returnStatement = ts.createReturn(expression, body); - setNodeEmitFlags(returnStatement, 12288 | 1024 | 32768); + ts.setEmitFlags(returnStatement, 12288 | 1024 | 32768); statements.push(returnStatement); closeBraceLocation = body; } @@ -38011,10 +39540,10 @@ var ts; } var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); if (!multiLine && singleLine) { - setNodeEmitFlags(block, 32); + ts.setEmitFlags(block, 32); } if (closeBraceLocation) { - setTokenSourceMapRange(block, 16, closeBraceLocation); + ts.setTokenSourceMapRange(block, 16, closeBraceLocation); } ts.setOriginalNode(block, node.body); return block; @@ -38055,7 +39584,7 @@ var ts; assignment = ts.flattenVariableDestructuringToExpression(context, decl, hoistVariableDeclaration, undefined, visitor); } else { - assignment = ts.createBinary(decl.name, 56, decl.initializer); + assignment = ts.createBinary(decl.name, 56, ts.visitNode(decl.initializer, visitor, ts.isExpression)); } (assignments || (assignments = [])).push(assignment); } @@ -38078,13 +39607,13 @@ var ts; : visitVariableDeclaration)); var declarationList = ts.createVariableDeclarationList(declarations, node); ts.setOriginalNode(declarationList, node); - setCommentRange(declarationList, node); + ts.setCommentRange(declarationList, node); if (node.transformFlags & 2097152 && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { var firstDeclaration = ts.firstOrUndefined(declarations); var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); } return declarationList; } @@ -38179,7 +39708,7 @@ var ts; ts.setOriginalNode(declarationList, initializer); var firstDeclaration = declarations[0]; var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); statements.push(ts.createVariableStatement(undefined, declarationList)); } else { @@ -38214,14 +39743,14 @@ var ts; statements.push(statement); } } - setNodeEmitFlags(expression, 1536 | getNodeEmitFlags(expression)); + ts.setEmitFlags(expression, 1536 | ts.getEmitFlags(expression)); var body = ts.createBlock(ts.createNodeArray(statements, statementsLocation), bodyLocation); - setNodeEmitFlags(body, 1536 | 12288); + ts.setEmitFlags(body, 1536 | 12288); var forStatement = ts.createFor(ts.createVariableDeclarationList([ ts.createVariableDeclaration(counter, undefined, ts.createLiteral(0), ts.moveRangePos(node.expression, -1)), ts.createVariableDeclaration(rhsReference, undefined, expression, node.expression) ], node.expression), ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length"), node.expression), ts.createPostfixIncrement(counter, node.expression), body, node); - setNodeEmitFlags(forStatement, 8192); + ts.setEmitFlags(forStatement, 8192); return forStatement; } function visitObjectLiteralExpression(node) { @@ -38239,7 +39768,7 @@ var ts; ts.Debug.assert(numInitialProperties !== numProperties); var temp = ts.createTempVariable(hoistVariableDeclaration); var expressions = []; - var assignment = ts.createAssignment(temp, setNodeEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, node.multiLine), 524288)); + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, node.multiLine), 524288)); if (node.multiLine) { assignment.startsOnNewLine = true; } @@ -38328,7 +39857,7 @@ var ts; loopBody = ts.createBlock([loopBody], undefined, true); } var isAsyncBlockContainingAwait = enclosingNonArrowFunction - && (enclosingNonArrowFunction.emitFlags & 2097152) !== 0 + && (ts.getEmitFlags(enclosingNonArrowFunction) & 2097152) !== 0 && (node.statement.transformFlags & 4194304) !== 0; var loopBodyFlags = 0; if (currentState.containsLexicalThis) { @@ -38338,7 +39867,7 @@ var ts; loopBodyFlags |= 2097152; } var convertedLoopVariable = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, undefined, setNodeEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) + ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) ])); var statements = [convertedLoopVariable]; var extraVariableDeclarations; @@ -38366,8 +39895,8 @@ var ts; if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var name_34 in currentState.hoistedLocalVariables) { - var identifier = currentState.hoistedLocalVariables[name_34]; + for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { + var identifier = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } @@ -38376,8 +39905,8 @@ var ts; if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _b = 0, loopOutParameters_1 = loopOutParameters; _b < loopOutParameters_1.length; _b++) { - var outParam = loopOutParameters_1[_b]; + for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { + var outParam = loopOutParameters_1[_d]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } @@ -38555,7 +40084,7 @@ var ts; function visitMethodDeclaration(node) { ts.Debug.assert(!ts.isComputedPropertyName(node.name)); var functionExpression = transformFunctionLikeToExpression(node, ts.moveRangePos(node, -1), undefined); - setNodeEmitFlags(functionExpression, 16384 | getNodeEmitFlags(functionExpression)); + ts.setEmitFlags(functionExpression, 16384 | ts.getEmitFlags(functionExpression)); return ts.createPropertyAssignment(node.name, functionExpression, node); } function visitShorthandPropertyAssignment(node) { @@ -38568,13 +40097,32 @@ var ts; return transformAndSpreadElements(node.elements, true, node.multiLine, node.elements.hasTrailingComma); } function visitCallExpression(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, true); + } + function visitImmediateSuperCallInBody(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, false); + } + function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 95) { + ts.setEmitFlags(thisArg, 128); + } + var resultingCall; if (node.transformFlags & 262144) { - return ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); + resultingCall = ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); } else { - return ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); + resultingCall = ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); } + if (node.expression.kind === 95) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 128); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + return assignToCapturedThis + ? ts.createAssignment(ts.createIdentifier("_this"), initializer) + : initializer; + } + return resultingCall; } function visitNewExpression(node) { ts.Debug.assert((node.transformFlags & 262144) !== 0); @@ -38694,12 +40242,12 @@ var ts; clone.statements = ts.createNodeArray(statements, node.statements); return clone; } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedEnclosingFunction = enclosingFunction; if (enabledSubstitutions & 1 && ts.isFunctionLike(node)) { enclosingFunction = node; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); enclosingFunction = savedEnclosingFunction; } function enableSubstitutionsForBlockScopedBindings() { @@ -38721,9 +40269,9 @@ var ts; context.enableEmitNotification(220); } } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } if (ts.isIdentifier(node)) { @@ -38773,7 +40321,7 @@ var ts; function substituteThisKeyword(node) { if (enabledSubstitutions & 1 && enclosingFunction - && enclosingFunction.emitFlags & 256) { + && ts.getEmitFlags(enclosingFunction) & 256) { return ts.createIdentifier("_this", node); } return node; @@ -38783,8 +40331,8 @@ var ts; } function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { if (node.name && !ts.isGeneratedIdentifier(node.name)) { - var name_35 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); + var name_36 = ts.getMutableClone(node.name); + emitFlags |= ts.getEmitFlags(node.name); if (!allowSourceMaps) { emitFlags |= 1536; } @@ -38792,9 +40340,9 @@ var ts; emitFlags |= 49152; } if (emitFlags) { - setNodeEmitFlags(name_35, emitFlags); + ts.setEmitFlags(name_36, emitFlags); } - return name_35; + return name_36; } return ts.getGeneratedNameForNode(node); } @@ -38842,7 +40390,7 @@ var ts; _a[7] = "endfinally", _a)); function transformGenerators(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration, setSourceMapRange = context.setSourceMapRange, setCommentRange = context.setCommentRange, setNodeEmitFlags = context.setNodeEmitFlags; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var resolver = context.getEmitResolver(); @@ -38876,6 +40424,9 @@ var ts; var withBlockStack; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (node.transformFlags & 1024) { currentSourceFile = node; node = ts.visitEachChild(node, visitor, context); @@ -38982,7 +40533,7 @@ var ts; } } function visitFunctionDeclaration(node) { - if (node.asteriskToken && node.emitFlags & 2097152) { + if (node.asteriskToken && ts.getEmitFlags(node) & 2097152) { node = ts.setOriginalNode(ts.createFunctionDeclaration(undefined, undefined, undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); } else { @@ -39003,7 +40554,7 @@ var ts; } } function visitFunctionExpression(node) { - if (node.asteriskToken && node.emitFlags & 2097152) { + if (node.asteriskToken && ts.getEmitFlags(node) & 2097152) { node = ts.setOriginalNode(ts.createFunctionExpression(undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); } else { @@ -39034,6 +40585,7 @@ var ts; var savedBlocks = blocks; var savedBlockOffsets = blockOffsets; var savedBlockActions = blockActions; + var savedBlockStack = blockStack; var savedLabelOffsets = labelOffsets; var savedLabelExpressions = labelExpressions; var savedNextLabelId = nextLabelId; @@ -39046,6 +40598,7 @@ var ts; blocks = undefined; blockOffsets = undefined; blockActions = undefined; + blockStack = undefined; labelOffsets = undefined; labelExpressions = undefined; nextLabelId = 1; @@ -39064,6 +40617,7 @@ var ts; blocks = savedBlocks; blockOffsets = savedBlockOffsets; blockActions = savedBlockActions; + blockStack = savedBlockStack; labelOffsets = savedLabelOffsets; labelExpressions = savedLabelExpressions; nextLabelId = savedNextLabelId; @@ -39079,7 +40633,7 @@ var ts; return undefined; } else { - if (node.emitFlags & 8388608) { + if (ts.getEmitFlags(node) & 8388608) { return node; } for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { @@ -39747,9 +41301,9 @@ var ts; } return -1; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } return node; @@ -39766,11 +41320,11 @@ var ts; if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { - var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); - if (name_36) { - var clone_8 = ts.getMutableClone(name_36); - setSourceMapRange(clone_8, node); - setCommentRange(clone_8, node); + var name_37 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); + if (name_37) { + var clone_8 = ts.getMutableClone(name_37); + ts.setSourceMapRange(clone_8, node); + ts.setCommentRange(clone_8, node); return clone_8; } } @@ -40164,7 +41718,7 @@ var ts; var buildResult = buildStatements(); return ts.createCall(ts.createHelperName(currentSourceFile.externalHelpersModuleName, "__generator"), undefined, [ ts.createThis(), - setNodeEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(state)], undefined, ts.createBlock(buildResult, undefined, buildResult.length > 0)), 4194304) + ts.setEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(state)], undefined, ts.createBlock(buildResult, undefined, buildResult.length > 0)), 4194304) ]); } function buildStatements() { @@ -40439,7 +41993,7 @@ var ts; _a[ts.ModuleKind.AMD] = transformAMDModule, _a[ts.ModuleKind.UMD] = transformUMDModule, _a)); - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, setNodeEmitFlags = context.setNodeEmitFlags, getNodeEmitFlags = context.getNodeEmitFlags, setSourceMapRange = context.setSourceMapRange; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -40464,6 +42018,9 @@ var ts; var hasExportStarsToExportValues; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); @@ -40489,7 +42046,7 @@ var ts; addExportEqualsIfNeeded(statements, false); var updated = updateSourceFile(node, statements); if (hasExportStarsToExportValues) { - setNodeEmitFlags(updated, 2 | getNodeEmitFlags(node)); + ts.setEmitFlags(updated, 2 | ts.getEmitFlags(node)); } return updated; } @@ -40500,7 +42057,7 @@ var ts; } function transformUMDModule(node) { var define = ts.createIdentifier("define"); - setNodeEmitFlags(define, 16); + ts.setEmitFlags(define, 16); return transformAsynchronousModule(node, define, undefined, false); } function transformAsynchronousModule(node, define, moduleName, includeNonAmdDependencies) { @@ -40527,7 +42084,7 @@ var ts; addExportEqualsIfNeeded(statements, true); var body = ts.createBlock(statements, undefined, true); if (hasExportStarsToExportValues) { - setNodeEmitFlags(body, 2); + ts.setEmitFlags(body, 2); } return body; } @@ -40535,12 +42092,12 @@ var ts; if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { if (emitAsReturn) { var statement = ts.createReturn(exportEquals.expression, exportEquals); - setNodeEmitFlags(statement, 12288 | 49152); + ts.setEmitFlags(statement, 12288 | 49152); statements.push(statement); } else { var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), exportEquals.expression), exportEquals); - setNodeEmitFlags(statement, 49152); + ts.setEmitFlags(statement, 49152); statements.push(statement); } } @@ -40603,7 +42160,7 @@ var ts; if (!ts.contains(externalImports, node)) { return undefined; } - setNodeEmitFlags(node.name, 128); + ts.setEmitFlags(node.name, 128); var statements = []; if (moduleKind !== ts.ModuleKind.AMD) { if (ts.hasModifier(node, 1)) { @@ -40691,16 +42248,16 @@ var ts; else { var names = ts.reduceEachChild(node, collectExportMembers, []); for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_37 = names_1[_i]; - addExportMemberAssignments(statements, name_37); + var name_38 = names_1[_i]; + addExportMemberAssignments(statements, name_38); } } } function collectExportMembers(names, node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && ts.isDeclaration(node)) { - var name_38 = node.name; - if (ts.isIdentifier(name_38)) { - names.push(name_38); + var name_39 = node.name; + if (ts.isIdentifier(name_39)) { + names.push(name_39); } } return ts.reduceEachChild(node, collectExportMembers, names); @@ -40718,7 +42275,7 @@ var ts; addExportDefault(statements, getDeclarationName(node), node); } else { - statements.push(createExportStatement(node.name, setNodeEmitFlags(ts.getSynthesizedClone(node.name), 262144), node)); + statements.push(createExportStatement(node.name, ts.setEmitFlags(ts.getSynthesizedClone(node.name), 262144), node)); } } function visitVariableStatement(node) { @@ -40835,25 +42392,25 @@ var ts; } function addVarForExportedEnumOrNamespaceDeclaration(statements, node) { var transformedStatement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, ts.createPropertyAccess(ts.createIdentifier("exports"), getDeclarationName(node)))], node); - setNodeEmitFlags(transformedStatement, 49152); + ts.setEmitFlags(transformedStatement, 49152); statements.push(transformedStatement); } function getDeclarationName(node) { return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { if (node.kind === 256) { bindingNameExportSpecifiersMap = bindingNameExportSpecifiersForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); bindingNameExportSpecifiersMap = undefined; } else { - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); } } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -40894,7 +42451,7 @@ var ts; var left = node.left; if (ts.isIdentifier(left) && ts.isAssignmentOperator(node.operatorToken.kind)) { if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, left.text)) { - setNodeEmitFlags(node, 128); + ts.setEmitFlags(node, 128); var nestedExportAssignment = void 0; for (var _i = 0, _a = bindingNameExportSpecifiersMap[left.text]; _i < _a.length; _i++) { var specifier = _a[_i]; @@ -40912,11 +42469,11 @@ var ts; var operand = node.operand; if (ts.isIdentifier(operand) && bindingNameExportSpecifiersForFileMap) { if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, operand.text)) { - setNodeEmitFlags(node, 128); + ts.setEmitFlags(node, 128); var transformedUnaryExpression = void 0; if (node.kind === 186) { - transformedUnaryExpression = ts.createBinary(operand, ts.createNode(operator === 41 ? 57 : 58), ts.createLiteral(1), node); - setNodeEmitFlags(transformedUnaryExpression, 128); + transformedUnaryExpression = ts.createBinary(operand, ts.createToken(operator === 41 ? 57 : 58), ts.createLiteral(1), node); + ts.setEmitFlags(transformedUnaryExpression, 128); } var nestedExportAssignment = void 0; for (var _i = 0, _a = bindingNameExportSpecifiersMap[operand.text]; _i < _a.length; _i++) { @@ -40931,7 +42488,7 @@ var ts; return node; } function trySubstituteExportedName(node) { - var emitFlags = getNodeEmitFlags(node); + var emitFlags = ts.getEmitFlags(node); if ((emitFlags & 262144) === 0) { var container = resolver.getReferencedExportContainer(node, (emitFlags & 131072) !== 0); if (container) { @@ -40943,7 +42500,7 @@ var ts; return undefined; } function trySubstituteImportedName(node) { - if ((getNodeEmitFlags(node) & 262144) === 0) { + if ((ts.getEmitFlags(node) & 262144) === 0) { var declaration = resolver.getReferencedImportDeclaration(node); if (declaration) { if (ts.isImportClause(declaration)) { @@ -40955,12 +42512,12 @@ var ts; } } else if (ts.isImportSpecifier(declaration)) { - var name_39 = declaration.propertyName || declaration.name; - if (name_39.originalKeywordKind === 77 && languageVersion <= 0) { - return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_39.text), node); + var name_40 = declaration.propertyName || declaration.name; + if (name_40.originalKeywordKind === 77 && languageVersion <= 0) { + return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_40.text), node); } else { - return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_39), node); + return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_40), node); } } } @@ -40982,7 +42539,7 @@ var ts; var statement = ts.createStatement(createExportAssignment(name, value)); statement.startsOnNewLine = true; if (location) { - setSourceMapRange(statement, location); + ts.setSourceMapRange(statement, location); } return statement; } @@ -41010,7 +42567,7 @@ var ts; var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); if (includeNonAmdDependencies && importAliasName) { - setNodeEmitFlags(importAliasName, 128); + ts.setEmitFlags(importAliasName, 128); aliasedModuleNames.push(externalModuleName); importAliasNames.push(ts.createParameter(importAliasName)); } @@ -41032,7 +42589,7 @@ var ts; var ts; (function (ts) { function transformSystemModule(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -41061,6 +42618,9 @@ var ts; var currentNode; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; currentNode = node; @@ -41093,12 +42653,12 @@ var ts; var body = ts.createFunctionExpression(undefined, undefined, undefined, [ ts.createParameter(exportFunctionForFile), ts.createParameter(contextObjectForFile) - ], undefined, setNodeEmitFlags(ts.createBlock(statements, undefined, true), 1)); + ], undefined, ts.setEmitFlags(ts.createBlock(statements, undefined, true), 1)); return updateSourceFile(node, [ ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), undefined, moduleName ? [moduleName, dependencies, body] : [dependencies, body])) - ], ~1 & getNodeEmitFlags(node)); + ], ~1 & ts.getEmitFlags(node)); var _a; } function addSystemModuleBody(statements, node, dependencyGroups) { @@ -41342,11 +42902,11 @@ var ts; } function visitFunctionDeclaration(node) { if (ts.hasModifier(node, 1)) { - var name_40 = node.name || ts.getGeneratedNameForNode(node); - var newNode = ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name_40, undefined, node.parameters, undefined, node.body, node); + var name_41 = node.name || ts.getGeneratedNameForNode(node); + var newNode = ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name_41, undefined, node.parameters, undefined, node.body, node); recordExportedFunctionDeclaration(node); if (!ts.hasModifier(node, 512)) { - recordExportName(name_40); + recordExportName(name_41); } ts.setOriginalNode(newNode, node); node = newNode; @@ -41357,13 +42917,13 @@ var ts; function visitExpressionStatement(node) { var originalNode = ts.getOriginalNode(node); if ((originalNode.kind === 225 || originalNode.kind === 224) && ts.hasModifier(originalNode, 1)) { - var name_41 = getDeclarationName(originalNode); + var name_42 = getDeclarationName(originalNode); if (originalNode.kind === 224) { - hoistVariableDeclaration(name_41); + hoistVariableDeclaration(name_42); } return [ node, - createExportStatement(name_41, name_41) + createExportStatement(name_42, name_42) ]; } return node; @@ -41517,19 +43077,19 @@ var ts; function visitBlock(node) { return ts.visitEachChild(node, visitNestedNode, context); } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { if (node.kind === 256) { exportFunctionForFile = exportFunctionForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); exportFunctionForFile = undefined; } else { - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); } } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } return node; @@ -41563,7 +43123,7 @@ var ts; return node; } function substituteAssignmentExpression(node) { - setNodeEmitFlags(node, 128); + ts.setEmitFlags(node, 128); var left = node.left; switch (left.kind) { case 69: @@ -41668,7 +43228,7 @@ var ts; var exportDeclaration = resolver.getReferencedExportContainer(operand); if (exportDeclaration) { var expr = ts.createPrefix(node.operator, operand, node); - setNodeEmitFlags(expr, 128); + ts.setEmitFlags(expr, 128); var call = createExportExpression(operand, expr); if (node.kind === 185) { return call; @@ -41701,7 +43261,7 @@ var ts; ts.createForIn(ts.createVariableDeclarationList([ ts.createVariableDeclaration(n, undefined) ]), m, ts.createBlock([ - setNodeEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32) + ts.setEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32) ])), ts.createStatement(ts.createCall(exportFunctionForFile, undefined, [exports])) ], undefined, true))); @@ -41801,7 +43361,7 @@ var ts; function updateSourceFile(node, statements, nodeEmitFlags) { var updated = ts.getMutableClone(node); updated.statements = ts.createNodeArray(statements, node.statements); - setNodeEmitFlags(updated, nodeEmitFlags); + ts.setEmitFlags(updated, nodeEmitFlags); return updated; } } @@ -41815,6 +43375,9 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; return ts.visitEachChild(node, visitor, context); @@ -41951,18 +43514,10 @@ var ts; return transformers; } ts.getTransformers = getTransformers; - var nextTransformId = 1; function transformFiles(resolver, host, sourceFiles, transformers) { - var transformId = nextTransformId; - nextTransformId++; - var tokenSourceMapRanges = ts.createMap(); var lexicalEnvironmentVariableDeclarationsStack = []; var lexicalEnvironmentFunctionDeclarationsStack = []; var enabledSyntaxKindFeatures = new Array(289); - var parseTreeNodesWithAnnotations = []; - var lastTokenSourceMapRangeNode; - var lastTokenSourceMapRangeToken; - var lastTokenSourceMapRange; var lexicalEnvironmentStackOffset = 0; var hoistedVariableDeclarations; var hoistedFunctionDeclarations; @@ -41971,47 +43526,24 @@ var ts; getCompilerOptions: function () { return host.getCompilerOptions(); }, getEmitResolver: function () { return resolver; }, getEmitHost: function () { return host; }, - getNodeEmitFlags: getNodeEmitFlags, - setNodeEmitFlags: setNodeEmitFlags, - getSourceMapRange: getSourceMapRange, - setSourceMapRange: setSourceMapRange, - getTokenSourceMapRange: getTokenSourceMapRange, - setTokenSourceMapRange: setTokenSourceMapRange, - getCommentRange: getCommentRange, - setCommentRange: setCommentRange, hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, startLexicalEnvironment: startLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, - onSubstituteNode: onSubstituteNode, + onSubstituteNode: function (emitContext, node) { return node; }, enableSubstitution: enableSubstitution, isSubstitutionEnabled: isSubstitutionEnabled, - onEmitNode: onEmitNode, + onEmitNode: function (node, emitContext, emitCallback) { return emitCallback(node, emitContext); }, enableEmitNotification: enableEmitNotification, isEmitNotificationEnabled: isEmitNotificationEnabled }; - var transformation = chain.apply(void 0, transformers)(context); + var transformation = ts.chain.apply(void 0, transformers)(context); var transformed = ts.map(sourceFiles, transformSourceFile); lexicalEnvironmentDisabled = true; return { - getSourceFiles: function () { return transformed; }, - getTokenSourceMapRange: getTokenSourceMapRange, - isSubstitutionEnabled: isSubstitutionEnabled, - isEmitNotificationEnabled: isEmitNotificationEnabled, - onSubstituteNode: context.onSubstituteNode, - onEmitNode: context.onEmitNode, - dispose: function () { - for (var _i = 0, parseTreeNodesWithAnnotations_1 = parseTreeNodesWithAnnotations; _i < parseTreeNodesWithAnnotations_1.length; _i++) { - var node = parseTreeNodesWithAnnotations_1[_i]; - if (node.transformId === transformId) { - node.transformId = 0; - node.emitFlags = 0; - node.commentRange = undefined; - node.sourceMapRange = undefined; - } - } - parseTreeNodesWithAnnotations.length = 0; - } + transformed: transformed, + emitNodeWithSubstitution: emitNodeWithSubstitution, + emitNodeWithNotification: emitNodeWithNotification }; function transformSourceFile(sourceFile) { if (ts.isDeclarationFile(sourceFile)) { @@ -42023,75 +43555,37 @@ var ts; enabledSyntaxKindFeatures[kind] |= 1; } function isSubstitutionEnabled(node) { - return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0; + return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0 + && (ts.getEmitFlags(node) & 128) === 0; } - function onSubstituteNode(node, isExpression) { - return node; + function emitNodeWithSubstitution(emitContext, node, emitCallback) { + if (node) { + if (isSubstitutionEnabled(node)) { + var substitute = context.onSubstituteNode(emitContext, node); + if (substitute && substitute !== node) { + emitCallback(emitContext, substitute); + return; + } + } + emitCallback(emitContext, node); + } } function enableEmitNotification(kind) { enabledSyntaxKindFeatures[kind] |= 2; } function isEmitNotificationEnabled(node) { return (enabledSyntaxKindFeatures[node.kind] & 2) !== 0 - || (getNodeEmitFlags(node) & 64) !== 0; + || (ts.getEmitFlags(node) & 64) !== 0; } - function onEmitNode(node, emit) { - emit(node); - } - function beforeSetAnnotation(node) { - if ((node.flags & 8) === 0 && node.transformId !== transformId) { - parseTreeNodesWithAnnotations.push(node); - node.transformId = transformId; - } - } - function getNodeEmitFlags(node) { - return node.emitFlags; - } - function setNodeEmitFlags(node, emitFlags) { - beforeSetAnnotation(node); - node.emitFlags = emitFlags; - return node; - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - function setSourceMapRange(node, range) { - beforeSetAnnotation(node); - node.sourceMapRange = range; - return node; - } - function getTokenSourceMapRange(node, token) { - if (lastTokenSourceMapRangeNode === node && lastTokenSourceMapRangeToken === token) { - return lastTokenSourceMapRange; - } - var range; - var current = node; - while (current) { - range = current.id ? tokenSourceMapRanges[current.id + "-" + token] : undefined; - if (range !== undefined) { - break; + function emitNodeWithNotification(emitContext, node, emitCallback) { + if (node) { + if (isEmitNotificationEnabled(node)) { + context.onEmitNode(emitContext, node, emitCallback); + } + else { + emitCallback(emitContext, node); } - current = current.original; } - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - return range; - } - function setTokenSourceMapRange(node, token, range) { - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - tokenSourceMapRanges[ts.getNodeId(node) + "-" + token] = range; - return node; - } - function getCommentRange(node) { - return node.commentRange || node; - } - function setCommentRange(node, range) { - beforeSetAnnotation(node); - node.commentRange = range; - return node; } function hoistVariableDeclaration(name) { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); @@ -42144,54 +43638,6 @@ var ts; } } ts.transformFiles = transformFiles; - function chain(a, b, c, d, e) { - if (e) { - var args_3 = []; - for (var i = 0; i < arguments.length; i++) { - args_3[i] = arguments[i]; - } - return function (t) { return compose.apply(void 0, ts.map(args_3, function (f) { return f(t); })); }; - } - else if (d) { - return function (t) { return compose(a(t), b(t), c(t), d(t)); }; - } - else if (c) { - return function (t) { return compose(a(t), b(t), c(t)); }; - } - else if (b) { - return function (t) { return compose(a(t), b(t)); }; - } - else if (a) { - return function (t) { return compose(a(t)); }; - } - else { - return function (t) { return function (u) { return u; }; }; - } - } - function compose(a, b, c, d, e) { - if (e) { - var args_4 = []; - for (var i = 0; i < arguments.length; i++) { - args_4[i] = arguments[i]; - } - return function (t) { return ts.reduceLeft(args_4, function (u, f) { return f(u); }, t); }; - } - else if (d) { - return function (t) { return d(c(b(a(t)))); }; - } - else if (c) { - return function (t) { return c(b(a(t))); }; - } - else if (b) { - return function (t) { return b(a(t)); }; - } - else if (a) { - return function (t) { return a(t); }; - } - else { - return function (t) { return t; }; - } - } var _a; })(ts || (ts = {})); var ts; @@ -42202,11 +43648,11 @@ var ts; return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, false); } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -42242,7 +43688,7 @@ var ts; ts.forEach(sourceFile.referencedFiles, function (fileReference) { var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { addedGlobalFileReference = true; } emittedReferencedFiles.push(referencedFile); @@ -42427,7 +43873,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 | 1024, writer); errorNameNode = undefined; } } @@ -42439,7 +43885,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 | 1024, writer); errorNameNode = undefined; } } @@ -42612,9 +44058,9 @@ var ts; var count = 0; while (true) { count++; - var name_42 = baseName + "_" + count; - if (!(name_42 in currentIdentifiers)) { - return name_42; + var name_43 = baseName + "_" + count; + if (!(name_43 in currentIdentifiers)) { + return name_43; } } } @@ -42632,7 +44078,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -43038,7 +44484,7 @@ var ts; } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); } function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; @@ -43606,14 +45052,14 @@ var ts; return emitSourceFile(node); } } - function writeReferencePath(referencedFile, addBundledFileReference) { + function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; if (ts.isDeclarationFile(referencedFile)) { declFileName = referencedFile.fileName; } else { - ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); } if (declFileName) { declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); @@ -43630,8 +45076,8 @@ var ts; } } } - function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencesOutput @@ -43657,41 +45103,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - if (compilerOptions.extendedDiagnostics) { - return createSourceMapWriterWithExtendedDiagnostics(host, writer); - } - return createSourceMapWriterWorker(host, writer); - } - else { - return getNullSourceMapWriter(); - } - } - ts.createSourceMapWriter = createSourceMapWriter; - var nullSourceMapWriter; - function getNullSourceMapWriter() { - if (nullSourceMapWriter === undefined) { - nullSourceMapWriter = { - initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, - reset: function () { }, - getSourceMapData: function () { return undefined; }, - setSourceFile: function (sourceFile) { }, - emitPos: function (pos) { }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitTokenStart: function (token, pos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - emitTokenEnd: function (token, end, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - changeEmitSourcePos: function () { }, - stopOverridingSpan: function () { }, - getText: function () { return undefined; }, - getSourceMappingURL: function () { return undefined; } - }; - } - return nullSourceMapWriter; - } - ts.getNullSourceMapWriter = getNullSourceMapWriter; var defaultLastEncodedSourceMapSpan = { emittedLine: 1, emittedColumn: 1, @@ -43699,42 +45110,38 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function createSourceMapWriterWorker(host, writer) { + function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var currentSourceText; var sourceMapDir; - var stopOverridingSpan = false; - var modifyLastSourcePos = false; var sourceMapSourceIndex; var lastRecordedSourceMapSpan; var lastEncodedSourceMapSpan; var lastEncodedNameIndex; var sourceMapData; - var disableDepth; + var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { initialize: initialize, reset: reset, getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, - emitStart: emitStart, - emitEnd: emitEnd, - emitTokenStart: emitTokenStart, - emitTokenEnd: emitTokenEnd, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: function () { return stopOverridingSpan = true; }, + emitNodeWithSourceMap: emitNodeWithSourceMap, + emitTokenWithSourceMap: emitTokenWithSourceMap, getText: getText, getSourceMappingURL: getSourceMappingURL }; function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (disabled) { + return; + } if (sourceMapData) { reset(); } currentSourceFile = undefined; currentSourceText = undefined; - disableDepth = 0; sourceMapSourceIndex = -1; lastRecordedSourceMapSpan = undefined; lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan; @@ -43774,6 +45181,9 @@ var ts; } } function reset() { + if (disabled) { + return; + } currentSourceFile = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; @@ -43781,38 +45191,6 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; - disableDepth = 0; - } - function enable() { - if (disableDepth > 0) { - disableDepth--; - } - } - function disable() { - disableDepth++; - } - function updateLastEncodedAndRecordedSpans() { - if (modifyLastSourcePos) { - modifyLastSourcePos = false; - lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; - lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; - sourceMapData.sourceMapDecodedMappings.pop(); - lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? - sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : - defaultLastEncodedSourceMapSpan; - var sourceMapMappings = sourceMapData.sourceMapMappings; - var lenthToSet = sourceMapMappings.length - 1; - for (; lenthToSet >= 0; lenthToSet--) { - var currentChar = sourceMapMappings.charAt(lenthToSet); - if (currentChar === ",") { - break; - } - if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { - break; - } - } - sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); - } } function encodeLastRecordedSourceMapSpan() { if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { @@ -43843,7 +45221,7 @@ var ts; sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); } function emitPos(pos) { - if (ts.positionIsSynthesized(pos) || disableDepth > 0) { + if (disabled || ts.positionIsSynthesized(pos)) { return; } if (extendedDiagnostics) { @@ -43868,84 +45246,68 @@ var ts; sourceColumn: sourceLinePos.character, sourceIndex: sourceMapSourceIndex }; - stopOverridingSpan = false; } - else if (!stopOverridingSpan) { + else { lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } - updateLastEncodedAndRecordedSpans(); if (extendedDiagnostics) { ts.performance.mark("afterSourcemap"); ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); } } - function getStartPosPastDecorators(range) { - var rangeHasDecorators = !!range.decorators; - return ts.skipTrivia(currentSourceText, rangeHasDecorators ? range.decorators.end : range.pos); - } - function emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(getStartPosPastDecorators(range)); - } - if (ignoreChildrenCallback(contextNode)) { - disable(); - } + function emitNodeWithSourceMap(emitContext, node, emitCallback) { + if (disabled) { + return emitCallback(emitContext, node); } - else { - emitPos(getStartPosPastDecorators(range)); + if (node) { + var emitNode = node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var _a = emitNode && emitNode.sourceMapRange || node, pos = _a.pos, end = _a.end; + if (node.kind !== 287 + && (emitFlags & 512) === 0 + && pos >= 0) { + emitPos(ts.skipTrivia(currentSourceText, pos)); + } + if (emitFlags & 2048) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; + } + else { + emitCallback(emitContext, node); + } + if (node.kind !== 287 + && (emitFlags & 1024) === 0 + && end >= 0) { + emitPos(end); + } } } - function emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (ignoreChildrenCallback(contextNode)) { - enable(); - } - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(range.end); - } + function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + if (disabled) { + return emitCallback(token, tokenPos); } - else { - emitPos(range.end); + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + tokenPos = ts.skipTrivia(currentSourceText, range ? range.pos : tokenPos); + if ((emitFlags & 4096) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - stopOverridingSpan = false; - } - function emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return ts.skipTrivia(currentSourceText, tokenStartPos); - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenStartPos = range.pos; - } + tokenPos = emitCallback(token, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 8192) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - tokenStartPos = ts.skipTrivia(currentSourceText, tokenStartPos); - emitPos(tokenStartPos); - return tokenStartPos; - } - function emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return tokenEndPos; - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenEndPos = range.end; - } - } - emitPos(tokenEndPos); - return tokenEndPos; - } - function changeEmitSourcePos() { - ts.Debug.assert(!modifyLastSourcePos); - modifyLastSourcePos = true; + return tokenPos; } function setSourceFile(sourceFile) { + if (disabled) { + return; + } currentSourceFile = sourceFile; currentSourceText = currentSourceFile.text; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; @@ -43961,6 +45323,9 @@ var ts; } } function getText() { + if (disabled) { + return; + } encodeLastRecordedSourceMapSpan(); return ts.stringify({ version: 3, @@ -43973,6 +45338,9 @@ var ts; }); } function getSourceMappingURL() { + if (disabled) { + return; + } if (compilerOptions.inlineSourceMap) { var base64SourceMapText = ts.convertToBase64(getText()); return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; @@ -43982,46 +45350,7 @@ var ts; } } } - function createSourceMapWriterWithExtendedDiagnostics(host, writer) { - var _a = createSourceMapWriterWorker(host, writer), initialize = _a.initialize, reset = _a.reset, getSourceMapData = _a.getSourceMapData, setSourceFile = _a.setSourceFile, emitPos = _a.emitPos, emitStart = _a.emitStart, emitEnd = _a.emitEnd, emitTokenStart = _a.emitTokenStart, emitTokenEnd = _a.emitTokenEnd, changeEmitSourcePos = _a.changeEmitSourcePos, stopOverridingSpan = _a.stopOverridingSpan, getText = _a.getText, getSourceMappingURL = _a.getSourceMappingURL; - return { - initialize: initialize, - reset: reset, - getSourceMapData: getSourceMapData, - setSourceFile: setSourceFile, - emitPos: function (pos) { - ts.performance.mark("sourcemapStart"); - emitPos(pos); - ts.performance.measure("sourceMapTime", "sourcemapStart"); - }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitStart"); - emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitStart"); - }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitEnd"); - emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitEnd"); - }, - emitTokenStart: function (token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenStart"); - tokenStartPos = emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenStart"); - return tokenStartPos; - }, - emitTokenEnd: function (token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenEnd"); - tokenEndPos = emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenEnd"); - return tokenEndPos; - }, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: stopOverridingSpan, - getText: getText, - getSourceMappingURL: getSourceMappingURL - }; - } + ts.createSourceMapWriter = createSourceMapWriter; var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64FormatEncode(inValue) { if (inValue < 64) { @@ -44071,20 +45400,22 @@ var ts; emitBodyWithDetachedComments: emitBodyWithDetachedComments, emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition }; - function emitNodeWithComments(node, emitCallback) { + function emitNodeWithComments(emitContext, node, emitCallback) { if (disabled) { - emitCallback(node); + emitCallback(emitContext, node); return; } if (node) { - var _a = node.commentRange || node, pos = _a.pos, end = _a.end; - var emitFlags = node.emitFlags; + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var emitFlags = ts.getEmitFlags(node); if ((pos < 0 && end < 0) || (pos === end)) { if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } } else { @@ -44113,10 +45444,12 @@ var ts; ts.performance.measure("commentTime", "preEmitNodeWithComment"); } if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } if (extendedDiagnostics) { ts.performance.mark("beginEmitNodeWithComment"); @@ -44138,7 +45471,7 @@ var ts; ts.performance.mark("preEmitBodyWithDetachedComments"); } var pos = detachedRange.pos, end = detachedRange.end; - var emitFlags = node.emitFlags; + var emitFlags = ts.getEmitFlags(node); var skipLeadingComments = pos < 0 || (emitFlags & 16384) !== 0; var skipTrailingComments = disabled || end < 0 || (emitFlags & 32768) !== 0; if (!skipLeadingComments) { @@ -44147,8 +45480,10 @@ var ts; if (extendedDiagnostics) { ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); } - if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 65536 && !disabled) { + disabled = true; + emitCallback(node); + disabled = false; } else { emitCallback(node); @@ -44256,16 +45591,6 @@ var ts; currentLineMap = ts.getLineStarts(currentSourceFile); detachedCommentsInfo = undefined; } - function disableCommentsAndEmit(node, emitCallback) { - if (disabled) { - emitCallback(node); - } - else { - disabled = true; - emitCallback(node); - disabled = false; - } - } function hasDetachedComments(pos) { return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; } @@ -44311,7 +45636,9 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function emitFiles(resolver, host, targetSourceFile) { + var id = function (s) { return s; }; + var nullTransformers = [function (ctx) { return id; }]; + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) { var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; @@ -44319,7 +45646,7 @@ var ts; var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};"; var metadataHelper = "\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};"; var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; - var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; + var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; var generatorHelper = "\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;\n return { next: verb(0), \"throw\": verb(1), \"return\": verb(2) };\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};"; var exportStarHelper = "\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}"; var umdHelper = "\n(function (dependencies, factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define(dependencies, factory);\n }\n})"; @@ -44332,11 +45659,11 @@ var ts; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); var newLine = host.getNewLine(); - var transformers = ts.getTransformers(compilerOptions); + var transformers = emitOnlyDtsFiles ? nullTransformers : ts.getTransformers(compilerOptions); var writer = ts.createTextWriter(newLine); var write = writer.write, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; var sourceMap = ts.createSourceMapWriter(host, writer); - var emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitTokenStart = sourceMap.emitTokenStart, emitTokenEnd = sourceMap.emitTokenEnd; + var emitNodeWithSourceMap = sourceMap.emitNodeWithSourceMap, emitTokenWithSourceMap = sourceMap.emitTokenWithSourceMap; var comments = ts.createCommentWriter(host, writer, sourceMap); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; var nodeIdToGeneratedName; @@ -44353,14 +45680,17 @@ var ts; var awaiterEmitted; var isOwnFileEmit; var emitSkipped = false; + var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); ts.performance.mark("beforeTransform"); - var transformed = ts.transformFiles(resolver, host, ts.getSourceFilesToEmit(host, targetSourceFile), transformers); + var _a = ts.transformFiles(resolver, host, sourceFiles, transformers), transformed = _a.transformed, emitNodeWithSubstitution = _a.emitNodeWithSubstitution, emitNodeWithNotification = _a.emitNodeWithNotification; ts.performance.measure("transformTime", "beforeTransform"); - var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode; ts.performance.mark("beforePrint"); - ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile); - transformed.dispose(); + ts.forEachTransformedEmitFile(host, transformed, emitFile, emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); + for (var _b = 0, sourceFiles_4 = sourceFiles; _b < sourceFiles_4.length; _b++) { + var sourceFile = sourceFiles_4[_b]; + ts.disposeEmitNodes(sourceFile); + } return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -44369,16 +45699,20 @@ var ts; }; function emitFile(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, isBundledEmit) { if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + if (!emitOnlyDtsFiles) { + printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } } else { emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; } if (!emitSkipped && emittedFilesList) { - emittedFilesList.push(jsFilePath); + if (!emitOnlyDtsFiles) { + emittedFilesList.push(jsFilePath); + } if (sourceMapFilePath) { emittedFilesList.push(sourceMapFilePath); } @@ -44394,8 +45728,8 @@ var ts; generatedNameSet = ts.createMap(); isOwnFileEmit = !isBundledEmit; if (isBundledEmit && moduleKind) { - for (var _a = 0, sourceFiles_4 = sourceFiles; _a < sourceFiles_4.length; _a++) { - var sourceFile = sourceFiles_4[_a]; + for (var _a = 0, sourceFiles_5 = sourceFiles; _a < sourceFiles_5.length; _a++) { + var sourceFile = sourceFiles_5[_a]; emitEmitHelpers(sourceFile); } } @@ -44431,73 +45765,61 @@ var ts; currentFileIdentifiers = node.identifiers; sourceMap.setSourceFile(node); comments.setSourceFile(node); - emitNodeWithNotification(node, emitWorker); + pipelineEmitWithNotification(0, node); } function emit(node) { - emitNodeWithNotification(node, emitWithComments); - } - function emitWithComments(node) { - emitNodeWithComments(node, emitWithSourceMap); - } - function emitWithSourceMap(node) { - emitNodeWithSourceMap(node, emitWorker); + pipelineEmitWithNotification(3, node); } function emitIdentifierName(node) { - if (node) { - emitNodeWithNotification(node, emitIdentifierNameWithComments); - } - } - function emitIdentifierNameWithComments(node) { - emitNodeWithComments(node, emitWorker); + pipelineEmitWithNotification(2, node); } function emitExpression(node) { - emitNodeWithNotification(node, emitExpressionWithComments); + pipelineEmitWithNotification(1, node); } - function emitExpressionWithComments(node) { - emitNodeWithComments(node, emitExpressionWithSourceMap); + function pipelineEmitWithNotification(emitContext, node) { + emitNodeWithNotification(emitContext, node, pipelineEmitWithComments); } - function emitExpressionWithSourceMap(node) { - emitNodeWithSourceMap(node, emitExpressionWorker); - } - function emitNodeWithNotification(node, emitCallback) { - if (node) { - if (isEmitNotificationEnabled(node)) { - onEmitNode(node, emitCallback); - } - else { - emitCallback(node); - } - } - } - function emitNodeWithSourceMap(node, emitCallback) { - if (node) { - emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - emitCallback(node); - emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - function shouldSkipLeadingCommentsForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 16384) !== 0; - } - function shouldSkipLeadingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 512) !== 0; - } - function shouldSkipTrailingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 1024) !== 0; - } - function shouldSkipSourceMapForChildren(node) { - return (node.emitFlags & 2048) !== 0; - } - function emitWorker(node) { - if (tryEmitSubstitute(node, emitWorker, false)) { + function pipelineEmitWithComments(emitContext, node) { + if (emitContext === 0) { + pipelineEmitWithSourceMap(emitContext, node); return; } + emitNodeWithComments(emitContext, node, pipelineEmitWithSourceMap); + } + function pipelineEmitWithSourceMap(emitContext, node) { + if (emitContext === 0 + || emitContext === 2) { + pipelineEmitWithSubstitution(emitContext, node); + return; + } + emitNodeWithSourceMap(emitContext, node, pipelineEmitWithSubstitution); + } + function pipelineEmitWithSubstitution(emitContext, node) { + emitNodeWithSubstitution(emitContext, node, pipelineEmitForContext); + } + function pipelineEmitForContext(emitContext, node) { + switch (emitContext) { + case 0: return pipelineEmitInSourceFileContext(node); + case 2: return pipelineEmitInIdentifierNameContext(node); + case 3: return pipelineEmitInUnspecifiedContext(node); + case 1: return pipelineEmitInExpressionContext(node); + } + } + function pipelineEmitInSourceFileContext(node) { + var kind = node.kind; + switch (kind) { + case 256: + return emitSourceFile(node); + } + } + function pipelineEmitInIdentifierNameContext(node) { + var kind = node.kind; + switch (kind) { + case 69: + return emitIdentifier(node); + } + } + function pipelineEmitInUnspecifiedContext(node) { var kind = node.kind; switch (kind) { case 12: @@ -44524,7 +45846,8 @@ var ts; case 132: case 133: case 137: - return writeTokenNode(node); + writeTokenText(kind); + return; case 139: return emitQualifiedName(node); case 140: @@ -44700,17 +46023,12 @@ var ts; return emitShorthandPropertyAssignment(node); case 255: return emitEnumMember(node); - case 256: - return emitSourceFile(node); } if (ts.isExpression(node)) { - return emitExpressionWorker(node); + return pipelineEmitWithSubstitution(1, node); } } - function emitExpressionWorker(node) { - if (tryEmitSubstitute(node, emitExpressionWorker, true)) { - return; - } + function pipelineEmitInExpressionContext(node) { var kind = node.kind; switch (kind) { case 8: @@ -44726,7 +46044,8 @@ var ts; case 95: case 99: case 97: - return writeTokenNode(node); + writeTokenText(kind); + return; case 170: return emitArrayLiteralExpression(node); case 171: @@ -44804,7 +46123,7 @@ var ts; } } function emitIdentifier(node) { - if (node.emitFlags & 16) { + if (ts.getEmitFlags(node) & 16) { writeLines(umdHelper); } else { @@ -45019,7 +46338,7 @@ var ts; write("{}"); } else { - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 524288; if (indentedFlag) { increaseIndent(); } @@ -45032,21 +46351,18 @@ var ts; } } function emitPropertyAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } var indentBeforeDot = false; var indentAfterDot = false; - if (!(node.emitFlags & 1048576)) { + if (!(ts.getEmitFlags(node) & 1048576)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentText, node.expression.end) + 1; var dotToken = { kind: 21, pos: dotRangeStart, end: dotRangeEnd }; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } - var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); emitExpression(node.expression); increaseIndentIf(indentBeforeDot); + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); write(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); @@ -45057,15 +46373,14 @@ var ts; var text = getLiteralTextOfNode(expression); return text.indexOf(ts.tokenToString(21)) < 0; } - else { - var constantValue = tryGetConstEnumValue(expression); - return isFinite(constantValue) && Math.floor(constantValue) === constantValue; + else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { + var constantValue = ts.getConstantValue(expression); + return isFinite(constantValue) + && Math.floor(constantValue) === constantValue + && compilerOptions.removeComments; } } function emitElementAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } emitExpression(node.expression); write("["); emitExpression(node.argumentExpression); @@ -45220,7 +46535,7 @@ var ts; } } function emitBlockStatements(node) { - if (node.emitFlags & 32) { + if (ts.getEmitFlags(node) & 32) { emitList(node, node.statements, 384); } else { @@ -45395,11 +46710,11 @@ var ts; var body = node.body; if (body) { if (ts.isBlock(body)) { - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 524288; if (indentedFlag) { increaseIndent(); } - if (node.emitFlags & 4194304) { + if (ts.getEmitFlags(node) & 4194304) { emitSignatureHead(node); emitBlockFunctionBody(node, body); } @@ -45431,7 +46746,7 @@ var ts; emitWithPrefix(": ", node.type); } function shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) { - if (body.emitFlags & 32) { + if (ts.getEmitFlags(body) & 32) { return true; } if (body.multiLine) { @@ -45486,7 +46801,7 @@ var ts; emitModifiers(node, node.modifiers); write("class"); emitNodeWithPrefix(" ", node.name, emitIdentifierName); - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 524288; if (indentedFlag) { increaseIndent(); } @@ -45548,7 +46863,7 @@ var ts; emit(body); } function emitModuleBlock(node) { - if (isSingleLineEmptyBlock(node)) { + if (isEmptyBlock(node)) { write("{ }"); } else { @@ -45745,8 +47060,8 @@ var ts; emit(node.name); write(": "); var initializer = node.initializer; - if (!shouldSkipLeadingCommentsForNode(initializer)) { - var commentRange = initializer.commentRange || initializer; + if ((ts.getEmitFlags(initializer) & 16384) === 0) { + var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } emitExpression(initializer); @@ -45794,7 +47109,7 @@ var ts; return statements.length; } function emitHelpers(node) { - var emitFlags = node.emitFlags; + var emitFlags = ts.getEmitFlags(node); var helpersEmitted = false; if (emitFlags & 1) { helpersEmitted = emitEmitHelpers(currentSourceFile); @@ -45900,31 +47215,6 @@ var ts; write(suffix); } } - function tryEmitSubstitute(node, emitNode, isExpression) { - if (isSubstitutionEnabled(node) && (node.emitFlags & 128) === 0) { - var substitute = onSubstituteNode(node, isExpression); - if (substitute !== node) { - substitute.emitFlags |= 128; - emitNode(substitute); - return true; - } - } - return false; - } - function tryEmitConstantValue(node) { - var constantValue = tryGetConstEnumValue(node); - if (constantValue !== undefined) { - write(String(constantValue)); - if (!compilerOptions.removeComments) { - var propertyName = ts.isPropertyAccessExpression(node) - ? ts.declarationNameToString(node.name) - : getTextOfNode(node.argumentExpression); - write(" /* " + propertyName + " */"); - } - return true; - } - return false; - } function emitEmbeddedStatement(node) { if (ts.isBlock(node)) { write(" "); @@ -46024,7 +47314,7 @@ var ts; } } if (shouldEmitInterveningComments) { - var commentRange = child.commentRange || child; + var commentRange = ts.getCommentRange(child); emitTrailingCommentsOfPosition(commentRange.pos); } else { @@ -46066,27 +47356,12 @@ var ts; } } function writeToken(token, pos, contextNode) { - var tokenStartPos = emitTokenStart(token, pos, contextNode, shouldSkipLeadingSourceMapForToken, getTokenSourceMapRange); - var tokenEndPos = writeTokenText(token, tokenStartPos); - return emitTokenEnd(token, tokenEndPos, contextNode, shouldSkipTrailingSourceMapForToken, getTokenSourceMapRange); - } - function shouldSkipLeadingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 4096) !== 0; - } - function shouldSkipTrailingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 8192) !== 0; + return emitTokenWithSourceMap(contextNode, token, pos, writeTokenText); } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); - return ts.positionIsSynthesized(pos) ? -1 : pos + tokenString.length; - } - function writeTokenNode(node) { - if (node) { - emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - writeTokenText(node.kind); - emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } + return pos < 0 ? pos : pos + tokenString.length; } function increaseIndentIf(value, valueToWriteWhenNotIndenting) { if (value) { @@ -46225,17 +47500,12 @@ var ts; } return ts.getLiteralText(node, currentSourceFile, languageVersion); } - function tryGetConstEnumValue(node) { - if (compilerOptions.isolatedModules) { - return undefined; - } - return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) - ? resolver.getConstantValue(node) - : undefined; - } function isSingleLineEmptyBlock(block) { return !block.multiLine - && block.statements.length === 0 + && isEmptyBlock(block); + } + function isEmptyBlock(block) { + return block.statements.length === 0 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function isUniqueName(name) { @@ -46255,21 +47525,21 @@ var ts; } function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_43 = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name_43)) { + var name_44 = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name_44)) { tempFlags |= flags; - return name_43; + return name_44; } } while (true) { var count = tempFlags & 268435455; tempFlags++; if (count !== 8 && count !== 13) { - var name_44 = count < 26 + var name_45 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); - if (isUniqueName(name_44)) { - return name_44; + if (isUniqueName(name_45)) { + return name_45; } } } @@ -46445,581 +47715,6 @@ var ts; return ts.getNormalizedPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; - function trace(host, message) { - host.trace(ts.formatMessage.apply(undefined, arguments)); - } - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - function hasZeroOrOneAsteriskCharacter(str) { - var seenAsterisk = false; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - return false; - } - } - } - return true; - } - ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; - } - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); - function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); - } - return typesFilePath_1; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } - } - } - } - var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); - if (typesFilePath) { - return typesFilePath; - } - if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); - } - var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - return mainFilePath; - } - return undefined; - } - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - return {}; - } - } - var typeReferenceExtensions = [".d.ts"]; - function getEffectiveTypeRoots(options, host) { - if (options.typeRoots) { - return options.typeRoots; - } - var currentDirectory; - if (options.configFilePath) { - currentDirectory = ts.getDirectoryPath(options.configFilePath); - } - else if (host.getCurrentDirectory) { - currentDirectory = host.getCurrentDirectory(); - } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; - } - var typeRoots; - while (true) { - var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - var parent_15 = ts.getDirectoryPath(currentDirectory); - if (parent_15 === currentDirectory) { - break; - } - currentDirectory = parent_15; - } - return typeRoots; - } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { - compilerOptions: options, - host: host, - skipTsx: true, - traceEnabled: traceEnabled - }; - var typeRoots = getEffectiveTypeRoots(options, host); - if (traceEnabled) { - if (containingFile === undefined) { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); - } - } - else { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); - } - } - } - var failedLookupLocations = []; - if (typeRoots && typeRoots.length) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); - } - var primarySearchPaths = typeRoots; - for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { - var typeRoot = primarySearchPaths_1[_i]; - var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); - var candidateDirectory = ts.getDirectoryPath(candidate); - var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); - if (resolvedFile_1) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); - } - return { - resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, - failedLookupLocations: failedLookupLocations - }; - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); - } - } - var resolvedFile; - var initialLocationForSecondaryLookup; - if (containingFile) { - initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); - } - if (initialLocationForSecondaryLookup !== undefined) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); - } - resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState); - if (traceEnabled) { - if (resolvedFile) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); - } - } - return { - resolvedTypeReferenceDirective: resolvedFile - ? { primary: false, resolvedFileName: resolvedFile } - : undefined, - failedLookupLocations: failedLookupLocations - }; - } - ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - var result; - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); - break; - case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host); - break; - } - if (traceEnabled) { - if (result.resolvedModule) { - trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); - } - else { - return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); - } - } - function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { - var subst = _a[_i]; - var path = matchedStar ? subst.replace("*", matchedStar) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - } - return undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - function tryParsePattern(pattern) { - ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var traceEnabled = isTraceEnabled(compilerOptions, host); - var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); - var isExternalLibraryImport = false; - if (!resolvedFileName) { - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); - } - resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); - isExternalLibraryImport = resolvedFileName !== undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); - } - } - if (resolvedFileName && host.realpath) { - var originalFileName = resolvedFileName; - resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); - } - } - return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); - } - var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); - return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); - } - function directoryProbablyExists(directoryName, host) { - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - if (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); - } - } - function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - return ts.forEach(extensions, function (ext) { - return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); - }); - } - function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; - } - } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); - if (typesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); - var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || - tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); - if (result) { - return result; - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); - } - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - failedLookupLocation.push(packageJsonPath); - } - return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); - } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); - var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - } - function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { - directory = ts.normalizeSlashes(directory); - while (true) { - var baseName = ts.getBaseFileName(directory); - if (baseName !== "node_modules") { - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - return packageResult; - } - else { - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; - } - } - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - break; - } - directory = parentPath; - } - return undefined; - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; - var failedLookupLocations = []; - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); - if (resolvedFileName) { - return createResolvedModule(resolvedFileName, false, failedLookupLocations); - } - var referencedSourceFile; - if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); - } - return referencedSourceFile - ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - ts.classicNameResolver = classicNameResolver; function createCompilerHost(options, setParentNodes) { var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { @@ -47121,7 +47816,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.getEnvironmentVariable(name, undefined); }, + getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; @@ -47181,41 +47876,14 @@ var ts; var resolutions = []; var cache = ts.createMap(); for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { - var name_45 = names_2[_i]; - var result = name_45 in cache - ? cache[name_45] - : cache[name_45] = loader(name_45, containingFile); + var name_46 = names_2[_i]; + var result = name_46 in cache + ? cache[name_46] + : cache[name_46] = loader(name_46, containingFile); resolutions.push(result); } return resolutions; } - function getAutomaticTypeDirectiveNames(options, host) { - if (options.types) { - return options.types; - } - var result = []; - if (host.directoryExists && host.getDirectories) { - var typeRoots = getEffectiveTypeRoots(options, host); - if (typeRoots) { - for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { - var root = typeRoots_1[_i]; - if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - result.push(ts.getBaseFileName(normalized)); - } - } - } - } - } - } - return result; - } - ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -47241,7 +47909,7 @@ var ts; resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; } else { - var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -47249,15 +47917,15 @@ var ts; resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; } else { - var loader_2 = function (typesRef, containingFile) { return resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; + var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); }; } var filesByName = ts.createFileMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - var typeReferences = getAutomaticTypeDirectiveNames(options, host); - if (typeReferences) { + var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + if (typeReferences.length) { var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { @@ -47299,7 +47967,8 @@ var ts; getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, - getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -47346,6 +48015,7 @@ var ts; (oldOptions.configFilePath !== options.configFilePath) || (oldOptions.baseUrl !== options.baseUrl) || (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || + !ts.arrayIsEqualTo(oldOptions.lib, options.lib) || !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || !ts.equalOwnProperties(oldOptions.paths, options.paths)) { @@ -47446,16 +48116,19 @@ var ts; function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false)); } - function emit(sourceFile, writeFileCallback, cancellationToken) { - return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); }); + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); } - function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { var declarationDiagnostics = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; @@ -47476,7 +48149,7 @@ var ts; } var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); ts.performance.mark("beforeEmit"); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -47991,7 +48664,6 @@ var ts; for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); - var resolvedPath = resolution ? ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName) : undefined; var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport; var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName); if (isFromNodeModulesSearch) { @@ -48003,7 +48675,7 @@ var ts; modulesWithElidedImports[file.path] = true; } else if (shouldAddFile) { - findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); + findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } if (isFromNodeModulesSearch) { currentNodeModulesDepth--; @@ -48017,8 +48689,8 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var file = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var file = sourceFiles_6[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -48029,8 +48701,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -48073,7 +48745,7 @@ var ts; if (!ts.hasProperty(options.paths, key)) { continue; } - if (!hasZeroOrOneAsteriskCharacter(key)) { + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { @@ -48084,7 +48756,7 @@ var ts; var subst = _a[_i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { - if (!hasZeroOrOneAsteriskCharacter(subst)) { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } @@ -48123,6 +48795,9 @@ var ts; if (options.lib && options.noLib) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")); } + if (options.noImplicitUseStrict && options.alwaysStrict) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict")); + } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); @@ -48685,7 +49360,7 @@ var ts; case 97: return true; case 69: - return node.originalKeywordKind === 97 && node.parent.kind === 142; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 142; default: return false; } @@ -49258,7 +49933,6 @@ var ts; } ts.isInNonReferenceComment = isInNonReferenceComment; })(ts || (ts = {})); -var ts; (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 142; @@ -49481,7 +50155,7 @@ var ts; return ts.ensureScriptKind(fileName, scriptKind); } ts.getScriptKind = getScriptKind; - function parseAndReEmitConfigJSONFile(content) { + function sanitizeConfigFile(configFileName, content) { var options = { fileName: "config.js", compilerOptions: { @@ -49492,14 +50166,17 @@ var ts; }; var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; var trimmedOutput = outputText.trim(); - var configJsonObject = JSON.parse(trimmedOutput.substring(1, trimmedOutput.length - 2)); for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; diagnostic.start = diagnostic.start - 1; } - return { configJsonObject: configJsonObject, diagnostics: diagnostics }; + var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), false), config = _b.config, error = _b.error; + return { + configJsonObject: config || {}, + diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics + }; } - ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile; + ts.sanitizeConfigFile = sanitizeConfigFile; })(ts || (ts = {})); var ts; (function (ts) { @@ -50701,8 +51378,7 @@ var ts; return; case 142: if (token.parent.name === token) { - var isThis_1 = token.kind === 69 && token.originalKeywordKind === 97; - return isThis_1 ? 3 : 17; + return ts.isThisIdentifier(token) ? 3 : 17; } return; } @@ -50743,13 +51419,13 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; if (isJsDocTagName) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, false); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, true); ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); } else { @@ -50773,17 +51449,17 @@ var ts; if (!isMemberCompletion && !isJsDocTagName) { ts.addRange(entries, keywordCompletions); } - return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation || ts.isSourceFileJavaScript(sourceFile), entries: entries }; + return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { var entries = []; var nameTable = ts.getNameTable(sourceFile); - for (var name_46 in nameTable) { - if (nameTable[name_46] === position) { + for (var name_47 in nameTable) { + if (nameTable[name_47] === position) { continue; } - if (!uniqueNames[name_46]) { - uniqueNames[name_46] = name_46; - var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_46), compilerOptions.target, true); + if (!uniqueNames[name_47]) { + uniqueNames[name_47] = name_47; + var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_47), compilerOptions.target, true); if (displayName) { var entry = { name: displayName, @@ -50833,7 +51509,9 @@ var ts; if (!node || node.kind !== 9) { return undefined; } - if (node.parent.kind === 253 && node.parent.parent.kind === 171) { + if (node.parent.kind === 253 && + node.parent.parent.kind === 171 && + node.parent.name === node) { return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent); } else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { @@ -50856,7 +51534,7 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } } @@ -50872,7 +51550,7 @@ var ts; } } if (entries.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; } return undefined; } @@ -50882,7 +51560,7 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } return undefined; @@ -50893,7 +51571,7 @@ var ts; var entries_2 = []; addStringLiteralCompletionsFromType(type, entries_2); if (entries_2.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } } return undefined; @@ -50934,6 +51612,7 @@ var ts; entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span); } return { + isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries @@ -50964,13 +51643,15 @@ var ts; } function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, span, exclude, result) { if (result === void 0) { result = []; } + if (fragment === undefined) { + fragment = ""; + } + fragment = ts.normalizeSlashes(fragment); fragment = ts.getDirectoryPath(fragment); - if (!fragment) { - fragment = "./"; - } - else { - fragment = ts.ensureTrailingDirectorySeparator(fragment); + if (fragment === "") { + fragment = "." + ts.directorySeparator; } + fragment = ts.ensureTrailingDirectorySeparator(fragment); var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment)); var baseDirectory = ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); @@ -51126,6 +51807,12 @@ var ts; if (!range) { return undefined; } + var completionInfo = { + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: true, + entries: [] + }; var text = sourceFile.text.substr(range.pos, position - range.pos); var match = tripleSlashDirectiveFragmentRegex.exec(text); if (match) { @@ -51133,22 +51820,16 @@ var ts; var kind = match[2]; var toComplete = match[3]; var scriptPath = ts.getDirectoryPath(sourceFile.path); - var entries_3; if (kind === "path") { var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - entries_3 = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), true, span_10, sourceFile.path); + completionInfo.entries = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), true, span_10, sourceFile.path); } else { var span_11 = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; - entries_3 = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); + completionInfo.entries = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); } - return { - isMemberCompletion: false, - isNewIdentifierLocation: true, - entries: entries_3 - }; } - return undefined; + return completionInfo; } function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { if (result === void 0) { result = []; } @@ -51347,7 +52028,7 @@ var ts; } } if (isJsDocTagName) { - return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; } if (!insideJsDocTagExpression) { log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); @@ -51399,6 +52080,7 @@ var ts; } } var semanticStart = ts.timestamp(); + var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; var symbols = []; @@ -51429,10 +52111,12 @@ var ts; if (!tryGetGlobalSymbols()) { return undefined; } + isGlobalCompletion = true; } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; function getTypeScriptMemberSymbols() { + isGlobalCompletion = false; isMemberCompletion = true; isNewIdentifierLocation = false; if (node.kind === 69 || node.kind === 139 || node.kind === 172) { @@ -51483,6 +52167,7 @@ var ts; var attrsType = void 0; if ((jsxContainer.kind === 242) || (jsxContainer.kind === 243)) { attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); + isGlobalCompletion = false; if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); isMemberCompletion = true; @@ -51842,8 +52527,8 @@ var ts; if (element.getStart() <= position && position <= element.getEnd()) { continue; } - var name_47 = element.propertyName || element.name; - existingImportsOrExports[name_47.text] = true; + var name_48 = element.propertyName || element.name; + existingImportsOrExports[name_48.text] = true; } if (!ts.someProperties(existingImportsOrExports)) { return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); @@ -51927,7 +52612,7 @@ var ts; sortText: "0" }); } - var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s* sourceFile.text.length) { return getBaseIndentation(options); } - if (options.IndentStyle === ts.IndentStyle.None) { + if (options.indentStyle === ts.IndentStyle.None) { return 0; } var precedingToken = ts.findPrecedingToken(position, sourceFile); @@ -58576,7 +59140,7 @@ var ts; return 0; } var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; - if (options.IndentStyle === ts.IndentStyle.Block) { + if (options.indentStyle === ts.IndentStyle.Block) { var current_1 = position; while (current_1 > 0) { var char = sourceFile.text.charCodeAt(current_1); @@ -58605,7 +59169,7 @@ var ts; indentationDelta = 0; } else { - indentationDelta = lineAtPosition !== currentStart.line ? options.IndentSize : 0; + indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0; } break; } @@ -58615,7 +59179,7 @@ var ts; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1) { - return actualIndentation + options.IndentSize; + return actualIndentation + options.indentSize; } previous = current; current = current.parent; @@ -58626,15 +59190,15 @@ var ts; return getIndentationForNodeWorker(current, currentStart, undefined, indentationDelta, sourceFile, options); } SmartIndenter.getIndentation = getIndentation; - function getBaseIndentation(options) { - return options.BaseIndentSize || 0; - } - SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, 0, sourceFile, options); } SmartIndenter.getIndentationForNode = getIndentationForNode; + function getBaseIndentation(options) { + return options.baseIndentSize || 0; + } + SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) { var parent = current.parent; var parentStart; @@ -58664,7 +59228,7 @@ var ts; } } if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { - indentationDelta += options.IndentSize; + indentationDelta += options.indentSize; } current = parent; currentStart = parentStart; @@ -58842,7 +59406,7 @@ var ts; break; } if (ch === 9) { - column += options.TabSize + (column % options.TabSize); + column += options.tabSize + (column % options.tabSize); } else { column++; @@ -58940,11 +59504,116 @@ var ts; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + var codeFixes = ts.createMap(); + function registerCodeFix(action) { + ts.forEach(action.errorCodes, function (error) { + var fixes = codeFixes[error]; + if (!fixes) { + fixes = []; + codeFixes[error] = fixes; + } + fixes.push(action); + }); + } + codefix.registerCodeFix = registerCodeFix; + function getSupportedErrorCodes() { + return Object.keys(codeFixes); + } + codefix.getSupportedErrorCodes = getSupportedErrorCodes; + function getFixes(context) { + var fixes = codeFixes[context.errorCode]; + var allActions = []; + ts.forEach(fixes, function (f) { + var actions = f.getCodeActions(context); + if (actions && actions.length > 0) { + allActions = allActions.concat(actions); + } + }); + return allActions; + } + codefix.getFixes = getFixes; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var codefix; + (function (codefix) { + function getOpenBraceEnd(constructor, sourceFile) { + return constructor.body.getFirstToken(sourceFile).getEnd(); + } + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 121) { + return undefined; + } + var newPosition = getOpenBraceEnd(token.parent, sourceFile); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), + changes: [{ fileName: sourceFile.fileName, textChanges: [{ newText: "super();", span: { start: newPosition, length: 0 } }] }] + }]; + } + }); + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 97) { + return undefined; + } + var constructor = ts.getContainingFunction(token); + var superCall = findSuperCall(constructor.body); + if (!superCall) { + return undefined; + } + if (superCall.expression && superCall.expression.kind == 174) { + var arguments_1 = superCall.expression.arguments; + for (var i = 0; i < arguments_1.length; i++) { + if (arguments_1[i].expression === token) { + return undefined; + } + } + } + var newPosition = getOpenBraceEnd(constructor, sourceFile); + var changes = [{ + fileName: sourceFile.fileName, textChanges: [{ + newText: superCall.getText(sourceFile), + span: { start: newPosition, length: 0 } + }, + { + newText: "", + span: { start: superCall.getStart(sourceFile), length: superCall.getWidth(sourceFile) } + }] + }]; + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), + changes: changes + }]; + function findSuperCall(n) { + if (n.kind === 202 && ts.isSuperCall(n.expression)) { + return n; + } + if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findSuperCall); + } + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { ts.servicesVersion = "0.5"; function createNode(kind, pos, end, parent) { var node = kind >= 139 ? new NodeObject(kind, pos, end) : - kind === 69 ? new IdentifierObject(kind, pos, end) : + kind === 69 ? new IdentifierObject(69, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; return node; @@ -59167,15 +59836,16 @@ var ts; var TokenObject = (function (_super) { __extends(TokenObject, _super); function TokenObject(kind, pos, end) { - _super.call(this, pos, end); - this.kind = kind; + var _this = _super.call(this, pos, end) || this; + _this.kind = kind; + return _this; } return TokenObject; }(TokenOrIdentifierObject)); var IdentifierObject = (function (_super) { __extends(IdentifierObject, _super); function IdentifierObject(kind, pos, end) { - _super.call(this, pos, end); + return _super.call(this, pos, end) || this; } return IdentifierObject; }(TokenOrIdentifierObject)); @@ -59249,7 +59919,7 @@ var ts; var SourceFileObject = (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { - _super.call(this, kind, pos, end); + return _super.call(this, kind, pos, end) || this; } SourceFileObject.prototype.update = function (newText, textChangeRange) { return ts.updateSourceFile(this, newText, textChangeRange); @@ -59406,6 +60076,30 @@ var ts; getSignatureConstructor: function () { return SignatureObject; } }; } + function toEditorSettings(optionsAsMap) { + var allPropertiesAreCamelCased = true; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) { + allPropertiesAreCamelCased = false; + break; + } + } + if (allPropertiesAreCamelCased) { + return optionsAsMap; + } + var settings = {}; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key)) { + var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1); + settings[newKey] = optionsAsMap[key]; + } + } + return settings; + } + ts.toEditorSettings = toEditorSettings; + function isCamelCase(s) { + return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); + } function displayPartsToString(displayParts) { if (displayParts) { return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join(""); @@ -59420,6 +60114,10 @@ var ts; }; } ts.getDefaultCompilerOptions = getDefaultCompilerOptions; + function getSupportedCodeFixes() { + return ts.codefix.getSupportedErrorCodes(); + } + ts.getSupportedCodeFixes = getSupportedCodeFixes; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; @@ -59583,7 +60281,8 @@ var ts; var ruleProvider; var program; var lastProjectVersion; - var useCaseSensitivefileNames = false; + var lastTypesRootVersion = 0; + var useCaseSensitivefileNames = host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(); var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); var currentDirectory = host.getCurrentDirectory(); if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { @@ -59619,6 +60318,12 @@ var ts; lastProjectVersion = hostProjectVersion; } } + var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; + if (lastTypesRootVersion !== typeRootsVersion) { + log("TypeRoots version has changed; provide new program"); + program = undefined; + lastTypesRootVersion = typeRootsVersion; + } var hostCache = new HostCache(host, getCanonicalFileName); if (programUpToDate()) { return; @@ -59878,12 +60583,12 @@ var ts; synchronizeHostData(); return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, findInStrings, findInComments); } - function getNavigateToItems(searchValue, maxResultCount, fileName) { + function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { synchronizeHostData(); var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); - return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount); + return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName) { + function getEmitOutput(fileName, emitOnlyDtsFiles) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var outputFiles = []; @@ -59894,7 +60599,7 @@ var ts; text: data }); } - var emitOutput = program.emit(sourceFile, writeFile, cancellationToken); + var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles); return { outputFiles: outputFiles, emitSkipped: emitOutput.emitSkipped @@ -59957,14 +60662,26 @@ var ts; return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); } function getNavigationBarItems(fileName) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function getNavigationTree(fileName) { + return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function isTsOrTsxFile(fileName) { + var kind = ts.getScriptKind(fileName, host); + return kind === 3 || kind === 4; } function getSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + return []; + } synchronizeHostData(); return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } function getEncodedSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + return { spans: [], endOfLineState: 0 }; + } synchronizeHostData(); return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } @@ -60020,34 +60737,60 @@ var ts; } function getIndentationAtPosition(fileName, position, editorOptions) { var start = ts.timestamp(); + var settings = toEditorSettings(editorOptions); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); start = ts.timestamp(); - var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); + var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings); log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); return result; } function getFormattingEditsForRange(fileName, start, end, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsForDocument(fileName, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var settings = toEditorSettings(options); if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); } else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); } else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); } return []; } + function getCodeFixesAtPosition(fileName, start, end, errorCodes) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var span = { start: start, length: end - start }; + var newLineChar = ts.getNewLineOrDefaultFromHost(host); + var allFixes = []; + ts.forEach(errorCodes, function (error) { + cancellationToken.throwIfCancellationRequested(); + var context = { + errorCode: error, + sourceFile: sourceFile, + span: span, + program: program, + newLineCharacter: newLineChar + }; + var fixes = ts.codefix.getFixes(context); + if (fixes) { + allFixes = allFixes.concat(fixes); + } + }); + return allFixes; + } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } @@ -60159,6 +60902,7 @@ var ts; getRenameInfo: getRenameInfo, findRenameLocations: findRenameLocations, getNavigationBarItems: getNavigationBarItems, + getNavigationTree: getNavigationTree, getOutliningSpans: getOutliningSpans, getTodoComments: getTodoComments, getBraceMatchingAtPosition: getBraceMatchingAtPosition, @@ -60168,6 +60912,7 @@ var ts; getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getCodeFixesAtPosition: getCodeFixesAtPosition, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, @@ -60233,43 +60978,2344 @@ var ts; (function (ts) { var server; (function (server) { - var spaceCache = []; - function generateSpaces(n) { - if (!spaceCache[n]) { - var strBuilder = ""; - for (var i = 0; i < n; i++) { - strBuilder += " "; - } - spaceCache[n] = strBuilder; + var ScriptInfo = (function () { + function ScriptInfo(host, fileName, content, scriptKind, isOpen, hasMixedContent) { + if (isOpen === void 0) { isOpen = false; } + if (hasMixedContent === void 0) { hasMixedContent = false; } + this.host = host; + this.fileName = fileName; + this.scriptKind = scriptKind; + this.isOpen = isOpen; + this.hasMixedContent = hasMixedContent; + this.containingProjects = []; + this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + this.svc = server.ScriptVersionCache.fromString(host, content); + this.scriptKind = scriptKind + ? scriptKind + : ts.getScriptKindFromFileName(fileName); } - return spaceCache[n]; + ScriptInfo.prototype.getFormatCodeSettings = function () { + return this.formatCodeSettings; + }; + ScriptInfo.prototype.attachToProject = function (project) { + var isNew = !this.isAttached(project); + if (isNew) { + this.containingProjects.push(project); + } + return isNew; + }; + ScriptInfo.prototype.isAttached = function (project) { + switch (this.containingProjects.length) { + case 0: return false; + case 1: return this.containingProjects[0] === project; + case 2: return this.containingProjects[0] === project || this.containingProjects[1] === project; + default: return ts.contains(this.containingProjects, project); + } + }; + ScriptInfo.prototype.detachFromProject = function (project) { + switch (this.containingProjects.length) { + case 0: + return; + case 1: + if (this.containingProjects[0] === project) { + this.containingProjects.pop(); + } + break; + case 2: + if (this.containingProjects[0] === project) { + this.containingProjects[0] = this.containingProjects.pop(); + } + else if (this.containingProjects[1] === project) { + this.containingProjects.pop(); + } + break; + default: + server.removeItemFromSet(this.containingProjects, project); + break; + } + }; + ScriptInfo.prototype.detachAllProjects = function () { + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + p.removeFile(this, false); + } + this.containingProjects.length = 0; + }; + ScriptInfo.prototype.getDefaultProject = function () { + if (this.containingProjects.length === 0) { + return server.Errors.ThrowNoProject(); + } + ts.Debug.assert(this.containingProjects.length !== 0); + return this.containingProjects[0]; + }; + ScriptInfo.prototype.setFormatOptions = function (formatSettings) { + if (formatSettings) { + if (!this.formatCodeSettings) { + this.formatCodeSettings = server.getDefaultFormatCodeSettings(this.host); + } + server.mergeMaps(this.formatCodeSettings, formatSettings); + } + }; + ScriptInfo.prototype.setWatcher = function (watcher) { + this.stopWatcher(); + this.fileWatcher = watcher; + }; + ScriptInfo.prototype.stopWatcher = function () { + if (this.fileWatcher) { + this.fileWatcher.close(); + this.fileWatcher = undefined; + } + }; + ScriptInfo.prototype.getLatestVersion = function () { + return this.svc.latestVersion().toString(); + }; + ScriptInfo.prototype.reload = function (script) { + this.svc.reload(script); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.saveTo = function (fileName) { + var snap = this.snap(); + this.host.writeFile(fileName, snap.getText(0, snap.getLength())); + }; + ScriptInfo.prototype.reloadFromFile = function () { + if (this.hasMixedContent) { + this.reload(""); + } + else { + this.svc.reloadFromFile(this.fileName); + this.markContainingProjectsAsDirty(); + } + }; + ScriptInfo.prototype.snap = function () { + return this.svc.getSnapshot(); + }; + ScriptInfo.prototype.getLineInfo = function (line) { + var snap = this.snap(); + return snap.index.lineNumberToInfo(line); + }; + ScriptInfo.prototype.editContent = function (start, end, newText) { + this.svc.edit(start, end - start, newText); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.markContainingProjectsAsDirty = function () { + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + p.markAsDirty(); + } + }; + ScriptInfo.prototype.lineToTextSpan = function (line) { + var index = this.snap().index; + var lineInfo = index.lineNumberToInfo(line + 1); + var len; + if (lineInfo.leaf) { + len = lineInfo.leaf.text.length; + } + else { + var nextLineInfo = index.lineNumberToInfo(line + 2); + len = nextLineInfo.offset - lineInfo.offset; + } + return ts.createTextSpan(lineInfo.offset, len); + }; + ScriptInfo.prototype.lineOffsetToPosition = function (line, offset) { + var index = this.snap().index; + var lineInfo = index.lineNumberToInfo(line); + return (lineInfo.offset + offset - 1); + }; + ScriptInfo.prototype.positionToLineOffset = function (position) { + var index = this.snap().index; + var lineOffset = index.charOffsetToLineNumberAndPos(position); + return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + }; + return ScriptInfo; + }()); + server.ScriptInfo = ScriptInfo; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + var LSHost = (function () { + function LSHost(host, project, cancellationToken) { + var _this = this; + this.host = host; + this.project = project; + this.cancellationToken = cancellationToken; + this.getCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); + this.resolvedModuleNames = ts.createFileMap(); + this.resolvedTypeReferenceDirectives = ts.createFileMap(); + if (host.trace) { + this.trace = function (s) { return host.trace(s); }; + } + this.resolveModuleName = function (moduleName, containingFile, compilerOptions, host) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); + if (primaryResult.resolvedModule) { + if (ts.fileExtensionIsAny(primaryResult.resolvedModule.resolvedFileName, ts.supportedTypeScriptExtensions)) { + return primaryResult; + } + } + var secondaryLookupFailedLookupLocations = []; + var globalCache = _this.project.projectService.typingsInstaller.globalTypingsCacheLocation; + if (_this.project.getTypingOptions().enableAutoDiscovery && globalCache) { + var traceEnabled = ts.isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + ts.trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, _this.project.getProjectName(), moduleName, globalCache); + } + var state = { compilerOptions: compilerOptions, host: host, skipTsx: false, traceEnabled: traceEnabled }; + var resolvedName = ts.loadModuleFromNodeModules(moduleName, globalCache, secondaryLookupFailedLookupLocations, state, true); + if (resolvedName) { + return ts.createResolvedModule(resolvedName, true, primaryResult.failedLookupLocations.concat(secondaryLookupFailedLookupLocations)); + } + } + if (!primaryResult.resolvedModule && secondaryLookupFailedLookupLocations.length) { + primaryResult.failedLookupLocations = primaryResult.failedLookupLocations.concat(secondaryLookupFailedLookupLocations); + } + return primaryResult; + }; + } + LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult) { + var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); + var currentResolutionsInFile = cache.get(path); + var newResolutions = ts.createMap(); + var resolvedModules = []; + var compilerOptions = this.getCompilationSettings(); + var lastDeletedFileName = this.project.projectService.lastDeletedFile && this.project.projectService.lastDeletedFile.fileName; + for (var _i = 0, names_3 = names; _i < names_3.length; _i++) { + var name_52 = names_3[_i]; + var resolution = newResolutions[name_52]; + if (!resolution) { + var existingResolution = currentResolutionsInFile && currentResolutionsInFile[name_52]; + if (moduleResolutionIsValid(existingResolution)) { + resolution = existingResolution; + } + else { + newResolutions[name_52] = resolution = loader(name_52, containingFile, compilerOptions, this); + } + } + ts.Debug.assert(resolution !== undefined); + resolvedModules.push(getResult(resolution)); + } + cache.set(path, newResolutions); + return resolvedModules; + function moduleResolutionIsValid(resolution) { + if (!resolution) { + return false; + } + var result = getResult(resolution); + if (result) { + if (result.resolvedFileName && result.resolvedFileName === lastDeletedFileName) { + return false; + } + return true; + } + return resolution.failedLookupLocations.length === 0; + } + }; + LSHost.prototype.getProjectVersion = function () { + return this.project.getProjectVersion(); + }; + LSHost.prototype.getCompilationSettings = function () { + return this.compilationSettings; + }; + LSHost.prototype.useCaseSensitiveFileNames = function () { + return this.host.useCaseSensitiveFileNames; + }; + LSHost.prototype.getCancellationToken = function () { + return this.cancellationToken; + }; + LSHost.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { + return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, function (m) { return m.resolvedTypeReferenceDirective; }); + }; + LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) { + return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, this.resolveModuleName, function (m) { return m.resolvedModule; }); + }; + LSHost.prototype.getDefaultLibFileName = function () { + var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath())); + return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings)); + }; + LSHost.prototype.getScriptSnapshot = function (filename) { + var scriptInfo = this.project.getScriptInfoLSHost(filename); + if (scriptInfo) { + return scriptInfo.snap(); + } + }; + LSHost.prototype.getScriptFileNames = function () { + return this.project.getRootFilesLSHost(); + }; + LSHost.prototype.getTypeRootsVersion = function () { + return this.project.typesVersion; + }; + LSHost.prototype.getScriptKind = function (fileName) { + var info = this.project.getScriptInfoLSHost(fileName); + return info && info.scriptKind; + }; + LSHost.prototype.getScriptVersion = function (filename) { + var info = this.project.getScriptInfoLSHost(filename); + return info && info.getLatestVersion(); + }; + LSHost.prototype.getCurrentDirectory = function () { + return this.host.getCurrentDirectory(); + }; + LSHost.prototype.resolvePath = function (path) { + return this.host.resolvePath(path); + }; + LSHost.prototype.fileExists = function (path) { + return this.host.fileExists(path); + }; + LSHost.prototype.readFile = function (fileName) { + return this.host.readFile(fileName); + }; + LSHost.prototype.directoryExists = function (path) { + return this.host.directoryExists(path); + }; + LSHost.prototype.readDirectory = function (path, extensions, exclude, include) { + return this.host.readDirectory(path, extensions, exclude, include); + }; + LSHost.prototype.getDirectories = function (path) { + return this.host.getDirectories(path); + }; + LSHost.prototype.notifyFileRemoved = function (info) { + this.resolvedModuleNames.remove(info.path); + this.resolvedTypeReferenceDirectives.remove(info.path); + }; + LSHost.prototype.setCompilationSettings = function (opt) { + this.compilationSettings = opt; + this.resolvedModuleNames.clear(); + this.resolvedTypeReferenceDirectives.clear(); + }; + return LSHost; + }()); + server.LSHost = LSHost; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + server.nullTypingsInstaller = { + enqueueInstallTypingsRequest: function () { }, + attach: function (projectService) { }, + onProjectClosed: function (p) { }, + globalTypingsCacheLocation: undefined + }; + var TypingsCacheEntry = (function () { + function TypingsCacheEntry() { + } + return TypingsCacheEntry; + }()); + function setIsEqualTo(arr1, arr2) { + if (arr1 === arr2) { + return true; + } + if ((arr1 || server.emptyArray).length === 0 && (arr2 || server.emptyArray).length === 0) { + return true; + } + var set = ts.createMap(); + var unique = 0; + for (var _i = 0, arr1_1 = arr1; _i < arr1_1.length; _i++) { + var v = arr1_1[_i]; + if (set[v] !== true) { + set[v] = true; + unique++; + } + } + for (var _a = 0, arr2_1 = arr2; _a < arr2_1.length; _a++) { + var v = arr2_1[_a]; + if (!ts.hasProperty(set, v)) { + return false; + } + if (set[v] === true) { + set[v] = false; + unique--; + } + } + return unique === 0; } - server.generateSpaces = generateSpaces; - function generateIndentString(n, editorOptions) { - if (editorOptions.ConvertTabsToSpaces) { - return generateSpaces(n); + function typingOptionsChanged(opt1, opt2) { + return opt1.enableAutoDiscovery !== opt2.enableAutoDiscovery || + !setIsEqualTo(opt1.include, opt2.include) || + !setIsEqualTo(opt1.exclude, opt2.exclude); + } + function compilerOptionsChanged(opt1, opt2) { + return opt1.allowJs != opt2.allowJs; + } + function toTypingsArray(arr) { + arr.sort(); + return arr; + } + var TypingsCache = (function () { + function TypingsCache(installer) { + this.installer = installer; + this.perProjectCache = ts.createMap(); } - else { - var result = ""; - for (var i = 0; i < Math.floor(n / editorOptions.TabSize); i++) { - result += "\t"; + TypingsCache.prototype.getTypingsForProject = function (project, forceRefresh) { + var typingOptions = project.getTypingOptions(); + if (!typingOptions || !typingOptions.enableAutoDiscovery) { + return server.emptyArray; } - for (var i = 0; i < n % editorOptions.TabSize; i++) { - result += " "; + var entry = this.perProjectCache[project.getProjectName()]; + var result = entry ? entry.typings : server.emptyArray; + if (forceRefresh || !entry || typingOptionsChanged(typingOptions, entry.typingOptions) || compilerOptionsChanged(project.getCompilerOptions(), entry.compilerOptions)) { + this.perProjectCache[project.getProjectName()] = { + compilerOptions: project.getCompilerOptions(), + typingOptions: typingOptions, + typings: result, + poisoned: true + }; + this.installer.enqueueInstallTypingsRequest(project, typingOptions); } return result; + }; + TypingsCache.prototype.invalidateCachedTypingsForProject = function (project) { + var typingOptions = project.getTypingOptions(); + if (!typingOptions.enableAutoDiscovery) { + return; + } + this.installer.enqueueInstallTypingsRequest(project, typingOptions); + }; + TypingsCache.prototype.updateTypingsForProject = function (projectName, compilerOptions, typingOptions, newTypings) { + this.perProjectCache[projectName] = { + compilerOptions: compilerOptions, + typingOptions: typingOptions, + typings: toTypingsArray(newTypings), + poisoned: false + }; + }; + TypingsCache.prototype.onProjectClosed = function (project) { + delete this.perProjectCache[project.getProjectName()]; + this.installer.onProjectClosed(project); + }; + return TypingsCache; + }()); + server.TypingsCache = TypingsCache; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + var crypto = require("crypto"); + function shouldEmitFile(scriptInfo) { + return !scriptInfo.hasMixedContent; + } + server.shouldEmitFile = shouldEmitFile; + var BuilderFileInfo = (function () { + function BuilderFileInfo(scriptInfo, project) { + this.scriptInfo = scriptInfo; + this.project = project; + } + BuilderFileInfo.prototype.isExternalModuleOrHasOnlyAmbientExternalModules = function () { + var sourceFile = this.getSourceFile(); + return ts.isExternalModule(sourceFile) || this.containsOnlyAmbientModules(sourceFile); + }; + BuilderFileInfo.prototype.containsOnlyAmbientModules = function (sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (statement.kind !== 225 || statement.name.kind !== 9) { + return false; + } + } + return true; + }; + BuilderFileInfo.prototype.computeHash = function (text) { + return crypto.createHash("md5") + .update(text) + .digest("base64"); + }; + BuilderFileInfo.prototype.getSourceFile = function () { + return this.project.getSourceFile(this.scriptInfo.path); + }; + BuilderFileInfo.prototype.updateShapeSignature = function () { + var sourceFile = this.getSourceFile(); + if (!sourceFile) { + return true; + } + var lastSignature = this.lastCheckedShapeSignature; + if (sourceFile.isDeclarationFile) { + this.lastCheckedShapeSignature = this.computeHash(sourceFile.text); + } + else { + var emitOutput = this.project.getFileEmitOutput(this.scriptInfo, true); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + this.lastCheckedShapeSignature = this.computeHash(emitOutput.outputFiles[0].text); + } + } + return !lastSignature || this.lastCheckedShapeSignature !== lastSignature; + }; + return BuilderFileInfo; + }()); + server.BuilderFileInfo = BuilderFileInfo; + var AbstractBuilder = (function () { + function AbstractBuilder(project, ctor) { + this.project = project; + this.ctor = ctor; + this.fileInfos = ts.createFileMap(); + } + AbstractBuilder.prototype.getFileInfo = function (path) { + return this.fileInfos.get(path); + }; + AbstractBuilder.prototype.getOrCreateFileInfo = function (path) { + var fileInfo = this.getFileInfo(path); + if (!fileInfo) { + var scriptInfo = this.project.getScriptInfo(path); + fileInfo = new this.ctor(scriptInfo, this.project); + this.setFileInfo(path, fileInfo); + } + return fileInfo; + }; + AbstractBuilder.prototype.getFileInfoPaths = function () { + return this.fileInfos.getKeys(); + }; + AbstractBuilder.prototype.setFileInfo = function (path, info) { + this.fileInfos.set(path, info); + }; + AbstractBuilder.prototype.removeFileInfo = function (path) { + this.fileInfos.remove(path); + }; + AbstractBuilder.prototype.forEachFileInfo = function (action) { + this.fileInfos.forEachValue(function (path, value) { return action(value); }); + }; + AbstractBuilder.prototype.emitFile = function (scriptInfo, writeFile) { + var fileInfo = this.getFileInfo(scriptInfo.path); + if (!fileInfo) { + return false; + } + var _a = this.project.getFileEmitOutput(fileInfo.scriptInfo, false), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles; + if (!emitSkipped) { + var projectRootPath = this.project.getProjectRootPath(); + for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) { + var outputFile = outputFiles_1[_i]; + var outputFileAbsoluteFileName = ts.getNormalizedAbsolutePath(outputFile.name, projectRootPath ? projectRootPath : ts.getDirectoryPath(scriptInfo.fileName)); + writeFile(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark); + } + } + return !emitSkipped; + }; + return AbstractBuilder; + }()); + var NonModuleBuilder = (function (_super) { + __extends(NonModuleBuilder, _super); + function NonModuleBuilder(project) { + var _this = _super.call(this, project, BuilderFileInfo) || this; + _this.project = project; + return _this; + } + NonModuleBuilder.prototype.onProjectUpdateGraph = function () { + }; + NonModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { + var info = this.getOrCreateFileInfo(scriptInfo.path); + var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName]; + if (info.updateShapeSignature()) { + var options = this.project.getCompilerOptions(); + if (options && (options.out || options.outFile)) { + return singleFileResult; + } + return this.project.getAllEmittableFiles(); + } + return singleFileResult; + }; + return NonModuleBuilder; + }(AbstractBuilder)); + var ModuleBuilderFileInfo = (function (_super) { + __extends(ModuleBuilderFileInfo, _super); + function ModuleBuilderFileInfo() { + var _this = _super.apply(this, arguments) || this; + _this.references = []; + _this.referencedBy = []; + return _this; + } + ModuleBuilderFileInfo.compareFileInfos = function (lf, rf) { + var l = lf.scriptInfo.fileName; + var r = rf.scriptInfo.fileName; + return (l < r ? -1 : (l > r ? 1 : 0)); + }; + ; + ModuleBuilderFileInfo.addToReferenceList = function (array, fileInfo) { + if (array.length === 0) { + array.push(fileInfo); + return; + } + var insertIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos); + if (insertIndex < 0) { + array.splice(~insertIndex, 0, fileInfo); + } + }; + ModuleBuilderFileInfo.removeFromReferenceList = function (array, fileInfo) { + if (!array || array.length === 0) { + return; + } + if (array[0] === fileInfo) { + array.splice(0, 1); + return; + } + var removeIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos); + if (removeIndex >= 0) { + array.splice(removeIndex, 1); + } + }; + ModuleBuilderFileInfo.prototype.addReferencedBy = function (fileInfo) { + ModuleBuilderFileInfo.addToReferenceList(this.referencedBy, fileInfo); + }; + ModuleBuilderFileInfo.prototype.removeReferencedBy = function (fileInfo) { + ModuleBuilderFileInfo.removeFromReferenceList(this.referencedBy, fileInfo); + }; + ModuleBuilderFileInfo.prototype.removeFileReferences = function () { + for (var _i = 0, _a = this.references; _i < _a.length; _i++) { + var reference = _a[_i]; + reference.removeReferencedBy(this); + } + this.references = []; + }; + return ModuleBuilderFileInfo; + }(BuilderFileInfo)); + var ModuleBuilder = (function (_super) { + __extends(ModuleBuilder, _super); + function ModuleBuilder(project) { + var _this = _super.call(this, project, ModuleBuilderFileInfo) || this; + _this.project = project; + return _this; + } + ModuleBuilder.prototype.getReferencedFileInfos = function (fileInfo) { + var _this = this; + if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { + return []; + } + var referencedFilePaths = this.project.getReferencedFiles(fileInfo.scriptInfo.path); + if (referencedFilePaths.length > 0) { + return ts.map(referencedFilePaths, function (f) { return _this.getOrCreateFileInfo(f); }).sort(ModuleBuilderFileInfo.compareFileInfos); + } + return []; + }; + ModuleBuilder.prototype.onProjectUpdateGraph = function () { + this.ensureProjectDependencyGraphUpToDate(); + }; + ModuleBuilder.prototype.ensureProjectDependencyGraphUpToDate = function () { + var _this = this; + if (!this.projectVersionForDependencyGraph || this.project.getProjectVersion() !== this.projectVersionForDependencyGraph) { + var currentScriptInfos = this.project.getScriptInfos(); + for (var _i = 0, currentScriptInfos_1 = currentScriptInfos; _i < currentScriptInfos_1.length; _i++) { + var scriptInfo = currentScriptInfos_1[_i]; + var fileInfo = this.getOrCreateFileInfo(scriptInfo.path); + this.updateFileReferences(fileInfo); + } + this.forEachFileInfo(function (fileInfo) { + if (!_this.project.containsScriptInfo(fileInfo.scriptInfo)) { + fileInfo.removeFileReferences(); + _this.removeFileInfo(fileInfo.scriptInfo.path); + } + }); + this.projectVersionForDependencyGraph = this.project.getProjectVersion(); + } + }; + ModuleBuilder.prototype.updateFileReferences = function (fileInfo) { + if (fileInfo.scriptVersionForReferences === fileInfo.scriptInfo.getLatestVersion()) { + return; + } + var newReferences = this.getReferencedFileInfos(fileInfo); + var oldReferences = fileInfo.references; + var oldIndex = 0; + var newIndex = 0; + while (oldIndex < oldReferences.length && newIndex < newReferences.length) { + var oldReference = oldReferences[oldIndex]; + var newReference = newReferences[newIndex]; + var compare = ModuleBuilderFileInfo.compareFileInfos(oldReference, newReference); + if (compare < 0) { + oldReference.removeReferencedBy(fileInfo); + oldIndex++; + } + else if (compare > 0) { + newReference.addReferencedBy(fileInfo); + newIndex++; + } + else { + oldIndex++; + newIndex++; + } + } + for (var i = oldIndex; i < oldReferences.length; i++) { + oldReferences[i].removeReferencedBy(fileInfo); + } + for (var i = newIndex; i < newReferences.length; i++) { + newReferences[i].addReferencedBy(fileInfo); + } + fileInfo.references = newReferences; + fileInfo.scriptVersionForReferences = fileInfo.scriptInfo.getLatestVersion(); + }; + ModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { + this.ensureProjectDependencyGraphUpToDate(); + var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName]; + var fileInfo = this.getFileInfo(scriptInfo.path); + if (!fileInfo || !fileInfo.updateShapeSignature()) { + return singleFileResult; + } + if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { + return this.project.getAllEmittableFiles(); + } + var options = this.project.getCompilerOptions(); + if (options && (options.isolatedModules || options.out || options.outFile)) { + return singleFileResult; + } + var queue = fileInfo.referencedBy.slice(0); + var fileNameSet = ts.createMap(); + fileNameSet[scriptInfo.fileName] = scriptInfo; + while (queue.length > 0) { + var processingFileInfo = queue.pop(); + if (processingFileInfo.updateShapeSignature() && processingFileInfo.referencedBy.length > 0) { + for (var _i = 0, _a = processingFileInfo.referencedBy; _i < _a.length; _i++) { + var potentialFileInfo = _a[_i]; + if (!fileNameSet[potentialFileInfo.scriptInfo.fileName]) { + queue.push(potentialFileInfo); + } + } + } + fileNameSet[processingFileInfo.scriptInfo.fileName] = processingFileInfo.scriptInfo; + } + var result = []; + for (var fileName in fileNameSet) { + if (shouldEmitFile(fileNameSet[fileName])) { + result.push(fileName); + } + } + return result; + }; + return ModuleBuilder; + }(AbstractBuilder)); + function createBuilder(project) { + var moduleKind = project.getCompilerOptions().module; + switch (moduleKind) { + case ts.ModuleKind.None: + return new NonModuleBuilder(project); + default: + return new ModuleBuilder(project); } } - server.generateIndentString = generateIndentString; + server.createBuilder = createBuilder; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + (function (ProjectKind) { + ProjectKind[ProjectKind["Inferred"] = 0] = "Inferred"; + ProjectKind[ProjectKind["Configured"] = 1] = "Configured"; + ProjectKind[ProjectKind["External"] = 2] = "External"; + })(server.ProjectKind || (server.ProjectKind = {})); + var ProjectKind = server.ProjectKind; + function remove(items, item) { + var index = items.indexOf(item); + if (index >= 0) { + items.splice(index, 1); + } + } + function countEachFileTypes(infos) { + var result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0 }; + for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { + var info = infos_1[_i]; + switch (info.scriptKind) { + case 1: + result.js += 1; + break; + case 2: + result.jsx += 1; + break; + case 3: + ts.fileExtensionIs(info.fileName, ".d.ts") + ? result.dts += 1 + : result.ts += 1; + break; + case 4: + result.tsx += 1; + break; + } + } + return result; + } + function hasOneOrMoreJsAndNoTsFiles(project) { + var counts = countEachFileTypes(project.getScriptInfos()); + return counts.js > 0 && counts.ts === 0 && counts.tsx === 0; + } + function allRootFilesAreJsOrDts(project) { + var counts = countEachFileTypes(project.getRootScriptInfos()); + return counts.ts === 0 && counts.tsx === 0; + } + server.allRootFilesAreJsOrDts = allRootFilesAreJsOrDts; + function allFilesAreJsOrDts(project) { + var counts = countEachFileTypes(project.getScriptInfos()); + return counts.ts === 0 && counts.tsx === 0; + } + server.allFilesAreJsOrDts = allFilesAreJsOrDts; + var Project = (function () { + function Project(projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) { + this.projectKind = projectKind; + this.projectService = projectService; + this.documentRegistry = documentRegistry; + this.languageServiceEnabled = languageServiceEnabled; + this.compilerOptions = compilerOptions; + this.compileOnSaveEnabled = compileOnSaveEnabled; + this.rootFiles = []; + this.rootFilesMap = ts.createFileMap(); + this.lastReportedVersion = 0; + this.projectStructureVersion = 0; + this.projectStateVersion = 0; + this.typesVersion = 0; + if (!this.compilerOptions) { + this.compilerOptions = ts.getDefaultCompilerOptions(); + this.compilerOptions.allowNonTsExtensions = true; + this.compilerOptions.allowJs = true; + } + else if (hasExplicitListOfFiles) { + this.compilerOptions.allowNonTsExtensions = true; + } + if (languageServiceEnabled) { + this.enableLanguageService(); + } + else { + this.disableLanguageService(); + } + this.builder = server.createBuilder(this); + this.markAsDirty(); + } + Project.prototype.isNonTsProject = function () { + this.updateGraph(); + return allFilesAreJsOrDts(this); + }; + Project.prototype.isJsOnlyProject = function () { + this.updateGraph(); + return hasOneOrMoreJsAndNoTsFiles(this); + }; + Project.prototype.getProjectErrors = function () { + return this.projectErrors; + }; + Project.prototype.getLanguageService = function (ensureSynchronized) { + if (ensureSynchronized === void 0) { ensureSynchronized = true; } + if (ensureSynchronized) { + this.updateGraph(); + } + return this.languageService; + }; + Project.prototype.getCompileOnSaveAffectedFileList = function (scriptInfo) { + if (!this.languageServiceEnabled) { + return []; + } + this.updateGraph(); + return this.builder.getFilesAffectedBy(scriptInfo); + }; + Project.prototype.getProjectVersion = function () { + return this.projectStateVersion.toString(); + }; + Project.prototype.enableLanguageService = function () { + var lsHost = new server.LSHost(this.projectService.host, this, this.projectService.cancellationToken); + lsHost.setCompilationSettings(this.compilerOptions); + this.languageService = ts.createLanguageService(lsHost, this.documentRegistry); + this.lsHost = lsHost; + this.languageServiceEnabled = true; + }; + Project.prototype.disableLanguageService = function () { + this.languageService = server.nullLanguageService; + this.lsHost = server.nullLanguageServiceHost; + this.languageServiceEnabled = false; + }; + Project.prototype.getSourceFile = function (path) { + if (!this.program) { + return undefined; + } + return this.program.getSourceFileByPath(path); + }; + Project.prototype.updateTypes = function () { + this.typesVersion++; + this.markAsDirty(); + this.updateGraph(); + }; + Project.prototype.close = function () { + if (this.program) { + for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { + var f = _a[_i]; + var info = this.projectService.getScriptInfo(f.fileName); + info.detachFromProject(this); + } + } + else { + for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) { + var root = _c[_b]; + root.detachFromProject(this); + } + } + this.rootFiles = undefined; + this.rootFilesMap = undefined; + this.program = undefined; + this.languageService.dispose(); + }; + Project.prototype.getCompilerOptions = function () { + return this.compilerOptions; + }; + Project.prototype.hasRoots = function () { + return this.rootFiles && this.rootFiles.length > 0; + }; + Project.prototype.getRootFiles = function () { + return this.rootFiles && this.rootFiles.map(function (info) { return info.fileName; }); + }; + Project.prototype.getRootFilesLSHost = function () { + var result = []; + if (this.rootFiles) { + for (var _i = 0, _a = this.rootFiles; _i < _a.length; _i++) { + var f = _a[_i]; + result.push(f.fileName); + } + if (this.typingFiles) { + for (var _b = 0, _c = this.typingFiles; _b < _c.length; _b++) { + var f = _c[_b]; + result.push(f); + } + } + } + return result; + }; + Project.prototype.getRootScriptInfos = function () { + return this.rootFiles; + }; + Project.prototype.getScriptInfos = function () { + var _this = this; + return ts.map(this.program.getSourceFiles(), function (sourceFile) { + var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.path); + if (!scriptInfo) { + ts.Debug.assert(false, "scriptInfo for a file '" + sourceFile.fileName + "' is missing."); + } + return scriptInfo; + }); + }; + Project.prototype.getFileEmitOutput = function (info, emitOnlyDtsFiles) { + if (!this.languageServiceEnabled) { + return undefined; + } + return this.getLanguageService().getEmitOutput(info.fileName, emitOnlyDtsFiles); + }; + Project.prototype.getFileNames = function () { + if (!this.program) { + return []; + } + if (!this.languageServiceEnabled) { + var rootFiles = this.getRootFiles(); + if (this.compilerOptions) { + var defaultLibrary = ts.getDefaultLibFilePath(this.compilerOptions); + if (defaultLibrary) { + (rootFiles || (rootFiles = [])).push(server.asNormalizedPath(defaultLibrary)); + } + } + return rootFiles; + } + var sourceFiles = this.program.getSourceFiles(); + return sourceFiles.map(function (sourceFile) { return server.asNormalizedPath(sourceFile.fileName); }); + }; + Project.prototype.getAllEmittableFiles = function () { + if (!this.languageServiceEnabled) { + return []; + } + var defaultLibraryFileName = ts.getDefaultLibFileName(this.compilerOptions); + var infos = this.getScriptInfos(); + var result = []; + for (var _i = 0, infos_2 = infos; _i < infos_2.length; _i++) { + var info = infos_2[_i]; + if (ts.getBaseFileName(info.fileName) !== defaultLibraryFileName && server.shouldEmitFile(info)) { + result.push(info.fileName); + } + } + return result; + }; + Project.prototype.containsScriptInfo = function (info) { + return this.isRoot(info) || (this.program && this.program.getSourceFileByPath(info.path) !== undefined); + }; + Project.prototype.containsFile = function (filename, requireOpen) { + var info = this.projectService.getScriptInfoForNormalizedPath(filename); + if (info && (info.isOpen || !requireOpen)) { + return this.containsScriptInfo(info); + } + }; + Project.prototype.isRoot = function (info) { + return this.rootFilesMap && this.rootFilesMap.contains(info.path); + }; + Project.prototype.addRoot = function (info) { + if (!this.isRoot(info)) { + this.rootFiles.push(info); + this.rootFilesMap.set(info.path, info); + info.attachToProject(this); + this.markAsDirty(); + } + }; + Project.prototype.removeFile = function (info, detachFromProject) { + if (detachFromProject === void 0) { detachFromProject = true; } + this.removeRootFileIfNecessary(info); + this.lsHost.notifyFileRemoved(info); + if (detachFromProject) { + info.detachFromProject(this); + } + this.markAsDirty(); + }; + Project.prototype.markAsDirty = function () { + this.projectStateVersion++; + }; + Project.prototype.updateGraph = function () { + if (!this.languageServiceEnabled) { + return true; + } + var hasChanges = this.updateGraphWorker(); + var cachedTypings = this.projectService.typingsCache.getTypingsForProject(this, hasChanges); + if (this.setTypings(cachedTypings)) { + hasChanges = this.updateGraphWorker() || hasChanges; + } + if (hasChanges) { + this.projectStructureVersion++; + } + return !hasChanges; + }; + Project.prototype.setTypings = function (typings) { + if (ts.arrayIsEqualTo(this.typingFiles, typings)) { + return false; + } + this.typingFiles = typings; + this.markAsDirty(); + return true; + }; + Project.prototype.updateGraphWorker = function () { + var oldProgram = this.program; + this.program = this.languageService.getProgram(); + var hasChanges = false; + if (!oldProgram || (this.program !== oldProgram && !oldProgram.structureIsReused)) { + hasChanges = true; + if (oldProgram) { + for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { + var f = _a[_i]; + if (this.program.getSourceFileByPath(f.path)) { + continue; + } + var scriptInfoToDetach = this.projectService.getScriptInfo(f.fileName); + if (scriptInfoToDetach) { + scriptInfoToDetach.detachFromProject(this); + } + } + } + } + this.builder.onProjectUpdateGraph(); + return hasChanges; + }; + Project.prototype.getScriptInfoLSHost = function (fileName) { + var scriptInfo = this.projectService.getOrCreateScriptInfo(fileName, false); + if (scriptInfo) { + scriptInfo.attachToProject(this); + } + return scriptInfo; + }; + Project.prototype.getScriptInfoForNormalizedPath = function (fileName) { + var scriptInfo = this.projectService.getOrCreateScriptInfoForNormalizedPath(fileName, false); + if (scriptInfo && !scriptInfo.isAttached(this)) { + return server.Errors.ThrowProjectDoesNotContainDocument(fileName, this); + } + return scriptInfo; + }; + Project.prototype.getScriptInfo = function (uncheckedFileName) { + return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + }; + Project.prototype.filesToString = function () { + if (!this.program) { + return ""; + } + var strBuilder = ""; + for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { + var file = _a[_i]; + strBuilder += file.fileName + "\n"; + } + return strBuilder; + }; + Project.prototype.setCompilerOptions = function (compilerOptions) { + if (compilerOptions) { + if (this.projectKind === ProjectKind.Inferred) { + compilerOptions.allowJs = true; + } + compilerOptions.allowNonTsExtensions = true; + this.compilerOptions = compilerOptions; + this.lsHost.setCompilationSettings(compilerOptions); + this.markAsDirty(); + } + }; + Project.prototype.reloadScript = function (filename) { + var script = this.projectService.getScriptInfoForNormalizedPath(filename); + if (script) { + ts.Debug.assert(script.isAttached(this)); + script.reloadFromFile(); + return true; + } + return false; + }; + Project.prototype.getChangesSinceVersion = function (lastKnownVersion) { + this.updateGraph(); + var info = { + projectName: this.getProjectName(), + version: this.projectStructureVersion, + isInferred: this.projectKind === ProjectKind.Inferred, + options: this.getCompilerOptions() + }; + if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) { + if (this.projectStructureVersion == this.lastReportedVersion) { + return { info: info, projectErrors: this.projectErrors }; + } + var lastReportedFileNames = this.lastReportedFileNames; + var currentFiles = ts.arrayToMap(this.getFileNames(), function (x) { return x; }); + var added = []; + var removed = []; + for (var id in currentFiles) { + if (!ts.hasProperty(lastReportedFileNames, id)) { + added.push(id); + } + } + for (var id in lastReportedFileNames) { + if (!ts.hasProperty(currentFiles, id)) { + removed.push(id); + } + } + this.lastReportedFileNames = currentFiles; + this.lastReportedVersion = this.projectStructureVersion; + return { info: info, changes: { added: added, removed: removed }, projectErrors: this.projectErrors }; + } + else { + var projectFileNames = this.getFileNames(); + this.lastReportedFileNames = ts.arrayToMap(projectFileNames, function (x) { return x; }); + this.lastReportedVersion = this.projectStructureVersion; + return { info: info, files: projectFileNames, projectErrors: this.projectErrors }; + } + }; + Project.prototype.getReferencedFiles = function (path) { + var _this = this; + if (!this.languageServiceEnabled) { + return []; + } + var sourceFile = this.getSourceFile(path); + if (!sourceFile) { + return []; + } + var referencedFiles = ts.createMap(); + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = this.program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = symbol.declarations[0].getSourceFile(); + if (declarationSourceFile) { + referencedFiles[declarationSourceFile.path] = true; + } + } + } + } + var currentDirectory = ts.getDirectoryPath(path); + var getCanonicalFileName = ts.createGetCanonicalFileName(this.projectService.host.useCaseSensitiveFileNames); + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, currentDirectory, getCanonicalFileName); + referencedFiles[referencedPath] = true; + } + } + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + for (var typeName in sourceFile.resolvedTypeReferenceDirectiveNames) { + var resolvedTypeReferenceDirective = sourceFile.resolvedTypeReferenceDirectiveNames[typeName]; + if (!resolvedTypeReferenceDirective) { + continue; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var typeFilePath = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + referencedFiles[typeFilePath] = true; + } + } + var allFileNames = ts.map(Object.keys(referencedFiles), function (key) { return key; }); + return ts.filter(allFileNames, function (file) { return _this.projectService.host.fileExists(file); }); + }; + Project.prototype.removeRootFileIfNecessary = function (info) { + if (this.isRoot(info)) { + remove(this.rootFiles, info); + this.rootFilesMap.remove(info.path); + } + }; + return Project; + }()); + server.Project = Project; + var InferredProject = (function (_super) { + __extends(InferredProject, _super); + function InferredProject(projectService, documentRegistry, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) { + var _this = _super.call(this, ProjectKind.Inferred, projectService, documentRegistry, undefined, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) || this; + _this.compileOnSaveEnabled = compileOnSaveEnabled; + _this.directoriesWatchedForTsconfig = []; + _this.inferredProjectName = server.makeInferredProjectName(InferredProject.NextId); + InferredProject.NextId++; + return _this; + } + InferredProject.prototype.getProjectName = function () { + return this.inferredProjectName; + }; + InferredProject.prototype.getProjectRootPath = function () { + if (this.projectService.useSingleInferredProject) { + return undefined; + } + var rootFiles = this.getRootFiles(); + return ts.getDirectoryPath(rootFiles[0]); + }; + InferredProject.prototype.close = function () { + _super.prototype.close.call(this); + for (var _i = 0, _a = this.directoriesWatchedForTsconfig; _i < _a.length; _i++) { + var directory = _a[_i]; + this.projectService.stopWatchingDirectory(directory); + } + }; + InferredProject.prototype.getTypingOptions = function () { + return { + enableAutoDiscovery: allRootFilesAreJsOrDts(this), + include: [], + exclude: [] + }; + }; + return InferredProject; + }(Project)); + InferredProject.NextId = 1; + server.InferredProject = InferredProject; + var ConfiguredProject = (function (_super) { + __extends(ConfiguredProject, _super); + function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, wildcardDirectories, languageServiceEnabled, compileOnSaveEnabled) { + var _this = _super.call(this, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) || this; + _this.configFileName = configFileName; + _this.wildcardDirectories = wildcardDirectories; + _this.compileOnSaveEnabled = compileOnSaveEnabled; + _this.openRefCount = 0; + return _this; + } + ConfiguredProject.prototype.getProjectRootPath = function () { + return ts.getDirectoryPath(this.configFileName); + }; + ConfiguredProject.prototype.setProjectErrors = function (projectErrors) { + this.projectErrors = projectErrors; + }; + ConfiguredProject.prototype.setTypingOptions = function (newTypingOptions) { + this.typingOptions = newTypingOptions; + }; + ConfiguredProject.prototype.getTypingOptions = function () { + return this.typingOptions; + }; + ConfiguredProject.prototype.getProjectName = function () { + return this.configFileName; + }; + ConfiguredProject.prototype.watchConfigFile = function (callback) { + var _this = this; + this.projectFileWatcher = this.projectService.host.watchFile(this.configFileName, function (_) { return callback(_this); }); + }; + ConfiguredProject.prototype.watchTypeRoots = function (callback) { + var _this = this; + var roots = this.getEffectiveTypeRoots(); + var watchers = []; + for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { + var root = roots_1[_i]; + this.projectService.logger.info("Add type root watcher for: " + root); + watchers.push(this.projectService.host.watchDirectory(root, function (path) { return callback(_this, path); }, false)); + } + this.typeRootsWatchers = watchers; + }; + ConfiguredProject.prototype.watchConfigDirectory = function (callback) { + var _this = this; + if (this.directoryWatcher) { + return; + } + var directoryToWatch = ts.getDirectoryPath(this.configFileName); + this.projectService.logger.info("Add recursive watcher for: " + directoryToWatch); + this.directoryWatcher = this.projectService.host.watchDirectory(directoryToWatch, function (path) { return callback(_this, path); }, true); + }; + ConfiguredProject.prototype.watchWildcards = function (callback) { + var _this = this; + if (!this.wildcardDirectories) { + return; + } + var configDirectoryPath = ts.getDirectoryPath(this.configFileName); + this.directoriesWatchedForWildcards = ts.reduceProperties(this.wildcardDirectories, function (watchers, flag, directory) { + if (ts.comparePaths(configDirectoryPath, directory, ".", !_this.projectService.host.useCaseSensitiveFileNames) !== 0) { + var recursive = (flag & 1) !== 0; + _this.projectService.logger.info("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); + watchers[directory] = _this.projectService.host.watchDirectory(directory, function (path) { return callback(_this, path); }, recursive); + } + return watchers; + }, {}); + }; + ConfiguredProject.prototype.stopWatchingDirectory = function () { + if (this.directoryWatcher) { + this.directoryWatcher.close(); + this.directoryWatcher = undefined; + } + }; + ConfiguredProject.prototype.close = function () { + _super.prototype.close.call(this); + if (this.projectFileWatcher) { + this.projectFileWatcher.close(); + } + if (this.typeRootsWatchers) { + for (var _i = 0, _a = this.typeRootsWatchers; _i < _a.length; _i++) { + var watcher = _a[_i]; + watcher.close(); + } + this.typeRootsWatchers = undefined; + } + for (var id in this.directoriesWatchedForWildcards) { + this.directoriesWatchedForWildcards[id].close(); + } + this.directoriesWatchedForWildcards = undefined; + this.stopWatchingDirectory(); + }; + ConfiguredProject.prototype.addOpenRef = function () { + this.openRefCount++; + }; + ConfiguredProject.prototype.deleteOpenRef = function () { + this.openRefCount--; + return this.openRefCount; + }; + ConfiguredProject.prototype.getEffectiveTypeRoots = function () { + return ts.getEffectiveTypeRoots(this.getCompilerOptions(), this.projectService.host) || []; + }; + return ConfiguredProject; + }(Project)); + server.ConfiguredProject = ConfiguredProject; + var ExternalProject = (function (_super) { + __extends(ExternalProject, _super); + function ExternalProject(externalProjectName, projectService, documentRegistry, compilerOptions, languageServiceEnabled, compileOnSaveEnabled, projectFilePath) { + var _this = _super.call(this, ProjectKind.External, projectService, documentRegistry, true, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) || this; + _this.externalProjectName = externalProjectName; + _this.compileOnSaveEnabled = compileOnSaveEnabled; + _this.projectFilePath = projectFilePath; + return _this; + } + ExternalProject.prototype.getProjectRootPath = function () { + if (this.projectFilePath) { + return ts.getDirectoryPath(this.projectFilePath); + } + return ts.getDirectoryPath(ts.normalizeSlashes(this.externalProjectName)); + }; + ExternalProject.prototype.getTypingOptions = function () { + return this.typingOptions; + }; + ExternalProject.prototype.setProjectErrors = function (projectErrors) { + this.projectErrors = projectErrors; + }; + ExternalProject.prototype.setTypingOptions = function (newTypingOptions) { + if (!newTypingOptions) { + newTypingOptions = { + enableAutoDiscovery: allRootFilesAreJsOrDts(this), + include: [], + exclude: [] + }; + } + else { + if (newTypingOptions.enableAutoDiscovery === undefined) { + newTypingOptions.enableAutoDiscovery = allRootFilesAreJsOrDts(this); + } + if (!newTypingOptions.include) { + newTypingOptions.include = []; + } + if (!newTypingOptions.exclude) { + newTypingOptions.exclude = []; + } + } + this.typingOptions = newTypingOptions; + }; + ExternalProject.prototype.getProjectName = function () { + return this.externalProjectName; + }; + return ExternalProject; + }(Project)); + server.ExternalProject = ExternalProject; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; + function combineProjectOutput(projects, action, comparer, areEqual) { + var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer); + return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; + } + server.combineProjectOutput = combineProjectOutput; + var fileNamePropertyReader = { + getFileName: function (x) { return x; }, + getScriptKind: function (_) { return undefined; }, + hasMixedContent: function (_) { return false; } + }; + var externalFilePropertyReader = { + getFileName: function (x) { return x.fileName; }, + getScriptKind: function (x) { return x.scriptKind; }, + hasMixedContent: function (x) { return x.hasMixedContent; } + }; + function findProjectByName(projectName, projects) { + for (var _i = 0, projects_1 = projects; _i < projects_1.length; _i++) { + var proj = projects_1[_i]; + if (proj.getProjectName() === projectName) { + return proj; + } + } + } + function createFileNotFoundDiagnostic(fileName) { + return ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName); + } + function isRootFileInInferredProject(info) { + if (info.containingProjects.length === 0) { + return false; + } + return info.containingProjects[0].projectKind === server.ProjectKind.Inferred && info.containingProjects[0].isRoot(info); + } + var DirectoryWatchers = (function () { + function DirectoryWatchers(projectService) { + this.projectService = projectService; + this.directoryWatchersForTsconfig = ts.createMap(); + this.directoryWatchersRefCount = ts.createMap(); + } + DirectoryWatchers.prototype.stopWatchingDirectory = function (directory) { + this.directoryWatchersRefCount[directory]--; + if (this.directoryWatchersRefCount[directory] === 0) { + this.projectService.logger.info("Close directory watcher for: " + directory); + this.directoryWatchersForTsconfig[directory].close(); + delete this.directoryWatchersForTsconfig[directory]; + } + }; + DirectoryWatchers.prototype.startWatchingContainingDirectoriesForFile = function (fileName, project, callback) { + var currentPath = ts.getDirectoryPath(fileName); + var parentPath = ts.getDirectoryPath(currentPath); + while (currentPath != parentPath) { + if (!this.directoryWatchersForTsconfig[currentPath]) { + this.projectService.logger.info("Add watcher for: " + currentPath); + this.directoryWatchersForTsconfig[currentPath] = this.projectService.host.watchDirectory(currentPath, callback); + this.directoryWatchersRefCount[currentPath] = 1; + } + else { + this.directoryWatchersRefCount[currentPath] += 1; + } + project.directoriesWatchedForTsconfig.push(currentPath); + currentPath = parentPath; + parentPath = ts.getDirectoryPath(parentPath); + } + }; + return DirectoryWatchers; + }()); + var ProjectService = (function () { + function ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, eventHandler) { + if (typingsInstaller === void 0) { typingsInstaller = server.nullTypingsInstaller; } + this.host = host; + this.logger = logger; + this.cancellationToken = cancellationToken; + this.useSingleInferredProject = useSingleInferredProject; + this.typingsInstaller = typingsInstaller; + this.eventHandler = eventHandler; + this.filenameToScriptInfo = ts.createFileMap(); + this.externalProjectToConfiguredProjectMap = ts.createMap(); + this.externalProjects = []; + this.inferredProjects = []; + this.configuredProjects = []; + this.openFiles = []; + this.toCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + this.directoryWatchers = new DirectoryWatchers(this); + this.throttledOperations = new server.ThrottledOperations(host); + this.typingsInstaller.attach(this); + this.typingsCache = new server.TypingsCache(this.typingsInstaller); + this.hostConfiguration = { + formatCodeOptions: server.getDefaultFormatCodeSettings(this.host), + hostInfo: "Unknown host" + }; + this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames, host.getCurrentDirectory()); + } + ProjectService.prototype.getChangedFiles_TestOnly = function () { + return this.changedFiles; + }; + ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () { + this.ensureInferredProjectsUpToDate(); + }; + ProjectService.prototype.updateTypingsForProject = function (response) { + var project = this.findProject(response.projectName); + if (!project) { + return; + } + switch (response.kind) { + case "set": + this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typingOptions, response.typings); + project.updateGraph(); + break; + case "invalidate": + this.typingsCache.invalidateCachedTypingsForProject(project); + break; + } + }; + ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions) { + this.compilerOptionsForInferredProjects = projectCompilerOptions; + this.compileOnSaveForInferredProjects = projectCompilerOptions.compileOnSave; + for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { + var proj = _a[_i]; + proj.setCompilerOptions(projectCompilerOptions); + proj.compileOnSaveEnabled = projectCompilerOptions.compileOnSave; + } + this.updateProjectGraphs(this.inferredProjects); + }; + ProjectService.prototype.stopWatchingDirectory = function (directory) { + this.directoryWatchers.stopWatchingDirectory(directory); + }; + ProjectService.prototype.findProject = function (projectName) { + if (projectName === undefined) { + return undefined; + } + if (server.isInferredProjectName(projectName)) { + this.ensureInferredProjectsUpToDate(); + return findProjectByName(projectName, this.inferredProjects); + } + return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(server.toNormalizedPath(projectName)); + }; + ProjectService.prototype.getDefaultProjectForFile = function (fileName, refreshInferredProjects) { + if (refreshInferredProjects) { + this.ensureInferredProjectsUpToDate(); + } + var scriptInfo = this.getScriptInfoForNormalizedPath(fileName); + return scriptInfo && scriptInfo.getDefaultProject(); + }; + ProjectService.prototype.ensureInferredProjectsUpToDate = function () { + if (this.changedFiles) { + var projectsToUpdate = void 0; + if (this.changedFiles.length === 1) { + projectsToUpdate = this.changedFiles[0].containingProjects; + } + else { + projectsToUpdate = []; + for (var _i = 0, _a = this.changedFiles; _i < _a.length; _i++) { + var f = _a[_i]; + projectsToUpdate = projectsToUpdate.concat(f.containingProjects); + } + } + this.updateProjectGraphs(projectsToUpdate); + this.changedFiles = undefined; + } + }; + ProjectService.prototype.findContainingExternalProject = function (fileName) { + for (var _i = 0, _a = this.externalProjects; _i < _a.length; _i++) { + var proj = _a[_i]; + if (proj.containsFile(fileName)) { + return proj; + } + } + return undefined; + }; + ProjectService.prototype.getFormatCodeOptions = function (file) { + var formatCodeSettings; + if (file) { + var info = this.getScriptInfoForNormalizedPath(file); + if (info) { + formatCodeSettings = info.getFormatCodeSettings(); + } + } + return formatCodeSettings || this.hostConfiguration.formatCodeOptions; + }; + ProjectService.prototype.updateProjectGraphs = function (projects) { + var shouldRefreshInferredProjects = false; + for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) { + var p = projects_2[_i]; + if (!p.updateGraph()) { + shouldRefreshInferredProjects = true; + } + } + if (shouldRefreshInferredProjects) { + this.refreshInferredProjects(); + } + }; + ProjectService.prototype.onSourceFileChanged = function (fileName) { + var info = this.getScriptInfoForNormalizedPath(fileName); + if (!info) { + this.logger.info("Error: got watch notification for unknown file: " + fileName); + return; + } + if (!this.host.fileExists(fileName)) { + this.handleDeletedFile(info); + } + else { + if (info && (!info.isOpen)) { + info.reloadFromFile(); + this.updateProjectGraphs(info.containingProjects); + } + } + }; + ProjectService.prototype.handleDeletedFile = function (info) { + this.logger.info(info.fileName + " deleted"); + info.stopWatcher(); + if (!info.isOpen) { + this.filenameToScriptInfo.remove(info.path); + this.lastDeletedFile = info; + var containingProjects = info.containingProjects.slice(); + info.detachAllProjects(); + this.updateProjectGraphs(containingProjects); + this.lastDeletedFile = undefined; + if (!this.eventHandler) { + return; + } + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var openFile = _a[_i]; + this.eventHandler({ eventName: "context", data: { project: openFile.getDefaultProject(), fileName: openFile.fileName } }); + } + } + this.printProjects(); + }; + ProjectService.prototype.onTypeRootFileChanged = function (project, fileName) { + var _this = this; + this.logger.info("Type root file " + fileName + " changed"); + this.throttledOperations.schedule(project.configFileName + " * type root", 250, function () { + project.updateTypes(); + _this.updateConfiguredProject(project); + _this.refreshInferredProjects(); + }); + }; + ProjectService.prototype.onSourceFileInDirectoryChangedForConfiguredProject = function (project, fileName) { + var _this = this; + if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions())) { + return; + } + this.logger.info("Detected source file changes: " + fileName); + this.throttledOperations.schedule(project.configFileName, 250, function () { return _this.handleChangeInSourceFileForConfiguredProject(project); }); + }; + ProjectService.prototype.handleChangeInSourceFileForConfiguredProject = function (project) { + var _this = this; + var _a = this.convertConfigFileContentToProjectOptions(project.configFileName), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors; + this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors); + var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); })); + var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); })); + if (!ts.arrayIsEqualTo(currentRootFiles.sort(), newRootFiles.sort())) { + this.logger.info("Updating configured project"); + this.updateConfiguredProject(project); + this.refreshInferredProjects(); + } + }; + ProjectService.prototype.onConfigChangedForConfiguredProject = function (project) { + this.logger.info("Config file changed: " + project.configFileName); + this.updateConfiguredProject(project); + this.refreshInferredProjects(); + }; + ProjectService.prototype.onConfigFileAddedForInferredProject = function (fileName) { + if (ts.getBaseFileName(fileName) != "tsconfig.json") { + this.logger.info(fileName + " is not tsconfig.json"); + return; + } + var configFileErrors = this.convertConfigFileContentToProjectOptions(fileName).configFileErrors; + this.reportConfigFileDiagnostics(fileName, configFileErrors); + this.logger.info("Detected newly added tsconfig file: " + fileName); + this.reloadProjects(); + }; + ProjectService.prototype.getCanonicalFileName = function (fileName) { + var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return ts.normalizePath(name); + }; + ProjectService.prototype.removeProject = function (project) { + this.logger.info("remove project: " + project.getRootFiles().toString()); + project.close(); + switch (project.projectKind) { + case server.ProjectKind.External: + server.removeItemFromSet(this.externalProjects, project); + break; + case server.ProjectKind.Configured: + server.removeItemFromSet(this.configuredProjects, project); + break; + case server.ProjectKind.Inferred: + server.removeItemFromSet(this.inferredProjects, project); + break; + } + }; + ProjectService.prototype.assignScriptInfoToInferredProjectIfNecessary = function (info, addToListOfOpenFiles) { + var externalProject = this.findContainingExternalProject(info.fileName); + if (externalProject) { + if (addToListOfOpenFiles) { + this.openFiles.push(info); + } + return; + } + var foundConfiguredProject = false; + for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + if (p.projectKind === server.ProjectKind.Configured) { + foundConfiguredProject = true; + if (addToListOfOpenFiles) { + (p).addOpenRef(); + } + } + } + if (foundConfiguredProject) { + if (addToListOfOpenFiles) { + this.openFiles.push(info); + } + return; + } + if (info.containingProjects.length === 0) { + var inferredProject = this.createInferredProjectWithRootFileIfNecessary(info); + if (!this.useSingleInferredProject) { + for (var _b = 0, _c = this.openFiles; _b < _c.length; _b++) { + var f = _c[_b]; + if (f.containingProjects.length === 0) { + continue; + } + var defaultProject = f.getDefaultProject(); + if (isRootFileInInferredProject(info) && defaultProject !== inferredProject && inferredProject.containsScriptInfo(f)) { + this.removeProject(defaultProject); + f.attachToProject(inferredProject); + } + } + } + } + if (addToListOfOpenFiles) { + this.openFiles.push(info); + } + }; + ProjectService.prototype.closeOpenFile = function (info) { + info.reloadFromFile(); + server.removeItemFromSet(this.openFiles, info); + info.isOpen = false; + var projectsToRemove; + for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + if (p.projectKind === server.ProjectKind.Configured) { + if (p.deleteOpenRef() === 0) { + (projectsToRemove || (projectsToRemove = [])).push(p); + } + } + else if (p.projectKind === server.ProjectKind.Inferred && p.isRoot(info)) { + (projectsToRemove || (projectsToRemove = [])).push(p); + } + } + if (projectsToRemove) { + for (var _b = 0, projectsToRemove_1 = projectsToRemove; _b < projectsToRemove_1.length; _b++) { + var project = projectsToRemove_1[_b]; + this.removeProject(project); + } + var orphanFiles = void 0; + for (var _c = 0, _d = this.openFiles; _c < _d.length; _c++) { + var f = _d[_c]; + if (f.containingProjects.length === 0) { + (orphanFiles || (orphanFiles = [])).push(f); + } + } + if (orphanFiles) { + for (var _e = 0, orphanFiles_1 = orphanFiles; _e < orphanFiles_1.length; _e++) { + var f = orphanFiles_1[_e]; + this.assignScriptInfoToInferredProjectIfNecessary(f, false); + } + } + } + if (info.containingProjects.length === 0) { + this.filenameToScriptInfo.remove(info.path); + } + }; + ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName) { + var searchPath = ts.getDirectoryPath(fileName); + this.logger.info("Search path: " + searchPath); + var configFileName = this.findConfigFile(server.asNormalizedPath(searchPath)); + if (!configFileName) { + this.logger.info("No config files found."); + return {}; + } + this.logger.info("Config file name: " + configFileName); + var project = this.findConfiguredProjectByProjectName(configFileName); + if (!project) { + var _a = this.openConfigFile(configFileName, fileName), success = _a.success, errors = _a.errors; + if (!success) { + return { configFileName: configFileName, configFileErrors: errors }; + } + this.logger.info("Opened configuration file " + configFileName); + if (errors && errors.length > 0) { + return { configFileName: configFileName, configFileErrors: errors }; + } + } + else { + this.updateConfiguredProject(project); + } + return { configFileName: configFileName }; + }; + ProjectService.prototype.findConfigFile = function (searchPath) { + while (true) { + var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json")); + if (this.host.fileExists(tsconfigFileName)) { + return tsconfigFileName; + } + var jsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "jsconfig.json")); + if (this.host.fileExists(jsconfigFileName)) { + return jsconfigFileName; + } + var parentPath = server.asNormalizedPath(ts.getDirectoryPath(searchPath)); + if (parentPath === searchPath) { + break; + } + searchPath = parentPath; + } + return undefined; + }; + ProjectService.prototype.printProjects = function () { + if (!this.logger.hasLevel(server.LogLevel.verbose)) { + return; + } + this.logger.startGroup(); + var counter = 0; + counter = printProjects(this.logger, this.externalProjects, counter); + counter = printProjects(this.logger, this.configuredProjects, counter); + counter = printProjects(this.logger, this.inferredProjects, counter); + this.logger.info("Open files: "); + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var rootFile = _a[_i]; + this.logger.info(rootFile.fileName); + } + this.logger.endGroup(); + function printProjects(logger, projects, counter) { + for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) { + var project = projects_3[_i]; + project.updateGraph(); + logger.info("Project '" + project.getProjectName() + "' (" + server.ProjectKind[project.projectKind] + ") " + counter); + logger.info(project.filesToString()); + logger.info("-----------------------------------------------"); + counter++; + } + return counter; + } + }; + ProjectService.prototype.findConfiguredProjectByProjectName = function (configFileName) { + return findProjectByName(configFileName, this.configuredProjects); + }; + ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) { + return findProjectByName(projectFileName, this.externalProjects); + }; + ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename) { + configFilename = ts.normalizePath(configFilename); + var configFileContent = this.host.readFile(configFilename); + var errors; + var result = ts.parseConfigFileTextToJson(configFilename, configFileContent); + var config = result.config; + if (result.error) { + var _a = ts.sanitizeConfigFile(configFilename, configFileContent), sanitizedConfig = _a.configJsonObject, diagnostics = _a.diagnostics; + config = sanitizedConfig; + errors = diagnostics.length ? diagnostics : [result.error]; + } + var parsedCommandLine = ts.parseJsonConfigFileContent(config, this.host, ts.getDirectoryPath(configFilename), {}, configFilename); + if (parsedCommandLine.errors.length) { + errors = ts.concatenate(errors, parsedCommandLine.errors); + } + ts.Debug.assert(!!parsedCommandLine.fileNames); + if (parsedCommandLine.fileNames.length === 0) { + (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); + return { success: false, configFileErrors: errors }; + } + var projectOptions = { + files: parsedCommandLine.fileNames, + compilerOptions: parsedCommandLine.options, + configHasFilesProperty: config["files"] !== undefined, + wildcardDirectories: ts.createMap(parsedCommandLine.wildcardDirectories), + typingOptions: parsedCommandLine.typingOptions, + compileOnSave: parsedCommandLine.compileOnSave + }; + return { success: true, projectOptions: projectOptions, configFileErrors: errors }; + }; + ProjectService.prototype.exceededTotalSizeLimitForNonTsFiles = function (options, fileNames, propertyReader) { + if (options && options.disableSizeLimit || !this.host.getFileSize) { + return false; + } + var totalNonTsFileSize = 0; + for (var _i = 0, fileNames_3 = fileNames; _i < fileNames_3.length; _i++) { + var f = fileNames_3[_i]; + var fileName = propertyReader.getFileName(f); + if (ts.hasTypeScriptFileExtension(fileName)) { + continue; + } + totalNonTsFileSize += this.host.getFileSize(fileName); + if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) { + return true; + } + } + return false; + }; + ProjectService.prototype.createAndAddExternalProject = function (projectFileName, files, options, typingOptions) { + var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, options, !this.exceededTotalSizeLimitForNonTsFiles(options, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); + this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, undefined, typingOptions, undefined); + this.externalProjects.push(project); + return project; + }; + ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) { + if (!this.eventHandler) { + return; + } + this.eventHandler({ + eventName: "configFileDiag", + data: { configFileName: configFileName, diagnostics: diagnostics || [], triggerFile: triggerFile } + }); + }; + ProjectService.prototype.createAndAddConfiguredProject = function (configFileName, projectOptions, configFileErrors, clientFileName) { + var _this = this; + var sizeLimitExceeded = this.exceededTotalSizeLimitForNonTsFiles(projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); + var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, projectOptions.wildcardDirectories, !sizeLimitExceeded, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave); + this.addFilesToProjectAndUpdateGraph(project, projectOptions.files, fileNamePropertyReader, clientFileName, projectOptions.typingOptions, configFileErrors); + project.watchConfigFile(function (project) { return _this.onConfigChangedForConfiguredProject(project); }); + if (!sizeLimitExceeded) { + this.watchConfigDirectoryForProject(project, projectOptions); + } + project.watchWildcards(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); }); + project.watchTypeRoots(function (project, path) { return _this.onTypeRootFileChanged(project, path); }); + this.configuredProjects.push(project); + return project; + }; + ProjectService.prototype.watchConfigDirectoryForProject = function (project, options) { + var _this = this; + if (!options.configHasFilesProperty) { + project.watchConfigDirectory(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); }); + } + }; + ProjectService.prototype.addFilesToProjectAndUpdateGraph = function (project, files, propertyReader, clientFileName, typingOptions, configFileErrors) { + var errors; + for (var _i = 0, files_4 = files; _i < files_4.length; _i++) { + var f = files_4[_i]; + var rootFilename = propertyReader.getFileName(f); + var scriptKind = propertyReader.getScriptKind(f); + var hasMixedContent = propertyReader.hasMixedContent(f); + if (this.host.fileExists(rootFilename)) { + var info = this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(rootFilename), clientFileName == rootFilename, undefined, scriptKind, hasMixedContent); + project.addRoot(info); + } + else { + (errors || (errors = [])).push(createFileNotFoundDiagnostic(rootFilename)); + } + } + project.setProjectErrors(ts.concatenate(configFileErrors, errors)); + project.setTypingOptions(typingOptions); + project.updateGraph(); + }; + ProjectService.prototype.openConfigFile = function (configFileName, clientFileName) { + var conversionResult = this.convertConfigFileContentToProjectOptions(configFileName); + var projectOptions = conversionResult.success + ? conversionResult.projectOptions + : { files: [], compilerOptions: {} }; + var project = this.createAndAddConfiguredProject(configFileName, projectOptions, conversionResult.configFileErrors, clientFileName); + return { + success: conversionResult.success, + project: project, + errors: project.getProjectErrors() + }; + }; + ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypingOptions, compileOnSave, configFileErrors) { + var oldRootScriptInfos = project.getRootScriptInfos(); + var newRootScriptInfos = []; + var newRootScriptInfoMap = server.createNormalizedPathMap(); + var projectErrors; + var rootFilesChanged = false; + for (var _i = 0, newUncheckedFiles_1 = newUncheckedFiles; _i < newUncheckedFiles_1.length; _i++) { + var f = newUncheckedFiles_1[_i]; + var newRootFile = propertyReader.getFileName(f); + if (!this.host.fileExists(newRootFile)) { + (projectErrors || (projectErrors = [])).push(createFileNotFoundDiagnostic(newRootFile)); + continue; + } + var normalizedPath = server.toNormalizedPath(newRootFile); + var scriptInfo = this.getScriptInfoForNormalizedPath(normalizedPath); + if (!scriptInfo || !project.isRoot(scriptInfo)) { + rootFilesChanged = true; + if (!scriptInfo) { + var scriptKind = propertyReader.getScriptKind(f); + var hasMixedContent = propertyReader.hasMixedContent(f); + scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, false, undefined, scriptKind, hasMixedContent); + } + } + newRootScriptInfos.push(scriptInfo); + newRootScriptInfoMap.set(scriptInfo.fileName, scriptInfo); + } + if (rootFilesChanged || newRootScriptInfos.length !== oldRootScriptInfos.length) { + var toAdd = void 0; + var toRemove = void 0; + for (var _a = 0, oldRootScriptInfos_1 = oldRootScriptInfos; _a < oldRootScriptInfos_1.length; _a++) { + var oldFile = oldRootScriptInfos_1[_a]; + if (!newRootScriptInfoMap.contains(oldFile.fileName)) { + (toRemove || (toRemove = [])).push(oldFile); + } + } + for (var _b = 0, newRootScriptInfos_1 = newRootScriptInfos; _b < newRootScriptInfos_1.length; _b++) { + var newFile = newRootScriptInfos_1[_b]; + if (!project.isRoot(newFile)) { + (toAdd || (toAdd = [])).push(newFile); + } + } + if (toRemove) { + for (var _c = 0, toRemove_1 = toRemove; _c < toRemove_1.length; _c++) { + var f = toRemove_1[_c]; + project.removeFile(f); + } + } + if (toAdd) { + for (var _d = 0, toAdd_1 = toAdd; _d < toAdd_1.length; _d++) { + var f = toAdd_1[_d]; + if (f.isOpen && isRootFileInInferredProject(f)) { + var inferredProject = f.containingProjects[0]; + inferredProject.removeFile(f); + if (!inferredProject.hasRoots()) { + this.removeProject(inferredProject); + } + } + project.addRoot(f); + } + } + } + project.setCompilerOptions(newOptions); + project.setTypingOptions(newTypingOptions); + if (compileOnSave !== undefined) { + project.compileOnSaveEnabled = compileOnSave; + } + project.setProjectErrors(ts.concatenate(configFileErrors, projectErrors)); + project.updateGraph(); + }; + ProjectService.prototype.updateConfiguredProject = function (project) { + if (!this.host.fileExists(project.configFileName)) { + this.logger.info("Config file deleted"); + this.removeProject(project); + return; + } + var _a = this.convertConfigFileContentToProjectOptions(project.configFileName), success = _a.success, projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors; + if (!success) { + this.updateNonInferredProject(project, [], fileNamePropertyReader, {}, {}, false, configFileErrors); + return configFileErrors; + } + if (this.exceededTotalSizeLimitForNonTsFiles(projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader)) { + project.setCompilerOptions(projectOptions.compilerOptions); + if (!project.languageServiceEnabled) { + return; + } + project.disableLanguageService(); + project.stopWatchingDirectory(); + } + else { + if (!project.languageServiceEnabled) { + project.enableLanguageService(); + } + this.watchConfigDirectoryForProject(project, projectOptions); + this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typingOptions, projectOptions.compileOnSave, configFileErrors); + } + }; + ProjectService.prototype.createInferredProjectWithRootFileIfNecessary = function (root) { + var _this = this; + var useExistingProject = this.useSingleInferredProject && this.inferredProjects.length; + var project = useExistingProject + ? this.inferredProjects[0] + : new server.InferredProject(this, this.documentRegistry, true, this.compilerOptionsForInferredProjects, this.compileOnSaveForInferredProjects); + project.addRoot(root); + this.directoryWatchers.startWatchingContainingDirectoriesForFile(root.fileName, project, function (fileName) { return _this.onConfigFileAddedForInferredProject(fileName); }); + project.updateGraph(); + if (!useExistingProject) { + this.inferredProjects.push(project); + } + return project; + }; + ProjectService.prototype.getOrCreateScriptInfo = function (uncheckedFileName, openedByClient, fileContent, scriptKind) { + return this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName), openedByClient, fileContent, scriptKind); + }; + ProjectService.prototype.getScriptInfo = function (uncheckedFileName) { + return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + }; + ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent) { + var _this = this; + var info = this.getScriptInfoForNormalizedPath(fileName); + if (!info) { + var content = void 0; + if (this.host.fileExists(fileName)) { + content = fileContent || (hasMixedContent ? "" : this.host.readFile(fileName)); + } + if (!content) { + if (openedByClient) { + content = ""; + } + } + if (content !== undefined) { + info = new server.ScriptInfo(this.host, fileName, content, scriptKind, openedByClient, hasMixedContent); + this.filenameToScriptInfo.set(info.path, info); + if (!info.isOpen && !hasMixedContent) { + info.setWatcher(this.host.watchFile(fileName, function (_) { return _this.onSourceFileChanged(fileName); })); + } + } + } + if (info) { + if (fileContent !== undefined) { + info.reload(fileContent); + } + if (openedByClient) { + info.isOpen = true; + } + } + return info; + }; + ProjectService.prototype.getScriptInfoForNormalizedPath = function (fileName) { + return this.getScriptInfoForPath(server.normalizedPathToPath(fileName, this.host.getCurrentDirectory(), this.toCanonicalFileName)); + }; + ProjectService.prototype.getScriptInfoForPath = function (fileName) { + return this.filenameToScriptInfo.get(fileName); + }; + ProjectService.prototype.setHostConfiguration = function (args) { + if (args.file) { + var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file)); + if (info) { + info.setFormatOptions(args.formatOptions); + this.logger.info("Host configuration update for file " + args.file); + } + } + else { + if (args.hostInfo !== undefined) { + this.hostConfiguration.hostInfo = args.hostInfo; + this.logger.info("Host information " + args.hostInfo); + } + if (args.formatOptions) { + server.mergeMaps(this.hostConfiguration.formatCodeOptions, args.formatOptions); + this.logger.info("Format host information updated"); + } + } + }; + ProjectService.prototype.closeLog = function () { + this.logger.close(); + }; + ProjectService.prototype.reloadProjects = function () { + this.logger.info("reload projects."); + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var info = _a[_i]; + this.openOrUpdateConfiguredProjectForFile(info.fileName); + } + this.refreshInferredProjects(); + }; + ProjectService.prototype.refreshInferredProjects = function () { + this.logger.info("updating project structure from ..."); + this.printProjects(); + var orphantedFiles = []; + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var info = _a[_i]; + if (info.containingProjects.length === 0) { + orphantedFiles.push(info); + } + else { + if (isRootFileInInferredProject(info) && info.containingProjects.length > 1) { + var inferredProject = info.containingProjects[0]; + ts.Debug.assert(inferredProject.projectKind === server.ProjectKind.Inferred); + inferredProject.removeFile(info); + if (!inferredProject.hasRoots()) { + this.removeProject(inferredProject); + } + } + } + } + for (var _b = 0, orphantedFiles_1 = orphantedFiles; _b < orphantedFiles_1.length; _b++) { + var f = orphantedFiles_1[_b]; + this.assignScriptInfoToInferredProjectIfNecessary(f, false); + } + for (var _c = 0, _d = this.inferredProjects; _c < _d.length; _c++) { + var p = _d[_c]; + p.updateGraph(); + } + this.printProjects(); + }; + ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind) { + return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind); + }; + ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent) { + var _a = this.findContainingExternalProject(fileName) + ? {} + : this.openOrUpdateConfiguredProjectForFile(fileName), _b = _a.configFileName, configFileName = _b === void 0 ? undefined : _b, _c = _a.configFileErrors, configFileErrors = _c === void 0 ? undefined : _c; + var info = this.getOrCreateScriptInfoForNormalizedPath(fileName, true, fileContent, scriptKind, hasMixedContent); + this.assignScriptInfoToInferredProjectIfNecessary(info, true); + this.printProjects(); + return { configFileName: configFileName, configFileErrors: configFileErrors }; + }; + ProjectService.prototype.closeClientFile = function (uncheckedFileName) { + var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + if (info) { + this.closeOpenFile(info); + info.isOpen = false; + } + this.printProjects(); + }; + ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { + var _loop_3 = function (proj) { + var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; }); + result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); + }; + for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { + var proj = currentProjects_1[_i]; + _loop_3(proj); + } + }; + ProjectService.prototype.synchronizeProjectList = function (knownProjects) { + var files = []; + this.collectChanges(knownProjects, this.externalProjects, files); + this.collectChanges(knownProjects, this.configuredProjects, files); + this.collectChanges(knownProjects, this.inferredProjects, files); + return files; + }; + ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) { + var recordChangedFiles = changedFiles && !openFiles && !closedFiles; + if (openFiles) { + for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) { + var file = openFiles_1[_i]; + var scriptInfo = this.getScriptInfo(file.fileName); + ts.Debug.assert(!scriptInfo || !scriptInfo.isOpen); + var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName); + this.openClientFileWithNormalizedPath(normalizedPath, file.content, file.scriptKind, file.hasMixedContent); + } + } + if (changedFiles) { + for (var _a = 0, changedFiles_1 = changedFiles; _a < changedFiles_1.length; _a++) { + var file = changedFiles_1[_a]; + var scriptInfo = this.getScriptInfo(file.fileName); + ts.Debug.assert(!!scriptInfo); + for (var i = file.changes.length - 1; i >= 0; i--) { + var change = file.changes[i]; + scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText); + } + if (recordChangedFiles) { + if (!this.changedFiles) { + this.changedFiles = [scriptInfo]; + } + else if (this.changedFiles.indexOf(scriptInfo) < 0) { + this.changedFiles.push(scriptInfo); + } + } + } + } + if (closedFiles) { + for (var _b = 0, closedFiles_1 = closedFiles; _b < closedFiles_1.length; _b++) { + var file = closedFiles_1[_b]; + this.closeClientFile(file); + } + } + if (openFiles || closedFiles) { + this.refreshInferredProjects(); + } + }; + ProjectService.prototype.closeConfiguredProject = function (configFile) { + var configuredProject = this.findConfiguredProjectByProjectName(configFile); + if (configuredProject && configuredProject.deleteOpenRef() === 0) { + this.removeProject(configuredProject); + } + }; + ProjectService.prototype.closeExternalProject = function (uncheckedFileName, suppressRefresh) { + if (suppressRefresh === void 0) { suppressRefresh = false; } + var fileName = server.toNormalizedPath(uncheckedFileName); + var configFiles = this.externalProjectToConfiguredProjectMap[fileName]; + if (configFiles) { + var shouldRefreshInferredProjects = false; + for (var _i = 0, configFiles_1 = configFiles; _i < configFiles_1.length; _i++) { + var configFile = configFiles_1[_i]; + if (this.closeConfiguredProject(configFile)) { + shouldRefreshInferredProjects = true; + } + } + delete this.externalProjectToConfiguredProjectMap[fileName]; + if (shouldRefreshInferredProjects && !suppressRefresh) { + this.refreshInferredProjects(); + } + } + else { + var externalProject = this.findExternalProjectByProjectName(uncheckedFileName); + if (externalProject) { + this.removeProject(externalProject); + if (!suppressRefresh) { + this.refreshInferredProjects(); + } + } + } + }; + ProjectService.prototype.openExternalProject = function (proj) { + var tsConfigFiles; + var rootFiles = []; + for (var _i = 0, _a = proj.rootFiles; _i < _a.length; _i++) { + var file = _a[_i]; + var normalized = server.toNormalizedPath(file.fileName); + if (ts.getBaseFileName(normalized) === "tsconfig.json") { + (tsConfigFiles || (tsConfigFiles = [])).push(normalized); + } + else { + rootFiles.push(file); + } + } + if (tsConfigFiles) { + tsConfigFiles.sort(); + } + var externalProject = this.findExternalProjectByProjectName(proj.projectFileName); + var exisingConfigFiles; + if (externalProject) { + if (!tsConfigFiles) { + this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, proj.options, proj.typingOptions, proj.options.compileOnSave, undefined); + return; + } + this.closeExternalProject(proj.projectFileName, true); + } + else if (this.externalProjectToConfiguredProjectMap[proj.projectFileName]) { + if (!tsConfigFiles) { + this.closeExternalProject(proj.projectFileName, true); + } + else { + var oldConfigFiles = this.externalProjectToConfiguredProjectMap[proj.projectFileName]; + var iNew = 0; + var iOld = 0; + while (iNew < tsConfigFiles.length && iOld < oldConfigFiles.length) { + var newConfig = tsConfigFiles[iNew]; + var oldConfig = oldConfigFiles[iOld]; + if (oldConfig < newConfig) { + this.closeConfiguredProject(oldConfig); + iOld++; + } + else if (oldConfig > newConfig) { + iNew++; + } + else { + (exisingConfigFiles || (exisingConfigFiles = [])).push(oldConfig); + iOld++; + iNew++; + } + } + for (var i = iOld; i < oldConfigFiles.length; i++) { + this.closeConfiguredProject(oldConfigFiles[i]); + } + } + } + if (tsConfigFiles) { + this.externalProjectToConfiguredProjectMap[proj.projectFileName] = tsConfigFiles; + for (var _b = 0, tsConfigFiles_1 = tsConfigFiles; _b < tsConfigFiles_1.length; _b++) { + var tsconfigFile = tsConfigFiles_1[_b]; + var project = this.findConfiguredProjectByProjectName(tsconfigFile); + if (!project) { + var result = this.openConfigFile(tsconfigFile); + project = result.success && result.project; + } + if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { + project.addOpenRef(); + } + } + } + else { + delete this.externalProjectToConfiguredProjectMap[proj.projectFileName]; + this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typingOptions); + } + this.refreshInferredProjects(); + }; + return ProjectService; + }()); + server.ProjectService = ProjectService; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + function hrTimeToMilliseconds(time) { + var seconds = time[0]; + var nanoseconds = time[1]; + return ((1e9 * seconds) + nanoseconds) / 1000000.0; + } + function shouldSkipSematicCheck(project) { + if (project.getCompilerOptions().skipLibCheck !== undefined) { + return false; + } + if ((project.projectKind === server.ProjectKind.Inferred || project.projectKind === server.ProjectKind.External) && project.isJsOnlyProject()) { + return true; + } + return false; + } function compareNumber(a, b) { - if (a < b) { - return -1; - } - else if (a === b) { - return 0; - } - else - return 1; + return a - b; } function compareFileStart(a, b) { if (a.file < b.file) { @@ -60288,10 +63334,12 @@ var ts; } } function formatDiag(fileName, project, diag) { + var scriptInfo = project.getScriptInfoForNormalizedPath(fileName); return { - start: project.compilerService.host.positionToLineOffset(fileName, diag.start), - end: project.compilerService.host.positionToLineOffset(fileName, diag.start + diag.length), - text: ts.flattenDiagnosticMessageText(diag.messageText, "\n") + start: scriptInfo.positionToLineOffset(diag.start), + end: scriptInfo.positionToLineOffset(diag.start + diag.length), + text: ts.flattenDiagnosticMessageText(diag.messageText, "\n"), + code: diag.code }; } function formatConfigFileDiag(diag) { @@ -60302,8 +63350,9 @@ var ts; }; } function allEditsBeforePos(edits, pos) { - for (var i = 0, len = edits.length; i < len; i++) { - if (ts.textSpanEnd(edits[i].span) >= pos) { + for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { + var edit = edits_1[_i]; + if (ts.textSpanEnd(edit.span) >= pos) { return false; } } @@ -60312,73 +63361,166 @@ var ts; var CommandNames; (function (CommandNames) { CommandNames.Brace = "brace"; + CommandNames.BraceFull = "brace-full"; + CommandNames.BraceCompletion = "braceCompletion"; CommandNames.Change = "change"; CommandNames.Close = "close"; CommandNames.Completions = "completions"; + CommandNames.CompletionsFull = "completions-full"; CommandNames.CompletionDetails = "completionEntryDetails"; + CommandNames.CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; + CommandNames.CompileOnSaveEmitFile = "compileOnSaveEmitFile"; CommandNames.Configure = "configure"; CommandNames.Definition = "definition"; + CommandNames.DefinitionFull = "definition-full"; CommandNames.Exit = "exit"; CommandNames.Format = "format"; CommandNames.Formatonkey = "formatonkey"; + CommandNames.FormatFull = "format-full"; + CommandNames.FormatonkeyFull = "formatonkey-full"; + CommandNames.FormatRangeFull = "formatRange-full"; CommandNames.Geterr = "geterr"; CommandNames.GeterrForProject = "geterrForProject"; CommandNames.Implementation = "implementation"; + CommandNames.ImplementationFull = "implementation-full"; CommandNames.SemanticDiagnosticsSync = "semanticDiagnosticsSync"; CommandNames.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; CommandNames.NavBar = "navbar"; + CommandNames.NavBarFull = "navbar-full"; + CommandNames.NavTree = "navtree"; + CommandNames.NavTreeFull = "navtree-full"; CommandNames.Navto = "navto"; + CommandNames.NavtoFull = "navto-full"; CommandNames.Occurrences = "occurrences"; CommandNames.DocumentHighlights = "documentHighlights"; + CommandNames.DocumentHighlightsFull = "documentHighlights-full"; CommandNames.Open = "open"; CommandNames.Quickinfo = "quickinfo"; + CommandNames.QuickinfoFull = "quickinfo-full"; CommandNames.References = "references"; + CommandNames.ReferencesFull = "references-full"; CommandNames.Reload = "reload"; CommandNames.Rename = "rename"; + CommandNames.RenameInfoFull = "rename-full"; + CommandNames.RenameLocationsFull = "renameLocations-full"; CommandNames.Saveto = "saveto"; CommandNames.SignatureHelp = "signatureHelp"; + CommandNames.SignatureHelpFull = "signatureHelp-full"; CommandNames.TypeDefinition = "typeDefinition"; CommandNames.ProjectInfo = "projectInfo"; CommandNames.ReloadProjects = "reloadProjects"; CommandNames.Unknown = "unknown"; + CommandNames.OpenExternalProject = "openExternalProject"; + CommandNames.OpenExternalProjects = "openExternalProjects"; + CommandNames.CloseExternalProject = "closeExternalProject"; + CommandNames.SynchronizeProjectList = "synchronizeProjectList"; + CommandNames.ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; + CommandNames.EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; + CommandNames.Cleanup = "cleanup"; + CommandNames.OutliningSpans = "outliningSpans"; + CommandNames.TodoComments = "todoComments"; + CommandNames.Indentation = "indentation"; + CommandNames.DocCommentTemplate = "docCommentTemplate"; + CommandNames.CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; + CommandNames.NameOrDottedNameSpan = "nameOrDottedNameSpan"; + CommandNames.BreakpointStatement = "breakpointStatement"; + CommandNames.CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; + CommandNames.GetCodeFixes = "getCodeFixes"; + CommandNames.GetCodeFixesFull = "getCodeFixes-full"; + CommandNames.GetSupportedCodeFixes = "getSupportedCodeFixes"; })(CommandNames = server.CommandNames || (server.CommandNames = {})); - var Errors; - (function (Errors) { - Errors.NoProject = new Error("No Project."); - Errors.ProjectLanguageServiceDisabled = new Error("The project's language service is disabled."); - })(Errors || (Errors = {})); + function formatMessage(msg, logger, byteLength, newLine) { + var verboseLogging = logger.hasLevel(server.LogLevel.verbose); + var json = JSON.stringify(msg); + if (verboseLogging) { + logger.info(msg.type + ": " + json); + } + var len = byteLength(json, "utf8"); + return "Content-Length: " + (1 + len) + "\r\n\r\n" + json + newLine; + } + server.formatMessage = formatMessage; var Session = (function () { - function Session(host, byteLength, hrtime, logger) { + function Session(host, cancellationToken, useSingleInferredProject, typingsInstaller, byteLength, hrtime, logger, canUseEvents, eventHandler) { var _this = this; this.host = host; + this.typingsInstaller = typingsInstaller; this.byteLength = byteLength; this.hrtime = hrtime; this.logger = logger; + this.canUseEvents = canUseEvents; this.changeSeq = 0; this.handlers = ts.createMap((_a = {}, + _a[CommandNames.OpenExternalProject] = function (request) { + _this.projectService.openExternalProject(request.arguments); + return _this.requiredResponse(true); + }, + _a[CommandNames.OpenExternalProjects] = function (request) { + for (var _i = 0, _a = request.arguments.projects; _i < _a.length; _i++) { + var proj = _a[_i]; + _this.projectService.openExternalProject(proj); + } + return _this.requiredResponse(true); + }, + _a[CommandNames.CloseExternalProject] = function (request) { + _this.projectService.closeExternalProject(request.arguments.projectFileName); + return _this.requiredResponse(true); + }, + _a[CommandNames.SynchronizeProjectList] = function (request) { + var result = _this.projectService.synchronizeProjectList(request.arguments.knownProjects); + if (!result.some(function (p) { return p.projectErrors && p.projectErrors.length !== 0; })) { + return _this.requiredResponse(result); + } + var converted = ts.map(result, function (p) { + if (!p.projectErrors || p.projectErrors.length === 0) { + return p; + } + return { + info: p.info, + changes: p.changes, + files: p.files, + projectErrors: _this.convertToDiagnosticsWithLinePosition(p.projectErrors, undefined) + }; + }); + return _this.requiredResponse(converted); + }, + _a[CommandNames.ApplyChangedToOpenFiles] = function (request) { + _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles); + _this.changeSeq++; + return _this.requiredResponse(true); + }, _a[CommandNames.Exit] = function () { _this.exit(); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Definition] = function (request) { - var defArgs = request.arguments; - return { response: _this.getDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getDefinition(request.arguments, true)); + }, + _a[CommandNames.DefinitionFull] = function (request) { + return _this.requiredResponse(_this.getDefinition(request.arguments, false)); }, _a[CommandNames.TypeDefinition] = function (request) { - var defArgs = request.arguments; - return { response: _this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getTypeDefinition(request.arguments)); }, _a[CommandNames.Implementation] = function (request) { - var implArgs = request.arguments; - return { response: _this.getImplementation(implArgs.line, implArgs.offset, implArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getImplementation(request.arguments, true)); + }, + _a[CommandNames.ImplementationFull] = function (request) { + return _this.requiredResponse(_this.getImplementation(request.arguments, false)); }, _a[CommandNames.References] = function (request) { - var defArgs = request.arguments; - return { response: _this.getReferences(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getReferences(request.arguments, true)); + }, + _a[CommandNames.ReferencesFull] = function (request) { + return _this.requiredResponse(_this.getReferences(request.arguments, false)); }, _a[CommandNames.Rename] = function (request) { - var renameArgs = request.arguments; - return { response: _this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings), responseRequired: true }; + return _this.requiredResponse(_this.getRenameLocations(request.arguments, true)); + }, + _a[CommandNames.RenameLocationsFull] = function (request) { + return _this.requiredResponse(_this.getRenameLocations(request.arguments, false)); + }, + _a[CommandNames.RenameInfoFull] = function (request) { + return _this.requiredResponse(_this.getRenameInfo(request.arguments)); }, _a[CommandNames.Open] = function (request) { var openArgs = request.arguments; @@ -60397,34 +63539,81 @@ var ts; scriptKind = 2; break; } - _this.openClientFile(openArgs.file, openArgs.fileContent, scriptKind); - return { responseRequired: false }; + _this.openClientFile(server.toNormalizedPath(openArgs.file), openArgs.fileContent, scriptKind); + return _this.notRequired(); }, _a[CommandNames.Quickinfo] = function (request) { - var quickinfoArgs = request.arguments; - return { response: _this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, true)); + }, + _a[CommandNames.QuickinfoFull] = function (request) { + return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, false)); + }, + _a[CommandNames.OutliningSpans] = function (request) { + return _this.requiredResponse(_this.getOutliningSpans(request.arguments)); + }, + _a[CommandNames.TodoComments] = function (request) { + return _this.requiredResponse(_this.getTodoComments(request.arguments)); + }, + _a[CommandNames.Indentation] = function (request) { + return _this.requiredResponse(_this.getIndentation(request.arguments)); + }, + _a[CommandNames.NameOrDottedNameSpan] = function (request) { + return _this.requiredResponse(_this.getNameOrDottedNameSpan(request.arguments)); + }, + _a[CommandNames.BreakpointStatement] = function (request) { + return _this.requiredResponse(_this.getBreakpointStatement(request.arguments)); + }, + _a[CommandNames.BraceCompletion] = function (request) { + return _this.requiredResponse(_this.isValidBraceCompletion(request.arguments)); + }, + _a[CommandNames.DocCommentTemplate] = function (request) { + return _this.requiredResponse(_this.getDocCommentTemplate(request.arguments)); }, _a[CommandNames.Format] = function (request) { - var formatArgs = request.arguments; - return { response: _this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getFormattingEditsForRange(request.arguments)); }, _a[CommandNames.Formatonkey] = function (request) { - var formatOnKeyArgs = request.arguments; - return { response: _this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getFormattingEditsAfterKeystroke(request.arguments)); + }, + _a[CommandNames.FormatFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsForDocumentFull(request.arguments)); + }, + _a[CommandNames.FormatonkeyFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsAfterKeystrokeFull(request.arguments)); + }, + _a[CommandNames.FormatRangeFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsForRangeFull(request.arguments)); }, _a[CommandNames.Completions] = function (request) { - var completionsArgs = request.arguments; - return { response: _this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getCompletions(request.arguments, true)); + }, + _a[CommandNames.CompletionsFull] = function (request) { + return _this.requiredResponse(_this.getCompletions(request.arguments, false)); }, _a[CommandNames.CompletionDetails] = function (request) { - var completionDetailsArgs = request.arguments; - return { - response: _this.getCompletionEntryDetails(completionDetailsArgs.line, completionDetailsArgs.offset, completionDetailsArgs.entryNames, completionDetailsArgs.file), responseRequired: true - }; + return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments)); + }, + _a[CommandNames.CompileOnSaveAffectedFileList] = function (request) { + return _this.requiredResponse(_this.getCompileOnSaveAffectedFileList(request.arguments)); + }, + _a[CommandNames.CompileOnSaveEmitFile] = function (request) { + return _this.requiredResponse(_this.emitFile(request.arguments)); }, _a[CommandNames.SignatureHelp] = function (request) { - var signatureHelpArgs = request.arguments; - return { response: _this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, true)); + }, + _a[CommandNames.SignatureHelpFull] = function (request) { + return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, false)); + }, + _a[CommandNames.CompilerOptionsDiagnosticsFull] = function (request) { + return _this.requiredResponse(_this.getCompilerOptionsDiagnostics(request.arguments)); + }, + _a[CommandNames.EncodedSemanticClassificationsFull] = function (request) { + return _this.requiredResponse(_this.getEncodedSemanticClassifications(request.arguments)); + }, + _a[CommandNames.Cleanup] = function (request) { + _this.cleanup(); + return _this.requiredResponse(true); }, _a[CommandNames.SemanticDiagnosticsSync] = function (request) { return _this.requiredResponse(_this.getSemanticDiagnosticsSync(request.arguments)); @@ -60441,72 +63630,94 @@ var ts; return { response: _this.getDiagnosticsForProject(delay, file), responseRequired: false }; }, _a[CommandNames.Change] = function (request) { - var changeArgs = request.arguments; - _this.change(changeArgs.line, changeArgs.offset, changeArgs.endLine, changeArgs.endOffset, changeArgs.insertString, changeArgs.file); - return { responseRequired: false }; + _this.change(request.arguments); + return _this.notRequired(); }, _a[CommandNames.Configure] = function (request) { - var configureArgs = request.arguments; - _this.projectService.setHostConfiguration(configureArgs); + _this.projectService.setHostConfiguration(request.arguments); _this.output(undefined, CommandNames.Configure, request.seq); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Reload] = function (request) { - var reloadArgs = request.arguments; - _this.reload(reloadArgs.file, reloadArgs.tmpfile, request.seq); - return { response: { reloadFinished: true }, responseRequired: true }; + _this.reload(request.arguments, request.seq); + return _this.requiredResponse({ reloadFinished: true }); }, _a[CommandNames.Saveto] = function (request) { var savetoArgs = request.arguments; _this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Close] = function (request) { var closeArgs = request.arguments; _this.closeClientFile(closeArgs.file); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Navto] = function (request) { - var navtoArgs = request.arguments; - return { response: _this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount, navtoArgs.currentFileOnly), responseRequired: true }; + return _this.requiredResponse(_this.getNavigateToItems(request.arguments, true)); + }, + _a[CommandNames.NavtoFull] = function (request) { + return _this.requiredResponse(_this.getNavigateToItems(request.arguments, false)); }, _a[CommandNames.Brace] = function (request) { - var braceArguments = request.arguments; - return { response: _this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file), responseRequired: true }; + return _this.requiredResponse(_this.getBraceMatching(request.arguments, true)); + }, + _a[CommandNames.BraceFull] = function (request) { + return _this.requiredResponse(_this.getBraceMatching(request.arguments, false)); }, _a[CommandNames.NavBar] = function (request) { - var navBarArgs = request.arguments; - return { response: _this.getNavigationBarItems(navBarArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, true)); + }, + _a[CommandNames.NavBarFull] = function (request) { + return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, false)); + }, + _a[CommandNames.NavTree] = function (request) { + return _this.requiredResponse(_this.getNavigationTree(request.arguments, true)); + }, + _a[CommandNames.NavTreeFull] = function (request) { + return _this.requiredResponse(_this.getNavigationTree(request.arguments, false)); }, _a[CommandNames.Occurrences] = function (request) { - var _a = request.arguments, line = _a.line, offset = _a.offset, fileName = _a.file; - return { response: _this.getOccurrences(line, offset, fileName), responseRequired: true }; + return _this.requiredResponse(_this.getOccurrences(request.arguments)); }, _a[CommandNames.DocumentHighlights] = function (request) { - var _a = request.arguments, line = _a.line, offset = _a.offset, fileName = _a.file, filesToSearch = _a.filesToSearch; - return { response: _this.getDocumentHighlights(line, offset, fileName, filesToSearch), responseRequired: true }; + return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, true)); + }, + _a[CommandNames.DocumentHighlightsFull] = function (request) { + return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, false)); + }, + _a[CommandNames.CompilerOptionsForInferredProjects] = function (request) { + return _this.requiredResponse(_this.setCompilerOptionsForInferredProjects(request.arguments)); }, _a[CommandNames.ProjectInfo] = function (request) { - var _a = request.arguments, file = _a.file, needFileNameList = _a.needFileNameList; - return { response: _this.getProjectInfo(file, needFileNameList), responseRequired: true }; + return _this.requiredResponse(_this.getProjectInfo(request.arguments)); }, _a[CommandNames.ReloadProjects] = function (request) { - _this.reloadProjects(); - return { responseRequired: false }; + _this.projectService.reloadProjects(); + return _this.notRequired(); + }, + _a[CommandNames.GetCodeFixes] = function (request) { + return _this.requiredResponse(_this.getCodeFixes(request.arguments, true)); + }, + _a[CommandNames.GetCodeFixesFull] = function (request) { + return _this.requiredResponse(_this.getCodeFixes(request.arguments, false)); + }, + _a[CommandNames.GetSupportedCodeFixes] = function (request) { + return _this.requiredResponse(_this.getSupportedCodeFixes()); }, _a)); - this.projectService = - new server.ProjectService(host, logger, function (event) { - _this.handleEvent(event); - }); + this.eventHander = canUseEvents + ? eventHandler || (function (event) { return _this.defaultEventHandler(event); }) + : undefined; + this.projectService = new server.ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, this.eventHander); + this.gcTimer = new server.GcTimer(host, 7000, logger); var _a; } - Session.prototype.handleEvent = function (event) { + Session.prototype.defaultEventHandler = function (event) { var _this = this; switch (event.eventName) { case "context": var _a = event.data, project = _a.project, fileName = _a.fileName; - this.projectService.log("got context event, updating diagnostics for" + fileName, "Info"); + this.projectService.logger.info("got context event, updating diagnostics for " + fileName); this.updateErrorCheck([{ fileName: fileName, project: project }], this.changeSeq, function (n) { return n === _this.changeSeq; }, 100); break; case "configFileDiag": @@ -60515,26 +63726,23 @@ var ts; } }; Session.prototype.logError = function (err, cmd) { - var typedErr = err; var msg = "Exception on executing command " + cmd; - if (typedErr.message) { - msg += ":\n" + typedErr.message; - if (typedErr.stack) { - msg += "\n" + typedErr.stack; + if (err.message) { + msg += ":\n" + err.message; + if (err.stack) { + msg += "\n" + err.stack; } } - this.projectService.log(msg); - }; - Session.prototype.sendLineToClient = function (line) { - this.host.write(line + this.host.newLine); + this.logger.msg(msg, server.Msg.Err); }; Session.prototype.send = function (msg) { - var json = JSON.stringify(msg); - if (this.logger.isVerbose()) { - this.logger.info(msg.type + ": " + json); + if (msg.type === "event" && !this.canUseEvents) { + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Session does not support events: ignored event: " + JSON.stringify(msg)); + } + return; } - this.sendLineToClient("Content-Length: " + (1 + this.byteLength(json, "utf8")) + - "\r\n\r\n" + json); + this.host.write(formatMessage(msg, this.logger, this.byteLength, this.host.newLine)); }; Session.prototype.configFileDiagnosticEvent = function (triggerFile, configFile, diagnostics) { var bakedDiags = ts.map(diagnostics, formatConfigFileDiag); @@ -60559,7 +63767,7 @@ var ts; }; this.send(ev); }; - Session.prototype.response = function (info, cmdName, reqSeq, errorMsg) { + Session.prototype.output = function (info, cmdName, reqSeq, errorMsg) { if (reqSeq === void 0) { reqSeq = 0; } var res = { seq: 0, @@ -60576,17 +63784,14 @@ var ts; } this.send(res); }; - Session.prototype.output = function (body, commandName, requestSequence, errorMessage) { - if (requestSequence === void 0) { requestSequence = 0; } - this.response(body, commandName, requestSequence, errorMessage); - }; Session.prototype.semanticCheck = function (file, project) { try { - var diags = project.compilerService.languageService.getSemanticDiagnostics(file); - if (diags) { - var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); - this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); + var diags = []; + if (!shouldSkipSematicCheck(project)) { + diags = project.getLanguageService().getSemanticDiagnostics(file); } + var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); + this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); } catch (err) { this.logError(err, "semantic check"); @@ -60594,7 +63799,7 @@ var ts; }; Session.prototype.syntacticCheck = function (file, project) { try { - var diags = project.compilerService.languageService.getSyntacticDiagnostics(file); + var diags = project.getLanguageService().getSyntacticDiagnostics(file); if (diags) { var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); this.event({ file: file, diagnostics: bakedDiags }, "syntaxDiag"); @@ -60604,15 +63809,12 @@ var ts; this.logError(err, "syntactic check"); } }; - Session.prototype.reloadProjects = function () { - this.projectService.reloadProjects(); - }; Session.prototype.updateProjectStructure = function (seq, matchSeq, ms) { var _this = this; if (ms === void 0) { ms = 1500; } - setTimeout(function () { + this.host.setTimeout(function () { if (matchSeq(seq)) { - _this.projectService.updateProjectStructure(); + _this.projectService.refreshInferredProjects(); } }, ms); }; @@ -60625,10 +63827,10 @@ var ts; followMs = ms; } if (this.errorTimer) { - clearTimeout(this.errorTimer); + this.host.clearTimeout(this.errorTimer); } if (this.immediateId) { - clearImmediate(this.immediateId); + this.host.clearImmediate(this.immediateId); this.immediateId = undefined; } var index = 0; @@ -60636,13 +63838,13 @@ var ts; if (matchSeq(seq)) { var checkSpec_1 = checkList[index]; index++; - if (checkSpec_1.project.getSourceFileFromName(checkSpec_1.fileName, requireOpen)) { + if (checkSpec_1.project.containsFile(checkSpec_1.fileName, requireOpen)) { _this.syntacticCheck(checkSpec_1.fileName, checkSpec_1.project); - _this.immediateId = setImmediate(function () { + _this.immediateId = _this.host.setImmediate(function () { _this.semanticCheck(checkSpec_1.fileName, checkSpec_1.project); _this.immediateId = undefined; if (checkList.length > index) { - _this.errorTimer = setTimeout(checkOne, followMs); + _this.errorTimer = _this.host.setTimeout(checkOne, followMs); } else { _this.errorTimer = undefined; @@ -60652,78 +63854,133 @@ var ts; } }; if ((checkList.length > index) && (matchSeq(seq))) { - this.errorTimer = setTimeout(checkOne, ms); + this.errorTimer = this.host.setTimeout(checkOne, ms); } }; - Session.prototype.getDefinition = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + Session.prototype.cleanProjects = function (caption, projects) { + if (!projects) { + return; } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var definitions = compilerService.languageService.getDefinitionAtPosition(file, position); + this.logger.info("cleaning " + caption); + for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { + var p = projects_4[_i]; + p.getLanguageService(false).cleanupSemanticCache(); + } + }; + Session.prototype.cleanup = function () { + this.cleanProjects("inferred projects", this.projectService.inferredProjects); + this.cleanProjects("configured projects", this.projectService.configuredProjects); + this.cleanProjects("external projects", this.projectService.externalProjects); + if (this.host.gc) { + this.logger.info("host.gc()"); + this.host.gc(); + } + }; + Session.prototype.getEncodedSemanticClassifications = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getEncodedSemanticClassifications(file, args); + }; + Session.prototype.getProject = function (projectFileName) { + return projectFileName && this.projectService.findProject(projectFileName); + }; + Session.prototype.getCompilerOptionsDiagnostics = function (args) { + var project = this.getProject(args.projectFileName); + return this.convertToDiagnosticsWithLinePosition(project.getLanguageService().getCompilerOptionsDiagnostics(), undefined); + }; + Session.prototype.convertToDiagnosticsWithLinePosition = function (diagnostics, scriptInfo) { + var _this = this; + return diagnostics.map(function (d) { return ({ + message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine), + start: d.start, + length: d.length, + category: ts.DiagnosticCategory[d.category].toLowerCase(), + code: d.code, + startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start), + endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start + d.length) + }); }); + }; + Session.prototype.getDiagnosticsWorker = function (args, selector, includeLinePosition) { + var _a = this.getFileAndProject(args), project = _a.project, file = _a.file; + if (shouldSkipSematicCheck(project)) { + return []; + } + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var diagnostics = selector(project, file); + return includeLinePosition + ? this.convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo) + : diagnostics.map(function (d) { return formatDiag(file, project, d); }); + }; + Session.prototype.getDefinition = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var definitions = project.getLanguageService().getDefinitionAtPosition(file, position); if (!definitions) { return undefined; } - return definitions.map(function (def) { return ({ - file: def.fileName, - start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), - end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) - }); }); - }; - Session.prototype.getTypeDefinition = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + if (simplifiedResult) { + return definitions.map(function (def) { + var defScriptInfo = project.getScriptInfo(def.fileName); + return { + file: def.fileName, + start: defScriptInfo.positionToLineOffset(def.textSpan.start), + end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan)) + }; + }); } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var definitions = compilerService.languageService.getTypeDefinitionAtPosition(file, position); + else { + return definitions; + } + }; + Session.prototype.getTypeDefinition = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var definitions = project.getLanguageService().getTypeDefinitionAtPosition(file, position); if (!definitions) { return undefined; } - return definitions.map(function (def) { return ({ - file: def.fileName, - start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), - end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) - }); }); + return definitions.map(function (def) { + var defScriptInfo = project.getScriptInfo(def.fileName); + return { + file: def.fileName, + start: defScriptInfo.positionToLineOffset(def.textSpan.start), + end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan)) + }; + }); }; - Session.prototype.getImplementation = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var implementations = compilerService.languageService.getImplementationAtPosition(file, compilerService.host.lineOffsetToPosition(file, line, offset)); + Session.prototype.getImplementation = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var implementations = project.getLanguageService().getImplementationAtPosition(file, position); if (!implementations) { - return undefined; + return []; + } + if (simplifiedResult) { + return implementations.map(function (impl) { return ({ + file: impl.fileName, + start: scriptInfo.positionToLineOffset(impl.textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(impl.textSpan)) + }); }); + } + else { + return implementations; } - return implementations.map(function (impl) { return ({ - file: impl.fileName, - start: compilerService.host.positionToLineOffset(impl.fileName, impl.textSpan.start), - end: compilerService.host.positionToLineOffset(impl.fileName, ts.textSpanEnd(impl.textSpan)) - }); }); }; - Session.prototype.getOccurrences = function (line, offset, fileName) { - fileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(fileName); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(fileName, line, offset); - var occurrences = compilerService.languageService.getOccurrencesAtPosition(fileName, position); + Session.prototype.getOccurrences = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var occurrences = project.getLanguageService().getOccurrencesAtPosition(file, position); if (!occurrences) { return undefined; } return occurrences.map(function (occurrence) { var fileName = occurrence.fileName, isWriteAccess = occurrence.isWriteAccess, textSpan = occurrence.textSpan; - var start = compilerService.host.positionToLineOffset(fileName, textSpan.start); - var end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan)); + var scriptInfo = project.getScriptInfo(fileName); + var start = scriptInfo.positionToLineOffset(textSpan.start); + var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)); return { start: start, end: end, @@ -60732,115 +63989,142 @@ var ts; }; }); }; - Session.prototype.getDiagnosticsWorker = function (args, selector) { - var file = ts.normalizePath(args.file); - var project = this.projectService.getProjectForFile(file); - if (!project) { - throw Errors.NoProject; - } - if (project.languageServiceDiabled) { - throw Errors.ProjectLanguageServiceDisabled; - } - var diagnostics = selector(project, file); - return ts.map(diagnostics, function (originalDiagnostic) { return formatDiag(file, project, originalDiagnostic); }); - }; Session.prototype.getSyntacticDiagnosticsSync = function (args) { - return this.getDiagnosticsWorker(args, function (project, file) { return project.compilerService.languageService.getSyntacticDiagnostics(file); }); + return this.getDiagnosticsWorker(args, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, args.includeLinePosition); }; Session.prototype.getSemanticDiagnosticsSync = function (args) { - return this.getDiagnosticsWorker(args, function (project, file) { return project.compilerService.languageService.getSemanticDiagnostics(file); }); + return this.getDiagnosticsWorker(args, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, args.includeLinePosition); }; - Session.prototype.getDocumentHighlights = function (line, offset, fileName, filesToSearch) { - fileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(fileName); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(fileName, line, offset); - var documentHighlights = compilerService.languageService.getDocumentHighlights(fileName, position, filesToSearch); + Session.prototype.getDocumentHighlights = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch); if (!documentHighlights) { return undefined; } - return documentHighlights.map(convertToDocumentHighlightsItem); + if (simplifiedResult) { + return documentHighlights.map(convertToDocumentHighlightsItem); + } + else { + return documentHighlights; + } function convertToDocumentHighlightsItem(documentHighlights) { var fileName = documentHighlights.fileName, highlightSpans = documentHighlights.highlightSpans; + var scriptInfo = project.getScriptInfo(fileName); return { file: fileName, highlightSpans: highlightSpans.map(convertHighlightSpan) }; function convertHighlightSpan(highlightSpan) { var textSpan = highlightSpan.textSpan, kind = highlightSpan.kind; - var start = compilerService.host.positionToLineOffset(fileName, textSpan.start); - var end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan)); + var start = scriptInfo.positionToLineOffset(textSpan.start); + var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)); return { start: start, end: end, kind: kind }; } } }; - Session.prototype.getProjectInfo = function (fileName, needFileNameList) { - fileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(fileName); - if (!project) { - throw Errors.NoProject; - } + Session.prototype.setCompilerOptionsForInferredProjects = function (args) { + this.projectService.setCompilerOptionsForInferredProjects(args.options); + }; + Session.prototype.getProjectInfo = function (args) { + return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList); + }; + Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList) { + var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName, true, true).project; var projectInfo = { - configFileName: project.projectFilename, - languageServiceDisabled: project.languageServiceDiabled + configFileName: project.getProjectName(), + languageServiceDisabled: !project.languageServiceEnabled, + fileNames: needFileNameList ? project.getFileNames() : undefined }; - if (needFileNameList) { - projectInfo.fileNames = project.getFileNames(); - } return projectInfo; }; - Session.prototype.getRenameLocations = function (line, offset, fileName, findInComments, findInStrings) { - var file = ts.normalizePath(fileName); - var info = this.projectService.getScriptInfo(file); - var projects = this.projectService.findReferencingProjects(info); - var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); - if (projectsWithLanguageServiceEnabeld.length === 0) { - throw Errors.NoProject; - } - var defaultProject = projectsWithLanguageServiceEnabeld[0]; - var defaultProjectCompilerService = defaultProject.compilerService; - var position = defaultProjectCompilerService.host.lineOffsetToPosition(file, line, offset); - var renameInfo = defaultProjectCompilerService.languageService.getRenameInfo(file, position); - if (!renameInfo) { - return undefined; - } - if (!renameInfo.canRename) { - return { - info: renameInfo, - locs: [] - }; - } - var fileSpans = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { - var compilerService = project.compilerService; - var renameLocations = compilerService.languageService.findRenameLocations(file, position, findInStrings, findInComments); - if (!renameLocations) { - return []; + Session.prototype.getRenameInfo = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + return project.getLanguageService().getRenameInfo(file, position); + }; + Session.prototype.getProjects = function (args) { + var projects; + if (args.projectFileName) { + var project = this.getProject(args.projectFileName); + if (project) { + projects = [project]; } - return renameLocations.map(function (location) { return ({ - file: location.fileName, - start: compilerService.host.positionToLineOffset(location.fileName, location.textSpan.start), - end: compilerService.host.positionToLineOffset(location.fileName, ts.textSpanEnd(location.textSpan)) - }); }); - }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; }); - var locs = fileSpans.reduce(function (accum, cur) { - var curFileAccum; - if (accum.length > 0) { - curFileAccum = accum[accum.length - 1]; - if (curFileAccum.file !== cur.file) { - curFileAccum = undefined; + } + else { + var scriptInfo = this.projectService.getScriptInfo(args.file); + projects = scriptInfo.containingProjects; + } + projects = ts.filter(projects, function (p) { return p.languageServiceEnabled; }); + if (!projects || !projects.length) { + return server.Errors.ThrowNoProject(); + } + return projects; + }; + Session.prototype.getRenameLocations = function (args, simplifiedResult) { + var file = server.toNormalizedPath(args.file); + var info = this.projectService.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, info); + var projects = this.getProjects(args); + if (simplifiedResult) { + var defaultProject = projects[0]; + var renameInfo = defaultProject.getLanguageService().getRenameInfo(file, position); + if (!renameInfo) { + return undefined; + } + if (!renameInfo.canRename) { + return { + info: renameInfo, + locs: [] + }; + } + var fileSpans = server.combineProjectOutput(projects, function (project) { + var renameLocations = project.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); + if (!renameLocations) { + return []; } + return renameLocations.map(function (location) { + var locationScriptInfo = project.getScriptInfo(location.fileName); + return { + file: location.fileName, + start: locationScriptInfo.positionToLineOffset(location.textSpan.start), + end: locationScriptInfo.positionToLineOffset(ts.textSpanEnd(location.textSpan)) + }; + }); + }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; }); + var locs = fileSpans.reduce(function (accum, cur) { + var curFileAccum; + if (accum.length > 0) { + curFileAccum = accum[accum.length - 1]; + if (curFileAccum.file !== cur.file) { + curFileAccum = undefined; + } + } + if (!curFileAccum) { + curFileAccum = { file: cur.file, locs: [] }; + accum.push(curFileAccum); + } + curFileAccum.locs.push({ start: cur.start, end: cur.end }); + return accum; + }, []); + return { info: renameInfo, locs: locs }; + } + else { + return server.combineProjectOutput(projects, function (p) { return p.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); }, undefined, renameLocationIsEqualTo); + } + function renameLocationIsEqualTo(a, b) { + if (a === b) { + return true; } - if (!curFileAccum) { - curFileAccum = { file: cur.file, locs: [] }; - accum.push(curFileAccum); + if (!a || !b) { + return false; } - curFileAccum.locs.push({ start: cur.start, end: cur.end }); - return accum; - }, []); - return { info: renameInfo, locs: locs }; + return a.fileName === b.fileName && + a.textSpan.start === b.textSpan.start && + a.textSpan.length === b.textSpan.length; + } function compareRenameLocation(a, b) { if (a.file < b.file) { return -1; @@ -60861,51 +64145,51 @@ var ts; } } }; - Session.prototype.getReferences = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var info = this.projectService.getScriptInfo(file); - var projects = this.projectService.findReferencingProjects(info); - var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); - if (projectsWithLanguageServiceEnabeld.length === 0) { - throw Errors.NoProject; - } - var defaultProject = projectsWithLanguageServiceEnabeld[0]; - var position = defaultProject.compilerService.host.lineOffsetToPosition(file, line, offset); - var nameInfo = defaultProject.compilerService.languageService.getQuickInfoAtPosition(file, position); - if (!nameInfo) { - return undefined; - } - var displayString = ts.displayPartsToString(nameInfo.displayParts); - var nameSpan = nameInfo.textSpan; - var nameColStart = defaultProject.compilerService.host.positionToLineOffset(file, nameSpan.start).offset; - var nameText = defaultProject.compilerService.host.getScriptSnapshot(file).getText(nameSpan.start, ts.textSpanEnd(nameSpan)); - var refs = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { - var compilerService = project.compilerService; - var references = compilerService.languageService.getReferencesAtPosition(file, position); - if (!references) { - return []; + Session.prototype.getReferences = function (args, simplifiedResult) { + var file = server.toNormalizedPath(args.file); + var projects = this.getProjects(args); + var defaultProject = projects[0]; + var scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + if (simplifiedResult) { + var nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position); + if (!nameInfo) { + return undefined; } - return references.map(function (ref) { - var start = compilerService.host.positionToLineOffset(ref.fileName, ref.textSpan.start); - var refLineSpan = compilerService.host.lineToTextSpan(ref.fileName, start.line - 1); - var snap = compilerService.host.getScriptSnapshot(ref.fileName); - var lineText = snap.getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); - return { - file: ref.fileName, - start: start, - lineText: lineText, - end: compilerService.host.positionToLineOffset(ref.fileName, ts.textSpanEnd(ref.textSpan)), - isWriteAccess: ref.isWriteAccess, - isDefinition: ref.isDefinition - }; - }); - }, compareFileStart, areReferencesResponseItemsForTheSameLocation); - return { - refs: refs, - symbolName: nameText, - symbolStartOffset: nameColStart, - symbolDisplayString: displayString - }; + var displayString = ts.displayPartsToString(nameInfo.displayParts); + var nameSpan = nameInfo.textSpan; + var nameColStart = scriptInfo.positionToLineOffset(nameSpan.start).offset; + var nameText = scriptInfo.snap().getText(nameSpan.start, ts.textSpanEnd(nameSpan)); + var refs = server.combineProjectOutput(projects, function (project) { + var references = project.getLanguageService().getReferencesAtPosition(file, position); + if (!references) { + return []; + } + return references.map(function (ref) { + var refScriptInfo = project.getScriptInfo(ref.fileName); + var start = refScriptInfo.positionToLineOffset(ref.textSpan.start); + var refLineSpan = refScriptInfo.lineToTextSpan(start.line - 1); + var lineText = refScriptInfo.snap().getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); + return { + file: ref.fileName, + start: start, + lineText: lineText, + end: refScriptInfo.positionToLineOffset(ts.textSpanEnd(ref.textSpan)), + isWriteAccess: ref.isWriteAccess, + isDefinition: ref.isDefinition + }; + }); + }, compareFileStart, areReferencesResponseItemsForTheSameLocation); + return { + refs: refs, + symbolName: nameText, + symbolStartOffset: nameColStart, + symbolDisplayString: displayString + }; + } + else { + return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().findReferences(file, position); }, undefined, undefined); + } function areReferencesResponseItemsForTheSameLocation(a, b) { if (a && b) { return a.file === b.file && @@ -60916,102 +64200,150 @@ var ts; } }; Session.prototype.openClientFile = function (fileName, fileContent, scriptKind) { - var file = ts.normalizePath(fileName); - var _a = this.projectService.openClientFile(file, fileContent, scriptKind), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; - if (configFileErrors) { - this.configFileDiagnosticEvent(fileName, configFileName, configFileErrors); + var _a = this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; + if (this.eventHander) { + this.eventHander({ + eventName: "configFileDiag", + data: { fileName: fileName, configFileName: configFileName, diagnostics: configFileErrors || [] } + }); } }; - Session.prototype.getQuickInfo = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + Session.prototype.getPosition = function (args, scriptInfo) { + return args.position !== undefined ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset); + }; + Session.prototype.getFileAndProject = function (args, errorOnMissingProject) { + if (errorOnMissingProject === void 0) { errorOnMissingProject = true; } + return this.getFileAndProjectWorker(args.file, args.projectFileName, true, errorOnMissingProject); + }; + Session.prototype.getFileAndProjectWithoutRefreshingInferredProjects = function (args, errorOnMissingProject) { + if (errorOnMissingProject === void 0) { errorOnMissingProject = true; } + return this.getFileAndProjectWorker(args.file, args.projectFileName, false, errorOnMissingProject); + }; + Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName, refreshInferredProjects, errorOnMissingProject) { + var file = server.toNormalizedPath(uncheckedFileName); + var project = this.getProject(projectFileName) || this.projectService.getDefaultProjectForFile(file, refreshInferredProjects); + if (!project && errorOnMissingProject) { + return server.Errors.ThrowNoProject(); } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var quickInfo = compilerService.languageService.getQuickInfoAtPosition(file, position); + return { file: file, project: project }; + }; + Session.prototype.getOutliningSpans = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + return project.getLanguageService(false).getOutliningSpans(file); + }; + Session.prototype.getTodoComments = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getTodoComments(file, args.descriptors); + }; + Session.prototype.getDocCommentTemplate = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + return project.getLanguageService(false).getDocCommentTemplateAtPosition(file, position); + }; + Session.prototype.getIndentation = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + var options = args.options || this.projectService.getFormatCodeOptions(file); + var indentation = project.getLanguageService(false).getIndentationAtPosition(file, position, options); + return { position: position, indentation: indentation }; + }; + Session.prototype.getBreakpointStatement = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + return project.getLanguageService(false).getBreakpointStatementAtPosition(file, position); + }; + Session.prototype.getNameOrDottedNameSpan = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + return project.getLanguageService(false).getNameOrDottedNameSpan(file, position, position); + }; + Session.prototype.isValidBraceCompletion = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + return project.getLanguageService(false).isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0)); + }; + Session.prototype.getQuickInfoWorker = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var quickInfo = project.getLanguageService().getQuickInfoAtPosition(file, this.getPosition(args, scriptInfo)); if (!quickInfo) { return undefined; } - var displayString = ts.displayPartsToString(quickInfo.displayParts); - var docString = ts.displayPartsToString(quickInfo.documentation); - return { - kind: quickInfo.kind, - kindModifiers: quickInfo.kindModifiers, - start: compilerService.host.positionToLineOffset(file, quickInfo.textSpan.start), - end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(quickInfo.textSpan)), - displayString: displayString, - documentation: docString - }; - }; - Session.prototype.getFormattingEditsForRange = function (line, offset, endLine, endOffset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + if (simplifiedResult) { + var displayString = ts.displayPartsToString(quickInfo.displayParts); + var docString = ts.displayPartsToString(quickInfo.documentation); + return { + kind: quickInfo.kind, + kindModifiers: quickInfo.kindModifiers, + start: scriptInfo.positionToLineOffset(quickInfo.textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(quickInfo.textSpan)), + displayString: displayString, + documentation: docString + }; } - var compilerService = project.compilerService; - var startPosition = compilerService.host.lineOffsetToPosition(file, line, offset); - var endPosition = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); - var edits = compilerService.languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); + else { + return quickInfo; + } + }; + Session.prototype.getFormattingEditsForRange = function (args) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset); + var endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + var edits = project.getLanguageService(false).getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); if (!edits) { return undefined; } - return edits.map(function (edit) { - return { - start: compilerService.host.positionToLineOffset(file, edit.span.start), - end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)), - newText: edit.newText ? edit.newText : "" - }; - }); + return edits.map(function (edit) { return _this.convertTextChangeToCodeEdit(edit, scriptInfo); }); }; - Session.prototype.getFormattingEditsAfterKeystroke = function (line, offset, key, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); + Session.prototype.getFormattingEditsForRangeFull = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var options = args.options || this.projectService.getFormatCodeOptions(file); + return project.getLanguageService(false).getFormattingEditsForRange(file, args.position, args.endPosition, options); + }; + Session.prototype.getFormattingEditsForDocumentFull = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var options = args.options || this.projectService.getFormatCodeOptions(file); + return project.getLanguageService(false).getFormattingEditsForDocument(file, options); + }; + Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var options = args.options || this.projectService.getFormatCodeOptions(file); + return project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, args.position, args.key, options); + }; + Session.prototype.getFormattingEditsAfterKeystroke = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = scriptInfo.lineOffsetToPosition(args.line, args.offset); var formatOptions = this.projectService.getFormatCodeOptions(file); - var edits = compilerService.languageService.getFormattingEditsAfterKeystroke(file, position, key, formatOptions); - if ((key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { - var scriptInfo = compilerService.host.getScriptInfo(file); - if (scriptInfo) { - var lineInfo = scriptInfo.getLineInfo(line); - if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) { - var lineText = lineInfo.leaf.text; - if (lineText.search("\\S") < 0) { - var editorOptions = { - BaseIndentSize: formatOptions.BaseIndentSize, - IndentSize: formatOptions.IndentSize, - TabSize: formatOptions.TabSize, - NewLineCharacter: formatOptions.NewLineCharacter, - ConvertTabsToSpaces: formatOptions.ConvertTabsToSpaces, - IndentStyle: ts.IndentStyle.Smart - }; - var preferredIndent = compilerService.languageService.getIndentationAtPosition(file, position, editorOptions); - var hasIndent = 0; - var i = void 0, len = void 0; - for (i = 0, len = lineText.length; i < len; i++) { - if (lineText.charAt(i) == " ") { - hasIndent++; - } - else if (lineText.charAt(i) == "\t") { - hasIndent += editorOptions.TabSize; - } - else { - break; - } + var edits = project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions); + if ((args.key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { + var lineInfo = scriptInfo.getLineInfo(args.line); + if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) { + var lineText = lineInfo.leaf.text; + if (lineText.search("\\S") < 0) { + var preferredIndent = project.getLanguageService(false).getIndentationAtPosition(file, position, formatOptions); + var hasIndent = 0; + var i = void 0, len = void 0; + for (i = 0, len = lineText.length; i < len; i++) { + if (lineText.charAt(i) == " ") { + hasIndent++; } - if (preferredIndent !== hasIndent) { - var firstNoWhiteSpacePosition = lineInfo.offset + i; - edits.push({ - span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition), - newText: generateIndentString(preferredIndent, editorOptions) - }); + else if (lineText.charAt(i) == "\t") { + hasIndent += formatOptions.tabSize; } + else { + break; + } + } + if (preferredIndent !== hasIndent) { + var firstNoWhiteSpacePosition = lineInfo.offset + i; + edits.push({ + span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition), + newText: ts.formatting.getIndentationString(preferredIndent, formatOptions) + }); } } } @@ -61021,89 +64353,106 @@ var ts; } return edits.map(function (edit) { return { - start: compilerService.host.positionToLineOffset(file, edit.span.start), - end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)), + start: scriptInfo.positionToLineOffset(edit.span.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(edit.span)), newText: edit.newText ? edit.newText : "" }; }); }; - Session.prototype.getCompletions = function (line, offset, prefix, fileName) { - if (!prefix) { - prefix = ""; - } - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var completions = compilerService.languageService.getCompletionsAtPosition(file, position); + Session.prototype.getCompletions = function (args, simplifiedResult) { + var _this = this; + var prefix = args.prefix || ""; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var completions = project.getLanguageService().getCompletionsAtPosition(file, position); if (!completions) { return undefined; } - return completions.entries.reduce(function (result, entry) { - if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { - var name_52 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; - var convertedSpan = undefined; - if (replacementSpan) { - convertedSpan = { - start: compilerService.host.positionToLineOffset(fileName, replacementSpan.start), - end: compilerService.host.positionToLineOffset(fileName, replacementSpan.start + replacementSpan.length) - }; + if (simplifiedResult) { + return completions.entries.reduce(function (result, entry) { + if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { + var name_53 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; + var convertedSpan = replacementSpan ? _this.decorateSpan(replacementSpan, scriptInfo) : undefined; + result.push({ name: name_53, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }); } - result.push({ name: name_52, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }); - } - return result; - }, []).sort(function (a, b) { return a.name.localeCompare(b.name); }); - }; - Session.prototype.getCompletionEntryDetails = function (line, offset, entryNames, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + return result; + }, []).sort(function (a, b) { return a.name.localeCompare(b.name); }); } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - return entryNames.reduce(function (accum, entryName) { - var details = compilerService.languageService.getCompletionEntryDetails(file, position, entryName); + else { + return completions; + } + }; + Session.prototype.getCompletionEntryDetails = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + return args.entryNames.reduce(function (accum, entryName) { + var details = project.getLanguageService().getCompletionEntryDetails(file, position, entryName); if (details) { accum.push(details); } return accum; }, []); }; - Session.prototype.getSignatureHelpItems = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + Session.prototype.getCompileOnSaveAffectedFileList = function (args) { + var info = this.projectService.getScriptInfo(args.file); + var result = []; + if (!info) { + return []; } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var helpItems = compilerService.languageService.getSignatureHelpItems(file, position); + var projectsToSearch = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; + for (var _i = 0, projectsToSearch_1 = projectsToSearch; _i < projectsToSearch_1.length; _i++) { + var project = projectsToSearch_1[_i]; + if (project.compileOnSaveEnabled && project.languageServiceEnabled) { + result.push({ + projectFileName: project.getProjectName(), + fileNames: project.getCompileOnSaveAffectedFileList(info) + }); + } + } + return result; + }; + Session.prototype.emitFile = function (args) { + var _this = this; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + if (!project) { + server.Errors.ThrowNoProject(); + } + var scriptInfo = project.getScriptInfo(file); + return project.builder.emitFile(scriptInfo, function (path, data, writeByteOrderMark) { return _this.host.writeFile(path, data, writeByteOrderMark); }); + }; + Session.prototype.getSignatureHelpItems = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var helpItems = project.getLanguageService().getSignatureHelpItems(file, position); if (!helpItems) { return undefined; } - var span = helpItems.applicableSpan; - var result = { - items: helpItems.items, - applicableSpan: { - start: compilerService.host.positionToLineOffset(file, span.start), - end: compilerService.host.positionToLineOffset(file, span.start + span.length) - }, - selectedItemIndex: helpItems.selectedItemIndex, - argumentIndex: helpItems.argumentIndex, - argumentCount: helpItems.argumentCount - }; - return result; + if (simplifiedResult) { + var span_16 = helpItems.applicableSpan; + return { + items: helpItems.items, + applicableSpan: { + start: scriptInfo.positionToLineOffset(span_16.start), + end: scriptInfo.positionToLineOffset(span_16.start + span_16.length) + }, + selectedItemIndex: helpItems.selectedItemIndex, + argumentIndex: helpItems.argumentIndex, + argumentCount: helpItems.argumentCount + }; + } + else { + return helpItems; + } }; Session.prototype.getDiagnostics = function (delay, fileNames) { var _this = this; - var checkList = fileNames.reduce(function (accum, fileName) { - fileName = ts.normalizePath(fileName); - var project = _this.projectService.getProjectForFile(fileName); - if (project && !project.languageServiceDiabled) { + var checkList = fileNames.reduce(function (accum, uncheckedFileName) { + var fileName = server.toNormalizedPath(uncheckedFileName); + var project = _this.projectService.getDefaultProjectForFile(fileName, true); + if (project) { accum.push({ fileName: fileName, project: project }); } return accum; @@ -61112,40 +64461,34 @@ var ts; this.updateErrorCheck(checkList, this.changeSeq, function (n) { return n === _this.changeSeq; }, delay); } }; - Session.prototype.change = function (line, offset, endLine, endOffset, insertString, fileName) { + Session.prototype.change = function (args) { var _this = this; - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (project && !project.languageServiceDiabled) { - var compilerService = project.compilerService; - var start = compilerService.host.lineOffsetToPosition(file, line, offset); - var end = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); + var _a = this.getFileAndProject(args, false), file = _a.file, project = _a.project; + if (project) { + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var start = scriptInfo.lineOffsetToPosition(args.line, args.offset); + var end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); if (start >= 0) { - compilerService.host.editScript(file, start, end, insertString); + scriptInfo.editContent(start, end, args.insertString); this.changeSeq++; } this.updateProjectStructure(this.changeSeq, function (n) { return n === _this.changeSeq; }); } }; - Session.prototype.reload = function (fileName, tempFileName, reqSeq) { - var _this = this; - if (reqSeq === void 0) { reqSeq = 0; } - var file = ts.normalizePath(fileName); - var tmpfile = ts.normalizePath(tempFileName); - var project = this.projectService.getProjectForFile(file); - if (project && !project.languageServiceDiabled) { + Session.prototype.reload = function (args, reqSeq) { + var file = server.toNormalizedPath(args.file); + var project = this.projectService.getDefaultProjectForFile(file, true); + if (project) { this.changeSeq++; - project.compilerService.host.reloadScript(file, tmpfile, function () { - _this.output(undefined, CommandNames.Reload, reqSeq); - }); + if (project.reloadScript(file)) { + this.output(undefined, CommandNames.Reload, reqSeq); + } } }; Session.prototype.saveToTmp = function (fileName, tempFileName) { - var file = ts.normalizePath(fileName); - var tmpfile = ts.normalizePath(tempFileName); - var project = this.projectService.getProjectForFile(file); - if (project && !project.languageServiceDiabled) { - project.compilerService.host.saveTo(file, tmpfile); + var scriptInfo = this.projectService.getScriptInfo(fileName); + if (scriptInfo) { + scriptInfo.saveTo(tempFileName); } }; Session.prototype.closeClientFile = function (fileName) { @@ -61155,77 +64498,108 @@ var ts; var file = ts.normalizePath(fileName); this.projectService.closeClientFile(file); }; - Session.prototype.decorateNavigationBarItem = function (project, fileName, items, lineIndex) { + Session.prototype.decorateNavigationBarItems = function (items, scriptInfo) { var _this = this; - if (!items) { - return undefined; - } - var compilerService = project.compilerService; - return items.map(function (item) { return ({ + return ts.map(items, function (item) { return ({ text: item.text, kind: item.kind, kindModifiers: item.kindModifiers, - spans: item.spans.map(function (span) { return ({ - start: compilerService.host.positionToLineOffset(fileName, span.start, lineIndex), - end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span), lineIndex) - }); }), - childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems, lineIndex), + spans: item.spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }), + childItems: _this.decorateNavigationBarItems(item.childItems, scriptInfo), indent: item.indent }); }); }; - Session.prototype.getNavigationBarItems = function (fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var items = compilerService.languageService.getNavigationBarItems(file); - if (!items) { - return undefined; - } - return this.decorateNavigationBarItem(project, fileName, items, compilerService.host.getLineIndex(fileName)); + Session.prototype.getNavigationBarItems = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var items = project.getLanguageService(false).getNavigationBarItems(file); + return !items + ? undefined + : simplifiedResult + ? this.decorateNavigationBarItems(items, project.getScriptInfoForNormalizedPath(file)) + : items; }; - Session.prototype.getNavigateToItems = function (searchValue, fileName, maxResultCount, currentFileOnly) { - var file = ts.normalizePath(fileName); - var info = this.projectService.getScriptInfo(file); - var projects = this.projectService.findReferencingProjects(info); - var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); - if (projectsWithLanguageServiceEnabeld.length === 0) { - throw Errors.NoProject; + Session.prototype.decorateNavigationTree = function (tree, scriptInfo) { + var _this = this; + return { + text: tree.text, + kind: tree.kind, + kindModifiers: tree.kindModifiers, + spans: tree.spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }), + childItems: ts.map(tree.childItems, function (item) { return _this.decorateNavigationTree(item, scriptInfo); }) + }; + }; + Session.prototype.decorateSpan = function (span, scriptInfo) { + return { + start: scriptInfo.positionToLineOffset(span.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(span)) + }; + }; + Session.prototype.getNavigationTree = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var tree = project.getLanguageService(false).getNavigationTree(file); + return !tree + ? undefined + : simplifiedResult + ? this.decorateNavigationTree(tree, project.getScriptInfoForNormalizedPath(file)) + : tree; + }; + Session.prototype.getNavigateToItems = function (args, simplifiedResult) { + var projects = this.getProjects(args); + var fileName = args.currentFileOnly ? args.file && ts.normalizeSlashes(args.file) : undefined; + if (simplifiedResult) { + return server.combineProjectOutput(projects, function (project) { + var navItems = project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); + if (!navItems) { + return []; + } + return navItems.map(function (navItem) { + var scriptInfo = project.getScriptInfo(navItem.fileName); + var start = scriptInfo.positionToLineOffset(navItem.textSpan.start); + var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(navItem.textSpan)); + var bakedItem = { + name: navItem.name, + kind: navItem.kind, + file: navItem.fileName, + start: start, + end: end + }; + if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { + bakedItem.kindModifiers = navItem.kindModifiers; + } + if (navItem.matchKind !== "none") { + bakedItem.matchKind = navItem.matchKind; + } + if (navItem.containerName && (navItem.containerName.length > 0)) { + bakedItem.containerName = navItem.containerName; + } + if (navItem.containerKind && (navItem.containerKind.length > 0)) { + bakedItem.containerKind = navItem.containerKind; + } + return bakedItem; + }); + }, undefined, areNavToItemsForTheSameLocation); } - var allNavToItems = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { - var compilerService = project.compilerService; - var navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount, currentFileOnly ? fileName : undefined); - if (!navItems) { - return []; + else { + return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); }, undefined, navigateToItemIsEqualTo); + } + function navigateToItemIsEqualTo(a, b) { + if (a === b) { + return true; } - return navItems.map(function (navItem) { - var start = compilerService.host.positionToLineOffset(navItem.fileName, navItem.textSpan.start); - var end = compilerService.host.positionToLineOffset(navItem.fileName, ts.textSpanEnd(navItem.textSpan)); - var bakedItem = { - name: navItem.name, - kind: navItem.kind, - file: navItem.fileName, - start: start, - end: end - }; - if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { - bakedItem.kindModifiers = navItem.kindModifiers; - } - if (navItem.matchKind !== "none") { - bakedItem.matchKind = navItem.matchKind; - } - if (navItem.containerName && (navItem.containerName.length > 0)) { - bakedItem.containerName = navItem.containerName; - } - if (navItem.containerKind && (navItem.containerKind.length > 0)) { - bakedItem.containerKind = navItem.containerKind; - } - return bakedItem; - }); - }, undefined, areNavToItemsForTheSameLocation); - return allNavToItems; + if (!a || !b) { + return false; + } + return a.containerKind === b.containerKind && + a.containerName === b.containerName && + a.fileName === b.fileName && + a.isCaseSensitive === b.isCaseSensitive && + a.kind === b.kind && + a.kindModifiers === b.containerName && + a.matchKind === b.matchKind && + a.name === b.name && + a.textSpan.start === b.textSpan.start && + a.textSpan.length === b.textSpan.length; + } function areNavToItemsForTheSameLocation(a, b) { if (a && b) { return a.file === b.file && @@ -61235,26 +64609,64 @@ var ts; return false; } }; - Session.prototype.getBraceMatching = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var spans = compilerService.languageService.getBraceMatchingAtPosition(file, position); - if (!spans) { + Session.prototype.getSupportedCodeFixes = function () { + return ts.getSupportedCodeFixes(); + }; + Session.prototype.getCodeFixes = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var startPosition = getStartPosition(); + var endPosition = getEndPosition(); + var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes); + if (!codeActions) { return undefined; } - return spans.map(function (span) { return ({ - start: compilerService.host.positionToLineOffset(file, span.start), - end: compilerService.host.positionToLineOffset(file, span.start + span.length) - }); }); + if (simplifiedResult) { + return codeActions.map(function (codeAction) { return _this.mapCodeAction(codeAction, scriptInfo); }); + } + else { + return codeActions; + } + function getStartPosition() { + return args.startPosition !== undefined ? args.startPosition : scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + } + function getEndPosition() { + return args.endPosition !== undefined ? args.endPosition : scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + } + }; + Session.prototype.mapCodeAction = function (codeAction, scriptInfo) { + var _this = this; + return { + description: codeAction.description, + changes: codeAction.changes.map(function (change) { return ({ + fileName: change.fileName, + textChanges: change.textChanges.map(function (textChange) { return _this.convertTextChangeToCodeEdit(textChange, scriptInfo); }) + }); }) + }; + }; + Session.prototype.convertTextChangeToCodeEdit = function (change, scriptInfo) { + return { + start: scriptInfo.positionToLineOffset(change.span.start), + end: scriptInfo.positionToLineOffset(change.span.start + change.span.length), + newText: change.newText ? change.newText : "" + }; + }; + Session.prototype.getBraceMatching = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var spans = project.getLanguageService(false).getBraceMatchingAtPosition(file, position); + return !spans + ? undefined + : simplifiedResult + ? spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }) + : spans; }; Session.prototype.getDiagnosticsForProject = function (delay, fileName) { var _this = this; - var _a = this.getProjectInfo(fileName, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; + var _a = this.getProjectInfoWorker(fileName, undefined, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; if (languageServiceDisabled) { return; } @@ -61263,8 +64675,8 @@ var ts; var mediumPriorityFiles = []; var lowPriorityFiles = []; var veryLowPriorityFiles = []; - var normalizedFileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(normalizedFileName); + var normalizedFileName = server.toNormalizedPath(fileName); + var project = this.projectService.getDefaultProjectForFile(normalizedFileName, true); for (var _i = 0, fileNamesInProject_1 = fileNamesInProject; _i < fileNamesInProject_1.length; _i++) { var fileNameInProject = fileNamesInProject_1[_i]; if (this.getCanonicalFileName(fileNameInProject) == this.getCanonicalFileName(fileName)) @@ -61283,10 +64695,7 @@ var ts; } fileNamesInProject = highPriorityFiles.concat(mediumPriorityFiles).concat(lowPriorityFiles).concat(veryLowPriorityFiles); if (fileNamesInProject.length > 0) { - var checkList = fileNamesInProject.map(function (fileName) { - var normalizedFileName = ts.normalizePath(fileName); - return { fileName: normalizedFileName, project: project }; - }); + var checkList = fileNamesInProject.map(function (fileName) { return ({ fileName: fileName, project: project }); }); this.updateErrorCheck(checkList, this.changeSeq, function (n) { return n == _this.changeSeq; }, delay, 200, false); } }; @@ -61296,6 +64705,9 @@ var ts; }; Session.prototype.exit = function () { }; + Session.prototype.notRequired = function () { + return { responseRequired: false }; + }; Session.prototype.requiredResponse = function (response) { return { response: response, responseRequired: true }; }; @@ -61311,31 +64723,32 @@ var ts; return handler(request); } else { - this.projectService.log("Unrecognized JSON command: " + JSON.stringify(request)); + this.logger.msg("Unrecognized JSON command: " + JSON.stringify(request), server.Msg.Err); this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); return { responseRequired: false }; } }; Session.prototype.onMessage = function (message) { + this.gcTimer.scheduleCollect(); var start; - if (this.logger.isVerbose()) { - this.logger.info("request: " + message); + if (this.logger.hasLevel(server.LogLevel.requestTime)) { start = this.hrtime(); + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("request: " + message); + } } var request; try { request = JSON.parse(message); var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired; - if (this.logger.isVerbose()) { - var elapsed = this.hrtime(start); - var seconds = elapsed[0]; - var nanoseconds = elapsed[1]; - var elapsedMs = ((1e9 * seconds) + nanoseconds) / 1000000.0; - var leader = "Elapsed time (in milliseconds)"; - if (!responseRequired) { - leader = "Async elapsed time (in milliseconds)"; + if (this.logger.hasLevel(server.LogLevel.requestTime)) { + var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); + if (responseRequired) { + this.logger.perftrc(request.seq + "::" + request.command + ": elapsed time (in milliseconds) " + elapsedTime); + } + else { + this.logger.perftrc(request.seq + "::" + request.command + ": async elapsed time (in milliseconds) " + elapsedTime); } - this.logger.msg(leader + ": " + elapsedMs.toFixed(4).toString(), "Perf"); } if (response) { this.output(response, request.command, request.seq); @@ -61346,6 +64759,8 @@ var ts; } catch (err) { if (err instanceof ts.OperationCanceledException) { + this.output({ canceled: true }, request.command, request.seq); + return; } this.logError(err, message); this.output(undefined, request ? request.command : CommandNames.Unknown, request ? request.seq : 0, "Error processing request. " + err.message + "\n" + err.stack); @@ -61361,1229 +64776,6 @@ var ts; var server; (function (server) { var lineCollectionCapacity = 4; - function mergeFormatOptions(formatCodeOptions, formatOptions) { - var hasOwnProperty = Object.prototype.hasOwnProperty; - Object.keys(formatOptions).forEach(function (key) { - var codeKey = key.charAt(0).toUpperCase() + key.substring(1); - if (hasOwnProperty.call(formatCodeOptions, codeKey)) { - formatCodeOptions[codeKey] = formatOptions[key]; - } - }); - } - server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; - var ScriptInfo = (function () { - function ScriptInfo(host, fileName, content, isOpen) { - if (isOpen === void 0) { isOpen = false; } - this.host = host; - this.fileName = fileName; - this.isOpen = isOpen; - this.children = []; - this.formatCodeOptions = ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host)); - this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); - this.svc = ScriptVersionCache.fromString(host, content); - } - ScriptInfo.prototype.setFormatOptions = function (formatOptions) { - if (formatOptions) { - mergeFormatOptions(this.formatCodeOptions, formatOptions); - } - }; - ScriptInfo.prototype.close = function () { - this.isOpen = false; - }; - ScriptInfo.prototype.addChild = function (childInfo) { - this.children.push(childInfo); - }; - ScriptInfo.prototype.snap = function () { - return this.svc.getSnapshot(); - }; - ScriptInfo.prototype.getText = function () { - var snap = this.snap(); - return snap.getText(0, snap.getLength()); - }; - ScriptInfo.prototype.getLineInfo = function (line) { - var snap = this.snap(); - return snap.index.lineNumberToInfo(line); - }; - ScriptInfo.prototype.editContent = function (start, end, newText) { - this.svc.edit(start, end - start, newText); - }; - ScriptInfo.prototype.getTextChangeRangeBetweenVersions = function (startVersion, endVersion) { - return this.svc.getTextChangesBetweenVersions(startVersion, endVersion); - }; - ScriptInfo.prototype.getChangeRange = function (oldSnapshot) { - return this.snap().getChangeRange(oldSnapshot); - }; - return ScriptInfo; - }()); - server.ScriptInfo = ScriptInfo; - var LSHost = (function () { - function LSHost(host, project) { - var _this = this; - this.host = host; - this.project = project; - this.roots = []; - this.getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - this.resolvedModuleNames = ts.createFileMap(); - this.resolvedTypeReferenceDirectives = ts.createFileMap(); - this.filenameToScript = ts.createFileMap(); - this.moduleResolutionHost = { - fileExists: function (fileName) { return _this.fileExists(fileName); }, - readFile: function (fileName) { return _this.host.readFile(fileName); }, - directoryExists: function (directoryName) { return _this.host.directoryExists(directoryName); } - }; - if (this.host.realpath) { - this.moduleResolutionHost.realpath = function (path) { return _this.host.realpath(path); }; - } - } - LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult) { - var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var currentResolutionsInFile = cache.get(path); - var newResolutions = ts.createMap(); - var resolvedModules = []; - var compilerOptions = this.getCompilationSettings(); - for (var _i = 0, names_3 = names; _i < names_3.length; _i++) { - var name_53 = names_3[_i]; - var resolution = newResolutions[name_53]; - if (!resolution) { - var existingResolution = currentResolutionsInFile && currentResolutionsInFile[name_53]; - if (moduleResolutionIsValid(existingResolution)) { - resolution = existingResolution; - } - else { - resolution = loader(name_53, containingFile, compilerOptions, this.moduleResolutionHost); - resolution.lastCheckTime = Date.now(); - newResolutions[name_53] = resolution; - } - } - ts.Debug.assert(resolution !== undefined); - resolvedModules.push(getResult(resolution)); - } - cache.set(path, newResolutions); - return resolvedModules; - function moduleResolutionIsValid(resolution) { - if (!resolution) { - return false; - } - if (getResult(resolution)) { - return true; - } - return resolution.failedLookupLocations.length === 0; - } - }; - LSHost.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { - return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, function (m) { return m.resolvedTypeReferenceDirective; }); - }; - LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) { - return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, ts.resolveModuleName, function (m) { return m.resolvedModule; }); - }; - LSHost.prototype.getDefaultLibFileName = function () { - var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath())); - return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings)); - }; - LSHost.prototype.getScriptSnapshot = function (filename) { - var scriptInfo = this.getScriptInfo(filename); - if (scriptInfo) { - return scriptInfo.snap(); - } - }; - LSHost.prototype.setCompilationSettings = function (opt) { - this.compilationSettings = opt; - this.resolvedModuleNames.clear(); - this.resolvedTypeReferenceDirectives.clear(); - }; - LSHost.prototype.lineAffectsRefs = function (filename, line) { - var info = this.getScriptInfo(filename); - var lineInfo = info.getLineInfo(line); - if (lineInfo && lineInfo.text) { - var regex = /reference|import|\/\*|\*\//; - return regex.test(lineInfo.text); - } - }; - LSHost.prototype.getCompilationSettings = function () { - return this.compilationSettings; - }; - LSHost.prototype.getScriptFileNames = function () { - return this.roots.map(function (root) { return root.fileName; }); - }; - LSHost.prototype.getScriptKind = function (fileName) { - var info = this.getScriptInfo(fileName); - if (!info) { - return undefined; - } - if (!info.scriptKind) { - info.scriptKind = ts.getScriptKindFromFileName(fileName); - } - return info.scriptKind; - }; - LSHost.prototype.getScriptVersion = function (filename) { - return this.getScriptInfo(filename).svc.latestVersion().toString(); - }; - LSHost.prototype.getCurrentDirectory = function () { - return ""; - }; - LSHost.prototype.getScriptIsOpen = function (filename) { - return this.getScriptInfo(filename).isOpen; - }; - LSHost.prototype.removeReferencedFile = function (info) { - if (!info.isOpen) { - this.filenameToScript.remove(info.path); - this.resolvedModuleNames.remove(info.path); - this.resolvedTypeReferenceDirectives.remove(info.path); - } - }; - LSHost.prototype.getScriptInfo = function (filename) { - var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var scriptInfo = this.filenameToScript.get(path); - if (!scriptInfo) { - scriptInfo = this.project.openReferencedFile(filename); - if (scriptInfo) { - this.filenameToScript.set(path, scriptInfo); - } - } - return scriptInfo; - }; - LSHost.prototype.addRoot = function (info) { - if (!this.filenameToScript.contains(info.path)) { - this.filenameToScript.set(info.path, info); - this.roots.push(info); - } - }; - LSHost.prototype.removeRoot = function (info) { - if (this.filenameToScript.contains(info.path)) { - this.filenameToScript.remove(info.path); - ts.unorderedRemoveItem(this.roots, info); - this.resolvedModuleNames.remove(info.path); - this.resolvedTypeReferenceDirectives.remove(info.path); - } - }; - LSHost.prototype.saveTo = function (filename, tmpfilename) { - var script = this.getScriptInfo(filename); - if (script) { - var snap = script.snap(); - this.host.writeFile(tmpfilename, snap.getText(0, snap.getLength())); - } - }; - LSHost.prototype.reloadScript = function (filename, tmpfilename, cb) { - var script = this.getScriptInfo(filename); - if (script) { - script.svc.reloadFromFile(tmpfilename, cb); - } - }; - LSHost.prototype.editScript = function (filename, start, end, newText) { - var script = this.getScriptInfo(filename); - if (script) { - script.editContent(start, end, newText); - return; - } - throw new Error("No script with name '" + filename + "'"); - }; - LSHost.prototype.fileExists = function (path) { - var result = this.host.fileExists(path); - return result; - }; - LSHost.prototype.directoryExists = function (path) { - return this.host.directoryExists(path); - }; - LSHost.prototype.getDirectories = function (path) { - return this.host.getDirectories(path); - }; - LSHost.prototype.readDirectory = function (path, extensions, exclude, include) { - return this.host.readDirectory(path, extensions, exclude, include); - }; - LSHost.prototype.readFile = function (path, encoding) { - return this.host.readFile(path, encoding); - }; - LSHost.prototype.lineToTextSpan = function (filename, line) { - var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var script = this.filenameToScript.get(path); - var index = script.snap().index; - var lineInfo = index.lineNumberToInfo(line + 1); - var len; - if (lineInfo.leaf) { - len = lineInfo.leaf.text.length; - } - else { - var nextLineInfo = index.lineNumberToInfo(line + 2); - len = nextLineInfo.offset - lineInfo.offset; - } - return ts.createTextSpan(lineInfo.offset, len); - }; - LSHost.prototype.lineOffsetToPosition = function (filename, line, offset) { - var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var script = this.filenameToScript.get(path); - var index = script.snap().index; - var lineInfo = index.lineNumberToInfo(line); - return (lineInfo.offset + offset - 1); - }; - LSHost.prototype.positionToLineOffset = function (filename, position, lineIndex) { - lineIndex = lineIndex || this.getLineIndex(filename); - var lineOffset = lineIndex.charOffsetToLineNumberAndPos(position); - return { line: lineOffset.line, offset: lineOffset.offset + 1 }; - }; - LSHost.prototype.getLineIndex = function (filename) { - var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var script = this.filenameToScript.get(path); - return script.snap().index; - }; - return LSHost; - }()); - server.LSHost = LSHost; - var Project = (function () { - function Project(projectService, projectOptions, languageServiceDiabled) { - if (languageServiceDiabled === void 0) { languageServiceDiabled = false; } - this.projectService = projectService; - this.projectOptions = projectOptions; - this.languageServiceDiabled = languageServiceDiabled; - this.directoriesWatchedForTsconfig = []; - this.filenameToSourceFile = ts.createMap(); - this.updateGraphSeq = 0; - this.openRefCount = 0; - if (projectOptions && projectOptions.files) { - projectOptions.compilerOptions.allowNonTsExtensions = true; - } - if (!languageServiceDiabled) { - this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions); - } - } - Project.prototype.enableLanguageService = function () { - if (this.languageServiceDiabled) { - this.compilerService = new CompilerService(this, this.projectOptions && this.projectOptions.compilerOptions); - } - this.languageServiceDiabled = false; - }; - Project.prototype.disableLanguageService = function () { - this.languageServiceDiabled = true; - }; - Project.prototype.addOpenRef = function () { - this.openRefCount++; - }; - Project.prototype.deleteOpenRef = function () { - this.openRefCount--; - return this.openRefCount; - }; - Project.prototype.openReferencedFile = function (filename) { - return this.projectService.openFile(filename, false); - }; - Project.prototype.getRootFiles = function () { - if (this.languageServiceDiabled) { - return this.projectOptions ? this.projectOptions.files : undefined; - } - return this.compilerService.host.roots.map(function (info) { return info.fileName; }); - }; - Project.prototype.getFileNames = function () { - if (this.languageServiceDiabled) { - if (!this.projectOptions) { - return undefined; - } - var fileNames = []; - if (this.projectOptions && this.projectOptions.compilerOptions) { - fileNames.push(ts.getDefaultLibFilePath(this.projectOptions.compilerOptions)); - } - ts.addRange(fileNames, this.projectOptions.files); - return fileNames; - } - var sourceFiles = this.program.getSourceFiles(); - return sourceFiles.map(function (sourceFile) { return sourceFile.fileName; }); - }; - Project.prototype.getSourceFile = function (info) { - if (this.languageServiceDiabled) { - return undefined; - } - return this.filenameToSourceFile[info.fileName]; - }; - Project.prototype.getSourceFileFromName = function (filename, requireOpen) { - if (this.languageServiceDiabled) { - return undefined; - } - var info = this.projectService.getScriptInfo(filename); - if (info) { - if ((!requireOpen) || info.isOpen) { - return this.getSourceFile(info); - } - } - }; - Project.prototype.isRoot = function (info) { - if (this.languageServiceDiabled) { - return undefined; - } - return this.compilerService.host.roots.some(function (root) { return root === info; }); - }; - Project.prototype.removeReferencedFile = function (info) { - if (this.languageServiceDiabled) { - return; - } - this.compilerService.host.removeReferencedFile(info); - this.updateGraph(); - }; - Project.prototype.updateFileMap = function () { - if (this.languageServiceDiabled) { - return; - } - this.filenameToSourceFile = ts.createMap(); - var sourceFiles = this.program.getSourceFiles(); - for (var i = 0, len = sourceFiles.length; i < len; i++) { - var normFilename = ts.normalizePath(sourceFiles[i].fileName); - this.filenameToSourceFile[normFilename] = sourceFiles[i]; - } - }; - Project.prototype.finishGraph = function () { - if (this.languageServiceDiabled) { - return; - } - this.updateGraph(); - this.compilerService.languageService.getNavigateToItems(".*"); - }; - Project.prototype.updateGraph = function () { - if (this.languageServiceDiabled) { - return; - } - this.program = this.compilerService.languageService.getProgram(); - this.updateFileMap(); - }; - Project.prototype.isConfiguredProject = function () { - return this.projectFilename; - }; - Project.prototype.addRoot = function (info) { - if (this.languageServiceDiabled) { - return; - } - this.compilerService.host.addRoot(info); - }; - Project.prototype.removeRoot = function (info) { - if (this.languageServiceDiabled) { - return; - } - this.compilerService.host.removeRoot(info); - }; - Project.prototype.filesToString = function () { - if (this.languageServiceDiabled) { - if (this.projectOptions) { - var strBuilder_1 = ""; - ts.forEach(this.projectOptions.files, function (file) { strBuilder_1 += file + "\n"; }); - return strBuilder_1; - } - } - var strBuilder = ""; - ts.forEachProperty(this.filenameToSourceFile, function (sourceFile) { strBuilder += sourceFile.fileName + "\n"; }); - return strBuilder; - }; - Project.prototype.setProjectOptions = function (projectOptions) { - this.projectOptions = projectOptions; - if (projectOptions.compilerOptions) { - projectOptions.compilerOptions.allowNonTsExtensions = true; - if (!this.languageServiceDiabled) { - this.compilerService.setCompilerOptions(projectOptions.compilerOptions); - } - } - }; - return Project; - }()); - server.Project = Project; - function combineProjectOutput(projects, action, comparer, areEqual) { - var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer); - return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; - } - server.combineProjectOutput = combineProjectOutput; - var ProjectService = (function () { - function ProjectService(host, psLogger, eventHandler) { - this.host = host; - this.psLogger = psLogger; - this.eventHandler = eventHandler; - this.filenameToScriptInfo = ts.createMap(); - this.openFileRoots = []; - this.inferredProjects = []; - this.configuredProjects = []; - this.openFilesReferenced = []; - this.openFileRootsConfigured = []; - this.directoryWatchersForTsconfig = ts.createMap(); - this.directoryWatchersRefCount = ts.createMap(); - this.timerForDetectingProjectFileListChanges = ts.createMap(); - this.addDefaultHostConfiguration(); - } - ProjectService.prototype.addDefaultHostConfiguration = function () { - this.hostConfiguration = { - formatCodeOptions: ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host)), - hostInfo: "Unknown host" - }; - }; - ProjectService.prototype.getFormatCodeOptions = function (file) { - if (file) { - var info = this.filenameToScriptInfo[file]; - if (info) { - return info.formatCodeOptions; - } - } - return this.hostConfiguration.formatCodeOptions; - }; - ProjectService.prototype.watchedFileChanged = function (fileName) { - var info = this.filenameToScriptInfo[fileName]; - if (!info) { - this.psLogger.info("Error: got watch notification for unknown file: " + fileName); - } - if (!this.host.fileExists(fileName)) { - this.fileDeletedInFilesystem(info); - } - else { - if (info && (!info.isOpen)) { - info.svc.reloadFromFile(info.fileName); - } - } - }; - ProjectService.prototype.directoryWatchedForSourceFilesChanged = function (project, fileName) { - if (fileName && !ts.isSupportedSourceFileName(fileName, project.projectOptions ? project.projectOptions.compilerOptions : undefined)) { - return; - } - this.log("Detected source file changes: " + fileName); - this.startTimerForDetectingProjectFileListChanges(project); - }; - ProjectService.prototype.startTimerForDetectingProjectFileListChanges = function (project) { - var _this = this; - if (this.timerForDetectingProjectFileListChanges[project.projectFilename]) { - this.host.clearTimeout(this.timerForDetectingProjectFileListChanges[project.projectFilename]); - } - this.timerForDetectingProjectFileListChanges[project.projectFilename] = this.host.setTimeout(function () { return _this.handleProjectFileListChanges(project); }, 250); - }; - ProjectService.prototype.handleProjectFileListChanges = function (project) { - var _this = this; - var _a = this.configFileToProjectOptions(project.projectFilename), projectOptions = _a.projectOptions, errors = _a.errors; - this.reportConfigFileDiagnostics(project.projectFilename, errors); - var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); })); - var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); })); - if (!ts.arrayIsEqualTo(currentRootFiles && currentRootFiles.sort(), newRootFiles && newRootFiles.sort())) { - this.updateConfiguredProject(project); - this.updateProjectStructure(); - } - }; - ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) { - if (diagnostics && diagnostics.length > 0) { - this.eventHandler({ - eventName: "configFileDiag", - data: { configFileName: configFileName, diagnostics: diagnostics, triggerFile: triggerFile } - }); - } - }; - ProjectService.prototype.directoryWatchedForTsconfigChanged = function (fileName) { - var _this = this; - if (ts.getBaseFileName(fileName) !== "tsconfig.json") { - this.log(fileName + " is not tsconfig.json"); - return; - } - this.log("Detected newly added tsconfig file: " + fileName); - var _a = this.configFileToProjectOptions(fileName), projectOptions = _a.projectOptions, errors = _a.errors; - this.reportConfigFileDiagnostics(fileName, errors); - if (!projectOptions) { - return; - } - var rootFilesInTsconfig = projectOptions.files.map(function (f) { return _this.getCanonicalFileName(f); }); - var openFileRoots = this.openFileRoots.map(function (s) { return _this.getCanonicalFileName(s.fileName); }); - for (var _i = 0, openFileRoots_1 = openFileRoots; _i < openFileRoots_1.length; _i++) { - var openFileRoot = openFileRoots_1[_i]; - if (rootFilesInTsconfig.indexOf(openFileRoot) >= 0) { - this.reloadProjects(); - return; - } - } - }; - ProjectService.prototype.getCanonicalFileName = function (fileName) { - var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - return ts.normalizePath(name); - }; - ProjectService.prototype.watchedProjectConfigFileChanged = function (project) { - this.log("Config file changed: " + project.projectFilename); - var configFileErrors = this.updateConfiguredProject(project); - this.updateProjectStructure(); - if (configFileErrors && configFileErrors.length > 0) { - this.eventHandler({ eventName: "configFileDiag", data: { triggerFile: project.projectFilename, configFileName: project.projectFilename, diagnostics: configFileErrors } }); - } - }; - ProjectService.prototype.log = function (msg, type) { - if (type === void 0) { type = "Err"; } - this.psLogger.msg(msg, type); - }; - ProjectService.prototype.setHostConfiguration = function (args) { - if (args.file) { - var info = this.filenameToScriptInfo[args.file]; - if (info) { - info.setFormatOptions(args.formatOptions); - this.log("Host configuration update for file " + args.file, "Info"); - } - } - else { - if (args.hostInfo !== undefined) { - this.hostConfiguration.hostInfo = args.hostInfo; - this.log("Host information " + args.hostInfo, "Info"); - } - if (args.formatOptions) { - mergeFormatOptions(this.hostConfiguration.formatCodeOptions, args.formatOptions); - this.log("Format host information updated", "Info"); - } - } - }; - ProjectService.prototype.closeLog = function () { - this.psLogger.close(); - }; - ProjectService.prototype.createInferredProject = function (root) { - var _this = this; - var project = new Project(this); - project.addRoot(root); - var currentPath = ts.getDirectoryPath(root.fileName); - var parentPath = ts.getDirectoryPath(currentPath); - while (currentPath != parentPath) { - if (!project.projectService.directoryWatchersForTsconfig[currentPath]) { - this.log("Add watcher for: " + currentPath); - project.projectService.directoryWatchersForTsconfig[currentPath] = - this.host.watchDirectory(currentPath, function (fileName) { return _this.directoryWatchedForTsconfigChanged(fileName); }); - project.projectService.directoryWatchersRefCount[currentPath] = 1; - } - else { - project.projectService.directoryWatchersRefCount[currentPath] += 1; - } - project.directoriesWatchedForTsconfig.push(currentPath); - currentPath = parentPath; - parentPath = ts.getDirectoryPath(parentPath); - } - project.finishGraph(); - this.inferredProjects.push(project); - return project; - }; - ProjectService.prototype.fileDeletedInFilesystem = function (info) { - this.psLogger.info(info.fileName + " deleted"); - if (info.fileWatcher) { - info.fileWatcher.close(); - info.fileWatcher = undefined; - } - if (!info.isOpen) { - this.filenameToScriptInfo[info.fileName] = undefined; - var referencingProjects = this.findReferencingProjects(info); - if (info.defaultProject) { - info.defaultProject.removeRoot(info); - } - for (var i = 0, len = referencingProjects.length; i < len; i++) { - referencingProjects[i].removeReferencedFile(info); - } - for (var j = 0, flen = this.openFileRoots.length; j < flen; j++) { - var openFile = this.openFileRoots[j]; - if (this.eventHandler) { - this.eventHandler({ eventName: "context", data: { project: openFile.defaultProject, fileName: openFile.fileName } }); - } - } - for (var j = 0, flen = this.openFilesReferenced.length; j < flen; j++) { - var openFile = this.openFilesReferenced[j]; - if (this.eventHandler) { - this.eventHandler({ eventName: "context", data: { project: openFile.defaultProject, fileName: openFile.fileName } }); - } - } - } - this.printProjects(); - }; - ProjectService.prototype.updateConfiguredProjectList = function () { - var configuredProjects = []; - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - if (this.configuredProjects[i].openRefCount > 0) { - configuredProjects.push(this.configuredProjects[i]); - } - } - this.configuredProjects = configuredProjects; - }; - ProjectService.prototype.removeProject = function (project) { - this.log("remove project: " + project.getRootFiles().toString()); - if (project.isConfiguredProject()) { - project.projectFileWatcher.close(); - project.directoryWatcher.close(); - ts.forEachProperty(project.directoriesWatchedForWildcards, function (watcher) { watcher.close(); }); - delete project.directoriesWatchedForWildcards; - ts.unorderedRemoveItem(this.configuredProjects, project); - } - else { - for (var _i = 0, _a = project.directoriesWatchedForTsconfig; _i < _a.length; _i++) { - var directory = _a[_i]; - project.projectService.directoryWatchersRefCount[directory]--; - if (!project.projectService.directoryWatchersRefCount[directory]) { - this.log("Close directory watcher for: " + directory); - project.projectService.directoryWatchersForTsconfig[directory].close(); - delete project.projectService.directoryWatchersForTsconfig[directory]; - } - } - ts.unorderedRemoveItem(this.inferredProjects, project); - } - var fileNames = project.getFileNames(); - for (var _b = 0, fileNames_3 = fileNames; _b < fileNames_3.length; _b++) { - var fileName = fileNames_3[_b]; - var info = this.getScriptInfo(fileName); - if (info.defaultProject == project) { - info.defaultProject = undefined; - } - } - }; - ProjectService.prototype.setConfiguredProjectRoot = function (info) { - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - var configuredProject = this.configuredProjects[i]; - if (configuredProject.isRoot(info)) { - info.defaultProject = configuredProject; - configuredProject.addOpenRef(); - return true; - } - } - return false; - }; - ProjectService.prototype.addOpenFile = function (info) { - if (this.setConfiguredProjectRoot(info)) { - this.openFileRootsConfigured.push(info); - } - else { - this.findReferencingProjects(info); - if (info.defaultProject) { - info.defaultProject.addOpenRef(); - this.openFilesReferenced.push(info); - } - else { - info.defaultProject = this.createInferredProject(info); - var openFileRoots = []; - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - var r = this.openFileRoots[i]; - if (info.defaultProject.getSourceFile(r)) { - this.removeProject(r.defaultProject); - this.openFilesReferenced.push(r); - r.defaultProject = info.defaultProject; - } - else { - openFileRoots.push(r); - } - } - this.openFileRoots = openFileRoots; - this.openFileRoots.push(info); - } - } - this.updateConfiguredProjectList(); - }; - ProjectService.prototype.closeOpenFile = function (info) { - info.svc.reloadFromFile(info.fileName); - var openFileRoots = []; - var removedProject; - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - if (info === this.openFileRoots[i]) { - removedProject = info.defaultProject; - } - else { - openFileRoots.push(this.openFileRoots[i]); - } - } - this.openFileRoots = openFileRoots; - if (!removedProject) { - var openFileRootsConfigured = []; - for (var i = 0, len = this.openFileRootsConfigured.length; i < len; i++) { - if (info === this.openFileRootsConfigured[i]) { - if (info.defaultProject.deleteOpenRef() === 0) { - removedProject = info.defaultProject; - } - } - else { - openFileRootsConfigured.push(this.openFileRootsConfigured[i]); - } - } - this.openFileRootsConfigured = openFileRootsConfigured; - } - if (removedProject) { - this.removeProject(removedProject); - var openFilesReferenced = []; - var orphanFiles = []; - for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { - var f = this.openFilesReferenced[i]; - if (f.defaultProject === removedProject || !f.defaultProject) { - f.defaultProject = undefined; - orphanFiles.push(f); - } - else { - openFilesReferenced.push(f); - } - } - this.openFilesReferenced = openFilesReferenced; - for (var i = 0, len = orphanFiles.length; i < len; i++) { - this.addOpenFile(orphanFiles[i]); - } - } - else { - ts.unorderedRemoveItem(this.openFilesReferenced, info); - } - info.close(); - }; - ProjectService.prototype.findReferencingProjects = function (info, excludedProject) { - var referencingProjects = []; - info.defaultProject = undefined; - for (var i = 0, len = this.inferredProjects.length; i < len; i++) { - var inferredProject = this.inferredProjects[i]; - inferredProject.updateGraph(); - if (inferredProject !== excludedProject) { - if (inferredProject.getSourceFile(info)) { - info.defaultProject = inferredProject; - referencingProjects.push(inferredProject); - } - } - } - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - var configuredProject = this.configuredProjects[i]; - configuredProject.updateGraph(); - if (configuredProject.getSourceFile(info)) { - info.defaultProject = configuredProject; - referencingProjects.push(configuredProject); - } - } - return referencingProjects; - }; - ProjectService.prototype.reloadProjects = function () { - this.log("reload projects."); - for (var _i = 0, _a = this.openFileRoots; _i < _a.length; _i++) { - var info = _a[_i]; - this.openOrUpdateConfiguredProjectForFile(info.fileName); - } - this.updateProjectStructure(); - }; - ProjectService.prototype.updateProjectStructure = function () { - this.log("updating project structure from ...", "Info"); - this.printProjects(); - var unattachedOpenFiles = []; - var openFileRootsConfigured = []; - for (var _i = 0, _a = this.openFileRootsConfigured; _i < _a.length; _i++) { - var info = _a[_i]; - var project = info.defaultProject; - if (!project || !(project.getSourceFile(info))) { - info.defaultProject = undefined; - unattachedOpenFiles.push(info); - } - else { - openFileRootsConfigured.push(info); - } - } - this.openFileRootsConfigured = openFileRootsConfigured; - var openFilesReferenced = []; - for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { - var referencedFile = this.openFilesReferenced[i]; - referencedFile.defaultProject.updateGraph(); - var sourceFile = referencedFile.defaultProject.getSourceFile(referencedFile); - if (sourceFile) { - openFilesReferenced.push(referencedFile); - } - else { - unattachedOpenFiles.push(referencedFile); - } - } - this.openFilesReferenced = openFilesReferenced; - var openFileRoots = []; - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - var rootFile = this.openFileRoots[i]; - var rootedProject = rootFile.defaultProject; - var referencingProjects = this.findReferencingProjects(rootFile, rootedProject); - if (rootFile.defaultProject && rootFile.defaultProject.isConfiguredProject()) { - if (!rootedProject.isConfiguredProject()) { - this.removeProject(rootedProject); - } - this.openFileRootsConfigured.push(rootFile); - } - else { - if (referencingProjects.length === 0) { - rootFile.defaultProject = rootedProject; - openFileRoots.push(rootFile); - } - else { - this.removeProject(rootedProject); - this.openFilesReferenced.push(rootFile); - } - } - } - this.openFileRoots = openFileRoots; - for (var i = 0, len = unattachedOpenFiles.length; i < len; i++) { - this.addOpenFile(unattachedOpenFiles[i]); - } - this.printProjects(); - }; - ProjectService.prototype.getScriptInfo = function (filename) { - filename = ts.normalizePath(filename); - return this.filenameToScriptInfo[filename]; - }; - ProjectService.prototype.openFile = function (fileName, openedByClient, fileContent, scriptKind) { - var _this = this; - fileName = ts.normalizePath(fileName); - var info = this.filenameToScriptInfo[fileName]; - if (!info) { - var content = void 0; - if (this.host.fileExists(fileName)) { - content = fileContent || this.host.readFile(fileName); - } - if (!content) { - if (openedByClient) { - content = ""; - } - } - if (content !== undefined) { - info = new ScriptInfo(this.host, fileName, content, openedByClient); - info.scriptKind = scriptKind; - info.setFormatOptions(this.getFormatCodeOptions()); - this.filenameToScriptInfo[fileName] = info; - if (!info.isOpen) { - info.fileWatcher = this.host.watchFile(fileName, function (_) { _this.watchedFileChanged(fileName); }); - } - } - } - if (info) { - if (fileContent) { - info.svc.reload(fileContent); - } - if (openedByClient) { - info.isOpen = true; - } - } - return info; - }; - ProjectService.prototype.findConfigFile = function (searchPath) { - while (true) { - var tsconfigFileName = ts.combinePaths(searchPath, "tsconfig.json"); - if (this.host.fileExists(tsconfigFileName)) { - return tsconfigFileName; - } - var jsconfigFileName = ts.combinePaths(searchPath, "jsconfig.json"); - if (this.host.fileExists(jsconfigFileName)) { - return jsconfigFileName; - } - var parentPath = ts.getDirectoryPath(searchPath); - if (parentPath === searchPath) { - break; - } - searchPath = parentPath; - } - return undefined; - }; - ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind) { - var _a = this.openOrUpdateConfiguredProjectForFile(fileName), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; - var info = this.openFile(fileName, true, fileContent, scriptKind); - this.addOpenFile(info); - this.printProjects(); - return { configFileName: configFileName, configFileErrors: configFileErrors }; - }; - ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName) { - var searchPath = ts.normalizePath(ts.getDirectoryPath(fileName)); - this.log("Search path: " + searchPath, "Info"); - var configFileName = this.findConfigFile(searchPath); - if (configFileName) { - this.log("Config file name: " + configFileName, "Info"); - var project = this.findConfiguredProjectByConfigFile(configFileName); - if (!project) { - var configResult = this.openConfigFile(configFileName, fileName); - if (!configResult.project) { - return { configFileName: configFileName, configFileErrors: configResult.errors }; - } - else { - this.log("Opened configuration file " + configFileName, "Info"); - this.configuredProjects.push(configResult.project); - if (configResult.errors && configResult.errors.length > 0) { - return { configFileName: configFileName, configFileErrors: configResult.errors }; - } - } - } - else { - this.updateConfiguredProject(project); - } - return { configFileName: configFileName }; - } - else { - this.log("No config files found."); - } - return {}; - }; - ProjectService.prototype.closeClientFile = function (filename) { - var info = this.filenameToScriptInfo[filename]; - if (info) { - this.closeOpenFile(info); - info.isOpen = false; - } - this.printProjects(); - }; - ProjectService.prototype.getProjectForFile = function (filename) { - var scriptInfo = this.filenameToScriptInfo[filename]; - if (scriptInfo) { - return scriptInfo.defaultProject; - } - }; - ProjectService.prototype.printProjectsForFile = function (filename) { - var scriptInfo = this.filenameToScriptInfo[filename]; - if (scriptInfo) { - this.psLogger.startGroup(); - this.psLogger.info("Projects for " + filename); - var projects = this.findReferencingProjects(scriptInfo); - for (var i = 0, len = projects.length; i < len; i++) { - this.psLogger.info("Project " + i.toString()); - } - this.psLogger.endGroup(); - } - else { - this.psLogger.info(filename + " not in any project"); - } - }; - ProjectService.prototype.printProjects = function () { - if (!this.psLogger.isVerbose()) { - return; - } - this.psLogger.startGroup(); - for (var i = 0, len = this.inferredProjects.length; i < len; i++) { - var project = this.inferredProjects[i]; - project.updateGraph(); - this.psLogger.info("Project " + i.toString()); - this.psLogger.info(project.filesToString()); - this.psLogger.info("-----------------------------------------------"); - } - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - var project = this.configuredProjects[i]; - project.updateGraph(); - this.psLogger.info("Project (configured) " + (i + this.inferredProjects.length).toString()); - this.psLogger.info(project.filesToString()); - this.psLogger.info("-----------------------------------------------"); - } - this.psLogger.info("Open file roots of inferred projects: "); - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - this.psLogger.info(this.openFileRoots[i].fileName); - } - this.psLogger.info("Open files referenced by inferred or configured projects: "); - for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { - var fileInfo = this.openFilesReferenced[i].fileName; - if (this.openFilesReferenced[i].defaultProject.isConfiguredProject()) { - fileInfo += " (configured)"; - } - this.psLogger.info(fileInfo); - } - this.psLogger.info("Open file roots of configured projects: "); - for (var i = 0, len = this.openFileRootsConfigured.length; i < len; i++) { - this.psLogger.info(this.openFileRootsConfigured[i].fileName); - } - this.psLogger.endGroup(); - }; - ProjectService.prototype.configProjectIsActive = function (fileName) { - return this.findConfiguredProjectByConfigFile(fileName) === undefined; - }; - ProjectService.prototype.findConfiguredProjectByConfigFile = function (configFileName) { - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - if (this.configuredProjects[i].projectFilename == configFileName) { - return this.configuredProjects[i]; - } - } - return undefined; - }; - ProjectService.prototype.configFileToProjectOptions = function (configFilename) { - configFilename = ts.normalizePath(configFilename); - var errors = []; - var dirPath = ts.getDirectoryPath(configFilename); - var contents = this.host.readFile(configFilename); - var _a = ts.parseAndReEmitConfigJSONFile(contents), configJsonObject = _a.configJsonObject, diagnostics = _a.diagnostics; - errors = ts.concatenate(errors, diagnostics); - var parsedCommandLine = ts.parseJsonConfigFileContent(configJsonObject, this.host, dirPath, {}, configFilename); - errors = ts.concatenate(errors, parsedCommandLine.errors); - ts.Debug.assert(!!parsedCommandLine.fileNames); - if (parsedCommandLine.fileNames.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); - return { errors: errors }; - } - else { - var projectOptions = { - files: parsedCommandLine.fileNames, - wildcardDirectories: parsedCommandLine.wildcardDirectories, - compilerOptions: parsedCommandLine.options - }; - return { projectOptions: projectOptions, errors: errors }; - } - }; - ProjectService.prototype.exceedTotalNonTsFileSizeLimit = function (fileNames) { - var totalNonTsFileSize = 0; - if (!this.host.getFileSize) { - return false; - } - for (var _i = 0, fileNames_4 = fileNames; _i < fileNames_4.length; _i++) { - var fileName = fileNames_4[_i]; - if (ts.hasTypeScriptFileExtension(fileName)) { - continue; - } - totalNonTsFileSize += this.host.getFileSize(fileName); - if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) { - return true; - } - } - return false; - }; - ProjectService.prototype.openConfigFile = function (configFilename, clientFileName) { - var _this = this; - var parseConfigFileResult = this.configFileToProjectOptions(configFilename); - var errors = parseConfigFileResult.errors; - if (!parseConfigFileResult.projectOptions) { - return { errors: errors }; - } - var projectOptions = parseConfigFileResult.projectOptions; - if (!projectOptions.compilerOptions.disableSizeLimit && projectOptions.compilerOptions.allowJs) { - if (this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { - var project_1 = this.createProject(configFilename, projectOptions, true); - project_1.projectFileWatcher = this.host.watchFile(ts.toPath(configFilename, configFilename, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), function (_) { return _this.watchedProjectConfigFileChanged(project_1); }); - return { project: project_1, errors: errors }; - } - } - var project = this.createProject(configFilename, projectOptions); - for (var _i = 0, _a = projectOptions.files; _i < _a.length; _i++) { - var rootFilename = _a[_i]; - if (this.host.fileExists(rootFilename)) { - var info = this.openFile(rootFilename, clientFileName == rootFilename); - project.addRoot(info); - } - else { - (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, rootFilename)); - } - } - project.finishGraph(); - project.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project); }); - var configDirectoryPath = ts.getDirectoryPath(configFilename); - this.log("Add recursive watcher for: " + configDirectoryPath); - project.directoryWatcher = this.host.watchDirectory(configDirectoryPath, function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true); - project.directoriesWatchedForWildcards = ts.reduceProperties(ts.createMap(projectOptions.wildcardDirectories), function (watchers, flag, directory) { - if (ts.comparePaths(configDirectoryPath, directory, ".", !_this.host.useCaseSensitiveFileNames) !== 0) { - var recursive = (flag & 1) !== 0; - _this.log("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); - watchers[directory] = _this.host.watchDirectory(directory, function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, recursive); - } - return watchers; - }, {}); - return { project: project, errors: errors }; - }; - ProjectService.prototype.updateConfiguredProject = function (project) { - var _this = this; - if (!this.host.fileExists(project.projectFilename)) { - this.log("Config file deleted"); - this.removeProject(project); - } - else { - var _a = this.configFileToProjectOptions(project.projectFilename), projectOptions = _a.projectOptions, errors = _a.errors; - if (!projectOptions) { - return errors; - } - else { - if (projectOptions.compilerOptions && !projectOptions.compilerOptions.disableSizeLimit && this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { - project.setProjectOptions(projectOptions); - if (project.languageServiceDiabled) { - return errors; - } - project.disableLanguageService(); - if (project.directoryWatcher) { - project.directoryWatcher.close(); - project.directoryWatcher = undefined; - } - return errors; - } - if (project.languageServiceDiabled) { - project.setProjectOptions(projectOptions); - project.enableLanguageService(); - project.directoryWatcher = this.host.watchDirectory(ts.getDirectoryPath(project.projectFilename), function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true); - for (var _i = 0, _b = projectOptions.files; _i < _b.length; _i++) { - var rootFilename = _b[_i]; - if (this.host.fileExists(rootFilename)) { - var info = this.openFile(rootFilename, false); - project.addRoot(info); - } - } - project.finishGraph(); - return errors; - } - var oldFileNames_1 = project.projectOptions ? project.projectOptions.files : project.compilerService.host.roots.map(function (info) { return info.fileName; }); - var newFileNames_1 = ts.filter(projectOptions.files, function (f) { return _this.host.fileExists(f); }); - var fileNamesToRemove = oldFileNames_1.filter(function (f) { return newFileNames_1.indexOf(f) < 0; }); - var fileNamesToAdd = newFileNames_1.filter(function (f) { return oldFileNames_1.indexOf(f) < 0; }); - for (var _c = 0, fileNamesToRemove_1 = fileNamesToRemove; _c < fileNamesToRemove_1.length; _c++) { - var fileName = fileNamesToRemove_1[_c]; - var info = this.getScriptInfo(fileName); - if (info) { - project.removeRoot(info); - } - } - for (var _d = 0, fileNamesToAdd_1 = fileNamesToAdd; _d < fileNamesToAdd_1.length; _d++) { - var fileName = fileNamesToAdd_1[_d]; - var info = this.getScriptInfo(fileName); - if (!info) { - info = this.openFile(fileName, false); - } - else { - if (info.isOpen) { - if (this.openFileRoots.indexOf(info) >= 0) { - ts.unorderedRemoveItem(this.openFileRoots, info); - if (info.defaultProject && !info.defaultProject.isConfiguredProject()) { - this.removeProject(info.defaultProject); - } - } - if (this.openFilesReferenced.indexOf(info) >= 0) { - ts.unorderedRemoveItem(this.openFilesReferenced, info); - } - this.openFileRootsConfigured.push(info); - info.defaultProject = project; - } - } - project.addRoot(info); - } - project.setProjectOptions(projectOptions); - project.finishGraph(); - } - return errors; - } - }; - ProjectService.prototype.createProject = function (projectFilename, projectOptions, languageServiceDisabled) { - var project = new Project(this, projectOptions, languageServiceDisabled); - project.projectFilename = projectFilename; - return project; - }; - return ProjectService; - }()); - server.ProjectService = ProjectService; - var CompilerService = (function () { - function CompilerService(project, opt) { - this.project = project; - this.documentRegistry = ts.createDocumentRegistry(); - this.host = new LSHost(project.projectService.host, project); - if (opt) { - this.setCompilerOptions(opt); - } - else { - var defaultOpts = ts.getDefaultCompilerOptions(); - defaultOpts.allowNonTsExtensions = true; - defaultOpts.allowJs = true; - this.setCompilerOptions(defaultOpts); - } - this.languageService = ts.createLanguageService(this.host, this.documentRegistry); - this.classifier = ts.createClassifier(); - } - CompilerService.prototype.setCompilerOptions = function (opt) { - this.settings = opt; - this.host.setCompilationSettings(opt); - }; - CompilerService.prototype.isExternalModule = function (filename) { - var sourceFile = this.languageService.getNonBoundSourceFile(filename); - return ts.isExternalModule(sourceFile); - }; - CompilerService.getDefaultFormatCodeOptions = function (host) { - return ts.clone({ - BaseIndentSize: 0, - IndentSize: 4, - TabSize: 4, - NewLineCharacter: host.newLine || "\n", - ConvertTabsToSpaces: true, - IndentStyle: ts.IndentStyle.Smart, - InsertSpaceAfterCommaDelimiter: true, - InsertSpaceAfterSemicolonInForStatements: true, - InsertSpaceBeforeAndAfterBinaryOperators: true, - InsertSpaceAfterKeywordsInControlFlowStatements: true, - InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false, - InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, - InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, - InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, - InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, - InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, - InsertSpaceAfterTypeAssertion: false, - PlaceOpenBraceOnNewLineForFunctions: false, - PlaceOpenBraceOnNewLineForControlBlocks: false - }); - }; - return CompilerService; - }()); - server.CompilerService = CompilerService; (function (CharRangeSection) { CharRangeSection[CharRangeSection["PreStart"] = 0] = "PreStart"; CharRangeSection[CharRangeSection["Start"] = 1] = "Start"; @@ -62605,16 +64797,17 @@ var ts; var EditWalker = (function (_super) { __extends(EditWalker, _super); function EditWalker() { - _super.call(this); - this.lineIndex = new LineIndex(); - this.endBranch = []; - this.state = CharRangeSection.Entire; - this.initialText = ""; - this.trailingText = ""; - this.suppressTrailingText = false; - this.lineIndex.root = new LineNode(); - this.startPath = [this.lineIndex.root]; - this.stack = [this.lineIndex.root]; + var _this = _super.call(this) || this; + _this.lineIndex = new LineIndex(); + _this.endBranch = []; + _this.state = CharRangeSection.Entire; + _this.initialText = ""; + _this.trailingText = ""; + _this.suppressTrailingText = false; + _this.lineIndex.root = new LineNode(); + _this.startPath = [_this.lineIndex.root]; + _this.stack = [_this.lineIndex.root]; + return _this; } EditWalker.prototype.insertLines = function (insertedText) { if (this.suppressTrailingText) { @@ -62801,10 +64994,19 @@ var ts; var ScriptVersionCache = (function () { function ScriptVersionCache() { this.changes = []; - this.versions = []; + this.versions = new Array(ScriptVersionCache.maxVersions); this.minVersion = 0; this.currentVersion = 0; } + ScriptVersionCache.prototype.versionToIndex = function (version) { + if (version < this.minVersion || version > this.currentVersion) { + return undefined; + } + return version % ScriptVersionCache.maxVersions; + }; + ScriptVersionCache.prototype.currentVersionToIndex = function () { + return this.currentVersion % ScriptVersionCache.maxVersions; + }; ScriptVersionCache.prototype.edit = function (pos, deleteLen, insertedText) { this.changes[this.changes.length] = new TextChange(pos, deleteLen, insertedText); if ((this.changes.length > ScriptVersionCache.changeNumberThreshold) || @@ -62814,7 +65016,7 @@ var ts; } }; ScriptVersionCache.prototype.latest = function () { - return this.versions[this.currentVersion]; + return this.versions[this.currentVersionToIndex()]; }; ScriptVersionCache.prototype.latestVersion = function () { if (this.changes.length > 0) { @@ -62822,32 +65024,30 @@ var ts; } return this.currentVersion; }; - ScriptVersionCache.prototype.reloadFromFile = function (filename, cb) { + ScriptVersionCache.prototype.reloadFromFile = function (filename) { var content = this.host.readFile(filename); if (!content) { content = ""; } this.reload(content); - if (cb) - cb(); }; ScriptVersionCache.prototype.reload = function (script) { this.currentVersion++; this.changes = []; var snap = new LineIndexSnapshot(this.currentVersion, this); - this.versions[this.currentVersion] = snap; + for (var i = 0; i < this.versions.length; i++) { + this.versions[i] = undefined; + } + this.versions[this.currentVersionToIndex()] = snap; snap.index = new LineIndex(); var lm = LineIndex.linesFromText(script); snap.index.load(lm.lines); - for (var i = this.minVersion; i < this.currentVersion; i++) { - this.versions[i] = undefined; - } this.minVersion = this.currentVersion; }; ScriptVersionCache.prototype.getSnapshot = function () { - var snap = this.versions[this.currentVersion]; + var snap = this.versions[this.currentVersionToIndex()]; if (this.changes.length > 0) { - var snapIndex = this.latest().index; + var snapIndex = snap.index; for (var i = 0, len = this.changes.length; i < len; i++) { var change = this.changes[i]; snapIndex = snapIndex.edit(change.pos, change.deleteLen, change.insertedText); @@ -62856,14 +65056,10 @@ var ts; snap.index = snapIndex; snap.changesSincePreviousVersion = this.changes; this.currentVersion = snap.version; - this.versions[snap.version] = snap; + this.versions[this.currentVersionToIndex()] = snap; this.changes = []; if ((this.currentVersion - this.minVersion) >= ScriptVersionCache.maxVersions) { - var oldMin = this.minVersion; this.minVersion = (this.currentVersion - ScriptVersionCache.maxVersions) + 1; - for (var j = oldMin; j < this.minVersion; j++) { - this.versions[j] = undefined; - } } } return snap; @@ -62873,7 +65069,7 @@ var ts; if (oldVersion >= this.minVersion) { var textChangeRanges = []; for (var i = oldVersion + 1; i <= newVersion; i++) { - var snap = this.versions[i]; + var snap = this.versions[this.versionToIndex(i)]; for (var j = 0, len = snap.changesSincePreviousVersion.length; j < len; j++) { var textChange = snap.changesSincePreviousVersion[j]; textChangeRanges[textChangeRanges.length] = textChange.getTextChangeRange(); @@ -63011,7 +65207,7 @@ var ts; done: false, leaf: function (relativeStart, relativeLength, ll) { if (!f(ll, relativeStart, relativeLength)) { - walkFns.done = true; + this.done = true; } } }; @@ -63024,7 +65220,7 @@ var ts; return source.substring(0, s) + nt + source.substring(s + dl, source.length); } if (this.root.charCount() === 0) { - if (newText) { + if (newText !== undefined) { this.load(LineIndex.linesFromText(newText).lines); return this; } @@ -63404,12 +65600,6 @@ var ts; function LineLeaf(text) { this.text = text; } - LineLeaf.prototype.setUdata = function (data) { - this.udata = data; - }; - LineLeaf.prototype.getUdata = function () { - return this.udata; - }; LineLeaf.prototype.isLeaf = function () { return true; }; @@ -63431,6 +65621,25 @@ var ts; (function (ts) { var server; (function (server) { + var net = require("net"); + var childProcess = require("child_process"); + var os = require("os"); + function getGlobalTypingsCacheLocation() { + var basePath; + switch (process.platform) { + case "win32": + basePath = process.env.LOCALAPPDATA || process.env.APPDATA || os.homedir(); + break; + case "linux": + basePath = os.homedir(); + break; + case "darwin": + basePath = ts.combinePaths(os.homedir(), "Library/Application Support/"); + break; + } + ts.Debug.assert(basePath !== undefined); + return ts.combinePaths(ts.normalizeSlashes(basePath), "Microsoft/TypeScript"); + } var readline = require("readline"); var fs = require("fs"); var rl = readline.createInterface({ @@ -63439,8 +65648,9 @@ var ts; terminal: false }); var Logger = (function () { - function Logger(logFilename, level) { + function Logger(logFilename, traceToConsole, level) { this.logFilename = logFilename; + this.traceToConsole = traceToConsole; this.level = level; this.fd = -1; this.seq = 0; @@ -63455,11 +65665,14 @@ var ts; fs.close(this.fd); } }; + Logger.prototype.getLogFileName = function () { + return this.logFilename; + }; Logger.prototype.perftrc = function (s) { - this.msg(s, "Perf"); + this.msg(s, server.Msg.Perf); }; Logger.prototype.info = function (s) { - this.msg(s, "Info"); + this.msg(s, server.Msg.Info); }; Logger.prototype.startGroup = function () { this.inGroup = true; @@ -63471,19 +65684,19 @@ var ts; this.firstInGroup = true; }; Logger.prototype.loggingEnabled = function () { - return !!this.logFilename; + return !!this.logFilename || this.traceToConsole; }; - Logger.prototype.isVerbose = function () { - return this.loggingEnabled() && (this.level == "verbose"); + Logger.prototype.hasLevel = function (level) { + return this.loggingEnabled() && this.level >= level; }; Logger.prototype.msg = function (s, type) { - if (type === void 0) { type = "Err"; } + if (type === void 0) { type = server.Msg.Err; } if (this.fd < 0) { if (this.logFilename) { this.fd = fs.openSync(this.logFilename, "w"); } } - if (this.fd >= 0) { + if (this.fd >= 0 || this.traceToConsole) { s = s + "\n"; var prefix = Logger.padStringRight(type + " " + this.seq.toString(), " "); if (this.firstInGroup) { @@ -63494,19 +65707,88 @@ var ts; this.seq++; this.firstInGroup = true; } - var buf = new Buffer(s); - fs.writeSync(this.fd, buf, 0, buf.length, null); + if (this.fd >= 0) { + var buf = new Buffer(s); + fs.writeSync(this.fd, buf, 0, buf.length, null); + } + if (this.traceToConsole) { + console.warn(s); + } } }; return Logger; }()); + var NodeTypingsInstaller = (function () { + function NodeTypingsInstaller(logger, eventPort, globalTypingsCacheLocation, newLine) { + var _this = this; + this.logger = logger; + this.eventPort = eventPort; + this.globalTypingsCacheLocation = globalTypingsCacheLocation; + this.newLine = newLine; + if (eventPort) { + var s_1 = net.connect({ port: eventPort }, function () { + _this.socket = s_1; + }); + } + } + NodeTypingsInstaller.prototype.attach = function (projectService) { + var _this = this; + this.projectService = projectService; + if (this.logger.hasLevel(server.LogLevel.requestTime)) { + this.logger.info("Binding..."); + } + var args = ["--globalTypingsCacheLocation", this.globalTypingsCacheLocation]; + if (this.logger.loggingEnabled() && this.logger.getLogFileName()) { + args.push("--logFile", ts.combinePaths(ts.getDirectoryPath(ts.normalizeSlashes(this.logger.getLogFileName())), "ti-" + process.pid + ".log")); + } + var execArgv = []; + { + for (var _i = 0, _a = process.execArgv; _i < _a.length; _i++) { + var arg = _a[_i]; + var match = /^--(debug|inspect)(=(\d+))?$/.exec(arg); + if (match) { + var currentPort = match[3] !== undefined + ? +match[3] + : match[1] === "debug" ? 5858 : 9229; + execArgv.push("--" + match[1] + "=" + (currentPort + 1)); + break; + } + } + } + this.installer = childProcess.fork(ts.combinePaths(__dirname, "typingsInstaller.js"), args, { execArgv: execArgv }); + this.installer.on("message", function (m) { return _this.handleMessage(m); }); + process.on("exit", function () { + _this.installer.kill(); + }); + }; + NodeTypingsInstaller.prototype.onProjectClosed = function (p) { + this.installer.send({ projectName: p.getProjectName(), kind: "closeProject" }); + }; + NodeTypingsInstaller.prototype.enqueueInstallTypingsRequest = function (project, typingOptions) { + var request = server.createInstallTypingsRequest(project, typingOptions); + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Sending request: " + JSON.stringify(request)); + } + this.installer.send(request); + }; + NodeTypingsInstaller.prototype.handleMessage = function (response) { + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Received response: " + JSON.stringify(response)); + } + this.projectService.updateTypingsForProject(response); + if (response.kind == "set" && this.socket) { + this.socket.write(server.formatMessage({ seq: 0, type: "event", message: response }, this.logger, Buffer.byteLength, this.newLine), "utf8"); + } + }; + return NodeTypingsInstaller; + }()); var IOSession = (function (_super) { __extends(IOSession, _super); - function IOSession(host, logger) { - _super.call(this, host, Buffer.byteLength, process.hrtime, logger); + function IOSession(host, cancellationToken, installerEventPort, canUseEvents, useSingleInferredProject, globalTypingsCacheLocation, logger) { + return _super.call(this, host, cancellationToken, useSingleInferredProject, new NodeTypingsInstaller(logger, installerEventPort, globalTypingsCacheLocation, host.newLine), Buffer.byteLength, process.hrtime, logger, canUseEvents) || this; } IOSession.prototype.exit = function () { - this.projectService.log("Exiting...", "Info"); + this.logger.info("Exiting..."); this.projectService.closeLog(); process.exit(0); }; @@ -63523,7 +65805,7 @@ var ts; return IOSession; }(server.Session)); function parseLoggingEnvironmentString(logEnvStr) { - var logEnv = {}; + var logEnv = { logToFile: true }; var args = logEnvStr.split(" "); for (var i = 0, len = args.length; i < (len - 1); i += 2) { var option = args[i]; @@ -63531,10 +65813,17 @@ var ts; if (option && value) { switch (option) { case "-file": - logEnv.file = value; + logEnv.file = ts.stripQuotes(value); break; case "-level": - logEnv.detailLevel = value; + var level = server.LogLevel[value]; + logEnv.detailLevel = typeof level === "number" ? level : server.LogLevel.normal; + break; + case "-traceToConsole": + logEnv.traceToConsole = value.toLowerCase() === "true"; + break; + case "-logToFile": + logEnv.logToFile = value.toLowerCase() === "true"; break; } } @@ -63543,21 +65832,25 @@ var ts; } function createLoggerFromEnv() { var fileName = undefined; - var detailLevel = "normal"; + var detailLevel = server.LogLevel.normal; + var traceToConsole = false; var logEnvStr = process.env["TSS_LOG"]; if (logEnvStr) { var logEnv = parseLoggingEnvironmentString(logEnvStr); - if (logEnv.file) { - fileName = logEnv.file; - } - else { - fileName = __dirname + "/.log" + process.pid.toString(); + if (logEnv.logToFile) { + if (logEnv.file) { + fileName = logEnv.file; + } + else { + fileName = __dirname + "/.log" + process.pid.toString(); + } } if (logEnv.detailLevel) { detailLevel = logEnv.detailLevel; } + traceToConsole = logEnv.traceToConsole; } - return new Logger(fileName, detailLevel); + return new Logger(fileName, traceToConsole, detailLevel); } function createPollingWatchedFileSet(interval, chunkSize) { if (interval === void 0) { interval = 2500; } @@ -63629,13 +65922,13 @@ var ts; var logger = createLoggerFromEnv(); var pending = []; var canWrite = true; - function writeMessage(s) { + function writeMessage(buf) { if (!canWrite) { - pending.push(s); + pending.push(buf); } else { canWrite = false; - process.stdout.write(new Buffer(s, "utf8"), setCanWriteFlagAndWriteMessageIfNecessary); + process.stdout.write(buf, setCanWriteFlagAndWriteMessageIfNecessary); } } function setCanWriteFlagAndWriteMessageIfNecessary() { @@ -63645,7 +65938,7 @@ var ts; } } var sys = ts.sys; - sys.write = function (s) { return writeMessage(s); }; + sys.write = function (s) { return writeMessage(new Buffer(s, "utf8")); }; sys.watchFile = function (fileName, callback) { var watchedFile = pollingWatchedFileSet.addFile(fileName, callback); return { @@ -63654,14 +65947,42 @@ var ts; }; sys.setTimeout = setTimeout; sys.clearTimeout = clearTimeout; - var ioSession = new IOSession(sys, logger); + sys.setImmediate = setImmediate; + sys.clearImmediate = clearImmediate; + if (typeof global !== "undefined" && global.gc) { + sys.gc = function () { return global.gc(); }; + } + var cancellationToken; + try { + var factory = require("./cancellationToken"); + cancellationToken = factory(sys.args); + } + catch (e) { + cancellationToken = { + isCancellationRequested: function () { return false; } + }; + } + ; + var eventPort; + { + var index = sys.args.indexOf("--eventPort"); + if (index >= 0 && index < sys.args.length - 1) { + var v = parseInt(sys.args[index + 1]); + if (!isNaN(v)) { + eventPort = v; + } + } + } + var useSingleInferredProject = sys.args.indexOf("--useSingleInferredProject") >= 0; + var ioSession = new IOSession(sys, cancellationToken, eventPort, eventPort === undefined, useSingleInferredProject, getGlobalTypingsCacheLocation(), logger); process.on("uncaughtException", function (err) { ioSession.logError(err, "unknown"); }); + process.noAsar = true; ioSession.listen(); })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); -var debugObjectHost = new Function("return this")(); +var debugObjectHost = (function () { return this; })(); var ts; (function (ts) { function logInternalError(logger, err) { @@ -63739,6 +66060,12 @@ var ts; } return this.shimHost.getProjectVersion(); }; + LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () { + if (!this.shimHost.getTypeRootsVersion) { + return 0; + } + return this.shimHost.getTypeRootsVersion(); + }; LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; }; @@ -63932,11 +66259,12 @@ var ts; var LanguageServiceShimObject = (function (_super) { __extends(LanguageServiceShimObject, _super); function LanguageServiceShimObject(factory, host, languageService) { - _super.call(this, factory); - this.host = host; - this.languageService = languageService; - this.logPerformance = false; - this.logger = this.host; + var _this = _super.call(this, factory) || this; + _this.host = host; + _this.languageService = languageService; + _this.logPerformance = false; + _this.logger = _this.host; + return _this; } LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); @@ -64115,6 +66443,10 @@ var ts; var _this = this; return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; + LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); }); + }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); @@ -64139,10 +66471,11 @@ var ts; var ClassifierShimObject = (function (_super) { __extends(ClassifierShimObject, _super); function ClassifierShimObject(factory, logger) { - _super.call(this, factory); - this.logger = logger; - this.logPerformance = false; - this.classifier = ts.createClassifier(); + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.logPerformance = false; + _this.classifier = ts.createClassifier(); + return _this; } ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { var _this = this; @@ -64164,10 +66497,11 @@ var ts; var CoreServicesShimObject = (function (_super) { __extends(CoreServicesShimObject, _super); function CoreServicesShimObject(factory, logger, host) { - _super.call(this, factory); - this.logger = logger; - this.host = host; - this.logPerformance = false; + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.host = host; + _this.logPerformance = false; + return _this; } CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 7ed6595bc80..c23bccf0a68 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -1,4 +1,700 @@ -/// +/// +/// +declare namespace ts.server.protocol { + namespace CommandTypes { + type Brace = "brace"; + type BraceFull = "brace-full"; + type BraceCompletion = "braceCompletion"; + type Change = "change"; + type Close = "close"; + type Completions = "completions"; + type CompletionsFull = "completions-full"; + type CompletionDetails = "completionEntryDetails"; + type CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; + type CompileOnSaveEmitFile = "compileOnSaveEmitFile"; + type Configure = "configure"; + type Definition = "definition"; + type DefinitionFull = "definition-full"; + type Implementation = "implementation"; + type ImplementationFull = "implementation-full"; + type Exit = "exit"; + type Format = "format"; + type Formatonkey = "formatonkey"; + type FormatFull = "format-full"; + type FormatonkeyFull = "formatonkey-full"; + type FormatRangeFull = "formatRange-full"; + type Geterr = "geterr"; + type GeterrForProject = "geterrForProject"; + type SemanticDiagnosticsSync = "semanticDiagnosticsSync"; + type SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; + type NavBar = "navbar"; + type NavBarFull = "navbar-full"; + type Navto = "navto"; + type NavtoFull = "navto-full"; + type NavTree = "navtree"; + type NavTreeFull = "navtree-full"; + type Occurrences = "occurrences"; + type DocumentHighlights = "documentHighlights"; + type DocumentHighlightsFull = "documentHighlights-full"; + type Open = "open"; + type Quickinfo = "quickinfo"; + type QuickinfoFull = "quickinfo-full"; + type References = "references"; + type ReferencesFull = "references-full"; + type Reload = "reload"; + type Rename = "rename"; + type RenameInfoFull = "rename-full"; + type RenameLocationsFull = "renameLocations-full"; + type Saveto = "saveto"; + type SignatureHelp = "signatureHelp"; + type SignatureHelpFull = "signatureHelp-full"; + type TypeDefinition = "typeDefinition"; + type ProjectInfo = "projectInfo"; + type ReloadProjects = "reloadProjects"; + type Unknown = "unknown"; + type OpenExternalProject = "openExternalProject"; + type OpenExternalProjects = "openExternalProjects"; + type CloseExternalProject = "closeExternalProject"; + type SynchronizeProjectList = "synchronizeProjectList"; + type ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; + type EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; + type Cleanup = "cleanup"; + type OutliningSpans = "outliningSpans"; + type TodoComments = "todoComments"; + type Indentation = "indentation"; + type DocCommentTemplate = "docCommentTemplate"; + type CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; + type NameOrDottedNameSpan = "nameOrDottedNameSpan"; + type BreakpointStatement = "breakpointStatement"; + type CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; + type GetCodeFixes = "getCodeFixes"; + type GetCodeFixesFull = "getCodeFixes-full"; + type GetSupportedCodeFixes = "getSupportedCodeFixes"; + } + interface Message { + seq: number; + type: string; + } + interface Request extends Message { + command: string; + arguments?: any; + } + interface ReloadProjectsRequest extends Message { + command: CommandTypes.ReloadProjects; + } + interface Event extends Message { + event: string; + body?: any; + } + interface Response extends Message { + request_seq: number; + success: boolean; + command: string; + message?: string; + body?: any; + } + interface FileRequestArgs { + file: string; + projectFileName?: string; + } + interface DocCommentTemplateRequest extends FileLocationRequest { + command: CommandTypes.DocCommentTemplate; + } + interface DocCommandTemplateResponse extends Response { + body?: TextInsertion; + } + interface TodoCommentRequest extends FileRequest { + command: CommandTypes.TodoComments; + arguments: TodoCommentRequestArgs; + } + interface TodoCommentRequestArgs extends FileRequestArgs { + descriptors: TodoCommentDescriptor[]; + } + interface TodoCommentsResponse extends Response { + body?: TodoComment[]; + } + interface OutliningSpansRequest extends FileRequest { + command: CommandTypes.OutliningSpans; + } + interface OutliningSpansResponse extends Response { + body?: OutliningSpan[]; + } + interface IndentationRequest extends FileLocationRequest { + command: CommandTypes.Indentation; + arguments: IndentationRequestArgs; + } + interface IndentationResponse extends Response { + body?: IndentationResult; + } + interface IndentationResult { + position: number; + indentation: number; + } + interface IndentationRequestArgs extends FileLocationRequestArgs { + options?: EditorSettings; + } + interface ProjectInfoRequestArgs extends FileRequestArgs { + needFileNameList: boolean; + } + interface ProjectInfoRequest extends Request { + command: CommandTypes.ProjectInfo; + arguments: ProjectInfoRequestArgs; + } + interface CompilerOptionsDiagnosticsRequest extends Request { + arguments: CompilerOptionsDiagnosticsRequestArgs; + } + interface CompilerOptionsDiagnosticsRequestArgs { + projectFileName: string; + } + interface ProjectInfo { + configFileName: string; + fileNames?: string[]; + languageServiceDisabled?: boolean; + } + interface DiagnosticWithLinePosition { + message: string; + start: number; + length: number; + startLocation: Location; + endLocation: Location; + category: string; + code: number; + } + interface ProjectInfoResponse extends Response { + body?: ProjectInfo; + } + interface FileRequest extends Request { + arguments: FileRequestArgs; + } + interface FileLocationRequestArgs extends FileRequestArgs { + line: number; + offset: number; + position?: number; + } + interface CodeFixRequest extends Request { + command: CommandTypes.GetCodeFixes; + arguments: CodeFixRequestArgs; + } + interface CodeFixRequestArgs extends FileRequestArgs { + startLine: number; + startOffset: number; + startPosition?: number; + endLine: number; + endOffset: number; + endPosition?: number; + errorCodes?: number[]; + } + interface GetCodeFixesResponse extends Response { + body?: CodeAction[]; + } + interface FileLocationRequest extends FileRequest { + arguments: FileLocationRequestArgs; + } + interface GetSupportedCodeFixesRequest extends Request { + command: CommandTypes.GetSupportedCodeFixes; + } + interface GetSupportedCodeFixesResponse extends Response { + body?: string[]; + } + interface EncodedSemanticClassificationsRequest extends FileRequest { + arguments: EncodedSemanticClassificationsRequestArgs; + } + interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { + start: number; + length: number; + } + interface DocumentHighlightsRequestArgs extends FileLocationRequestArgs { + filesToSearch: string[]; + } + interface DefinitionRequest extends FileLocationRequest { + command: CommandTypes.Definition; + } + interface TypeDefinitionRequest extends FileLocationRequest { + command: CommandTypes.TypeDefinition; + } + interface ImplementationRequest extends FileLocationRequest { + command: CommandTypes.Implementation; + } + interface Location { + line: number; + offset: number; + } + interface TextSpan { + start: Location; + end: Location; + } + interface FileSpan extends TextSpan { + file: string; + } + interface DefinitionResponse extends Response { + body?: FileSpan[]; + } + interface TypeDefinitionResponse extends Response { + body?: FileSpan[]; + } + interface ImplementationResponse extends Response { + body?: FileSpan[]; + } + interface BraceCompletionRequest extends FileLocationRequest { + command: CommandTypes.BraceCompletion; + arguments: BraceCompletionRequestArgs; + } + interface BraceCompletionRequestArgs extends FileLocationRequestArgs { + openingBrace: string; + } + interface OccurrencesRequest extends FileLocationRequest { + command: CommandTypes.Occurrences; + } + interface OccurrencesResponseItem extends FileSpan { + isWriteAccess: boolean; + } + interface OccurrencesResponse extends Response { + body?: OccurrencesResponseItem[]; + } + interface DocumentHighlightsRequest extends FileLocationRequest { + command: CommandTypes.DocumentHighlights; + arguments: DocumentHighlightsRequestArgs; + } + interface HighlightSpan extends TextSpan { + kind: string; + } + interface DocumentHighlightsItem { + file: string; + highlightSpans: HighlightSpan[]; + } + interface DocumentHighlightsResponse extends Response { + body?: DocumentHighlightsItem[]; + } + interface ReferencesRequest extends FileLocationRequest { + command: CommandTypes.References; + } + interface ReferencesResponseItem extends FileSpan { + lineText: string; + isWriteAccess: boolean; + isDefinition: boolean; + } + interface ReferencesResponseBody { + refs: ReferencesResponseItem[]; + symbolName: string; + symbolStartOffset: number; + symbolDisplayString: string; + } + interface ReferencesResponse extends Response { + body?: ReferencesResponseBody; + } + interface RenameRequestArgs extends FileLocationRequestArgs { + findInComments?: boolean; + findInStrings?: boolean; + } + interface RenameRequest extends FileLocationRequest { + command: CommandTypes.Rename; + arguments: RenameRequestArgs; + } + interface RenameInfo { + canRename: boolean; + localizedErrorMessage?: string; + displayName: string; + fullDisplayName: string; + kind: string; + kindModifiers: string; + } + interface SpanGroup { + file: string; + locs: TextSpan[]; + } + interface RenameResponseBody { + info: RenameInfo; + locs: SpanGroup[]; + } + interface RenameResponse extends Response { + body?: RenameResponseBody; + } + interface ExternalFile { + fileName: string; + scriptKind?: ScriptKind; + hasMixedContent?: boolean; + content?: string; + } + interface ExternalProject { + projectFileName: string; + rootFiles: ExternalFile[]; + options: ExternalProjectCompilerOptions; + typingOptions?: TypingOptions; + } + interface ExternalProjectCompilerOptions extends CompilerOptions { + compileOnSave?: boolean; + } + interface ProjectVersionInfo { + projectName: string; + isInferred: boolean; + version: number; + options: CompilerOptions; + } + interface ProjectChanges { + added: string[]; + removed: string[]; + } + interface ProjectFiles { + info?: ProjectVersionInfo; + files?: string[]; + changes?: ProjectChanges; + } + interface ProjectFilesWithDiagnostics extends ProjectFiles { + projectErrors: DiagnosticWithLinePosition[]; + } + interface ChangedOpenFile { + fileName: string; + changes: ts.TextChange[]; + } + interface ConfigureRequestArguments { + hostInfo?: string; + file?: string; + formatOptions?: FormatCodeSettings; + } + interface ConfigureRequest extends Request { + command: CommandTypes.Configure; + arguments: ConfigureRequestArguments; + } + interface ConfigureResponse extends Response { + } + interface OpenRequestArgs extends FileRequestArgs { + fileContent?: string; + scriptKindName?: "TS" | "JS" | "TSX" | "JSX"; + } + interface OpenRequest extends Request { + command: CommandTypes.Open; + arguments: OpenRequestArgs; + } + interface OpenExternalProjectRequest extends Request { + command: CommandTypes.OpenExternalProject; + arguments: OpenExternalProjectArgs; + } + type OpenExternalProjectArgs = ExternalProject; + interface OpenExternalProjectsRequest extends Request { + command: CommandTypes.OpenExternalProjects; + arguments: OpenExternalProjectsArgs; + } + interface OpenExternalProjectsArgs { + projects: ExternalProject[]; + } + interface OpenExternalProjectResponse extends Response { + } + interface OpenExternalProjectsResponse extends Response { + } + interface CloseExternalProjectRequest extends Request { + command: CommandTypes.CloseExternalProject; + arguments: CloseExternalProjectRequestArgs; + } + interface CloseExternalProjectRequestArgs { + projectFileName: string; + } + interface CloseExternalProjectResponse extends Response { + } + interface SynchronizeProjectListRequest extends Request { + arguments: SynchronizeProjectListRequestArgs; + } + interface SynchronizeProjectListRequestArgs { + knownProjects: protocol.ProjectVersionInfo[]; + } + interface ApplyChangedToOpenFilesRequest extends Request { + arguments: ApplyChangedToOpenFilesRequestArgs; + } + interface ApplyChangedToOpenFilesRequestArgs { + openFiles?: ExternalFile[]; + changedFiles?: ChangedOpenFile[]; + closedFiles?: string[]; + } + interface SetCompilerOptionsForInferredProjectsRequest extends Request { + command: CommandTypes.CompilerOptionsForInferredProjects; + arguments: SetCompilerOptionsForInferredProjectsArgs; + } + interface SetCompilerOptionsForInferredProjectsArgs { + options: ExternalProjectCompilerOptions; + } + interface SetCompilerOptionsForInferredProjectsResponse extends Response { + } + interface ExitRequest extends Request { + command: CommandTypes.Exit; + } + interface CloseRequest extends FileRequest { + command: CommandTypes.Close; + } + interface CompileOnSaveAffectedFileListRequest extends FileRequest { + command: CommandTypes.CompileOnSaveAffectedFileList; + } + interface CompileOnSaveAffectedFileListSingleProject { + projectFileName: string; + fileNames: string[]; + } + interface CompileOnSaveAffectedFileListResponse extends Response { + body: CompileOnSaveAffectedFileListSingleProject[]; + } + interface CompileOnSaveEmitFileRequest extends FileRequest { + command: CommandTypes.CompileOnSaveEmitFile; + arguments: CompileOnSaveEmitFileRequestArgs; + } + interface CompileOnSaveEmitFileRequestArgs extends FileRequestArgs { + forced?: boolean; + } + interface QuickInfoRequest extends FileLocationRequest { + command: CommandTypes.Quickinfo; + } + interface QuickInfoResponseBody { + kind: string; + kindModifiers: string; + start: Location; + end: Location; + displayString: string; + documentation: string; + } + interface QuickInfoResponse extends Response { + body?: QuickInfoResponseBody; + } + interface FormatRequestArgs extends FileLocationRequestArgs { + endLine: number; + endOffset: number; + endPosition?: number; + options?: FormatCodeSettings; + } + interface FormatRequest extends FileLocationRequest { + command: CommandTypes.Format; + arguments: FormatRequestArgs; + } + interface CodeEdit { + start: Location; + end: Location; + newText: string; + } + interface FileCodeEdits { + fileName: string; + textChanges: CodeEdit[]; + } + interface CodeFixResponse extends Response { + body?: CodeAction[]; + } + interface CodeAction { + description: string; + changes: FileCodeEdits[]; + } + interface FormatResponse extends Response { + body?: CodeEdit[]; + } + interface FormatOnKeyRequestArgs extends FileLocationRequestArgs { + key: string; + options?: FormatCodeSettings; + } + interface FormatOnKeyRequest extends FileLocationRequest { + command: CommandTypes.Formatonkey; + arguments: FormatOnKeyRequestArgs; + } + interface CompletionsRequestArgs extends FileLocationRequestArgs { + prefix?: string; + } + interface CompletionsRequest extends FileLocationRequest { + command: CommandTypes.Completions; + arguments: CompletionsRequestArgs; + } + interface CompletionDetailsRequestArgs extends FileLocationRequestArgs { + entryNames: string[]; + } + interface CompletionDetailsRequest extends FileLocationRequest { + command: CommandTypes.CompletionDetails; + arguments: CompletionDetailsRequestArgs; + } + interface SymbolDisplayPart { + text: string; + kind: string; + } + interface CompletionEntry { + name: string; + kind: string; + kindModifiers: string; + sortText: string; + replacementSpan?: TextSpan; + } + interface CompletionEntryDetails { + name: string; + kind: string; + kindModifiers: string; + displayParts: SymbolDisplayPart[]; + documentation: SymbolDisplayPart[]; + } + interface CompletionsResponse extends Response { + body?: CompletionEntry[]; + } + interface CompletionDetailsResponse extends Response { + body?: CompletionEntryDetails[]; + } + interface SignatureHelpParameter { + name: string; + documentation: SymbolDisplayPart[]; + displayParts: SymbolDisplayPart[]; + isOptional: boolean; + } + interface SignatureHelpItem { + isVariadic: boolean; + prefixDisplayParts: SymbolDisplayPart[]; + suffixDisplayParts: SymbolDisplayPart[]; + separatorDisplayParts: SymbolDisplayPart[]; + parameters: SignatureHelpParameter[]; + documentation: SymbolDisplayPart[]; + } + interface SignatureHelpItems { + items: SignatureHelpItem[]; + applicableSpan: TextSpan; + selectedItemIndex: number; + argumentIndex: number; + argumentCount: number; + } + interface SignatureHelpRequestArgs extends FileLocationRequestArgs { + } + interface SignatureHelpRequest extends FileLocationRequest { + command: CommandTypes.SignatureHelp; + arguments: SignatureHelpRequestArgs; + } + interface SignatureHelpResponse extends Response { + body?: SignatureHelpItems; + } + interface SemanticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SemanticDiagnosticsSync; + arguments: SemanticDiagnosticsSyncRequestArgs; + } + interface SemanticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + interface SemanticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + interface SyntacticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SyntacticDiagnosticsSync; + arguments: SyntacticDiagnosticsSyncRequestArgs; + } + interface SyntacticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + interface SyntacticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + interface GeterrForProjectRequestArgs { + file: string; + delay: number; + } + interface GeterrForProjectRequest extends Request { + command: CommandTypes.GeterrForProject; + arguments: GeterrForProjectRequestArgs; + } + interface GeterrRequestArgs { + files: string[]; + delay: number; + } + interface GeterrRequest extends Request { + command: CommandTypes.Geterr; + arguments: GeterrRequestArgs; + } + interface Diagnostic { + start: Location; + end: Location; + text: string; + code?: number; + } + interface DiagnosticEventBody { + file: string; + diagnostics: Diagnostic[]; + } + interface DiagnosticEvent extends Event { + body?: DiagnosticEventBody; + } + interface ConfigFileDiagnosticEventBody { + triggerFile: string; + configFile: string; + diagnostics: Diagnostic[]; + } + interface ConfigFileDiagnosticEvent extends Event { + body?: ConfigFileDiagnosticEventBody; + event: "configFileDiag"; + } + interface ReloadRequestArgs extends FileRequestArgs { + tmpfile: string; + } + interface ReloadRequest extends FileRequest { + command: CommandTypes.Reload; + arguments: ReloadRequestArgs; + } + interface ReloadResponse extends Response { + } + interface SavetoRequestArgs extends FileRequestArgs { + tmpfile: string; + } + interface SavetoRequest extends FileRequest { + command: CommandTypes.Saveto; + arguments: SavetoRequestArgs; + } + interface NavtoRequestArgs extends FileRequestArgs { + searchValue: string; + maxResultCount?: number; + currentFileOnly?: boolean; + projectFileName?: string; + } + interface NavtoRequest extends FileRequest { + command: CommandTypes.Navto; + arguments: NavtoRequestArgs; + } + interface NavtoItem { + name: string; + kind: string; + matchKind?: string; + isCaseSensitive?: boolean; + kindModifiers?: string; + file: string; + start: Location; + end: Location; + containerName?: string; + containerKind?: string; + } + interface NavtoResponse extends Response { + body?: NavtoItem[]; + } + interface ChangeRequestArgs extends FormatRequestArgs { + insertString?: string; + } + interface ChangeRequest extends FileLocationRequest { + command: CommandTypes.Change; + arguments: ChangeRequestArgs; + } + interface BraceResponse extends Response { + body?: TextSpan[]; + } + interface BraceRequest extends FileLocationRequest { + command: CommandTypes.Brace; + } + interface NavBarRequest extends FileRequest { + command: CommandTypes.NavBar; + } + interface NavTreeRequest extends FileRequest { + command: CommandTypes.NavTree; + } + interface NavigationBarItem { + text: string; + kind: string; + kindModifiers?: string; + spans: TextSpan[]; + childItems?: NavigationBarItem[]; + indent: number; + } + interface NavigationTree { + text: string; + kind: string; + kindModifiers: string; + spans: TextSpan[]; + childItems?: NavigationTree[]; + } + interface NavBarResponse extends Response { + body?: NavigationBarItem[]; + } + interface NavTreeResponse extends Response { + body?: NavigationTree; + } +} declare namespace ts { interface MapLike { [index: string]: T; @@ -15,6 +711,7 @@ declare namespace ts { contains(fileName: Path): boolean; remove(fileName: Path): void; forEachValue(f: (key: Path, v: T) => void): void; + getKeys(): Path[]; clear(): void; } interface TextRange { @@ -374,7 +1071,6 @@ declare namespace ts { ContextFlags = 1540096, TypeExcludesFlags = 327680, } - type ModifiersArray = NodeArray; const enum ModifierFlags { None = 0, Export = 1, @@ -421,19 +1117,24 @@ declare namespace ts { nextContainer?: Node; localSymbol?: Symbol; flowNode?: FlowNode; - transformId?: number; - emitFlags?: NodeEmitFlags; - sourceMapRange?: TextRange; - commentRange?: TextRange; + emitNode?: EmitNode; } interface NodeArray extends Array, TextRange { hasTrailingComma?: boolean; } - interface Token extends Node { - __tokenTag: any; - } - interface Modifier extends Token { + interface Token extends Node { + kind: TKind; } + type DotDotDotToken = Token; + type QuestionToken = Token; + type ColonToken = Token; + type EqualsToken = Token; + type AsteriskToken = Token; + type EqualsGreaterThanToken = Token; + type EndOfFileToken = Token; + type AtToken = Token; + type Modifier = Token | Token | Token | Token | Token | Token | Token | Token | Token | Token | Token; + type ModifiersArray = NodeArray; const enum GeneratedIdentifierKind { None = 0, Auto = 1, @@ -442,6 +1143,7 @@ declare namespace ts { Node = 4, } interface Identifier extends PrimaryExpression { + kind: SyntaxKind.Identifier; text: string; originalKeywordKind?: SyntaxKind; autoGenerateKind?: GeneratedIdentifierKind; @@ -451,6 +1153,7 @@ declare namespace ts { resolvedSymbol: Symbol; } interface QualifiedName extends Node { + kind: SyntaxKind.QualifiedName; left: EntityName; right: Identifier; } @@ -462,15 +1165,18 @@ declare namespace ts { name?: DeclarationName; } interface DeclarationStatement extends Declaration, Statement { - name?: Identifier; + name?: Identifier | LiteralExpression; } interface ComputedPropertyName extends Node { + kind: SyntaxKind.ComputedPropertyName; expression: Expression; } interface Decorator extends Node { + kind: SyntaxKind.Decorator; expression: LeftHandSideExpression; } interface TypeParameterDeclaration extends Declaration { + kind: SyntaxKind.TypeParameter; name: Identifier; constraint?: TypeNode; expression?: Expression; @@ -482,40 +1188,48 @@ declare namespace ts { type?: TypeNode; } interface CallSignatureDeclaration extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.CallSignature; } interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; interface VariableDeclaration extends Declaration { + kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList; name: BindingName; type?: TypeNode; initializer?: Expression; } interface VariableDeclarationList extends Node { + kind: SyntaxKind.VariableDeclarationList; declarations: NodeArray; } interface ParameterDeclaration extends Declaration { - dotDotDotToken?: Node; + kind: SyntaxKind.Parameter; + dotDotDotToken?: DotDotDotToken; name: BindingName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } interface BindingElement extends Declaration { + kind: SyntaxKind.BindingElement; propertyName?: PropertyName; - dotDotDotToken?: Node; + dotDotDotToken?: DotDotDotToken; name: BindingName; initializer?: Expression; } interface PropertySignature extends TypeElement { + kind: SyntaxKind.PropertySignature | SyntaxKind.JSDocRecordMember; name: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } interface PropertyDeclaration extends ClassElement { - questionToken?: Node; + kind: SyntaxKind.PropertyDeclaration; + questionToken?: QuestionToken; name: PropertyName; type?: TypeNode; initializer?: Expression; @@ -526,22 +1240,23 @@ declare namespace ts { } type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration; interface PropertyAssignment extends ObjectLiteralElement { - _propertyAssignmentBrand: any; + kind: SyntaxKind.PropertyAssignment; name: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; initializer: Expression; } interface ShorthandPropertyAssignment extends ObjectLiteralElement { + kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; - questionToken?: Node; - equalsToken?: Node; + questionToken?: QuestionToken; + equalsToken?: Token; objectAssignmentInitializer?: Expression; } interface VariableLikeDeclaration extends Declaration { propertyName?: PropertyName; - dotDotDotToken?: Node; + dotDotDotToken?: DotDotDotToken; name: DeclarationName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } @@ -552,96 +1267,119 @@ declare namespace ts { elements: NodeArray; } interface ObjectBindingPattern extends BindingPattern { + kind: SyntaxKind.ObjectBindingPattern; elements: NodeArray; } type ArrayBindingElement = BindingElement | OmittedExpression; interface ArrayBindingPattern extends BindingPattern { + kind: SyntaxKind.ArrayBindingPattern; elements: NodeArray; } interface FunctionLikeDeclaration extends SignatureDeclaration { _functionLikeDeclarationBrand: any; - asteriskToken?: Node; - questionToken?: Node; + asteriskToken?: AsteriskToken; + questionToken?: QuestionToken; body?: Block | Expression; } interface FunctionDeclaration extends FunctionLikeDeclaration, DeclarationStatement { + kind: SyntaxKind.FunctionDeclaration; name?: Identifier; body?: FunctionBody; } interface MethodSignature extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.MethodSignature; name: PropertyName; } interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.MethodDeclaration; name: PropertyName; body?: FunctionBody; } interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { + kind: SyntaxKind.Constructor; body?: FunctionBody; } interface SemicolonClassElement extends ClassElement { - _semicolonClassElementBrand: any; + kind: SyntaxKind.SemicolonClassElement; } - interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { - _accessorDeclarationBrand: any; + interface GetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.GetAccessor; name: PropertyName; body: FunctionBody; } - interface GetAccessorDeclaration extends AccessorDeclaration { - } - interface SetAccessorDeclaration extends AccessorDeclaration { + interface SetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.SetAccessor; + name: PropertyName; + body: FunctionBody; } + type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement, TypeElement { - _indexSignatureDeclarationBrand: any; + kind: SyntaxKind.IndexSignature; } interface TypeNode extends Node { _typeNodeBrand: any; } + interface KeywordTypeNode extends TypeNode { + kind: SyntaxKind.AnyKeyword | SyntaxKind.NumberKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.VoidKeyword; + } interface ThisTypeNode extends TypeNode { - _thisTypeNodeBrand: any; + kind: SyntaxKind.ThisType; } interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration { - _functionOrConstructorTypeNodeBrand: any; + kind: SyntaxKind.FunctionType | SyntaxKind.ConstructorType; } interface FunctionTypeNode extends FunctionOrConstructorTypeNode { + kind: SyntaxKind.FunctionType; } interface ConstructorTypeNode extends FunctionOrConstructorTypeNode { + kind: SyntaxKind.ConstructorType; } interface TypeReferenceNode extends TypeNode { + kind: SyntaxKind.TypeReference; typeName: EntityName; typeArguments?: NodeArray; } interface TypePredicateNode extends TypeNode { + kind: SyntaxKind.TypePredicate; parameterName: Identifier | ThisTypeNode; type: TypeNode; } interface TypeQueryNode extends TypeNode { + kind: SyntaxKind.TypeQuery; exprName: EntityName; } interface TypeLiteralNode extends TypeNode, Declaration { + kind: SyntaxKind.TypeLiteral; members: NodeArray; } interface ArrayTypeNode extends TypeNode { + kind: SyntaxKind.ArrayType; elementType: TypeNode; } interface TupleTypeNode extends TypeNode { + kind: SyntaxKind.TupleType; elementTypes: NodeArray; } interface UnionOrIntersectionTypeNode extends TypeNode { + kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType; types: NodeArray; } interface UnionTypeNode extends UnionOrIntersectionTypeNode { + kind: SyntaxKind.UnionType; } interface IntersectionTypeNode extends UnionOrIntersectionTypeNode { + kind: SyntaxKind.IntersectionType; } interface ParenthesizedTypeNode extends TypeNode { + kind: SyntaxKind.ParenthesizedType; type: TypeNode; } interface LiteralTypeNode extends TypeNode { - _stringLiteralTypeBrand: any; + kind: SyntaxKind.LiteralType; literal: Expression; } interface StringLiteral extends LiteralExpression { - _stringLiteralBrand: any; + kind: SyntaxKind.StringLiteral; textSourceNode?: Identifier | StringLiteral; } interface Expression extends Node { @@ -649,9 +1387,10 @@ declare namespace ts { contextualType?: Type; } interface OmittedExpression extends Expression { - _omittedExpressionBrand: any; + kind: SyntaxKind.OmittedExpression; } interface PartiallyEmittedExpression extends LeftHandSideExpression { + kind: SyntaxKind.PartiallyEmittedExpression; expression: Expression; } interface UnaryExpression extends Expression { @@ -660,13 +1399,17 @@ declare namespace ts { interface IncrementExpression extends UnaryExpression { _incrementExpressionBrand: any; } + type PrefixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.TildeToken | SyntaxKind.ExclamationToken; interface PrefixUnaryExpression extends IncrementExpression { - operator: SyntaxKind; + kind: SyntaxKind.PrefixUnaryExpression; + operator: PrefixUnaryOperator; operand: UnaryExpression; } + type PostfixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken; interface PostfixUnaryExpression extends IncrementExpression { + kind: SyntaxKind.PostfixUnaryExpression; operand: LeftHandSideExpression; - operator: SyntaxKind; + operator: PostfixUnaryOperator; } interface PostfixExpression extends UnaryExpression { _postfixExpressionBrand: any; @@ -680,42 +1423,83 @@ declare namespace ts { interface PrimaryExpression extends MemberExpression { _primaryExpressionBrand: any; } + interface NullLiteral extends PrimaryExpression { + kind: SyntaxKind.NullKeyword; + } + interface BooleanLiteral extends PrimaryExpression { + kind: SyntaxKind.TrueKeyword | SyntaxKind.FalseKeyword; + } + interface ThisExpression extends PrimaryExpression { + kind: SyntaxKind.ThisKeyword; + } + interface SuperExpression extends PrimaryExpression { + kind: SyntaxKind.SuperKeyword; + } interface DeleteExpression extends UnaryExpression { + kind: SyntaxKind.DeleteExpression; expression: UnaryExpression; } interface TypeOfExpression extends UnaryExpression { + kind: SyntaxKind.TypeOfExpression; expression: UnaryExpression; } interface VoidExpression extends UnaryExpression { + kind: SyntaxKind.VoidExpression; expression: UnaryExpression; } interface AwaitExpression extends UnaryExpression { + kind: SyntaxKind.AwaitExpression; expression: UnaryExpression; } interface YieldExpression extends Expression { - asteriskToken?: Node; + kind: SyntaxKind.YieldExpression; + asteriskToken?: AsteriskToken; expression?: Expression; } + type ExponentiationOperator = SyntaxKind.AsteriskAsteriskToken; + type MultiplicativeOperator = SyntaxKind.AsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken; + type MultiplicativeOperatorOrHigher = ExponentiationOperator | MultiplicativeOperator; + type AdditiveOperator = SyntaxKind.PlusToken | SyntaxKind.MinusToken; + type AdditiveOperatorOrHigher = MultiplicativeOperatorOrHigher | AdditiveOperator; + type ShiftOperator = SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken; + type ShiftOperatorOrHigher = AdditiveOperatorOrHigher | ShiftOperator; + type RelationalOperator = SyntaxKind.LessThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.InstanceOfKeyword | SyntaxKind.InKeyword; + type RelationalOperatorOrHigher = ShiftOperatorOrHigher | RelationalOperator; + type EqualityOperator = SyntaxKind.EqualsEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.ExclamationEqualsToken; + type EqualityOperatorOrHigher = RelationalOperatorOrHigher | EqualityOperator; + type BitwiseOperator = SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken; + type BitwiseOperatorOrHigher = EqualityOperatorOrHigher | BitwiseOperator; + type LogicalOperator = SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken; + type LogicalOperatorOrHigher = BitwiseOperatorOrHigher | LogicalOperator; + type CompoundAssignmentOperator = SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken; + type AssignmentOperator = SyntaxKind.EqualsToken | CompoundAssignmentOperator; + type AssignmentOperatorOrHigher = LogicalOperatorOrHigher | AssignmentOperator; + type BinaryOperator = AssignmentOperatorOrHigher | SyntaxKind.CommaToken; + type BinaryOperatorToken = Token; interface BinaryExpression extends Expression, Declaration { + kind: SyntaxKind.BinaryExpression; left: Expression; - operatorToken: Node; + operatorToken: BinaryOperatorToken; right: Expression; } interface ConditionalExpression extends Expression { + kind: SyntaxKind.ConditionalExpression; condition: Expression; - questionToken: Node; + questionToken: QuestionToken; whenTrue: Expression; - colonToken: Node; + colonToken: ColonToken; whenFalse: Expression; } type FunctionBody = Block; type ConciseBody = FunctionBody | Expression; interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { + kind: SyntaxKind.FunctionExpression; name?: Identifier; body: FunctionBody; } interface ArrowFunction extends Expression, FunctionLikeDeclaration { - equalsGreaterThanToken: Node; + kind: SyntaxKind.ArrowFunction; + equalsGreaterThanToken: EqualsGreaterThanToken; body: ConciseBody; } interface LiteralLikeNode extends Node { @@ -727,137 +1511,192 @@ declare namespace ts { interface LiteralExpression extends LiteralLikeNode, PrimaryExpression { _literalExpressionBrand: any; } + interface RegularExpressionLiteral extends LiteralExpression { + kind: SyntaxKind.RegularExpressionLiteral; + } + interface NoSubstitutionTemplateLiteral extends LiteralExpression { + kind: SyntaxKind.NoSubstitutionTemplateLiteral; + } interface NumericLiteral extends LiteralExpression { - _numericLiteralBrand: any; + kind: SyntaxKind.NumericLiteral; trailingComment?: string; } - interface TemplateLiteralFragment extends LiteralLikeNode { - _templateLiteralFragmentBrand: any; + interface TemplateHead extends LiteralLikeNode { + kind: SyntaxKind.TemplateHead; } - type Template = TemplateExpression | LiteralExpression; + interface TemplateMiddle extends LiteralLikeNode { + kind: SyntaxKind.TemplateMiddle; + } + interface TemplateTail extends LiteralLikeNode { + kind: SyntaxKind.TemplateTail; + } + type TemplateLiteral = TemplateExpression | NoSubstitutionTemplateLiteral; interface TemplateExpression extends PrimaryExpression { - head: TemplateLiteralFragment; + kind: SyntaxKind.TemplateExpression; + head: TemplateHead; templateSpans: NodeArray; } interface TemplateSpan extends Node { + kind: SyntaxKind.TemplateSpan; expression: Expression; - literal: TemplateLiteralFragment; + literal: TemplateMiddle | TemplateTail; } interface ParenthesizedExpression extends PrimaryExpression { + kind: SyntaxKind.ParenthesizedExpression; expression: Expression; } interface ArrayLiteralExpression extends PrimaryExpression { + kind: SyntaxKind.ArrayLiteralExpression; elements: NodeArray; multiLine?: boolean; } interface SpreadElementExpression extends Expression { + kind: SyntaxKind.SpreadElementExpression; expression: Expression; } interface ObjectLiteralExpressionBase extends PrimaryExpression, Declaration { properties: NodeArray; } interface ObjectLiteralExpression extends ObjectLiteralExpressionBase { + kind: SyntaxKind.ObjectLiteralExpression; multiLine?: boolean; } type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression; type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; interface PropertyAccessExpression extends MemberExpression, Declaration { + kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; } + interface SuperPropertyAccessExpression extends PropertyAccessExpression { + expression: SuperExpression; + } interface PropertyAccessEntityNameExpression extends PropertyAccessExpression { _propertyAccessExpressionLikeQualifiedNameBrand?: any; expression: EntityNameExpression; } interface ElementAccessExpression extends MemberExpression { + kind: SyntaxKind.ElementAccessExpression; expression: LeftHandSideExpression; argumentExpression?: Expression; } + interface SuperElementAccessExpression extends ElementAccessExpression { + expression: SuperExpression; + } + type SuperProperty = SuperPropertyAccessExpression | SuperElementAccessExpression; interface CallExpression extends LeftHandSideExpression, Declaration { + kind: SyntaxKind.CallExpression; expression: LeftHandSideExpression; typeArguments?: NodeArray; arguments: NodeArray; } + interface SuperCall extends CallExpression { + expression: SuperExpression; + } interface ExpressionWithTypeArguments extends TypeNode { + kind: SyntaxKind.ExpressionWithTypeArguments; expression: LeftHandSideExpression; typeArguments?: NodeArray; } - interface NewExpression extends CallExpression, PrimaryExpression { + interface NewExpression extends PrimaryExpression, Declaration { + kind: SyntaxKind.NewExpression; + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + arguments: NodeArray; } interface TaggedTemplateExpression extends MemberExpression { + kind: SyntaxKind.TaggedTemplateExpression; tag: LeftHandSideExpression; - template: Template; + template: TemplateLiteral; } type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; interface AsExpression extends Expression { + kind: SyntaxKind.AsExpression; expression: Expression; type: TypeNode; } interface TypeAssertion extends UnaryExpression { + kind: SyntaxKind.TypeAssertionExpression; type: TypeNode; expression: UnaryExpression; } type AssertionExpression = TypeAssertion | AsExpression; interface NonNullExpression extends LeftHandSideExpression { + kind: SyntaxKind.NonNullExpression; expression: Expression; } interface JsxElement extends PrimaryExpression { + kind: SyntaxKind.JsxElement; openingElement: JsxOpeningElement; children: NodeArray; closingElement: JsxClosingElement; } type JsxTagNameExpression = PrimaryExpression | PropertyAccessExpression; interface JsxOpeningElement extends Expression { - _openingElementBrand?: any; + kind: SyntaxKind.JsxOpeningElement; tagName: JsxTagNameExpression; attributes: NodeArray; } - interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement { - _selfClosingElementBrand?: any; + interface JsxSelfClosingElement extends PrimaryExpression { + kind: SyntaxKind.JsxSelfClosingElement; + tagName: JsxTagNameExpression; + attributes: NodeArray; } type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute; interface JsxAttribute extends Node { + kind: SyntaxKind.JsxAttribute; name: Identifier; initializer?: StringLiteral | JsxExpression; } interface JsxSpreadAttribute extends Node { + kind: SyntaxKind.JsxSpreadAttribute; expression: Expression; } interface JsxClosingElement extends Node { + kind: SyntaxKind.JsxClosingElement; tagName: JsxTagNameExpression; } interface JsxExpression extends Expression { + kind: SyntaxKind.JsxExpression; expression?: Expression; } interface JsxText extends Node { - _jsxTextExpressionBrand: any; + kind: SyntaxKind.JsxText; } type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement; interface Statement extends Node { _statementBrand: any; } interface NotEmittedStatement extends Statement { + kind: SyntaxKind.NotEmittedStatement; } interface EmptyStatement extends Statement { + kind: SyntaxKind.EmptyStatement; } interface DebuggerStatement extends Statement { + kind: SyntaxKind.DebuggerStatement; } interface MissingDeclaration extends DeclarationStatement, ClassElement, ObjectLiteralElement, TypeElement { + kind: SyntaxKind.MissingDeclaration; name?: Identifier; } type BlockLike = SourceFile | Block | ModuleBlock | CaseClause; interface Block extends Statement { + kind: SyntaxKind.Block; statements: NodeArray; multiLine?: boolean; } interface VariableStatement extends Statement { + kind: SyntaxKind.VariableStatement; declarationList: VariableDeclarationList; } interface ExpressionStatement extends Statement { + kind: SyntaxKind.ExpressionStatement; expression: Expression; } interface IfStatement extends Statement { + kind: SyntaxKind.IfStatement; expression: Expression; thenStatement: Statement; elseStatement?: Statement; @@ -866,68 +1705,85 @@ declare namespace ts { statement: Statement; } interface DoStatement extends IterationStatement { + kind: SyntaxKind.DoStatement; expression: Expression; } interface WhileStatement extends IterationStatement { + kind: SyntaxKind.WhileStatement; expression: Expression; } type ForInitializer = VariableDeclarationList | Expression; interface ForStatement extends IterationStatement { + kind: SyntaxKind.ForStatement; initializer?: ForInitializer; condition?: Expression; incrementor?: Expression; } interface ForInStatement extends IterationStatement { + kind: SyntaxKind.ForInStatement; initializer: ForInitializer; expression: Expression; } interface ForOfStatement extends IterationStatement { + kind: SyntaxKind.ForOfStatement; initializer: ForInitializer; expression: Expression; } interface BreakStatement extends Statement { + kind: SyntaxKind.BreakStatement; label?: Identifier; } interface ContinueStatement extends Statement { + kind: SyntaxKind.ContinueStatement; label?: Identifier; } type BreakOrContinueStatement = BreakStatement | ContinueStatement; interface ReturnStatement extends Statement { + kind: SyntaxKind.ReturnStatement; expression?: Expression; } interface WithStatement extends Statement { + kind: SyntaxKind.WithStatement; expression: Expression; statement: Statement; } interface SwitchStatement extends Statement { + kind: SyntaxKind.SwitchStatement; expression: Expression; caseBlock: CaseBlock; possiblyExhaustive?: boolean; } interface CaseBlock extends Node { + kind: SyntaxKind.CaseBlock; clauses: NodeArray; } interface CaseClause extends Node { + kind: SyntaxKind.CaseClause; expression: Expression; statements: NodeArray; } interface DefaultClause extends Node { + kind: SyntaxKind.DefaultClause; statements: NodeArray; } type CaseOrDefaultClause = CaseClause | DefaultClause; interface LabeledStatement extends Statement { + kind: SyntaxKind.LabeledStatement; label: Identifier; statement: Statement; } interface ThrowStatement extends Statement { + kind: SyntaxKind.ThrowStatement; expression: Expression; } interface TryStatement extends Statement { + kind: SyntaxKind.TryStatement; tryBlock: Block; catchClause?: CatchClause; finallyBlock?: Block; } interface CatchClause extends Node { + kind: SyntaxKind.CatchClause; variableDeclaration: VariableDeclaration; block: Block; } @@ -939,9 +1795,11 @@ declare namespace ts { members: NodeArray; } interface ClassDeclaration extends ClassLikeDeclaration, DeclarationStatement { + kind: SyntaxKind.ClassDeclaration; name?: Identifier; } interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { + kind: SyntaxKind.ClassExpression; } interface ClassElement extends Declaration { _classElementBrand: any; @@ -950,85 +1808,108 @@ declare namespace ts { interface TypeElement extends Declaration { _typeElementBrand: any; name?: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; } interface InterfaceDeclaration extends DeclarationStatement { + kind: SyntaxKind.InterfaceDeclaration; name: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; members: NodeArray; } interface HeritageClause extends Node { + kind: SyntaxKind.HeritageClause; token: SyntaxKind; types?: NodeArray; } interface TypeAliasDeclaration extends DeclarationStatement { + kind: SyntaxKind.TypeAliasDeclaration; name: Identifier; typeParameters?: NodeArray; type: TypeNode; } interface EnumMember extends Declaration { + kind: SyntaxKind.EnumMember; name: PropertyName; initializer?: Expression; } interface EnumDeclaration extends DeclarationStatement { + kind: SyntaxKind.EnumDeclaration; name: Identifier; members: NodeArray; } type ModuleBody = ModuleBlock | ModuleDeclaration; type ModuleName = Identifier | StringLiteral; interface ModuleDeclaration extends DeclarationStatement { + kind: SyntaxKind.ModuleDeclaration; name: Identifier | LiteralExpression; - body?: ModuleBlock | ModuleDeclaration; + body?: ModuleBlock | NamespaceDeclaration; + } + interface NamespaceDeclaration extends ModuleDeclaration { + name: Identifier; + body: ModuleBlock | NamespaceDeclaration; } interface ModuleBlock extends Node, Statement { + kind: SyntaxKind.ModuleBlock; statements: NodeArray; } type ModuleReference = EntityName | ExternalModuleReference; interface ImportEqualsDeclaration extends DeclarationStatement { + kind: SyntaxKind.ImportEqualsDeclaration; name: Identifier; moduleReference: ModuleReference; } interface ExternalModuleReference extends Node { + kind: SyntaxKind.ExternalModuleReference; expression?: Expression; } interface ImportDeclaration extends Statement { + kind: SyntaxKind.ImportDeclaration; importClause?: ImportClause; moduleSpecifier: Expression; } type NamedImportBindings = NamespaceImport | NamedImports; interface ImportClause extends Declaration { + kind: SyntaxKind.ImportClause; name?: Identifier; namedBindings?: NamedImportBindings; } interface NamespaceImport extends Declaration { + kind: SyntaxKind.NamespaceImport; name: Identifier; } interface NamespaceExportDeclaration extends DeclarationStatement { + kind: SyntaxKind.NamespaceExportDeclaration; name: Identifier; moduleReference: LiteralLikeNode; } interface ExportDeclaration extends DeclarationStatement { + kind: SyntaxKind.ExportDeclaration; exportClause?: NamedExports; moduleSpecifier?: Expression; } interface NamedImports extends Node { + kind: SyntaxKind.NamedImports; elements: NodeArray; } interface NamedExports extends Node { + kind: SyntaxKind.NamedExports; elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; interface ImportSpecifier extends Declaration { + kind: SyntaxKind.ImportSpecifier; propertyName?: Identifier; name: Identifier; } interface ExportSpecifier extends Declaration { + kind: SyntaxKind.ExportSpecifier; propertyName?: Identifier; name: Identifier; } type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier; interface ExportAssignment extends DeclarationStatement { + kind: SyntaxKind.ExportAssignment; isExportEquals?: boolean; expression: Expression; } @@ -1040,95 +1921,121 @@ declare namespace ts { kind: SyntaxKind; } interface JSDocTypeExpression extends Node { + kind: SyntaxKind.JSDocTypeExpression; type: JSDocType; } interface JSDocType extends TypeNode { _jsDocTypeBrand: any; } interface JSDocAllType extends JSDocType { - _JSDocAllTypeBrand: any; + kind: SyntaxKind.JSDocAllType; } interface JSDocUnknownType extends JSDocType { - _JSDocUnknownTypeBrand: any; + kind: SyntaxKind.JSDocUnknownType; } interface JSDocArrayType extends JSDocType { + kind: SyntaxKind.JSDocArrayType; elementType: JSDocType; } interface JSDocUnionType extends JSDocType { + kind: SyntaxKind.JSDocUnionType; types: NodeArray; } interface JSDocTupleType extends JSDocType { + kind: SyntaxKind.JSDocTupleType; types: NodeArray; } interface JSDocNonNullableType extends JSDocType { + kind: SyntaxKind.JSDocNonNullableType; type: JSDocType; } interface JSDocNullableType extends JSDocType { + kind: SyntaxKind.JSDocNullableType; type: JSDocType; } - interface JSDocRecordType extends JSDocType, TypeLiteralNode { + interface JSDocRecordType extends JSDocType { + kind: SyntaxKind.JSDocRecordType; literal: TypeLiteralNode; } interface JSDocTypeReference extends JSDocType { + kind: SyntaxKind.JSDocTypeReference; name: EntityName; typeArguments: NodeArray; } interface JSDocOptionalType extends JSDocType { + kind: SyntaxKind.JSDocOptionalType; type: JSDocType; } interface JSDocFunctionType extends JSDocType, SignatureDeclaration { + kind: SyntaxKind.JSDocFunctionType; parameters: NodeArray; type: JSDocType; } interface JSDocVariadicType extends JSDocType { + kind: SyntaxKind.JSDocVariadicType; type: JSDocType; } interface JSDocConstructorType extends JSDocType { + kind: SyntaxKind.JSDocConstructorType; type: JSDocType; } interface JSDocThisType extends JSDocType { + kind: SyntaxKind.JSDocThisType; type: JSDocType; } interface JSDocLiteralType extends JSDocType { + kind: SyntaxKind.JSDocLiteralType; literal: LiteralTypeNode; } type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDocRecordMember extends PropertySignature { + kind: SyntaxKind.JSDocRecordMember; name: Identifier | LiteralExpression; type?: JSDocType; } interface JSDoc extends Node { + kind: SyntaxKind.JSDocComment; tags: NodeArray | undefined; comment: string | undefined; } interface JSDocTag extends Node { - atToken: Node; + atToken: AtToken; tagName: Identifier; comment: string | undefined; } + interface JSDocUnknownTag extends JSDocTag { + kind: SyntaxKind.JSDocTag; + } interface JSDocTemplateTag extends JSDocTag { + kind: SyntaxKind.JSDocTemplateTag; typeParameters: NodeArray; } interface JSDocReturnTag extends JSDocTag { + kind: SyntaxKind.JSDocReturnTag; typeExpression: JSDocTypeExpression; } interface JSDocTypeTag extends JSDocTag { + kind: SyntaxKind.JSDocTypeTag; typeExpression: JSDocTypeExpression; } interface JSDocTypedefTag extends JSDocTag, Declaration { + kind: SyntaxKind.JSDocTypedefTag; name?: Identifier; typeExpression?: JSDocTypeExpression; jsDocTypeLiteral?: JSDocTypeLiteral; } interface JSDocPropertyTag extends JSDocTag, TypeElement { + kind: SyntaxKind.JSDocPropertyTag; name: Identifier; typeExpression: JSDocTypeExpression; } interface JSDocTypeLiteral extends JSDocType { + kind: SyntaxKind.JSDocTypeLiteral; jsDocPropertyTags?: NodeArray; jsDocTypeTag?: JSDocTypeTag; } interface JSDocParameterTag extends JSDocTag { + kind: SyntaxKind.JSDocParameterTag; preParameterName?: Identifier; typeExpression?: JSDocTypeExpression; postParameterName?: Identifier; @@ -1154,7 +2061,7 @@ declare namespace ts { id?: number; } interface FlowStart extends FlowNode { - container?: FunctionExpression | ArrowFunction; + container?: FunctionExpression | ArrowFunction | MethodDeclaration; } interface FlowLabel extends FlowNode { antecedents: FlowNode[]; @@ -1183,8 +2090,9 @@ declare namespace ts { name: string; } interface SourceFile extends Declaration { + kind: SyntaxKind.SourceFile; statements: NodeArray; - endOfFileToken: Node; + endOfFileToken: Token; fileName: string; path: Path; text: string; @@ -1239,7 +2147,7 @@ declare namespace ts { interface Program extends ScriptReferenceHost { getRootFileNames(): string[]; getSourceFiles(): SourceFile[]; - emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult; + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean): EmitResult; getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; @@ -1248,6 +2156,7 @@ declare namespace ts { getTypeChecker(): TypeChecker; getCommonSourceDirectory(): string; getDiagnosticsProducingTypeChecker(): TypeChecker; + dropDiagnosticsProducingTypeChecker(): void; getClassifiableNames(): Map; getNodeCount(): number; getIdentifierCount(): number; @@ -1379,6 +2288,7 @@ declare namespace ts { UseFullyQualifiedType = 128, InFirstTypeArgument = 256, InTypeAlias = 512, + UseTypeAliasValue = 1024, } const enum SymbolFormatFlags { None = 0, @@ -1399,9 +2309,10 @@ declare namespace ts { type: Type; } interface ThisTypePredicate extends TypePredicateBase { - _thisTypePredicateBrand: any; + kind: TypePredicateKind.This; } interface IdentifierTypePredicate extends TypePredicateBase { + kind: TypePredicateKind.Identifier; parameterName: string; parameterIndex: number; } @@ -1457,8 +2368,8 @@ declare namespace ts { getExternalModuleFileFromDeclaration(declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration): SourceFile; getTypeReferenceDirectivesForEntityName(name: EntityNameOrEntityNameExpression): string[]; getTypeReferenceDirectivesForSymbol(symbol: Symbol, meaning?: SymbolFlags): string[]; - isLiteralConstDeclaration(node: VariableDeclaration): boolean; - writeLiteralConstValue(node: VariableDeclaration, writer: SymbolWriter): void; + isLiteralConstDeclaration(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration): boolean; + writeLiteralConstValue(node: VariableDeclaration | PropertyDeclaration | PropertySignature | ParameterDeclaration, writer: SymbolWriter): void; } const enum SymbolFlags { None = 0, @@ -1556,7 +2467,8 @@ declare namespace ts { mapper?: TypeMapper; referenced?: boolean; containingType?: UnionOrIntersectionType; - hasCommonType?: boolean; + hasNonUniformType?: boolean; + isPartial?: boolean; isDiscriminantProperty?: boolean; resolvedExports?: SymbolTable; exportsChecked?: boolean; @@ -1641,8 +2553,6 @@ declare namespace ts { ContainsWideningType = 33554432, ContainsObjectLiteral = 67108864, ContainsAnyFunctionType = 134217728, - ThisType = 268435456, - ObjectLiteralPatternWithComputedProperties = 536870912, Nullable = 6144, Literal = 480, StringOrNumberLiteral = 96, @@ -1659,7 +2569,7 @@ declare namespace ts { StructuredType = 4161536, StructuredOrTypeParameter = 4177920, Narrowable = 4178943, - NotUnionOrUnit = 2589191, + NotUnionOrUnit = 2589185, RequiresWidening = 100663296, PropagatingFlags = 234881024, } @@ -1687,6 +2597,7 @@ declare namespace ts { baseType: EnumType & UnionType; } interface ObjectType extends Type { + isObjectLiteralPatternWithComputedProperties?: boolean; } interface InterfaceType extends ObjectType { typeParameters: TypeParameter[]; @@ -1743,6 +2654,7 @@ declare namespace ts { target?: TypeParameter; mapper?: TypeMapper; resolvedApparentType: Type; + isThisType?: boolean; } const enum SignatureKind { Call = 0, @@ -1830,16 +2742,14 @@ declare namespace ts { Classic = 1, NodeJs = 2, } - type RootPaths = string[]; - type PathSubstitutions = MapLike; - type TsConfigOnlyOptions = RootPaths | PathSubstitutions; - type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions; + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike; interface CompilerOptions { allowJs?: boolean; allowNonTsExtensions?: boolean; allowSyntheticDefaultImports?: boolean; allowUnreachableCode?: boolean; allowUnusedLabels?: boolean; + alwaysStrict?: boolean; baseUrl?: string; charset?: string; configFilePath?: string; @@ -1884,14 +2794,14 @@ declare namespace ts { out?: string; outDir?: string; outFile?: string; - paths?: PathSubstitutions; + paths?: MapLike; preserveConstEnums?: boolean; project?: string; pretty?: DiagnosticStyle; reactNamespace?: string; removeComments?: boolean; rootDir?: string; - rootDirs?: RootPaths; + rootDirs?: string[]; skipLibCheck?: boolean; skipDefaultLibCheck?: boolean; sourceMap?: boolean; @@ -1974,6 +2884,7 @@ declare namespace ts { raw?: any; errors: Diagnostic[]; wildcardDirectories?: MapLike; + compileOnSave?: boolean; } const enum WatchDirectoryFlags { None = 0, @@ -2221,7 +3132,15 @@ declare namespace ts { TypeScriptClassSyntaxMask = 137216, ES6FunctionSyntaxMask = 81920, } - const enum NodeEmitFlags { + interface EmitNode { + flags?: EmitFlags; + commentRange?: TextRange; + sourceMapRange?: TextRange; + tokenSourceMapRanges?: Map; + annotatedNodes?: Node[]; + constantValue?: number; + } + const enum EmitFlags { EmitEmitHelpers = 1, EmitExportStar = 2, EmitSuperHelper = 4, @@ -2250,6 +3169,12 @@ declare namespace ts { ReuseTempVariableScope = 4194304, CustomPrologue = 8388608, } + const enum EmitContext { + SourceFile = 0, + Expression = 1, + IdentifierName = 2, + Unspecified = 3, + } interface LexicalEnvironment { startLexicalEnvironment(): void; endLexicalEnvironment(): Statement[]; @@ -2327,7 +3252,7 @@ declare namespace ts { function singleOrUndefined(array: T[]): T; function singleOrMany(array: T[]): T | T[]; function lastOrUndefined(array: T[]): T; - function binarySearch(array: number[], value: number): number; + function binarySearch(array: T[], value: T, comparer?: (v1: T, v2: T) => number): number; function reduceLeft(array: T[], f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U; function reduceLeft(array: T[], f: (memo: T, value: T, i: number) => T): T; function reduceRight(array: T[], f: (memo: U, value: T, i: number) => U, initial: U, start?: number, count?: number): U; @@ -2354,6 +3279,8 @@ declare namespace ts { function multiMapRemove(map: Map, key: string, value: V): void; function isArray(value: any): value is any[]; function memoize(callback: () => T): () => T; + function chain(...args: ((t: T) => (u: U) => U)[]): (t: T) => (u: U) => U; + function compose(...args: ((t: T) => T)[]): (t: T) => T; let localizedDiagnosticMessages: Map; function getLocaleSpecificMessage(message: DiagnosticMessage): string; function createFileDiagnostic(file: SourceFile, start: number, length: number, message: DiagnosticMessage, ...args: any[]): Diagnostic; @@ -2375,7 +3302,12 @@ declare namespace ts { function getDirectoryPath(path: Path): Path; function getDirectoryPath(path: string): string; function isUrl(path: string): boolean; + function isExternalModuleNameRelative(moduleName: string): boolean; + function getEmitScriptTarget(compilerOptions: CompilerOptions): ScriptTarget; + function getEmitModuleKind(compilerOptions: CompilerOptions): ModuleKind; + function hasZeroOrOneAsteriskCharacter(str: string): boolean; function isRootedDiskPath(path: string): boolean; + function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string; function getNormalizedPathComponents(path: string, currentDirectory: string): string[]; function getNormalizedAbsolutePath(fileName: string, currentDirectory: string): string; function getNormalizedPathFromPathComponents(pathComponents: string[]): string; @@ -2409,6 +3341,8 @@ declare namespace ts { const supportedTypescriptExtensionsForExtractExtension: string[]; const supportedJavascriptExtensions: string[]; function getSupportedExtensions(options?: CompilerOptions): string[]; + function hasJavaScriptFileExtension(fileName: string): boolean; + function hasTypeScriptFileExtension(fileName: string): boolean; function isSupportedSourceFileName(fileName: string, compilerOptions?: CompilerOptions): boolean; const enum ExtensionPriority { TypeScriptFiles = 0, @@ -2427,9 +3361,9 @@ declare namespace ts { function changeExtension(path: T, newExtension: string): T; interface ObjectAllocator { getNodeConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Node; - getTokenConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Token; - getIdentifierConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => Token; - getSourceFileConstructor(): new (kind: SyntaxKind, pos?: number, end?: number) => SourceFile; + getTokenConstructor(): new (kind: TKind, pos?: number, end?: number) => Token; + getIdentifierConstructor(): new (kind: SyntaxKind.Identifier, pos?: number, end?: number) => Identifier; + getSourceFileConstructor(): new (kind: SyntaxKind.SourceFile, pos?: number, end?: number) => SourceFile; getSymbolConstructor(): new (flags: SymbolFlags, name: string) => Symbol; getTypeConstructor(): new (checker: TypeChecker, flags: TypeFlags) => Type; getSignatureConstructor(): new (checker: TypeChecker) => Signature; @@ -2442,15 +3376,21 @@ declare namespace ts { VeryAggressive = 3, } namespace Debug { + let currentAssertionLevel: AssertionLevel; function shouldAssert(level: AssertionLevel): boolean; function assert(expression: boolean, message?: string, verboseDebugInfo?: () => string): void; function fail(message?: string): void; } - function getEnvironmentVariable(name: string, host?: CompilerHost): string; function orderedRemoveItemAt(array: T[], index: number): void; function unorderedRemoveItemAt(array: T[], index: number): void; function unorderedRemoveItem(array: T[], item: T): void; function createGetCanonicalFileName(useCaseSensitiveFileNames: boolean): (fileName: string) => string; + function matchPatternOrExact(patternStrings: string[], candidate: string): string | Pattern | undefined; + function patternText({prefix, suffix}: Pattern): string; + function matchedText(pattern: Pattern, candidate: string): string; + function findBestPatternMatch(values: T[], getPattern: (value: T) => Pattern, candidate: string): T | undefined; + function tryParsePattern(pattern: string): Pattern | undefined; + function positionIsSynthesized(pos: number): boolean; } declare namespace ts { type FileWatcherCallback = (fileName: string, removed?: boolean) => void; @@ -2493,10 +3433,10 @@ declare namespace ts { directoryName: string; referenceCount: number; } - var sys: System; + let sys: System; } declare namespace ts { - var Diagnostics: { + const Diagnostics: { Unterminated_string_literal: { code: number; category: DiagnosticCategory; @@ -4417,7 +5357,7 @@ declare namespace ts { key: string; message: string; }; - All_symbols_within_a_with_block_will_be_resolved_to_any: { + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: number; category: DiagnosticCategory; key: string; @@ -5383,7 +6323,7 @@ declare namespace ts { key: string; message: string; }; - Identifier_0_must_be_imported_from_a_module: { + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: number; category: DiagnosticCategory; key: string; @@ -6781,6 +7721,18 @@ declare namespace ts { key: string; message: string; }; + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; Variable_0_implicitly_has_an_1_type: { code: number; category: DiagnosticCategory; @@ -6925,6 +7877,12 @@ declare namespace ts { key: string; message: string; }; + Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; You_cannot_rename_this_element: { code: number; category: DiagnosticCategory; @@ -7105,6 +8063,48 @@ declare namespace ts { key: string; message: string; }; + Add_missing_super_call: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Make_super_call_the_first_statement_in_the_constructor: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Change_extends_to_implements: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Remove_unused_identifiers: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Implement_interface_on_reference: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Implement_interface_on_class: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; + Implement_inherited_abstract_class: { + code: number; + category: DiagnosticCategory; + key: string; + message: string; + }; }; } declare namespace ts { @@ -7174,6 +8174,7 @@ declare namespace ts { function createScanner(languageVersion: ScriptTarget, skipTrivia: boolean, languageVariant?: LanguageVariant, text?: string, onError?: ErrorCallback, start?: number, length?: number): Scanner; } declare namespace ts { + const compileOnSaveCommandLineOption: CommandLineOption; const optionDeclarations: CommandLineOption[]; let typingOptionDeclarations: CommandLineOption[]; interface OptionNameMap { @@ -7190,7 +8191,7 @@ declare namespace ts { config?: any; error?: Diagnostic; }; - function parseConfigFileTextToJson(fileName: string, jsonText: string): { + function parseConfigFileTextToJson(fileName: string, jsonText: string, stripComments?: boolean): { config?: any; error?: Diagnostic; }; @@ -7198,15 +8199,136 @@ declare namespace ts { compilerOptions: Map; }; function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[]): ParsedCommandLine; + function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; }; function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { - options: CompilerOptions; + options: TypingOptions; errors: Diagnostic[]; }; } +declare namespace ts.JsTyping { + interface TypingResolutionHost { + directoryExists: (path: string) => boolean; + fileExists: (fileName: string) => boolean; + readFile: (path: string, encoding?: string) => string; + readDirectory: (rootDir: string, extensions: string[], excludes: string[], includes: string[], depth?: number) => string[]; + } + function discoverTypings(host: TypingResolutionHost, fileNames: string[], projectRootPath: Path, safeListPath: Path, packageNameToTypingLocation: Map, typingOptions: TypingOptions, compilerOptions: CompilerOptions): { + cachedTypingPaths: string[]; + newTypingNames: string[]; + filesToWatch: string[]; + }; +} +declare namespace ts.server { + enum LogLevel { + terse = 0, + normal = 1, + requestTime = 2, + verbose = 3, + } + const emptyArray: ReadonlyArray; + interface Logger { + close(): void; + hasLevel(level: LogLevel): boolean; + loggingEnabled(): boolean; + perftrc(s: string): void; + info(s: string): void; + startGroup(): void; + endGroup(): void; + msg(s: string, type?: Msg.Types): void; + getLogFileName(): string; + } + namespace Msg { + type Err = "Err"; + const Err: Err; + type Info = "Info"; + const Info: Info; + type Perf = "Perf"; + const Perf: Perf; + type Types = Err | Info | Perf; + } + function createInstallTypingsRequest(project: Project, typingOptions: TypingOptions, cachePath?: string): DiscoverTypings; + namespace Errors { + function ThrowNoProject(): never; + function ThrowProjectLanguageServiceDisabled(): never; + function ThrowProjectDoesNotContainDocument(fileName: string, project: Project): never; + } + function getDefaultFormatCodeSettings(host: ServerHost): FormatCodeSettings; + function mergeMaps(target: MapLike, source: MapLike): void; + function removeItemFromSet(items: T[], itemToRemove: T): void; + type NormalizedPath = string & { + __normalizedPathTag: any; + }; + function toNormalizedPath(fileName: string): NormalizedPath; + function normalizedPathToPath(normalizedPath: NormalizedPath, currentDirectory: string, getCanonicalFileName: (f: string) => string): Path; + function asNormalizedPath(fileName: string): NormalizedPath; + interface NormalizedPathMap { + get(path: NormalizedPath): T; + set(path: NormalizedPath, value: T): void; + contains(path: NormalizedPath): boolean; + remove(path: NormalizedPath): void; + } + function createNormalizedPathMap(): NormalizedPathMap; + const nullLanguageService: LanguageService; + interface ServerLanguageServiceHost { + setCompilationSettings(options: CompilerOptions): void; + notifyFileRemoved(info: ScriptInfo): void; + } + const nullLanguageServiceHost: ServerLanguageServiceHost; + interface ProjectOptions { + configHasFilesProperty?: boolean; + files?: string[]; + wildcardDirectories?: Map; + compilerOptions?: CompilerOptions; + typingOptions?: TypingOptions; + compileOnSave?: boolean; + } + function isInferredProjectName(name: string): boolean; + function makeInferredProjectName(counter: number): string; + class ThrottledOperations { + private readonly host; + private pendingTimeouts; + constructor(host: ServerHost); + schedule(operationId: string, delay: number, cb: () => void): void; + private static run(self, operationId, cb); + } + class GcTimer { + private readonly host; + private readonly delay; + private readonly logger; + private timerId; + constructor(host: ServerHost, delay: number, logger: Logger); + scheduleCollect(): void; + private static run(self); + } +} +declare namespace ts { + function trace(host: ModuleResolutionHost, message: DiagnosticMessage, ...args: any[]): void; + function isTraceEnabled(compilerOptions: CompilerOptions, host: ModuleResolutionHost): boolean; + function createResolvedModule(resolvedFileName: string, isExternalLibraryImport: boolean, failedLookupLocations: string[]): ResolvedModuleWithFailedLookupLocations; + interface ModuleResolutionState { + host: ModuleResolutionHost; + compilerOptions: CompilerOptions; + traceEnabled: boolean; + skipTsx: boolean; + } + function getEffectiveTypeRoots(options: CompilerOptions, host: { + directoryExists?: (directoryName: string) => boolean; + getCurrentDirectory?: () => string; + }): string[] | undefined; + function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; + function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function directoryProbablyExists(directoryName: string, host: { + directoryExists?: (directoryName: string) => boolean; + }): boolean; + function loadModuleFromNodeModules(moduleName: string, directory: string, failedLookupLocations: string[], state: ModuleResolutionState, checkOneLevel: boolean): string; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; +} declare namespace ts { const externalHelpersModuleNameText = "tslib"; interface ReferencePathMatchResult { @@ -7231,7 +8353,7 @@ declare namespace ts { function getSingleLineStringWriter(): StringSymbolWriter; function releaseStringWriter(writer: StringSymbolWriter): void; function getFullWidth(node: Node): number; - function arrayIsEqualTo(array1: T[], array2: T[], equaler?: (a: T, b: T) => boolean): boolean; + function arrayIsEqualTo(array1: ReadonlyArray, array2: ReadonlyArray, equaler?: (a: T, b: T) => boolean): boolean; function hasResolvedModule(sourceFile: SourceFile, moduleNameText: string): boolean; function getResolvedModule(sourceFile: SourceFile, moduleNameText: string): ResolvedModule; function setResolvedModule(sourceFile: SourceFile, moduleNameText: string, resolvedModule: ResolvedModule): void; @@ -7280,7 +8402,7 @@ declare namespace ts { function isConstEnumDeclaration(node: Node): boolean; function isConst(node: Node): boolean; function isLet(node: Node): boolean; - function isSuperCallExpression(n: Node): boolean; + function isSuperCall(n: Node): n is SuperCall; function isPrologueDirective(node: Node): boolean; function getLeadingCommentRangesOfNode(node: Node, sourceFileOfNode: SourceFile): CommentRange[]; function getLeadingCommentRangesOfNodeFromText(node: Node, text: string): CommentRange[]; @@ -7301,6 +8423,7 @@ declare namespace ts { function isIterationStatement(node: Node, lookInLabeledStatements: boolean): node is IterationStatement; function isFunctionBlock(node: Node): boolean; function isObjectLiteralMethod(node: Node): node is MethodDeclaration; + function isObjectLiteralOrClassExpressionMethod(node: Node): node is MethodDeclaration; function isIdentifierTypePredicate(predicate: TypePredicate): predicate is IdentifierTypePredicate; function isThisTypePredicate(predicate: TypePredicate): predicate is ThisTypePredicate; function getContainingFunction(node: Node): FunctionLikeDeclaration; @@ -7308,7 +8431,7 @@ declare namespace ts { function getThisContainer(node: Node, includeArrowFunctions: boolean): Node; function getSuperContainer(node: Node, stopOnFunctions: boolean): Node; function getImmediatelyInvokedFunctionExpression(func: Node): CallExpression; - function isSuperProperty(node: Node): node is (PropertyAccessExpression | ElementAccessExpression); + function isSuperProperty(node: Node): node is SuperProperty; function getEntityNameFromTypeNode(node: TypeNode): EntityNameOrEntityNameExpression; function isCallLikeExpression(node: Node): node is CallLikeExpression; function getInvokedExpression(node: CallLikeExpression): Expression; @@ -7318,7 +8441,6 @@ declare namespace ts { function childIsDecorated(node: Node): boolean; function isJSXTagName(node: Node): boolean; function isPartOfExpression(node: Node): boolean; - function isExternalModuleNameRelative(moduleName: string): boolean; function isInstantiatedModule(node: ModuleDeclaration, preserveConstEnums: boolean): boolean; function isExternalModuleImportEqualsDeclaration(node: Node): boolean; function getExternalModuleImportEqualsDeclarationExpression(node: Node): Expression; @@ -7330,7 +8452,7 @@ declare namespace ts { function isDeclarationOfFunctionExpression(s: Symbol): boolean; function getSpecialPropertyAssignmentKind(expression: Node): SpecialPropertyAssignmentKind; function getExternalModuleName(node: Node): Expression; - function getNamespaceDeclarationNode(node: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration): NamespaceImport; + function getNamespaceDeclarationNode(node: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration): ImportEqualsDeclaration | NamespaceImport; function isDefaultImport(node: ImportDeclaration | ImportEqualsDeclaration | ExportDeclaration): boolean; function hasQuestionToken(node: Node): boolean; function isJSDocConstructSignature(node: Node): boolean; @@ -7373,7 +8495,6 @@ declare namespace ts { function getRootDeclaration(node: Node): Node; function nodeStartsNewLexicalEnvironment(node: Node): boolean; function nodeIsSynthesized(node: TextRange): boolean; - function positionIsSynthesized(pos: number): boolean; function getOriginalNode(node: Node): Node; function isParseTreeNode(node: Node): boolean; function getParseTreeNode(node: Node): Node; @@ -7387,7 +8508,7 @@ declare namespace ts { function getExpressionAssociativity(expression: Expression): Associativity; function getOperatorAssociativity(kind: SyntaxKind, operator: SyntaxKind, hasArguments?: boolean): Associativity; function getExpressionPrecedence(expression: Expression): 0 | 1 | -1 | 2 | 4 | 3 | 16 | 10 | 5 | 6 | 11 | 8 | 19 | 18 | 17 | 15 | 14 | 13 | 12 | 9 | 7; - function getOperator(expression: Expression): SyntaxKind; + function getOperator(expression: Expression): SyntaxKind.Unknown | SyntaxKind.EndOfFileToken | SyntaxKind.SingleLineCommentTrivia | SyntaxKind.MultiLineCommentTrivia | SyntaxKind.NewLineTrivia | SyntaxKind.WhitespaceTrivia | SyntaxKind.ShebangTrivia | SyntaxKind.ConflictMarkerTrivia | SyntaxKind.NumericLiteral | SyntaxKind.StringLiteral | SyntaxKind.RegularExpressionLiteral | SyntaxKind.NoSubstitutionTemplateLiteral | SyntaxKind.TemplateHead | SyntaxKind.TemplateMiddle | SyntaxKind.TemplateTail | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.OpenParenToken | SyntaxKind.CloseParenToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.DotToken | SyntaxKind.DotDotDotToken | SyntaxKind.SemicolonToken | SyntaxKind.CommaToken | SyntaxKind.LessThanToken | SyntaxKind.LessThanSlashToken | SyntaxKind.GreaterThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.EqualsEqualsToken | SyntaxKind.ExclamationEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.EqualsGreaterThanToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.AsteriskToken | SyntaxKind.AsteriskAsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken | SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken | SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken | SyntaxKind.ExclamationToken | SyntaxKind.TildeToken | SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken | SyntaxKind.QuestionToken | SyntaxKind.ColonToken | SyntaxKind.AtToken | SyntaxKind.EqualsToken | SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken | SyntaxKind.Identifier | SyntaxKind.BreakKeyword | SyntaxKind.CaseKeyword | SyntaxKind.CatchKeyword | SyntaxKind.ClassKeyword | SyntaxKind.ConstKeyword | SyntaxKind.ContinueKeyword | SyntaxKind.DebuggerKeyword | SyntaxKind.DefaultKeyword | SyntaxKind.DeleteKeyword | SyntaxKind.DoKeyword | SyntaxKind.ElseKeyword | SyntaxKind.EnumKeyword | SyntaxKind.ExportKeyword | SyntaxKind.ExtendsKeyword | SyntaxKind.FalseKeyword | SyntaxKind.FinallyKeyword | SyntaxKind.ForKeyword | SyntaxKind.FunctionKeyword | SyntaxKind.IfKeyword | SyntaxKind.ImportKeyword | SyntaxKind.InKeyword | SyntaxKind.InstanceOfKeyword | SyntaxKind.NewKeyword | SyntaxKind.NullKeyword | SyntaxKind.ReturnKeyword | SyntaxKind.SuperKeyword | SyntaxKind.SwitchKeyword | SyntaxKind.ThisKeyword | SyntaxKind.ThrowKeyword | SyntaxKind.TrueKeyword | SyntaxKind.TryKeyword | SyntaxKind.TypeOfKeyword | SyntaxKind.VarKeyword | SyntaxKind.VoidKeyword | SyntaxKind.WhileKeyword | SyntaxKind.WithKeyword | SyntaxKind.ImplementsKeyword | SyntaxKind.InterfaceKeyword | SyntaxKind.LetKeyword | SyntaxKind.PackageKeyword | SyntaxKind.PrivateKeyword | SyntaxKind.ProtectedKeyword | SyntaxKind.PublicKeyword | SyntaxKind.StaticKeyword | SyntaxKind.YieldKeyword | SyntaxKind.AbstractKeyword | SyntaxKind.AsKeyword | SyntaxKind.AnyKeyword | SyntaxKind.AsyncKeyword | SyntaxKind.AwaitKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.ConstructorKeyword | SyntaxKind.DeclareKeyword | SyntaxKind.GetKeyword | SyntaxKind.IsKeyword | SyntaxKind.ModuleKeyword | SyntaxKind.NamespaceKeyword | SyntaxKind.NeverKeyword | SyntaxKind.ReadonlyKeyword | SyntaxKind.RequireKeyword | SyntaxKind.NumberKeyword | SyntaxKind.SetKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.TypeKeyword | SyntaxKind.UndefinedKeyword | SyntaxKind.FromKeyword | SyntaxKind.GlobalKeyword | SyntaxKind.OfKeyword | SyntaxKind.QualifiedName | SyntaxKind.ComputedPropertyName | SyntaxKind.TypeParameter | SyntaxKind.Parameter | SyntaxKind.Decorator | SyntaxKind.PropertySignature | SyntaxKind.PropertyDeclaration | SyntaxKind.MethodSignature | SyntaxKind.MethodDeclaration | SyntaxKind.Constructor | SyntaxKind.GetAccessor | SyntaxKind.SetAccessor | SyntaxKind.CallSignature | SyntaxKind.ConstructSignature | SyntaxKind.IndexSignature | SyntaxKind.TypePredicate | SyntaxKind.TypeReference | SyntaxKind.FunctionType | SyntaxKind.ConstructorType | SyntaxKind.TypeQuery | SyntaxKind.TypeLiteral | SyntaxKind.ArrayType | SyntaxKind.TupleType | SyntaxKind.UnionType | SyntaxKind.IntersectionType | SyntaxKind.ParenthesizedType | SyntaxKind.ThisType | SyntaxKind.LiteralType | SyntaxKind.ObjectBindingPattern | SyntaxKind.ArrayBindingPattern | SyntaxKind.BindingElement | SyntaxKind.ArrayLiteralExpression | SyntaxKind.ObjectLiteralExpression | SyntaxKind.PropertyAccessExpression | SyntaxKind.ElementAccessExpression | SyntaxKind.CallExpression | SyntaxKind.NewExpression | SyntaxKind.TaggedTemplateExpression | SyntaxKind.TypeAssertionExpression | SyntaxKind.ParenthesizedExpression | SyntaxKind.FunctionExpression | SyntaxKind.ArrowFunction | SyntaxKind.DeleteExpression | SyntaxKind.TypeOfExpression | SyntaxKind.VoidExpression | SyntaxKind.AwaitExpression | SyntaxKind.ConditionalExpression | SyntaxKind.TemplateExpression | SyntaxKind.YieldExpression | SyntaxKind.SpreadElementExpression | SyntaxKind.ClassExpression | SyntaxKind.OmittedExpression | SyntaxKind.ExpressionWithTypeArguments | SyntaxKind.AsExpression | SyntaxKind.NonNullExpression | SyntaxKind.TemplateSpan | SyntaxKind.SemicolonClassElement | SyntaxKind.Block | SyntaxKind.VariableStatement | SyntaxKind.EmptyStatement | SyntaxKind.ExpressionStatement | SyntaxKind.IfStatement | SyntaxKind.DoStatement | SyntaxKind.WhileStatement | SyntaxKind.ForStatement | SyntaxKind.ForInStatement | SyntaxKind.ForOfStatement | SyntaxKind.ContinueStatement | SyntaxKind.BreakStatement | SyntaxKind.ReturnStatement | SyntaxKind.WithStatement | SyntaxKind.SwitchStatement | SyntaxKind.LabeledStatement | SyntaxKind.ThrowStatement | SyntaxKind.TryStatement | SyntaxKind.DebuggerStatement | SyntaxKind.VariableDeclaration | SyntaxKind.VariableDeclarationList | SyntaxKind.FunctionDeclaration | SyntaxKind.ClassDeclaration | SyntaxKind.InterfaceDeclaration | SyntaxKind.TypeAliasDeclaration | SyntaxKind.EnumDeclaration | SyntaxKind.ModuleDeclaration | SyntaxKind.ModuleBlock | SyntaxKind.CaseBlock | SyntaxKind.NamespaceExportDeclaration | SyntaxKind.ImportEqualsDeclaration | SyntaxKind.ImportDeclaration | SyntaxKind.ImportClause | SyntaxKind.NamespaceImport | SyntaxKind.NamedImports | SyntaxKind.ImportSpecifier | SyntaxKind.ExportAssignment | SyntaxKind.ExportDeclaration | SyntaxKind.NamedExports | SyntaxKind.ExportSpecifier | SyntaxKind.MissingDeclaration | SyntaxKind.ExternalModuleReference | SyntaxKind.JsxElement | SyntaxKind.JsxSelfClosingElement | SyntaxKind.JsxOpeningElement | SyntaxKind.JsxText | SyntaxKind.JsxClosingElement | SyntaxKind.JsxAttribute | SyntaxKind.JsxSpreadAttribute | SyntaxKind.JsxExpression | SyntaxKind.CaseClause | SyntaxKind.DefaultClause | SyntaxKind.HeritageClause | SyntaxKind.CatchClause | SyntaxKind.PropertyAssignment | SyntaxKind.ShorthandPropertyAssignment | SyntaxKind.EnumMember | SyntaxKind.SourceFile | SyntaxKind.JSDocTypeExpression | SyntaxKind.JSDocAllType | SyntaxKind.JSDocUnknownType | SyntaxKind.JSDocArrayType | SyntaxKind.JSDocUnionType | SyntaxKind.JSDocTupleType | SyntaxKind.JSDocNullableType | SyntaxKind.JSDocNonNullableType | SyntaxKind.JSDocRecordType | SyntaxKind.JSDocRecordMember | SyntaxKind.JSDocTypeReference | SyntaxKind.JSDocOptionalType | SyntaxKind.JSDocFunctionType | SyntaxKind.JSDocVariadicType | SyntaxKind.JSDocConstructorType | SyntaxKind.JSDocThisType | SyntaxKind.JSDocComment | SyntaxKind.JSDocTag | SyntaxKind.JSDocParameterTag | SyntaxKind.JSDocReturnTag | SyntaxKind.JSDocTypeTag | SyntaxKind.JSDocTemplateTag | SyntaxKind.JSDocTypedefTag | SyntaxKind.JSDocPropertyTag | SyntaxKind.JSDocTypeLiteral | SyntaxKind.JSDocLiteralType | SyntaxKind.JSDocNullKeyword | SyntaxKind.JSDocUndefinedKeyword | SyntaxKind.JSDocNeverKeyword | SyntaxKind.SyntaxList | SyntaxKind.NotEmittedStatement | SyntaxKind.PartiallyEmittedExpression | SyntaxKind.Count; function getOperatorPrecedence(nodeKind: SyntaxKind, operatorKind: SyntaxKind, hasArguments?: boolean): 0 | 1 | -1 | 2 | 4 | 3 | 16 | 10 | 5 | 6 | 11 | 8 | 19 | 18 | 17 | 15 | 14 | 13 | 12 | 9 | 7; function createDiagnosticCollection(): DiagnosticCollection; function escapeString(s: string): string; @@ -7413,26 +8534,28 @@ declare namespace ts { function getIndentSize(): number; function createTextWriter(newLine: String): EmitTextWriter; function getResolvedExternalModuleName(host: EmitHost, file: SourceFile): string; - function getExternalModuleNameFromDeclaration(host: EmitHost, resolver: EmitResolver, declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration): string; + function getExternalModuleNameFromDeclaration(host: EmitHost, resolver: EmitResolver, declaration: ImportEqualsDeclaration | ImportDeclaration | ExportDeclaration | ModuleDeclaration): string; function getExternalModuleNameFromPath(host: EmitHost, fileName: string): string; function getOwnEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost, extension: string): string; function getDeclarationEmitOutputFilePath(sourceFile: SourceFile, host: EmitHost): string; - function getEmitScriptTarget(compilerOptions: CompilerOptions): ScriptTarget; - function getEmitModuleKind(compilerOptions: CompilerOptions): ModuleKind; interface EmitFileNames { jsFilePath: string; sourceMapFilePath: string; declarationFilePath: string; } function getSourceFilesToEmit(host: EmitHost, targetSourceFile?: SourceFile): SourceFile[]; - function forEachTransformedEmitFile(host: EmitHost, sourceFiles: SourceFile[], action: (jsFilePath: string, sourceMapFilePath: string, declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean) => void): void; - function forEachExpectedEmitFile(host: EmitHost, action: (emitFileNames: EmitFileNames, sourceFiles: SourceFile[], isBundledEmit: boolean) => void, targetSourceFile?: SourceFile): void; + function forEachTransformedEmitFile(host: EmitHost, sourceFiles: SourceFile[], action: (jsFilePath: string, sourceMapFilePath: string, declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean) => void, emitOnlyDtsFiles?: boolean): void; + function forEachExpectedEmitFile(host: EmitHost, action: (emitFileNames: EmitFileNames, sourceFiles: SourceFile[], isBundledEmit: boolean, emitOnlyDtsFiles: boolean) => void, targetSourceFile?: SourceFile, emitOnlyDtsFiles?: boolean): void; function getSourceFilePathInNewDir(sourceFile: SourceFile, host: EmitHost, newDirPath: string): string; function writeFile(host: EmitHost, diagnostics: DiagnosticCollection, fileName: string, data: string, writeByteOrderMark: boolean, sourceFiles?: SourceFile[]): void; function getLineOfLocalPosition(currentSourceFile: SourceFile, pos: number): number; function getLineOfLocalPositionFromLineMap(lineMap: number[], pos: number): number; function getFirstConstructorWithBody(node: ClassLikeDeclaration): ConstructorDeclaration; - function getSetAccessorTypeAnnotationNode(accessor: AccessorDeclaration): TypeNode; + function getSetAccessorTypeAnnotationNode(accessor: SetAccessorDeclaration): TypeNode; + function getThisParameter(signature: SignatureDeclaration): ParameterDeclaration | undefined; + function parameterIsThisKeyword(parameter: ParameterDeclaration): boolean; + function isThisIdentifier(node: Node | undefined): boolean; + function identifierIsThisKeyword(id: Identifier): boolean; interface AllAccessorDeclarations { firstAccessor: AccessorDeclaration; secondAccessor: AccessorDeclaration; @@ -7463,12 +8586,9 @@ declare namespace ts { function isRightSideOfQualifiedNameOrPropertyAccess(node: Node): boolean; function isEmptyObjectLiteralOrArrayLiteral(expression: Node): boolean; function getLocalSymbolForExportDefault(symbol: Symbol): Symbol; - function hasJavaScriptFileExtension(fileName: string): boolean; - function hasTypeScriptFileExtension(fileName: string): boolean; function tryExtractTypeScriptExtension(fileName: string): string | undefined; const stringify: (value: any) => string; function convertToBase64(input: string): string; - function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string; function getNewLineCharacter(options: CompilerOptions): string; function isSimpleExpression(node: Expression): boolean; function formatSyntaxKind(kind: SyntaxKind): string; @@ -7504,7 +8624,8 @@ declare namespace ts { function isTextualLiteralKind(kind: SyntaxKind): boolean; function isLiteralExpression(node: Node): node is LiteralExpression; function isTemplateLiteralKind(kind: SyntaxKind): boolean; - function isTemplateLiteralFragment(node: Node): node is TemplateLiteralFragment; + function isTemplateHead(node: Node): node is TemplateHead; + function isTemplateMiddleOrTemplateTail(node: Node): node is TemplateMiddle | TemplateTail; function isIdentifier(node: Node): node is Identifier; function isGeneratedIdentifier(node: Node): boolean; function isModifier(node: Node): node is Modifier; @@ -7529,7 +8650,7 @@ declare namespace ts { function isBinaryExpression(node: Node): node is BinaryExpression; function isConditionalExpression(node: Node): node is ConditionalExpression; function isCallExpression(node: Node): node is CallExpression; - function isTemplate(node: Node): node is Template; + function isTemplateLiteral(node: Node): node is TemplateLiteral; function isSpreadElementExpression(node: Node): node is SpreadElementExpression; function isExpressionWithTypeArguments(node: Node): node is ExpressionWithTypeArguments; function isLeftHandSideExpression(node: Node): node is LeftHandSideExpression; @@ -7613,24 +8734,25 @@ declare namespace ts { function createLiteral(textSource: StringLiteral | Identifier, location?: TextRange): StringLiteral; function createLiteral(value: string, location?: TextRange): StringLiteral; function createLiteral(value: number, location?: TextRange): NumericLiteral; + function createLiteral(value: boolean, location?: TextRange): BooleanLiteral; function createLiteral(value: string | number | boolean, location?: TextRange): PrimaryExpression; function createIdentifier(text: string, location?: TextRange): Identifier; function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined, location?: TextRange): Identifier; function createLoopVariable(location?: TextRange): Identifier; function createUniqueName(text: string, location?: TextRange): Identifier; function getGeneratedNameForNode(node: Node, location?: TextRange): Identifier; - function createToken(token: SyntaxKind): Node; + function createToken(token: TKind): Token; function createSuper(): PrimaryExpression; function createThis(location?: TextRange): PrimaryExpression; function createNull(): PrimaryExpression; function createComputedPropertyName(expression: Expression, location?: TextRange): ComputedPropertyName; function updateComputedPropertyName(node: ComputedPropertyName, expression: Expression): ComputedPropertyName; function createParameter(name: string | Identifier | BindingPattern, initializer?: Expression, location?: TextRange): ParameterDeclaration; - function createParameterDeclaration(decorators: Decorator[], modifiers: Modifier[], dotDotDotToken: Node, name: string | Identifier | BindingPattern, questionToken: Node, type: TypeNode, initializer: Expression, location?: TextRange, flags?: NodeFlags): ParameterDeclaration; + function createParameterDeclaration(decorators: Decorator[], modifiers: Modifier[], dotDotDotToken: DotDotDotToken, name: string | Identifier | BindingPattern, questionToken: QuestionToken, type: TypeNode, initializer: Expression, location?: TextRange, flags?: NodeFlags): ParameterDeclaration; function updateParameterDeclaration(node: ParameterDeclaration, decorators: Decorator[], modifiers: Modifier[], name: BindingName, type: TypeNode, initializer: Expression): ParameterDeclaration; - function createProperty(decorators: Decorator[], modifiers: Modifier[], name: string | PropertyName, questionToken: Node, type: TypeNode, initializer: Expression, location?: TextRange): PropertyDeclaration; + function createProperty(decorators: Decorator[], modifiers: Modifier[], name: string | PropertyName, questionToken: QuestionToken, type: TypeNode, initializer: Expression, location?: TextRange): PropertyDeclaration; function updateProperty(node: PropertyDeclaration, decorators: Decorator[], modifiers: Modifier[], name: PropertyName, type: TypeNode, initializer: Expression): PropertyDeclaration; - function createMethod(decorators: Decorator[], modifiers: Modifier[], asteriskToken: Node, name: string | PropertyName, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags): MethodDeclaration; + function createMethod(decorators: Decorator[], modifiers: Modifier[], asteriskToken: AsteriskToken, name: string | PropertyName, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags): MethodDeclaration; function updateMethod(node: MethodDeclaration, decorators: Decorator[], modifiers: Modifier[], name: PropertyName, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block): MethodDeclaration; function createConstructor(decorators: Decorator[], modifiers: Modifier[], parameters: ParameterDeclaration[], body: Block, location?: TextRange, flags?: NodeFlags): ConstructorDeclaration; function updateConstructor(node: ConstructorDeclaration, decorators: Decorator[], modifiers: Modifier[], parameters: ParameterDeclaration[], body: Block): ConstructorDeclaration; @@ -7642,7 +8764,7 @@ declare namespace ts { function updateObjectBindingPattern(node: ObjectBindingPattern, elements: BindingElement[]): ObjectBindingPattern; function createArrayBindingPattern(elements: ArrayBindingElement[], location?: TextRange): ArrayBindingPattern; function updateArrayBindingPattern(node: ArrayBindingPattern, elements: ArrayBindingElement[]): ArrayBindingPattern; - function createBindingElement(propertyName: string | PropertyName, dotDotDotToken: Node, name: string | BindingName, initializer?: Expression, location?: TextRange): BindingElement; + function createBindingElement(propertyName: string | PropertyName, dotDotDotToken: DotDotDotToken, name: string | BindingName, initializer?: Expression, location?: TextRange): BindingElement; function updateBindingElement(node: BindingElement, propertyName: PropertyName, name: BindingName, initializer: Expression): BindingElement; function createArrayLiteral(elements?: Expression[], location?: TextRange, multiLine?: boolean): ArrayLiteralExpression; function updateArrayLiteral(node: ArrayLiteralExpression, elements: Expression[]): ArrayLiteralExpression; @@ -7656,13 +8778,13 @@ declare namespace ts { function updateCall(node: CallExpression, expression: Expression, typeArguments: TypeNode[], argumentsArray: Expression[]): CallExpression; function createNew(expression: Expression, typeArguments: TypeNode[], argumentsArray: Expression[], location?: TextRange, flags?: NodeFlags): NewExpression; function updateNew(node: NewExpression, expression: Expression, typeArguments: TypeNode[], argumentsArray: Expression[]): NewExpression; - function createTaggedTemplate(tag: Expression, template: Template, location?: TextRange): TaggedTemplateExpression; - function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: Template): TaggedTemplateExpression; + function createTaggedTemplate(tag: Expression, template: TemplateLiteral, location?: TextRange): TaggedTemplateExpression; + function updateTaggedTemplate(node: TaggedTemplateExpression, tag: Expression, template: TemplateLiteral): TaggedTemplateExpression; function createParen(expression: Expression, location?: TextRange): ParenthesizedExpression; function updateParen(node: ParenthesizedExpression, expression: Expression): ParenthesizedExpression; - function createFunctionExpression(asteriskToken: Node, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags): FunctionExpression; + function createFunctionExpression(asteriskToken: AsteriskToken, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags): FunctionExpression; function updateFunctionExpression(node: FunctionExpression, name: Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block): FunctionExpression; - function createArrowFunction(modifiers: Modifier[], typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, equalsGreaterThanToken: Node, body: ConciseBody, location?: TextRange, flags?: NodeFlags): ArrowFunction; + function createArrowFunction(modifiers: Modifier[], typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, equalsGreaterThanToken: EqualsGreaterThanToken, body: ConciseBody, location?: TextRange, flags?: NodeFlags): ArrowFunction; function updateArrowFunction(node: ArrowFunction, modifiers: Modifier[], typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: ConciseBody): ArrowFunction; function createDelete(expression: Expression, location?: TextRange): DeleteExpression; function updateDelete(node: DeleteExpression, expression: Expression): Expression; @@ -7672,17 +8794,17 @@ declare namespace ts { function updateVoid(node: VoidExpression, expression: Expression): VoidExpression; function createAwait(expression: Expression, location?: TextRange): AwaitExpression; function updateAwait(node: AwaitExpression, expression: Expression): AwaitExpression; - function createPrefix(operator: SyntaxKind, operand: Expression, location?: TextRange): PrefixUnaryExpression; + function createPrefix(operator: PrefixUnaryOperator, operand: Expression, location?: TextRange): PrefixUnaryExpression; function updatePrefix(node: PrefixUnaryExpression, operand: Expression): PrefixUnaryExpression; - function createPostfix(operand: Expression, operator: SyntaxKind, location?: TextRange): PostfixUnaryExpression; + function createPostfix(operand: Expression, operator: PostfixUnaryOperator, location?: TextRange): PostfixUnaryExpression; function updatePostfix(node: PostfixUnaryExpression, operand: Expression): PostfixUnaryExpression; - function createBinary(left: Expression, operator: SyntaxKind | Node, right: Expression, location?: TextRange): BinaryExpression; + function createBinary(left: Expression, operator: BinaryOperator | BinaryOperatorToken, right: Expression, location?: TextRange): BinaryExpression; function updateBinary(node: BinaryExpression, left: Expression, right: Expression): BinaryExpression; - function createConditional(condition: Expression, questionToken: Node, whenTrue: Expression, colonToken: Node, whenFalse: Expression, location?: TextRange): ConditionalExpression; + function createConditional(condition: Expression, questionToken: QuestionToken, whenTrue: Expression, colonToken: ColonToken, whenFalse: Expression, location?: TextRange): ConditionalExpression; function updateConditional(node: ConditionalExpression, condition: Expression, whenTrue: Expression, whenFalse: Expression): ConditionalExpression; - function createTemplateExpression(head: TemplateLiteralFragment, templateSpans: TemplateSpan[], location?: TextRange): TemplateExpression; - function updateTemplateExpression(node: TemplateExpression, head: TemplateLiteralFragment, templateSpans: TemplateSpan[]): TemplateExpression; - function createYield(asteriskToken: Node, expression: Expression, location?: TextRange): YieldExpression; + function createTemplateExpression(head: TemplateHead, templateSpans: TemplateSpan[], location?: TextRange): TemplateExpression; + function updateTemplateExpression(node: TemplateExpression, head: TemplateHead, templateSpans: TemplateSpan[]): TemplateExpression; + function createYield(asteriskToken: AsteriskToken, expression: Expression, location?: TextRange): YieldExpression; function updateYield(node: YieldExpression, expression: Expression): YieldExpression; function createSpread(expression: Expression, location?: TextRange): SpreadElementExpression; function updateSpread(node: SpreadElementExpression, expression: Expression): SpreadElementExpression; @@ -7691,8 +8813,8 @@ declare namespace ts { function createOmittedExpression(location?: TextRange): OmittedExpression; function createExpressionWithTypeArguments(typeArguments: TypeNode[], expression: Expression, location?: TextRange): ExpressionWithTypeArguments; function updateExpressionWithTypeArguments(node: ExpressionWithTypeArguments, typeArguments: TypeNode[], expression: Expression): ExpressionWithTypeArguments; - function createTemplateSpan(expression: Expression, literal: TemplateLiteralFragment, location?: TextRange): TemplateSpan; - function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateLiteralFragment): TemplateSpan; + function createTemplateSpan(expression: Expression, literal: TemplateMiddle | TemplateTail, location?: TextRange): TemplateSpan; + function updateTemplateSpan(node: TemplateSpan, expression: Expression, literal: TemplateMiddle | TemplateTail): TemplateSpan; function createBlock(statements: Statement[], location?: TextRange, multiLine?: boolean, flags?: NodeFlags): Block; function updateBlock(node: Block, statements: Statement[]): Block; function createVariableStatement(modifiers: Modifier[], declarationList: VariableDeclarationList | VariableDeclaration[], location?: TextRange, flags?: NodeFlags): VariableStatement; @@ -7715,9 +8837,9 @@ declare namespace ts { function createForIn(initializer: ForInitializer, expression: Expression, statement: Statement, location?: TextRange): ForInStatement; function updateForIn(node: ForInStatement, initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; function createForOf(initializer: ForInitializer, expression: Expression, statement: Statement, location?: TextRange): ForOfStatement; - function updateForOf(node: ForInStatement, initializer: ForInitializer, expression: Expression, statement: Statement): ForInStatement; - function createContinue(label?: Identifier, location?: TextRange): BreakStatement; - function updateContinue(node: ContinueStatement, label: Identifier): BreakStatement; + function updateForOf(node: ForOfStatement, initializer: ForInitializer, expression: Expression, statement: Statement): ForOfStatement; + function createContinue(label?: Identifier, location?: TextRange): ContinueStatement; + function updateContinue(node: ContinueStatement, label: Identifier): ContinueStatement; function createBreak(label?: Identifier, location?: TextRange): BreakStatement; function updateBreak(node: BreakStatement, label: Identifier): BreakStatement; function createReturn(expression?: Expression, location?: TextRange): ReturnStatement; @@ -7734,7 +8856,7 @@ declare namespace ts { function updateTry(node: TryStatement, tryBlock: Block, catchClause: CatchClause, finallyBlock: Block): TryStatement; function createCaseBlock(clauses: CaseOrDefaultClause[], location?: TextRange): CaseBlock; function updateCaseBlock(node: CaseBlock, clauses: CaseOrDefaultClause[]): CaseBlock; - function createFunctionDeclaration(decorators: Decorator[], modifiers: Modifier[], asteriskToken: Node, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags): FunctionDeclaration; + function createFunctionDeclaration(decorators: Decorator[], modifiers: Modifier[], asteriskToken: AsteriskToken, name: string | Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block, location?: TextRange, flags?: NodeFlags): FunctionDeclaration; function updateFunctionDeclaration(node: FunctionDeclaration, decorators: Decorator[], modifiers: Modifier[], name: Identifier, typeParameters: TypeParameterDeclaration[], parameters: ParameterDeclaration[], type: TypeNode, body: Block): FunctionDeclaration; function createClassDeclaration(decorators: Decorator[], modifiers: Modifier[], name: Identifier, typeParameters: TypeParameterDeclaration[], heritageClauses: HeritageClause[], members: ClassElement[], location?: TextRange): ClassDeclaration; function updateClassDeclaration(node: ClassDeclaration, decorators: Decorator[], modifiers: Modifier[], name: Identifier, typeParameters: TypeParameterDeclaration[], heritageClauses: HeritageClause[], members: ClassElement[]): ClassDeclaration; @@ -7828,6 +8950,7 @@ declare namespace ts { function createExpressionForPropertyName(memberName: PropertyName): Expression; function createExpressionForObjectLiteralElementLike(node: ObjectLiteralExpression, property: ObjectLiteralElementLike, receiver: Expression): Expression; function addPrologueDirectives(target: Statement[], source: Statement[], ensureUseStrict?: boolean, visitor?: (node: Node) => VisitResult): number; + function ensureUseStrict(node: SourceFile): SourceFile; function parenthesizeBinaryOperand(binaryOperator: SyntaxKind, operand: Expression, isLeftSideOfBinary: boolean, leftOperand?: Expression): Expression; function parenthesizeForNew(expression: Expression): LeftHandSideExpression; function parenthesizeForAccess(expression: Expression): LeftHandSideExpression; @@ -7852,6 +8975,17 @@ declare namespace ts { function skipPartiallyEmittedExpressions(node: Node): Node; function startOnNewLine(node: T): T; function setOriginalNode(node: T, original: Node): T; + function disposeEmitNodes(sourceFile: SourceFile): void; + function getEmitFlags(node: Node): EmitFlags; + function setEmitFlags(node: T, emitFlags: EmitFlags): T; + function setSourceMapRange(node: T, range: TextRange): T; + function setTokenSourceMapRange(node: T, token: SyntaxKind, range: TextRange): T; + function setCommentRange(node: T, range: TextRange): T; + function getCommentRange(node: Node): TextRange; + function getSourceMapRange(node: Node): TextRange; + function getTokenSourceMapRange(node: Node, token: SyntaxKind): TextRange; + function getConstantValue(node: PropertyAccessExpression | ElementAccessExpression): number; + function setConstantValue(node: PropertyAccessExpression | ElementAccessExpression, value: number): PropertyAccessExpression | ElementAccessExpression; function setTextRange(node: T, location: TextRange): T; function setNodeFlags(node: T, flags: NodeFlags): T; function setMultiLine(node: T, multiLine: boolean): T; @@ -7940,34 +9074,22 @@ declare namespace ts { } declare namespace ts { interface TransformationResult { - getSourceFiles(): SourceFile[]; - getTokenSourceMapRange(node: Node, token: SyntaxKind): TextRange; - isSubstitutionEnabled(node: Node): boolean; - isEmitNotificationEnabled(node: Node): boolean; - onSubstituteNode(node: Node, isExpression: boolean): Node; - onEmitNode(node: Node, emitCallback: (node: Node) => void): void; - dispose(): void; + transformed: SourceFile[]; + emitNodeWithSubstitution(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void; + emitNodeWithNotification(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void; } interface TransformationContext extends LexicalEnvironment { getCompilerOptions(): CompilerOptions; getEmitResolver(): EmitResolver; getEmitHost(): EmitHost; - getNodeEmitFlags(node: Node): NodeEmitFlags; - setNodeEmitFlags(node: T, flags: NodeEmitFlags): T; - getSourceMapRange(node: Node): TextRange; - setSourceMapRange(node: T, range: TextRange): T; - getTokenSourceMapRange(node: Node, token: SyntaxKind): TextRange; - setTokenSourceMapRange(node: T, token: SyntaxKind, range: TextRange): T; - getCommentRange(node: Node): TextRange; - setCommentRange(node: T, range: TextRange): T; hoistFunctionDeclaration(node: FunctionDeclaration): void; hoistVariableDeclaration(node: Identifier): void; enableSubstitution(kind: SyntaxKind): void; isSubstitutionEnabled(node: Node): boolean; - onSubstituteNode?: (node: Node, isExpression: boolean) => Node; + onSubstituteNode?: (emitContext: EmitContext, node: Node) => Node; enableEmitNotification(kind: SyntaxKind): void; isEmitNotificationEnabled(node: Node): boolean; - onEmitNode?: (node: Node, emit: (node: Node) => void) => void; + onEmitNode?: (emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void) => void; } type Transformer = (context: TransformationContext) => (node: SourceFile) => SourceFile; function getTransformers(compilerOptions: CompilerOptions): Transformer[]; @@ -7975,63 +9097,40 @@ declare namespace ts { } declare namespace ts { function getDeclarationDiagnostics(host: EmitHost, resolver: EmitResolver, targetSourceFile: SourceFile): Diagnostic[]; - function writeDeclarationFile(declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean, host: EmitHost, resolver: EmitResolver, emitterDiagnostics: DiagnosticCollection): boolean; + function writeDeclarationFile(declarationFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean, host: EmitHost, resolver: EmitResolver, emitterDiagnostics: DiagnosticCollection, emitOnlyDtsFiles: boolean): boolean; } declare namespace ts { interface SourceMapWriter { initialize(filePath: string, sourceMapFilePath: string, sourceFiles: SourceFile[], isBundledEmit: boolean): void; reset(): void; - getSourceMapData(): SourceMapData; setSourceFile(sourceFile: SourceFile): void; emitPos(pos: number): void; - emitStart(range: TextRange): void; - emitStart(range: TextRange, contextNode: Node, ignoreNodeCallback: (node: Node) => boolean, ignoreChildrenCallback: (node: Node) => boolean, getTextRangeCallbackCallback: (node: Node) => TextRange): void; - emitEnd(range: TextRange): void; - emitEnd(range: TextRange, contextNode: Node, ignoreNodeCallback: (node: Node) => boolean, ignoreChildrenCallback: (node: Node) => boolean, getTextRangeCallbackCallback: (node: Node) => TextRange): void; - emitTokenStart(token: SyntaxKind, tokenStartPos: number): number; - emitTokenStart(token: SyntaxKind, tokenStartPos: number, contextNode: Node, ignoreTokenCallback: (node: Node, token: SyntaxKind) => boolean, getTokenTextRangeCallback: (node: Node, token: SyntaxKind) => TextRange): number; - emitTokenEnd(token: SyntaxKind, tokenEndPos: number): number; - emitTokenEnd(token: SyntaxKind, tokenEndPos: number, contextNode: Node, ignoreTokenCallback: (node: Node, token: SyntaxKind) => boolean, getTokenTextRangeCallback: (node: Node, token: SyntaxKind) => TextRange): number; - changeEmitSourcePos(): void; - stopOverridingSpan(): void; + emitNodeWithSourceMap(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void; + emitTokenWithSourceMap(node: Node, token: SyntaxKind, tokenStartPos: number, emitCallback: (token: SyntaxKind, tokenStartPos: number) => number): number; getText(): string; getSourceMappingURL(): string; + getSourceMapData(): SourceMapData; } function createSourceMapWriter(host: EmitHost, writer: EmitTextWriter): SourceMapWriter; - function getNullSourceMapWriter(): SourceMapWriter; } declare namespace ts { interface CommentWriter { reset(): void; setSourceFile(sourceFile: SourceFile): void; - emitNodeWithComments(node: Node, emitCallback: (node: Node) => void): void; + emitNodeWithComments(emitContext: EmitContext, node: Node, emitCallback: (emitContext: EmitContext, node: Node) => void): void; emitBodyWithDetachedComments(node: Node, detachedRange: TextRange, emitCallback: (node: Node) => void): void; emitTrailingCommentsOfPosition(pos: number): void; } function createCommentWriter(host: EmitHost, writer: EmitTextWriter, sourceMap: SourceMapWriter): CommentWriter; } declare namespace ts { - function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile): EmitResult; + function emitFiles(resolver: EmitResolver, host: EmitHost, targetSourceFile: SourceFile, emitOnlyDtsFiles?: boolean): EmitResult; } declare namespace ts { const version = "2.1.0"; function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; function resolveTripleslashReference(moduleName: string, containingFile: string): string; function computeCommonSourceDirectoryOfFilenames(fileNames: string[], currentDirectory: string, getCanonicalFileName: (fileName: string) => string): string; - function hasZeroOrOneAsteriskCharacter(str: string): boolean; - function getEffectiveTypeRoots(options: CompilerOptions, host: { - directoryExists?: (directoryName: string) => boolean; - getCurrentDirectory?: () => string; - }): string[] | undefined; - function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function findBestPatternMatch(values: T[], getPattern: (value: T) => Pattern, candidate: string): T | undefined; - function tryParsePattern(pattern: string): Pattern | undefined; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function directoryProbablyExists(directoryName: string, host: { - directoryExists?: (directoryName: string) => boolean; - }): boolean; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; interface FormatDiagnosticsHost { @@ -8041,7 +9140,6 @@ declare namespace ts { } function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; - function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts { @@ -8135,6 +9233,7 @@ declare namespace ts { readDirectory?(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; readFile?(path: string, encoding?: string): string; fileExists?(path: string): boolean; + getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; directoryExists?(directoryName: string): boolean; @@ -8165,18 +9264,20 @@ declare namespace ts { findReferences(fileName: string, position: number): ReferencedSymbol[]; getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): NavigateToItem[]; + getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; + getNavigationTree(fileName: string): NavigationTree; getOutliningSpans(fileName: string): OutliningSpan[]; getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; - getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number; - getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[]; - getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[]; - getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[]; + getIndentationAtPosition(fileName: string, position: number, options: EditorOptions | EditorSettings): number; + getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; - getEmitOutput(fileName: string): EmitOutput; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[]): CodeAction[]; + getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; getNonBoundSourceFile(fileName: string): SourceFile; getSourceFile(fileName: string): SourceFile; @@ -8200,6 +9301,13 @@ declare namespace ts { bolded: boolean; grayed: boolean; } + interface NavigationTree { + text: string; + kind: string; + kindModifiers: string; + spans: TextSpan[]; + childItems?: NavigationTree[]; + } interface TodoCommentDescriptor { text: string; priority: number; @@ -8213,6 +9321,14 @@ declare namespace ts { span: TextSpan; newText: string; } + interface FileTextChanges { + fileName: string; + textChanges: TextChange[]; + } + interface CodeAction { + description: string; + changes: FileTextChanges[]; + } interface TextInsertion { newText: string; caretOffset: number; @@ -8257,6 +9373,11 @@ declare namespace ts { containerName: string; containerKind: string; } + enum IndentStyle { + None = 0, + Block = 1, + Smart = 2, + } interface EditorOptions { BaseIndentSize?: number; IndentSize: number; @@ -8265,10 +9386,13 @@ declare namespace ts { ConvertTabsToSpaces: boolean; IndentStyle: IndentStyle; } - enum IndentStyle { - None = 0, - Block = 1, - Smart = 2, + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle; } interface FormatCodeOptions extends EditorOptions { InsertSpaceAfterCommaDelimiter: boolean; @@ -8284,7 +9408,21 @@ declare namespace ts { InsertSpaceAfterTypeAssertion?: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; - [s: string]: boolean | number | string | undefined; + } + interface FormatCodeSettings extends EditorSettings { + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; } interface DefinitionInfo { fileName: string; @@ -8367,6 +9505,7 @@ declare namespace ts { argumentCount: number; } interface CompletionInfo { + isGlobalCompletion: boolean; isMemberCompletion: boolean; isNewIdentifierLocation: boolean; entries: CompletionEntry[]; @@ -8628,7 +9767,7 @@ declare namespace ts { function stripQuotes(name: string): string; function scriptKindIs(fileName: string, host: LanguageServiceHost, ...scriptKinds: ScriptKind[]): boolean; function getScriptKind(fileName: string, host?: LanguageServiceHost): ScriptKind; - function parseAndReEmitConfigJSONFile(content: string): { + function sanitizeConfigFile(configFileName: string, content: string): { configJsonObject: any; diagnostics: Diagnostic[]; }; @@ -8686,24 +9825,12 @@ declare namespace ts.JsDoc { function getAllJsDocCompletionEntries(): CompletionEntry[]; function getDocCommentTemplateAtPosition(newLine: string, sourceFile: SourceFile, position: number): TextInsertion; } -declare namespace ts.JsTyping { - interface TypingResolutionHost { - directoryExists: (path: string) => boolean; - fileExists: (fileName: string) => boolean; - readFile: (path: string, encoding?: string) => string; - readDirectory: (rootDir: string, extensions: string[], excludes: string[], includes: string[], depth?: number) => string[]; - } - function discoverTypings(host: TypingResolutionHost, fileNames: string[], projectRootPath: Path, safeListPath: Path, packageNameToTypingLocation: Map, typingOptions: TypingOptions, compilerOptions: CompilerOptions): { - cachedTypingPaths: string[]; - newTypingNames: string[]; - filesToWatch: string[]; - }; -} declare namespace ts.NavigateTo { - function getNavigateToItems(sourceFiles: SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number): NavigateToItem[]; + function getNavigateToItems(sourceFiles: SourceFile[], checker: TypeChecker, cancellationToken: CancellationToken, searchValue: string, maxResultCount: number, excludeDtsFiles: boolean): NavigateToItem[]; } declare namespace ts.NavigationBar { function getNavigationBarItems(sourceFile: SourceFile): NavigationBarItem[]; + function getNavigationTree(sourceFile: SourceFile): NavigationTree; } declare namespace ts.OutliningElementsCollector { function collectElements(sourceFile: SourceFile): OutliningSpan[]; @@ -9148,7 +10275,7 @@ declare namespace ts.formatting { getRuleName(rule: Rule): string; getRuleByName(name: string): Rule; getRulesMap(): RulesMap; - ensureUpToDate(options: ts.FormatCodeOptions): void; + ensureUpToDate(options: ts.FormatCodeSettings): void; private createActiveRules(options); } } @@ -9161,35 +10288,58 @@ declare namespace ts.formatting { token: TextRangeWithKind; trailingTrivia: TextRangeWithKind[]; } - function formatOnEnter(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[]; - function formatOnSemicolon(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[]; - function formatOnClosingCurly(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[]; - function formatDocument(sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[]; - function formatSelection(start: number, end: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeOptions): TextChange[]; - function getIndentationString(indentation: number, options: FormatCodeOptions): string; + function formatOnEnter(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[]; + function formatOnSemicolon(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[]; + function formatOnClosingCurly(position: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[]; + function formatDocument(sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[]; + function formatSelection(start: number, end: number, sourceFile: SourceFile, rulesProvider: RulesProvider, options: FormatCodeSettings): TextChange[]; + function getIndentationString(indentation: number, options: EditorSettings): string; } declare namespace ts.formatting { namespace SmartIndenter { - function getIndentation(position: number, sourceFile: SourceFile, options: EditorOptions): number; - function getBaseIndentation(options: EditorOptions): number; - function getIndentationForNode(n: Node, ignoreActualIndentationRange: TextRange, sourceFile: SourceFile, options: FormatCodeOptions): number; + function getIndentation(position: number, sourceFile: SourceFile, options: EditorSettings): number; + function getIndentationForNode(n: Node, ignoreActualIndentationRange: TextRange, sourceFile: SourceFile, options: EditorSettings): number; + function getBaseIndentation(options: EditorSettings): number; function childStartsOnTheSameLineWithElseInIfStatement(parent: Node, child: TextRangeWithKind, childStartLine: number, sourceFile: SourceFile): boolean; - function findFirstNonWhitespaceCharacterAndColumn(startPos: number, endPos: number, sourceFile: SourceFile, options: EditorOptions): { + function findFirstNonWhitespaceCharacterAndColumn(startPos: number, endPos: number, sourceFile: SourceFile, options: EditorSettings): { column: number; character: number; }; - function findFirstNonWhitespaceColumn(startPos: number, endPos: number, sourceFile: SourceFile, options: EditorOptions): number; + function findFirstNonWhitespaceColumn(startPos: number, endPos: number, sourceFile: SourceFile, options: EditorSettings): number; function nodeWillIndentChild(parent: TextRangeWithKind, child: TextRangeWithKind, indentByDefault: boolean): boolean; function shouldIndentChildNode(parent: TextRangeWithKind, child?: TextRangeWithKind): boolean; } } +declare namespace ts { + interface CodeFix { + errorCodes: number[]; + getCodeActions(context: CodeFixContext): CodeAction[] | undefined; + } + interface CodeFixContext { + errorCode: number; + sourceFile: SourceFile; + span: TextSpan; + program: Program; + newLineCharacter: string; + } + namespace codefix { + function registerCodeFix(action: CodeFix): void; + function getSupportedErrorCodes(): string[]; + function getFixes(context: CodeFixContext): CodeAction[]; + } +} +declare namespace ts.codefix { +} declare namespace ts { const servicesVersion = "0.5"; interface DisplayPartsSymbolWriter extends SymbolWriter { displayParts(): SymbolDisplayPart[]; } + function toEditorSettings(options: FormatCodeOptions | FormatCodeSettings): FormatCodeSettings; + function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; function displayPartsToString(displayParts: SymbolDisplayPart[]): string; function getDefaultCompilerOptions(): CompilerOptions; + function getSupportedCodeFixes(): string[]; function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; @@ -9198,101 +10348,516 @@ declare namespace ts { function getDefaultLibFilePath(options: CompilerOptions): string; } declare namespace ts.server { - function generateSpaces(n: number): string; - function generateIndentString(n: number, editorOptions: EditorOptions): string; + class ScriptInfo { + private readonly host; + readonly fileName: NormalizedPath; + readonly scriptKind: ScriptKind; + isOpen: boolean; + hasMixedContent: boolean; + readonly containingProjects: Project[]; + private formatCodeSettings; + readonly path: Path; + private fileWatcher; + private svc; + constructor(host: ServerHost, fileName: NormalizedPath, content: string, scriptKind: ScriptKind, isOpen?: boolean, hasMixedContent?: boolean); + getFormatCodeSettings(): FormatCodeSettings; + attachToProject(project: Project): boolean; + isAttached(project: Project): boolean; + detachFromProject(project: Project): void; + detachAllProjects(): void; + getDefaultProject(): Project; + setFormatOptions(formatSettings: FormatCodeSettings): void; + setWatcher(watcher: FileWatcher): void; + stopWatcher(): void; + getLatestVersion(): string; + reload(script: string): void; + saveTo(fileName: string): void; + reloadFromFile(): void; + snap(): LineIndexSnapshot; + getLineInfo(line: number): ILineInfo; + editContent(start: number, end: number, newText: string): void; + markContainingProjectsAsDirty(): void; + lineToTextSpan(line: number): TextSpan; + lineOffsetToPosition(line: number, offset: number): number; + positionToLineOffset(position: number): ILineInfo; + } +} +declare namespace ts.server { + class LSHost implements ts.LanguageServiceHost, ModuleResolutionHost, ServerLanguageServiceHost { + private readonly host; + private readonly project; + private readonly cancellationToken; + private compilationSettings; + private readonly resolvedModuleNames; + private readonly resolvedTypeReferenceDirectives; + private readonly getCanonicalFileName; + private readonly resolveModuleName; + readonly trace: (s: string) => void; + constructor(host: ServerHost, project: Project, cancellationToken: HostCancellationToken); + private resolveNamesWithLocalCache(names, containingFile, cache, loader, getResult); + getProjectVersion(): string; + getCompilationSettings(): CompilerOptions; + useCaseSensitiveFileNames(): boolean; + getCancellationToken(): HostCancellationToken; + resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; + resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModule[]; + getDefaultLibFileName(): string; + getScriptSnapshot(filename: string): ts.IScriptSnapshot; + getScriptFileNames(): string[]; + getTypeRootsVersion(): number; + getScriptKind(fileName: string): ScriptKind; + getScriptVersion(filename: string): string; + getCurrentDirectory(): string; + resolvePath(path: string): string; + fileExists(path: string): boolean; + readFile(fileName: string): string; + directoryExists(path: string): boolean; + readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; + getDirectories(path: string): string[]; + notifyFileRemoved(info: ScriptInfo): void; + setCompilationSettings(opt: ts.CompilerOptions): void; + } +} +declare namespace ts.server { + interface ITypingsInstaller { + enqueueInstallTypingsRequest(p: Project, typingOptions: TypingOptions): void; + attach(projectService: ProjectService): void; + onProjectClosed(p: Project): void; + readonly globalTypingsCacheLocation: string; + } + const nullTypingsInstaller: ITypingsInstaller; + interface TypingsArray extends ReadonlyArray { + " __typingsArrayBrand": any; + } + class TypingsCache { + private readonly installer; + private readonly perProjectCache; + constructor(installer: ITypingsInstaller); + getTypingsForProject(project: Project, forceRefresh: boolean): TypingsArray; + invalidateCachedTypingsForProject(project: Project): void; + updateTypingsForProject(projectName: string, compilerOptions: CompilerOptions, typingOptions: TypingOptions, newTypings: string[]): void; + onProjectClosed(project: Project): void; + } +} +declare namespace ts.server { + function shouldEmitFile(scriptInfo: ScriptInfo): boolean; + class BuilderFileInfo { + readonly scriptInfo: ScriptInfo; + readonly project: Project; + private lastCheckedShapeSignature; + constructor(scriptInfo: ScriptInfo, project: Project); + isExternalModuleOrHasOnlyAmbientExternalModules(): boolean; + private containsOnlyAmbientModules(sourceFile); + private computeHash(text); + private getSourceFile(); + updateShapeSignature(): boolean; + } + interface Builder { + readonly project: Project; + getFilesAffectedBy(scriptInfo: ScriptInfo): string[]; + onProjectUpdateGraph(): void; + emitFile(scriptInfo: ScriptInfo, writeFile: (path: string, data: string, writeByteOrderMark?: boolean) => void): boolean; + } + function createBuilder(project: Project): Builder; +} +declare namespace ts.server { + enum ProjectKind { + Inferred = 0, + Configured = 1, + External = 2, + } + function allRootFilesAreJsOrDts(project: Project): boolean; + function allFilesAreJsOrDts(project: Project): boolean; + interface ProjectFilesWithTSDiagnostics extends protocol.ProjectFiles { + projectErrors: Diagnostic[]; + } + abstract class Project { + readonly projectKind: ProjectKind; + readonly projectService: ProjectService; + private documentRegistry; + languageServiceEnabled: boolean; + private compilerOptions; + compileOnSaveEnabled: boolean; + private rootFiles; + private rootFilesMap; + private lsHost; + private program; + private languageService; + builder: Builder; + private lastReportedFileNames; + private lastReportedVersion; + private projectStructureVersion; + private projectStateVersion; + private typingFiles; + protected projectErrors: Diagnostic[]; + typesVersion: number; + isNonTsProject(): boolean; + isJsOnlyProject(): boolean; + constructor(projectKind: ProjectKind, projectService: ProjectService, documentRegistry: ts.DocumentRegistry, hasExplicitListOfFiles: boolean, languageServiceEnabled: boolean, compilerOptions: CompilerOptions, compileOnSaveEnabled: boolean); + getProjectErrors(): Diagnostic[]; + getLanguageService(ensureSynchronized?: boolean): LanguageService; + getCompileOnSaveAffectedFileList(scriptInfo: ScriptInfo): string[]; + getProjectVersion(): string; + enableLanguageService(): void; + disableLanguageService(): void; + abstract getProjectName(): string; + abstract getProjectRootPath(): string | undefined; + abstract getTypingOptions(): TypingOptions; + getSourceFile(path: Path): SourceFile; + updateTypes(): void; + close(): void; + getCompilerOptions(): CompilerOptions; + hasRoots(): boolean; + getRootFiles(): NormalizedPath[]; + getRootFilesLSHost(): string[]; + getRootScriptInfos(): ScriptInfo[]; + getScriptInfos(): ScriptInfo[]; + getFileEmitOutput(info: ScriptInfo, emitOnlyDtsFiles: boolean): EmitOutput; + getFileNames(): NormalizedPath[]; + getAllEmittableFiles(): string[]; + containsScriptInfo(info: ScriptInfo): boolean; + containsFile(filename: NormalizedPath, requireOpen?: boolean): boolean; + isRoot(info: ScriptInfo): boolean; + addRoot(info: ScriptInfo): void; + removeFile(info: ScriptInfo, detachFromProject?: boolean): void; + markAsDirty(): void; + updateGraph(): boolean; + private setTypings(typings); + private updateGraphWorker(); + getScriptInfoLSHost(fileName: string): ScriptInfo; + getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo; + getScriptInfo(uncheckedFileName: string): ScriptInfo; + filesToString(): string; + setCompilerOptions(compilerOptions: CompilerOptions): void; + reloadScript(filename: NormalizedPath): boolean; + getChangesSinceVersion(lastKnownVersion?: number): ProjectFilesWithTSDiagnostics; + getReferencedFiles(path: Path): Path[]; + private removeRootFileIfNecessary(info); + } + class InferredProject extends Project { + compileOnSaveEnabled: boolean; + private static NextId; + private readonly inferredProjectName; + directoriesWatchedForTsconfig: string[]; + constructor(projectService: ProjectService, documentRegistry: ts.DocumentRegistry, languageServiceEnabled: boolean, compilerOptions: CompilerOptions, compileOnSaveEnabled: boolean); + getProjectName(): string; + getProjectRootPath(): string; + close(): void; + getTypingOptions(): TypingOptions; + } + class ConfiguredProject extends Project { + readonly configFileName: NormalizedPath; + private wildcardDirectories; + compileOnSaveEnabled: boolean; + private typingOptions; + private projectFileWatcher; + private directoryWatcher; + private directoriesWatchedForWildcards; + private typeRootsWatchers; + openRefCount: number; + constructor(configFileName: NormalizedPath, projectService: ProjectService, documentRegistry: ts.DocumentRegistry, hasExplicitListOfFiles: boolean, compilerOptions: CompilerOptions, wildcardDirectories: Map, languageServiceEnabled: boolean, compileOnSaveEnabled: boolean); + getProjectRootPath(): string; + setProjectErrors(projectErrors: Diagnostic[]): void; + setTypingOptions(newTypingOptions: TypingOptions): void; + getTypingOptions(): TypingOptions; + getProjectName(): NormalizedPath; + watchConfigFile(callback: (project: ConfiguredProject) => void): void; + watchTypeRoots(callback: (project: ConfiguredProject, path: string) => void): void; + watchConfigDirectory(callback: (project: ConfiguredProject, path: string) => void): void; + watchWildcards(callback: (project: ConfiguredProject, path: string) => void): void; + stopWatchingDirectory(): void; + close(): void; + addOpenRef(): void; + deleteOpenRef(): number; + getEffectiveTypeRoots(): string[]; + } + class ExternalProject extends Project { + readonly externalProjectName: string; + compileOnSaveEnabled: boolean; + private readonly projectFilePath; + private typingOptions; + constructor(externalProjectName: string, projectService: ProjectService, documentRegistry: ts.DocumentRegistry, compilerOptions: CompilerOptions, languageServiceEnabled: boolean, compileOnSaveEnabled: boolean, projectFilePath?: string); + getProjectRootPath(): string; + getTypingOptions(): TypingOptions; + setProjectErrors(projectErrors: Diagnostic[]): void; + setTypingOptions(newTypingOptions: TypingOptions): void; + getProjectName(): string; + } +} +declare namespace ts.server { + const maxProgramSizeForNonTsFiles: number; + type ProjectServiceEvent = { + eventName: "context"; + data: { + project: Project; + fileName: NormalizedPath; + }; + } | { + eventName: "configFileDiag"; + data: { + triggerFile?: string; + configFileName: string; + diagnostics: Diagnostic[]; + }; + }; + interface ProjectServiceEventHandler { + (event: ProjectServiceEvent): void; + } + function combineProjectOutput(projects: Project[], action: (project: Project) => T[], comparer?: (a: T, b: T) => number, areEqual?: (a: T, b: T) => boolean): T[]; + interface HostConfiguration { + formatCodeOptions: FormatCodeSettings; + hostInfo: string; + } + interface OpenConfiguredProjectResult { + configFileName?: string; + configFileErrors?: Diagnostic[]; + } + class ProjectService { + readonly host: ServerHost; + readonly logger: Logger; + readonly cancellationToken: HostCancellationToken; + readonly useSingleInferredProject: boolean; + readonly typingsInstaller: ITypingsInstaller; + private readonly eventHandler; + readonly typingsCache: TypingsCache; + private readonly documentRegistry; + private readonly filenameToScriptInfo; + private readonly externalProjectToConfiguredProjectMap; + readonly externalProjects: ExternalProject[]; + readonly inferredProjects: InferredProject[]; + readonly configuredProjects: ConfiguredProject[]; + readonly openFiles: ScriptInfo[]; + private compilerOptionsForInferredProjects; + private compileOnSaveForInferredProjects; + private readonly directoryWatchers; + private readonly throttledOperations; + private readonly hostConfiguration; + private changedFiles; + private toCanonicalFileName; + lastDeletedFile: ScriptInfo; + constructor(host: ServerHost, logger: Logger, cancellationToken: HostCancellationToken, useSingleInferredProject: boolean, typingsInstaller?: ITypingsInstaller, eventHandler?: ProjectServiceEventHandler); + getChangedFiles_TestOnly(): ScriptInfo[]; + ensureInferredProjectsUpToDate_TestOnly(): void; + updateTypingsForProject(response: SetTypings | InvalidateCachedTypings): void; + setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.ExternalProjectCompilerOptions): void; + stopWatchingDirectory(directory: string): void; + findProject(projectName: string): Project; + getDefaultProjectForFile(fileName: NormalizedPath, refreshInferredProjects: boolean): Project; + private ensureInferredProjectsUpToDate(); + private findContainingExternalProject(fileName); + getFormatCodeOptions(file?: NormalizedPath): FormatCodeSettings; + private updateProjectGraphs(projects); + private onSourceFileChanged(fileName); + private handleDeletedFile(info); + private onTypeRootFileChanged(project, fileName); + private onSourceFileInDirectoryChangedForConfiguredProject(project, fileName); + private handleChangeInSourceFileForConfiguredProject(project); + private onConfigChangedForConfiguredProject(project); + private onConfigFileAddedForInferredProject(fileName); + private getCanonicalFileName(fileName); + private removeProject(project); + private assignScriptInfoToInferredProjectIfNecessary(info, addToListOfOpenFiles); + private closeOpenFile(info); + private openOrUpdateConfiguredProjectForFile(fileName); + private findConfigFile(searchPath); + private printProjects(); + private findConfiguredProjectByProjectName(configFileName); + private findExternalProjectByProjectName(projectFileName); + private convertConfigFileContentToProjectOptions(configFilename); + private exceededTotalSizeLimitForNonTsFiles(options, fileNames, propertyReader); + private createAndAddExternalProject(projectFileName, files, options, typingOptions); + private reportConfigFileDiagnostics(configFileName, diagnostics, triggerFile?); + private createAndAddConfiguredProject(configFileName, projectOptions, configFileErrors, clientFileName?); + private watchConfigDirectoryForProject(project, options); + private addFilesToProjectAndUpdateGraph(project, files, propertyReader, clientFileName, typingOptions, configFileErrors); + private openConfigFile(configFileName, clientFileName?); + private updateNonInferredProject(project, newUncheckedFiles, propertyReader, newOptions, newTypingOptions, compileOnSave, configFileErrors); + private updateConfiguredProject(project); + createInferredProjectWithRootFileIfNecessary(root: ScriptInfo): InferredProject; + getOrCreateScriptInfo(uncheckedFileName: string, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind): ScriptInfo; + getScriptInfo(uncheckedFileName: string): ScriptInfo; + getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean): ScriptInfo; + getScriptInfoForNormalizedPath(fileName: NormalizedPath): ScriptInfo; + getScriptInfoForPath(fileName: Path): ScriptInfo; + setHostConfiguration(args: protocol.ConfigureRequestArguments): void; + closeLog(): void; + reloadProjects(): void; + refreshInferredProjects(): void; + openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind): OpenConfiguredProjectResult; + openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean): OpenConfiguredProjectResult; + closeClientFile(uncheckedFileName: string): void; + private collectChanges(lastKnownProjectVersions, currentProjects, result); + synchronizeProjectList(knownProjects: protocol.ProjectVersionInfo[]): ProjectFilesWithTSDiagnostics[]; + applyChangesInOpenFiles(openFiles: protocol.ExternalFile[], changedFiles: protocol.ChangedOpenFile[], closedFiles: string[]): void; + private closeConfiguredProject(configFile); + closeExternalProject(uncheckedFileName: string, suppressRefresh?: boolean): void; + openExternalProject(proj: protocol.ExternalProject): void; + } +} +declare namespace ts.server { interface PendingErrorCheck { - fileName: string; + fileName: NormalizedPath; project: Project; } namespace CommandNames { - const Brace = "brace"; - const Change = "change"; - const Close = "close"; - const Completions = "completions"; - const CompletionDetails = "completionEntryDetails"; - const Configure = "configure"; - const Definition = "definition"; - const Exit = "exit"; - const Format = "format"; - const Formatonkey = "formatonkey"; - const Geterr = "geterr"; - const GeterrForProject = "geterrForProject"; - const Implementation = "implementation"; - const SemanticDiagnosticsSync = "semanticDiagnosticsSync"; - const SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; - const NavBar = "navbar"; - const Navto = "navto"; - const Occurrences = "occurrences"; - const DocumentHighlights = "documentHighlights"; - const Open = "open"; - const Quickinfo = "quickinfo"; - const References = "references"; - const Reload = "reload"; - const Rename = "rename"; - const Saveto = "saveto"; - const SignatureHelp = "signatureHelp"; - const TypeDefinition = "typeDefinition"; - const ProjectInfo = "projectInfo"; - const ReloadProjects = "reloadProjects"; - const Unknown = "unknown"; - } - interface ServerHost extends ts.System { - setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; - clearTimeout(timeoutId: any): void; + const Brace: protocol.CommandTypes.Brace; + const BraceFull: protocol.CommandTypes.BraceFull; + const BraceCompletion: protocol.CommandTypes.BraceCompletion; + const Change: protocol.CommandTypes.Change; + const Close: protocol.CommandTypes.Close; + const Completions: protocol.CommandTypes.Completions; + const CompletionsFull: protocol.CommandTypes.CompletionsFull; + const CompletionDetails: protocol.CommandTypes.CompletionDetails; + const CompileOnSaveAffectedFileList: protocol.CommandTypes.CompileOnSaveAffectedFileList; + const CompileOnSaveEmitFile: protocol.CommandTypes.CompileOnSaveEmitFile; + const Configure: protocol.CommandTypes.Configure; + const Definition: protocol.CommandTypes.Definition; + const DefinitionFull: protocol.CommandTypes.DefinitionFull; + const Exit: protocol.CommandTypes.Exit; + const Format: protocol.CommandTypes.Format; + const Formatonkey: protocol.CommandTypes.Formatonkey; + const FormatFull: protocol.CommandTypes.FormatFull; + const FormatonkeyFull: protocol.CommandTypes.FormatonkeyFull; + const FormatRangeFull: protocol.CommandTypes.FormatRangeFull; + const Geterr: protocol.CommandTypes.Geterr; + const GeterrForProject: protocol.CommandTypes.GeterrForProject; + const Implementation: protocol.CommandTypes.Implementation; + const ImplementationFull: protocol.CommandTypes.ImplementationFull; + const SemanticDiagnosticsSync: protocol.CommandTypes.SemanticDiagnosticsSync; + const SyntacticDiagnosticsSync: protocol.CommandTypes.SyntacticDiagnosticsSync; + const NavBar: protocol.CommandTypes.NavBar; + const NavBarFull: protocol.CommandTypes.NavBarFull; + const NavTree: protocol.CommandTypes.NavTree; + const NavTreeFull: protocol.CommandTypes.NavTreeFull; + const Navto: protocol.CommandTypes.Navto; + const NavtoFull: protocol.CommandTypes.NavtoFull; + const Occurrences: protocol.CommandTypes.Occurrences; + const DocumentHighlights: protocol.CommandTypes.DocumentHighlights; + const DocumentHighlightsFull: protocol.CommandTypes.DocumentHighlightsFull; + const Open: protocol.CommandTypes.Open; + const Quickinfo: protocol.CommandTypes.Quickinfo; + const QuickinfoFull: protocol.CommandTypes.QuickinfoFull; + const References: protocol.CommandTypes.References; + const ReferencesFull: protocol.CommandTypes.ReferencesFull; + const Reload: protocol.CommandTypes.Reload; + const Rename: protocol.CommandTypes.Rename; + const RenameInfoFull: protocol.CommandTypes.RenameInfoFull; + const RenameLocationsFull: protocol.CommandTypes.RenameLocationsFull; + const Saveto: protocol.CommandTypes.Saveto; + const SignatureHelp: protocol.CommandTypes.SignatureHelp; + const SignatureHelpFull: protocol.CommandTypes.SignatureHelpFull; + const TypeDefinition: protocol.CommandTypes.TypeDefinition; + const ProjectInfo: protocol.CommandTypes.ProjectInfo; + const ReloadProjects: protocol.CommandTypes.ReloadProjects; + const Unknown: protocol.CommandTypes.Unknown; + const OpenExternalProject: protocol.CommandTypes.OpenExternalProject; + const OpenExternalProjects: protocol.CommandTypes.OpenExternalProjects; + const CloseExternalProject: protocol.CommandTypes.CloseExternalProject; + const SynchronizeProjectList: protocol.CommandTypes.SynchronizeProjectList; + const ApplyChangedToOpenFiles: protocol.CommandTypes.ApplyChangedToOpenFiles; + const EncodedSemanticClassificationsFull: protocol.CommandTypes.EncodedSemanticClassificationsFull; + const Cleanup: protocol.CommandTypes.Cleanup; + const OutliningSpans: protocol.CommandTypes.OutliningSpans; + const TodoComments: protocol.CommandTypes.TodoComments; + const Indentation: protocol.CommandTypes.Indentation; + const DocCommentTemplate: protocol.CommandTypes.DocCommentTemplate; + const CompilerOptionsDiagnosticsFull: protocol.CommandTypes.CompilerOptionsDiagnosticsFull; + const NameOrDottedNameSpan: protocol.CommandTypes.NameOrDottedNameSpan; + const BreakpointStatement: protocol.CommandTypes.BreakpointStatement; + const CompilerOptionsForInferredProjects: protocol.CommandTypes.CompilerOptionsForInferredProjects; + const GetCodeFixes: protocol.CommandTypes.GetCodeFixes; + const GetCodeFixesFull: protocol.CommandTypes.GetCodeFixesFull; + const GetSupportedCodeFixes: protocol.CommandTypes.GetSupportedCodeFixes; } + function formatMessage(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string; class Session { private host; + protected readonly typingsInstaller: ITypingsInstaller; private byteLength; private hrtime; - private logger; + protected logger: Logger; + protected readonly canUseEvents: boolean; + private readonly gcTimer; protected projectService: ProjectService; private errorTimer; private immediateId; private changeSeq; - constructor(host: ServerHost, byteLength: (buf: string, encoding?: string) => number, hrtime: (start?: number[]) => number[], logger: Logger); - private handleEvent(event); + private eventHander; + constructor(host: ServerHost, cancellationToken: HostCancellationToken, useSingleInferredProject: boolean, typingsInstaller: ITypingsInstaller, byteLength: (buf: string, encoding?: string) => number, hrtime: (start?: number[]) => number[], logger: Logger, canUseEvents: boolean, eventHandler?: ProjectServiceEventHandler); + private defaultEventHandler(event); logError(err: Error, cmd: string): void; - private sendLineToClient(line); send(msg: protocol.Message): void; configFileDiagnosticEvent(triggerFile: string, configFile: string, diagnostics: ts.Diagnostic[]): void; event(info: any, eventName: string): void; - private response(info, cmdName, reqSeq?, errorMsg?); - output(body: any, commandName: string, requestSequence?: number, errorMessage?: string): void; + output(info: any, cmdName: string, reqSeq?: number, errorMsg?: string): void; private semanticCheck(file, project); private syntacticCheck(file, project); - private reloadProjects(); private updateProjectStructure(seq, matchSeq, ms?); private updateErrorCheck(checkList, seq, matchSeq, ms?, followMs?, requireOpen?); - private getDefinition(line, offset, fileName); - private getTypeDefinition(line, offset, fileName); - private getImplementation(line, offset, fileName); - private getOccurrences(line, offset, fileName); - private getDiagnosticsWorker(args, selector); + private cleanProjects(caption, projects); + private cleanup(); + private getEncodedSemanticClassifications(args); + private getProject(projectFileName); + private getCompilerOptionsDiagnostics(args); + private convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo); + private getDiagnosticsWorker(args, selector, includeLinePosition); + private getDefinition(args, simplifiedResult); + private getTypeDefinition(args); + private getImplementation(args, simplifiedResult); + private getOccurrences(args); private getSyntacticDiagnosticsSync(args); private getSemanticDiagnosticsSync(args); - private getDocumentHighlights(line, offset, fileName, filesToSearch); - private getProjectInfo(fileName, needFileNameList); - private getRenameLocations(line, offset, fileName, findInComments, findInStrings); - private getReferences(line, offset, fileName); + private getDocumentHighlights(args, simplifiedResult); + private setCompilerOptionsForInferredProjects(args); + private getProjectInfo(args); + private getProjectInfoWorker(uncheckedFileName, projectFileName, needFileNameList); + private getRenameInfo(args); + private getProjects(args); + private getRenameLocations(args, simplifiedResult); + private getReferences(args, simplifiedResult); private openClientFile(fileName, fileContent?, scriptKind?); - private getQuickInfo(line, offset, fileName); - private getFormattingEditsForRange(line, offset, endLine, endOffset, fileName); - private getFormattingEditsAfterKeystroke(line, offset, key, fileName); - private getCompletions(line, offset, prefix, fileName); - private getCompletionEntryDetails(line, offset, entryNames, fileName); - private getSignatureHelpItems(line, offset, fileName); + private getPosition(args, scriptInfo); + private getFileAndProject(args, errorOnMissingProject?); + private getFileAndProjectWithoutRefreshingInferredProjects(args, errorOnMissingProject?); + private getFileAndProjectWorker(uncheckedFileName, projectFileName, refreshInferredProjects, errorOnMissingProject); + private getOutliningSpans(args); + private getTodoComments(args); + private getDocCommentTemplate(args); + private getIndentation(args); + private getBreakpointStatement(args); + private getNameOrDottedNameSpan(args); + private isValidBraceCompletion(args); + private getQuickInfoWorker(args, simplifiedResult); + private getFormattingEditsForRange(args); + private getFormattingEditsForRangeFull(args); + private getFormattingEditsForDocumentFull(args); + private getFormattingEditsAfterKeystrokeFull(args); + private getFormattingEditsAfterKeystroke(args); + private getCompletions(args, simplifiedResult); + private getCompletionEntryDetails(args); + private getCompileOnSaveAffectedFileList(args); + private emitFile(args); + private getSignatureHelpItems(args, simplifiedResult); private getDiagnostics(delay, fileNames); - private change(line, offset, endLine, endOffset, insertString, fileName); - private reload(fileName, tempFileName, reqSeq?); + private change(args); + private reload(args, reqSeq); private saveToTmp(fileName, tempFileName); private closeClientFile(fileName); - private decorateNavigationBarItem(project, fileName, items, lineIndex); - private getNavigationBarItems(fileName); - private getNavigateToItems(searchValue, fileName, maxResultCount?, currentFileOnly?); - private getBraceMatching(line, offset, fileName); + private decorateNavigationBarItems(items, scriptInfo); + private getNavigationBarItems(args, simplifiedResult); + private decorateNavigationTree(tree, scriptInfo); + private decorateSpan(span, scriptInfo); + private getNavigationTree(args, simplifiedResult); + private getNavigateToItems(args, simplifiedResult); + private getSupportedCodeFixes(); + private getCodeFixes(args, simplifiedResult); + private mapCodeAction(codeAction, scriptInfo); + private convertTextChangeToCodeEdit(change, scriptInfo); + private getBraceMatching(args, simplifiedResult); getDiagnosticsForProject(delay: number, fileName: string): void; getCanonicalFileName(fileName: string): string; exit(): void; + private notRequired(); private requiredResponse(response); private handlers; addProtocolHandler(command: string, handler: (request: protocol.Request) => { @@ -9307,227 +10872,6 @@ declare namespace ts.server { } } declare namespace ts.server { - interface Logger { - close(): void; - isVerbose(): boolean; - loggingEnabled(): boolean; - perftrc(s: string): void; - info(s: string): void; - startGroup(): void; - endGroup(): void; - msg(s: string, type?: string): void; - } - const maxProgramSizeForNonTsFiles: number; - class ScriptInfo { - private host; - fileName: string; - isOpen: boolean; - svc: ScriptVersionCache; - children: ScriptInfo[]; - defaultProject: Project; - fileWatcher: FileWatcher; - formatCodeOptions: FormatCodeOptions; - path: Path; - scriptKind: ScriptKind; - constructor(host: ServerHost, fileName: string, content: string, isOpen?: boolean); - setFormatOptions(formatOptions: protocol.FormatOptions): void; - close(): void; - addChild(childInfo: ScriptInfo): void; - snap(): LineIndexSnapshot; - getText(): string; - getLineInfo(line: number): ILineInfo; - editContent(start: number, end: number, newText: string): void; - getTextChangeRangeBetweenVersions(startVersion: number, endVersion: number): ts.TextChangeRange; - getChangeRange(oldSnapshot: ts.IScriptSnapshot): ts.TextChangeRange; - } - class LSHost implements ts.LanguageServiceHost { - host: ServerHost; - project: Project; - ls: ts.LanguageService; - compilationSettings: ts.CompilerOptions; - filenameToScript: ts.FileMap; - roots: ScriptInfo[]; - private resolvedModuleNames; - private resolvedTypeReferenceDirectives; - private moduleResolutionHost; - private getCanonicalFileName; - constructor(host: ServerHost, project: Project); - private resolveNamesWithLocalCache(names, containingFile, cache, loader, getResult); - resolveTypeReferenceDirectives(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; - resolveModuleNames(moduleNames: string[], containingFile: string): ResolvedModule[]; - getDefaultLibFileName(): string; - getScriptSnapshot(filename: string): ts.IScriptSnapshot; - setCompilationSettings(opt: ts.CompilerOptions): void; - lineAffectsRefs(filename: string, line: number): boolean; - getCompilationSettings(): CompilerOptions; - getScriptFileNames(): string[]; - getScriptKind(fileName: string): ScriptKind; - getScriptVersion(filename: string): string; - getCurrentDirectory(): string; - getScriptIsOpen(filename: string): boolean; - removeReferencedFile(info: ScriptInfo): void; - getScriptInfo(filename: string): ScriptInfo; - addRoot(info: ScriptInfo): void; - removeRoot(info: ScriptInfo): void; - saveTo(filename: string, tmpfilename: string): void; - reloadScript(filename: string, tmpfilename: string, cb: () => any): void; - editScript(filename: string, start: number, end: number, newText: string): void; - fileExists(path: string): boolean; - directoryExists(path: string): boolean; - getDirectories(path: string): string[]; - readDirectory(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; - readFile(path: string, encoding?: string): string; - lineToTextSpan(filename: string, line: number): ts.TextSpan; - lineOffsetToPosition(filename: string, line: number, offset: number): number; - positionToLineOffset(filename: string, position: number, lineIndex?: LineIndex): ILineInfo; - getLineIndex(filename: string): LineIndex; - } - interface ProjectOptions { - files?: string[]; - wildcardDirectories?: ts.MapLike; - compilerOptions?: ts.CompilerOptions; - } - class Project { - projectService: ProjectService; - projectOptions: ProjectOptions; - languageServiceDiabled: boolean; - compilerService: CompilerService; - projectFilename: string; - projectFileWatcher: FileWatcher; - directoryWatcher: FileWatcher; - directoriesWatchedForWildcards: Map; - directoriesWatchedForTsconfig: string[]; - program: ts.Program; - filenameToSourceFile: Map; - updateGraphSeq: number; - openRefCount: number; - constructor(projectService: ProjectService, projectOptions?: ProjectOptions, languageServiceDiabled?: boolean); - enableLanguageService(): void; - disableLanguageService(): void; - addOpenRef(): void; - deleteOpenRef(): number; - openReferencedFile(filename: string): ScriptInfo; - getRootFiles(): string[]; - getFileNames(): string[]; - getSourceFile(info: ScriptInfo): SourceFile; - getSourceFileFromName(filename: string, requireOpen?: boolean): SourceFile; - isRoot(info: ScriptInfo): boolean; - removeReferencedFile(info: ScriptInfo): void; - updateFileMap(): void; - finishGraph(): void; - updateGraph(): void; - isConfiguredProject(): string; - addRoot(info: ScriptInfo): void; - removeRoot(info: ScriptInfo): void; - filesToString(): string; - setProjectOptions(projectOptions: ProjectOptions): void; - } - interface ProjectOpenResult { - success?: boolean; - errorMsg?: string; - project?: Project; - } - function combineProjectOutput(projects: Project[], action: (project: Project) => T[], comparer?: (a: T, b: T) => number, areEqual?: (a: T, b: T) => boolean): T[]; - type ProjectServiceEvent = { - eventName: "context"; - data: { - project: Project; - fileName: string; - }; - } | { - eventName: "configFileDiag"; - data: { - triggerFile?: string; - configFileName: string; - diagnostics: Diagnostic[]; - }; - }; - interface ProjectServiceEventHandler { - (event: ProjectServiceEvent): void; - } - interface HostConfiguration { - formatCodeOptions: ts.FormatCodeOptions; - hostInfo: string; - } - class ProjectService { - host: ServerHost; - psLogger: Logger; - eventHandler: ProjectServiceEventHandler; - filenameToScriptInfo: Map; - openFileRoots: ScriptInfo[]; - inferredProjects: Project[]; - configuredProjects: Project[]; - openFilesReferenced: ScriptInfo[]; - openFileRootsConfigured: ScriptInfo[]; - directoryWatchersForTsconfig: Map; - directoryWatchersRefCount: Map; - hostConfiguration: HostConfiguration; - timerForDetectingProjectFileListChanges: Map; - constructor(host: ServerHost, psLogger: Logger, eventHandler?: ProjectServiceEventHandler); - addDefaultHostConfiguration(): void; - getFormatCodeOptions(file?: string): FormatCodeOptions; - watchedFileChanged(fileName: string): void; - directoryWatchedForSourceFilesChanged(project: Project, fileName: string): void; - startTimerForDetectingProjectFileListChanges(project: Project): void; - handleProjectFileListChanges(project: Project): void; - reportConfigFileDiagnostics(configFileName: string, diagnostics: Diagnostic[], triggerFile?: string): void; - directoryWatchedForTsconfigChanged(fileName: string): void; - getCanonicalFileName(fileName: string): string; - watchedProjectConfigFileChanged(project: Project): void; - log(msg: string, type?: string): void; - setHostConfiguration(args: ts.server.protocol.ConfigureRequestArguments): void; - closeLog(): void; - createInferredProject(root: ScriptInfo): Project; - fileDeletedInFilesystem(info: ScriptInfo): void; - updateConfiguredProjectList(): void; - removeProject(project: Project): void; - setConfiguredProjectRoot(info: ScriptInfo): boolean; - addOpenFile(info: ScriptInfo): void; - closeOpenFile(info: ScriptInfo): void; - findReferencingProjects(info: ScriptInfo, excludedProject?: Project): Project[]; - reloadProjects(): void; - updateProjectStructure(): void; - getScriptInfo(filename: string): ScriptInfo; - openFile(fileName: string, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind): ScriptInfo; - findConfigFile(searchPath: string): string; - openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind): { - configFileName?: string; - configFileErrors?: Diagnostic[]; - }; - openOrUpdateConfiguredProjectForFile(fileName: string): { - configFileName?: string; - configFileErrors?: Diagnostic[]; - }; - closeClientFile(filename: string): void; - getProjectForFile(filename: string): Project; - printProjectsForFile(filename: string): void; - printProjects(): void; - configProjectIsActive(fileName: string): boolean; - findConfiguredProjectByConfigFile(configFileName: string): Project; - configFileToProjectOptions(configFilename: string): { - projectOptions?: ProjectOptions; - errors: Diagnostic[]; - }; - private exceedTotalNonTsFileSizeLimit(fileNames); - openConfigFile(configFilename: string, clientFileName?: string): { - project?: Project; - errors: Diagnostic[]; - }; - updateConfiguredProject(project: Project): Diagnostic[]; - createProject(projectFilename: string, projectOptions?: ProjectOptions, languageServiceDisabled?: boolean): Project; - } - class CompilerService { - project: Project; - host: LSHost; - languageService: ts.LanguageService; - classifier: ts.Classifier; - settings: ts.CompilerOptions; - documentRegistry: DocumentRegistry; - constructor(project: Project, opt?: ts.CompilerOptions); - setCompilerOptions(opt: ts.CompilerOptions): void; - isExternalModule(filename: string): boolean; - static getDefaultFormatCodeOptions(host: ServerHost): ts.FormatCodeOptions; - } interface LineCollection { charCount(): number; lineCount(): number; @@ -9566,15 +10910,17 @@ declare namespace ts.server { changes: TextChange[]; versions: LineIndexSnapshot[]; minVersion: number; - private currentVersion; private host; + private currentVersion; static changeNumberThreshold: number; static changeLengthThreshold: number; static maxVersions: number; + private versionToIndex(version); + private currentVersionToIndex(); edit(pos: number, deleteLen: number, insertedText?: string): void; latest(): LineIndexSnapshot; latestVersion(): number; - reloadFromFile(filename: string, cb?: () => any): void; + reloadFromFile(filename: string): void; reload(script: string): void; getSnapshot(): LineIndexSnapshot; getTextChangesBetweenVersions(oldVersion: number, newVersion: number): TextChangeRange; @@ -9643,10 +10989,7 @@ declare namespace ts.server { } class LineLeaf implements LineCollection { text: string; - udata: any; constructor(text: string); - setUdata(data: any): void; - getUdata(): any; isLeaf(): boolean; walk(rangeStart: number, rangeLength: number, walkFns: ILineIndexWalker): void; charCount(): number; @@ -9680,6 +11023,7 @@ declare namespace ts { getNewLine?(): string; getProjectVersion?(): string; useCaseSensitiveFileNames?(): boolean; + getTypeRootsVersion?(): number; readDirectory(rootDir: string, extension: string, basePaths?: string, excludeEx?: string, includeFileEx?: string, includeDirEx?: string, depth?: number): string; readFile(path: string, encoding?: string): string; fileExists(path: string): boolean; @@ -9739,6 +11083,7 @@ declare namespace ts { getDocumentHighlights(fileName: string, position: number, filesToSearch: string): string; getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): string; getNavigationBarItems(fileName: string): string; + getNavigationTree(fileName: string): string; getOutliningSpans(fileName: string): string; getTodoComments(fileName: string, todoCommentDescriptors: string): string; getBraceMatchingAtPosition(fileName: string, position: number): string; @@ -9775,6 +11120,7 @@ declare namespace ts { trace(s: string): void; error(s: string): void; getProjectVersion(): string; + getTypeRootsVersion(): number; useCaseSensitiveFileNames(): boolean; getCompilationSettings(): CompilerOptions; getScriptFileNames(): string[]; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index a8fa909efcc..a360ac081ec 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -72,7 +72,6 @@ var ts; (function (ts) { ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; })(ts || (ts = {})); -var ts; (function (ts) { var performance; (function (performance) { @@ -150,6 +149,7 @@ var ts; contains: contains, remove: remove, forEachValue: forEachValueInMap, + getKeys: getKeys, clear: clear }; function forEachValueInMap(f) { @@ -157,6 +157,13 @@ var ts; f(key, files[key]); } } + function getKeys() { + var keys = []; + for (var key in files) { + keys.push(key); + } + return keys; + } function get(path) { return files[toKey(path)]; } @@ -533,16 +540,22 @@ var ts; : undefined; } ts.lastOrUndefined = lastOrUndefined; - function binarySearch(array, value) { + function binarySearch(array, value, comparer) { + if (!array || array.length === 0) { + return -1; + } var low = 0; var high = array.length - 1; + comparer = comparer !== undefined + ? comparer + : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; - if (midValue === value) { + if (comparer(midValue, value) === 0) { return middle; } - else if (midValue > value) { + else if (comparer(midValue, value) > 0) { high = middle - 1; } else { @@ -776,6 +789,56 @@ var ts; }; } ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (t) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { baseIndex = baseIndex || 0; return text.replace(/{(\d+)}/g, function (match, index) { return args[+index + baseIndex]; }); @@ -1012,10 +1075,45 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; + function isExternalModuleNameRelative(moduleName) { + return /^\.\.?($|[\\/])/.test(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; function isRootedDiskPath(path) { return getRootLength(path) !== 0; } ts.isRootedDiskPath = isRootedDiskPath; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); + } + ts.convertToRelativePath = convertToRelativePath; function normalizedPathComponents(path, rootLength) { var normalizedParts = getNormalizedParts(path, rootLength); return [path.substr(0, rootLength)].concat(normalizedParts); @@ -1389,6 +1487,14 @@ var ts; return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } ts.getSupportedExtensions = getSupportedExtensions; + function hasJavaScriptFileExtension(fileName) { + return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; @@ -1480,7 +1586,6 @@ var ts; this.transformFlags = 0; this.parent = undefined; this.original = undefined; - this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, @@ -1493,9 +1598,9 @@ var ts; }; var Debug; (function (Debug) { - var currentAssertionLevel; + Debug.currentAssertionLevel = 0; function shouldAssert(level) { - return getCurrentAssertionLevel() >= level; + return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -1513,30 +1618,7 @@ var ts; Debug.assert(false, message); } Debug.fail = fail; - function getCurrentAssertionLevel() { - if (currentAssertionLevel !== undefined) { - return currentAssertionLevel; - } - if (ts.sys === undefined) { - return 0; - } - var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); - currentAssertionLevel = developmentMode - ? 1 - : 0; - return currentAssertionLevel; - } })(Debug = ts.Debug || (ts.Debug = {})); - function getEnvironmentVariable(name, host) { - if (host && host.getEnvironmentVariable) { - return host.getEnvironmentVariable(name); - } - if (ts.sys && ts.sys.getEnvironmentVariable) { - return ts.sys.getEnvironmentVariable(name); - } - return ""; - } - ts.getEnvironmentVariable = getEnvironmentVariable; function orderedRemoveItemAt(array, index) { for (var i = index; i < array.length - 1; i++) { array[i] = array[i + 1]; @@ -1567,6 +1649,64 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + function tryParsePattern(pattern) { + Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; })(ts || (ts = {})); var ts; (function (ts) { @@ -1760,8 +1900,14 @@ var ts; function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; } + function isFileSystemCaseSensitive() { + if (platform === "win32" || platform === "win64") { + return false; + } + return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + } var platform = _os.platform(); - var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); function readFile(fileName, encoding) { if (!fileExists(fileName)) { return undefined; @@ -1886,6 +2032,9 @@ var ts; }, watchDirectory: function (directoryName, callback, recursive) { var options; + if (!directoryExists(directoryName)) { + return; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -1997,19 +2146,43 @@ var ts; realpath: realpath }; } + function recursiveCreateDirectory(directoryPath, sys) { + var basePath = ts.getDirectoryPath(directoryPath); + var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + if (shouldCreateParent) { + recursiveCreateDirectory(basePath, sys); + } + if (shouldCreateParent || !sys.directoryExists(directoryPath)) { + sys.createDirectory(directoryPath); + } + } + var sys; if (typeof ChakraHost !== "undefined") { - return getChakraSystem(); + sys = getChakraSystem(); } else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { - return getWScriptSystem(); + sys = getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { - return getNodeSystem(); + sys = getNodeSystem(); } - else { - return undefined; + if (sys) { + var originalWriteFile_1 = sys.writeFile; + sys.writeFile = function (path, data, writeBom) { + var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); + if (directoryPath && !sys.directoryExists(directoryPath)) { + recursiveCreateDirectory(directoryPath, sys); + } + originalWriteFile_1.call(sys, path, data, writeBom); + }; } + return sys; })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 + : 0; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -2334,7 +2507,7 @@ var ts; The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class" }, - All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "All_symbols_within_a_with_block_will_be_resolved_to_any_2410", message: "All symbols within a 'with' block will be resolved to 'any'." }, + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, @@ -2495,7 +2668,7 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, - Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, @@ -2728,6 +2901,8 @@ var ts; No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file" }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -2752,6 +2927,7 @@ var ts; Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, + Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type 'any' in some locations where its type cannot be determined." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -2781,7 +2957,14 @@ var ts; super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } + The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." }, + Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, + Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, + Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'" }, + Remove_unused_identifiers: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_unused_identifiers_90004", message: "Remove unused identifiers" }, + Implement_interface_on_reference: { code: 90005, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_reference_90005", message: "Implement interface on reference" }, + Implement_interface_on_class: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_class_90006", message: "Implement interface on class" }, + Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class" } }; })(ts || (ts = {})); var ts; @@ -3691,7 +3874,7 @@ var ts; return token = 69; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8"); + ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); var value = 0; var numberOfDigits = 0; while (true) { @@ -4334,11 +4517,13 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; ts.optionDeclarations = [ { name: "charset", type: "string" }, + ts.compileOnSaveCommandLineOption, { name: "declaration", shortName: "d", @@ -4761,6 +4946,11 @@ var ts; name: "importHelpers", type: "boolean", description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "alwaysStrict", + type: "boolean", + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file } ]; ts.typingOptionDeclarations = [ @@ -4962,10 +5152,11 @@ var ts; return parseConfigFileTextToJson(fileName, text); } ts.readConfigFile = readConfigFile; - function parseConfigFileTextToJson(fileName, jsonText) { + function parseConfigFileTextToJson(fileName, jsonText, stripComments) { + if (stripComments === void 0) { stripComments = true; } try { - var jsonTextWithoutComments = removeComments(jsonText); - return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; + var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; + return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; @@ -5099,13 +5290,15 @@ var ts; options = ts.extend(existingOptions, options); options.configFilePath = configFileName; var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, errors: errors, - wildcardDirectories: wildcardDirectories + wildcardDirectories: wildcardDirectories, + compileOnSave: compileOnSave }; function tryExtendsName(extendedConfig) { if (!(ts.isRootedDiskPath(extendedConfig) || ts.startsWith(ts.normalizeSlashes(extendedConfig), "./") || ts.startsWith(ts.normalizeSlashes(extendedConfig), "../"))) { @@ -5183,6 +5376,17 @@ var ts; var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + if (typeof result === "boolean" && result) { + return result; + } + return false; + } + ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); @@ -5196,7 +5400,9 @@ var ts; } ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } + : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } @@ -5395,6 +5601,937 @@ var ts; } })(ts || (ts = {})); var ts; +(function (ts) { + var JsTyping; + (function (JsTyping) { + ; + ; + var safeList; + var EmptySafeList = ts.createMap(); + function discoverTypings(host, fileNames, projectRootPath, safeListPath, packageNameToTypingLocation, typingOptions, compilerOptions) { + var inferredTypings = ts.createMap(); + if (!typingOptions || !typingOptions.enableAutoDiscovery) { + return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; + } + fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { + var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)); + return kind === 1 || kind === 2; + }); + if (!safeList) { + var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); + safeList = result.config ? ts.createMap(result.config) : EmptySafeList; + } + var filesToWatch = []; + var searchDirs = []; + var exclude = []; + mergeTypings(typingOptions.include); + exclude = typingOptions.exclude || []; + var possibleSearchDirs = ts.map(fileNames, ts.getDirectoryPath); + if (projectRootPath !== undefined) { + possibleSearchDirs.push(projectRootPath); + } + searchDirs = ts.deduplicate(possibleSearchDirs); + for (var _i = 0, searchDirs_1 = searchDirs; _i < searchDirs_1.length; _i++) { + var searchDir = searchDirs_1[_i]; + var packageJsonPath = ts.combinePaths(searchDir, "package.json"); + getTypingNamesFromJson(packageJsonPath, filesToWatch); + var bowerJsonPath = ts.combinePaths(searchDir, "bower.json"); + getTypingNamesFromJson(bowerJsonPath, filesToWatch); + var nodeModulesPath = ts.combinePaths(searchDir, "node_modules"); + getTypingNamesFromNodeModuleFolder(nodeModulesPath); + } + getTypingNamesFromSourceFileNames(fileNames); + for (var name_7 in packageNameToTypingLocation) { + if (name_7 in inferredTypings && !inferredTypings[name_7]) { + inferredTypings[name_7] = packageNameToTypingLocation[name_7]; + } + } + for (var _a = 0, exclude_1 = exclude; _a < exclude_1.length; _a++) { + var excludeTypingName = exclude_1[_a]; + delete inferredTypings[excludeTypingName]; + } + var newTypingNames = []; + var cachedTypingPaths = []; + for (var typing in inferredTypings) { + if (inferredTypings[typing] !== undefined) { + cachedTypingPaths.push(inferredTypings[typing]); + } + else { + newTypingNames.push(typing); + } + } + return { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch }; + function mergeTypings(typingNames) { + if (!typingNames) { + return; + } + for (var _i = 0, typingNames_1 = typingNames; _i < typingNames_1.length; _i++) { + var typing = typingNames_1[_i]; + if (!(typing in inferredTypings)) { + inferredTypings[typing] = undefined; + } + } + } + function getTypingNamesFromJson(jsonPath, filesToWatch) { + var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); + if (result.config) { + var jsonConfig = result.config; + filesToWatch.push(jsonPath); + if (jsonConfig.dependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); + } + if (jsonConfig.devDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.devDependencies)); + } + if (jsonConfig.optionalDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.optionalDependencies)); + } + if (jsonConfig.peerDependencies) { + mergeTypings(ts.getOwnKeys(jsonConfig.peerDependencies)); + } + } + } + function getTypingNamesFromSourceFileNames(fileNames) { + var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); + var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); + var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); + if (safeList !== EmptySafeList) { + mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); + } + var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2; }); + if (hasJsxFile) { + mergeTypings(["react"]); + } + } + function getTypingNamesFromNodeModuleFolder(nodeModulesPath) { + if (!host.directoryExists(nodeModulesPath)) { + return; + } + var typingNames = []; + var fileNames = host.readDirectory(nodeModulesPath, [".json"], undefined, undefined, 2); + for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { + var fileName = fileNames_2[_i]; + var normalizedFileName = ts.normalizePath(fileName); + if (ts.getBaseFileName(normalizedFileName) !== "package.json") { + continue; + } + var result = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + if (!result.config) { + continue; + } + var packageJson = result.config; + if (packageJson._requiredBy && + ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { + continue; + } + if (!packageJson.name) { + continue; + } + if (packageJson.typings) { + var absolutePath = ts.getNormalizedAbsolutePath(packageJson.typings, ts.getDirectoryPath(normalizedFileName)); + inferredTypings[packageJson.name] = absolutePath; + } + else { + typingNames.push(packageJson.name); + } + } + mergeTypings(typingNames); + } + } + JsTyping.discoverTypings = discoverTypings; + })(JsTyping = ts.JsTyping || (ts.JsTyping = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + (function (LogLevel) { + LogLevel[LogLevel["terse"] = 0] = "terse"; + LogLevel[LogLevel["normal"] = 1] = "normal"; + LogLevel[LogLevel["requestTime"] = 2] = "requestTime"; + LogLevel[LogLevel["verbose"] = 3] = "verbose"; + })(server.LogLevel || (server.LogLevel = {})); + var LogLevel = server.LogLevel; + server.emptyArray = []; + var Msg; + (function (Msg) { + Msg.Err = "Err"; + Msg.Info = "Info"; + Msg.Perf = "Perf"; + })(Msg = server.Msg || (server.Msg = {})); + function getProjectRootPath(project) { + switch (project.projectKind) { + case server.ProjectKind.Configured: + return ts.getDirectoryPath(project.getProjectName()); + case server.ProjectKind.Inferred: + return ""; + case server.ProjectKind.External: + var projectName = ts.normalizeSlashes(project.getProjectName()); + return project.projectService.host.fileExists(projectName) ? ts.getDirectoryPath(projectName) : projectName; + } + } + function createInstallTypingsRequest(project, typingOptions, cachePath) { + return { + projectName: project.getProjectName(), + fileNames: project.getFileNames(), + compilerOptions: project.getCompilerOptions(), + typingOptions: typingOptions, + projectRootPath: getProjectRootPath(project), + cachePath: cachePath, + kind: "discover" + }; + } + server.createInstallTypingsRequest = createInstallTypingsRequest; + var Errors; + (function (Errors) { + function ThrowNoProject() { + throw new Error("No Project."); + } + Errors.ThrowNoProject = ThrowNoProject; + function ThrowProjectLanguageServiceDisabled() { + throw new Error("The project's language service is disabled."); + } + Errors.ThrowProjectLanguageServiceDisabled = ThrowProjectLanguageServiceDisabled; + function ThrowProjectDoesNotContainDocument(fileName, project) { + throw new Error("Project '" + project.getProjectName() + "' does not contain document '" + fileName + "'"); + } + Errors.ThrowProjectDoesNotContainDocument = ThrowProjectDoesNotContainDocument; + })(Errors = server.Errors || (server.Errors = {})); + function getDefaultFormatCodeSettings(host) { + return { + indentSize: 4, + tabSize: 4, + newLineCharacter: host.newLine || "\n", + convertTabsToSpaces: true, + indentStyle: ts.IndentStyle.Smart, + insertSpaceAfterCommaDelimiter: true, + insertSpaceAfterSemicolonInForStatements: true, + insertSpaceBeforeAndAfterBinaryOperators: true, + insertSpaceAfterKeywordsInControlFlowStatements: true, + insertSpaceAfterFunctionKeywordForAnonymousFunctions: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, + placeOpenBraceOnNewLineForFunctions: false, + placeOpenBraceOnNewLineForControlBlocks: false + }; + } + server.getDefaultFormatCodeSettings = getDefaultFormatCodeSettings; + function mergeMaps(target, source) { + for (var key in source) { + if (ts.hasProperty(source, key)) { + target[key] = source[key]; + } + } + } + server.mergeMaps = mergeMaps; + function removeItemFromSet(items, itemToRemove) { + if (items.length === 0) { + return; + } + var index = items.indexOf(itemToRemove); + if (index < 0) { + return; + } + if (index === items.length - 1) { + items.pop(); + } + else { + items[index] = items.pop(); + } + } + server.removeItemFromSet = removeItemFromSet; + function toNormalizedPath(fileName) { + return ts.normalizePath(fileName); + } + server.toNormalizedPath = toNormalizedPath; + function normalizedPathToPath(normalizedPath, currentDirectory, getCanonicalFileName) { + var f = ts.isRootedDiskPath(normalizedPath) ? normalizedPath : ts.getNormalizedAbsolutePath(normalizedPath, currentDirectory); + return getCanonicalFileName(f); + } + server.normalizedPathToPath = normalizedPathToPath; + function asNormalizedPath(fileName) { + return fileName; + } + server.asNormalizedPath = asNormalizedPath; + function createNormalizedPathMap() { + var map = Object.create(null); + return { + get: function (path) { + return map[path]; + }, + set: function (path, value) { + map[path] = value; + }, + contains: function (path) { + return ts.hasProperty(map, path); + }, + remove: function (path) { + delete map[path]; + } + }; + } + server.createNormalizedPathMap = createNormalizedPathMap; + function throwLanguageServiceIsDisabledError() { + throw new Error("LanguageService is disabled"); + } + server.nullLanguageService = { + cleanupSemanticCache: throwLanguageServiceIsDisabledError, + getSyntacticDiagnostics: throwLanguageServiceIsDisabledError, + getSemanticDiagnostics: throwLanguageServiceIsDisabledError, + getCompilerOptionsDiagnostics: throwLanguageServiceIsDisabledError, + getSyntacticClassifications: throwLanguageServiceIsDisabledError, + getEncodedSyntacticClassifications: throwLanguageServiceIsDisabledError, + getSemanticClassifications: throwLanguageServiceIsDisabledError, + getEncodedSemanticClassifications: throwLanguageServiceIsDisabledError, + getCompletionsAtPosition: throwLanguageServiceIsDisabledError, + findReferences: throwLanguageServiceIsDisabledError, + getCompletionEntryDetails: throwLanguageServiceIsDisabledError, + getQuickInfoAtPosition: throwLanguageServiceIsDisabledError, + findRenameLocations: throwLanguageServiceIsDisabledError, + getNameOrDottedNameSpan: throwLanguageServiceIsDisabledError, + getBreakpointStatementAtPosition: throwLanguageServiceIsDisabledError, + getBraceMatchingAtPosition: throwLanguageServiceIsDisabledError, + getSignatureHelpItems: throwLanguageServiceIsDisabledError, + getDefinitionAtPosition: throwLanguageServiceIsDisabledError, + getRenameInfo: throwLanguageServiceIsDisabledError, + getTypeDefinitionAtPosition: throwLanguageServiceIsDisabledError, + getReferencesAtPosition: throwLanguageServiceIsDisabledError, + getDocumentHighlights: throwLanguageServiceIsDisabledError, + getOccurrencesAtPosition: throwLanguageServiceIsDisabledError, + getNavigateToItems: throwLanguageServiceIsDisabledError, + getNavigationBarItems: throwLanguageServiceIsDisabledError, + getNavigationTree: throwLanguageServiceIsDisabledError, + getOutliningSpans: throwLanguageServiceIsDisabledError, + getTodoComments: throwLanguageServiceIsDisabledError, + getIndentationAtPosition: throwLanguageServiceIsDisabledError, + getFormattingEditsForRange: throwLanguageServiceIsDisabledError, + getFormattingEditsForDocument: throwLanguageServiceIsDisabledError, + getFormattingEditsAfterKeystroke: throwLanguageServiceIsDisabledError, + getDocCommentTemplateAtPosition: throwLanguageServiceIsDisabledError, + isValidBraceCompletionAtPosition: throwLanguageServiceIsDisabledError, + getEmitOutput: throwLanguageServiceIsDisabledError, + getProgram: throwLanguageServiceIsDisabledError, + getNonBoundSourceFile: throwLanguageServiceIsDisabledError, + dispose: throwLanguageServiceIsDisabledError, + getCompletionEntrySymbol: throwLanguageServiceIsDisabledError, + getImplementationAtPosition: throwLanguageServiceIsDisabledError, + getSourceFile: throwLanguageServiceIsDisabledError, + getCodeFixesAtPosition: throwLanguageServiceIsDisabledError + }; + server.nullLanguageServiceHost = { + setCompilationSettings: function () { return undefined; }, + notifyFileRemoved: function () { return undefined; } + }; + function isInferredProjectName(name) { + return /dev\/null\/inferredProject\d+\*/.test(name); + } + server.isInferredProjectName = isInferredProjectName; + function makeInferredProjectName(counter) { + return "/dev/null/inferredProject" + counter + "*"; + } + server.makeInferredProjectName = makeInferredProjectName; + var ThrottledOperations = (function () { + function ThrottledOperations(host) { + this.host = host; + this.pendingTimeouts = ts.createMap(); + } + ThrottledOperations.prototype.schedule = function (operationId, delay, cb) { + if (ts.hasProperty(this.pendingTimeouts, operationId)) { + this.host.clearTimeout(this.pendingTimeouts[operationId]); + } + this.pendingTimeouts[operationId] = this.host.setTimeout(ThrottledOperations.run, delay, this, operationId, cb); + }; + ThrottledOperations.run = function (self, operationId, cb) { + delete self.pendingTimeouts[operationId]; + cb(); + }; + return ThrottledOperations; + }()); + server.ThrottledOperations = ThrottledOperations; + var GcTimer = (function () { + function GcTimer(host, delay, logger) { + this.host = host; + this.delay = delay; + this.logger = logger; + } + GcTimer.prototype.scheduleCollect = function () { + if (!this.host.gc || this.timerId != undefined) { + return; + } + this.timerId = this.host.setTimeout(GcTimer.run, this.delay, this); + }; + GcTimer.run = function (self) { + self.timerId = undefined; + var log = self.logger.hasLevel(LogLevel.requestTime); + var before = log && self.host.getMemoryUsage(); + self.host.gc(); + if (log) { + var after = self.host.getMemoryUsage(); + self.logger.perftrc("GC::before " + before + ", after " + after); + } + }; + return GcTimer; + }()); + server.GcTimer = GcTimer; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function trace(host, message) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; + } + ts.createResolvedModule = createResolvedModule; + function moduleHasNonRelativeName(moduleName) { + return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); + } + function tryReadTypesSection(packageJsonPath, baseDirectory, state) { + var jsonContent = readJson(packageJsonPath, state.host); + function tryReadFromField(fieldName) { + if (ts.hasProperty(jsonContent, fieldName)) { + var typesFile = jsonContent[fieldName]; + if (typeof typesFile === "string") { + var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); + } + return typesFilePath_1; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); + } + } + } + } + var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); + if (typesFilePath) { + return typesFilePath; + } + if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); + } + var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); + return mainFilePath; + } + return undefined; + } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + return {}; + } + } + var typeReferenceExtensions = [".d.ts"]; + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + return currentDirectory !== undefined && getDefaultTypeRoots(currentDirectory, host); + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + } + var typeRoots; + while (true) { + var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + var parent_1 = ts.getDirectoryPath(currentDirectory); + if (parent_1 === currentDirectory) { + break; + } + currentDirectory = parent_1; + } + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + var traceEnabled = isTraceEnabled(options, host); + var moduleResolutionState = { + compilerOptions: options, + host: host, + skipTsx: true, + traceEnabled: traceEnabled + }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === undefined) { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + } + } + else { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + } + } + } + var failedLookupLocations = []; + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + var primarySearchPaths = typeRoots; + for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { + var typeRoot = primarySearchPaths_1[_i]; + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); + if (resolvedFile_1) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); + } + return { + resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, + failedLookupLocations: failedLookupLocations + }; + } + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + var resolvedFile; + var initialLocationForSecondaryLookup; + if (containingFile) { + initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); + } + if (initialLocationForSecondaryLookup !== undefined) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, false); + if (traceEnabled) { + if (resolvedFile) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); + } + else { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + return { + resolvedTypeReferenceDirective: resolvedFile + ? { primary: false, resolvedFileName: resolvedFile } + : undefined, + failedLookupLocations: failedLookupLocations + }; + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + function getAutomaticTypeDirectiveNames(options, host) { + if (options.types) { + return options.types; + } + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + result.push(ts.getBaseFileName(normalized)); + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); + } + else { + return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); + } + } + function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { + var subst = _a[_i]; + var path = matchedStar ? subst.replace("*", matchedStar) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + } + return undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); + var isExternalLibraryImport = false; + if (!resolvedFileName) { + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state, false); + isExternalLibraryImport = resolvedFileName !== undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); + } + } + if (resolvedFileName && host.realpath) { + var originalFileName = resolvedFileName; + resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); + } + } + return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + function directoryProbablyExists(directoryName, host) { + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + if (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); + } + } + function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + return ts.forEach(extensions, function (ext) { + return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); + }); + } + function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + failedLookupLocation.push(fileName); + return undefined; + } + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { + var packageJsonPath = pathToPackageJson(candidate); + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); + if (typesFile) { + var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); + var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || + tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); + if (result) { + return result; + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); + } + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + failedLookupLocation.push(packageJsonPath); + } + return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); + } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } + function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); + var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + } + function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, false); + } + ts.loadModuleFromNodeModules = loadModuleFromNodeModules; + function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, false, true); + } + function loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, typesOnly) { + directory = ts.normalizeSlashes(directory); + while (true) { + var baseName = ts.getBaseFileName(directory); + if (baseName !== "node_modules") { + var packageResult = void 0; + if (!typesOnly) { + packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); + if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { + return packageResult; + } + } + var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); + if (typesResult || packageResult) { + return typesResult || packageResult; + } + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory || checkOneLevel) { + break; + } + directory = parentPath; + } + return undefined; + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; + var failedLookupLocations = []; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, false, failedLookupLocations); + } + var referencedSourceFile; + if (moduleHasNonRelativeName(moduleName)) { + referencedSourceFile = referencedSourceFile = loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) || + loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); + } + return referencedSourceFile + ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } + : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + } + ts.classicNameResolver = classicNameResolver; + function loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) { + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); + if (referencedSourceFile) { + return referencedSourceFile; + } + var parentPath = ts.getDirectoryPath(containingDirectory); + if (parentPath === containingDirectory) { + return undefined; + } + containingDirectory = parentPath; + } + } +})(ts || (ts = {})); +var ts; (function (ts) { ts.externalHelpersModuleNameText = "tslib"; function getDeclarationOfKind(symbol, kind) { @@ -5877,10 +7014,10 @@ var ts; return !!(ts.getCombinedNodeFlags(node) & 1); } ts.isLet = isLet; - function isSuperCallExpression(n) { + function isSuperCall(n) { return n.kind === 174 && n.expression.kind === 95; } - ts.isSuperCallExpression = isSuperCallExpression; + ts.isSuperCall = isSuperCall; function isPrologueDirective(node) { return node.kind === 202 && node.expression.kind === 9; } @@ -5943,23 +7080,23 @@ var ts; case 139: case 172: case 97: - var parent_1 = node.parent; - if (parent_1.kind === 158) { + var parent_2 = node.parent; + if (parent_2.kind === 158) { return false; } - if (154 <= parent_1.kind && parent_1.kind <= 166) { + if (154 <= parent_2.kind && parent_2.kind <= 166) { return true; } - switch (parent_1.kind) { + switch (parent_2.kind) { case 194: - return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_1); + return !isExpressionWithTypeArgumentsInClassExtendsClause(parent_2); case 141: - return node === parent_1.constraint; + return node === parent_2.constraint; case 145: case 144: case 142: case 218: - return node === parent_1.type; + return node === parent_2.type; case 220: case 179: case 180: @@ -5968,16 +7105,16 @@ var ts; case 146: case 149: case 150: - return node === parent_1.type; + return node === parent_2.type; case 151: case 152: case 153: - return node === parent_1.type; + return node === parent_2.type; case 177: - return node === parent_1.type; + return node === parent_2.type; case 174: case 175: - return parent_1.typeArguments && ts.indexOf(parent_1.typeArguments, node) >= 0; + return parent_2.typeArguments && ts.indexOf(parent_2.typeArguments, node) >= 0; case 176: return false; } @@ -6030,9 +7167,9 @@ var ts; return; default: if (isFunctionLike(node)) { - var name_7 = node.name; - if (name_7 && name_7.kind === 140) { - traverse(name_7.expression); + var name_8 = node.name; + if (name_8 && name_8.kind === 140) { + traverse(name_8.expression); return; } } @@ -6128,6 +7265,12 @@ var ts; return node && node.kind === 147 && node.parent.kind === 171; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 147 && + (node.parent.kind === 171 || + node.parent.kind === 192); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { return predicate && predicate.kind === 1; } @@ -6238,13 +7381,13 @@ var ts; function getImmediatelyInvokedFunctionExpression(func) { if (func.kind === 179 || func.kind === 180) { var prev = func; - var parent_2 = func.parent; - while (parent_2.kind === 178) { - prev = parent_2; - parent_2 = parent_2.parent; + var parent_3 = func.parent; + while (parent_3.kind === 178) { + prev = parent_3; + parent_3 = parent_3.parent; } - if (parent_2.kind === 174 && parent_2.expression === prev) { - return parent_2; + if (parent_3.kind === 174 && parent_3.expression === prev) { + return parent_3; } } } @@ -6390,8 +7533,8 @@ var ts; case 8: case 9: case 97: - var parent_3 = node.parent; - switch (parent_3.kind) { + var parent_4 = node.parent; + switch (parent_4.kind) { case 218: case 142: case 145: @@ -6399,7 +7542,7 @@ var ts; case 255: case 253: case 169: - return parent_3.initializer === node; + return parent_4.initializer === node; case 202: case 203: case 204: @@ -6410,32 +7553,32 @@ var ts; case 249: case 215: case 213: - return parent_3.expression === node; + return parent_4.expression === node; case 206: - var forStatement = parent_3; + var forStatement = parent_4; return (forStatement.initializer === node && forStatement.initializer.kind !== 219) || forStatement.condition === node || forStatement.incrementor === node; case 207: case 208: - var forInStatement = parent_3; + var forInStatement = parent_4; return (forInStatement.initializer === node && forInStatement.initializer.kind !== 219) || forInStatement.expression === node; case 177: case 195: - return node === parent_3.expression; + return node === parent_4.expression; case 197: - return node === parent_3.expression; + return node === parent_4.expression; case 140: - return node === parent_3.expression; + return node === parent_4.expression; case 143: case 248: case 247: return true; case 194: - return parent_3.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_3); + return parent_4.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent_4); default: - if (isPartOfExpression(parent_3)) { + if (isPartOfExpression(parent_4)) { return true; } } @@ -6443,10 +7586,6 @@ var ts; return false; } ts.isPartOfExpression = isPartOfExpression; - function isExternalModuleNameRelative(moduleName) { - return /^\.\.?($|[\\/])/.test(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { var moduleState = ts.getModuleInstanceState(node); return moduleState === 1 || @@ -6650,17 +7789,17 @@ var ts; node.parent && node.parent.kind === 225) { result = append(result, getJSDocs(node.parent, checkParentVariableStatement, getDocs, getTags)); } - var parent_4 = node.parent; - var isSourceOfAssignmentExpressionStatement = parent_4 && parent_4.parent && - parent_4.kind === 187 && - parent_4.operatorToken.kind === 56 && - parent_4.parent.kind === 202; + var parent_5 = node.parent; + var isSourceOfAssignmentExpressionStatement = parent_5 && parent_5.parent && + parent_5.kind === 187 && + parent_5.operatorToken.kind === 56 && + parent_5.parent.kind === 202; if (isSourceOfAssignmentExpressionStatement) { - result = append(result, getJSDocs(parent_4.parent, checkParentVariableStatement, getDocs, getTags)); + result = append(result, getJSDocs(parent_5.parent, checkParentVariableStatement, getDocs, getTags)); } - var isPropertyAssignmentExpression = parent_4 && parent_4.kind === 253; + var isPropertyAssignmentExpression = parent_5 && parent_5.kind === 253; if (isPropertyAssignmentExpression) { - result = append(result, getJSDocs(parent_4, checkParentVariableStatement, getDocs, getTags)); + result = append(result, getJSDocs(parent_5, checkParentVariableStatement, getDocs, getTags)); } if (node.kind === 142) { var paramTags = getJSDocParameterTag(node, checkParentVariableStatement); @@ -6693,8 +7832,8 @@ var ts; } } else if (param.name.kind === 69) { - var name_8 = param.name.text; - var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 && tag.parameterName.text === name_8; }); + var name_9 = param.name.text; + var paramTags = ts.filter(tags, function (tag) { return tag.kind === 275 && tag.parameterName.text === name_9; }); if (paramTags) { return paramTags; } @@ -6765,20 +7904,20 @@ var ts; node = node.parent; } while (true) { - var parent_5 = node.parent; - if (parent_5.kind === 170 || parent_5.kind === 191) { - node = parent_5; + var parent_6 = node.parent; + if (parent_6.kind === 170 || parent_6.kind === 191) { + node = parent_6; continue; } - if (parent_5.kind === 253 || parent_5.kind === 254) { - node = parent_5.parent; + if (parent_6.kind === 253 || parent_6.kind === 254) { + node = parent_6.parent; continue; } - return parent_5.kind === 187 && - isAssignmentOperator(parent_5.operatorToken.kind) && - parent_5.left === node || - (parent_5.kind === 207 || parent_5.kind === 208) && - parent_5.initializer === node; + return parent_6.kind === 187 && + isAssignmentOperator(parent_6.operatorToken.kind) && + parent_6.left === node || + (parent_6.kind === 207 || parent_6.kind === 208) && + parent_6.initializer === node; } } ts.isAssignmentTarget = isAssignmentTarget; @@ -7044,14 +8183,10 @@ var ts; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(node) { - return positionIsSynthesized(node.pos) - || positionIsSynthesized(node.end); + return ts.positionIsSynthesized(node.pos) + || ts.positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function positionIsSynthesized(pos) { - return !(pos >= 0); - } - ts.positionIsSynthesized = positionIsSynthesized; function getOriginalNode(node) { if (node) { while (node.original !== undefined) { @@ -7487,28 +8622,16 @@ var ts; function getDeclarationEmitOutputFilePath(sourceFile, host) { var options = host.getCompilerOptions(); var outputDir = options.declarationDir || options.outDir; - if (options.declaration) { - var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; - } + var path = outputDir + ? getSourceFilePathInNewDir(sourceFile, host, outputDir) + : sourceFile.fileName; + return ts.removeFileExtension(path) + ".d.ts"; } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; - function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0; - } - ts.getEmitScriptTarget = getEmitScriptTarget; - function getEmitModuleKind(compilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) === 2 ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; - } - ts.getEmitModuleKind = getEmitModuleKind; function getSourceFilesToEmit(host, targetSourceFile) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { - var moduleKind = getEmitModuleKind(options); + var moduleKind = ts.getEmitModuleKind(options); var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; var sourceFiles = host.getSourceFiles(); return ts.filter(sourceFiles, moduleEmitEnabled ? isNonDeclarationFile : isBundleEmitNonExternalModule); @@ -7525,7 +8648,7 @@ var ts; function isBundleEmitNonExternalModule(sourceFile) { return !isDeclarationFile(sourceFile) && !ts.isExternalModule(sourceFile); } - function forEachTransformedEmitFile(host, sourceFiles, action) { + function forEachTransformedEmitFile(host, sourceFiles, action, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { onBundledEmit(host, sourceFiles); @@ -7552,7 +8675,7 @@ var ts; } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (options.declaration || emitOnlyDtsFiles) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], false); } function onBundledEmit(host, sourceFiles) { @@ -7568,7 +8691,7 @@ var ts; function getSourceMapFilePath(jsFilePath, options) { return options.sourceMap ? jsFilePath + ".map" : undefined; } - function forEachExpectedEmitFile(host, action, targetSourceFile) { + function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { onBundledEmit(host); @@ -7595,18 +8718,19 @@ var ts; } } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var emitFileNames = { jsFilePath: jsFilePath, sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), - declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined + declarationFilePath: declarationFilePath }; - action(emitFileNames, [sourceFile], false); + action(emitFileNames, [sourceFile], false, emitOnlyDtsFiles); } function onBundledEmit(host) { var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile) && (!ts.isExternalModule(sourceFile) || - !!getEmitModuleKind(options)); }); + !!ts.getEmitModuleKind(options)); }); if (bundledSources.length) { var jsFilePath = options.outFile || options.out; var emitFileNames = { @@ -7614,7 +8738,7 @@ var ts; sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined }; - action(emitFileNames, bundledSources, true); + action(emitFileNames, bundledSources, true, emitOnlyDtsFiles); } } } @@ -7651,13 +8775,32 @@ var ts; ts.getFirstConstructorWithBody = getFirstConstructorWithBody; function getSetAccessorTypeAnnotationNode(accessor) { if (accessor && accessor.parameters.length > 0) { - var hasThis = accessor.parameters.length === 2 && - accessor.parameters[0].name.kind === 69 && - accessor.parameters[0].name.originalKeywordKind === 97; + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); return accessor.parameters[hasThis ? 1 : 0].type; } } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + if (signature.parameters.length) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return node && node.kind === 69 && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 97; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -7971,14 +9114,6 @@ var ts; return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function hasJavaScriptFileExtension(fileName) { - return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function tryExtractTypeScriptExtension(fileName) { return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); } @@ -8069,12 +9204,6 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !ts.isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); - } - ts.convertToRelativePath = convertToRelativePath; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { @@ -8163,9 +9292,9 @@ var ts; if (syntaxKindCache[kind]) { return syntaxKindCache[kind]; } - for (var name_9 in syntaxKindEnum) { - if (syntaxKindEnum[name_9] === kind) { - return syntaxKindCache[kind] = kind.toString() + " (" + name_9 + ")"; + for (var name_10 in syntaxKindEnum) { + if (syntaxKindEnum[name_10] === kind) { + return syntaxKindCache[kind] = kind.toString() + " (" + name_10 + ")"; } } } @@ -8175,7 +9304,7 @@ var ts; } ts.formatSyntaxKind = formatSyntaxKind; function movePos(pos, value) { - return positionIsSynthesized(pos) ? -1 : pos + value; + return ts.positionIsSynthesized(pos) ? -1 : pos + value; } ts.movePos = movePos; function createRange(pos, end) { @@ -8244,7 +9373,7 @@ var ts; } ts.positionsAreOnSameLine = positionsAreOnSameLine; function getStartPositionOfRange(range, sourceFile) { - return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); } ts.getStartPositionOfRange = getStartPositionOfRange; function collectExternalModuleInfo(sourceFile, resolver) { @@ -8281,8 +9410,8 @@ var ts; else { for (var _b = 0, _c = node.exportClause.elements; _b < _c.length; _b++) { var specifier = _c[_b]; - var name_10 = (specifier.propertyName || specifier.name).text; - (exportSpecifiers[name_10] || (exportSpecifiers[name_10] = [])).push(specifier); + var name_11 = (specifier.propertyName || specifier.name).text; + (exportSpecifiers[name_11] || (exportSpecifiers[name_11] = [])).push(specifier); } } break; @@ -8344,15 +9473,16 @@ var ts; return 11 <= kind && kind <= 14; } ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isTemplateLiteralFragmentKind(kind) { - return kind === 12 - || kind === 13 + function isTemplateHead(node) { + return node.kind === 12; + } + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 13 || kind === 14; } - function isTemplateLiteralFragment(node) { - return isTemplateLiteralFragmentKind(node.kind); - } - ts.isTemplateLiteralFragment = isTemplateLiteralFragment; + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; function isIdentifier(node) { return node.kind === 69; } @@ -8491,12 +9621,12 @@ var ts; return node.kind === 174; } ts.isCallExpression = isCallExpression; - function isTemplate(node) { + function isTemplateLiteral(node) { var kind = node.kind; return kind === 189 || kind === 11; } - ts.isTemplate = isTemplate; + ts.isTemplateLiteral = isTemplateLiteral; function isSpreadElementExpression(node) { return node.kind === 191; } @@ -8827,7 +9957,6 @@ var ts; } ts.isWatchSet = isWatchSet; })(ts || (ts = {})); -var ts; (function (ts) { function getDefaultLibFileName(options) { return options.target === 2 ? "lib.es6.d.ts" : "lib.d.ts"; @@ -9062,7 +10191,7 @@ var ts; ts.createSynthesizedNodeArray = createSynthesizedNodeArray; function getSynthesizedClone(node) { var clone = createNode(node.kind, undefined, node.flags); - clone.original = node; + setOriginalNode(clone, node); for (var key in node) { if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { continue; @@ -9094,7 +10223,7 @@ var ts; node.text = value; return node; } - else { + else if (value) { var node = createNode(9, location, undefined); node.textSourceNode = value; node.text = value.text; @@ -9381,7 +10510,7 @@ var ts; function createPropertyAccess(expression, name, location, flags) { var node = createNode(172, location, flags); node.expression = parenthesizeForAccess(expression); - node.emitFlags = 1048576; + (node.emitNode || (node.emitNode = {})).flags |= 1048576; node.name = typeof name === "string" ? createIdentifier(name) : name; return node; } @@ -9389,7 +10518,7 @@ var ts; function updatePropertyAccess(node, expression, name) { if (node.expression !== expression || node.name !== name) { var propertyAccess = createPropertyAccess(expression, name, node, node.flags); - propertyAccess.emitFlags = node.emitFlags; + (propertyAccess.emitNode || (propertyAccess.emitNode = {})).flags = getEmitFlags(node); return updateNode(propertyAccess, node); } return node; @@ -9493,7 +10622,7 @@ var ts; node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken || createNode(34); + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(34); node.body = parenthesizeConciseBody(body); return node; } @@ -9586,7 +10715,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right, location) { - var operatorToken = typeof operator === "number" ? createSynthesizedNode(operator) : operator; + var operatorToken = typeof operator === "number" ? createToken(operator) : operator; var operatorKind = operatorToken.kind; var node = createNode(187, location); node.left = parenthesizeBinaryOperand(operatorKind, left, true, undefined); @@ -10486,13 +11615,13 @@ var ts; } else { var expression = ts.isIdentifier(memberName) ? createPropertyAccess(target, memberName, location) : createElementAccess(target, memberName, location); - expression.emitFlags |= 2048; + (expression.emitNode || (expression.emitNode = {})).flags |= 2048; return expression; } } ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName; function createRestParameter(name) { - return createParameterDeclaration(undefined, undefined, createSynthesizedNode(22), name, undefined, undefined, undefined); + return createParameterDeclaration(undefined, undefined, createToken(22), name, undefined, undefined, undefined); } ts.createRestParameter = createRestParameter; function createFunctionCall(func, thisArg, argumentsList, location) { @@ -10606,8 +11735,8 @@ var ts; } ts.createDecorateHelper = createDecorateHelper; function createAwaiterHelper(externalHelpersModuleName, hasLexicalArguments, promiseConstructor, body) { - var generatorFunc = createFunctionExpression(createNode(37), undefined, undefined, [], undefined, body); - generatorFunc.emitFlags |= 2097152; + var generatorFunc = createFunctionExpression(createToken(37), undefined, undefined, [], undefined, body); + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 2097152; return createCall(createHelperName(externalHelpersModuleName, "__awaiter"), undefined, [ createThis(), hasLexicalArguments ? createIdentifier("arguments") : createVoidZero(), @@ -10834,7 +11963,7 @@ var ts; target.push(startOnNewLine(createStatement(createLiteral("use strict")))); foundUseStrict = true; } - if (statement.emitFlags & 8388608) { + if (getEmitFlags(statement) & 8388608) { target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { @@ -10846,6 +11975,28 @@ var ts; return statementOffset; } ts.addPrologueDirectives = addPrologueDirectives; + function ensureUseStrict(node) { + var foundUseStrict = false; + for (var _i = 0, _a = node.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + break; + } + } + else { + break; + } + } + if (!foundUseStrict) { + var statements = []; + statements.push(startOnNewLine(createStatement(createLiteral("use strict")))); + return updateSourceFileNode(node, statements.concat(node.statements)); + } + return node; + } + ts.ensureUseStrict = ensureUseStrict; function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) { var skipped = skipPartiallyEmittedExpressions(operand); if (skipped.kind === 178) { @@ -11085,17 +12236,112 @@ var ts; function setOriginalNode(node, original) { node.original = original; if (original) { - var emitFlags = original.emitFlags, commentRange = original.commentRange, sourceMapRange = original.sourceMapRange; - if (emitFlags) - node.emitFlags = emitFlags; - if (commentRange) - node.commentRange = commentRange; - if (sourceMapRange) - node.sourceMapRange = sourceMapRange; + var emitNode = original.emitNode; + if (emitNode) + node.emitNode = mergeEmitNode(emitNode, node.emitNode); } return node; } ts.setOriginalNode = setOriginalNode; + function mergeEmitNode(sourceEmitNode, destEmitNode) { + var flags = sourceEmitNode.flags, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges; + if (!destEmitNode && (flags || commentRange || sourceMapRange || tokenSourceMapRanges)) + destEmitNode = {}; + if (flags) + destEmitNode.flags = flags; + if (commentRange) + destEmitNode.commentRange = commentRange; + if (sourceMapRange) + destEmitNode.sourceMapRange = sourceMapRange; + if (tokenSourceMapRanges) + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + return destEmitNode; + } + function mergeTokenSourceMapRanges(sourceRanges, destRanges) { + if (!destRanges) + destRanges = ts.createMap(); + ts.copyProperties(sourceRanges, destRanges); + return destRanges; + } + function disposeEmitNodes(sourceFile) { + sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile)); + var emitNode = sourceFile && sourceFile.emitNode; + var annotatedNodes = emitNode && emitNode.annotatedNodes; + if (annotatedNodes) { + for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) { + var node = annotatedNodes_1[_i]; + node.emitNode = undefined; + } + } + } + ts.disposeEmitNodes = disposeEmitNodes; + function getOrCreateEmitNode(node) { + if (!node.emitNode) { + if (ts.isParseTreeNode(node)) { + if (node.kind === 256) { + return node.emitNode = { annotatedNodes: [node] }; + } + var sourceFile = ts.getSourceFileOfNode(node); + getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); + } + node.emitNode = {}; + } + return node.emitNode; + } + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags; + } + ts.getEmitFlags = getEmitFlags; + function setEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).flags = emitFlags; + return node; + } + ts.setEmitFlags = setEmitFlags; + function setSourceMapRange(node, range) { + getOrCreateEmitNode(node).sourceMapRange = range; + return node; + } + ts.setSourceMapRange = setSourceMapRange; + function setTokenSourceMapRange(node, token, range) { + var emitNode = getOrCreateEmitNode(node); + var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = ts.createMap()); + tokenSourceMapRanges[token] = range; + return node; + } + ts.setTokenSourceMapRange = setTokenSourceMapRange; + function setCommentRange(node, range) { + getOrCreateEmitNode(node).commentRange = range; + return node; + } + ts.setCommentRange = setCommentRange; + function getCommentRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.commentRange) || node; + } + ts.getCommentRange = getCommentRange; + function getSourceMapRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.sourceMapRange) || node; + } + ts.getSourceMapRange = getSourceMapRange; + function getTokenSourceMapRange(node, token) { + var emitNode = node.emitNode; + var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; + return tokenSourceMapRanges && tokenSourceMapRanges[token]; + } + ts.getTokenSourceMapRange = getTokenSourceMapRange; + function getConstantValue(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.constantValue; + } + ts.getConstantValue = getConstantValue; + function setConstantValue(node, value) { + var emitNode = getOrCreateEmitNode(node); + emitNode.constantValue = value; + return node; + } + ts.setConstantValue = setConstantValue; function setTextRange(node, location) { if (location) { node.pos = location.pos; @@ -11122,8 +12368,8 @@ var ts; function getLocalNameForExternalImport(node, sourceFile) { var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); if (namespaceDeclaration && !ts.isDefaultImport(node)) { - var name_11 = namespaceDeclaration.name; - return ts.isGeneratedIdentifier(name_11) ? name_11 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); + var name_12 = namespaceDeclaration.name; + return ts.isGeneratedIdentifier(name_12) ? name_12 : createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, namespaceDeclaration.name)); } if (node.kind === 230 && node.importClause) { return getGeneratedNameForNode(node); @@ -12205,7 +13451,7 @@ var ts; case 16: return token() === 18 || token() === 20; case 18: - return token() === 27 || token() === 17; + return token() !== 24; case 20: return token() === 15 || token() === 16; case 13: @@ -12533,7 +13779,7 @@ var ts; } function parseTemplateExpression() { var template = createNode(189); - template.head = parseTemplateLiteralFragment(); + template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 12, "Template head has wrong token kind"); var templateSpans = createNodeArray(); do { @@ -12549,7 +13795,7 @@ var ts; var literal; if (token() === 16) { reScanTemplateToken(); - literal = parseTemplateLiteralFragment(); + literal = parseTemplateMiddleOrTemplateTail(); } else { literal = parseExpectedToken(14, false, ts.Diagnostics._0_expected, ts.tokenToString(16)); @@ -12560,8 +13806,15 @@ var ts; function parseLiteralNode(internName) { return parseLiteralLikeNode(token(), internName); } - function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token(), false); + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token(), false); + ts.Debug.assert(fragment.kind === 12, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token(), false); + ts.Debug.assert(fragment.kind === 13 || fragment.kind === 14, "Template fragment has wrong token kind"); + return fragment; } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -14822,8 +16075,8 @@ var ts; return parsePropertyOrMethodDeclaration(fullStart, decorators, modifiers); } if (decorators || modifiers) { - var name_12 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); - return parsePropertyDeclaration(fullStart, decorators, modifiers, name_12, undefined); + var name_13 = createMissingNode(69, true, ts.Diagnostics.Declaration_expected); + return parsePropertyDeclaration(fullStart, decorators, modifiers, name_13, undefined); } ts.Debug.fail("Should not have attempted to parse class member declaration."); } @@ -14909,7 +16162,7 @@ var ts; parseExpected(56); node.type = parseType(); parseSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } function parseEnumMember() { var node = createNode(255, scanner.getStartPos()); @@ -15847,8 +17100,8 @@ var ts; if (typeExpression.type.kind === 267) { var jsDocTypeReference = typeExpression.type; if (jsDocTypeReference.name.kind === 69) { - var name_13 = jsDocTypeReference.name; - if (name_13.text === "Object") { + var name_14 = jsDocTypeReference.name; + if (name_14.text === "Object") { typedefTag.jsDocTypeLiteral = scanChildTags(); } } @@ -15934,14 +17187,14 @@ var ts; } var typeParameters = createNodeArray(); while (true) { - var name_14 = parseJSDocIdentifierName(); + var name_15 = parseJSDocIdentifierName(); skipWhitespace(); - if (!name_14) { + if (!name_15) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(141, name_14.pos); - typeParameter.name = name_14; + var typeParameter = createNode(141, name_15.pos); + typeParameter.name = name_15; finishNode(typeParameter); typeParameters.push(typeParameter); if (token() === 24) { @@ -16344,7 +17597,7 @@ var ts; file = f; options = opts; languageVersion = ts.getEmitScriptTarget(options); - inStrictMode = !!file.externalModuleIndicator; + inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; skipTransformFlagAggregation = ts.isDeclarationFile(file); @@ -16374,6 +17627,14 @@ var ts; subtreeTransformFlags = 0; } return bindSourceFile; + function bindInStrictMode(file, opts) { + if (opts.alwaysStrict && !ts.isDeclarationFile(file)) { + return true; + } + else { + return !!file.externalModuleIndicator; + } + } function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); @@ -16492,11 +17753,17 @@ var ts; var message_1 = symbol.flags & 2 ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (ts.hasModifier(declaration, 512)) { + if (symbol.declarations && symbol.declarations.length) { + if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } - }); + else { + if (symbol.declarations && symbol.declarations.length && + (isDefaultExport || (node.kind === 235 && !node.isExportEquals))) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + } + } ts.forEach(symbol.declarations, function (declaration) { file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); }); @@ -16561,7 +17828,7 @@ var ts; } else { currentFlow = { flags: 2 }; - if (containerFlags & 16) { + if (containerFlags & (16 | 128)) { currentFlow.container = node; } currentReturnTarget = undefined; @@ -17016,7 +18283,9 @@ var ts; currentFlow = preTryFlow; bind(node.finallyBlock); } - currentFlow = finishFlowLabel(postFinallyLabel); + if (!node.finallyBlock || !(currentFlow.flags & 1)) { + currentFlow = finishFlowLabel(postFinallyLabel); + } } function bindSwitchStatement(node) { var postSwitchLabel = createBranchLabel(); @@ -17149,7 +18418,7 @@ var ts; } else { ts.forEachChild(node, bind); - if (node.operator === 57 || node.operator === 42) { + if (node.operator === 41 || node.operator === 42) { bindAssignmentTargetFlow(node.operand); } } @@ -17248,9 +18517,12 @@ var ts; return 1 | 32; case 256: return 1 | 4 | 32; + case 147: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 | 4 | 32 | 8 | 128; + } case 148: case 220: - case 147: case 146: case 149: case 150: @@ -17782,7 +19054,7 @@ var ts; var flags = node.kind === 235 && ts.exportAssignmentIsAlias(node) ? 8388608 : 4; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 | 8388608); + declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 | 8388608 | 32 | 16); } } function bindNamespaceExportDeclaration(node) { @@ -17794,12 +19066,12 @@ var ts; return; } else { - var parent_6 = node.parent; - if (!ts.isExternalModule(parent_6)) { + var parent_7 = node.parent; + if (!ts.isExternalModule(parent_7)) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files)); return; } - if (!parent_6.isDeclarationFile) { + if (!parent_7.isDeclarationFile) { file.bindDiagnostics.push(ts.createDiagnosticForNode(node, ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files)); return; } @@ -17979,6 +19251,9 @@ var ts; emitFlags |= 2048; } } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } return ts.hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); @@ -18117,8 +19392,7 @@ var ts; if (node.questionToken) { transformFlags |= 3; } - if (subtreeFlags & 2048 - || (name && ts.isIdentifier(name) && name.originalKeywordKind === 97)) { + if (subtreeFlags & 2048 || ts.isThisIdentifier(name)) { transformFlags |= 3; } if (modifierFlags & 92) { @@ -18220,7 +19494,7 @@ var ts; || (subtreeFlags & 2048)) { transformFlags |= 3; } - if (asteriskToken && node.emitFlags & 2097152) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152) { transformFlags |= 1536; } node.transformFlags = transformFlags | 536870912; @@ -18265,7 +19539,7 @@ var ts; if (subtreeFlags & 81920) { transformFlags |= 192; } - if (asteriskToken && node.emitFlags & 2097152) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152) { transformFlags |= 1536; } } @@ -18282,7 +19556,7 @@ var ts; if (subtreeFlags & 81920) { transformFlags |= 192; } - if (asteriskToken && node.emitFlags & 2097152) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152) { transformFlags |= 1536; } node.transformFlags = transformFlags | 536870912; @@ -18618,6 +19892,7 @@ var ts; var unknownSymbol = createSymbol(4 | 67108864, "unknown"); var resolvingSymbol = createSymbol(67108864, "__resolving__"); var anyType = createIntrinsicType(1, "any"); + var autoType = createIntrinsicType(1, "any"); var unknownType = createIntrinsicType(1, "unknown"); var undefinedType = createIntrinsicType(2048, "undefined"); var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 | 33554432, "undefined"); @@ -19175,7 +20450,7 @@ var ts; if (result && isInExternalModule && (meaning & 107455) === 107455) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 228) { - error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name); } } } @@ -19335,28 +20610,28 @@ var ts; var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier); var targetSymbol = resolveESModuleSymbol(moduleSymbol, node.moduleSpecifier); if (targetSymbol) { - var name_15 = specifier.propertyName || specifier.name; - if (name_15.text) { + var name_16 = specifier.propertyName || specifier.name; + if (name_16.text) { if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) { return moduleSymbol; } var symbolFromVariable = void 0; if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports["export="]) { - symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_15.text); + symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name_16.text); } else { - symbolFromVariable = getPropertyOfVariable(targetSymbol, name_15.text); + symbolFromVariable = getPropertyOfVariable(targetSymbol, name_16.text); } symbolFromVariable = resolveSymbol(symbolFromVariable); - var symbolFromModule = getExportOfModule(targetSymbol, name_15.text); - if (!symbolFromModule && allowSyntheticDefaultImports && name_15.text === "default") { + var symbolFromModule = getExportOfModule(targetSymbol, name_16.text); + if (!symbolFromModule && allowSyntheticDefaultImports && name_16.text === "default") { symbolFromModule = resolveExternalModuleSymbol(moduleSymbol) || resolveSymbol(moduleSymbol); } var symbol = symbolFromModule && symbolFromVariable ? combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) : symbolFromModule || symbolFromVariable; if (!symbol) { - error(name_15, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_15)); + error(name_16, ts.Diagnostics.Module_0_has_no_exported_member_1, getFullyQualifiedName(moduleSymbol), ts.declarationNameToString(name_16)); } return symbol; } @@ -19593,6 +20868,7 @@ var ts; } function getExportsForModule(moduleSymbol) { var visitedSymbols = []; + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || moduleSymbol.exports; function visit(symbol) { if (!(symbol && symbol.flags & 1952 && !ts.contains(visitedSymbols, symbol))) { @@ -20077,9 +21353,9 @@ var ts; var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent_7) { - walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), false); + var parent_8 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_8) { + walkSymbol(parent_8, getQualifiedLeftMeaning(meaning), false); } } if (accessibleSymbolChain) { @@ -20114,7 +21390,7 @@ var ts; ? "any" : type.intrinsicName); } - else if (type.flags & 268435456) { + else if (type.flags & 16384 && type.isThisType) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } @@ -20131,7 +21407,7 @@ var ts; else if (type.flags & (32768 | 65536 | 16 | 16384)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } - else if (!(flags & 512) && type.flags & (2097152 | 1572864) && type.aliasSymbol && + else if (!(flags & 512) && ((type.flags & 2097152 && !type.target) || type.flags & 1572864) && type.aliasSymbol && isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); @@ -20201,12 +21477,12 @@ var ts; var length_1 = outerTypeParameters.length; while (i < length_1) { var start = i; - var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_9 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_9); if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_8, typeArguments, start, i, flags); + writeSymbolTypeReference(parent_9, typeArguments, start, i, flags); writePunctuation(writer, 21); } } @@ -20595,12 +21871,12 @@ var ts; if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_9 = getDeclarationContainer(node); + var parent_10 = getDeclarationContainer(node); if (!(ts.getCombinedModifierFlags(node) & 1) && - !(node.kind !== 229 && parent_9.kind !== 256 && ts.isInAmbientContext(parent_9))) { - return isGlobalSourceFile(parent_9); + !(node.kind !== 229 && parent_10.kind !== 256 && ts.isInAmbientContext(parent_10))) { + return isGlobalSourceFile(parent_10); } - return isDeclarationVisible(parent_9); + return isDeclarationVisible(parent_10); case 145: case 144: case 149: @@ -20787,19 +22063,19 @@ var ts; } var type; if (pattern.kind === 167) { - var name_16 = declaration.propertyName || declaration.name; - if (isComputedNonLiteralName(name_16)) { + var name_17 = declaration.propertyName || declaration.name; + if (isComputedNonLiteralName(name_17)) { return anyType; } if (declaration.initializer) { getContextualType(declaration.initializer); } - var text = getTextOfPropertyName(name_16); + var text = getTextOfPropertyName(name_17); type = getTypeOfPropertyOfType(parentType, text) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); if (!type) { - error(name_16, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_16)); + error(name_17, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(parentType), ts.declarationNameToString(name_17)); return unknownType; } } @@ -20858,6 +22134,10 @@ var ts; } return undefined; } + function isAutoVariableInitializer(initializer) { + var expr = initializer && ts.skipParentheses(initializer); + return !expr || expr.kind === 93 || expr.kind === 69 && getResolvedSymbol(expr) === undefinedSymbol; + } function addOptionality(type, optional) { return strictNullChecks && optional ? includeFalsyTypes(type, 2048) : type; } @@ -20880,6 +22160,11 @@ var ts; if (declaration.type) { return addOptionality(getTypeFromTypeNode(declaration.type), declaration.questionToken && includeOptionality); } + if (declaration.kind === 218 && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedNodeFlags(declaration) & 2) && !(ts.getCombinedModifierFlags(declaration) & 1) && + !ts.isInAmbientContext(declaration) && isAutoVariableInitializer(declaration.initializer)) { + return autoType; + } if (declaration.kind === 142) { var func = declaration.parent; if (func.kind === 150 && !ts.hasDynamicName(func)) { @@ -20951,7 +22236,7 @@ var ts; result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 536870912; + result.isObjectLiteralPatternWithComputedProperties = true; } return result; } @@ -21420,7 +22705,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); + type.thisType = createType(16384); + type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -21953,13 +23239,24 @@ var ts; var current = _a[_i]; for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { var prop = _c[_b]; - getPropertyOfUnionOrIntersectionType(type, prop.name); + getUnionOrIntersectionProperty(type, prop.name); } if (type.flags & 524288) { break; } } - return type.resolvedProperties ? symbolsToArray(type.resolvedProperties) : emptyArray; + var props = type.resolvedProperties; + if (props) { + var result = []; + for (var key in props) { + var prop = props[key]; + if (!(prop.flags & 268435456 && prop.isPartial)) { + result.push(prop); + } + } + return result; + } + return emptyArray; } function getPropertiesOfType(type) { type = getApparentType(type); @@ -21998,6 +23295,7 @@ var ts; var props; var commonFlags = (containingType.flags & 1048576) ? 536870912 : 0; var isReadonly = false; + var isPartial = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); @@ -22016,20 +23314,20 @@ var ts; } } else if (containingType.flags & 524288) { - return undefined; + isPartial = true; } } } if (!props) { return undefined; } - if (props.length === 1) { + if (props.length === 1 && !isPartial) { return props[0]; } var propTypes = []; var declarations = []; var commonType = undefined; - var hasCommonType = true; + var hasNonUniformType = false; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { @@ -22040,22 +23338,20 @@ var ts; commonType = type; } else if (type !== commonType) { - hasCommonType = false; + hasNonUniformType = true; } - propTypes.push(getTypeOfSymbol(prop)); + propTypes.push(type); } - var result = createSymbol(4 | - 67108864 | - 268435456 | - commonFlags, name); + var result = createSymbol(4 | 67108864 | 268435456 | commonFlags, name); result.containingType = containingType; - result.hasCommonType = hasCommonType; + result.hasNonUniformType = hasNonUniformType; + result.isPartial = isPartial; result.declarations = declarations; result.isReadonly = isReadonly; result.type = containingType.flags & 524288 ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } - function getPropertyOfUnionOrIntersectionType(type, name) { + function getUnionOrIntersectionProperty(type, name) { var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); var property = properties[name]; if (!property) { @@ -22066,6 +23362,10 @@ var ts; } return property; } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + return property && !(property.flags & 268435456 && property.isPartial) ? property : undefined; + } function getPropertyOfType(type, name) { type = getApparentType(type); if (type.flags & 2588672) { @@ -22438,7 +23738,7 @@ var ts; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 268435456) && type.flags & 16384 && !ts.contains(checked, type)) { + while (type && type.flags & 16384 && !(type.isThisType) && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -22722,7 +24022,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 | 268435456); + type.thisType = createType(16384); + type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; type.declaredCallSignatures = emptyArray; @@ -22821,7 +24122,24 @@ var ts; } return false; } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 256) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 256) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } var i = types.length; while (i > 0) { i--; @@ -23796,7 +25114,8 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 536870912) && maybeTypeOfKind(target, 2588672)) { + if (maybeTypeOfKind(target, 2588672) && + (!(target.flags & 2588672) || !target.isObjectLiteralPatternWithComputedProperties)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -25001,17 +26320,10 @@ var ts; } function isDiscriminantProperty(type, name) { if (type && type.flags & 524288) { - var prop = getPropertyOfType(type, name); - if (!prop) { - var filteredType = getTypeWithFacts(type, 4194304); - if (filteredType !== type && filteredType.flags & 524288) { - prop = getPropertyOfType(filteredType, name); - } - } + var prop = getUnionOrIntersectionProperty(type, name); if (prop && prop.flags & 268435456) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !prop.hasCommonType && - isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = prop.hasNonUniformType && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -25288,6 +26600,23 @@ var ts; } return f(type) ? type : neverType; } + function mapType(type, f) { + return type.flags & 524288 ? getUnionType(ts.map(type.types, f)) : f(type); + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 2 ? extractTypesOfKind(typeWithLiterals, 2 | 32) : + t.flags & 4 ? extractTypesOfKind(typeWithLiterals, 4 | 64) : + t; + }); + } + return typeWithPrimitives; + } function isIncomplete(flowType) { return flowType.flags === 0; } @@ -25302,7 +26631,9 @@ var ts; if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048); + var initialType = assumeInitialized ? declaredType : + declaredType === autoType ? undefinedType : + includeFalsyTypes(declaredType, 2048); var visitedFlowStart = visitedFlowCount; var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; @@ -25364,10 +26695,13 @@ var ts; function getTypeAtFlowAssignment(flow) { var node = flow.node; if (isMatchingReference(reference, node)) { - var isIncrementOrDecrement = node.parent.kind === 185 || node.parent.kind === 186; - return declaredType.flags & 524288 && !isIncrementOrDecrement ? - getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : - declaredType; + if (node.parent.kind === 185 || node.parent.kind === 186) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + return declaredType === autoType ? getBaseTypeOfLiteralType(getInitialOrAssignedType(node)) : + declaredType.flags & 524288 ? getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : + declaredType; } if (containsMatchingReference(reference, node)) { return declaredType; @@ -25553,12 +26887,12 @@ var ts; assumeTrue ? 16384 : 131072; return getTypeWithFacts(type, facts); } - if (type.flags & 2589191) { + if (type.flags & 2589185) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 ? type : narrowedType; + return narrowedType.flags & 8192 ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -25596,7 +26930,8 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); + var caseType = discriminantType.flags & 8192 ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -25723,7 +27058,7 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpression(location) && !ts.isAssignmentTarget(location)) { + if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { var type = checkExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; @@ -25846,14 +27181,26 @@ var ts; var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; while (flowContainer !== declarationContainer && - (flowContainer.kind === 179 || flowContainer.kind === 180) && + (flowContainer.kind === 179 || + flowContainer.kind === 180 || + ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } - var assumeInitialized = !strictNullChecks || (type.flags & 1) !== 0 || isParameter || - isOuterVariable || ts.isInAmbientContext(declaration); + var assumeInitialized = isParameter || isOuterVariable || + type !== autoType && (!strictNullChecks || (type.flags & 1) !== 0) || + ts.isInAmbientContext(declaration); var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); - if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { + if (type === autoType) { + if (flowType === autoType) { + if (compilerOptions.noImplicitAny) { + error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol)); + error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(anyType)); + } + return anyType; + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 2048) && getFalsyFlags(flowType) & 2048) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); return type; } @@ -25938,7 +27285,7 @@ var ts; } } function findFirstSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return n; } else if (ts.isFunctionLike(n)) { @@ -26003,7 +27350,7 @@ var ts; captureLexicalThis(node, container); } if (ts.isFunctionLike(container) && - (!isInParameterInitializerBeforeContainingFunction(node) || getFunctionLikeThisParameter(container))) { + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { if (container.kind === 179 && ts.isInJavaScriptFile(container.parent) && ts.getSpecialPropertyAssignmentKind(container.parent) === 3) { @@ -26222,11 +27569,11 @@ var ts; } if (ts.isBindingPattern(declaration.parent)) { var parentDeclaration = declaration.parent.parent; - var name_17 = declaration.propertyName || declaration.name; + var name_18 = declaration.propertyName || declaration.name; if (ts.isVariableLike(parentDeclaration) && parentDeclaration.type && - !ts.isBindingPattern(name_17)) { - var text = getTextOfPropertyName(name_17); + !ts.isBindingPattern(name_18)) { + var text = getTextOfPropertyName(name_18); if (text) { return getTypeOfPropertyOfType(getTypeFromTypeNode(parentDeclaration.type), text); } @@ -26663,7 +28010,8 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 536870912)) { + else if (contextualTypeHasPattern && + !(contextualType.flags & 2588672 && contextualType.isObjectLiteralPatternWithComputedProperties)) { var impliedProp = getPropertyOfType(contextualType, member.name); if (impliedProp) { prop.flags |= impliedProp.flags & 536870912; @@ -26714,7 +28062,10 @@ var ts; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216; - result.flags |= 8388608 | 67108864 | freshObjectLiteralFlag | (typeFlags & 234881024) | (patternWithComputedProperties ? 536870912 : 0); + result.flags |= 8388608 | 67108864 | freshObjectLiteralFlag | (typeFlags & 234881024); + if (patternWithComputedProperties) { + result.isObjectLiteralPatternWithComputedProperties = true; + } if (inDestructuringPattern) { result.pattern = node; } @@ -27109,7 +28460,7 @@ var ts; if (flags & 32) { return true; } - if (type.flags & 268435456) { + if (type.flags & 16384 && type.isThisType) { type = getConstraintOfTypeParameter(type); } if (!(getTargetType(type).flags & (32768 | 65536) && hasBaseType(type, enclosingClass))) { @@ -27150,7 +28501,7 @@ var ts; var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 268435456 ? apparentType : type); + reportNonexistentProperty(right, type.flags & 16384 && type.isThisType ? apparentType : type); } return unknownType; } @@ -27266,15 +28617,15 @@ var ts; return unknownType; } if (node.argumentExpression) { - var name_18 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); - if (name_18 !== undefined) { - var prop = getPropertyOfType(objectType, name_18); + var name_19 = getPropertyNameForIndexedAccess(node.argumentExpression, indexType); + if (name_19 !== undefined) { + var prop = getPropertyOfType(objectType, name_19); if (prop) { getNodeLinks(node).resolvedSymbol = prop; return getTypeOfSymbol(prop); } else if (isConstEnum) { - error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_18, symbolToString(objectType.symbol)); + error(node.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_const_enum_1, name_19, symbolToString(objectType.symbol)); return unknownType; } } @@ -27375,19 +28726,19 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_10 = signature.declaration && signature.declaration.parent; + var parent_11 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_10 === lastParent) { + if (lastParent && parent_11 === lastParent) { index++; } else { - lastParent = parent_10; + lastParent = parent_11; index = cutoffIndex; } } else { index = cutoffIndex = result.length; - lastParent = parent_10; + lastParent = parent_11; } lastSymbol = symbol; if (signature.hasLiteralTypes) { @@ -28290,7 +29641,9 @@ var ts; if (!contextualSignature) { reportErrorsFromWidening(func, type); } - if (isUnitType(type) && !(contextualSignature && isLiteralContextualType(getReturnTypeOfSignature(contextualSignature)))) { + if (isUnitType(type) && + !(contextualSignature && + isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { type = getWidenedLiteralType(type); } var widenedType = getWidenedType(type); @@ -28440,7 +29793,7 @@ var ts; } } } - if (produceDiagnostics && node.kind !== 147 && node.kind !== 146) { + if (produceDiagnostics && node.kind !== 147) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } @@ -28690,14 +30043,14 @@ var ts; } function checkObjectLiteralDestructuringPropertyAssignment(objectLiteralType, property, contextualMapper) { if (property.kind === 253 || property.kind === 254) { - var name_19 = property.name; - if (name_19.kind === 140) { - checkComputedPropertyName(name_19); + var name_20 = property.name; + if (name_20.kind === 140) { + checkComputedPropertyName(name_20); } - if (isComputedNonLiteralName(name_19)) { + if (isComputedNonLiteralName(name_20)) { return undefined; } - var text = getTextOfPropertyName(name_19); + var text = getTextOfPropertyName(name_20); var type = isTypeAny(objectLiteralType) ? objectLiteralType : getTypeOfPropertyOfType(objectLiteralType, text) || @@ -28712,7 +30065,7 @@ var ts; } } else { - error(name_19, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_19)); + error(name_20, ts.Diagnostics.Type_0_has_no_property_1_and_no_string_index_signature, typeToString(objectLiteralType), ts.declarationNameToString(name_20)); } } else { @@ -29361,9 +30714,9 @@ var ts; else if (parameterName) { var hasReportedError = false; for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) { - var name_20 = _a[_i].name; - if (ts.isBindingPattern(name_20) && - checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_20, parameterName, typePredicate.parameterName)) { + var name_21 = _a[_i].name; + if (ts.isBindingPattern(name_21) && + checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_21, parameterName, typePredicate.parameterName)) { hasReportedError = true; break; } @@ -29383,9 +30736,9 @@ var ts; case 156: case 147: case 146: - var parent_11 = node.parent; - if (node === parent_11.type) { - return parent_11; + var parent_12 = node.parent; + if (node === parent_12.type) { + return parent_12; } } } @@ -29395,15 +30748,15 @@ var ts; if (ts.isOmittedExpression(element)) { continue; } - var name_21 = element.name; - if (name_21.kind === 69 && - name_21.text === predicateVariableName) { + var name_22 = element.name; + if (name_22.kind === 69 && + name_22.text === predicateVariableName) { error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName); return true; } - else if (name_21.kind === 168 || - name_21.kind === 167) { - if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_21, predicateVariableNode, predicateVariableName)) { + else if (name_22.kind === 168 || + name_22.kind === 167) { + if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name_22, predicateVariableNode, predicateVariableName)) { return true; } } @@ -29596,7 +30949,7 @@ var ts; return n.name && containsSuperCall(n.name); } function containsSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return true; } else if (ts.isFunctionLike(n)) { @@ -29622,6 +30975,7 @@ var ts; } var containingClassDecl = node.parent; if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); if (superCall) { @@ -29635,7 +30989,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 202 && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 202 && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -30345,7 +31699,7 @@ var ts; var parameter = local.valueDeclaration; if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && - !parameterIsThisKeyword(parameter) && + !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(parameter)) { error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } @@ -30360,9 +31714,6 @@ var ts; } } } - function parameterIsThisKeyword(parameter) { - return parameter.name && parameter.name.originalKeywordKind === 97; - } function parameterNameStartsWithUnderscore(parameter) { return parameter.name && parameter.name.kind === 69 && parameter.name.text.charCodeAt(0) === 95; } @@ -30500,6 +31851,9 @@ var ts; } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + if (modulekind >= ts.ModuleKind.ES6) { + return; + } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } @@ -30547,8 +31901,8 @@ var ts; container.kind === 225 || container.kind === 256); if (!namesShareScope) { - var name_22 = symbolToString(localDeclarationSymbol); - error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_22, name_22); + var name_23 = symbolToString(localDeclarationSymbol); + error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name_23, name_23); } } } @@ -30603,6 +31957,9 @@ var ts; } } } + function convertAutoToAny(type) { + return type === autoType ? anyType : type; + } function checkVariableLikeDeclaration(node) { checkDecorators(node); checkSourceElement(node.type); @@ -30616,12 +31973,12 @@ var ts; if (node.propertyName && node.propertyName.kind === 140) { checkComputedPropertyName(node.propertyName); } - var parent_12 = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent_12); - var name_23 = node.propertyName || node.name; - var property = getPropertyOfType(parentType, getTextOfPropertyName(name_23)); - if (parent_12.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property); + var parent_13 = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent_13); + var name_24 = node.propertyName || node.name; + var property = getPropertyOfType(parentType, getTextOfPropertyName(name_24)); + if (parent_13.initializer && property && getParentOfSymbol(property)) { + checkClassPropertyAccess(parent_13, parent_13.initializer, parentType, property); } } if (ts.isBindingPattern(node.name)) { @@ -30639,7 +31996,7 @@ var ts; return; } var symbol = getSymbolOfNode(node); - var type = getTypeOfVariableOrParameterOrProperty(symbol); + var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); if (node === symbol.valueDeclaration) { if (node.initializer && node.parent.parent.kind !== 207) { checkTypeAssignableTo(checkExpressionCached(node.initializer), type, node, undefined); @@ -30647,7 +32004,7 @@ var ts; } } else { - var declarationType = getWidenedTypeForVariableLikeDeclaration(node); + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); } @@ -31022,7 +32379,12 @@ var ts; } } checkExpression(node.expression); - error(node.expression, ts.Diagnostics.All_symbols_within_a_with_block_will_be_resolved_to_any); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } } function checkSwitchStatement(node) { checkGrammarStatementInAmbientContext(node); @@ -31741,9 +33103,11 @@ var ts; grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (ts.isIdentifier(node.name)) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); if (symbol.flags & 512 @@ -31818,9 +33182,9 @@ var ts; break; case 169: case 218: - var name_24 = node.name; - if (ts.isBindingPattern(name_24)) { - for (var _b = 0, _c = name_24.elements; _b < _c.length; _b++) { + var name_25 = node.name; + if (ts.isBindingPattern(name_25)) { + for (var _b = 0, _c = name_25.elements; _b < _c.length; _b++) { var el = _c[_b]; checkModuleAugmentationElement(el, isGlobalAugmentation); } @@ -31982,9 +33346,11 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 256 && node.parent.kind !== 226 && node.parent.kind !== 225) { - return grammarErrorOnFirstToken(node, errorMessage); + var isInAppropriateContext = node.parent.kind === 256 || node.parent.kind === 226 || node.parent.kind === 225; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); } + return !isInAppropriateContext; } function checkExportSpecifier(node) { checkAliasSymbol(node); @@ -32046,12 +33412,12 @@ var ts; error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements); } } - var exports = getExportsOfModule(moduleSymbol); - for (var id in exports) { + var exports_1 = getExportsOfModule(moduleSymbol); + for (var id in exports_1) { if (id === "__export") { continue; } - var _a = exports[id], declarations = _a.declarations, flags = _a.flags; + var _a = exports_1[id], declarations = _a.declarations, flags = _a.flags; if (flags & (1920 | 64 | 384)) { continue; } @@ -32071,7 +33437,8 @@ var ts; links.exportsChecked = true; } function isNotOverload(declaration) { - return declaration.kind !== 220 || !!declaration.body; + return (declaration.kind !== 220 && declaration.kind !== 147) || + !!declaration.body; } } function checkSourceElement(node) { @@ -32556,6 +33923,9 @@ var ts; node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } + if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, false)) { + return resolveExternalModuleName(node, node); + } case 8: if (node.parent.kind === 173 && node.parent.argumentExpression === node) { var objectType = checkExpression(node.parent.expression); @@ -32670,9 +34040,9 @@ var ts; function getRootSymbols(symbol) { if (symbol.flags & 268435456) { var symbols_3 = []; - var name_25 = symbol.name; + var name_26 = symbol.name; ts.forEach(getSymbolLinks(symbol).containingType.types, function (t) { - var symbol = getPropertyOfType(t, name_25); + var symbol = getPropertyOfType(t, name_26); if (symbol) { symbols_3.push(symbol); } @@ -32979,9 +34349,9 @@ var ts; } var location = reference; if (startInDeclarationContainer) { - var parent_13 = reference.parent; - if (ts.isDeclaration(parent_13) && reference === parent_13.name) { - location = getDeclarationContainer(parent_13); + var parent_14 = reference.parent; + if (ts.isDeclaration(parent_14) && reference === parent_14.name) { + location = getDeclarationContainer(parent_14); } } return resolveName(location, reference.text, 107455 | 1048576 | 8388608, undefined, undefined); @@ -33090,9 +34460,9 @@ var ts; } var current = symbol; while (true) { - var parent_14 = getParentOfSymbol(current); - if (parent_14) { - current = parent_14; + var parent_15 = getParentOfSymbol(current); + if (parent_15) { + current = parent_15; } else { break; @@ -33211,26 +34581,26 @@ var ts; if (compilerOptions.importHelpers && firstFileRequestingExternalHelpers) { var helpersModule = resolveExternalModule(firstFileRequestingExternalHelpers, ts.externalHelpersModuleNameText, ts.Diagnostics.Cannot_find_module_0, undefined); if (helpersModule) { - var exports = helpersModule.exports; + var exports_2 = helpersModule.exports; if (requestedExternalEmitHelpers & 1024 && languageVersion < 2) { - verifyHelperSymbol(exports, "__extends", 107455); + verifyHelperSymbol(exports_2, "__extends", 107455); } if (requestedExternalEmitHelpers & 16384 && compilerOptions.jsx !== 1) { - verifyHelperSymbol(exports, "__assign", 107455); + verifyHelperSymbol(exports_2, "__assign", 107455); } if (requestedExternalEmitHelpers & 2048) { - verifyHelperSymbol(exports, "__decorate", 107455); + verifyHelperSymbol(exports_2, "__decorate", 107455); if (compilerOptions.emitDecoratorMetadata) { - verifyHelperSymbol(exports, "__metadata", 107455); + verifyHelperSymbol(exports_2, "__metadata", 107455); } } if (requestedExternalEmitHelpers & 4096) { - verifyHelperSymbol(exports, "__param", 107455); + verifyHelperSymbol(exports_2, "__param", 107455); } if (requestedExternalEmitHelpers & 8192) { - verifyHelperSymbol(exports, "__awaiter", 107455); + verifyHelperSymbol(exports_2, "__awaiter", 107455); if (languageVersion < 2) { - verifyHelperSymbol(exports, "__generator", 107455); + verifyHelperSymbol(exports_2, "__generator", 107455); } } } @@ -33652,8 +35022,8 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_2 = args; _i < args_2.length; _i++) { - var arg = args_2[_i]; + for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { + var arg = args_4[_i]; if (arg.kind === 193) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } @@ -33761,10 +35131,9 @@ var ts; var GetOrSetAccessor = GetAccessor | SetAccessor; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; - var name_26 = prop.name; - if (prop.kind === 193 || - name_26.kind === 140) { - checkGrammarComputedPropertyName(name_26); + var name_27 = prop.name; + if (name_27.kind === 140) { + checkGrammarComputedPropertyName(name_27); } if (prop.kind === 254 && !inDestructuring && prop.objectAssignmentInitializer) { return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment); @@ -33780,8 +35149,8 @@ var ts; var currentKind = void 0; if (prop.kind === 253 || prop.kind === 254) { checkGrammarForInvalidQuestionMark(prop, prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional); - if (name_26.kind === 8) { - checkGrammarNumericLiteral(name_26); + if (name_27.kind === 8) { + checkGrammarNumericLiteral(name_27); } currentKind = Property; } @@ -33797,7 +35166,7 @@ var ts; else { ts.Debug.fail("Unexpected syntax kind:" + prop.kind); } - var effectiveName = ts.getPropertyNameForPropertyNameNode(name_26); + var effectiveName = ts.getPropertyNameForPropertyNameNode(name_27); if (effectiveName === undefined) { continue; } @@ -33807,18 +35176,18 @@ var ts; else { var existingKind = seen[effectiveName]; if (currentKind === Property && existingKind === Property) { - grammarErrorOnNode(name_26, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_26)); + grammarErrorOnNode(name_27, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name_27)); } else if ((currentKind & GetOrSetAccessor) && (existingKind & GetOrSetAccessor)) { if (existingKind !== GetOrSetAccessor && currentKind !== existingKind) { seen[effectiveName] = currentKind | existingKind; } else { - return grammarErrorOnNode(name_26, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); + return grammarErrorOnNode(name_27, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name); } } else { - return grammarErrorOnNode(name_26, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); + return grammarErrorOnNode(name_27, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name); } } } @@ -33831,12 +35200,12 @@ var ts; continue; } var jsxAttr = attr; - var name_27 = jsxAttr.name; - if (!seen[name_27.text]) { - seen[name_27.text] = true; + var name_28 = jsxAttr.name; + if (!seen[name_28.text]) { + seen[name_28.text] = true; } else { - return grammarErrorOnNode(name_27, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); + return grammarErrorOnNode(name_28, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name); } var initializer = jsxAttr.initializer; if (initializer && initializer.kind === 248 && !initializer.expression) { @@ -33919,17 +35288,8 @@ var ts; return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 149 ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 149 ? 1 : 2) && - accessor.parameters[0].name.kind === 69 && - accessor.parameters[0].name.originalKeywordKind === 97) { - return accessor.parameters[0]; - } - } - function getFunctionLikeThisParameter(func) { - if (func.parameters.length && - func.parameters[0].name.kind === 69 && - func.parameters[0].name.originalKeywordKind === 97) { - return func.parameters[0]; + if (accessor.parameters.length === (accessor.kind === 149 ? 1 : 2)) { + return ts.getThisParameter(accessor); } } function checkGrammarForNonSymbolComputedProperty(node, message) { @@ -34763,7 +36123,7 @@ var ts; case 175: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); case 176: - return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplate)); + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); case 178: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); case 179: @@ -34787,7 +36147,7 @@ var ts; case 188: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 189: - return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateLiteralFragment), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); case 190: return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); case 191: @@ -34797,7 +36157,7 @@ var ts; case 194: return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); case 197: - return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateLiteralFragment)); + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); case 199: return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); case 200: @@ -35072,7 +36432,7 @@ var ts; return expression; function emitAssignment(name, value, location) { var expression = ts.createAssignment(name, value, location); - context.setNodeEmitFlags(expression, 2048); + ts.setEmitFlags(expression, 2048); ts.aggregateTransformFlags(expression); expressions.push(expression); } @@ -35089,7 +36449,7 @@ var ts; return declarations; function emitAssignment(name, value, location) { var declaration = ts.createVariableDeclaration(name, undefined, value, location); - context.setNodeEmitFlags(declaration, 2048); + ts.setEmitFlags(declaration, 2048); ts.aggregateTransformFlags(declaration); declarations.push(declaration); } @@ -35113,7 +36473,7 @@ var ts; } var declaration = ts.createVariableDeclaration(name, undefined, value, location); declaration.original = original; - context.setNodeEmitFlags(declaration, 2048); + ts.setEmitFlags(declaration, 2048); declarations.push(declaration); ts.aggregateTransformFlags(declaration); } @@ -35153,7 +36513,7 @@ var ts; function emitPendingAssignment(name, value, location, original) { var expression = ts.createAssignment(name, value, location); expression.original = original; - context.setNodeEmitFlags(expression, 2048); + ts.setEmitFlags(expression, 2048); pendingAssignments.push(expression); return expression; } @@ -35197,10 +36557,10 @@ var ts; emitArrayLiteralAssignment(target, value, location); } else { - var name_28 = ts.getMutableClone(target); - context.setSourceMapRange(name_28, target); - context.setCommentRange(name_28, target); - emitAssignment(name_28, value, location, undefined); + var name_29 = ts.getMutableClone(target); + ts.setSourceMapRange(name_29, target); + ts.setCommentRange(name_29, target); + emitAssignment(name_29, value, location, undefined); } } function emitObjectLiteralAssignment(target, value, location) { @@ -35314,7 +36674,7 @@ var ts; (function (ts) { var USE_NEW_TYPE_METADATA_FORMAT = false; function transformTypeScript(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, setCommentRange = context.setCommentRange, setSourceMapRange = context.setSourceMapRange, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -35323,10 +36683,13 @@ var ts; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; + context.enableSubstitution(172); + context.enableSubstitution(173); var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; var currentScope; + var currentScopeFirstDeclarationsOfName; var currentSourceFileExternalHelpersModuleName; var enabledSubstitutions; var classAliases; @@ -35334,12 +36697,19 @@ var ts; var currentSuperContainer; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitNode(node, visitor, ts.isSourceFile); } function saveStateAndInvoke(node, f) { var savedCurrentScope = currentScope; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; onBeforeVisitNode(node); var visited = f(node); + if (currentScope !== savedCurrentScope) { + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + } currentScope = savedCurrentScope; return visited; } @@ -35493,11 +36863,22 @@ var ts; case 226: case 199: currentScope = node; + currentScopeFirstDeclarationsOfName = undefined; + break; + case 221: + case 220: + if (ts.hasModifier(node, 2)) { + break; + } + recordEmittedDeclarationInScope(node); break; } } function visitSourceFile(node) { currentSourceFile = node; + if (compilerOptions.alwaysStrict) { + node = ts.ensureUseStrict(node); + } if (node.flags & 31744 && compilerOptions.importHelpers && (ts.isExternalModule(node) || compilerOptions.isolatedModules)) { @@ -35519,7 +36900,7 @@ var ts; else { node = ts.visitEachChild(node, visitor, context); } - setNodeEmitFlags(node, 1 | node.emitFlags); + ts.setEmitFlags(node, 1 | ts.getEmitFlags(node)); return node; } function shouldEmitDecorateCallForClass(node) { @@ -35549,7 +36930,7 @@ var ts; var classDeclaration = ts.createClassDeclaration(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), name, undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, hasExtendsClause), node); ts.setOriginalNode(classDeclaration, node); if (staticProperties.length > 0) { - setNodeEmitFlags(classDeclaration, 1024 | getNodeEmitFlags(classDeclaration)); + ts.setEmitFlags(classDeclaration, 1024 | ts.getEmitFlags(classDeclaration)); } statements.push(classDeclaration); } @@ -35591,7 +36972,7 @@ var ts; var transformedClassExpression = ts.createVariableStatement(undefined, ts.createLetDeclarationList([ ts.createVariableDeclaration(classAlias || declaredName, undefined, classExpression) ]), location); - setCommentRange(transformedClassExpression, node); + ts.setCommentRange(transformedClassExpression, node); statements.push(ts.setOriginalNode(transformedClassExpression, node)); if (classAlias) { statements.push(ts.setOriginalNode(ts.createVariableStatement(undefined, ts.createLetDeclarationList([ @@ -35612,7 +36993,7 @@ var ts; enableSubstitutionForClassAliases(); classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); } - setNodeEmitFlags(classExpression, 524288 | getNodeEmitFlags(classExpression)); + ts.setEmitFlags(classExpression, 524288 | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); ts.addRange(expressions, generateInitializedPropertyExpressions(node, staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); @@ -35673,7 +37054,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 202 && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 202 && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -35692,9 +37073,9 @@ var ts; ts.Debug.assert(ts.isIdentifier(node.name)); var name = node.name; var propertyName = ts.getMutableClone(name); - setNodeEmitFlags(propertyName, 49152 | 1536); + ts.setEmitFlags(propertyName, 49152 | 1536); var localName = ts.getMutableClone(name); - setNodeEmitFlags(localName, 49152); + ts.setEmitFlags(localName, 49152); return ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), propertyName, node.name), localName), ts.moveRangePos(node, -1))); } function getInitializedProperties(node, isStatic) { @@ -35715,8 +37096,8 @@ var ts; for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var property = properties_7[_i]; var statement = ts.createStatement(transformInitializedProperty(node, property, receiver)); - setSourceMapRange(statement, ts.moveRangePastModifiers(property)); - setCommentRange(statement, property); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); statements.push(statement); } } @@ -35726,8 +37107,8 @@ var ts; var property = properties_8[_i]; var expression = transformInitializedProperty(node, property, receiver); expression.startsOnNewLine = true; - setSourceMapRange(expression, ts.moveRangePastModifiers(property)); - setCommentRange(expression, property); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + ts.setCommentRange(expression, property); expressions.push(expression); } return expressions; @@ -35868,7 +37249,7 @@ var ts; : ts.createNull() : undefined; var helper = ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); - setNodeEmitFlags(helper, 49152); + ts.setEmitFlags(helper, 49152); return helper; } function addConstructorDecorationStatement(statements, node, decoratedClassAlias) { @@ -35886,12 +37267,12 @@ var ts; if (decoratedClassAlias) { var expression = ts.createAssignment(decoratedClassAlias, ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node))); var result = ts.createAssignment(getDeclarationName(node), expression, ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152); + ts.setEmitFlags(result, 49152); return result; } else { var result = ts.createAssignment(getDeclarationName(node), ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node)), ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152); + ts.setEmitFlags(result, 49152); return result; } } @@ -35905,7 +37286,7 @@ var ts; for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) { var decorator = decorators_1[_i]; var helper = ts.createParamHelper(currentSourceFileExternalHelpersModuleName, transformDecorator(decorator), parameterOffset, decorator.expression); - setNodeEmitFlags(helper, 49152); + ts.setEmitFlags(helper, 49152); expressions.push(helper); } } @@ -36070,10 +37451,33 @@ var ts; : ts.createIdentifier("Symbol"); case 155: return serializeTypeReferenceNode(node); + case 163: + case 162: + { + var unionOrIntersection = node; + var serializedUnion = void 0; + for (var _i = 0, _a = unionOrIntersection.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var serializedIndividual = serializeTypeNode(typeNode); + if (serializedIndividual.kind !== 69) { + serializedUnion = undefined; + break; + } + if (serializedIndividual.text === "Object") { + return serializedIndividual; + } + if (serializedUnion && serializedUnion.text !== serializedIndividual.text) { + serializedUnion = undefined; + break; + } + serializedUnion = serializedIndividual; + } + if (serializedUnion) { + return serializedUnion; + } + } case 158: case 159: - case 162: - case 163: case 117: case 165: break; @@ -36117,14 +37521,14 @@ var ts; function serializeEntityNameAsExpression(node, useFallback) { switch (node.kind) { case 69: - var name_29 = ts.getMutableClone(node); - name_29.flags &= ~8; - name_29.original = undefined; - name_29.parent = currentScope; + var name_30 = ts.getMutableClone(node); + name_30.flags &= ~8; + name_30.original = undefined; + name_30.parent = currentScope; if (useFallback) { - return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_29), ts.createLiteral("undefined")), name_29); + return ts.createLogicalAnd(ts.createStrictInequality(ts.createTypeOf(name_30), ts.createLiteral("undefined")), name_30); } - return name_29; + return name_30; case 139: return serializeQualifiedNameAsExpression(node, useFallback); } @@ -36194,8 +37598,8 @@ var ts; return undefined; } var method = ts.createMethod(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), undefined, ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, transformFunctionBody(node), node); - setCommentRange(method, node); - setSourceMapRange(method, ts.moveRangePastDecorators(node)); + ts.setCommentRange(method, node); + ts.setSourceMapRange(method, ts.moveRangePastDecorators(node)); ts.setOriginalNode(method, node); return method; } @@ -36207,8 +37611,8 @@ var ts; return undefined; } var accessor = ts.createGetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), undefined, node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setCommentRange(accessor, node); + ts.setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); ts.setOriginalNode(accessor, node); return accessor; } @@ -36217,8 +37621,8 @@ var ts; return undefined; } var accessor = ts.createSetAccessor(undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitNodes(node.parameters, visitor, ts.isParameter), node.body ? ts.visitEachChild(node.body, visitor, context) : ts.createBlock([]), node); - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setCommentRange(accessor, node); + ts.setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); ts.setOriginalNode(accessor, node); return accessor; } @@ -36313,11 +37717,11 @@ var ts; if (languageVersion >= 2) { if (resolver.getNodeCheckFlags(node) & 4096) { enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 8); + ts.setEmitFlags(block, 8); } else if (resolver.getNodeCheckFlags(node) & 2048) { enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 4); + ts.setEmitFlags(block, 4); } } return block; @@ -36327,14 +37731,14 @@ var ts; } } function visitParameter(node) { - if (node.name && ts.isIdentifier(node.name) && node.name.originalKeywordKind === 97) { + if (ts.parameterIsThisKeyword(node)) { return undefined; } var parameter = ts.createParameterDeclaration(undefined, undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), undefined, undefined, ts.visitNode(node.initializer, visitor, ts.isExpression), ts.moveRangePastModifiers(node)); ts.setOriginalNode(parameter, node); - setCommentRange(parameter, node); - setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - setNodeEmitFlags(parameter.name, 1024); + ts.setCommentRange(parameter, node); + ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(parameter.name, 1024); return parameter; } function visitVariableStatement(node) { @@ -36383,12 +37787,13 @@ var ts; || compilerOptions.isolatedModules; } function shouldEmitVarForEnumDeclaration(node) { - return !ts.hasModifier(node, 1) - || (isES6ExportedDeclaration(node) && ts.isFirstDeclarationOfKind(node, node.kind)); + return isFirstEmittedDeclarationInScope(node) + && (!ts.hasModifier(node, 1) + || isES6ExportedDeclaration(node)); } function addVarForEnumExportedFromNamespace(statements, node) { var statement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, getExportName(node))]); - setSourceMapRange(statement, node); + ts.setSourceMapRange(statement, node); statements.push(statement); } function visitEnumDeclaration(node) { @@ -36397,6 +37802,7 @@ var ts; } var statements = []; var emitFlags = 64; + recordEmittedDeclarationInScope(node); if (shouldEmitVarForEnumDeclaration(node)) { addVarForEnumOrModuleDeclaration(statements, node); if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { @@ -36408,7 +37814,7 @@ var ts; var exportName = getExportName(node); var enumStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformEnumBody(node, containerName)), undefined, [ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()))]), node); ts.setOriginalNode(enumStatement, node); - setNodeEmitFlags(enumStatement, emitFlags); + ts.setEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); if (isNamespaceExport(node)) { addVarForEnumExportedFromNamespace(statements, node); @@ -36447,18 +37853,32 @@ var ts; function shouldEmitModuleDeclaration(node) { return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } - function isModuleMergedWithES6Class(node) { - return languageVersion === 2 - && ts.isMergedWithClass(node); - } function isES6ExportedDeclaration(node) { return isExternalModuleExport(node) && moduleKind === ts.ModuleKind.ES6; } + function recordEmittedDeclarationInScope(node) { + var name = node.symbol && node.symbol.name; + if (name) { + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createMap(); + } + if (!(name in currentScopeFirstDeclarationsOfName)) { + currentScopeFirstDeclarationsOfName[name] = node; + } + } + } + function isFirstEmittedDeclarationInScope(node) { + if (currentScopeFirstDeclarationsOfName) { + var name_31 = node.symbol && node.symbol.name; + if (name_31) { + return currentScopeFirstDeclarationsOfName[name_31] === node; + } + } + return false; + } function shouldEmitVarForModuleDeclaration(node) { - return !isModuleMergedWithES6Class(node) - && (!isES6ExportedDeclaration(node) - || ts.isFirstDeclarationOfKind(node, node.kind)); + return isFirstEmittedDeclarationInScope(node); } function addVarForEnumOrModuleDeclaration(statements, node) { var statement = ts.createVariableStatement(isES6ExportedDeclaration(node) @@ -36468,13 +37888,13 @@ var ts; ]); ts.setOriginalNode(statement, node); if (node.kind === 224) { - setSourceMapRange(statement.declarationList, node); + ts.setSourceMapRange(statement.declarationList, node); } else { - setSourceMapRange(statement, node); + ts.setSourceMapRange(statement, node); } - setCommentRange(statement, node); - setNodeEmitFlags(statement, 32768); + ts.setCommentRange(statement, node); + ts.setEmitFlags(statement, 32768); statements.push(statement); } function visitModuleDeclaration(node) { @@ -36485,6 +37905,7 @@ var ts; enableSubstitutionForNamespaceExports(); var statements = []; var emitFlags = 64; + recordEmittedDeclarationInScope(node); if (shouldEmitVarForModuleDeclaration(node)) { addVarForEnumOrModuleDeclaration(statements, node); if (moduleKind !== ts.ModuleKind.System || currentScope !== currentSourceFile) { @@ -36501,15 +37922,17 @@ var ts; } var moduleStatement = ts.createStatement(ts.createCall(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(parameterName)], undefined, transformModuleBody(node, containerName)), undefined, [moduleArg]), node); ts.setOriginalNode(moduleStatement, node); - setNodeEmitFlags(moduleStatement, emitFlags); + ts.setEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); return statements; } function transformModuleBody(node, namespaceLocalName) { var savedCurrentNamespaceContainerName = currentNamespaceContainerName; var savedCurrentNamespace = currentNamespace; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; currentNamespaceContainerName = namespaceLocalName; currentNamespace = node; + currentScopeFirstDeclarationsOfName = undefined; var statements = []; startLexicalEnvironment(); var statementsLocation; @@ -36536,9 +37959,10 @@ var ts; ts.addRange(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), blockLocation, true); if (body.kind !== 226) { - setNodeEmitFlags(block, block.emitFlags | 49152); + ts.setEmitFlags(block, ts.getEmitFlags(block) | 49152); } return block; } @@ -36561,7 +37985,7 @@ var ts; return undefined; } var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); - setNodeEmitFlags(moduleReference, 49152 | 65536); + ts.setEmitFlags(moduleReference, 49152 | 65536); if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { return ts.setOriginalNode(ts.createVariableStatement(ts.visitNodes(node.modifiers, visitor, ts.isModifier), ts.createVariableDeclarationList([ ts.createVariableDeclaration(node.name, undefined, moduleReference) @@ -36590,9 +38014,9 @@ var ts; } function addExportMemberAssignment(statements, node) { var expression = ts.createAssignment(getExportName(node), getLocalName(node, true)); - setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + ts.setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); var statement = ts.createStatement(expression); - setSourceMapRange(statement, ts.createRange(-1, node.end)); + ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); } function createNamespaceExport(exportName, exportValue, location) { @@ -36613,7 +38037,7 @@ var ts; emitFlags |= 1536; } if (emitFlags) { - setNodeEmitFlags(qualifiedName, emitFlags); + ts.setEmitFlags(qualifiedName, emitFlags); } return qualifiedName; } @@ -36622,7 +38046,7 @@ var ts; } function getNamespaceParameterName(node) { var name = ts.getGeneratedNameForNode(node); - setSourceMapRange(name, node.name); + ts.setSourceMapRange(name, node.name); return name; } function getNamespaceContainerName(node) { @@ -36639,8 +38063,8 @@ var ts; } function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { if (node.name) { - var name_30 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); + var name_32 = ts.getMutableClone(node.name); + emitFlags |= ts.getEmitFlags(node.name); if (!allowSourceMaps) { emitFlags |= 1536; } @@ -36648,9 +38072,9 @@ var ts; emitFlags |= 49152; } if (emitFlags) { - setNodeEmitFlags(name_30, emitFlags); + ts.setEmitFlags(name_32, emitFlags); } - return name_30; + return name_32; } else { return ts.getGeneratedNameForNode(node); @@ -36712,7 +38136,7 @@ var ts; function isTransformedEnumDeclaration(node) { return ts.getOriginalNode(node).kind === 224; } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedApplicableSubstitutions = applicableSubstitutions; var savedCurrentSuperContainer = currentSuperContainer; if (enabledSubstitutions & 4 && isSuperContainer(node)) { @@ -36724,13 +38148,13 @@ var ts; if (enabledSubstitutions & 8 && isTransformedEnumDeclaration(node)) { applicableSubstitutions |= 8; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); applicableSubstitutions = savedApplicableSubstitutions; currentSuperContainer = savedCurrentSuperContainer; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -36740,14 +38164,14 @@ var ts; } function substituteShorthandPropertyAssignment(node) { if (enabledSubstitutions & 2) { - var name_31 = node.name; - var exportedName = trySubstituteNamespaceExportedName(name_31); + var name_33 = node.name; + var exportedName = trySubstituteNamespaceExportedName(name_33); if (exportedName) { if (node.objectAssignmentInitializer) { var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); - return ts.createPropertyAssignment(name_31, initializer, node); + return ts.createPropertyAssignment(name_33, initializer, node); } - return ts.createPropertyAssignment(name_31, exportedName, node); + return ts.createPropertyAssignment(name_33, exportedName, node); } } return node; @@ -36756,16 +38180,15 @@ var ts; switch (node.kind) { case 69: return substituteExpressionIdentifier(node); - } - if (enabledSubstitutions & 4) { - switch (node.kind) { - case 174: + case 172: + return substitutePropertyAccessExpression(node); + case 173: + return substituteElementAccessExpression(node); + case 174: + if (enabledSubstitutions & 4) { return substituteCallExpression(node); - case 172: - return substitutePropertyAccessExpression(node); - case 173: - return substituteElementAccessExpression(node); - } + } + break; } return node; } @@ -36782,8 +38205,8 @@ var ts; var classAlias = classAliases[declaration.id]; if (classAlias) { var clone_4 = ts.getSynthesizedClone(classAlias); - setSourceMapRange(clone_4, node); - setCommentRange(clone_4, node); + ts.setSourceMapRange(clone_4, node); + ts.setCommentRange(clone_4, node); return clone_4; } } @@ -36792,7 +38215,7 @@ var ts; return undefined; } function trySubstituteNamespaceExportedName(node) { - if (enabledSubstitutions & applicableSubstitutions && (getNodeEmitFlags(node) & 262144) === 0) { + if (enabledSubstitutions & applicableSubstitutions && (ts.getEmitFlags(node) & 262144) === 0) { var container = resolver.getReferencedExportContainer(node, false); if (container) { var substitute = (applicableSubstitutions & 2 && container.kind === 225) || @@ -36820,23 +38243,48 @@ var ts; return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 95) { + if (enabledSubstitutions & 4 && node.expression.kind === 95) { var flags = getSuperContainerAsyncMethodFlags(); if (flags) { return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); } } - return node; + return substituteConstantValue(node); } function substituteElementAccessExpression(node) { - if (node.expression.kind === 95) { + if (enabledSubstitutions & 4 && node.expression.kind === 95) { var flags = getSuperContainerAsyncMethodFlags(); if (flags) { return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); } } + return substituteConstantValue(node); + } + function substituteConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + var substitute = ts.createLiteral(constantValue); + ts.setSourceMapRange(substitute, node); + ts.setCommentRange(substitute, node); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : ts.getTextOfNode(node.argumentExpression); + substitute.trailingComment = " " + propertyName + " "; + } + ts.setConstantValue(node, constantValue); + return substitute; + } return node; } + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; + } + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) + ? resolver.getConstantValue(node) + : undefined; + } function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { if (flags & 4096) { return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), undefined, [argumentExpression]), "value", location); @@ -36860,6 +38308,9 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; node = ts.visitEachChild(node, visitor, context); currentSourceFile = undefined; @@ -37018,12 +38469,12 @@ var ts; return getTagName(node.openingElement); } else { - var name_32 = node.tagName; - if (ts.isIdentifier(name_32) && ts.isIntrinsicJsxName(name_32.text)) { - return ts.createLiteral(name_32.text); + var name_34 = node.tagName; + if (ts.isIdentifier(name_34) && ts.isIntrinsicJsxName(name_34.text)) { + return ts.createLiteral(name_34.text); } else { - return ts.createExpressionFromEntityName(name_32); + return ts.createExpressionFromEntityName(name_34); } } } @@ -37305,6 +38756,9 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitEachChild(node, visitor, context); } function visitor(node) { @@ -37364,7 +38818,7 @@ var ts; var ts; (function (ts) { function transformES6(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, getCommentRange = context.getCommentRange, setCommentRange = context.setCommentRange, getSourceMapRange = context.getSourceMapRange, setSourceMapRange = context.setSourceMapRange, setTokenSourceMapRange = context.setTokenSourceMapRange; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var previousOnSubstituteNode = context.onSubstituteNode; var previousOnEmitNode = context.onEmitNode; @@ -37384,6 +38838,9 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; currentText = node.text; return ts.visitNode(node, visitor, ts.isSourceFile); @@ -37553,7 +39010,7 @@ var ts; enclosingFunction = currentNode; if (currentNode.kind !== 180) { enclosingNonArrowFunction = currentNode; - if (!(currentNode.emitFlags & 2097152)) { + if (!(ts.getEmitFlags(currentNode) & 2097152)) { enclosingNonAsyncFunctionBody = currentNode; } } @@ -37690,15 +39147,15 @@ var ts; } var extendsClauseElement = ts.getClassExtendsHeritageClauseElement(node); var classFunction = ts.createFunctionExpression(undefined, undefined, undefined, extendsClauseElement ? [ts.createParameter("_super")] : [], undefined, transformClassBody(node, extendsClauseElement)); - if (getNodeEmitFlags(node) & 524288) { - setNodeEmitFlags(classFunction, 524288); + if (ts.getEmitFlags(node) & 524288) { + ts.setEmitFlags(classFunction, 524288); } var inner = ts.createPartiallyEmittedExpression(classFunction); inner.end = node.end; - setNodeEmitFlags(inner, 49152); + ts.setEmitFlags(inner, 49152); var outer = ts.createPartiallyEmittedExpression(inner); outer.end = ts.skipTrivia(currentText, node.pos); - setNodeEmitFlags(outer, 49152); + ts.setEmitFlags(outer, 49152); return ts.createParen(ts.createCall(outer, undefined, extendsClauseElement ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] : [])); @@ -37713,14 +39170,14 @@ var ts; var localName = getLocalName(node); var outer = ts.createPartiallyEmittedExpression(localName); outer.end = closingBraceLocation.end; - setNodeEmitFlags(outer, 49152); + ts.setEmitFlags(outer, 49152); var statement = ts.createReturn(outer); statement.pos = closingBraceLocation.pos; - setNodeEmitFlags(statement, 49152 | 12288); + ts.setEmitFlags(statement, 49152 | 12288); statements.push(statement); ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, node.members), undefined, true); - setNodeEmitFlags(block, 49152); + ts.setEmitFlags(block, 49152); return block; } function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { @@ -37731,7 +39188,11 @@ var ts; function addConstructor(statements, node, extendsClauseElement) { var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); - statements.push(ts.createFunctionDeclaration(undefined, undefined, undefined, getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), constructor || node)); + var constructorFunction = ts.createFunctionDeclaration(undefined, undefined, undefined, getDeclarationName(node), undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), constructor || node); + if (extendsClauseElement) { + ts.setEmitFlags(constructorFunction, 256); + } + statements.push(constructorFunction); } function transformConstructorParameters(constructor, hasSynthesizedSuper) { if (constructor && !hasSynthesizedSuper) { @@ -37742,33 +39203,98 @@ var ts; function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { var statements = []; startLexicalEnvironment(); + var statementOffset = -1; + if (hasSynthesizedSuper) { + statementOffset = 1; + } + else if (constructor) { + statementOffset = ts.addPrologueDirectives(statements, constructor.body.statements, false, visitor); + } if (constructor) { - addCaptureThisForNodeIfNeeded(statements, constructor); addDefaultValueAssignmentsIfNeeded(statements, constructor); addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); + } + var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, !!extendsClauseElement, hasSynthesizedSuper, statementOffset); + if (superCaptureStatus === 1 || superCaptureStatus === 2) { + statementOffset++; } - addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper); if (constructor) { - var body = saveStateAndInvoke(constructor, hasSynthesizedSuper ? transformConstructorBodyWithSynthesizedSuper : transformConstructorBodyWithoutSynthesizedSuper); + var body = saveStateAndInvoke(constructor, function (constructor) { return ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, statementOffset); }); ts.addRange(statements, body); } + if (extendsClauseElement + && superCaptureStatus !== 2 + && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { + statements.push(ts.createReturn(ts.createIdentifier("_this"))); + } ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, constructor ? constructor.body.statements : node.members), constructor ? constructor.body : node, true); if (!constructor) { - setNodeEmitFlags(block, 49152); + ts.setEmitFlags(block, 49152); } return block; } - function transformConstructorBodyWithSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 1); - } - function transformConstructorBodyWithoutSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 0); - } - function addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper) { - if (constructor ? hasSynthesizedSuper : extendsClauseElement) { - statements.push(ts.createStatement(ts.createFunctionApply(ts.createIdentifier("_super"), ts.createThis(), ts.createIdentifier("arguments")), extendsClauseElement)); + function isSufficientlyCoveredByReturnStatements(statement) { + if (statement.kind === 211) { + return true; } + else if (statement.kind === 203) { + var ifStatement = statement; + if (ifStatement.elseStatement) { + return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && + isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); + } + } + else if (statement.kind === 199) { + var lastStatement = ts.lastOrUndefined(statement.statements); + if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { + return true; + } + } + return false; + } + function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, hasExtendsClause, hasSynthesizedSuper, statementOffset) { + if (!hasExtendsClause) { + if (ctor) { + addCaptureThisForNodeIfNeeded(statements, ctor); + } + return 0; + } + if (!ctor) { + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + return 2; + } + if (hasSynthesizedSuper) { + captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); + enableSubstitutionsForCapturedThis(); + return 1; + } + var firstStatement; + var superCallExpression; + var ctorStatements = ctor.body.statements; + if (statementOffset < ctorStatements.length) { + firstStatement = ctorStatements[statementOffset]; + if (firstStatement.kind === 202 && ts.isSuperCall(firstStatement.expression)) { + var superCall = firstStatement.expression; + superCallExpression = ts.setOriginalNode(saveStateAndInvoke(superCall, visitImmediateSuperCallInBody), superCall); + } + } + if (superCallExpression && statementOffset === ctorStatements.length - 1) { + statements.push(ts.createReturn(superCallExpression)); + return 2; + } + captureThisForNode(statements, ctor, superCallExpression, firstStatement); + if (superCallExpression) { + return 1; + } + return 0; + } + function createDefaultSuperCallOrThis() { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 128); + var superCall = ts.createFunctionApply(ts.createIdentifier("_super"), actualThis, ts.createIdentifier("arguments")); + return ts.createLogicalOr(superCall, actualThis); } function visitParameter(node) { if (node.dotDotDotToken) { @@ -37793,34 +39319,34 @@ var ts; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - var name_33 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + var name_35 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; if (dotDotDotToken) { continue; } - if (ts.isBindingPattern(name_33)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name_33, initializer); + if (ts.isBindingPattern(name_35)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name_35, initializer); } else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name_33, initializer); + addDefaultValueAssignmentForInitializer(statements, parameter, name_35, initializer); } } } function addDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) { var temp = ts.getGeneratedNameForNode(parameter); if (name.elements.length > 0) { - statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608)); + statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608)); } else if (initializer) { - statements.push(setNodeEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608)); + statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608)); } } function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); - var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), setNodeEmitFlags(ts.createBlock([ - ts.createStatement(ts.createAssignment(setNodeEmitFlags(ts.getMutableClone(name), 1536), setNodeEmitFlags(initializer, 1536 | getNodeEmitFlags(initializer)), parameter)) + var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), ts.setEmitFlags(ts.createBlock([ + ts.createStatement(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 1536), ts.setEmitFlags(initializer, 1536 | ts.getEmitFlags(initializer)), parameter)) ], parameter), 32 | 1024 | 12288), undefined, parameter); statement.startsOnNewLine = true; - setNodeEmitFlags(statement, 12288 | 1024 | 8388608); + ts.setEmitFlags(statement, 12288 | 1024 | 8388608); statements.push(statement); } function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) { @@ -37832,11 +39358,11 @@ var ts; return; } var declarationName = ts.getMutableClone(parameter.name); - setNodeEmitFlags(declarationName, 1536); + ts.setEmitFlags(declarationName, 1536); var expressionName = ts.getSynthesizedClone(parameter.name); var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); - statements.push(setNodeEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + statements.push(ts.setEmitFlags(ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(declarationName, undefined, ts.createArrayLiteral([])) ]), parameter), 8388608)); var forStatement = ts.createFor(ts.createVariableDeclarationList([ @@ -37844,21 +39370,24 @@ var ts; ], parameter), ts.createLessThan(temp, ts.createPropertyAccess(ts.createIdentifier("arguments"), "length"), parameter), ts.createPostfixIncrement(temp, parameter), ts.createBlock([ ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), parameter)) ])); - setNodeEmitFlags(forStatement, 8388608); + ts.setEmitFlags(forStatement, 8388608); ts.startOnNewLine(forStatement); statements.push(forStatement); } function addCaptureThisForNodeIfNeeded(statements, node) { if (node.transformFlags & 16384 && node.kind !== 180) { - enableSubstitutionsForCapturedThis(); - var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("_this", undefined, ts.createThis()) - ])); - setNodeEmitFlags(captureThisStatement, 49152 | 8388608); - setSourceMapRange(captureThisStatement, node); - statements.push(captureThisStatement); + captureThisForNode(statements, node, ts.createThis()); } } + function captureThisForNode(statements, node, initializer, originalStatement) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("_this", undefined, initializer) + ]), originalStatement); + ts.setEmitFlags(captureThisStatement, 49152 | 8388608); + ts.setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } function addClassMembers(statements, node) { for (var _i = 0, _a = node.members; _i < _a.length; _i++) { var member = _a[_i]; @@ -37888,43 +39417,43 @@ var ts; return ts.createEmptyStatement(member); } function transformClassMethodDeclarationToStatement(receiver, member) { - var commentRange = getCommentRange(member); - var sourceMapRange = getSourceMapRange(member); + var commentRange = ts.getCommentRange(member); + var sourceMapRange = ts.getSourceMapRange(member); var func = transformFunctionLikeToExpression(member, member, undefined); - setNodeEmitFlags(func, 49152); - setSourceMapRange(func, sourceMapRange); + ts.setEmitFlags(func, 49152); + ts.setSourceMapRange(func, sourceMapRange); var statement = ts.createStatement(ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), member.name), func), member); ts.setOriginalNode(statement, member); - setCommentRange(statement, commentRange); - setNodeEmitFlags(statement, 1536); + ts.setCommentRange(statement, commentRange); + ts.setEmitFlags(statement, 1536); return statement; } function transformAccessorsToStatement(receiver, accessors) { - var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, false), getSourceMapRange(accessors.firstAccessor)); - setNodeEmitFlags(statement, 49152); + var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, false), ts.getSourceMapRange(accessors.firstAccessor)); + ts.setEmitFlags(statement, 49152); return statement; } function transformAccessorsToExpression(receiver, _a, startsOnNewLine) { var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor; var target = ts.getMutableClone(receiver); - setNodeEmitFlags(target, 49152 | 1024); - setSourceMapRange(target, firstAccessor.name); + ts.setEmitFlags(target, 49152 | 1024); + ts.setSourceMapRange(target, firstAccessor.name); var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); - setNodeEmitFlags(propertyName, 49152 | 512); - setSourceMapRange(propertyName, firstAccessor.name); + ts.setEmitFlags(propertyName, 49152 | 512); + ts.setSourceMapRange(propertyName, firstAccessor.name); var properties = []; if (getAccessor) { var getterFunction = transformFunctionLikeToExpression(getAccessor, undefined, undefined); - setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); + ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor)); var getter = ts.createPropertyAssignment("get", getterFunction); - setCommentRange(getter, getCommentRange(getAccessor)); + ts.setCommentRange(getter, ts.getCommentRange(getAccessor)); properties.push(getter); } if (setAccessor) { var setterFunction = transformFunctionLikeToExpression(setAccessor, undefined, undefined); - setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); + ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor)); var setter = ts.createPropertyAssignment("set", setterFunction); - setCommentRange(setter, getCommentRange(setAccessor)); + ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); properties.push(setter); } properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); @@ -37943,7 +39472,7 @@ var ts; enableSubstitutionsForCapturedThis(); } var func = transformFunctionLikeToExpression(node, node, undefined); - setNodeEmitFlags(func, 256); + ts.setEmitFlags(func, 256); return func; } function visitFunctionExpression(node) { @@ -38000,7 +39529,7 @@ var ts; } var expression = ts.visitNode(body, visitor, ts.isExpression); var returnStatement = ts.createReturn(expression, body); - setNodeEmitFlags(returnStatement, 12288 | 1024 | 32768); + ts.setEmitFlags(returnStatement, 12288 | 1024 | 32768); statements.push(returnStatement); closeBraceLocation = body; } @@ -38011,10 +39540,10 @@ var ts; } var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); if (!multiLine && singleLine) { - setNodeEmitFlags(block, 32); + ts.setEmitFlags(block, 32); } if (closeBraceLocation) { - setTokenSourceMapRange(block, 16, closeBraceLocation); + ts.setTokenSourceMapRange(block, 16, closeBraceLocation); } ts.setOriginalNode(block, node.body); return block; @@ -38055,7 +39584,7 @@ var ts; assignment = ts.flattenVariableDestructuringToExpression(context, decl, hoistVariableDeclaration, undefined, visitor); } else { - assignment = ts.createBinary(decl.name, 56, decl.initializer); + assignment = ts.createBinary(decl.name, 56, ts.visitNode(decl.initializer, visitor, ts.isExpression)); } (assignments || (assignments = [])).push(assignment); } @@ -38078,13 +39607,13 @@ var ts; : visitVariableDeclaration)); var declarationList = ts.createVariableDeclarationList(declarations, node); ts.setOriginalNode(declarationList, node); - setCommentRange(declarationList, node); + ts.setCommentRange(declarationList, node); if (node.transformFlags & 2097152 && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { var firstDeclaration = ts.firstOrUndefined(declarations); var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); } return declarationList; } @@ -38179,7 +39708,7 @@ var ts; ts.setOriginalNode(declarationList, initializer); var firstDeclaration = declarations[0]; var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); statements.push(ts.createVariableStatement(undefined, declarationList)); } else { @@ -38214,14 +39743,14 @@ var ts; statements.push(statement); } } - setNodeEmitFlags(expression, 1536 | getNodeEmitFlags(expression)); + ts.setEmitFlags(expression, 1536 | ts.getEmitFlags(expression)); var body = ts.createBlock(ts.createNodeArray(statements, statementsLocation), bodyLocation); - setNodeEmitFlags(body, 1536 | 12288); + ts.setEmitFlags(body, 1536 | 12288); var forStatement = ts.createFor(ts.createVariableDeclarationList([ ts.createVariableDeclaration(counter, undefined, ts.createLiteral(0), ts.moveRangePos(node.expression, -1)), ts.createVariableDeclaration(rhsReference, undefined, expression, node.expression) ], node.expression), ts.createLessThan(counter, ts.createPropertyAccess(rhsReference, "length"), node.expression), ts.createPostfixIncrement(counter, node.expression), body, node); - setNodeEmitFlags(forStatement, 8192); + ts.setEmitFlags(forStatement, 8192); return forStatement; } function visitObjectLiteralExpression(node) { @@ -38239,7 +39768,7 @@ var ts; ts.Debug.assert(numInitialProperties !== numProperties); var temp = ts.createTempVariable(hoistVariableDeclaration); var expressions = []; - var assignment = ts.createAssignment(temp, setNodeEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, node.multiLine), 524288)); + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), undefined, node.multiLine), 524288)); if (node.multiLine) { assignment.startsOnNewLine = true; } @@ -38328,7 +39857,7 @@ var ts; loopBody = ts.createBlock([loopBody], undefined, true); } var isAsyncBlockContainingAwait = enclosingNonArrowFunction - && (enclosingNonArrowFunction.emitFlags & 2097152) !== 0 + && (ts.getEmitFlags(enclosingNonArrowFunction) & 2097152) !== 0 && (node.statement.transformFlags & 4194304) !== 0; var loopBodyFlags = 0; if (currentState.containsLexicalThis) { @@ -38338,7 +39867,7 @@ var ts; loopBodyFlags |= 2097152; } var convertedLoopVariable = ts.createVariableStatement(undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration(functionName, undefined, setNodeEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) + ts.createVariableDeclaration(functionName, undefined, ts.setEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37) : undefined, undefined, undefined, loopParameters, undefined, loopBody), loopBodyFlags)) ])); var statements = [convertedLoopVariable]; var extraVariableDeclarations; @@ -38366,8 +39895,8 @@ var ts; if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var name_34 in currentState.hoistedLocalVariables) { - var identifier = currentState.hoistedLocalVariables[name_34]; + for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { + var identifier = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } @@ -38376,8 +39905,8 @@ var ts; if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _b = 0, loopOutParameters_1 = loopOutParameters; _b < loopOutParameters_1.length; _b++) { - var outParam = loopOutParameters_1[_b]; + for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { + var outParam = loopOutParameters_1[_d]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } @@ -38555,7 +40084,7 @@ var ts; function visitMethodDeclaration(node) { ts.Debug.assert(!ts.isComputedPropertyName(node.name)); var functionExpression = transformFunctionLikeToExpression(node, ts.moveRangePos(node, -1), undefined); - setNodeEmitFlags(functionExpression, 16384 | getNodeEmitFlags(functionExpression)); + ts.setEmitFlags(functionExpression, 16384 | ts.getEmitFlags(functionExpression)); return ts.createPropertyAssignment(node.name, functionExpression, node); } function visitShorthandPropertyAssignment(node) { @@ -38568,13 +40097,32 @@ var ts; return transformAndSpreadElements(node.elements, true, node.multiLine, node.elements.hasTrailingComma); } function visitCallExpression(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, true); + } + function visitImmediateSuperCallInBody(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, false); + } + function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 95) { + ts.setEmitFlags(thisArg, 128); + } + var resultingCall; if (node.transformFlags & 262144) { - return ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); + resultingCall = ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, false, false, false)); } else { - return ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); + resultingCall = ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), node); } + if (node.expression.kind === 95) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 128); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + return assignToCapturedThis + ? ts.createAssignment(ts.createIdentifier("_this"), initializer) + : initializer; + } + return resultingCall; } function visitNewExpression(node) { ts.Debug.assert((node.transformFlags & 262144) !== 0); @@ -38694,12 +40242,12 @@ var ts; clone.statements = ts.createNodeArray(statements, node.statements); return clone; } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedEnclosingFunction = enclosingFunction; if (enabledSubstitutions & 1 && ts.isFunctionLike(node)) { enclosingFunction = node; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); enclosingFunction = savedEnclosingFunction; } function enableSubstitutionsForBlockScopedBindings() { @@ -38721,9 +40269,9 @@ var ts; context.enableEmitNotification(220); } } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } if (ts.isIdentifier(node)) { @@ -38773,7 +40321,7 @@ var ts; function substituteThisKeyword(node) { if (enabledSubstitutions & 1 && enclosingFunction - && enclosingFunction.emitFlags & 256) { + && ts.getEmitFlags(enclosingFunction) & 256) { return ts.createIdentifier("_this", node); } return node; @@ -38783,8 +40331,8 @@ var ts; } function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { if (node.name && !ts.isGeneratedIdentifier(node.name)) { - var name_35 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); + var name_36 = ts.getMutableClone(node.name); + emitFlags |= ts.getEmitFlags(node.name); if (!allowSourceMaps) { emitFlags |= 1536; } @@ -38792,9 +40340,9 @@ var ts; emitFlags |= 49152; } if (emitFlags) { - setNodeEmitFlags(name_35, emitFlags); + ts.setEmitFlags(name_36, emitFlags); } - return name_35; + return name_36; } return ts.getGeneratedNameForNode(node); } @@ -38842,7 +40390,7 @@ var ts; _a[7] = "endfinally", _a)); function transformGenerators(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration, setSourceMapRange = context.setSourceMapRange, setCommentRange = context.setCommentRange, setNodeEmitFlags = context.setNodeEmitFlags; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var resolver = context.getEmitResolver(); @@ -38876,6 +40424,9 @@ var ts; var withBlockStack; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (node.transformFlags & 1024) { currentSourceFile = node; node = ts.visitEachChild(node, visitor, context); @@ -38982,7 +40533,7 @@ var ts; } } function visitFunctionDeclaration(node) { - if (node.asteriskToken && node.emitFlags & 2097152) { + if (node.asteriskToken && ts.getEmitFlags(node) & 2097152) { node = ts.setOriginalNode(ts.createFunctionDeclaration(undefined, undefined, undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); } else { @@ -39003,7 +40554,7 @@ var ts; } } function visitFunctionExpression(node) { - if (node.asteriskToken && node.emitFlags & 2097152) { + if (node.asteriskToken && ts.getEmitFlags(node) & 2097152) { node = ts.setOriginalNode(ts.createFunctionExpression(undefined, node.name, undefined, node.parameters, undefined, transformGeneratorFunctionBody(node.body), node), node); } else { @@ -39034,6 +40585,7 @@ var ts; var savedBlocks = blocks; var savedBlockOffsets = blockOffsets; var savedBlockActions = blockActions; + var savedBlockStack = blockStack; var savedLabelOffsets = labelOffsets; var savedLabelExpressions = labelExpressions; var savedNextLabelId = nextLabelId; @@ -39046,6 +40598,7 @@ var ts; blocks = undefined; blockOffsets = undefined; blockActions = undefined; + blockStack = undefined; labelOffsets = undefined; labelExpressions = undefined; nextLabelId = 1; @@ -39064,6 +40617,7 @@ var ts; blocks = savedBlocks; blockOffsets = savedBlockOffsets; blockActions = savedBlockActions; + blockStack = savedBlockStack; labelOffsets = savedLabelOffsets; labelExpressions = savedLabelExpressions; nextLabelId = savedNextLabelId; @@ -39079,7 +40633,7 @@ var ts; return undefined; } else { - if (node.emitFlags & 8388608) { + if (ts.getEmitFlags(node) & 8388608) { return node; } for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { @@ -39747,9 +41301,9 @@ var ts; } return -1; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } return node; @@ -39766,11 +41320,11 @@ var ts; if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { - var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); - if (name_36) { - var clone_8 = ts.getMutableClone(name_36); - setSourceMapRange(clone_8, node); - setCommentRange(clone_8, node); + var name_37 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); + if (name_37) { + var clone_8 = ts.getMutableClone(name_37); + ts.setSourceMapRange(clone_8, node); + ts.setCommentRange(clone_8, node); return clone_8; } } @@ -40164,7 +41718,7 @@ var ts; var buildResult = buildStatements(); return ts.createCall(ts.createHelperName(currentSourceFile.externalHelpersModuleName, "__generator"), undefined, [ ts.createThis(), - setNodeEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(state)], undefined, ts.createBlock(buildResult, undefined, buildResult.length > 0)), 4194304) + ts.setEmitFlags(ts.createFunctionExpression(undefined, undefined, undefined, [ts.createParameter(state)], undefined, ts.createBlock(buildResult, undefined, buildResult.length > 0)), 4194304) ]); } function buildStatements() { @@ -40439,7 +41993,7 @@ var ts; _a[ts.ModuleKind.AMD] = transformAMDModule, _a[ts.ModuleKind.UMD] = transformUMDModule, _a)); - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, setNodeEmitFlags = context.setNodeEmitFlags, getNodeEmitFlags = context.getNodeEmitFlags, setSourceMapRange = context.setSourceMapRange; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -40464,6 +42018,9 @@ var ts; var hasExportStarsToExportValues; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; (_a = ts.collectExternalModuleInfo(node, resolver), externalImports = _a.externalImports, exportSpecifiers = _a.exportSpecifiers, exportEquals = _a.exportEquals, hasExportStarsToExportValues = _a.hasExportStarsToExportValues, _a); @@ -40489,7 +42046,7 @@ var ts; addExportEqualsIfNeeded(statements, false); var updated = updateSourceFile(node, statements); if (hasExportStarsToExportValues) { - setNodeEmitFlags(updated, 2 | getNodeEmitFlags(node)); + ts.setEmitFlags(updated, 2 | ts.getEmitFlags(node)); } return updated; } @@ -40500,7 +42057,7 @@ var ts; } function transformUMDModule(node) { var define = ts.createIdentifier("define"); - setNodeEmitFlags(define, 16); + ts.setEmitFlags(define, 16); return transformAsynchronousModule(node, define, undefined, false); } function transformAsynchronousModule(node, define, moduleName, includeNonAmdDependencies) { @@ -40527,7 +42084,7 @@ var ts; addExportEqualsIfNeeded(statements, true); var body = ts.createBlock(statements, undefined, true); if (hasExportStarsToExportValues) { - setNodeEmitFlags(body, 2); + ts.setEmitFlags(body, 2); } return body; } @@ -40535,12 +42092,12 @@ var ts; if (exportEquals && resolver.isValueAliasDeclaration(exportEquals)) { if (emitAsReturn) { var statement = ts.createReturn(exportEquals.expression, exportEquals); - setNodeEmitFlags(statement, 12288 | 49152); + ts.setEmitFlags(statement, 12288 | 49152); statements.push(statement); } else { var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), exportEquals.expression), exportEquals); - setNodeEmitFlags(statement, 49152); + ts.setEmitFlags(statement, 49152); statements.push(statement); } } @@ -40603,7 +42160,7 @@ var ts; if (!ts.contains(externalImports, node)) { return undefined; } - setNodeEmitFlags(node.name, 128); + ts.setEmitFlags(node.name, 128); var statements = []; if (moduleKind !== ts.ModuleKind.AMD) { if (ts.hasModifier(node, 1)) { @@ -40691,16 +42248,16 @@ var ts; else { var names = ts.reduceEachChild(node, collectExportMembers, []); for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_37 = names_1[_i]; - addExportMemberAssignments(statements, name_37); + var name_38 = names_1[_i]; + addExportMemberAssignments(statements, name_38); } } } function collectExportMembers(names, node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && ts.isDeclaration(node)) { - var name_38 = node.name; - if (ts.isIdentifier(name_38)) { - names.push(name_38); + var name_39 = node.name; + if (ts.isIdentifier(name_39)) { + names.push(name_39); } } return ts.reduceEachChild(node, collectExportMembers, names); @@ -40718,7 +42275,7 @@ var ts; addExportDefault(statements, getDeclarationName(node), node); } else { - statements.push(createExportStatement(node.name, setNodeEmitFlags(ts.getSynthesizedClone(node.name), 262144), node)); + statements.push(createExportStatement(node.name, ts.setEmitFlags(ts.getSynthesizedClone(node.name), 262144), node)); } } function visitVariableStatement(node) { @@ -40835,25 +42392,25 @@ var ts; } function addVarForExportedEnumOrNamespaceDeclaration(statements, node) { var transformedStatement = ts.createVariableStatement(undefined, [ts.createVariableDeclaration(getDeclarationName(node), undefined, ts.createPropertyAccess(ts.createIdentifier("exports"), getDeclarationName(node)))], node); - setNodeEmitFlags(transformedStatement, 49152); + ts.setEmitFlags(transformedStatement, 49152); statements.push(transformedStatement); } function getDeclarationName(node) { return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { if (node.kind === 256) { bindingNameExportSpecifiersMap = bindingNameExportSpecifiersForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); bindingNameExportSpecifiersMap = undefined; } else { - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); } } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -40894,7 +42451,7 @@ var ts; var left = node.left; if (ts.isIdentifier(left) && ts.isAssignmentOperator(node.operatorToken.kind)) { if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, left.text)) { - setNodeEmitFlags(node, 128); + ts.setEmitFlags(node, 128); var nestedExportAssignment = void 0; for (var _i = 0, _a = bindingNameExportSpecifiersMap[left.text]; _i < _a.length; _i++) { var specifier = _a[_i]; @@ -40912,11 +42469,11 @@ var ts; var operand = node.operand; if (ts.isIdentifier(operand) && bindingNameExportSpecifiersForFileMap) { if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, operand.text)) { - setNodeEmitFlags(node, 128); + ts.setEmitFlags(node, 128); var transformedUnaryExpression = void 0; if (node.kind === 186) { - transformedUnaryExpression = ts.createBinary(operand, ts.createNode(operator === 41 ? 57 : 58), ts.createLiteral(1), node); - setNodeEmitFlags(transformedUnaryExpression, 128); + transformedUnaryExpression = ts.createBinary(operand, ts.createToken(operator === 41 ? 57 : 58), ts.createLiteral(1), node); + ts.setEmitFlags(transformedUnaryExpression, 128); } var nestedExportAssignment = void 0; for (var _i = 0, _a = bindingNameExportSpecifiersMap[operand.text]; _i < _a.length; _i++) { @@ -40931,7 +42488,7 @@ var ts; return node; } function trySubstituteExportedName(node) { - var emitFlags = getNodeEmitFlags(node); + var emitFlags = ts.getEmitFlags(node); if ((emitFlags & 262144) === 0) { var container = resolver.getReferencedExportContainer(node, (emitFlags & 131072) !== 0); if (container) { @@ -40943,7 +42500,7 @@ var ts; return undefined; } function trySubstituteImportedName(node) { - if ((getNodeEmitFlags(node) & 262144) === 0) { + if ((ts.getEmitFlags(node) & 262144) === 0) { var declaration = resolver.getReferencedImportDeclaration(node); if (declaration) { if (ts.isImportClause(declaration)) { @@ -40955,12 +42512,12 @@ var ts; } } else if (ts.isImportSpecifier(declaration)) { - var name_39 = declaration.propertyName || declaration.name; - if (name_39.originalKeywordKind === 77 && languageVersion <= 0) { - return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_39.text), node); + var name_40 = declaration.propertyName || declaration.name; + if (name_40.originalKeywordKind === 77 && languageVersion <= 0) { + return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_40.text), node); } else { - return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_39), node); + return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_40), node); } } } @@ -40982,7 +42539,7 @@ var ts; var statement = ts.createStatement(createExportAssignment(name, value)); statement.startsOnNewLine = true; if (location) { - setSourceMapRange(statement, location); + ts.setSourceMapRange(statement, location); } return statement; } @@ -41010,7 +42567,7 @@ var ts; var externalModuleName = ts.getExternalModuleNameLiteral(importNode, currentSourceFile, host, resolver, compilerOptions); var importAliasName = ts.getLocalNameForExternalImport(importNode, currentSourceFile); if (includeNonAmdDependencies && importAliasName) { - setNodeEmitFlags(importAliasName, 128); + ts.setEmitFlags(importAliasName, 128); aliasedModuleNames.push(externalModuleName); importAliasNames.push(ts.createParameter(importAliasName)); } @@ -41032,7 +42589,7 @@ var ts; var ts; (function (ts) { function transformSystemModule(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -41061,6 +42618,9 @@ var ts; var currentNode; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; currentNode = node; @@ -41093,12 +42653,12 @@ var ts; var body = ts.createFunctionExpression(undefined, undefined, undefined, [ ts.createParameter(exportFunctionForFile), ts.createParameter(contextObjectForFile) - ], undefined, setNodeEmitFlags(ts.createBlock(statements, undefined, true), 1)); + ], undefined, ts.setEmitFlags(ts.createBlock(statements, undefined, true), 1)); return updateSourceFile(node, [ ts.createStatement(ts.createCall(ts.createPropertyAccess(ts.createIdentifier("System"), "register"), undefined, moduleName ? [moduleName, dependencies, body] : [dependencies, body])) - ], ~1 & getNodeEmitFlags(node)); + ], ~1 & ts.getEmitFlags(node)); var _a; } function addSystemModuleBody(statements, node, dependencyGroups) { @@ -41342,11 +42902,11 @@ var ts; } function visitFunctionDeclaration(node) { if (ts.hasModifier(node, 1)) { - var name_40 = node.name || ts.getGeneratedNameForNode(node); - var newNode = ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name_40, undefined, node.parameters, undefined, node.body, node); + var name_41 = node.name || ts.getGeneratedNameForNode(node); + var newNode = ts.createFunctionDeclaration(undefined, undefined, node.asteriskToken, name_41, undefined, node.parameters, undefined, node.body, node); recordExportedFunctionDeclaration(node); if (!ts.hasModifier(node, 512)) { - recordExportName(name_40); + recordExportName(name_41); } ts.setOriginalNode(newNode, node); node = newNode; @@ -41357,13 +42917,13 @@ var ts; function visitExpressionStatement(node) { var originalNode = ts.getOriginalNode(node); if ((originalNode.kind === 225 || originalNode.kind === 224) && ts.hasModifier(originalNode, 1)) { - var name_41 = getDeclarationName(originalNode); + var name_42 = getDeclarationName(originalNode); if (originalNode.kind === 224) { - hoistVariableDeclaration(name_41); + hoistVariableDeclaration(name_42); } return [ node, - createExportStatement(name_41, name_41) + createExportStatement(name_42, name_42) ]; } return node; @@ -41517,19 +43077,19 @@ var ts; function visitBlock(node) { return ts.visitEachChild(node, visitNestedNode, context); } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { if (node.kind === 256) { exportFunctionForFile = exportFunctionForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); exportFunctionForFile = undefined; } else { - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); } } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1) { return substituteExpression(node); } return node; @@ -41563,7 +43123,7 @@ var ts; return node; } function substituteAssignmentExpression(node) { - setNodeEmitFlags(node, 128); + ts.setEmitFlags(node, 128); var left = node.left; switch (left.kind) { case 69: @@ -41668,7 +43228,7 @@ var ts; var exportDeclaration = resolver.getReferencedExportContainer(operand); if (exportDeclaration) { var expr = ts.createPrefix(node.operator, operand, node); - setNodeEmitFlags(expr, 128); + ts.setEmitFlags(expr, 128); var call = createExportExpression(operand, expr); if (node.kind === 185) { return call; @@ -41701,7 +43261,7 @@ var ts; ts.createForIn(ts.createVariableDeclarationList([ ts.createVariableDeclaration(n, undefined) ]), m, ts.createBlock([ - setNodeEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32) + ts.setEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32) ])), ts.createStatement(ts.createCall(exportFunctionForFile, undefined, [exports])) ], undefined, true))); @@ -41801,7 +43361,7 @@ var ts; function updateSourceFile(node, statements, nodeEmitFlags) { var updated = ts.getMutableClone(node); updated.statements = ts.createNodeArray(statements, node.statements); - setNodeEmitFlags(updated, nodeEmitFlags); + ts.setEmitFlags(updated, nodeEmitFlags); return updated; } } @@ -41815,6 +43375,9 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; return ts.visitEachChild(node, visitor, context); @@ -41951,18 +43514,10 @@ var ts; return transformers; } ts.getTransformers = getTransformers; - var nextTransformId = 1; function transformFiles(resolver, host, sourceFiles, transformers) { - var transformId = nextTransformId; - nextTransformId++; - var tokenSourceMapRanges = ts.createMap(); var lexicalEnvironmentVariableDeclarationsStack = []; var lexicalEnvironmentFunctionDeclarationsStack = []; var enabledSyntaxKindFeatures = new Array(289); - var parseTreeNodesWithAnnotations = []; - var lastTokenSourceMapRangeNode; - var lastTokenSourceMapRangeToken; - var lastTokenSourceMapRange; var lexicalEnvironmentStackOffset = 0; var hoistedVariableDeclarations; var hoistedFunctionDeclarations; @@ -41971,47 +43526,24 @@ var ts; getCompilerOptions: function () { return host.getCompilerOptions(); }, getEmitResolver: function () { return resolver; }, getEmitHost: function () { return host; }, - getNodeEmitFlags: getNodeEmitFlags, - setNodeEmitFlags: setNodeEmitFlags, - getSourceMapRange: getSourceMapRange, - setSourceMapRange: setSourceMapRange, - getTokenSourceMapRange: getTokenSourceMapRange, - setTokenSourceMapRange: setTokenSourceMapRange, - getCommentRange: getCommentRange, - setCommentRange: setCommentRange, hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, startLexicalEnvironment: startLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, - onSubstituteNode: onSubstituteNode, + onSubstituteNode: function (emitContext, node) { return node; }, enableSubstitution: enableSubstitution, isSubstitutionEnabled: isSubstitutionEnabled, - onEmitNode: onEmitNode, + onEmitNode: function (node, emitContext, emitCallback) { return emitCallback(node, emitContext); }, enableEmitNotification: enableEmitNotification, isEmitNotificationEnabled: isEmitNotificationEnabled }; - var transformation = chain.apply(void 0, transformers)(context); + var transformation = ts.chain.apply(void 0, transformers)(context); var transformed = ts.map(sourceFiles, transformSourceFile); lexicalEnvironmentDisabled = true; return { - getSourceFiles: function () { return transformed; }, - getTokenSourceMapRange: getTokenSourceMapRange, - isSubstitutionEnabled: isSubstitutionEnabled, - isEmitNotificationEnabled: isEmitNotificationEnabled, - onSubstituteNode: context.onSubstituteNode, - onEmitNode: context.onEmitNode, - dispose: function () { - for (var _i = 0, parseTreeNodesWithAnnotations_1 = parseTreeNodesWithAnnotations; _i < parseTreeNodesWithAnnotations_1.length; _i++) { - var node = parseTreeNodesWithAnnotations_1[_i]; - if (node.transformId === transformId) { - node.transformId = 0; - node.emitFlags = 0; - node.commentRange = undefined; - node.sourceMapRange = undefined; - } - } - parseTreeNodesWithAnnotations.length = 0; - } + transformed: transformed, + emitNodeWithSubstitution: emitNodeWithSubstitution, + emitNodeWithNotification: emitNodeWithNotification }; function transformSourceFile(sourceFile) { if (ts.isDeclarationFile(sourceFile)) { @@ -42023,75 +43555,37 @@ var ts; enabledSyntaxKindFeatures[kind] |= 1; } function isSubstitutionEnabled(node) { - return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0; + return (enabledSyntaxKindFeatures[node.kind] & 1) !== 0 + && (ts.getEmitFlags(node) & 128) === 0; } - function onSubstituteNode(node, isExpression) { - return node; + function emitNodeWithSubstitution(emitContext, node, emitCallback) { + if (node) { + if (isSubstitutionEnabled(node)) { + var substitute = context.onSubstituteNode(emitContext, node); + if (substitute && substitute !== node) { + emitCallback(emitContext, substitute); + return; + } + } + emitCallback(emitContext, node); + } } function enableEmitNotification(kind) { enabledSyntaxKindFeatures[kind] |= 2; } function isEmitNotificationEnabled(node) { return (enabledSyntaxKindFeatures[node.kind] & 2) !== 0 - || (getNodeEmitFlags(node) & 64) !== 0; + || (ts.getEmitFlags(node) & 64) !== 0; } - function onEmitNode(node, emit) { - emit(node); - } - function beforeSetAnnotation(node) { - if ((node.flags & 8) === 0 && node.transformId !== transformId) { - parseTreeNodesWithAnnotations.push(node); - node.transformId = transformId; - } - } - function getNodeEmitFlags(node) { - return node.emitFlags; - } - function setNodeEmitFlags(node, emitFlags) { - beforeSetAnnotation(node); - node.emitFlags = emitFlags; - return node; - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - function setSourceMapRange(node, range) { - beforeSetAnnotation(node); - node.sourceMapRange = range; - return node; - } - function getTokenSourceMapRange(node, token) { - if (lastTokenSourceMapRangeNode === node && lastTokenSourceMapRangeToken === token) { - return lastTokenSourceMapRange; - } - var range; - var current = node; - while (current) { - range = current.id ? tokenSourceMapRanges[current.id + "-" + token] : undefined; - if (range !== undefined) { - break; + function emitNodeWithNotification(emitContext, node, emitCallback) { + if (node) { + if (isEmitNotificationEnabled(node)) { + context.onEmitNode(emitContext, node, emitCallback); + } + else { + emitCallback(emitContext, node); } - current = current.original; } - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - return range; - } - function setTokenSourceMapRange(node, token, range) { - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - tokenSourceMapRanges[ts.getNodeId(node) + "-" + token] = range; - return node; - } - function getCommentRange(node) { - return node.commentRange || node; - } - function setCommentRange(node, range) { - beforeSetAnnotation(node); - node.commentRange = range; - return node; } function hoistVariableDeclaration(name) { ts.Debug.assert(!lexicalEnvironmentDisabled, "Cannot modify the lexical environment during the print phase."); @@ -42144,54 +43638,6 @@ var ts; } } ts.transformFiles = transformFiles; - function chain(a, b, c, d, e) { - if (e) { - var args_3 = []; - for (var i = 0; i < arguments.length; i++) { - args_3[i] = arguments[i]; - } - return function (t) { return compose.apply(void 0, ts.map(args_3, function (f) { return f(t); })); }; - } - else if (d) { - return function (t) { return compose(a(t), b(t), c(t), d(t)); }; - } - else if (c) { - return function (t) { return compose(a(t), b(t), c(t)); }; - } - else if (b) { - return function (t) { return compose(a(t), b(t)); }; - } - else if (a) { - return function (t) { return compose(a(t)); }; - } - else { - return function (t) { return function (u) { return u; }; }; - } - } - function compose(a, b, c, d, e) { - if (e) { - var args_4 = []; - for (var i = 0; i < arguments.length; i++) { - args_4[i] = arguments[i]; - } - return function (t) { return ts.reduceLeft(args_4, function (u, f) { return f(u); }, t); }; - } - else if (d) { - return function (t) { return d(c(b(a(t)))); }; - } - else if (c) { - return function (t) { return c(b(a(t))); }; - } - else if (b) { - return function (t) { return b(a(t)); }; - } - else if (a) { - return function (t) { return a(t); }; - } - else { - return function (t) { return t; }; - } - } var _a; })(ts || (ts = {})); var ts; @@ -42202,11 +43648,11 @@ var ts; return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, false); } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -42242,7 +43688,7 @@ var ts; ts.forEach(sourceFile.referencedFiles, function (fileReference) { var referencedFile = ts.tryResolveScriptReference(host, sourceFile, fileReference); if (referencedFile && !ts.contains(emittedReferencedFiles, referencedFile)) { - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { addedGlobalFileReference = true; } emittedReferencedFiles.push(referencedFile); @@ -42427,7 +43873,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 | 1024, writer); errorNameNode = undefined; } } @@ -42439,7 +43885,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 | 1024, writer); errorNameNode = undefined; } } @@ -42612,9 +44058,9 @@ var ts; var count = 0; while (true) { count++; - var name_42 = baseName + "_" + count; - if (!(name_42 in currentIdentifiers)) { - return name_42; + var name_43 = baseName + "_" + count; + if (!(name_43 in currentIdentifiers)) { + return name_43; } } } @@ -42632,7 +44078,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -43038,7 +44484,7 @@ var ts; } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); } function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; @@ -43606,14 +45052,14 @@ var ts; return emitSourceFile(node); } } - function writeReferencePath(referencedFile, addBundledFileReference) { + function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; if (ts.isDeclarationFile(referencedFile)) { declFileName = referencedFile.fileName; } else { - ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); } if (declFileName) { declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, false); @@ -43630,8 +45076,8 @@ var ts; } } } - function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencesOutput @@ -43657,41 +45103,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - if (compilerOptions.extendedDiagnostics) { - return createSourceMapWriterWithExtendedDiagnostics(host, writer); - } - return createSourceMapWriterWorker(host, writer); - } - else { - return getNullSourceMapWriter(); - } - } - ts.createSourceMapWriter = createSourceMapWriter; - var nullSourceMapWriter; - function getNullSourceMapWriter() { - if (nullSourceMapWriter === undefined) { - nullSourceMapWriter = { - initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, - reset: function () { }, - getSourceMapData: function () { return undefined; }, - setSourceFile: function (sourceFile) { }, - emitPos: function (pos) { }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitTokenStart: function (token, pos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - emitTokenEnd: function (token, end, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - changeEmitSourcePos: function () { }, - stopOverridingSpan: function () { }, - getText: function () { return undefined; }, - getSourceMappingURL: function () { return undefined; } - }; - } - return nullSourceMapWriter; - } - ts.getNullSourceMapWriter = getNullSourceMapWriter; var defaultLastEncodedSourceMapSpan = { emittedLine: 1, emittedColumn: 1, @@ -43699,42 +45110,38 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function createSourceMapWriterWorker(host, writer) { + function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var currentSourceText; var sourceMapDir; - var stopOverridingSpan = false; - var modifyLastSourcePos = false; var sourceMapSourceIndex; var lastRecordedSourceMapSpan; var lastEncodedSourceMapSpan; var lastEncodedNameIndex; var sourceMapData; - var disableDepth; + var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { initialize: initialize, reset: reset, getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, - emitStart: emitStart, - emitEnd: emitEnd, - emitTokenStart: emitTokenStart, - emitTokenEnd: emitTokenEnd, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: function () { return stopOverridingSpan = true; }, + emitNodeWithSourceMap: emitNodeWithSourceMap, + emitTokenWithSourceMap: emitTokenWithSourceMap, getText: getText, getSourceMappingURL: getSourceMappingURL }; function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (disabled) { + return; + } if (sourceMapData) { reset(); } currentSourceFile = undefined; currentSourceText = undefined; - disableDepth = 0; sourceMapSourceIndex = -1; lastRecordedSourceMapSpan = undefined; lastEncodedSourceMapSpan = defaultLastEncodedSourceMapSpan; @@ -43774,6 +45181,9 @@ var ts; } } function reset() { + if (disabled) { + return; + } currentSourceFile = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; @@ -43781,38 +45191,6 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; - disableDepth = 0; - } - function enable() { - if (disableDepth > 0) { - disableDepth--; - } - } - function disable() { - disableDepth++; - } - function updateLastEncodedAndRecordedSpans() { - if (modifyLastSourcePos) { - modifyLastSourcePos = false; - lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; - lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; - sourceMapData.sourceMapDecodedMappings.pop(); - lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? - sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : - defaultLastEncodedSourceMapSpan; - var sourceMapMappings = sourceMapData.sourceMapMappings; - var lenthToSet = sourceMapMappings.length - 1; - for (; lenthToSet >= 0; lenthToSet--) { - var currentChar = sourceMapMappings.charAt(lenthToSet); - if (currentChar === ",") { - break; - } - if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { - break; - } - } - sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); - } } function encodeLastRecordedSourceMapSpan() { if (!lastRecordedSourceMapSpan || lastRecordedSourceMapSpan === lastEncodedSourceMapSpan) { @@ -43843,7 +45221,7 @@ var ts; sourceMapData.sourceMapDecodedMappings.push(lastEncodedSourceMapSpan); } function emitPos(pos) { - if (ts.positionIsSynthesized(pos) || disableDepth > 0) { + if (disabled || ts.positionIsSynthesized(pos)) { return; } if (extendedDiagnostics) { @@ -43868,84 +45246,68 @@ var ts; sourceColumn: sourceLinePos.character, sourceIndex: sourceMapSourceIndex }; - stopOverridingSpan = false; } - else if (!stopOverridingSpan) { + else { lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } - updateLastEncodedAndRecordedSpans(); if (extendedDiagnostics) { ts.performance.mark("afterSourcemap"); ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); } } - function getStartPosPastDecorators(range) { - var rangeHasDecorators = !!range.decorators; - return ts.skipTrivia(currentSourceText, rangeHasDecorators ? range.decorators.end : range.pos); - } - function emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(getStartPosPastDecorators(range)); - } - if (ignoreChildrenCallback(contextNode)) { - disable(); - } + function emitNodeWithSourceMap(emitContext, node, emitCallback) { + if (disabled) { + return emitCallback(emitContext, node); } - else { - emitPos(getStartPosPastDecorators(range)); + if (node) { + var emitNode = node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var _a = emitNode && emitNode.sourceMapRange || node, pos = _a.pos, end = _a.end; + if (node.kind !== 287 + && (emitFlags & 512) === 0 + && pos >= 0) { + emitPos(ts.skipTrivia(currentSourceText, pos)); + } + if (emitFlags & 2048) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; + } + else { + emitCallback(emitContext, node); + } + if (node.kind !== 287 + && (emitFlags & 1024) === 0 + && end >= 0) { + emitPos(end); + } } } - function emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (ignoreChildrenCallback(contextNode)) { - enable(); - } - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(range.end); - } + function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + if (disabled) { + return emitCallback(token, tokenPos); } - else { - emitPos(range.end); + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + tokenPos = ts.skipTrivia(currentSourceText, range ? range.pos : tokenPos); + if ((emitFlags & 4096) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - stopOverridingSpan = false; - } - function emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return ts.skipTrivia(currentSourceText, tokenStartPos); - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenStartPos = range.pos; - } + tokenPos = emitCallback(token, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 8192) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - tokenStartPos = ts.skipTrivia(currentSourceText, tokenStartPos); - emitPos(tokenStartPos); - return tokenStartPos; - } - function emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return tokenEndPos; - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenEndPos = range.end; - } - } - emitPos(tokenEndPos); - return tokenEndPos; - } - function changeEmitSourcePos() { - ts.Debug.assert(!modifyLastSourcePos); - modifyLastSourcePos = true; + return tokenPos; } function setSourceFile(sourceFile) { + if (disabled) { + return; + } currentSourceFile = sourceFile; currentSourceText = currentSourceFile.text; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; @@ -43961,6 +45323,9 @@ var ts; } } function getText() { + if (disabled) { + return; + } encodeLastRecordedSourceMapSpan(); return ts.stringify({ version: 3, @@ -43973,6 +45338,9 @@ var ts; }); } function getSourceMappingURL() { + if (disabled) { + return; + } if (compilerOptions.inlineSourceMap) { var base64SourceMapText = ts.convertToBase64(getText()); return sourceMapData.jsSourceMappingURL = "data:application/json;base64," + base64SourceMapText; @@ -43982,46 +45350,7 @@ var ts; } } } - function createSourceMapWriterWithExtendedDiagnostics(host, writer) { - var _a = createSourceMapWriterWorker(host, writer), initialize = _a.initialize, reset = _a.reset, getSourceMapData = _a.getSourceMapData, setSourceFile = _a.setSourceFile, emitPos = _a.emitPos, emitStart = _a.emitStart, emitEnd = _a.emitEnd, emitTokenStart = _a.emitTokenStart, emitTokenEnd = _a.emitTokenEnd, changeEmitSourcePos = _a.changeEmitSourcePos, stopOverridingSpan = _a.stopOverridingSpan, getText = _a.getText, getSourceMappingURL = _a.getSourceMappingURL; - return { - initialize: initialize, - reset: reset, - getSourceMapData: getSourceMapData, - setSourceFile: setSourceFile, - emitPos: function (pos) { - ts.performance.mark("sourcemapStart"); - emitPos(pos); - ts.performance.measure("sourceMapTime", "sourcemapStart"); - }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitStart"); - emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitStart"); - }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitEnd"); - emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitEnd"); - }, - emitTokenStart: function (token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenStart"); - tokenStartPos = emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenStart"); - return tokenStartPos; - }, - emitTokenEnd: function (token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenEnd"); - tokenEndPos = emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenEnd"); - return tokenEndPos; - }, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: stopOverridingSpan, - getText: getText, - getSourceMappingURL: getSourceMappingURL - }; - } + ts.createSourceMapWriter = createSourceMapWriter; var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64FormatEncode(inValue) { if (inValue < 64) { @@ -44071,20 +45400,22 @@ var ts; emitBodyWithDetachedComments: emitBodyWithDetachedComments, emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition }; - function emitNodeWithComments(node, emitCallback) { + function emitNodeWithComments(emitContext, node, emitCallback) { if (disabled) { - emitCallback(node); + emitCallback(emitContext, node); return; } if (node) { - var _a = node.commentRange || node, pos = _a.pos, end = _a.end; - var emitFlags = node.emitFlags; + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var emitFlags = ts.getEmitFlags(node); if ((pos < 0 && end < 0) || (pos === end)) { if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } } else { @@ -44113,10 +45444,12 @@ var ts; ts.performance.measure("commentTime", "preEmitNodeWithComment"); } if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } if (extendedDiagnostics) { ts.performance.mark("beginEmitNodeWithComment"); @@ -44138,7 +45471,7 @@ var ts; ts.performance.mark("preEmitBodyWithDetachedComments"); } var pos = detachedRange.pos, end = detachedRange.end; - var emitFlags = node.emitFlags; + var emitFlags = ts.getEmitFlags(node); var skipLeadingComments = pos < 0 || (emitFlags & 16384) !== 0; var skipTrailingComments = disabled || end < 0 || (emitFlags & 32768) !== 0; if (!skipLeadingComments) { @@ -44147,8 +45480,10 @@ var ts; if (extendedDiagnostics) { ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); } - if (emitFlags & 65536) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 65536 && !disabled) { + disabled = true; + emitCallback(node); + disabled = false; } else { emitCallback(node); @@ -44256,16 +45591,6 @@ var ts; currentLineMap = ts.getLineStarts(currentSourceFile); detachedCommentsInfo = undefined; } - function disableCommentsAndEmit(node, emitCallback) { - if (disabled) { - emitCallback(node); - } - else { - disabled = true; - emitCallback(node); - disabled = false; - } - } function hasDetachedComments(pos) { return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; } @@ -44311,7 +45636,9 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - function emitFiles(resolver, host, targetSourceFile) { + var id = function (s) { return s; }; + var nullTransformers = [function (ctx) { return id; }]; + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) { var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); var extendsHelper = "\nvar __extends = (this && this.__extends) || function (d, b) {\n for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];\n function __() { this.constructor = d; }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n};"; @@ -44319,7 +45646,7 @@ var ts; var decorateHelper = "\nvar __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\n return c > 3 && r && Object.defineProperty(target, key, r), r;\n};"; var metadataHelper = "\nvar __metadata = (this && this.__metadata) || function (k, v) {\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(k, v);\n};"; var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; - var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; + var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; var generatorHelper = "\nvar __generator = (this && this.__generator) || function (thisArg, body) {\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t;\n return { next: verb(0), \"throw\": verb(1), \"return\": verb(2) };\n function verb(n) { return function (v) { return step([n, v]); }; }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (_) try {\n if (f = 1, y && (t = y[op[0] & 2 ? \"return\" : op[0] ? \"throw\" : \"next\"]) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [0, t.value];\n switch (op[0]) {\n case 0: case 1: t = op; break;\n case 4: _.label++; return { value: op[1], done: false };\n case 5: _.label++; y = op[1]; op = [0]; continue;\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\n if (t[2]) _.ops.pop();\n _.trys.pop(); continue;\n }\n op = body.call(thisArg, _);\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\n }\n};"; var exportStarHelper = "\nfunction __export(m) {\n for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];\n}"; var umdHelper = "\n(function (dependencies, factory) {\n if (typeof module === 'object' && typeof module.exports === 'object') {\n var v = factory(require, exports); if (v !== undefined) module.exports = v;\n }\n else if (typeof define === 'function' && define.amd) {\n define(dependencies, factory);\n }\n})"; @@ -44332,11 +45659,11 @@ var ts; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); var newLine = host.getNewLine(); - var transformers = ts.getTransformers(compilerOptions); + var transformers = emitOnlyDtsFiles ? nullTransformers : ts.getTransformers(compilerOptions); var writer = ts.createTextWriter(newLine); var write = writer.write, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; var sourceMap = ts.createSourceMapWriter(host, writer); - var emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitTokenStart = sourceMap.emitTokenStart, emitTokenEnd = sourceMap.emitTokenEnd; + var emitNodeWithSourceMap = sourceMap.emitNodeWithSourceMap, emitTokenWithSourceMap = sourceMap.emitTokenWithSourceMap; var comments = ts.createCommentWriter(host, writer, sourceMap); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; var nodeIdToGeneratedName; @@ -44353,14 +45680,17 @@ var ts; var awaiterEmitted; var isOwnFileEmit; var emitSkipped = false; + var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); ts.performance.mark("beforeTransform"); - var transformed = ts.transformFiles(resolver, host, ts.getSourceFilesToEmit(host, targetSourceFile), transformers); + var _a = ts.transformFiles(resolver, host, sourceFiles, transformers), transformed = _a.transformed, emitNodeWithSubstitution = _a.emitNodeWithSubstitution, emitNodeWithNotification = _a.emitNodeWithNotification; ts.performance.measure("transformTime", "beforeTransform"); - var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode; ts.performance.mark("beforePrint"); - ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile); - transformed.dispose(); + ts.forEachTransformedEmitFile(host, transformed, emitFile, emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); + for (var _b = 0, sourceFiles_4 = sourceFiles; _b < sourceFiles_4.length; _b++) { + var sourceFile = sourceFiles_4[_b]; + ts.disposeEmitNodes(sourceFile); + } return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -44369,16 +45699,20 @@ var ts; }; function emitFile(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, isBundledEmit) { if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + if (!emitOnlyDtsFiles) { + printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } } else { emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; } if (!emitSkipped && emittedFilesList) { - emittedFilesList.push(jsFilePath); + if (!emitOnlyDtsFiles) { + emittedFilesList.push(jsFilePath); + } if (sourceMapFilePath) { emittedFilesList.push(sourceMapFilePath); } @@ -44394,8 +45728,8 @@ var ts; generatedNameSet = ts.createMap(); isOwnFileEmit = !isBundledEmit; if (isBundledEmit && moduleKind) { - for (var _a = 0, sourceFiles_4 = sourceFiles; _a < sourceFiles_4.length; _a++) { - var sourceFile = sourceFiles_4[_a]; + for (var _a = 0, sourceFiles_5 = sourceFiles; _a < sourceFiles_5.length; _a++) { + var sourceFile = sourceFiles_5[_a]; emitEmitHelpers(sourceFile); } } @@ -44431,73 +45765,61 @@ var ts; currentFileIdentifiers = node.identifiers; sourceMap.setSourceFile(node); comments.setSourceFile(node); - emitNodeWithNotification(node, emitWorker); + pipelineEmitWithNotification(0, node); } function emit(node) { - emitNodeWithNotification(node, emitWithComments); - } - function emitWithComments(node) { - emitNodeWithComments(node, emitWithSourceMap); - } - function emitWithSourceMap(node) { - emitNodeWithSourceMap(node, emitWorker); + pipelineEmitWithNotification(3, node); } function emitIdentifierName(node) { - if (node) { - emitNodeWithNotification(node, emitIdentifierNameWithComments); - } - } - function emitIdentifierNameWithComments(node) { - emitNodeWithComments(node, emitWorker); + pipelineEmitWithNotification(2, node); } function emitExpression(node) { - emitNodeWithNotification(node, emitExpressionWithComments); + pipelineEmitWithNotification(1, node); } - function emitExpressionWithComments(node) { - emitNodeWithComments(node, emitExpressionWithSourceMap); + function pipelineEmitWithNotification(emitContext, node) { + emitNodeWithNotification(emitContext, node, pipelineEmitWithComments); } - function emitExpressionWithSourceMap(node) { - emitNodeWithSourceMap(node, emitExpressionWorker); - } - function emitNodeWithNotification(node, emitCallback) { - if (node) { - if (isEmitNotificationEnabled(node)) { - onEmitNode(node, emitCallback); - } - else { - emitCallback(node); - } - } - } - function emitNodeWithSourceMap(node, emitCallback) { - if (node) { - emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - emitCallback(node); - emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - function shouldSkipLeadingCommentsForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 16384) !== 0; - } - function shouldSkipLeadingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 512) !== 0; - } - function shouldSkipTrailingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 1024) !== 0; - } - function shouldSkipSourceMapForChildren(node) { - return (node.emitFlags & 2048) !== 0; - } - function emitWorker(node) { - if (tryEmitSubstitute(node, emitWorker, false)) { + function pipelineEmitWithComments(emitContext, node) { + if (emitContext === 0) { + pipelineEmitWithSourceMap(emitContext, node); return; } + emitNodeWithComments(emitContext, node, pipelineEmitWithSourceMap); + } + function pipelineEmitWithSourceMap(emitContext, node) { + if (emitContext === 0 + || emitContext === 2) { + pipelineEmitWithSubstitution(emitContext, node); + return; + } + emitNodeWithSourceMap(emitContext, node, pipelineEmitWithSubstitution); + } + function pipelineEmitWithSubstitution(emitContext, node) { + emitNodeWithSubstitution(emitContext, node, pipelineEmitForContext); + } + function pipelineEmitForContext(emitContext, node) { + switch (emitContext) { + case 0: return pipelineEmitInSourceFileContext(node); + case 2: return pipelineEmitInIdentifierNameContext(node); + case 3: return pipelineEmitInUnspecifiedContext(node); + case 1: return pipelineEmitInExpressionContext(node); + } + } + function pipelineEmitInSourceFileContext(node) { + var kind = node.kind; + switch (kind) { + case 256: + return emitSourceFile(node); + } + } + function pipelineEmitInIdentifierNameContext(node) { + var kind = node.kind; + switch (kind) { + case 69: + return emitIdentifier(node); + } + } + function pipelineEmitInUnspecifiedContext(node) { var kind = node.kind; switch (kind) { case 12: @@ -44524,7 +45846,8 @@ var ts; case 132: case 133: case 137: - return writeTokenNode(node); + writeTokenText(kind); + return; case 139: return emitQualifiedName(node); case 140: @@ -44700,17 +46023,12 @@ var ts; return emitShorthandPropertyAssignment(node); case 255: return emitEnumMember(node); - case 256: - return emitSourceFile(node); } if (ts.isExpression(node)) { - return emitExpressionWorker(node); + return pipelineEmitWithSubstitution(1, node); } } - function emitExpressionWorker(node) { - if (tryEmitSubstitute(node, emitExpressionWorker, true)) { - return; - } + function pipelineEmitInExpressionContext(node) { var kind = node.kind; switch (kind) { case 8: @@ -44726,7 +46044,8 @@ var ts; case 95: case 99: case 97: - return writeTokenNode(node); + writeTokenText(kind); + return; case 170: return emitArrayLiteralExpression(node); case 171: @@ -44804,7 +46123,7 @@ var ts; } } function emitIdentifier(node) { - if (node.emitFlags & 16) { + if (ts.getEmitFlags(node) & 16) { writeLines(umdHelper); } else { @@ -45019,7 +46338,7 @@ var ts; write("{}"); } else { - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 524288; if (indentedFlag) { increaseIndent(); } @@ -45032,21 +46351,18 @@ var ts; } } function emitPropertyAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } var indentBeforeDot = false; var indentAfterDot = false; - if (!(node.emitFlags & 1048576)) { + if (!(ts.getEmitFlags(node) & 1048576)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentText, node.expression.end) + 1; var dotToken = { kind: 21, pos: dotRangeStart, end: dotRangeEnd }; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } - var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); emitExpression(node.expression); increaseIndentIf(indentBeforeDot); + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); write(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); @@ -45057,15 +46373,14 @@ var ts; var text = getLiteralTextOfNode(expression); return text.indexOf(ts.tokenToString(21)) < 0; } - else { - var constantValue = tryGetConstEnumValue(expression); - return isFinite(constantValue) && Math.floor(constantValue) === constantValue; + else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { + var constantValue = ts.getConstantValue(expression); + return isFinite(constantValue) + && Math.floor(constantValue) === constantValue + && compilerOptions.removeComments; } } function emitElementAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } emitExpression(node.expression); write("["); emitExpression(node.argumentExpression); @@ -45220,7 +46535,7 @@ var ts; } } function emitBlockStatements(node) { - if (node.emitFlags & 32) { + if (ts.getEmitFlags(node) & 32) { emitList(node, node.statements, 384); } else { @@ -45395,11 +46710,11 @@ var ts; var body = node.body; if (body) { if (ts.isBlock(body)) { - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 524288; if (indentedFlag) { increaseIndent(); } - if (node.emitFlags & 4194304) { + if (ts.getEmitFlags(node) & 4194304) { emitSignatureHead(node); emitBlockFunctionBody(node, body); } @@ -45431,7 +46746,7 @@ var ts; emitWithPrefix(": ", node.type); } function shouldEmitBlockFunctionBodyOnSingleLine(parentNode, body) { - if (body.emitFlags & 32) { + if (ts.getEmitFlags(body) & 32) { return true; } if (body.multiLine) { @@ -45486,7 +46801,7 @@ var ts; emitModifiers(node, node.modifiers); write("class"); emitNodeWithPrefix(" ", node.name, emitIdentifierName); - var indentedFlag = node.emitFlags & 524288; + var indentedFlag = ts.getEmitFlags(node) & 524288; if (indentedFlag) { increaseIndent(); } @@ -45548,7 +46863,7 @@ var ts; emit(body); } function emitModuleBlock(node) { - if (isSingleLineEmptyBlock(node)) { + if (isEmptyBlock(node)) { write("{ }"); } else { @@ -45745,8 +47060,8 @@ var ts; emit(node.name); write(": "); var initializer = node.initializer; - if (!shouldSkipLeadingCommentsForNode(initializer)) { - var commentRange = initializer.commentRange || initializer; + if ((ts.getEmitFlags(initializer) & 16384) === 0) { + var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } emitExpression(initializer); @@ -45794,7 +47109,7 @@ var ts; return statements.length; } function emitHelpers(node) { - var emitFlags = node.emitFlags; + var emitFlags = ts.getEmitFlags(node); var helpersEmitted = false; if (emitFlags & 1) { helpersEmitted = emitEmitHelpers(currentSourceFile); @@ -45900,31 +47215,6 @@ var ts; write(suffix); } } - function tryEmitSubstitute(node, emitNode, isExpression) { - if (isSubstitutionEnabled(node) && (node.emitFlags & 128) === 0) { - var substitute = onSubstituteNode(node, isExpression); - if (substitute !== node) { - substitute.emitFlags |= 128; - emitNode(substitute); - return true; - } - } - return false; - } - function tryEmitConstantValue(node) { - var constantValue = tryGetConstEnumValue(node); - if (constantValue !== undefined) { - write(String(constantValue)); - if (!compilerOptions.removeComments) { - var propertyName = ts.isPropertyAccessExpression(node) - ? ts.declarationNameToString(node.name) - : getTextOfNode(node.argumentExpression); - write(" /* " + propertyName + " */"); - } - return true; - } - return false; - } function emitEmbeddedStatement(node) { if (ts.isBlock(node)) { write(" "); @@ -46024,7 +47314,7 @@ var ts; } } if (shouldEmitInterveningComments) { - var commentRange = child.commentRange || child; + var commentRange = ts.getCommentRange(child); emitTrailingCommentsOfPosition(commentRange.pos); } else { @@ -46066,27 +47356,12 @@ var ts; } } function writeToken(token, pos, contextNode) { - var tokenStartPos = emitTokenStart(token, pos, contextNode, shouldSkipLeadingSourceMapForToken, getTokenSourceMapRange); - var tokenEndPos = writeTokenText(token, tokenStartPos); - return emitTokenEnd(token, tokenEndPos, contextNode, shouldSkipTrailingSourceMapForToken, getTokenSourceMapRange); - } - function shouldSkipLeadingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 4096) !== 0; - } - function shouldSkipTrailingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 8192) !== 0; + return emitTokenWithSourceMap(contextNode, token, pos, writeTokenText); } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); - return ts.positionIsSynthesized(pos) ? -1 : pos + tokenString.length; - } - function writeTokenNode(node) { - if (node) { - emitStart(node, node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - writeTokenText(node.kind); - emitEnd(node, node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } + return pos < 0 ? pos : pos + tokenString.length; } function increaseIndentIf(value, valueToWriteWhenNotIndenting) { if (value) { @@ -46225,17 +47500,12 @@ var ts; } return ts.getLiteralText(node, currentSourceFile, languageVersion); } - function tryGetConstEnumValue(node) { - if (compilerOptions.isolatedModules) { - return undefined; - } - return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) - ? resolver.getConstantValue(node) - : undefined; - } function isSingleLineEmptyBlock(block) { return !block.multiLine - && block.statements.length === 0 + && isEmptyBlock(block); + } + function isEmptyBlock(block) { + return block.statements.length === 0 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function isUniqueName(name) { @@ -46255,21 +47525,21 @@ var ts; } function makeTempVariableName(flags) { if (flags && !(tempFlags & flags)) { - var name_43 = flags === 268435456 ? "_i" : "_n"; - if (isUniqueName(name_43)) { + var name_44 = flags === 268435456 ? "_i" : "_n"; + if (isUniqueName(name_44)) { tempFlags |= flags; - return name_43; + return name_44; } } while (true) { var count = tempFlags & 268435455; tempFlags++; if (count !== 8 && count !== 13) { - var name_44 = count < 26 + var name_45 = count < 26 ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); - if (isUniqueName(name_44)) { - return name_44; + if (isUniqueName(name_45)) { + return name_45; } } } @@ -46445,581 +47715,6 @@ var ts; return ts.getNormalizedPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; - function trace(host, message) { - host.trace(ts.formatMessage.apply(undefined, arguments)); - } - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - function hasZeroOrOneAsteriskCharacter(str) { - var seenAsterisk = false; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - return false; - } - } - } - return true; - } - ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; - } - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); - function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); - } - return typesFilePath_1; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } - } - } - } - var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); - if (typesFilePath) { - return typesFilePath; - } - if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); - } - var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - return mainFilePath; - } - return undefined; - } - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - return {}; - } - } - var typeReferenceExtensions = [".d.ts"]; - function getEffectiveTypeRoots(options, host) { - if (options.typeRoots) { - return options.typeRoots; - } - var currentDirectory; - if (options.configFilePath) { - currentDirectory = ts.getDirectoryPath(options.configFilePath); - } - else if (host.getCurrentDirectory) { - currentDirectory = host.getCurrentDirectory(); - } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; - } - var typeRoots; - while (true) { - var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - var parent_15 = ts.getDirectoryPath(currentDirectory); - if (parent_15 === currentDirectory) { - break; - } - currentDirectory = parent_15; - } - return typeRoots; - } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { - compilerOptions: options, - host: host, - skipTsx: true, - traceEnabled: traceEnabled - }; - var typeRoots = getEffectiveTypeRoots(options, host); - if (traceEnabled) { - if (containingFile === undefined) { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); - } - } - else { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); - } - } - } - var failedLookupLocations = []; - if (typeRoots && typeRoots.length) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); - } - var primarySearchPaths = typeRoots; - for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { - var typeRoot = primarySearchPaths_1[_i]; - var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); - var candidateDirectory = ts.getDirectoryPath(candidate); - var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); - if (resolvedFile_1) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); - } - return { - resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, - failedLookupLocations: failedLookupLocations - }; - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); - } - } - var resolvedFile; - var initialLocationForSecondaryLookup; - if (containingFile) { - initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); - } - if (initialLocationForSecondaryLookup !== undefined) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); - } - resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState); - if (traceEnabled) { - if (resolvedFile) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); - } - } - return { - resolvedTypeReferenceDirective: resolvedFile - ? { primary: false, resolvedFileName: resolvedFile } - : undefined, - failedLookupLocations: failedLookupLocations - }; - } - ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - var result; - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); - break; - case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host); - break; - } - if (traceEnabled) { - if (result.resolvedModule) { - trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); - } - else { - return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); - } - } - function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { - var subst = _a[_i]; - var path = matchedStar ? subst.replace("*", matchedStar) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - } - return undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - function tryParsePattern(pattern) { - ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var traceEnabled = isTraceEnabled(compilerOptions, host); - var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); - var isExternalLibraryImport = false; - if (!resolvedFileName) { - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); - } - resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); - isExternalLibraryImport = resolvedFileName !== undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, false, state); - } - } - if (resolvedFileName && host.realpath) { - var originalFileName = resolvedFileName; - resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); - } - } - return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); - } - var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); - return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); - } - function directoryProbablyExists(directoryName, host) { - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - if (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); - } - } - function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - return ts.forEach(extensions, function (ext) { - return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); - }); - } - function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; - } - } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); - if (typesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); - var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || - tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); - if (result) { - return result; - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); - } - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - failedLookupLocation.push(packageJsonPath); - } - return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); - } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); - var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - } - function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { - directory = ts.normalizeSlashes(directory); - while (true) { - var baseName = ts.getBaseFileName(directory); - if (baseName !== "node_modules") { - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - return packageResult; - } - else { - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; - } - } - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - break; - } - directory = parentPath; - } - return undefined; - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; - var failedLookupLocations = []; - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); - if (resolvedFileName) { - return createResolvedModule(resolvedFileName, false, failedLookupLocations); - } - var referencedSourceFile; - if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, false, state); - } - return referencedSourceFile - ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - ts.classicNameResolver = classicNameResolver; function createCompilerHost(options, setParentNodes) { var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { @@ -47121,7 +47816,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.getEnvironmentVariable(name, undefined); }, + getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; @@ -47181,41 +47876,14 @@ var ts; var resolutions = []; var cache = ts.createMap(); for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { - var name_45 = names_2[_i]; - var result = name_45 in cache - ? cache[name_45] - : cache[name_45] = loader(name_45, containingFile); + var name_46 = names_2[_i]; + var result = name_46 in cache + ? cache[name_46] + : cache[name_46] = loader(name_46, containingFile); resolutions.push(result); } return resolutions; } - function getAutomaticTypeDirectiveNames(options, host) { - if (options.types) { - return options.types; - } - var result = []; - if (host.directoryExists && host.getDirectories) { - var typeRoots = getEffectiveTypeRoots(options, host); - if (typeRoots) { - for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { - var root = typeRoots_1[_i]; - if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - result.push(ts.getBaseFileName(normalized)); - } - } - } - } - } - } - return result; - } - ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -47241,7 +47909,7 @@ var ts; resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; } else { - var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -47249,15 +47917,15 @@ var ts; resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; } else { - var loader_2 = function (typesRef, containingFile) { return resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; + var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); }; } var filesByName = ts.createFileMap(); var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? ts.createFileMap(function (fileName) { return fileName.toLowerCase(); }) : undefined; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, false); }); - var typeReferences = getAutomaticTypeDirectiveNames(options, host); - if (typeReferences) { + var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + if (typeReferences.length) { var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { @@ -47299,7 +47967,8 @@ var ts; getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, - getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -47346,6 +48015,7 @@ var ts; (oldOptions.configFilePath !== options.configFilePath) || (oldOptions.baseUrl !== options.baseUrl) || (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || + !ts.arrayIsEqualTo(oldOptions.lib, options.lib) || !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || !ts.equalOwnProperties(oldOptions.paths, options.paths)) { @@ -47446,16 +48116,19 @@ var ts; function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, true)); } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, false)); } - function emit(sourceFile, writeFileCallback, cancellationToken) { - return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); }); + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); } - function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { var declarationDiagnostics = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; @@ -47476,7 +48149,7 @@ var ts; } var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); ts.performance.mark("beforeEmit"); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -47991,7 +48664,6 @@ var ts; for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); - var resolvedPath = resolution ? ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName) : undefined; var isFromNodeModulesSearch = resolution && resolution.isExternalLibraryImport; var isJsFileFromNodeModules = isFromNodeModulesSearch && ts.hasJavaScriptFileExtension(resolution.resolvedFileName); if (isFromNodeModulesSearch) { @@ -48003,7 +48675,7 @@ var ts; modulesWithElidedImports[file.path] = true; } else if (shouldAddFile) { - findSourceFile(resolution.resolvedFileName, resolvedPath, false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); + findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), false, false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } if (isFromNodeModulesSearch) { currentNodeModulesDepth--; @@ -48017,8 +48689,8 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var file = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var file = sourceFiles_6[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -48029,8 +48701,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -48073,7 +48745,7 @@ var ts; if (!ts.hasProperty(options.paths, key)) { continue; } - if (!hasZeroOrOneAsteriskCharacter(key)) { + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { @@ -48084,7 +48756,7 @@ var ts; var subst = _a[_i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { - if (!hasZeroOrOneAsteriskCharacter(subst)) { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } @@ -48123,6 +48795,9 @@ var ts; if (options.lib && options.noLib) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")); } + if (options.noImplicitUseStrict && options.alwaysStrict) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict")); + } var languageVersion = options.target || 0; var outFile = options.outFile || options.out; var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); @@ -48685,7 +49360,7 @@ var ts; case 97: return true; case 69: - return node.originalKeywordKind === 97 && node.parent.kind === 142; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 142; default: return false; } @@ -49258,7 +49933,6 @@ var ts; } ts.isInNonReferenceComment = isInNonReferenceComment; })(ts || (ts = {})); -var ts; (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 142; @@ -49481,7 +50155,7 @@ var ts; return ts.ensureScriptKind(fileName, scriptKind); } ts.getScriptKind = getScriptKind; - function parseAndReEmitConfigJSONFile(content) { + function sanitizeConfigFile(configFileName, content) { var options = { fileName: "config.js", compilerOptions: { @@ -49492,14 +50166,17 @@ var ts; }; var _a = ts.transpileModule("(" + content + ")", options), outputText = _a.outputText, diagnostics = _a.diagnostics; var trimmedOutput = outputText.trim(); - var configJsonObject = JSON.parse(trimmedOutput.substring(1, trimmedOutput.length - 2)); for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; diagnostic.start = diagnostic.start - 1; } - return { configJsonObject: configJsonObject, diagnostics: diagnostics }; + var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), false), config = _b.config, error = _b.error; + return { + configJsonObject: config || {}, + diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics + }; } - ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile; + ts.sanitizeConfigFile = sanitizeConfigFile; })(ts || (ts = {})); var ts; (function (ts) { @@ -50701,8 +51378,7 @@ var ts; return; case 142: if (token.parent.name === token) { - var isThis_1 = token.kind === 69 && token.originalKeywordKind === 97; - return isThis_1 ? 3 : 17; + return ts.isThisIdentifier(token) ? 3 : 17; } return; } @@ -50743,13 +51419,13 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; if (isJsDocTagName) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, false); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, true); ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); } else { @@ -50773,17 +51449,17 @@ var ts; if (!isMemberCompletion && !isJsDocTagName) { ts.addRange(entries, keywordCompletions); } - return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation || ts.isSourceFileJavaScript(sourceFile), entries: entries }; + return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { var entries = []; var nameTable = ts.getNameTable(sourceFile); - for (var name_46 in nameTable) { - if (nameTable[name_46] === position) { + for (var name_47 in nameTable) { + if (nameTable[name_47] === position) { continue; } - if (!uniqueNames[name_46]) { - uniqueNames[name_46] = name_46; - var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_46), compilerOptions.target, true); + if (!uniqueNames[name_47]) { + uniqueNames[name_47] = name_47; + var displayName = getCompletionEntryDisplayName(ts.unescapeIdentifier(name_47), compilerOptions.target, true); if (displayName) { var entry = { name: displayName, @@ -50833,7 +51509,9 @@ var ts; if (!node || node.kind !== 9) { return undefined; } - if (node.parent.kind === 253 && node.parent.parent.kind === 171) { + if (node.parent.kind === 253 && + node.parent.parent.kind === 171 && + node.parent.name === node) { return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent); } else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { @@ -50856,7 +51534,7 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } } @@ -50872,7 +51550,7 @@ var ts; } } if (entries.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; } return undefined; } @@ -50882,7 +51560,7 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } return undefined; @@ -50893,7 +51571,7 @@ var ts; var entries_2 = []; addStringLiteralCompletionsFromType(type, entries_2); if (entries_2.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } } return undefined; @@ -50934,6 +51612,7 @@ var ts; entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span); } return { + isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries @@ -50964,13 +51643,15 @@ var ts; } function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, span, exclude, result) { if (result === void 0) { result = []; } + if (fragment === undefined) { + fragment = ""; + } + fragment = ts.normalizeSlashes(fragment); fragment = ts.getDirectoryPath(fragment); - if (!fragment) { - fragment = "./"; - } - else { - fragment = ts.ensureTrailingDirectorySeparator(fragment); + if (fragment === "") { + fragment = "." + ts.directorySeparator; } + fragment = ts.ensureTrailingDirectorySeparator(fragment); var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment)); var baseDirectory = ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); @@ -51126,6 +51807,12 @@ var ts; if (!range) { return undefined; } + var completionInfo = { + isGlobalCompletion: false, + isMemberCompletion: false, + isNewIdentifierLocation: true, + entries: [] + }; var text = sourceFile.text.substr(range.pos, position - range.pos); var match = tripleSlashDirectiveFragmentRegex.exec(text); if (match) { @@ -51133,22 +51820,16 @@ var ts; var kind = match[2]; var toComplete = match[3]; var scriptPath = ts.getDirectoryPath(sourceFile.path); - var entries_3; if (kind === "path") { var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - entries_3 = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), true, span_10, sourceFile.path); + completionInfo.entries = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), true, span_10, sourceFile.path); } else { var span_11 = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; - entries_3 = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); + completionInfo.entries = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); } - return { - isMemberCompletion: false, - isNewIdentifierLocation: true, - entries: entries_3 - }; } - return undefined; + return completionInfo; } function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { if (result === void 0) { result = []; } @@ -51347,7 +52028,7 @@ var ts; } } if (isJsDocTagName) { - return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; } if (!insideJsDocTagExpression) { log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); @@ -51399,6 +52080,7 @@ var ts; } } var semanticStart = ts.timestamp(); + var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; var symbols = []; @@ -51429,10 +52111,12 @@ var ts; if (!tryGetGlobalSymbols()) { return undefined; } + isGlobalCompletion = true; } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; function getTypeScriptMemberSymbols() { + isGlobalCompletion = false; isMemberCompletion = true; isNewIdentifierLocation = false; if (node.kind === 69 || node.kind === 139 || node.kind === 172) { @@ -51483,6 +52167,7 @@ var ts; var attrsType = void 0; if ((jsxContainer.kind === 242) || (jsxContainer.kind === 243)) { attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); + isGlobalCompletion = false; if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); isMemberCompletion = true; @@ -51842,8 +52527,8 @@ var ts; if (element.getStart() <= position && position <= element.getEnd()) { continue; } - var name_47 = element.propertyName || element.name; - existingImportsOrExports[name_47.text] = true; + var name_48 = element.propertyName || element.name; + existingImportsOrExports[name_48.text] = true; } if (!ts.someProperties(existingImportsOrExports)) { return ts.filter(exportsOfModule, function (e) { return e.name !== "default"; }); @@ -51927,7 +52612,7 @@ var ts; sortText: "0" }); } - var tripleSlashDirectiveFragmentRegex = /^(\/\/\/\s* sourceFile.text.length) { return getBaseIndentation(options); } - if (options.IndentStyle === ts.IndentStyle.None) { + if (options.indentStyle === ts.IndentStyle.None) { return 0; } var precedingToken = ts.findPrecedingToken(position, sourceFile); @@ -58576,7 +59140,7 @@ var ts; return 0; } var lineAtPosition = sourceFile.getLineAndCharacterOfPosition(position).line; - if (options.IndentStyle === ts.IndentStyle.Block) { + if (options.indentStyle === ts.IndentStyle.Block) { var current_1 = position; while (current_1 > 0) { var char = sourceFile.text.charCodeAt(current_1); @@ -58605,7 +59169,7 @@ var ts; indentationDelta = 0; } else { - indentationDelta = lineAtPosition !== currentStart.line ? options.IndentSize : 0; + indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0; } break; } @@ -58615,7 +59179,7 @@ var ts; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1) { - return actualIndentation + options.IndentSize; + return actualIndentation + options.indentSize; } previous = current; current = current.parent; @@ -58626,15 +59190,15 @@ var ts; return getIndentationForNodeWorker(current, currentStart, undefined, indentationDelta, sourceFile, options); } SmartIndenter.getIndentation = getIndentation; - function getBaseIndentation(options) { - return options.BaseIndentSize || 0; - } - SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, 0, sourceFile, options); } SmartIndenter.getIndentationForNode = getIndentationForNode; + function getBaseIndentation(options) { + return options.baseIndentSize || 0; + } + SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) { var parent = current.parent; var parentStart; @@ -58664,7 +59228,7 @@ var ts; } } if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { - indentationDelta += options.IndentSize; + indentationDelta += options.indentSize; } current = parent; currentStart = parentStart; @@ -58842,7 +59406,7 @@ var ts; break; } if (ch === 9) { - column += options.TabSize + (column % options.TabSize); + column += options.tabSize + (column % options.tabSize); } else { column++; @@ -58940,11 +59504,116 @@ var ts; })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + var codeFixes = ts.createMap(); + function registerCodeFix(action) { + ts.forEach(action.errorCodes, function (error) { + var fixes = codeFixes[error]; + if (!fixes) { + fixes = []; + codeFixes[error] = fixes; + } + fixes.push(action); + }); + } + codefix.registerCodeFix = registerCodeFix; + function getSupportedErrorCodes() { + return Object.keys(codeFixes); + } + codefix.getSupportedErrorCodes = getSupportedErrorCodes; + function getFixes(context) { + var fixes = codeFixes[context.errorCode]; + var allActions = []; + ts.forEach(fixes, function (f) { + var actions = f.getCodeActions(context); + if (actions && actions.length > 0) { + allActions = allActions.concat(actions); + } + }); + return allActions; + } + codefix.getFixes = getFixes; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var codefix; + (function (codefix) { + function getOpenBraceEnd(constructor, sourceFile) { + return constructor.body.getFirstToken(sourceFile).getEnd(); + } + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 121) { + return undefined; + } + var newPosition = getOpenBraceEnd(token.parent, sourceFile); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), + changes: [{ fileName: sourceFile.fileName, textChanges: [{ newText: "super();", span: { start: newPosition, length: 0 } }] }] + }]; + } + }); + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 97) { + return undefined; + } + var constructor = ts.getContainingFunction(token); + var superCall = findSuperCall(constructor.body); + if (!superCall) { + return undefined; + } + if (superCall.expression && superCall.expression.kind == 174) { + var arguments_1 = superCall.expression.arguments; + for (var i = 0; i < arguments_1.length; i++) { + if (arguments_1[i].expression === token) { + return undefined; + } + } + } + var newPosition = getOpenBraceEnd(constructor, sourceFile); + var changes = [{ + fileName: sourceFile.fileName, textChanges: [{ + newText: superCall.getText(sourceFile), + span: { start: newPosition, length: 0 } + }, + { + newText: "", + span: { start: superCall.getStart(sourceFile), length: superCall.getWidth(sourceFile) } + }] + }]; + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), + changes: changes + }]; + function findSuperCall(n) { + if (n.kind === 202 && ts.isSuperCall(n.expression)) { + return n; + } + if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findSuperCall); + } + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { ts.servicesVersion = "0.5"; function createNode(kind, pos, end, parent) { var node = kind >= 139 ? new NodeObject(kind, pos, end) : - kind === 69 ? new IdentifierObject(kind, pos, end) : + kind === 69 ? new IdentifierObject(69, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; return node; @@ -59167,15 +59836,16 @@ var ts; var TokenObject = (function (_super) { __extends(TokenObject, _super); function TokenObject(kind, pos, end) { - _super.call(this, pos, end); - this.kind = kind; + var _this = _super.call(this, pos, end) || this; + _this.kind = kind; + return _this; } return TokenObject; }(TokenOrIdentifierObject)); var IdentifierObject = (function (_super) { __extends(IdentifierObject, _super); function IdentifierObject(kind, pos, end) { - _super.call(this, pos, end); + return _super.call(this, pos, end) || this; } return IdentifierObject; }(TokenOrIdentifierObject)); @@ -59249,7 +59919,7 @@ var ts; var SourceFileObject = (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { - _super.call(this, kind, pos, end); + return _super.call(this, kind, pos, end) || this; } SourceFileObject.prototype.update = function (newText, textChangeRange) { return ts.updateSourceFile(this, newText, textChangeRange); @@ -59406,6 +60076,30 @@ var ts; getSignatureConstructor: function () { return SignatureObject; } }; } + function toEditorSettings(optionsAsMap) { + var allPropertiesAreCamelCased = true; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) { + allPropertiesAreCamelCased = false; + break; + } + } + if (allPropertiesAreCamelCased) { + return optionsAsMap; + } + var settings = {}; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key)) { + var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1); + settings[newKey] = optionsAsMap[key]; + } + } + return settings; + } + ts.toEditorSettings = toEditorSettings; + function isCamelCase(s) { + return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); + } function displayPartsToString(displayParts) { if (displayParts) { return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join(""); @@ -59420,6 +60114,10 @@ var ts; }; } ts.getDefaultCompilerOptions = getDefaultCompilerOptions; + function getSupportedCodeFixes() { + return ts.codefix.getSupportedErrorCodes(); + } + ts.getSupportedCodeFixes = getSupportedCodeFixes; var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; @@ -59583,7 +60281,8 @@ var ts; var ruleProvider; var program; var lastProjectVersion; - var useCaseSensitivefileNames = false; + var lastTypesRootVersion = 0; + var useCaseSensitivefileNames = host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(); var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); var currentDirectory = host.getCurrentDirectory(); if (!ts.localizedDiagnosticMessages && host.getLocalizedDiagnosticMessages) { @@ -59619,6 +60318,12 @@ var ts; lastProjectVersion = hostProjectVersion; } } + var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; + if (lastTypesRootVersion !== typeRootsVersion) { + log("TypeRoots version has changed; provide new program"); + program = undefined; + lastTypesRootVersion = typeRootsVersion; + } var hostCache = new HostCache(host, getCanonicalFileName); if (programUpToDate()) { return; @@ -59878,12 +60583,12 @@ var ts; synchronizeHostData(); return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, findInStrings, findInComments); } - function getNavigateToItems(searchValue, maxResultCount, fileName) { + function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { synchronizeHostData(); var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); - return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount); + return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName) { + function getEmitOutput(fileName, emitOnlyDtsFiles) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var outputFiles = []; @@ -59894,7 +60599,7 @@ var ts; text: data }); } - var emitOutput = program.emit(sourceFile, writeFile, cancellationToken); + var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles); return { outputFiles: outputFiles, emitSkipped: emitOutput.emitSkipped @@ -59957,14 +60662,26 @@ var ts; return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); } function getNavigationBarItems(fileName) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function getNavigationTree(fileName) { + return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function isTsOrTsxFile(fileName) { + var kind = ts.getScriptKind(fileName, host); + return kind === 3 || kind === 4; } function getSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + return []; + } synchronizeHostData(); return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } function getEncodedSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + return { spans: [], endOfLineState: 0 }; + } synchronizeHostData(); return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } @@ -60020,34 +60737,60 @@ var ts; } function getIndentationAtPosition(fileName, position, editorOptions) { var start = ts.timestamp(); + var settings = toEditorSettings(editorOptions); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); start = ts.timestamp(); - var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); + var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings); log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); return result; } function getFormattingEditsForRange(fileName, start, end, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsForDocument(fileName, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var settings = toEditorSettings(options); if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); } else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); } else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); } return []; } + function getCodeFixesAtPosition(fileName, start, end, errorCodes) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var span = { start: start, length: end - start }; + var newLineChar = ts.getNewLineOrDefaultFromHost(host); + var allFixes = []; + ts.forEach(errorCodes, function (error) { + cancellationToken.throwIfCancellationRequested(); + var context = { + errorCode: error, + sourceFile: sourceFile, + span: span, + program: program, + newLineCharacter: newLineChar + }; + var fixes = ts.codefix.getFixes(context); + if (fixes) { + allFixes = allFixes.concat(fixes); + } + }); + return allFixes; + } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } @@ -60159,6 +60902,7 @@ var ts; getRenameInfo: getRenameInfo, findRenameLocations: findRenameLocations, getNavigationBarItems: getNavigationBarItems, + getNavigationTree: getNavigationTree, getOutliningSpans: getOutliningSpans, getTodoComments: getTodoComments, getBraceMatchingAtPosition: getBraceMatchingAtPosition, @@ -60168,6 +60912,7 @@ var ts; getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getCodeFixesAtPosition: getCodeFixesAtPosition, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, @@ -60233,43 +60978,2344 @@ var ts; (function (ts) { var server; (function (server) { - var spaceCache = []; - function generateSpaces(n) { - if (!spaceCache[n]) { - var strBuilder = ""; - for (var i = 0; i < n; i++) { - strBuilder += " "; - } - spaceCache[n] = strBuilder; + var ScriptInfo = (function () { + function ScriptInfo(host, fileName, content, scriptKind, isOpen, hasMixedContent) { + if (isOpen === void 0) { isOpen = false; } + if (hasMixedContent === void 0) { hasMixedContent = false; } + this.host = host; + this.fileName = fileName; + this.scriptKind = scriptKind; + this.isOpen = isOpen; + this.hasMixedContent = hasMixedContent; + this.containingProjects = []; + this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); + this.svc = server.ScriptVersionCache.fromString(host, content); + this.scriptKind = scriptKind + ? scriptKind + : ts.getScriptKindFromFileName(fileName); } - return spaceCache[n]; + ScriptInfo.prototype.getFormatCodeSettings = function () { + return this.formatCodeSettings; + }; + ScriptInfo.prototype.attachToProject = function (project) { + var isNew = !this.isAttached(project); + if (isNew) { + this.containingProjects.push(project); + } + return isNew; + }; + ScriptInfo.prototype.isAttached = function (project) { + switch (this.containingProjects.length) { + case 0: return false; + case 1: return this.containingProjects[0] === project; + case 2: return this.containingProjects[0] === project || this.containingProjects[1] === project; + default: return ts.contains(this.containingProjects, project); + } + }; + ScriptInfo.prototype.detachFromProject = function (project) { + switch (this.containingProjects.length) { + case 0: + return; + case 1: + if (this.containingProjects[0] === project) { + this.containingProjects.pop(); + } + break; + case 2: + if (this.containingProjects[0] === project) { + this.containingProjects[0] = this.containingProjects.pop(); + } + else if (this.containingProjects[1] === project) { + this.containingProjects.pop(); + } + break; + default: + server.removeItemFromSet(this.containingProjects, project); + break; + } + }; + ScriptInfo.prototype.detachAllProjects = function () { + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + p.removeFile(this, false); + } + this.containingProjects.length = 0; + }; + ScriptInfo.prototype.getDefaultProject = function () { + if (this.containingProjects.length === 0) { + return server.Errors.ThrowNoProject(); + } + ts.Debug.assert(this.containingProjects.length !== 0); + return this.containingProjects[0]; + }; + ScriptInfo.prototype.setFormatOptions = function (formatSettings) { + if (formatSettings) { + if (!this.formatCodeSettings) { + this.formatCodeSettings = server.getDefaultFormatCodeSettings(this.host); + } + server.mergeMaps(this.formatCodeSettings, formatSettings); + } + }; + ScriptInfo.prototype.setWatcher = function (watcher) { + this.stopWatcher(); + this.fileWatcher = watcher; + }; + ScriptInfo.prototype.stopWatcher = function () { + if (this.fileWatcher) { + this.fileWatcher.close(); + this.fileWatcher = undefined; + } + }; + ScriptInfo.prototype.getLatestVersion = function () { + return this.svc.latestVersion().toString(); + }; + ScriptInfo.prototype.reload = function (script) { + this.svc.reload(script); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.saveTo = function (fileName) { + var snap = this.snap(); + this.host.writeFile(fileName, snap.getText(0, snap.getLength())); + }; + ScriptInfo.prototype.reloadFromFile = function () { + if (this.hasMixedContent) { + this.reload(""); + } + else { + this.svc.reloadFromFile(this.fileName); + this.markContainingProjectsAsDirty(); + } + }; + ScriptInfo.prototype.snap = function () { + return this.svc.getSnapshot(); + }; + ScriptInfo.prototype.getLineInfo = function (line) { + var snap = this.snap(); + return snap.index.lineNumberToInfo(line); + }; + ScriptInfo.prototype.editContent = function (start, end, newText) { + this.svc.edit(start, end - start, newText); + this.markContainingProjectsAsDirty(); + }; + ScriptInfo.prototype.markContainingProjectsAsDirty = function () { + for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + p.markAsDirty(); + } + }; + ScriptInfo.prototype.lineToTextSpan = function (line) { + var index = this.snap().index; + var lineInfo = index.lineNumberToInfo(line + 1); + var len; + if (lineInfo.leaf) { + len = lineInfo.leaf.text.length; + } + else { + var nextLineInfo = index.lineNumberToInfo(line + 2); + len = nextLineInfo.offset - lineInfo.offset; + } + return ts.createTextSpan(lineInfo.offset, len); + }; + ScriptInfo.prototype.lineOffsetToPosition = function (line, offset) { + var index = this.snap().index; + var lineInfo = index.lineNumberToInfo(line); + return (lineInfo.offset + offset - 1); + }; + ScriptInfo.prototype.positionToLineOffset = function (position) { + var index = this.snap().index; + var lineOffset = index.charOffsetToLineNumberAndPos(position); + return { line: lineOffset.line, offset: lineOffset.offset + 1 }; + }; + return ScriptInfo; + }()); + server.ScriptInfo = ScriptInfo; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + var LSHost = (function () { + function LSHost(host, project, cancellationToken) { + var _this = this; + this.host = host; + this.project = project; + this.cancellationToken = cancellationToken; + this.getCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); + this.resolvedModuleNames = ts.createFileMap(); + this.resolvedTypeReferenceDirectives = ts.createFileMap(); + if (host.trace) { + this.trace = function (s) { return host.trace(s); }; + } + this.resolveModuleName = function (moduleName, containingFile, compilerOptions, host) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); + if (primaryResult.resolvedModule) { + if (ts.fileExtensionIsAny(primaryResult.resolvedModule.resolvedFileName, ts.supportedTypeScriptExtensions)) { + return primaryResult; + } + } + var secondaryLookupFailedLookupLocations = []; + var globalCache = _this.project.projectService.typingsInstaller.globalTypingsCacheLocation; + if (_this.project.getTypingOptions().enableAutoDiscovery && globalCache) { + var traceEnabled = ts.isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + ts.trace(host, ts.Diagnostics.Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2, _this.project.getProjectName(), moduleName, globalCache); + } + var state = { compilerOptions: compilerOptions, host: host, skipTsx: false, traceEnabled: traceEnabled }; + var resolvedName = ts.loadModuleFromNodeModules(moduleName, globalCache, secondaryLookupFailedLookupLocations, state, true); + if (resolvedName) { + return ts.createResolvedModule(resolvedName, true, primaryResult.failedLookupLocations.concat(secondaryLookupFailedLookupLocations)); + } + } + if (!primaryResult.resolvedModule && secondaryLookupFailedLookupLocations.length) { + primaryResult.failedLookupLocations = primaryResult.failedLookupLocations.concat(secondaryLookupFailedLookupLocations); + } + return primaryResult; + }; + } + LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult) { + var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); + var currentResolutionsInFile = cache.get(path); + var newResolutions = ts.createMap(); + var resolvedModules = []; + var compilerOptions = this.getCompilationSettings(); + var lastDeletedFileName = this.project.projectService.lastDeletedFile && this.project.projectService.lastDeletedFile.fileName; + for (var _i = 0, names_3 = names; _i < names_3.length; _i++) { + var name_52 = names_3[_i]; + var resolution = newResolutions[name_52]; + if (!resolution) { + var existingResolution = currentResolutionsInFile && currentResolutionsInFile[name_52]; + if (moduleResolutionIsValid(existingResolution)) { + resolution = existingResolution; + } + else { + newResolutions[name_52] = resolution = loader(name_52, containingFile, compilerOptions, this); + } + } + ts.Debug.assert(resolution !== undefined); + resolvedModules.push(getResult(resolution)); + } + cache.set(path, newResolutions); + return resolvedModules; + function moduleResolutionIsValid(resolution) { + if (!resolution) { + return false; + } + var result = getResult(resolution); + if (result) { + if (result.resolvedFileName && result.resolvedFileName === lastDeletedFileName) { + return false; + } + return true; + } + return resolution.failedLookupLocations.length === 0; + } + }; + LSHost.prototype.getProjectVersion = function () { + return this.project.getProjectVersion(); + }; + LSHost.prototype.getCompilationSettings = function () { + return this.compilationSettings; + }; + LSHost.prototype.useCaseSensitiveFileNames = function () { + return this.host.useCaseSensitiveFileNames; + }; + LSHost.prototype.getCancellationToken = function () { + return this.cancellationToken; + }; + LSHost.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { + return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, function (m) { return m.resolvedTypeReferenceDirective; }); + }; + LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) { + return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, this.resolveModuleName, function (m) { return m.resolvedModule; }); + }; + LSHost.prototype.getDefaultLibFileName = function () { + var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath())); + return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings)); + }; + LSHost.prototype.getScriptSnapshot = function (filename) { + var scriptInfo = this.project.getScriptInfoLSHost(filename); + if (scriptInfo) { + return scriptInfo.snap(); + } + }; + LSHost.prototype.getScriptFileNames = function () { + return this.project.getRootFilesLSHost(); + }; + LSHost.prototype.getTypeRootsVersion = function () { + return this.project.typesVersion; + }; + LSHost.prototype.getScriptKind = function (fileName) { + var info = this.project.getScriptInfoLSHost(fileName); + return info && info.scriptKind; + }; + LSHost.prototype.getScriptVersion = function (filename) { + var info = this.project.getScriptInfoLSHost(filename); + return info && info.getLatestVersion(); + }; + LSHost.prototype.getCurrentDirectory = function () { + return this.host.getCurrentDirectory(); + }; + LSHost.prototype.resolvePath = function (path) { + return this.host.resolvePath(path); + }; + LSHost.prototype.fileExists = function (path) { + return this.host.fileExists(path); + }; + LSHost.prototype.readFile = function (fileName) { + return this.host.readFile(fileName); + }; + LSHost.prototype.directoryExists = function (path) { + return this.host.directoryExists(path); + }; + LSHost.prototype.readDirectory = function (path, extensions, exclude, include) { + return this.host.readDirectory(path, extensions, exclude, include); + }; + LSHost.prototype.getDirectories = function (path) { + return this.host.getDirectories(path); + }; + LSHost.prototype.notifyFileRemoved = function (info) { + this.resolvedModuleNames.remove(info.path); + this.resolvedTypeReferenceDirectives.remove(info.path); + }; + LSHost.prototype.setCompilationSettings = function (opt) { + this.compilationSettings = opt; + this.resolvedModuleNames.clear(); + this.resolvedTypeReferenceDirectives.clear(); + }; + return LSHost; + }()); + server.LSHost = LSHost; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + server.nullTypingsInstaller = { + enqueueInstallTypingsRequest: function () { }, + attach: function (projectService) { }, + onProjectClosed: function (p) { }, + globalTypingsCacheLocation: undefined + }; + var TypingsCacheEntry = (function () { + function TypingsCacheEntry() { + } + return TypingsCacheEntry; + }()); + function setIsEqualTo(arr1, arr2) { + if (arr1 === arr2) { + return true; + } + if ((arr1 || server.emptyArray).length === 0 && (arr2 || server.emptyArray).length === 0) { + return true; + } + var set = ts.createMap(); + var unique = 0; + for (var _i = 0, arr1_1 = arr1; _i < arr1_1.length; _i++) { + var v = arr1_1[_i]; + if (set[v] !== true) { + set[v] = true; + unique++; + } + } + for (var _a = 0, arr2_1 = arr2; _a < arr2_1.length; _a++) { + var v = arr2_1[_a]; + if (!ts.hasProperty(set, v)) { + return false; + } + if (set[v] === true) { + set[v] = false; + unique--; + } + } + return unique === 0; } - server.generateSpaces = generateSpaces; - function generateIndentString(n, editorOptions) { - if (editorOptions.ConvertTabsToSpaces) { - return generateSpaces(n); + function typingOptionsChanged(opt1, opt2) { + return opt1.enableAutoDiscovery !== opt2.enableAutoDiscovery || + !setIsEqualTo(opt1.include, opt2.include) || + !setIsEqualTo(opt1.exclude, opt2.exclude); + } + function compilerOptionsChanged(opt1, opt2) { + return opt1.allowJs != opt2.allowJs; + } + function toTypingsArray(arr) { + arr.sort(); + return arr; + } + var TypingsCache = (function () { + function TypingsCache(installer) { + this.installer = installer; + this.perProjectCache = ts.createMap(); } - else { - var result = ""; - for (var i = 0; i < Math.floor(n / editorOptions.TabSize); i++) { - result += "\t"; + TypingsCache.prototype.getTypingsForProject = function (project, forceRefresh) { + var typingOptions = project.getTypingOptions(); + if (!typingOptions || !typingOptions.enableAutoDiscovery) { + return server.emptyArray; } - for (var i = 0; i < n % editorOptions.TabSize; i++) { - result += " "; + var entry = this.perProjectCache[project.getProjectName()]; + var result = entry ? entry.typings : server.emptyArray; + if (forceRefresh || !entry || typingOptionsChanged(typingOptions, entry.typingOptions) || compilerOptionsChanged(project.getCompilerOptions(), entry.compilerOptions)) { + this.perProjectCache[project.getProjectName()] = { + compilerOptions: project.getCompilerOptions(), + typingOptions: typingOptions, + typings: result, + poisoned: true + }; + this.installer.enqueueInstallTypingsRequest(project, typingOptions); } return result; + }; + TypingsCache.prototype.invalidateCachedTypingsForProject = function (project) { + var typingOptions = project.getTypingOptions(); + if (!typingOptions.enableAutoDiscovery) { + return; + } + this.installer.enqueueInstallTypingsRequest(project, typingOptions); + }; + TypingsCache.prototype.updateTypingsForProject = function (projectName, compilerOptions, typingOptions, newTypings) { + this.perProjectCache[projectName] = { + compilerOptions: compilerOptions, + typingOptions: typingOptions, + typings: toTypingsArray(newTypings), + poisoned: false + }; + }; + TypingsCache.prototype.onProjectClosed = function (project) { + delete this.perProjectCache[project.getProjectName()]; + this.installer.onProjectClosed(project); + }; + return TypingsCache; + }()); + server.TypingsCache = TypingsCache; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + var crypto = require("crypto"); + function shouldEmitFile(scriptInfo) { + return !scriptInfo.hasMixedContent; + } + server.shouldEmitFile = shouldEmitFile; + var BuilderFileInfo = (function () { + function BuilderFileInfo(scriptInfo, project) { + this.scriptInfo = scriptInfo; + this.project = project; + } + BuilderFileInfo.prototype.isExternalModuleOrHasOnlyAmbientExternalModules = function () { + var sourceFile = this.getSourceFile(); + return ts.isExternalModule(sourceFile) || this.containsOnlyAmbientModules(sourceFile); + }; + BuilderFileInfo.prototype.containsOnlyAmbientModules = function (sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (statement.kind !== 225 || statement.name.kind !== 9) { + return false; + } + } + return true; + }; + BuilderFileInfo.prototype.computeHash = function (text) { + return crypto.createHash("md5") + .update(text) + .digest("base64"); + }; + BuilderFileInfo.prototype.getSourceFile = function () { + return this.project.getSourceFile(this.scriptInfo.path); + }; + BuilderFileInfo.prototype.updateShapeSignature = function () { + var sourceFile = this.getSourceFile(); + if (!sourceFile) { + return true; + } + var lastSignature = this.lastCheckedShapeSignature; + if (sourceFile.isDeclarationFile) { + this.lastCheckedShapeSignature = this.computeHash(sourceFile.text); + } + else { + var emitOutput = this.project.getFileEmitOutput(this.scriptInfo, true); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + this.lastCheckedShapeSignature = this.computeHash(emitOutput.outputFiles[0].text); + } + } + return !lastSignature || this.lastCheckedShapeSignature !== lastSignature; + }; + return BuilderFileInfo; + }()); + server.BuilderFileInfo = BuilderFileInfo; + var AbstractBuilder = (function () { + function AbstractBuilder(project, ctor) { + this.project = project; + this.ctor = ctor; + this.fileInfos = ts.createFileMap(); + } + AbstractBuilder.prototype.getFileInfo = function (path) { + return this.fileInfos.get(path); + }; + AbstractBuilder.prototype.getOrCreateFileInfo = function (path) { + var fileInfo = this.getFileInfo(path); + if (!fileInfo) { + var scriptInfo = this.project.getScriptInfo(path); + fileInfo = new this.ctor(scriptInfo, this.project); + this.setFileInfo(path, fileInfo); + } + return fileInfo; + }; + AbstractBuilder.prototype.getFileInfoPaths = function () { + return this.fileInfos.getKeys(); + }; + AbstractBuilder.prototype.setFileInfo = function (path, info) { + this.fileInfos.set(path, info); + }; + AbstractBuilder.prototype.removeFileInfo = function (path) { + this.fileInfos.remove(path); + }; + AbstractBuilder.prototype.forEachFileInfo = function (action) { + this.fileInfos.forEachValue(function (path, value) { return action(value); }); + }; + AbstractBuilder.prototype.emitFile = function (scriptInfo, writeFile) { + var fileInfo = this.getFileInfo(scriptInfo.path); + if (!fileInfo) { + return false; + } + var _a = this.project.getFileEmitOutput(fileInfo.scriptInfo, false), emitSkipped = _a.emitSkipped, outputFiles = _a.outputFiles; + if (!emitSkipped) { + var projectRootPath = this.project.getProjectRootPath(); + for (var _i = 0, outputFiles_1 = outputFiles; _i < outputFiles_1.length; _i++) { + var outputFile = outputFiles_1[_i]; + var outputFileAbsoluteFileName = ts.getNormalizedAbsolutePath(outputFile.name, projectRootPath ? projectRootPath : ts.getDirectoryPath(scriptInfo.fileName)); + writeFile(outputFileAbsoluteFileName, outputFile.text, outputFile.writeByteOrderMark); + } + } + return !emitSkipped; + }; + return AbstractBuilder; + }()); + var NonModuleBuilder = (function (_super) { + __extends(NonModuleBuilder, _super); + function NonModuleBuilder(project) { + var _this = _super.call(this, project, BuilderFileInfo) || this; + _this.project = project; + return _this; + } + NonModuleBuilder.prototype.onProjectUpdateGraph = function () { + }; + NonModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { + var info = this.getOrCreateFileInfo(scriptInfo.path); + var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName]; + if (info.updateShapeSignature()) { + var options = this.project.getCompilerOptions(); + if (options && (options.out || options.outFile)) { + return singleFileResult; + } + return this.project.getAllEmittableFiles(); + } + return singleFileResult; + }; + return NonModuleBuilder; + }(AbstractBuilder)); + var ModuleBuilderFileInfo = (function (_super) { + __extends(ModuleBuilderFileInfo, _super); + function ModuleBuilderFileInfo() { + var _this = _super.apply(this, arguments) || this; + _this.references = []; + _this.referencedBy = []; + return _this; + } + ModuleBuilderFileInfo.compareFileInfos = function (lf, rf) { + var l = lf.scriptInfo.fileName; + var r = rf.scriptInfo.fileName; + return (l < r ? -1 : (l > r ? 1 : 0)); + }; + ; + ModuleBuilderFileInfo.addToReferenceList = function (array, fileInfo) { + if (array.length === 0) { + array.push(fileInfo); + return; + } + var insertIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos); + if (insertIndex < 0) { + array.splice(~insertIndex, 0, fileInfo); + } + }; + ModuleBuilderFileInfo.removeFromReferenceList = function (array, fileInfo) { + if (!array || array.length === 0) { + return; + } + if (array[0] === fileInfo) { + array.splice(0, 1); + return; + } + var removeIndex = ts.binarySearch(array, fileInfo, ModuleBuilderFileInfo.compareFileInfos); + if (removeIndex >= 0) { + array.splice(removeIndex, 1); + } + }; + ModuleBuilderFileInfo.prototype.addReferencedBy = function (fileInfo) { + ModuleBuilderFileInfo.addToReferenceList(this.referencedBy, fileInfo); + }; + ModuleBuilderFileInfo.prototype.removeReferencedBy = function (fileInfo) { + ModuleBuilderFileInfo.removeFromReferenceList(this.referencedBy, fileInfo); + }; + ModuleBuilderFileInfo.prototype.removeFileReferences = function () { + for (var _i = 0, _a = this.references; _i < _a.length; _i++) { + var reference = _a[_i]; + reference.removeReferencedBy(this); + } + this.references = []; + }; + return ModuleBuilderFileInfo; + }(BuilderFileInfo)); + var ModuleBuilder = (function (_super) { + __extends(ModuleBuilder, _super); + function ModuleBuilder(project) { + var _this = _super.call(this, project, ModuleBuilderFileInfo) || this; + _this.project = project; + return _this; + } + ModuleBuilder.prototype.getReferencedFileInfos = function (fileInfo) { + var _this = this; + if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { + return []; + } + var referencedFilePaths = this.project.getReferencedFiles(fileInfo.scriptInfo.path); + if (referencedFilePaths.length > 0) { + return ts.map(referencedFilePaths, function (f) { return _this.getOrCreateFileInfo(f); }).sort(ModuleBuilderFileInfo.compareFileInfos); + } + return []; + }; + ModuleBuilder.prototype.onProjectUpdateGraph = function () { + this.ensureProjectDependencyGraphUpToDate(); + }; + ModuleBuilder.prototype.ensureProjectDependencyGraphUpToDate = function () { + var _this = this; + if (!this.projectVersionForDependencyGraph || this.project.getProjectVersion() !== this.projectVersionForDependencyGraph) { + var currentScriptInfos = this.project.getScriptInfos(); + for (var _i = 0, currentScriptInfos_1 = currentScriptInfos; _i < currentScriptInfos_1.length; _i++) { + var scriptInfo = currentScriptInfos_1[_i]; + var fileInfo = this.getOrCreateFileInfo(scriptInfo.path); + this.updateFileReferences(fileInfo); + } + this.forEachFileInfo(function (fileInfo) { + if (!_this.project.containsScriptInfo(fileInfo.scriptInfo)) { + fileInfo.removeFileReferences(); + _this.removeFileInfo(fileInfo.scriptInfo.path); + } + }); + this.projectVersionForDependencyGraph = this.project.getProjectVersion(); + } + }; + ModuleBuilder.prototype.updateFileReferences = function (fileInfo) { + if (fileInfo.scriptVersionForReferences === fileInfo.scriptInfo.getLatestVersion()) { + return; + } + var newReferences = this.getReferencedFileInfos(fileInfo); + var oldReferences = fileInfo.references; + var oldIndex = 0; + var newIndex = 0; + while (oldIndex < oldReferences.length && newIndex < newReferences.length) { + var oldReference = oldReferences[oldIndex]; + var newReference = newReferences[newIndex]; + var compare = ModuleBuilderFileInfo.compareFileInfos(oldReference, newReference); + if (compare < 0) { + oldReference.removeReferencedBy(fileInfo); + oldIndex++; + } + else if (compare > 0) { + newReference.addReferencedBy(fileInfo); + newIndex++; + } + else { + oldIndex++; + newIndex++; + } + } + for (var i = oldIndex; i < oldReferences.length; i++) { + oldReferences[i].removeReferencedBy(fileInfo); + } + for (var i = newIndex; i < newReferences.length; i++) { + newReferences[i].addReferencedBy(fileInfo); + } + fileInfo.references = newReferences; + fileInfo.scriptVersionForReferences = fileInfo.scriptInfo.getLatestVersion(); + }; + ModuleBuilder.prototype.getFilesAffectedBy = function (scriptInfo) { + this.ensureProjectDependencyGraphUpToDate(); + var singleFileResult = scriptInfo.hasMixedContent ? [] : [scriptInfo.fileName]; + var fileInfo = this.getFileInfo(scriptInfo.path); + if (!fileInfo || !fileInfo.updateShapeSignature()) { + return singleFileResult; + } + if (!fileInfo.isExternalModuleOrHasOnlyAmbientExternalModules()) { + return this.project.getAllEmittableFiles(); + } + var options = this.project.getCompilerOptions(); + if (options && (options.isolatedModules || options.out || options.outFile)) { + return singleFileResult; + } + var queue = fileInfo.referencedBy.slice(0); + var fileNameSet = ts.createMap(); + fileNameSet[scriptInfo.fileName] = scriptInfo; + while (queue.length > 0) { + var processingFileInfo = queue.pop(); + if (processingFileInfo.updateShapeSignature() && processingFileInfo.referencedBy.length > 0) { + for (var _i = 0, _a = processingFileInfo.referencedBy; _i < _a.length; _i++) { + var potentialFileInfo = _a[_i]; + if (!fileNameSet[potentialFileInfo.scriptInfo.fileName]) { + queue.push(potentialFileInfo); + } + } + } + fileNameSet[processingFileInfo.scriptInfo.fileName] = processingFileInfo.scriptInfo; + } + var result = []; + for (var fileName in fileNameSet) { + if (shouldEmitFile(fileNameSet[fileName])) { + result.push(fileName); + } + } + return result; + }; + return ModuleBuilder; + }(AbstractBuilder)); + function createBuilder(project) { + var moduleKind = project.getCompilerOptions().module; + switch (moduleKind) { + case ts.ModuleKind.None: + return new NonModuleBuilder(project); + default: + return new ModuleBuilder(project); } } - server.generateIndentString = generateIndentString; + server.createBuilder = createBuilder; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + (function (ProjectKind) { + ProjectKind[ProjectKind["Inferred"] = 0] = "Inferred"; + ProjectKind[ProjectKind["Configured"] = 1] = "Configured"; + ProjectKind[ProjectKind["External"] = 2] = "External"; + })(server.ProjectKind || (server.ProjectKind = {})); + var ProjectKind = server.ProjectKind; + function remove(items, item) { + var index = items.indexOf(item); + if (index >= 0) { + items.splice(index, 1); + } + } + function countEachFileTypes(infos) { + var result = { js: 0, jsx: 0, ts: 0, tsx: 0, dts: 0 }; + for (var _i = 0, infos_1 = infos; _i < infos_1.length; _i++) { + var info = infos_1[_i]; + switch (info.scriptKind) { + case 1: + result.js += 1; + break; + case 2: + result.jsx += 1; + break; + case 3: + ts.fileExtensionIs(info.fileName, ".d.ts") + ? result.dts += 1 + : result.ts += 1; + break; + case 4: + result.tsx += 1; + break; + } + } + return result; + } + function hasOneOrMoreJsAndNoTsFiles(project) { + var counts = countEachFileTypes(project.getScriptInfos()); + return counts.js > 0 && counts.ts === 0 && counts.tsx === 0; + } + function allRootFilesAreJsOrDts(project) { + var counts = countEachFileTypes(project.getRootScriptInfos()); + return counts.ts === 0 && counts.tsx === 0; + } + server.allRootFilesAreJsOrDts = allRootFilesAreJsOrDts; + function allFilesAreJsOrDts(project) { + var counts = countEachFileTypes(project.getScriptInfos()); + return counts.ts === 0 && counts.tsx === 0; + } + server.allFilesAreJsOrDts = allFilesAreJsOrDts; + var Project = (function () { + function Project(projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) { + this.projectKind = projectKind; + this.projectService = projectService; + this.documentRegistry = documentRegistry; + this.languageServiceEnabled = languageServiceEnabled; + this.compilerOptions = compilerOptions; + this.compileOnSaveEnabled = compileOnSaveEnabled; + this.rootFiles = []; + this.rootFilesMap = ts.createFileMap(); + this.lastReportedVersion = 0; + this.projectStructureVersion = 0; + this.projectStateVersion = 0; + this.typesVersion = 0; + if (!this.compilerOptions) { + this.compilerOptions = ts.getDefaultCompilerOptions(); + this.compilerOptions.allowNonTsExtensions = true; + this.compilerOptions.allowJs = true; + } + else if (hasExplicitListOfFiles) { + this.compilerOptions.allowNonTsExtensions = true; + } + if (languageServiceEnabled) { + this.enableLanguageService(); + } + else { + this.disableLanguageService(); + } + this.builder = server.createBuilder(this); + this.markAsDirty(); + } + Project.prototype.isNonTsProject = function () { + this.updateGraph(); + return allFilesAreJsOrDts(this); + }; + Project.prototype.isJsOnlyProject = function () { + this.updateGraph(); + return hasOneOrMoreJsAndNoTsFiles(this); + }; + Project.prototype.getProjectErrors = function () { + return this.projectErrors; + }; + Project.prototype.getLanguageService = function (ensureSynchronized) { + if (ensureSynchronized === void 0) { ensureSynchronized = true; } + if (ensureSynchronized) { + this.updateGraph(); + } + return this.languageService; + }; + Project.prototype.getCompileOnSaveAffectedFileList = function (scriptInfo) { + if (!this.languageServiceEnabled) { + return []; + } + this.updateGraph(); + return this.builder.getFilesAffectedBy(scriptInfo); + }; + Project.prototype.getProjectVersion = function () { + return this.projectStateVersion.toString(); + }; + Project.prototype.enableLanguageService = function () { + var lsHost = new server.LSHost(this.projectService.host, this, this.projectService.cancellationToken); + lsHost.setCompilationSettings(this.compilerOptions); + this.languageService = ts.createLanguageService(lsHost, this.documentRegistry); + this.lsHost = lsHost; + this.languageServiceEnabled = true; + }; + Project.prototype.disableLanguageService = function () { + this.languageService = server.nullLanguageService; + this.lsHost = server.nullLanguageServiceHost; + this.languageServiceEnabled = false; + }; + Project.prototype.getSourceFile = function (path) { + if (!this.program) { + return undefined; + } + return this.program.getSourceFileByPath(path); + }; + Project.prototype.updateTypes = function () { + this.typesVersion++; + this.markAsDirty(); + this.updateGraph(); + }; + Project.prototype.close = function () { + if (this.program) { + for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { + var f = _a[_i]; + var info = this.projectService.getScriptInfo(f.fileName); + info.detachFromProject(this); + } + } + else { + for (var _b = 0, _c = this.rootFiles; _b < _c.length; _b++) { + var root = _c[_b]; + root.detachFromProject(this); + } + } + this.rootFiles = undefined; + this.rootFilesMap = undefined; + this.program = undefined; + this.languageService.dispose(); + }; + Project.prototype.getCompilerOptions = function () { + return this.compilerOptions; + }; + Project.prototype.hasRoots = function () { + return this.rootFiles && this.rootFiles.length > 0; + }; + Project.prototype.getRootFiles = function () { + return this.rootFiles && this.rootFiles.map(function (info) { return info.fileName; }); + }; + Project.prototype.getRootFilesLSHost = function () { + var result = []; + if (this.rootFiles) { + for (var _i = 0, _a = this.rootFiles; _i < _a.length; _i++) { + var f = _a[_i]; + result.push(f.fileName); + } + if (this.typingFiles) { + for (var _b = 0, _c = this.typingFiles; _b < _c.length; _b++) { + var f = _c[_b]; + result.push(f); + } + } + } + return result; + }; + Project.prototype.getRootScriptInfos = function () { + return this.rootFiles; + }; + Project.prototype.getScriptInfos = function () { + var _this = this; + return ts.map(this.program.getSourceFiles(), function (sourceFile) { + var scriptInfo = _this.projectService.getScriptInfoForPath(sourceFile.path); + if (!scriptInfo) { + ts.Debug.assert(false, "scriptInfo for a file '" + sourceFile.fileName + "' is missing."); + } + return scriptInfo; + }); + }; + Project.prototype.getFileEmitOutput = function (info, emitOnlyDtsFiles) { + if (!this.languageServiceEnabled) { + return undefined; + } + return this.getLanguageService().getEmitOutput(info.fileName, emitOnlyDtsFiles); + }; + Project.prototype.getFileNames = function () { + if (!this.program) { + return []; + } + if (!this.languageServiceEnabled) { + var rootFiles = this.getRootFiles(); + if (this.compilerOptions) { + var defaultLibrary = ts.getDefaultLibFilePath(this.compilerOptions); + if (defaultLibrary) { + (rootFiles || (rootFiles = [])).push(server.asNormalizedPath(defaultLibrary)); + } + } + return rootFiles; + } + var sourceFiles = this.program.getSourceFiles(); + return sourceFiles.map(function (sourceFile) { return server.asNormalizedPath(sourceFile.fileName); }); + }; + Project.prototype.getAllEmittableFiles = function () { + if (!this.languageServiceEnabled) { + return []; + } + var defaultLibraryFileName = ts.getDefaultLibFileName(this.compilerOptions); + var infos = this.getScriptInfos(); + var result = []; + for (var _i = 0, infos_2 = infos; _i < infos_2.length; _i++) { + var info = infos_2[_i]; + if (ts.getBaseFileName(info.fileName) !== defaultLibraryFileName && server.shouldEmitFile(info)) { + result.push(info.fileName); + } + } + return result; + }; + Project.prototype.containsScriptInfo = function (info) { + return this.isRoot(info) || (this.program && this.program.getSourceFileByPath(info.path) !== undefined); + }; + Project.prototype.containsFile = function (filename, requireOpen) { + var info = this.projectService.getScriptInfoForNormalizedPath(filename); + if (info && (info.isOpen || !requireOpen)) { + return this.containsScriptInfo(info); + } + }; + Project.prototype.isRoot = function (info) { + return this.rootFilesMap && this.rootFilesMap.contains(info.path); + }; + Project.prototype.addRoot = function (info) { + if (!this.isRoot(info)) { + this.rootFiles.push(info); + this.rootFilesMap.set(info.path, info); + info.attachToProject(this); + this.markAsDirty(); + } + }; + Project.prototype.removeFile = function (info, detachFromProject) { + if (detachFromProject === void 0) { detachFromProject = true; } + this.removeRootFileIfNecessary(info); + this.lsHost.notifyFileRemoved(info); + if (detachFromProject) { + info.detachFromProject(this); + } + this.markAsDirty(); + }; + Project.prototype.markAsDirty = function () { + this.projectStateVersion++; + }; + Project.prototype.updateGraph = function () { + if (!this.languageServiceEnabled) { + return true; + } + var hasChanges = this.updateGraphWorker(); + var cachedTypings = this.projectService.typingsCache.getTypingsForProject(this, hasChanges); + if (this.setTypings(cachedTypings)) { + hasChanges = this.updateGraphWorker() || hasChanges; + } + if (hasChanges) { + this.projectStructureVersion++; + } + return !hasChanges; + }; + Project.prototype.setTypings = function (typings) { + if (ts.arrayIsEqualTo(this.typingFiles, typings)) { + return false; + } + this.typingFiles = typings; + this.markAsDirty(); + return true; + }; + Project.prototype.updateGraphWorker = function () { + var oldProgram = this.program; + this.program = this.languageService.getProgram(); + var hasChanges = false; + if (!oldProgram || (this.program !== oldProgram && !oldProgram.structureIsReused)) { + hasChanges = true; + if (oldProgram) { + for (var _i = 0, _a = oldProgram.getSourceFiles(); _i < _a.length; _i++) { + var f = _a[_i]; + if (this.program.getSourceFileByPath(f.path)) { + continue; + } + var scriptInfoToDetach = this.projectService.getScriptInfo(f.fileName); + if (scriptInfoToDetach) { + scriptInfoToDetach.detachFromProject(this); + } + } + } + } + this.builder.onProjectUpdateGraph(); + return hasChanges; + }; + Project.prototype.getScriptInfoLSHost = function (fileName) { + var scriptInfo = this.projectService.getOrCreateScriptInfo(fileName, false); + if (scriptInfo) { + scriptInfo.attachToProject(this); + } + return scriptInfo; + }; + Project.prototype.getScriptInfoForNormalizedPath = function (fileName) { + var scriptInfo = this.projectService.getOrCreateScriptInfoForNormalizedPath(fileName, false); + if (scriptInfo && !scriptInfo.isAttached(this)) { + return server.Errors.ThrowProjectDoesNotContainDocument(fileName, this); + } + return scriptInfo; + }; + Project.prototype.getScriptInfo = function (uncheckedFileName) { + return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + }; + Project.prototype.filesToString = function () { + if (!this.program) { + return ""; + } + var strBuilder = ""; + for (var _i = 0, _a = this.program.getSourceFiles(); _i < _a.length; _i++) { + var file = _a[_i]; + strBuilder += file.fileName + "\n"; + } + return strBuilder; + }; + Project.prototype.setCompilerOptions = function (compilerOptions) { + if (compilerOptions) { + if (this.projectKind === ProjectKind.Inferred) { + compilerOptions.allowJs = true; + } + compilerOptions.allowNonTsExtensions = true; + this.compilerOptions = compilerOptions; + this.lsHost.setCompilationSettings(compilerOptions); + this.markAsDirty(); + } + }; + Project.prototype.reloadScript = function (filename) { + var script = this.projectService.getScriptInfoForNormalizedPath(filename); + if (script) { + ts.Debug.assert(script.isAttached(this)); + script.reloadFromFile(); + return true; + } + return false; + }; + Project.prototype.getChangesSinceVersion = function (lastKnownVersion) { + this.updateGraph(); + var info = { + projectName: this.getProjectName(), + version: this.projectStructureVersion, + isInferred: this.projectKind === ProjectKind.Inferred, + options: this.getCompilerOptions() + }; + if (this.lastReportedFileNames && lastKnownVersion === this.lastReportedVersion) { + if (this.projectStructureVersion == this.lastReportedVersion) { + return { info: info, projectErrors: this.projectErrors }; + } + var lastReportedFileNames = this.lastReportedFileNames; + var currentFiles = ts.arrayToMap(this.getFileNames(), function (x) { return x; }); + var added = []; + var removed = []; + for (var id in currentFiles) { + if (!ts.hasProperty(lastReportedFileNames, id)) { + added.push(id); + } + } + for (var id in lastReportedFileNames) { + if (!ts.hasProperty(currentFiles, id)) { + removed.push(id); + } + } + this.lastReportedFileNames = currentFiles; + this.lastReportedVersion = this.projectStructureVersion; + return { info: info, changes: { added: added, removed: removed }, projectErrors: this.projectErrors }; + } + else { + var projectFileNames = this.getFileNames(); + this.lastReportedFileNames = ts.arrayToMap(projectFileNames, function (x) { return x; }); + this.lastReportedVersion = this.projectStructureVersion; + return { info: info, files: projectFileNames, projectErrors: this.projectErrors }; + } + }; + Project.prototype.getReferencedFiles = function (path) { + var _this = this; + if (!this.languageServiceEnabled) { + return []; + } + var sourceFile = this.getSourceFile(path); + if (!sourceFile) { + return []; + } + var referencedFiles = ts.createMap(); + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = this.program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = symbol.declarations[0].getSourceFile(); + if (declarationSourceFile) { + referencedFiles[declarationSourceFile.path] = true; + } + } + } + } + var currentDirectory = ts.getDirectoryPath(path); + var getCanonicalFileName = ts.createGetCanonicalFileName(this.projectService.host.useCaseSensitiveFileNames); + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, currentDirectory, getCanonicalFileName); + referencedFiles[referencedPath] = true; + } + } + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + for (var typeName in sourceFile.resolvedTypeReferenceDirectiveNames) { + var resolvedTypeReferenceDirective = sourceFile.resolvedTypeReferenceDirectiveNames[typeName]; + if (!resolvedTypeReferenceDirective) { + continue; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var typeFilePath = ts.toPath(fileName, currentDirectory, getCanonicalFileName); + referencedFiles[typeFilePath] = true; + } + } + var allFileNames = ts.map(Object.keys(referencedFiles), function (key) { return key; }); + return ts.filter(allFileNames, function (file) { return _this.projectService.host.fileExists(file); }); + }; + Project.prototype.removeRootFileIfNecessary = function (info) { + if (this.isRoot(info)) { + remove(this.rootFiles, info); + this.rootFilesMap.remove(info.path); + } + }; + return Project; + }()); + server.Project = Project; + var InferredProject = (function (_super) { + __extends(InferredProject, _super); + function InferredProject(projectService, documentRegistry, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) { + var _this = _super.call(this, ProjectKind.Inferred, projectService, documentRegistry, undefined, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) || this; + _this.compileOnSaveEnabled = compileOnSaveEnabled; + _this.directoriesWatchedForTsconfig = []; + _this.inferredProjectName = server.makeInferredProjectName(InferredProject.NextId); + InferredProject.NextId++; + return _this; + } + InferredProject.prototype.getProjectName = function () { + return this.inferredProjectName; + }; + InferredProject.prototype.getProjectRootPath = function () { + if (this.projectService.useSingleInferredProject) { + return undefined; + } + var rootFiles = this.getRootFiles(); + return ts.getDirectoryPath(rootFiles[0]); + }; + InferredProject.prototype.close = function () { + _super.prototype.close.call(this); + for (var _i = 0, _a = this.directoriesWatchedForTsconfig; _i < _a.length; _i++) { + var directory = _a[_i]; + this.projectService.stopWatchingDirectory(directory); + } + }; + InferredProject.prototype.getTypingOptions = function () { + return { + enableAutoDiscovery: allRootFilesAreJsOrDts(this), + include: [], + exclude: [] + }; + }; + return InferredProject; + }(Project)); + InferredProject.NextId = 1; + server.InferredProject = InferredProject; + var ConfiguredProject = (function (_super) { + __extends(ConfiguredProject, _super); + function ConfiguredProject(configFileName, projectService, documentRegistry, hasExplicitListOfFiles, compilerOptions, wildcardDirectories, languageServiceEnabled, compileOnSaveEnabled) { + var _this = _super.call(this, ProjectKind.Configured, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) || this; + _this.configFileName = configFileName; + _this.wildcardDirectories = wildcardDirectories; + _this.compileOnSaveEnabled = compileOnSaveEnabled; + _this.openRefCount = 0; + return _this; + } + ConfiguredProject.prototype.getProjectRootPath = function () { + return ts.getDirectoryPath(this.configFileName); + }; + ConfiguredProject.prototype.setProjectErrors = function (projectErrors) { + this.projectErrors = projectErrors; + }; + ConfiguredProject.prototype.setTypingOptions = function (newTypingOptions) { + this.typingOptions = newTypingOptions; + }; + ConfiguredProject.prototype.getTypingOptions = function () { + return this.typingOptions; + }; + ConfiguredProject.prototype.getProjectName = function () { + return this.configFileName; + }; + ConfiguredProject.prototype.watchConfigFile = function (callback) { + var _this = this; + this.projectFileWatcher = this.projectService.host.watchFile(this.configFileName, function (_) { return callback(_this); }); + }; + ConfiguredProject.prototype.watchTypeRoots = function (callback) { + var _this = this; + var roots = this.getEffectiveTypeRoots(); + var watchers = []; + for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) { + var root = roots_1[_i]; + this.projectService.logger.info("Add type root watcher for: " + root); + watchers.push(this.projectService.host.watchDirectory(root, function (path) { return callback(_this, path); }, false)); + } + this.typeRootsWatchers = watchers; + }; + ConfiguredProject.prototype.watchConfigDirectory = function (callback) { + var _this = this; + if (this.directoryWatcher) { + return; + } + var directoryToWatch = ts.getDirectoryPath(this.configFileName); + this.projectService.logger.info("Add recursive watcher for: " + directoryToWatch); + this.directoryWatcher = this.projectService.host.watchDirectory(directoryToWatch, function (path) { return callback(_this, path); }, true); + }; + ConfiguredProject.prototype.watchWildcards = function (callback) { + var _this = this; + if (!this.wildcardDirectories) { + return; + } + var configDirectoryPath = ts.getDirectoryPath(this.configFileName); + this.directoriesWatchedForWildcards = ts.reduceProperties(this.wildcardDirectories, function (watchers, flag, directory) { + if (ts.comparePaths(configDirectoryPath, directory, ".", !_this.projectService.host.useCaseSensitiveFileNames) !== 0) { + var recursive = (flag & 1) !== 0; + _this.projectService.logger.info("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); + watchers[directory] = _this.projectService.host.watchDirectory(directory, function (path) { return callback(_this, path); }, recursive); + } + return watchers; + }, {}); + }; + ConfiguredProject.prototype.stopWatchingDirectory = function () { + if (this.directoryWatcher) { + this.directoryWatcher.close(); + this.directoryWatcher = undefined; + } + }; + ConfiguredProject.prototype.close = function () { + _super.prototype.close.call(this); + if (this.projectFileWatcher) { + this.projectFileWatcher.close(); + } + if (this.typeRootsWatchers) { + for (var _i = 0, _a = this.typeRootsWatchers; _i < _a.length; _i++) { + var watcher = _a[_i]; + watcher.close(); + } + this.typeRootsWatchers = undefined; + } + for (var id in this.directoriesWatchedForWildcards) { + this.directoriesWatchedForWildcards[id].close(); + } + this.directoriesWatchedForWildcards = undefined; + this.stopWatchingDirectory(); + }; + ConfiguredProject.prototype.addOpenRef = function () { + this.openRefCount++; + }; + ConfiguredProject.prototype.deleteOpenRef = function () { + this.openRefCount--; + return this.openRefCount; + }; + ConfiguredProject.prototype.getEffectiveTypeRoots = function () { + return ts.getEffectiveTypeRoots(this.getCompilerOptions(), this.projectService.host) || []; + }; + return ConfiguredProject; + }(Project)); + server.ConfiguredProject = ConfiguredProject; + var ExternalProject = (function (_super) { + __extends(ExternalProject, _super); + function ExternalProject(externalProjectName, projectService, documentRegistry, compilerOptions, languageServiceEnabled, compileOnSaveEnabled, projectFilePath) { + var _this = _super.call(this, ProjectKind.External, projectService, documentRegistry, true, languageServiceEnabled, compilerOptions, compileOnSaveEnabled) || this; + _this.externalProjectName = externalProjectName; + _this.compileOnSaveEnabled = compileOnSaveEnabled; + _this.projectFilePath = projectFilePath; + return _this; + } + ExternalProject.prototype.getProjectRootPath = function () { + if (this.projectFilePath) { + return ts.getDirectoryPath(this.projectFilePath); + } + return ts.getDirectoryPath(ts.normalizeSlashes(this.externalProjectName)); + }; + ExternalProject.prototype.getTypingOptions = function () { + return this.typingOptions; + }; + ExternalProject.prototype.setProjectErrors = function (projectErrors) { + this.projectErrors = projectErrors; + }; + ExternalProject.prototype.setTypingOptions = function (newTypingOptions) { + if (!newTypingOptions) { + newTypingOptions = { + enableAutoDiscovery: allRootFilesAreJsOrDts(this), + include: [], + exclude: [] + }; + } + else { + if (newTypingOptions.enableAutoDiscovery === undefined) { + newTypingOptions.enableAutoDiscovery = allRootFilesAreJsOrDts(this); + } + if (!newTypingOptions.include) { + newTypingOptions.include = []; + } + if (!newTypingOptions.exclude) { + newTypingOptions.exclude = []; + } + } + this.typingOptions = newTypingOptions; + }; + ExternalProject.prototype.getProjectName = function () { + return this.externalProjectName; + }; + return ExternalProject; + }(Project)); + server.ExternalProject = ExternalProject; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; + function combineProjectOutput(projects, action, comparer, areEqual) { + var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer); + return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; + } + server.combineProjectOutput = combineProjectOutput; + var fileNamePropertyReader = { + getFileName: function (x) { return x; }, + getScriptKind: function (_) { return undefined; }, + hasMixedContent: function (_) { return false; } + }; + var externalFilePropertyReader = { + getFileName: function (x) { return x.fileName; }, + getScriptKind: function (x) { return x.scriptKind; }, + hasMixedContent: function (x) { return x.hasMixedContent; } + }; + function findProjectByName(projectName, projects) { + for (var _i = 0, projects_1 = projects; _i < projects_1.length; _i++) { + var proj = projects_1[_i]; + if (proj.getProjectName() === projectName) { + return proj; + } + } + } + function createFileNotFoundDiagnostic(fileName) { + return ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, fileName); + } + function isRootFileInInferredProject(info) { + if (info.containingProjects.length === 0) { + return false; + } + return info.containingProjects[0].projectKind === server.ProjectKind.Inferred && info.containingProjects[0].isRoot(info); + } + var DirectoryWatchers = (function () { + function DirectoryWatchers(projectService) { + this.projectService = projectService; + this.directoryWatchersForTsconfig = ts.createMap(); + this.directoryWatchersRefCount = ts.createMap(); + } + DirectoryWatchers.prototype.stopWatchingDirectory = function (directory) { + this.directoryWatchersRefCount[directory]--; + if (this.directoryWatchersRefCount[directory] === 0) { + this.projectService.logger.info("Close directory watcher for: " + directory); + this.directoryWatchersForTsconfig[directory].close(); + delete this.directoryWatchersForTsconfig[directory]; + } + }; + DirectoryWatchers.prototype.startWatchingContainingDirectoriesForFile = function (fileName, project, callback) { + var currentPath = ts.getDirectoryPath(fileName); + var parentPath = ts.getDirectoryPath(currentPath); + while (currentPath != parentPath) { + if (!this.directoryWatchersForTsconfig[currentPath]) { + this.projectService.logger.info("Add watcher for: " + currentPath); + this.directoryWatchersForTsconfig[currentPath] = this.projectService.host.watchDirectory(currentPath, callback); + this.directoryWatchersRefCount[currentPath] = 1; + } + else { + this.directoryWatchersRefCount[currentPath] += 1; + } + project.directoriesWatchedForTsconfig.push(currentPath); + currentPath = parentPath; + parentPath = ts.getDirectoryPath(parentPath); + } + }; + return DirectoryWatchers; + }()); + var ProjectService = (function () { + function ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, eventHandler) { + if (typingsInstaller === void 0) { typingsInstaller = server.nullTypingsInstaller; } + this.host = host; + this.logger = logger; + this.cancellationToken = cancellationToken; + this.useSingleInferredProject = useSingleInferredProject; + this.typingsInstaller = typingsInstaller; + this.eventHandler = eventHandler; + this.filenameToScriptInfo = ts.createFileMap(); + this.externalProjectToConfiguredProjectMap = ts.createMap(); + this.externalProjects = []; + this.inferredProjects = []; + this.configuredProjects = []; + this.openFiles = []; + this.toCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); + this.directoryWatchers = new DirectoryWatchers(this); + this.throttledOperations = new server.ThrottledOperations(host); + this.typingsInstaller.attach(this); + this.typingsCache = new server.TypingsCache(this.typingsInstaller); + this.hostConfiguration = { + formatCodeOptions: server.getDefaultFormatCodeSettings(this.host), + hostInfo: "Unknown host" + }; + this.documentRegistry = ts.createDocumentRegistry(host.useCaseSensitiveFileNames, host.getCurrentDirectory()); + } + ProjectService.prototype.getChangedFiles_TestOnly = function () { + return this.changedFiles; + }; + ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () { + this.ensureInferredProjectsUpToDate(); + }; + ProjectService.prototype.updateTypingsForProject = function (response) { + var project = this.findProject(response.projectName); + if (!project) { + return; + } + switch (response.kind) { + case "set": + this.typingsCache.updateTypingsForProject(response.projectName, response.compilerOptions, response.typingOptions, response.typings); + project.updateGraph(); + break; + case "invalidate": + this.typingsCache.invalidateCachedTypingsForProject(project); + break; + } + }; + ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions) { + this.compilerOptionsForInferredProjects = projectCompilerOptions; + this.compileOnSaveForInferredProjects = projectCompilerOptions.compileOnSave; + for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { + var proj = _a[_i]; + proj.setCompilerOptions(projectCompilerOptions); + proj.compileOnSaveEnabled = projectCompilerOptions.compileOnSave; + } + this.updateProjectGraphs(this.inferredProjects); + }; + ProjectService.prototype.stopWatchingDirectory = function (directory) { + this.directoryWatchers.stopWatchingDirectory(directory); + }; + ProjectService.prototype.findProject = function (projectName) { + if (projectName === undefined) { + return undefined; + } + if (server.isInferredProjectName(projectName)) { + this.ensureInferredProjectsUpToDate(); + return findProjectByName(projectName, this.inferredProjects); + } + return this.findExternalProjectByProjectName(projectName) || this.findConfiguredProjectByProjectName(server.toNormalizedPath(projectName)); + }; + ProjectService.prototype.getDefaultProjectForFile = function (fileName, refreshInferredProjects) { + if (refreshInferredProjects) { + this.ensureInferredProjectsUpToDate(); + } + var scriptInfo = this.getScriptInfoForNormalizedPath(fileName); + return scriptInfo && scriptInfo.getDefaultProject(); + }; + ProjectService.prototype.ensureInferredProjectsUpToDate = function () { + if (this.changedFiles) { + var projectsToUpdate = void 0; + if (this.changedFiles.length === 1) { + projectsToUpdate = this.changedFiles[0].containingProjects; + } + else { + projectsToUpdate = []; + for (var _i = 0, _a = this.changedFiles; _i < _a.length; _i++) { + var f = _a[_i]; + projectsToUpdate = projectsToUpdate.concat(f.containingProjects); + } + } + this.updateProjectGraphs(projectsToUpdate); + this.changedFiles = undefined; + } + }; + ProjectService.prototype.findContainingExternalProject = function (fileName) { + for (var _i = 0, _a = this.externalProjects; _i < _a.length; _i++) { + var proj = _a[_i]; + if (proj.containsFile(fileName)) { + return proj; + } + } + return undefined; + }; + ProjectService.prototype.getFormatCodeOptions = function (file) { + var formatCodeSettings; + if (file) { + var info = this.getScriptInfoForNormalizedPath(file); + if (info) { + formatCodeSettings = info.getFormatCodeSettings(); + } + } + return formatCodeSettings || this.hostConfiguration.formatCodeOptions; + }; + ProjectService.prototype.updateProjectGraphs = function (projects) { + var shouldRefreshInferredProjects = false; + for (var _i = 0, projects_2 = projects; _i < projects_2.length; _i++) { + var p = projects_2[_i]; + if (!p.updateGraph()) { + shouldRefreshInferredProjects = true; + } + } + if (shouldRefreshInferredProjects) { + this.refreshInferredProjects(); + } + }; + ProjectService.prototype.onSourceFileChanged = function (fileName) { + var info = this.getScriptInfoForNormalizedPath(fileName); + if (!info) { + this.logger.info("Error: got watch notification for unknown file: " + fileName); + return; + } + if (!this.host.fileExists(fileName)) { + this.handleDeletedFile(info); + } + else { + if (info && (!info.isOpen)) { + info.reloadFromFile(); + this.updateProjectGraphs(info.containingProjects); + } + } + }; + ProjectService.prototype.handleDeletedFile = function (info) { + this.logger.info(info.fileName + " deleted"); + info.stopWatcher(); + if (!info.isOpen) { + this.filenameToScriptInfo.remove(info.path); + this.lastDeletedFile = info; + var containingProjects = info.containingProjects.slice(); + info.detachAllProjects(); + this.updateProjectGraphs(containingProjects); + this.lastDeletedFile = undefined; + if (!this.eventHandler) { + return; + } + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var openFile = _a[_i]; + this.eventHandler({ eventName: "context", data: { project: openFile.getDefaultProject(), fileName: openFile.fileName } }); + } + } + this.printProjects(); + }; + ProjectService.prototype.onTypeRootFileChanged = function (project, fileName) { + var _this = this; + this.logger.info("Type root file " + fileName + " changed"); + this.throttledOperations.schedule(project.configFileName + " * type root", 250, function () { + project.updateTypes(); + _this.updateConfiguredProject(project); + _this.refreshInferredProjects(); + }); + }; + ProjectService.prototype.onSourceFileInDirectoryChangedForConfiguredProject = function (project, fileName) { + var _this = this; + if (fileName && !ts.isSupportedSourceFileName(fileName, project.getCompilerOptions())) { + return; + } + this.logger.info("Detected source file changes: " + fileName); + this.throttledOperations.schedule(project.configFileName, 250, function () { return _this.handleChangeInSourceFileForConfiguredProject(project); }); + }; + ProjectService.prototype.handleChangeInSourceFileForConfiguredProject = function (project) { + var _this = this; + var _a = this.convertConfigFileContentToProjectOptions(project.configFileName), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors; + this.reportConfigFileDiagnostics(project.getProjectName(), configFileErrors); + var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); })); + var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); })); + if (!ts.arrayIsEqualTo(currentRootFiles.sort(), newRootFiles.sort())) { + this.logger.info("Updating configured project"); + this.updateConfiguredProject(project); + this.refreshInferredProjects(); + } + }; + ProjectService.prototype.onConfigChangedForConfiguredProject = function (project) { + this.logger.info("Config file changed: " + project.configFileName); + this.updateConfiguredProject(project); + this.refreshInferredProjects(); + }; + ProjectService.prototype.onConfigFileAddedForInferredProject = function (fileName) { + if (ts.getBaseFileName(fileName) != "tsconfig.json") { + this.logger.info(fileName + " is not tsconfig.json"); + return; + } + var configFileErrors = this.convertConfigFileContentToProjectOptions(fileName).configFileErrors; + this.reportConfigFileDiagnostics(fileName, configFileErrors); + this.logger.info("Detected newly added tsconfig file: " + fileName); + this.reloadProjects(); + }; + ProjectService.prototype.getCanonicalFileName = function (fileName) { + var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); + return ts.normalizePath(name); + }; + ProjectService.prototype.removeProject = function (project) { + this.logger.info("remove project: " + project.getRootFiles().toString()); + project.close(); + switch (project.projectKind) { + case server.ProjectKind.External: + server.removeItemFromSet(this.externalProjects, project); + break; + case server.ProjectKind.Configured: + server.removeItemFromSet(this.configuredProjects, project); + break; + case server.ProjectKind.Inferred: + server.removeItemFromSet(this.inferredProjects, project); + break; + } + }; + ProjectService.prototype.assignScriptInfoToInferredProjectIfNecessary = function (info, addToListOfOpenFiles) { + var externalProject = this.findContainingExternalProject(info.fileName); + if (externalProject) { + if (addToListOfOpenFiles) { + this.openFiles.push(info); + } + return; + } + var foundConfiguredProject = false; + for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + if (p.projectKind === server.ProjectKind.Configured) { + foundConfiguredProject = true; + if (addToListOfOpenFiles) { + (p).addOpenRef(); + } + } + } + if (foundConfiguredProject) { + if (addToListOfOpenFiles) { + this.openFiles.push(info); + } + return; + } + if (info.containingProjects.length === 0) { + var inferredProject = this.createInferredProjectWithRootFileIfNecessary(info); + if (!this.useSingleInferredProject) { + for (var _b = 0, _c = this.openFiles; _b < _c.length; _b++) { + var f = _c[_b]; + if (f.containingProjects.length === 0) { + continue; + } + var defaultProject = f.getDefaultProject(); + if (isRootFileInInferredProject(info) && defaultProject !== inferredProject && inferredProject.containsScriptInfo(f)) { + this.removeProject(defaultProject); + f.attachToProject(inferredProject); + } + } + } + } + if (addToListOfOpenFiles) { + this.openFiles.push(info); + } + }; + ProjectService.prototype.closeOpenFile = function (info) { + info.reloadFromFile(); + server.removeItemFromSet(this.openFiles, info); + info.isOpen = false; + var projectsToRemove; + for (var _i = 0, _a = info.containingProjects; _i < _a.length; _i++) { + var p = _a[_i]; + if (p.projectKind === server.ProjectKind.Configured) { + if (p.deleteOpenRef() === 0) { + (projectsToRemove || (projectsToRemove = [])).push(p); + } + } + else if (p.projectKind === server.ProjectKind.Inferred && p.isRoot(info)) { + (projectsToRemove || (projectsToRemove = [])).push(p); + } + } + if (projectsToRemove) { + for (var _b = 0, projectsToRemove_1 = projectsToRemove; _b < projectsToRemove_1.length; _b++) { + var project = projectsToRemove_1[_b]; + this.removeProject(project); + } + var orphanFiles = void 0; + for (var _c = 0, _d = this.openFiles; _c < _d.length; _c++) { + var f = _d[_c]; + if (f.containingProjects.length === 0) { + (orphanFiles || (orphanFiles = [])).push(f); + } + } + if (orphanFiles) { + for (var _e = 0, orphanFiles_1 = orphanFiles; _e < orphanFiles_1.length; _e++) { + var f = orphanFiles_1[_e]; + this.assignScriptInfoToInferredProjectIfNecessary(f, false); + } + } + } + if (info.containingProjects.length === 0) { + this.filenameToScriptInfo.remove(info.path); + } + }; + ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName) { + var searchPath = ts.getDirectoryPath(fileName); + this.logger.info("Search path: " + searchPath); + var configFileName = this.findConfigFile(server.asNormalizedPath(searchPath)); + if (!configFileName) { + this.logger.info("No config files found."); + return {}; + } + this.logger.info("Config file name: " + configFileName); + var project = this.findConfiguredProjectByProjectName(configFileName); + if (!project) { + var _a = this.openConfigFile(configFileName, fileName), success = _a.success, errors = _a.errors; + if (!success) { + return { configFileName: configFileName, configFileErrors: errors }; + } + this.logger.info("Opened configuration file " + configFileName); + if (errors && errors.length > 0) { + return { configFileName: configFileName, configFileErrors: errors }; + } + } + else { + this.updateConfiguredProject(project); + } + return { configFileName: configFileName }; + }; + ProjectService.prototype.findConfigFile = function (searchPath) { + while (true) { + var tsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "tsconfig.json")); + if (this.host.fileExists(tsconfigFileName)) { + return tsconfigFileName; + } + var jsconfigFileName = server.asNormalizedPath(ts.combinePaths(searchPath, "jsconfig.json")); + if (this.host.fileExists(jsconfigFileName)) { + return jsconfigFileName; + } + var parentPath = server.asNormalizedPath(ts.getDirectoryPath(searchPath)); + if (parentPath === searchPath) { + break; + } + searchPath = parentPath; + } + return undefined; + }; + ProjectService.prototype.printProjects = function () { + if (!this.logger.hasLevel(server.LogLevel.verbose)) { + return; + } + this.logger.startGroup(); + var counter = 0; + counter = printProjects(this.logger, this.externalProjects, counter); + counter = printProjects(this.logger, this.configuredProjects, counter); + counter = printProjects(this.logger, this.inferredProjects, counter); + this.logger.info("Open files: "); + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var rootFile = _a[_i]; + this.logger.info(rootFile.fileName); + } + this.logger.endGroup(); + function printProjects(logger, projects, counter) { + for (var _i = 0, projects_3 = projects; _i < projects_3.length; _i++) { + var project = projects_3[_i]; + project.updateGraph(); + logger.info("Project '" + project.getProjectName() + "' (" + server.ProjectKind[project.projectKind] + ") " + counter); + logger.info(project.filesToString()); + logger.info("-----------------------------------------------"); + counter++; + } + return counter; + } + }; + ProjectService.prototype.findConfiguredProjectByProjectName = function (configFileName) { + return findProjectByName(configFileName, this.configuredProjects); + }; + ProjectService.prototype.findExternalProjectByProjectName = function (projectFileName) { + return findProjectByName(projectFileName, this.externalProjects); + }; + ProjectService.prototype.convertConfigFileContentToProjectOptions = function (configFilename) { + configFilename = ts.normalizePath(configFilename); + var configFileContent = this.host.readFile(configFilename); + var errors; + var result = ts.parseConfigFileTextToJson(configFilename, configFileContent); + var config = result.config; + if (result.error) { + var _a = ts.sanitizeConfigFile(configFilename, configFileContent), sanitizedConfig = _a.configJsonObject, diagnostics = _a.diagnostics; + config = sanitizedConfig; + errors = diagnostics.length ? diagnostics : [result.error]; + } + var parsedCommandLine = ts.parseJsonConfigFileContent(config, this.host, ts.getDirectoryPath(configFilename), {}, configFilename); + if (parsedCommandLine.errors.length) { + errors = ts.concatenate(errors, parsedCommandLine.errors); + } + ts.Debug.assert(!!parsedCommandLine.fileNames); + if (parsedCommandLine.fileNames.length === 0) { + (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); + return { success: false, configFileErrors: errors }; + } + var projectOptions = { + files: parsedCommandLine.fileNames, + compilerOptions: parsedCommandLine.options, + configHasFilesProperty: config["files"] !== undefined, + wildcardDirectories: ts.createMap(parsedCommandLine.wildcardDirectories), + typingOptions: parsedCommandLine.typingOptions, + compileOnSave: parsedCommandLine.compileOnSave + }; + return { success: true, projectOptions: projectOptions, configFileErrors: errors }; + }; + ProjectService.prototype.exceededTotalSizeLimitForNonTsFiles = function (options, fileNames, propertyReader) { + if (options && options.disableSizeLimit || !this.host.getFileSize) { + return false; + } + var totalNonTsFileSize = 0; + for (var _i = 0, fileNames_3 = fileNames; _i < fileNames_3.length; _i++) { + var f = fileNames_3[_i]; + var fileName = propertyReader.getFileName(f); + if (ts.hasTypeScriptFileExtension(fileName)) { + continue; + } + totalNonTsFileSize += this.host.getFileSize(fileName); + if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) { + return true; + } + } + return false; + }; + ProjectService.prototype.createAndAddExternalProject = function (projectFileName, files, options, typingOptions) { + var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, options, !this.exceededTotalSizeLimitForNonTsFiles(options, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); + this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, undefined, typingOptions, undefined); + this.externalProjects.push(project); + return project; + }; + ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) { + if (!this.eventHandler) { + return; + } + this.eventHandler({ + eventName: "configFileDiag", + data: { configFileName: configFileName, diagnostics: diagnostics || [], triggerFile: triggerFile } + }); + }; + ProjectService.prototype.createAndAddConfiguredProject = function (configFileName, projectOptions, configFileErrors, clientFileName) { + var _this = this; + var sizeLimitExceeded = this.exceededTotalSizeLimitForNonTsFiles(projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); + var project = new server.ConfiguredProject(configFileName, this, this.documentRegistry, projectOptions.configHasFilesProperty, projectOptions.compilerOptions, projectOptions.wildcardDirectories, !sizeLimitExceeded, projectOptions.compileOnSave === undefined ? false : projectOptions.compileOnSave); + this.addFilesToProjectAndUpdateGraph(project, projectOptions.files, fileNamePropertyReader, clientFileName, projectOptions.typingOptions, configFileErrors); + project.watchConfigFile(function (project) { return _this.onConfigChangedForConfiguredProject(project); }); + if (!sizeLimitExceeded) { + this.watchConfigDirectoryForProject(project, projectOptions); + } + project.watchWildcards(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); }); + project.watchTypeRoots(function (project, path) { return _this.onTypeRootFileChanged(project, path); }); + this.configuredProjects.push(project); + return project; + }; + ProjectService.prototype.watchConfigDirectoryForProject = function (project, options) { + var _this = this; + if (!options.configHasFilesProperty) { + project.watchConfigDirectory(function (project, path) { return _this.onSourceFileInDirectoryChangedForConfiguredProject(project, path); }); + } + }; + ProjectService.prototype.addFilesToProjectAndUpdateGraph = function (project, files, propertyReader, clientFileName, typingOptions, configFileErrors) { + var errors; + for (var _i = 0, files_4 = files; _i < files_4.length; _i++) { + var f = files_4[_i]; + var rootFilename = propertyReader.getFileName(f); + var scriptKind = propertyReader.getScriptKind(f); + var hasMixedContent = propertyReader.hasMixedContent(f); + if (this.host.fileExists(rootFilename)) { + var info = this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(rootFilename), clientFileName == rootFilename, undefined, scriptKind, hasMixedContent); + project.addRoot(info); + } + else { + (errors || (errors = [])).push(createFileNotFoundDiagnostic(rootFilename)); + } + } + project.setProjectErrors(ts.concatenate(configFileErrors, errors)); + project.setTypingOptions(typingOptions); + project.updateGraph(); + }; + ProjectService.prototype.openConfigFile = function (configFileName, clientFileName) { + var conversionResult = this.convertConfigFileContentToProjectOptions(configFileName); + var projectOptions = conversionResult.success + ? conversionResult.projectOptions + : { files: [], compilerOptions: {} }; + var project = this.createAndAddConfiguredProject(configFileName, projectOptions, conversionResult.configFileErrors, clientFileName); + return { + success: conversionResult.success, + project: project, + errors: project.getProjectErrors() + }; + }; + ProjectService.prototype.updateNonInferredProject = function (project, newUncheckedFiles, propertyReader, newOptions, newTypingOptions, compileOnSave, configFileErrors) { + var oldRootScriptInfos = project.getRootScriptInfos(); + var newRootScriptInfos = []; + var newRootScriptInfoMap = server.createNormalizedPathMap(); + var projectErrors; + var rootFilesChanged = false; + for (var _i = 0, newUncheckedFiles_1 = newUncheckedFiles; _i < newUncheckedFiles_1.length; _i++) { + var f = newUncheckedFiles_1[_i]; + var newRootFile = propertyReader.getFileName(f); + if (!this.host.fileExists(newRootFile)) { + (projectErrors || (projectErrors = [])).push(createFileNotFoundDiagnostic(newRootFile)); + continue; + } + var normalizedPath = server.toNormalizedPath(newRootFile); + var scriptInfo = this.getScriptInfoForNormalizedPath(normalizedPath); + if (!scriptInfo || !project.isRoot(scriptInfo)) { + rootFilesChanged = true; + if (!scriptInfo) { + var scriptKind = propertyReader.getScriptKind(f); + var hasMixedContent = propertyReader.hasMixedContent(f); + scriptInfo = this.getOrCreateScriptInfoForNormalizedPath(normalizedPath, false, undefined, scriptKind, hasMixedContent); + } + } + newRootScriptInfos.push(scriptInfo); + newRootScriptInfoMap.set(scriptInfo.fileName, scriptInfo); + } + if (rootFilesChanged || newRootScriptInfos.length !== oldRootScriptInfos.length) { + var toAdd = void 0; + var toRemove = void 0; + for (var _a = 0, oldRootScriptInfos_1 = oldRootScriptInfos; _a < oldRootScriptInfos_1.length; _a++) { + var oldFile = oldRootScriptInfos_1[_a]; + if (!newRootScriptInfoMap.contains(oldFile.fileName)) { + (toRemove || (toRemove = [])).push(oldFile); + } + } + for (var _b = 0, newRootScriptInfos_1 = newRootScriptInfos; _b < newRootScriptInfos_1.length; _b++) { + var newFile = newRootScriptInfos_1[_b]; + if (!project.isRoot(newFile)) { + (toAdd || (toAdd = [])).push(newFile); + } + } + if (toRemove) { + for (var _c = 0, toRemove_1 = toRemove; _c < toRemove_1.length; _c++) { + var f = toRemove_1[_c]; + project.removeFile(f); + } + } + if (toAdd) { + for (var _d = 0, toAdd_1 = toAdd; _d < toAdd_1.length; _d++) { + var f = toAdd_1[_d]; + if (f.isOpen && isRootFileInInferredProject(f)) { + var inferredProject = f.containingProjects[0]; + inferredProject.removeFile(f); + if (!inferredProject.hasRoots()) { + this.removeProject(inferredProject); + } + } + project.addRoot(f); + } + } + } + project.setCompilerOptions(newOptions); + project.setTypingOptions(newTypingOptions); + if (compileOnSave !== undefined) { + project.compileOnSaveEnabled = compileOnSave; + } + project.setProjectErrors(ts.concatenate(configFileErrors, projectErrors)); + project.updateGraph(); + }; + ProjectService.prototype.updateConfiguredProject = function (project) { + if (!this.host.fileExists(project.configFileName)) { + this.logger.info("Config file deleted"); + this.removeProject(project); + return; + } + var _a = this.convertConfigFileContentToProjectOptions(project.configFileName), success = _a.success, projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors; + if (!success) { + this.updateNonInferredProject(project, [], fileNamePropertyReader, {}, {}, false, configFileErrors); + return configFileErrors; + } + if (this.exceededTotalSizeLimitForNonTsFiles(projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader)) { + project.setCompilerOptions(projectOptions.compilerOptions); + if (!project.languageServiceEnabled) { + return; + } + project.disableLanguageService(); + project.stopWatchingDirectory(); + } + else { + if (!project.languageServiceEnabled) { + project.enableLanguageService(); + } + this.watchConfigDirectoryForProject(project, projectOptions); + this.updateNonInferredProject(project, projectOptions.files, fileNamePropertyReader, projectOptions.compilerOptions, projectOptions.typingOptions, projectOptions.compileOnSave, configFileErrors); + } + }; + ProjectService.prototype.createInferredProjectWithRootFileIfNecessary = function (root) { + var _this = this; + var useExistingProject = this.useSingleInferredProject && this.inferredProjects.length; + var project = useExistingProject + ? this.inferredProjects[0] + : new server.InferredProject(this, this.documentRegistry, true, this.compilerOptionsForInferredProjects, this.compileOnSaveForInferredProjects); + project.addRoot(root); + this.directoryWatchers.startWatchingContainingDirectoriesForFile(root.fileName, project, function (fileName) { return _this.onConfigFileAddedForInferredProject(fileName); }); + project.updateGraph(); + if (!useExistingProject) { + this.inferredProjects.push(project); + } + return project; + }; + ProjectService.prototype.getOrCreateScriptInfo = function (uncheckedFileName, openedByClient, fileContent, scriptKind) { + return this.getOrCreateScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName), openedByClient, fileContent, scriptKind); + }; + ProjectService.prototype.getScriptInfo = function (uncheckedFileName) { + return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + }; + ProjectService.prototype.getOrCreateScriptInfoForNormalizedPath = function (fileName, openedByClient, fileContent, scriptKind, hasMixedContent) { + var _this = this; + var info = this.getScriptInfoForNormalizedPath(fileName); + if (!info) { + var content = void 0; + if (this.host.fileExists(fileName)) { + content = fileContent || (hasMixedContent ? "" : this.host.readFile(fileName)); + } + if (!content) { + if (openedByClient) { + content = ""; + } + } + if (content !== undefined) { + info = new server.ScriptInfo(this.host, fileName, content, scriptKind, openedByClient, hasMixedContent); + this.filenameToScriptInfo.set(info.path, info); + if (!info.isOpen && !hasMixedContent) { + info.setWatcher(this.host.watchFile(fileName, function (_) { return _this.onSourceFileChanged(fileName); })); + } + } + } + if (info) { + if (fileContent !== undefined) { + info.reload(fileContent); + } + if (openedByClient) { + info.isOpen = true; + } + } + return info; + }; + ProjectService.prototype.getScriptInfoForNormalizedPath = function (fileName) { + return this.getScriptInfoForPath(server.normalizedPathToPath(fileName, this.host.getCurrentDirectory(), this.toCanonicalFileName)); + }; + ProjectService.prototype.getScriptInfoForPath = function (fileName) { + return this.filenameToScriptInfo.get(fileName); + }; + ProjectService.prototype.setHostConfiguration = function (args) { + if (args.file) { + var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file)); + if (info) { + info.setFormatOptions(args.formatOptions); + this.logger.info("Host configuration update for file " + args.file); + } + } + else { + if (args.hostInfo !== undefined) { + this.hostConfiguration.hostInfo = args.hostInfo; + this.logger.info("Host information " + args.hostInfo); + } + if (args.formatOptions) { + server.mergeMaps(this.hostConfiguration.formatCodeOptions, args.formatOptions); + this.logger.info("Format host information updated"); + } + } + }; + ProjectService.prototype.closeLog = function () { + this.logger.close(); + }; + ProjectService.prototype.reloadProjects = function () { + this.logger.info("reload projects."); + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var info = _a[_i]; + this.openOrUpdateConfiguredProjectForFile(info.fileName); + } + this.refreshInferredProjects(); + }; + ProjectService.prototype.refreshInferredProjects = function () { + this.logger.info("updating project structure from ..."); + this.printProjects(); + var orphantedFiles = []; + for (var _i = 0, _a = this.openFiles; _i < _a.length; _i++) { + var info = _a[_i]; + if (info.containingProjects.length === 0) { + orphantedFiles.push(info); + } + else { + if (isRootFileInInferredProject(info) && info.containingProjects.length > 1) { + var inferredProject = info.containingProjects[0]; + ts.Debug.assert(inferredProject.projectKind === server.ProjectKind.Inferred); + inferredProject.removeFile(info); + if (!inferredProject.hasRoots()) { + this.removeProject(inferredProject); + } + } + } + } + for (var _b = 0, orphantedFiles_1 = orphantedFiles; _b < orphantedFiles_1.length; _b++) { + var f = orphantedFiles_1[_b]; + this.assignScriptInfoToInferredProjectIfNecessary(f, false); + } + for (var _c = 0, _d = this.inferredProjects; _c < _d.length; _c++) { + var p = _d[_c]; + p.updateGraph(); + } + this.printProjects(); + }; + ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind) { + return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind); + }; + ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent) { + var _a = this.findContainingExternalProject(fileName) + ? {} + : this.openOrUpdateConfiguredProjectForFile(fileName), _b = _a.configFileName, configFileName = _b === void 0 ? undefined : _b, _c = _a.configFileErrors, configFileErrors = _c === void 0 ? undefined : _c; + var info = this.getOrCreateScriptInfoForNormalizedPath(fileName, true, fileContent, scriptKind, hasMixedContent); + this.assignScriptInfoToInferredProjectIfNecessary(info, true); + this.printProjects(); + return { configFileName: configFileName, configFileErrors: configFileErrors }; + }; + ProjectService.prototype.closeClientFile = function (uncheckedFileName) { + var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); + if (info) { + this.closeOpenFile(info); + info.isOpen = false; + } + this.printProjects(); + }; + ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { + var _loop_3 = function (proj) { + var knownProject = ts.forEach(lastKnownProjectVersions, function (p) { return p.projectName === proj.getProjectName() && p; }); + result.push(proj.getChangesSinceVersion(knownProject && knownProject.version)); + }; + for (var _i = 0, currentProjects_1 = currentProjects; _i < currentProjects_1.length; _i++) { + var proj = currentProjects_1[_i]; + _loop_3(proj); + } + }; + ProjectService.prototype.synchronizeProjectList = function (knownProjects) { + var files = []; + this.collectChanges(knownProjects, this.externalProjects, files); + this.collectChanges(knownProjects, this.configuredProjects, files); + this.collectChanges(knownProjects, this.inferredProjects, files); + return files; + }; + ProjectService.prototype.applyChangesInOpenFiles = function (openFiles, changedFiles, closedFiles) { + var recordChangedFiles = changedFiles && !openFiles && !closedFiles; + if (openFiles) { + for (var _i = 0, openFiles_1 = openFiles; _i < openFiles_1.length; _i++) { + var file = openFiles_1[_i]; + var scriptInfo = this.getScriptInfo(file.fileName); + ts.Debug.assert(!scriptInfo || !scriptInfo.isOpen); + var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName); + this.openClientFileWithNormalizedPath(normalizedPath, file.content, file.scriptKind, file.hasMixedContent); + } + } + if (changedFiles) { + for (var _a = 0, changedFiles_1 = changedFiles; _a < changedFiles_1.length; _a++) { + var file = changedFiles_1[_a]; + var scriptInfo = this.getScriptInfo(file.fileName); + ts.Debug.assert(!!scriptInfo); + for (var i = file.changes.length - 1; i >= 0; i--) { + var change = file.changes[i]; + scriptInfo.editContent(change.span.start, change.span.start + change.span.length, change.newText); + } + if (recordChangedFiles) { + if (!this.changedFiles) { + this.changedFiles = [scriptInfo]; + } + else if (this.changedFiles.indexOf(scriptInfo) < 0) { + this.changedFiles.push(scriptInfo); + } + } + } + } + if (closedFiles) { + for (var _b = 0, closedFiles_1 = closedFiles; _b < closedFiles_1.length; _b++) { + var file = closedFiles_1[_b]; + this.closeClientFile(file); + } + } + if (openFiles || closedFiles) { + this.refreshInferredProjects(); + } + }; + ProjectService.prototype.closeConfiguredProject = function (configFile) { + var configuredProject = this.findConfiguredProjectByProjectName(configFile); + if (configuredProject && configuredProject.deleteOpenRef() === 0) { + this.removeProject(configuredProject); + } + }; + ProjectService.prototype.closeExternalProject = function (uncheckedFileName, suppressRefresh) { + if (suppressRefresh === void 0) { suppressRefresh = false; } + var fileName = server.toNormalizedPath(uncheckedFileName); + var configFiles = this.externalProjectToConfiguredProjectMap[fileName]; + if (configFiles) { + var shouldRefreshInferredProjects = false; + for (var _i = 0, configFiles_1 = configFiles; _i < configFiles_1.length; _i++) { + var configFile = configFiles_1[_i]; + if (this.closeConfiguredProject(configFile)) { + shouldRefreshInferredProjects = true; + } + } + delete this.externalProjectToConfiguredProjectMap[fileName]; + if (shouldRefreshInferredProjects && !suppressRefresh) { + this.refreshInferredProjects(); + } + } + else { + var externalProject = this.findExternalProjectByProjectName(uncheckedFileName); + if (externalProject) { + this.removeProject(externalProject); + if (!suppressRefresh) { + this.refreshInferredProjects(); + } + } + } + }; + ProjectService.prototype.openExternalProject = function (proj) { + var tsConfigFiles; + var rootFiles = []; + for (var _i = 0, _a = proj.rootFiles; _i < _a.length; _i++) { + var file = _a[_i]; + var normalized = server.toNormalizedPath(file.fileName); + if (ts.getBaseFileName(normalized) === "tsconfig.json") { + (tsConfigFiles || (tsConfigFiles = [])).push(normalized); + } + else { + rootFiles.push(file); + } + } + if (tsConfigFiles) { + tsConfigFiles.sort(); + } + var externalProject = this.findExternalProjectByProjectName(proj.projectFileName); + var exisingConfigFiles; + if (externalProject) { + if (!tsConfigFiles) { + this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, proj.options, proj.typingOptions, proj.options.compileOnSave, undefined); + return; + } + this.closeExternalProject(proj.projectFileName, true); + } + else if (this.externalProjectToConfiguredProjectMap[proj.projectFileName]) { + if (!tsConfigFiles) { + this.closeExternalProject(proj.projectFileName, true); + } + else { + var oldConfigFiles = this.externalProjectToConfiguredProjectMap[proj.projectFileName]; + var iNew = 0; + var iOld = 0; + while (iNew < tsConfigFiles.length && iOld < oldConfigFiles.length) { + var newConfig = tsConfigFiles[iNew]; + var oldConfig = oldConfigFiles[iOld]; + if (oldConfig < newConfig) { + this.closeConfiguredProject(oldConfig); + iOld++; + } + else if (oldConfig > newConfig) { + iNew++; + } + else { + (exisingConfigFiles || (exisingConfigFiles = [])).push(oldConfig); + iOld++; + iNew++; + } + } + for (var i = iOld; i < oldConfigFiles.length; i++) { + this.closeConfiguredProject(oldConfigFiles[i]); + } + } + } + if (tsConfigFiles) { + this.externalProjectToConfiguredProjectMap[proj.projectFileName] = tsConfigFiles; + for (var _b = 0, tsConfigFiles_1 = tsConfigFiles; _b < tsConfigFiles_1.length; _b++) { + var tsconfigFile = tsConfigFiles_1[_b]; + var project = this.findConfiguredProjectByProjectName(tsconfigFile); + if (!project) { + var result = this.openConfigFile(tsconfigFile); + project = result.success && result.project; + } + if (project && !ts.contains(exisingConfigFiles, tsconfigFile)) { + project.addOpenRef(); + } + } + } + else { + delete this.externalProjectToConfiguredProjectMap[proj.projectFileName]; + this.createAndAddExternalProject(proj.projectFileName, rootFiles, proj.options, proj.typingOptions); + } + this.refreshInferredProjects(); + }; + return ProjectService; + }()); + server.ProjectService = ProjectService; + })(server = ts.server || (ts.server = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + var server; + (function (server) { + function hrTimeToMilliseconds(time) { + var seconds = time[0]; + var nanoseconds = time[1]; + return ((1e9 * seconds) + nanoseconds) / 1000000.0; + } + function shouldSkipSematicCheck(project) { + if (project.getCompilerOptions().skipLibCheck !== undefined) { + return false; + } + if ((project.projectKind === server.ProjectKind.Inferred || project.projectKind === server.ProjectKind.External) && project.isJsOnlyProject()) { + return true; + } + return false; + } function compareNumber(a, b) { - if (a < b) { - return -1; - } - else if (a === b) { - return 0; - } - else - return 1; + return a - b; } function compareFileStart(a, b) { if (a.file < b.file) { @@ -60288,10 +63334,12 @@ var ts; } } function formatDiag(fileName, project, diag) { + var scriptInfo = project.getScriptInfoForNormalizedPath(fileName); return { - start: project.compilerService.host.positionToLineOffset(fileName, diag.start), - end: project.compilerService.host.positionToLineOffset(fileName, diag.start + diag.length), - text: ts.flattenDiagnosticMessageText(diag.messageText, "\n") + start: scriptInfo.positionToLineOffset(diag.start), + end: scriptInfo.positionToLineOffset(diag.start + diag.length), + text: ts.flattenDiagnosticMessageText(diag.messageText, "\n"), + code: diag.code }; } function formatConfigFileDiag(diag) { @@ -60302,8 +63350,9 @@ var ts; }; } function allEditsBeforePos(edits, pos) { - for (var i = 0, len = edits.length; i < len; i++) { - if (ts.textSpanEnd(edits[i].span) >= pos) { + for (var _i = 0, edits_1 = edits; _i < edits_1.length; _i++) { + var edit = edits_1[_i]; + if (ts.textSpanEnd(edit.span) >= pos) { return false; } } @@ -60312,73 +63361,166 @@ var ts; var CommandNames; (function (CommandNames) { CommandNames.Brace = "brace"; + CommandNames.BraceFull = "brace-full"; + CommandNames.BraceCompletion = "braceCompletion"; CommandNames.Change = "change"; CommandNames.Close = "close"; CommandNames.Completions = "completions"; + CommandNames.CompletionsFull = "completions-full"; CommandNames.CompletionDetails = "completionEntryDetails"; + CommandNames.CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; + CommandNames.CompileOnSaveEmitFile = "compileOnSaveEmitFile"; CommandNames.Configure = "configure"; CommandNames.Definition = "definition"; + CommandNames.DefinitionFull = "definition-full"; CommandNames.Exit = "exit"; CommandNames.Format = "format"; CommandNames.Formatonkey = "formatonkey"; + CommandNames.FormatFull = "format-full"; + CommandNames.FormatonkeyFull = "formatonkey-full"; + CommandNames.FormatRangeFull = "formatRange-full"; CommandNames.Geterr = "geterr"; CommandNames.GeterrForProject = "geterrForProject"; CommandNames.Implementation = "implementation"; + CommandNames.ImplementationFull = "implementation-full"; CommandNames.SemanticDiagnosticsSync = "semanticDiagnosticsSync"; CommandNames.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; CommandNames.NavBar = "navbar"; + CommandNames.NavBarFull = "navbar-full"; + CommandNames.NavTree = "navtree"; + CommandNames.NavTreeFull = "navtree-full"; CommandNames.Navto = "navto"; + CommandNames.NavtoFull = "navto-full"; CommandNames.Occurrences = "occurrences"; CommandNames.DocumentHighlights = "documentHighlights"; + CommandNames.DocumentHighlightsFull = "documentHighlights-full"; CommandNames.Open = "open"; CommandNames.Quickinfo = "quickinfo"; + CommandNames.QuickinfoFull = "quickinfo-full"; CommandNames.References = "references"; + CommandNames.ReferencesFull = "references-full"; CommandNames.Reload = "reload"; CommandNames.Rename = "rename"; + CommandNames.RenameInfoFull = "rename-full"; + CommandNames.RenameLocationsFull = "renameLocations-full"; CommandNames.Saveto = "saveto"; CommandNames.SignatureHelp = "signatureHelp"; + CommandNames.SignatureHelpFull = "signatureHelp-full"; CommandNames.TypeDefinition = "typeDefinition"; CommandNames.ProjectInfo = "projectInfo"; CommandNames.ReloadProjects = "reloadProjects"; CommandNames.Unknown = "unknown"; + CommandNames.OpenExternalProject = "openExternalProject"; + CommandNames.OpenExternalProjects = "openExternalProjects"; + CommandNames.CloseExternalProject = "closeExternalProject"; + CommandNames.SynchronizeProjectList = "synchronizeProjectList"; + CommandNames.ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; + CommandNames.EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; + CommandNames.Cleanup = "cleanup"; + CommandNames.OutliningSpans = "outliningSpans"; + CommandNames.TodoComments = "todoComments"; + CommandNames.Indentation = "indentation"; + CommandNames.DocCommentTemplate = "docCommentTemplate"; + CommandNames.CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; + CommandNames.NameOrDottedNameSpan = "nameOrDottedNameSpan"; + CommandNames.BreakpointStatement = "breakpointStatement"; + CommandNames.CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; + CommandNames.GetCodeFixes = "getCodeFixes"; + CommandNames.GetCodeFixesFull = "getCodeFixes-full"; + CommandNames.GetSupportedCodeFixes = "getSupportedCodeFixes"; })(CommandNames = server.CommandNames || (server.CommandNames = {})); - var Errors; - (function (Errors) { - Errors.NoProject = new Error("No Project."); - Errors.ProjectLanguageServiceDisabled = new Error("The project's language service is disabled."); - })(Errors || (Errors = {})); + function formatMessage(msg, logger, byteLength, newLine) { + var verboseLogging = logger.hasLevel(server.LogLevel.verbose); + var json = JSON.stringify(msg); + if (verboseLogging) { + logger.info(msg.type + ": " + json); + } + var len = byteLength(json, "utf8"); + return "Content-Length: " + (1 + len) + "\r\n\r\n" + json + newLine; + } + server.formatMessage = formatMessage; var Session = (function () { - function Session(host, byteLength, hrtime, logger) { + function Session(host, cancellationToken, useSingleInferredProject, typingsInstaller, byteLength, hrtime, logger, canUseEvents, eventHandler) { var _this = this; this.host = host; + this.typingsInstaller = typingsInstaller; this.byteLength = byteLength; this.hrtime = hrtime; this.logger = logger; + this.canUseEvents = canUseEvents; this.changeSeq = 0; this.handlers = ts.createMap((_a = {}, + _a[CommandNames.OpenExternalProject] = function (request) { + _this.projectService.openExternalProject(request.arguments); + return _this.requiredResponse(true); + }, + _a[CommandNames.OpenExternalProjects] = function (request) { + for (var _i = 0, _a = request.arguments.projects; _i < _a.length; _i++) { + var proj = _a[_i]; + _this.projectService.openExternalProject(proj); + } + return _this.requiredResponse(true); + }, + _a[CommandNames.CloseExternalProject] = function (request) { + _this.projectService.closeExternalProject(request.arguments.projectFileName); + return _this.requiredResponse(true); + }, + _a[CommandNames.SynchronizeProjectList] = function (request) { + var result = _this.projectService.synchronizeProjectList(request.arguments.knownProjects); + if (!result.some(function (p) { return p.projectErrors && p.projectErrors.length !== 0; })) { + return _this.requiredResponse(result); + } + var converted = ts.map(result, function (p) { + if (!p.projectErrors || p.projectErrors.length === 0) { + return p; + } + return { + info: p.info, + changes: p.changes, + files: p.files, + projectErrors: _this.convertToDiagnosticsWithLinePosition(p.projectErrors, undefined) + }; + }); + return _this.requiredResponse(converted); + }, + _a[CommandNames.ApplyChangedToOpenFiles] = function (request) { + _this.projectService.applyChangesInOpenFiles(request.arguments.openFiles, request.arguments.changedFiles, request.arguments.closedFiles); + _this.changeSeq++; + return _this.requiredResponse(true); + }, _a[CommandNames.Exit] = function () { _this.exit(); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Definition] = function (request) { - var defArgs = request.arguments; - return { response: _this.getDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getDefinition(request.arguments, true)); + }, + _a[CommandNames.DefinitionFull] = function (request) { + return _this.requiredResponse(_this.getDefinition(request.arguments, false)); }, _a[CommandNames.TypeDefinition] = function (request) { - var defArgs = request.arguments; - return { response: _this.getTypeDefinition(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getTypeDefinition(request.arguments)); }, _a[CommandNames.Implementation] = function (request) { - var implArgs = request.arguments; - return { response: _this.getImplementation(implArgs.line, implArgs.offset, implArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getImplementation(request.arguments, true)); + }, + _a[CommandNames.ImplementationFull] = function (request) { + return _this.requiredResponse(_this.getImplementation(request.arguments, false)); }, _a[CommandNames.References] = function (request) { - var defArgs = request.arguments; - return { response: _this.getReferences(defArgs.line, defArgs.offset, defArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getReferences(request.arguments, true)); + }, + _a[CommandNames.ReferencesFull] = function (request) { + return _this.requiredResponse(_this.getReferences(request.arguments, false)); }, _a[CommandNames.Rename] = function (request) { - var renameArgs = request.arguments; - return { response: _this.getRenameLocations(renameArgs.line, renameArgs.offset, renameArgs.file, renameArgs.findInComments, renameArgs.findInStrings), responseRequired: true }; + return _this.requiredResponse(_this.getRenameLocations(request.arguments, true)); + }, + _a[CommandNames.RenameLocationsFull] = function (request) { + return _this.requiredResponse(_this.getRenameLocations(request.arguments, false)); + }, + _a[CommandNames.RenameInfoFull] = function (request) { + return _this.requiredResponse(_this.getRenameInfo(request.arguments)); }, _a[CommandNames.Open] = function (request) { var openArgs = request.arguments; @@ -60397,34 +63539,81 @@ var ts; scriptKind = 2; break; } - _this.openClientFile(openArgs.file, openArgs.fileContent, scriptKind); - return { responseRequired: false }; + _this.openClientFile(server.toNormalizedPath(openArgs.file), openArgs.fileContent, scriptKind); + return _this.notRequired(); }, _a[CommandNames.Quickinfo] = function (request) { - var quickinfoArgs = request.arguments; - return { response: _this.getQuickInfo(quickinfoArgs.line, quickinfoArgs.offset, quickinfoArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, true)); + }, + _a[CommandNames.QuickinfoFull] = function (request) { + return _this.requiredResponse(_this.getQuickInfoWorker(request.arguments, false)); + }, + _a[CommandNames.OutliningSpans] = function (request) { + return _this.requiredResponse(_this.getOutliningSpans(request.arguments)); + }, + _a[CommandNames.TodoComments] = function (request) { + return _this.requiredResponse(_this.getTodoComments(request.arguments)); + }, + _a[CommandNames.Indentation] = function (request) { + return _this.requiredResponse(_this.getIndentation(request.arguments)); + }, + _a[CommandNames.NameOrDottedNameSpan] = function (request) { + return _this.requiredResponse(_this.getNameOrDottedNameSpan(request.arguments)); + }, + _a[CommandNames.BreakpointStatement] = function (request) { + return _this.requiredResponse(_this.getBreakpointStatement(request.arguments)); + }, + _a[CommandNames.BraceCompletion] = function (request) { + return _this.requiredResponse(_this.isValidBraceCompletion(request.arguments)); + }, + _a[CommandNames.DocCommentTemplate] = function (request) { + return _this.requiredResponse(_this.getDocCommentTemplate(request.arguments)); }, _a[CommandNames.Format] = function (request) { - var formatArgs = request.arguments; - return { response: _this.getFormattingEditsForRange(formatArgs.line, formatArgs.offset, formatArgs.endLine, formatArgs.endOffset, formatArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getFormattingEditsForRange(request.arguments)); }, _a[CommandNames.Formatonkey] = function (request) { - var formatOnKeyArgs = request.arguments; - return { response: _this.getFormattingEditsAfterKeystroke(formatOnKeyArgs.line, formatOnKeyArgs.offset, formatOnKeyArgs.key, formatOnKeyArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getFormattingEditsAfterKeystroke(request.arguments)); + }, + _a[CommandNames.FormatFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsForDocumentFull(request.arguments)); + }, + _a[CommandNames.FormatonkeyFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsAfterKeystrokeFull(request.arguments)); + }, + _a[CommandNames.FormatRangeFull] = function (request) { + return _this.requiredResponse(_this.getFormattingEditsForRangeFull(request.arguments)); }, _a[CommandNames.Completions] = function (request) { - var completionsArgs = request.arguments; - return { response: _this.getCompletions(completionsArgs.line, completionsArgs.offset, completionsArgs.prefix, completionsArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getCompletions(request.arguments, true)); + }, + _a[CommandNames.CompletionsFull] = function (request) { + return _this.requiredResponse(_this.getCompletions(request.arguments, false)); }, _a[CommandNames.CompletionDetails] = function (request) { - var completionDetailsArgs = request.arguments; - return { - response: _this.getCompletionEntryDetails(completionDetailsArgs.line, completionDetailsArgs.offset, completionDetailsArgs.entryNames, completionDetailsArgs.file), responseRequired: true - }; + return _this.requiredResponse(_this.getCompletionEntryDetails(request.arguments)); + }, + _a[CommandNames.CompileOnSaveAffectedFileList] = function (request) { + return _this.requiredResponse(_this.getCompileOnSaveAffectedFileList(request.arguments)); + }, + _a[CommandNames.CompileOnSaveEmitFile] = function (request) { + return _this.requiredResponse(_this.emitFile(request.arguments)); }, _a[CommandNames.SignatureHelp] = function (request) { - var signatureHelpArgs = request.arguments; - return { response: _this.getSignatureHelpItems(signatureHelpArgs.line, signatureHelpArgs.offset, signatureHelpArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, true)); + }, + _a[CommandNames.SignatureHelpFull] = function (request) { + return _this.requiredResponse(_this.getSignatureHelpItems(request.arguments, false)); + }, + _a[CommandNames.CompilerOptionsDiagnosticsFull] = function (request) { + return _this.requiredResponse(_this.getCompilerOptionsDiagnostics(request.arguments)); + }, + _a[CommandNames.EncodedSemanticClassificationsFull] = function (request) { + return _this.requiredResponse(_this.getEncodedSemanticClassifications(request.arguments)); + }, + _a[CommandNames.Cleanup] = function (request) { + _this.cleanup(); + return _this.requiredResponse(true); }, _a[CommandNames.SemanticDiagnosticsSync] = function (request) { return _this.requiredResponse(_this.getSemanticDiagnosticsSync(request.arguments)); @@ -60441,72 +63630,94 @@ var ts; return { response: _this.getDiagnosticsForProject(delay, file), responseRequired: false }; }, _a[CommandNames.Change] = function (request) { - var changeArgs = request.arguments; - _this.change(changeArgs.line, changeArgs.offset, changeArgs.endLine, changeArgs.endOffset, changeArgs.insertString, changeArgs.file); - return { responseRequired: false }; + _this.change(request.arguments); + return _this.notRequired(); }, _a[CommandNames.Configure] = function (request) { - var configureArgs = request.arguments; - _this.projectService.setHostConfiguration(configureArgs); + _this.projectService.setHostConfiguration(request.arguments); _this.output(undefined, CommandNames.Configure, request.seq); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Reload] = function (request) { - var reloadArgs = request.arguments; - _this.reload(reloadArgs.file, reloadArgs.tmpfile, request.seq); - return { response: { reloadFinished: true }, responseRequired: true }; + _this.reload(request.arguments, request.seq); + return _this.requiredResponse({ reloadFinished: true }); }, _a[CommandNames.Saveto] = function (request) { var savetoArgs = request.arguments; _this.saveToTmp(savetoArgs.file, savetoArgs.tmpfile); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Close] = function (request) { var closeArgs = request.arguments; _this.closeClientFile(closeArgs.file); - return { responseRequired: false }; + return _this.notRequired(); }, _a[CommandNames.Navto] = function (request) { - var navtoArgs = request.arguments; - return { response: _this.getNavigateToItems(navtoArgs.searchValue, navtoArgs.file, navtoArgs.maxResultCount, navtoArgs.currentFileOnly), responseRequired: true }; + return _this.requiredResponse(_this.getNavigateToItems(request.arguments, true)); + }, + _a[CommandNames.NavtoFull] = function (request) { + return _this.requiredResponse(_this.getNavigateToItems(request.arguments, false)); }, _a[CommandNames.Brace] = function (request) { - var braceArguments = request.arguments; - return { response: _this.getBraceMatching(braceArguments.line, braceArguments.offset, braceArguments.file), responseRequired: true }; + return _this.requiredResponse(_this.getBraceMatching(request.arguments, true)); + }, + _a[CommandNames.BraceFull] = function (request) { + return _this.requiredResponse(_this.getBraceMatching(request.arguments, false)); }, _a[CommandNames.NavBar] = function (request) { - var navBarArgs = request.arguments; - return { response: _this.getNavigationBarItems(navBarArgs.file), responseRequired: true }; + return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, true)); + }, + _a[CommandNames.NavBarFull] = function (request) { + return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, false)); + }, + _a[CommandNames.NavTree] = function (request) { + return _this.requiredResponse(_this.getNavigationTree(request.arguments, true)); + }, + _a[CommandNames.NavTreeFull] = function (request) { + return _this.requiredResponse(_this.getNavigationTree(request.arguments, false)); }, _a[CommandNames.Occurrences] = function (request) { - var _a = request.arguments, line = _a.line, offset = _a.offset, fileName = _a.file; - return { response: _this.getOccurrences(line, offset, fileName), responseRequired: true }; + return _this.requiredResponse(_this.getOccurrences(request.arguments)); }, _a[CommandNames.DocumentHighlights] = function (request) { - var _a = request.arguments, line = _a.line, offset = _a.offset, fileName = _a.file, filesToSearch = _a.filesToSearch; - return { response: _this.getDocumentHighlights(line, offset, fileName, filesToSearch), responseRequired: true }; + return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, true)); + }, + _a[CommandNames.DocumentHighlightsFull] = function (request) { + return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, false)); + }, + _a[CommandNames.CompilerOptionsForInferredProjects] = function (request) { + return _this.requiredResponse(_this.setCompilerOptionsForInferredProjects(request.arguments)); }, _a[CommandNames.ProjectInfo] = function (request) { - var _a = request.arguments, file = _a.file, needFileNameList = _a.needFileNameList; - return { response: _this.getProjectInfo(file, needFileNameList), responseRequired: true }; + return _this.requiredResponse(_this.getProjectInfo(request.arguments)); }, _a[CommandNames.ReloadProjects] = function (request) { - _this.reloadProjects(); - return { responseRequired: false }; + _this.projectService.reloadProjects(); + return _this.notRequired(); + }, + _a[CommandNames.GetCodeFixes] = function (request) { + return _this.requiredResponse(_this.getCodeFixes(request.arguments, true)); + }, + _a[CommandNames.GetCodeFixesFull] = function (request) { + return _this.requiredResponse(_this.getCodeFixes(request.arguments, false)); + }, + _a[CommandNames.GetSupportedCodeFixes] = function (request) { + return _this.requiredResponse(_this.getSupportedCodeFixes()); }, _a)); - this.projectService = - new server.ProjectService(host, logger, function (event) { - _this.handleEvent(event); - }); + this.eventHander = canUseEvents + ? eventHandler || (function (event) { return _this.defaultEventHandler(event); }) + : undefined; + this.projectService = new server.ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, this.eventHander); + this.gcTimer = new server.GcTimer(host, 7000, logger); var _a; } - Session.prototype.handleEvent = function (event) { + Session.prototype.defaultEventHandler = function (event) { var _this = this; switch (event.eventName) { case "context": var _a = event.data, project = _a.project, fileName = _a.fileName; - this.projectService.log("got context event, updating diagnostics for" + fileName, "Info"); + this.projectService.logger.info("got context event, updating diagnostics for " + fileName); this.updateErrorCheck([{ fileName: fileName, project: project }], this.changeSeq, function (n) { return n === _this.changeSeq; }, 100); break; case "configFileDiag": @@ -60515,26 +63726,23 @@ var ts; } }; Session.prototype.logError = function (err, cmd) { - var typedErr = err; var msg = "Exception on executing command " + cmd; - if (typedErr.message) { - msg += ":\n" + typedErr.message; - if (typedErr.stack) { - msg += "\n" + typedErr.stack; + if (err.message) { + msg += ":\n" + err.message; + if (err.stack) { + msg += "\n" + err.stack; } } - this.projectService.log(msg); - }; - Session.prototype.sendLineToClient = function (line) { - this.host.write(line + this.host.newLine); + this.logger.msg(msg, server.Msg.Err); }; Session.prototype.send = function (msg) { - var json = JSON.stringify(msg); - if (this.logger.isVerbose()) { - this.logger.info(msg.type + ": " + json); + if (msg.type === "event" && !this.canUseEvents) { + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("Session does not support events: ignored event: " + JSON.stringify(msg)); + } + return; } - this.sendLineToClient("Content-Length: " + (1 + this.byteLength(json, "utf8")) + - "\r\n\r\n" + json); + this.host.write(formatMessage(msg, this.logger, this.byteLength, this.host.newLine)); }; Session.prototype.configFileDiagnosticEvent = function (triggerFile, configFile, diagnostics) { var bakedDiags = ts.map(diagnostics, formatConfigFileDiag); @@ -60559,7 +63767,7 @@ var ts; }; this.send(ev); }; - Session.prototype.response = function (info, cmdName, reqSeq, errorMsg) { + Session.prototype.output = function (info, cmdName, reqSeq, errorMsg) { if (reqSeq === void 0) { reqSeq = 0; } var res = { seq: 0, @@ -60576,17 +63784,14 @@ var ts; } this.send(res); }; - Session.prototype.output = function (body, commandName, requestSequence, errorMessage) { - if (requestSequence === void 0) { requestSequence = 0; } - this.response(body, commandName, requestSequence, errorMessage); - }; Session.prototype.semanticCheck = function (file, project) { try { - var diags = project.compilerService.languageService.getSemanticDiagnostics(file); - if (diags) { - var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); - this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); + var diags = []; + if (!shouldSkipSematicCheck(project)) { + diags = project.getLanguageService().getSemanticDiagnostics(file); } + var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); + this.event({ file: file, diagnostics: bakedDiags }, "semanticDiag"); } catch (err) { this.logError(err, "semantic check"); @@ -60594,7 +63799,7 @@ var ts; }; Session.prototype.syntacticCheck = function (file, project) { try { - var diags = project.compilerService.languageService.getSyntacticDiagnostics(file); + var diags = project.getLanguageService().getSyntacticDiagnostics(file); if (diags) { var bakedDiags = diags.map(function (diag) { return formatDiag(file, project, diag); }); this.event({ file: file, diagnostics: bakedDiags }, "syntaxDiag"); @@ -60604,15 +63809,12 @@ var ts; this.logError(err, "syntactic check"); } }; - Session.prototype.reloadProjects = function () { - this.projectService.reloadProjects(); - }; Session.prototype.updateProjectStructure = function (seq, matchSeq, ms) { var _this = this; if (ms === void 0) { ms = 1500; } - setTimeout(function () { + this.host.setTimeout(function () { if (matchSeq(seq)) { - _this.projectService.updateProjectStructure(); + _this.projectService.refreshInferredProjects(); } }, ms); }; @@ -60625,10 +63827,10 @@ var ts; followMs = ms; } if (this.errorTimer) { - clearTimeout(this.errorTimer); + this.host.clearTimeout(this.errorTimer); } if (this.immediateId) { - clearImmediate(this.immediateId); + this.host.clearImmediate(this.immediateId); this.immediateId = undefined; } var index = 0; @@ -60636,13 +63838,13 @@ var ts; if (matchSeq(seq)) { var checkSpec_1 = checkList[index]; index++; - if (checkSpec_1.project.getSourceFileFromName(checkSpec_1.fileName, requireOpen)) { + if (checkSpec_1.project.containsFile(checkSpec_1.fileName, requireOpen)) { _this.syntacticCheck(checkSpec_1.fileName, checkSpec_1.project); - _this.immediateId = setImmediate(function () { + _this.immediateId = _this.host.setImmediate(function () { _this.semanticCheck(checkSpec_1.fileName, checkSpec_1.project); _this.immediateId = undefined; if (checkList.length > index) { - _this.errorTimer = setTimeout(checkOne, followMs); + _this.errorTimer = _this.host.setTimeout(checkOne, followMs); } else { _this.errorTimer = undefined; @@ -60652,78 +63854,133 @@ var ts; } }; if ((checkList.length > index) && (matchSeq(seq))) { - this.errorTimer = setTimeout(checkOne, ms); + this.errorTimer = this.host.setTimeout(checkOne, ms); } }; - Session.prototype.getDefinition = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + Session.prototype.cleanProjects = function (caption, projects) { + if (!projects) { + return; } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var definitions = compilerService.languageService.getDefinitionAtPosition(file, position); + this.logger.info("cleaning " + caption); + for (var _i = 0, projects_4 = projects; _i < projects_4.length; _i++) { + var p = projects_4[_i]; + p.getLanguageService(false).cleanupSemanticCache(); + } + }; + Session.prototype.cleanup = function () { + this.cleanProjects("inferred projects", this.projectService.inferredProjects); + this.cleanProjects("configured projects", this.projectService.configuredProjects); + this.cleanProjects("external projects", this.projectService.externalProjects); + if (this.host.gc) { + this.logger.info("host.gc()"); + this.host.gc(); + } + }; + Session.prototype.getEncodedSemanticClassifications = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getEncodedSemanticClassifications(file, args); + }; + Session.prototype.getProject = function (projectFileName) { + return projectFileName && this.projectService.findProject(projectFileName); + }; + Session.prototype.getCompilerOptionsDiagnostics = function (args) { + var project = this.getProject(args.projectFileName); + return this.convertToDiagnosticsWithLinePosition(project.getLanguageService().getCompilerOptionsDiagnostics(), undefined); + }; + Session.prototype.convertToDiagnosticsWithLinePosition = function (diagnostics, scriptInfo) { + var _this = this; + return diagnostics.map(function (d) { return ({ + message: ts.flattenDiagnosticMessageText(d.messageText, _this.host.newLine), + start: d.start, + length: d.length, + category: ts.DiagnosticCategory[d.category].toLowerCase(), + code: d.code, + startLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start), + endLocation: scriptInfo && scriptInfo.positionToLineOffset(d.start + d.length) + }); }); + }; + Session.prototype.getDiagnosticsWorker = function (args, selector, includeLinePosition) { + var _a = this.getFileAndProject(args), project = _a.project, file = _a.file; + if (shouldSkipSematicCheck(project)) { + return []; + } + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var diagnostics = selector(project, file); + return includeLinePosition + ? this.convertToDiagnosticsWithLinePosition(diagnostics, scriptInfo) + : diagnostics.map(function (d) { return formatDiag(file, project, d); }); + }; + Session.prototype.getDefinition = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var definitions = project.getLanguageService().getDefinitionAtPosition(file, position); if (!definitions) { return undefined; } - return definitions.map(function (def) { return ({ - file: def.fileName, - start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), - end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) - }); }); - }; - Session.prototype.getTypeDefinition = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + if (simplifiedResult) { + return definitions.map(function (def) { + var defScriptInfo = project.getScriptInfo(def.fileName); + return { + file: def.fileName, + start: defScriptInfo.positionToLineOffset(def.textSpan.start), + end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan)) + }; + }); } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var definitions = compilerService.languageService.getTypeDefinitionAtPosition(file, position); + else { + return definitions; + } + }; + Session.prototype.getTypeDefinition = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var definitions = project.getLanguageService().getTypeDefinitionAtPosition(file, position); if (!definitions) { return undefined; } - return definitions.map(function (def) { return ({ - file: def.fileName, - start: compilerService.host.positionToLineOffset(def.fileName, def.textSpan.start), - end: compilerService.host.positionToLineOffset(def.fileName, ts.textSpanEnd(def.textSpan)) - }); }); + return definitions.map(function (def) { + var defScriptInfo = project.getScriptInfo(def.fileName); + return { + file: def.fileName, + start: defScriptInfo.positionToLineOffset(def.textSpan.start), + end: defScriptInfo.positionToLineOffset(ts.textSpanEnd(def.textSpan)) + }; + }); }; - Session.prototype.getImplementation = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var implementations = compilerService.languageService.getImplementationAtPosition(file, compilerService.host.lineOffsetToPosition(file, line, offset)); + Session.prototype.getImplementation = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var implementations = project.getLanguageService().getImplementationAtPosition(file, position); if (!implementations) { - return undefined; + return []; + } + if (simplifiedResult) { + return implementations.map(function (impl) { return ({ + file: impl.fileName, + start: scriptInfo.positionToLineOffset(impl.textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(impl.textSpan)) + }); }); + } + else { + return implementations; } - return implementations.map(function (impl) { return ({ - file: impl.fileName, - start: compilerService.host.positionToLineOffset(impl.fileName, impl.textSpan.start), - end: compilerService.host.positionToLineOffset(impl.fileName, ts.textSpanEnd(impl.textSpan)) - }); }); }; - Session.prototype.getOccurrences = function (line, offset, fileName) { - fileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(fileName); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(fileName, line, offset); - var occurrences = compilerService.languageService.getOccurrencesAtPosition(fileName, position); + Session.prototype.getOccurrences = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var occurrences = project.getLanguageService().getOccurrencesAtPosition(file, position); if (!occurrences) { return undefined; } return occurrences.map(function (occurrence) { var fileName = occurrence.fileName, isWriteAccess = occurrence.isWriteAccess, textSpan = occurrence.textSpan; - var start = compilerService.host.positionToLineOffset(fileName, textSpan.start); - var end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan)); + var scriptInfo = project.getScriptInfo(fileName); + var start = scriptInfo.positionToLineOffset(textSpan.start); + var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)); return { start: start, end: end, @@ -60732,115 +63989,142 @@ var ts; }; }); }; - Session.prototype.getDiagnosticsWorker = function (args, selector) { - var file = ts.normalizePath(args.file); - var project = this.projectService.getProjectForFile(file); - if (!project) { - throw Errors.NoProject; - } - if (project.languageServiceDiabled) { - throw Errors.ProjectLanguageServiceDisabled; - } - var diagnostics = selector(project, file); - return ts.map(diagnostics, function (originalDiagnostic) { return formatDiag(file, project, originalDiagnostic); }); - }; Session.prototype.getSyntacticDiagnosticsSync = function (args) { - return this.getDiagnosticsWorker(args, function (project, file) { return project.compilerService.languageService.getSyntacticDiagnostics(file); }); + return this.getDiagnosticsWorker(args, function (project, file) { return project.getLanguageService().getSyntacticDiagnostics(file); }, args.includeLinePosition); }; Session.prototype.getSemanticDiagnosticsSync = function (args) { - return this.getDiagnosticsWorker(args, function (project, file) { return project.compilerService.languageService.getSemanticDiagnostics(file); }); + return this.getDiagnosticsWorker(args, function (project, file) { return project.getLanguageService().getSemanticDiagnostics(file); }, args.includeLinePosition); }; - Session.prototype.getDocumentHighlights = function (line, offset, fileName, filesToSearch) { - fileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(fileName); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(fileName, line, offset); - var documentHighlights = compilerService.languageService.getDocumentHighlights(fileName, position, filesToSearch); + Session.prototype.getDocumentHighlights = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var documentHighlights = project.getLanguageService().getDocumentHighlights(file, position, args.filesToSearch); if (!documentHighlights) { return undefined; } - return documentHighlights.map(convertToDocumentHighlightsItem); + if (simplifiedResult) { + return documentHighlights.map(convertToDocumentHighlightsItem); + } + else { + return documentHighlights; + } function convertToDocumentHighlightsItem(documentHighlights) { var fileName = documentHighlights.fileName, highlightSpans = documentHighlights.highlightSpans; + var scriptInfo = project.getScriptInfo(fileName); return { file: fileName, highlightSpans: highlightSpans.map(convertHighlightSpan) }; function convertHighlightSpan(highlightSpan) { var textSpan = highlightSpan.textSpan, kind = highlightSpan.kind; - var start = compilerService.host.positionToLineOffset(fileName, textSpan.start); - var end = compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(textSpan)); + var start = scriptInfo.positionToLineOffset(textSpan.start); + var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(textSpan)); return { start: start, end: end, kind: kind }; } } }; - Session.prototype.getProjectInfo = function (fileName, needFileNameList) { - fileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(fileName); - if (!project) { - throw Errors.NoProject; - } + Session.prototype.setCompilerOptionsForInferredProjects = function (args) { + this.projectService.setCompilerOptionsForInferredProjects(args.options); + }; + Session.prototype.getProjectInfo = function (args) { + return this.getProjectInfoWorker(args.file, args.projectFileName, args.needFileNameList); + }; + Session.prototype.getProjectInfoWorker = function (uncheckedFileName, projectFileName, needFileNameList) { + var project = this.getFileAndProjectWorker(uncheckedFileName, projectFileName, true, true).project; var projectInfo = { - configFileName: project.projectFilename, - languageServiceDisabled: project.languageServiceDiabled + configFileName: project.getProjectName(), + languageServiceDisabled: !project.languageServiceEnabled, + fileNames: needFileNameList ? project.getFileNames() : undefined }; - if (needFileNameList) { - projectInfo.fileNames = project.getFileNames(); - } return projectInfo; }; - Session.prototype.getRenameLocations = function (line, offset, fileName, findInComments, findInStrings) { - var file = ts.normalizePath(fileName); - var info = this.projectService.getScriptInfo(file); - var projects = this.projectService.findReferencingProjects(info); - var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); - if (projectsWithLanguageServiceEnabeld.length === 0) { - throw Errors.NoProject; - } - var defaultProject = projectsWithLanguageServiceEnabeld[0]; - var defaultProjectCompilerService = defaultProject.compilerService; - var position = defaultProjectCompilerService.host.lineOffsetToPosition(file, line, offset); - var renameInfo = defaultProjectCompilerService.languageService.getRenameInfo(file, position); - if (!renameInfo) { - return undefined; - } - if (!renameInfo.canRename) { - return { - info: renameInfo, - locs: [] - }; - } - var fileSpans = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { - var compilerService = project.compilerService; - var renameLocations = compilerService.languageService.findRenameLocations(file, position, findInStrings, findInComments); - if (!renameLocations) { - return []; + Session.prototype.getRenameInfo = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + return project.getLanguageService().getRenameInfo(file, position); + }; + Session.prototype.getProjects = function (args) { + var projects; + if (args.projectFileName) { + var project = this.getProject(args.projectFileName); + if (project) { + projects = [project]; } - return renameLocations.map(function (location) { return ({ - file: location.fileName, - start: compilerService.host.positionToLineOffset(location.fileName, location.textSpan.start), - end: compilerService.host.positionToLineOffset(location.fileName, ts.textSpanEnd(location.textSpan)) - }); }); - }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; }); - var locs = fileSpans.reduce(function (accum, cur) { - var curFileAccum; - if (accum.length > 0) { - curFileAccum = accum[accum.length - 1]; - if (curFileAccum.file !== cur.file) { - curFileAccum = undefined; + } + else { + var scriptInfo = this.projectService.getScriptInfo(args.file); + projects = scriptInfo.containingProjects; + } + projects = ts.filter(projects, function (p) { return p.languageServiceEnabled; }); + if (!projects || !projects.length) { + return server.Errors.ThrowNoProject(); + } + return projects; + }; + Session.prototype.getRenameLocations = function (args, simplifiedResult) { + var file = server.toNormalizedPath(args.file); + var info = this.projectService.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, info); + var projects = this.getProjects(args); + if (simplifiedResult) { + var defaultProject = projects[0]; + var renameInfo = defaultProject.getLanguageService().getRenameInfo(file, position); + if (!renameInfo) { + return undefined; + } + if (!renameInfo.canRename) { + return { + info: renameInfo, + locs: [] + }; + } + var fileSpans = server.combineProjectOutput(projects, function (project) { + var renameLocations = project.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); + if (!renameLocations) { + return []; } + return renameLocations.map(function (location) { + var locationScriptInfo = project.getScriptInfo(location.fileName); + return { + file: location.fileName, + start: locationScriptInfo.positionToLineOffset(location.textSpan.start), + end: locationScriptInfo.positionToLineOffset(ts.textSpanEnd(location.textSpan)) + }; + }); + }, compareRenameLocation, function (a, b) { return a.file === b.file && a.start.line === b.start.line && a.start.offset === b.start.offset; }); + var locs = fileSpans.reduce(function (accum, cur) { + var curFileAccum; + if (accum.length > 0) { + curFileAccum = accum[accum.length - 1]; + if (curFileAccum.file !== cur.file) { + curFileAccum = undefined; + } + } + if (!curFileAccum) { + curFileAccum = { file: cur.file, locs: [] }; + accum.push(curFileAccum); + } + curFileAccum.locs.push({ start: cur.start, end: cur.end }); + return accum; + }, []); + return { info: renameInfo, locs: locs }; + } + else { + return server.combineProjectOutput(projects, function (p) { return p.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); }, undefined, renameLocationIsEqualTo); + } + function renameLocationIsEqualTo(a, b) { + if (a === b) { + return true; } - if (!curFileAccum) { - curFileAccum = { file: cur.file, locs: [] }; - accum.push(curFileAccum); + if (!a || !b) { + return false; } - curFileAccum.locs.push({ start: cur.start, end: cur.end }); - return accum; - }, []); - return { info: renameInfo, locs: locs }; + return a.fileName === b.fileName && + a.textSpan.start === b.textSpan.start && + a.textSpan.length === b.textSpan.length; + } function compareRenameLocation(a, b) { if (a.file < b.file) { return -1; @@ -60861,51 +64145,51 @@ var ts; } } }; - Session.prototype.getReferences = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var info = this.projectService.getScriptInfo(file); - var projects = this.projectService.findReferencingProjects(info); - var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); - if (projectsWithLanguageServiceEnabeld.length === 0) { - throw Errors.NoProject; - } - var defaultProject = projectsWithLanguageServiceEnabeld[0]; - var position = defaultProject.compilerService.host.lineOffsetToPosition(file, line, offset); - var nameInfo = defaultProject.compilerService.languageService.getQuickInfoAtPosition(file, position); - if (!nameInfo) { - return undefined; - } - var displayString = ts.displayPartsToString(nameInfo.displayParts); - var nameSpan = nameInfo.textSpan; - var nameColStart = defaultProject.compilerService.host.positionToLineOffset(file, nameSpan.start).offset; - var nameText = defaultProject.compilerService.host.getScriptSnapshot(file).getText(nameSpan.start, ts.textSpanEnd(nameSpan)); - var refs = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { - var compilerService = project.compilerService; - var references = compilerService.languageService.getReferencesAtPosition(file, position); - if (!references) { - return []; + Session.prototype.getReferences = function (args, simplifiedResult) { + var file = server.toNormalizedPath(args.file); + var projects = this.getProjects(args); + var defaultProject = projects[0]; + var scriptInfo = defaultProject.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + if (simplifiedResult) { + var nameInfo = defaultProject.getLanguageService().getQuickInfoAtPosition(file, position); + if (!nameInfo) { + return undefined; } - return references.map(function (ref) { - var start = compilerService.host.positionToLineOffset(ref.fileName, ref.textSpan.start); - var refLineSpan = compilerService.host.lineToTextSpan(ref.fileName, start.line - 1); - var snap = compilerService.host.getScriptSnapshot(ref.fileName); - var lineText = snap.getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); - return { - file: ref.fileName, - start: start, - lineText: lineText, - end: compilerService.host.positionToLineOffset(ref.fileName, ts.textSpanEnd(ref.textSpan)), - isWriteAccess: ref.isWriteAccess, - isDefinition: ref.isDefinition - }; - }); - }, compareFileStart, areReferencesResponseItemsForTheSameLocation); - return { - refs: refs, - symbolName: nameText, - symbolStartOffset: nameColStart, - symbolDisplayString: displayString - }; + var displayString = ts.displayPartsToString(nameInfo.displayParts); + var nameSpan = nameInfo.textSpan; + var nameColStart = scriptInfo.positionToLineOffset(nameSpan.start).offset; + var nameText = scriptInfo.snap().getText(nameSpan.start, ts.textSpanEnd(nameSpan)); + var refs = server.combineProjectOutput(projects, function (project) { + var references = project.getLanguageService().getReferencesAtPosition(file, position); + if (!references) { + return []; + } + return references.map(function (ref) { + var refScriptInfo = project.getScriptInfo(ref.fileName); + var start = refScriptInfo.positionToLineOffset(ref.textSpan.start); + var refLineSpan = refScriptInfo.lineToTextSpan(start.line - 1); + var lineText = refScriptInfo.snap().getText(refLineSpan.start, ts.textSpanEnd(refLineSpan)).replace(/\r|\n/g, ""); + return { + file: ref.fileName, + start: start, + lineText: lineText, + end: refScriptInfo.positionToLineOffset(ts.textSpanEnd(ref.textSpan)), + isWriteAccess: ref.isWriteAccess, + isDefinition: ref.isDefinition + }; + }); + }, compareFileStart, areReferencesResponseItemsForTheSameLocation); + return { + refs: refs, + symbolName: nameText, + symbolStartOffset: nameColStart, + symbolDisplayString: displayString + }; + } + else { + return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().findReferences(file, position); }, undefined, undefined); + } function areReferencesResponseItemsForTheSameLocation(a, b) { if (a && b) { return a.file === b.file && @@ -60916,102 +64200,150 @@ var ts; } }; Session.prototype.openClientFile = function (fileName, fileContent, scriptKind) { - var file = ts.normalizePath(fileName); - var _a = this.projectService.openClientFile(file, fileContent, scriptKind), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; - if (configFileErrors) { - this.configFileDiagnosticEvent(fileName, configFileName, configFileErrors); + var _a = this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; + if (this.eventHander) { + this.eventHander({ + eventName: "configFileDiag", + data: { fileName: fileName, configFileName: configFileName, diagnostics: configFileErrors || [] } + }); } }; - Session.prototype.getQuickInfo = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + Session.prototype.getPosition = function (args, scriptInfo) { + return args.position !== undefined ? args.position : scriptInfo.lineOffsetToPosition(args.line, args.offset); + }; + Session.prototype.getFileAndProject = function (args, errorOnMissingProject) { + if (errorOnMissingProject === void 0) { errorOnMissingProject = true; } + return this.getFileAndProjectWorker(args.file, args.projectFileName, true, errorOnMissingProject); + }; + Session.prototype.getFileAndProjectWithoutRefreshingInferredProjects = function (args, errorOnMissingProject) { + if (errorOnMissingProject === void 0) { errorOnMissingProject = true; } + return this.getFileAndProjectWorker(args.file, args.projectFileName, false, errorOnMissingProject); + }; + Session.prototype.getFileAndProjectWorker = function (uncheckedFileName, projectFileName, refreshInferredProjects, errorOnMissingProject) { + var file = server.toNormalizedPath(uncheckedFileName); + var project = this.getProject(projectFileName) || this.projectService.getDefaultProjectForFile(file, refreshInferredProjects); + if (!project && errorOnMissingProject) { + return server.Errors.ThrowNoProject(); } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var quickInfo = compilerService.languageService.getQuickInfoAtPosition(file, position); + return { file: file, project: project }; + }; + Session.prototype.getOutliningSpans = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + return project.getLanguageService(false).getOutliningSpans(file); + }; + Session.prototype.getTodoComments = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + return project.getLanguageService().getTodoComments(file, args.descriptors); + }; + Session.prototype.getDocCommentTemplate = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + return project.getLanguageService(false).getDocCommentTemplateAtPosition(file, position); + }; + Session.prototype.getIndentation = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + var options = args.options || this.projectService.getFormatCodeOptions(file); + var indentation = project.getLanguageService(false).getIndentationAtPosition(file, position, options); + return { position: position, indentation: indentation }; + }; + Session.prototype.getBreakpointStatement = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + return project.getLanguageService(false).getBreakpointStatementAtPosition(file, position); + }; + Session.prototype.getNameOrDottedNameSpan = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + return project.getLanguageService(false).getNameOrDottedNameSpan(file, position, position); + }; + Session.prototype.isValidBraceCompletion = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); + return project.getLanguageService(false).isValidBraceCompletionAtPosition(file, position, args.openingBrace.charCodeAt(0)); + }; + Session.prototype.getQuickInfoWorker = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var quickInfo = project.getLanguageService().getQuickInfoAtPosition(file, this.getPosition(args, scriptInfo)); if (!quickInfo) { return undefined; } - var displayString = ts.displayPartsToString(quickInfo.displayParts); - var docString = ts.displayPartsToString(quickInfo.documentation); - return { - kind: quickInfo.kind, - kindModifiers: quickInfo.kindModifiers, - start: compilerService.host.positionToLineOffset(file, quickInfo.textSpan.start), - end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(quickInfo.textSpan)), - displayString: displayString, - documentation: docString - }; - }; - Session.prototype.getFormattingEditsForRange = function (line, offset, endLine, endOffset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + if (simplifiedResult) { + var displayString = ts.displayPartsToString(quickInfo.displayParts); + var docString = ts.displayPartsToString(quickInfo.documentation); + return { + kind: quickInfo.kind, + kindModifiers: quickInfo.kindModifiers, + start: scriptInfo.positionToLineOffset(quickInfo.textSpan.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(quickInfo.textSpan)), + displayString: displayString, + documentation: docString + }; } - var compilerService = project.compilerService; - var startPosition = compilerService.host.lineOffsetToPosition(file, line, offset); - var endPosition = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); - var edits = compilerService.languageService.getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); + else { + return quickInfo; + } + }; + Session.prototype.getFormattingEditsForRange = function (args) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var startPosition = scriptInfo.lineOffsetToPosition(args.line, args.offset); + var endPosition = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + var edits = project.getLanguageService(false).getFormattingEditsForRange(file, startPosition, endPosition, this.projectService.getFormatCodeOptions(file)); if (!edits) { return undefined; } - return edits.map(function (edit) { - return { - start: compilerService.host.positionToLineOffset(file, edit.span.start), - end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)), - newText: edit.newText ? edit.newText : "" - }; - }); + return edits.map(function (edit) { return _this.convertTextChangeToCodeEdit(edit, scriptInfo); }); }; - Session.prototype.getFormattingEditsAfterKeystroke = function (line, offset, key, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); + Session.prototype.getFormattingEditsForRangeFull = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var options = args.options || this.projectService.getFormatCodeOptions(file); + return project.getLanguageService(false).getFormattingEditsForRange(file, args.position, args.endPosition, options); + }; + Session.prototype.getFormattingEditsForDocumentFull = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var options = args.options || this.projectService.getFormatCodeOptions(file); + return project.getLanguageService(false).getFormattingEditsForDocument(file, options); + }; + Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var options = args.options || this.projectService.getFormatCodeOptions(file); + return project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, args.position, args.key, options); + }; + Session.prototype.getFormattingEditsAfterKeystroke = function (args) { + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = scriptInfo.lineOffsetToPosition(args.line, args.offset); var formatOptions = this.projectService.getFormatCodeOptions(file); - var edits = compilerService.languageService.getFormattingEditsAfterKeystroke(file, position, key, formatOptions); - if ((key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { - var scriptInfo = compilerService.host.getScriptInfo(file); - if (scriptInfo) { - var lineInfo = scriptInfo.getLineInfo(line); - if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) { - var lineText = lineInfo.leaf.text; - if (lineText.search("\\S") < 0) { - var editorOptions = { - BaseIndentSize: formatOptions.BaseIndentSize, - IndentSize: formatOptions.IndentSize, - TabSize: formatOptions.TabSize, - NewLineCharacter: formatOptions.NewLineCharacter, - ConvertTabsToSpaces: formatOptions.ConvertTabsToSpaces, - IndentStyle: ts.IndentStyle.Smart - }; - var preferredIndent = compilerService.languageService.getIndentationAtPosition(file, position, editorOptions); - var hasIndent = 0; - var i = void 0, len = void 0; - for (i = 0, len = lineText.length; i < len; i++) { - if (lineText.charAt(i) == " ") { - hasIndent++; - } - else if (lineText.charAt(i) == "\t") { - hasIndent += editorOptions.TabSize; - } - else { - break; - } + var edits = project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, position, args.key, formatOptions); + if ((args.key == "\n") && ((!edits) || (edits.length === 0) || allEditsBeforePos(edits, position))) { + var lineInfo = scriptInfo.getLineInfo(args.line); + if (lineInfo && (lineInfo.leaf) && (lineInfo.leaf.text)) { + var lineText = lineInfo.leaf.text; + if (lineText.search("\\S") < 0) { + var preferredIndent = project.getLanguageService(false).getIndentationAtPosition(file, position, formatOptions); + var hasIndent = 0; + var i = void 0, len = void 0; + for (i = 0, len = lineText.length; i < len; i++) { + if (lineText.charAt(i) == " ") { + hasIndent++; } - if (preferredIndent !== hasIndent) { - var firstNoWhiteSpacePosition = lineInfo.offset + i; - edits.push({ - span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition), - newText: generateIndentString(preferredIndent, editorOptions) - }); + else if (lineText.charAt(i) == "\t") { + hasIndent += formatOptions.tabSize; } + else { + break; + } + } + if (preferredIndent !== hasIndent) { + var firstNoWhiteSpacePosition = lineInfo.offset + i; + edits.push({ + span: ts.createTextSpanFromBounds(lineInfo.offset, firstNoWhiteSpacePosition), + newText: ts.formatting.getIndentationString(preferredIndent, formatOptions) + }); } } } @@ -61021,89 +64353,106 @@ var ts; } return edits.map(function (edit) { return { - start: compilerService.host.positionToLineOffset(file, edit.span.start), - end: compilerService.host.positionToLineOffset(file, ts.textSpanEnd(edit.span)), + start: scriptInfo.positionToLineOffset(edit.span.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(edit.span)), newText: edit.newText ? edit.newText : "" }; }); }; - Session.prototype.getCompletions = function (line, offset, prefix, fileName) { - if (!prefix) { - prefix = ""; - } - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var completions = compilerService.languageService.getCompletionsAtPosition(file, position); + Session.prototype.getCompletions = function (args, simplifiedResult) { + var _this = this; + var prefix = args.prefix || ""; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var completions = project.getLanguageService().getCompletionsAtPosition(file, position); if (!completions) { return undefined; } - return completions.entries.reduce(function (result, entry) { - if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { - var name_52 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; - var convertedSpan = undefined; - if (replacementSpan) { - convertedSpan = { - start: compilerService.host.positionToLineOffset(fileName, replacementSpan.start), - end: compilerService.host.positionToLineOffset(fileName, replacementSpan.start + replacementSpan.length) - }; + if (simplifiedResult) { + return completions.entries.reduce(function (result, entry) { + if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { + var name_53 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; + var convertedSpan = replacementSpan ? _this.decorateSpan(replacementSpan, scriptInfo) : undefined; + result.push({ name: name_53, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }); } - result.push({ name: name_52, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }); - } - return result; - }, []).sort(function (a, b) { return a.name.localeCompare(b.name); }); - }; - Session.prototype.getCompletionEntryDetails = function (line, offset, entryNames, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + return result; + }, []).sort(function (a, b) { return a.name.localeCompare(b.name); }); } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - return entryNames.reduce(function (accum, entryName) { - var details = compilerService.languageService.getCompletionEntryDetails(file, position, entryName); + else { + return completions; + } + }; + Session.prototype.getCompletionEntryDetails = function (args) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + return args.entryNames.reduce(function (accum, entryName) { + var details = project.getLanguageService().getCompletionEntryDetails(file, position, entryName); if (details) { accum.push(details); } return accum; }, []); }; - Session.prototype.getSignatureHelpItems = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; + Session.prototype.getCompileOnSaveAffectedFileList = function (args) { + var info = this.projectService.getScriptInfo(args.file); + var result = []; + if (!info) { + return []; } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var helpItems = compilerService.languageService.getSignatureHelpItems(file, position); + var projectsToSearch = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; + for (var _i = 0, projectsToSearch_1 = projectsToSearch; _i < projectsToSearch_1.length; _i++) { + var project = projectsToSearch_1[_i]; + if (project.compileOnSaveEnabled && project.languageServiceEnabled) { + result.push({ + projectFileName: project.getProjectName(), + fileNames: project.getCompileOnSaveAffectedFileList(info) + }); + } + } + return result; + }; + Session.prototype.emitFile = function (args) { + var _this = this; + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + if (!project) { + server.Errors.ThrowNoProject(); + } + var scriptInfo = project.getScriptInfo(file); + return project.builder.emitFile(scriptInfo, function (path, data, writeByteOrderMark) { return _this.host.writeFile(path, data, writeByteOrderMark); }); + }; + Session.prototype.getSignatureHelpItems = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var helpItems = project.getLanguageService().getSignatureHelpItems(file, position); if (!helpItems) { return undefined; } - var span = helpItems.applicableSpan; - var result = { - items: helpItems.items, - applicableSpan: { - start: compilerService.host.positionToLineOffset(file, span.start), - end: compilerService.host.positionToLineOffset(file, span.start + span.length) - }, - selectedItemIndex: helpItems.selectedItemIndex, - argumentIndex: helpItems.argumentIndex, - argumentCount: helpItems.argumentCount - }; - return result; + if (simplifiedResult) { + var span_16 = helpItems.applicableSpan; + return { + items: helpItems.items, + applicableSpan: { + start: scriptInfo.positionToLineOffset(span_16.start), + end: scriptInfo.positionToLineOffset(span_16.start + span_16.length) + }, + selectedItemIndex: helpItems.selectedItemIndex, + argumentIndex: helpItems.argumentIndex, + argumentCount: helpItems.argumentCount + }; + } + else { + return helpItems; + } }; Session.prototype.getDiagnostics = function (delay, fileNames) { var _this = this; - var checkList = fileNames.reduce(function (accum, fileName) { - fileName = ts.normalizePath(fileName); - var project = _this.projectService.getProjectForFile(fileName); - if (project && !project.languageServiceDiabled) { + var checkList = fileNames.reduce(function (accum, uncheckedFileName) { + var fileName = server.toNormalizedPath(uncheckedFileName); + var project = _this.projectService.getDefaultProjectForFile(fileName, true); + if (project) { accum.push({ fileName: fileName, project: project }); } return accum; @@ -61112,40 +64461,34 @@ var ts; this.updateErrorCheck(checkList, this.changeSeq, function (n) { return n === _this.changeSeq; }, delay); } }; - Session.prototype.change = function (line, offset, endLine, endOffset, insertString, fileName) { + Session.prototype.change = function (args) { var _this = this; - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (project && !project.languageServiceDiabled) { - var compilerService = project.compilerService; - var start = compilerService.host.lineOffsetToPosition(file, line, offset); - var end = compilerService.host.lineOffsetToPosition(file, endLine, endOffset); + var _a = this.getFileAndProject(args, false), file = _a.file, project = _a.project; + if (project) { + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var start = scriptInfo.lineOffsetToPosition(args.line, args.offset); + var end = scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); if (start >= 0) { - compilerService.host.editScript(file, start, end, insertString); + scriptInfo.editContent(start, end, args.insertString); this.changeSeq++; } this.updateProjectStructure(this.changeSeq, function (n) { return n === _this.changeSeq; }); } }; - Session.prototype.reload = function (fileName, tempFileName, reqSeq) { - var _this = this; - if (reqSeq === void 0) { reqSeq = 0; } - var file = ts.normalizePath(fileName); - var tmpfile = ts.normalizePath(tempFileName); - var project = this.projectService.getProjectForFile(file); - if (project && !project.languageServiceDiabled) { + Session.prototype.reload = function (args, reqSeq) { + var file = server.toNormalizedPath(args.file); + var project = this.projectService.getDefaultProjectForFile(file, true); + if (project) { this.changeSeq++; - project.compilerService.host.reloadScript(file, tmpfile, function () { - _this.output(undefined, CommandNames.Reload, reqSeq); - }); + if (project.reloadScript(file)) { + this.output(undefined, CommandNames.Reload, reqSeq); + } } }; Session.prototype.saveToTmp = function (fileName, tempFileName) { - var file = ts.normalizePath(fileName); - var tmpfile = ts.normalizePath(tempFileName); - var project = this.projectService.getProjectForFile(file); - if (project && !project.languageServiceDiabled) { - project.compilerService.host.saveTo(file, tmpfile); + var scriptInfo = this.projectService.getScriptInfo(fileName); + if (scriptInfo) { + scriptInfo.saveTo(tempFileName); } }; Session.prototype.closeClientFile = function (fileName) { @@ -61155,77 +64498,108 @@ var ts; var file = ts.normalizePath(fileName); this.projectService.closeClientFile(file); }; - Session.prototype.decorateNavigationBarItem = function (project, fileName, items, lineIndex) { + Session.prototype.decorateNavigationBarItems = function (items, scriptInfo) { var _this = this; - if (!items) { - return undefined; - } - var compilerService = project.compilerService; - return items.map(function (item) { return ({ + return ts.map(items, function (item) { return ({ text: item.text, kind: item.kind, kindModifiers: item.kindModifiers, - spans: item.spans.map(function (span) { return ({ - start: compilerService.host.positionToLineOffset(fileName, span.start, lineIndex), - end: compilerService.host.positionToLineOffset(fileName, ts.textSpanEnd(span), lineIndex) - }); }), - childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems, lineIndex), + spans: item.spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }), + childItems: _this.decorateNavigationBarItems(item.childItems, scriptInfo), indent: item.indent }); }); }; - Session.prototype.getNavigationBarItems = function (fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var items = compilerService.languageService.getNavigationBarItems(file); - if (!items) { - return undefined; - } - return this.decorateNavigationBarItem(project, fileName, items, compilerService.host.getLineIndex(fileName)); + Session.prototype.getNavigationBarItems = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var items = project.getLanguageService(false).getNavigationBarItems(file); + return !items + ? undefined + : simplifiedResult + ? this.decorateNavigationBarItems(items, project.getScriptInfoForNormalizedPath(file)) + : items; }; - Session.prototype.getNavigateToItems = function (searchValue, fileName, maxResultCount, currentFileOnly) { - var file = ts.normalizePath(fileName); - var info = this.projectService.getScriptInfo(file); - var projects = this.projectService.findReferencingProjects(info); - var projectsWithLanguageServiceEnabeld = ts.filter(projects, function (p) { return !p.languageServiceDiabled; }); - if (projectsWithLanguageServiceEnabeld.length === 0) { - throw Errors.NoProject; + Session.prototype.decorateNavigationTree = function (tree, scriptInfo) { + var _this = this; + return { + text: tree.text, + kind: tree.kind, + kindModifiers: tree.kindModifiers, + spans: tree.spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }), + childItems: ts.map(tree.childItems, function (item) { return _this.decorateNavigationTree(item, scriptInfo); }) + }; + }; + Session.prototype.decorateSpan = function (span, scriptInfo) { + return { + start: scriptInfo.positionToLineOffset(span.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(span)) + }; + }; + Session.prototype.getNavigationTree = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var tree = project.getLanguageService(false).getNavigationTree(file); + return !tree + ? undefined + : simplifiedResult + ? this.decorateNavigationTree(tree, project.getScriptInfoForNormalizedPath(file)) + : tree; + }; + Session.prototype.getNavigateToItems = function (args, simplifiedResult) { + var projects = this.getProjects(args); + var fileName = args.currentFileOnly ? args.file && ts.normalizeSlashes(args.file) : undefined; + if (simplifiedResult) { + return server.combineProjectOutput(projects, function (project) { + var navItems = project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); + if (!navItems) { + return []; + } + return navItems.map(function (navItem) { + var scriptInfo = project.getScriptInfo(navItem.fileName); + var start = scriptInfo.positionToLineOffset(navItem.textSpan.start); + var end = scriptInfo.positionToLineOffset(ts.textSpanEnd(navItem.textSpan)); + var bakedItem = { + name: navItem.name, + kind: navItem.kind, + file: navItem.fileName, + start: start, + end: end + }; + if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { + bakedItem.kindModifiers = navItem.kindModifiers; + } + if (navItem.matchKind !== "none") { + bakedItem.matchKind = navItem.matchKind; + } + if (navItem.containerName && (navItem.containerName.length > 0)) { + bakedItem.containerName = navItem.containerName; + } + if (navItem.containerKind && (navItem.containerKind.length > 0)) { + bakedItem.containerKind = navItem.containerKind; + } + return bakedItem; + }); + }, undefined, areNavToItemsForTheSameLocation); } - var allNavToItems = server.combineProjectOutput(projectsWithLanguageServiceEnabeld, function (project) { - var compilerService = project.compilerService; - var navItems = compilerService.languageService.getNavigateToItems(searchValue, maxResultCount, currentFileOnly ? fileName : undefined); - if (!navItems) { - return []; + else { + return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); }, undefined, navigateToItemIsEqualTo); + } + function navigateToItemIsEqualTo(a, b) { + if (a === b) { + return true; } - return navItems.map(function (navItem) { - var start = compilerService.host.positionToLineOffset(navItem.fileName, navItem.textSpan.start); - var end = compilerService.host.positionToLineOffset(navItem.fileName, ts.textSpanEnd(navItem.textSpan)); - var bakedItem = { - name: navItem.name, - kind: navItem.kind, - file: navItem.fileName, - start: start, - end: end - }; - if (navItem.kindModifiers && (navItem.kindModifiers !== "")) { - bakedItem.kindModifiers = navItem.kindModifiers; - } - if (navItem.matchKind !== "none") { - bakedItem.matchKind = navItem.matchKind; - } - if (navItem.containerName && (navItem.containerName.length > 0)) { - bakedItem.containerName = navItem.containerName; - } - if (navItem.containerKind && (navItem.containerKind.length > 0)) { - bakedItem.containerKind = navItem.containerKind; - } - return bakedItem; - }); - }, undefined, areNavToItemsForTheSameLocation); - return allNavToItems; + if (!a || !b) { + return false; + } + return a.containerKind === b.containerKind && + a.containerName === b.containerName && + a.fileName === b.fileName && + a.isCaseSensitive === b.isCaseSensitive && + a.kind === b.kind && + a.kindModifiers === b.containerName && + a.matchKind === b.matchKind && + a.name === b.name && + a.textSpan.start === b.textSpan.start && + a.textSpan.length === b.textSpan.length; + } function areNavToItemsForTheSameLocation(a, b) { if (a && b) { return a.file === b.file && @@ -61235,26 +64609,64 @@ var ts; return false; } }; - Session.prototype.getBraceMatching = function (line, offset, fileName) { - var file = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(file); - if (!project || project.languageServiceDiabled) { - throw Errors.NoProject; - } - var compilerService = project.compilerService; - var position = compilerService.host.lineOffsetToPosition(file, line, offset); - var spans = compilerService.languageService.getBraceMatchingAtPosition(file, position); - if (!spans) { + Session.prototype.getSupportedCodeFixes = function () { + return ts.getSupportedCodeFixes(); + }; + Session.prototype.getCodeFixes = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var startPosition = getStartPosition(); + var endPosition = getEndPosition(); + var codeActions = project.getLanguageService().getCodeFixesAtPosition(file, startPosition, endPosition, args.errorCodes); + if (!codeActions) { return undefined; } - return spans.map(function (span) { return ({ - start: compilerService.host.positionToLineOffset(file, span.start), - end: compilerService.host.positionToLineOffset(file, span.start + span.length) - }); }); + if (simplifiedResult) { + return codeActions.map(function (codeAction) { return _this.mapCodeAction(codeAction, scriptInfo); }); + } + else { + return codeActions; + } + function getStartPosition() { + return args.startPosition !== undefined ? args.startPosition : scriptInfo.lineOffsetToPosition(args.startLine, args.startOffset); + } + function getEndPosition() { + return args.endPosition !== undefined ? args.endPosition : scriptInfo.lineOffsetToPosition(args.endLine, args.endOffset); + } + }; + Session.prototype.mapCodeAction = function (codeAction, scriptInfo) { + var _this = this; + return { + description: codeAction.description, + changes: codeAction.changes.map(function (change) { return ({ + fileName: change.fileName, + textChanges: change.textChanges.map(function (textChange) { return _this.convertTextChangeToCodeEdit(textChange, scriptInfo); }) + }); }) + }; + }; + Session.prototype.convertTextChangeToCodeEdit = function (change, scriptInfo) { + return { + start: scriptInfo.positionToLineOffset(change.span.start), + end: scriptInfo.positionToLineOffset(change.span.start + change.span.length), + newText: change.newText ? change.newText : "" + }; + }; + Session.prototype.getBraceMatching = function (args, simplifiedResult) { + var _this = this; + var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; + var scriptInfo = project.getScriptInfoForNormalizedPath(file); + var position = this.getPosition(args, scriptInfo); + var spans = project.getLanguageService(false).getBraceMatchingAtPosition(file, position); + return !spans + ? undefined + : simplifiedResult + ? spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }) + : spans; }; Session.prototype.getDiagnosticsForProject = function (delay, fileName) { var _this = this; - var _a = this.getProjectInfo(fileName, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; + var _a = this.getProjectInfoWorker(fileName, undefined, true), fileNames = _a.fileNames, languageServiceDisabled = _a.languageServiceDisabled; if (languageServiceDisabled) { return; } @@ -61263,8 +64675,8 @@ var ts; var mediumPriorityFiles = []; var lowPriorityFiles = []; var veryLowPriorityFiles = []; - var normalizedFileName = ts.normalizePath(fileName); - var project = this.projectService.getProjectForFile(normalizedFileName); + var normalizedFileName = server.toNormalizedPath(fileName); + var project = this.projectService.getDefaultProjectForFile(normalizedFileName, true); for (var _i = 0, fileNamesInProject_1 = fileNamesInProject; _i < fileNamesInProject_1.length; _i++) { var fileNameInProject = fileNamesInProject_1[_i]; if (this.getCanonicalFileName(fileNameInProject) == this.getCanonicalFileName(fileName)) @@ -61283,10 +64695,7 @@ var ts; } fileNamesInProject = highPriorityFiles.concat(mediumPriorityFiles).concat(lowPriorityFiles).concat(veryLowPriorityFiles); if (fileNamesInProject.length > 0) { - var checkList = fileNamesInProject.map(function (fileName) { - var normalizedFileName = ts.normalizePath(fileName); - return { fileName: normalizedFileName, project: project }; - }); + var checkList = fileNamesInProject.map(function (fileName) { return ({ fileName: fileName, project: project }); }); this.updateErrorCheck(checkList, this.changeSeq, function (n) { return n == _this.changeSeq; }, delay, 200, false); } }; @@ -61296,6 +64705,9 @@ var ts; }; Session.prototype.exit = function () { }; + Session.prototype.notRequired = function () { + return { responseRequired: false }; + }; Session.prototype.requiredResponse = function (response) { return { response: response, responseRequired: true }; }; @@ -61311,31 +64723,32 @@ var ts; return handler(request); } else { - this.projectService.log("Unrecognized JSON command: " + JSON.stringify(request)); + this.logger.msg("Unrecognized JSON command: " + JSON.stringify(request), server.Msg.Err); this.output(undefined, CommandNames.Unknown, request.seq, "Unrecognized JSON command: " + request.command); return { responseRequired: false }; } }; Session.prototype.onMessage = function (message) { + this.gcTimer.scheduleCollect(); var start; - if (this.logger.isVerbose()) { - this.logger.info("request: " + message); + if (this.logger.hasLevel(server.LogLevel.requestTime)) { start = this.hrtime(); + if (this.logger.hasLevel(server.LogLevel.verbose)) { + this.logger.info("request: " + message); + } } var request; try { request = JSON.parse(message); var _a = this.executeCommand(request), response = _a.response, responseRequired = _a.responseRequired; - if (this.logger.isVerbose()) { - var elapsed = this.hrtime(start); - var seconds = elapsed[0]; - var nanoseconds = elapsed[1]; - var elapsedMs = ((1e9 * seconds) + nanoseconds) / 1000000.0; - var leader = "Elapsed time (in milliseconds)"; - if (!responseRequired) { - leader = "Async elapsed time (in milliseconds)"; + if (this.logger.hasLevel(server.LogLevel.requestTime)) { + var elapsedTime = hrTimeToMilliseconds(this.hrtime(start)).toFixed(4); + if (responseRequired) { + this.logger.perftrc(request.seq + "::" + request.command + ": elapsed time (in milliseconds) " + elapsedTime); + } + else { + this.logger.perftrc(request.seq + "::" + request.command + ": async elapsed time (in milliseconds) " + elapsedTime); } - this.logger.msg(leader + ": " + elapsedMs.toFixed(4).toString(), "Perf"); } if (response) { this.output(response, request.command, request.seq); @@ -61346,6 +64759,8 @@ var ts; } catch (err) { if (err instanceof ts.OperationCanceledException) { + this.output({ canceled: true }, request.command, request.seq); + return; } this.logError(err, message); this.output(undefined, request ? request.command : CommandNames.Unknown, request ? request.seq : 0, "Error processing request. " + err.message + "\n" + err.stack); @@ -61361,1229 +64776,6 @@ var ts; var server; (function (server) { var lineCollectionCapacity = 4; - function mergeFormatOptions(formatCodeOptions, formatOptions) { - var hasOwnProperty = Object.prototype.hasOwnProperty; - Object.keys(formatOptions).forEach(function (key) { - var codeKey = key.charAt(0).toUpperCase() + key.substring(1); - if (hasOwnProperty.call(formatCodeOptions, codeKey)) { - formatCodeOptions[codeKey] = formatOptions[key]; - } - }); - } - server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; - var ScriptInfo = (function () { - function ScriptInfo(host, fileName, content, isOpen) { - if (isOpen === void 0) { isOpen = false; } - this.host = host; - this.fileName = fileName; - this.isOpen = isOpen; - this.children = []; - this.formatCodeOptions = ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host)); - this.path = ts.toPath(fileName, host.getCurrentDirectory(), ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames)); - this.svc = ScriptVersionCache.fromString(host, content); - } - ScriptInfo.prototype.setFormatOptions = function (formatOptions) { - if (formatOptions) { - mergeFormatOptions(this.formatCodeOptions, formatOptions); - } - }; - ScriptInfo.prototype.close = function () { - this.isOpen = false; - }; - ScriptInfo.prototype.addChild = function (childInfo) { - this.children.push(childInfo); - }; - ScriptInfo.prototype.snap = function () { - return this.svc.getSnapshot(); - }; - ScriptInfo.prototype.getText = function () { - var snap = this.snap(); - return snap.getText(0, snap.getLength()); - }; - ScriptInfo.prototype.getLineInfo = function (line) { - var snap = this.snap(); - return snap.index.lineNumberToInfo(line); - }; - ScriptInfo.prototype.editContent = function (start, end, newText) { - this.svc.edit(start, end - start, newText); - }; - ScriptInfo.prototype.getTextChangeRangeBetweenVersions = function (startVersion, endVersion) { - return this.svc.getTextChangesBetweenVersions(startVersion, endVersion); - }; - ScriptInfo.prototype.getChangeRange = function (oldSnapshot) { - return this.snap().getChangeRange(oldSnapshot); - }; - return ScriptInfo; - }()); - server.ScriptInfo = ScriptInfo; - var LSHost = (function () { - function LSHost(host, project) { - var _this = this; - this.host = host; - this.project = project; - this.roots = []; - this.getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - this.resolvedModuleNames = ts.createFileMap(); - this.resolvedTypeReferenceDirectives = ts.createFileMap(); - this.filenameToScript = ts.createFileMap(); - this.moduleResolutionHost = { - fileExists: function (fileName) { return _this.fileExists(fileName); }, - readFile: function (fileName) { return _this.host.readFile(fileName); }, - directoryExists: function (directoryName) { return _this.host.directoryExists(directoryName); } - }; - if (this.host.realpath) { - this.moduleResolutionHost.realpath = function (path) { return _this.host.realpath(path); }; - } - } - LSHost.prototype.resolveNamesWithLocalCache = function (names, containingFile, cache, loader, getResult) { - var path = ts.toPath(containingFile, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var currentResolutionsInFile = cache.get(path); - var newResolutions = ts.createMap(); - var resolvedModules = []; - var compilerOptions = this.getCompilationSettings(); - for (var _i = 0, names_3 = names; _i < names_3.length; _i++) { - var name_53 = names_3[_i]; - var resolution = newResolutions[name_53]; - if (!resolution) { - var existingResolution = currentResolutionsInFile && currentResolutionsInFile[name_53]; - if (moduleResolutionIsValid(existingResolution)) { - resolution = existingResolution; - } - else { - resolution = loader(name_53, containingFile, compilerOptions, this.moduleResolutionHost); - resolution.lastCheckTime = Date.now(); - newResolutions[name_53] = resolution; - } - } - ts.Debug.assert(resolution !== undefined); - resolvedModules.push(getResult(resolution)); - } - cache.set(path, newResolutions); - return resolvedModules; - function moduleResolutionIsValid(resolution) { - if (!resolution) { - return false; - } - if (getResult(resolution)) { - return true; - } - return resolution.failedLookupLocations.length === 0; - } - }; - LSHost.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { - return this.resolveNamesWithLocalCache(typeDirectiveNames, containingFile, this.resolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, function (m) { return m.resolvedTypeReferenceDirective; }); - }; - LSHost.prototype.resolveModuleNames = function (moduleNames, containingFile) { - return this.resolveNamesWithLocalCache(moduleNames, containingFile, this.resolvedModuleNames, ts.resolveModuleName, function (m) { return m.resolvedModule; }); - }; - LSHost.prototype.getDefaultLibFileName = function () { - var nodeModuleBinDir = ts.getDirectoryPath(ts.normalizePath(this.host.getExecutingFilePath())); - return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilationSettings)); - }; - LSHost.prototype.getScriptSnapshot = function (filename) { - var scriptInfo = this.getScriptInfo(filename); - if (scriptInfo) { - return scriptInfo.snap(); - } - }; - LSHost.prototype.setCompilationSettings = function (opt) { - this.compilationSettings = opt; - this.resolvedModuleNames.clear(); - this.resolvedTypeReferenceDirectives.clear(); - }; - LSHost.prototype.lineAffectsRefs = function (filename, line) { - var info = this.getScriptInfo(filename); - var lineInfo = info.getLineInfo(line); - if (lineInfo && lineInfo.text) { - var regex = /reference|import|\/\*|\*\//; - return regex.test(lineInfo.text); - } - }; - LSHost.prototype.getCompilationSettings = function () { - return this.compilationSettings; - }; - LSHost.prototype.getScriptFileNames = function () { - return this.roots.map(function (root) { return root.fileName; }); - }; - LSHost.prototype.getScriptKind = function (fileName) { - var info = this.getScriptInfo(fileName); - if (!info) { - return undefined; - } - if (!info.scriptKind) { - info.scriptKind = ts.getScriptKindFromFileName(fileName); - } - return info.scriptKind; - }; - LSHost.prototype.getScriptVersion = function (filename) { - return this.getScriptInfo(filename).svc.latestVersion().toString(); - }; - LSHost.prototype.getCurrentDirectory = function () { - return ""; - }; - LSHost.prototype.getScriptIsOpen = function (filename) { - return this.getScriptInfo(filename).isOpen; - }; - LSHost.prototype.removeReferencedFile = function (info) { - if (!info.isOpen) { - this.filenameToScript.remove(info.path); - this.resolvedModuleNames.remove(info.path); - this.resolvedTypeReferenceDirectives.remove(info.path); - } - }; - LSHost.prototype.getScriptInfo = function (filename) { - var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var scriptInfo = this.filenameToScript.get(path); - if (!scriptInfo) { - scriptInfo = this.project.openReferencedFile(filename); - if (scriptInfo) { - this.filenameToScript.set(path, scriptInfo); - } - } - return scriptInfo; - }; - LSHost.prototype.addRoot = function (info) { - if (!this.filenameToScript.contains(info.path)) { - this.filenameToScript.set(info.path, info); - this.roots.push(info); - } - }; - LSHost.prototype.removeRoot = function (info) { - if (this.filenameToScript.contains(info.path)) { - this.filenameToScript.remove(info.path); - ts.unorderedRemoveItem(this.roots, info); - this.resolvedModuleNames.remove(info.path); - this.resolvedTypeReferenceDirectives.remove(info.path); - } - }; - LSHost.prototype.saveTo = function (filename, tmpfilename) { - var script = this.getScriptInfo(filename); - if (script) { - var snap = script.snap(); - this.host.writeFile(tmpfilename, snap.getText(0, snap.getLength())); - } - }; - LSHost.prototype.reloadScript = function (filename, tmpfilename, cb) { - var script = this.getScriptInfo(filename); - if (script) { - script.svc.reloadFromFile(tmpfilename, cb); - } - }; - LSHost.prototype.editScript = function (filename, start, end, newText) { - var script = this.getScriptInfo(filename); - if (script) { - script.editContent(start, end, newText); - return; - } - throw new Error("No script with name '" + filename + "'"); - }; - LSHost.prototype.fileExists = function (path) { - var result = this.host.fileExists(path); - return result; - }; - LSHost.prototype.directoryExists = function (path) { - return this.host.directoryExists(path); - }; - LSHost.prototype.getDirectories = function (path) { - return this.host.getDirectories(path); - }; - LSHost.prototype.readDirectory = function (path, extensions, exclude, include) { - return this.host.readDirectory(path, extensions, exclude, include); - }; - LSHost.prototype.readFile = function (path, encoding) { - return this.host.readFile(path, encoding); - }; - LSHost.prototype.lineToTextSpan = function (filename, line) { - var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var script = this.filenameToScript.get(path); - var index = script.snap().index; - var lineInfo = index.lineNumberToInfo(line + 1); - var len; - if (lineInfo.leaf) { - len = lineInfo.leaf.text.length; - } - else { - var nextLineInfo = index.lineNumberToInfo(line + 2); - len = nextLineInfo.offset - lineInfo.offset; - } - return ts.createTextSpan(lineInfo.offset, len); - }; - LSHost.prototype.lineOffsetToPosition = function (filename, line, offset) { - var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var script = this.filenameToScript.get(path); - var index = script.snap().index; - var lineInfo = index.lineNumberToInfo(line); - return (lineInfo.offset + offset - 1); - }; - LSHost.prototype.positionToLineOffset = function (filename, position, lineIndex) { - lineIndex = lineIndex || this.getLineIndex(filename); - var lineOffset = lineIndex.charOffsetToLineNumberAndPos(position); - return { line: lineOffset.line, offset: lineOffset.offset + 1 }; - }; - LSHost.prototype.getLineIndex = function (filename) { - var path = ts.toPath(filename, this.host.getCurrentDirectory(), this.getCanonicalFileName); - var script = this.filenameToScript.get(path); - return script.snap().index; - }; - return LSHost; - }()); - server.LSHost = LSHost; - var Project = (function () { - function Project(projectService, projectOptions, languageServiceDiabled) { - if (languageServiceDiabled === void 0) { languageServiceDiabled = false; } - this.projectService = projectService; - this.projectOptions = projectOptions; - this.languageServiceDiabled = languageServiceDiabled; - this.directoriesWatchedForTsconfig = []; - this.filenameToSourceFile = ts.createMap(); - this.updateGraphSeq = 0; - this.openRefCount = 0; - if (projectOptions && projectOptions.files) { - projectOptions.compilerOptions.allowNonTsExtensions = true; - } - if (!languageServiceDiabled) { - this.compilerService = new CompilerService(this, projectOptions && projectOptions.compilerOptions); - } - } - Project.prototype.enableLanguageService = function () { - if (this.languageServiceDiabled) { - this.compilerService = new CompilerService(this, this.projectOptions && this.projectOptions.compilerOptions); - } - this.languageServiceDiabled = false; - }; - Project.prototype.disableLanguageService = function () { - this.languageServiceDiabled = true; - }; - Project.prototype.addOpenRef = function () { - this.openRefCount++; - }; - Project.prototype.deleteOpenRef = function () { - this.openRefCount--; - return this.openRefCount; - }; - Project.prototype.openReferencedFile = function (filename) { - return this.projectService.openFile(filename, false); - }; - Project.prototype.getRootFiles = function () { - if (this.languageServiceDiabled) { - return this.projectOptions ? this.projectOptions.files : undefined; - } - return this.compilerService.host.roots.map(function (info) { return info.fileName; }); - }; - Project.prototype.getFileNames = function () { - if (this.languageServiceDiabled) { - if (!this.projectOptions) { - return undefined; - } - var fileNames = []; - if (this.projectOptions && this.projectOptions.compilerOptions) { - fileNames.push(ts.getDefaultLibFilePath(this.projectOptions.compilerOptions)); - } - ts.addRange(fileNames, this.projectOptions.files); - return fileNames; - } - var sourceFiles = this.program.getSourceFiles(); - return sourceFiles.map(function (sourceFile) { return sourceFile.fileName; }); - }; - Project.prototype.getSourceFile = function (info) { - if (this.languageServiceDiabled) { - return undefined; - } - return this.filenameToSourceFile[info.fileName]; - }; - Project.prototype.getSourceFileFromName = function (filename, requireOpen) { - if (this.languageServiceDiabled) { - return undefined; - } - var info = this.projectService.getScriptInfo(filename); - if (info) { - if ((!requireOpen) || info.isOpen) { - return this.getSourceFile(info); - } - } - }; - Project.prototype.isRoot = function (info) { - if (this.languageServiceDiabled) { - return undefined; - } - return this.compilerService.host.roots.some(function (root) { return root === info; }); - }; - Project.prototype.removeReferencedFile = function (info) { - if (this.languageServiceDiabled) { - return; - } - this.compilerService.host.removeReferencedFile(info); - this.updateGraph(); - }; - Project.prototype.updateFileMap = function () { - if (this.languageServiceDiabled) { - return; - } - this.filenameToSourceFile = ts.createMap(); - var sourceFiles = this.program.getSourceFiles(); - for (var i = 0, len = sourceFiles.length; i < len; i++) { - var normFilename = ts.normalizePath(sourceFiles[i].fileName); - this.filenameToSourceFile[normFilename] = sourceFiles[i]; - } - }; - Project.prototype.finishGraph = function () { - if (this.languageServiceDiabled) { - return; - } - this.updateGraph(); - this.compilerService.languageService.getNavigateToItems(".*"); - }; - Project.prototype.updateGraph = function () { - if (this.languageServiceDiabled) { - return; - } - this.program = this.compilerService.languageService.getProgram(); - this.updateFileMap(); - }; - Project.prototype.isConfiguredProject = function () { - return this.projectFilename; - }; - Project.prototype.addRoot = function (info) { - if (this.languageServiceDiabled) { - return; - } - this.compilerService.host.addRoot(info); - }; - Project.prototype.removeRoot = function (info) { - if (this.languageServiceDiabled) { - return; - } - this.compilerService.host.removeRoot(info); - }; - Project.prototype.filesToString = function () { - if (this.languageServiceDiabled) { - if (this.projectOptions) { - var strBuilder_1 = ""; - ts.forEach(this.projectOptions.files, function (file) { strBuilder_1 += file + "\n"; }); - return strBuilder_1; - } - } - var strBuilder = ""; - ts.forEachProperty(this.filenameToSourceFile, function (sourceFile) { strBuilder += sourceFile.fileName + "\n"; }); - return strBuilder; - }; - Project.prototype.setProjectOptions = function (projectOptions) { - this.projectOptions = projectOptions; - if (projectOptions.compilerOptions) { - projectOptions.compilerOptions.allowNonTsExtensions = true; - if (!this.languageServiceDiabled) { - this.compilerService.setCompilerOptions(projectOptions.compilerOptions); - } - } - }; - return Project; - }()); - server.Project = Project; - function combineProjectOutput(projects, action, comparer, areEqual) { - var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer); - return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; - } - server.combineProjectOutput = combineProjectOutput; - var ProjectService = (function () { - function ProjectService(host, psLogger, eventHandler) { - this.host = host; - this.psLogger = psLogger; - this.eventHandler = eventHandler; - this.filenameToScriptInfo = ts.createMap(); - this.openFileRoots = []; - this.inferredProjects = []; - this.configuredProjects = []; - this.openFilesReferenced = []; - this.openFileRootsConfigured = []; - this.directoryWatchersForTsconfig = ts.createMap(); - this.directoryWatchersRefCount = ts.createMap(); - this.timerForDetectingProjectFileListChanges = ts.createMap(); - this.addDefaultHostConfiguration(); - } - ProjectService.prototype.addDefaultHostConfiguration = function () { - this.hostConfiguration = { - formatCodeOptions: ts.clone(CompilerService.getDefaultFormatCodeOptions(this.host)), - hostInfo: "Unknown host" - }; - }; - ProjectService.prototype.getFormatCodeOptions = function (file) { - if (file) { - var info = this.filenameToScriptInfo[file]; - if (info) { - return info.formatCodeOptions; - } - } - return this.hostConfiguration.formatCodeOptions; - }; - ProjectService.prototype.watchedFileChanged = function (fileName) { - var info = this.filenameToScriptInfo[fileName]; - if (!info) { - this.psLogger.info("Error: got watch notification for unknown file: " + fileName); - } - if (!this.host.fileExists(fileName)) { - this.fileDeletedInFilesystem(info); - } - else { - if (info && (!info.isOpen)) { - info.svc.reloadFromFile(info.fileName); - } - } - }; - ProjectService.prototype.directoryWatchedForSourceFilesChanged = function (project, fileName) { - if (fileName && !ts.isSupportedSourceFileName(fileName, project.projectOptions ? project.projectOptions.compilerOptions : undefined)) { - return; - } - this.log("Detected source file changes: " + fileName); - this.startTimerForDetectingProjectFileListChanges(project); - }; - ProjectService.prototype.startTimerForDetectingProjectFileListChanges = function (project) { - var _this = this; - if (this.timerForDetectingProjectFileListChanges[project.projectFilename]) { - this.host.clearTimeout(this.timerForDetectingProjectFileListChanges[project.projectFilename]); - } - this.timerForDetectingProjectFileListChanges[project.projectFilename] = this.host.setTimeout(function () { return _this.handleProjectFileListChanges(project); }, 250); - }; - ProjectService.prototype.handleProjectFileListChanges = function (project) { - var _this = this; - var _a = this.configFileToProjectOptions(project.projectFilename), projectOptions = _a.projectOptions, errors = _a.errors; - this.reportConfigFileDiagnostics(project.projectFilename, errors); - var newRootFiles = projectOptions.files.map((function (f) { return _this.getCanonicalFileName(f); })); - var currentRootFiles = project.getRootFiles().map((function (f) { return _this.getCanonicalFileName(f); })); - if (!ts.arrayIsEqualTo(currentRootFiles && currentRootFiles.sort(), newRootFiles && newRootFiles.sort())) { - this.updateConfiguredProject(project); - this.updateProjectStructure(); - } - }; - ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) { - if (diagnostics && diagnostics.length > 0) { - this.eventHandler({ - eventName: "configFileDiag", - data: { configFileName: configFileName, diagnostics: diagnostics, triggerFile: triggerFile } - }); - } - }; - ProjectService.prototype.directoryWatchedForTsconfigChanged = function (fileName) { - var _this = this; - if (ts.getBaseFileName(fileName) !== "tsconfig.json") { - this.log(fileName + " is not tsconfig.json"); - return; - } - this.log("Detected newly added tsconfig file: " + fileName); - var _a = this.configFileToProjectOptions(fileName), projectOptions = _a.projectOptions, errors = _a.errors; - this.reportConfigFileDiagnostics(fileName, errors); - if (!projectOptions) { - return; - } - var rootFilesInTsconfig = projectOptions.files.map(function (f) { return _this.getCanonicalFileName(f); }); - var openFileRoots = this.openFileRoots.map(function (s) { return _this.getCanonicalFileName(s.fileName); }); - for (var _i = 0, openFileRoots_1 = openFileRoots; _i < openFileRoots_1.length; _i++) { - var openFileRoot = openFileRoots_1[_i]; - if (rootFilesInTsconfig.indexOf(openFileRoot) >= 0) { - this.reloadProjects(); - return; - } - } - }; - ProjectService.prototype.getCanonicalFileName = function (fileName) { - var name = this.host.useCaseSensitiveFileNames ? fileName : fileName.toLowerCase(); - return ts.normalizePath(name); - }; - ProjectService.prototype.watchedProjectConfigFileChanged = function (project) { - this.log("Config file changed: " + project.projectFilename); - var configFileErrors = this.updateConfiguredProject(project); - this.updateProjectStructure(); - if (configFileErrors && configFileErrors.length > 0) { - this.eventHandler({ eventName: "configFileDiag", data: { triggerFile: project.projectFilename, configFileName: project.projectFilename, diagnostics: configFileErrors } }); - } - }; - ProjectService.prototype.log = function (msg, type) { - if (type === void 0) { type = "Err"; } - this.psLogger.msg(msg, type); - }; - ProjectService.prototype.setHostConfiguration = function (args) { - if (args.file) { - var info = this.filenameToScriptInfo[args.file]; - if (info) { - info.setFormatOptions(args.formatOptions); - this.log("Host configuration update for file " + args.file, "Info"); - } - } - else { - if (args.hostInfo !== undefined) { - this.hostConfiguration.hostInfo = args.hostInfo; - this.log("Host information " + args.hostInfo, "Info"); - } - if (args.formatOptions) { - mergeFormatOptions(this.hostConfiguration.formatCodeOptions, args.formatOptions); - this.log("Format host information updated", "Info"); - } - } - }; - ProjectService.prototype.closeLog = function () { - this.psLogger.close(); - }; - ProjectService.prototype.createInferredProject = function (root) { - var _this = this; - var project = new Project(this); - project.addRoot(root); - var currentPath = ts.getDirectoryPath(root.fileName); - var parentPath = ts.getDirectoryPath(currentPath); - while (currentPath != parentPath) { - if (!project.projectService.directoryWatchersForTsconfig[currentPath]) { - this.log("Add watcher for: " + currentPath); - project.projectService.directoryWatchersForTsconfig[currentPath] = - this.host.watchDirectory(currentPath, function (fileName) { return _this.directoryWatchedForTsconfigChanged(fileName); }); - project.projectService.directoryWatchersRefCount[currentPath] = 1; - } - else { - project.projectService.directoryWatchersRefCount[currentPath] += 1; - } - project.directoriesWatchedForTsconfig.push(currentPath); - currentPath = parentPath; - parentPath = ts.getDirectoryPath(parentPath); - } - project.finishGraph(); - this.inferredProjects.push(project); - return project; - }; - ProjectService.prototype.fileDeletedInFilesystem = function (info) { - this.psLogger.info(info.fileName + " deleted"); - if (info.fileWatcher) { - info.fileWatcher.close(); - info.fileWatcher = undefined; - } - if (!info.isOpen) { - this.filenameToScriptInfo[info.fileName] = undefined; - var referencingProjects = this.findReferencingProjects(info); - if (info.defaultProject) { - info.defaultProject.removeRoot(info); - } - for (var i = 0, len = referencingProjects.length; i < len; i++) { - referencingProjects[i].removeReferencedFile(info); - } - for (var j = 0, flen = this.openFileRoots.length; j < flen; j++) { - var openFile = this.openFileRoots[j]; - if (this.eventHandler) { - this.eventHandler({ eventName: "context", data: { project: openFile.defaultProject, fileName: openFile.fileName } }); - } - } - for (var j = 0, flen = this.openFilesReferenced.length; j < flen; j++) { - var openFile = this.openFilesReferenced[j]; - if (this.eventHandler) { - this.eventHandler({ eventName: "context", data: { project: openFile.defaultProject, fileName: openFile.fileName } }); - } - } - } - this.printProjects(); - }; - ProjectService.prototype.updateConfiguredProjectList = function () { - var configuredProjects = []; - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - if (this.configuredProjects[i].openRefCount > 0) { - configuredProjects.push(this.configuredProjects[i]); - } - } - this.configuredProjects = configuredProjects; - }; - ProjectService.prototype.removeProject = function (project) { - this.log("remove project: " + project.getRootFiles().toString()); - if (project.isConfiguredProject()) { - project.projectFileWatcher.close(); - project.directoryWatcher.close(); - ts.forEachProperty(project.directoriesWatchedForWildcards, function (watcher) { watcher.close(); }); - delete project.directoriesWatchedForWildcards; - ts.unorderedRemoveItem(this.configuredProjects, project); - } - else { - for (var _i = 0, _a = project.directoriesWatchedForTsconfig; _i < _a.length; _i++) { - var directory = _a[_i]; - project.projectService.directoryWatchersRefCount[directory]--; - if (!project.projectService.directoryWatchersRefCount[directory]) { - this.log("Close directory watcher for: " + directory); - project.projectService.directoryWatchersForTsconfig[directory].close(); - delete project.projectService.directoryWatchersForTsconfig[directory]; - } - } - ts.unorderedRemoveItem(this.inferredProjects, project); - } - var fileNames = project.getFileNames(); - for (var _b = 0, fileNames_3 = fileNames; _b < fileNames_3.length; _b++) { - var fileName = fileNames_3[_b]; - var info = this.getScriptInfo(fileName); - if (info.defaultProject == project) { - info.defaultProject = undefined; - } - } - }; - ProjectService.prototype.setConfiguredProjectRoot = function (info) { - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - var configuredProject = this.configuredProjects[i]; - if (configuredProject.isRoot(info)) { - info.defaultProject = configuredProject; - configuredProject.addOpenRef(); - return true; - } - } - return false; - }; - ProjectService.prototype.addOpenFile = function (info) { - if (this.setConfiguredProjectRoot(info)) { - this.openFileRootsConfigured.push(info); - } - else { - this.findReferencingProjects(info); - if (info.defaultProject) { - info.defaultProject.addOpenRef(); - this.openFilesReferenced.push(info); - } - else { - info.defaultProject = this.createInferredProject(info); - var openFileRoots = []; - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - var r = this.openFileRoots[i]; - if (info.defaultProject.getSourceFile(r)) { - this.removeProject(r.defaultProject); - this.openFilesReferenced.push(r); - r.defaultProject = info.defaultProject; - } - else { - openFileRoots.push(r); - } - } - this.openFileRoots = openFileRoots; - this.openFileRoots.push(info); - } - } - this.updateConfiguredProjectList(); - }; - ProjectService.prototype.closeOpenFile = function (info) { - info.svc.reloadFromFile(info.fileName); - var openFileRoots = []; - var removedProject; - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - if (info === this.openFileRoots[i]) { - removedProject = info.defaultProject; - } - else { - openFileRoots.push(this.openFileRoots[i]); - } - } - this.openFileRoots = openFileRoots; - if (!removedProject) { - var openFileRootsConfigured = []; - for (var i = 0, len = this.openFileRootsConfigured.length; i < len; i++) { - if (info === this.openFileRootsConfigured[i]) { - if (info.defaultProject.deleteOpenRef() === 0) { - removedProject = info.defaultProject; - } - } - else { - openFileRootsConfigured.push(this.openFileRootsConfigured[i]); - } - } - this.openFileRootsConfigured = openFileRootsConfigured; - } - if (removedProject) { - this.removeProject(removedProject); - var openFilesReferenced = []; - var orphanFiles = []; - for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { - var f = this.openFilesReferenced[i]; - if (f.defaultProject === removedProject || !f.defaultProject) { - f.defaultProject = undefined; - orphanFiles.push(f); - } - else { - openFilesReferenced.push(f); - } - } - this.openFilesReferenced = openFilesReferenced; - for (var i = 0, len = orphanFiles.length; i < len; i++) { - this.addOpenFile(orphanFiles[i]); - } - } - else { - ts.unorderedRemoveItem(this.openFilesReferenced, info); - } - info.close(); - }; - ProjectService.prototype.findReferencingProjects = function (info, excludedProject) { - var referencingProjects = []; - info.defaultProject = undefined; - for (var i = 0, len = this.inferredProjects.length; i < len; i++) { - var inferredProject = this.inferredProjects[i]; - inferredProject.updateGraph(); - if (inferredProject !== excludedProject) { - if (inferredProject.getSourceFile(info)) { - info.defaultProject = inferredProject; - referencingProjects.push(inferredProject); - } - } - } - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - var configuredProject = this.configuredProjects[i]; - configuredProject.updateGraph(); - if (configuredProject.getSourceFile(info)) { - info.defaultProject = configuredProject; - referencingProjects.push(configuredProject); - } - } - return referencingProjects; - }; - ProjectService.prototype.reloadProjects = function () { - this.log("reload projects."); - for (var _i = 0, _a = this.openFileRoots; _i < _a.length; _i++) { - var info = _a[_i]; - this.openOrUpdateConfiguredProjectForFile(info.fileName); - } - this.updateProjectStructure(); - }; - ProjectService.prototype.updateProjectStructure = function () { - this.log("updating project structure from ...", "Info"); - this.printProjects(); - var unattachedOpenFiles = []; - var openFileRootsConfigured = []; - for (var _i = 0, _a = this.openFileRootsConfigured; _i < _a.length; _i++) { - var info = _a[_i]; - var project = info.defaultProject; - if (!project || !(project.getSourceFile(info))) { - info.defaultProject = undefined; - unattachedOpenFiles.push(info); - } - else { - openFileRootsConfigured.push(info); - } - } - this.openFileRootsConfigured = openFileRootsConfigured; - var openFilesReferenced = []; - for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { - var referencedFile = this.openFilesReferenced[i]; - referencedFile.defaultProject.updateGraph(); - var sourceFile = referencedFile.defaultProject.getSourceFile(referencedFile); - if (sourceFile) { - openFilesReferenced.push(referencedFile); - } - else { - unattachedOpenFiles.push(referencedFile); - } - } - this.openFilesReferenced = openFilesReferenced; - var openFileRoots = []; - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - var rootFile = this.openFileRoots[i]; - var rootedProject = rootFile.defaultProject; - var referencingProjects = this.findReferencingProjects(rootFile, rootedProject); - if (rootFile.defaultProject && rootFile.defaultProject.isConfiguredProject()) { - if (!rootedProject.isConfiguredProject()) { - this.removeProject(rootedProject); - } - this.openFileRootsConfigured.push(rootFile); - } - else { - if (referencingProjects.length === 0) { - rootFile.defaultProject = rootedProject; - openFileRoots.push(rootFile); - } - else { - this.removeProject(rootedProject); - this.openFilesReferenced.push(rootFile); - } - } - } - this.openFileRoots = openFileRoots; - for (var i = 0, len = unattachedOpenFiles.length; i < len; i++) { - this.addOpenFile(unattachedOpenFiles[i]); - } - this.printProjects(); - }; - ProjectService.prototype.getScriptInfo = function (filename) { - filename = ts.normalizePath(filename); - return this.filenameToScriptInfo[filename]; - }; - ProjectService.prototype.openFile = function (fileName, openedByClient, fileContent, scriptKind) { - var _this = this; - fileName = ts.normalizePath(fileName); - var info = this.filenameToScriptInfo[fileName]; - if (!info) { - var content = void 0; - if (this.host.fileExists(fileName)) { - content = fileContent || this.host.readFile(fileName); - } - if (!content) { - if (openedByClient) { - content = ""; - } - } - if (content !== undefined) { - info = new ScriptInfo(this.host, fileName, content, openedByClient); - info.scriptKind = scriptKind; - info.setFormatOptions(this.getFormatCodeOptions()); - this.filenameToScriptInfo[fileName] = info; - if (!info.isOpen) { - info.fileWatcher = this.host.watchFile(fileName, function (_) { _this.watchedFileChanged(fileName); }); - } - } - } - if (info) { - if (fileContent) { - info.svc.reload(fileContent); - } - if (openedByClient) { - info.isOpen = true; - } - } - return info; - }; - ProjectService.prototype.findConfigFile = function (searchPath) { - while (true) { - var tsconfigFileName = ts.combinePaths(searchPath, "tsconfig.json"); - if (this.host.fileExists(tsconfigFileName)) { - return tsconfigFileName; - } - var jsconfigFileName = ts.combinePaths(searchPath, "jsconfig.json"); - if (this.host.fileExists(jsconfigFileName)) { - return jsconfigFileName; - } - var parentPath = ts.getDirectoryPath(searchPath); - if (parentPath === searchPath) { - break; - } - searchPath = parentPath; - } - return undefined; - }; - ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind) { - var _a = this.openOrUpdateConfiguredProjectForFile(fileName), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; - var info = this.openFile(fileName, true, fileContent, scriptKind); - this.addOpenFile(info); - this.printProjects(); - return { configFileName: configFileName, configFileErrors: configFileErrors }; - }; - ProjectService.prototype.openOrUpdateConfiguredProjectForFile = function (fileName) { - var searchPath = ts.normalizePath(ts.getDirectoryPath(fileName)); - this.log("Search path: " + searchPath, "Info"); - var configFileName = this.findConfigFile(searchPath); - if (configFileName) { - this.log("Config file name: " + configFileName, "Info"); - var project = this.findConfiguredProjectByConfigFile(configFileName); - if (!project) { - var configResult = this.openConfigFile(configFileName, fileName); - if (!configResult.project) { - return { configFileName: configFileName, configFileErrors: configResult.errors }; - } - else { - this.log("Opened configuration file " + configFileName, "Info"); - this.configuredProjects.push(configResult.project); - if (configResult.errors && configResult.errors.length > 0) { - return { configFileName: configFileName, configFileErrors: configResult.errors }; - } - } - } - else { - this.updateConfiguredProject(project); - } - return { configFileName: configFileName }; - } - else { - this.log("No config files found."); - } - return {}; - }; - ProjectService.prototype.closeClientFile = function (filename) { - var info = this.filenameToScriptInfo[filename]; - if (info) { - this.closeOpenFile(info); - info.isOpen = false; - } - this.printProjects(); - }; - ProjectService.prototype.getProjectForFile = function (filename) { - var scriptInfo = this.filenameToScriptInfo[filename]; - if (scriptInfo) { - return scriptInfo.defaultProject; - } - }; - ProjectService.prototype.printProjectsForFile = function (filename) { - var scriptInfo = this.filenameToScriptInfo[filename]; - if (scriptInfo) { - this.psLogger.startGroup(); - this.psLogger.info("Projects for " + filename); - var projects = this.findReferencingProjects(scriptInfo); - for (var i = 0, len = projects.length; i < len; i++) { - this.psLogger.info("Project " + i.toString()); - } - this.psLogger.endGroup(); - } - else { - this.psLogger.info(filename + " not in any project"); - } - }; - ProjectService.prototype.printProjects = function () { - if (!this.psLogger.isVerbose()) { - return; - } - this.psLogger.startGroup(); - for (var i = 0, len = this.inferredProjects.length; i < len; i++) { - var project = this.inferredProjects[i]; - project.updateGraph(); - this.psLogger.info("Project " + i.toString()); - this.psLogger.info(project.filesToString()); - this.psLogger.info("-----------------------------------------------"); - } - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - var project = this.configuredProjects[i]; - project.updateGraph(); - this.psLogger.info("Project (configured) " + (i + this.inferredProjects.length).toString()); - this.psLogger.info(project.filesToString()); - this.psLogger.info("-----------------------------------------------"); - } - this.psLogger.info("Open file roots of inferred projects: "); - for (var i = 0, len = this.openFileRoots.length; i < len; i++) { - this.psLogger.info(this.openFileRoots[i].fileName); - } - this.psLogger.info("Open files referenced by inferred or configured projects: "); - for (var i = 0, len = this.openFilesReferenced.length; i < len; i++) { - var fileInfo = this.openFilesReferenced[i].fileName; - if (this.openFilesReferenced[i].defaultProject.isConfiguredProject()) { - fileInfo += " (configured)"; - } - this.psLogger.info(fileInfo); - } - this.psLogger.info("Open file roots of configured projects: "); - for (var i = 0, len = this.openFileRootsConfigured.length; i < len; i++) { - this.psLogger.info(this.openFileRootsConfigured[i].fileName); - } - this.psLogger.endGroup(); - }; - ProjectService.prototype.configProjectIsActive = function (fileName) { - return this.findConfiguredProjectByConfigFile(fileName) === undefined; - }; - ProjectService.prototype.findConfiguredProjectByConfigFile = function (configFileName) { - for (var i = 0, len = this.configuredProjects.length; i < len; i++) { - if (this.configuredProjects[i].projectFilename == configFileName) { - return this.configuredProjects[i]; - } - } - return undefined; - }; - ProjectService.prototype.configFileToProjectOptions = function (configFilename) { - configFilename = ts.normalizePath(configFilename); - var errors = []; - var dirPath = ts.getDirectoryPath(configFilename); - var contents = this.host.readFile(configFilename); - var _a = ts.parseAndReEmitConfigJSONFile(contents), configJsonObject = _a.configJsonObject, diagnostics = _a.diagnostics; - errors = ts.concatenate(errors, diagnostics); - var parsedCommandLine = ts.parseJsonConfigFileContent(configJsonObject, this.host, dirPath, {}, configFilename); - errors = ts.concatenate(errors, parsedCommandLine.errors); - ts.Debug.assert(!!parsedCommandLine.fileNames); - if (parsedCommandLine.fileNames.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); - return { errors: errors }; - } - else { - var projectOptions = { - files: parsedCommandLine.fileNames, - wildcardDirectories: parsedCommandLine.wildcardDirectories, - compilerOptions: parsedCommandLine.options - }; - return { projectOptions: projectOptions, errors: errors }; - } - }; - ProjectService.prototype.exceedTotalNonTsFileSizeLimit = function (fileNames) { - var totalNonTsFileSize = 0; - if (!this.host.getFileSize) { - return false; - } - for (var _i = 0, fileNames_4 = fileNames; _i < fileNames_4.length; _i++) { - var fileName = fileNames_4[_i]; - if (ts.hasTypeScriptFileExtension(fileName)) { - continue; - } - totalNonTsFileSize += this.host.getFileSize(fileName); - if (totalNonTsFileSize > server.maxProgramSizeForNonTsFiles) { - return true; - } - } - return false; - }; - ProjectService.prototype.openConfigFile = function (configFilename, clientFileName) { - var _this = this; - var parseConfigFileResult = this.configFileToProjectOptions(configFilename); - var errors = parseConfigFileResult.errors; - if (!parseConfigFileResult.projectOptions) { - return { errors: errors }; - } - var projectOptions = parseConfigFileResult.projectOptions; - if (!projectOptions.compilerOptions.disableSizeLimit && projectOptions.compilerOptions.allowJs) { - if (this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { - var project_1 = this.createProject(configFilename, projectOptions, true); - project_1.projectFileWatcher = this.host.watchFile(ts.toPath(configFilename, configFilename, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), function (_) { return _this.watchedProjectConfigFileChanged(project_1); }); - return { project: project_1, errors: errors }; - } - } - var project = this.createProject(configFilename, projectOptions); - for (var _i = 0, _a = projectOptions.files; _i < _a.length; _i++) { - var rootFilename = _a[_i]; - if (this.host.fileExists(rootFilename)) { - var info = this.openFile(rootFilename, clientFileName == rootFilename); - project.addRoot(info); - } - else { - (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, rootFilename)); - } - } - project.finishGraph(); - project.projectFileWatcher = this.host.watchFile(configFilename, function (_) { return _this.watchedProjectConfigFileChanged(project); }); - var configDirectoryPath = ts.getDirectoryPath(configFilename); - this.log("Add recursive watcher for: " + configDirectoryPath); - project.directoryWatcher = this.host.watchDirectory(configDirectoryPath, function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true); - project.directoriesWatchedForWildcards = ts.reduceProperties(ts.createMap(projectOptions.wildcardDirectories), function (watchers, flag, directory) { - if (ts.comparePaths(configDirectoryPath, directory, ".", !_this.host.useCaseSensitiveFileNames) !== 0) { - var recursive = (flag & 1) !== 0; - _this.log("Add " + (recursive ? "recursive " : "") + "watcher for: " + directory); - watchers[directory] = _this.host.watchDirectory(directory, function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, recursive); - } - return watchers; - }, {}); - return { project: project, errors: errors }; - }; - ProjectService.prototype.updateConfiguredProject = function (project) { - var _this = this; - if (!this.host.fileExists(project.projectFilename)) { - this.log("Config file deleted"); - this.removeProject(project); - } - else { - var _a = this.configFileToProjectOptions(project.projectFilename), projectOptions = _a.projectOptions, errors = _a.errors; - if (!projectOptions) { - return errors; - } - else { - if (projectOptions.compilerOptions && !projectOptions.compilerOptions.disableSizeLimit && this.exceedTotalNonTsFileSizeLimit(projectOptions.files)) { - project.setProjectOptions(projectOptions); - if (project.languageServiceDiabled) { - return errors; - } - project.disableLanguageService(); - if (project.directoryWatcher) { - project.directoryWatcher.close(); - project.directoryWatcher = undefined; - } - return errors; - } - if (project.languageServiceDiabled) { - project.setProjectOptions(projectOptions); - project.enableLanguageService(); - project.directoryWatcher = this.host.watchDirectory(ts.getDirectoryPath(project.projectFilename), function (path) { return _this.directoryWatchedForSourceFilesChanged(project, path); }, true); - for (var _i = 0, _b = projectOptions.files; _i < _b.length; _i++) { - var rootFilename = _b[_i]; - if (this.host.fileExists(rootFilename)) { - var info = this.openFile(rootFilename, false); - project.addRoot(info); - } - } - project.finishGraph(); - return errors; - } - var oldFileNames_1 = project.projectOptions ? project.projectOptions.files : project.compilerService.host.roots.map(function (info) { return info.fileName; }); - var newFileNames_1 = ts.filter(projectOptions.files, function (f) { return _this.host.fileExists(f); }); - var fileNamesToRemove = oldFileNames_1.filter(function (f) { return newFileNames_1.indexOf(f) < 0; }); - var fileNamesToAdd = newFileNames_1.filter(function (f) { return oldFileNames_1.indexOf(f) < 0; }); - for (var _c = 0, fileNamesToRemove_1 = fileNamesToRemove; _c < fileNamesToRemove_1.length; _c++) { - var fileName = fileNamesToRemove_1[_c]; - var info = this.getScriptInfo(fileName); - if (info) { - project.removeRoot(info); - } - } - for (var _d = 0, fileNamesToAdd_1 = fileNamesToAdd; _d < fileNamesToAdd_1.length; _d++) { - var fileName = fileNamesToAdd_1[_d]; - var info = this.getScriptInfo(fileName); - if (!info) { - info = this.openFile(fileName, false); - } - else { - if (info.isOpen) { - if (this.openFileRoots.indexOf(info) >= 0) { - ts.unorderedRemoveItem(this.openFileRoots, info); - if (info.defaultProject && !info.defaultProject.isConfiguredProject()) { - this.removeProject(info.defaultProject); - } - } - if (this.openFilesReferenced.indexOf(info) >= 0) { - ts.unorderedRemoveItem(this.openFilesReferenced, info); - } - this.openFileRootsConfigured.push(info); - info.defaultProject = project; - } - } - project.addRoot(info); - } - project.setProjectOptions(projectOptions); - project.finishGraph(); - } - return errors; - } - }; - ProjectService.prototype.createProject = function (projectFilename, projectOptions, languageServiceDisabled) { - var project = new Project(this, projectOptions, languageServiceDisabled); - project.projectFilename = projectFilename; - return project; - }; - return ProjectService; - }()); - server.ProjectService = ProjectService; - var CompilerService = (function () { - function CompilerService(project, opt) { - this.project = project; - this.documentRegistry = ts.createDocumentRegistry(); - this.host = new LSHost(project.projectService.host, project); - if (opt) { - this.setCompilerOptions(opt); - } - else { - var defaultOpts = ts.getDefaultCompilerOptions(); - defaultOpts.allowNonTsExtensions = true; - defaultOpts.allowJs = true; - this.setCompilerOptions(defaultOpts); - } - this.languageService = ts.createLanguageService(this.host, this.documentRegistry); - this.classifier = ts.createClassifier(); - } - CompilerService.prototype.setCompilerOptions = function (opt) { - this.settings = opt; - this.host.setCompilationSettings(opt); - }; - CompilerService.prototype.isExternalModule = function (filename) { - var sourceFile = this.languageService.getNonBoundSourceFile(filename); - return ts.isExternalModule(sourceFile); - }; - CompilerService.getDefaultFormatCodeOptions = function (host) { - return ts.clone({ - BaseIndentSize: 0, - IndentSize: 4, - TabSize: 4, - NewLineCharacter: host.newLine || "\n", - ConvertTabsToSpaces: true, - IndentStyle: ts.IndentStyle.Smart, - InsertSpaceAfterCommaDelimiter: true, - InsertSpaceAfterSemicolonInForStatements: true, - InsertSpaceBeforeAndAfterBinaryOperators: true, - InsertSpaceAfterKeywordsInControlFlowStatements: true, - InsertSpaceAfterFunctionKeywordForAnonymousFunctions: false, - InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, - InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: false, - InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces: true, - InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, - InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: false, - InsertSpaceAfterTypeAssertion: false, - PlaceOpenBraceOnNewLineForFunctions: false, - PlaceOpenBraceOnNewLineForControlBlocks: false - }); - }; - return CompilerService; - }()); - server.CompilerService = CompilerService; (function (CharRangeSection) { CharRangeSection[CharRangeSection["PreStart"] = 0] = "PreStart"; CharRangeSection[CharRangeSection["Start"] = 1] = "Start"; @@ -62605,16 +64797,17 @@ var ts; var EditWalker = (function (_super) { __extends(EditWalker, _super); function EditWalker() { - _super.call(this); - this.lineIndex = new LineIndex(); - this.endBranch = []; - this.state = CharRangeSection.Entire; - this.initialText = ""; - this.trailingText = ""; - this.suppressTrailingText = false; - this.lineIndex.root = new LineNode(); - this.startPath = [this.lineIndex.root]; - this.stack = [this.lineIndex.root]; + var _this = _super.call(this) || this; + _this.lineIndex = new LineIndex(); + _this.endBranch = []; + _this.state = CharRangeSection.Entire; + _this.initialText = ""; + _this.trailingText = ""; + _this.suppressTrailingText = false; + _this.lineIndex.root = new LineNode(); + _this.startPath = [_this.lineIndex.root]; + _this.stack = [_this.lineIndex.root]; + return _this; } EditWalker.prototype.insertLines = function (insertedText) { if (this.suppressTrailingText) { @@ -62801,10 +64994,19 @@ var ts; var ScriptVersionCache = (function () { function ScriptVersionCache() { this.changes = []; - this.versions = []; + this.versions = new Array(ScriptVersionCache.maxVersions); this.minVersion = 0; this.currentVersion = 0; } + ScriptVersionCache.prototype.versionToIndex = function (version) { + if (version < this.minVersion || version > this.currentVersion) { + return undefined; + } + return version % ScriptVersionCache.maxVersions; + }; + ScriptVersionCache.prototype.currentVersionToIndex = function () { + return this.currentVersion % ScriptVersionCache.maxVersions; + }; ScriptVersionCache.prototype.edit = function (pos, deleteLen, insertedText) { this.changes[this.changes.length] = new TextChange(pos, deleteLen, insertedText); if ((this.changes.length > ScriptVersionCache.changeNumberThreshold) || @@ -62814,7 +65016,7 @@ var ts; } }; ScriptVersionCache.prototype.latest = function () { - return this.versions[this.currentVersion]; + return this.versions[this.currentVersionToIndex()]; }; ScriptVersionCache.prototype.latestVersion = function () { if (this.changes.length > 0) { @@ -62822,32 +65024,30 @@ var ts; } return this.currentVersion; }; - ScriptVersionCache.prototype.reloadFromFile = function (filename, cb) { + ScriptVersionCache.prototype.reloadFromFile = function (filename) { var content = this.host.readFile(filename); if (!content) { content = ""; } this.reload(content); - if (cb) - cb(); }; ScriptVersionCache.prototype.reload = function (script) { this.currentVersion++; this.changes = []; var snap = new LineIndexSnapshot(this.currentVersion, this); - this.versions[this.currentVersion] = snap; + for (var i = 0; i < this.versions.length; i++) { + this.versions[i] = undefined; + } + this.versions[this.currentVersionToIndex()] = snap; snap.index = new LineIndex(); var lm = LineIndex.linesFromText(script); snap.index.load(lm.lines); - for (var i = this.minVersion; i < this.currentVersion; i++) { - this.versions[i] = undefined; - } this.minVersion = this.currentVersion; }; ScriptVersionCache.prototype.getSnapshot = function () { - var snap = this.versions[this.currentVersion]; + var snap = this.versions[this.currentVersionToIndex()]; if (this.changes.length > 0) { - var snapIndex = this.latest().index; + var snapIndex = snap.index; for (var i = 0, len = this.changes.length; i < len; i++) { var change = this.changes[i]; snapIndex = snapIndex.edit(change.pos, change.deleteLen, change.insertedText); @@ -62856,14 +65056,10 @@ var ts; snap.index = snapIndex; snap.changesSincePreviousVersion = this.changes; this.currentVersion = snap.version; - this.versions[snap.version] = snap; + this.versions[this.currentVersionToIndex()] = snap; this.changes = []; if ((this.currentVersion - this.minVersion) >= ScriptVersionCache.maxVersions) { - var oldMin = this.minVersion; this.minVersion = (this.currentVersion - ScriptVersionCache.maxVersions) + 1; - for (var j = oldMin; j < this.minVersion; j++) { - this.versions[j] = undefined; - } } } return snap; @@ -62873,7 +65069,7 @@ var ts; if (oldVersion >= this.minVersion) { var textChangeRanges = []; for (var i = oldVersion + 1; i <= newVersion; i++) { - var snap = this.versions[i]; + var snap = this.versions[this.versionToIndex(i)]; for (var j = 0, len = snap.changesSincePreviousVersion.length; j < len; j++) { var textChange = snap.changesSincePreviousVersion[j]; textChangeRanges[textChangeRanges.length] = textChange.getTextChangeRange(); @@ -63011,7 +65207,7 @@ var ts; done: false, leaf: function (relativeStart, relativeLength, ll) { if (!f(ll, relativeStart, relativeLength)) { - walkFns.done = true; + this.done = true; } } }; @@ -63024,7 +65220,7 @@ var ts; return source.substring(0, s) + nt + source.substring(s + dl, source.length); } if (this.root.charCount() === 0) { - if (newText) { + if (newText !== undefined) { this.load(LineIndex.linesFromText(newText).lines); return this; } @@ -63404,12 +65600,6 @@ var ts; function LineLeaf(text) { this.text = text; } - LineLeaf.prototype.setUdata = function (data) { - this.udata = data; - }; - LineLeaf.prototype.getUdata = function () { - return this.udata; - }; LineLeaf.prototype.isLeaf = function () { return true; }; @@ -63427,7 +65617,7 @@ var ts; server.LineLeaf = LineLeaf; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); -var debugObjectHost = new Function("return this")(); +var debugObjectHost = (function () { return this; })(); var ts; (function (ts) { function logInternalError(logger, err) { @@ -63505,6 +65695,12 @@ var ts; } return this.shimHost.getProjectVersion(); }; + LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () { + if (!this.shimHost.getTypeRootsVersion) { + return 0; + } + return this.shimHost.getTypeRootsVersion(); + }; LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; }; @@ -63698,11 +65894,12 @@ var ts; var LanguageServiceShimObject = (function (_super) { __extends(LanguageServiceShimObject, _super); function LanguageServiceShimObject(factory, host, languageService) { - _super.call(this, factory); - this.host = host; - this.languageService = languageService; - this.logPerformance = false; - this.logger = this.host; + var _this = _super.call(this, factory) || this; + _this.host = host; + _this.languageService = languageService; + _this.logPerformance = false; + _this.logger = _this.host; + return _this; } LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); @@ -63881,6 +66078,10 @@ var ts; var _this = this; return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; + LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); }); + }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); @@ -63905,10 +66106,11 @@ var ts; var ClassifierShimObject = (function (_super) { __extends(ClassifierShimObject, _super); function ClassifierShimObject(factory, logger) { - _super.call(this, factory); - this.logger = logger; - this.logPerformance = false; - this.classifier = ts.createClassifier(); + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.logPerformance = false; + _this.classifier = ts.createClassifier(); + return _this; } ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { var _this = this; @@ -63930,10 +66132,11 @@ var ts; var CoreServicesShimObject = (function (_super) { __extends(CoreServicesShimObject, _super); function CoreServicesShimObject(factory, logger, host) { - _super.call(this, factory); - this.logger = logger; - this.host = host; - this.logPerformance = false; + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.host = host; + _this.logPerformance = false; + return _this; } CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 9116a629d6d..c915bd9efc8 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -29,6 +29,7 @@ declare namespace ts { contains(fileName: Path): boolean; remove(fileName: Path): void; forEachValue(f: (key: Path, v: T) => void): void; + getKeys(): Path[]; clear(): void; } interface TextRange { @@ -388,7 +389,6 @@ declare namespace ts { ContextFlags = 1540096, TypeExcludesFlags = 327680, } - type ModifiersArray = NodeArray; enum ModifierFlags { None = 0, Export = 1, @@ -425,12 +425,21 @@ declare namespace ts { interface NodeArray extends Array, TextRange { hasTrailingComma?: boolean; } - interface Token extends Node { - __tokenTag: any; - } - interface Modifier extends Token { + interface Token extends Node { + kind: TKind; } + type DotDotDotToken = Token; + type QuestionToken = Token; + type ColonToken = Token; + type EqualsToken = Token; + type AsteriskToken = Token; + type EqualsGreaterThanToken = Token; + type EndOfFileToken = Token; + type AtToken = Token; + type Modifier = Token | Token | Token | Token | Token | Token | Token | Token | Token | Token | Token; + type ModifiersArray = NodeArray; interface Identifier extends PrimaryExpression { + kind: SyntaxKind.Identifier; text: string; originalKeywordKind?: SyntaxKind; } @@ -438,6 +447,7 @@ declare namespace ts { resolvedSymbol: Symbol; } interface QualifiedName extends Node { + kind: SyntaxKind.QualifiedName; left: EntityName; right: Identifier; } @@ -449,15 +459,18 @@ declare namespace ts { name?: DeclarationName; } interface DeclarationStatement extends Declaration, Statement { - name?: Identifier; + name?: Identifier | LiteralExpression; } interface ComputedPropertyName extends Node { + kind: SyntaxKind.ComputedPropertyName; expression: Expression; } interface Decorator extends Node { + kind: SyntaxKind.Decorator; expression: LeftHandSideExpression; } interface TypeParameterDeclaration extends Declaration { + kind: SyntaxKind.TypeParameter; name: Identifier; constraint?: TypeNode; expression?: Expression; @@ -469,40 +482,48 @@ declare namespace ts { type?: TypeNode; } interface CallSignatureDeclaration extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.CallSignature; } interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; interface VariableDeclaration extends Declaration { + kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList; name: BindingName; type?: TypeNode; initializer?: Expression; } interface VariableDeclarationList extends Node { + kind: SyntaxKind.VariableDeclarationList; declarations: NodeArray; } interface ParameterDeclaration extends Declaration { - dotDotDotToken?: Node; + kind: SyntaxKind.Parameter; + dotDotDotToken?: DotDotDotToken; name: BindingName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } interface BindingElement extends Declaration { + kind: SyntaxKind.BindingElement; propertyName?: PropertyName; - dotDotDotToken?: Node; + dotDotDotToken?: DotDotDotToken; name: BindingName; initializer?: Expression; } interface PropertySignature extends TypeElement { + kind: SyntaxKind.PropertySignature | SyntaxKind.JSDocRecordMember; name: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } interface PropertyDeclaration extends ClassElement { - questionToken?: Node; + kind: SyntaxKind.PropertyDeclaration; + questionToken?: QuestionToken; name: PropertyName; type?: TypeNode; initializer?: Expression; @@ -513,22 +534,23 @@ declare namespace ts { } type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration; interface PropertyAssignment extends ObjectLiteralElement { - _propertyAssignmentBrand: any; + kind: SyntaxKind.PropertyAssignment; name: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; initializer: Expression; } interface ShorthandPropertyAssignment extends ObjectLiteralElement { + kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; - questionToken?: Node; - equalsToken?: Node; + questionToken?: QuestionToken; + equalsToken?: Token; objectAssignmentInitializer?: Expression; } interface VariableLikeDeclaration extends Declaration { propertyName?: PropertyName; - dotDotDotToken?: Node; + dotDotDotToken?: DotDotDotToken; name: DeclarationName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } @@ -539,10 +561,12 @@ declare namespace ts { elements: NodeArray; } interface ObjectBindingPattern extends BindingPattern { + kind: SyntaxKind.ObjectBindingPattern; elements: NodeArray; } type ArrayBindingElement = BindingElement | OmittedExpression; interface ArrayBindingPattern extends BindingPattern { + kind: SyntaxKind.ArrayBindingPattern; elements: NodeArray; } /** @@ -555,95 +579,116 @@ declare namespace ts { */ interface FunctionLikeDeclaration extends SignatureDeclaration { _functionLikeDeclarationBrand: any; - asteriskToken?: Node; - questionToken?: Node; + asteriskToken?: AsteriskToken; + questionToken?: QuestionToken; body?: Block | Expression; } interface FunctionDeclaration extends FunctionLikeDeclaration, DeclarationStatement { + kind: SyntaxKind.FunctionDeclaration; name?: Identifier; body?: FunctionBody; } interface MethodSignature extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.MethodSignature; name: PropertyName; } interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.MethodDeclaration; name: PropertyName; body?: FunctionBody; } interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { + kind: SyntaxKind.Constructor; body?: FunctionBody; } interface SemicolonClassElement extends ClassElement { - _semicolonClassElementBrand: any; + kind: SyntaxKind.SemicolonClassElement; } - interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { - _accessorDeclarationBrand: any; + interface GetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.GetAccessor; name: PropertyName; body: FunctionBody; } - interface GetAccessorDeclaration extends AccessorDeclaration { - } - interface SetAccessorDeclaration extends AccessorDeclaration { + interface SetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.SetAccessor; + name: PropertyName; + body: FunctionBody; } + type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement, TypeElement { - _indexSignatureDeclarationBrand: any; + kind: SyntaxKind.IndexSignature; } interface TypeNode extends Node { _typeNodeBrand: any; } + interface KeywordTypeNode extends TypeNode { + kind: SyntaxKind.AnyKeyword | SyntaxKind.NumberKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.VoidKeyword; + } interface ThisTypeNode extends TypeNode { - _thisTypeNodeBrand: any; + kind: SyntaxKind.ThisType; } interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration { - _functionOrConstructorTypeNodeBrand: any; + kind: SyntaxKind.FunctionType | SyntaxKind.ConstructorType; } interface FunctionTypeNode extends FunctionOrConstructorTypeNode { + kind: SyntaxKind.FunctionType; } interface ConstructorTypeNode extends FunctionOrConstructorTypeNode { + kind: SyntaxKind.ConstructorType; } interface TypeReferenceNode extends TypeNode { + kind: SyntaxKind.TypeReference; typeName: EntityName; typeArguments?: NodeArray; } interface TypePredicateNode extends TypeNode { + kind: SyntaxKind.TypePredicate; parameterName: Identifier | ThisTypeNode; type: TypeNode; } interface TypeQueryNode extends TypeNode { + kind: SyntaxKind.TypeQuery; exprName: EntityName; } interface TypeLiteralNode extends TypeNode, Declaration { + kind: SyntaxKind.TypeLiteral; members: NodeArray; } interface ArrayTypeNode extends TypeNode { + kind: SyntaxKind.ArrayType; elementType: TypeNode; } interface TupleTypeNode extends TypeNode { + kind: SyntaxKind.TupleType; elementTypes: NodeArray; } interface UnionOrIntersectionTypeNode extends TypeNode { + kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType; types: NodeArray; } interface UnionTypeNode extends UnionOrIntersectionTypeNode { + kind: SyntaxKind.UnionType; } interface IntersectionTypeNode extends UnionOrIntersectionTypeNode { + kind: SyntaxKind.IntersectionType; } interface ParenthesizedTypeNode extends TypeNode { + kind: SyntaxKind.ParenthesizedType; type: TypeNode; } interface LiteralTypeNode extends TypeNode { - _stringLiteralTypeBrand: any; + kind: SyntaxKind.LiteralType; literal: Expression; } interface StringLiteral extends LiteralExpression { - _stringLiteralBrand: any; + kind: SyntaxKind.StringLiteral; } interface Expression extends Node { _expressionBrand: any; contextualType?: Type; } interface OmittedExpression extends Expression { - _omittedExpressionBrand: any; + kind: SyntaxKind.OmittedExpression; } interface UnaryExpression extends Expression { _unaryExpressionBrand: any; @@ -651,13 +696,17 @@ declare namespace ts { interface IncrementExpression extends UnaryExpression { _incrementExpressionBrand: any; } + type PrefixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.TildeToken | SyntaxKind.ExclamationToken; interface PrefixUnaryExpression extends IncrementExpression { - operator: SyntaxKind; + kind: SyntaxKind.PrefixUnaryExpression; + operator: PrefixUnaryOperator; operand: UnaryExpression; } + type PostfixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken; interface PostfixUnaryExpression extends IncrementExpression { + kind: SyntaxKind.PostfixUnaryExpression; operand: LeftHandSideExpression; - operator: SyntaxKind; + operator: PostfixUnaryOperator; } interface PostfixExpression extends UnaryExpression { _postfixExpressionBrand: any; @@ -671,42 +720,83 @@ declare namespace ts { interface PrimaryExpression extends MemberExpression { _primaryExpressionBrand: any; } + interface NullLiteral extends PrimaryExpression { + kind: SyntaxKind.NullKeyword; + } + interface BooleanLiteral extends PrimaryExpression { + kind: SyntaxKind.TrueKeyword | SyntaxKind.FalseKeyword; + } + interface ThisExpression extends PrimaryExpression { + kind: SyntaxKind.ThisKeyword; + } + interface SuperExpression extends PrimaryExpression { + kind: SyntaxKind.SuperKeyword; + } interface DeleteExpression extends UnaryExpression { + kind: SyntaxKind.DeleteExpression; expression: UnaryExpression; } interface TypeOfExpression extends UnaryExpression { + kind: SyntaxKind.TypeOfExpression; expression: UnaryExpression; } interface VoidExpression extends UnaryExpression { + kind: SyntaxKind.VoidExpression; expression: UnaryExpression; } interface AwaitExpression extends UnaryExpression { + kind: SyntaxKind.AwaitExpression; expression: UnaryExpression; } interface YieldExpression extends Expression { - asteriskToken?: Node; + kind: SyntaxKind.YieldExpression; + asteriskToken?: AsteriskToken; expression?: Expression; } + type ExponentiationOperator = SyntaxKind.AsteriskAsteriskToken; + type MultiplicativeOperator = SyntaxKind.AsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken; + type MultiplicativeOperatorOrHigher = ExponentiationOperator | MultiplicativeOperator; + type AdditiveOperator = SyntaxKind.PlusToken | SyntaxKind.MinusToken; + type AdditiveOperatorOrHigher = MultiplicativeOperatorOrHigher | AdditiveOperator; + type ShiftOperator = SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken; + type ShiftOperatorOrHigher = AdditiveOperatorOrHigher | ShiftOperator; + type RelationalOperator = SyntaxKind.LessThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.InstanceOfKeyword | SyntaxKind.InKeyword; + type RelationalOperatorOrHigher = ShiftOperatorOrHigher | RelationalOperator; + type EqualityOperator = SyntaxKind.EqualsEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.ExclamationEqualsToken; + type EqualityOperatorOrHigher = RelationalOperatorOrHigher | EqualityOperator; + type BitwiseOperator = SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken; + type BitwiseOperatorOrHigher = EqualityOperatorOrHigher | BitwiseOperator; + type LogicalOperator = SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken; + type LogicalOperatorOrHigher = BitwiseOperatorOrHigher | LogicalOperator; + type CompoundAssignmentOperator = SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken; + type AssignmentOperator = SyntaxKind.EqualsToken | CompoundAssignmentOperator; + type AssignmentOperatorOrHigher = LogicalOperatorOrHigher | AssignmentOperator; + type BinaryOperator = AssignmentOperatorOrHigher | SyntaxKind.CommaToken; + type BinaryOperatorToken = Token; interface BinaryExpression extends Expression, Declaration { + kind: SyntaxKind.BinaryExpression; left: Expression; - operatorToken: Node; + operatorToken: BinaryOperatorToken; right: Expression; } interface ConditionalExpression extends Expression { + kind: SyntaxKind.ConditionalExpression; condition: Expression; - questionToken: Node; + questionToken: QuestionToken; whenTrue: Expression; - colonToken: Node; + colonToken: ColonToken; whenFalse: Expression; } type FunctionBody = Block; type ConciseBody = FunctionBody | Expression; interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { + kind: SyntaxKind.FunctionExpression; name?: Identifier; body: FunctionBody; } interface ArrowFunction extends Expression, FunctionLikeDeclaration { - equalsGreaterThanToken: Node; + kind: SyntaxKind.ArrowFunction; + equalsGreaterThanToken: EqualsGreaterThanToken; body: ConciseBody; } interface LiteralLikeNode extends Node { @@ -717,29 +807,46 @@ declare namespace ts { interface LiteralExpression extends LiteralLikeNode, PrimaryExpression { _literalExpressionBrand: any; } + interface RegularExpressionLiteral extends LiteralExpression { + kind: SyntaxKind.RegularExpressionLiteral; + } + interface NoSubstitutionTemplateLiteral extends LiteralExpression { + kind: SyntaxKind.NoSubstitutionTemplateLiteral; + } interface NumericLiteral extends LiteralExpression { - _numericLiteralBrand: any; + kind: SyntaxKind.NumericLiteral; trailingComment?: string; } - interface TemplateLiteralFragment extends LiteralLikeNode { - _templateLiteralFragmentBrand: any; + interface TemplateHead extends LiteralLikeNode { + kind: SyntaxKind.TemplateHead; } - type Template = TemplateExpression | LiteralExpression; + interface TemplateMiddle extends LiteralLikeNode { + kind: SyntaxKind.TemplateMiddle; + } + interface TemplateTail extends LiteralLikeNode { + kind: SyntaxKind.TemplateTail; + } + type TemplateLiteral = TemplateExpression | NoSubstitutionTemplateLiteral; interface TemplateExpression extends PrimaryExpression { - head: TemplateLiteralFragment; + kind: SyntaxKind.TemplateExpression; + head: TemplateHead; templateSpans: NodeArray; } interface TemplateSpan extends Node { + kind: SyntaxKind.TemplateSpan; expression: Expression; - literal: TemplateLiteralFragment; + literal: TemplateMiddle | TemplateTail; } interface ParenthesizedExpression extends PrimaryExpression { + kind: SyntaxKind.ParenthesizedExpression; expression: Expression; } interface ArrayLiteralExpression extends PrimaryExpression { + kind: SyntaxKind.ArrayLiteralExpression; elements: NodeArray; } interface SpreadElementExpression extends Expression { + kind: SyntaxKind.SpreadElementExpression; expression: Expression; } /** @@ -752,104 +859,141 @@ declare namespace ts { properties: NodeArray; } interface ObjectLiteralExpression extends ObjectLiteralExpressionBase { + kind: SyntaxKind.ObjectLiteralExpression; } type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression; type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; interface PropertyAccessExpression extends MemberExpression, Declaration { + kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; } + interface SuperPropertyAccessExpression extends PropertyAccessExpression { + expression: SuperExpression; + } /** Brand for a PropertyAccessExpression which, like a QualifiedName, consists of a sequence of identifiers separated by dots. */ interface PropertyAccessEntityNameExpression extends PropertyAccessExpression { _propertyAccessExpressionLikeQualifiedNameBrand?: any; expression: EntityNameExpression; } interface ElementAccessExpression extends MemberExpression { + kind: SyntaxKind.ElementAccessExpression; expression: LeftHandSideExpression; argumentExpression?: Expression; } + interface SuperElementAccessExpression extends ElementAccessExpression { + expression: SuperExpression; + } + type SuperProperty = SuperPropertyAccessExpression | SuperElementAccessExpression; interface CallExpression extends LeftHandSideExpression, Declaration { + kind: SyntaxKind.CallExpression; expression: LeftHandSideExpression; typeArguments?: NodeArray; arguments: NodeArray; } + interface SuperCall extends CallExpression { + expression: SuperExpression; + } interface ExpressionWithTypeArguments extends TypeNode { + kind: SyntaxKind.ExpressionWithTypeArguments; expression: LeftHandSideExpression; typeArguments?: NodeArray; } - interface NewExpression extends CallExpression, PrimaryExpression { + interface NewExpression extends PrimaryExpression, Declaration { + kind: SyntaxKind.NewExpression; + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + arguments: NodeArray; } interface TaggedTemplateExpression extends MemberExpression { + kind: SyntaxKind.TaggedTemplateExpression; tag: LeftHandSideExpression; - template: Template; + template: TemplateLiteral; } type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; interface AsExpression extends Expression { + kind: SyntaxKind.AsExpression; expression: Expression; type: TypeNode; } interface TypeAssertion extends UnaryExpression { + kind: SyntaxKind.TypeAssertionExpression; type: TypeNode; expression: UnaryExpression; } type AssertionExpression = TypeAssertion | AsExpression; interface NonNullExpression extends LeftHandSideExpression { + kind: SyntaxKind.NonNullExpression; expression: Expression; } interface JsxElement extends PrimaryExpression { + kind: SyntaxKind.JsxElement; openingElement: JsxOpeningElement; children: NodeArray; closingElement: JsxClosingElement; } type JsxTagNameExpression = PrimaryExpression | PropertyAccessExpression; interface JsxOpeningElement extends Expression { - _openingElementBrand?: any; + kind: SyntaxKind.JsxOpeningElement; tagName: JsxTagNameExpression; attributes: NodeArray; } - interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement { - _selfClosingElementBrand?: any; + interface JsxSelfClosingElement extends PrimaryExpression { + kind: SyntaxKind.JsxSelfClosingElement; + tagName: JsxTagNameExpression; + attributes: NodeArray; } type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute; interface JsxAttribute extends Node { + kind: SyntaxKind.JsxAttribute; name: Identifier; initializer?: StringLiteral | JsxExpression; } interface JsxSpreadAttribute extends Node { + kind: SyntaxKind.JsxSpreadAttribute; expression: Expression; } interface JsxClosingElement extends Node { + kind: SyntaxKind.JsxClosingElement; tagName: JsxTagNameExpression; } interface JsxExpression extends Expression { + kind: SyntaxKind.JsxExpression; expression?: Expression; } interface JsxText extends Node { - _jsxTextExpressionBrand: any; + kind: SyntaxKind.JsxText; } type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement; interface Statement extends Node { _statementBrand: any; } interface EmptyStatement extends Statement { + kind: SyntaxKind.EmptyStatement; } interface DebuggerStatement extends Statement { + kind: SyntaxKind.DebuggerStatement; } interface MissingDeclaration extends DeclarationStatement, ClassElement, ObjectLiteralElement, TypeElement { + kind: SyntaxKind.MissingDeclaration; name?: Identifier; } type BlockLike = SourceFile | Block | ModuleBlock | CaseClause; interface Block extends Statement { + kind: SyntaxKind.Block; statements: NodeArray; } interface VariableStatement extends Statement { + kind: SyntaxKind.VariableStatement; declarationList: VariableDeclarationList; } interface ExpressionStatement extends Statement { + kind: SyntaxKind.ExpressionStatement; expression: Expression; } interface IfStatement extends Statement { + kind: SyntaxKind.IfStatement; expression: Expression; thenStatement: Statement; elseStatement?: Statement; @@ -858,68 +1002,85 @@ declare namespace ts { statement: Statement; } interface DoStatement extends IterationStatement { + kind: SyntaxKind.DoStatement; expression: Expression; } interface WhileStatement extends IterationStatement { + kind: SyntaxKind.WhileStatement; expression: Expression; } type ForInitializer = VariableDeclarationList | Expression; interface ForStatement extends IterationStatement { + kind: SyntaxKind.ForStatement; initializer?: ForInitializer; condition?: Expression; incrementor?: Expression; } interface ForInStatement extends IterationStatement { + kind: SyntaxKind.ForInStatement; initializer: ForInitializer; expression: Expression; } interface ForOfStatement extends IterationStatement { + kind: SyntaxKind.ForOfStatement; initializer: ForInitializer; expression: Expression; } interface BreakStatement extends Statement { + kind: SyntaxKind.BreakStatement; label?: Identifier; } interface ContinueStatement extends Statement { + kind: SyntaxKind.ContinueStatement; label?: Identifier; } type BreakOrContinueStatement = BreakStatement | ContinueStatement; interface ReturnStatement extends Statement { + kind: SyntaxKind.ReturnStatement; expression?: Expression; } interface WithStatement extends Statement { + kind: SyntaxKind.WithStatement; expression: Expression; statement: Statement; } interface SwitchStatement extends Statement { + kind: SyntaxKind.SwitchStatement; expression: Expression; caseBlock: CaseBlock; possiblyExhaustive?: boolean; } interface CaseBlock extends Node { + kind: SyntaxKind.CaseBlock; clauses: NodeArray; } interface CaseClause extends Node { + kind: SyntaxKind.CaseClause; expression: Expression; statements: NodeArray; } interface DefaultClause extends Node { + kind: SyntaxKind.DefaultClause; statements: NodeArray; } type CaseOrDefaultClause = CaseClause | DefaultClause; interface LabeledStatement extends Statement { + kind: SyntaxKind.LabeledStatement; label: Identifier; statement: Statement; } interface ThrowStatement extends Statement { + kind: SyntaxKind.ThrowStatement; expression: Expression; } interface TryStatement extends Statement { + kind: SyntaxKind.TryStatement; tryBlock: Block; catchClause?: CatchClause; finallyBlock?: Block; } interface CatchClause extends Node { + kind: SyntaxKind.CatchClause; variableDeclaration: VariableDeclaration; block: Block; } @@ -931,9 +1092,11 @@ declare namespace ts { members: NodeArray; } interface ClassDeclaration extends ClassLikeDeclaration, DeclarationStatement { + kind: SyntaxKind.ClassDeclaration; name?: Identifier; } interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { + kind: SyntaxKind.ClassExpression; } interface ClassElement extends Declaration { _classElementBrand: any; @@ -942,85 +1105,108 @@ declare namespace ts { interface TypeElement extends Declaration { _typeElementBrand: any; name?: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; } interface InterfaceDeclaration extends DeclarationStatement { + kind: SyntaxKind.InterfaceDeclaration; name: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; members: NodeArray; } interface HeritageClause extends Node { + kind: SyntaxKind.HeritageClause; token: SyntaxKind; types?: NodeArray; } interface TypeAliasDeclaration extends DeclarationStatement { + kind: SyntaxKind.TypeAliasDeclaration; name: Identifier; typeParameters?: NodeArray; type: TypeNode; } interface EnumMember extends Declaration { + kind: SyntaxKind.EnumMember; name: PropertyName; initializer?: Expression; } interface EnumDeclaration extends DeclarationStatement { + kind: SyntaxKind.EnumDeclaration; name: Identifier; members: NodeArray; } type ModuleBody = ModuleBlock | ModuleDeclaration; type ModuleName = Identifier | StringLiteral; interface ModuleDeclaration extends DeclarationStatement { + kind: SyntaxKind.ModuleDeclaration; name: Identifier | LiteralExpression; - body?: ModuleBlock | ModuleDeclaration; + body?: ModuleBlock | NamespaceDeclaration; + } + interface NamespaceDeclaration extends ModuleDeclaration { + name: Identifier; + body: ModuleBlock | NamespaceDeclaration; } interface ModuleBlock extends Node, Statement { + kind: SyntaxKind.ModuleBlock; statements: NodeArray; } type ModuleReference = EntityName | ExternalModuleReference; interface ImportEqualsDeclaration extends DeclarationStatement { + kind: SyntaxKind.ImportEqualsDeclaration; name: Identifier; moduleReference: ModuleReference; } interface ExternalModuleReference extends Node { + kind: SyntaxKind.ExternalModuleReference; expression?: Expression; } interface ImportDeclaration extends Statement { + kind: SyntaxKind.ImportDeclaration; importClause?: ImportClause; moduleSpecifier: Expression; } type NamedImportBindings = NamespaceImport | NamedImports; interface ImportClause extends Declaration { + kind: SyntaxKind.ImportClause; name?: Identifier; namedBindings?: NamedImportBindings; } interface NamespaceImport extends Declaration { + kind: SyntaxKind.NamespaceImport; name: Identifier; } interface NamespaceExportDeclaration extends DeclarationStatement { + kind: SyntaxKind.NamespaceExportDeclaration; name: Identifier; moduleReference: LiteralLikeNode; } interface ExportDeclaration extends DeclarationStatement { + kind: SyntaxKind.ExportDeclaration; exportClause?: NamedExports; moduleSpecifier?: Expression; } interface NamedImports extends Node { + kind: SyntaxKind.NamedImports; elements: NodeArray; } interface NamedExports extends Node { + kind: SyntaxKind.NamedExports; elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; interface ImportSpecifier extends Declaration { + kind: SyntaxKind.ImportSpecifier; propertyName?: Identifier; name: Identifier; } interface ExportSpecifier extends Declaration { + kind: SyntaxKind.ExportSpecifier; propertyName?: Identifier; name: Identifier; } type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier; interface ExportAssignment extends DeclarationStatement { + kind: SyntaxKind.ExportAssignment; isExportEquals?: boolean; expression: Expression; } @@ -1032,95 +1218,121 @@ declare namespace ts { kind: SyntaxKind; } interface JSDocTypeExpression extends Node { + kind: SyntaxKind.JSDocTypeExpression; type: JSDocType; } interface JSDocType extends TypeNode { _jsDocTypeBrand: any; } interface JSDocAllType extends JSDocType { - _JSDocAllTypeBrand: any; + kind: SyntaxKind.JSDocAllType; } interface JSDocUnknownType extends JSDocType { - _JSDocUnknownTypeBrand: any; + kind: SyntaxKind.JSDocUnknownType; } interface JSDocArrayType extends JSDocType { + kind: SyntaxKind.JSDocArrayType; elementType: JSDocType; } interface JSDocUnionType extends JSDocType { + kind: SyntaxKind.JSDocUnionType; types: NodeArray; } interface JSDocTupleType extends JSDocType { + kind: SyntaxKind.JSDocTupleType; types: NodeArray; } interface JSDocNonNullableType extends JSDocType { + kind: SyntaxKind.JSDocNonNullableType; type: JSDocType; } interface JSDocNullableType extends JSDocType { + kind: SyntaxKind.JSDocNullableType; type: JSDocType; } - interface JSDocRecordType extends JSDocType, TypeLiteralNode { + interface JSDocRecordType extends JSDocType { + kind: SyntaxKind.JSDocRecordType; literal: TypeLiteralNode; } interface JSDocTypeReference extends JSDocType { + kind: SyntaxKind.JSDocTypeReference; name: EntityName; typeArguments: NodeArray; } interface JSDocOptionalType extends JSDocType { + kind: SyntaxKind.JSDocOptionalType; type: JSDocType; } interface JSDocFunctionType extends JSDocType, SignatureDeclaration { + kind: SyntaxKind.JSDocFunctionType; parameters: NodeArray; type: JSDocType; } interface JSDocVariadicType extends JSDocType { + kind: SyntaxKind.JSDocVariadicType; type: JSDocType; } interface JSDocConstructorType extends JSDocType { + kind: SyntaxKind.JSDocConstructorType; type: JSDocType; } interface JSDocThisType extends JSDocType { + kind: SyntaxKind.JSDocThisType; type: JSDocType; } interface JSDocLiteralType extends JSDocType { + kind: SyntaxKind.JSDocLiteralType; literal: LiteralTypeNode; } type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDocRecordMember extends PropertySignature { + kind: SyntaxKind.JSDocRecordMember; name: Identifier | LiteralExpression; type?: JSDocType; } interface JSDoc extends Node { + kind: SyntaxKind.JSDocComment; tags: NodeArray | undefined; comment: string | undefined; } interface JSDocTag extends Node { - atToken: Node; + atToken: AtToken; tagName: Identifier; comment: string | undefined; } + interface JSDocUnknownTag extends JSDocTag { + kind: SyntaxKind.JSDocTag; + } interface JSDocTemplateTag extends JSDocTag { + kind: SyntaxKind.JSDocTemplateTag; typeParameters: NodeArray; } interface JSDocReturnTag extends JSDocTag { + kind: SyntaxKind.JSDocReturnTag; typeExpression: JSDocTypeExpression; } interface JSDocTypeTag extends JSDocTag { + kind: SyntaxKind.JSDocTypeTag; typeExpression: JSDocTypeExpression; } interface JSDocTypedefTag extends JSDocTag, Declaration { + kind: SyntaxKind.JSDocTypedefTag; name?: Identifier; typeExpression?: JSDocTypeExpression; jsDocTypeLiteral?: JSDocTypeLiteral; } interface JSDocPropertyTag extends JSDocTag, TypeElement { + kind: SyntaxKind.JSDocPropertyTag; name: Identifier; typeExpression: JSDocTypeExpression; } interface JSDocTypeLiteral extends JSDocType { + kind: SyntaxKind.JSDocTypeLiteral; jsDocPropertyTags?: NodeArray; jsDocTypeTag?: JSDocTypeTag; } interface JSDocParameterTag extends JSDocTag { + kind: SyntaxKind.JSDocParameterTag; /** the parameter name, if provided *before* the type (TypeScript-style) */ preParameterName?: Identifier; typeExpression?: JSDocTypeExpression; @@ -1149,7 +1361,7 @@ declare namespace ts { id?: number; } interface FlowStart extends FlowNode { - container?: FunctionExpression | ArrowFunction; + container?: FunctionExpression | ArrowFunction | MethodDeclaration; } interface FlowLabel extends FlowNode { antecedents: FlowNode[]; @@ -1178,8 +1390,9 @@ declare namespace ts { name: string; } interface SourceFile extends Declaration { + kind: SyntaxKind.SourceFile; statements: NodeArray; - endOfFileToken: Node; + endOfFileToken: Token; fileName: string; path: Path; text: string; @@ -1245,7 +1458,7 @@ declare namespace ts { * used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter * will be invoked when writing the JavaScript and declaration files. */ - emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult; + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean): EmitResult; getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; @@ -1372,6 +1585,7 @@ declare namespace ts { UseFullyQualifiedType = 128, InFirstTypeArgument = 256, InTypeAlias = 512, + UseTypeAliasValue = 1024, } enum SymbolFormatFlags { None = 0, @@ -1387,9 +1601,10 @@ declare namespace ts { type: Type; } interface ThisTypePredicate extends TypePredicateBase { - _thisTypePredicateBrand: any; + kind: TypePredicateKind.This; } interface IdentifierTypePredicate extends TypePredicateBase { + kind: TypePredicateKind.Identifier; parameterName: string; parameterIndex: number; } @@ -1495,8 +1710,6 @@ declare namespace ts { Intersection = 1048576, Anonymous = 2097152, Instantiated = 4194304, - ThisType = 268435456, - ObjectLiteralPatternWithComputedProperties = 536870912, Literal = 480, StringOrNumberLiteral = 96, PossiblyFalsy = 7406, @@ -1509,7 +1722,7 @@ declare namespace ts { StructuredType = 4161536, StructuredOrTypeParameter = 4177920, Narrowable = 4178943, - NotUnionOrUnit = 2589191, + NotUnionOrUnit = 2589185, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -1531,6 +1744,7 @@ declare namespace ts { baseType: EnumType & UnionType; } interface ObjectType extends Type { + isObjectLiteralPatternWithComputedProperties?: boolean; } interface InterfaceType extends ObjectType { typeParameters: TypeParameter[]; @@ -1614,15 +1828,13 @@ declare namespace ts { Classic = 1, NodeJs = 2, } - type RootPaths = string[]; - type PathSubstitutions = MapLike; - type TsConfigOnlyOptions = RootPaths | PathSubstitutions; - type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions; + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike; interface CompilerOptions { allowJs?: boolean; allowSyntheticDefaultImports?: boolean; allowUnreachableCode?: boolean; allowUnusedLabels?: boolean; + alwaysStrict?: boolean; baseUrl?: string; charset?: string; declaration?: boolean; @@ -1660,13 +1872,13 @@ declare namespace ts { out?: string; outDir?: string; outFile?: string; - paths?: PathSubstitutions; + paths?: MapLike; preserveConstEnums?: boolean; project?: string; reactNamespace?: string; removeComments?: boolean; rootDir?: string; - rootDirs?: RootPaths; + rootDirs?: string[]; skipLibCheck?: boolean; skipDefaultLibCheck?: boolean; sourceMap?: boolean; @@ -1742,6 +1954,7 @@ declare namespace ts { raw?: any; errors: Diagnostic[]; wildcardDirectories?: MapLike; + compileOnSave?: boolean; } enum WatchDirectoryFlags { None = 0, @@ -1846,7 +2059,7 @@ declare namespace ts { directoryName: string; referenceCount: number; } - var sys: System; + let sys: System; } declare namespace ts { interface ErrorCallback { @@ -1944,10 +2157,6 @@ declare namespace ts { function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { - /** The version of the TypeScript compiler release */ - const version = "2.1.0"; - function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; - function resolveTripleslashReference(moduleName: string, containingFile: string): string; function getEffectiveTypeRoots(options: CompilerOptions, host: { directoryExists?: (directoryName: string) => boolean; getCurrentDirectory?: () => string; @@ -1958,18 +2167,6 @@ declare namespace ts { * is assumed to be the same as root directory of the project. */ function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; - function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - interface FormatDiagnosticsHost { - getCurrentDirectory(): string; - getCanonicalFileName(fileName: string): string; - getNewLine(): string; - } - function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; - function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; /** * Given a set of options, returns the set of type directive names * that should be included for this program automatically. @@ -1979,6 +2176,24 @@ declare namespace ts { * this list is only the set of defaults that are implicitly included. */ function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; +} +declare namespace ts { + /** The version of the TypeScript compiler release */ + const version = "2.1.0"; + function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; + function resolveTripleslashReference(moduleName: string, containingFile: string): string; + function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; + function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + interface FormatDiagnosticsHost { + getCurrentDirectory(): string; + getCanonicalFileName(fileName: string): string; + getNewLine(): string; + } + function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; + function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts { @@ -1995,7 +2210,7 @@ declare namespace ts { * @param fileName The path to the config file * @param jsonText The text of the config file */ - function parseConfigFileTextToJson(fileName: string, jsonText: string): { + function parseConfigFileTextToJson(fileName: string, jsonText: string, stripComments?: boolean): { config?: any; error?: Diagnostic; }; @@ -2007,12 +2222,13 @@ declare namespace ts { * file to. e.g. outDir */ function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[]): ParsedCommandLine; + function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; }; function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { - options: CompilerOptions; + options: TypingOptions; errors: Diagnostic[]; }; } @@ -2118,6 +2334,7 @@ declare namespace ts { readDirectory?(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; readFile?(path: string, encoding?: string): string; fileExists?(path: string): boolean; + getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; directoryExists?(directoryName: string): boolean; @@ -2155,18 +2372,20 @@ declare namespace ts { getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; /** @deprecated */ getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): NavigateToItem[]; + getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; + getNavigationTree(fileName: string): NavigationTree; getOutliningSpans(fileName: string): OutliningSpan[]; getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; - getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number; - getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[]; - getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[]; - getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[]; + getIndentationAtPosition(fileName: string, position: number, options: EditorOptions | EditorSettings): number; + getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; - getEmitOutput(fileName: string): EmitOutput; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[]): CodeAction[]; + getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; } @@ -2178,6 +2397,12 @@ declare namespace ts { textSpan: TextSpan; classificationType: string; } + /** + * Navigation bar interface designed for visual studio's dual-column layout. + * This does not form a proper tree. + * The navbar is returned as a list of top-level items, each of which has a list of child items. + * Child items always have an empty array for their `childItems`. + */ interface NavigationBarItem { text: string; kind: string; @@ -2188,6 +2413,25 @@ declare namespace ts { bolded: boolean; grayed: boolean; } + /** + * Node in a tree of nested declarations in a file. + * The top node is always a script or module node. + */ + interface NavigationTree { + /** Name of the declaration, or a short description, e.g. "". */ + text: string; + /** A ScriptElementKind */ + kind: string; + /** ScriptElementKindModifier separated by commas, e.g. "public,abstract" */ + kindModifiers: string; + /** + * Spans of the nodes that generated this declaration. + * There will be more than one if this is the result of merging. + */ + spans: TextSpan[]; + /** Present if non-empty */ + childItems?: NavigationTree[]; + } interface TodoCommentDescriptor { text: string; priority: number; @@ -2201,6 +2445,16 @@ declare namespace ts { span: TextSpan; newText: string; } + interface FileTextChanges { + fileName: string; + textChanges: TextChange[]; + } + interface CodeAction { + /** Description of the code action to display in the UI of the editor */ + description: string; + /** Text changes to apply to each file as part of the code action */ + changes: FileTextChanges[]; + } interface TextInsertion { newText: string; /** The position in newText the caret should point to after the insertion. */ @@ -2246,6 +2500,11 @@ declare namespace ts { containerName: string; containerKind: string; } + enum IndentStyle { + None = 0, + Block = 1, + Smart = 2, + } interface EditorOptions { BaseIndentSize?: number; IndentSize: number; @@ -2254,10 +2513,13 @@ declare namespace ts { ConvertTabsToSpaces: boolean; IndentStyle: IndentStyle; } - enum IndentStyle { - None = 0, - Block = 1, - Smart = 2, + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle; } interface FormatCodeOptions extends EditorOptions { InsertSpaceAfterCommaDelimiter: boolean; @@ -2273,7 +2535,21 @@ declare namespace ts { InsertSpaceAfterTypeAssertion?: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; - [s: string]: boolean | number | string | undefined; + } + interface FormatCodeSettings extends EditorSettings { + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; } interface DefinitionInfo { fileName: string; @@ -2366,7 +2642,11 @@ declare namespace ts { argumentCount: number; } interface CompletionInfo { + isGlobalCompletion: boolean; isMemberCompletion: boolean; + /** + * true when the current location also allows for a new identifier + */ isNewIdentifierLocation: boolean; entries: CompletionEntry[]; } @@ -2687,8 +2967,10 @@ declare namespace ts { interface DisplayPartsSymbolWriter extends SymbolWriter { displayParts(): SymbolDisplayPart[]; } + function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; function displayPartsToString(displayParts: SymbolDisplayPart[]): string; function getDefaultCompilerOptions(): CompilerOptions; + function getSupportedCodeFixes(): string[]; function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; diff --git a/lib/typescript.js b/lib/typescript.js index 14fbdce59a8..c534a725901 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -502,6 +502,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 128] = "UseFullyQualifiedType"; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 256] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 512] = "InTypeAlias"; + TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 1024] = "UseTypeAliasValue"; })(ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var TypeFormatFlags = ts.TypeFormatFlags; (function (SymbolFormatFlags) { @@ -685,8 +686,6 @@ var ts; TypeFlags[TypeFlags["ContainsObjectLiteral"] = 67108864] = "ContainsObjectLiteral"; /* @internal */ TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 134217728] = "ContainsAnyFunctionType"; - TypeFlags[TypeFlags["ThisType"] = 268435456] = "ThisType"; - TypeFlags[TypeFlags["ObjectLiteralPatternWithComputedProperties"] = 536870912] = "ObjectLiteralPatternWithComputedProperties"; /* @internal */ TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; TypeFlags[TypeFlags["Literal"] = 480] = "Literal"; @@ -709,7 +708,7 @@ var ts; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never TypeFlags[TypeFlags["Narrowable"] = 4178943] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 2589191] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 2589185] = "NotUnionOrUnit"; /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 100663296] = "RequiresWidening"; /* @internal */ @@ -993,36 +992,44 @@ var ts; })(ts.TransformFlags || (ts.TransformFlags = {})); var TransformFlags = ts.TransformFlags; /* @internal */ - (function (NodeEmitFlags) { - NodeEmitFlags[NodeEmitFlags["EmitEmitHelpers"] = 1] = "EmitEmitHelpers"; - NodeEmitFlags[NodeEmitFlags["EmitExportStar"] = 2] = "EmitExportStar"; - NodeEmitFlags[NodeEmitFlags["EmitSuperHelper"] = 4] = "EmitSuperHelper"; - NodeEmitFlags[NodeEmitFlags["EmitAdvancedSuperHelper"] = 8] = "EmitAdvancedSuperHelper"; - NodeEmitFlags[NodeEmitFlags["UMDDefine"] = 16] = "UMDDefine"; - NodeEmitFlags[NodeEmitFlags["SingleLine"] = 32] = "SingleLine"; - NodeEmitFlags[NodeEmitFlags["AdviseOnEmitNode"] = 64] = "AdviseOnEmitNode"; - NodeEmitFlags[NodeEmitFlags["NoSubstitution"] = 128] = "NoSubstitution"; - NodeEmitFlags[NodeEmitFlags["CapturesThis"] = 256] = "CapturesThis"; - NodeEmitFlags[NodeEmitFlags["NoLeadingSourceMap"] = 512] = "NoLeadingSourceMap"; - NodeEmitFlags[NodeEmitFlags["NoTrailingSourceMap"] = 1024] = "NoTrailingSourceMap"; - NodeEmitFlags[NodeEmitFlags["NoSourceMap"] = 1536] = "NoSourceMap"; - NodeEmitFlags[NodeEmitFlags["NoNestedSourceMaps"] = 2048] = "NoNestedSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoTokenLeadingSourceMaps"] = 4096] = "NoTokenLeadingSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoTokenTrailingSourceMaps"] = 8192] = "NoTokenTrailingSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoTokenSourceMaps"] = 12288] = "NoTokenSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoLeadingComments"] = 16384] = "NoLeadingComments"; - NodeEmitFlags[NodeEmitFlags["NoTrailingComments"] = 32768] = "NoTrailingComments"; - NodeEmitFlags[NodeEmitFlags["NoComments"] = 49152] = "NoComments"; - NodeEmitFlags[NodeEmitFlags["NoNestedComments"] = 65536] = "NoNestedComments"; - NodeEmitFlags[NodeEmitFlags["ExportName"] = 131072] = "ExportName"; - NodeEmitFlags[NodeEmitFlags["LocalName"] = 262144] = "LocalName"; - NodeEmitFlags[NodeEmitFlags["Indented"] = 524288] = "Indented"; - NodeEmitFlags[NodeEmitFlags["NoIndentation"] = 1048576] = "NoIndentation"; - NodeEmitFlags[NodeEmitFlags["AsyncFunctionBody"] = 2097152] = "AsyncFunctionBody"; - NodeEmitFlags[NodeEmitFlags["ReuseTempVariableScope"] = 4194304] = "ReuseTempVariableScope"; - NodeEmitFlags[NodeEmitFlags["CustomPrologue"] = 8388608] = "CustomPrologue"; - })(ts.NodeEmitFlags || (ts.NodeEmitFlags = {})); - var NodeEmitFlags = ts.NodeEmitFlags; + (function (EmitFlags) { + EmitFlags[EmitFlags["EmitEmitHelpers"] = 1] = "EmitEmitHelpers"; + EmitFlags[EmitFlags["EmitExportStar"] = 2] = "EmitExportStar"; + EmitFlags[EmitFlags["EmitSuperHelper"] = 4] = "EmitSuperHelper"; + EmitFlags[EmitFlags["EmitAdvancedSuperHelper"] = 8] = "EmitAdvancedSuperHelper"; + EmitFlags[EmitFlags["UMDDefine"] = 16] = "UMDDefine"; + EmitFlags[EmitFlags["SingleLine"] = 32] = "SingleLine"; + EmitFlags[EmitFlags["AdviseOnEmitNode"] = 64] = "AdviseOnEmitNode"; + EmitFlags[EmitFlags["NoSubstitution"] = 128] = "NoSubstitution"; + EmitFlags[EmitFlags["CapturesThis"] = 256] = "CapturesThis"; + EmitFlags[EmitFlags["NoLeadingSourceMap"] = 512] = "NoLeadingSourceMap"; + EmitFlags[EmitFlags["NoTrailingSourceMap"] = 1024] = "NoTrailingSourceMap"; + EmitFlags[EmitFlags["NoSourceMap"] = 1536] = "NoSourceMap"; + EmitFlags[EmitFlags["NoNestedSourceMaps"] = 2048] = "NoNestedSourceMaps"; + EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 4096] = "NoTokenLeadingSourceMaps"; + EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 8192] = "NoTokenTrailingSourceMaps"; + EmitFlags[EmitFlags["NoTokenSourceMaps"] = 12288] = "NoTokenSourceMaps"; + EmitFlags[EmitFlags["NoLeadingComments"] = 16384] = "NoLeadingComments"; + EmitFlags[EmitFlags["NoTrailingComments"] = 32768] = "NoTrailingComments"; + EmitFlags[EmitFlags["NoComments"] = 49152] = "NoComments"; + EmitFlags[EmitFlags["NoNestedComments"] = 65536] = "NoNestedComments"; + EmitFlags[EmitFlags["ExportName"] = 131072] = "ExportName"; + EmitFlags[EmitFlags["LocalName"] = 262144] = "LocalName"; + EmitFlags[EmitFlags["Indented"] = 524288] = "Indented"; + EmitFlags[EmitFlags["NoIndentation"] = 1048576] = "NoIndentation"; + EmitFlags[EmitFlags["AsyncFunctionBody"] = 2097152] = "AsyncFunctionBody"; + EmitFlags[EmitFlags["ReuseTempVariableScope"] = 4194304] = "ReuseTempVariableScope"; + EmitFlags[EmitFlags["CustomPrologue"] = 8388608] = "CustomPrologue"; + })(ts.EmitFlags || (ts.EmitFlags = {})); + var EmitFlags = ts.EmitFlags; + /* @internal */ + (function (EmitContext) { + EmitContext[EmitContext["SourceFile"] = 0] = "SourceFile"; + EmitContext[EmitContext["Expression"] = 1] = "Expression"; + EmitContext[EmitContext["IdentifierName"] = 2] = "IdentifierName"; + EmitContext[EmitContext["Unspecified"] = 3] = "Unspecified"; + })(ts.EmitContext || (ts.EmitContext = {})); + var EmitContext = ts.EmitContext; })(ts || (ts = {})); /*@internal*/ var ts; @@ -1032,7 +1039,6 @@ var ts; })(ts || (ts = {})); /*@internal*/ /** Performance measurements for the compiler. */ -var ts; (function (ts) { var performance; (function (performance) { @@ -1164,6 +1170,7 @@ var ts; contains: contains, remove: remove, forEachValue: forEachValueInMap, + getKeys: getKeys, clear: clear }; function forEachValueInMap(f) { @@ -1171,6 +1178,13 @@ var ts; f(key, files[key]); } } + function getKeys() { + var keys = []; + for (var key in files) { + keys.push(key); + } + return keys; + } // path should already be well-formed so it does not need to be normalized function get(path) { return files[toKey(path)]; @@ -1501,6 +1515,7 @@ var ts; return array1.concat(array2); } ts.concatenate = concatenate; + // TODO: fixme (N^2) - add optional comparer so collection can be sorted before deduplication. function deduplicate(array, areEqual) { var result; if (array) { @@ -1604,16 +1619,22 @@ var ts; * @param array A sorted array whose first element must be no larger than number * @param number The value to be searched for in the array. */ - function binarySearch(array, value) { + function binarySearch(array, value, comparer) { + if (!array || array.length === 0) { + return -1; + } var low = 0; var high = array.length - 1; + comparer = comparer !== undefined + ? comparer + : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; - if (midValue === value) { + if (comparer(midValue, value) === 0) { return middle; } - else if (midValue > value) { + else if (comparer(midValue, value) > 0) { high = middle - 1; } else { @@ -1929,6 +1950,56 @@ var ts; }; } ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (t) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { baseIndex = baseIndex || 0; return text.replace(/{(\d+)}/g, function (match, index) { return args[+index + baseIndex]; }); @@ -2096,7 +2167,9 @@ var ts; return path.replace(/\\/g, "/"); } ts.normalizeSlashes = normalizeSlashes; - // Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files") + /** + * Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files") + */ function getRootLength(path) { if (path.charCodeAt(0) === 47 /* slash */) { if (path.charCodeAt(1) !== 47 /* slash */) @@ -2129,6 +2202,11 @@ var ts; return 0; } ts.getRootLength = getRootLength; + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ ts.directorySeparator = "/"; var directorySeparatorCharCode = 47 /* slash */; function getNormalizedParts(normalizedSlashedPath, rootLength) { @@ -2178,10 +2256,49 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; + function isExternalModuleNameRelative(moduleName) { + // TypeScript 1.0 spec (April 2014): 11.2.1 + // An external module name is "relative" if the first term is "." or "..". + return /^\.\.?($|[\\/])/.test(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0 /* ES3 */; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + /* @internal */ + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42 /* asterisk */) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + // have already seen asterisk + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; function isRootedDiskPath(path) { return getRootLength(path) !== 0; } ts.isRootedDiskPath = isRootedDiskPath; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; function normalizedPathComponents(path, rootLength) { var normalizedParts = getNormalizedParts(path, rootLength); return [path.substr(0, rootLength)].concat(normalizedParts); @@ -2625,6 +2742,14 @@ var ts; return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } ts.getSupportedExtensions = getSupportedExtensions; + function hasJavaScriptFileExtension(fileName) { + return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; @@ -2737,7 +2862,6 @@ var ts; this.transformFlags = 0 /* None */; this.parent = undefined; this.original = undefined; - this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, @@ -2757,9 +2881,9 @@ var ts; var AssertionLevel = ts.AssertionLevel; var Debug; (function (Debug) { - var currentAssertionLevel; + Debug.currentAssertionLevel = 0 /* None */; function shouldAssert(level) { - return getCurrentAssertionLevel() >= level; + return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -2777,30 +2901,7 @@ var ts; Debug.assert(/*expression*/ false, message); } Debug.fail = fail; - function getCurrentAssertionLevel() { - if (currentAssertionLevel !== undefined) { - return currentAssertionLevel; - } - if (ts.sys === undefined) { - return 0 /* None */; - } - var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); - currentAssertionLevel = developmentMode - ? 1 /* Normal */ - : 0 /* None */; - return currentAssertionLevel; - } })(Debug = ts.Debug || (ts.Debug = {})); - function getEnvironmentVariable(name, host) { - if (host && host.getEnvironmentVariable) { - return host.getEnvironmentVariable(name); - } - if (ts.sys && ts.sys.getEnvironmentVariable) { - return ts.sys.getEnvironmentVariable(name); - } - return ""; - } - ts.getEnvironmentVariable = getEnvironmentVariable; /** Remove an item from an array, moving everything to its right one space left. */ function orderedRemoveItemAt(array, index) { // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`. @@ -2836,6 +2937,84 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; + /** + * patternStrings contains both pattern strings (containing "*") and regular strings. + * Return an exact match if possible, or a pattern match, or undefined. + * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) + */ + /* @internal */ + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + // pattern was matched as is - no need to search further + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + /* @internal */ + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + /** + * Given that candidate matches pattern, returns the text matching the '*'. + * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" + */ + /* @internal */ + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + /** Return the object corresponding to the best pattern to match `candidate`. */ + /* @internal */ + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + // use length of prefix as betterness criteria + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + /* @internal */ + function tryParsePattern(pattern) { + // This should be verified outside of here and a proper error thrown. + Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + // This is a fast way of testing the following conditions: + // pos === undefined || pos === null || isNaN(pos) || pos < 0; + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; })(ts || (ts = {})); /// var ts; @@ -3040,9 +3219,17 @@ var ts; function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; } + function isFileSystemCaseSensitive() { + // win32\win64 are case insensitive platforms + if (platform === "win32" || platform === "win64") { + return false; + } + // convert current file name to upper case / lower case and check if file exists + // (guards against cases when name is already all uppercase or lowercase) + return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + } var platform = _os.platform(); - // win32\win64 are case insensitive platforms, MacOS (darwin) by default is also case insensitive - var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); function readFile(fileName, encoding) { if (!fileExists(fileName)) { return undefined; @@ -3182,6 +3369,9 @@ var ts; // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) var options; + if (!directoryExists(directoryName)) { + return; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -3299,21 +3489,46 @@ var ts; realpath: realpath }; } + function recursiveCreateDirectory(directoryPath, sys) { + var basePath = ts.getDirectoryPath(directoryPath); + var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + if (shouldCreateParent) { + recursiveCreateDirectory(basePath, sys); + } + if (shouldCreateParent || !sys.directoryExists(directoryPath)) { + sys.createDirectory(directoryPath); + } + } + var sys; if (typeof ChakraHost !== "undefined") { - return getChakraSystem(); + sys = getChakraSystem(); } else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { - return getWScriptSystem(); + sys = getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { // process and process.nextTick checks if current environment is node-like // process.browser check excludes webpack and browserify - return getNodeSystem(); + sys = getNodeSystem(); } - else { - return undefined; // Unsupported host + if (sys) { + // patch writefile to create folder before writing the file + var originalWriteFile_1 = sys.writeFile; + sys.writeFile = function (path, data, writeBom) { + var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); + if (directoryPath && !sys.directoryExists(directoryPath)) { + recursiveCreateDirectory(directoryPath, sys); + } + originalWriteFile_1.call(sys, path, data, writeBom); + }; } + return sys; })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 /* Normal */ + : 0 /* None */; + } })(ts || (ts = {})); // /// @@ -3641,7 +3856,7 @@ var ts; The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class" }, - All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "All_symbols_within_a_with_block_will_be_resolved_to_any_2410", message: "All symbols within a 'with' block will be resolved to 'any'." }, + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, @@ -3802,7 +4017,7 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, - Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, @@ -4035,6 +4250,8 @@ var ts; No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file" }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -4059,6 +4276,7 @@ var ts; Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, + Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type 'any' in some locations where its type cannot be determined." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -4088,7 +4306,14 @@ var ts; super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } + The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." }, + Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, + Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, + Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'" }, + Remove_unused_identifiers: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_unused_identifiers_90004", message: "Remove unused identifiers" }, + Implement_interface_on_reference: { code: 90005, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_reference_90005", message: "Implement interface on reference" }, + Implement_interface_on_class: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_class_90006", message: "Implement interface on class" }, + Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class" } }; })(ts || (ts = {})); /// @@ -5145,7 +5370,7 @@ var ts; return token = 69 /* Identifier */; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8"); + ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); var value = 0; // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. @@ -6364,10 +6589,10 @@ var ts; return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */); } ts.isLet = isLet; - function isSuperCallExpression(n) { + function isSuperCall(n) { return n.kind === 174 /* CallExpression */ && n.expression.kind === 95 /* SuperKeyword */; } - ts.isSuperCallExpression = isSuperCallExpression; + ts.isSuperCall = isSuperCall; function isPrologueDirective(node) { return node.kind === 202 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; } @@ -6636,6 +6861,12 @@ var ts; return node && node.kind === 147 /* MethodDeclaration */ && node.parent.kind === 171 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 147 /* MethodDeclaration */ && + (node.parent.kind === 171 /* ObjectLiteralExpression */ || + node.parent.kind === 192 /* ClassExpression */); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { return predicate && predicate.kind === 1 /* Identifier */; } @@ -6723,11 +6954,11 @@ var ts; } ts.getThisContainer = getThisContainer; /** - * Given an super call\property node returns a closest node where either - * - super call\property is legal in the node and not legal in the parent node the node. + * Given an super call/property node, returns the closest node where + * - a super call/property access is legal in the node and not legal in the parent node the node. * i.e. super call is legal in constructor but not legal in the class body. - * - node is arrow function (so caller might need to call getSuperContainer in case it needs to climb higher) - * - super call\property is definitely illegal in the node (but might be legal in some subnode) + * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher) + * - a super call/property is definitely illegal in the container (but might be legal in some subnode) * i.e. super property access is illegal in function declaration but can be legal in the statement list */ function getSuperContainer(node, stopOnFunctions) { @@ -6988,12 +7219,6 @@ var ts; return false; } ts.isPartOfExpression = isPartOfExpression; - function isExternalModuleNameRelative(moduleName) { - // TypeScript 1.0 spec (April 2014): 11.2.1 - // An external module name is "relative" if the first term is "." or "..". - return /^\.\.?($|[\\/])/.test(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { var moduleState = ts.getModuleInstanceState(node); return moduleState === 1 /* Instantiated */ || @@ -7655,16 +7880,10 @@ var ts; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(node) { - return positionIsSynthesized(node.pos) - || positionIsSynthesized(node.end); + return ts.positionIsSynthesized(node.pos) + || ts.positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function positionIsSynthesized(pos) { - // This is a fast way of testing the following conditions: - // pos === undefined || pos === null || isNaN(pos) || pos < 0; - return !(pos >= 0); - } - ts.positionIsSynthesized = positionIsSynthesized; function getOriginalNode(node) { if (node) { while (node.original !== undefined) { @@ -8125,24 +8344,12 @@ var ts; function getDeclarationEmitOutputFilePath(sourceFile, host) { var options = host.getCompilerOptions(); var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified - if (options.declaration) { - var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; - } + var path = outputDir + ? getSourceFilePathInNewDir(sourceFile, host, outputDir) + : sourceFile.fileName; + return ts.removeFileExtension(path) + ".d.ts"; } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; - function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0 /* ES3 */; - } - ts.getEmitScriptTarget = getEmitScriptTarget; - function getEmitModuleKind(compilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; - } - ts.getEmitModuleKind = getEmitModuleKind; /** * Gets the source files that are expected to have an emit output. * @@ -8155,7 +8362,7 @@ var ts; function getSourceFilesToEmit(host, targetSourceFile) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { - var moduleKind = getEmitModuleKind(options); + var moduleKind = ts.getEmitModuleKind(options); var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; var sourceFiles = host.getSourceFiles(); // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified @@ -8184,7 +8391,7 @@ var ts; * @param sourceFiles The transformed source files to emit. * @param action The action to execute. */ - function forEachTransformedEmitFile(host, sourceFiles, action) { + function forEachTransformedEmitFile(host, sourceFiles, action, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); // Emit on each source file if (options.outFile || options.out) { @@ -8217,7 +8424,7 @@ var ts; } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (options.declaration || emitOnlyDtsFiles) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], /*isBundledEmit*/ false); } function onBundledEmit(host, sourceFiles) { @@ -8242,7 +8449,7 @@ var ts; * @param action The action to execute. * @param targetSourceFile An optional target source file to emit. */ - function forEachExpectedEmitFile(host, action, targetSourceFile) { + function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); // Emit on each source file if (options.outFile || options.out) { @@ -8275,12 +8482,13 @@ var ts; } } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var emitFileNames = { jsFilePath: jsFilePath, sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), - declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined + declarationFilePath: declarationFilePath }; - action(emitFileNames, [sourceFile], /*isBundledEmit*/ false); + action(emitFileNames, [sourceFile], /*isBundledEmit*/ false, emitOnlyDtsFiles); } function onBundledEmit(host) { // Can emit only sources that are not declaration file and are either non module code or module with @@ -8288,7 +8496,7 @@ var ts; var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile) && (!ts.isExternalModule(sourceFile) || - !!getEmitModuleKind(options)); }); + !!ts.getEmitModuleKind(options)); }); if (bundledSources.length) { var jsFilePath = options.outFile || options.out; var emitFileNames = { @@ -8296,7 +8504,7 @@ var ts; sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined }; - action(emitFileNames, bundledSources, /*isBundledEmit*/ true); + action(emitFileNames, bundledSources, /*isBundledEmit*/ true, emitOnlyDtsFiles); } } } @@ -8331,15 +8539,35 @@ var ts; }); } ts.getFirstConstructorWithBody = getFirstConstructorWithBody; + /** Get the type annotaion for the value parameter. */ function getSetAccessorTypeAnnotationNode(accessor) { if (accessor && accessor.parameters.length > 0) { - var hasThis = accessor.parameters.length === 2 && - accessor.parameters[0].name.kind === 69 /* Identifier */ && - accessor.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */; + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); return accessor.parameters[hasThis ? 1 : 0].type; } } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + if (signature.parameters.length) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return node && node.kind === 69 /* Identifier */ && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 97 /* ThisKeyword */; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -8700,14 +8928,6 @@ var ts; return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function hasJavaScriptFileExtension(fileName) { - return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ function tryExtractTypeScriptExtension(fileName) { return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); @@ -8820,12 +9040,6 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !ts.isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /* isAbsolutePathAnUrl */ false); - } - ts.convertToRelativePath = convertToRelativePath; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { @@ -8938,7 +9152,7 @@ var ts; * @param value The delta. */ function movePos(pos, value) { - return positionIsSynthesized(pos) ? -1 : pos + value; + return ts.positionIsSynthesized(pos) ? -1 : pos + value; } ts.movePos = movePos; /** @@ -9054,7 +9268,7 @@ var ts; } ts.positionsAreOnSameLine = positionsAreOnSameLine; function getStartPositionOfRange(range, sourceFile) { - return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); } ts.getStartPositionOfRange = getStartPositionOfRange; function collectExternalModuleInfo(sourceFile, resolver) { @@ -9179,15 +9393,16 @@ var ts; return 11 /* FirstTemplateToken */ <= kind && kind <= 14 /* LastTemplateToken */; } ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isTemplateLiteralFragmentKind(kind) { - return kind === 12 /* TemplateHead */ - || kind === 13 /* TemplateMiddle */ + function isTemplateHead(node) { + return node.kind === 12 /* TemplateHead */; + } + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 13 /* TemplateMiddle */ || kind === 14 /* TemplateTail */; } - function isTemplateLiteralFragment(node) { - return isTemplateLiteralFragmentKind(node.kind); - } - ts.isTemplateLiteralFragment = isTemplateLiteralFragment; + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; // Identifiers function isIdentifier(node) { return node.kind === 69 /* Identifier */; @@ -9340,12 +9555,12 @@ var ts; return node.kind === 174 /* CallExpression */; } ts.isCallExpression = isCallExpression; - function isTemplate(node) { + function isTemplateLiteral(node) { var kind = node.kind; return kind === 189 /* TemplateExpression */ || kind === 11 /* NoSubstitutionTemplateLiteral */; } - ts.isTemplate = isTemplate; + ts.isTemplateLiteral = isTemplateLiteral; function isSpreadElementExpression(node) { return node.kind === 191 /* SpreadElementExpression */; } @@ -9688,7 +9903,6 @@ var ts; } ts.isWatchSet = isWatchSet; })(ts || (ts = {})); -var ts; (function (ts) { function getDefaultLibFileName(options) { return options.target === 2 /* ES6 */ ? "lib.es6.d.ts" : "lib.d.ts"; @@ -10029,7 +10243,7 @@ var ts; // the original node. We also need to exclude specific properties and only include own- // properties (to skip members already defined on the shared prototype). var clone = createNode(node.kind, /*location*/ undefined, node.flags); - clone.original = node; + setOriginalNode(clone, node); for (var key in node) { if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { continue; @@ -10064,7 +10278,7 @@ var ts; node.text = value; return node; } - else { + else if (value) { var node = createNode(9 /* StringLiteral */, location, /*flags*/ undefined); node.textSourceNode = value; node.text = value.text; @@ -10364,7 +10578,7 @@ var ts; function createPropertyAccess(expression, name, location, flags) { var node = createNode(172 /* PropertyAccessExpression */, location, flags); node.expression = parenthesizeForAccess(expression); - node.emitFlags = 1048576 /* NoIndentation */; + (node.emitNode || (node.emitNode = {})).flags |= 1048576 /* NoIndentation */; node.name = typeof name === "string" ? createIdentifier(name) : name; return node; } @@ -10373,7 +10587,7 @@ var ts; if (node.expression !== expression || node.name !== name) { var propertyAccess = createPropertyAccess(expression, name, /*location*/ node, node.flags); // Because we are updating existed propertyAccess we want to inherit its emitFlags instead of using default from createPropertyAccess - propertyAccess.emitFlags = node.emitFlags; + (propertyAccess.emitNode || (propertyAccess.emitNode = {})).flags = getEmitFlags(node); return updateNode(propertyAccess, node); } return node; @@ -10477,7 +10691,7 @@ var ts; node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken || createNode(34 /* EqualsGreaterThanToken */); + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(34 /* EqualsGreaterThanToken */); node.body = parenthesizeConciseBody(body); return node; } @@ -10570,7 +10784,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right, location) { - var operatorToken = typeof operator === "number" ? createSynthesizedNode(operator) : operator; + var operatorToken = typeof operator === "number" ? createToken(operator) : operator; var operatorKind = operatorToken.kind; var node = createNode(187 /* BinaryExpression */, location); node.left = parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); @@ -11492,7 +11706,7 @@ var ts; } else { var expression = ts.isIdentifier(memberName) ? createPropertyAccess(target, memberName, location) : createElementAccess(target, memberName, location); - expression.emitFlags |= 2048 /* NoNestedSourceMaps */; + (expression.emitNode || (expression.emitNode = {})).flags |= 2048 /* NoNestedSourceMaps */; return expression; } } @@ -11500,7 +11714,7 @@ var ts; function createRestParameter(name) { return createParameterDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, createSynthesizedNode(22 /* DotDotDotToken */), name, + /*modifiers*/ undefined, createToken(22 /* DotDotDotToken */), name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); @@ -11630,13 +11844,13 @@ var ts; } ts.createDecorateHelper = createDecorateHelper; function createAwaiterHelper(externalHelpersModuleName, hasLexicalArguments, promiseConstructor, body) { - var generatorFunc = createFunctionExpression(createNode(37 /* AsteriskToken */), + var generatorFunc = createFunctionExpression(createToken(37 /* AsteriskToken */), /*name*/ undefined, /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, body); // Mark this node as originally an async function - generatorFunc.emitFlags |= 2097152 /* AsyncFunctionBody */; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 2097152 /* AsyncFunctionBody */; return createCall(createHelperName(externalHelpersModuleName, "__awaiter"), /*typeArguments*/ undefined, [ createThis(), @@ -11953,7 +12167,7 @@ var ts; target.push(startOnNewLine(createStatement(createLiteral("use strict")))); foundUseStrict = true; } - if (statement.emitFlags & 8388608 /* CustomPrologue */) { + if (getEmitFlags(statement) & 8388608 /* CustomPrologue */) { target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { @@ -11965,6 +12179,34 @@ var ts; return statementOffset; } ts.addPrologueDirectives = addPrologueDirectives; + /** + * Ensures "use strict" directive is added + * + * @param node source file + */ + function ensureUseStrict(node) { + var foundUseStrict = false; + for (var _i = 0, _a = node.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + break; + } + } + else { + break; + } + } + if (!foundUseStrict) { + var statements = []; + statements.push(startOnNewLine(createStatement(createLiteral("use strict")))); + // add "use strict" as the first statement + return updateSourceFileNode(node, statements.concat(node.statements)); + } + return node; + } + ts.ensureUseStrict = ensureUseStrict; /** * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended * order of operations. @@ -12323,17 +12565,180 @@ var ts; function setOriginalNode(node, original) { node.original = original; if (original) { - var emitFlags = original.emitFlags, commentRange = original.commentRange, sourceMapRange = original.sourceMapRange; - if (emitFlags) - node.emitFlags = emitFlags; - if (commentRange) - node.commentRange = commentRange; - if (sourceMapRange) - node.sourceMapRange = sourceMapRange; + var emitNode = original.emitNode; + if (emitNode) + node.emitNode = mergeEmitNode(emitNode, node.emitNode); } return node; } ts.setOriginalNode = setOriginalNode; + function mergeEmitNode(sourceEmitNode, destEmitNode) { + var flags = sourceEmitNode.flags, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges; + if (!destEmitNode && (flags || commentRange || sourceMapRange || tokenSourceMapRanges)) + destEmitNode = {}; + if (flags) + destEmitNode.flags = flags; + if (commentRange) + destEmitNode.commentRange = commentRange; + if (sourceMapRange) + destEmitNode.sourceMapRange = sourceMapRange; + if (tokenSourceMapRanges) + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + return destEmitNode; + } + function mergeTokenSourceMapRanges(sourceRanges, destRanges) { + if (!destRanges) + destRanges = ts.createMap(); + ts.copyProperties(sourceRanges, destRanges); + return destRanges; + } + /** + * Clears any EmitNode entries from parse-tree nodes. + * @param sourceFile A source file. + */ + function disposeEmitNodes(sourceFile) { + // During transformation we may need to annotate a parse tree node with transient + // transformation properties. As parse tree nodes live longer than transformation + // nodes, we need to make sure we reclaim any memory allocated for custom ranges + // from these nodes to ensure we do not hold onto entire subtrees just for position + // information. We also need to reset these nodes to a pre-transformation state + // for incremental parsing scenarios so that we do not impact later emit. + sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile)); + var emitNode = sourceFile && sourceFile.emitNode; + var annotatedNodes = emitNode && emitNode.annotatedNodes; + if (annotatedNodes) { + for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) { + var node = annotatedNodes_1[_i]; + node.emitNode = undefined; + } + } + } + ts.disposeEmitNodes = disposeEmitNodes; + /** + * Associates a node with the current transformation, initializing + * various transient transformation properties. + * + * @param node The node. + */ + function getOrCreateEmitNode(node) { + if (!node.emitNode) { + if (ts.isParseTreeNode(node)) { + // To avoid holding onto transformation artifacts, we keep track of any + // parse tree node we are annotating. This allows us to clean them up after + // all transformations have completed. + if (node.kind === 256 /* SourceFile */) { + return node.emitNode = { annotatedNodes: [node] }; + } + var sourceFile = ts.getSourceFileOfNode(node); + getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); + } + node.emitNode = {}; + } + return node.emitNode; + } + /** + * Gets flags that control emit behavior of a node. + * + * @param node The node. + */ + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags; + } + ts.getEmitFlags = getEmitFlags; + /** + * Sets flags that control emit behavior of a node. + * + * @param node The node. + * @param emitFlags The NodeEmitFlags for the node. + */ + function setEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).flags = emitFlags; + return node; + } + ts.setEmitFlags = setEmitFlags; + /** + * Sets a custom text range to use when emitting source maps. + * + * @param node The node. + * @param range The text range. + */ + function setSourceMapRange(node, range) { + getOrCreateEmitNode(node).sourceMapRange = range; + return node; + } + ts.setSourceMapRange = setSourceMapRange; + /** + * Sets the TextRange to use for source maps for a token of a node. + * + * @param node The node. + * @param token The token. + * @param range The text range. + */ + function setTokenSourceMapRange(node, token, range) { + var emitNode = getOrCreateEmitNode(node); + var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = ts.createMap()); + tokenSourceMapRanges[token] = range; + return node; + } + ts.setTokenSourceMapRange = setTokenSourceMapRange; + /** + * Sets a custom text range to use when emitting comments. + */ + function setCommentRange(node, range) { + getOrCreateEmitNode(node).commentRange = range; + return node; + } + ts.setCommentRange = setCommentRange; + /** + * Gets a custom text range to use when emitting comments. + * + * @param node The node. + */ + function getCommentRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.commentRange) || node; + } + ts.getCommentRange = getCommentRange; + /** + * Gets a custom text range to use when emitting source maps. + * + * @param node The node. + */ + function getSourceMapRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.sourceMapRange) || node; + } + ts.getSourceMapRange = getSourceMapRange; + /** + * Gets the TextRange to use for source maps for a token of a node. + * + * @param node The node. + * @param token The token. + */ + function getTokenSourceMapRange(node, token) { + var emitNode = node.emitNode; + var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; + return tokenSourceMapRanges && tokenSourceMapRanges[token]; + } + ts.getTokenSourceMapRange = getTokenSourceMapRange; + /** + * Gets the constant value to emit for an expression. + */ + function getConstantValue(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.constantValue; + } + ts.getConstantValue = getConstantValue; + /** + * Sets the constant value to emit for an expression. + */ + function setConstantValue(node, value) { + var emitNode = getOrCreateEmitNode(node); + emitNode.constantValue = value; + return node; + } + ts.setConstantValue = setConstantValue; function setTextRange(node, location) { if (location) { node.pos = location.pos; @@ -12376,13 +12781,13 @@ var ts; } ts.getLocalNameForExternalImport = getLocalNameForExternalImport; /** - * Get the name of a target module from an import/export declaration as should be written in the emitted output. - * The emitted output name can be different from the input if: - * 1. The module has a /// - * 2. --out or --outFile is used, making the name relative to the rootDir - * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System). - * Otherwise, a new StringLiteral node representing the module name will be returned. - */ + * Get the name of a target module from an import/export declaration as should be written in the emitted output. + * The emitted output name can be different from the input if: + * 1. The module has a /// + * 2. --out or --outFile is used, making the name relative to the rootDir + * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System). + * Otherwise, a new StringLiteral node representing the module name will be returned. + */ function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { var moduleName = ts.getExternalModuleName(importNode); if (moduleName.kind === 9 /* StringLiteral */) { @@ -13683,8 +14088,8 @@ var ts; // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery return token() === 18 /* CloseParenToken */ || token() === 20 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; case 18 /* TypeArguments */: - // Tokens other than '>' are here for better error recovery - return token() === 27 /* GreaterThanToken */ || token() === 17 /* OpenParenToken */; + // All other tokens should cause the type-argument to terminate except comma token + return token() !== 24 /* CommaToken */; case 20 /* HeritageClauses */: return token() === 15 /* OpenBraceToken */ || token() === 16 /* CloseBraceToken */; case 13 /* JsxAttributes */: @@ -14135,7 +14540,7 @@ var ts; } function parseTemplateExpression() { var template = createNode(189 /* TemplateExpression */); - template.head = parseTemplateLiteralFragment(); + template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 12 /* TemplateHead */, "Template head has wrong token kind"); var templateSpans = createNodeArray(); do { @@ -14151,7 +14556,7 @@ var ts; var literal; if (token() === 16 /* CloseBraceToken */) { reScanTemplateToken(); - literal = parseTemplateLiteralFragment(); + literal = parseTemplateMiddleOrTemplateTail(); } else { literal = parseExpectedToken(14 /* TemplateTail */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(16 /* CloseBraceToken */)); @@ -14162,8 +14567,15 @@ var ts; function parseLiteralNode(internName) { return parseLiteralLikeNode(token(), internName); } - function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token(), /*internName*/ false); + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token(), /*internName*/ false); + ts.Debug.assert(fragment.kind === 12 /* TemplateHead */, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token(), /*internName*/ false); + ts.Debug.assert(fragment.kind === 13 /* TemplateMiddle */ || fragment.kind === 14 /* TemplateTail */, "Template fragment has wrong token kind"); + return fragment; } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -17144,7 +17556,7 @@ var ts; parseExpected(56 /* EqualsToken */); node.type = parseType(); parseSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } // In an ambient declaration, the grammar only allows integer literals as initializers. // In a non-ambient declaration, the grammar allows uninitialized members only in a @@ -17702,6 +18114,7 @@ var ts; var parameter = createNode(142 /* Parameter */); parameter.type = parseJSDocType(); if (parseOptional(56 /* EqualsToken */)) { + // TODO(rbuckton): Can this be changed to SyntaxKind.QuestionToken? parameter.questionToken = createNode(56 /* EqualsToken */); } return finishNode(parameter); @@ -18895,6 +19308,7 @@ var ts; ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression"; ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals"; ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; + ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; })(ContainerFlags || (ContainerFlags = {})); var binder = createBinder(); function bindSourceFile(file, options) { @@ -18927,7 +19341,8 @@ var ts; var emitFlags; // If this file is an external module, then it is automatically in strict-mode according to // ES6. If it is not an external module, then we'll determine if it is in strict mode or - // not depending on if we see "use strict" in certain places (or if we hit a class/namespace). + // not depending on if we see "use strict" in certain places or if we hit a class/namespace + // or if compiler options contain alwaysStrict. var inStrictMode; var symbolCount = 0; var Symbol; @@ -18941,7 +19356,7 @@ var ts; file = f; options = opts; languageVersion = ts.getEmitScriptTarget(options); - inStrictMode = !!file.externalModuleIndicator; + inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; skipTransformFlagAggregation = ts.isDeclarationFile(file); @@ -18971,6 +19386,15 @@ var ts; subtreeTransformFlags = 0 /* None */; } return bindSourceFile; + function bindInStrictMode(file, opts) { + if (opts.alwaysStrict && !ts.isDeclarationFile(file)) { + // bind in strict mode source files with alwaysStrict option + return true; + } + else { + return !!file.externalModuleIndicator; + } + } function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); @@ -19134,11 +19558,24 @@ var ts; var message_1 = symbol.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (ts.hasModifier(declaration, 512 /* Default */)) { + if (symbol.declarations && symbol.declarations.length) { + // If the current node is a default export of some sort, then check if + // there are any other default exports that we need to error on. + // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. + if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } - }); + else { + // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. + // Error on multiple export default in the following case: + // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default + // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) + if (symbol.declarations && symbol.declarations.length && + (isDefaultExport || (node.kind === 235 /* ExportAssignment */ && !node.isExportEquals))) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + } + } ts.forEach(symbol.declarations, function (declaration) { file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); }); @@ -19243,7 +19680,7 @@ var ts; } else { currentFlow = { flags: 2 /* Start */ }; - if (containerFlags & 16 /* IsFunctionExpression */) { + if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { currentFlow.container = node; } currentReturnTarget = undefined; @@ -19705,7 +20142,11 @@ var ts; currentFlow = preTryFlow; bind(node.finallyBlock); } - currentFlow = finishFlowLabel(postFinallyLabel); + // if try statement has finally block and flow after finally block is unreachable - keep it + // otherwise use whatever flow was accumulated at postFinallyLabel + if (!node.finallyBlock || !(currentFlow.flags & 1 /* Unreachable */)) { + currentFlow = finishFlowLabel(postFinallyLabel); + } } function bindSwitchStatement(node) { var postSwitchLabel = createBranchLabel(); @@ -19840,7 +20281,7 @@ var ts; } else { ts.forEachChild(node, bind); - if (node.operator === 57 /* PlusEqualsToken */ || node.operator === 42 /* MinusMinusToken */) { + if (node.operator === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) { bindAssignmentTargetFlow(node.operand); } } @@ -19942,9 +20383,12 @@ var ts; return 1 /* IsContainer */ | 32 /* HasLocals */; case 256 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; + case 147 /* MethodDeclaration */: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; + } case 148 /* Constructor */: case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: case 146 /* MethodSignature */: case 149 /* GetAccessor */: case 150 /* SetAccessor */: @@ -20588,10 +21032,13 @@ var ts; bindAnonymousDeclaration(node, 8388608 /* Alias */, getDeclarationName(node)); } else { + // An export default clause with an expression exports a value + // We want to exclude both class and function here, this is necessary to issue an error when there are both + // default export-assignment and default export function and class declaration. var flags = node.kind === 235 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) ? 8388608 /* Alias */ : 4 /* Property */; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); + declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 /* Property */ | 8388608 /* AliasExcludes */ | 32 /* Class */ | 16 /* Function */); } } function bindNamespaceExportDeclaration(node) { @@ -20829,6 +21276,9 @@ var ts; emitFlags |= 2048 /* HasDecorators */; } } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } return ts.hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); @@ -20994,8 +21444,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // If the parameter's name is 'this', then it is TypeScript syntax. - if (subtreeFlags & 2048 /* ContainsDecorators */ - || (name && ts.isIdentifier(name) && name.originalKeywordKind === 97 /* ThisKeyword */)) { + if (subtreeFlags & 2048 /* ContainsDecorators */ || ts.isThisIdentifier(name)) { transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. @@ -21128,7 +21577,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // Currently, we only support generators that were originally async function bodies. - if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152 /* AsyncFunctionBody */) { transformFlags |= 1536 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -21190,7 +21639,7 @@ var ts; // down-level generator. // Currently we do not support transforming any other generator fucntions // down level. - if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152 /* AsyncFunctionBody */) { transformFlags |= 1536 /* AssertGenerator */; } } @@ -21216,7 +21665,7 @@ var ts; // down-level generator. // Currently we do not support transforming any other generator fucntions // down level. - if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152 /* AsyncFunctionBody */) { transformFlags |= 1536 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -21500,6 +21949,677 @@ var ts; return transformFlags & ~excludeFlags; } })(ts || (ts = {})); +/// +/// +var ts; +(function (ts) { + function trace(host, message) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + /* @internal */ + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + /* @internal */ + function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; + } + ts.createResolvedModule = createResolvedModule; + function moduleHasNonRelativeName(moduleName) { + return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); + } + function tryReadTypesSection(packageJsonPath, baseDirectory, state) { + var jsonContent = readJson(packageJsonPath, state.host); + function tryReadFromField(fieldName) { + if (ts.hasProperty(jsonContent, fieldName)) { + var typesFile = jsonContent[fieldName]; + if (typeof typesFile === "string") { + var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); + } + return typesFilePath_1; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); + } + } + } + } + var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); + if (typesFilePath) { + return typesFilePath; + } + // Use the main module for inferring types if no types package specified and the allowJs is set + if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); + } + var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); + return mainFilePath; + } + return undefined; + } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + var typeReferenceExtensions = [".d.ts"]; + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + return currentDirectory !== undefined && getDefaultTypeRoots(currentDirectory, host); + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + /** + * Returns the path to every node_modules/@types directory from some ancestor directory. + * Returns undefined if there are none. + */ + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + } + var typeRoots; + while (true) { + var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + var parent_7 = ts.getDirectoryPath(currentDirectory); + if (parent_7 === currentDirectory) { + break; + } + currentDirectory = parent_7; + } + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + /** + * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. + * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups + * is assumed to be the same as root directory of the project. + */ + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + var traceEnabled = isTraceEnabled(options, host); + var moduleResolutionState = { + compilerOptions: options, + host: host, + skipTsx: true, + traceEnabled: traceEnabled + }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === undefined) { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + } + } + else { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + } + } + } + var failedLookupLocations = []; + // Check primary library paths + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + var primarySearchPaths = typeRoots; + for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { + var typeRoot = primarySearchPaths_1[_i]; + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); + if (resolvedFile_1) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); + } + return { + resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, + failedLookupLocations: failedLookupLocations + }; + } + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + var resolvedFile; + var initialLocationForSecondaryLookup; + if (containingFile) { + initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); + } + if (initialLocationForSecondaryLookup !== undefined) { + // check secondary locations + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*checkOneLevel*/ false); + if (traceEnabled) { + if (resolvedFile) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); + } + else { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + return { + resolvedTypeReferenceDirective: resolvedFile + ? { primary: false, resolvedFileName: resolvedFile } + : undefined, + failedLookupLocations: failedLookupLocations + }; + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + /** + * Given a set of options, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options, host) { + // Use explicit type list from tsconfig.json + if (options.types) { + return options.types; + } + // Walk the primary type lookup locations + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + // tslint:disable-next-line:no-null-keyword + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + // Return just the type directive names + result.push(ts.getBaseFileName(normalized)); + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + /** + * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to + * mitigate differences between design time structure of the project and its runtime counterpart so the same import name + * can be resolved successfully by TypeScript compiler and runtime module loader. + * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will + * fallback to standard resolution routine. + * + * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative + * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will + * be '/a/b/c/d' + * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names + * will be resolved based on the content of the module name. + * Structure of 'paths' compiler options + * 'paths': { + * pattern-1: [...substitutions], + * pattern-2: [...substitutions], + * ... + * pattern-n: [...substitutions] + * } + * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against + * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. + * If pattern contains '*' then to match pattern "*" module name must start with the and end with . + * denotes part of the module name between and . + * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. + * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module + * from the candidate location. + * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every + * substitution in the list and replace '*' with string. If candidate location is not rooted it + * will be converted to absolute using baseUrl. + * For example: + * baseUrl: /a/b/c + * "paths": { + * // match all module names + * "*": [ + * "*", // use matched name as is, + * // will be looked as /a/b/c/ + * + * "folder1/*" // substitution will convert matched name to 'folder1/', + * // since it is not rooted then final candidate location will be /a/b/c/folder1/ + * ], + * // match module names that start with 'components/' + * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', + * // it is rooted so it will be final candidate location + * } + * + * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if + * they were in the same location. For example lets say there are two files + * '/local/src/content/file1.ts' + * '/shared/components/contracts/src/content/protocols/file2.ts' + * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so + * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. + * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all + * root dirs were merged together. + * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. + * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: + * '/local/src/content/protocols/file2' and try to load it - failure. + * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will + * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining + * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. + */ + function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); + } + else { + return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); + } + } + function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + // rootDirs are expected to be absolute + // in case of tsconfig.json this will happen automatically - compiler will expand relative names + // using location of tsconfig.json as base location + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + // first - try to load from a initial location + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + // then try to resolve using remaining entries in rootDirs + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + // skip the initially matched entry + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + // string is for exact match + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { + var subst = _a[_i]; + var path = matchedStar ? subst.replace("*", matchedStar) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + } + return undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); + var isExternalLibraryImport = false; + if (!resolvedFileName) { + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state, /*checkOneLevel*/ false); + isExternalLibraryImport = resolvedFileName !== undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + } + } + if (resolvedFileName && host.realpath) { + var originalFileName = resolvedFileName; + resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); + } + } + return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + /* @internal */ + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + /** + * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary + * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. + */ + function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; + // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" + if (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); + } + } + /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ + function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + return ts.forEach(extensions, function (ext) { + return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); + }); + } + /** Return the file if it exists. */ + function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + failedLookupLocation.push(fileName); + return undefined; + } + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { + var packageJsonPath = pathToPackageJson(candidate); + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); + if (typesFile) { + var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); + // A package.json "typings" may specify an exact filename, or may choose to omit an extension. + var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || + tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); + if (result) { + return result; + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); + } + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results + failedLookupLocation.push(packageJsonPath); + } + return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); + } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } + function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); + var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + } + /* @internal */ + function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, /*typesOnly*/ false); + } + ts.loadModuleFromNodeModules = loadModuleFromNodeModules; + function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, /*checkOneLevel*/ false, /*typesOnly*/ true); + } + function loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, typesOnly) { + directory = ts.normalizeSlashes(directory); + while (true) { + var baseName = ts.getBaseFileName(directory); + if (baseName !== "node_modules") { + var packageResult = void 0; + if (!typesOnly) { + // Try to load source from the package + packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); + if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { + // Always prefer a TypeScript (.ts, .tsx, .d.ts) file shipped with the package + return packageResult; + } + } + // Else prefer a types package over non-TypeScript results (e.g. JavaScript files) + var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); + if (typesResult || packageResult) { + return typesResult || packageResult; + } + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory || checkOneLevel) { + break; + } + directory = parentPath; + } + return undefined; + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; + var failedLookupLocations = []; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ false, failedLookupLocations); + } + var referencedSourceFile; + if (moduleHasNonRelativeName(moduleName)) { + referencedSourceFile = referencedSourceFile = loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) || + // If we didn't find the file normally, look it up in @types. + loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + } + return referencedSourceFile + ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } + : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + } + ts.classicNameResolver = classicNameResolver; + /** Climb up parent directories looking for a module. */ + function loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) { + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + if (referencedSourceFile) { + return referencedSourceFile; + } + var parentPath = ts.getDirectoryPath(containingDirectory); + if (parentPath === containingDirectory) { + return undefined; + } + containingDirectory = parentPath; + } + } +})(ts || (ts = {})); +/// /// /* @internal */ var ts; @@ -21607,6 +22727,7 @@ var ts; var unknownSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "unknown"); var resolvingSymbol = createSymbol(67108864 /* Transient */, "__resolving__"); var anyType = createIntrinsicType(1 /* Any */, "any"); + var autoType = createIntrinsicType(1 /* Any */, "any"); var unknownType = createIntrinsicType(1 /* Any */, "unknown"); var undefinedType = createIntrinsicType(2048 /* Undefined */, "undefined"); var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 /* Undefined */ | 33554432 /* ContainsWideningType */, "undefined"); @@ -22350,7 +23471,7 @@ var ts; if (result && isInExternalModule && (meaning & 107455 /* Value */) === 107455 /* Value */) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 228 /* NamespaceExportDeclaration */) { - error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name); } } } @@ -22833,6 +23954,8 @@ var ts; } function getExportsForModule(moduleSymbol) { var visitedSymbols = []; + // A module defined by an 'export=' consists on one export that needs to be resolved + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || moduleSymbol.exports; // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. @@ -23407,9 +24530,9 @@ var ts; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. - var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent_7) { - walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + var parent_8 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_8) { + walkSymbol(parent_8, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); } } if (accessibleSymbolChain) { @@ -23453,7 +24576,7 @@ var ts; ? "any" : type.intrinsicName); } - else if (type.flags & 268435456 /* ThisType */) { + else if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } @@ -23471,9 +24594,14 @@ var ts; // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); } - else if (!(flags & 512 /* InTypeAlias */) && type.flags & (2097152 /* Anonymous */ | 1572864 /* UnionOrIntersection */) && type.aliasSymbol && + else if (!(flags & 512 /* InTypeAlias */) && ((type.flags & 2097152 /* Anonymous */ && !type.target) || type.flags & 1572864 /* UnionOrIntersection */) && type.aliasSymbol && isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { - // Only write out inferred type with its corresponding type-alias if type-alias is visible + // We emit inferred type as type-alias at the current localtion if all the following is true + // the input type is has alias symbol that is accessible + // the input type is a union, intersection or anonymous type that is fully instantiated (if not we want to keep dive into) + // e.g.: export type Bar = () => [X, Y]; + // export type Foo = Bar; + // export const y = (x: Foo) => 1 // we want to emit as ...x: () => [any, string]) var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); } @@ -23549,14 +24677,14 @@ var ts; while (i < length_1) { // Find group of type arguments for type parameters with the same declaring container. var start = i; - var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_9 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_9); // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_8, typeArguments, start, i, flags); + writeSymbolTypeReference(parent_9, typeArguments, start, i, flags); writePunctuation(writer, 21 /* DotToken */); } } @@ -23960,14 +25088,14 @@ var ts; if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_9 = getDeclarationContainer(node); + var parent_10 = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 229 /* ImportEqualsDeclaration */ && parent_9.kind !== 256 /* SourceFile */ && ts.isInAmbientContext(parent_9))) { - return isGlobalSourceFile(parent_9); + !(node.kind !== 229 /* ImportEqualsDeclaration */ && parent_10.kind !== 256 /* SourceFile */ && ts.isInAmbientContext(parent_10))) { + return isGlobalSourceFile(parent_10); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible - return isDeclarationVisible(parent_9); + return isDeclarationVisible(parent_10); case 145 /* PropertyDeclaration */: case 144 /* PropertySignature */: case 149 /* GetAccessor */: @@ -24274,6 +25402,10 @@ var ts; } return undefined; } + function isAutoVariableInitializer(initializer) { + var expr = initializer && ts.skipParentheses(initializer); + return !expr || expr.kind === 93 /* NullKeyword */ || expr.kind === 69 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; + } function addOptionality(type, optional) { return strictNullChecks && optional ? includeFalsyTypes(type, 2048 /* Undefined */) : type; } @@ -24306,6 +25438,13 @@ var ts; if (declaration.type) { return addOptionality(getTypeFromTypeNode(declaration.type), /*optional*/ declaration.questionToken && includeOptionality); } + // Use control flow type inference for non-ambient, non-exported var or let variables with no initializer + // or a 'null' or 'undefined' initializer. + if (declaration.kind === 218 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && + !ts.isInAmbientContext(declaration) && isAutoVariableInitializer(declaration.initializer)) { + return autoType; + } if (declaration.kind === 142 /* Parameter */) { var func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present @@ -24389,7 +25528,7 @@ var ts; result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 536870912 /* ObjectLiteralPatternWithComputedProperties */; + result.isObjectLiteralPatternWithComputedProperties = true; } return result; } @@ -24935,7 +26074,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */ | 268435456 /* ThisType */); + type.thisType = createType(16384 /* TypeParameter */); + type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -25509,7 +26649,7 @@ var ts; var current = _a[_i]; for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { var prop = _c[_b]; - getPropertyOfUnionOrIntersectionType(type, prop.name); + getUnionOrIntersectionProperty(type, prop.name); } // The properties of a union type are those that are present in all constituent types, so // we only need to check the properties of the first type @@ -25517,7 +26657,19 @@ var ts; break; } } - return type.resolvedProperties ? symbolsToArray(type.resolvedProperties) : emptyArray; + var props = type.resolvedProperties; + if (props) { + var result = []; + for (var key in props) { + var prop = props[key]; + // We need to filter out partial properties in union types + if (!(prop.flags & 268435456 /* SyntheticProperty */ && prop.isPartial)) { + result.push(prop); + } + } + return result; + } + return emptyArray; } function getPropertiesOfType(type) { type = getApparentType(type); @@ -25566,6 +26718,7 @@ var ts; // Flags we want to propagate to the result if they exist in all source symbols var commonFlags = (containingType.flags & 1048576 /* Intersection */) ? 536870912 /* Optional */ : 0 /* None */; var isReadonly = false; + var isPartial = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); @@ -25584,21 +26737,20 @@ var ts; } } else if (containingType.flags & 524288 /* Union */) { - // A union type requires the property to be present in all constituent types - return undefined; + isPartial = true; } } } if (!props) { return undefined; } - if (props.length === 1) { + if (props.length === 1 && !isPartial) { return props[0]; } var propTypes = []; var declarations = []; var commonType = undefined; - var hasCommonType = true; + var hasNonUniformType = false; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { @@ -25609,22 +26761,25 @@ var ts; commonType = type; } else if (type !== commonType) { - hasCommonType = false; + hasNonUniformType = true; } - propTypes.push(getTypeOfSymbol(prop)); + propTypes.push(type); } - var result = createSymbol(4 /* Property */ | - 67108864 /* Transient */ | - 268435456 /* SyntheticProperty */ | - commonFlags, name); + var result = createSymbol(4 /* Property */ | 67108864 /* Transient */ | 268435456 /* SyntheticProperty */ | commonFlags, name); result.containingType = containingType; - result.hasCommonType = hasCommonType; + result.hasNonUniformType = hasNonUniformType; + result.isPartial = isPartial; result.declarations = declarations; result.isReadonly = isReadonly; result.type = containingType.flags & 524288 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } - function getPropertyOfUnionOrIntersectionType(type, name) { + // Return the symbol for a given property in a union or intersection type, or undefined if the property + // does not exist in any constituent type. Note that the returned property may only be present in some + // constituents, in which case the isPartial flag is set when the containing type is union type. We need + // these partial properties when identifying discriminant properties, but otherwise they are filtered out + // and do not appear to be present in the union type. + function getUnionOrIntersectionProperty(type, name) { var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); var property = properties[name]; if (!property) { @@ -25635,6 +26790,11 @@ var ts; } return property; } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + // We need to filter out partial properties in union types + return property && !(property.flags & 268435456 /* SyntheticProperty */ && property.isPartial) ? property : undefined; + } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from @@ -26040,7 +27200,7 @@ var ts; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 268435456 /* ThisType */) && type.flags & 16384 /* TypeParameter */ && !ts.contains(checked, type)) { + while (type && type.flags & 16384 /* TypeParameter */ && !(type.isThisType) && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -26365,7 +27525,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */ | 268435456 /* ThisType */); + type.thisType = createType(16384 /* TypeParameter */); + type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; type.declaredCallSignatures = emptyArray; @@ -26466,7 +27627,24 @@ var ts; } return false; } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 256 /* EnumLiteral */) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 256 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } var i = types.length; while (i > 0) { i--; @@ -27553,7 +28731,8 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 536870912 /* ObjectLiteralPatternWithComputedProperties */) && maybeTypeOfKind(target, 2588672 /* ObjectType */)) { + if (maybeTypeOfKind(target, 2588672 /* ObjectType */) && + (!(target.flags & 2588672 /* ObjectType */) || !target.isObjectLiteralPatternWithComputedProperties)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -28917,21 +30096,10 @@ var ts; } function isDiscriminantProperty(type, name) { if (type && type.flags & 524288 /* Union */) { - var prop = getPropertyOfType(type, name); - if (!prop) { - // The type may be a union that includes nullable or primitive types. If filtering - // those out produces a different type, get the property from that type instead. - // Effectively, we're checking if this *could* be a discriminant property once nullable - // and primitive types are removed by other type guards. - var filteredType = getTypeWithFacts(type, 4194304 /* Discriminatable */); - if (filteredType !== type && filteredType.flags & 524288 /* Union */) { - prop = getPropertyOfType(filteredType, name); - } - } + var prop = getUnionOrIntersectionProperty(type, name); if (prop && prop.flags & 268435456 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !prop.hasCommonType && - isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = prop.hasNonUniformType && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -29218,6 +30386,26 @@ var ts; } return f(type) ? type : neverType; } + function mapType(type, f) { + return type.flags & 524288 /* Union */ ? getUnionType(ts.map(type.types, f)) : f(type); + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + // Return a new type in which occurrences of the string and number primitive types in + // typeWithPrimitives have been replaced with occurrences of string literals and numeric + // literals in typeWithLiterals, respectively. + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32 /* StringLiteral */) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64 /* NumberLiteral */)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 2 /* String */ ? extractTypesOfKind(typeWithLiterals, 2 /* String */ | 32 /* StringLiteral */) : + t.flags & 4 /* Number */ ? extractTypesOfKind(typeWithLiterals, 4 /* Number */ | 64 /* NumberLiteral */) : + t; + }); + } + return typeWithPrimitives; + } function isIncomplete(flowType) { return flowType.flags === 0; } @@ -29232,7 +30420,9 @@ var ts; if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943 /* Narrowable */)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048 /* Undefined */); + var initialType = assumeInitialized ? declaredType : + declaredType === autoType ? undefinedType : + includeFalsyTypes(declaredType, 2048 /* Undefined */); var visitedFlowStart = visitedFlowCount; var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; @@ -29304,10 +30494,13 @@ var ts; // Assignments only narrow the computed type if the declared type is a union type. Thus, we // only need to evaluate the assigned type if the declared type is a union type. if (isMatchingReference(reference, node)) { - var isIncrementOrDecrement = node.parent.kind === 185 /* PrefixUnaryExpression */ || node.parent.kind === 186 /* PostfixUnaryExpression */; - return declaredType.flags & 524288 /* Union */ && !isIncrementOrDecrement ? - getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : - declaredType; + if (node.parent.kind === 185 /* PrefixUnaryExpression */ || node.parent.kind === 186 /* PostfixUnaryExpression */) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + return declaredType === autoType ? getBaseTypeOfLiteralType(getInitialOrAssignedType(node)) : + declaredType.flags & 524288 /* Union */ ? getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : + declaredType; } // We didn't have a direct match. However, if the reference is a dotted name, this // may be an assignment to a left hand part of the reference. For example, for a @@ -29531,12 +30724,12 @@ var ts; assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; return getTypeWithFacts(type, facts); } - if (type.flags & 2589191 /* NotUnionOrUnit */) { + if (type.flags & 2589185 /* NotUnionOrUnit */) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 /* Never */ ? type : narrowedType; + return narrowedType.flags & 8192 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -29581,7 +30774,8 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 /* Never */ ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); + var caseType = discriminantType.flags & 8192 /* Never */ ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -29728,7 +30922,7 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpression(location) && !ts.isAssignmentTarget(location)) { + if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { var type = checkExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; @@ -29877,20 +31071,32 @@ var ts; // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. while (flowContainer !== declarationContainer && - (flowContainer.kind === 179 /* FunctionExpression */ || flowContainer.kind === 180 /* ArrowFunction */) && + (flowContainer.kind === 179 /* FunctionExpression */ || + flowContainer.kind === 180 /* ArrowFunction */ || + ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - var assumeInitialized = !strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isParameter || - isOuterVariable || ts.isInAmbientContext(declaration); + var assumeInitialized = isParameter || isOuterVariable || + type !== autoType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0) || + ts.isInAmbientContext(declaration); var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the // control flow based type does include undefined. - if (!assumeInitialized && !(getFalsyFlags(type) & 2048 /* Undefined */) && getFalsyFlags(flowType) & 2048 /* Undefined */) { + if (type === autoType) { + if (flowType === autoType) { + if (compilerOptions.noImplicitAny) { + error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol)); + error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(anyType)); + } + return anyType; + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 2048 /* Undefined */) && getFalsyFlags(flowType) & 2048 /* Undefined */) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; @@ -29988,7 +31194,7 @@ var ts; } } function findFirstSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return n; } else if (ts.isFunctionLike(n)) { @@ -30081,7 +31287,7 @@ var ts; captureLexicalThis(node, container); } if (ts.isFunctionLike(container) && - (!isInParameterInitializerBeforeContainingFunction(node) || getFunctionLikeThisParameter(container))) { + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. Check if it's the RHS // of a x.prototype.y = function [name]() { .... } @@ -30141,8 +31347,8 @@ var ts; var isCallExpression = node.parent.kind === 174 /* CallExpression */ && node.parent.expression === node; var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var needToCaptureLexicalThis = false; + // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - // adjust the container reference in case if super is used inside arrow functions with arbitrary deep nesting while (container && container.kind === 180 /* ArrowFunction */) { container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES6 */; @@ -30954,7 +32160,8 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 536870912 /* ObjectLiteralPatternWithComputedProperties */)) { + else if (contextualTypeHasPattern && + !(contextualType.flags & 2588672 /* ObjectType */ && contextualType.isObjectLiteralPatternWithComputedProperties)) { // If object literal is contextually typed by the implied type of a binding pattern, and if the // binding pattern specifies a default value for the property, make the property optional. var impliedProp = getPropertyOfType(contextualType, member.name); @@ -31014,7 +32221,10 @@ var ts; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216 /* FreshLiteral */; - result.flags |= 8388608 /* ObjectLiteral */ | 67108864 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 234881024 /* PropagatingFlags */) | (patternWithComputedProperties ? 536870912 /* ObjectLiteralPatternWithComputedProperties */ : 0); + result.flags |= 8388608 /* ObjectLiteral */ | 67108864 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 234881024 /* PropagatingFlags */); + if (patternWithComputedProperties) { + result.isObjectLiteralPatternWithComputedProperties = true; + } if (inDestructuringPattern) { result.pattern = node; } @@ -31523,7 +32733,7 @@ var ts; return true; } // An instance property must be accessed through an instance of the enclosing class - if (type.flags & 268435456 /* ThisType */) { + if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { // get the original type -- represented as the type constraint of the 'this' type type = getConstraintOfTypeParameter(type); } @@ -31567,7 +32777,7 @@ var ts; var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 268435456 /* ThisType */ ? apparentType : type); + reportNonexistentProperty(right, type.flags & 16384 /* TypeParameter */ && type.isThisType ? apparentType : type); } return unknownType; } @@ -31848,13 +33058,13 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_10 = signature.declaration && signature.declaration.parent; + var parent_11 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_10 === lastParent) { + if (lastParent && parent_11 === lastParent) { index++; } else { - lastParent = parent_10; + lastParent = parent_11; index = cutoffIndex; } } @@ -31862,7 +33072,7 @@ var ts; // current declaration belongs to a different symbol // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex index = cutoffIndex = result.length; - lastParent = parent_10; + lastParent = parent_11; } lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless @@ -33121,7 +34331,9 @@ var ts; if (!contextualSignature) { reportErrorsFromWidening(func, type); } - if (isUnitType(type) && !(contextualSignature && isLiteralContextualType(getReturnTypeOfSignature(contextualSignature)))) { + if (isUnitType(type) && + !(contextualSignature && + isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { type = getWidenedLiteralType(type); } var widenedType = getWidenedType(type); @@ -33305,7 +34517,7 @@ var ts; } } } - if (produceDiagnostics && node.kind !== 147 /* MethodDeclaration */ && node.kind !== 146 /* MethodSignature */) { + if (produceDiagnostics && node.kind !== 147 /* MethodDeclaration */) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } @@ -34388,9 +35600,9 @@ var ts; case 156 /* FunctionType */: case 147 /* MethodDeclaration */: case 146 /* MethodSignature */: - var parent_11 = node.parent; - if (node === parent_11.type) { - return parent_11; + var parent_12 = node.parent; + if (node === parent_12.type) { + return parent_12; } } } @@ -34628,7 +35840,7 @@ var ts; return n.name && containsSuperCall(n.name); } function containsSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return true; } else if (ts.isFunctionLike(n)) { @@ -34657,6 +35869,7 @@ var ts; // constructors of derived classes must contain at least one super call somewhere in their function body. var containingClassDecl = node.parent; if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); if (superCall) { @@ -34677,7 +35890,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 202 /* ExpressionStatement */ && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 202 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -35607,7 +36820,7 @@ var ts; var parameter = local.valueDeclaration; if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && - !parameterIsThisKeyword(parameter) && + !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(parameter)) { error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } @@ -35622,9 +36835,6 @@ var ts; } } } - function parameterIsThisKeyword(parameter) { - return parameter.name && parameter.name.originalKeywordKind === 97 /* ThisKeyword */; - } function parameterNameStartsWithUnderscore(parameter) { return parameter.name && parameter.name.kind === 69 /* Identifier */ && parameter.name.text.charCodeAt(0) === 95 /* _ */; } @@ -35772,6 +36982,10 @@ var ts; } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + // No need to check for require or exports for ES6 modules and later + if (modulekind >= ts.ModuleKind.ES6) { + return; + } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } @@ -35926,6 +37140,9 @@ var ts; } } } + function convertAutoToAny(type) { + return type === autoType ? anyType : type; + } // Check variable, parameter, or property declaration function checkVariableLikeDeclaration(node) { checkDecorators(node); @@ -35946,12 +37163,12 @@ var ts; checkComputedPropertyName(node.propertyName); } // check private/protected variable access - var parent_12 = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent_12); + var parent_13 = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent_13); var name_21 = node.propertyName || node.name; var property = getPropertyOfType(parentType, getTextOfPropertyName(name_21)); - if (parent_12.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property); + if (parent_13.initializer && property && getParentOfSymbol(property)) { + checkClassPropertyAccess(parent_13, parent_13.initializer, parentType, property); } } // For a binding pattern, check contained binding elements @@ -35973,7 +37190,7 @@ var ts; return; } var symbol = getSymbolOfNode(node); - var type = getTypeOfVariableOrParameterOrProperty(symbol); + var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer // Don't validate for-in initializer as it is already an error @@ -35985,7 +37202,7 @@ var ts; else { // Node is a secondary declaration, check that type is identical to primary declaration and check that // initializer is consistent with type associated with the node - var declarationType = getWidenedTypeForVariableLikeDeclaration(node); + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); } @@ -36480,7 +37697,12 @@ var ts; } } checkExpression(node.expression); - error(node.expression, ts.Diagnostics.All_symbols_within_a_with_block_will_be_resolved_to_any); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } } function checkSwitchStatement(node) { // Grammar checking @@ -37288,9 +38510,11 @@ var ts; grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (ts.isIdentifier(node.name)) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); // The following checks only apply on a non-ambient instantiated module declaration. @@ -37568,9 +38792,11 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 256 /* SourceFile */ && node.parent.kind !== 226 /* ModuleBlock */ && node.parent.kind !== 225 /* ModuleDeclaration */) { - return grammarErrorOnFirstToken(node, errorMessage); + var isInAppropriateContext = node.parent.kind === 256 /* SourceFile */ || node.parent.kind === 226 /* ModuleBlock */ || node.parent.kind === 225 /* ModuleDeclaration */; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); } + return !isInAppropriateContext; } function checkExportSpecifier(node) { checkAliasSymbol(node); @@ -37668,7 +38894,8 @@ var ts; links.exportsChecked = true; } function isNotOverload(declaration) { - return declaration.kind !== 220 /* FunctionDeclaration */ || !!declaration.body; + return (declaration.kind !== 220 /* FunctionDeclaration */ && declaration.kind !== 147 /* MethodDeclaration */) || + !!declaration.body; } } function checkSourceElement(node) { @@ -38202,6 +39429,9 @@ var ts; node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } + if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) { + return resolveExternalModuleName(node, node); + } // Fall through case 8 /* NumericLiteral */: // index access @@ -38726,9 +39956,9 @@ var ts; if (startInDeclarationContainer) { // When resolving the name of a declaration as a value, we need to start resolution // at a point outside of the declaration. - var parent_13 = reference.parent; - if (ts.isDeclaration(parent_13) && reference === parent_13.name) { - location = getDeclarationContainer(parent_13); + var parent_14 = reference.parent; + if (ts.isDeclaration(parent_14) && reference === parent_14.name) { + location = getDeclarationContainer(parent_14); } } return resolveName(location, reference.text, 107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); @@ -38852,9 +40082,9 @@ var ts; // external modules cannot define or contribute to type declaration files var current = symbol; while (true) { - var parent_14 = getParentOfSymbol(current); - if (parent_14) { - current = parent_14; + var parent_15 = getParentOfSymbol(current); + if (parent_15) { + current = parent_15; } else { break; @@ -39437,8 +40667,8 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_2 = args; _i < args_2.length; _i++) { - var arg = args_2[_i]; + for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { + var arg = args_4[_i]; if (arg.kind === 193 /* OmittedExpression */) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } @@ -39550,8 +40780,7 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; var name_24 = prop.name; - if (prop.kind === 193 /* OmittedExpression */ || - name_24.kind === 140 /* ComputedPropertyName */) { + if (name_24.kind === 140 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name_24); } @@ -39731,17 +40960,8 @@ var ts; return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 149 /* GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 149 /* GetAccessor */ ? 1 : 2) && - accessor.parameters[0].name.kind === 69 /* Identifier */ && - accessor.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */) { - return accessor.parameters[0]; - } - } - function getFunctionLikeThisParameter(func) { - if (func.parameters.length && - func.parameters[0].name.kind === 69 /* Identifier */ && - func.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */) { - return func.parameters[0]; + if (accessor.parameters.length === (accessor.kind === 149 /* GetAccessor */ ? 1 : 2)) { + return ts.getThisParameter(accessor); } } function checkGrammarForNonSymbolComputedProperty(node, message) { @@ -40673,7 +41893,7 @@ var ts; case 175 /* NewExpression */: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); case 176 /* TaggedTemplateExpression */: - return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplate)); + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); case 178 /* ParenthesizedExpression */: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); case 179 /* FunctionExpression */: @@ -40697,7 +41917,7 @@ var ts; case 188 /* ConditionalExpression */: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 189 /* TemplateExpression */: - return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateLiteralFragment), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); case 190 /* YieldExpression */: return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); case 191 /* SpreadElementExpression */: @@ -40708,7 +41928,7 @@ var ts; return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); // Misc case 197 /* TemplateSpan */: - return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateLiteralFragment)); + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Element case 199 /* Block */: return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); @@ -41055,7 +42275,7 @@ var ts; var expression = ts.createAssignment(name, value, location); // NOTE: this completely disables source maps, but aligns with the behavior of // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(expression, 2048 /* NoNestedSourceMaps */); + ts.setEmitFlags(expression, 2048 /* NoNestedSourceMaps */); ts.aggregateTransformFlags(expression); expressions.push(expression); } @@ -41081,7 +42301,7 @@ var ts; var declaration = ts.createVariableDeclaration(name, /*type*/ undefined, value, location); // NOTE: this completely disables source maps, but aligns with the behavior of // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); + ts.setEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); ts.aggregateTransformFlags(declaration); declarations.push(declaration); } @@ -41114,7 +42334,7 @@ var ts; declaration.original = original; // NOTE: this completely disables source maps, but aligns with the behavior of // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); + ts.setEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); declarations.push(declaration); ts.aggregateTransformFlags(declaration); } @@ -41164,7 +42384,7 @@ var ts; expression.original = original; // NOTE: this completely disables source maps, but aligns with the behavior of // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(expression, 2048 /* NoNestedSourceMaps */); + ts.setEmitFlags(expression, 2048 /* NoNestedSourceMaps */); pendingAssignments.push(expression); return expression; } @@ -41210,8 +42430,8 @@ var ts; } else { var name_26 = ts.getMutableClone(target); - context.setSourceMapRange(name_26, target); - context.setCommentRange(name_26, target); + ts.setSourceMapRange(name_26, target); + ts.setCommentRange(name_26, target); emitAssignment(name_26, value, location, /*original*/ undefined); } } @@ -41380,7 +42600,7 @@ var ts; TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers"; })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {})); function transformTypeScript(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, setCommentRange = context.setCommentRange, setSourceMapRange = context.setSourceMapRange, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -41391,11 +42611,15 @@ var ts; // Set new transformation hooks. context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; + // Enable substitution for property/element access to emit const enum values. + context.enableSubstitution(172 /* PropertyAccessExpression */); + context.enableSubstitution(173 /* ElementAccessExpression */); // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; var currentScope; + var currentScopeFirstDeclarationsOfName; var currentSourceFileExternalHelpersModuleName; /** * Keeps track of whether expression substitution has been enabled for specific edge cases. @@ -41424,6 +42648,9 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitNode(node, visitor, ts.isSourceFile); } /** @@ -41434,10 +42661,14 @@ var ts; function saveStateAndInvoke(node, f) { // Save state var savedCurrentScope = currentScope; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; // Handle state changes before visiting a node. onBeforeVisitNode(node); var visited = f(node); // Restore state + if (currentScope !== savedCurrentScope) { + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + } currentScope = savedCurrentScope; return visited; } @@ -41702,11 +42933,23 @@ var ts; case 226 /* ModuleBlock */: case 199 /* Block */: currentScope = node; + currentScopeFirstDeclarationsOfName = undefined; + break; + case 221 /* ClassDeclaration */: + case 220 /* FunctionDeclaration */: + if (ts.hasModifier(node, 2 /* Ambient */)) { + break; + } + recordEmittedDeclarationInScope(node); break; } } function visitSourceFile(node) { currentSourceFile = node; + // ensure "use strict" is emitted in all scenarios in alwaysStrict mode + if (compilerOptions.alwaysStrict) { + node = ts.ensureUseStrict(node); + } // If the source file requires any helpers and is an external module, and // the importHelpers compiler option is enabled, emit a synthesized import // statement for the helpers library. @@ -41733,7 +42976,7 @@ var ts; else { node = ts.visitEachChild(node, visitor, context); } - setNodeEmitFlags(node, 1 /* EmitEmitHelpers */ | node.emitFlags); + ts.setEmitFlags(node, 1 /* EmitEmitHelpers */ | ts.getEmitFlags(node)); return node; } /** @@ -41792,7 +43035,7 @@ var ts; // To better align with the old emitter, we should not emit a trailing source map // entry if the class has static properties. if (staticProperties.length > 0) { - setNodeEmitFlags(classDeclaration, 1024 /* NoTrailingSourceMap */ | getNodeEmitFlags(classDeclaration)); + ts.setEmitFlags(classDeclaration, 1024 /* NoTrailingSourceMap */ | ts.getEmitFlags(classDeclaration)); } statements.push(classDeclaration); } @@ -41951,7 +43194,7 @@ var ts; /*type*/ undefined, classExpression) ]), /*location*/ location); - setCommentRange(transformedClassExpression, node); + ts.setCommentRange(transformedClassExpression, node); statements.push(ts.setOriginalNode( /*node*/ transformedClassExpression, /*original*/ node)); @@ -41996,7 +43239,7 @@ var ts; } // To preserve the behavior of the old emitter, we explicitly indent // the body of a class with static initializers. - setNodeEmitFlags(classExpression, 524288 /* Indented */ | getNodeEmitFlags(classExpression)); + ts.setEmitFlags(classExpression, 524288 /* Indented */ | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); ts.addRange(expressions, generateInitializedPropertyExpressions(node, staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); @@ -42151,7 +43394,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 202 /* ExpressionStatement */ && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 202 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -42185,9 +43428,9 @@ var ts; ts.Debug.assert(ts.isIdentifier(node.name)); var name = node.name; var propertyName = ts.getMutableClone(name); - setNodeEmitFlags(propertyName, 49152 /* NoComments */ | 1536 /* NoSourceMap */); + ts.setEmitFlags(propertyName, 49152 /* NoComments */ | 1536 /* NoSourceMap */); var localName = ts.getMutableClone(name); - setNodeEmitFlags(localName, 49152 /* NoComments */); + ts.setEmitFlags(localName, 49152 /* NoComments */); return ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), propertyName, /*location*/ node.name), localName), /*location*/ ts.moveRangePos(node, -1))); @@ -42239,8 +43482,8 @@ var ts; for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var property = properties_7[_i]; var statement = ts.createStatement(transformInitializedProperty(node, property, receiver)); - setSourceMapRange(statement, ts.moveRangePastModifiers(property)); - setCommentRange(statement, property); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); statements.push(statement); } } @@ -42257,8 +43500,8 @@ var ts; var property = properties_8[_i]; var expression = transformInitializedProperty(node, property, receiver); expression.startsOnNewLine = true; - setSourceMapRange(expression, ts.moveRangePastModifiers(property)); - setCommentRange(expression, property); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + ts.setCommentRange(expression, property); expressions.push(expression); } return expressions; @@ -42524,7 +43767,7 @@ var ts; : ts.createNull() : undefined; var helper = ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); - setNodeEmitFlags(helper, 49152 /* NoComments */); + ts.setEmitFlags(helper, 49152 /* NoComments */); return helper; } /** @@ -42562,12 +43805,12 @@ var ts; if (decoratedClassAlias) { var expression = ts.createAssignment(decoratedClassAlias, ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node))); var result = ts.createAssignment(getDeclarationName(node), expression, ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152 /* NoComments */); + ts.setEmitFlags(result, 49152 /* NoComments */); return result; } else { var result = ts.createAssignment(getDeclarationName(node), ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node)), ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152 /* NoComments */); + ts.setEmitFlags(result, 49152 /* NoComments */); return result; } } @@ -42593,7 +43836,7 @@ var ts; var decorator = decorators_1[_i]; var helper = ts.createParamHelper(currentSourceFileExternalHelpersModuleName, transformDecorator(decorator), parameterOffset, /*location*/ decorator.expression); - setNodeEmitFlags(helper, 49152 /* NoComments */); + ts.setEmitFlags(helper, 49152 /* NoComments */); expressions.push(helper); } } @@ -42824,10 +44067,38 @@ var ts; : ts.createIdentifier("Symbol"); case 155 /* TypeReference */: return serializeTypeReferenceNode(node); + case 163 /* IntersectionType */: + case 162 /* UnionType */: + { + var unionOrIntersection = node; + var serializedUnion = void 0; + for (var _i = 0, _a = unionOrIntersection.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var serializedIndividual = serializeTypeNode(typeNode); + // Non identifier + if (serializedIndividual.kind !== 69 /* Identifier */) { + serializedUnion = undefined; + break; + } + // One of the individual is global object, return immediately + if (serializedIndividual.text === "Object") { + return serializedIndividual; + } + // Different types + if (serializedUnion && serializedUnion.text !== serializedIndividual.text) { + serializedUnion = undefined; + break; + } + serializedUnion = serializedIndividual; + } + // If we were able to find common type + if (serializedUnion) { + return serializedUnion; + } + } + // Fallthrough case 158 /* TypeQuery */: case 159 /* TypeLiteral */: - case 162 /* UnionType */: - case 163 /* IntersectionType */: case 117 /* AnyKeyword */: case 165 /* ThisType */: break; @@ -43027,8 +44298,8 @@ var ts; /*location*/ node); // While we emit the source map for the node after skipping decorators and modifiers, // we need to emit the comments for the original range. - setCommentRange(method, node); - setSourceMapRange(method, ts.moveRangePastDecorators(node)); + ts.setCommentRange(method, node); + ts.setSourceMapRange(method, ts.moveRangePastDecorators(node)); ts.setOriginalNode(method, node); return method; } @@ -43060,8 +44331,8 @@ var ts; /*location*/ node); // While we emit the source map for the node after skipping decorators and modifiers, // we need to emit the comments for the original range. - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setCommentRange(accessor, node); + ts.setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); ts.setOriginalNode(accessor, node); return accessor; } @@ -43083,8 +44354,8 @@ var ts; /*location*/ node); // While we emit the source map for the node after skipping decorators and modifiers, // we need to emit the comments for the original range. - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setCommentRange(accessor, node); + ts.setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); ts.setOriginalNode(accessor, node); return accessor; } @@ -43220,11 +44491,11 @@ var ts; if (languageVersion >= 2 /* ES6 */) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 8 /* EmitAdvancedSuperHelper */); + ts.setEmitFlags(block, 8 /* EmitAdvancedSuperHelper */); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 4 /* EmitSuperHelper */); + ts.setEmitFlags(block, 4 /* EmitSuperHelper */); } } return block; @@ -43244,7 +44515,7 @@ var ts; * @param node The parameter declaration node. */ function visitParameter(node) { - if (node.name && ts.isIdentifier(node.name) && node.name.originalKeywordKind === 97 /* ThisKeyword */) { + if (ts.parameterIsThisKeyword(node)) { return undefined; } var parameter = ts.createParameterDeclaration( @@ -43256,9 +44527,9 @@ var ts; // While we emit the source map for the node after skipping decorators and modifiers, // we need to emit the comments for the original range. ts.setOriginalNode(parameter, node); - setCommentRange(parameter, node); - setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - setNodeEmitFlags(parameter.name, 1024 /* NoTrailingSourceMap */); + ts.setCommentRange(parameter, node); + ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(parameter.name, 1024 /* NoTrailingSourceMap */); return parameter; } /** @@ -43351,8 +44622,9 @@ var ts; || compilerOptions.isolatedModules; } function shouldEmitVarForEnumDeclaration(node) { - return !ts.hasModifier(node, 1 /* Export */) - || (isES6ExportedDeclaration(node) && ts.isFirstDeclarationOfKind(node, node.kind)); + return isFirstEmittedDeclarationInScope(node) + && (!ts.hasModifier(node, 1 /* Export */) + || isES6ExportedDeclaration(node)); } /* * Adds a trailing VariableStatement for an enum or module declaration. @@ -43361,7 +44633,7 @@ var ts; var statement = ts.createVariableStatement( /*modifiers*/ undefined, [ts.createVariableDeclaration(getDeclarationName(node), /*type*/ undefined, getExportName(node))]); - setSourceMapRange(statement, node); + ts.setSourceMapRange(statement, node); statements.push(statement); } /** @@ -43382,6 +44654,7 @@ var ts; // If needed, we should emit a variable declaration for the enum. If we emit // a leading variable declaration, we should not emit leading comments for the // enum body. + recordEmittedDeclarationInScope(node); if (shouldEmitVarForEnumDeclaration(node)) { addVarForEnumOrModuleDeclaration(statements, node); // We should still emit the comments if we are emitting a system module. @@ -43407,7 +44680,7 @@ var ts; /*typeArguments*/ undefined, [ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()))]), /*location*/ node); ts.setOriginalNode(enumStatement, node); - setNodeEmitFlags(enumStatement, emitFlags); + ts.setEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); if (isNamespaceExport(node)) { addVarForEnumExportedFromNamespace(statements, node); @@ -43473,18 +44746,43 @@ var ts; function shouldEmitModuleDeclaration(node) { return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } - function isModuleMergedWithES6Class(node) { - return languageVersion === 2 /* ES6 */ - && ts.isMergedWithClass(node); - } function isES6ExportedDeclaration(node) { return isExternalModuleExport(node) && moduleKind === ts.ModuleKind.ES6; } + /** + * Records that a declaration was emitted in the current scope, if it was the first + * declaration for the provided symbol. + * + * NOTE: if there is ever a transformation above this one, we may not be able to rely + * on symbol names. + */ + function recordEmittedDeclarationInScope(node) { + var name = node.symbol && node.symbol.name; + if (name) { + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createMap(); + } + if (!(name in currentScopeFirstDeclarationsOfName)) { + currentScopeFirstDeclarationsOfName[name] = node; + } + } + } + /** + * Determines whether a declaration is the first declaration with the same name emitted + * in the current scope. + */ + function isFirstEmittedDeclarationInScope(node) { + if (currentScopeFirstDeclarationsOfName) { + var name_28 = node.symbol && node.symbol.name; + if (name_28) { + return currentScopeFirstDeclarationsOfName[name_28] === node; + } + } + return false; + } function shouldEmitVarForModuleDeclaration(node) { - return !isModuleMergedWithES6Class(node) - && (!isES6ExportedDeclaration(node) - || ts.isFirstDeclarationOfKind(node, node.kind)); + return isFirstEmittedDeclarationInScope(node); } /** * Adds a leading VariableStatement for a enum or module declaration. @@ -43499,10 +44797,10 @@ var ts; ts.setOriginalNode(statement, /*original*/ node); // Adjust the source map emit to match the old emitter. if (node.kind === 224 /* EnumDeclaration */) { - setSourceMapRange(statement.declarationList, node); + ts.setSourceMapRange(statement.declarationList, node); } else { - setSourceMapRange(statement, node); + ts.setSourceMapRange(statement, node); } // Trailing comments for module declaration should be emitted after the function closure // instead of the variable statement: @@ -43522,8 +44820,8 @@ var ts; // } // })(m1 || (m1 = {})); // trailing comment module // - setCommentRange(statement, node); - setNodeEmitFlags(statement, 32768 /* NoTrailingComments */); + ts.setCommentRange(statement, node); + ts.setEmitFlags(statement, 32768 /* NoTrailingComments */); statements.push(statement); } /** @@ -43546,6 +44844,7 @@ var ts; // If needed, we should emit a variable declaration for the module. If we emit // a leading variable declaration, we should not emit leading comments for the // module body. + recordEmittedDeclarationInScope(node); if (shouldEmitVarForModuleDeclaration(node)) { addVarForEnumOrModuleDeclaration(statements, node); // We should still emit the comments if we are emitting a system module. @@ -43579,7 +44878,7 @@ var ts; /*typeArguments*/ undefined, [moduleArg]), /*location*/ node); ts.setOriginalNode(moduleStatement, node); - setNodeEmitFlags(moduleStatement, emitFlags); + ts.setEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); return statements; } @@ -43591,8 +44890,10 @@ var ts; function transformModuleBody(node, namespaceLocalName) { var savedCurrentNamespaceContainerName = currentNamespaceContainerName; var savedCurrentNamespace = currentNamespace; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; currentNamespaceContainerName = namespaceLocalName; currentNamespace = node; + currentScopeFirstDeclarationsOfName = undefined; var statements = []; startLexicalEnvironment(); var statementsLocation; @@ -43619,6 +44920,7 @@ var ts; ts.addRange(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; var block = ts.createBlock(ts.createNodeArray(statements, /*location*/ statementsLocation), /*location*/ blockLocation, @@ -43644,7 +44946,7 @@ var ts; // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. if (body.kind !== 226 /* ModuleBlock */) { - setNodeEmitFlags(block, block.emitFlags | 49152 /* NoComments */); + ts.setEmitFlags(block, ts.getEmitFlags(block) | 49152 /* NoComments */); } return block; } @@ -43680,7 +44982,7 @@ var ts; return undefined; } var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); - setNodeEmitFlags(moduleReference, 49152 /* NoComments */ | 65536 /* NoNestedComments */); + ts.setEmitFlags(moduleReference, 49152 /* NoComments */ | 65536 /* NoNestedComments */); if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { // export var ${name} = ${moduleReference}; // var ${name} = ${moduleReference}; @@ -43736,9 +45038,9 @@ var ts; } function addExportMemberAssignment(statements, node) { var expression = ts.createAssignment(getExportName(node), getLocalName(node, /*noSourceMaps*/ true)); - setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + ts.setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); var statement = ts.createStatement(expression); - setSourceMapRange(statement, ts.createRange(-1, node.end)); + ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); } function createNamespaceExport(exportName, exportValue, location) { @@ -43761,7 +45063,7 @@ var ts; emitFlags |= 1536 /* NoSourceMap */; } if (emitFlags) { - setNodeEmitFlags(qualifiedName, emitFlags); + ts.setEmitFlags(qualifiedName, emitFlags); } return qualifiedName; } @@ -43773,7 +45075,7 @@ var ts; */ function getNamespaceParameterName(node) { var name = ts.getGeneratedNameForNode(node); - setSourceMapRange(name, node.name); + ts.setSourceMapRange(name, node.name); return name; } /** @@ -43822,8 +45124,8 @@ var ts; */ function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { if (node.name) { - var name_28 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); + var name_29 = ts.getMutableClone(node.name); + emitFlags |= ts.getEmitFlags(node.name); if (!allowSourceMaps) { emitFlags |= 1536 /* NoSourceMap */; } @@ -43831,9 +45133,9 @@ var ts; emitFlags |= 49152 /* NoComments */; } if (emitFlags) { - setNodeEmitFlags(name_28, emitFlags); + ts.setEmitFlags(name_29, emitFlags); } - return name_28; + return name_29; } else { return ts.getGeneratedNameForNode(node); @@ -43910,7 +45212,7 @@ var ts; * @param node The node to emit. * @param emit A callback used to emit the node in the printer. */ - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedApplicableSubstitutions = applicableSubstitutions; var savedCurrentSuperContainer = currentSuperContainer; // If we need to support substitutions for `super` in an async method, @@ -43924,7 +45226,7 @@ var ts; if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) { applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); applicableSubstitutions = savedApplicableSubstitutions; currentSuperContainer = savedCurrentSuperContainer; } @@ -43935,9 +45237,9 @@ var ts; * @param isExpression A value indicating whether the node is to be used in an expression * position. */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -43947,16 +45249,16 @@ var ts; } function substituteShorthandPropertyAssignment(node) { if (enabledSubstitutions & 2 /* NamespaceExports */) { - var name_29 = node.name; - var exportedName = trySubstituteNamespaceExportedName(name_29); + var name_30 = node.name; + var exportedName = trySubstituteNamespaceExportedName(name_30); if (exportedName) { // A shorthand property with an assignment initializer is probably part of a // destructuring assignment if (node.objectAssignmentInitializer) { var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); - return ts.createPropertyAssignment(name_29, initializer, /*location*/ node); + return ts.createPropertyAssignment(name_30, initializer, /*location*/ node); } - return ts.createPropertyAssignment(name_29, exportedName, /*location*/ node); + return ts.createPropertyAssignment(name_30, exportedName, /*location*/ node); } } return node; @@ -43965,16 +45267,15 @@ var ts; switch (node.kind) { case 69 /* Identifier */: return substituteExpressionIdentifier(node); - } - if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */) { - switch (node.kind) { - case 174 /* CallExpression */: + case 172 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 173 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + case 174 /* CallExpression */: + if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */) { return substituteCallExpression(node); - case 172 /* PropertyAccessExpression */: - return substitutePropertyAccessExpression(node); - case 173 /* ElementAccessExpression */: - return substituteElementAccessExpression(node); - } + } + break; } return node; } @@ -43996,8 +45297,8 @@ var ts; var classAlias = classAliases[declaration.id]; if (classAlias) { var clone_4 = ts.getSynthesizedClone(classAlias); - setSourceMapRange(clone_4, node); - setCommentRange(clone_4, node); + ts.setSourceMapRange(clone_4, node); + ts.setCommentRange(clone_4, node); return clone_4; } } @@ -44007,7 +45308,7 @@ var ts; } function trySubstituteNamespaceExportedName(node) { // If this is explicitly a local name, do not substitute. - if (enabledSubstitutions & applicableSubstitutions && (getNodeEmitFlags(node) & 262144 /* LocalName */) === 0) { + if (enabledSubstitutions & applicableSubstitutions && (ts.getEmitFlags(node) & 262144 /* LocalName */) === 0) { // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); @@ -44038,23 +45339,48 @@ var ts; return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 95 /* SuperKeyword */) { + if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */ && node.expression.kind === 95 /* SuperKeyword */) { var flags = getSuperContainerAsyncMethodFlags(); if (flags) { return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); } } - return node; + return substituteConstantValue(node); } function substituteElementAccessExpression(node) { - if (node.expression.kind === 95 /* SuperKeyword */) { + if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */ && node.expression.kind === 95 /* SuperKeyword */) { var flags = getSuperContainerAsyncMethodFlags(); if (flags) { return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); } } + return substituteConstantValue(node); + } + function substituteConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + var substitute = ts.createLiteral(constantValue); + ts.setSourceMapRange(substitute, node); + ts.setCommentRange(substitute, node); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : ts.getTextOfNode(node.argumentExpression); + substitute.trailingComment = " " + propertyName + " "; + } + ts.setConstantValue(node, constantValue); + return substitute; + } return node; } + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; + } + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) + ? resolver.getConstantValue(node) + : undefined; + } function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { if (flags & 4096 /* AsyncMethodWithSuperBinding */) { return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), @@ -44083,6 +45409,9 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; return ts.visitEachChild(node, visitor, context); @@ -44201,7 +45530,7 @@ var ts; var ts; (function (ts) { function transformSystemModule(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -44230,6 +45559,9 @@ var ts; var currentNode; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; currentNode = node; @@ -44283,7 +45615,7 @@ var ts; ts.createParameter(exportFunctionForFile), ts.createParameter(contextObjectForFile) ], - /*type*/ undefined, setNodeEmitFlags(ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true), 1 /* EmitEmitHelpers */)); + /*type*/ undefined, ts.setEmitFlags(ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true), 1 /* EmitEmitHelpers */)); // Write the call to `System.register` // Clear the emit-helpers flag for later passes since we'll have already used it in the module body // So the helper will be emit at the correct position instead of at the top of the source-file @@ -44292,7 +45624,7 @@ var ts; /*typeArguments*/ undefined, moduleName ? [moduleName, dependencies, body] : [dependencies, body])) - ], /*nodeEmitFlags*/ ~1 /* EmitEmitHelpers */ & getNodeEmitFlags(node)); + ], /*nodeEmitFlags*/ ~1 /* EmitEmitHelpers */ & ts.getEmitFlags(node)); var _a; } /** @@ -44676,17 +46008,17 @@ var ts; function visitFunctionDeclaration(node) { if (ts.hasModifier(node, 1 /* Export */)) { // If the function is exported, ensure it has a name and rewrite the function without any export flags. - var name_30 = node.name || ts.getGeneratedNameForNode(node); + var name_31 = node.name || ts.getGeneratedNameForNode(node); var newNode = ts.createFunctionDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, node.asteriskToken, name_30, + /*modifiers*/ undefined, node.asteriskToken, name_31, /*typeParameters*/ undefined, node.parameters, /*type*/ undefined, node.body, /*location*/ node); // Record a declaration export in the outer module body function. recordExportedFunctionDeclaration(node); if (!ts.hasModifier(node, 512 /* Default */)) { - recordExportName(name_30); + recordExportName(name_31); } ts.setOriginalNode(newNode, node); node = newNode; @@ -44698,16 +46030,16 @@ var ts; function visitExpressionStatement(node) { var originalNode = ts.getOriginalNode(node); if ((originalNode.kind === 225 /* ModuleDeclaration */ || originalNode.kind === 224 /* EnumDeclaration */) && ts.hasModifier(originalNode, 1 /* Export */)) { - var name_31 = getDeclarationName(originalNode); + var name_32 = getDeclarationName(originalNode); // We only need to hoistVariableDeclaration for EnumDeclaration // as ModuleDeclaration is already hoisted when the transformer call visitVariableStatement // which then call transformsVariable for each declaration in declarationList if (originalNode.kind === 224 /* EnumDeclaration */) { - hoistVariableDeclaration(name_31); + hoistVariableDeclaration(name_32); } return [ node, - createExportStatement(name_31, name_31) + createExportStatement(name_32, name_32) ]; } return node; @@ -44952,14 +46284,14 @@ var ts; // // Substitutions // - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { if (node.kind === 256 /* SourceFile */) { exportFunctionForFile = exportFunctionForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); exportFunctionForFile = undefined; } else { - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); } } /** @@ -44969,9 +46301,9 @@ var ts; * @param isExpression A value indicating whether the node is to be used in an expression * position. */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } return node; @@ -45013,7 +46345,7 @@ var ts; return node; } function substituteAssignmentExpression(node) { - setNodeEmitFlags(node, 128 /* NoSubstitution */); + ts.setEmitFlags(node, 128 /* NoSubstitution */); var left = node.left; switch (left.kind) { case 69 /* Identifier */: @@ -45118,7 +46450,7 @@ var ts; var exportDeclaration = resolver.getReferencedExportContainer(operand); if (exportDeclaration) { var expr = ts.createPrefix(node.operator, operand, node); - setNodeEmitFlags(expr, 128 /* NoSubstitution */); + ts.setEmitFlags(expr, 128 /* NoSubstitution */); var call = createExportExpression(operand, expr); if (node.kind === 185 /* PrefixUnaryExpression */) { return call; @@ -45165,7 +46497,7 @@ var ts; ts.createForIn(ts.createVariableDeclarationList([ ts.createVariableDeclaration(n, /*type*/ undefined) ]), m, ts.createBlock([ - setNodeEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32 /* SingleLine */) + ts.setEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32 /* SingleLine */) ])), ts.createStatement(ts.createCall(exportFunctionForFile, /*typeArguments*/ undefined, [exports])) @@ -45283,7 +46615,7 @@ var ts; function updateSourceFile(node, statements, nodeEmitFlags) { var updated = ts.getMutableClone(node); updated.statements = ts.createNodeArray(statements, node.statements); - setNodeEmitFlags(updated, nodeEmitFlags); + ts.setEmitFlags(updated, nodeEmitFlags); return updated; } } @@ -45301,7 +46633,7 @@ var ts; _a[ts.ModuleKind.AMD] = transformAMDModule, _a[ts.ModuleKind.UMD] = transformUMDModule, _a)); - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, setNodeEmitFlags = context.setNodeEmitFlags, getNodeEmitFlags = context.getNodeEmitFlags, setSourceMapRange = context.setSourceMapRange; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -45333,6 +46665,9 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; // Collect information about the external module. @@ -45365,7 +46700,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); var updated = updateSourceFile(node, statements); if (hasExportStarsToExportValues) { - setNodeEmitFlags(updated, 2 /* EmitExportStar */ | getNodeEmitFlags(node)); + ts.setEmitFlags(updated, 2 /* EmitExportStar */ | ts.getEmitFlags(node)); } return updated; } @@ -45386,7 +46721,7 @@ var ts; */ function transformUMDModule(node) { var define = ts.createIdentifier("define"); - setNodeEmitFlags(define, 16 /* UMDDefine */); + ts.setEmitFlags(define, 16 /* UMDDefine */); return transformAsynchronousModule(node, define, /*moduleName*/ undefined, /*includeNonAmdDependencies*/ false); } /** @@ -45466,7 +46801,7 @@ var ts; if (hasExportStarsToExportValues) { // If we have any `export * from ...` declarations // we need to inform the emitter to add the __export helper. - setNodeEmitFlags(body, 2 /* EmitExportStar */); + ts.setEmitFlags(body, 2 /* EmitExportStar */); } return body; } @@ -45475,13 +46810,13 @@ var ts; if (emitAsReturn) { var statement = ts.createReturn(exportEquals.expression, /*location*/ exportEquals); - setNodeEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 49152 /* NoComments */); + ts.setEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 49152 /* NoComments */); statements.push(statement); } else { var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), exportEquals.expression), /*location*/ exportEquals); - setNodeEmitFlags(statement, 49152 /* NoComments */); + ts.setEmitFlags(statement, 49152 /* NoComments */); statements.push(statement); } } @@ -45574,7 +46909,7 @@ var ts; } // Set emitFlags on the name of the importEqualsDeclaration // This is so the printer will not substitute the identifier - setNodeEmitFlags(node.name, 128 /* NoSubstitution */); + ts.setEmitFlags(node.name, 128 /* NoSubstitution */); var statements = []; if (moduleKind !== ts.ModuleKind.AMD) { if (ts.hasModifier(node, 1 /* Export */)) { @@ -45678,16 +47013,16 @@ var ts; else { var names = ts.reduceEachChild(node, collectExportMembers, []); for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_32 = names_1[_i]; - addExportMemberAssignments(statements, name_32); + var name_33 = names_1[_i]; + addExportMemberAssignments(statements, name_33); } } } function collectExportMembers(names, node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && ts.isDeclaration(node)) { - var name_33 = node.name; - if (ts.isIdentifier(name_33)) { - names.push(name_33); + var name_34 = node.name; + if (ts.isIdentifier(name_34)) { + names.push(name_34); } } return ts.reduceEachChild(node, collectExportMembers, names); @@ -45706,7 +47041,7 @@ var ts; addExportDefault(statements, getDeclarationName(node), /*location*/ node); } else { - statements.push(createExportStatement(node.name, setNodeEmitFlags(ts.getSynthesizedClone(node.name), 262144 /* LocalName */), /*location*/ node)); + statements.push(createExportStatement(node.name, ts.setEmitFlags(ts.getSynthesizedClone(node.name), 262144 /* LocalName */), /*location*/ node)); } } function visitVariableStatement(node) { @@ -45856,20 +47191,20 @@ var ts; /*modifiers*/ undefined, [ts.createVariableDeclaration(getDeclarationName(node), /*type*/ undefined, ts.createPropertyAccess(ts.createIdentifier("exports"), getDeclarationName(node)))], /*location*/ node); - setNodeEmitFlags(transformedStatement, 49152 /* NoComments */); + ts.setEmitFlags(transformedStatement, 49152 /* NoComments */); statements.push(transformedStatement); } function getDeclarationName(node) { return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { if (node.kind === 256 /* SourceFile */) { bindingNameExportSpecifiersMap = bindingNameExportSpecifiersForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); bindingNameExportSpecifiersMap = undefined; } else { - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); } } /** @@ -45879,9 +47214,9 @@ var ts; * @param isExpression A value indicating whether the node is to be used in an expression * position. */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -45925,7 +47260,7 @@ var ts; // If the left-hand-side of the binaryExpression is an identifier and its is export through export Specifier if (ts.isIdentifier(left) && ts.isAssignmentOperator(node.operatorToken.kind)) { if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, left.text)) { - setNodeEmitFlags(node, 128 /* NoSubstitution */); + ts.setEmitFlags(node, 128 /* NoSubstitution */); var nestedExportAssignment = void 0; for (var _i = 0, _a = bindingNameExportSpecifiersMap[left.text]; _i < _a.length; _i++) { var specifier = _a[_i]; @@ -45945,13 +47280,13 @@ var ts; var operand = node.operand; if (ts.isIdentifier(operand) && bindingNameExportSpecifiersForFileMap) { if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, operand.text)) { - setNodeEmitFlags(node, 128 /* NoSubstitution */); + ts.setEmitFlags(node, 128 /* NoSubstitution */); var transformedUnaryExpression = void 0; if (node.kind === 186 /* PostfixUnaryExpression */) { - transformedUnaryExpression = ts.createBinary(operand, ts.createNode(operator === 41 /* PlusPlusToken */ ? 57 /* PlusEqualsToken */ : 58 /* MinusEqualsToken */), ts.createLiteral(1), + transformedUnaryExpression = ts.createBinary(operand, ts.createToken(operator === 41 /* PlusPlusToken */ ? 57 /* PlusEqualsToken */ : 58 /* MinusEqualsToken */), ts.createLiteral(1), /*location*/ node); // We have to set no substitution flag here to prevent visit the binary expression and substitute it again as we will preform all necessary substitution in here - setNodeEmitFlags(transformedUnaryExpression, 128 /* NoSubstitution */); + ts.setEmitFlags(transformedUnaryExpression, 128 /* NoSubstitution */); } var nestedExportAssignment = void 0; for (var _i = 0, _a = bindingNameExportSpecifiersMap[operand.text]; _i < _a.length; _i++) { @@ -45966,7 +47301,7 @@ var ts; return node; } function trySubstituteExportedName(node) { - var emitFlags = getNodeEmitFlags(node); + var emitFlags = ts.getEmitFlags(node); if ((emitFlags & 262144 /* LocalName */) === 0) { var container = resolver.getReferencedExportContainer(node, (emitFlags & 131072 /* ExportName */) !== 0); if (container) { @@ -45979,7 +47314,7 @@ var ts; return undefined; } function trySubstituteImportedName(node) { - if ((getNodeEmitFlags(node) & 262144 /* LocalName */) === 0) { + if ((ts.getEmitFlags(node) & 262144 /* LocalName */) === 0) { var declaration = resolver.getReferencedImportDeclaration(node); if (declaration) { if (ts.isImportClause(declaration)) { @@ -45994,14 +47329,14 @@ var ts; } } else if (ts.isImportSpecifier(declaration)) { - var name_34 = declaration.propertyName || declaration.name; - if (name_34.originalKeywordKind === 77 /* DefaultKeyword */ && languageVersion <= 0 /* ES3 */) { + var name_35 = declaration.propertyName || declaration.name; + if (name_35.originalKeywordKind === 77 /* DefaultKeyword */ && languageVersion <= 0 /* ES3 */) { // TODO: ES3 transform to handle x.default -> x["default"] - return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_34.text), + return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_35.text), /*location*/ node); } else { - return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_34), + return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_35), /*location*/ node); } } @@ -46025,7 +47360,7 @@ var ts; var statement = ts.createStatement(createExportAssignment(name, value)); statement.startsOnNewLine = true; if (location) { - setSourceMapRange(statement, location); + ts.setSourceMapRange(statement, location); } return statement; } @@ -46063,7 +47398,7 @@ var ts; if (includeNonAmdDependencies && importAliasName) { // Set emitFlags on the name of the classDeclaration // This is so that when printer will not substitute the identifier - setNodeEmitFlags(importAliasName, 128 /* NoSubstitution */); + ts.setEmitFlags(importAliasName, 128 /* NoSubstitution */); aliasedModuleNames.push(externalModuleName); importAliasNames.push(ts.createParameter(importAliasName)); } @@ -46098,6 +47433,9 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; node = ts.visitEachChild(node, visitor, context); currentSourceFile = undefined; @@ -46280,12 +47618,12 @@ var ts; return getTagName(node.openingElement); } else { - var name_35 = node.tagName; - if (ts.isIdentifier(name_35) && ts.isIntrinsicJsxName(name_35.text)) { - return ts.createLiteral(name_35.text); + var name_36 = node.tagName; + if (ts.isIdentifier(name_36) && ts.isIntrinsicJsxName(name_36.text)) { + return ts.createLiteral(name_36.text); } else { - return ts.createExpressionFromEntityName(name_35); + return ts.createExpressionFromEntityName(name_36); } } } @@ -46575,6 +47913,9 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitEachChild(node, visitor, context); } function visitor(node) { @@ -46820,7 +48161,7 @@ var ts; _a[7 /* Endfinally */] = "endfinally", _a)); function transformGenerators(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration, setSourceMapRange = context.setSourceMapRange, setCommentRange = context.setCommentRange, setNodeEmitFlags = context.setNodeEmitFlags; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var resolver = context.getEmitResolver(); @@ -46870,6 +48211,9 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (node.transformFlags & 1024 /* ContainsGenerator */) { currentSourceFile = node; node = ts.visitEachChild(node, visitor, context); @@ -47011,7 +48355,7 @@ var ts; */ function visitFunctionDeclaration(node) { // Currently, we only support generators that were originally async functions. - if (node.asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (node.asteriskToken && ts.getEmitFlags(node) & 2097152 /* AsyncFunctionBody */) { node = ts.setOriginalNode(ts.createFunctionDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, @@ -47050,7 +48394,7 @@ var ts; */ function visitFunctionExpression(node) { // Currently, we only support generators that were originally async functions. - if (node.asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (node.asteriskToken && ts.getEmitFlags(node) & 2097152 /* AsyncFunctionBody */) { node = ts.setOriginalNode(ts.createFunctionExpression( /*asteriskToken*/ undefined, node.name, /*typeParameters*/ undefined, node.parameters, @@ -47099,6 +48443,7 @@ var ts; var savedBlocks = blocks; var savedBlockOffsets = blockOffsets; var savedBlockActions = blockActions; + var savedBlockStack = blockStack; var savedLabelOffsets = labelOffsets; var savedLabelExpressions = labelExpressions; var savedNextLabelId = nextLabelId; @@ -47112,6 +48457,7 @@ var ts; blocks = undefined; blockOffsets = undefined; blockActions = undefined; + blockStack = undefined; labelOffsets = undefined; labelExpressions = undefined; nextLabelId = 1; @@ -47132,6 +48478,7 @@ var ts; blocks = savedBlocks; blockOffsets = savedBlockOffsets; blockActions = savedBlockActions; + blockStack = savedBlockStack; labelOffsets = savedLabelOffsets; labelExpressions = savedLabelExpressions; nextLabelId = savedNextLabelId; @@ -47156,7 +48503,7 @@ var ts; } else { // Do not hoist custom prologues. - if (node.emitFlags & 8388608 /* CustomPrologue */) { + if (ts.getEmitFlags(node) & 8388608 /* CustomPrologue */) { return node; } for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { @@ -48202,9 +49549,9 @@ var ts; } return -1; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } return node; @@ -48221,11 +49568,11 @@ var ts; if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { - var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); - if (name_36) { - var clone_7 = ts.getMutableClone(name_36); - setSourceMapRange(clone_7, node); - setCommentRange(clone_7, node); + var name_37 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); + if (name_37) { + var clone_7 = ts.getMutableClone(name_37); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); return clone_7; } } @@ -48815,7 +50162,7 @@ var ts; return ts.createCall(ts.createHelperName(currentSourceFile.externalHelpersModuleName, "__generator"), /*typeArguments*/ undefined, [ ts.createThis(), - setNodeEmitFlags(ts.createFunctionExpression( + ts.setEmitFlags(ts.createFunctionExpression( /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, [ts.createParameter(state)], @@ -49218,8 +50565,32 @@ var ts; Jump[Jump["Continue"] = 4] = "Continue"; Jump[Jump["Return"] = 8] = "Return"; })(Jump || (Jump = {})); + var SuperCaptureResult; + (function (SuperCaptureResult) { + /** + * A capture may have been added for calls to 'super', but + * the caller should emit subsequent statements normally. + */ + SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * var _this = _super.call(...) || this; + * + * Callers should skip the current statement. + */ + SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * return _super.call(...) || this; + * + * Callers should skip the current statement and avoid any returns of '_this'. + */ + SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn"; + })(SuperCaptureResult || (SuperCaptureResult = {})); function transformES6(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, getCommentRange = context.getCommentRange, setCommentRange = context.setCommentRange, getSourceMapRange = context.getSourceMapRange, setSourceMapRange = context.setSourceMapRange, setTokenSourceMapRange = context.setTokenSourceMapRange; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var previousOnSubstituteNode = context.onSubstituteNode; var previousOnEmitNode = context.onEmitNode; @@ -49247,6 +50618,9 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; currentText = node.text; return ts.visitNode(node, visitor, ts.isSourceFile); @@ -49418,7 +50792,7 @@ var ts; enclosingFunction = currentNode; if (currentNode.kind !== 180 /* ArrowFunction */) { enclosingNonArrowFunction = currentNode; - if (!(currentNode.emitFlags & 2097152 /* AsyncFunctionBody */)) { + if (!(ts.getEmitFlags(currentNode) & 2097152 /* AsyncFunctionBody */)) { enclosingNonAsyncFunctionBody = currentNode; } } @@ -49634,17 +51008,17 @@ var ts; // To preserve the behavior of the old emitter, we explicitly indent // the body of the function here if it was requested in an earlier // transformation. - if (getNodeEmitFlags(node) & 524288 /* Indented */) { - setNodeEmitFlags(classFunction, 524288 /* Indented */); + if (ts.getEmitFlags(node) & 524288 /* Indented */) { + ts.setEmitFlags(classFunction, 524288 /* Indented */); } // "inner" and "outer" below are added purely to preserve source map locations from // the old emitter var inner = ts.createPartiallyEmittedExpression(classFunction); inner.end = node.end; - setNodeEmitFlags(inner, 49152 /* NoComments */); + ts.setEmitFlags(inner, 49152 /* NoComments */); var outer = ts.createPartiallyEmittedExpression(inner); outer.end = ts.skipTrivia(currentText, node.pos); - setNodeEmitFlags(outer, 49152 /* NoComments */); + ts.setEmitFlags(outer, 49152 /* NoComments */); return ts.createParen(ts.createCall(outer, /*typeArguments*/ undefined, extendsClauseElement ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] @@ -49669,14 +51043,14 @@ var ts; // emit with the original emitter. var outer = ts.createPartiallyEmittedExpression(localName); outer.end = closingBraceLocation.end; - setNodeEmitFlags(outer, 49152 /* NoComments */); + ts.setEmitFlags(outer, 49152 /* NoComments */); var statement = ts.createReturn(outer); statement.pos = closingBraceLocation.pos; - setNodeEmitFlags(statement, 49152 /* NoComments */ | 12288 /* NoTokenSourceMaps */); + ts.setEmitFlags(statement, 49152 /* NoComments */ | 12288 /* NoTokenSourceMaps */); statements.push(statement); ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, /*location*/ node.members), /*location*/ undefined, /*multiLine*/ true); - setNodeEmitFlags(block, 49152 /* NoComments */); + ts.setEmitFlags(block, 49152 /* NoComments */); return block; } /** @@ -49702,13 +51076,17 @@ var ts; function addConstructor(statements, node, extendsClauseElement) { var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); - statements.push(ts.createFunctionDeclaration( + var constructorFunction = ts.createFunctionDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, /*asteriskToken*/ undefined, getDeclarationName(node), /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), - /*location*/ constructor || node)); + /*location*/ constructor || node); + if (extendsClauseElement) { + ts.setEmitFlags(constructorFunction, 256 /* CapturesThis */); + } + statements.push(constructorFunction); } /** * Transforms the parameters of the constructor declaration of a class. @@ -49740,51 +51118,146 @@ var ts; function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { var statements = []; startLexicalEnvironment(); + var statementOffset = -1; + if (hasSynthesizedSuper) { + // If a super call has already been synthesized, + // we're going to assume that we should just transform everything after that. + // The assumption is that no prior step in the pipeline has added any prologue directives. + statementOffset = 1; + } + else if (constructor) { + // Otherwise, try to emit all potential prologue directives first. + statementOffset = ts.addPrologueDirectives(statements, constructor.body.statements, /*ensureUseStrict*/ false, visitor); + } if (constructor) { - addCaptureThisForNodeIfNeeded(statements, constructor); addDefaultValueAssignmentsIfNeeded(statements, constructor); addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); + } + var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, !!extendsClauseElement, hasSynthesizedSuper, statementOffset); + // The last statement expression was replaced. Skip it. + if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { + statementOffset++; } - addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper); if (constructor) { - var body = saveStateAndInvoke(constructor, hasSynthesizedSuper ? transformConstructorBodyWithSynthesizedSuper : transformConstructorBodyWithoutSynthesizedSuper); + var body = saveStateAndInvoke(constructor, function (constructor) { return ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset); }); ts.addRange(statements, body); } + // Return `_this` unless we're sure enough that it would be pointless to add a return statement. + // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return. + if (extendsClauseElement + && superCaptureStatus !== 2 /* ReplaceWithReturn */ + && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { + statements.push(ts.createReturn(ts.createIdentifier("_this"))); + } ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, /*location*/ constructor ? constructor.body.statements : node.members), /*location*/ constructor ? constructor.body : node, /*multiLine*/ true); if (!constructor) { - setNodeEmitFlags(block, 49152 /* NoComments */); + ts.setEmitFlags(block, 49152 /* NoComments */); } return block; } - function transformConstructorBodyWithSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 1); - } - function transformConstructorBodyWithoutSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 0); + /** + * We want to try to avoid emitting a return statement in certain cases if a user already returned something. + * It would generate obviously dead code, so we'll try to make things a little bit prettier + * by doing a minimal check on whether some common patterns always explicitly return. + */ + function isSufficientlyCoveredByReturnStatements(statement) { + // A return statement is considered covered. + if (statement.kind === 211 /* ReturnStatement */) { + return true; + } + else if (statement.kind === 203 /* IfStatement */) { + var ifStatement = statement; + if (ifStatement.elseStatement) { + return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && + isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); + } + } + else if (statement.kind === 199 /* Block */) { + var lastStatement = ts.lastOrUndefined(statement.statements); + if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { + return true; + } + } + return false; } /** - * Adds a synthesized call to `_super` if it is needed. + * Declares a `_this` variable for derived classes and for when arrow functions capture `this`. * - * @param statements The statements for the new constructor body. - * @param constructor The constructor for the class. - * @param extendsClauseElement The expression for the class `extends` clause. - * @param hasSynthesizedSuper A value indicating whether the constructor starts with a - * synthesized `super` call. + * @returns The new statement offset into the `statements` array. */ - function addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper) { - // If the TypeScript transformer needed to synthesize a constructor for property - // initializers, it would have also added a synthetic `...args` parameter and - // `super` call. - // If this is the case, or if the class has an `extends` clause but no - // constructor, we emit a synthesized call to `_super`. - if (constructor ? hasSynthesizedSuper : extendsClauseElement) { - statements.push(ts.createStatement(ts.createFunctionApply(ts.createIdentifier("_super"), ts.createThis(), ts.createIdentifier("arguments")), - /*location*/ extendsClauseElement)); + function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, hasExtendsClause, hasSynthesizedSuper, statementOffset) { + // If this isn't a derived class, just capture 'this' for arrow functions if necessary. + if (!hasExtendsClause) { + if (ctor) { + addCaptureThisForNodeIfNeeded(statements, ctor); + } + return 0 /* NoReplacement */; } + // We must be here because the user didn't write a constructor + // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. + // If that's the case we can just immediately return the result of a 'super()' call. + if (!ctor) { + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + return 2 /* ReplaceWithReturn */; + } + // The constructor exists, but it and the 'super()' call it contains were generated + // for something like property initializers. + // Create a captured '_this' variable and assume it will subsequently be used. + if (hasSynthesizedSuper) { + captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); + enableSubstitutionsForCapturedThis(); + return 1 /* ReplaceSuperCapture */; + } + // Most of the time, a 'super' call will be the first real statement in a constructor body. + // In these cases, we'd like to transform these into a *single* statement instead of a declaration + // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer, + // we'd get: + // + // var _this; + // _this = _super.call(...) || this; + // + // instead of + // + // var _this = _super.call(...) || this; + // + // Additionally, if the 'super()' call is the last statement, we should just avoid capturing + // entirely and immediately return the result like so: + // + // return _super.call(...) || this; + // + var firstStatement; + var superCallExpression; + var ctorStatements = ctor.body.statements; + if (statementOffset < ctorStatements.length) { + firstStatement = ctorStatements[statementOffset]; + if (firstStatement.kind === 202 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { + var superCall = firstStatement.expression; + superCallExpression = ts.setOriginalNode(saveStateAndInvoke(superCall, visitImmediateSuperCallInBody), superCall); + } + } + // Return the result if we have an immediate super() call on the last statement. + if (superCallExpression && statementOffset === ctorStatements.length - 1) { + statements.push(ts.createReturn(superCallExpression)); + return 2 /* ReplaceWithReturn */; + } + // Perform the capture. + captureThisForNode(statements, ctor, superCallExpression, firstStatement); + // If we're actually replacing the original statement, we need to signal this to the caller. + if (superCallExpression) { + return 1 /* ReplaceSuperCapture */; + } + return 0 /* NoReplacement */; + } + function createDefaultSuperCallOrThis() { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 128 /* NoSubstitution */); + var superCall = ts.createFunctionApply(ts.createIdentifier("_super"), actualThis, ts.createIdentifier("arguments")); + return ts.createLogicalOr(superCall, actualThis); } /** * Visits a parameter declaration. @@ -49837,17 +51310,17 @@ var ts; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - var name_37 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + var name_38 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; // A rest parameter cannot have a binding pattern or an initializer, // so let's just ignore it. if (dotDotDotToken) { continue; } - if (ts.isBindingPattern(name_37)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name_37, initializer); + if (ts.isBindingPattern(name_38)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name_38, initializer); } else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name_37, initializer); + addDefaultValueAssignmentForInitializer(statements, parameter, name_38, initializer); } } } @@ -49865,11 +51338,11 @@ var ts; // we usually don't want to emit a var declaration; however, in the presence // of an initializer, we must emit that expression to preserve side effects. if (name.elements.length > 0) { - statements.push(setNodeEmitFlags(ts.createVariableStatement( + statements.push(ts.setEmitFlags(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608 /* CustomPrologue */)); } else if (initializer) { - statements.push(setNodeEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608 /* CustomPrologue */)); + statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608 /* CustomPrologue */)); } } /** @@ -49882,14 +51355,14 @@ var ts; */ function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); - var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), setNodeEmitFlags(ts.createBlock([ - ts.createStatement(ts.createAssignment(setNodeEmitFlags(ts.getMutableClone(name), 1536 /* NoSourceMap */), setNodeEmitFlags(initializer, 1536 /* NoSourceMap */ | getNodeEmitFlags(initializer)), + var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), ts.setEmitFlags(ts.createBlock([ + ts.createStatement(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 1536 /* NoSourceMap */), ts.setEmitFlags(initializer, 1536 /* NoSourceMap */ | ts.getEmitFlags(initializer)), /*location*/ parameter)) ], /*location*/ parameter), 32 /* SingleLine */ | 1024 /* NoTrailingSourceMap */ | 12288 /* NoTokenSourceMaps */), /*elseStatement*/ undefined, /*location*/ parameter); statement.startsOnNewLine = true; - setNodeEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 8388608 /* CustomPrologue */); + ts.setEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 8388608 /* CustomPrologue */); statements.push(statement); } /** @@ -49919,13 +51392,13 @@ var ts; } // `declarationName` is the name of the local declaration for the parameter. var declarationName = ts.getMutableClone(parameter.name); - setNodeEmitFlags(declarationName, 1536 /* NoSourceMap */); + ts.setEmitFlags(declarationName, 1536 /* NoSourceMap */); // `expressionName` is the name of the parameter used in expressions. var expressionName = ts.getSynthesizedClone(parameter.name); var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); // var param = []; - statements.push(setNodeEmitFlags(ts.createVariableStatement( + statements.push(ts.setEmitFlags(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(declarationName, /*type*/ undefined, ts.createArrayLiteral([])) @@ -49941,7 +51414,7 @@ var ts; ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), /*location*/ parameter)) ])); - setNodeEmitFlags(forStatement, 8388608 /* CustomPrologue */); + ts.setEmitFlags(forStatement, 8388608 /* CustomPrologue */); ts.startOnNewLine(forStatement); statements.push(forStatement); } @@ -49953,17 +51426,20 @@ var ts; */ function addCaptureThisForNodeIfNeeded(statements, node) { if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 180 /* ArrowFunction */) { - enableSubstitutionsForCapturedThis(); - var captureThisStatement = ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("_this", - /*type*/ undefined, ts.createThis()) - ])); - setNodeEmitFlags(captureThisStatement, 49152 /* NoComments */ | 8388608 /* CustomPrologue */); - setSourceMapRange(captureThisStatement, node); - statements.push(captureThisStatement); + captureThisForNode(statements, node, ts.createThis()); } } + function captureThisForNode(statements, node, initializer, originalStatement) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("_this", + /*type*/ undefined, initializer) + ]), originalStatement); + ts.setEmitFlags(captureThisStatement, 49152 /* NoComments */ | 8388608 /* CustomPrologue */); + ts.setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } /** * Adds statements to the class body function for a class to define the members of the * class. @@ -50012,20 +51488,20 @@ var ts; * @param member The MethodDeclaration node. */ function transformClassMethodDeclarationToStatement(receiver, member) { - var commentRange = getCommentRange(member); - var sourceMapRange = getSourceMapRange(member); + var commentRange = ts.getCommentRange(member); + var sourceMapRange = ts.getSourceMapRange(member); var func = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined); - setNodeEmitFlags(func, 49152 /* NoComments */); - setSourceMapRange(func, sourceMapRange); + ts.setEmitFlags(func, 49152 /* NoComments */); + ts.setSourceMapRange(func, sourceMapRange); var statement = ts.createStatement(ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name), func), /*location*/ member); ts.setOriginalNode(statement, member); - setCommentRange(statement, commentRange); + ts.setCommentRange(statement, commentRange); // The location for the statement is used to emit comments only. // No source map should be emitted for this statement to align with the // old emitter. - setNodeEmitFlags(statement, 1536 /* NoSourceMap */); + ts.setEmitFlags(statement, 1536 /* NoSourceMap */); return statement; } /** @@ -50036,11 +51512,11 @@ var ts; */ function transformAccessorsToStatement(receiver, accessors) { var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, /*startsOnNewLine*/ false), - /*location*/ getSourceMapRange(accessors.firstAccessor)); + /*location*/ ts.getSourceMapRange(accessors.firstAccessor)); // The location for the statement is used to emit source maps only. // No comments should be emitted for this statement to align with the // old emitter. - setNodeEmitFlags(statement, 49152 /* NoComments */); + ts.setEmitFlags(statement, 49152 /* NoComments */); return statement; } /** @@ -50054,24 +51530,24 @@ var ts; // To align with source maps in the old emitter, the receiver and property name // arguments are both mapped contiguously to the accessor name. var target = ts.getMutableClone(receiver); - setNodeEmitFlags(target, 49152 /* NoComments */ | 1024 /* NoTrailingSourceMap */); - setSourceMapRange(target, firstAccessor.name); + ts.setEmitFlags(target, 49152 /* NoComments */ | 1024 /* NoTrailingSourceMap */); + ts.setSourceMapRange(target, firstAccessor.name); var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); - setNodeEmitFlags(propertyName, 49152 /* NoComments */ | 512 /* NoLeadingSourceMap */); - setSourceMapRange(propertyName, firstAccessor.name); + ts.setEmitFlags(propertyName, 49152 /* NoComments */ | 512 /* NoLeadingSourceMap */); + ts.setSourceMapRange(propertyName, firstAccessor.name); var properties = []; if (getAccessor) { var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined); - setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); + ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor)); var getter = ts.createPropertyAssignment("get", getterFunction); - setCommentRange(getter, getCommentRange(getAccessor)); + ts.setCommentRange(getter, ts.getCommentRange(getAccessor)); properties.push(getter); } if (setAccessor) { var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined); - setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); + ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor)); var setter = ts.createPropertyAssignment("set", setterFunction); - setCommentRange(setter, getCommentRange(setAccessor)); + ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); properties.push(setter); } properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); @@ -50096,7 +51572,7 @@ var ts; enableSubstitutionsForCapturedThis(); } var func = transformFunctionLikeToExpression(node, /*location*/ node, /*name*/ undefined); - setNodeEmitFlags(func, 256 /* CapturesThis */); + ts.setEmitFlags(func, 256 /* CapturesThis */); return func; } /** @@ -50191,7 +51667,7 @@ var ts; } var expression = ts.visitNode(body, visitor, ts.isExpression); var returnStatement = ts.createReturn(expression, /*location*/ body); - setNodeEmitFlags(returnStatement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 32768 /* NoTrailingComments */); + ts.setEmitFlags(returnStatement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 32768 /* NoTrailingComments */); statements.push(returnStatement); // To align with the source map emit for the old emitter, we set a custom // source map location for the close brace. @@ -50205,10 +51681,10 @@ var ts; } var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); if (!multiLine && singleLine) { - setNodeEmitFlags(block, 32 /* SingleLine */); + ts.setEmitFlags(block, 32 /* SingleLine */); } if (closeBraceLocation) { - setTokenSourceMapRange(block, 16 /* CloseBraceToken */, closeBraceLocation); + ts.setTokenSourceMapRange(block, 16 /* CloseBraceToken */, closeBraceLocation); } ts.setOriginalNode(block, node.body); return block; @@ -50274,7 +51750,7 @@ var ts; assignment = ts.flattenVariableDestructuringToExpression(context, decl, hoistVariableDeclaration, /*nameSubstitution*/ undefined, visitor); } else { - assignment = ts.createBinary(decl.name, 56 /* EqualsToken */, decl.initializer); + assignment = ts.createBinary(decl.name, 56 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); } (assignments || (assignments = [])).push(assignment); } @@ -50303,7 +51779,7 @@ var ts; : visitVariableDeclaration)); var declarationList = ts.createVariableDeclarationList(declarations, /*location*/ node); ts.setOriginalNode(declarationList, node); - setCommentRange(declarationList, node); + ts.setCommentRange(declarationList, node); if (node.transformFlags & 2097152 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { @@ -50311,7 +51787,7 @@ var ts; // the source map range for the declaration list. var firstDeclaration = ts.firstOrUndefined(declarations); var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); } return declarationList; } @@ -50501,7 +51977,7 @@ var ts; // emitter. var firstDeclaration = declarations[0]; var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); statements.push(ts.createVariableStatement( /*modifiers*/ undefined, declarationList)); } @@ -50549,12 +52025,12 @@ var ts; } } // The old emitter does not emit source maps for the expression - setNodeEmitFlags(expression, 1536 /* NoSourceMap */ | getNodeEmitFlags(expression)); + ts.setEmitFlags(expression, 1536 /* NoSourceMap */ | ts.getEmitFlags(expression)); // The old emitter does not emit source maps for the block. // We add the location to preserve comments. var body = ts.createBlock(ts.createNodeArray(statements, /*location*/ statementsLocation), /*location*/ bodyLocation); - setNodeEmitFlags(body, 1536 /* NoSourceMap */ | 12288 /* NoTokenSourceMaps */); + ts.setEmitFlags(body, 1536 /* NoSourceMap */ | 12288 /* NoTokenSourceMaps */); var forStatement = ts.createFor(ts.createVariableDeclarationList([ ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0), /*location*/ ts.moveRangePos(node.expression, -1)), ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression, /*location*/ node.expression) @@ -50562,7 +52038,7 @@ var ts; /*location*/ node.expression), ts.createPostfixIncrement(counter, /*location*/ node.expression), body, /*location*/ node); // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter. - setNodeEmitFlags(forStatement, 8192 /* NoTokenTrailingSourceMaps */); + ts.setEmitFlags(forStatement, 8192 /* NoTokenTrailingSourceMaps */); return forStatement; } /** @@ -50591,7 +52067,7 @@ var ts; var temp = ts.createTempVariable(hoistVariableDeclaration); // Write out the first non-computed properties, then emit the rest through indexing on the temp variable. var expressions = []; - var assignment = ts.createAssignment(temp, setNodeEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), /*location*/ undefined, node.multiLine), 524288 /* Indented */)); if (node.multiLine) { assignment.startsOnNewLine = true; @@ -50698,7 +52174,7 @@ var ts; loopBody = ts.createBlock([loopBody], /*location*/ undefined, /*multiline*/ true); } var isAsyncBlockContainingAwait = enclosingNonArrowFunction - && (enclosingNonArrowFunction.emitFlags & 2097152 /* AsyncFunctionBody */) !== 0 + && (ts.getEmitFlags(enclosingNonArrowFunction) & 2097152 /* AsyncFunctionBody */) !== 0 && (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; var loopBodyFlags = 0; if (currentState.containsLexicalThis) { @@ -50710,7 +52186,7 @@ var ts; var convertedLoopVariable = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(functionName, - /*type*/ undefined, setNodeEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37 /* AsteriskToken */) : undefined, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37 /* AsteriskToken */) : undefined, /*name*/ undefined, /*typeParameters*/ undefined, loopParameters, /*type*/ undefined, loopBody), loopBodyFlags)) @@ -50756,8 +52232,8 @@ var ts; extraVariableDeclarations = []; } // hoist collected variable declarations - for (var name_38 in currentState.hoistedLocalVariables) { - var identifier = currentState.hoistedLocalVariables[name_38]; + for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { + var identifier = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } @@ -50767,8 +52243,8 @@ var ts; if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _b = 0, loopOutParameters_1 = loopOutParameters; _b < loopOutParameters_1.length; _b++) { - var outParam = loopOutParameters_1[_b]; + for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { + var outParam = loopOutParameters_1[_d]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } @@ -51003,7 +52479,7 @@ var ts; // Methods with computed property names are handled in visitObjectLiteralExpression. ts.Debug.assert(!ts.isComputedPropertyName(node.name)); var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined); - setNodeEmitFlags(functionExpression, 16384 /* NoLeadingComments */ | getNodeEmitFlags(functionExpression)); + ts.setEmitFlags(functionExpression, 16384 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression)); return ts.createPropertyAssignment(node.name, functionExpression, /*location*/ node); } @@ -51040,9 +52516,19 @@ var ts; * @param node a CallExpression. */ function visitCallExpression(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); + } + function visitImmediateSuperCallInBody(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false); + } + function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 95 /* SuperKeyword */) { + ts.setEmitFlags(thisArg, 128 /* NoSubstitution */); + } + var resultingCall; if (node.transformFlags & 262144 /* ContainsSpreadElementExpression */) { // [source] // f(...a, b) @@ -51057,7 +52543,7 @@ var ts; // _super.apply(this, a.concat([b])) // _super.m.apply(this, a.concat([b])) // _super.prototype.m.apply(this, a.concat([b])) - return ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); + resultingCall = ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); } else { // [source] @@ -51069,9 +52555,18 @@ var ts; // _super.call(this, a) // _super.m.call(this, a) // _super.prototype.m.call(this, a) - return ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + resultingCall = ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), /*location*/ node); } + if (node.expression.kind === 95 /* SuperKeyword */) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 128 /* NoSubstitution */); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + return assignToCapturedThis + ? ts.createAssignment(ts.createIdentifier("_this"), initializer) + : initializer; + } + return resultingCall; } /** * Visits a NewExpression that contains a spread element. @@ -51313,13 +52808,13 @@ var ts; * * @param node The node to be printed. */ - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedEnclosingFunction = enclosingFunction; if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) { // If we are tracking a captured `this`, keep track of the enclosing function. enclosingFunction = node; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); enclosingFunction = savedEnclosingFunction; } /** @@ -51356,9 +52851,9 @@ var ts; * @param isExpression A value indicating whether the node is to be used in an expression * position. */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } if (ts.isIdentifier(node)) { @@ -51434,7 +52929,7 @@ var ts; function substituteThisKeyword(node) { if (enabledSubstitutions & 1 /* CapturedThis */ && enclosingFunction - && enclosingFunction.emitFlags & 256 /* CapturesThis */) { + && ts.getEmitFlags(enclosingFunction) & 256 /* CapturesThis */) { return ts.createIdentifier("_this", /*location*/ node); } return node; @@ -51461,7 +52956,7 @@ var ts; function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { if (node.name && !ts.isGeneratedIdentifier(node.name)) { var name_39 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); + emitFlags |= ts.getEmitFlags(node.name); if (!allowSourceMaps) { emitFlags |= 1536 /* NoSourceMap */; } @@ -51469,7 +52964,7 @@ var ts; emitFlags |= 49152 /* NoComments */; } if (emitFlags) { - setNodeEmitFlags(name_39, emitFlags); + ts.setEmitFlags(name_39, emitFlags); } return name_39; } @@ -51552,13 +53047,6 @@ var ts; return transformers; } ts.getTransformers = getTransformers; - /** - * Tracks a monotonically increasing transformation id used to associate a node with a specific - * transformation. This ensures transient properties related to transformations can be safely - * stored on source tree nodes that may be reused across multiple transformations (such as - * with compile-on-save). - */ - var nextTransformId = 1; /** * Transforms an array of SourceFiles by passing them through each transformer. * @@ -51568,16 +53056,9 @@ var ts; * @param transforms An array of Transformers. */ function transformFiles(resolver, host, sourceFiles, transformers) { - var transformId = nextTransformId; - nextTransformId++; - var tokenSourceMapRanges = ts.createMap(); var lexicalEnvironmentVariableDeclarationsStack = []; var lexicalEnvironmentFunctionDeclarationsStack = []; var enabledSyntaxKindFeatures = new Array(289 /* Count */); - var parseTreeNodesWithAnnotations = []; - var lastTokenSourceMapRangeNode; - var lastTokenSourceMapRangeToken; - var lastTokenSourceMapRange; var lexicalEnvironmentStackOffset = 0; var hoistedVariableDeclarations; var hoistedFunctionDeclarations; @@ -51588,56 +53069,27 @@ var ts; getCompilerOptions: function () { return host.getCompilerOptions(); }, getEmitResolver: function () { return resolver; }, getEmitHost: function () { return host; }, - getNodeEmitFlags: getNodeEmitFlags, - setNodeEmitFlags: setNodeEmitFlags, - getSourceMapRange: getSourceMapRange, - setSourceMapRange: setSourceMapRange, - getTokenSourceMapRange: getTokenSourceMapRange, - setTokenSourceMapRange: setTokenSourceMapRange, - getCommentRange: getCommentRange, - setCommentRange: setCommentRange, hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, startLexicalEnvironment: startLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, - onSubstituteNode: onSubstituteNode, + onSubstituteNode: function (emitContext, node) { return node; }, enableSubstitution: enableSubstitution, isSubstitutionEnabled: isSubstitutionEnabled, - onEmitNode: onEmitNode, + onEmitNode: function (node, emitContext, emitCallback) { return emitCallback(node, emitContext); }, enableEmitNotification: enableEmitNotification, isEmitNotificationEnabled: isEmitNotificationEnabled }; // Chain together and initialize each transformer. - var transformation = chain.apply(void 0, transformers)(context); + var transformation = ts.chain.apply(void 0, transformers)(context); // Transform each source file. var transformed = ts.map(sourceFiles, transformSourceFile); // Disable modification of the lexical environment. lexicalEnvironmentDisabled = true; return { - getSourceFiles: function () { return transformed; }, - getTokenSourceMapRange: getTokenSourceMapRange, - isSubstitutionEnabled: isSubstitutionEnabled, - isEmitNotificationEnabled: isEmitNotificationEnabled, - onSubstituteNode: context.onSubstituteNode, - onEmitNode: context.onEmitNode, - dispose: function () { - // During transformation we may need to annotate a parse tree node with transient - // transformation properties. As parse tree nodes live longer than transformation - // nodes, we need to make sure we reclaim any memory allocated for custom ranges - // from these nodes to ensure we do not hold onto entire subtrees just for position - // information. We also need to reset these nodes to a pre-transformation state - // for incremental parsing scenarios so that we do not impact later emit. - for (var _i = 0, parseTreeNodesWithAnnotations_1 = parseTreeNodesWithAnnotations; _i < parseTreeNodesWithAnnotations_1.length; _i++) { - var node = parseTreeNodesWithAnnotations_1[_i]; - if (node.transformId === transformId) { - node.transformId = 0; - node.emitFlags = 0; - node.commentRange = undefined; - node.sourceMapRange = undefined; - } - } - parseTreeNodesWithAnnotations.length = 0; - } + transformed: transformed, + emitNodeWithSubstitution: emitNodeWithSubstitution, + emitNodeWithNotification: emitNodeWithNotification }; /** * Transforms a source file. @@ -51660,17 +53112,27 @@ var ts; * Determines whether expression substitutions are enabled for the provided node. */ function isSubstitutionEnabled(node) { - return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0; + return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0 + && (ts.getEmitFlags(node) & 128 /* NoSubstitution */) === 0; } /** - * Default hook for node substitutions. + * Emits a node with possible substitution. * - * @param node The node to substitute. - * @param isExpression A value indicating whether the node is to be used in an expression - * position. + * @param emitContext The current emit context. + * @param node The node to emit. + * @param emitCallback The callback used to emit the node or its substitute. */ - function onSubstituteNode(node, isExpression) { - return node; + function emitNodeWithSubstitution(emitContext, node, emitCallback) { + if (node) { + if (isSubstitutionEnabled(node)) { + var substitute = context.onSubstituteNode(emitContext, node); + if (substitute && substitute !== node) { + emitCallback(emitContext, substitute); + return; + } + } + emitCallback(emitContext, node); + } } /** * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind. @@ -51684,141 +53146,24 @@ var ts; */ function isEmitNotificationEnabled(node) { return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0 - || (getNodeEmitFlags(node) & 64 /* AdviseOnEmitNode */) !== 0; + || (ts.getEmitFlags(node) & 64 /* AdviseOnEmitNode */) !== 0; } /** - * Default hook for node emit. + * Emits a node with possible emit notification. * + * @param emitContext The current emit context. * @param node The node to emit. - * @param emit A callback used to emit the node in the printer. + * @param emitCallback The callback used to emit the node. */ - function onEmitNode(node, emit) { - emit(node); - } - /** - * Associates a node with the current transformation, initializing - * various transient transformation properties. - * - * @param node The node. - */ - function beforeSetAnnotation(node) { - if ((node.flags & 8 /* Synthesized */) === 0 && node.transformId !== transformId) { - // To avoid holding onto transformation artifacts, we keep track of any - // parse tree node we are annotating. This allows us to clean them up after - // all transformations have completed. - parseTreeNodesWithAnnotations.push(node); - node.transformId = transformId; - } - } - /** - * Gets flags that control emit behavior of a node. - * - * If the node does not have its own NodeEmitFlags set, the node emit flags of its - * original pointer are used. - * - * @param node The node. - */ - function getNodeEmitFlags(node) { - return node.emitFlags; - } - /** - * Sets flags that control emit behavior of a node. - * - * @param node The node. - * @param emitFlags The NodeEmitFlags for the node. - */ - function setNodeEmitFlags(node, emitFlags) { - beforeSetAnnotation(node); - node.emitFlags = emitFlags; - return node; - } - /** - * Gets a custom text range to use when emitting source maps. - * - * If a node does not have its own custom source map text range, the custom source map - * text range of its original pointer is used. - * - * @param node The node. - */ - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - /** - * Sets a custom text range to use when emitting source maps. - * - * @param node The node. - * @param range The text range. - */ - function setSourceMapRange(node, range) { - beforeSetAnnotation(node); - node.sourceMapRange = range; - return node; - } - /** - * Gets the TextRange to use for source maps for a token of a node. - * - * If a node does not have its own custom source map text range for a token, the custom - * source map text range for the token of its original pointer is used. - * - * @param node The node. - * @param token The token. - */ - function getTokenSourceMapRange(node, token) { - // As a performance optimization, use the cached value of the most recent node. - // This helps for cases where this function is called repeatedly for the same node. - if (lastTokenSourceMapRangeNode === node && lastTokenSourceMapRangeToken === token) { - return lastTokenSourceMapRange; - } - // Get the custom token source map range for a node or from one of its original nodes. - // Custom token ranges are not stored on the node to avoid the GC burden. - var range; - var current = node; - while (current) { - range = current.id ? tokenSourceMapRanges[current.id + "-" + token] : undefined; - if (range !== undefined) { - break; + function emitNodeWithNotification(emitContext, node, emitCallback) { + if (node) { + if (isEmitNotificationEnabled(node)) { + context.onEmitNode(emitContext, node, emitCallback); + } + else { + emitCallback(emitContext, node); } - current = current.original; } - // Cache the most recently requested value. - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - return range; - } - /** - * Sets the TextRange to use for source maps for a token of a node. - * - * @param node The node. - * @param token The token. - * @param range The text range. - */ - function setTokenSourceMapRange(node, token, range) { - // Cache the most recently requested value. - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - tokenSourceMapRanges[ts.getNodeId(node) + "-" + token] = range; - return node; - } - /** - * Gets a custom text range to use when emitting comments. - * - * If a node does not have its own custom source map text range, the custom source map - * text range of its original pointer is used. - * - * @param node The node. - */ - function getCommentRange(node) { - return node.commentRange || node; - } - /** - * Sets a custom text range to use when emitting comments. - */ - function setCommentRange(node, range) { - beforeSetAnnotation(node); - node.commentRange = range; - return node; } /** * Records a hoisted variable declaration for the provided name within a lexical environment. @@ -51891,95 +53236,12 @@ var ts; } } ts.transformFiles = transformFiles; - function chain(a, b, c, d, e) { - if (e) { - var args_3 = []; - for (var i = 0; i < arguments.length; i++) { - args_3[i] = arguments[i]; - } - return function (t) { return compose.apply(void 0, ts.map(args_3, function (f) { return f(t); })); }; - } - else if (d) { - return function (t) { return compose(a(t), b(t), c(t), d(t)); }; - } - else if (c) { - return function (t) { return compose(a(t), b(t), c(t)); }; - } - else if (b) { - return function (t) { return compose(a(t), b(t)); }; - } - else if (a) { - return function (t) { return compose(a(t)); }; - } - else { - return function (t) { return function (u) { return u; }; }; - } - } - function compose(a, b, c, d, e) { - if (e) { - var args_4 = []; - for (var i = 0; i < arguments.length; i++) { - args_4[i] = arguments[i]; - } - return function (t) { return ts.reduceLeft(args_4, function (u, f) { return f(u); }, t); }; - } - else if (d) { - return function (t) { return d(c(b(a(t)))); }; - } - else if (c) { - return function (t) { return c(b(a(t))); }; - } - else if (b) { - return function (t) { return b(a(t)); }; - } - else if (a) { - return function (t) { return a(t); }; - } - else { - return function (t) { return t; }; - } - } var _a; })(ts || (ts = {})); /// /* @internal */ var ts; (function (ts) { - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - if (compilerOptions.extendedDiagnostics) { - return createSourceMapWriterWithExtendedDiagnostics(host, writer); - } - return createSourceMapWriterWorker(host, writer); - } - else { - return getNullSourceMapWriter(); - } - } - ts.createSourceMapWriter = createSourceMapWriter; - var nullSourceMapWriter; - function getNullSourceMapWriter() { - if (nullSourceMapWriter === undefined) { - nullSourceMapWriter = { - initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, - reset: function () { }, - getSourceMapData: function () { return undefined; }, - setSourceFile: function (sourceFile) { }, - emitPos: function (pos) { }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitTokenStart: function (token, pos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - emitTokenEnd: function (token, end, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - changeEmitSourcePos: function () { }, - stopOverridingSpan: function () { }, - getText: function () { return undefined; }, - getSourceMappingURL: function () { return undefined; } - }; - } - return nullSourceMapWriter; - } - ts.getNullSourceMapWriter = getNullSourceMapWriter; // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans var defaultLastEncodedSourceMapSpan = { emittedLine: 1, @@ -51988,14 +53250,12 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function createSourceMapWriterWorker(host, writer) { + function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var currentSourceText; var sourceMapDir; // The directory in which sourcemap will be - var stopOverridingSpan = false; - var modifyLastSourcePos = false; // Current source map file and its index in the sources list var sourceMapSourceIndex; // Last recorded and encoded spans @@ -52004,24 +53264,15 @@ var ts; var lastEncodedNameIndex; // Source map data var sourceMapData; - // This keeps track of the number of times `disable` has been called without a - // corresponding call to `enable`. As long as this value is non-zero, mappings will not - // be recorded. - // This is primarily used to provide a better experience when debugging binding - // patterns and destructuring assignments for simple expressions. - var disableDepth; + var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { initialize: initialize, reset: reset, getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, - emitStart: emitStart, - emitEnd: emitEnd, - emitTokenStart: emitTokenStart, - emitTokenEnd: emitTokenEnd, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: function () { return stopOverridingSpan = true; }, + emitNodeWithSourceMap: emitNodeWithSourceMap, + emitTokenWithSourceMap: emitTokenWithSourceMap, getText: getText, getSourceMappingURL: getSourceMappingURL }; @@ -52034,12 +53285,14 @@ var ts; * @param isBundledEmit A value indicating whether the generated output file is a bundle. */ function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (disabled) { + return; + } if (sourceMapData) { reset(); } currentSourceFile = undefined; currentSourceText = undefined; - disableDepth = 0; // Current source map file and its index in the sources list sourceMapSourceIndex = -1; // Last recorded and encoded spans @@ -52093,6 +53346,9 @@ var ts; * Reset the SourceMapWriter to an empty state. */ function reset() { + if (disabled) { + return; + } currentSourceFile = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; @@ -52100,56 +53356,6 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; - disableDepth = 0; - } - /** - * Re-enables the recording of mappings. - */ - function enable() { - if (disableDepth > 0) { - disableDepth--; - } - } - /** - * Disables the recording of mappings. - */ - function disable() { - disableDepth++; - } - function updateLastEncodedAndRecordedSpans() { - if (modifyLastSourcePos) { - // Reset the source pos - modifyLastSourcePos = false; - // Change Last recorded Map with last encoded emit line and character - lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; - lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; - // Pop sourceMapDecodedMappings to remove last entry - sourceMapData.sourceMapDecodedMappings.pop(); - // Point the lastEncodedSourceMapSpace to the previous encoded sourceMapSpan - // If the list is empty which indicates that we are at the beginning of the file, - // we have to reset it to default value (same value when we first initialize sourceMapWriter) - lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? - sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : - defaultLastEncodedSourceMapSpan; - // TODO: Update lastEncodedNameIndex - // Since we dont support this any more, lets not worry about it right now. - // When we start supporting nameIndex, we will get back to this - // Change the encoded source map - var sourceMapMappings = sourceMapData.sourceMapMappings; - var lenthToSet = sourceMapMappings.length - 1; - for (; lenthToSet >= 0; lenthToSet--) { - var currentChar = sourceMapMappings.charAt(lenthToSet); - if (currentChar === ",") { - // Separator for the entry found - break; - } - if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { - // Last line separator found - break; - } - } - sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); - } } // Encoding for sourcemap span function encodeLastRecordedSourceMapSpan() { @@ -52197,7 +53403,7 @@ var ts; * @param pos The position. */ function emitPos(pos) { - if (ts.positionIsSynthesized(pos) || disableDepth > 0) { + if (disabled || ts.positionIsSynthesized(pos)) { return; } if (extendedDiagnostics) { @@ -52226,84 +53432,78 @@ var ts; sourceColumn: sourceLinePos.character, sourceIndex: sourceMapSourceIndex }; - stopOverridingSpan = false; } - else if (!stopOverridingSpan) { + else { // Take the new pos instead since there is no change in emittedLine and column since last location lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } - updateLastEncodedAndRecordedSpans(); if (extendedDiagnostics) { ts.performance.mark("afterSourcemap"); ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); } } - function getStartPosPastDecorators(range) { - var rangeHasDecorators = !!range.decorators; - return ts.skipTrivia(currentSourceText, rangeHasDecorators ? range.decorators.end : range.pos); - } - function emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(getStartPosPastDecorators(range)); - } - if (ignoreChildrenCallback(contextNode)) { - disable(); - } + /** + * Emits a node with possible leading and trailing source maps. + * + * @param node The node to emit. + * @param emitCallback The callback used to emit the node. + */ + function emitNodeWithSourceMap(emitContext, node, emitCallback) { + if (disabled) { + return emitCallback(emitContext, node); } - else { - emitPos(getStartPosPastDecorators(range)); + if (node) { + var emitNode = node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var _a = emitNode && emitNode.sourceMapRange || node, pos = _a.pos, end = _a.end; + if (node.kind !== 287 /* NotEmittedStatement */ + && (emitFlags & 512 /* NoLeadingSourceMap */) === 0 + && pos >= 0) { + emitPos(ts.skipTrivia(currentSourceText, pos)); + } + if (emitFlags & 2048 /* NoNestedSourceMaps */) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; + } + else { + emitCallback(emitContext, node); + } + if (node.kind !== 287 /* NotEmittedStatement */ + && (emitFlags & 1024 /* NoTrailingSourceMap */) === 0 + && end >= 0) { + emitPos(end); + } } } - function emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (ignoreChildrenCallback(contextNode)) { - enable(); - } - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(range.end); - } + /** + * Emits a token of a node with possible leading and trailing source maps. + * + * @param node The node containing the token. + * @param token The token to emit. + * @param tokenStartPos The start pos of the token. + * @param emitCallback The callback used to emit the token. + */ + function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + if (disabled) { + return emitCallback(token, tokenPos); } - else { - emitPos(range.end); + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + tokenPos = ts.skipTrivia(currentSourceText, range ? range.pos : tokenPos); + if ((emitFlags & 4096 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - stopOverridingSpan = false; - } - function emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return ts.skipTrivia(currentSourceText, tokenStartPos); - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenStartPos = range.pos; - } + tokenPos = emitCallback(token, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 8192 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - tokenStartPos = ts.skipTrivia(currentSourceText, tokenStartPos); - emitPos(tokenStartPos); - return tokenStartPos; - } - function emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return tokenEndPos; - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenEndPos = range.end; - } - } - emitPos(tokenEndPos); - return tokenEndPos; - } - // @deprecated - function changeEmitSourcePos() { - ts.Debug.assert(!modifyLastSourcePos); - modifyLastSourcePos = true; + return tokenPos; } /** * Set the current source file. @@ -52311,6 +53511,9 @@ var ts; * @param sourceFile The source file. */ function setSourceFile(sourceFile) { + if (disabled) { + return; + } currentSourceFile = sourceFile; currentSourceText = currentSourceFile.text; // Add the file to tsFilePaths @@ -52334,6 +53537,9 @@ var ts; * Gets the text for the source map. */ function getText() { + if (disabled) { + return; + } encodeLastRecordedSourceMapSpan(); return ts.stringify({ version: 3, @@ -52349,6 +53555,9 @@ var ts; * Gets the SourceMappingURL for the source map. */ function getSourceMappingURL() { + if (disabled) { + return; + } if (compilerOptions.inlineSourceMap) { // Encode the sourceMap into the sourceMap url var base64SourceMapText = ts.convertToBase64(getText()); @@ -52359,46 +53568,7 @@ var ts; } } } - function createSourceMapWriterWithExtendedDiagnostics(host, writer) { - var _a = createSourceMapWriterWorker(host, writer), initialize = _a.initialize, reset = _a.reset, getSourceMapData = _a.getSourceMapData, setSourceFile = _a.setSourceFile, emitPos = _a.emitPos, emitStart = _a.emitStart, emitEnd = _a.emitEnd, emitTokenStart = _a.emitTokenStart, emitTokenEnd = _a.emitTokenEnd, changeEmitSourcePos = _a.changeEmitSourcePos, stopOverridingSpan = _a.stopOverridingSpan, getText = _a.getText, getSourceMappingURL = _a.getSourceMappingURL; - return { - initialize: initialize, - reset: reset, - getSourceMapData: getSourceMapData, - setSourceFile: setSourceFile, - emitPos: function (pos) { - ts.performance.mark("sourcemapStart"); - emitPos(pos); - ts.performance.measure("sourceMapTime", "sourcemapStart"); - }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitStart"); - emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitStart"); - }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitEnd"); - emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitEnd"); - }, - emitTokenStart: function (token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenStart"); - tokenStartPos = emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenStart"); - return tokenStartPos; - }, - emitTokenEnd: function (token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenEnd"); - tokenEndPos = emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenEnd"); - return tokenEndPos; - }, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: stopOverridingSpan, - getText: getText, - getSourceMappingURL: getSourceMappingURL - }; - } + ts.createSourceMapWriter = createSourceMapWriter; var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64FormatEncode(inValue) { if (inValue < 64) { @@ -52457,21 +53627,23 @@ var ts; emitBodyWithDetachedComments: emitBodyWithDetachedComments, emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition }; - function emitNodeWithComments(node, emitCallback) { + function emitNodeWithComments(emitContext, node, emitCallback) { if (disabled) { - emitCallback(node); + emitCallback(emitContext, node); return; } if (node) { - var _a = node.commentRange || node, pos = _a.pos, end = _a.end; - var emitFlags = node.emitFlags; + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var emitFlags = ts.getEmitFlags(node); if ((pos < 0 && end < 0) || (pos === end)) { // Both pos and end are synthesized, so just emit the node without comments. if (emitFlags & 65536 /* NoNestedComments */) { - disableCommentsAndEmit(node, emitCallback); + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } } else { @@ -52505,10 +53677,12 @@ var ts; ts.performance.measure("commentTime", "preEmitNodeWithComment"); } if (emitFlags & 65536 /* NoNestedComments */) { - disableCommentsAndEmit(node, emitCallback); + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } if (extendedDiagnostics) { ts.performance.mark("beginEmitNodeWithComment"); @@ -52533,7 +53707,7 @@ var ts; ts.performance.mark("preEmitBodyWithDetachedComments"); } var pos = detachedRange.pos, end = detachedRange.end; - var emitFlags = node.emitFlags; + var emitFlags = ts.getEmitFlags(node); var skipLeadingComments = pos < 0 || (emitFlags & 16384 /* NoLeadingComments */) !== 0; var skipTrailingComments = disabled || end < 0 || (emitFlags & 32768 /* NoTrailingComments */) !== 0; if (!skipLeadingComments) { @@ -52542,8 +53716,10 @@ var ts; if (extendedDiagnostics) { ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); } - if (emitFlags & 65536 /* NoNestedComments */) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 65536 /* NoNestedComments */ && !disabled) { + disabled = true; + emitCallback(node); + disabled = false; } else { emitCallback(node); @@ -52664,16 +53840,6 @@ var ts; currentLineMap = ts.getLineStarts(currentSourceFile); detachedCommentsInfo = undefined; } - function disableCommentsAndEmit(node, emitCallback) { - if (disabled) { - emitCallback(node); - } - else { - disabled = true; - emitCallback(node); - disabled = false; - } - } function hasDetachedComments(pos) { return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; } @@ -52735,11 +53901,11 @@ var ts; return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, /*emitOnlyDtsFiles*/ false); } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -52786,7 +53952,7 @@ var ts; // global file reference is added only // - if it is not bundled emit (because otherwise it would be self reference) // - and it is not already added - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { addedGlobalFileReference = true; } emittedReferencedFiles.push(referencedFile); @@ -52987,7 +54153,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); errorNameNode = undefined; } } @@ -53000,7 +54166,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); errorNameNode = undefined; } } @@ -53202,7 +54368,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -53624,7 +54790,7 @@ var ts; } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); } function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; @@ -54265,7 +55431,7 @@ var ts; * @param referencedFile * @param addBundledFileReference Determines if global file reference corresponding to bundled file should be emitted or not */ - function writeReferencePath(referencedFile, addBundledFileReference) { + function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; if (ts.isDeclarationFile(referencedFile)) { @@ -54274,7 +55440,7 @@ var ts; } else { // Get the declaration file path - ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); } if (declFileName) { declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -54294,8 +55460,8 @@ var ts; } } /* @internal */ - function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencesOutput @@ -54335,8 +55501,10 @@ var ts; TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; TempFlags[TempFlags["_i"] = 268435456] = "_i"; })(TempFlags || (TempFlags = {})); + var id = function (s) { return s; }; + var nullTransformers = [function (ctx) { return id; }]; // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature - function emitFiles(resolver, host, targetSourceFile) { + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) { var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); // emit output for the __extends helper function @@ -54352,7 +55520,7 @@ var ts; // emit output for the __param helper function var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; // emit output for the __awaiter helper function - var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; + var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; // The __generator helper is used by down-level transformations to emulate the runtime // semantics of an ES2015 generator function. When called, this helper returns an // object that implements the Iterator protocol, in that it has `next`, `return`, and @@ -54426,11 +55594,11 @@ var ts; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); var newLine = host.getNewLine(); - var transformers = ts.getTransformers(compilerOptions); + var transformers = emitOnlyDtsFiles ? nullTransformers : ts.getTransformers(compilerOptions); var writer = ts.createTextWriter(newLine); var write = writer.write, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; var sourceMap = ts.createSourceMapWriter(host, writer); - var emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitTokenStart = sourceMap.emitTokenStart, emitTokenEnd = sourceMap.emitTokenEnd; + var emitNodeWithSourceMap = sourceMap.emitNodeWithSourceMap, emitTokenWithSourceMap = sourceMap.emitTokenWithSourceMap; var comments = ts.createCommentWriter(host, writer, sourceMap); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; var nodeIdToGeneratedName; @@ -54447,18 +55615,20 @@ var ts; var awaiterEmitted; var isOwnFileEmit; var emitSkipped = false; - ts.performance.mark("beforeTransform"); + var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); // Transform the source files - var transformed = ts.transformFiles(resolver, host, ts.getSourceFilesToEmit(host, targetSourceFile), transformers); + ts.performance.mark("beforeTransform"); + var _a = ts.transformFiles(resolver, host, sourceFiles, transformers), transformed = _a.transformed, emitNodeWithSubstitution = _a.emitNodeWithSubstitution, emitNodeWithNotification = _a.emitNodeWithNotification; ts.performance.measure("transformTime", "beforeTransform"); - // Extract helpers from the result - var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode; - ts.performance.mark("beforePrint"); // Emit each output file - ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile); - // Clean up after transformation - transformed.dispose(); + ts.performance.mark("beforePrint"); + ts.forEachTransformedEmitFile(host, transformed, emitFile, emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); + // Clean up emit nodes on parse tree + for (var _b = 0, sourceFiles_4 = sourceFiles; _b < sourceFiles_4.length; _b++) { + var sourceFile = sourceFiles_4[_b]; + ts.disposeEmitNodes(sourceFile); + } return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -54468,16 +55638,20 @@ var ts; function emitFile(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, isBundledEmit) { // Make sure not to write js file and source map file if any of them cannot be written if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + if (!emitOnlyDtsFiles) { + printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } } else { emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; } if (!emitSkipped && emittedFilesList) { - emittedFilesList.push(jsFilePath); + if (!emitOnlyDtsFiles) { + emittedFilesList.push(jsFilePath); + } if (sourceMapFilePath) { emittedFilesList.push(sourceMapFilePath); } @@ -54494,8 +55668,8 @@ var ts; isOwnFileEmit = !isBundledEmit; // Emit helpers from all the files if (isBundledEmit && moduleKind) { - for (var _a = 0, sourceFiles_4 = sourceFiles; _a < sourceFiles_4.length; _a++) { - var sourceFile = sourceFiles_4[_a]; + for (var _a = 0, sourceFiles_5 = sourceFiles; _a < sourceFiles_5.length; _a++) { + var sourceFile = sourceFiles_5[_a]; emitEmitHelpers(sourceFile); } } @@ -54536,135 +55710,124 @@ var ts; currentFileIdentifiers = node.identifiers; sourceMap.setSourceFile(node); comments.setSourceFile(node); - emitNodeWithNotification(node, emitWorker); + pipelineEmitWithNotification(0 /* SourceFile */, node); } /** * Emits a node. */ function emit(node) { - emitNodeWithNotification(node, emitWithComments); + pipelineEmitWithNotification(3 /* Unspecified */, node); } /** - * Emits a node with comments. - * - * NOTE: Do not call this method directly. It is part of the emit pipeline - * and should only be called indirectly from emit. + * Emits an IdentifierName. */ - function emitWithComments(node) { - emitNodeWithComments(node, emitWithSourceMap); - } - /** - * Emits a node with source maps. - * - * NOTE: Do not call this method directly. It is part of the emit pipeline - * and should only be called indirectly from emitWithComments. - */ - function emitWithSourceMap(node) { - emitNodeWithSourceMap(node, emitWorker); - } function emitIdentifierName(node) { - if (node) { - emitNodeWithNotification(node, emitIdentifierNameWithComments); - } - } - function emitIdentifierNameWithComments(node) { - emitNodeWithComments(node, emitWorker); + pipelineEmitWithNotification(2 /* IdentifierName */, node); } /** * Emits an expression node. */ function emitExpression(node) { - emitNodeWithNotification(node, emitExpressionWithComments); + pipelineEmitWithNotification(1 /* Expression */, node); } /** - * Emits an expression with comments. + * Emits a node with possible notification. * - * NOTE: Do not call this method directly. It is part of the emitExpression pipeline - * and should only be called indirectly from emitExpression. + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called from printSourceFile, emit, emitExpression, or + * emitIdentifierName. */ - function emitExpressionWithComments(node) { - emitNodeWithComments(node, emitExpressionWithSourceMap); + function pipelineEmitWithNotification(emitContext, node) { + emitNodeWithNotification(emitContext, node, pipelineEmitWithComments); } /** - * Emits an expression with source maps. + * Emits a node with comments. * - * NOTE: Do not call this method directly. It is part of the emitExpression pipeline - * and should only be called indirectly from emitExpressionWithComments. + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithNotification. */ - function emitExpressionWithSourceMap(node) { - emitNodeWithSourceMap(node, emitExpressionWorker); - } - /** - * Emits a node with emit notification if available. - */ - function emitNodeWithNotification(node, emitCallback) { - if (node) { - if (isEmitNotificationEnabled(node)) { - onEmitNode(node, emitCallback); - } - else { - emitCallback(node); - } - } - } - function emitNodeWithSourceMap(node, emitCallback) { - if (node) { - emitStart(/*range*/ node, /*contextNode*/ node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - emitCallback(node); - emitEnd(/*range*/ node, /*contextNode*/ node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - /** - * Determines whether to skip leading comment emit for a node. - * - * We do not emit comments for NotEmittedStatement nodes or any node that has - * NodeEmitFlags.NoLeadingComments. - * - * @param node A Node. - */ - function shouldSkipLeadingCommentsForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 16384 /* NoLeadingComments */) !== 0; - } - /** - * Determines whether to skip source map emit for the start position of a node. - * - * We do not emit source maps for NotEmittedStatement nodes or any node that - * has NodeEmitFlags.NoLeadingSourceMap. - * - * @param node A Node. - */ - function shouldSkipLeadingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 512 /* NoLeadingSourceMap */) !== 0; - } - /** - * Determines whether to skip source map emit for the end position of a node. - * - * We do not emit source maps for NotEmittedStatement nodes or any node that - * has NodeEmitFlags.NoTrailingSourceMap. - * - * @param node A Node. - */ - function shouldSkipTrailingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 1024 /* NoTrailingSourceMap */) !== 0; - } - /** - * Determines whether to skip source map emit for a node and its children. - * - * We do not emit source maps for a node that has NodeEmitFlags.NoNestedSourceMaps. - */ - function shouldSkipSourceMapForChildren(node) { - return (node.emitFlags & 2048 /* NoNestedSourceMaps */) !== 0; - } - function emitWorker(node) { - if (tryEmitSubstitute(node, emitWorker, /*isExpression*/ false)) { + function pipelineEmitWithComments(emitContext, node) { + // Do not emit comments for SourceFile + if (emitContext === 0 /* SourceFile */) { + pipelineEmitWithSourceMap(emitContext, node); return; } + emitNodeWithComments(emitContext, node, pipelineEmitWithSourceMap); + } + /** + * Emits a node with source maps. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithComments. + */ + function pipelineEmitWithSourceMap(emitContext, node) { + // Do not emit source mappings for SourceFile or IdentifierName + if (emitContext === 0 /* SourceFile */ + || emitContext === 2 /* IdentifierName */) { + pipelineEmitWithSubstitution(emitContext, node); + return; + } + emitNodeWithSourceMap(emitContext, node, pipelineEmitWithSubstitution); + } + /** + * Emits a node with possible substitution. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithSourceMap or + * pipelineEmitInUnspecifiedContext (when picking a more specific context). + */ + function pipelineEmitWithSubstitution(emitContext, node) { + emitNodeWithSubstitution(emitContext, node, pipelineEmitForContext); + } + /** + * Emits a node. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithSubstitution. + */ + function pipelineEmitForContext(emitContext, node) { + switch (emitContext) { + case 0 /* SourceFile */: return pipelineEmitInSourceFileContext(node); + case 2 /* IdentifierName */: return pipelineEmitInIdentifierNameContext(node); + case 3 /* Unspecified */: return pipelineEmitInUnspecifiedContext(node); + case 1 /* Expression */: return pipelineEmitInExpressionContext(node); + } + } + /** + * Emits a node in the SourceFile EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInSourceFileContext(node) { + var kind = node.kind; + switch (kind) { + // Top-level nodes + case 256 /* SourceFile */: + return emitSourceFile(node); + } + } + /** + * Emits a node in the IdentifierName EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInIdentifierNameContext(node) { + var kind = node.kind; + switch (kind) { + // Identifiers + case 69 /* Identifier */: + return emitIdentifier(node); + } + } + /** + * Emits a node in the Unspecified EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInUnspecifiedContext(node) { var kind = node.kind; switch (kind) { // Pseudo-literals @@ -54696,7 +55859,8 @@ var ts; case 132 /* StringKeyword */: case 133 /* SymbolKeyword */: case 137 /* GlobalKeyword */: - return writeTokenNode(node); + writeTokenText(kind); + return; // Parse tree nodes // Names case 139 /* QualifiedName */: @@ -54886,18 +56050,20 @@ var ts; // Enum case 255 /* EnumMember */: return emitEnumMember(node); - // Top-level nodes - case 256 /* SourceFile */: - return emitSourceFile(node); } + // If the node is an expression, try to emit it as an expression with + // substitution. if (ts.isExpression(node)) { - return emitExpressionWorker(node); + return pipelineEmitWithSubstitution(1 /* Expression */, node); } } - function emitExpressionWorker(node) { - if (tryEmitSubstitute(node, emitExpressionWorker, /*isExpression*/ true)) { - return; - } + /** + * Emits a node in the Expression EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInExpressionContext(node) { var kind = node.kind; switch (kind) { // Literals @@ -54916,7 +56082,8 @@ var ts; case 95 /* SuperKeyword */: case 99 /* TrueKeyword */: case 97 /* ThisKeyword */: - return writeTokenNode(node); + writeTokenText(kind); + return; // Expressions case 170 /* ArrayLiteralExpression */: return emitArrayLiteralExpression(node); @@ -55010,7 +56177,7 @@ var ts; // Identifiers // function emitIdentifier(node) { - if (node.emitFlags & 16 /* UMDDefine */) { + if (ts.getEmitFlags(node) & 16 /* UMDDefine */) { writeLines(umdHelper); } else { @@ -55243,7 +56410,7 @@ var ts; write("{}"); } else { - var indentedFlag = node.emitFlags & 524288 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 524288 /* Indented */; if (indentedFlag) { increaseIndent(); } @@ -55256,21 +56423,18 @@ var ts; } } function emitPropertyAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } var indentBeforeDot = false; var indentAfterDot = false; - if (!(node.emitFlags & 1048576 /* NoIndentation */)) { + if (!(ts.getEmitFlags(node) & 1048576 /* NoIndentation */)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentText, node.expression.end) + 1; var dotToken = { kind: 21 /* DotToken */, pos: dotRangeStart, end: dotRangeEnd }; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } - var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); emitExpression(node.expression); increaseIndentIf(indentBeforeDot); + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); write(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); @@ -55284,17 +56448,16 @@ var ts; var text = getLiteralTextOfNode(expression); return text.indexOf(ts.tokenToString(21 /* DotToken */)) < 0; } - else { + else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { // check if constant enum value is integer - var constantValue = tryGetConstEnumValue(expression); + var constantValue = ts.getConstantValue(expression); // isFinite handles cases when constantValue is undefined - return isFinite(constantValue) && Math.floor(constantValue) === constantValue; + return isFinite(constantValue) + && Math.floor(constantValue) === constantValue + && compilerOptions.removeComments; } } function emitElementAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } emitExpression(node.expression); write("["); emitExpression(node.argumentExpression); @@ -55467,7 +56630,7 @@ var ts; } } function emitBlockStatements(node) { - if (node.emitFlags & 32 /* SingleLine */) { + if (ts.getEmitFlags(node) & 32 /* SingleLine */) { emitList(node, node.statements, 384 /* SingleLineBlockStatements */); } else { @@ -55645,11 +56808,11 @@ var ts; var body = node.body; if (body) { if (ts.isBlock(body)) { - var indentedFlag = node.emitFlags & 524288 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 524288 /* Indented */; if (indentedFlag) { increaseIndent(); } - if (node.emitFlags & 4194304 /* ReuseTempVariableScope */) { + if (ts.getEmitFlags(node) & 4194304 /* ReuseTempVariableScope */) { emitSignatureHead(node); emitBlockFunctionBody(node, body); } @@ -55687,7 +56850,7 @@ var ts; // * The body is explicitly marked as multi-line. // * A non-synthesized body's start and end position are on different lines. // * Any statement in the body starts on a new line. - if (body.emitFlags & 32 /* SingleLine */) { + if (ts.getEmitFlags(body) & 32 /* SingleLine */) { return true; } if (body.multiLine) { @@ -55743,7 +56906,7 @@ var ts; emitModifiers(node, node.modifiers); write("class"); emitNodeWithPrefix(" ", node.name, emitIdentifierName); - var indentedFlag = node.emitFlags & 524288 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 524288 /* Indented */; if (indentedFlag) { increaseIndent(); } @@ -55805,7 +56968,7 @@ var ts; emit(body); } function emitModuleBlock(node) { - if (isSingleLineEmptyBlock(node)) { + if (isEmptyBlock(node)) { write("{ }"); } else { @@ -56023,8 +57186,8 @@ var ts; // "comment1" is not considered to be leading comment for node.initializer // but rather a trailing comment on the previous node. var initializer = node.initializer; - if (!shouldSkipLeadingCommentsForNode(initializer)) { - var commentRange = initializer.commentRange || initializer; + if ((ts.getEmitFlags(initializer) & 16384 /* NoLeadingComments */) === 0) { + var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } emitExpression(initializer); @@ -56084,7 +57247,7 @@ var ts; return statements.length; } function emitHelpers(node) { - var emitFlags = node.emitFlags; + var emitFlags = ts.getEmitFlags(node); var helpersEmitted = false; if (emitFlags & 1 /* EmitEmitHelpers */) { helpersEmitted = emitEmitHelpers(currentSourceFile); @@ -56197,31 +57360,6 @@ var ts; write(suffix); } } - function tryEmitSubstitute(node, emitNode, isExpression) { - if (isSubstitutionEnabled(node) && (node.emitFlags & 128 /* NoSubstitution */) === 0) { - var substitute = onSubstituteNode(node, isExpression); - if (substitute !== node) { - substitute.emitFlags |= 128 /* NoSubstitution */; - emitNode(substitute); - return true; - } - } - return false; - } - function tryEmitConstantValue(node) { - var constantValue = tryGetConstEnumValue(node); - if (constantValue !== undefined) { - write(String(constantValue)); - if (!compilerOptions.removeComments) { - var propertyName = ts.isPropertyAccessExpression(node) - ? ts.declarationNameToString(node.name) - : getTextOfNode(node.argumentExpression); - write(" /* " + propertyName + " */"); - } - return true; - } - return false; - } function emitEmbeddedStatement(node) { if (ts.isBlock(node)) { write(" "); @@ -56329,7 +57467,7 @@ var ts; } } if (shouldEmitInterveningComments) { - var commentRange = child.commentRange || child; + var commentRange = ts.getCommentRange(child); emitTrailingCommentsOfPosition(commentRange.pos); } else { @@ -56375,27 +57513,12 @@ var ts; } } function writeToken(token, pos, contextNode) { - var tokenStartPos = emitTokenStart(token, pos, contextNode, shouldSkipLeadingSourceMapForToken, getTokenSourceMapRange); - var tokenEndPos = writeTokenText(token, tokenStartPos); - return emitTokenEnd(token, tokenEndPos, contextNode, shouldSkipTrailingSourceMapForToken, getTokenSourceMapRange); - } - function shouldSkipLeadingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 4096 /* NoTokenLeadingSourceMaps */) !== 0; - } - function shouldSkipTrailingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 8192 /* NoTokenTrailingSourceMaps */) !== 0; + return emitTokenWithSourceMap(contextNode, token, pos, writeTokenText); } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); - return ts.positionIsSynthesized(pos) ? -1 : pos + tokenString.length; - } - function writeTokenNode(node) { - if (node) { - emitStart(/*range*/ node, /*contextNode*/ node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - writeTokenText(node.kind); - emitEnd(/*range*/ node, /*contextNode*/ node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } + return pos < 0 ? pos : pos + tokenString.length; } function increaseIndentIf(value, valueToWriteWhenNotIndenting) { if (value) { @@ -56539,17 +57662,12 @@ var ts; } return ts.getLiteralText(node, currentSourceFile, languageVersion); } - function tryGetConstEnumValue(node) { - if (compilerOptions.isolatedModules) { - return undefined; - } - return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) - ? resolver.getConstantValue(node) - : undefined; - } function isSingleLineEmptyBlock(block) { return !block.multiLine - && block.statements.length === 0 + && isEmptyBlock(block); + } + function isEmptyBlock(block) { + return block.statements.length === 0 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function isUniqueName(name) { @@ -56878,695 +57996,6 @@ var ts; return ts.getNormalizedPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; - function trace(host, message) { - host.trace(ts.formatMessage.apply(undefined, arguments)); - } - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - /* @internal */ - function hasZeroOrOneAsteriskCharacter(str) { - var seenAsterisk = false; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42 /* asterisk */) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - // have already seen asterisk - return false; - } - } - } - return true; - } - ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; - } - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); - function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); - } - return typesFilePath_1; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } - } - } - } - var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); - if (typesFilePath) { - return typesFilePath; - } - // Use the main module for inferring types if no types package specified and the allowJs is set - if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); - } - var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - return mainFilePath; - } - return undefined; - } - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; - } - } - var typeReferenceExtensions = [".d.ts"]; - function getEffectiveTypeRoots(options, host) { - if (options.typeRoots) { - return options.typeRoots; - } - var currentDirectory; - if (options.configFilePath) { - currentDirectory = ts.getDirectoryPath(options.configFilePath); - } - else if (host.getCurrentDirectory) { - currentDirectory = host.getCurrentDirectory(); - } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - /** - * Returns the path to every node_modules/@types directory from some ancestor directory. - * Returns undefined if there are none. - */ - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; - } - var typeRoots; - while (true) { - var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - var parent_15 = ts.getDirectoryPath(currentDirectory); - if (parent_15 === currentDirectory) { - break; - } - currentDirectory = parent_15; - } - return typeRoots; - } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); - /** - * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. - * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups - * is assumed to be the same as root directory of the project. - */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { - compilerOptions: options, - host: host, - skipTsx: true, - traceEnabled: traceEnabled - }; - var typeRoots = getEffectiveTypeRoots(options, host); - if (traceEnabled) { - if (containingFile === undefined) { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); - } - } - else { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); - } - } - } - var failedLookupLocations = []; - // Check primary library paths - if (typeRoots && typeRoots.length) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); - } - var primarySearchPaths = typeRoots; - for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { - var typeRoot = primarySearchPaths_1[_i]; - var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); - var candidateDirectory = ts.getDirectoryPath(candidate); - var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); - if (resolvedFile_1) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); - } - return { - resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, - failedLookupLocations: failedLookupLocations - }; - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); - } - } - var resolvedFile; - var initialLocationForSecondaryLookup; - if (containingFile) { - initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); - } - if (initialLocationForSecondaryLookup !== undefined) { - // check secondary locations - if (traceEnabled) { - trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); - } - resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState); - if (traceEnabled) { - if (resolvedFile) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); - } - } - return { - resolvedTypeReferenceDirective: resolvedFile - ? { primary: false, resolvedFileName: resolvedFile } - : undefined, - failedLookupLocations: failedLookupLocations - }; - } - ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - var result; - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); - break; - case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host); - break; - } - if (traceEnabled) { - if (result.resolvedModule) { - trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - /** - * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to - * mitigate differences between design time structure of the project and its runtime counterpart so the same import name - * can be resolved successfully by TypeScript compiler and runtime module loader. - * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will - * fallback to standard resolution routine. - * - * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative - * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will - * be '/a/b/c/d' - * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names - * will be resolved based on the content of the module name. - * Structure of 'paths' compiler options - * 'paths': { - * pattern-1: [...substitutions], - * pattern-2: [...substitutions], - * ... - * pattern-n: [...substitutions] - * } - * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against - * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. - * If pattern contains '*' then to match pattern "*" module name must start with the and end with . - * denotes part of the module name between and . - * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. - * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module - * from the candidate location. - * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every - * substitution in the list and replace '*' with string. If candidate location is not rooted it - * will be converted to absolute using baseUrl. - * For example: - * baseUrl: /a/b/c - * "paths": { - * // match all module names - * "*": [ - * "*", // use matched name as is, - * // will be looked as /a/b/c/ - * - * "folder1/*" // substitution will convert matched name to 'folder1/', - * // since it is not rooted then final candidate location will be /a/b/c/folder1/ - * ], - * // match module names that start with 'components/' - * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', - * // it is rooted so it will be final candidate location - * } - * - * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if - * they were in the same location. For example lets say there are two files - * '/local/src/content/file1.ts' - * '/shared/components/contracts/src/content/protocols/file2.ts' - * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so - * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. - * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all - * root dirs were merged together. - * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. - * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: - * '/local/src/content/protocols/file2' and try to load it - failure. - * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will - * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining - * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. - */ - function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); - } - else { - return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); - } - } - function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - // rootDirs are expected to be absolute - // in case of tsconfig.json this will happen automatically - compiler will expand relative names - // using location of tsconfig.json as base location - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - // first - try to load from a initial location - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - // then try to resolve using remaining entries in rootDirs - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - // skip the initially matched entry - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - // string is for exact match - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { - var subst = _a[_i]; - var path = matchedStar ? subst.replace("*", matchedStar) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - } - return undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - /** - * patternStrings contains both pattern strings (containing "*") and regular strings. - * Return an exact match if possible, or a pattern match, or undefined. - * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) - */ - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - // pattern was matched as is - no need to search further - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - /** - * Given that candidate matches pattern, returns the text matching the '*'. - * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" - */ - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - /** Return the object corresponding to the best pattern to match `candidate`. */ - /* @internal */ - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - // use length of prefix as betterness criteria - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - /* @internal */ - function tryParsePattern(pattern) { - // This should be verified outside of here and a proper error thrown. - ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var traceEnabled = isTraceEnabled(compilerOptions, host); - var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); - var isExternalLibraryImport = false; - if (!resolvedFileName) { - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); - } - resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); - isExternalLibraryImport = resolvedFileName !== undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - } - } - if (resolvedFileName && host.realpath) { - var originalFileName = resolvedFileName; - resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); - } - } - return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); - } - var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); - return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); - } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - /** - * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary - * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. - */ - function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; - // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); - } - } - /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - return ts.forEach(extensions, function (ext) { - return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); - }); - } - /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; - } - } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); - if (typesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); - // A package.json "typings" may specify an exact filename, or may choose to omit an extension. - var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || - tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); - if (result) { - return result; - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); - } - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocation.push(packageJsonPath); - } - return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); - } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); - var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - } - function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { - directory = ts.normalizeSlashes(directory); - while (true) { - var baseName = ts.getBaseFileName(directory); - if (baseName !== "node_modules") { - // Try to load source from the package - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - // Always prefer a TypeScript (.ts, .tsx, .d.ts) file shipped with the package - return packageResult; - } - else { - // Else prefer a types package over non-TypeScript results (e.g. JavaScript files) - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; - } - } - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - break; - } - directory = parentPath; - } - return undefined; - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; - var failedLookupLocations = []; - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); - if (resolvedFileName) { - return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ false, failedLookupLocations); - } - var referencedSourceFile; - if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - } - return referencedSourceFile - ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - ts.classicNameResolver = classicNameResolver; function createCompilerHost(options, setParentNodes) { var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { @@ -57672,7 +58101,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.getEnvironmentVariable(name, /*host*/ undefined); }, + getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; @@ -57740,45 +58169,6 @@ var ts; } return resolutions; } - /** - * Given a set of options, returns the set of type directive names - * that should be included for this program automatically. - * This list could either come from the config file, - * or from enumerating the types root + initial secondary types lookup location. - * More type directives might appear in the program later as a result of loading actual source files; - * this list is only the set of defaults that are implicitly included. - */ - function getAutomaticTypeDirectiveNames(options, host) { - // Use explicit type list from tsconfig.json - if (options.types) { - return options.types; - } - // Walk the primary type lookup locations - var result = []; - if (host.directoryExists && host.getDirectories) { - var typeRoots = getEffectiveTypeRoots(options, host); - if (typeRoots) { - for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { - var root = typeRoots_1[_i]; - if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); - // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); - } - } - } - } - } - } - return result; - } - ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -57815,7 +58205,7 @@ var ts; resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; } else { - var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -57823,7 +58213,7 @@ var ts; resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; } else { - var loader_2 = function (typesRef, containingFile) { return resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; + var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); }; } var filesByName = ts.createFileMap(); @@ -57833,8 +58223,8 @@ var ts; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders - var typeReferences = getAutomaticTypeDirectiveNames(options, host); - if (typeReferences) { + var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + if (typeReferences.length) { // This containingFilename needs to match with the one used in managed-side var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); @@ -57884,7 +58274,8 @@ var ts; getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, - getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -57938,6 +58329,7 @@ var ts; (oldOptions.configFilePath !== options.configFilePath) || (oldOptions.baseUrl !== options.baseUrl) || (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || + !ts.arrayIsEqualTo(oldOptions.lib, options.lib) || !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || !ts.equalOwnProperties(oldOptions.paths, options.paths)) { @@ -58054,16 +58446,19 @@ var ts; function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); } - function emit(sourceFile, writeFileCallback, cancellationToken) { - return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); }); + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); } - function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { var declarationDiagnostics = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; @@ -58095,7 +58490,7 @@ var ts; // checked is to not pass the file to getEmitResolver. var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); ts.performance.mark("beforeEmit"); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -58659,7 +59054,6 @@ var ts; for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); - var resolvedPath = resolution ? ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName) : undefined; // add file to program only if: // - resolution was successful // - noResolve is falsy @@ -58676,7 +59070,7 @@ var ts; modulesWithElidedImports[file.path] = true; } else if (shouldAddFile) { - findSourceFile(resolution.resolvedFileName, resolvedPath, + findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /*isDefaultLib*/ false, /*isReference*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } if (isFromNodeModulesSearch) { @@ -58692,8 +59086,8 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var file = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var file = sourceFiles_6[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -58704,8 +59098,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -58748,7 +59142,7 @@ var ts; if (!ts.hasProperty(options.paths, key)) { continue; } - if (!hasZeroOrOneAsteriskCharacter(key)) { + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { @@ -58759,7 +59153,7 @@ var ts; var subst = _a[_i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { - if (!hasZeroOrOneAsteriskCharacter(subst)) { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } @@ -58799,6 +59193,9 @@ var ts; if (options.lib && options.noLib) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")); } + if (options.noImplicitUseStrict && options.alwaysStrict) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict")); + } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); @@ -58891,12 +59288,15 @@ var ts; /// var ts; (function (ts) { + /* @internal */ + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; /* @internal */ ts.optionDeclarations = [ { name: "charset", type: "string" }, + ts.compileOnSaveCommandLineOption, { name: "declaration", shortName: "d", @@ -59327,6 +59727,11 @@ var ts; name: "importHelpers", type: "boolean", description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "alwaysStrict", + type: "boolean", + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file } ]; /* @internal */ @@ -59547,10 +59952,11 @@ var ts; * @param fileName The path to the config file * @param jsonText The text of the config file */ - function parseConfigFileTextToJson(fileName, jsonText) { + function parseConfigFileTextToJson(fileName, jsonText, stripComments) { + if (stripComments === void 0) { stripComments = true; } try { - var jsonTextWithoutComments = removeComments(jsonText); - return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; + var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; + return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; @@ -59712,13 +60118,15 @@ var ts; options = ts.extend(existingOptions, options); options.configFilePath = configFileName; var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, errors: errors, - wildcardDirectories: wildcardDirectories + wildcardDirectories: wildcardDirectories, + compileOnSave: compileOnSave }; function tryExtendsName(extendedConfig) { // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) @@ -59799,6 +60207,17 @@ var ts; var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + if (typeof result === "boolean" && result) { + return result; + } + return false; + } + ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); @@ -59812,7 +60231,9 @@ var ts; } ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } + : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } @@ -60742,7 +61163,7 @@ var ts; return true; case 69 /* Identifier */: // 'this' as a parameter - return node.originalKeywordKind === 97 /* ThisKeyword */ && node.parent.kind === 142 /* Parameter */; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 142 /* Parameter */; default: return false; } @@ -61420,7 +61841,6 @@ var ts; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ -var ts; (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 142 /* Parameter */; @@ -61657,7 +62077,7 @@ var ts; return ts.ensureScriptKind(fileName, scriptKind); } ts.getScriptKind = getScriptKind; - function parseAndReEmitConfigJSONFile(content) { + function sanitizeConfigFile(configFileName, content) { var options = { fileName: "config.js", compilerOptions: { @@ -61671,14 +62091,17 @@ var ts; // also, the emitted result will have "(" in the beginning and ");" in the end. We need to strip these // as well var trimmedOutput = outputText.trim(); - var configJsonObject = JSON.parse(trimmedOutput.substring(1, trimmedOutput.length - 2)); for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; diagnostic.start = diagnostic.start - 1; } - return { configJsonObject: configJsonObject, diagnostics: diagnostics }; + var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), /*stripComments*/ false), config = _b.config, error = _b.error; + return { + configJsonObject: config || {}, + diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics + }; } - ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile; + ts.sanitizeConfigFile = sanitizeConfigFile; })(ts || (ts = {})); var ts; (function (ts) { @@ -62538,8 +62961,7 @@ var ts; return; case 142 /* Parameter */: if (token.parent.name === token) { - var isThis_1 = token.kind === 69 /* Identifier */ && token.originalKeywordKind === 97 /* ThisKeyword */; - return isThis_1 ? 3 /* keyword */ : 17 /* parameterName */; + return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; } return; } @@ -62583,14 +63005,14 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; if (isJsDocTagName) { // If the current position is a jsDoc tag name, only tag names should be provided for completion - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ false); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true); ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); } else { @@ -62619,7 +63041,7 @@ var ts; if (!isMemberCompletion && !isJsDocTagName) { ts.addRange(entries, keywordCompletions); } - return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation || ts.isSourceFileJavaScript(sourceFile), entries: entries }; + return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { var entries = []; var nameTable = ts.getNameTable(sourceFile); @@ -62690,7 +63112,9 @@ var ts; if (!node || node.kind !== 9 /* StringLiteral */) { return undefined; } - if (node.parent.kind === 253 /* PropertyAssignment */ && node.parent.parent.kind === 171 /* ObjectLiteralExpression */) { + if (node.parent.kind === 253 /* PropertyAssignment */ && + node.parent.parent.kind === 171 /* ObjectLiteralExpression */ && + node.parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { // 'jspm:dev': string @@ -62740,7 +63164,7 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } } @@ -62756,7 +63180,7 @@ var ts; } } if (entries.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; } return undefined; } @@ -62766,7 +63190,7 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/ false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } return undefined; @@ -62777,7 +63201,7 @@ var ts; var entries_2 = []; addStringLiteralCompletionsFromType(type, entries_2); if (entries_2.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } } return undefined; @@ -62819,6 +63243,7 @@ var ts; entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span); } return { + isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries @@ -62854,15 +63279,24 @@ var ts; } return result; } + /** + * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. + */ function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, span, exclude, result) { if (result === void 0) { result = []; } + if (fragment === undefined) { + fragment = ""; + } + fragment = ts.normalizeSlashes(fragment); + /** + * Remove the basename from the path. Note that we don't use the basename to filter completions; + * the client is responsible for refining completions. + */ fragment = ts.getDirectoryPath(fragment); - if (!fragment) { - fragment = "./"; - } - else { - fragment = ts.ensureTrailingDirectorySeparator(fragment); + if (fragment === "") { + fragment = "." + ts.directorySeparator; } + fragment = ts.ensureTrailingDirectorySeparator(fragment); var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment)); var baseDirectory = ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); @@ -62870,6 +63304,12 @@ var ts; // Enumerate the available files if possible var files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); if (files) { + /** + * Multiple file entries might map to the same truncated name once we remove extensions + * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: + * + * both foo.ts and foo.tsx become foo + */ var foundFiles = ts.createMap(); for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { var filePath = files_3[_i]; @@ -63039,6 +63479,19 @@ var ts; if (!range) { return undefined; } + var completionInfo = { + /** + * We don't want the editor to offer any other completions, such as snippets, inside a comment. + */ + isGlobalCompletion: false, + isMemberCompletion: false, + /** + * The user may type in a path that doesn't yet exist, creating a "new identifier" + * with respect to the collection of identifiers the server is aware of. + */ + isNewIdentifierLocation: true, + entries: [] + }; var text = sourceFile.text.substr(range.pos, position - range.pos); var match = tripleSlashDirectiveFragmentRegex.exec(text); if (match) { @@ -63046,24 +63499,18 @@ var ts; var kind = match[2]; var toComplete = match[3]; var scriptPath = ts.getDirectoryPath(sourceFile.path); - var entries_3; if (kind === "path") { // Give completions for a relative path var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - entries_3 = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, sourceFile.path); + completionInfo.entries = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, sourceFile.path); } else { // Give completions based on the typings available var span_11 = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; - entries_3 = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); + completionInfo.entries = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); } - return { - isMemberCompletion: false, - isNewIdentifierLocation: true, - entries: entries_3 - }; } - return undefined; + return completionInfo; } function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { if (result === void 0) { result = []; } @@ -63285,7 +63732,7 @@ var ts; } } if (isJsDocTagName) { - return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; } if (!insideJsDocTagExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal @@ -63349,6 +63796,7 @@ var ts; } } var semanticStart = ts.timestamp(); + var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; var symbols = []; @@ -63382,11 +63830,13 @@ var ts; if (!tryGetGlobalSymbols()) { return undefined; } + isGlobalCompletion = true; } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; function getTypeScriptMemberSymbols() { // Right of dot member completion list + isGlobalCompletion = false; isMemberCompletion = true; isNewIdentifierLocation = false; if (node.kind === 69 /* Identifier */ || node.kind === 139 /* QualifiedName */ || node.kind === 172 /* PropertyAccessExpression */) { @@ -63448,6 +63898,7 @@ var ts; if ((jsxContainer.kind === 242 /* JsxSelfClosingElement */) || (jsxContainer.kind === 243 /* JsxOpeningElement */)) { // Cursor is inside a JSX self-closing element or opening element attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); + isGlobalCompletion = false; if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); isMemberCompletion = true; @@ -64026,9 +64477,15 @@ var ts; * Matches a triple slash reference directive with an incomplete string literal for its path. Used * to determine if the caret is currently within the string literal and capture the literal fragment * for completions. - * For example, this matches /// +/// +/// +/// /* @internal */ var ts; (function (ts) { @@ -66442,6 +66901,7 @@ var ts; // A map of loose file names to library names // that we are confident require typings var safeList; + var EmptySafeList = ts.createMap(); /** * @param host is the object providing I/O related operations. * @param fileNames are the file names that belong to the same project @@ -66458,10 +66918,13 @@ var ts; return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } // Only infer typings for .js and .jsx files - fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 1 /* JS */, 2 /* JSX */); }); + fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { + var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)); + return kind === 1 /* JS */ || kind === 2 /* JSX */; + }); if (!safeList) { var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); - safeList = ts.createMap(result.config); + safeList = result.config ? ts.createMap(result.config) : EmptySafeList; } var filesToWatch = []; // Directories to search for package.json, bower.json and other typing information @@ -66552,13 +67015,10 @@ var ts; var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); - if (safeList === undefined) { - mergeTypings(cleanedTypingNames); - } - else { + if (safeList !== EmptySafeList) { mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); } - var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 2 /* JSX */); }); + var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2 /* JSX */; }); if (hasJsxFile) { mergeTypings(["react"]); } @@ -66573,7 +67033,7 @@ var ts; return; } var typingNames = []; - var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + var fileNames = host.readDirectory(nodeModulesPath, [".json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { var fileName = fileNames_2[_i]; var normalizedFileName = ts.normalizePath(fileName); @@ -66616,7 +67076,7 @@ var ts; (function (ts) { var NavigateTo; (function (NavigateTo) { - function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount) { + function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; // This means "compare in a case insensitive manner." @@ -66624,6 +67084,9 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); + if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) { + return; + } var nameToDeclarations = sourceFile.getNamedDeclarations(); for (var name_49 in nameToDeclarations) { var declarations = nameToDeclarations[name_49]; @@ -66803,6 +67266,13 @@ var ts; return result; } NavigationBar.getNavigationBarItems = getNavigationBarItems; + function getNavigationTree(sourceFile) { + curSourceFile = sourceFile; + var result = convertToTree(rootNavigationBarNode(sourceFile)); + curSourceFile = undefined; + return result; + } + NavigationBar.getNavigationTree = getNavigationTree; // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`. var curSourceFile; function nodeText(node) { @@ -67077,7 +67547,7 @@ var ts; } } // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. - var collator = typeof Intl === "undefined" ? undefined : new Intl.Collator(); + var collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; // Intl is missing in Safari, and node 0.10 treats "a" as greater than "B". var localeCompareIsCorrect = collator && collator.compare("a", "B") < 0; var localeCompareFix = localeCompareIsCorrect ? collator.compare : function (a, b) { @@ -67242,6 +67712,15 @@ var ts; } // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance. var emptyChildItemArray = []; + function convertToTree(n) { + return { + text: getItemName(n.node), + kind: ts.getNodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToTree) + }; + } function convertToTopLevelItem(n) { return { text: getItemName(n.node), @@ -67265,16 +67744,16 @@ var ts; grayed: false }; } - function getSpans(n) { - var spans = [getNodeSpan(n.node)]; - if (n.additionalNodes) { - for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { - var node = _a[_i]; - spans.push(getNodeSpan(node)); - } + } + function getSpans(n) { + var spans = [getNodeSpan(n.node)]; + if (n.additionalNodes) { + for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { + var node = _a[_i]; + spans.push(getNodeSpan(node)); } - return spans; } + return spans; } function getModuleName(moduleDeclaration) { // We want to maintain quotation marks. @@ -71005,25 +71484,25 @@ var ts; }; RulesProvider.prototype.createActiveRules = function (options) { var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.InsertSpaceAfterCommaDelimiter) { + if (options.insertSpaceAfterCommaDelimiter) { rules.push(this.globalRules.SpaceAfterComma); } else { rules.push(this.globalRules.NoSpaceAfterComma); } - if (options.InsertSpaceAfterFunctionKeywordForAnonymousFunctions) { + if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); } else { rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); } - if (options.InsertSpaceAfterKeywordsInControlFlowStatements) { + if (options.insertSpaceAfterKeywordsInControlFlowStatements) { rules.push(this.globalRules.SpaceAfterKeywordInControl); } else { rules.push(this.globalRules.NoSpaceAfterKeywordInControl); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { rules.push(this.globalRules.SpaceAfterOpenParen); rules.push(this.globalRules.SpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); @@ -71033,7 +71512,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { rules.push(this.globalRules.SpaceAfterOpenBracket); rules.push(this.globalRules.SpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); @@ -71045,7 +71524,7 @@ var ts; } // The default value of InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces is true // so if the option is undefined, we should treat it as true as well - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { rules.push(this.globalRules.SpaceAfterOpenBrace); rules.push(this.globalRules.SpaceBeforeCloseBrace); rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); @@ -71055,7 +71534,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBrace); rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { + if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); } @@ -71063,7 +71542,7 @@ var ts; rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { + if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); } @@ -71071,13 +71550,13 @@ var ts; rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); } - if (options.InsertSpaceAfterSemicolonInForStatements) { + if (options.insertSpaceAfterSemicolonInForStatements) { rules.push(this.globalRules.SpaceAfterSemicolonInFor); } else { rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); } - if (options.InsertSpaceBeforeAndAfterBinaryOperators) { + if (options.insertSpaceBeforeAndAfterBinaryOperators) { rules.push(this.globalRules.SpaceBeforeBinaryOperator); rules.push(this.globalRules.SpaceAfterBinaryOperator); } @@ -71085,14 +71564,14 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); rules.push(this.globalRules.NoSpaceAfterBinaryOperator); } - if (options.PlaceOpenBraceOnNewLineForControlBlocks) { + if (options.placeOpenBraceOnNewLineForControlBlocks) { rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); } - if (options.PlaceOpenBraceOnNewLineForFunctions) { + if (options.placeOpenBraceOnNewLineForFunctions) { rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); } - if (options.InsertSpaceAfterTypeAssertion) { + if (options.insertSpaceAfterTypeAssertion) { rules.push(this.globalRules.SpaceAfterTypeAssertion); } else { @@ -71222,7 +71701,7 @@ var ts; return ts.rangeContainsRange(parent.members, node); case 225 /* ModuleDeclaration */: var body = parent.body; - return body && body.kind === 199 /* Block */ && ts.rangeContainsRange(body.statements, node); + return body && body.kind === 226 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); case 256 /* SourceFile */: case 199 /* Block */: case 226 /* ModuleBlock */: @@ -71332,7 +71811,7 @@ var ts; break; } if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) { - return options.IndentSize; + return options.indentSize; } previousLine = line; child = n; @@ -71404,7 +71883,7 @@ var ts; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { var indentation = inheritedIndentation; - var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0; + var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent @@ -71412,7 +71891,7 @@ var ts; indentation = startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta); + delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta); } else if (indentation === -1 /* Unknown */) { if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { @@ -71493,13 +71972,13 @@ var ts; recomputeIndentation: function (lineAdded) { if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { if (lineAdded) { - indentation += options.IndentSize; + indentation += options.indentSize; } else { - indentation -= options.IndentSize; + indentation -= options.indentSize; } if (formatting.SmartIndenter.shouldIndentChildNode(node)) { - delta = options.IndentSize; + delta = options.indentSize; } else { delta = 0; @@ -71919,7 +72398,7 @@ var ts; // edit should not be applied only if we have one line feed between elements var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { - recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.NewLineCharacter); + recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); } break; case 2 /* Space */: @@ -71980,14 +72459,14 @@ var ts; var internedSpacesIndentation; function getIndentationString(indentation, options) { // reset interned strings if FormatCodeOptions were changed - var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.TabSize || internedSizes.indentSize !== options.IndentSize); + var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize); if (resetInternedStrings) { - internedSizes = { tabSize: options.TabSize, indentSize: options.IndentSize }; + internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize }; internedTabsIndentation = internedSpacesIndentation = undefined; } - if (!options.ConvertTabsToSpaces) { - var tabs = Math.floor(indentation / options.TabSize); - var spaces = indentation - tabs * options.TabSize; + if (!options.convertTabsToSpaces) { + var tabs = Math.floor(indentation / options.tabSize); + var spaces = indentation - tabs * options.tabSize; var tabString = void 0; if (!internedTabsIndentation) { internedTabsIndentation = []; @@ -72002,13 +72481,13 @@ var ts; } else { var spacesString = void 0; - var quotient = Math.floor(indentation / options.IndentSize); - var remainder = indentation % options.IndentSize; + var quotient = Math.floor(indentation / options.indentSize); + var remainder = indentation % options.indentSize; if (!internedSpacesIndentation) { internedSpacesIndentation = []; } if (internedSpacesIndentation[quotient] === undefined) { - spacesString = repeat(" ", options.IndentSize * quotient); + spacesString = repeat(" ", options.indentSize * quotient); internedSpacesIndentation[quotient] = spacesString; } else { @@ -72045,7 +72524,7 @@ var ts; } // no indentation when the indent style is set to none, // so we can return fast - if (options.IndentStyle === ts.IndentStyle.None) { + if (options.indentStyle === ts.IndentStyle.None) { return 0; } var precedingToken = ts.findPrecedingToken(position, sourceFile); @@ -72061,7 +72540,7 @@ var ts; // indentation is first non-whitespace character in a previous line // for block indentation, we should look for a line which contains something that's not // whitespace. - if (options.IndentStyle === ts.IndentStyle.Block) { + if (options.indentStyle === ts.IndentStyle.Block) { // move backwards until we find a line with a non-whitespace character, // then find the first non-whitespace character for that line. var current_1 = position; @@ -72095,7 +72574,7 @@ var ts; indentationDelta = 0; } else { - indentationDelta = lineAtPosition !== currentStart.line ? options.IndentSize : 0; + indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0; } break; } @@ -72106,7 +72585,7 @@ var ts; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { - return actualIndentation + options.IndentSize; + return actualIndentation + options.indentSize; } previous = current; current = current.parent; @@ -72118,15 +72597,15 @@ var ts; return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, options); } SmartIndenter.getIndentation = getIndentation; - function getBaseIndentation(options) { - return options.BaseIndentSize || 0; - } - SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, options); } SmartIndenter.getIndentationForNode = getIndentationForNode; + function getBaseIndentation(options) { + return options.baseIndentSize || 0; + } + SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) { var parent = current.parent; var parentStart; @@ -72161,7 +72640,7 @@ var ts; } // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { - indentationDelta += options.IndentSize; + indentationDelta += options.indentSize; } current = parent; currentStart = parentStart; @@ -72371,7 +72850,7 @@ var ts; break; } if (ch === 9 /* tab */) { - column += options.TabSize + (column % options.TabSize); + column += options.tabSize + (column % options.tabSize); } else { column++; @@ -72473,6 +72952,117 @@ var ts; })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var codeFixes = ts.createMap(); + function registerCodeFix(action) { + ts.forEach(action.errorCodes, function (error) { + var fixes = codeFixes[error]; + if (!fixes) { + fixes = []; + codeFixes[error] = fixes; + } + fixes.push(action); + }); + } + codefix.registerCodeFix = registerCodeFix; + function getSupportedErrorCodes() { + return Object.keys(codeFixes); + } + codefix.getSupportedErrorCodes = getSupportedErrorCodes; + function getFixes(context) { + var fixes = codeFixes[context.errorCode]; + var allActions = []; + ts.forEach(fixes, function (f) { + var actions = f.getCodeActions(context); + if (actions && actions.length > 0) { + allActions = allActions.concat(actions); + } + }); + return allActions; + } + codefix.getFixes = getFixes; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + function getOpenBraceEnd(constructor, sourceFile) { + // First token is the open curly, this is where we want to put the 'super' call. + return constructor.body.getFirstToken(sourceFile).getEnd(); + } + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 121 /* ConstructorKeyword */) { + return undefined; + } + var newPosition = getOpenBraceEnd(token.parent, sourceFile); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), + changes: [{ fileName: sourceFile.fileName, textChanges: [{ newText: "super();", span: { start: newPosition, length: 0 } }] }] + }]; + } + }); + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 97 /* ThisKeyword */) { + return undefined; + } + var constructor = ts.getContainingFunction(token); + var superCall = findSuperCall(constructor.body); + if (!superCall) { + return undefined; + } + // figure out if the this access is actuall inside the supercall + // i.e. super(this.a), since in that case we won't suggest a fix + if (superCall.expression && superCall.expression.kind == 174 /* CallExpression */) { + var arguments_1 = superCall.expression.arguments; + for (var i = 0; i < arguments_1.length; i++) { + if (arguments_1[i].expression === token) { + return undefined; + } + } + } + var newPosition = getOpenBraceEnd(constructor, sourceFile); + var changes = [{ + fileName: sourceFile.fileName, textChanges: [{ + newText: superCall.getText(sourceFile), + span: { start: newPosition, length: 0 } + }, + { + newText: "", + span: { start: superCall.getStart(sourceFile), length: superCall.getWidth(sourceFile) } + }] + }]; + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), + changes: changes + }]; + function findSuperCall(n) { + if (n.kind === 202 /* ExpressionStatement */ && ts.isSuperCall(n.expression)) { + return n; + } + if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findSuperCall); + } + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/// /// /// /// @@ -72498,13 +73088,15 @@ var ts; /// /// /// +/// +/// var ts; (function (ts) { /** The version of the language service API */ ts.servicesVersion = "0.5"; function createNode(kind, pos, end, parent) { var node = kind >= 139 /* FirstNode */ ? new NodeObject(kind, pos, end) : - kind === 69 /* Identifier */ ? new IdentifierObject(kind, pos, end) : + kind === 69 /* Identifier */ ? new IdentifierObject(69 /* Identifier */, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; return node; @@ -72732,15 +73324,16 @@ var ts; var TokenObject = (function (_super) { __extends(TokenObject, _super); function TokenObject(kind, pos, end) { - _super.call(this, pos, end); - this.kind = kind; + var _this = _super.call(this, pos, end) || this; + _this.kind = kind; + return _this; } return TokenObject; }(TokenOrIdentifierObject)); var IdentifierObject = (function (_super) { __extends(IdentifierObject, _super); function IdentifierObject(kind, pos, end) { - _super.call(this, pos, end); + return _super.call(this, pos, end) || this; } return IdentifierObject; }(TokenOrIdentifierObject)); @@ -72816,7 +73409,7 @@ var ts; var SourceFileObject = (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { - _super.call(this, kind, pos, end); + return _super.call(this, kind, pos, end) || this; } SourceFileObject.prototype.update = function (newText, textChangeRange) { return ts.updateSourceFile(this, newText, textChangeRange); @@ -72985,6 +73578,30 @@ var ts; getSignatureConstructor: function () { return SignatureObject; } }; } + function toEditorSettings(optionsAsMap) { + var allPropertiesAreCamelCased = true; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) { + allPropertiesAreCamelCased = false; + break; + } + } + if (allPropertiesAreCamelCased) { + return optionsAsMap; + } + var settings = {}; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key)) { + var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1); + settings[newKey] = optionsAsMap[key]; + } + } + return settings; + } + ts.toEditorSettings = toEditorSettings; + function isCamelCase(s) { + return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); + } function displayPartsToString(displayParts) { if (displayParts) { return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join(""); @@ -73000,9 +73617,13 @@ var ts; }; } ts.getDefaultCompilerOptions = getDefaultCompilerOptions; - // Cache host information about script should be refreshed + function getSupportedCodeFixes() { + return ts.codefix.getSupportedErrorCodes(); + } + ts.getSupportedCodeFixes = getSupportedCodeFixes; + // Cache host information about script Should be refreshed // at each language service public entry point, since we don't know when - // set of scripts handled by the host changes. + // the set of scripts handled by the host changes. var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; @@ -73185,7 +73806,8 @@ var ts; var ruleProvider; var program; var lastProjectVersion; - var useCaseSensitivefileNames = false; + var lastTypesRootVersion = 0; + var useCaseSensitivefileNames = host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(); var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); var currentDirectory = host.getCurrentDirectory(); // Check if the localized messages json is set, otherwise query the host for it @@ -73224,6 +73846,12 @@ var ts; lastProjectVersion = hostProjectVersion; } } + var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; + if (lastTypesRootVersion !== typeRootsVersion) { + log("TypeRoots version has changed; provide new program"); + program = undefined; + lastTypesRootVersion = typeRootsVersion; + } // Get a fresh cache of the host information var hostCache = new HostCache(host, getCanonicalFileName); // If the program is already up-to-date, we can reuse it @@ -73553,12 +74181,12 @@ var ts; return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, findInStrings, findInComments); } /// NavigateTo - function getNavigateToItems(searchValue, maxResultCount, fileName) { + function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { synchronizeHostData(); var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); - return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount); + return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName) { + function getEmitOutput(fileName, emitOnlyDtsFiles) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var outputFiles = []; @@ -73569,7 +74197,7 @@ var ts; text: data }); } - var emitOutput = program.emit(sourceFile, writeFile, cancellationToken); + var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles); return { outputFiles: outputFiles, emitSkipped: emitOutput.emitSkipped @@ -73647,14 +74275,28 @@ var ts; return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); } function getNavigationBarItems(fileName) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function getNavigationTree(fileName) { + return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function isTsOrTsxFile(fileName) { + var kind = ts.getScriptKind(fileName, host); + return kind === 3 /* TS */ || kind === 4 /* TSX */; } function getSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + // do not run semantic classification on non-ts-or-tsx files + return []; + } synchronizeHostData(); return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } function getEncodedSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + // do not run semantic classification on non-ts-or-tsx files + return { spans: [], endOfLineState: 0 /* None */ }; + } synchronizeHostData(); return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } @@ -73715,34 +74357,60 @@ var ts; } function getIndentationAtPosition(fileName, position, editorOptions) { var start = ts.timestamp(); + var settings = toEditorSettings(editorOptions); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); start = ts.timestamp(); - var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); + var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings); log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); return result; } function getFormattingEditsForRange(fileName, start, end, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsForDocument(fileName, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var settings = toEditorSettings(options); if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); } else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); } else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); } return []; } + function getCodeFixesAtPosition(fileName, start, end, errorCodes) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var span = { start: start, length: end - start }; + var newLineChar = ts.getNewLineOrDefaultFromHost(host); + var allFixes = []; + ts.forEach(errorCodes, function (error) { + cancellationToken.throwIfCancellationRequested(); + var context = { + errorCode: error, + sourceFile: sourceFile, + span: span, + program: program, + newLineCharacter: newLineChar + }; + var fixes = ts.codefix.getFixes(context); + if (fixes) { + allFixes = allFixes.concat(fixes); + } + }); + return allFixes; + } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } @@ -73926,6 +74594,7 @@ var ts; getRenameInfo: getRenameInfo, findRenameLocations: findRenameLocations, getNavigationBarItems: getNavigationBarItems, + getNavigationTree: getNavigationTree, getOutliningSpans: getOutliningSpans, getTodoComments: getTodoComments, getBraceMatchingAtPosition: getBraceMatchingAtPosition, @@ -73935,6 +74604,7 @@ var ts; getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getCodeFixesAtPosition: getCodeFixesAtPosition, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, @@ -74624,7 +75294,7 @@ var ts; // /// /* @internal */ -var debugObjectHost = new Function("return this")(); +var debugObjectHost = (function () { return this; })(); // We need to use 'null' to interface with the managed side. /* tslint:disable:no-null-keyword */ /* tslint:disable:no-in-operator */ @@ -74712,6 +75382,12 @@ var ts; } return this.shimHost.getProjectVersion(); }; + LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () { + if (!this.shimHost.getTypeRootsVersion) { + return 0; + } + return this.shimHost.getTypeRootsVersion(); + }; LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; }; @@ -74914,11 +75590,12 @@ var ts; var LanguageServiceShimObject = (function (_super) { __extends(LanguageServiceShimObject, _super); function LanguageServiceShimObject(factory, host, languageService) { - _super.call(this, factory); - this.host = host; - this.languageService = languageService; - this.logPerformance = false; - this.logger = this.host; + var _this = _super.call(this, factory) || this; + _this.host = host; + _this.languageService = languageService; + _this.logPerformance = false; + _this.logger = _this.host; + return _this; } LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); @@ -75156,6 +75833,10 @@ var ts; var _this = this; return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; + LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); }); + }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); @@ -75182,10 +75863,11 @@ var ts; var ClassifierShimObject = (function (_super) { __extends(ClassifierShimObject, _super); function ClassifierShimObject(factory, logger) { - _super.call(this, factory); - this.logger = logger; - this.logPerformance = false; - this.classifier = ts.createClassifier(); + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.logPerformance = false; + _this.classifier = ts.createClassifier(); + return _this; } ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { var _this = this; @@ -75208,10 +75890,11 @@ var ts; var CoreServicesShimObject = (function (_super) { __extends(CoreServicesShimObject, _super); function CoreServicesShimObject(factory, logger, host) { - _super.call(this, factory); - this.logger = logger; - this.host = host; - this.logPerformance = false; + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.host = host; + _this.logPerformance = false; + return _this; } CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index e9c209674b5..5f319ffb74c 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -29,6 +29,7 @@ declare namespace ts { contains(fileName: Path): boolean; remove(fileName: Path): void; forEachValue(f: (key: Path, v: T) => void): void; + getKeys(): Path[]; clear(): void; } interface TextRange { @@ -388,7 +389,6 @@ declare namespace ts { ContextFlags = 1540096, TypeExcludesFlags = 327680, } - type ModifiersArray = NodeArray; enum ModifierFlags { None = 0, Export = 1, @@ -425,12 +425,21 @@ declare namespace ts { interface NodeArray extends Array, TextRange { hasTrailingComma?: boolean; } - interface Token extends Node { - __tokenTag: any; - } - interface Modifier extends Token { + interface Token extends Node { + kind: TKind; } + type DotDotDotToken = Token; + type QuestionToken = Token; + type ColonToken = Token; + type EqualsToken = Token; + type AsteriskToken = Token; + type EqualsGreaterThanToken = Token; + type EndOfFileToken = Token; + type AtToken = Token; + type Modifier = Token | Token | Token | Token | Token | Token | Token | Token | Token | Token | Token; + type ModifiersArray = NodeArray; interface Identifier extends PrimaryExpression { + kind: SyntaxKind.Identifier; text: string; originalKeywordKind?: SyntaxKind; } @@ -438,6 +447,7 @@ declare namespace ts { resolvedSymbol: Symbol; } interface QualifiedName extends Node { + kind: SyntaxKind.QualifiedName; left: EntityName; right: Identifier; } @@ -449,15 +459,18 @@ declare namespace ts { name?: DeclarationName; } interface DeclarationStatement extends Declaration, Statement { - name?: Identifier; + name?: Identifier | LiteralExpression; } interface ComputedPropertyName extends Node { + kind: SyntaxKind.ComputedPropertyName; expression: Expression; } interface Decorator extends Node { + kind: SyntaxKind.Decorator; expression: LeftHandSideExpression; } interface TypeParameterDeclaration extends Declaration { + kind: SyntaxKind.TypeParameter; name: Identifier; constraint?: TypeNode; expression?: Expression; @@ -469,40 +482,48 @@ declare namespace ts { type?: TypeNode; } interface CallSignatureDeclaration extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.CallSignature; } interface ConstructSignatureDeclaration extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.ConstructSignature; } type BindingName = Identifier | BindingPattern; interface VariableDeclaration extends Declaration { + kind: SyntaxKind.VariableDeclaration; parent?: VariableDeclarationList; name: BindingName; type?: TypeNode; initializer?: Expression; } interface VariableDeclarationList extends Node { + kind: SyntaxKind.VariableDeclarationList; declarations: NodeArray; } interface ParameterDeclaration extends Declaration { - dotDotDotToken?: Node; + kind: SyntaxKind.Parameter; + dotDotDotToken?: DotDotDotToken; name: BindingName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } interface BindingElement extends Declaration { + kind: SyntaxKind.BindingElement; propertyName?: PropertyName; - dotDotDotToken?: Node; + dotDotDotToken?: DotDotDotToken; name: BindingName; initializer?: Expression; } interface PropertySignature extends TypeElement { + kind: SyntaxKind.PropertySignature | SyntaxKind.JSDocRecordMember; name: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } interface PropertyDeclaration extends ClassElement { - questionToken?: Node; + kind: SyntaxKind.PropertyDeclaration; + questionToken?: QuestionToken; name: PropertyName; type?: TypeNode; initializer?: Expression; @@ -513,22 +534,23 @@ declare namespace ts { } type ObjectLiteralElementLike = PropertyAssignment | ShorthandPropertyAssignment | MethodDeclaration | AccessorDeclaration; interface PropertyAssignment extends ObjectLiteralElement { - _propertyAssignmentBrand: any; + kind: SyntaxKind.PropertyAssignment; name: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; initializer: Expression; } interface ShorthandPropertyAssignment extends ObjectLiteralElement { + kind: SyntaxKind.ShorthandPropertyAssignment; name: Identifier; - questionToken?: Node; - equalsToken?: Node; + questionToken?: QuestionToken; + equalsToken?: Token; objectAssignmentInitializer?: Expression; } interface VariableLikeDeclaration extends Declaration { propertyName?: PropertyName; - dotDotDotToken?: Node; + dotDotDotToken?: DotDotDotToken; name: DeclarationName; - questionToken?: Node; + questionToken?: QuestionToken; type?: TypeNode; initializer?: Expression; } @@ -539,10 +561,12 @@ declare namespace ts { elements: NodeArray; } interface ObjectBindingPattern extends BindingPattern { + kind: SyntaxKind.ObjectBindingPattern; elements: NodeArray; } type ArrayBindingElement = BindingElement | OmittedExpression; interface ArrayBindingPattern extends BindingPattern { + kind: SyntaxKind.ArrayBindingPattern; elements: NodeArray; } /** @@ -555,95 +579,116 @@ declare namespace ts { */ interface FunctionLikeDeclaration extends SignatureDeclaration { _functionLikeDeclarationBrand: any; - asteriskToken?: Node; - questionToken?: Node; + asteriskToken?: AsteriskToken; + questionToken?: QuestionToken; body?: Block | Expression; } interface FunctionDeclaration extends FunctionLikeDeclaration, DeclarationStatement { + kind: SyntaxKind.FunctionDeclaration; name?: Identifier; body?: FunctionBody; } interface MethodSignature extends SignatureDeclaration, TypeElement { + kind: SyntaxKind.MethodSignature; name: PropertyName; } interface MethodDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.MethodDeclaration; name: PropertyName; body?: FunctionBody; } interface ConstructorDeclaration extends FunctionLikeDeclaration, ClassElement { + kind: SyntaxKind.Constructor; body?: FunctionBody; } interface SemicolonClassElement extends ClassElement { - _semicolonClassElementBrand: any; + kind: SyntaxKind.SemicolonClassElement; } - interface AccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { - _accessorDeclarationBrand: any; + interface GetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.GetAccessor; name: PropertyName; body: FunctionBody; } - interface GetAccessorDeclaration extends AccessorDeclaration { - } - interface SetAccessorDeclaration extends AccessorDeclaration { + interface SetAccessorDeclaration extends FunctionLikeDeclaration, ClassElement, ObjectLiteralElement { + kind: SyntaxKind.SetAccessor; + name: PropertyName; + body: FunctionBody; } + type AccessorDeclaration = GetAccessorDeclaration | SetAccessorDeclaration; interface IndexSignatureDeclaration extends SignatureDeclaration, ClassElement, TypeElement { - _indexSignatureDeclarationBrand: any; + kind: SyntaxKind.IndexSignature; } interface TypeNode extends Node { _typeNodeBrand: any; } + interface KeywordTypeNode extends TypeNode { + kind: SyntaxKind.AnyKeyword | SyntaxKind.NumberKeyword | SyntaxKind.BooleanKeyword | SyntaxKind.StringKeyword | SyntaxKind.SymbolKeyword | SyntaxKind.VoidKeyword; + } interface ThisTypeNode extends TypeNode { - _thisTypeNodeBrand: any; + kind: SyntaxKind.ThisType; } interface FunctionOrConstructorTypeNode extends TypeNode, SignatureDeclaration { - _functionOrConstructorTypeNodeBrand: any; + kind: SyntaxKind.FunctionType | SyntaxKind.ConstructorType; } interface FunctionTypeNode extends FunctionOrConstructorTypeNode { + kind: SyntaxKind.FunctionType; } interface ConstructorTypeNode extends FunctionOrConstructorTypeNode { + kind: SyntaxKind.ConstructorType; } interface TypeReferenceNode extends TypeNode { + kind: SyntaxKind.TypeReference; typeName: EntityName; typeArguments?: NodeArray; } interface TypePredicateNode extends TypeNode { + kind: SyntaxKind.TypePredicate; parameterName: Identifier | ThisTypeNode; type: TypeNode; } interface TypeQueryNode extends TypeNode { + kind: SyntaxKind.TypeQuery; exprName: EntityName; } interface TypeLiteralNode extends TypeNode, Declaration { + kind: SyntaxKind.TypeLiteral; members: NodeArray; } interface ArrayTypeNode extends TypeNode { + kind: SyntaxKind.ArrayType; elementType: TypeNode; } interface TupleTypeNode extends TypeNode { + kind: SyntaxKind.TupleType; elementTypes: NodeArray; } interface UnionOrIntersectionTypeNode extends TypeNode { + kind: SyntaxKind.UnionType | SyntaxKind.IntersectionType; types: NodeArray; } interface UnionTypeNode extends UnionOrIntersectionTypeNode { + kind: SyntaxKind.UnionType; } interface IntersectionTypeNode extends UnionOrIntersectionTypeNode { + kind: SyntaxKind.IntersectionType; } interface ParenthesizedTypeNode extends TypeNode { + kind: SyntaxKind.ParenthesizedType; type: TypeNode; } interface LiteralTypeNode extends TypeNode { - _stringLiteralTypeBrand: any; + kind: SyntaxKind.LiteralType; literal: Expression; } interface StringLiteral extends LiteralExpression { - _stringLiteralBrand: any; + kind: SyntaxKind.StringLiteral; } interface Expression extends Node { _expressionBrand: any; contextualType?: Type; } interface OmittedExpression extends Expression { - _omittedExpressionBrand: any; + kind: SyntaxKind.OmittedExpression; } interface UnaryExpression extends Expression { _unaryExpressionBrand: any; @@ -651,13 +696,17 @@ declare namespace ts { interface IncrementExpression extends UnaryExpression { _incrementExpressionBrand: any; } + type PrefixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken | SyntaxKind.PlusToken | SyntaxKind.MinusToken | SyntaxKind.TildeToken | SyntaxKind.ExclamationToken; interface PrefixUnaryExpression extends IncrementExpression { - operator: SyntaxKind; + kind: SyntaxKind.PrefixUnaryExpression; + operator: PrefixUnaryOperator; operand: UnaryExpression; } + type PostfixUnaryOperator = SyntaxKind.PlusPlusToken | SyntaxKind.MinusMinusToken; interface PostfixUnaryExpression extends IncrementExpression { + kind: SyntaxKind.PostfixUnaryExpression; operand: LeftHandSideExpression; - operator: SyntaxKind; + operator: PostfixUnaryOperator; } interface PostfixExpression extends UnaryExpression { _postfixExpressionBrand: any; @@ -671,42 +720,83 @@ declare namespace ts { interface PrimaryExpression extends MemberExpression { _primaryExpressionBrand: any; } + interface NullLiteral extends PrimaryExpression { + kind: SyntaxKind.NullKeyword; + } + interface BooleanLiteral extends PrimaryExpression { + kind: SyntaxKind.TrueKeyword | SyntaxKind.FalseKeyword; + } + interface ThisExpression extends PrimaryExpression { + kind: SyntaxKind.ThisKeyword; + } + interface SuperExpression extends PrimaryExpression { + kind: SyntaxKind.SuperKeyword; + } interface DeleteExpression extends UnaryExpression { + kind: SyntaxKind.DeleteExpression; expression: UnaryExpression; } interface TypeOfExpression extends UnaryExpression { + kind: SyntaxKind.TypeOfExpression; expression: UnaryExpression; } interface VoidExpression extends UnaryExpression { + kind: SyntaxKind.VoidExpression; expression: UnaryExpression; } interface AwaitExpression extends UnaryExpression { + kind: SyntaxKind.AwaitExpression; expression: UnaryExpression; } interface YieldExpression extends Expression { - asteriskToken?: Node; + kind: SyntaxKind.YieldExpression; + asteriskToken?: AsteriskToken; expression?: Expression; } + type ExponentiationOperator = SyntaxKind.AsteriskAsteriskToken; + type MultiplicativeOperator = SyntaxKind.AsteriskToken | SyntaxKind.SlashToken | SyntaxKind.PercentToken; + type MultiplicativeOperatorOrHigher = ExponentiationOperator | MultiplicativeOperator; + type AdditiveOperator = SyntaxKind.PlusToken | SyntaxKind.MinusToken; + type AdditiveOperatorOrHigher = MultiplicativeOperatorOrHigher | AdditiveOperator; + type ShiftOperator = SyntaxKind.LessThanLessThanToken | SyntaxKind.GreaterThanGreaterThanToken | SyntaxKind.GreaterThanGreaterThanGreaterThanToken; + type ShiftOperatorOrHigher = AdditiveOperatorOrHigher | ShiftOperator; + type RelationalOperator = SyntaxKind.LessThanToken | SyntaxKind.LessThanEqualsToken | SyntaxKind.GreaterThanToken | SyntaxKind.GreaterThanEqualsToken | SyntaxKind.InstanceOfKeyword | SyntaxKind.InKeyword; + type RelationalOperatorOrHigher = ShiftOperatorOrHigher | RelationalOperator; + type EqualityOperator = SyntaxKind.EqualsEqualsToken | SyntaxKind.EqualsEqualsEqualsToken | SyntaxKind.ExclamationEqualsEqualsToken | SyntaxKind.ExclamationEqualsToken; + type EqualityOperatorOrHigher = RelationalOperatorOrHigher | EqualityOperator; + type BitwiseOperator = SyntaxKind.AmpersandToken | SyntaxKind.BarToken | SyntaxKind.CaretToken; + type BitwiseOperatorOrHigher = EqualityOperatorOrHigher | BitwiseOperator; + type LogicalOperator = SyntaxKind.AmpersandAmpersandToken | SyntaxKind.BarBarToken; + type LogicalOperatorOrHigher = BitwiseOperatorOrHigher | LogicalOperator; + type CompoundAssignmentOperator = SyntaxKind.PlusEqualsToken | SyntaxKind.MinusEqualsToken | SyntaxKind.AsteriskAsteriskEqualsToken | SyntaxKind.AsteriskEqualsToken | SyntaxKind.SlashEqualsToken | SyntaxKind.PercentEqualsToken | SyntaxKind.AmpersandEqualsToken | SyntaxKind.BarEqualsToken | SyntaxKind.CaretEqualsToken | SyntaxKind.LessThanLessThanEqualsToken | SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken | SyntaxKind.GreaterThanGreaterThanEqualsToken; + type AssignmentOperator = SyntaxKind.EqualsToken | CompoundAssignmentOperator; + type AssignmentOperatorOrHigher = LogicalOperatorOrHigher | AssignmentOperator; + type BinaryOperator = AssignmentOperatorOrHigher | SyntaxKind.CommaToken; + type BinaryOperatorToken = Token; interface BinaryExpression extends Expression, Declaration { + kind: SyntaxKind.BinaryExpression; left: Expression; - operatorToken: Node; + operatorToken: BinaryOperatorToken; right: Expression; } interface ConditionalExpression extends Expression { + kind: SyntaxKind.ConditionalExpression; condition: Expression; - questionToken: Node; + questionToken: QuestionToken; whenTrue: Expression; - colonToken: Node; + colonToken: ColonToken; whenFalse: Expression; } type FunctionBody = Block; type ConciseBody = FunctionBody | Expression; interface FunctionExpression extends PrimaryExpression, FunctionLikeDeclaration { + kind: SyntaxKind.FunctionExpression; name?: Identifier; body: FunctionBody; } interface ArrowFunction extends Expression, FunctionLikeDeclaration { - equalsGreaterThanToken: Node; + kind: SyntaxKind.ArrowFunction; + equalsGreaterThanToken: EqualsGreaterThanToken; body: ConciseBody; } interface LiteralLikeNode extends Node { @@ -717,29 +807,46 @@ declare namespace ts { interface LiteralExpression extends LiteralLikeNode, PrimaryExpression { _literalExpressionBrand: any; } + interface RegularExpressionLiteral extends LiteralExpression { + kind: SyntaxKind.RegularExpressionLiteral; + } + interface NoSubstitutionTemplateLiteral extends LiteralExpression { + kind: SyntaxKind.NoSubstitutionTemplateLiteral; + } interface NumericLiteral extends LiteralExpression { - _numericLiteralBrand: any; + kind: SyntaxKind.NumericLiteral; trailingComment?: string; } - interface TemplateLiteralFragment extends LiteralLikeNode { - _templateLiteralFragmentBrand: any; + interface TemplateHead extends LiteralLikeNode { + kind: SyntaxKind.TemplateHead; } - type Template = TemplateExpression | LiteralExpression; + interface TemplateMiddle extends LiteralLikeNode { + kind: SyntaxKind.TemplateMiddle; + } + interface TemplateTail extends LiteralLikeNode { + kind: SyntaxKind.TemplateTail; + } + type TemplateLiteral = TemplateExpression | NoSubstitutionTemplateLiteral; interface TemplateExpression extends PrimaryExpression { - head: TemplateLiteralFragment; + kind: SyntaxKind.TemplateExpression; + head: TemplateHead; templateSpans: NodeArray; } interface TemplateSpan extends Node { + kind: SyntaxKind.TemplateSpan; expression: Expression; - literal: TemplateLiteralFragment; + literal: TemplateMiddle | TemplateTail; } interface ParenthesizedExpression extends PrimaryExpression { + kind: SyntaxKind.ParenthesizedExpression; expression: Expression; } interface ArrayLiteralExpression extends PrimaryExpression { + kind: SyntaxKind.ArrayLiteralExpression; elements: NodeArray; } interface SpreadElementExpression extends Expression { + kind: SyntaxKind.SpreadElementExpression; expression: Expression; } /** @@ -752,104 +859,141 @@ declare namespace ts { properties: NodeArray; } interface ObjectLiteralExpression extends ObjectLiteralExpressionBase { + kind: SyntaxKind.ObjectLiteralExpression; } type EntityNameExpression = Identifier | PropertyAccessEntityNameExpression; type EntityNameOrEntityNameExpression = EntityName | EntityNameExpression; interface PropertyAccessExpression extends MemberExpression, Declaration { + kind: SyntaxKind.PropertyAccessExpression; expression: LeftHandSideExpression; name: Identifier; } + interface SuperPropertyAccessExpression extends PropertyAccessExpression { + expression: SuperExpression; + } /** Brand for a PropertyAccessExpression which, like a QualifiedName, consists of a sequence of identifiers separated by dots. */ interface PropertyAccessEntityNameExpression extends PropertyAccessExpression { _propertyAccessExpressionLikeQualifiedNameBrand?: any; expression: EntityNameExpression; } interface ElementAccessExpression extends MemberExpression { + kind: SyntaxKind.ElementAccessExpression; expression: LeftHandSideExpression; argumentExpression?: Expression; } + interface SuperElementAccessExpression extends ElementAccessExpression { + expression: SuperExpression; + } + type SuperProperty = SuperPropertyAccessExpression | SuperElementAccessExpression; interface CallExpression extends LeftHandSideExpression, Declaration { + kind: SyntaxKind.CallExpression; expression: LeftHandSideExpression; typeArguments?: NodeArray; arguments: NodeArray; } + interface SuperCall extends CallExpression { + expression: SuperExpression; + } interface ExpressionWithTypeArguments extends TypeNode { + kind: SyntaxKind.ExpressionWithTypeArguments; expression: LeftHandSideExpression; typeArguments?: NodeArray; } - interface NewExpression extends CallExpression, PrimaryExpression { + interface NewExpression extends PrimaryExpression, Declaration { + kind: SyntaxKind.NewExpression; + expression: LeftHandSideExpression; + typeArguments?: NodeArray; + arguments: NodeArray; } interface TaggedTemplateExpression extends MemberExpression { + kind: SyntaxKind.TaggedTemplateExpression; tag: LeftHandSideExpression; - template: Template; + template: TemplateLiteral; } type CallLikeExpression = CallExpression | NewExpression | TaggedTemplateExpression | Decorator; interface AsExpression extends Expression { + kind: SyntaxKind.AsExpression; expression: Expression; type: TypeNode; } interface TypeAssertion extends UnaryExpression { + kind: SyntaxKind.TypeAssertionExpression; type: TypeNode; expression: UnaryExpression; } type AssertionExpression = TypeAssertion | AsExpression; interface NonNullExpression extends LeftHandSideExpression { + kind: SyntaxKind.NonNullExpression; expression: Expression; } interface JsxElement extends PrimaryExpression { + kind: SyntaxKind.JsxElement; openingElement: JsxOpeningElement; children: NodeArray; closingElement: JsxClosingElement; } type JsxTagNameExpression = PrimaryExpression | PropertyAccessExpression; interface JsxOpeningElement extends Expression { - _openingElementBrand?: any; + kind: SyntaxKind.JsxOpeningElement; tagName: JsxTagNameExpression; attributes: NodeArray; } - interface JsxSelfClosingElement extends PrimaryExpression, JsxOpeningElement { - _selfClosingElementBrand?: any; + interface JsxSelfClosingElement extends PrimaryExpression { + kind: SyntaxKind.JsxSelfClosingElement; + tagName: JsxTagNameExpression; + attributes: NodeArray; } type JsxOpeningLikeElement = JsxSelfClosingElement | JsxOpeningElement; type JsxAttributeLike = JsxAttribute | JsxSpreadAttribute; interface JsxAttribute extends Node { + kind: SyntaxKind.JsxAttribute; name: Identifier; initializer?: StringLiteral | JsxExpression; } interface JsxSpreadAttribute extends Node { + kind: SyntaxKind.JsxSpreadAttribute; expression: Expression; } interface JsxClosingElement extends Node { + kind: SyntaxKind.JsxClosingElement; tagName: JsxTagNameExpression; } interface JsxExpression extends Expression { + kind: SyntaxKind.JsxExpression; expression?: Expression; } interface JsxText extends Node { - _jsxTextExpressionBrand: any; + kind: SyntaxKind.JsxText; } type JsxChild = JsxText | JsxExpression | JsxElement | JsxSelfClosingElement; interface Statement extends Node { _statementBrand: any; } interface EmptyStatement extends Statement { + kind: SyntaxKind.EmptyStatement; } interface DebuggerStatement extends Statement { + kind: SyntaxKind.DebuggerStatement; } interface MissingDeclaration extends DeclarationStatement, ClassElement, ObjectLiteralElement, TypeElement { + kind: SyntaxKind.MissingDeclaration; name?: Identifier; } type BlockLike = SourceFile | Block | ModuleBlock | CaseClause; interface Block extends Statement { + kind: SyntaxKind.Block; statements: NodeArray; } interface VariableStatement extends Statement { + kind: SyntaxKind.VariableStatement; declarationList: VariableDeclarationList; } interface ExpressionStatement extends Statement { + kind: SyntaxKind.ExpressionStatement; expression: Expression; } interface IfStatement extends Statement { + kind: SyntaxKind.IfStatement; expression: Expression; thenStatement: Statement; elseStatement?: Statement; @@ -858,68 +1002,85 @@ declare namespace ts { statement: Statement; } interface DoStatement extends IterationStatement { + kind: SyntaxKind.DoStatement; expression: Expression; } interface WhileStatement extends IterationStatement { + kind: SyntaxKind.WhileStatement; expression: Expression; } type ForInitializer = VariableDeclarationList | Expression; interface ForStatement extends IterationStatement { + kind: SyntaxKind.ForStatement; initializer?: ForInitializer; condition?: Expression; incrementor?: Expression; } interface ForInStatement extends IterationStatement { + kind: SyntaxKind.ForInStatement; initializer: ForInitializer; expression: Expression; } interface ForOfStatement extends IterationStatement { + kind: SyntaxKind.ForOfStatement; initializer: ForInitializer; expression: Expression; } interface BreakStatement extends Statement { + kind: SyntaxKind.BreakStatement; label?: Identifier; } interface ContinueStatement extends Statement { + kind: SyntaxKind.ContinueStatement; label?: Identifier; } type BreakOrContinueStatement = BreakStatement | ContinueStatement; interface ReturnStatement extends Statement { + kind: SyntaxKind.ReturnStatement; expression?: Expression; } interface WithStatement extends Statement { + kind: SyntaxKind.WithStatement; expression: Expression; statement: Statement; } interface SwitchStatement extends Statement { + kind: SyntaxKind.SwitchStatement; expression: Expression; caseBlock: CaseBlock; possiblyExhaustive?: boolean; } interface CaseBlock extends Node { + kind: SyntaxKind.CaseBlock; clauses: NodeArray; } interface CaseClause extends Node { + kind: SyntaxKind.CaseClause; expression: Expression; statements: NodeArray; } interface DefaultClause extends Node { + kind: SyntaxKind.DefaultClause; statements: NodeArray; } type CaseOrDefaultClause = CaseClause | DefaultClause; interface LabeledStatement extends Statement { + kind: SyntaxKind.LabeledStatement; label: Identifier; statement: Statement; } interface ThrowStatement extends Statement { + kind: SyntaxKind.ThrowStatement; expression: Expression; } interface TryStatement extends Statement { + kind: SyntaxKind.TryStatement; tryBlock: Block; catchClause?: CatchClause; finallyBlock?: Block; } interface CatchClause extends Node { + kind: SyntaxKind.CatchClause; variableDeclaration: VariableDeclaration; block: Block; } @@ -931,9 +1092,11 @@ declare namespace ts { members: NodeArray; } interface ClassDeclaration extends ClassLikeDeclaration, DeclarationStatement { + kind: SyntaxKind.ClassDeclaration; name?: Identifier; } interface ClassExpression extends ClassLikeDeclaration, PrimaryExpression { + kind: SyntaxKind.ClassExpression; } interface ClassElement extends Declaration { _classElementBrand: any; @@ -942,85 +1105,108 @@ declare namespace ts { interface TypeElement extends Declaration { _typeElementBrand: any; name?: PropertyName; - questionToken?: Node; + questionToken?: QuestionToken; } interface InterfaceDeclaration extends DeclarationStatement { + kind: SyntaxKind.InterfaceDeclaration; name: Identifier; typeParameters?: NodeArray; heritageClauses?: NodeArray; members: NodeArray; } interface HeritageClause extends Node { + kind: SyntaxKind.HeritageClause; token: SyntaxKind; types?: NodeArray; } interface TypeAliasDeclaration extends DeclarationStatement { + kind: SyntaxKind.TypeAliasDeclaration; name: Identifier; typeParameters?: NodeArray; type: TypeNode; } interface EnumMember extends Declaration { + kind: SyntaxKind.EnumMember; name: PropertyName; initializer?: Expression; } interface EnumDeclaration extends DeclarationStatement { + kind: SyntaxKind.EnumDeclaration; name: Identifier; members: NodeArray; } type ModuleBody = ModuleBlock | ModuleDeclaration; type ModuleName = Identifier | StringLiteral; interface ModuleDeclaration extends DeclarationStatement { + kind: SyntaxKind.ModuleDeclaration; name: Identifier | LiteralExpression; - body?: ModuleBlock | ModuleDeclaration; + body?: ModuleBlock | NamespaceDeclaration; + } + interface NamespaceDeclaration extends ModuleDeclaration { + name: Identifier; + body: ModuleBlock | NamespaceDeclaration; } interface ModuleBlock extends Node, Statement { + kind: SyntaxKind.ModuleBlock; statements: NodeArray; } type ModuleReference = EntityName | ExternalModuleReference; interface ImportEqualsDeclaration extends DeclarationStatement { + kind: SyntaxKind.ImportEqualsDeclaration; name: Identifier; moduleReference: ModuleReference; } interface ExternalModuleReference extends Node { + kind: SyntaxKind.ExternalModuleReference; expression?: Expression; } interface ImportDeclaration extends Statement { + kind: SyntaxKind.ImportDeclaration; importClause?: ImportClause; moduleSpecifier: Expression; } type NamedImportBindings = NamespaceImport | NamedImports; interface ImportClause extends Declaration { + kind: SyntaxKind.ImportClause; name?: Identifier; namedBindings?: NamedImportBindings; } interface NamespaceImport extends Declaration { + kind: SyntaxKind.NamespaceImport; name: Identifier; } interface NamespaceExportDeclaration extends DeclarationStatement { + kind: SyntaxKind.NamespaceExportDeclaration; name: Identifier; moduleReference: LiteralLikeNode; } interface ExportDeclaration extends DeclarationStatement { + kind: SyntaxKind.ExportDeclaration; exportClause?: NamedExports; moduleSpecifier?: Expression; } interface NamedImports extends Node { + kind: SyntaxKind.NamedImports; elements: NodeArray; } interface NamedExports extends Node { + kind: SyntaxKind.NamedExports; elements: NodeArray; } type NamedImportsOrExports = NamedImports | NamedExports; interface ImportSpecifier extends Declaration { + kind: SyntaxKind.ImportSpecifier; propertyName?: Identifier; name: Identifier; } interface ExportSpecifier extends Declaration { + kind: SyntaxKind.ExportSpecifier; propertyName?: Identifier; name: Identifier; } type ImportOrExportSpecifier = ImportSpecifier | ExportSpecifier; interface ExportAssignment extends DeclarationStatement { + kind: SyntaxKind.ExportAssignment; isExportEquals?: boolean; expression: Expression; } @@ -1032,95 +1218,121 @@ declare namespace ts { kind: SyntaxKind; } interface JSDocTypeExpression extends Node { + kind: SyntaxKind.JSDocTypeExpression; type: JSDocType; } interface JSDocType extends TypeNode { _jsDocTypeBrand: any; } interface JSDocAllType extends JSDocType { - _JSDocAllTypeBrand: any; + kind: SyntaxKind.JSDocAllType; } interface JSDocUnknownType extends JSDocType { - _JSDocUnknownTypeBrand: any; + kind: SyntaxKind.JSDocUnknownType; } interface JSDocArrayType extends JSDocType { + kind: SyntaxKind.JSDocArrayType; elementType: JSDocType; } interface JSDocUnionType extends JSDocType { + kind: SyntaxKind.JSDocUnionType; types: NodeArray; } interface JSDocTupleType extends JSDocType { + kind: SyntaxKind.JSDocTupleType; types: NodeArray; } interface JSDocNonNullableType extends JSDocType { + kind: SyntaxKind.JSDocNonNullableType; type: JSDocType; } interface JSDocNullableType extends JSDocType { + kind: SyntaxKind.JSDocNullableType; type: JSDocType; } - interface JSDocRecordType extends JSDocType, TypeLiteralNode { + interface JSDocRecordType extends JSDocType { + kind: SyntaxKind.JSDocRecordType; literal: TypeLiteralNode; } interface JSDocTypeReference extends JSDocType { + kind: SyntaxKind.JSDocTypeReference; name: EntityName; typeArguments: NodeArray; } interface JSDocOptionalType extends JSDocType { + kind: SyntaxKind.JSDocOptionalType; type: JSDocType; } interface JSDocFunctionType extends JSDocType, SignatureDeclaration { + kind: SyntaxKind.JSDocFunctionType; parameters: NodeArray; type: JSDocType; } interface JSDocVariadicType extends JSDocType { + kind: SyntaxKind.JSDocVariadicType; type: JSDocType; } interface JSDocConstructorType extends JSDocType { + kind: SyntaxKind.JSDocConstructorType; type: JSDocType; } interface JSDocThisType extends JSDocType { + kind: SyntaxKind.JSDocThisType; type: JSDocType; } interface JSDocLiteralType extends JSDocType { + kind: SyntaxKind.JSDocLiteralType; literal: LiteralTypeNode; } type JSDocTypeReferencingNode = JSDocThisType | JSDocConstructorType | JSDocVariadicType | JSDocOptionalType | JSDocNullableType | JSDocNonNullableType; interface JSDocRecordMember extends PropertySignature { + kind: SyntaxKind.JSDocRecordMember; name: Identifier | LiteralExpression; type?: JSDocType; } interface JSDoc extends Node { + kind: SyntaxKind.JSDocComment; tags: NodeArray | undefined; comment: string | undefined; } interface JSDocTag extends Node { - atToken: Node; + atToken: AtToken; tagName: Identifier; comment: string | undefined; } + interface JSDocUnknownTag extends JSDocTag { + kind: SyntaxKind.JSDocTag; + } interface JSDocTemplateTag extends JSDocTag { + kind: SyntaxKind.JSDocTemplateTag; typeParameters: NodeArray; } interface JSDocReturnTag extends JSDocTag { + kind: SyntaxKind.JSDocReturnTag; typeExpression: JSDocTypeExpression; } interface JSDocTypeTag extends JSDocTag { + kind: SyntaxKind.JSDocTypeTag; typeExpression: JSDocTypeExpression; } interface JSDocTypedefTag extends JSDocTag, Declaration { + kind: SyntaxKind.JSDocTypedefTag; name?: Identifier; typeExpression?: JSDocTypeExpression; jsDocTypeLiteral?: JSDocTypeLiteral; } interface JSDocPropertyTag extends JSDocTag, TypeElement { + kind: SyntaxKind.JSDocPropertyTag; name: Identifier; typeExpression: JSDocTypeExpression; } interface JSDocTypeLiteral extends JSDocType { + kind: SyntaxKind.JSDocTypeLiteral; jsDocPropertyTags?: NodeArray; jsDocTypeTag?: JSDocTypeTag; } interface JSDocParameterTag extends JSDocTag { + kind: SyntaxKind.JSDocParameterTag; /** the parameter name, if provided *before* the type (TypeScript-style) */ preParameterName?: Identifier; typeExpression?: JSDocTypeExpression; @@ -1149,7 +1361,7 @@ declare namespace ts { id?: number; } interface FlowStart extends FlowNode { - container?: FunctionExpression | ArrowFunction; + container?: FunctionExpression | ArrowFunction | MethodDeclaration; } interface FlowLabel extends FlowNode { antecedents: FlowNode[]; @@ -1178,8 +1390,9 @@ declare namespace ts { name: string; } interface SourceFile extends Declaration { + kind: SyntaxKind.SourceFile; statements: NodeArray; - endOfFileToken: Node; + endOfFileToken: Token; fileName: string; path: Path; text: string; @@ -1245,7 +1458,7 @@ declare namespace ts { * used for writing the JavaScript and declaration files. Otherwise, the writeFile parameter * will be invoked when writing the JavaScript and declaration files. */ - emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult; + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean): EmitResult; getOptionsDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; getGlobalDiagnostics(cancellationToken?: CancellationToken): Diagnostic[]; getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; @@ -1372,6 +1585,7 @@ declare namespace ts { UseFullyQualifiedType = 128, InFirstTypeArgument = 256, InTypeAlias = 512, + UseTypeAliasValue = 1024, } enum SymbolFormatFlags { None = 0, @@ -1387,9 +1601,10 @@ declare namespace ts { type: Type; } interface ThisTypePredicate extends TypePredicateBase { - _thisTypePredicateBrand: any; + kind: TypePredicateKind.This; } interface IdentifierTypePredicate extends TypePredicateBase { + kind: TypePredicateKind.Identifier; parameterName: string; parameterIndex: number; } @@ -1495,8 +1710,6 @@ declare namespace ts { Intersection = 1048576, Anonymous = 2097152, Instantiated = 4194304, - ThisType = 268435456, - ObjectLiteralPatternWithComputedProperties = 536870912, Literal = 480, StringOrNumberLiteral = 96, PossiblyFalsy = 7406, @@ -1509,7 +1722,7 @@ declare namespace ts { StructuredType = 4161536, StructuredOrTypeParameter = 4177920, Narrowable = 4178943, - NotUnionOrUnit = 2589191, + NotUnionOrUnit = 2589185, } type DestructuringPattern = BindingPattern | ObjectLiteralExpression | ArrayLiteralExpression; interface Type { @@ -1531,6 +1744,7 @@ declare namespace ts { baseType: EnumType & UnionType; } interface ObjectType extends Type { + isObjectLiteralPatternWithComputedProperties?: boolean; } interface InterfaceType extends ObjectType { typeParameters: TypeParameter[]; @@ -1614,15 +1828,13 @@ declare namespace ts { Classic = 1, NodeJs = 2, } - type RootPaths = string[]; - type PathSubstitutions = MapLike; - type TsConfigOnlyOptions = RootPaths | PathSubstitutions; - type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions; + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike; interface CompilerOptions { allowJs?: boolean; allowSyntheticDefaultImports?: boolean; allowUnreachableCode?: boolean; allowUnusedLabels?: boolean; + alwaysStrict?: boolean; baseUrl?: string; charset?: string; declaration?: boolean; @@ -1660,13 +1872,13 @@ declare namespace ts { out?: string; outDir?: string; outFile?: string; - paths?: PathSubstitutions; + paths?: MapLike; preserveConstEnums?: boolean; project?: string; reactNamespace?: string; removeComments?: boolean; rootDir?: string; - rootDirs?: RootPaths; + rootDirs?: string[]; skipLibCheck?: boolean; skipDefaultLibCheck?: boolean; sourceMap?: boolean; @@ -1742,6 +1954,7 @@ declare namespace ts { raw?: any; errors: Diagnostic[]; wildcardDirectories?: MapLike; + compileOnSave?: boolean; } enum WatchDirectoryFlags { None = 0, @@ -1846,7 +2059,7 @@ declare namespace ts { directoryName: string; referenceCount: number; } - var sys: System; + let sys: System; } declare namespace ts { interface ErrorCallback { @@ -1944,10 +2157,6 @@ declare namespace ts { function updateSourceFile(sourceFile: SourceFile, newText: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; } declare namespace ts { - /** The version of the TypeScript compiler release */ - const version = "2.1.0"; - function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; - function resolveTripleslashReference(moduleName: string, containingFile: string): string; function getEffectiveTypeRoots(options: CompilerOptions, host: { directoryExists?: (directoryName: string) => boolean; getCurrentDirectory?: () => string; @@ -1958,18 +2167,6 @@ declare namespace ts { * is assumed to be the same as root directory of the project. */ function resolveTypeReferenceDirective(typeReferenceDirectiveName: string, containingFile: string, options: CompilerOptions, host: ModuleResolutionHost): ResolvedTypeReferenceDirectiveWithFailedLookupLocations; - function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; - function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; - function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; - interface FormatDiagnosticsHost { - getCurrentDirectory(): string; - getCanonicalFileName(fileName: string): string; - getNewLine(): string; - } - function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; - function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; /** * Given a set of options, returns the set of type directive names * that should be included for this program automatically. @@ -1979,6 +2176,24 @@ declare namespace ts { * this list is only the set of defaults that are implicitly included. */ function getAutomaticTypeDirectiveNames(options: CompilerOptions, host: ModuleResolutionHost): string[]; + function resolveModuleName(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function nodeModuleNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; + function classicNameResolver(moduleName: string, containingFile: string, compilerOptions: CompilerOptions, host: ModuleResolutionHost): ResolvedModuleWithFailedLookupLocations; +} +declare namespace ts { + /** The version of the TypeScript compiler release */ + const version = "2.1.0"; + function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string; + function resolveTripleslashReference(moduleName: string, containingFile: string): string; + function createCompilerHost(options: CompilerOptions, setParentNodes?: boolean): CompilerHost; + function getPreEmitDiagnostics(program: Program, sourceFile?: SourceFile, cancellationToken?: CancellationToken): Diagnostic[]; + interface FormatDiagnosticsHost { + getCurrentDirectory(): string; + getCanonicalFileName(fileName: string): string; + getNewLine(): string; + } + function formatDiagnostics(diagnostics: Diagnostic[], host: FormatDiagnosticsHost): string; + function flattenDiagnosticMessageText(messageText: string | DiagnosticMessageChain, newLine: string): string; function createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } declare namespace ts { @@ -1995,7 +2210,7 @@ declare namespace ts { * @param fileName The path to the config file * @param jsonText The text of the config file */ - function parseConfigFileTextToJson(fileName: string, jsonText: string): { + function parseConfigFileTextToJson(fileName: string, jsonText: string, stripComments?: boolean): { config?: any; error?: Diagnostic; }; @@ -2007,12 +2222,13 @@ declare namespace ts { * file to. e.g. outDir */ function parseJsonConfigFileContent(json: any, host: ParseConfigHost, basePath: string, existingOptions?: CompilerOptions, configFileName?: string, resolutionStack?: Path[]): ParsedCommandLine; + function convertCompileOnSaveOptionFromJson(jsonOption: any, basePath: string, errors: Diagnostic[]): boolean; function convertCompilerOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { options: CompilerOptions; errors: Diagnostic[]; }; function convertTypingOptionsFromJson(jsonOptions: any, basePath: string, configFileName?: string): { - options: CompilerOptions; + options: TypingOptions; errors: Diagnostic[]; }; } @@ -2118,6 +2334,7 @@ declare namespace ts { readDirectory?(path: string, extensions?: string[], exclude?: string[], include?: string[]): string[]; readFile?(path: string, encoding?: string): string; fileExists?(path: string): boolean; + getTypeRootsVersion?(): number; resolveModuleNames?(moduleNames: string[], containingFile: string): ResolvedModule[]; resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string): ResolvedTypeReferenceDirective[]; directoryExists?(directoryName: string): boolean; @@ -2155,18 +2372,20 @@ declare namespace ts { getDocumentHighlights(fileName: string, position: number, filesToSearch: string[]): DocumentHighlights[]; /** @deprecated */ getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; - getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string): NavigateToItem[]; + getNavigateToItems(searchValue: string, maxResultCount?: number, fileName?: string, excludeDtsFiles?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; + getNavigationTree(fileName: string): NavigationTree; getOutliningSpans(fileName: string): OutliningSpan[]; getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; - getIndentationAtPosition(fileName: string, position: number, options: EditorOptions): number; - getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions): TextChange[]; - getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions): TextChange[]; - getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions): TextChange[]; + getIndentationAtPosition(fileName: string, position: number, options: EditorOptions | EditorSettings): number; + getFormattingEditsForRange(fileName: string, start: number, end: number, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsForDocument(fileName: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; + getFormattingEditsAfterKeystroke(fileName: string, position: number, key: string, options: FormatCodeOptions | FormatCodeSettings): TextChange[]; getDocCommentTemplateAtPosition(fileName: string, position: number): TextInsertion; isValidBraceCompletionAtPosition(fileName: string, position: number, openingBrace: number): boolean; - getEmitOutput(fileName: string): EmitOutput; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[]): CodeAction[]; + getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; getProgram(): Program; dispose(): void; } @@ -2178,6 +2397,12 @@ declare namespace ts { textSpan: TextSpan; classificationType: string; } + /** + * Navigation bar interface designed for visual studio's dual-column layout. + * This does not form a proper tree. + * The navbar is returned as a list of top-level items, each of which has a list of child items. + * Child items always have an empty array for their `childItems`. + */ interface NavigationBarItem { text: string; kind: string; @@ -2188,6 +2413,25 @@ declare namespace ts { bolded: boolean; grayed: boolean; } + /** + * Node in a tree of nested declarations in a file. + * The top node is always a script or module node. + */ + interface NavigationTree { + /** Name of the declaration, or a short description, e.g. "". */ + text: string; + /** A ScriptElementKind */ + kind: string; + /** ScriptElementKindModifier separated by commas, e.g. "public,abstract" */ + kindModifiers: string; + /** + * Spans of the nodes that generated this declaration. + * There will be more than one if this is the result of merging. + */ + spans: TextSpan[]; + /** Present if non-empty */ + childItems?: NavigationTree[]; + } interface TodoCommentDescriptor { text: string; priority: number; @@ -2201,6 +2445,16 @@ declare namespace ts { span: TextSpan; newText: string; } + interface FileTextChanges { + fileName: string; + textChanges: TextChange[]; + } + interface CodeAction { + /** Description of the code action to display in the UI of the editor */ + description: string; + /** Text changes to apply to each file as part of the code action */ + changes: FileTextChanges[]; + } interface TextInsertion { newText: string; /** The position in newText the caret should point to after the insertion. */ @@ -2246,6 +2500,11 @@ declare namespace ts { containerName: string; containerKind: string; } + enum IndentStyle { + None = 0, + Block = 1, + Smart = 2, + } interface EditorOptions { BaseIndentSize?: number; IndentSize: number; @@ -2254,10 +2513,13 @@ declare namespace ts { ConvertTabsToSpaces: boolean; IndentStyle: IndentStyle; } - enum IndentStyle { - None = 0, - Block = 1, - Smart = 2, + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle; } interface FormatCodeOptions extends EditorOptions { InsertSpaceAfterCommaDelimiter: boolean; @@ -2273,7 +2535,21 @@ declare namespace ts { InsertSpaceAfterTypeAssertion?: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; - [s: string]: boolean | number | string | undefined; + } + interface FormatCodeSettings extends EditorSettings { + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + insertSpaceAfterTypeAssertion?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; } interface DefinitionInfo { fileName: string; @@ -2366,7 +2642,11 @@ declare namespace ts { argumentCount: number; } interface CompletionInfo { + isGlobalCompletion: boolean; isMemberCompletion: boolean; + /** + * true when the current location also allows for a new identifier + */ isNewIdentifierLocation: boolean; entries: CompletionEntry[]; } @@ -2687,8 +2967,10 @@ declare namespace ts { interface DisplayPartsSymbolWriter extends SymbolWriter { displayParts(): SymbolDisplayPart[]; } + function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; function displayPartsToString(displayParts: SymbolDisplayPart[]): string; function getDefaultCompilerOptions(): CompilerOptions; + function getSupportedCodeFixes(): string[]; function createLanguageServiceSourceFile(fileName: string, scriptSnapshot: IScriptSnapshot, scriptTarget: ScriptTarget, version: string, setNodeParents: boolean, scriptKind?: ScriptKind): SourceFile; let disableIncrementalParsing: boolean; function updateLanguageServiceSourceFile(sourceFile: SourceFile, scriptSnapshot: IScriptSnapshot, version: string, textChangeRange: TextChangeRange, aggressiveChecks?: boolean): SourceFile; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 14fbdce59a8..c534a725901 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -502,6 +502,7 @@ var ts; TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 128] = "UseFullyQualifiedType"; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 256] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 512] = "InTypeAlias"; + TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 1024] = "UseTypeAliasValue"; })(ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var TypeFormatFlags = ts.TypeFormatFlags; (function (SymbolFormatFlags) { @@ -685,8 +686,6 @@ var ts; TypeFlags[TypeFlags["ContainsObjectLiteral"] = 67108864] = "ContainsObjectLiteral"; /* @internal */ TypeFlags[TypeFlags["ContainsAnyFunctionType"] = 134217728] = "ContainsAnyFunctionType"; - TypeFlags[TypeFlags["ThisType"] = 268435456] = "ThisType"; - TypeFlags[TypeFlags["ObjectLiteralPatternWithComputedProperties"] = 536870912] = "ObjectLiteralPatternWithComputedProperties"; /* @internal */ TypeFlags[TypeFlags["Nullable"] = 6144] = "Nullable"; TypeFlags[TypeFlags["Literal"] = 480] = "Literal"; @@ -709,7 +708,7 @@ var ts; // 'Narrowable' types are types where narrowing actually narrows. // This *should* be every type other than null, undefined, void, and never TypeFlags[TypeFlags["Narrowable"] = 4178943] = "Narrowable"; - TypeFlags[TypeFlags["NotUnionOrUnit"] = 2589191] = "NotUnionOrUnit"; + TypeFlags[TypeFlags["NotUnionOrUnit"] = 2589185] = "NotUnionOrUnit"; /* @internal */ TypeFlags[TypeFlags["RequiresWidening"] = 100663296] = "RequiresWidening"; /* @internal */ @@ -993,36 +992,44 @@ var ts; })(ts.TransformFlags || (ts.TransformFlags = {})); var TransformFlags = ts.TransformFlags; /* @internal */ - (function (NodeEmitFlags) { - NodeEmitFlags[NodeEmitFlags["EmitEmitHelpers"] = 1] = "EmitEmitHelpers"; - NodeEmitFlags[NodeEmitFlags["EmitExportStar"] = 2] = "EmitExportStar"; - NodeEmitFlags[NodeEmitFlags["EmitSuperHelper"] = 4] = "EmitSuperHelper"; - NodeEmitFlags[NodeEmitFlags["EmitAdvancedSuperHelper"] = 8] = "EmitAdvancedSuperHelper"; - NodeEmitFlags[NodeEmitFlags["UMDDefine"] = 16] = "UMDDefine"; - NodeEmitFlags[NodeEmitFlags["SingleLine"] = 32] = "SingleLine"; - NodeEmitFlags[NodeEmitFlags["AdviseOnEmitNode"] = 64] = "AdviseOnEmitNode"; - NodeEmitFlags[NodeEmitFlags["NoSubstitution"] = 128] = "NoSubstitution"; - NodeEmitFlags[NodeEmitFlags["CapturesThis"] = 256] = "CapturesThis"; - NodeEmitFlags[NodeEmitFlags["NoLeadingSourceMap"] = 512] = "NoLeadingSourceMap"; - NodeEmitFlags[NodeEmitFlags["NoTrailingSourceMap"] = 1024] = "NoTrailingSourceMap"; - NodeEmitFlags[NodeEmitFlags["NoSourceMap"] = 1536] = "NoSourceMap"; - NodeEmitFlags[NodeEmitFlags["NoNestedSourceMaps"] = 2048] = "NoNestedSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoTokenLeadingSourceMaps"] = 4096] = "NoTokenLeadingSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoTokenTrailingSourceMaps"] = 8192] = "NoTokenTrailingSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoTokenSourceMaps"] = 12288] = "NoTokenSourceMaps"; - NodeEmitFlags[NodeEmitFlags["NoLeadingComments"] = 16384] = "NoLeadingComments"; - NodeEmitFlags[NodeEmitFlags["NoTrailingComments"] = 32768] = "NoTrailingComments"; - NodeEmitFlags[NodeEmitFlags["NoComments"] = 49152] = "NoComments"; - NodeEmitFlags[NodeEmitFlags["NoNestedComments"] = 65536] = "NoNestedComments"; - NodeEmitFlags[NodeEmitFlags["ExportName"] = 131072] = "ExportName"; - NodeEmitFlags[NodeEmitFlags["LocalName"] = 262144] = "LocalName"; - NodeEmitFlags[NodeEmitFlags["Indented"] = 524288] = "Indented"; - NodeEmitFlags[NodeEmitFlags["NoIndentation"] = 1048576] = "NoIndentation"; - NodeEmitFlags[NodeEmitFlags["AsyncFunctionBody"] = 2097152] = "AsyncFunctionBody"; - NodeEmitFlags[NodeEmitFlags["ReuseTempVariableScope"] = 4194304] = "ReuseTempVariableScope"; - NodeEmitFlags[NodeEmitFlags["CustomPrologue"] = 8388608] = "CustomPrologue"; - })(ts.NodeEmitFlags || (ts.NodeEmitFlags = {})); - var NodeEmitFlags = ts.NodeEmitFlags; + (function (EmitFlags) { + EmitFlags[EmitFlags["EmitEmitHelpers"] = 1] = "EmitEmitHelpers"; + EmitFlags[EmitFlags["EmitExportStar"] = 2] = "EmitExportStar"; + EmitFlags[EmitFlags["EmitSuperHelper"] = 4] = "EmitSuperHelper"; + EmitFlags[EmitFlags["EmitAdvancedSuperHelper"] = 8] = "EmitAdvancedSuperHelper"; + EmitFlags[EmitFlags["UMDDefine"] = 16] = "UMDDefine"; + EmitFlags[EmitFlags["SingleLine"] = 32] = "SingleLine"; + EmitFlags[EmitFlags["AdviseOnEmitNode"] = 64] = "AdviseOnEmitNode"; + EmitFlags[EmitFlags["NoSubstitution"] = 128] = "NoSubstitution"; + EmitFlags[EmitFlags["CapturesThis"] = 256] = "CapturesThis"; + EmitFlags[EmitFlags["NoLeadingSourceMap"] = 512] = "NoLeadingSourceMap"; + EmitFlags[EmitFlags["NoTrailingSourceMap"] = 1024] = "NoTrailingSourceMap"; + EmitFlags[EmitFlags["NoSourceMap"] = 1536] = "NoSourceMap"; + EmitFlags[EmitFlags["NoNestedSourceMaps"] = 2048] = "NoNestedSourceMaps"; + EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 4096] = "NoTokenLeadingSourceMaps"; + EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 8192] = "NoTokenTrailingSourceMaps"; + EmitFlags[EmitFlags["NoTokenSourceMaps"] = 12288] = "NoTokenSourceMaps"; + EmitFlags[EmitFlags["NoLeadingComments"] = 16384] = "NoLeadingComments"; + EmitFlags[EmitFlags["NoTrailingComments"] = 32768] = "NoTrailingComments"; + EmitFlags[EmitFlags["NoComments"] = 49152] = "NoComments"; + EmitFlags[EmitFlags["NoNestedComments"] = 65536] = "NoNestedComments"; + EmitFlags[EmitFlags["ExportName"] = 131072] = "ExportName"; + EmitFlags[EmitFlags["LocalName"] = 262144] = "LocalName"; + EmitFlags[EmitFlags["Indented"] = 524288] = "Indented"; + EmitFlags[EmitFlags["NoIndentation"] = 1048576] = "NoIndentation"; + EmitFlags[EmitFlags["AsyncFunctionBody"] = 2097152] = "AsyncFunctionBody"; + EmitFlags[EmitFlags["ReuseTempVariableScope"] = 4194304] = "ReuseTempVariableScope"; + EmitFlags[EmitFlags["CustomPrologue"] = 8388608] = "CustomPrologue"; + })(ts.EmitFlags || (ts.EmitFlags = {})); + var EmitFlags = ts.EmitFlags; + /* @internal */ + (function (EmitContext) { + EmitContext[EmitContext["SourceFile"] = 0] = "SourceFile"; + EmitContext[EmitContext["Expression"] = 1] = "Expression"; + EmitContext[EmitContext["IdentifierName"] = 2] = "IdentifierName"; + EmitContext[EmitContext["Unspecified"] = 3] = "Unspecified"; + })(ts.EmitContext || (ts.EmitContext = {})); + var EmitContext = ts.EmitContext; })(ts || (ts = {})); /*@internal*/ var ts; @@ -1032,7 +1039,6 @@ var ts; })(ts || (ts = {})); /*@internal*/ /** Performance measurements for the compiler. */ -var ts; (function (ts) { var performance; (function (performance) { @@ -1164,6 +1170,7 @@ var ts; contains: contains, remove: remove, forEachValue: forEachValueInMap, + getKeys: getKeys, clear: clear }; function forEachValueInMap(f) { @@ -1171,6 +1178,13 @@ var ts; f(key, files[key]); } } + function getKeys() { + var keys = []; + for (var key in files) { + keys.push(key); + } + return keys; + } // path should already be well-formed so it does not need to be normalized function get(path) { return files[toKey(path)]; @@ -1501,6 +1515,7 @@ var ts; return array1.concat(array2); } ts.concatenate = concatenate; + // TODO: fixme (N^2) - add optional comparer so collection can be sorted before deduplication. function deduplicate(array, areEqual) { var result; if (array) { @@ -1604,16 +1619,22 @@ var ts; * @param array A sorted array whose first element must be no larger than number * @param number The value to be searched for in the array. */ - function binarySearch(array, value) { + function binarySearch(array, value, comparer) { + if (!array || array.length === 0) { + return -1; + } var low = 0; var high = array.length - 1; + comparer = comparer !== undefined + ? comparer + : function (v1, v2) { return (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); }; while (low <= high) { var middle = low + ((high - low) >> 1); var midValue = array[middle]; - if (midValue === value) { + if (comparer(midValue, value) === 0) { return middle; } - else if (midValue > value) { + else if (comparer(midValue, value) > 0) { high = middle - 1; } else { @@ -1929,6 +1950,56 @@ var ts; }; } ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (t) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { baseIndex = baseIndex || 0; return text.replace(/{(\d+)}/g, function (match, index) { return args[+index + baseIndex]; }); @@ -2096,7 +2167,9 @@ var ts; return path.replace(/\\/g, "/"); } ts.normalizeSlashes = normalizeSlashes; - // Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files") + /** + * Returns length of path root (i.e. length of "/", "x:/", "//server/share/, file:///user/files") + */ function getRootLength(path) { if (path.charCodeAt(0) === 47 /* slash */) { if (path.charCodeAt(1) !== 47 /* slash */) @@ -2129,6 +2202,11 @@ var ts; return 0; } ts.getRootLength = getRootLength; + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ ts.directorySeparator = "/"; var directorySeparatorCharCode = 47 /* slash */; function getNormalizedParts(normalizedSlashedPath, rootLength) { @@ -2178,10 +2256,49 @@ var ts; return path && !isRootedDiskPath(path) && path.indexOf("://") !== -1; } ts.isUrl = isUrl; + function isExternalModuleNameRelative(moduleName) { + // TypeScript 1.0 spec (April 2014): 11.2.1 + // An external module name is "relative" if the first term is "." or "..". + return /^\.\.?($|[\\/])/.test(moduleName); + } + ts.isExternalModuleNameRelative = isExternalModuleNameRelative; + function getEmitScriptTarget(compilerOptions) { + return compilerOptions.target || 0 /* ES3 */; + } + ts.getEmitScriptTarget = getEmitScriptTarget; + function getEmitModuleKind(compilerOptions) { + return typeof compilerOptions.module === "number" ? + compilerOptions.module : + getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; + } + ts.getEmitModuleKind = getEmitModuleKind; + /* @internal */ + function hasZeroOrOneAsteriskCharacter(str) { + var seenAsterisk = false; + for (var i = 0; i < str.length; i++) { + if (str.charCodeAt(i) === 42 /* asterisk */) { + if (!seenAsterisk) { + seenAsterisk = true; + } + else { + // have already seen asterisk + return false; + } + } + } + return true; + } + ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; function isRootedDiskPath(path) { return getRootLength(path) !== 0; } ts.isRootedDiskPath = isRootedDiskPath; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; function normalizedPathComponents(path, rootLength) { var normalizedParts = getNormalizedParts(path, rootLength); return [path.substr(0, rootLength)].concat(normalizedParts); @@ -2625,6 +2742,14 @@ var ts; return options && options.allowJs ? allSupportedExtensions : ts.supportedTypeScriptExtensions; } ts.getSupportedExtensions = getSupportedExtensions; + function hasJavaScriptFileExtension(fileName) { + return forEach(ts.supportedJavascriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; + function hasTypeScriptFileExtension(fileName) { + return forEach(ts.supportedTypeScriptExtensions, function (extension) { return fileExtensionIs(fileName, extension); }); + } + ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; function isSupportedSourceFileName(fileName, compilerOptions) { if (!fileName) { return false; @@ -2737,7 +2862,6 @@ var ts; this.transformFlags = 0 /* None */; this.parent = undefined; this.original = undefined; - this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, @@ -2757,9 +2881,9 @@ var ts; var AssertionLevel = ts.AssertionLevel; var Debug; (function (Debug) { - var currentAssertionLevel; + Debug.currentAssertionLevel = 0 /* None */; function shouldAssert(level) { - return getCurrentAssertionLevel() >= level; + return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -2777,30 +2901,7 @@ var ts; Debug.assert(/*expression*/ false, message); } Debug.fail = fail; - function getCurrentAssertionLevel() { - if (currentAssertionLevel !== undefined) { - return currentAssertionLevel; - } - if (ts.sys === undefined) { - return 0 /* None */; - } - var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); - currentAssertionLevel = developmentMode - ? 1 /* Normal */ - : 0 /* None */; - return currentAssertionLevel; - } })(Debug = ts.Debug || (ts.Debug = {})); - function getEnvironmentVariable(name, host) { - if (host && host.getEnvironmentVariable) { - return host.getEnvironmentVariable(name); - } - if (ts.sys && ts.sys.getEnvironmentVariable) { - return ts.sys.getEnvironmentVariable(name); - } - return ""; - } - ts.getEnvironmentVariable = getEnvironmentVariable; /** Remove an item from an array, moving everything to its right one space left. */ function orderedRemoveItemAt(array, index) { // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`. @@ -2836,6 +2937,84 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; + /** + * patternStrings contains both pattern strings (containing "*") and regular strings. + * Return an exact match if possible, or a pattern match, or undefined. + * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) + */ + /* @internal */ + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + // pattern was matched as is - no need to search further + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + /* @internal */ + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + /** + * Given that candidate matches pattern, returns the text matching the '*'. + * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" + */ + /* @internal */ + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + /** Return the object corresponding to the best pattern to match `candidate`. */ + /* @internal */ + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + // use length of prefix as betterness criteria + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + /* @internal */ + function tryParsePattern(pattern) { + // This should be verified outside of here and a proper error thrown. + Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; + function positionIsSynthesized(pos) { + // This is a fast way of testing the following conditions: + // pos === undefined || pos === null || isNaN(pos) || pos < 0; + return !(pos >= 0); + } + ts.positionIsSynthesized = positionIsSynthesized; })(ts || (ts = {})); /// var ts; @@ -3040,9 +3219,17 @@ var ts; function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; } + function isFileSystemCaseSensitive() { + // win32\win64 are case insensitive platforms + if (platform === "win32" || platform === "win64") { + return false; + } + // convert current file name to upper case / lower case and check if file exists + // (guards against cases when name is already all uppercase or lowercase) + return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + } var platform = _os.platform(); - // win32\win64 are case insensitive platforms, MacOS (darwin) by default is also case insensitive - var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); function readFile(fileName, encoding) { if (!fileExists(fileName)) { return undefined; @@ -3182,6 +3369,9 @@ var ts; // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) var options; + if (!directoryExists(directoryName)) { + return; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -3299,21 +3489,46 @@ var ts; realpath: realpath }; } + function recursiveCreateDirectory(directoryPath, sys) { + var basePath = ts.getDirectoryPath(directoryPath); + var shouldCreateParent = directoryPath !== basePath && !sys.directoryExists(basePath); + if (shouldCreateParent) { + recursiveCreateDirectory(basePath, sys); + } + if (shouldCreateParent || !sys.directoryExists(directoryPath)) { + sys.createDirectory(directoryPath); + } + } + var sys; if (typeof ChakraHost !== "undefined") { - return getChakraSystem(); + sys = getChakraSystem(); } else if (typeof WScript !== "undefined" && typeof ActiveXObject === "function") { - return getWScriptSystem(); + sys = getWScriptSystem(); } else if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") { // process and process.nextTick checks if current environment is node-like // process.browser check excludes webpack and browserify - return getNodeSystem(); + sys = getNodeSystem(); } - else { - return undefined; // Unsupported host + if (sys) { + // patch writefile to create folder before writing the file + var originalWriteFile_1 = sys.writeFile; + sys.writeFile = function (path, data, writeBom) { + var directoryPath = ts.getDirectoryPath(ts.normalizeSlashes(path)); + if (directoryPath && !sys.directoryExists(directoryPath)) { + recursiveCreateDirectory(directoryPath, sys); + } + originalWriteFile_1.call(sys, path, data, writeBom); + }; } + return sys; })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 /* Normal */ + : 0 /* None */; + } })(ts || (ts = {})); // /// @@ -3641,7 +3856,7 @@ var ts; The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class" }, - All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "All_symbols_within_a_with_block_will_be_resolved_to_any_2410", message: "All symbols within a 'with' block will be resolved to 'any'." }, + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, @@ -3802,7 +4017,7 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, - Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, @@ -4035,6 +4250,8 @@ var ts; No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0: { code: 6137, category: ts.DiagnosticCategory.Message, key: "No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0_6137", message: "No types specified in 'package.json' but 'allowJs' is set, so returning 'main' value of '{0}'" }, Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, + Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file" }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -4059,6 +4276,7 @@ var ts; Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, + Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type 'any' in some locations where its type cannot be determined." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -4088,7 +4306,14 @@ var ts; super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } + The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." }, + Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, + Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, + Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'" }, + Remove_unused_identifiers: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_unused_identifiers_90004", message: "Remove unused identifiers" }, + Implement_interface_on_reference: { code: 90005, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_reference_90005", message: "Implement interface on reference" }, + Implement_interface_on_class: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_class_90006", message: "Implement interface on class" }, + Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class" } }; })(ts || (ts = {})); /// @@ -5145,7 +5370,7 @@ var ts; return token = 69 /* Identifier */; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8"); + ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); var value = 0; // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b. // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O. @@ -6364,10 +6589,10 @@ var ts; return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */); } ts.isLet = isLet; - function isSuperCallExpression(n) { + function isSuperCall(n) { return n.kind === 174 /* CallExpression */ && n.expression.kind === 95 /* SuperKeyword */; } - ts.isSuperCallExpression = isSuperCallExpression; + ts.isSuperCall = isSuperCall; function isPrologueDirective(node) { return node.kind === 202 /* ExpressionStatement */ && node.expression.kind === 9 /* StringLiteral */; } @@ -6636,6 +6861,12 @@ var ts; return node && node.kind === 147 /* MethodDeclaration */ && node.parent.kind === 171 /* ObjectLiteralExpression */; } ts.isObjectLiteralMethod = isObjectLiteralMethod; + function isObjectLiteralOrClassExpressionMethod(node) { + return node.kind === 147 /* MethodDeclaration */ && + (node.parent.kind === 171 /* ObjectLiteralExpression */ || + node.parent.kind === 192 /* ClassExpression */); + } + ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod; function isIdentifierTypePredicate(predicate) { return predicate && predicate.kind === 1 /* Identifier */; } @@ -6723,11 +6954,11 @@ var ts; } ts.getThisContainer = getThisContainer; /** - * Given an super call\property node returns a closest node where either - * - super call\property is legal in the node and not legal in the parent node the node. + * Given an super call/property node, returns the closest node where + * - a super call/property access is legal in the node and not legal in the parent node the node. * i.e. super call is legal in constructor but not legal in the class body. - * - node is arrow function (so caller might need to call getSuperContainer in case it needs to climb higher) - * - super call\property is definitely illegal in the node (but might be legal in some subnode) + * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher) + * - a super call/property is definitely illegal in the container (but might be legal in some subnode) * i.e. super property access is illegal in function declaration but can be legal in the statement list */ function getSuperContainer(node, stopOnFunctions) { @@ -6988,12 +7219,6 @@ var ts; return false; } ts.isPartOfExpression = isPartOfExpression; - function isExternalModuleNameRelative(moduleName) { - // TypeScript 1.0 spec (April 2014): 11.2.1 - // An external module name is "relative" if the first term is "." or "..". - return /^\.\.?($|[\\/])/.test(moduleName); - } - ts.isExternalModuleNameRelative = isExternalModuleNameRelative; function isInstantiatedModule(node, preserveConstEnums) { var moduleState = ts.getModuleInstanceState(node); return moduleState === 1 /* Instantiated */ || @@ -7655,16 +7880,10 @@ var ts; } ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment; function nodeIsSynthesized(node) { - return positionIsSynthesized(node.pos) - || positionIsSynthesized(node.end); + return ts.positionIsSynthesized(node.pos) + || ts.positionIsSynthesized(node.end); } ts.nodeIsSynthesized = nodeIsSynthesized; - function positionIsSynthesized(pos) { - // This is a fast way of testing the following conditions: - // pos === undefined || pos === null || isNaN(pos) || pos < 0; - return !(pos >= 0); - } - ts.positionIsSynthesized = positionIsSynthesized; function getOriginalNode(node) { if (node) { while (node.original !== undefined) { @@ -8125,24 +8344,12 @@ var ts; function getDeclarationEmitOutputFilePath(sourceFile, host) { var options = host.getCompilerOptions(); var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified - if (options.declaration) { - var path = outputDir - ? getSourceFilePathInNewDir(sourceFile, host, outputDir) - : sourceFile.fileName; - return ts.removeFileExtension(path) + ".d.ts"; - } + var path = outputDir + ? getSourceFilePathInNewDir(sourceFile, host, outputDir) + : sourceFile.fileName; + return ts.removeFileExtension(path) + ".d.ts"; } ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath; - function getEmitScriptTarget(compilerOptions) { - return compilerOptions.target || 0 /* ES3 */; - } - ts.getEmitScriptTarget = getEmitScriptTarget; - function getEmitModuleKind(compilerOptions) { - return typeof compilerOptions.module === "number" ? - compilerOptions.module : - getEmitScriptTarget(compilerOptions) === 2 /* ES6 */ ? ts.ModuleKind.ES6 : ts.ModuleKind.CommonJS; - } - ts.getEmitModuleKind = getEmitModuleKind; /** * Gets the source files that are expected to have an emit output. * @@ -8155,7 +8362,7 @@ var ts; function getSourceFilesToEmit(host, targetSourceFile) { var options = host.getCompilerOptions(); if (options.outFile || options.out) { - var moduleKind = getEmitModuleKind(options); + var moduleKind = ts.getEmitModuleKind(options); var moduleEmitEnabled = moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System; var sourceFiles = host.getSourceFiles(); // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified @@ -8184,7 +8391,7 @@ var ts; * @param sourceFiles The transformed source files to emit. * @param action The action to execute. */ - function forEachTransformedEmitFile(host, sourceFiles, action) { + function forEachTransformedEmitFile(host, sourceFiles, action, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); // Emit on each source file if (options.outFile || options.out) { @@ -8217,7 +8424,7 @@ var ts; } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); - var declarationFilePath = !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (options.declaration || emitOnlyDtsFiles) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; action(jsFilePath, sourceMapFilePath, declarationFilePath, [sourceFile], /*isBundledEmit*/ false); } function onBundledEmit(host, sourceFiles) { @@ -8242,7 +8449,7 @@ var ts; * @param action The action to execute. * @param targetSourceFile An optional target source file to emit. */ - function forEachExpectedEmitFile(host, action, targetSourceFile) { + function forEachExpectedEmitFile(host, action, targetSourceFile, emitOnlyDtsFiles) { var options = host.getCompilerOptions(); // Emit on each source file if (options.outFile || options.out) { @@ -8275,12 +8482,13 @@ var ts; } } var jsFilePath = getOwnEmitOutputFilePath(sourceFile, host, extension); + var declarationFilePath = !isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; var emitFileNames = { jsFilePath: jsFilePath, sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), - declarationFilePath: !isSourceFileJavaScript(sourceFile) ? getDeclarationEmitOutputFilePath(sourceFile, host) : undefined + declarationFilePath: declarationFilePath }; - action(emitFileNames, [sourceFile], /*isBundledEmit*/ false); + action(emitFileNames, [sourceFile], /*isBundledEmit*/ false, emitOnlyDtsFiles); } function onBundledEmit(host) { // Can emit only sources that are not declaration file and are either non module code or module with @@ -8288,7 +8496,7 @@ var ts; var bundledSources = ts.filter(host.getSourceFiles(), function (sourceFile) { return !isDeclarationFile(sourceFile) && !host.isSourceFileFromExternalLibrary(sourceFile) && (!ts.isExternalModule(sourceFile) || - !!getEmitModuleKind(options)); }); + !!ts.getEmitModuleKind(options)); }); if (bundledSources.length) { var jsFilePath = options.outFile || options.out; var emitFileNames = { @@ -8296,7 +8504,7 @@ var ts; sourceMapFilePath: getSourceMapFilePath(jsFilePath, options), declarationFilePath: options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : undefined }; - action(emitFileNames, bundledSources, /*isBundledEmit*/ true); + action(emitFileNames, bundledSources, /*isBundledEmit*/ true, emitOnlyDtsFiles); } } } @@ -8331,15 +8539,35 @@ var ts; }); } ts.getFirstConstructorWithBody = getFirstConstructorWithBody; + /** Get the type annotaion for the value parameter. */ function getSetAccessorTypeAnnotationNode(accessor) { if (accessor && accessor.parameters.length > 0) { - var hasThis = accessor.parameters.length === 2 && - accessor.parameters[0].name.kind === 69 /* Identifier */ && - accessor.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */; + var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]); return accessor.parameters[hasThis ? 1 : 0].type; } } ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode; + function getThisParameter(signature) { + if (signature.parameters.length) { + var thisParameter = signature.parameters[0]; + if (parameterIsThisKeyword(thisParameter)) { + return thisParameter; + } + } + } + ts.getThisParameter = getThisParameter; + function parameterIsThisKeyword(parameter) { + return isThisIdentifier(parameter.name); + } + ts.parameterIsThisKeyword = parameterIsThisKeyword; + function isThisIdentifier(node) { + return node && node.kind === 69 /* Identifier */ && identifierIsThisKeyword(node); + } + ts.isThisIdentifier = isThisIdentifier; + function identifierIsThisKeyword(id) { + return id.originalKeywordKind === 97 /* ThisKeyword */; + } + ts.identifierIsThisKeyword = identifierIsThisKeyword; function getAllAccessorDeclarations(declarations, accessor) { var firstAccessor; var secondAccessor; @@ -8700,14 +8928,6 @@ var ts; return symbol && symbol.valueDeclaration && hasModifier(symbol.valueDeclaration, 512 /* Default */) ? symbol.valueDeclaration.localSymbol : undefined; } ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault; - function hasJavaScriptFileExtension(fileName) { - return ts.forEach(ts.supportedJavascriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } - ts.hasJavaScriptFileExtension = hasJavaScriptFileExtension; - function hasTypeScriptFileExtension(fileName) { - return ts.forEach(ts.supportedTypeScriptExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); }); - } - ts.hasTypeScriptFileExtension = hasTypeScriptFileExtension; /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */ function tryExtractTypeScriptExtension(fileName) { return ts.find(ts.supportedTypescriptExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); }); @@ -8820,12 +9040,6 @@ var ts; return result; } ts.convertToBase64 = convertToBase64; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !ts.isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /* isAbsolutePathAnUrl */ false); - } - ts.convertToRelativePath = convertToRelativePath; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; function getNewLineCharacter(options) { @@ -8938,7 +9152,7 @@ var ts; * @param value The delta. */ function movePos(pos, value) { - return positionIsSynthesized(pos) ? -1 : pos + value; + return ts.positionIsSynthesized(pos) ? -1 : pos + value; } ts.movePos = movePos; /** @@ -9054,7 +9268,7 @@ var ts; } ts.positionsAreOnSameLine = positionsAreOnSameLine; function getStartPositionOfRange(range, sourceFile) { - return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); + return ts.positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos); } ts.getStartPositionOfRange = getStartPositionOfRange; function collectExternalModuleInfo(sourceFile, resolver) { @@ -9179,15 +9393,16 @@ var ts; return 11 /* FirstTemplateToken */ <= kind && kind <= 14 /* LastTemplateToken */; } ts.isTemplateLiteralKind = isTemplateLiteralKind; - function isTemplateLiteralFragmentKind(kind) { - return kind === 12 /* TemplateHead */ - || kind === 13 /* TemplateMiddle */ + function isTemplateHead(node) { + return node.kind === 12 /* TemplateHead */; + } + ts.isTemplateHead = isTemplateHead; + function isTemplateMiddleOrTemplateTail(node) { + var kind = node.kind; + return kind === 13 /* TemplateMiddle */ || kind === 14 /* TemplateTail */; } - function isTemplateLiteralFragment(node) { - return isTemplateLiteralFragmentKind(node.kind); - } - ts.isTemplateLiteralFragment = isTemplateLiteralFragment; + ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail; // Identifiers function isIdentifier(node) { return node.kind === 69 /* Identifier */; @@ -9340,12 +9555,12 @@ var ts; return node.kind === 174 /* CallExpression */; } ts.isCallExpression = isCallExpression; - function isTemplate(node) { + function isTemplateLiteral(node) { var kind = node.kind; return kind === 189 /* TemplateExpression */ || kind === 11 /* NoSubstitutionTemplateLiteral */; } - ts.isTemplate = isTemplate; + ts.isTemplateLiteral = isTemplateLiteral; function isSpreadElementExpression(node) { return node.kind === 191 /* SpreadElementExpression */; } @@ -9688,7 +9903,6 @@ var ts; } ts.isWatchSet = isWatchSet; })(ts || (ts = {})); -var ts; (function (ts) { function getDefaultLibFileName(options) { return options.target === 2 /* ES6 */ ? "lib.es6.d.ts" : "lib.d.ts"; @@ -10029,7 +10243,7 @@ var ts; // the original node. We also need to exclude specific properties and only include own- // properties (to skip members already defined on the shared prototype). var clone = createNode(node.kind, /*location*/ undefined, node.flags); - clone.original = node; + setOriginalNode(clone, node); for (var key in node) { if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) { continue; @@ -10064,7 +10278,7 @@ var ts; node.text = value; return node; } - else { + else if (value) { var node = createNode(9 /* StringLiteral */, location, /*flags*/ undefined); node.textSourceNode = value; node.text = value.text; @@ -10364,7 +10578,7 @@ var ts; function createPropertyAccess(expression, name, location, flags) { var node = createNode(172 /* PropertyAccessExpression */, location, flags); node.expression = parenthesizeForAccess(expression); - node.emitFlags = 1048576 /* NoIndentation */; + (node.emitNode || (node.emitNode = {})).flags |= 1048576 /* NoIndentation */; node.name = typeof name === "string" ? createIdentifier(name) : name; return node; } @@ -10373,7 +10587,7 @@ var ts; if (node.expression !== expression || node.name !== name) { var propertyAccess = createPropertyAccess(expression, name, /*location*/ node, node.flags); // Because we are updating existed propertyAccess we want to inherit its emitFlags instead of using default from createPropertyAccess - propertyAccess.emitFlags = node.emitFlags; + (propertyAccess.emitNode || (propertyAccess.emitNode = {})).flags = getEmitFlags(node); return updateNode(propertyAccess, node); } return node; @@ -10477,7 +10691,7 @@ var ts; node.typeParameters = typeParameters ? createNodeArray(typeParameters) : undefined; node.parameters = createNodeArray(parameters); node.type = type; - node.equalsGreaterThanToken = equalsGreaterThanToken || createNode(34 /* EqualsGreaterThanToken */); + node.equalsGreaterThanToken = equalsGreaterThanToken || createToken(34 /* EqualsGreaterThanToken */); node.body = parenthesizeConciseBody(body); return node; } @@ -10570,7 +10784,7 @@ var ts; } ts.updatePostfix = updatePostfix; function createBinary(left, operator, right, location) { - var operatorToken = typeof operator === "number" ? createSynthesizedNode(operator) : operator; + var operatorToken = typeof operator === "number" ? createToken(operator) : operator; var operatorKind = operatorToken.kind; var node = createNode(187 /* BinaryExpression */, location); node.left = parenthesizeBinaryOperand(operatorKind, left, /*isLeftSideOfBinary*/ true, /*leftOperand*/ undefined); @@ -11492,7 +11706,7 @@ var ts; } else { var expression = ts.isIdentifier(memberName) ? createPropertyAccess(target, memberName, location) : createElementAccess(target, memberName, location); - expression.emitFlags |= 2048 /* NoNestedSourceMaps */; + (expression.emitNode || (expression.emitNode = {})).flags |= 2048 /* NoNestedSourceMaps */; return expression; } } @@ -11500,7 +11714,7 @@ var ts; function createRestParameter(name) { return createParameterDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, createSynthesizedNode(22 /* DotDotDotToken */), name, + /*modifiers*/ undefined, createToken(22 /* DotDotDotToken */), name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined); @@ -11630,13 +11844,13 @@ var ts; } ts.createDecorateHelper = createDecorateHelper; function createAwaiterHelper(externalHelpersModuleName, hasLexicalArguments, promiseConstructor, body) { - var generatorFunc = createFunctionExpression(createNode(37 /* AsteriskToken */), + var generatorFunc = createFunctionExpression(createToken(37 /* AsteriskToken */), /*name*/ undefined, /*typeParameters*/ undefined, /*parameters*/ [], /*type*/ undefined, body); // Mark this node as originally an async function - generatorFunc.emitFlags |= 2097152 /* AsyncFunctionBody */; + (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 2097152 /* AsyncFunctionBody */; return createCall(createHelperName(externalHelpersModuleName, "__awaiter"), /*typeArguments*/ undefined, [ createThis(), @@ -11953,7 +12167,7 @@ var ts; target.push(startOnNewLine(createStatement(createLiteral("use strict")))); foundUseStrict = true; } - if (statement.emitFlags & 8388608 /* CustomPrologue */) { + if (getEmitFlags(statement) & 8388608 /* CustomPrologue */) { target.push(visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement); } else { @@ -11965,6 +12179,34 @@ var ts; return statementOffset; } ts.addPrologueDirectives = addPrologueDirectives; + /** + * Ensures "use strict" directive is added + * + * @param node source file + */ + function ensureUseStrict(node) { + var foundUseStrict = false; + for (var _i = 0, _a = node.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (ts.isPrologueDirective(statement)) { + if (isUseStrictPrologue(statement)) { + foundUseStrict = true; + break; + } + } + else { + break; + } + } + if (!foundUseStrict) { + var statements = []; + statements.push(startOnNewLine(createStatement(createLiteral("use strict")))); + // add "use strict" as the first statement + return updateSourceFileNode(node, statements.concat(node.statements)); + } + return node; + } + ts.ensureUseStrict = ensureUseStrict; /** * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended * order of operations. @@ -12323,17 +12565,180 @@ var ts; function setOriginalNode(node, original) { node.original = original; if (original) { - var emitFlags = original.emitFlags, commentRange = original.commentRange, sourceMapRange = original.sourceMapRange; - if (emitFlags) - node.emitFlags = emitFlags; - if (commentRange) - node.commentRange = commentRange; - if (sourceMapRange) - node.sourceMapRange = sourceMapRange; + var emitNode = original.emitNode; + if (emitNode) + node.emitNode = mergeEmitNode(emitNode, node.emitNode); } return node; } ts.setOriginalNode = setOriginalNode; + function mergeEmitNode(sourceEmitNode, destEmitNode) { + var flags = sourceEmitNode.flags, commentRange = sourceEmitNode.commentRange, sourceMapRange = sourceEmitNode.sourceMapRange, tokenSourceMapRanges = sourceEmitNode.tokenSourceMapRanges; + if (!destEmitNode && (flags || commentRange || sourceMapRange || tokenSourceMapRanges)) + destEmitNode = {}; + if (flags) + destEmitNode.flags = flags; + if (commentRange) + destEmitNode.commentRange = commentRange; + if (sourceMapRange) + destEmitNode.sourceMapRange = sourceMapRange; + if (tokenSourceMapRanges) + destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges); + return destEmitNode; + } + function mergeTokenSourceMapRanges(sourceRanges, destRanges) { + if (!destRanges) + destRanges = ts.createMap(); + ts.copyProperties(sourceRanges, destRanges); + return destRanges; + } + /** + * Clears any EmitNode entries from parse-tree nodes. + * @param sourceFile A source file. + */ + function disposeEmitNodes(sourceFile) { + // During transformation we may need to annotate a parse tree node with transient + // transformation properties. As parse tree nodes live longer than transformation + // nodes, we need to make sure we reclaim any memory allocated for custom ranges + // from these nodes to ensure we do not hold onto entire subtrees just for position + // information. We also need to reset these nodes to a pre-transformation state + // for incremental parsing scenarios so that we do not impact later emit. + sourceFile = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile)); + var emitNode = sourceFile && sourceFile.emitNode; + var annotatedNodes = emitNode && emitNode.annotatedNodes; + if (annotatedNodes) { + for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) { + var node = annotatedNodes_1[_i]; + node.emitNode = undefined; + } + } + } + ts.disposeEmitNodes = disposeEmitNodes; + /** + * Associates a node with the current transformation, initializing + * various transient transformation properties. + * + * @param node The node. + */ + function getOrCreateEmitNode(node) { + if (!node.emitNode) { + if (ts.isParseTreeNode(node)) { + // To avoid holding onto transformation artifacts, we keep track of any + // parse tree node we are annotating. This allows us to clean them up after + // all transformations have completed. + if (node.kind === 256 /* SourceFile */) { + return node.emitNode = { annotatedNodes: [node] }; + } + var sourceFile = ts.getSourceFileOfNode(node); + getOrCreateEmitNode(sourceFile).annotatedNodes.push(node); + } + node.emitNode = {}; + } + return node.emitNode; + } + /** + * Gets flags that control emit behavior of a node. + * + * @param node The node. + */ + function getEmitFlags(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.flags; + } + ts.getEmitFlags = getEmitFlags; + /** + * Sets flags that control emit behavior of a node. + * + * @param node The node. + * @param emitFlags The NodeEmitFlags for the node. + */ + function setEmitFlags(node, emitFlags) { + getOrCreateEmitNode(node).flags = emitFlags; + return node; + } + ts.setEmitFlags = setEmitFlags; + /** + * Sets a custom text range to use when emitting source maps. + * + * @param node The node. + * @param range The text range. + */ + function setSourceMapRange(node, range) { + getOrCreateEmitNode(node).sourceMapRange = range; + return node; + } + ts.setSourceMapRange = setSourceMapRange; + /** + * Sets the TextRange to use for source maps for a token of a node. + * + * @param node The node. + * @param token The token. + * @param range The text range. + */ + function setTokenSourceMapRange(node, token, range) { + var emitNode = getOrCreateEmitNode(node); + var tokenSourceMapRanges = emitNode.tokenSourceMapRanges || (emitNode.tokenSourceMapRanges = ts.createMap()); + tokenSourceMapRanges[token] = range; + return node; + } + ts.setTokenSourceMapRange = setTokenSourceMapRange; + /** + * Sets a custom text range to use when emitting comments. + */ + function setCommentRange(node, range) { + getOrCreateEmitNode(node).commentRange = range; + return node; + } + ts.setCommentRange = setCommentRange; + /** + * Gets a custom text range to use when emitting comments. + * + * @param node The node. + */ + function getCommentRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.commentRange) || node; + } + ts.getCommentRange = getCommentRange; + /** + * Gets a custom text range to use when emitting source maps. + * + * @param node The node. + */ + function getSourceMapRange(node) { + var emitNode = node.emitNode; + return (emitNode && emitNode.sourceMapRange) || node; + } + ts.getSourceMapRange = getSourceMapRange; + /** + * Gets the TextRange to use for source maps for a token of a node. + * + * @param node The node. + * @param token The token. + */ + function getTokenSourceMapRange(node, token) { + var emitNode = node.emitNode; + var tokenSourceMapRanges = emitNode && emitNode.tokenSourceMapRanges; + return tokenSourceMapRanges && tokenSourceMapRanges[token]; + } + ts.getTokenSourceMapRange = getTokenSourceMapRange; + /** + * Gets the constant value to emit for an expression. + */ + function getConstantValue(node) { + var emitNode = node.emitNode; + return emitNode && emitNode.constantValue; + } + ts.getConstantValue = getConstantValue; + /** + * Sets the constant value to emit for an expression. + */ + function setConstantValue(node, value) { + var emitNode = getOrCreateEmitNode(node); + emitNode.constantValue = value; + return node; + } + ts.setConstantValue = setConstantValue; function setTextRange(node, location) { if (location) { node.pos = location.pos; @@ -12376,13 +12781,13 @@ var ts; } ts.getLocalNameForExternalImport = getLocalNameForExternalImport; /** - * Get the name of a target module from an import/export declaration as should be written in the emitted output. - * The emitted output name can be different from the input if: - * 1. The module has a /// - * 2. --out or --outFile is used, making the name relative to the rootDir - * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System). - * Otherwise, a new StringLiteral node representing the module name will be returned. - */ + * Get the name of a target module from an import/export declaration as should be written in the emitted output. + * The emitted output name can be different from the input if: + * 1. The module has a /// + * 2. --out or --outFile is used, making the name relative to the rootDir + * 3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System). + * Otherwise, a new StringLiteral node representing the module name will be returned. + */ function getExternalModuleNameLiteral(importNode, sourceFile, host, resolver, compilerOptions) { var moduleName = ts.getExternalModuleName(importNode); if (moduleName.kind === 9 /* StringLiteral */) { @@ -13683,8 +14088,8 @@ var ts; // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery return token() === 18 /* CloseParenToken */ || token() === 20 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/; case 18 /* TypeArguments */: - // Tokens other than '>' are here for better error recovery - return token() === 27 /* GreaterThanToken */ || token() === 17 /* OpenParenToken */; + // All other tokens should cause the type-argument to terminate except comma token + return token() !== 24 /* CommaToken */; case 20 /* HeritageClauses */: return token() === 15 /* OpenBraceToken */ || token() === 16 /* CloseBraceToken */; case 13 /* JsxAttributes */: @@ -14135,7 +14540,7 @@ var ts; } function parseTemplateExpression() { var template = createNode(189 /* TemplateExpression */); - template.head = parseTemplateLiteralFragment(); + template.head = parseTemplateHead(); ts.Debug.assert(template.head.kind === 12 /* TemplateHead */, "Template head has wrong token kind"); var templateSpans = createNodeArray(); do { @@ -14151,7 +14556,7 @@ var ts; var literal; if (token() === 16 /* CloseBraceToken */) { reScanTemplateToken(); - literal = parseTemplateLiteralFragment(); + literal = parseTemplateMiddleOrTemplateTail(); } else { literal = parseExpectedToken(14 /* TemplateTail */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(16 /* CloseBraceToken */)); @@ -14162,8 +14567,15 @@ var ts; function parseLiteralNode(internName) { return parseLiteralLikeNode(token(), internName); } - function parseTemplateLiteralFragment() { - return parseLiteralLikeNode(token(), /*internName*/ false); + function parseTemplateHead() { + var fragment = parseLiteralLikeNode(token(), /*internName*/ false); + ts.Debug.assert(fragment.kind === 12 /* TemplateHead */, "Template head has wrong token kind"); + return fragment; + } + function parseTemplateMiddleOrTemplateTail() { + var fragment = parseLiteralLikeNode(token(), /*internName*/ false); + ts.Debug.assert(fragment.kind === 13 /* TemplateMiddle */ || fragment.kind === 14 /* TemplateTail */, "Template fragment has wrong token kind"); + return fragment; } function parseLiteralLikeNode(kind, internName) { var node = createNode(kind); @@ -17144,7 +17556,7 @@ var ts; parseExpected(56 /* EqualsToken */); node.type = parseType(); parseSemicolon(); - return finishNode(node); + return addJSDocComment(finishNode(node)); } // In an ambient declaration, the grammar only allows integer literals as initializers. // In a non-ambient declaration, the grammar allows uninitialized members only in a @@ -17702,6 +18114,7 @@ var ts; var parameter = createNode(142 /* Parameter */); parameter.type = parseJSDocType(); if (parseOptional(56 /* EqualsToken */)) { + // TODO(rbuckton): Can this be changed to SyntaxKind.QuestionToken? parameter.questionToken = createNode(56 /* EqualsToken */); } return finishNode(parameter); @@ -18895,6 +19308,7 @@ var ts; ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression"; ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals"; ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; + ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; })(ContainerFlags || (ContainerFlags = {})); var binder = createBinder(); function bindSourceFile(file, options) { @@ -18927,7 +19341,8 @@ var ts; var emitFlags; // If this file is an external module, then it is automatically in strict-mode according to // ES6. If it is not an external module, then we'll determine if it is in strict mode or - // not depending on if we see "use strict" in certain places (or if we hit a class/namespace). + // not depending on if we see "use strict" in certain places or if we hit a class/namespace + // or if compiler options contain alwaysStrict. var inStrictMode; var symbolCount = 0; var Symbol; @@ -18941,7 +19356,7 @@ var ts; file = f; options = opts; languageVersion = ts.getEmitScriptTarget(options); - inStrictMode = !!file.externalModuleIndicator; + inStrictMode = bindInStrictMode(file, opts); classifiableNames = ts.createMap(); symbolCount = 0; skipTransformFlagAggregation = ts.isDeclarationFile(file); @@ -18971,6 +19386,15 @@ var ts; subtreeTransformFlags = 0 /* None */; } return bindSourceFile; + function bindInStrictMode(file, opts) { + if (opts.alwaysStrict && !ts.isDeclarationFile(file)) { + // bind in strict mode source files with alwaysStrict option + return true; + } + else { + return !!file.externalModuleIndicator; + } + } function createSymbol(flags, name) { symbolCount++; return new Symbol(flags, name); @@ -19134,11 +19558,24 @@ var ts; var message_1 = symbol.flags & 2 /* BlockScopedVariable */ ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0; - ts.forEach(symbol.declarations, function (declaration) { - if (ts.hasModifier(declaration, 512 /* Default */)) { + if (symbol.declarations && symbol.declarations.length) { + // If the current node is a default export of some sort, then check if + // there are any other default exports that we need to error on. + // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set. + if (isDefaultExport) { message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; } - }); + else { + // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration. + // Error on multiple export default in the following case: + // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default + // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers) + if (symbol.declarations && symbol.declarations.length && + (isDefaultExport || (node.kind === 235 /* ExportAssignment */ && !node.isExportEquals))) { + message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports; + } + } + } ts.forEach(symbol.declarations, function (declaration) { file.bindDiagnostics.push(ts.createDiagnosticForNode(declaration.name || declaration, message_1, getDisplayName(declaration))); }); @@ -19243,7 +19680,7 @@ var ts; } else { currentFlow = { flags: 2 /* Start */ }; - if (containerFlags & 16 /* IsFunctionExpression */) { + if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { currentFlow.container = node; } currentReturnTarget = undefined; @@ -19705,7 +20142,11 @@ var ts; currentFlow = preTryFlow; bind(node.finallyBlock); } - currentFlow = finishFlowLabel(postFinallyLabel); + // if try statement has finally block and flow after finally block is unreachable - keep it + // otherwise use whatever flow was accumulated at postFinallyLabel + if (!node.finallyBlock || !(currentFlow.flags & 1 /* Unreachable */)) { + currentFlow = finishFlowLabel(postFinallyLabel); + } } function bindSwitchStatement(node) { var postSwitchLabel = createBranchLabel(); @@ -19840,7 +20281,7 @@ var ts; } else { ts.forEachChild(node, bind); - if (node.operator === 57 /* PlusEqualsToken */ || node.operator === 42 /* MinusMinusToken */) { + if (node.operator === 41 /* PlusPlusToken */ || node.operator === 42 /* MinusMinusToken */) { bindAssignmentTargetFlow(node.operand); } } @@ -19942,9 +20383,12 @@ var ts; return 1 /* IsContainer */ | 32 /* HasLocals */; case 256 /* SourceFile */: return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */; + case 147 /* MethodDeclaration */: + if (ts.isObjectLiteralOrClassExpressionMethod(node)) { + return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */; + } case 148 /* Constructor */: case 220 /* FunctionDeclaration */: - case 147 /* MethodDeclaration */: case 146 /* MethodSignature */: case 149 /* GetAccessor */: case 150 /* SetAccessor */: @@ -20588,10 +21032,13 @@ var ts; bindAnonymousDeclaration(node, 8388608 /* Alias */, getDeclarationName(node)); } else { + // An export default clause with an expression exports a value + // We want to exclude both class and function here, this is necessary to issue an error when there are both + // default export-assignment and default export function and class declaration. var flags = node.kind === 235 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node) ? 8388608 /* Alias */ : 4 /* Property */; - declareSymbol(container.symbol.exports, container.symbol, node, flags, 0 /* PropertyExcludes */ | 8388608 /* AliasExcludes */); + declareSymbol(container.symbol.exports, container.symbol, node, flags, 4 /* Property */ | 8388608 /* AliasExcludes */ | 32 /* Class */ | 16 /* Function */); } } function bindNamespaceExportDeclaration(node) { @@ -20829,6 +21276,9 @@ var ts; emitFlags |= 2048 /* HasDecorators */; } } + if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) { + node.flowNode = currentFlow; + } return ts.hasDynamicName(node) ? bindAnonymousDeclaration(node, symbolFlags, "__computed") : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes); @@ -20994,8 +21444,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // If the parameter's name is 'this', then it is TypeScript syntax. - if (subtreeFlags & 2048 /* ContainsDecorators */ - || (name && ts.isIdentifier(name) && name.originalKeywordKind === 97 /* ThisKeyword */)) { + if (subtreeFlags & 2048 /* ContainsDecorators */ || ts.isThisIdentifier(name)) { transformFlags |= 3 /* AssertTypeScript */; } // If a parameter has an accessibility modifier, then it is TypeScript syntax. @@ -21128,7 +21577,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } // Currently, we only support generators that were originally async function bodies. - if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152 /* AsyncFunctionBody */) { transformFlags |= 1536 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -21190,7 +21639,7 @@ var ts; // down-level generator. // Currently we do not support transforming any other generator fucntions // down level. - if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152 /* AsyncFunctionBody */) { transformFlags |= 1536 /* AssertGenerator */; } } @@ -21216,7 +21665,7 @@ var ts; // down-level generator. // Currently we do not support transforming any other generator fucntions // down level. - if (asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (asteriskToken && ts.getEmitFlags(node) & 2097152 /* AsyncFunctionBody */) { transformFlags |= 1536 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; @@ -21500,6 +21949,677 @@ var ts; return transformFlags & ~excludeFlags; } })(ts || (ts = {})); +/// +/// +var ts; +(function (ts) { + function trace(host, message) { + host.trace(ts.formatMessage.apply(undefined, arguments)); + } + ts.trace = trace; + /* @internal */ + function isTraceEnabled(compilerOptions, host) { + return compilerOptions.traceResolution && host.trace !== undefined; + } + ts.isTraceEnabled = isTraceEnabled; + /* @internal */ + function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { + return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; + } + ts.createResolvedModule = createResolvedModule; + function moduleHasNonRelativeName(moduleName) { + return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); + } + function tryReadTypesSection(packageJsonPath, baseDirectory, state) { + var jsonContent = readJson(packageJsonPath, state.host); + function tryReadFromField(fieldName) { + if (ts.hasProperty(jsonContent, fieldName)) { + var typesFile = jsonContent[fieldName]; + if (typeof typesFile === "string") { + var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); + } + return typesFilePath_1; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); + } + } + } + } + var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); + if (typesFilePath) { + return typesFilePath; + } + // Use the main module for inferring types if no types package specified and the allowJs is set + if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); + } + var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); + return mainFilePath; + } + return undefined; + } + function readJson(path, host) { + try { + var jsonText = host.readFile(path); + return jsonText ? JSON.parse(jsonText) : {}; + } + catch (e) { + // gracefully handle if readFile fails or returns not JSON + return {}; + } + } + var typeReferenceExtensions = [".d.ts"]; + function getEffectiveTypeRoots(options, host) { + if (options.typeRoots) { + return options.typeRoots; + } + var currentDirectory; + if (options.configFilePath) { + currentDirectory = ts.getDirectoryPath(options.configFilePath); + } + else if (host.getCurrentDirectory) { + currentDirectory = host.getCurrentDirectory(); + } + return currentDirectory !== undefined && getDefaultTypeRoots(currentDirectory, host); + } + ts.getEffectiveTypeRoots = getEffectiveTypeRoots; + /** + * Returns the path to every node_modules/@types directory from some ancestor directory. + * Returns undefined if there are none. + */ + function getDefaultTypeRoots(currentDirectory, host) { + if (!host.directoryExists) { + return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; + } + var typeRoots; + while (true) { + var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); + if (host.directoryExists(atTypes)) { + (typeRoots || (typeRoots = [])).push(atTypes); + } + var parent_7 = ts.getDirectoryPath(currentDirectory); + if (parent_7 === currentDirectory) { + break; + } + currentDirectory = parent_7; + } + return typeRoots; + } + var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); + /** + * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. + * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups + * is assumed to be the same as root directory of the project. + */ + function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { + var traceEnabled = isTraceEnabled(options, host); + var moduleResolutionState = { + compilerOptions: options, + host: host, + skipTsx: true, + traceEnabled: traceEnabled + }; + var typeRoots = getEffectiveTypeRoots(options, host); + if (traceEnabled) { + if (containingFile === undefined) { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); + } + } + else { + if (typeRoots === undefined) { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); + } + else { + trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); + } + } + } + var failedLookupLocations = []; + // Check primary library paths + if (typeRoots && typeRoots.length) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); + } + var primarySearchPaths = typeRoots; + for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { + var typeRoot = primarySearchPaths_1[_i]; + var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); + var candidateDirectory = ts.getDirectoryPath(candidate); + var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); + if (resolvedFile_1) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); + } + return { + resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, + failedLookupLocations: failedLookupLocations + }; + } + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); + } + } + var resolvedFile; + var initialLocationForSecondaryLookup; + if (containingFile) { + initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); + } + if (initialLocationForSecondaryLookup !== undefined) { + // check secondary locations + if (traceEnabled) { + trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); + } + resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState, /*checkOneLevel*/ false); + if (traceEnabled) { + if (resolvedFile) { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); + } + else { + trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); + } + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); + } + } + return { + resolvedTypeReferenceDirective: resolvedFile + ? { primary: false, resolvedFileName: resolvedFile } + : undefined, + failedLookupLocations: failedLookupLocations + }; + } + ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; + /** + * Given a set of options, returns the set of type directive names + * that should be included for this program automatically. + * This list could either come from the config file, + * or from enumerating the types root + initial secondary types lookup location. + * More type directives might appear in the program later as a result of loading actual source files; + * this list is only the set of defaults that are implicitly included. + */ + function getAutomaticTypeDirectiveNames(options, host) { + // Use explicit type list from tsconfig.json + if (options.types) { + return options.types; + } + // Walk the primary type lookup locations + var result = []; + if (host.directoryExists && host.getDirectories) { + var typeRoots = getEffectiveTypeRoots(options, host); + if (typeRoots) { + for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { + var root = typeRoots_1[_i]; + if (host.directoryExists(root)) { + for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { + var typeDirectivePath = _b[_a]; + var normalized = ts.normalizePath(typeDirectivePath); + var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); + // tslint:disable-next-line:no-null-keyword + var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; + if (!isNotNeededPackage) { + // Return just the type directive names + result.push(ts.getBaseFileName(normalized)); + } + } + } + } + } + } + return result; + } + ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); + } + var moduleResolution = compilerOptions.moduleResolution; + if (moduleResolution === undefined) { + moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; + if (traceEnabled) { + trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + else { + if (traceEnabled) { + trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); + } + } + var result; + switch (moduleResolution) { + case ts.ModuleResolutionKind.NodeJs: + result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); + break; + case ts.ModuleResolutionKind.Classic: + result = classicNameResolver(moduleName, containingFile, compilerOptions, host); + break; + } + if (traceEnabled) { + if (result.resolvedModule) { + trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); + } + else { + trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); + } + } + return result; + } + ts.resolveModuleName = resolveModuleName; + /** + * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to + * mitigate differences between design time structure of the project and its runtime counterpart so the same import name + * can be resolved successfully by TypeScript compiler and runtime module loader. + * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will + * fallback to standard resolution routine. + * + * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative + * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will + * be '/a/b/c/d' + * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names + * will be resolved based on the content of the module name. + * Structure of 'paths' compiler options + * 'paths': { + * pattern-1: [...substitutions], + * pattern-2: [...substitutions], + * ... + * pattern-n: [...substitutions] + * } + * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against + * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. + * If pattern contains '*' then to match pattern "*" module name must start with the and end with . + * denotes part of the module name between and . + * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. + * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module + * from the candidate location. + * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every + * substitution in the list and replace '*' with string. If candidate location is not rooted it + * will be converted to absolute using baseUrl. + * For example: + * baseUrl: /a/b/c + * "paths": { + * // match all module names + * "*": [ + * "*", // use matched name as is, + * // will be looked as /a/b/c/ + * + * "folder1/*" // substitution will convert matched name to 'folder1/', + * // since it is not rooted then final candidate location will be /a/b/c/folder1/ + * ], + * // match module names that start with 'components/' + * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', + * // it is rooted so it will be final candidate location + * } + * + * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if + * they were in the same location. For example lets say there are two files + * '/local/src/content/file1.ts' + * '/shared/components/contracts/src/content/protocols/file2.ts' + * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so + * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. + * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all + * root dirs were merged together. + * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. + * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: + * '/local/src/content/protocols/file2' and try to load it - failure. + * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will + * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining + * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. + */ + function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (moduleHasNonRelativeName(moduleName)) { + return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); + } + else { + return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); + } + } + function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.rootDirs) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); + } + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var matchedRootDir; + var matchedNormalizedPrefix; + for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { + var rootDir = _a[_i]; + // rootDirs are expected to be absolute + // in case of tsconfig.json this will happen automatically - compiler will expand relative names + // using location of tsconfig.json as base location + var normalizedRoot = ts.normalizePath(rootDir); + if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { + normalizedRoot += ts.directorySeparator; + } + var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && + (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); + } + if (isLongestMatchingPrefix) { + matchedNormalizedPrefix = normalizedRoot; + matchedRootDir = rootDir; + } + } + if (matchedNormalizedPrefix) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); + } + var suffix = candidate.substr(matchedNormalizedPrefix.length); + // first - try to load from a initial location + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); + } + // then try to resolve using remaining entries in rootDirs + for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { + var rootDir = _c[_b]; + if (rootDir === matchedRootDir) { + // skip the initially matched entry + continue; + } + var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); + } + var baseDirectory = ts.getDirectoryPath(candidate_1); + var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); + if (resolvedFileName_1) { + return resolvedFileName_1; + } + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); + } + } + return undefined; + } + function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { + if (!state.compilerOptions.baseUrl) { + return undefined; + } + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); + } + // string is for exact match + var matchedPattern = undefined; + if (state.compilerOptions.paths) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); + } + matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); + } + if (matchedPattern) { + var matchedStar = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); + } + for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { + var subst = _a[_i]; + var path = matchedStar ? subst.replace("*", matchedStar) : subst; + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); + } + var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + if (resolvedFileName) { + return resolvedFileName; + } + } + return undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); + } + return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); + } + } + function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { + var containingDirectory = ts.getDirectoryPath(containingFile); + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var traceEnabled = isTraceEnabled(compilerOptions, host); + var failedLookupLocations = []; + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); + var isExternalLibraryImport = false; + if (!resolvedFileName) { + if (moduleHasNonRelativeName(moduleName)) { + if (traceEnabled) { + trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); + } + resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state, /*checkOneLevel*/ false); + isExternalLibraryImport = resolvedFileName !== undefined; + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + } + } + if (resolvedFileName && host.realpath) { + var originalFileName = resolvedFileName; + resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); + if (traceEnabled) { + trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); + } + } + return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); + } + ts.nodeModuleNameResolver = nodeModuleNameResolver; + function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); + } + var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); + return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); + } + /* @internal */ + function directoryProbablyExists(directoryName, host) { + // if host does not support 'directoryExists' assume that directory will exist + return !host.directoryExists || host.directoryExists(directoryName); + } + ts.directoryProbablyExists = directoryProbablyExists; + /** + * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary + * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. + */ + function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" + var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); + if (resolvedByAddingExtension) { + return resolvedByAddingExtension; + } + // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; + // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" + if (ts.hasJavaScriptFileExtension(candidate)) { + var extensionless = ts.removeFileExtension(candidate); + if (state.traceEnabled) { + var extension = candidate.substring(extensionless.length); + trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); + } + return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); + } + } + /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ + function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures) { + // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing + var directory = ts.getDirectoryPath(candidate); + if (directory) { + onlyRecordFailures = !directoryProbablyExists(directory, state.host); + } + } + return ts.forEach(extensions, function (ext) { + return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); + }); + } + /** Return the file if it exists. */ + function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { + if (!onlyRecordFailures && state.host.fileExists(fileName)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); + } + return fileName; + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); + } + failedLookupLocation.push(fileName); + return undefined; + } + } + function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { + var packageJsonPath = pathToPackageJson(candidate); + var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); + if (directoryExists && state.host.fileExists(packageJsonPath)) { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); + if (typesFile) { + var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); + // A package.json "typings" may specify an exact filename, or may choose to omit an extension. + var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || + tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); + if (result) { + return result; + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); + } + } + } + else { + if (state.traceEnabled) { + trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); + } + // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results + failedLookupLocation.push(packageJsonPath); + } + return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); + } + function pathToPackageJson(directory) { + return ts.combinePaths(directory, "package.json"); + } + function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { + var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); + var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); + var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); + var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); + var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); + if (result) { + return result; + } + } + /* @internal */ + function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, /*typesOnly*/ false); + } + ts.loadModuleFromNodeModules = loadModuleFromNodeModules; + function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, /*checkOneLevel*/ false, /*typesOnly*/ true); + } + function loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, typesOnly) { + directory = ts.normalizeSlashes(directory); + while (true) { + var baseName = ts.getBaseFileName(directory); + if (baseName !== "node_modules") { + var packageResult = void 0; + if (!typesOnly) { + // Try to load source from the package + packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); + if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { + // Always prefer a TypeScript (.ts, .tsx, .d.ts) file shipped with the package + return packageResult; + } + } + // Else prefer a types package over non-TypeScript results (e.g. JavaScript files) + var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); + if (typesResult || packageResult) { + return typesResult || packageResult; + } + } + var parentPath = ts.getDirectoryPath(directory); + if (parentPath === directory || checkOneLevel) { + break; + } + directory = parentPath; + } + return undefined; + } + function classicNameResolver(moduleName, containingFile, compilerOptions, host) { + var traceEnabled = isTraceEnabled(compilerOptions, host); + var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; + var failedLookupLocations = []; + var supportedExtensions = ts.getSupportedExtensions(compilerOptions); + var containingDirectory = ts.getDirectoryPath(containingFile); + var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); + if (resolvedFileName) { + return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ false, failedLookupLocations); + } + var referencedSourceFile; + if (moduleHasNonRelativeName(moduleName)) { + referencedSourceFile = referencedSourceFile = loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) || + // If we didn't find the file normally, look it up in @types. + loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); + } + else { + var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + } + return referencedSourceFile + ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } + : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; + } + ts.classicNameResolver = classicNameResolver; + /** Climb up parent directories looking for a module. */ + function loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) { + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); + if (referencedSourceFile) { + return referencedSourceFile; + } + var parentPath = ts.getDirectoryPath(containingDirectory); + if (parentPath === containingDirectory) { + return undefined; + } + containingDirectory = parentPath; + } + } +})(ts || (ts = {})); +/// /// /* @internal */ var ts; @@ -21607,6 +22727,7 @@ var ts; var unknownSymbol = createSymbol(4 /* Property */ | 67108864 /* Transient */, "unknown"); var resolvingSymbol = createSymbol(67108864 /* Transient */, "__resolving__"); var anyType = createIntrinsicType(1 /* Any */, "any"); + var autoType = createIntrinsicType(1 /* Any */, "any"); var unknownType = createIntrinsicType(1 /* Any */, "unknown"); var undefinedType = createIntrinsicType(2048 /* Undefined */, "undefined"); var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(2048 /* Undefined */ | 33554432 /* ContainsWideningType */, "undefined"); @@ -22350,7 +23471,7 @@ var ts; if (result && isInExternalModule && (meaning & 107455 /* Value */) === 107455 /* Value */) { var decls = result.declarations; if (decls && decls.length === 1 && decls[0].kind === 228 /* NamespaceExportDeclaration */) { - error(errorLocation, ts.Diagnostics.Identifier_0_must_be_imported_from_a_module, name); + error(errorLocation, ts.Diagnostics._0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead, name); } } } @@ -22833,6 +23954,8 @@ var ts; } function getExportsForModule(moduleSymbol) { var visitedSymbols = []; + // A module defined by an 'export=' consists on one export that needs to be resolved + moduleSymbol = resolveExternalModuleSymbol(moduleSymbol); return visit(moduleSymbol) || moduleSymbol.exports; // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example, // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error. @@ -23407,9 +24530,9 @@ var ts; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { // Go up and add our parent. - var parent_7 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent_7) { - walkSymbol(parent_7, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); + var parent_8 = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); + if (parent_8) { + walkSymbol(parent_8, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); } } if (accessibleSymbolChain) { @@ -23453,7 +24576,7 @@ var ts; ? "any" : type.intrinsicName); } - else if (type.flags & 268435456 /* ThisType */) { + else if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { if (inObjectTypeLiteral) { writer.reportInaccessibleThisError(); } @@ -23471,9 +24594,14 @@ var ts; // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); } - else if (!(flags & 512 /* InTypeAlias */) && type.flags & (2097152 /* Anonymous */ | 1572864 /* UnionOrIntersection */) && type.aliasSymbol && + else if (!(flags & 512 /* InTypeAlias */) && ((type.flags & 2097152 /* Anonymous */ && !type.target) || type.flags & 1572864 /* UnionOrIntersection */) && type.aliasSymbol && isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { - // Only write out inferred type with its corresponding type-alias if type-alias is visible + // We emit inferred type as type-alias at the current localtion if all the following is true + // the input type is has alias symbol that is accessible + // the input type is a union, intersection or anonymous type that is fully instantiated (if not we want to keep dive into) + // e.g.: export type Bar = () => [X, Y]; + // export type Foo = Bar; + // export const y = (x: Foo) => 1 // we want to emit as ...x: () => [any, string]) var typeArguments = type.aliasTypeArguments; writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); } @@ -23549,14 +24677,14 @@ var ts; while (i < length_1) { // Find group of type arguments for type parameters with the same declaring container. var start = i; - var parent_8 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); + var parent_9 = getParentSymbolOfTypeParameter(outerTypeParameters[i]); do { i++; - } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_8); + } while (i < length_1 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent_9); // When type parameters are their own type arguments for the whole group (i.e. we have // the default outer type arguments), we don't show the group. if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent_8, typeArguments, start, i, flags); + writeSymbolTypeReference(parent_9, typeArguments, start, i, flags); writePunctuation(writer, 21 /* DotToken */); } } @@ -23960,14 +25088,14 @@ var ts; if (ts.isExternalModuleAugmentation(node)) { return true; } - var parent_9 = getDeclarationContainer(node); + var parent_10 = getDeclarationContainer(node); // If the node is not exported or it is not ambient module element (except import declaration) if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) && - !(node.kind !== 229 /* ImportEqualsDeclaration */ && parent_9.kind !== 256 /* SourceFile */ && ts.isInAmbientContext(parent_9))) { - return isGlobalSourceFile(parent_9); + !(node.kind !== 229 /* ImportEqualsDeclaration */ && parent_10.kind !== 256 /* SourceFile */ && ts.isInAmbientContext(parent_10))) { + return isGlobalSourceFile(parent_10); } // Exported members/ambient module elements (exception import declaration) are visible if parent is visible - return isDeclarationVisible(parent_9); + return isDeclarationVisible(parent_10); case 145 /* PropertyDeclaration */: case 144 /* PropertySignature */: case 149 /* GetAccessor */: @@ -24274,6 +25402,10 @@ var ts; } return undefined; } + function isAutoVariableInitializer(initializer) { + var expr = initializer && ts.skipParentheses(initializer); + return !expr || expr.kind === 93 /* NullKeyword */ || expr.kind === 69 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol; + } function addOptionality(type, optional) { return strictNullChecks && optional ? includeFalsyTypes(type, 2048 /* Undefined */) : type; } @@ -24306,6 +25438,13 @@ var ts; if (declaration.type) { return addOptionality(getTypeFromTypeNode(declaration.type), /*optional*/ declaration.questionToken && includeOptionality); } + // Use control flow type inference for non-ambient, non-exported var or let variables with no initializer + // or a 'null' or 'undefined' initializer. + if (declaration.kind === 218 /* VariableDeclaration */ && !ts.isBindingPattern(declaration.name) && + !(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && + !ts.isInAmbientContext(declaration) && isAutoVariableInitializer(declaration.initializer)) { + return autoType; + } if (declaration.kind === 142 /* Parameter */) { var func = declaration.parent; // For a parameter of a set accessor, use the type of the get accessor if one is present @@ -24389,7 +25528,7 @@ var ts; result.pattern = pattern; } if (hasComputedProperties) { - result.flags |= 536870912 /* ObjectLiteralPatternWithComputedProperties */; + result.isObjectLiteralPatternWithComputedProperties = true; } return result; } @@ -24935,7 +26074,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */ | 268435456 /* ThisType */); + type.thisType = createType(16384 /* TypeParameter */); + type.thisType.isThisType = true; type.thisType.symbol = symbol; type.thisType.constraint = type; } @@ -25509,7 +26649,7 @@ var ts; var current = _a[_i]; for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) { var prop = _c[_b]; - getPropertyOfUnionOrIntersectionType(type, prop.name); + getUnionOrIntersectionProperty(type, prop.name); } // The properties of a union type are those that are present in all constituent types, so // we only need to check the properties of the first type @@ -25517,7 +26657,19 @@ var ts; break; } } - return type.resolvedProperties ? symbolsToArray(type.resolvedProperties) : emptyArray; + var props = type.resolvedProperties; + if (props) { + var result = []; + for (var key in props) { + var prop = props[key]; + // We need to filter out partial properties in union types + if (!(prop.flags & 268435456 /* SyntheticProperty */ && prop.isPartial)) { + result.push(prop); + } + } + return result; + } + return emptyArray; } function getPropertiesOfType(type) { type = getApparentType(type); @@ -25566,6 +26718,7 @@ var ts; // Flags we want to propagate to the result if they exist in all source symbols var commonFlags = (containingType.flags & 1048576 /* Intersection */) ? 536870912 /* Optional */ : 0 /* None */; var isReadonly = false; + var isPartial = false; for (var _i = 0, types_2 = types; _i < types_2.length; _i++) { var current = types_2[_i]; var type = getApparentType(current); @@ -25584,21 +26737,20 @@ var ts; } } else if (containingType.flags & 524288 /* Union */) { - // A union type requires the property to be present in all constituent types - return undefined; + isPartial = true; } } } if (!props) { return undefined; } - if (props.length === 1) { + if (props.length === 1 && !isPartial) { return props[0]; } var propTypes = []; var declarations = []; var commonType = undefined; - var hasCommonType = true; + var hasNonUniformType = false; for (var _a = 0, props_1 = props; _a < props_1.length; _a++) { var prop = props_1[_a]; if (prop.declarations) { @@ -25609,22 +26761,25 @@ var ts; commonType = type; } else if (type !== commonType) { - hasCommonType = false; + hasNonUniformType = true; } - propTypes.push(getTypeOfSymbol(prop)); + propTypes.push(type); } - var result = createSymbol(4 /* Property */ | - 67108864 /* Transient */ | - 268435456 /* SyntheticProperty */ | - commonFlags, name); + var result = createSymbol(4 /* Property */ | 67108864 /* Transient */ | 268435456 /* SyntheticProperty */ | commonFlags, name); result.containingType = containingType; - result.hasCommonType = hasCommonType; + result.hasNonUniformType = hasNonUniformType; + result.isPartial = isPartial; result.declarations = declarations; result.isReadonly = isReadonly; result.type = containingType.flags & 524288 /* Union */ ? getUnionType(propTypes) : getIntersectionType(propTypes); return result; } - function getPropertyOfUnionOrIntersectionType(type, name) { + // Return the symbol for a given property in a union or intersection type, or undefined if the property + // does not exist in any constituent type. Note that the returned property may only be present in some + // constituents, in which case the isPartial flag is set when the containing type is union type. We need + // these partial properties when identifying discriminant properties, but otherwise they are filtered out + // and do not appear to be present in the union type. + function getUnionOrIntersectionProperty(type, name) { var properties = type.resolvedProperties || (type.resolvedProperties = ts.createMap()); var property = properties[name]; if (!property) { @@ -25635,6 +26790,11 @@ var ts; } return property; } + function getPropertyOfUnionOrIntersectionType(type, name) { + var property = getUnionOrIntersectionProperty(type, name); + // We need to filter out partial properties in union types + return property && !(property.flags & 268435456 /* SyntheticProperty */ && property.isPartial) ? property : undefined; + } /** * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from @@ -26040,7 +27200,7 @@ var ts; } function hasConstraintReferenceTo(type, target) { var checked; - while (type && !(type.flags & 268435456 /* ThisType */) && type.flags & 16384 /* TypeParameter */ && !ts.contains(checked, type)) { + while (type && type.flags & 16384 /* TypeParameter */ && !(type.isThisType) && !ts.contains(checked, type)) { if (type === target) { return true; } @@ -26365,7 +27525,8 @@ var ts; type.instantiations[getTypeListId(type.typeParameters)] = type; type.target = type; type.typeArguments = type.typeParameters; - type.thisType = createType(16384 /* TypeParameter */ | 268435456 /* ThisType */); + type.thisType = createType(16384 /* TypeParameter */); + type.thisType.isThisType = true; type.thisType.constraint = type; type.declaredProperties = properties; type.declaredCallSignatures = emptyArray; @@ -26466,7 +27627,24 @@ var ts; } return false; } + function isSetOfLiteralsFromSameEnum(types) { + var first = types[0]; + if (first.flags & 256 /* EnumLiteral */) { + var firstEnum = getParentOfSymbol(first.symbol); + for (var i = 1; i < types.length; i++) { + var other = types[i]; + if (!(other.flags & 256 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) { + return false; + } + } + return true; + } + return false; + } function removeSubtypes(types) { + if (types.length === 0 || isSetOfLiteralsFromSameEnum(types)) { + return; + } var i = types.length; while (i > 0) { i--; @@ -27553,7 +28731,8 @@ var ts; !t.numberIndexInfo; } function hasExcessProperties(source, target, reportErrors) { - if (!(target.flags & 536870912 /* ObjectLiteralPatternWithComputedProperties */) && maybeTypeOfKind(target, 2588672 /* ObjectType */)) { + if (maybeTypeOfKind(target, 2588672 /* ObjectType */) && + (!(target.flags & 2588672 /* ObjectType */) || !target.isObjectLiteralPatternWithComputedProperties)) { for (var _i = 0, _a = getPropertiesOfObjectType(source); _i < _a.length; _i++) { var prop = _a[_i]; if (!isKnownProperty(target, prop.name)) { @@ -28917,21 +30096,10 @@ var ts; } function isDiscriminantProperty(type, name) { if (type && type.flags & 524288 /* Union */) { - var prop = getPropertyOfType(type, name); - if (!prop) { - // The type may be a union that includes nullable or primitive types. If filtering - // those out produces a different type, get the property from that type instead. - // Effectively, we're checking if this *could* be a discriminant property once nullable - // and primitive types are removed by other type guards. - var filteredType = getTypeWithFacts(type, 4194304 /* Discriminatable */); - if (filteredType !== type && filteredType.flags & 524288 /* Union */) { - prop = getPropertyOfType(filteredType, name); - } - } + var prop = getUnionOrIntersectionProperty(type, name); if (prop && prop.flags & 268435456 /* SyntheticProperty */) { if (prop.isDiscriminantProperty === undefined) { - prop.isDiscriminantProperty = !prop.hasCommonType && - isLiteralType(getTypeOfSymbol(prop)); + prop.isDiscriminantProperty = prop.hasNonUniformType && isLiteralType(getTypeOfSymbol(prop)); } return prop.isDiscriminantProperty; } @@ -29218,6 +30386,26 @@ var ts; } return f(type) ? type : neverType; } + function mapType(type, f) { + return type.flags & 524288 /* Union */ ? getUnionType(ts.map(type.types, f)) : f(type); + } + function extractTypesOfKind(type, kind) { + return filterType(type, function (t) { return (t.flags & kind) !== 0; }); + } + // Return a new type in which occurrences of the string and number primitive types in + // typeWithPrimitives have been replaced with occurrences of string literals and numeric + // literals in typeWithLiterals, respectively. + function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) { + if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 32 /* StringLiteral */) || + isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 64 /* NumberLiteral */)) { + return mapType(typeWithPrimitives, function (t) { + return t.flags & 2 /* String */ ? extractTypesOfKind(typeWithLiterals, 2 /* String */ | 32 /* StringLiteral */) : + t.flags & 4 /* Number */ ? extractTypesOfKind(typeWithLiterals, 4 /* Number */ | 64 /* NumberLiteral */) : + t; + }); + } + return typeWithPrimitives; + } function isIncomplete(flowType) { return flowType.flags === 0; } @@ -29232,7 +30420,9 @@ var ts; if (!reference.flowNode || assumeInitialized && !(declaredType.flags & 4178943 /* Narrowable */)) { return declaredType; } - var initialType = assumeInitialized ? declaredType : includeFalsyTypes(declaredType, 2048 /* Undefined */); + var initialType = assumeInitialized ? declaredType : + declaredType === autoType ? undefinedType : + includeFalsyTypes(declaredType, 2048 /* Undefined */); var visitedFlowStart = visitedFlowCount; var result = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode)); visitedFlowCount = visitedFlowStart; @@ -29304,10 +30494,13 @@ var ts; // Assignments only narrow the computed type if the declared type is a union type. Thus, we // only need to evaluate the assigned type if the declared type is a union type. if (isMatchingReference(reference, node)) { - var isIncrementOrDecrement = node.parent.kind === 185 /* PrefixUnaryExpression */ || node.parent.kind === 186 /* PostfixUnaryExpression */; - return declaredType.flags & 524288 /* Union */ && !isIncrementOrDecrement ? - getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : - declaredType; + if (node.parent.kind === 185 /* PrefixUnaryExpression */ || node.parent.kind === 186 /* PostfixUnaryExpression */) { + var flowType = getTypeAtFlowNode(flow.antecedent); + return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType)); + } + return declaredType === autoType ? getBaseTypeOfLiteralType(getInitialOrAssignedType(node)) : + declaredType.flags & 524288 /* Union */ ? getAssignmentReducedType(declaredType, getInitialOrAssignedType(node)) : + declaredType; } // We didn't have a direct match. However, if the reference is a dotted name, this // may be an assignment to a left hand part of the reference. For example, for a @@ -29531,12 +30724,12 @@ var ts; assumeTrue ? 16384 /* EQUndefined */ : 131072 /* NEUndefined */; return getTypeWithFacts(type, facts); } - if (type.flags & 2589191 /* NotUnionOrUnit */) { + if (type.flags & 2589185 /* NotUnionOrUnit */) { return type; } if (assumeTrue) { var narrowedType = filterType(type, function (t) { return areTypesComparable(t, valueType); }); - return narrowedType.flags & 8192 /* Never */ ? type : narrowedType; + return narrowedType.flags & 8192 /* Never */ ? type : replacePrimitivesWithLiterals(narrowedType, valueType); } if (isUnitType(valueType)) { var regularType_1 = getRegularTypeOfLiteralType(valueType); @@ -29581,7 +30774,8 @@ var ts; var clauseTypes = switchTypes.slice(clauseStart, clauseEnd); var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType); var discriminantType = getUnionType(clauseTypes); - var caseType = discriminantType.flags & 8192 /* Never */ ? neverType : filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }); + var caseType = discriminantType.flags & 8192 /* Never */ ? neverType : + replacePrimitivesWithLiterals(filterType(type, function (t) { return isTypeComparableTo(discriminantType, t); }), discriminantType); if (!hasDefaultClause) { return caseType; } @@ -29728,7 +30922,7 @@ var ts; if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) { location = location.parent; } - if (ts.isExpression(location) && !ts.isAssignmentTarget(location)) { + if (ts.isPartOfExpression(location) && !ts.isAssignmentTarget(location)) { var type = checkExpression(location); if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) { return type; @@ -29877,20 +31071,32 @@ var ts; // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. while (flowContainer !== declarationContainer && - (flowContainer.kind === 179 /* FunctionExpression */ || flowContainer.kind === 180 /* ArrowFunction */) && + (flowContainer.kind === 179 /* FunctionExpression */ || + flowContainer.kind === 180 /* ArrowFunction */ || + ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isReadonlySymbol(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } // We only look for uninitialized variables in strict null checking mode, and only when we can analyze // the entire control flow graph from the variable's declaration (i.e. when the flow container and // declaration container are the same). - var assumeInitialized = !strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isParameter || - isOuterVariable || ts.isInAmbientContext(declaration); + var assumeInitialized = isParameter || isOuterVariable || + type !== autoType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0) || + ts.isInAmbientContext(declaration); var flowType = getFlowTypeOfReference(node, type, assumeInitialized, flowContainer); // A variable is considered uninitialized when it is possible to analyze the entire control flow graph // from declaration to use, and when the variable's declared type doesn't include undefined but the // control flow based type does include undefined. - if (!assumeInitialized && !(getFalsyFlags(type) & 2048 /* Undefined */) && getFalsyFlags(flowType) & 2048 /* Undefined */) { + if (type === autoType) { + if (flowType === autoType) { + if (compilerOptions.noImplicitAny) { + error(declaration.name, ts.Diagnostics.Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined, symbolToString(symbol)); + error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(anyType)); + } + return anyType; + } + } + else if (!assumeInitialized && !(getFalsyFlags(type) & 2048 /* Undefined */) && getFalsyFlags(flowType) & 2048 /* Undefined */) { error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol)); // Return the declared type to reduce follow-on errors return type; @@ -29988,7 +31194,7 @@ var ts; } } function findFirstSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return n; } else if (ts.isFunctionLike(n)) { @@ -30081,7 +31287,7 @@ var ts; captureLexicalThis(node, container); } if (ts.isFunctionLike(container) && - (!isInParameterInitializerBeforeContainingFunction(node) || getFunctionLikeThisParameter(container))) { + (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. // If this is a function in a JS file, it might be a class method. Check if it's the RHS // of a x.prototype.y = function [name]() { .... } @@ -30141,8 +31347,8 @@ var ts; var isCallExpression = node.parent.kind === 174 /* CallExpression */ && node.parent.expression === node; var container = ts.getSuperContainer(node, /*stopOnFunctions*/ true); var needToCaptureLexicalThis = false; + // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting if (!isCallExpression) { - // adjust the container reference in case if super is used inside arrow functions with arbitrary deep nesting while (container && container.kind === 180 /* ArrowFunction */) { container = ts.getSuperContainer(container, /*stopOnFunctions*/ true); needToCaptureLexicalThis = languageVersion < 2 /* ES6 */; @@ -30954,7 +32160,8 @@ var ts; patternWithComputedProperties = true; } } - else if (contextualTypeHasPattern && !(contextualType.flags & 536870912 /* ObjectLiteralPatternWithComputedProperties */)) { + else if (contextualTypeHasPattern && + !(contextualType.flags & 2588672 /* ObjectType */ && contextualType.isObjectLiteralPatternWithComputedProperties)) { // If object literal is contextually typed by the implied type of a binding pattern, and if the // binding pattern specifies a default value for the property, make the property optional. var impliedProp = getPropertyOfType(contextualType, member.name); @@ -31014,7 +32221,10 @@ var ts; var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, propertiesArray, 1 /* Number */) : undefined; var result = createAnonymousType(node.symbol, propertiesTable, emptyArray, emptyArray, stringIndexInfo, numberIndexInfo); var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 16777216 /* FreshLiteral */; - result.flags |= 8388608 /* ObjectLiteral */ | 67108864 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 234881024 /* PropagatingFlags */) | (patternWithComputedProperties ? 536870912 /* ObjectLiteralPatternWithComputedProperties */ : 0); + result.flags |= 8388608 /* ObjectLiteral */ | 67108864 /* ContainsObjectLiteral */ | freshObjectLiteralFlag | (typeFlags & 234881024 /* PropagatingFlags */); + if (patternWithComputedProperties) { + result.isObjectLiteralPatternWithComputedProperties = true; + } if (inDestructuringPattern) { result.pattern = node; } @@ -31523,7 +32733,7 @@ var ts; return true; } // An instance property must be accessed through an instance of the enclosing class - if (type.flags & 268435456 /* ThisType */) { + if (type.flags & 16384 /* TypeParameter */ && type.isThisType) { // get the original type -- represented as the type constraint of the 'this' type type = getConstraintOfTypeParameter(type); } @@ -31567,7 +32777,7 @@ var ts; var prop = getPropertyOfType(apparentType, right.text); if (!prop) { if (right.text && !checkAndReportErrorForExtendingInterface(node)) { - reportNonexistentProperty(right, type.flags & 268435456 /* ThisType */ ? apparentType : type); + reportNonexistentProperty(right, type.flags & 16384 /* TypeParameter */ && type.isThisType ? apparentType : type); } return unknownType; } @@ -31848,13 +33058,13 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var signature = signatures_2[_i]; var symbol = signature.declaration && getSymbolOfNode(signature.declaration); - var parent_10 = signature.declaration && signature.declaration.parent; + var parent_11 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { - if (lastParent && parent_10 === lastParent) { + if (lastParent && parent_11 === lastParent) { index++; } else { - lastParent = parent_10; + lastParent = parent_11; index = cutoffIndex; } } @@ -31862,7 +33072,7 @@ var ts; // current declaration belongs to a different symbol // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex index = cutoffIndex = result.length; - lastParent = parent_10; + lastParent = parent_11; } lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless @@ -33121,7 +34331,9 @@ var ts; if (!contextualSignature) { reportErrorsFromWidening(func, type); } - if (isUnitType(type) && !(contextualSignature && isLiteralContextualType(getReturnTypeOfSignature(contextualSignature)))) { + if (isUnitType(type) && + !(contextualSignature && + isLiteralContextualType(contextualSignature === getSignatureFromDeclaration(func) ? type : getReturnTypeOfSignature(contextualSignature)))) { type = getWidenedLiteralType(type); } var widenedType = getWidenedType(type); @@ -33305,7 +34517,7 @@ var ts; } } } - if (produceDiagnostics && node.kind !== 147 /* MethodDeclaration */ && node.kind !== 146 /* MethodSignature */) { + if (produceDiagnostics && node.kind !== 147 /* MethodDeclaration */) { checkCollisionWithCapturedSuperVariable(node, node.name); checkCollisionWithCapturedThisVariable(node, node.name); } @@ -34388,9 +35600,9 @@ var ts; case 156 /* FunctionType */: case 147 /* MethodDeclaration */: case 146 /* MethodSignature */: - var parent_11 = node.parent; - if (node === parent_11.type) { - return parent_11; + var parent_12 = node.parent; + if (node === parent_12.type) { + return parent_12; } } } @@ -34628,7 +35840,7 @@ var ts; return n.name && containsSuperCall(n.name); } function containsSuperCall(n) { - if (ts.isSuperCallExpression(n)) { + if (ts.isSuperCall(n)) { return true; } else if (ts.isFunctionLike(n)) { @@ -34657,6 +35869,7 @@ var ts; // constructors of derived classes must contain at least one super call somewhere in their function body. var containingClassDecl = node.parent; if (ts.getClassExtendsHeritageClauseElement(containingClassDecl)) { + captureLexicalThis(node.parent, containingClassDecl); var classExtendsNull = classDeclarationExtendsNull(containingClassDecl); var superCall = getSuperCallInConstructor(node); if (superCall) { @@ -34677,7 +35890,7 @@ var ts; var superCallStatement = void 0; for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) { var statement = statements_2[_i]; - if (statement.kind === 202 /* ExpressionStatement */ && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 202 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { superCallStatement = statement; break; } @@ -35607,7 +36820,7 @@ var ts; var parameter = local.valueDeclaration; if (compilerOptions.noUnusedParameters && !ts.isParameterPropertyDeclaration(parameter) && - !parameterIsThisKeyword(parameter) && + !ts.parameterIsThisKeyword(parameter) && !parameterNameStartsWithUnderscore(parameter)) { error(local.valueDeclaration.name, ts.Diagnostics._0_is_declared_but_never_used, local.name); } @@ -35622,9 +36835,6 @@ var ts; } } } - function parameterIsThisKeyword(parameter) { - return parameter.name && parameter.name.originalKeywordKind === 97 /* ThisKeyword */; - } function parameterNameStartsWithUnderscore(parameter) { return parameter.name && parameter.name.kind === 69 /* Identifier */ && parameter.name.text.charCodeAt(0) === 95 /* _ */; } @@ -35772,6 +36982,10 @@ var ts; } } function checkCollisionWithRequireExportsInGeneratedCode(node, name) { + // No need to check for require or exports for ES6 modules and later + if (modulekind >= ts.ModuleKind.ES6) { + return; + } if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) { return; } @@ -35926,6 +37140,9 @@ var ts; } } } + function convertAutoToAny(type) { + return type === autoType ? anyType : type; + } // Check variable, parameter, or property declaration function checkVariableLikeDeclaration(node) { checkDecorators(node); @@ -35946,12 +37163,12 @@ var ts; checkComputedPropertyName(node.propertyName); } // check private/protected variable access - var parent_12 = node.parent.parent; - var parentType = getTypeForBindingElementParent(parent_12); + var parent_13 = node.parent.parent; + var parentType = getTypeForBindingElementParent(parent_13); var name_21 = node.propertyName || node.name; var property = getPropertyOfType(parentType, getTextOfPropertyName(name_21)); - if (parent_12.initializer && property && getParentOfSymbol(property)) { - checkClassPropertyAccess(parent_12, parent_12.initializer, parentType, property); + if (parent_13.initializer && property && getParentOfSymbol(property)) { + checkClassPropertyAccess(parent_13, parent_13.initializer, parentType, property); } } // For a binding pattern, check contained binding elements @@ -35973,7 +37190,7 @@ var ts; return; } var symbol = getSymbolOfNode(node); - var type = getTypeOfVariableOrParameterOrProperty(symbol); + var type = convertAutoToAny(getTypeOfVariableOrParameterOrProperty(symbol)); if (node === symbol.valueDeclaration) { // Node is the primary declaration of the symbol, just validate the initializer // Don't validate for-in initializer as it is already an error @@ -35985,7 +37202,7 @@ var ts; else { // Node is a secondary declaration, check that type is identical to primary declaration and check that // initializer is consistent with type associated with the node - var declarationType = getWidenedTypeForVariableLikeDeclaration(node); + var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node)); if (type !== unknownType && declarationType !== unknownType && !isTypeIdenticalTo(type, declarationType)) { error(node.name, ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2, ts.declarationNameToString(node.name), typeToString(type), typeToString(declarationType)); } @@ -36480,7 +37697,12 @@ var ts; } } checkExpression(node.expression); - error(node.expression, ts.Diagnostics.All_symbols_within_a_with_block_will_be_resolved_to_any); + var sourceFile = ts.getSourceFileOfNode(node); + if (!hasParseDiagnostics(sourceFile)) { + var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start; + var end = node.statement.pos; + grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any); + } } function checkSwitchStatement(node) { // Grammar checking @@ -37288,9 +38510,11 @@ var ts; grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names); } } - checkCollisionWithCapturedThisVariable(node, node.name); - checkCollisionWithRequireExportsInGeneratedCode(node, node.name); - checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + if (ts.isIdentifier(node.name)) { + checkCollisionWithCapturedThisVariable(node, node.name); + checkCollisionWithRequireExportsInGeneratedCode(node, node.name); + checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name); + } checkExportsOnMergedDeclarations(node); var symbol = getSymbolOfNode(node); // The following checks only apply on a non-ambient instantiated module declaration. @@ -37568,9 +38792,11 @@ var ts; } } function checkGrammarModuleElementContext(node, errorMessage) { - if (node.parent.kind !== 256 /* SourceFile */ && node.parent.kind !== 226 /* ModuleBlock */ && node.parent.kind !== 225 /* ModuleDeclaration */) { - return grammarErrorOnFirstToken(node, errorMessage); + var isInAppropriateContext = node.parent.kind === 256 /* SourceFile */ || node.parent.kind === 226 /* ModuleBlock */ || node.parent.kind === 225 /* ModuleDeclaration */; + if (!isInAppropriateContext) { + grammarErrorOnFirstToken(node, errorMessage); } + return !isInAppropriateContext; } function checkExportSpecifier(node) { checkAliasSymbol(node); @@ -37668,7 +38894,8 @@ var ts; links.exportsChecked = true; } function isNotOverload(declaration) { - return declaration.kind !== 220 /* FunctionDeclaration */ || !!declaration.body; + return (declaration.kind !== 220 /* FunctionDeclaration */ && declaration.kind !== 147 /* MethodDeclaration */) || + !!declaration.body; } } function checkSourceElement(node) { @@ -38202,6 +39429,9 @@ var ts; node.parent.moduleSpecifier === node)) { return resolveExternalModuleName(node, node); } + if (ts.isInJavaScriptFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false)) { + return resolveExternalModuleName(node, node); + } // Fall through case 8 /* NumericLiteral */: // index access @@ -38726,9 +39956,9 @@ var ts; if (startInDeclarationContainer) { // When resolving the name of a declaration as a value, we need to start resolution // at a point outside of the declaration. - var parent_13 = reference.parent; - if (ts.isDeclaration(parent_13) && reference === parent_13.name) { - location = getDeclarationContainer(parent_13); + var parent_14 = reference.parent; + if (ts.isDeclaration(parent_14) && reference === parent_14.name) { + location = getDeclarationContainer(parent_14); } } return resolveName(location, reference.text, 107455 /* Value */ | 1048576 /* ExportValue */ | 8388608 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined); @@ -38852,9 +40082,9 @@ var ts; // external modules cannot define or contribute to type declaration files var current = symbol; while (true) { - var parent_14 = getParentOfSymbol(current); - if (parent_14) { - current = parent_14; + var parent_15 = getParentOfSymbol(current); + if (parent_15) { + current = parent_15; } else { break; @@ -39437,8 +40667,8 @@ var ts; function checkGrammarForOmittedArgument(node, args) { if (args) { var sourceFile = ts.getSourceFileOfNode(node); - for (var _i = 0, args_2 = args; _i < args_2.length; _i++) { - var arg = args_2[_i]; + for (var _i = 0, args_4 = args; _i < args_4.length; _i++) { + var arg = args_4[_i]; if (arg.kind === 193 /* OmittedExpression */) { return grammarErrorAtPos(sourceFile, arg.pos, 0, ts.Diagnostics.Argument_expression_expected); } @@ -39550,8 +40780,7 @@ var ts; for (var _i = 0, _a = node.properties; _i < _a.length; _i++) { var prop = _a[_i]; var name_24 = prop.name; - if (prop.kind === 193 /* OmittedExpression */ || - name_24.kind === 140 /* ComputedPropertyName */) { + if (name_24.kind === 140 /* ComputedPropertyName */) { // If the name is not a ComputedPropertyName, the grammar checking will skip it checkGrammarComputedPropertyName(name_24); } @@ -39731,17 +40960,8 @@ var ts; return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 149 /* GetAccessor */ ? 0 : 1); } function getAccessorThisParameter(accessor) { - if (accessor.parameters.length === (accessor.kind === 149 /* GetAccessor */ ? 1 : 2) && - accessor.parameters[0].name.kind === 69 /* Identifier */ && - accessor.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */) { - return accessor.parameters[0]; - } - } - function getFunctionLikeThisParameter(func) { - if (func.parameters.length && - func.parameters[0].name.kind === 69 /* Identifier */ && - func.parameters[0].name.originalKeywordKind === 97 /* ThisKeyword */) { - return func.parameters[0]; + if (accessor.parameters.length === (accessor.kind === 149 /* GetAccessor */ ? 1 : 2)) { + return ts.getThisParameter(accessor); } } function checkGrammarForNonSymbolComputedProperty(node, message) { @@ -40673,7 +41893,7 @@ var ts; case 175 /* NewExpression */: return ts.updateNew(node, visitNode(node.expression, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNodes(node.arguments, visitor, ts.isExpression)); case 176 /* TaggedTemplateExpression */: - return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplate)); + return ts.updateTaggedTemplate(node, visitNode(node.tag, visitor, ts.isExpression), visitNode(node.template, visitor, ts.isTemplateLiteral)); case 178 /* ParenthesizedExpression */: return ts.updateParen(node, visitNode(node.expression, visitor, ts.isExpression)); case 179 /* FunctionExpression */: @@ -40697,7 +41917,7 @@ var ts; case 188 /* ConditionalExpression */: return ts.updateConditional(node, visitNode(node.condition, visitor, ts.isExpression), visitNode(node.whenTrue, visitor, ts.isExpression), visitNode(node.whenFalse, visitor, ts.isExpression)); case 189 /* TemplateExpression */: - return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateLiteralFragment), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); + return ts.updateTemplateExpression(node, visitNode(node.head, visitor, ts.isTemplateHead), visitNodes(node.templateSpans, visitor, ts.isTemplateSpan)); case 190 /* YieldExpression */: return ts.updateYield(node, visitNode(node.expression, visitor, ts.isExpression)); case 191 /* SpreadElementExpression */: @@ -40708,7 +41928,7 @@ var ts; return ts.updateExpressionWithTypeArguments(node, visitNodes(node.typeArguments, visitor, ts.isTypeNode), visitNode(node.expression, visitor, ts.isExpression)); // Misc case 197 /* TemplateSpan */: - return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateLiteralFragment)); + return ts.updateTemplateSpan(node, visitNode(node.expression, visitor, ts.isExpression), visitNode(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail)); // Element case 199 /* Block */: return ts.updateBlock(node, visitNodes(node.statements, visitor, ts.isStatement)); @@ -41055,7 +42275,7 @@ var ts; var expression = ts.createAssignment(name, value, location); // NOTE: this completely disables source maps, but aligns with the behavior of // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(expression, 2048 /* NoNestedSourceMaps */); + ts.setEmitFlags(expression, 2048 /* NoNestedSourceMaps */); ts.aggregateTransformFlags(expression); expressions.push(expression); } @@ -41081,7 +42301,7 @@ var ts; var declaration = ts.createVariableDeclaration(name, /*type*/ undefined, value, location); // NOTE: this completely disables source maps, but aligns with the behavior of // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); + ts.setEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); ts.aggregateTransformFlags(declaration); declarations.push(declaration); } @@ -41114,7 +42334,7 @@ var ts; declaration.original = original; // NOTE: this completely disables source maps, but aligns with the behavior of // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); + ts.setEmitFlags(declaration, 2048 /* NoNestedSourceMaps */); declarations.push(declaration); ts.aggregateTransformFlags(declaration); } @@ -41164,7 +42384,7 @@ var ts; expression.original = original; // NOTE: this completely disables source maps, but aligns with the behavior of // `emitAssignment` in the old emitter. - context.setNodeEmitFlags(expression, 2048 /* NoNestedSourceMaps */); + ts.setEmitFlags(expression, 2048 /* NoNestedSourceMaps */); pendingAssignments.push(expression); return expression; } @@ -41210,8 +42430,8 @@ var ts; } else { var name_26 = ts.getMutableClone(target); - context.setSourceMapRange(name_26, target); - context.setCommentRange(name_26, target); + ts.setSourceMapRange(name_26, target); + ts.setCommentRange(name_26, target); emitAssignment(name_26, value, location, /*original*/ undefined); } } @@ -41380,7 +42600,7 @@ var ts; TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers"; })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {})); function transformTypeScript(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, setCommentRange = context.setCommentRange, setSourceMapRange = context.setSourceMapRange, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -41391,11 +42611,15 @@ var ts; // Set new transformation hooks. context.onEmitNode = onEmitNode; context.onSubstituteNode = onSubstituteNode; + // Enable substitution for property/element access to emit const enum values. + context.enableSubstitution(172 /* PropertyAccessExpression */); + context.enableSubstitution(173 /* ElementAccessExpression */); // These variables contain state that changes as we descend into the tree. var currentSourceFile; var currentNamespace; var currentNamespaceContainerName; var currentScope; + var currentScopeFirstDeclarationsOfName; var currentSourceFileExternalHelpersModuleName; /** * Keeps track of whether expression substitution has been enabled for specific edge cases. @@ -41424,6 +42648,9 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitNode(node, visitor, ts.isSourceFile); } /** @@ -41434,10 +42661,14 @@ var ts; function saveStateAndInvoke(node, f) { // Save state var savedCurrentScope = currentScope; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; // Handle state changes before visiting a node. onBeforeVisitNode(node); var visited = f(node); // Restore state + if (currentScope !== savedCurrentScope) { + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; + } currentScope = savedCurrentScope; return visited; } @@ -41702,11 +42933,23 @@ var ts; case 226 /* ModuleBlock */: case 199 /* Block */: currentScope = node; + currentScopeFirstDeclarationsOfName = undefined; + break; + case 221 /* ClassDeclaration */: + case 220 /* FunctionDeclaration */: + if (ts.hasModifier(node, 2 /* Ambient */)) { + break; + } + recordEmittedDeclarationInScope(node); break; } } function visitSourceFile(node) { currentSourceFile = node; + // ensure "use strict" is emitted in all scenarios in alwaysStrict mode + if (compilerOptions.alwaysStrict) { + node = ts.ensureUseStrict(node); + } // If the source file requires any helpers and is an external module, and // the importHelpers compiler option is enabled, emit a synthesized import // statement for the helpers library. @@ -41733,7 +42976,7 @@ var ts; else { node = ts.visitEachChild(node, visitor, context); } - setNodeEmitFlags(node, 1 /* EmitEmitHelpers */ | node.emitFlags); + ts.setEmitFlags(node, 1 /* EmitEmitHelpers */ | ts.getEmitFlags(node)); return node; } /** @@ -41792,7 +43035,7 @@ var ts; // To better align with the old emitter, we should not emit a trailing source map // entry if the class has static properties. if (staticProperties.length > 0) { - setNodeEmitFlags(classDeclaration, 1024 /* NoTrailingSourceMap */ | getNodeEmitFlags(classDeclaration)); + ts.setEmitFlags(classDeclaration, 1024 /* NoTrailingSourceMap */ | ts.getEmitFlags(classDeclaration)); } statements.push(classDeclaration); } @@ -41951,7 +43194,7 @@ var ts; /*type*/ undefined, classExpression) ]), /*location*/ location); - setCommentRange(transformedClassExpression, node); + ts.setCommentRange(transformedClassExpression, node); statements.push(ts.setOriginalNode( /*node*/ transformedClassExpression, /*original*/ node)); @@ -41996,7 +43239,7 @@ var ts; } // To preserve the behavior of the old emitter, we explicitly indent // the body of a class with static initializers. - setNodeEmitFlags(classExpression, 524288 /* Indented */ | getNodeEmitFlags(classExpression)); + ts.setEmitFlags(classExpression, 524288 /* Indented */ | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); ts.addRange(expressions, generateInitializedPropertyExpressions(node, staticProperties, temp)); expressions.push(ts.startOnNewLine(temp)); @@ -42151,7 +43394,7 @@ var ts; return index; } var statement = statements[index]; - if (statement.kind === 202 /* ExpressionStatement */ && ts.isSuperCallExpression(statement.expression)) { + if (statement.kind === 202 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) { result.push(ts.visitNode(statement, visitor, ts.isStatement)); return index + 1; } @@ -42185,9 +43428,9 @@ var ts; ts.Debug.assert(ts.isIdentifier(node.name)); var name = node.name; var propertyName = ts.getMutableClone(name); - setNodeEmitFlags(propertyName, 49152 /* NoComments */ | 1536 /* NoSourceMap */); + ts.setEmitFlags(propertyName, 49152 /* NoComments */ | 1536 /* NoSourceMap */); var localName = ts.getMutableClone(name); - setNodeEmitFlags(localName, 49152 /* NoComments */); + ts.setEmitFlags(localName, 49152 /* NoComments */); return ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createThis(), propertyName, /*location*/ node.name), localName), /*location*/ ts.moveRangePos(node, -1))); @@ -42239,8 +43482,8 @@ var ts; for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var property = properties_7[_i]; var statement = ts.createStatement(transformInitializedProperty(node, property, receiver)); - setSourceMapRange(statement, ts.moveRangePastModifiers(property)); - setCommentRange(statement, property); + ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property)); + ts.setCommentRange(statement, property); statements.push(statement); } } @@ -42257,8 +43500,8 @@ var ts; var property = properties_8[_i]; var expression = transformInitializedProperty(node, property, receiver); expression.startsOnNewLine = true; - setSourceMapRange(expression, ts.moveRangePastModifiers(property)); - setCommentRange(expression, property); + ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property)); + ts.setCommentRange(expression, property); expressions.push(expression); } return expressions; @@ -42524,7 +43767,7 @@ var ts; : ts.createNull() : undefined; var helper = ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, prefix, memberName, descriptor, ts.moveRangePastDecorators(member)); - setNodeEmitFlags(helper, 49152 /* NoComments */); + ts.setEmitFlags(helper, 49152 /* NoComments */); return helper; } /** @@ -42562,12 +43805,12 @@ var ts; if (decoratedClassAlias) { var expression = ts.createAssignment(decoratedClassAlias, ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node))); var result = ts.createAssignment(getDeclarationName(node), expression, ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152 /* NoComments */); + ts.setEmitFlags(result, 49152 /* NoComments */); return result; } else { var result = ts.createAssignment(getDeclarationName(node), ts.createDecorateHelper(currentSourceFileExternalHelpersModuleName, decoratorExpressions, getDeclarationName(node)), ts.moveRangePastDecorators(node)); - setNodeEmitFlags(result, 49152 /* NoComments */); + ts.setEmitFlags(result, 49152 /* NoComments */); return result; } } @@ -42593,7 +43836,7 @@ var ts; var decorator = decorators_1[_i]; var helper = ts.createParamHelper(currentSourceFileExternalHelpersModuleName, transformDecorator(decorator), parameterOffset, /*location*/ decorator.expression); - setNodeEmitFlags(helper, 49152 /* NoComments */); + ts.setEmitFlags(helper, 49152 /* NoComments */); expressions.push(helper); } } @@ -42824,10 +44067,38 @@ var ts; : ts.createIdentifier("Symbol"); case 155 /* TypeReference */: return serializeTypeReferenceNode(node); + case 163 /* IntersectionType */: + case 162 /* UnionType */: + { + var unionOrIntersection = node; + var serializedUnion = void 0; + for (var _i = 0, _a = unionOrIntersection.types; _i < _a.length; _i++) { + var typeNode = _a[_i]; + var serializedIndividual = serializeTypeNode(typeNode); + // Non identifier + if (serializedIndividual.kind !== 69 /* Identifier */) { + serializedUnion = undefined; + break; + } + // One of the individual is global object, return immediately + if (serializedIndividual.text === "Object") { + return serializedIndividual; + } + // Different types + if (serializedUnion && serializedUnion.text !== serializedIndividual.text) { + serializedUnion = undefined; + break; + } + serializedUnion = serializedIndividual; + } + // If we were able to find common type + if (serializedUnion) { + return serializedUnion; + } + } + // Fallthrough case 158 /* TypeQuery */: case 159 /* TypeLiteral */: - case 162 /* UnionType */: - case 163 /* IntersectionType */: case 117 /* AnyKeyword */: case 165 /* ThisType */: break; @@ -43027,8 +44298,8 @@ var ts; /*location*/ node); // While we emit the source map for the node after skipping decorators and modifiers, // we need to emit the comments for the original range. - setCommentRange(method, node); - setSourceMapRange(method, ts.moveRangePastDecorators(node)); + ts.setCommentRange(method, node); + ts.setSourceMapRange(method, ts.moveRangePastDecorators(node)); ts.setOriginalNode(method, node); return method; } @@ -43060,8 +44331,8 @@ var ts; /*location*/ node); // While we emit the source map for the node after skipping decorators and modifiers, // we need to emit the comments for the original range. - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setCommentRange(accessor, node); + ts.setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); ts.setOriginalNode(accessor, node); return accessor; } @@ -43083,8 +44354,8 @@ var ts; /*location*/ node); // While we emit the source map for the node after skipping decorators and modifiers, // we need to emit the comments for the original range. - setCommentRange(accessor, node); - setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); + ts.setCommentRange(accessor, node); + ts.setSourceMapRange(accessor, ts.moveRangePastDecorators(node)); ts.setOriginalNode(accessor, node); return accessor; } @@ -43220,11 +44491,11 @@ var ts; if (languageVersion >= 2 /* ES6 */) { if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) { enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 8 /* EmitAdvancedSuperHelper */); + ts.setEmitFlags(block, 8 /* EmitAdvancedSuperHelper */); } else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) { enableSubstitutionForAsyncMethodsWithSuper(); - setNodeEmitFlags(block, 4 /* EmitSuperHelper */); + ts.setEmitFlags(block, 4 /* EmitSuperHelper */); } } return block; @@ -43244,7 +44515,7 @@ var ts; * @param node The parameter declaration node. */ function visitParameter(node) { - if (node.name && ts.isIdentifier(node.name) && node.name.originalKeywordKind === 97 /* ThisKeyword */) { + if (ts.parameterIsThisKeyword(node)) { return undefined; } var parameter = ts.createParameterDeclaration( @@ -43256,9 +44527,9 @@ var ts; // While we emit the source map for the node after skipping decorators and modifiers, // we need to emit the comments for the original range. ts.setOriginalNode(parameter, node); - setCommentRange(parameter, node); - setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); - setNodeEmitFlags(parameter.name, 1024 /* NoTrailingSourceMap */); + ts.setCommentRange(parameter, node); + ts.setSourceMapRange(parameter, ts.moveRangePastModifiers(node)); + ts.setEmitFlags(parameter.name, 1024 /* NoTrailingSourceMap */); return parameter; } /** @@ -43351,8 +44622,9 @@ var ts; || compilerOptions.isolatedModules; } function shouldEmitVarForEnumDeclaration(node) { - return !ts.hasModifier(node, 1 /* Export */) - || (isES6ExportedDeclaration(node) && ts.isFirstDeclarationOfKind(node, node.kind)); + return isFirstEmittedDeclarationInScope(node) + && (!ts.hasModifier(node, 1 /* Export */) + || isES6ExportedDeclaration(node)); } /* * Adds a trailing VariableStatement for an enum or module declaration. @@ -43361,7 +44633,7 @@ var ts; var statement = ts.createVariableStatement( /*modifiers*/ undefined, [ts.createVariableDeclaration(getDeclarationName(node), /*type*/ undefined, getExportName(node))]); - setSourceMapRange(statement, node); + ts.setSourceMapRange(statement, node); statements.push(statement); } /** @@ -43382,6 +44654,7 @@ var ts; // If needed, we should emit a variable declaration for the enum. If we emit // a leading variable declaration, we should not emit leading comments for the // enum body. + recordEmittedDeclarationInScope(node); if (shouldEmitVarForEnumDeclaration(node)) { addVarForEnumOrModuleDeclaration(statements, node); // We should still emit the comments if we are emitting a system module. @@ -43407,7 +44680,7 @@ var ts; /*typeArguments*/ undefined, [ts.createLogicalOr(exportName, ts.createAssignment(exportName, ts.createObjectLiteral()))]), /*location*/ node); ts.setOriginalNode(enumStatement, node); - setNodeEmitFlags(enumStatement, emitFlags); + ts.setEmitFlags(enumStatement, emitFlags); statements.push(enumStatement); if (isNamespaceExport(node)) { addVarForEnumExportedFromNamespace(statements, node); @@ -43473,18 +44746,43 @@ var ts; function shouldEmitModuleDeclaration(node) { return ts.isInstantiatedModule(node, compilerOptions.preserveConstEnums || compilerOptions.isolatedModules); } - function isModuleMergedWithES6Class(node) { - return languageVersion === 2 /* ES6 */ - && ts.isMergedWithClass(node); - } function isES6ExportedDeclaration(node) { return isExternalModuleExport(node) && moduleKind === ts.ModuleKind.ES6; } + /** + * Records that a declaration was emitted in the current scope, if it was the first + * declaration for the provided symbol. + * + * NOTE: if there is ever a transformation above this one, we may not be able to rely + * on symbol names. + */ + function recordEmittedDeclarationInScope(node) { + var name = node.symbol && node.symbol.name; + if (name) { + if (!currentScopeFirstDeclarationsOfName) { + currentScopeFirstDeclarationsOfName = ts.createMap(); + } + if (!(name in currentScopeFirstDeclarationsOfName)) { + currentScopeFirstDeclarationsOfName[name] = node; + } + } + } + /** + * Determines whether a declaration is the first declaration with the same name emitted + * in the current scope. + */ + function isFirstEmittedDeclarationInScope(node) { + if (currentScopeFirstDeclarationsOfName) { + var name_28 = node.symbol && node.symbol.name; + if (name_28) { + return currentScopeFirstDeclarationsOfName[name_28] === node; + } + } + return false; + } function shouldEmitVarForModuleDeclaration(node) { - return !isModuleMergedWithES6Class(node) - && (!isES6ExportedDeclaration(node) - || ts.isFirstDeclarationOfKind(node, node.kind)); + return isFirstEmittedDeclarationInScope(node); } /** * Adds a leading VariableStatement for a enum or module declaration. @@ -43499,10 +44797,10 @@ var ts; ts.setOriginalNode(statement, /*original*/ node); // Adjust the source map emit to match the old emitter. if (node.kind === 224 /* EnumDeclaration */) { - setSourceMapRange(statement.declarationList, node); + ts.setSourceMapRange(statement.declarationList, node); } else { - setSourceMapRange(statement, node); + ts.setSourceMapRange(statement, node); } // Trailing comments for module declaration should be emitted after the function closure // instead of the variable statement: @@ -43522,8 +44820,8 @@ var ts; // } // })(m1 || (m1 = {})); // trailing comment module // - setCommentRange(statement, node); - setNodeEmitFlags(statement, 32768 /* NoTrailingComments */); + ts.setCommentRange(statement, node); + ts.setEmitFlags(statement, 32768 /* NoTrailingComments */); statements.push(statement); } /** @@ -43546,6 +44844,7 @@ var ts; // If needed, we should emit a variable declaration for the module. If we emit // a leading variable declaration, we should not emit leading comments for the // module body. + recordEmittedDeclarationInScope(node); if (shouldEmitVarForModuleDeclaration(node)) { addVarForEnumOrModuleDeclaration(statements, node); // We should still emit the comments if we are emitting a system module. @@ -43579,7 +44878,7 @@ var ts; /*typeArguments*/ undefined, [moduleArg]), /*location*/ node); ts.setOriginalNode(moduleStatement, node); - setNodeEmitFlags(moduleStatement, emitFlags); + ts.setEmitFlags(moduleStatement, emitFlags); statements.push(moduleStatement); return statements; } @@ -43591,8 +44890,10 @@ var ts; function transformModuleBody(node, namespaceLocalName) { var savedCurrentNamespaceContainerName = currentNamespaceContainerName; var savedCurrentNamespace = currentNamespace; + var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName; currentNamespaceContainerName = namespaceLocalName; currentNamespace = node; + currentScopeFirstDeclarationsOfName = undefined; var statements = []; startLexicalEnvironment(); var statementsLocation; @@ -43619,6 +44920,7 @@ var ts; ts.addRange(statements, endLexicalEnvironment()); currentNamespaceContainerName = savedCurrentNamespaceContainerName; currentNamespace = savedCurrentNamespace; + currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName; var block = ts.createBlock(ts.createNodeArray(statements, /*location*/ statementsLocation), /*location*/ blockLocation, @@ -43644,7 +44946,7 @@ var ts; // })(hello || (hello = {})); // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces. if (body.kind !== 226 /* ModuleBlock */) { - setNodeEmitFlags(block, block.emitFlags | 49152 /* NoComments */); + ts.setEmitFlags(block, ts.getEmitFlags(block) | 49152 /* NoComments */); } return block; } @@ -43680,7 +44982,7 @@ var ts; return undefined; } var moduleReference = ts.createExpressionFromEntityName(node.moduleReference); - setNodeEmitFlags(moduleReference, 49152 /* NoComments */ | 65536 /* NoNestedComments */); + ts.setEmitFlags(moduleReference, 49152 /* NoComments */ | 65536 /* NoNestedComments */); if (isNamedExternalModuleExport(node) || !isNamespaceExport(node)) { // export var ${name} = ${moduleReference}; // var ${name} = ${moduleReference}; @@ -43736,9 +45038,9 @@ var ts; } function addExportMemberAssignment(statements, node) { var expression = ts.createAssignment(getExportName(node), getLocalName(node, /*noSourceMaps*/ true)); - setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); + ts.setSourceMapRange(expression, ts.createRange(node.name.pos, node.end)); var statement = ts.createStatement(expression); - setSourceMapRange(statement, ts.createRange(-1, node.end)); + ts.setSourceMapRange(statement, ts.createRange(-1, node.end)); statements.push(statement); } function createNamespaceExport(exportName, exportValue, location) { @@ -43761,7 +45063,7 @@ var ts; emitFlags |= 1536 /* NoSourceMap */; } if (emitFlags) { - setNodeEmitFlags(qualifiedName, emitFlags); + ts.setEmitFlags(qualifiedName, emitFlags); } return qualifiedName; } @@ -43773,7 +45075,7 @@ var ts; */ function getNamespaceParameterName(node) { var name = ts.getGeneratedNameForNode(node); - setSourceMapRange(name, node.name); + ts.setSourceMapRange(name, node.name); return name; } /** @@ -43822,8 +45124,8 @@ var ts; */ function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { if (node.name) { - var name_28 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); + var name_29 = ts.getMutableClone(node.name); + emitFlags |= ts.getEmitFlags(node.name); if (!allowSourceMaps) { emitFlags |= 1536 /* NoSourceMap */; } @@ -43831,9 +45133,9 @@ var ts; emitFlags |= 49152 /* NoComments */; } if (emitFlags) { - setNodeEmitFlags(name_28, emitFlags); + ts.setEmitFlags(name_29, emitFlags); } - return name_28; + return name_29; } else { return ts.getGeneratedNameForNode(node); @@ -43910,7 +45212,7 @@ var ts; * @param node The node to emit. * @param emit A callback used to emit the node in the printer. */ - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedApplicableSubstitutions = applicableSubstitutions; var savedCurrentSuperContainer = currentSuperContainer; // If we need to support substitutions for `super` in an async method, @@ -43924,7 +45226,7 @@ var ts; if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) { applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); applicableSubstitutions = savedApplicableSubstitutions; currentSuperContainer = savedCurrentSuperContainer; } @@ -43935,9 +45237,9 @@ var ts; * @param isExpression A value indicating whether the node is to be used in an expression * position. */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -43947,16 +45249,16 @@ var ts; } function substituteShorthandPropertyAssignment(node) { if (enabledSubstitutions & 2 /* NamespaceExports */) { - var name_29 = node.name; - var exportedName = trySubstituteNamespaceExportedName(name_29); + var name_30 = node.name; + var exportedName = trySubstituteNamespaceExportedName(name_30); if (exportedName) { // A shorthand property with an assignment initializer is probably part of a // destructuring assignment if (node.objectAssignmentInitializer) { var initializer = ts.createAssignment(exportedName, node.objectAssignmentInitializer); - return ts.createPropertyAssignment(name_29, initializer, /*location*/ node); + return ts.createPropertyAssignment(name_30, initializer, /*location*/ node); } - return ts.createPropertyAssignment(name_29, exportedName, /*location*/ node); + return ts.createPropertyAssignment(name_30, exportedName, /*location*/ node); } } return node; @@ -43965,16 +45267,15 @@ var ts; switch (node.kind) { case 69 /* Identifier */: return substituteExpressionIdentifier(node); - } - if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */) { - switch (node.kind) { - case 174 /* CallExpression */: + case 172 /* PropertyAccessExpression */: + return substitutePropertyAccessExpression(node); + case 173 /* ElementAccessExpression */: + return substituteElementAccessExpression(node); + case 174 /* CallExpression */: + if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */) { return substituteCallExpression(node); - case 172 /* PropertyAccessExpression */: - return substitutePropertyAccessExpression(node); - case 173 /* ElementAccessExpression */: - return substituteElementAccessExpression(node); - } + } + break; } return node; } @@ -43996,8 +45297,8 @@ var ts; var classAlias = classAliases[declaration.id]; if (classAlias) { var clone_4 = ts.getSynthesizedClone(classAlias); - setSourceMapRange(clone_4, node); - setCommentRange(clone_4, node); + ts.setSourceMapRange(clone_4, node); + ts.setCommentRange(clone_4, node); return clone_4; } } @@ -44007,7 +45308,7 @@ var ts; } function trySubstituteNamespaceExportedName(node) { // If this is explicitly a local name, do not substitute. - if (enabledSubstitutions & applicableSubstitutions && (getNodeEmitFlags(node) & 262144 /* LocalName */) === 0) { + if (enabledSubstitutions & applicableSubstitutions && (ts.getEmitFlags(node) & 262144 /* LocalName */) === 0) { // If we are nested within a namespace declaration, we may need to qualifiy // an identifier that is exported from a merged namespace. var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false); @@ -44038,23 +45339,48 @@ var ts; return node; } function substitutePropertyAccessExpression(node) { - if (node.expression.kind === 95 /* SuperKeyword */) { + if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */ && node.expression.kind === 95 /* SuperKeyword */) { var flags = getSuperContainerAsyncMethodFlags(); if (flags) { return createSuperAccessInAsyncMethod(ts.createLiteral(node.name.text), flags, node); } } - return node; + return substituteConstantValue(node); } function substituteElementAccessExpression(node) { - if (node.expression.kind === 95 /* SuperKeyword */) { + if (enabledSubstitutions & 4 /* AsyncMethodsWithSuper */ && node.expression.kind === 95 /* SuperKeyword */) { var flags = getSuperContainerAsyncMethodFlags(); if (flags) { return createSuperAccessInAsyncMethod(node.argumentExpression, flags, node); } } + return substituteConstantValue(node); + } + function substituteConstantValue(node) { + var constantValue = tryGetConstEnumValue(node); + if (constantValue !== undefined) { + var substitute = ts.createLiteral(constantValue); + ts.setSourceMapRange(substitute, node); + ts.setCommentRange(substitute, node); + if (!compilerOptions.removeComments) { + var propertyName = ts.isPropertyAccessExpression(node) + ? ts.declarationNameToString(node.name) + : ts.getTextOfNode(node.argumentExpression); + substitute.trailingComment = " " + propertyName + " "; + } + ts.setConstantValue(node, constantValue); + return substitute; + } return node; } + function tryGetConstEnumValue(node) { + if (compilerOptions.isolatedModules) { + return undefined; + } + return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) + ? resolver.getConstantValue(node) + : undefined; + } function createSuperAccessInAsyncMethod(argumentExpression, flags, location) { if (flags & 4096 /* AsyncMethodWithSuperBinding */) { return ts.createPropertyAccess(ts.createCall(ts.createIdentifier("_super"), @@ -44083,6 +45409,9 @@ var ts; var currentSourceFile; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; return ts.visitEachChild(node, visitor, context); @@ -44201,7 +45530,7 @@ var ts; var ts; (function (ts) { function transformSystemModule(context) { - var getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, hoistFunctionDeclaration = context.hoistFunctionDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -44230,6 +45559,9 @@ var ts; var currentNode; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; currentNode = node; @@ -44283,7 +45615,7 @@ var ts; ts.createParameter(exportFunctionForFile), ts.createParameter(contextObjectForFile) ], - /*type*/ undefined, setNodeEmitFlags(ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true), 1 /* EmitEmitHelpers */)); + /*type*/ undefined, ts.setEmitFlags(ts.createBlock(statements, /*location*/ undefined, /*multiLine*/ true), 1 /* EmitEmitHelpers */)); // Write the call to `System.register` // Clear the emit-helpers flag for later passes since we'll have already used it in the module body // So the helper will be emit at the correct position instead of at the top of the source-file @@ -44292,7 +45624,7 @@ var ts; /*typeArguments*/ undefined, moduleName ? [moduleName, dependencies, body] : [dependencies, body])) - ], /*nodeEmitFlags*/ ~1 /* EmitEmitHelpers */ & getNodeEmitFlags(node)); + ], /*nodeEmitFlags*/ ~1 /* EmitEmitHelpers */ & ts.getEmitFlags(node)); var _a; } /** @@ -44676,17 +46008,17 @@ var ts; function visitFunctionDeclaration(node) { if (ts.hasModifier(node, 1 /* Export */)) { // If the function is exported, ensure it has a name and rewrite the function without any export flags. - var name_30 = node.name || ts.getGeneratedNameForNode(node); + var name_31 = node.name || ts.getGeneratedNameForNode(node); var newNode = ts.createFunctionDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, node.asteriskToken, name_30, + /*modifiers*/ undefined, node.asteriskToken, name_31, /*typeParameters*/ undefined, node.parameters, /*type*/ undefined, node.body, /*location*/ node); // Record a declaration export in the outer module body function. recordExportedFunctionDeclaration(node); if (!ts.hasModifier(node, 512 /* Default */)) { - recordExportName(name_30); + recordExportName(name_31); } ts.setOriginalNode(newNode, node); node = newNode; @@ -44698,16 +46030,16 @@ var ts; function visitExpressionStatement(node) { var originalNode = ts.getOriginalNode(node); if ((originalNode.kind === 225 /* ModuleDeclaration */ || originalNode.kind === 224 /* EnumDeclaration */) && ts.hasModifier(originalNode, 1 /* Export */)) { - var name_31 = getDeclarationName(originalNode); + var name_32 = getDeclarationName(originalNode); // We only need to hoistVariableDeclaration for EnumDeclaration // as ModuleDeclaration is already hoisted when the transformer call visitVariableStatement // which then call transformsVariable for each declaration in declarationList if (originalNode.kind === 224 /* EnumDeclaration */) { - hoistVariableDeclaration(name_31); + hoistVariableDeclaration(name_32); } return [ node, - createExportStatement(name_31, name_31) + createExportStatement(name_32, name_32) ]; } return node; @@ -44952,14 +46284,14 @@ var ts; // // Substitutions // - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { if (node.kind === 256 /* SourceFile */) { exportFunctionForFile = exportFunctionForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); exportFunctionForFile = undefined; } else { - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); } } /** @@ -44969,9 +46301,9 @@ var ts; * @param isExpression A value indicating whether the node is to be used in an expression * position. */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } return node; @@ -45013,7 +46345,7 @@ var ts; return node; } function substituteAssignmentExpression(node) { - setNodeEmitFlags(node, 128 /* NoSubstitution */); + ts.setEmitFlags(node, 128 /* NoSubstitution */); var left = node.left; switch (left.kind) { case 69 /* Identifier */: @@ -45118,7 +46450,7 @@ var ts; var exportDeclaration = resolver.getReferencedExportContainer(operand); if (exportDeclaration) { var expr = ts.createPrefix(node.operator, operand, node); - setNodeEmitFlags(expr, 128 /* NoSubstitution */); + ts.setEmitFlags(expr, 128 /* NoSubstitution */); var call = createExportExpression(operand, expr); if (node.kind === 185 /* PrefixUnaryExpression */) { return call; @@ -45165,7 +46497,7 @@ var ts; ts.createForIn(ts.createVariableDeclarationList([ ts.createVariableDeclaration(n, /*type*/ undefined) ]), m, ts.createBlock([ - setNodeEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32 /* SingleLine */) + ts.setEmitFlags(ts.createIf(condition, ts.createStatement(ts.createAssignment(ts.createElementAccess(exports, n), ts.createElementAccess(m, n)))), 32 /* SingleLine */) ])), ts.createStatement(ts.createCall(exportFunctionForFile, /*typeArguments*/ undefined, [exports])) @@ -45283,7 +46615,7 @@ var ts; function updateSourceFile(node, statements, nodeEmitFlags) { var updated = ts.getMutableClone(node); updated.statements = ts.createNodeArray(statements, node.statements); - setNodeEmitFlags(updated, nodeEmitFlags); + ts.setEmitFlags(updated, nodeEmitFlags); return updated; } } @@ -45301,7 +46633,7 @@ var ts; _a[ts.ModuleKind.AMD] = transformAMDModule, _a[ts.ModuleKind.UMD] = transformUMDModule, _a)); - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, setNodeEmitFlags = context.setNodeEmitFlags, getNodeEmitFlags = context.getNodeEmitFlags, setSourceMapRange = context.setSourceMapRange; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var resolver = context.getEmitResolver(); var host = context.getEmitHost(); @@ -45333,6 +46665,9 @@ var ts; * @param node The SourceFile node. */ function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (ts.isExternalModule(node) || compilerOptions.isolatedModules) { currentSourceFile = node; // Collect information about the external module. @@ -45365,7 +46700,7 @@ var ts; addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false); var updated = updateSourceFile(node, statements); if (hasExportStarsToExportValues) { - setNodeEmitFlags(updated, 2 /* EmitExportStar */ | getNodeEmitFlags(node)); + ts.setEmitFlags(updated, 2 /* EmitExportStar */ | ts.getEmitFlags(node)); } return updated; } @@ -45386,7 +46721,7 @@ var ts; */ function transformUMDModule(node) { var define = ts.createIdentifier("define"); - setNodeEmitFlags(define, 16 /* UMDDefine */); + ts.setEmitFlags(define, 16 /* UMDDefine */); return transformAsynchronousModule(node, define, /*moduleName*/ undefined, /*includeNonAmdDependencies*/ false); } /** @@ -45466,7 +46801,7 @@ var ts; if (hasExportStarsToExportValues) { // If we have any `export * from ...` declarations // we need to inform the emitter to add the __export helper. - setNodeEmitFlags(body, 2 /* EmitExportStar */); + ts.setEmitFlags(body, 2 /* EmitExportStar */); } return body; } @@ -45475,13 +46810,13 @@ var ts; if (emitAsReturn) { var statement = ts.createReturn(exportEquals.expression, /*location*/ exportEquals); - setNodeEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 49152 /* NoComments */); + ts.setEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 49152 /* NoComments */); statements.push(statement); } else { var statement = ts.createStatement(ts.createAssignment(ts.createPropertyAccess(ts.createIdentifier("module"), "exports"), exportEquals.expression), /*location*/ exportEquals); - setNodeEmitFlags(statement, 49152 /* NoComments */); + ts.setEmitFlags(statement, 49152 /* NoComments */); statements.push(statement); } } @@ -45574,7 +46909,7 @@ var ts; } // Set emitFlags on the name of the importEqualsDeclaration // This is so the printer will not substitute the identifier - setNodeEmitFlags(node.name, 128 /* NoSubstitution */); + ts.setEmitFlags(node.name, 128 /* NoSubstitution */); var statements = []; if (moduleKind !== ts.ModuleKind.AMD) { if (ts.hasModifier(node, 1 /* Export */)) { @@ -45678,16 +47013,16 @@ var ts; else { var names = ts.reduceEachChild(node, collectExportMembers, []); for (var _i = 0, names_1 = names; _i < names_1.length; _i++) { - var name_32 = names_1[_i]; - addExportMemberAssignments(statements, name_32); + var name_33 = names_1[_i]; + addExportMemberAssignments(statements, name_33); } } } function collectExportMembers(names, node) { if (ts.isAliasSymbolDeclaration(node) && resolver.isValueAliasDeclaration(node) && ts.isDeclaration(node)) { - var name_33 = node.name; - if (ts.isIdentifier(name_33)) { - names.push(name_33); + var name_34 = node.name; + if (ts.isIdentifier(name_34)) { + names.push(name_34); } } return ts.reduceEachChild(node, collectExportMembers, names); @@ -45706,7 +47041,7 @@ var ts; addExportDefault(statements, getDeclarationName(node), /*location*/ node); } else { - statements.push(createExportStatement(node.name, setNodeEmitFlags(ts.getSynthesizedClone(node.name), 262144 /* LocalName */), /*location*/ node)); + statements.push(createExportStatement(node.name, ts.setEmitFlags(ts.getSynthesizedClone(node.name), 262144 /* LocalName */), /*location*/ node)); } } function visitVariableStatement(node) { @@ -45856,20 +47191,20 @@ var ts; /*modifiers*/ undefined, [ts.createVariableDeclaration(getDeclarationName(node), /*type*/ undefined, ts.createPropertyAccess(ts.createIdentifier("exports"), getDeclarationName(node)))], /*location*/ node); - setNodeEmitFlags(transformedStatement, 49152 /* NoComments */); + ts.setEmitFlags(transformedStatement, 49152 /* NoComments */); statements.push(transformedStatement); } function getDeclarationName(node) { return node.name ? ts.getSynthesizedClone(node.name) : ts.getGeneratedNameForNode(node); } - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { if (node.kind === 256 /* SourceFile */) { bindingNameExportSpecifiersMap = bindingNameExportSpecifiersForFileMap[ts.getOriginalNodeId(node)]; - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); bindingNameExportSpecifiersMap = undefined; } else { - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); } } /** @@ -45879,9 +47214,9 @@ var ts; * @param isExpression A value indicating whether the node is to be used in an expression * position. */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } else if (ts.isShorthandPropertyAssignment(node)) { @@ -45925,7 +47260,7 @@ var ts; // If the left-hand-side of the binaryExpression is an identifier and its is export through export Specifier if (ts.isIdentifier(left) && ts.isAssignmentOperator(node.operatorToken.kind)) { if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, left.text)) { - setNodeEmitFlags(node, 128 /* NoSubstitution */); + ts.setEmitFlags(node, 128 /* NoSubstitution */); var nestedExportAssignment = void 0; for (var _i = 0, _a = bindingNameExportSpecifiersMap[left.text]; _i < _a.length; _i++) { var specifier = _a[_i]; @@ -45945,13 +47280,13 @@ var ts; var operand = node.operand; if (ts.isIdentifier(operand) && bindingNameExportSpecifiersForFileMap) { if (bindingNameExportSpecifiersMap && ts.hasProperty(bindingNameExportSpecifiersMap, operand.text)) { - setNodeEmitFlags(node, 128 /* NoSubstitution */); + ts.setEmitFlags(node, 128 /* NoSubstitution */); var transformedUnaryExpression = void 0; if (node.kind === 186 /* PostfixUnaryExpression */) { - transformedUnaryExpression = ts.createBinary(operand, ts.createNode(operator === 41 /* PlusPlusToken */ ? 57 /* PlusEqualsToken */ : 58 /* MinusEqualsToken */), ts.createLiteral(1), + transformedUnaryExpression = ts.createBinary(operand, ts.createToken(operator === 41 /* PlusPlusToken */ ? 57 /* PlusEqualsToken */ : 58 /* MinusEqualsToken */), ts.createLiteral(1), /*location*/ node); // We have to set no substitution flag here to prevent visit the binary expression and substitute it again as we will preform all necessary substitution in here - setNodeEmitFlags(transformedUnaryExpression, 128 /* NoSubstitution */); + ts.setEmitFlags(transformedUnaryExpression, 128 /* NoSubstitution */); } var nestedExportAssignment = void 0; for (var _i = 0, _a = bindingNameExportSpecifiersMap[operand.text]; _i < _a.length; _i++) { @@ -45966,7 +47301,7 @@ var ts; return node; } function trySubstituteExportedName(node) { - var emitFlags = getNodeEmitFlags(node); + var emitFlags = ts.getEmitFlags(node); if ((emitFlags & 262144 /* LocalName */) === 0) { var container = resolver.getReferencedExportContainer(node, (emitFlags & 131072 /* ExportName */) !== 0); if (container) { @@ -45979,7 +47314,7 @@ var ts; return undefined; } function trySubstituteImportedName(node) { - if ((getNodeEmitFlags(node) & 262144 /* LocalName */) === 0) { + if ((ts.getEmitFlags(node) & 262144 /* LocalName */) === 0) { var declaration = resolver.getReferencedImportDeclaration(node); if (declaration) { if (ts.isImportClause(declaration)) { @@ -45994,14 +47329,14 @@ var ts; } } else if (ts.isImportSpecifier(declaration)) { - var name_34 = declaration.propertyName || declaration.name; - if (name_34.originalKeywordKind === 77 /* DefaultKeyword */ && languageVersion <= 0 /* ES3 */) { + var name_35 = declaration.propertyName || declaration.name; + if (name_35.originalKeywordKind === 77 /* DefaultKeyword */ && languageVersion <= 0 /* ES3 */) { // TODO: ES3 transform to handle x.default -> x["default"] - return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_34.text), + return ts.createElementAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.createLiteral(name_35.text), /*location*/ node); } else { - return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_34), + return ts.createPropertyAccess(ts.getGeneratedNameForNode(declaration.parent.parent.parent), ts.getSynthesizedClone(name_35), /*location*/ node); } } @@ -46025,7 +47360,7 @@ var ts; var statement = ts.createStatement(createExportAssignment(name, value)); statement.startsOnNewLine = true; if (location) { - setSourceMapRange(statement, location); + ts.setSourceMapRange(statement, location); } return statement; } @@ -46063,7 +47398,7 @@ var ts; if (includeNonAmdDependencies && importAliasName) { // Set emitFlags on the name of the classDeclaration // This is so that when printer will not substitute the identifier - setNodeEmitFlags(importAliasName, 128 /* NoSubstitution */); + ts.setEmitFlags(importAliasName, 128 /* NoSubstitution */); aliasedModuleNames.push(externalModuleName); importAliasNames.push(ts.createParameter(importAliasName)); } @@ -46098,6 +47433,9 @@ var ts; * @param node A SourceFile node. */ function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; node = ts.visitEachChild(node, visitor, context); currentSourceFile = undefined; @@ -46280,12 +47618,12 @@ var ts; return getTagName(node.openingElement); } else { - var name_35 = node.tagName; - if (ts.isIdentifier(name_35) && ts.isIntrinsicJsxName(name_35.text)) { - return ts.createLiteral(name_35.text); + var name_36 = node.tagName; + if (ts.isIdentifier(name_36) && ts.isIntrinsicJsxName(name_36.text)) { + return ts.createLiteral(name_36.text); } else { - return ts.createExpressionFromEntityName(name_35); + return ts.createExpressionFromEntityName(name_36); } } } @@ -46575,6 +47913,9 @@ var ts; var hoistVariableDeclaration = context.hoistVariableDeclaration; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } return ts.visitEachChild(node, visitor, context); } function visitor(node) { @@ -46820,7 +48161,7 @@ var ts; _a[7 /* Endfinally */] = "endfinally", _a)); function transformGenerators(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration, setSourceMapRange = context.setSourceMapRange, setCommentRange = context.setCommentRange, setNodeEmitFlags = context.setNodeEmitFlags; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration; var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var resolver = context.getEmitResolver(); @@ -46870,6 +48211,9 @@ var ts; var withBlockStack; // A stack containing `with` blocks. return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } if (node.transformFlags & 1024 /* ContainsGenerator */) { currentSourceFile = node; node = ts.visitEachChild(node, visitor, context); @@ -47011,7 +48355,7 @@ var ts; */ function visitFunctionDeclaration(node) { // Currently, we only support generators that were originally async functions. - if (node.asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (node.asteriskToken && ts.getEmitFlags(node) & 2097152 /* AsyncFunctionBody */) { node = ts.setOriginalNode(ts.createFunctionDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, @@ -47050,7 +48394,7 @@ var ts; */ function visitFunctionExpression(node) { // Currently, we only support generators that were originally async functions. - if (node.asteriskToken && node.emitFlags & 2097152 /* AsyncFunctionBody */) { + if (node.asteriskToken && ts.getEmitFlags(node) & 2097152 /* AsyncFunctionBody */) { node = ts.setOriginalNode(ts.createFunctionExpression( /*asteriskToken*/ undefined, node.name, /*typeParameters*/ undefined, node.parameters, @@ -47099,6 +48443,7 @@ var ts; var savedBlocks = blocks; var savedBlockOffsets = blockOffsets; var savedBlockActions = blockActions; + var savedBlockStack = blockStack; var savedLabelOffsets = labelOffsets; var savedLabelExpressions = labelExpressions; var savedNextLabelId = nextLabelId; @@ -47112,6 +48457,7 @@ var ts; blocks = undefined; blockOffsets = undefined; blockActions = undefined; + blockStack = undefined; labelOffsets = undefined; labelExpressions = undefined; nextLabelId = 1; @@ -47132,6 +48478,7 @@ var ts; blocks = savedBlocks; blockOffsets = savedBlockOffsets; blockActions = savedBlockActions; + blockStack = savedBlockStack; labelOffsets = savedLabelOffsets; labelExpressions = savedLabelExpressions; nextLabelId = savedNextLabelId; @@ -47156,7 +48503,7 @@ var ts; } else { // Do not hoist custom prologues. - if (node.emitFlags & 8388608 /* CustomPrologue */) { + if (ts.getEmitFlags(node) & 8388608 /* CustomPrologue */) { return node; } for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) { @@ -48202,9 +49549,9 @@ var ts; } return -1; } - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } return node; @@ -48221,11 +49568,11 @@ var ts; if (ts.isIdentifier(original) && original.parent) { var declaration = resolver.getReferencedValueDeclaration(original); if (declaration) { - var name_36 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); - if (name_36) { - var clone_7 = ts.getMutableClone(name_36); - setSourceMapRange(clone_7, node); - setCommentRange(clone_7, node); + var name_37 = ts.getProperty(renamedCatchVariableDeclarations, String(ts.getOriginalNodeId(declaration))); + if (name_37) { + var clone_7 = ts.getMutableClone(name_37); + ts.setSourceMapRange(clone_7, node); + ts.setCommentRange(clone_7, node); return clone_7; } } @@ -48815,7 +50162,7 @@ var ts; return ts.createCall(ts.createHelperName(currentSourceFile.externalHelpersModuleName, "__generator"), /*typeArguments*/ undefined, [ ts.createThis(), - setNodeEmitFlags(ts.createFunctionExpression( + ts.setEmitFlags(ts.createFunctionExpression( /*asteriskToken*/ undefined, /*name*/ undefined, /*typeParameters*/ undefined, [ts.createParameter(state)], @@ -49218,8 +50565,32 @@ var ts; Jump[Jump["Continue"] = 4] = "Continue"; Jump[Jump["Return"] = 8] = "Return"; })(Jump || (Jump = {})); + var SuperCaptureResult; + (function (SuperCaptureResult) { + /** + * A capture may have been added for calls to 'super', but + * the caller should emit subsequent statements normally. + */ + SuperCaptureResult[SuperCaptureResult["NoReplacement"] = 0] = "NoReplacement"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * var _this = _super.call(...) || this; + * + * Callers should skip the current statement. + */ + SuperCaptureResult[SuperCaptureResult["ReplaceSuperCapture"] = 1] = "ReplaceSuperCapture"; + /** + * A call to 'super()' got replaced with a capturing statement like: + * + * return _super.call(...) || this; + * + * Callers should skip the current statement and avoid any returns of '_this'. + */ + SuperCaptureResult[SuperCaptureResult["ReplaceWithReturn"] = 2] = "ReplaceWithReturn"; + })(SuperCaptureResult || (SuperCaptureResult = {})); function transformES6(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration, getNodeEmitFlags = context.getNodeEmitFlags, setNodeEmitFlags = context.setNodeEmitFlags, getCommentRange = context.getCommentRange, setCommentRange = context.setCommentRange, getSourceMapRange = context.getSourceMapRange, setSourceMapRange = context.setSourceMapRange, setTokenSourceMapRange = context.setTokenSourceMapRange; + var startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var previousOnSubstituteNode = context.onSubstituteNode; var previousOnEmitNode = context.onEmitNode; @@ -49247,6 +50618,9 @@ var ts; var enabledSubstitutions; return transformSourceFile; function transformSourceFile(node) { + if (ts.isDeclarationFile(node)) { + return node; + } currentSourceFile = node; currentText = node.text; return ts.visitNode(node, visitor, ts.isSourceFile); @@ -49418,7 +50792,7 @@ var ts; enclosingFunction = currentNode; if (currentNode.kind !== 180 /* ArrowFunction */) { enclosingNonArrowFunction = currentNode; - if (!(currentNode.emitFlags & 2097152 /* AsyncFunctionBody */)) { + if (!(ts.getEmitFlags(currentNode) & 2097152 /* AsyncFunctionBody */)) { enclosingNonAsyncFunctionBody = currentNode; } } @@ -49634,17 +51008,17 @@ var ts; // To preserve the behavior of the old emitter, we explicitly indent // the body of the function here if it was requested in an earlier // transformation. - if (getNodeEmitFlags(node) & 524288 /* Indented */) { - setNodeEmitFlags(classFunction, 524288 /* Indented */); + if (ts.getEmitFlags(node) & 524288 /* Indented */) { + ts.setEmitFlags(classFunction, 524288 /* Indented */); } // "inner" and "outer" below are added purely to preserve source map locations from // the old emitter var inner = ts.createPartiallyEmittedExpression(classFunction); inner.end = node.end; - setNodeEmitFlags(inner, 49152 /* NoComments */); + ts.setEmitFlags(inner, 49152 /* NoComments */); var outer = ts.createPartiallyEmittedExpression(inner); outer.end = ts.skipTrivia(currentText, node.pos); - setNodeEmitFlags(outer, 49152 /* NoComments */); + ts.setEmitFlags(outer, 49152 /* NoComments */); return ts.createParen(ts.createCall(outer, /*typeArguments*/ undefined, extendsClauseElement ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)] @@ -49669,14 +51043,14 @@ var ts; // emit with the original emitter. var outer = ts.createPartiallyEmittedExpression(localName); outer.end = closingBraceLocation.end; - setNodeEmitFlags(outer, 49152 /* NoComments */); + ts.setEmitFlags(outer, 49152 /* NoComments */); var statement = ts.createReturn(outer); statement.pos = closingBraceLocation.pos; - setNodeEmitFlags(statement, 49152 /* NoComments */ | 12288 /* NoTokenSourceMaps */); + ts.setEmitFlags(statement, 49152 /* NoComments */ | 12288 /* NoTokenSourceMaps */); statements.push(statement); ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, /*location*/ node.members), /*location*/ undefined, /*multiLine*/ true); - setNodeEmitFlags(block, 49152 /* NoComments */); + ts.setEmitFlags(block, 49152 /* NoComments */); return block; } /** @@ -49702,13 +51076,17 @@ var ts; function addConstructor(statements, node, extendsClauseElement) { var constructor = ts.getFirstConstructorWithBody(node); var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined); - statements.push(ts.createFunctionDeclaration( + var constructorFunction = ts.createFunctionDeclaration( /*decorators*/ undefined, /*modifiers*/ undefined, /*asteriskToken*/ undefined, getDeclarationName(node), /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper), - /*location*/ constructor || node)); + /*location*/ constructor || node); + if (extendsClauseElement) { + ts.setEmitFlags(constructorFunction, 256 /* CapturesThis */); + } + statements.push(constructorFunction); } /** * Transforms the parameters of the constructor declaration of a class. @@ -49740,51 +51118,146 @@ var ts; function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) { var statements = []; startLexicalEnvironment(); + var statementOffset = -1; + if (hasSynthesizedSuper) { + // If a super call has already been synthesized, + // we're going to assume that we should just transform everything after that. + // The assumption is that no prior step in the pipeline has added any prologue directives. + statementOffset = 1; + } + else if (constructor) { + // Otherwise, try to emit all potential prologue directives first. + statementOffset = ts.addPrologueDirectives(statements, constructor.body.statements, /*ensureUseStrict*/ false, visitor); + } if (constructor) { - addCaptureThisForNodeIfNeeded(statements, constructor); addDefaultValueAssignmentsIfNeeded(statements, constructor); addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper); + ts.Debug.assert(statementOffset >= 0, "statementOffset not initialized correctly!"); + } + var superCaptureStatus = declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, constructor, !!extendsClauseElement, hasSynthesizedSuper, statementOffset); + // The last statement expression was replaced. Skip it. + if (superCaptureStatus === 1 /* ReplaceSuperCapture */ || superCaptureStatus === 2 /* ReplaceWithReturn */) { + statementOffset++; } - addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper); if (constructor) { - var body = saveStateAndInvoke(constructor, hasSynthesizedSuper ? transformConstructorBodyWithSynthesizedSuper : transformConstructorBodyWithoutSynthesizedSuper); + var body = saveStateAndInvoke(constructor, function (constructor) { return ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset); }); ts.addRange(statements, body); } + // Return `_this` unless we're sure enough that it would be pointless to add a return statement. + // If there's a constructor that we can tell returns in enough places, then we *do not* want to add a return. + if (extendsClauseElement + && superCaptureStatus !== 2 /* ReplaceWithReturn */ + && !(constructor && isSufficientlyCoveredByReturnStatements(constructor.body))) { + statements.push(ts.createReturn(ts.createIdentifier("_this"))); + } ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(ts.createNodeArray(statements, /*location*/ constructor ? constructor.body.statements : node.members), /*location*/ constructor ? constructor.body : node, /*multiLine*/ true); if (!constructor) { - setNodeEmitFlags(block, 49152 /* NoComments */); + ts.setEmitFlags(block, 49152 /* NoComments */); } return block; } - function transformConstructorBodyWithSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 1); - } - function transformConstructorBodyWithoutSynthesizedSuper(node) { - return ts.visitNodes(node.body.statements, visitor, ts.isStatement, 0); + /** + * We want to try to avoid emitting a return statement in certain cases if a user already returned something. + * It would generate obviously dead code, so we'll try to make things a little bit prettier + * by doing a minimal check on whether some common patterns always explicitly return. + */ + function isSufficientlyCoveredByReturnStatements(statement) { + // A return statement is considered covered. + if (statement.kind === 211 /* ReturnStatement */) { + return true; + } + else if (statement.kind === 203 /* IfStatement */) { + var ifStatement = statement; + if (ifStatement.elseStatement) { + return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) && + isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement); + } + } + else if (statement.kind === 199 /* Block */) { + var lastStatement = ts.lastOrUndefined(statement.statements); + if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) { + return true; + } + } + return false; } /** - * Adds a synthesized call to `_super` if it is needed. + * Declares a `_this` variable for derived classes and for when arrow functions capture `this`. * - * @param statements The statements for the new constructor body. - * @param constructor The constructor for the class. - * @param extendsClauseElement The expression for the class `extends` clause. - * @param hasSynthesizedSuper A value indicating whether the constructor starts with a - * synthesized `super` call. + * @returns The new statement offset into the `statements` array. */ - function addDefaultSuperCallIfNeeded(statements, constructor, extendsClauseElement, hasSynthesizedSuper) { - // If the TypeScript transformer needed to synthesize a constructor for property - // initializers, it would have also added a synthetic `...args` parameter and - // `super` call. - // If this is the case, or if the class has an `extends` clause but no - // constructor, we emit a synthesized call to `_super`. - if (constructor ? hasSynthesizedSuper : extendsClauseElement) { - statements.push(ts.createStatement(ts.createFunctionApply(ts.createIdentifier("_super"), ts.createThis(), ts.createIdentifier("arguments")), - /*location*/ extendsClauseElement)); + function declareOrCaptureOrReturnThisForConstructorIfNeeded(statements, ctor, hasExtendsClause, hasSynthesizedSuper, statementOffset) { + // If this isn't a derived class, just capture 'this' for arrow functions if necessary. + if (!hasExtendsClause) { + if (ctor) { + addCaptureThisForNodeIfNeeded(statements, ctor); + } + return 0 /* NoReplacement */; } + // We must be here because the user didn't write a constructor + // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec. + // If that's the case we can just immediately return the result of a 'super()' call. + if (!ctor) { + statements.push(ts.createReturn(createDefaultSuperCallOrThis())); + return 2 /* ReplaceWithReturn */; + } + // The constructor exists, but it and the 'super()' call it contains were generated + // for something like property initializers. + // Create a captured '_this' variable and assume it will subsequently be used. + if (hasSynthesizedSuper) { + captureThisForNode(statements, ctor, createDefaultSuperCallOrThis()); + enableSubstitutionsForCapturedThis(); + return 1 /* ReplaceSuperCapture */; + } + // Most of the time, a 'super' call will be the first real statement in a constructor body. + // In these cases, we'd like to transform these into a *single* statement instead of a declaration + // followed by an assignment statement for '_this'. For instance, if we emitted without an initializer, + // we'd get: + // + // var _this; + // _this = _super.call(...) || this; + // + // instead of + // + // var _this = _super.call(...) || this; + // + // Additionally, if the 'super()' call is the last statement, we should just avoid capturing + // entirely and immediately return the result like so: + // + // return _super.call(...) || this; + // + var firstStatement; + var superCallExpression; + var ctorStatements = ctor.body.statements; + if (statementOffset < ctorStatements.length) { + firstStatement = ctorStatements[statementOffset]; + if (firstStatement.kind === 202 /* ExpressionStatement */ && ts.isSuperCall(firstStatement.expression)) { + var superCall = firstStatement.expression; + superCallExpression = ts.setOriginalNode(saveStateAndInvoke(superCall, visitImmediateSuperCallInBody), superCall); + } + } + // Return the result if we have an immediate super() call on the last statement. + if (superCallExpression && statementOffset === ctorStatements.length - 1) { + statements.push(ts.createReturn(superCallExpression)); + return 2 /* ReplaceWithReturn */; + } + // Perform the capture. + captureThisForNode(statements, ctor, superCallExpression, firstStatement); + // If we're actually replacing the original statement, we need to signal this to the caller. + if (superCallExpression) { + return 1 /* ReplaceSuperCapture */; + } + return 0 /* NoReplacement */; + } + function createDefaultSuperCallOrThis() { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 128 /* NoSubstitution */); + var superCall = ts.createFunctionApply(ts.createIdentifier("_super"), actualThis, ts.createIdentifier("arguments")); + return ts.createLogicalOr(superCall, actualThis); } /** * Visits a parameter declaration. @@ -49837,17 +51310,17 @@ var ts; } for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { var parameter = _a[_i]; - var name_37 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; + var name_38 = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken; // A rest parameter cannot have a binding pattern or an initializer, // so let's just ignore it. if (dotDotDotToken) { continue; } - if (ts.isBindingPattern(name_37)) { - addDefaultValueAssignmentForBindingPattern(statements, parameter, name_37, initializer); + if (ts.isBindingPattern(name_38)) { + addDefaultValueAssignmentForBindingPattern(statements, parameter, name_38, initializer); } else if (initializer) { - addDefaultValueAssignmentForInitializer(statements, parameter, name_37, initializer); + addDefaultValueAssignmentForInitializer(statements, parameter, name_38, initializer); } } } @@ -49865,11 +51338,11 @@ var ts; // we usually don't want to emit a var declaration; however, in the presence // of an initializer, we must emit that expression to preserve side effects. if (name.elements.length > 0) { - statements.push(setNodeEmitFlags(ts.createVariableStatement( + statements.push(ts.setEmitFlags(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList(ts.flattenParameterDestructuring(context, parameter, temp, visitor))), 8388608 /* CustomPrologue */)); } else if (initializer) { - statements.push(setNodeEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608 /* CustomPrologue */)); + statements.push(ts.setEmitFlags(ts.createStatement(ts.createAssignment(temp, ts.visitNode(initializer, visitor, ts.isExpression))), 8388608 /* CustomPrologue */)); } } /** @@ -49882,14 +51355,14 @@ var ts; */ function addDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) { initializer = ts.visitNode(initializer, visitor, ts.isExpression); - var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), setNodeEmitFlags(ts.createBlock([ - ts.createStatement(ts.createAssignment(setNodeEmitFlags(ts.getMutableClone(name), 1536 /* NoSourceMap */), setNodeEmitFlags(initializer, 1536 /* NoSourceMap */ | getNodeEmitFlags(initializer)), + var statement = ts.createIf(ts.createStrictEquality(ts.getSynthesizedClone(name), ts.createVoidZero()), ts.setEmitFlags(ts.createBlock([ + ts.createStatement(ts.createAssignment(ts.setEmitFlags(ts.getMutableClone(name), 1536 /* NoSourceMap */), ts.setEmitFlags(initializer, 1536 /* NoSourceMap */ | ts.getEmitFlags(initializer)), /*location*/ parameter)) ], /*location*/ parameter), 32 /* SingleLine */ | 1024 /* NoTrailingSourceMap */ | 12288 /* NoTokenSourceMaps */), /*elseStatement*/ undefined, /*location*/ parameter); statement.startsOnNewLine = true; - setNodeEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 8388608 /* CustomPrologue */); + ts.setEmitFlags(statement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 8388608 /* CustomPrologue */); statements.push(statement); } /** @@ -49919,13 +51392,13 @@ var ts; } // `declarationName` is the name of the local declaration for the parameter. var declarationName = ts.getMutableClone(parameter.name); - setNodeEmitFlags(declarationName, 1536 /* NoSourceMap */); + ts.setEmitFlags(declarationName, 1536 /* NoSourceMap */); // `expressionName` is the name of the parameter used in expressions. var expressionName = ts.getSynthesizedClone(parameter.name); var restIndex = node.parameters.length - 1; var temp = ts.createLoopVariable(); // var param = []; - statements.push(setNodeEmitFlags(ts.createVariableStatement( + statements.push(ts.setEmitFlags(ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(declarationName, /*type*/ undefined, ts.createArrayLiteral([])) @@ -49941,7 +51414,7 @@ var ts; ts.startOnNewLine(ts.createStatement(ts.createAssignment(ts.createElementAccess(expressionName, ts.createSubtract(temp, ts.createLiteral(restIndex))), ts.createElementAccess(ts.createIdentifier("arguments"), temp)), /*location*/ parameter)) ])); - setNodeEmitFlags(forStatement, 8388608 /* CustomPrologue */); + ts.setEmitFlags(forStatement, 8388608 /* CustomPrologue */); ts.startOnNewLine(forStatement); statements.push(forStatement); } @@ -49953,17 +51426,20 @@ var ts; */ function addCaptureThisForNodeIfNeeded(statements, node) { if (node.transformFlags & 16384 /* ContainsCapturedLexicalThis */ && node.kind !== 180 /* ArrowFunction */) { - enableSubstitutionsForCapturedThis(); - var captureThisStatement = ts.createVariableStatement( - /*modifiers*/ undefined, ts.createVariableDeclarationList([ - ts.createVariableDeclaration("_this", - /*type*/ undefined, ts.createThis()) - ])); - setNodeEmitFlags(captureThisStatement, 49152 /* NoComments */ | 8388608 /* CustomPrologue */); - setSourceMapRange(captureThisStatement, node); - statements.push(captureThisStatement); + captureThisForNode(statements, node, ts.createThis()); } } + function captureThisForNode(statements, node, initializer, originalStatement) { + enableSubstitutionsForCapturedThis(); + var captureThisStatement = ts.createVariableStatement( + /*modifiers*/ undefined, ts.createVariableDeclarationList([ + ts.createVariableDeclaration("_this", + /*type*/ undefined, initializer) + ]), originalStatement); + ts.setEmitFlags(captureThisStatement, 49152 /* NoComments */ | 8388608 /* CustomPrologue */); + ts.setSourceMapRange(captureThisStatement, node); + statements.push(captureThisStatement); + } /** * Adds statements to the class body function for a class to define the members of the * class. @@ -50012,20 +51488,20 @@ var ts; * @param member The MethodDeclaration node. */ function transformClassMethodDeclarationToStatement(receiver, member) { - var commentRange = getCommentRange(member); - var sourceMapRange = getSourceMapRange(member); + var commentRange = ts.getCommentRange(member); + var sourceMapRange = ts.getSourceMapRange(member); var func = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined); - setNodeEmitFlags(func, 49152 /* NoComments */); - setSourceMapRange(func, sourceMapRange); + ts.setEmitFlags(func, 49152 /* NoComments */); + ts.setSourceMapRange(func, sourceMapRange); var statement = ts.createStatement(ts.createAssignment(ts.createMemberAccessForPropertyName(receiver, ts.visitNode(member.name, visitor, ts.isPropertyName), /*location*/ member.name), func), /*location*/ member); ts.setOriginalNode(statement, member); - setCommentRange(statement, commentRange); + ts.setCommentRange(statement, commentRange); // The location for the statement is used to emit comments only. // No source map should be emitted for this statement to align with the // old emitter. - setNodeEmitFlags(statement, 1536 /* NoSourceMap */); + ts.setEmitFlags(statement, 1536 /* NoSourceMap */); return statement; } /** @@ -50036,11 +51512,11 @@ var ts; */ function transformAccessorsToStatement(receiver, accessors) { var statement = ts.createStatement(transformAccessorsToExpression(receiver, accessors, /*startsOnNewLine*/ false), - /*location*/ getSourceMapRange(accessors.firstAccessor)); + /*location*/ ts.getSourceMapRange(accessors.firstAccessor)); // The location for the statement is used to emit source maps only. // No comments should be emitted for this statement to align with the // old emitter. - setNodeEmitFlags(statement, 49152 /* NoComments */); + ts.setEmitFlags(statement, 49152 /* NoComments */); return statement; } /** @@ -50054,24 +51530,24 @@ var ts; // To align with source maps in the old emitter, the receiver and property name // arguments are both mapped contiguously to the accessor name. var target = ts.getMutableClone(receiver); - setNodeEmitFlags(target, 49152 /* NoComments */ | 1024 /* NoTrailingSourceMap */); - setSourceMapRange(target, firstAccessor.name); + ts.setEmitFlags(target, 49152 /* NoComments */ | 1024 /* NoTrailingSourceMap */); + ts.setSourceMapRange(target, firstAccessor.name); var propertyName = ts.createExpressionForPropertyName(ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName)); - setNodeEmitFlags(propertyName, 49152 /* NoComments */ | 512 /* NoLeadingSourceMap */); - setSourceMapRange(propertyName, firstAccessor.name); + ts.setEmitFlags(propertyName, 49152 /* NoComments */ | 512 /* NoLeadingSourceMap */); + ts.setSourceMapRange(propertyName, firstAccessor.name); var properties = []; if (getAccessor) { var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined); - setSourceMapRange(getterFunction, getSourceMapRange(getAccessor)); + ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor)); var getter = ts.createPropertyAssignment("get", getterFunction); - setCommentRange(getter, getCommentRange(getAccessor)); + ts.setCommentRange(getter, ts.getCommentRange(getAccessor)); properties.push(getter); } if (setAccessor) { var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined); - setSourceMapRange(setterFunction, getSourceMapRange(setAccessor)); + ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor)); var setter = ts.createPropertyAssignment("set", setterFunction); - setCommentRange(setter, getCommentRange(setAccessor)); + ts.setCommentRange(setter, ts.getCommentRange(setAccessor)); properties.push(setter); } properties.push(ts.createPropertyAssignment("enumerable", ts.createLiteral(true)), ts.createPropertyAssignment("configurable", ts.createLiteral(true))); @@ -50096,7 +51572,7 @@ var ts; enableSubstitutionsForCapturedThis(); } var func = transformFunctionLikeToExpression(node, /*location*/ node, /*name*/ undefined); - setNodeEmitFlags(func, 256 /* CapturesThis */); + ts.setEmitFlags(func, 256 /* CapturesThis */); return func; } /** @@ -50191,7 +51667,7 @@ var ts; } var expression = ts.visitNode(body, visitor, ts.isExpression); var returnStatement = ts.createReturn(expression, /*location*/ body); - setNodeEmitFlags(returnStatement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 32768 /* NoTrailingComments */); + ts.setEmitFlags(returnStatement, 12288 /* NoTokenSourceMaps */ | 1024 /* NoTrailingSourceMap */ | 32768 /* NoTrailingComments */); statements.push(returnStatement); // To align with the source map emit for the old emitter, we set a custom // source map location for the close brace. @@ -50205,10 +51681,10 @@ var ts; } var block = ts.createBlock(ts.createNodeArray(statements, statementsLocation), node.body, multiLine); if (!multiLine && singleLine) { - setNodeEmitFlags(block, 32 /* SingleLine */); + ts.setEmitFlags(block, 32 /* SingleLine */); } if (closeBraceLocation) { - setTokenSourceMapRange(block, 16 /* CloseBraceToken */, closeBraceLocation); + ts.setTokenSourceMapRange(block, 16 /* CloseBraceToken */, closeBraceLocation); } ts.setOriginalNode(block, node.body); return block; @@ -50274,7 +51750,7 @@ var ts; assignment = ts.flattenVariableDestructuringToExpression(context, decl, hoistVariableDeclaration, /*nameSubstitution*/ undefined, visitor); } else { - assignment = ts.createBinary(decl.name, 56 /* EqualsToken */, decl.initializer); + assignment = ts.createBinary(decl.name, 56 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression)); } (assignments || (assignments = [])).push(assignment); } @@ -50303,7 +51779,7 @@ var ts; : visitVariableDeclaration)); var declarationList = ts.createVariableDeclarationList(declarations, /*location*/ node); ts.setOriginalNode(declarationList, node); - setCommentRange(declarationList, node); + ts.setCommentRange(declarationList, node); if (node.transformFlags & 2097152 /* ContainsBindingPattern */ && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.lastOrUndefined(node.declarations).name))) { @@ -50311,7 +51787,7 @@ var ts; // the source map range for the declaration list. var firstDeclaration = ts.firstOrUndefined(declarations); var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); } return declarationList; } @@ -50501,7 +51977,7 @@ var ts; // emitter. var firstDeclaration = declarations[0]; var lastDeclaration = ts.lastOrUndefined(declarations); - setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); + ts.setSourceMapRange(declarationList, ts.createRange(firstDeclaration.pos, lastDeclaration.end)); statements.push(ts.createVariableStatement( /*modifiers*/ undefined, declarationList)); } @@ -50549,12 +52025,12 @@ var ts; } } // The old emitter does not emit source maps for the expression - setNodeEmitFlags(expression, 1536 /* NoSourceMap */ | getNodeEmitFlags(expression)); + ts.setEmitFlags(expression, 1536 /* NoSourceMap */ | ts.getEmitFlags(expression)); // The old emitter does not emit source maps for the block. // We add the location to preserve comments. var body = ts.createBlock(ts.createNodeArray(statements, /*location*/ statementsLocation), /*location*/ bodyLocation); - setNodeEmitFlags(body, 1536 /* NoSourceMap */ | 12288 /* NoTokenSourceMaps */); + ts.setEmitFlags(body, 1536 /* NoSourceMap */ | 12288 /* NoTokenSourceMaps */); var forStatement = ts.createFor(ts.createVariableDeclarationList([ ts.createVariableDeclaration(counter, /*type*/ undefined, ts.createLiteral(0), /*location*/ ts.moveRangePos(node.expression, -1)), ts.createVariableDeclaration(rhsReference, /*type*/ undefined, expression, /*location*/ node.expression) @@ -50562,7 +52038,7 @@ var ts; /*location*/ node.expression), ts.createPostfixIncrement(counter, /*location*/ node.expression), body, /*location*/ node); // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter. - setNodeEmitFlags(forStatement, 8192 /* NoTokenTrailingSourceMaps */); + ts.setEmitFlags(forStatement, 8192 /* NoTokenTrailingSourceMaps */); return forStatement; } /** @@ -50591,7 +52067,7 @@ var ts; var temp = ts.createTempVariable(hoistVariableDeclaration); // Write out the first non-computed properties, then emit the rest through indexing on the temp variable. var expressions = []; - var assignment = ts.createAssignment(temp, setNodeEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), + var assignment = ts.createAssignment(temp, ts.setEmitFlags(ts.createObjectLiteral(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), /*location*/ undefined, node.multiLine), 524288 /* Indented */)); if (node.multiLine) { assignment.startsOnNewLine = true; @@ -50698,7 +52174,7 @@ var ts; loopBody = ts.createBlock([loopBody], /*location*/ undefined, /*multiline*/ true); } var isAsyncBlockContainingAwait = enclosingNonArrowFunction - && (enclosingNonArrowFunction.emitFlags & 2097152 /* AsyncFunctionBody */) !== 0 + && (ts.getEmitFlags(enclosingNonArrowFunction) & 2097152 /* AsyncFunctionBody */) !== 0 && (node.statement.transformFlags & 4194304 /* ContainsYield */) !== 0; var loopBodyFlags = 0; if (currentState.containsLexicalThis) { @@ -50710,7 +52186,7 @@ var ts; var convertedLoopVariable = ts.createVariableStatement( /*modifiers*/ undefined, ts.createVariableDeclarationList([ ts.createVariableDeclaration(functionName, - /*type*/ undefined, setNodeEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37 /* AsteriskToken */) : undefined, + /*type*/ undefined, ts.setEmitFlags(ts.createFunctionExpression(isAsyncBlockContainingAwait ? ts.createToken(37 /* AsteriskToken */) : undefined, /*name*/ undefined, /*typeParameters*/ undefined, loopParameters, /*type*/ undefined, loopBody), loopBodyFlags)) @@ -50756,8 +52232,8 @@ var ts; extraVariableDeclarations = []; } // hoist collected variable declarations - for (var name_38 in currentState.hoistedLocalVariables) { - var identifier = currentState.hoistedLocalVariables[name_38]; + for (var _b = 0, _c = currentState.hoistedLocalVariables; _b < _c.length; _b++) { + var identifier = _c[_b]; extraVariableDeclarations.push(ts.createVariableDeclaration(identifier)); } } @@ -50767,8 +52243,8 @@ var ts; if (!extraVariableDeclarations) { extraVariableDeclarations = []; } - for (var _b = 0, loopOutParameters_1 = loopOutParameters; _b < loopOutParameters_1.length; _b++) { - var outParam = loopOutParameters_1[_b]; + for (var _d = 0, loopOutParameters_1 = loopOutParameters; _d < loopOutParameters_1.length; _d++) { + var outParam = loopOutParameters_1[_d]; extraVariableDeclarations.push(ts.createVariableDeclaration(outParam.outParamName)); } } @@ -51003,7 +52479,7 @@ var ts; // Methods with computed property names are handled in visitObjectLiteralExpression. ts.Debug.assert(!ts.isComputedPropertyName(node.name)); var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined); - setNodeEmitFlags(functionExpression, 16384 /* NoLeadingComments */ | getNodeEmitFlags(functionExpression)); + ts.setEmitFlags(functionExpression, 16384 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression)); return ts.createPropertyAssignment(node.name, functionExpression, /*location*/ node); } @@ -51040,9 +52516,19 @@ var ts; * @param node a CallExpression. */ function visitCallExpression(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true); + } + function visitImmediateSuperCallInBody(node) { + return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false); + } + function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) { // We are here either because SuperKeyword was used somewhere in the expression, or // because we contain a SpreadElementExpression. var _a = ts.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg; + if (node.expression.kind === 95 /* SuperKeyword */) { + ts.setEmitFlags(thisArg, 128 /* NoSubstitution */); + } + var resultingCall; if (node.transformFlags & 262144 /* ContainsSpreadElementExpression */) { // [source] // f(...a, b) @@ -51057,7 +52543,7 @@ var ts; // _super.apply(this, a.concat([b])) // _super.m.apply(this, a.concat([b])) // _super.prototype.m.apply(this, a.concat([b])) - return ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); + resultingCall = ts.createFunctionApply(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)); } else { // [source] @@ -51069,9 +52555,18 @@ var ts; // _super.call(this, a) // _super.m.call(this, a) // _super.prototype.m.call(this, a) - return ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), + resultingCall = ts.createFunctionCall(ts.visitNode(target, visitor, ts.isExpression), ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression), /*location*/ node); } + if (node.expression.kind === 95 /* SuperKeyword */) { + var actualThis = ts.createThis(); + ts.setEmitFlags(actualThis, 128 /* NoSubstitution */); + var initializer = ts.createLogicalOr(resultingCall, actualThis); + return assignToCapturedThis + ? ts.createAssignment(ts.createIdentifier("_this"), initializer) + : initializer; + } + return resultingCall; } /** * Visits a NewExpression that contains a spread element. @@ -51313,13 +52808,13 @@ var ts; * * @param node The node to be printed. */ - function onEmitNode(node, emit) { + function onEmitNode(emitContext, node, emitCallback) { var savedEnclosingFunction = enclosingFunction; if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) { // If we are tracking a captured `this`, keep track of the enclosing function. enclosingFunction = node; } - previousOnEmitNode(node, emit); + previousOnEmitNode(emitContext, node, emitCallback); enclosingFunction = savedEnclosingFunction; } /** @@ -51356,9 +52851,9 @@ var ts; * @param isExpression A value indicating whether the node is to be used in an expression * position. */ - function onSubstituteNode(node, isExpression) { - node = previousOnSubstituteNode(node, isExpression); - if (isExpression) { + function onSubstituteNode(emitContext, node) { + node = previousOnSubstituteNode(emitContext, node); + if (emitContext === 1 /* Expression */) { return substituteExpression(node); } if (ts.isIdentifier(node)) { @@ -51434,7 +52929,7 @@ var ts; function substituteThisKeyword(node) { if (enabledSubstitutions & 1 /* CapturedThis */ && enclosingFunction - && enclosingFunction.emitFlags & 256 /* CapturesThis */) { + && ts.getEmitFlags(enclosingFunction) & 256 /* CapturesThis */) { return ts.createIdentifier("_this", /*location*/ node); } return node; @@ -51461,7 +52956,7 @@ var ts; function getDeclarationName(node, allowComments, allowSourceMaps, emitFlags) { if (node.name && !ts.isGeneratedIdentifier(node.name)) { var name_39 = ts.getMutableClone(node.name); - emitFlags |= getNodeEmitFlags(node.name); + emitFlags |= ts.getEmitFlags(node.name); if (!allowSourceMaps) { emitFlags |= 1536 /* NoSourceMap */; } @@ -51469,7 +52964,7 @@ var ts; emitFlags |= 49152 /* NoComments */; } if (emitFlags) { - setNodeEmitFlags(name_39, emitFlags); + ts.setEmitFlags(name_39, emitFlags); } return name_39; } @@ -51552,13 +53047,6 @@ var ts; return transformers; } ts.getTransformers = getTransformers; - /** - * Tracks a monotonically increasing transformation id used to associate a node with a specific - * transformation. This ensures transient properties related to transformations can be safely - * stored on source tree nodes that may be reused across multiple transformations (such as - * with compile-on-save). - */ - var nextTransformId = 1; /** * Transforms an array of SourceFiles by passing them through each transformer. * @@ -51568,16 +53056,9 @@ var ts; * @param transforms An array of Transformers. */ function transformFiles(resolver, host, sourceFiles, transformers) { - var transformId = nextTransformId; - nextTransformId++; - var tokenSourceMapRanges = ts.createMap(); var lexicalEnvironmentVariableDeclarationsStack = []; var lexicalEnvironmentFunctionDeclarationsStack = []; var enabledSyntaxKindFeatures = new Array(289 /* Count */); - var parseTreeNodesWithAnnotations = []; - var lastTokenSourceMapRangeNode; - var lastTokenSourceMapRangeToken; - var lastTokenSourceMapRange; var lexicalEnvironmentStackOffset = 0; var hoistedVariableDeclarations; var hoistedFunctionDeclarations; @@ -51588,56 +53069,27 @@ var ts; getCompilerOptions: function () { return host.getCompilerOptions(); }, getEmitResolver: function () { return resolver; }, getEmitHost: function () { return host; }, - getNodeEmitFlags: getNodeEmitFlags, - setNodeEmitFlags: setNodeEmitFlags, - getSourceMapRange: getSourceMapRange, - setSourceMapRange: setSourceMapRange, - getTokenSourceMapRange: getTokenSourceMapRange, - setTokenSourceMapRange: setTokenSourceMapRange, - getCommentRange: getCommentRange, - setCommentRange: setCommentRange, hoistVariableDeclaration: hoistVariableDeclaration, hoistFunctionDeclaration: hoistFunctionDeclaration, startLexicalEnvironment: startLexicalEnvironment, endLexicalEnvironment: endLexicalEnvironment, - onSubstituteNode: onSubstituteNode, + onSubstituteNode: function (emitContext, node) { return node; }, enableSubstitution: enableSubstitution, isSubstitutionEnabled: isSubstitutionEnabled, - onEmitNode: onEmitNode, + onEmitNode: function (node, emitContext, emitCallback) { return emitCallback(node, emitContext); }, enableEmitNotification: enableEmitNotification, isEmitNotificationEnabled: isEmitNotificationEnabled }; // Chain together and initialize each transformer. - var transformation = chain.apply(void 0, transformers)(context); + var transformation = ts.chain.apply(void 0, transformers)(context); // Transform each source file. var transformed = ts.map(sourceFiles, transformSourceFile); // Disable modification of the lexical environment. lexicalEnvironmentDisabled = true; return { - getSourceFiles: function () { return transformed; }, - getTokenSourceMapRange: getTokenSourceMapRange, - isSubstitutionEnabled: isSubstitutionEnabled, - isEmitNotificationEnabled: isEmitNotificationEnabled, - onSubstituteNode: context.onSubstituteNode, - onEmitNode: context.onEmitNode, - dispose: function () { - // During transformation we may need to annotate a parse tree node with transient - // transformation properties. As parse tree nodes live longer than transformation - // nodes, we need to make sure we reclaim any memory allocated for custom ranges - // from these nodes to ensure we do not hold onto entire subtrees just for position - // information. We also need to reset these nodes to a pre-transformation state - // for incremental parsing scenarios so that we do not impact later emit. - for (var _i = 0, parseTreeNodesWithAnnotations_1 = parseTreeNodesWithAnnotations; _i < parseTreeNodesWithAnnotations_1.length; _i++) { - var node = parseTreeNodesWithAnnotations_1[_i]; - if (node.transformId === transformId) { - node.transformId = 0; - node.emitFlags = 0; - node.commentRange = undefined; - node.sourceMapRange = undefined; - } - } - parseTreeNodesWithAnnotations.length = 0; - } + transformed: transformed, + emitNodeWithSubstitution: emitNodeWithSubstitution, + emitNodeWithNotification: emitNodeWithNotification }; /** * Transforms a source file. @@ -51660,17 +53112,27 @@ var ts; * Determines whether expression substitutions are enabled for the provided node. */ function isSubstitutionEnabled(node) { - return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0; + return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0 + && (ts.getEmitFlags(node) & 128 /* NoSubstitution */) === 0; } /** - * Default hook for node substitutions. + * Emits a node with possible substitution. * - * @param node The node to substitute. - * @param isExpression A value indicating whether the node is to be used in an expression - * position. + * @param emitContext The current emit context. + * @param node The node to emit. + * @param emitCallback The callback used to emit the node or its substitute. */ - function onSubstituteNode(node, isExpression) { - return node; + function emitNodeWithSubstitution(emitContext, node, emitCallback) { + if (node) { + if (isSubstitutionEnabled(node)) { + var substitute = context.onSubstituteNode(emitContext, node); + if (substitute && substitute !== node) { + emitCallback(emitContext, substitute); + return; + } + } + emitCallback(emitContext, node); + } } /** * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind. @@ -51684,141 +53146,24 @@ var ts; */ function isEmitNotificationEnabled(node) { return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0 - || (getNodeEmitFlags(node) & 64 /* AdviseOnEmitNode */) !== 0; + || (ts.getEmitFlags(node) & 64 /* AdviseOnEmitNode */) !== 0; } /** - * Default hook for node emit. + * Emits a node with possible emit notification. * + * @param emitContext The current emit context. * @param node The node to emit. - * @param emit A callback used to emit the node in the printer. + * @param emitCallback The callback used to emit the node. */ - function onEmitNode(node, emit) { - emit(node); - } - /** - * Associates a node with the current transformation, initializing - * various transient transformation properties. - * - * @param node The node. - */ - function beforeSetAnnotation(node) { - if ((node.flags & 8 /* Synthesized */) === 0 && node.transformId !== transformId) { - // To avoid holding onto transformation artifacts, we keep track of any - // parse tree node we are annotating. This allows us to clean them up after - // all transformations have completed. - parseTreeNodesWithAnnotations.push(node); - node.transformId = transformId; - } - } - /** - * Gets flags that control emit behavior of a node. - * - * If the node does not have its own NodeEmitFlags set, the node emit flags of its - * original pointer are used. - * - * @param node The node. - */ - function getNodeEmitFlags(node) { - return node.emitFlags; - } - /** - * Sets flags that control emit behavior of a node. - * - * @param node The node. - * @param emitFlags The NodeEmitFlags for the node. - */ - function setNodeEmitFlags(node, emitFlags) { - beforeSetAnnotation(node); - node.emitFlags = emitFlags; - return node; - } - /** - * Gets a custom text range to use when emitting source maps. - * - * If a node does not have its own custom source map text range, the custom source map - * text range of its original pointer is used. - * - * @param node The node. - */ - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - /** - * Sets a custom text range to use when emitting source maps. - * - * @param node The node. - * @param range The text range. - */ - function setSourceMapRange(node, range) { - beforeSetAnnotation(node); - node.sourceMapRange = range; - return node; - } - /** - * Gets the TextRange to use for source maps for a token of a node. - * - * If a node does not have its own custom source map text range for a token, the custom - * source map text range for the token of its original pointer is used. - * - * @param node The node. - * @param token The token. - */ - function getTokenSourceMapRange(node, token) { - // As a performance optimization, use the cached value of the most recent node. - // This helps for cases where this function is called repeatedly for the same node. - if (lastTokenSourceMapRangeNode === node && lastTokenSourceMapRangeToken === token) { - return lastTokenSourceMapRange; - } - // Get the custom token source map range for a node or from one of its original nodes. - // Custom token ranges are not stored on the node to avoid the GC burden. - var range; - var current = node; - while (current) { - range = current.id ? tokenSourceMapRanges[current.id + "-" + token] : undefined; - if (range !== undefined) { - break; + function emitNodeWithNotification(emitContext, node, emitCallback) { + if (node) { + if (isEmitNotificationEnabled(node)) { + context.onEmitNode(emitContext, node, emitCallback); + } + else { + emitCallback(emitContext, node); } - current = current.original; } - // Cache the most recently requested value. - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - return range; - } - /** - * Sets the TextRange to use for source maps for a token of a node. - * - * @param node The node. - * @param token The token. - * @param range The text range. - */ - function setTokenSourceMapRange(node, token, range) { - // Cache the most recently requested value. - lastTokenSourceMapRangeNode = node; - lastTokenSourceMapRangeToken = token; - lastTokenSourceMapRange = range; - tokenSourceMapRanges[ts.getNodeId(node) + "-" + token] = range; - return node; - } - /** - * Gets a custom text range to use when emitting comments. - * - * If a node does not have its own custom source map text range, the custom source map - * text range of its original pointer is used. - * - * @param node The node. - */ - function getCommentRange(node) { - return node.commentRange || node; - } - /** - * Sets a custom text range to use when emitting comments. - */ - function setCommentRange(node, range) { - beforeSetAnnotation(node); - node.commentRange = range; - return node; } /** * Records a hoisted variable declaration for the provided name within a lexical environment. @@ -51891,95 +53236,12 @@ var ts; } } ts.transformFiles = transformFiles; - function chain(a, b, c, d, e) { - if (e) { - var args_3 = []; - for (var i = 0; i < arguments.length; i++) { - args_3[i] = arguments[i]; - } - return function (t) { return compose.apply(void 0, ts.map(args_3, function (f) { return f(t); })); }; - } - else if (d) { - return function (t) { return compose(a(t), b(t), c(t), d(t)); }; - } - else if (c) { - return function (t) { return compose(a(t), b(t), c(t)); }; - } - else if (b) { - return function (t) { return compose(a(t), b(t)); }; - } - else if (a) { - return function (t) { return compose(a(t)); }; - } - else { - return function (t) { return function (u) { return u; }; }; - } - } - function compose(a, b, c, d, e) { - if (e) { - var args_4 = []; - for (var i = 0; i < arguments.length; i++) { - args_4[i] = arguments[i]; - } - return function (t) { return ts.reduceLeft(args_4, function (u, f) { return f(u); }, t); }; - } - else if (d) { - return function (t) { return d(c(b(a(t)))); }; - } - else if (c) { - return function (t) { return c(b(a(t))); }; - } - else if (b) { - return function (t) { return b(a(t)); }; - } - else if (a) { - return function (t) { return a(t); }; - } - else { - return function (t) { return t; }; - } - } var _a; })(ts || (ts = {})); /// /* @internal */ var ts; (function (ts) { - function createSourceMapWriter(host, writer) { - var compilerOptions = host.getCompilerOptions(); - if (compilerOptions.sourceMap || compilerOptions.inlineSourceMap) { - if (compilerOptions.extendedDiagnostics) { - return createSourceMapWriterWithExtendedDiagnostics(host, writer); - } - return createSourceMapWriterWorker(host, writer); - } - else { - return getNullSourceMapWriter(); - } - } - ts.createSourceMapWriter = createSourceMapWriter; - var nullSourceMapWriter; - function getNullSourceMapWriter() { - if (nullSourceMapWriter === undefined) { - nullSourceMapWriter = { - initialize: function (filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { }, - reset: function () { }, - getSourceMapData: function () { return undefined; }, - setSourceFile: function (sourceFile) { }, - emitPos: function (pos) { }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { }, - emitTokenStart: function (token, pos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - emitTokenEnd: function (token, end, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { return -1; }, - changeEmitSourcePos: function () { }, - stopOverridingSpan: function () { }, - getText: function () { return undefined; }, - getSourceMappingURL: function () { return undefined; } - }; - } - return nullSourceMapWriter; - } - ts.getNullSourceMapWriter = getNullSourceMapWriter; // Used for initialize lastEncodedSourceMapSpan and reset lastEncodedSourceMapSpan when updateLastEncodedAndRecordedSpans var defaultLastEncodedSourceMapSpan = { emittedLine: 1, @@ -51988,14 +53250,12 @@ var ts; sourceColumn: 1, sourceIndex: 0 }; - function createSourceMapWriterWorker(host, writer) { + function createSourceMapWriter(host, writer) { var compilerOptions = host.getCompilerOptions(); var extendedDiagnostics = compilerOptions.extendedDiagnostics; var currentSourceFile; var currentSourceText; var sourceMapDir; // The directory in which sourcemap will be - var stopOverridingSpan = false; - var modifyLastSourcePos = false; // Current source map file and its index in the sources list var sourceMapSourceIndex; // Last recorded and encoded spans @@ -52004,24 +53264,15 @@ var ts; var lastEncodedNameIndex; // Source map data var sourceMapData; - // This keeps track of the number of times `disable` has been called without a - // corresponding call to `enable`. As long as this value is non-zero, mappings will not - // be recorded. - // This is primarily used to provide a better experience when debugging binding - // patterns and destructuring assignments for simple expressions. - var disableDepth; + var disabled = !(compilerOptions.sourceMap || compilerOptions.inlineSourceMap); return { initialize: initialize, reset: reset, getSourceMapData: function () { return sourceMapData; }, setSourceFile: setSourceFile, emitPos: emitPos, - emitStart: emitStart, - emitEnd: emitEnd, - emitTokenStart: emitTokenStart, - emitTokenEnd: emitTokenEnd, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: function () { return stopOverridingSpan = true; }, + emitNodeWithSourceMap: emitNodeWithSourceMap, + emitTokenWithSourceMap: emitTokenWithSourceMap, getText: getText, getSourceMappingURL: getSourceMappingURL }; @@ -52034,12 +53285,14 @@ var ts; * @param isBundledEmit A value indicating whether the generated output file is a bundle. */ function initialize(filePath, sourceMapFilePath, sourceFiles, isBundledEmit) { + if (disabled) { + return; + } if (sourceMapData) { reset(); } currentSourceFile = undefined; currentSourceText = undefined; - disableDepth = 0; // Current source map file and its index in the sources list sourceMapSourceIndex = -1; // Last recorded and encoded spans @@ -52093,6 +53346,9 @@ var ts; * Reset the SourceMapWriter to an empty state. */ function reset() { + if (disabled) { + return; + } currentSourceFile = undefined; sourceMapDir = undefined; sourceMapSourceIndex = undefined; @@ -52100,56 +53356,6 @@ var ts; lastEncodedSourceMapSpan = undefined; lastEncodedNameIndex = undefined; sourceMapData = undefined; - disableDepth = 0; - } - /** - * Re-enables the recording of mappings. - */ - function enable() { - if (disableDepth > 0) { - disableDepth--; - } - } - /** - * Disables the recording of mappings. - */ - function disable() { - disableDepth++; - } - function updateLastEncodedAndRecordedSpans() { - if (modifyLastSourcePos) { - // Reset the source pos - modifyLastSourcePos = false; - // Change Last recorded Map with last encoded emit line and character - lastRecordedSourceMapSpan.emittedLine = lastEncodedSourceMapSpan.emittedLine; - lastRecordedSourceMapSpan.emittedColumn = lastEncodedSourceMapSpan.emittedColumn; - // Pop sourceMapDecodedMappings to remove last entry - sourceMapData.sourceMapDecodedMappings.pop(); - // Point the lastEncodedSourceMapSpace to the previous encoded sourceMapSpan - // If the list is empty which indicates that we are at the beginning of the file, - // we have to reset it to default value (same value when we first initialize sourceMapWriter) - lastEncodedSourceMapSpan = sourceMapData.sourceMapDecodedMappings.length ? - sourceMapData.sourceMapDecodedMappings[sourceMapData.sourceMapDecodedMappings.length - 1] : - defaultLastEncodedSourceMapSpan; - // TODO: Update lastEncodedNameIndex - // Since we dont support this any more, lets not worry about it right now. - // When we start supporting nameIndex, we will get back to this - // Change the encoded source map - var sourceMapMappings = sourceMapData.sourceMapMappings; - var lenthToSet = sourceMapMappings.length - 1; - for (; lenthToSet >= 0; lenthToSet--) { - var currentChar = sourceMapMappings.charAt(lenthToSet); - if (currentChar === ",") { - // Separator for the entry found - break; - } - if (currentChar === ";" && lenthToSet !== 0 && sourceMapMappings.charAt(lenthToSet - 1) !== ";") { - // Last line separator found - break; - } - } - sourceMapData.sourceMapMappings = sourceMapMappings.substr(0, Math.max(0, lenthToSet)); - } } // Encoding for sourcemap span function encodeLastRecordedSourceMapSpan() { @@ -52197,7 +53403,7 @@ var ts; * @param pos The position. */ function emitPos(pos) { - if (ts.positionIsSynthesized(pos) || disableDepth > 0) { + if (disabled || ts.positionIsSynthesized(pos)) { return; } if (extendedDiagnostics) { @@ -52226,84 +53432,78 @@ var ts; sourceColumn: sourceLinePos.character, sourceIndex: sourceMapSourceIndex }; - stopOverridingSpan = false; } - else if (!stopOverridingSpan) { + else { // Take the new pos instead since there is no change in emittedLine and column since last location lastRecordedSourceMapSpan.sourceLine = sourceLinePos.line; lastRecordedSourceMapSpan.sourceColumn = sourceLinePos.character; lastRecordedSourceMapSpan.sourceIndex = sourceMapSourceIndex; } - updateLastEncodedAndRecordedSpans(); if (extendedDiagnostics) { ts.performance.mark("afterSourcemap"); ts.performance.measure("Source Map", "beforeSourcemap", "afterSourcemap"); } } - function getStartPosPastDecorators(range) { - var rangeHasDecorators = !!range.decorators; - return ts.skipTrivia(currentSourceText, rangeHasDecorators ? range.decorators.end : range.pos); - } - function emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(getStartPosPastDecorators(range)); - } - if (ignoreChildrenCallback(contextNode)) { - disable(); - } + /** + * Emits a node with possible leading and trailing source maps. + * + * @param node The node to emit. + * @param emitCallback The callback used to emit the node. + */ + function emitNodeWithSourceMap(emitContext, node, emitCallback) { + if (disabled) { + return emitCallback(emitContext, node); } - else { - emitPos(getStartPosPastDecorators(range)); + if (node) { + var emitNode = node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var _a = emitNode && emitNode.sourceMapRange || node, pos = _a.pos, end = _a.end; + if (node.kind !== 287 /* NotEmittedStatement */ + && (emitFlags & 512 /* NoLeadingSourceMap */) === 0 + && pos >= 0) { + emitPos(ts.skipTrivia(currentSourceText, pos)); + } + if (emitFlags & 2048 /* NoNestedSourceMaps */) { + disabled = true; + emitCallback(emitContext, node); + disabled = false; + } + else { + emitCallback(emitContext, node); + } + if (node.kind !== 287 /* NotEmittedStatement */ + && (emitFlags & 1024 /* NoTrailingSourceMap */) === 0 + && end >= 0) { + emitPos(end); + } } } - function emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - if (contextNode) { - if (ignoreChildrenCallback(contextNode)) { - enable(); - } - if (!ignoreNodeCallback(contextNode)) { - range = getTextRangeCallback(contextNode) || range; - emitPos(range.end); - } + /** + * Emits a token of a node with possible leading and trailing source maps. + * + * @param node The node containing the token. + * @param token The token to emit. + * @param tokenStartPos The start pos of the token. + * @param emitCallback The callback used to emit the token. + */ + function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + if (disabled) { + return emitCallback(token, tokenPos); } - else { - emitPos(range.end); + var emitNode = node && node.emitNode; + var emitFlags = emitNode && emitNode.flags; + var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token]; + tokenPos = ts.skipTrivia(currentSourceText, range ? range.pos : tokenPos); + if ((emitFlags & 4096 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - stopOverridingSpan = false; - } - function emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return ts.skipTrivia(currentSourceText, tokenStartPos); - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenStartPos = range.pos; - } + tokenPos = emitCallback(token, tokenPos); + if (range) + tokenPos = range.end; + if ((emitFlags & 8192 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { + emitPos(tokenPos); } - tokenStartPos = ts.skipTrivia(currentSourceText, tokenStartPos); - emitPos(tokenStartPos); - return tokenStartPos; - } - function emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - if (contextNode) { - if (ignoreTokenCallback(contextNode, token)) { - return tokenEndPos; - } - var range = getTokenTextRangeCallback(contextNode, token); - if (range) { - tokenEndPos = range.end; - } - } - emitPos(tokenEndPos); - return tokenEndPos; - } - // @deprecated - function changeEmitSourcePos() { - ts.Debug.assert(!modifyLastSourcePos); - modifyLastSourcePos = true; + return tokenPos; } /** * Set the current source file. @@ -52311,6 +53511,9 @@ var ts; * @param sourceFile The source file. */ function setSourceFile(sourceFile) { + if (disabled) { + return; + } currentSourceFile = sourceFile; currentSourceText = currentSourceFile.text; // Add the file to tsFilePaths @@ -52334,6 +53537,9 @@ var ts; * Gets the text for the source map. */ function getText() { + if (disabled) { + return; + } encodeLastRecordedSourceMapSpan(); return ts.stringify({ version: 3, @@ -52349,6 +53555,9 @@ var ts; * Gets the SourceMappingURL for the source map. */ function getSourceMappingURL() { + if (disabled) { + return; + } if (compilerOptions.inlineSourceMap) { // Encode the sourceMap into the sourceMap url var base64SourceMapText = ts.convertToBase64(getText()); @@ -52359,46 +53568,7 @@ var ts; } } } - function createSourceMapWriterWithExtendedDiagnostics(host, writer) { - var _a = createSourceMapWriterWorker(host, writer), initialize = _a.initialize, reset = _a.reset, getSourceMapData = _a.getSourceMapData, setSourceFile = _a.setSourceFile, emitPos = _a.emitPos, emitStart = _a.emitStart, emitEnd = _a.emitEnd, emitTokenStart = _a.emitTokenStart, emitTokenEnd = _a.emitTokenEnd, changeEmitSourcePos = _a.changeEmitSourcePos, stopOverridingSpan = _a.stopOverridingSpan, getText = _a.getText, getSourceMappingURL = _a.getSourceMappingURL; - return { - initialize: initialize, - reset: reset, - getSourceMapData: getSourceMapData, - setSourceFile: setSourceFile, - emitPos: function (pos) { - ts.performance.mark("sourcemapStart"); - emitPos(pos); - ts.performance.measure("sourceMapTime", "sourcemapStart"); - }, - emitStart: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitStart"); - emitStart(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitStart"); - }, - emitEnd: function (range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitEnd"); - emitEnd(range, contextNode, ignoreNodeCallback, ignoreChildrenCallback, getTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitEnd"); - }, - emitTokenStart: function (token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenStart"); - tokenStartPos = emitTokenStart(token, tokenStartPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenStart"); - return tokenStartPos; - }, - emitTokenEnd: function (token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback) { - ts.performance.mark("emitSourcemap:emitTokenEnd"); - tokenEndPos = emitTokenEnd(token, tokenEndPos, contextNode, ignoreTokenCallback, getTokenTextRangeCallback); - ts.performance.measure("sourceMapTime", "emitSourcemap:emitTokenEnd"); - return tokenEndPos; - }, - changeEmitSourcePos: changeEmitSourcePos, - stopOverridingSpan: stopOverridingSpan, - getText: getText, - getSourceMappingURL: getSourceMappingURL - }; - } + ts.createSourceMapWriter = createSourceMapWriter; var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; function base64FormatEncode(inValue) { if (inValue < 64) { @@ -52457,21 +53627,23 @@ var ts; emitBodyWithDetachedComments: emitBodyWithDetachedComments, emitTrailingCommentsOfPosition: emitTrailingCommentsOfPosition }; - function emitNodeWithComments(node, emitCallback) { + function emitNodeWithComments(emitContext, node, emitCallback) { if (disabled) { - emitCallback(node); + emitCallback(emitContext, node); return; } if (node) { - var _a = node.commentRange || node, pos = _a.pos, end = _a.end; - var emitFlags = node.emitFlags; + var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end; + var emitFlags = ts.getEmitFlags(node); if ((pos < 0 && end < 0) || (pos === end)) { // Both pos and end are synthesized, so just emit the node without comments. if (emitFlags & 65536 /* NoNestedComments */) { - disableCommentsAndEmit(node, emitCallback); + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } } else { @@ -52505,10 +53677,12 @@ var ts; ts.performance.measure("commentTime", "preEmitNodeWithComment"); } if (emitFlags & 65536 /* NoNestedComments */) { - disableCommentsAndEmit(node, emitCallback); + disabled = true; + emitCallback(emitContext, node); + disabled = false; } else { - emitCallback(node); + emitCallback(emitContext, node); } if (extendedDiagnostics) { ts.performance.mark("beginEmitNodeWithComment"); @@ -52533,7 +53707,7 @@ var ts; ts.performance.mark("preEmitBodyWithDetachedComments"); } var pos = detachedRange.pos, end = detachedRange.end; - var emitFlags = node.emitFlags; + var emitFlags = ts.getEmitFlags(node); var skipLeadingComments = pos < 0 || (emitFlags & 16384 /* NoLeadingComments */) !== 0; var skipTrailingComments = disabled || end < 0 || (emitFlags & 32768 /* NoTrailingComments */) !== 0; if (!skipLeadingComments) { @@ -52542,8 +53716,10 @@ var ts; if (extendedDiagnostics) { ts.performance.measure("commentTime", "preEmitBodyWithDetachedComments"); } - if (emitFlags & 65536 /* NoNestedComments */) { - disableCommentsAndEmit(node, emitCallback); + if (emitFlags & 65536 /* NoNestedComments */ && !disabled) { + disabled = true; + emitCallback(node); + disabled = false; } else { emitCallback(node); @@ -52664,16 +53840,6 @@ var ts; currentLineMap = ts.getLineStarts(currentSourceFile); detachedCommentsInfo = undefined; } - function disableCommentsAndEmit(node, emitCallback) { - if (disabled) { - emitCallback(node); - } - else { - disabled = true; - emitCallback(node); - disabled = false; - } - } function hasDetachedComments(pos) { return detachedCommentsInfo !== undefined && ts.lastOrUndefined(detachedCommentsInfo).nodePos === pos; } @@ -52735,11 +53901,11 @@ var ts; return declarationDiagnostics.getDiagnostics(targetSourceFile ? targetSourceFile.fileName : undefined); function getDeclarationDiagnosticsFromFile(_a, sources, isBundledEmit) { var declarationFilePath = _a.declarationFilePath; - emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit); + emitDeclarations(host, resolver, declarationDiagnostics, declarationFilePath, sources, isBundledEmit, /*emitOnlyDtsFiles*/ false); } } ts.getDeclarationDiagnostics = getDeclarationDiagnostics; - function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit) { + function emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles) { var newLine = host.getNewLine(); var compilerOptions = host.getCompilerOptions(); var write; @@ -52786,7 +53952,7 @@ var ts; // global file reference is added only // - if it is not bundled emit (because otherwise it would be self reference) // - and it is not already added - if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference)) { + if (writeReferencePath(referencedFile, !isBundledEmit && !addedGlobalFileReference, emitOnlyDtsFiles)) { addedGlobalFileReference = true; } emittedReferencedFiles.push(referencedFile); @@ -52987,7 +54153,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); errorNameNode = undefined; } } @@ -53000,7 +54166,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); errorNameNode = undefined; } } @@ -53202,7 +54368,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -53624,7 +54790,7 @@ var ts; } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); } function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; @@ -54265,7 +55431,7 @@ var ts; * @param referencedFile * @param addBundledFileReference Determines if global file reference corresponding to bundled file should be emitted or not */ - function writeReferencePath(referencedFile, addBundledFileReference) { + function writeReferencePath(referencedFile, addBundledFileReference, emitOnlyDtsFiles) { var declFileName; var addedBundledEmitReference = false; if (ts.isDeclarationFile(referencedFile)) { @@ -54274,7 +55440,7 @@ var ts; } else { // Get the declaration file path - ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile); + ts.forEachExpectedEmitFile(host, getDeclFileName, referencedFile, emitOnlyDtsFiles); } if (declFileName) { declFileName = ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizeSlashes(declarationFilePath)), declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, @@ -54294,8 +55460,8 @@ var ts; } } /* @internal */ - function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics) { - var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit); + function writeDeclarationFile(declarationFilePath, sourceFiles, isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { + var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFiles, isBundledEmit, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; if (!emitSkipped) { var declarationOutput = emitDeclarationResult.referencesOutput @@ -54335,8 +55501,10 @@ var ts; TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; TempFlags[TempFlags["_i"] = 268435456] = "_i"; })(TempFlags || (TempFlags = {})); + var id = function (s) { return s; }; + var nullTransformers = [function (ctx) { return id; }]; // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature - function emitFiles(resolver, host, targetSourceFile) { + function emitFiles(resolver, host, targetSourceFile, emitOnlyDtsFiles) { var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); // emit output for the __extends helper function @@ -54352,7 +55520,7 @@ var ts; // emit output for the __param helper function var paramHelper = "\nvar __param = (this && this.__param) || function (paramIndex, decorator) {\n return function (target, key) { decorator(target, key, paramIndex); }\n};"; // emit output for the __awaiter helper function - var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; + var awaiterHelper = "\nvar __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {\n return new (P || (P = Promise))(function (resolve, reject) {\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\n function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }\n step((generator = generator.apply(thisArg, _arguments)).next());\n });\n};"; // The __generator helper is used by down-level transformations to emulate the runtime // semantics of an ES2015 generator function. When called, this helper returns an // object that implements the Iterator protocol, in that it has `next`, `return`, and @@ -54426,11 +55594,11 @@ var ts; var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined; var emitterDiagnostics = ts.createDiagnosticCollection(); var newLine = host.getNewLine(); - var transformers = ts.getTransformers(compilerOptions); + var transformers = emitOnlyDtsFiles ? nullTransformers : ts.getTransformers(compilerOptions); var writer = ts.createTextWriter(newLine); var write = writer.write, writeLine = writer.writeLine, increaseIndent = writer.increaseIndent, decreaseIndent = writer.decreaseIndent; var sourceMap = ts.createSourceMapWriter(host, writer); - var emitStart = sourceMap.emitStart, emitEnd = sourceMap.emitEnd, emitTokenStart = sourceMap.emitTokenStart, emitTokenEnd = sourceMap.emitTokenEnd; + var emitNodeWithSourceMap = sourceMap.emitNodeWithSourceMap, emitTokenWithSourceMap = sourceMap.emitTokenWithSourceMap; var comments = ts.createCommentWriter(host, writer, sourceMap); var emitNodeWithComments = comments.emitNodeWithComments, emitBodyWithDetachedComments = comments.emitBodyWithDetachedComments, emitTrailingCommentsOfPosition = comments.emitTrailingCommentsOfPosition; var nodeIdToGeneratedName; @@ -54447,18 +55615,20 @@ var ts; var awaiterEmitted; var isOwnFileEmit; var emitSkipped = false; - ts.performance.mark("beforeTransform"); + var sourceFiles = ts.getSourceFilesToEmit(host, targetSourceFile); // Transform the source files - var transformed = ts.transformFiles(resolver, host, ts.getSourceFilesToEmit(host, targetSourceFile), transformers); + ts.performance.mark("beforeTransform"); + var _a = ts.transformFiles(resolver, host, sourceFiles, transformers), transformed = _a.transformed, emitNodeWithSubstitution = _a.emitNodeWithSubstitution, emitNodeWithNotification = _a.emitNodeWithNotification; ts.performance.measure("transformTime", "beforeTransform"); - // Extract helpers from the result - var getTokenSourceMapRange = transformed.getTokenSourceMapRange, isSubstitutionEnabled = transformed.isSubstitutionEnabled, isEmitNotificationEnabled = transformed.isEmitNotificationEnabled, onSubstituteNode = transformed.onSubstituteNode, onEmitNode = transformed.onEmitNode; - ts.performance.mark("beforePrint"); // Emit each output file - ts.forEachTransformedEmitFile(host, transformed.getSourceFiles(), emitFile); - // Clean up after transformation - transformed.dispose(); + ts.performance.mark("beforePrint"); + ts.forEachTransformedEmitFile(host, transformed, emitFile, emitOnlyDtsFiles); ts.performance.measure("printTime", "beforePrint"); + // Clean up emit nodes on parse tree + for (var _b = 0, sourceFiles_4 = sourceFiles; _b < sourceFiles_4.length; _b++) { + var sourceFile = sourceFiles_4[_b]; + ts.disposeEmitNodes(sourceFile); + } return { emitSkipped: emitSkipped, diagnostics: emitterDiagnostics.getDiagnostics(), @@ -54468,16 +55638,20 @@ var ts; function emitFile(jsFilePath, sourceMapFilePath, declarationFilePath, sourceFiles, isBundledEmit) { // Make sure not to write js file and source map file if any of them cannot be written if (!host.isEmitBlocked(jsFilePath) && !compilerOptions.noEmit) { - printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + if (!emitOnlyDtsFiles) { + printFile(jsFilePath, sourceMapFilePath, sourceFiles, isBundledEmit); + } } else { emitSkipped = true; } if (declarationFilePath) { - emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics) || emitSkipped; + emitSkipped = ts.writeDeclarationFile(declarationFilePath, ts.getOriginalSourceFiles(sourceFiles), isBundledEmit, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) || emitSkipped; } if (!emitSkipped && emittedFilesList) { - emittedFilesList.push(jsFilePath); + if (!emitOnlyDtsFiles) { + emittedFilesList.push(jsFilePath); + } if (sourceMapFilePath) { emittedFilesList.push(sourceMapFilePath); } @@ -54494,8 +55668,8 @@ var ts; isOwnFileEmit = !isBundledEmit; // Emit helpers from all the files if (isBundledEmit && moduleKind) { - for (var _a = 0, sourceFiles_4 = sourceFiles; _a < sourceFiles_4.length; _a++) { - var sourceFile = sourceFiles_4[_a]; + for (var _a = 0, sourceFiles_5 = sourceFiles; _a < sourceFiles_5.length; _a++) { + var sourceFile = sourceFiles_5[_a]; emitEmitHelpers(sourceFile); } } @@ -54536,135 +55710,124 @@ var ts; currentFileIdentifiers = node.identifiers; sourceMap.setSourceFile(node); comments.setSourceFile(node); - emitNodeWithNotification(node, emitWorker); + pipelineEmitWithNotification(0 /* SourceFile */, node); } /** * Emits a node. */ function emit(node) { - emitNodeWithNotification(node, emitWithComments); + pipelineEmitWithNotification(3 /* Unspecified */, node); } /** - * Emits a node with comments. - * - * NOTE: Do not call this method directly. It is part of the emit pipeline - * and should only be called indirectly from emit. + * Emits an IdentifierName. */ - function emitWithComments(node) { - emitNodeWithComments(node, emitWithSourceMap); - } - /** - * Emits a node with source maps. - * - * NOTE: Do not call this method directly. It is part of the emit pipeline - * and should only be called indirectly from emitWithComments. - */ - function emitWithSourceMap(node) { - emitNodeWithSourceMap(node, emitWorker); - } function emitIdentifierName(node) { - if (node) { - emitNodeWithNotification(node, emitIdentifierNameWithComments); - } - } - function emitIdentifierNameWithComments(node) { - emitNodeWithComments(node, emitWorker); + pipelineEmitWithNotification(2 /* IdentifierName */, node); } /** * Emits an expression node. */ function emitExpression(node) { - emitNodeWithNotification(node, emitExpressionWithComments); + pipelineEmitWithNotification(1 /* Expression */, node); } /** - * Emits an expression with comments. + * Emits a node with possible notification. * - * NOTE: Do not call this method directly. It is part of the emitExpression pipeline - * and should only be called indirectly from emitExpression. + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called from printSourceFile, emit, emitExpression, or + * emitIdentifierName. */ - function emitExpressionWithComments(node) { - emitNodeWithComments(node, emitExpressionWithSourceMap); + function pipelineEmitWithNotification(emitContext, node) { + emitNodeWithNotification(emitContext, node, pipelineEmitWithComments); } /** - * Emits an expression with source maps. + * Emits a node with comments. * - * NOTE: Do not call this method directly. It is part of the emitExpression pipeline - * and should only be called indirectly from emitExpressionWithComments. + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithNotification. */ - function emitExpressionWithSourceMap(node) { - emitNodeWithSourceMap(node, emitExpressionWorker); - } - /** - * Emits a node with emit notification if available. - */ - function emitNodeWithNotification(node, emitCallback) { - if (node) { - if (isEmitNotificationEnabled(node)) { - onEmitNode(node, emitCallback); - } - else { - emitCallback(node); - } - } - } - function emitNodeWithSourceMap(node, emitCallback) { - if (node) { - emitStart(/*range*/ node, /*contextNode*/ node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - emitCallback(node); - emitEnd(/*range*/ node, /*contextNode*/ node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } - } - function getSourceMapRange(node) { - return node.sourceMapRange || node; - } - /** - * Determines whether to skip leading comment emit for a node. - * - * We do not emit comments for NotEmittedStatement nodes or any node that has - * NodeEmitFlags.NoLeadingComments. - * - * @param node A Node. - */ - function shouldSkipLeadingCommentsForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 16384 /* NoLeadingComments */) !== 0; - } - /** - * Determines whether to skip source map emit for the start position of a node. - * - * We do not emit source maps for NotEmittedStatement nodes or any node that - * has NodeEmitFlags.NoLeadingSourceMap. - * - * @param node A Node. - */ - function shouldSkipLeadingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 512 /* NoLeadingSourceMap */) !== 0; - } - /** - * Determines whether to skip source map emit for the end position of a node. - * - * We do not emit source maps for NotEmittedStatement nodes or any node that - * has NodeEmitFlags.NoTrailingSourceMap. - * - * @param node A Node. - */ - function shouldSkipTrailingSourceMapForNode(node) { - return ts.isNotEmittedStatement(node) - || (node.emitFlags & 1024 /* NoTrailingSourceMap */) !== 0; - } - /** - * Determines whether to skip source map emit for a node and its children. - * - * We do not emit source maps for a node that has NodeEmitFlags.NoNestedSourceMaps. - */ - function shouldSkipSourceMapForChildren(node) { - return (node.emitFlags & 2048 /* NoNestedSourceMaps */) !== 0; - } - function emitWorker(node) { - if (tryEmitSubstitute(node, emitWorker, /*isExpression*/ false)) { + function pipelineEmitWithComments(emitContext, node) { + // Do not emit comments for SourceFile + if (emitContext === 0 /* SourceFile */) { + pipelineEmitWithSourceMap(emitContext, node); return; } + emitNodeWithComments(emitContext, node, pipelineEmitWithSourceMap); + } + /** + * Emits a node with source maps. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithComments. + */ + function pipelineEmitWithSourceMap(emitContext, node) { + // Do not emit source mappings for SourceFile or IdentifierName + if (emitContext === 0 /* SourceFile */ + || emitContext === 2 /* IdentifierName */) { + pipelineEmitWithSubstitution(emitContext, node); + return; + } + emitNodeWithSourceMap(emitContext, node, pipelineEmitWithSubstitution); + } + /** + * Emits a node with possible substitution. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithSourceMap or + * pipelineEmitInUnspecifiedContext (when picking a more specific context). + */ + function pipelineEmitWithSubstitution(emitContext, node) { + emitNodeWithSubstitution(emitContext, node, pipelineEmitForContext); + } + /** + * Emits a node. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitWithSubstitution. + */ + function pipelineEmitForContext(emitContext, node) { + switch (emitContext) { + case 0 /* SourceFile */: return pipelineEmitInSourceFileContext(node); + case 2 /* IdentifierName */: return pipelineEmitInIdentifierNameContext(node); + case 3 /* Unspecified */: return pipelineEmitInUnspecifiedContext(node); + case 1 /* Expression */: return pipelineEmitInExpressionContext(node); + } + } + /** + * Emits a node in the SourceFile EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInSourceFileContext(node) { + var kind = node.kind; + switch (kind) { + // Top-level nodes + case 256 /* SourceFile */: + return emitSourceFile(node); + } + } + /** + * Emits a node in the IdentifierName EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInIdentifierNameContext(node) { + var kind = node.kind; + switch (kind) { + // Identifiers + case 69 /* Identifier */: + return emitIdentifier(node); + } + } + /** + * Emits a node in the Unspecified EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInUnspecifiedContext(node) { var kind = node.kind; switch (kind) { // Pseudo-literals @@ -54696,7 +55859,8 @@ var ts; case 132 /* StringKeyword */: case 133 /* SymbolKeyword */: case 137 /* GlobalKeyword */: - return writeTokenNode(node); + writeTokenText(kind); + return; // Parse tree nodes // Names case 139 /* QualifiedName */: @@ -54886,18 +56050,20 @@ var ts; // Enum case 255 /* EnumMember */: return emitEnumMember(node); - // Top-level nodes - case 256 /* SourceFile */: - return emitSourceFile(node); } + // If the node is an expression, try to emit it as an expression with + // substitution. if (ts.isExpression(node)) { - return emitExpressionWorker(node); + return pipelineEmitWithSubstitution(1 /* Expression */, node); } } - function emitExpressionWorker(node) { - if (tryEmitSubstitute(node, emitExpressionWorker, /*isExpression*/ true)) { - return; - } + /** + * Emits a node in the Expression EmitContext. + * + * NOTE: Do not call this method directly. It is part of the emit pipeline + * and should only be called indirectly from pipelineEmitForContext. + */ + function pipelineEmitInExpressionContext(node) { var kind = node.kind; switch (kind) { // Literals @@ -54916,7 +56082,8 @@ var ts; case 95 /* SuperKeyword */: case 99 /* TrueKeyword */: case 97 /* ThisKeyword */: - return writeTokenNode(node); + writeTokenText(kind); + return; // Expressions case 170 /* ArrayLiteralExpression */: return emitArrayLiteralExpression(node); @@ -55010,7 +56177,7 @@ var ts; // Identifiers // function emitIdentifier(node) { - if (node.emitFlags & 16 /* UMDDefine */) { + if (ts.getEmitFlags(node) & 16 /* UMDDefine */) { writeLines(umdHelper); } else { @@ -55243,7 +56410,7 @@ var ts; write("{}"); } else { - var indentedFlag = node.emitFlags & 524288 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 524288 /* Indented */; if (indentedFlag) { increaseIndent(); } @@ -55256,21 +56423,18 @@ var ts; } } function emitPropertyAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } var indentBeforeDot = false; var indentAfterDot = false; - if (!(node.emitFlags & 1048576 /* NoIndentation */)) { + if (!(ts.getEmitFlags(node) & 1048576 /* NoIndentation */)) { var dotRangeStart = node.expression.end; var dotRangeEnd = ts.skipTrivia(currentText, node.expression.end) + 1; var dotToken = { kind: 21 /* DotToken */, pos: dotRangeStart, end: dotRangeEnd }; indentBeforeDot = needsIndentation(node, node.expression, dotToken); indentAfterDot = needsIndentation(node, dotToken, node.name); } - var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); emitExpression(node.expression); increaseIndentIf(indentBeforeDot); + var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); write(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); @@ -55284,17 +56448,16 @@ var ts; var text = getLiteralTextOfNode(expression); return text.indexOf(ts.tokenToString(21 /* DotToken */)) < 0; } - else { + else if (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression)) { // check if constant enum value is integer - var constantValue = tryGetConstEnumValue(expression); + var constantValue = ts.getConstantValue(expression); // isFinite handles cases when constantValue is undefined - return isFinite(constantValue) && Math.floor(constantValue) === constantValue; + return isFinite(constantValue) + && Math.floor(constantValue) === constantValue + && compilerOptions.removeComments; } } function emitElementAccessExpression(node) { - if (tryEmitConstantValue(node)) { - return; - } emitExpression(node.expression); write("["); emitExpression(node.argumentExpression); @@ -55467,7 +56630,7 @@ var ts; } } function emitBlockStatements(node) { - if (node.emitFlags & 32 /* SingleLine */) { + if (ts.getEmitFlags(node) & 32 /* SingleLine */) { emitList(node, node.statements, 384 /* SingleLineBlockStatements */); } else { @@ -55645,11 +56808,11 @@ var ts; var body = node.body; if (body) { if (ts.isBlock(body)) { - var indentedFlag = node.emitFlags & 524288 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 524288 /* Indented */; if (indentedFlag) { increaseIndent(); } - if (node.emitFlags & 4194304 /* ReuseTempVariableScope */) { + if (ts.getEmitFlags(node) & 4194304 /* ReuseTempVariableScope */) { emitSignatureHead(node); emitBlockFunctionBody(node, body); } @@ -55687,7 +56850,7 @@ var ts; // * The body is explicitly marked as multi-line. // * A non-synthesized body's start and end position are on different lines. // * Any statement in the body starts on a new line. - if (body.emitFlags & 32 /* SingleLine */) { + if (ts.getEmitFlags(body) & 32 /* SingleLine */) { return true; } if (body.multiLine) { @@ -55743,7 +56906,7 @@ var ts; emitModifiers(node, node.modifiers); write("class"); emitNodeWithPrefix(" ", node.name, emitIdentifierName); - var indentedFlag = node.emitFlags & 524288 /* Indented */; + var indentedFlag = ts.getEmitFlags(node) & 524288 /* Indented */; if (indentedFlag) { increaseIndent(); } @@ -55805,7 +56968,7 @@ var ts; emit(body); } function emitModuleBlock(node) { - if (isSingleLineEmptyBlock(node)) { + if (isEmptyBlock(node)) { write("{ }"); } else { @@ -56023,8 +57186,8 @@ var ts; // "comment1" is not considered to be leading comment for node.initializer // but rather a trailing comment on the previous node. var initializer = node.initializer; - if (!shouldSkipLeadingCommentsForNode(initializer)) { - var commentRange = initializer.commentRange || initializer; + if ((ts.getEmitFlags(initializer) & 16384 /* NoLeadingComments */) === 0) { + var commentRange = ts.getCommentRange(initializer); emitTrailingCommentsOfPosition(commentRange.pos); } emitExpression(initializer); @@ -56084,7 +57247,7 @@ var ts; return statements.length; } function emitHelpers(node) { - var emitFlags = node.emitFlags; + var emitFlags = ts.getEmitFlags(node); var helpersEmitted = false; if (emitFlags & 1 /* EmitEmitHelpers */) { helpersEmitted = emitEmitHelpers(currentSourceFile); @@ -56197,31 +57360,6 @@ var ts; write(suffix); } } - function tryEmitSubstitute(node, emitNode, isExpression) { - if (isSubstitutionEnabled(node) && (node.emitFlags & 128 /* NoSubstitution */) === 0) { - var substitute = onSubstituteNode(node, isExpression); - if (substitute !== node) { - substitute.emitFlags |= 128 /* NoSubstitution */; - emitNode(substitute); - return true; - } - } - return false; - } - function tryEmitConstantValue(node) { - var constantValue = tryGetConstEnumValue(node); - if (constantValue !== undefined) { - write(String(constantValue)); - if (!compilerOptions.removeComments) { - var propertyName = ts.isPropertyAccessExpression(node) - ? ts.declarationNameToString(node.name) - : getTextOfNode(node.argumentExpression); - write(" /* " + propertyName + " */"); - } - return true; - } - return false; - } function emitEmbeddedStatement(node) { if (ts.isBlock(node)) { write(" "); @@ -56329,7 +57467,7 @@ var ts; } } if (shouldEmitInterveningComments) { - var commentRange = child.commentRange || child; + var commentRange = ts.getCommentRange(child); emitTrailingCommentsOfPosition(commentRange.pos); } else { @@ -56375,27 +57513,12 @@ var ts; } } function writeToken(token, pos, contextNode) { - var tokenStartPos = emitTokenStart(token, pos, contextNode, shouldSkipLeadingSourceMapForToken, getTokenSourceMapRange); - var tokenEndPos = writeTokenText(token, tokenStartPos); - return emitTokenEnd(token, tokenEndPos, contextNode, shouldSkipTrailingSourceMapForToken, getTokenSourceMapRange); - } - function shouldSkipLeadingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 4096 /* NoTokenLeadingSourceMaps */) !== 0; - } - function shouldSkipTrailingSourceMapForToken(contextNode) { - return (contextNode.emitFlags & 8192 /* NoTokenTrailingSourceMaps */) !== 0; + return emitTokenWithSourceMap(contextNode, token, pos, writeTokenText); } function writeTokenText(token, pos) { var tokenString = ts.tokenToString(token); write(tokenString); - return ts.positionIsSynthesized(pos) ? -1 : pos + tokenString.length; - } - function writeTokenNode(node) { - if (node) { - emitStart(/*range*/ node, /*contextNode*/ node, shouldSkipLeadingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - writeTokenText(node.kind); - emitEnd(/*range*/ node, /*contextNode*/ node, shouldSkipTrailingSourceMapForNode, shouldSkipSourceMapForChildren, getSourceMapRange); - } + return pos < 0 ? pos : pos + tokenString.length; } function increaseIndentIf(value, valueToWriteWhenNotIndenting) { if (value) { @@ -56539,17 +57662,12 @@ var ts; } return ts.getLiteralText(node, currentSourceFile, languageVersion); } - function tryGetConstEnumValue(node) { - if (compilerOptions.isolatedModules) { - return undefined; - } - return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) - ? resolver.getConstantValue(node) - : undefined; - } function isSingleLineEmptyBlock(block) { return !block.multiLine - && block.statements.length === 0 + && isEmptyBlock(block); + } + function isEmptyBlock(block) { + return block.statements.length === 0 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile); } function isUniqueName(name) { @@ -56878,695 +57996,6 @@ var ts; return ts.getNormalizedPathFromPathComponents(commonPathComponents); } ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames; - function trace(host, message) { - host.trace(ts.formatMessage.apply(undefined, arguments)); - } - function isTraceEnabled(compilerOptions, host) { - return compilerOptions.traceResolution && host.trace !== undefined; - } - /* @internal */ - function hasZeroOrOneAsteriskCharacter(str) { - var seenAsterisk = false; - for (var i = 0; i < str.length; i++) { - if (str.charCodeAt(i) === 42 /* asterisk */) { - if (!seenAsterisk) { - seenAsterisk = true; - } - else { - // have already seen asterisk - return false; - } - } - } - return true; - } - ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - function createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations) { - return { resolvedModule: resolvedFileName ? { resolvedFileName: resolvedFileName, isExternalLibraryImport: isExternalLibraryImport } : undefined, failedLookupLocations: failedLookupLocations }; - } - function moduleHasNonRelativeName(moduleName) { - return !(ts.isRootedDiskPath(moduleName) || ts.isExternalModuleNameRelative(moduleName)); - } - function tryReadTypesSection(packageJsonPath, baseDirectory, state) { - var jsonContent = readJson(packageJsonPath, state.host); - function tryReadFromField(fieldName) { - if (ts.hasProperty(jsonContent, fieldName)) { - var typesFile = jsonContent[fieldName]; - if (typeof typesFile === "string") { - var typesFilePath_1 = ts.normalizePath(ts.combinePaths(baseDirectory, typesFile)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, typesFile, typesFilePath_1); - } - return typesFilePath_1; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_string_got_1, fieldName, typeof typesFile); - } - } - } - } - var typesFilePath = tryReadFromField("typings") || tryReadFromField("types"); - if (typesFilePath) { - return typesFilePath; - } - // Use the main module for inferring types if no types package specified and the allowJs is set - if (state.compilerOptions.allowJs && jsonContent.main && typeof jsonContent.main === "string") { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.No_types_specified_in_package_json_but_allowJs_is_set_so_returning_main_value_of_0, jsonContent.main); - } - var mainFilePath = ts.normalizePath(ts.combinePaths(baseDirectory, jsonContent.main)); - return mainFilePath; - } - return undefined; - } - function readJson(path, host) { - try { - var jsonText = host.readFile(path); - return jsonText ? JSON.parse(jsonText) : {}; - } - catch (e) { - // gracefully handle if readFile fails or returns not JSON - return {}; - } - } - var typeReferenceExtensions = [".d.ts"]; - function getEffectiveTypeRoots(options, host) { - if (options.typeRoots) { - return options.typeRoots; - } - var currentDirectory; - if (options.configFilePath) { - currentDirectory = ts.getDirectoryPath(options.configFilePath); - } - else if (host.getCurrentDirectory) { - currentDirectory = host.getCurrentDirectory(); - } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); - } - ts.getEffectiveTypeRoots = getEffectiveTypeRoots; - /** - * Returns the path to every node_modules/@types directory from some ancestor directory. - * Returns undefined if there are none. - */ - function getDefaultTypeRoots(currentDirectory, host) { - if (!host.directoryExists) { - return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)]; - } - var typeRoots; - while (true) { - var atTypes = ts.combinePaths(currentDirectory, nodeModulesAtTypes); - if (host.directoryExists(atTypes)) { - (typeRoots || (typeRoots = [])).push(atTypes); - } - var parent_15 = ts.getDirectoryPath(currentDirectory); - if (parent_15 === currentDirectory) { - break; - } - currentDirectory = parent_15; - } - return typeRoots; - } - var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types"); - /** - * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown. - * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups - * is assumed to be the same as root directory of the project. - */ - function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host) { - var traceEnabled = isTraceEnabled(options, host); - var moduleResolutionState = { - compilerOptions: options, - host: host, - skipTsx: true, - traceEnabled: traceEnabled - }; - var typeRoots = getEffectiveTypeRoots(options, host); - if (traceEnabled) { - if (containingFile === undefined) { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots); - } - } - else { - if (typeRoots === undefined) { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile); - } - else { - trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots); - } - } - } - var failedLookupLocations = []; - // Check primary library paths - if (typeRoots && typeRoots.length) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", ")); - } - var primarySearchPaths = typeRoots; - for (var _i = 0, primarySearchPaths_1 = primarySearchPaths; _i < primarySearchPaths_1.length; _i++) { - var typeRoot = primarySearchPaths_1[_i]; - var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName); - var candidateDirectory = ts.getDirectoryPath(candidate); - var resolvedFile_1 = loadNodeModuleFromDirectory(typeReferenceExtensions, candidate, failedLookupLocations, !directoryProbablyExists(candidateDirectory, host), moduleResolutionState); - if (resolvedFile_1) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile_1, true); - } - return { - resolvedTypeReferenceDirective: { primary: true, resolvedFileName: resolvedFile_1 }, - failedLookupLocations: failedLookupLocations - }; - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths); - } - } - var resolvedFile; - var initialLocationForSecondaryLookup; - if (containingFile) { - initialLocationForSecondaryLookup = ts.getDirectoryPath(containingFile); - } - if (initialLocationForSecondaryLookup !== undefined) { - // check secondary locations - if (traceEnabled) { - trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup); - } - resolvedFile = loadModuleFromNodeModules(typeReferenceDirectiveName, initialLocationForSecondaryLookup, failedLookupLocations, moduleResolutionState); - if (traceEnabled) { - if (resolvedFile) { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFile, false); - } - else { - trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName); - } - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder); - } - } - return { - resolvedTypeReferenceDirective: resolvedFile - ? { primary: false, resolvedFileName: resolvedFile } - : undefined, - failedLookupLocations: failedLookupLocations - }; - } - ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective; - function resolveModuleName(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile); - } - var moduleResolution = compilerOptions.moduleResolution; - if (moduleResolution === undefined) { - moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic; - if (traceEnabled) { - trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - else { - if (traceEnabled) { - trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]); - } - } - var result; - switch (moduleResolution) { - case ts.ModuleResolutionKind.NodeJs: - result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host); - break; - case ts.ModuleResolutionKind.Classic: - result = classicNameResolver(moduleName, containingFile, compilerOptions, host); - break; - } - if (traceEnabled) { - if (result.resolvedModule) { - trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName); - } - else { - trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName); - } - } - return result; - } - ts.resolveModuleName = resolveModuleName; - /** - * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to - * mitigate differences between design time structure of the project and its runtime counterpart so the same import name - * can be resolved successfully by TypeScript compiler and runtime module loader. - * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will - * fallback to standard resolution routine. - * - * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative - * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will - * be '/a/b/c/d' - * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names - * will be resolved based on the content of the module name. - * Structure of 'paths' compiler options - * 'paths': { - * pattern-1: [...substitutions], - * pattern-2: [...substitutions], - * ... - * pattern-n: [...substitutions] - * } - * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against - * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case. - * If pattern contains '*' then to match pattern "*" module name must start with the and end with . - * denotes part of the module name between and . - * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked. - * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module - * from the candidate location. - * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every - * substitution in the list and replace '*' with string. If candidate location is not rooted it - * will be converted to absolute using baseUrl. - * For example: - * baseUrl: /a/b/c - * "paths": { - * // match all module names - * "*": [ - * "*", // use matched name as is, - * // will be looked as /a/b/c/ - * - * "folder1/*" // substitution will convert matched name to 'folder1/', - * // since it is not rooted then final candidate location will be /a/b/c/folder1/ - * ], - * // match module names that start with 'components/' - * "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/ to '/root/components/folder1/', - * // it is rooted so it will be final candidate location - * } - * - * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if - * they were in the same location. For example lets say there are two files - * '/local/src/content/file1.ts' - * '/shared/components/contracts/src/content/protocols/file2.ts' - * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so - * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime. - * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all - * root dirs were merged together. - * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ]. - * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file: - * '/local/src/content/protocols/file2' and try to load it - failure. - * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will - * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining - * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location. - */ - function tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (moduleHasNonRelativeName(moduleName)) { - return tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state); - } - else { - return tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state); - } - } - function tryLoadModuleUsingRootDirs(moduleName, containingDirectory, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.rootDirs) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName); - } - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - var matchedRootDir; - var matchedNormalizedPrefix; - for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) { - var rootDir = _a[_i]; - // rootDirs are expected to be absolute - // in case of tsconfig.json this will happen automatically - compiler will expand relative names - // using location of tsconfig.json as base location - var normalizedRoot = ts.normalizePath(rootDir); - if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) { - normalizedRoot += ts.directorySeparator; - } - var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) && - (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix); - } - if (isLongestMatchingPrefix) { - matchedNormalizedPrefix = normalizedRoot; - matchedRootDir = rootDir; - } - } - if (matchedNormalizedPrefix) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix); - } - var suffix = candidate.substr(matchedNormalizedPrefix.length); - // first - try to load from a initial location - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(containingDirectory, state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs); - } - // then try to resolve using remaining entries in rootDirs - for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) { - var rootDir = _c[_b]; - if (rootDir === matchedRootDir) { - // skip the initially matched entry - continue; - } - var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1); - } - var baseDirectory = ts.getDirectoryPath(candidate_1); - var resolvedFileName_1 = loader(candidate_1, supportedExtensions, failedLookupLocations, !directoryProbablyExists(baseDirectory, state.host), state); - if (resolvedFileName_1) { - return resolvedFileName_1; - } - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed); - } - } - return undefined; - } - function tryLoadModuleUsingBaseUrl(moduleName, loader, failedLookupLocations, supportedExtensions, state) { - if (!state.compilerOptions.baseUrl) { - return undefined; - } - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, state.compilerOptions.baseUrl, moduleName); - } - // string is for exact match - var matchedPattern = undefined; - if (state.compilerOptions.paths) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); - } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); - } - if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); - } - for (var _i = 0, _a = state.compilerOptions.paths[matchedPatternText]; _i < _a.length; _i++) { - var subst = _a[_i]; - var path = matchedStar ? subst.replace("*", matchedStar) : subst; - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, path)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path); - } - var resolvedFileName = loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - if (resolvedFileName) { - return resolvedFileName; - } - } - return undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(state.compilerOptions.baseUrl, moduleName)); - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, state.compilerOptions.baseUrl, candidate); - } - return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); - } - } - /** - * patternStrings contains both pattern strings (containing "*") and regular strings. - * Return an exact match if possible, or a pattern match, or undefined. - * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.) - */ - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - // pattern was matched as is - no need to search further - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - /** - * Given that candidate matches pattern, returns the text matching the '*'. - * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar" - */ - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - /** Return the object corresponding to the best pattern to match `candidate`. */ - /* @internal */ - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - // use length of prefix as betterness criteria - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - /* @internal */ - function tryParsePattern(pattern) { - // This should be verified outside of here and a proper error thrown. - ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; - function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { - var containingDirectory = ts.getDirectoryPath(containingFile); - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var traceEnabled = isTraceEnabled(compilerOptions, host); - var failedLookupLocations = []; - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: false }; - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, nodeLoadModuleByRelativeName, failedLookupLocations, supportedExtensions, state); - var isExternalLibraryImport = false; - if (!resolvedFileName) { - if (moduleHasNonRelativeName(moduleName)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder, moduleName); - } - resolvedFileName = loadModuleFromNodeModules(moduleName, containingDirectory, failedLookupLocations, state); - isExternalLibraryImport = resolvedFileName !== undefined; - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - resolvedFileName = nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - } - } - if (resolvedFileName && host.realpath) { - var originalFileName = resolvedFileName; - resolvedFileName = ts.normalizePath(host.realpath(resolvedFileName)); - if (traceEnabled) { - trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, originalFileName, resolvedFileName); - } - } - return createResolvedModule(resolvedFileName, isExternalLibraryImport, failedLookupLocations); - } - ts.nodeModuleNameResolver = nodeModuleNameResolver; - function nodeLoadModuleByRelativeName(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0, candidate); - } - var resolvedFileName = !ts.pathEndsWithDirectorySeparator(candidate) && loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, onlyRecordFailures, state); - return resolvedFileName || loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, onlyRecordFailures, state); - } - /* @internal */ - function directoryProbablyExists(directoryName, host) { - // if host does not support 'directoryExists' assume that directory will exist - return !host.directoryExists || host.directoryExists(directoryName); - } - ts.directoryProbablyExists = directoryProbablyExists; - /** - * @param {boolean} onlyRecordFailures - if true then function won't try to actually load files but instead record all attempts as failures. This flag is necessary - * in cases when we know upfront that all load attempts will fail (because containing folder does not exists) however we still need to record all failed lookup locations. - */ - function loadModuleFromFile(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts" - var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state); - if (resolvedByAddingExtension) { - return resolvedByAddingExtension; - } - // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one; - // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts" - if (ts.hasJavaScriptFileExtension(candidate)) { - var extensionless = ts.removeFileExtension(candidate); - if (state.traceEnabled) { - var extension = candidate.substring(extensionless.length); - trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension); - } - return tryAddingExtensions(extensionless, extensions, failedLookupLocation, onlyRecordFailures, state); - } - } - /** Try to return an existing file that adds one of the `extensions` to `candidate`. */ - function tryAddingExtensions(candidate, extensions, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures) { - // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing - var directory = ts.getDirectoryPath(candidate); - if (directory) { - onlyRecordFailures = !directoryProbablyExists(directory, state.host); - } - } - return ts.forEach(extensions, function (ext) { - return !(state.skipTsx && ts.isJsxOrTsxExtension(ext)) && tryFile(candidate + ext, failedLookupLocation, onlyRecordFailures, state); - }); - } - /** Return the file if it exists. */ - function tryFile(fileName, failedLookupLocation, onlyRecordFailures, state) { - if (!onlyRecordFailures && state.host.fileExists(fileName)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName); - } - return fileName; - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName); - } - failedLookupLocation.push(fileName); - return undefined; - } - } - function loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocation, onlyRecordFailures, state) { - var packageJsonPath = pathToPackageJson(candidate); - var directoryExists = !onlyRecordFailures && directoryProbablyExists(candidate, state.host); - if (directoryExists && state.host.fileExists(packageJsonPath)) { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } - var typesFile = tryReadTypesSection(packageJsonPath, candidate, state); - if (typesFile) { - var onlyRecordFailures_1 = !directoryProbablyExists(ts.getDirectoryPath(typesFile), state.host); - // A package.json "typings" may specify an exact filename, or may choose to omit an extension. - var result = tryFile(typesFile, failedLookupLocation, onlyRecordFailures_1, state) || - tryAddingExtensions(typesFile, extensions, failedLookupLocation, onlyRecordFailures_1, state); - if (result) { - return result; - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.package_json_does_not_have_types_field); - } - } - } - else { - if (state.traceEnabled) { - trace(state.host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath); - } - // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results - failedLookupLocation.push(packageJsonPath); - } - return loadModuleFromFile(ts.combinePaths(candidate, "index"), extensions, failedLookupLocation, !directoryExists, state); - } - function pathToPackageJson(directory) { - return ts.combinePaths(directory, "package.json"); - } - function loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state) { - var nodeModulesFolder = ts.combinePaths(directory, "node_modules"); - var nodeModulesFolderExists = directoryProbablyExists(nodeModulesFolder, state.host); - var candidate = ts.normalizePath(ts.combinePaths(nodeModulesFolder, moduleName)); - var supportedExtensions = ts.getSupportedExtensions(state.compilerOptions); - var result = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - result = loadNodeModuleFromDirectory(supportedExtensions, candidate, failedLookupLocations, !nodeModulesFolderExists, state); - if (result) { - return result; - } - } - function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state) { - directory = ts.normalizeSlashes(directory); - while (true) { - var baseName = ts.getBaseFileName(directory); - if (baseName !== "node_modules") { - // Try to load source from the package - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - // Always prefer a TypeScript (.ts, .tsx, .d.ts) file shipped with the package - return packageResult; - } - else { - // Else prefer a types package over non-TypeScript results (e.g. JavaScript files) - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; - } - } - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - break; - } - directory = parentPath; - } - return undefined; - } - function classicNameResolver(moduleName, containingFile, compilerOptions, host) { - var traceEnabled = isTraceEnabled(compilerOptions, host); - var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; - var failedLookupLocations = []; - var supportedExtensions = ts.getSupportedExtensions(compilerOptions); - var containingDirectory = ts.getDirectoryPath(containingFile); - var resolvedFileName = tryLoadModuleUsingOptionalResolutionSettings(moduleName, containingDirectory, loadModuleFromFile, failedLookupLocations, supportedExtensions, state); - if (resolvedFileName) { - return createResolvedModule(resolvedFileName, /*isExternalLibraryImport*/ false, failedLookupLocations); - } - var referencedSourceFile; - if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } - } - else { - var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(candidate, supportedExtensions, failedLookupLocations, /*onlyRecordFailures*/ false, state); - } - return referencedSourceFile - ? { resolvedModule: { resolvedFileName: referencedSourceFile }, failedLookupLocations: failedLookupLocations } - : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; - } - ts.classicNameResolver = classicNameResolver; function createCompilerHost(options, setParentNodes) { var existingDirectories = ts.createMap(); function getCanonicalFileName(fileName) { @@ -57672,7 +58101,7 @@ var ts; readFile: function (fileName) { return ts.sys.readFile(fileName); }, trace: function (s) { return ts.sys.write(s + newLine); }, directoryExists: function (directoryName) { return ts.sys.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return ts.getEnvironmentVariable(name, /*host*/ undefined); }, + getEnvironmentVariable: function (name) { return ts.sys.getEnvironmentVariable ? ts.sys.getEnvironmentVariable(name) : ""; }, getDirectories: function (path) { return ts.sys.getDirectories(path); }, realpath: realpath }; @@ -57740,45 +58169,6 @@ var ts; } return resolutions; } - /** - * Given a set of options, returns the set of type directive names - * that should be included for this program automatically. - * This list could either come from the config file, - * or from enumerating the types root + initial secondary types lookup location. - * More type directives might appear in the program later as a result of loading actual source files; - * this list is only the set of defaults that are implicitly included. - */ - function getAutomaticTypeDirectiveNames(options, host) { - // Use explicit type list from tsconfig.json - if (options.types) { - return options.types; - } - // Walk the primary type lookup locations - var result = []; - if (host.directoryExists && host.getDirectories) { - var typeRoots = getEffectiveTypeRoots(options, host); - if (typeRoots) { - for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) { - var root = typeRoots_1[_i]; - if (host.directoryExists(root)) { - for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) { - var typeDirectivePath = _b[_a]; - var normalized = ts.normalizePath(typeDirectivePath); - var packageJsonPath = pathToPackageJson(ts.combinePaths(root, normalized)); - // tslint:disable-next-line:no-null-keyword - var isNotNeededPackage = host.fileExists(packageJsonPath) && readJson(packageJsonPath, host).typings === null; - if (!isNotNeededPackage) { - // Return just the type directive names - result.push(ts.getBaseFileName(normalized)); - } - } - } - } - } - } - return result; - } - ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames; function createProgram(rootNames, options, host, oldProgram) { var program; var files = []; @@ -57815,7 +58205,7 @@ var ts; resolveModuleNamesWorker = function (moduleNames, containingFile) { return host.resolveModuleNames(moduleNames, containingFile); }; } else { - var loader_1 = function (moduleName, containingFile) { return resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; + var loader_1 = function (moduleName, containingFile) { return ts.resolveModuleName(moduleName, containingFile, options, host).resolvedModule; }; resolveModuleNamesWorker = function (moduleNames, containingFile) { return loadWithLocalCache(moduleNames, containingFile, loader_1); }; } var resolveTypeReferenceDirectiveNamesWorker; @@ -57823,7 +58213,7 @@ var ts; resolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }; } else { - var loader_2 = function (typesRef, containingFile) { return resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; + var loader_2 = function (typesRef, containingFile) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host).resolvedTypeReferenceDirective; }; resolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile) { return loadWithLocalCache(typeReferenceDirectiveNames, containingFile, loader_2); }; } var filesByName = ts.createFileMap(); @@ -57833,8 +58223,8 @@ var ts; if (!tryReuseStructureFromOldProgram()) { ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false); }); // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders - var typeReferences = getAutomaticTypeDirectiveNames(options, host); - if (typeReferences) { + var typeReferences = ts.getAutomaticTypeDirectiveNames(options, host); + if (typeReferences.length) { // This containingFilename needs to match with the one used in managed-side var containingFilename = ts.combinePaths(host.getCurrentDirectory(), "__inferred type names__.ts"); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); @@ -57884,7 +58274,8 @@ var ts; getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); }, getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); }, getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; }, - getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; } + getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; }, + dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -57938,6 +58329,7 @@ var ts; (oldOptions.configFilePath !== options.configFilePath) || (oldOptions.baseUrl !== options.baseUrl) || (oldOptions.maxNodeModuleJsDepth !== options.maxNodeModuleJsDepth) || + !ts.arrayIsEqualTo(oldOptions.lib, options.lib) || !ts.arrayIsEqualTo(oldOptions.typeRoots, oldOptions.typeRoots) || !ts.arrayIsEqualTo(oldOptions.rootDirs, options.rootDirs) || !ts.equalOwnProperties(oldOptions.paths, options.paths)) { @@ -58054,16 +58446,19 @@ var ts; function getDiagnosticsProducingTypeChecker() { return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true)); } + function dropDiagnosticsProducingTypeChecker() { + diagnosticsProducingTypeChecker = undefined; + } function getTypeChecker() { return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false)); } - function emit(sourceFile, writeFileCallback, cancellationToken) { - return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken); }); + function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { + return runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles); }); } function isEmitBlocked(emitFileName) { return hasEmitBlockingDiagnostics.contains(ts.toPath(emitFileName, currentDirectory, getCanonicalFileName)); } - function emitWorker(program, sourceFile, writeFileCallback, cancellationToken) { + function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles) { var declarationDiagnostics = []; if (options.noEmit) { return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; @@ -58095,7 +58490,7 @@ var ts; // checked is to not pass the file to getEmitResolver. var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); ts.performance.mark("beforeEmit"); - var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile); + var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles); ts.performance.mark("afterEmit"); ts.performance.measure("Emit", "beforeEmit", "afterEmit"); return emitResult; @@ -58659,7 +59054,6 @@ var ts; for (var i = 0; i < moduleNames.length; i++) { var resolution = resolutions[i]; ts.setResolvedModule(file, moduleNames[i], resolution); - var resolvedPath = resolution ? ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName) : undefined; // add file to program only if: // - resolution was successful // - noResolve is falsy @@ -58676,7 +59070,7 @@ var ts; modulesWithElidedImports[file.path] = true; } else if (shouldAddFile) { - findSourceFile(resolution.resolvedFileName, resolvedPath, + findSourceFile(resolution.resolvedFileName, ts.toPath(resolution.resolvedFileName, currentDirectory, getCanonicalFileName), /*isDefaultLib*/ false, /*isReference*/ false, file, ts.skipTrivia(file.text, file.imports[i].pos), file.imports[i].end); } if (isFromNodeModulesSearch) { @@ -58692,8 +59086,8 @@ var ts; } function computeCommonSourceDirectory(sourceFiles) { var fileNames = []; - for (var _i = 0, sourceFiles_5 = sourceFiles; _i < sourceFiles_5.length; _i++) { - var file = sourceFiles_5[_i]; + for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { + var file = sourceFiles_6[_i]; if (!file.isDeclarationFile) { fileNames.push(file.fileName); } @@ -58704,8 +59098,8 @@ var ts; var allFilesBelongToPath = true; if (sourceFiles) { var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory)); - for (var _i = 0, sourceFiles_6 = sourceFiles; _i < sourceFiles_6.length; _i++) { - var sourceFile = sourceFiles_6[_i]; + for (var _i = 0, sourceFiles_7 = sourceFiles; _i < sourceFiles_7.length; _i++) { + var sourceFile = sourceFiles_7[_i]; if (!ts.isDeclarationFile(sourceFile)) { var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory)); if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) { @@ -58748,7 +59142,7 @@ var ts; if (!ts.hasProperty(options.paths, key)) { continue; } - if (!hasZeroOrOneAsteriskCharacter(key)) { + if (!ts.hasZeroOrOneAsteriskCharacter(key)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key)); } if (ts.isArray(options.paths[key])) { @@ -58759,7 +59153,7 @@ var ts; var subst = _a[_i]; var typeOfSubst = typeof subst; if (typeOfSubst === "string") { - if (!hasZeroOrOneAsteriskCharacter(subst)) { + if (!ts.hasZeroOrOneAsteriskCharacter(subst)) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Substitution_0_in_pattern_1_in_can_have_at_most_one_Asterisk_character, subst, key)); } } @@ -58799,6 +59193,9 @@ var ts; if (options.lib && options.noLib) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib")); } + if (options.noImplicitUseStrict && options.alwaysStrict) { + programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict")); + } var languageVersion = options.target || 0 /* ES3 */; var outFile = options.outFile || options.out; var firstNonAmbientExternalModuleSourceFile = ts.forEach(files, function (f) { return ts.isExternalModule(f) && !ts.isDeclarationFile(f) ? f : undefined; }); @@ -58891,12 +59288,15 @@ var ts; /// var ts; (function (ts) { + /* @internal */ + ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" }; /* @internal */ ts.optionDeclarations = [ { name: "charset", type: "string" }, + ts.compileOnSaveCommandLineOption, { name: "declaration", shortName: "d", @@ -59327,6 +59727,11 @@ var ts; name: "importHelpers", type: "boolean", description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "alwaysStrict", + type: "boolean", + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file } ]; /* @internal */ @@ -59547,10 +59952,11 @@ var ts; * @param fileName The path to the config file * @param jsonText The text of the config file */ - function parseConfigFileTextToJson(fileName, jsonText) { + function parseConfigFileTextToJson(fileName, jsonText, stripComments) { + if (stripComments === void 0) { stripComments = true; } try { - var jsonTextWithoutComments = removeComments(jsonText); - return { config: /\S/.test(jsonTextWithoutComments) ? JSON.parse(jsonTextWithoutComments) : {} }; + var jsonTextToParse = stripComments ? removeComments(jsonText) : jsonText; + return { config: /\S/.test(jsonTextToParse) ? JSON.parse(jsonTextToParse) : {} }; } catch (e) { return { error: ts.createCompilerDiagnostic(ts.Diagnostics.Failed_to_parse_file_0_Colon_1, fileName, e.message) }; @@ -59712,13 +60118,15 @@ var ts; options = ts.extend(existingOptions, options); options.configFilePath = configFileName; var _c = getFileNames(errors), fileNames = _c.fileNames, wildcardDirectories = _c.wildcardDirectories; + var compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors); return { options: options, fileNames: fileNames, typingOptions: typingOptions, raw: json, errors: errors, - wildcardDirectories: wildcardDirectories + wildcardDirectories: wildcardDirectories, + compileOnSave: compileOnSave }; function tryExtendsName(extendedConfig) { // If the path isn't a rooted or relative path, don't try to resolve it (we reserve the right to special case module-id like paths in the future) @@ -59799,6 +60207,17 @@ var ts; var _b; } ts.parseJsonConfigFileContent = parseJsonConfigFileContent; + function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) { + if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) { + return false; + } + var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption["compileOnSave"], basePath, errors); + if (typeof result === "boolean" && result) { + return result; + } + return false; + } + ts.convertCompileOnSaveOptionFromJson = convertCompileOnSaveOptionFromJson; function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) { var errors = []; var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName); @@ -59812,7 +60231,9 @@ var ts; } ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { - var options = ts.getBaseFileName(configFileName) === "jsconfig.json" ? { allowJs: true, maxNodeModuleJsDepth: 2 } : {}; + var options = ts.getBaseFileName(configFileName) === "jsconfig.json" + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } + : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; } @@ -60742,7 +61163,7 @@ var ts; return true; case 69 /* Identifier */: // 'this' as a parameter - return node.originalKeywordKind === 97 /* ThisKeyword */ && node.parent.kind === 142 /* Parameter */; + return ts.identifierIsThisKeyword(node) && node.parent.kind === 142 /* Parameter */; default: return false; } @@ -61420,7 +61841,6 @@ var ts; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ -var ts; (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { return symbol.declarations && symbol.declarations.length > 0 && symbol.declarations[0].kind === 142 /* Parameter */; @@ -61657,7 +62077,7 @@ var ts; return ts.ensureScriptKind(fileName, scriptKind); } ts.getScriptKind = getScriptKind; - function parseAndReEmitConfigJSONFile(content) { + function sanitizeConfigFile(configFileName, content) { var options = { fileName: "config.js", compilerOptions: { @@ -61671,14 +62091,17 @@ var ts; // also, the emitted result will have "(" in the beginning and ");" in the end. We need to strip these // as well var trimmedOutput = outputText.trim(); - var configJsonObject = JSON.parse(trimmedOutput.substring(1, trimmedOutput.length - 2)); for (var _i = 0, diagnostics_2 = diagnostics; _i < diagnostics_2.length; _i++) { var diagnostic = diagnostics_2[_i]; diagnostic.start = diagnostic.start - 1; } - return { configJsonObject: configJsonObject, diagnostics: diagnostics }; + var _b = ts.parseConfigFileTextToJson(configFileName, trimmedOutput.substring(1, trimmedOutput.length - 2), /*stripComments*/ false), config = _b.config, error = _b.error; + return { + configJsonObject: config || {}, + diagnostics: error ? ts.concatenate(diagnostics, [error]) : diagnostics + }; } - ts.parseAndReEmitConfigJSONFile = parseAndReEmitConfigJSONFile; + ts.sanitizeConfigFile = sanitizeConfigFile; })(ts || (ts = {})); var ts; (function (ts) { @@ -62538,8 +62961,7 @@ var ts; return; case 142 /* Parameter */: if (token.parent.name === token) { - var isThis_1 = token.kind === 69 /* Identifier */ && token.originalKeywordKind === 97 /* ThisKeyword */; - return isThis_1 ? 3 /* keyword */ : 17 /* parameterName */; + return ts.isThisIdentifier(token) ? 3 /* keyword */ : 17 /* parameterName */; } return; } @@ -62583,14 +63005,14 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; + var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, isJsDocTagName = completionData.isJsDocTagName; if (isJsDocTagName) { // If the current position is a jsDoc tag name, only tag names should be provided for completion - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: ts.JsDoc.getAllJsDocCompletionEntries() }; } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ false); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true); ts.addRange(entries, getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames)); } else { @@ -62619,7 +63041,7 @@ var ts; if (!isMemberCompletion && !isJsDocTagName) { ts.addRange(entries, keywordCompletions); } - return { isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation || ts.isSourceFileJavaScript(sourceFile), entries: entries }; + return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames) { var entries = []; var nameTable = ts.getNameTable(sourceFile); @@ -62690,7 +63112,9 @@ var ts; if (!node || node.kind !== 9 /* StringLiteral */) { return undefined; } - if (node.parent.kind === 253 /* PropertyAssignment */ && node.parent.parent.kind === 171 /* ObjectLiteralExpression */) { + if (node.parent.kind === 253 /* PropertyAssignment */ && + node.parent.parent.kind === 171 /* ObjectLiteralExpression */ && + node.parent.name === node) { // Get quoted name of properties of the object literal expression // i.e. interface ConfigFiles { // 'jspm:dev': string @@ -62740,7 +63164,7 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } } @@ -62756,7 +63180,7 @@ var ts; } } if (entries.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries }; } return undefined; } @@ -62766,7 +63190,7 @@ var ts; if (type) { getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, node, /*performCharacterChecks*/ false); if (entries.length) { - return { isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; + return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } } return undefined; @@ -62777,7 +63201,7 @@ var ts; var entries_2 = []; addStringLiteralCompletionsFromType(type, entries_2); if (entries_2.length) { - return { isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_2 }; } } return undefined; @@ -62819,6 +63243,7 @@ var ts; entries = getCompletionEntriesForNonRelativeModules(literalValue, scriptDirectory, span); } return { + isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: true, entries: entries @@ -62854,15 +63279,24 @@ var ts; } return result; } + /** + * Given a path ending at a directory, gets the completions for the path, and filters for those entries containing the basename. + */ function getCompletionEntriesForDirectoryFragment(fragment, scriptPath, extensions, includeExtensions, span, exclude, result) { if (result === void 0) { result = []; } + if (fragment === undefined) { + fragment = ""; + } + fragment = ts.normalizeSlashes(fragment); + /** + * Remove the basename from the path. Note that we don't use the basename to filter completions; + * the client is responsible for refining completions. + */ fragment = ts.getDirectoryPath(fragment); - if (!fragment) { - fragment = "./"; - } - else { - fragment = ts.ensureTrailingDirectorySeparator(fragment); + if (fragment === "") { + fragment = "." + ts.directorySeparator; } + fragment = ts.ensureTrailingDirectorySeparator(fragment); var absolutePath = normalizeAndPreserveTrailingSlash(ts.isRootedDiskPath(fragment) ? fragment : ts.combinePaths(scriptPath, fragment)); var baseDirectory = ts.getDirectoryPath(absolutePath); var ignoreCase = !(host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames()); @@ -62870,6 +63304,12 @@ var ts; // Enumerate the available files if possible var files = tryReadDirectory(host, baseDirectory, extensions, /*exclude*/ undefined, /*include*/ ["./*"]); if (files) { + /** + * Multiple file entries might map to the same truncated name once we remove extensions + * (happens iff includeExtensions === false)so we use a set-like data structure. Eg: + * + * both foo.ts and foo.tsx become foo + */ var foundFiles = ts.createMap(); for (var _i = 0, files_3 = files; _i < files_3.length; _i++) { var filePath = files_3[_i]; @@ -63039,6 +63479,19 @@ var ts; if (!range) { return undefined; } + var completionInfo = { + /** + * We don't want the editor to offer any other completions, such as snippets, inside a comment. + */ + isGlobalCompletion: false, + isMemberCompletion: false, + /** + * The user may type in a path that doesn't yet exist, creating a "new identifier" + * with respect to the collection of identifiers the server is aware of. + */ + isNewIdentifierLocation: true, + entries: [] + }; var text = sourceFile.text.substr(range.pos, position - range.pos); var match = tripleSlashDirectiveFragmentRegex.exec(text); if (match) { @@ -63046,24 +63499,18 @@ var ts; var kind = match[2]; var toComplete = match[3]; var scriptPath = ts.getDirectoryPath(sourceFile.path); - var entries_3; if (kind === "path") { // Give completions for a relative path var span_10 = getDirectoryFragmentTextSpan(toComplete, range.pos + prefix.length); - entries_3 = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, sourceFile.path); + completionInfo.entries = getCompletionEntriesForDirectoryFragment(toComplete, scriptPath, ts.getSupportedExtensions(compilerOptions), /*includeExtensions*/ true, span_10, sourceFile.path); } else { // Give completions based on the typings available var span_11 = { start: range.pos + prefix.length, length: match[0].length - prefix.length }; - entries_3 = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); + completionInfo.entries = getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span_11); } - return { - isMemberCompletion: false, - isNewIdentifierLocation: true, - entries: entries_3 - }; } - return undefined; + return completionInfo; } function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { if (result === void 0) { result = []; } @@ -63285,7 +63732,7 @@ var ts; } } if (isJsDocTagName) { - return { symbols: undefined, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; + return { symbols: undefined, isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, location: undefined, isRightOfDot: false, isJsDocTagName: isJsDocTagName }; } if (!insideJsDocTagExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal @@ -63349,6 +63796,7 @@ var ts; } } var semanticStart = ts.timestamp(); + var isGlobalCompletion = false; var isMemberCompletion; var isNewIdentifierLocation; var symbols = []; @@ -63382,11 +63830,13 @@ var ts; if (!tryGetGlobalSymbols()) { return undefined; } + isGlobalCompletion = true; } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); - return { symbols: symbols, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; + return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), isJsDocTagName: isJsDocTagName }; function getTypeScriptMemberSymbols() { // Right of dot member completion list + isGlobalCompletion = false; isMemberCompletion = true; isNewIdentifierLocation = false; if (node.kind === 69 /* Identifier */ || node.kind === 139 /* QualifiedName */ || node.kind === 172 /* PropertyAccessExpression */) { @@ -63448,6 +63898,7 @@ var ts; if ((jsxContainer.kind === 242 /* JsxSelfClosingElement */) || (jsxContainer.kind === 243 /* JsxOpeningElement */)) { // Cursor is inside a JSX self-closing element or opening element attrsType = typeChecker.getJsxElementAttributesType(jsxContainer); + isGlobalCompletion = false; if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes); isMemberCompletion = true; @@ -64026,9 +64477,15 @@ var ts; * Matches a triple slash reference directive with an incomplete string literal for its path. Used * to determine if the caret is currently within the string literal and capture the literal fragment * for completions. - * For example, this matches /// +/// +/// +/// /* @internal */ var ts; (function (ts) { @@ -66442,6 +66901,7 @@ var ts; // A map of loose file names to library names // that we are confident require typings var safeList; + var EmptySafeList = ts.createMap(); /** * @param host is the object providing I/O related operations. * @param fileNames are the file names that belong to the same project @@ -66458,10 +66918,13 @@ var ts; return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] }; } // Only infer typings for .js and .jsx files - fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 1 /* JS */, 2 /* JSX */); }); + fileNames = ts.filter(ts.map(fileNames, ts.normalizePath), function (f) { + var kind = ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)); + return kind === 1 /* JS */ || kind === 2 /* JSX */; + }); if (!safeList) { var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); }); - safeList = ts.createMap(result.config); + safeList = result.config ? ts.createMap(result.config) : EmptySafeList; } var filesToWatch = []; // Directories to search for package.json, bower.json and other typing information @@ -66552,13 +67015,10 @@ var ts; var jsFileNames = ts.filter(fileNames, ts.hasJavaScriptFileExtension); var inferredTypingNames = ts.map(jsFileNames, function (f) { return ts.removeFileExtension(ts.getBaseFileName(f.toLowerCase())); }); var cleanedTypingNames = ts.map(inferredTypingNames, function (f) { return f.replace(/((?:\.|-)min(?=\.|$))|((?:-|\.)\d+)/g, ""); }); - if (safeList === undefined) { - mergeTypings(cleanedTypingNames); - } - else { + if (safeList !== EmptySafeList) { mergeTypings(ts.filter(cleanedTypingNames, function (f) { return f in safeList; })); } - var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.scriptKindIs(f, /*LanguageServiceHost*/ undefined, 2 /* JSX */); }); + var hasJsxFile = ts.forEach(fileNames, function (f) { return ts.ensureScriptKind(f, ts.getScriptKindFromFileName(f)) === 2 /* JSX */; }); if (hasJsxFile) { mergeTypings(["react"]); } @@ -66573,7 +67033,7 @@ var ts; return; } var typingNames = []; - var fileNames = host.readDirectory(nodeModulesPath, ["*.json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); + var fileNames = host.readDirectory(nodeModulesPath, [".json"], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2); for (var _i = 0, fileNames_2 = fileNames; _i < fileNames_2.length; _i++) { var fileName = fileNames_2[_i]; var normalizedFileName = ts.normalizePath(fileName); @@ -66616,7 +67076,7 @@ var ts; (function (ts) { var NavigateTo; (function (NavigateTo) { - function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount) { + function getNavigateToItems(sourceFiles, checker, cancellationToken, searchValue, maxResultCount, excludeDtsFiles) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; // This means "compare in a case insensitive manner." @@ -66624,6 +67084,9 @@ var ts; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] ts.forEach(sourceFiles, function (sourceFile) { cancellationToken.throwIfCancellationRequested(); + if (excludeDtsFiles && ts.fileExtensionIs(sourceFile.fileName, ".d.ts")) { + return; + } var nameToDeclarations = sourceFile.getNamedDeclarations(); for (var name_49 in nameToDeclarations) { var declarations = nameToDeclarations[name_49]; @@ -66803,6 +67266,13 @@ var ts; return result; } NavigationBar.getNavigationBarItems = getNavigationBarItems; + function getNavigationTree(sourceFile) { + curSourceFile = sourceFile; + var result = convertToTree(rootNavigationBarNode(sourceFile)); + curSourceFile = undefined; + return result; + } + NavigationBar.getNavigationTree = getNavigationTree; // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`. var curSourceFile; function nodeText(node) { @@ -67077,7 +67547,7 @@ var ts; } } // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. - var collator = typeof Intl === "undefined" ? undefined : new Intl.Collator(); + var collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; // Intl is missing in Safari, and node 0.10 treats "a" as greater than "B". var localeCompareIsCorrect = collator && collator.compare("a", "B") < 0; var localeCompareFix = localeCompareIsCorrect ? collator.compare : function (a, b) { @@ -67242,6 +67712,15 @@ var ts; } // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance. var emptyChildItemArray = []; + function convertToTree(n) { + return { + text: getItemName(n.node), + kind: ts.getNodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToTree) + }; + } function convertToTopLevelItem(n) { return { text: getItemName(n.node), @@ -67265,16 +67744,16 @@ var ts; grayed: false }; } - function getSpans(n) { - var spans = [getNodeSpan(n.node)]; - if (n.additionalNodes) { - for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { - var node = _a[_i]; - spans.push(getNodeSpan(node)); - } + } + function getSpans(n) { + var spans = [getNodeSpan(n.node)]; + if (n.additionalNodes) { + for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { + var node = _a[_i]; + spans.push(getNodeSpan(node)); } - return spans; } + return spans; } function getModuleName(moduleDeclaration) { // We want to maintain quotation marks. @@ -71005,25 +71484,25 @@ var ts; }; RulesProvider.prototype.createActiveRules = function (options) { var rules = this.globalRules.HighPriorityCommonRules.slice(0); - if (options.InsertSpaceAfterCommaDelimiter) { + if (options.insertSpaceAfterCommaDelimiter) { rules.push(this.globalRules.SpaceAfterComma); } else { rules.push(this.globalRules.NoSpaceAfterComma); } - if (options.InsertSpaceAfterFunctionKeywordForAnonymousFunctions) { + if (options.insertSpaceAfterFunctionKeywordForAnonymousFunctions) { rules.push(this.globalRules.SpaceAfterAnonymousFunctionKeyword); } else { rules.push(this.globalRules.NoSpaceAfterAnonymousFunctionKeyword); } - if (options.InsertSpaceAfterKeywordsInControlFlowStatements) { + if (options.insertSpaceAfterKeywordsInControlFlowStatements) { rules.push(this.globalRules.SpaceAfterKeywordInControl); } else { rules.push(this.globalRules.NoSpaceAfterKeywordInControl); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis) { rules.push(this.globalRules.SpaceAfterOpenParen); rules.push(this.globalRules.SpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); @@ -71033,7 +71512,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseParen); rules.push(this.globalRules.NoSpaceBetweenParens); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets) { rules.push(this.globalRules.SpaceAfterOpenBracket); rules.push(this.globalRules.SpaceBeforeCloseBracket); rules.push(this.globalRules.NoSpaceBetweenBrackets); @@ -71045,7 +71524,7 @@ var ts; } // The default value of InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces is true // so if the option is undefined, we should treat it as true as well - if (options.InsertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { + if (options.insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces !== false) { rules.push(this.globalRules.SpaceAfterOpenBrace); rules.push(this.globalRules.SpaceBeforeCloseBrace); rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); @@ -71055,7 +71534,7 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeCloseBrace); rules.push(this.globalRules.NoSpaceBetweenEmptyBraceBrackets); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { + if (options.insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces) { rules.push(this.globalRules.SpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.SpaceBeforeTemplateMiddleAndTail); } @@ -71063,7 +71542,7 @@ var ts; rules.push(this.globalRules.NoSpaceAfterTemplateHeadAndMiddle); rules.push(this.globalRules.NoSpaceBeforeTemplateMiddleAndTail); } - if (options.InsertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { + if (options.insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces) { rules.push(this.globalRules.SpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.SpaceBeforeCloseBraceInJsxExpression); } @@ -71071,13 +71550,13 @@ var ts; rules.push(this.globalRules.NoSpaceAfterOpenBraceInJsxExpression); rules.push(this.globalRules.NoSpaceBeforeCloseBraceInJsxExpression); } - if (options.InsertSpaceAfterSemicolonInForStatements) { + if (options.insertSpaceAfterSemicolonInForStatements) { rules.push(this.globalRules.SpaceAfterSemicolonInFor); } else { rules.push(this.globalRules.NoSpaceAfterSemicolonInFor); } - if (options.InsertSpaceBeforeAndAfterBinaryOperators) { + if (options.insertSpaceBeforeAndAfterBinaryOperators) { rules.push(this.globalRules.SpaceBeforeBinaryOperator); rules.push(this.globalRules.SpaceAfterBinaryOperator); } @@ -71085,14 +71564,14 @@ var ts; rules.push(this.globalRules.NoSpaceBeforeBinaryOperator); rules.push(this.globalRules.NoSpaceAfterBinaryOperator); } - if (options.PlaceOpenBraceOnNewLineForControlBlocks) { + if (options.placeOpenBraceOnNewLineForControlBlocks) { rules.push(this.globalRules.NewLineBeforeOpenBraceInControl); } - if (options.PlaceOpenBraceOnNewLineForFunctions) { + if (options.placeOpenBraceOnNewLineForFunctions) { rules.push(this.globalRules.NewLineBeforeOpenBraceInFunction); rules.push(this.globalRules.NewLineBeforeOpenBraceInTypeScriptDeclWithBlock); } - if (options.InsertSpaceAfterTypeAssertion) { + if (options.insertSpaceAfterTypeAssertion) { rules.push(this.globalRules.SpaceAfterTypeAssertion); } else { @@ -71222,7 +71701,7 @@ var ts; return ts.rangeContainsRange(parent.members, node); case 225 /* ModuleDeclaration */: var body = parent.body; - return body && body.kind === 199 /* Block */ && ts.rangeContainsRange(body.statements, node); + return body && body.kind === 226 /* ModuleBlock */ && ts.rangeContainsRange(body.statements, node); case 256 /* SourceFile */: case 199 /* Block */: case 226 /* ModuleBlock */: @@ -71332,7 +71811,7 @@ var ts; break; } if (formatting.SmartIndenter.shouldIndentChildNode(n, child)) { - return options.IndentSize; + return options.indentSize; } previousLine = line; child = n; @@ -71404,7 +71883,7 @@ var ts; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { var indentation = inheritedIndentation; - var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.IndentSize : 0; + var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent @@ -71412,7 +71891,7 @@ var ts; indentation = startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.IndentSize, parentDynamicIndentation.getDelta(node) + delta); + delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta); } else if (indentation === -1 /* Unknown */) { if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { @@ -71493,13 +71972,13 @@ var ts; recomputeIndentation: function (lineAdded) { if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { if (lineAdded) { - indentation += options.IndentSize; + indentation += options.indentSize; } else { - indentation -= options.IndentSize; + indentation -= options.indentSize; } if (formatting.SmartIndenter.shouldIndentChildNode(node)) { - delta = options.IndentSize; + delta = options.indentSize; } else { delta = 0; @@ -71919,7 +72398,7 @@ var ts; // edit should not be applied only if we have one line feed between elements var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { - recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.NewLineCharacter); + recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); } break; case 2 /* Space */: @@ -71980,14 +72459,14 @@ var ts; var internedSpacesIndentation; function getIndentationString(indentation, options) { // reset interned strings if FormatCodeOptions were changed - var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.TabSize || internedSizes.indentSize !== options.IndentSize); + var resetInternedStrings = !internedSizes || (internedSizes.tabSize !== options.tabSize || internedSizes.indentSize !== options.indentSize); if (resetInternedStrings) { - internedSizes = { tabSize: options.TabSize, indentSize: options.IndentSize }; + internedSizes = { tabSize: options.tabSize, indentSize: options.indentSize }; internedTabsIndentation = internedSpacesIndentation = undefined; } - if (!options.ConvertTabsToSpaces) { - var tabs = Math.floor(indentation / options.TabSize); - var spaces = indentation - tabs * options.TabSize; + if (!options.convertTabsToSpaces) { + var tabs = Math.floor(indentation / options.tabSize); + var spaces = indentation - tabs * options.tabSize; var tabString = void 0; if (!internedTabsIndentation) { internedTabsIndentation = []; @@ -72002,13 +72481,13 @@ var ts; } else { var spacesString = void 0; - var quotient = Math.floor(indentation / options.IndentSize); - var remainder = indentation % options.IndentSize; + var quotient = Math.floor(indentation / options.indentSize); + var remainder = indentation % options.indentSize; if (!internedSpacesIndentation) { internedSpacesIndentation = []; } if (internedSpacesIndentation[quotient] === undefined) { - spacesString = repeat(" ", options.IndentSize * quotient); + spacesString = repeat(" ", options.indentSize * quotient); internedSpacesIndentation[quotient] = spacesString; } else { @@ -72045,7 +72524,7 @@ var ts; } // no indentation when the indent style is set to none, // so we can return fast - if (options.IndentStyle === ts.IndentStyle.None) { + if (options.indentStyle === ts.IndentStyle.None) { return 0; } var precedingToken = ts.findPrecedingToken(position, sourceFile); @@ -72061,7 +72540,7 @@ var ts; // indentation is first non-whitespace character in a previous line // for block indentation, we should look for a line which contains something that's not // whitespace. - if (options.IndentStyle === ts.IndentStyle.Block) { + if (options.indentStyle === ts.IndentStyle.Block) { // move backwards until we find a line with a non-whitespace character, // then find the first non-whitespace character for that line. var current_1 = position; @@ -72095,7 +72574,7 @@ var ts; indentationDelta = 0; } else { - indentationDelta = lineAtPosition !== currentStart.line ? options.IndentSize : 0; + indentationDelta = lineAtPosition !== currentStart.line ? options.indentSize : 0; } break; } @@ -72106,7 +72585,7 @@ var ts; } actualIndentation = getLineIndentationWhenExpressionIsInMultiLine(current, sourceFile, options); if (actualIndentation !== -1 /* Unknown */) { - return actualIndentation + options.IndentSize; + return actualIndentation + options.indentSize; } previous = current; current = current.parent; @@ -72118,15 +72597,15 @@ var ts; return getIndentationForNodeWorker(current, currentStart, /*ignoreActualIndentationRange*/ undefined, indentationDelta, sourceFile, options); } SmartIndenter.getIndentation = getIndentation; - function getBaseIndentation(options) { - return options.BaseIndentSize || 0; - } - SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNode(n, ignoreActualIndentationRange, sourceFile, options) { var start = sourceFile.getLineAndCharacterOfPosition(n.getStart(sourceFile)); return getIndentationForNodeWorker(n, start, ignoreActualIndentationRange, /*indentationDelta*/ 0, sourceFile, options); } SmartIndenter.getIndentationForNode = getIndentationForNode; + function getBaseIndentation(options) { + return options.baseIndentSize || 0; + } + SmartIndenter.getBaseIndentation = getBaseIndentation; function getIndentationForNodeWorker(current, currentStart, ignoreActualIndentationRange, indentationDelta, sourceFile, options) { var parent = current.parent; var parentStart; @@ -72161,7 +72640,7 @@ var ts; } // increase indentation if parent node wants its content to be indented and parent and child nodes don't start on the same line if (shouldIndentChildNode(parent, current) && !parentAndChildShareLine) { - indentationDelta += options.IndentSize; + indentationDelta += options.indentSize; } current = parent; currentStart = parentStart; @@ -72371,7 +72850,7 @@ var ts; break; } if (ch === 9 /* tab */) { - column += options.TabSize + (column % options.TabSize); + column += options.tabSize + (column % options.tabSize); } else { column++; @@ -72473,6 +72952,117 @@ var ts; })(SmartIndenter = formatting.SmartIndenter || (formatting.SmartIndenter = {})); })(formatting = ts.formatting || (ts.formatting = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + var codeFixes = ts.createMap(); + function registerCodeFix(action) { + ts.forEach(action.errorCodes, function (error) { + var fixes = codeFixes[error]; + if (!fixes) { + fixes = []; + codeFixes[error] = fixes; + } + fixes.push(action); + }); + } + codefix.registerCodeFix = registerCodeFix; + function getSupportedErrorCodes() { + return Object.keys(codeFixes); + } + codefix.getSupportedErrorCodes = getSupportedErrorCodes; + function getFixes(context) { + var fixes = codeFixes[context.errorCode]; + var allActions = []; + ts.forEach(fixes, function (f) { + var actions = f.getCodeActions(context); + if (actions && actions.length > 0) { + allActions = allActions.concat(actions); + } + }); + return allActions; + } + codefix.getFixes = getFixes; + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + function getOpenBraceEnd(constructor, sourceFile) { + // First token is the open curly, this is where we want to put the 'super' call. + return constructor.body.getFirstToken(sourceFile).getEnd(); + } + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 121 /* ConstructorKeyword */) { + return undefined; + } + var newPosition = getOpenBraceEnd(token.parent, sourceFile); + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Add_missing_super_call), + changes: [{ fileName: sourceFile.fileName, textChanges: [{ newText: "super();", span: { start: newPosition, length: 0 } }] }] + }]; + } + }); + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class.code], + getCodeActions: function (context) { + var sourceFile = context.sourceFile; + var token = ts.getTokenAtPosition(sourceFile, context.span.start); + if (token.kind !== 97 /* ThisKeyword */) { + return undefined; + } + var constructor = ts.getContainingFunction(token); + var superCall = findSuperCall(constructor.body); + if (!superCall) { + return undefined; + } + // figure out if the this access is actuall inside the supercall + // i.e. super(this.a), since in that case we won't suggest a fix + if (superCall.expression && superCall.expression.kind == 174 /* CallExpression */) { + var arguments_1 = superCall.expression.arguments; + for (var i = 0; i < arguments_1.length; i++) { + if (arguments_1[i].expression === token) { + return undefined; + } + } + } + var newPosition = getOpenBraceEnd(constructor, sourceFile); + var changes = [{ + fileName: sourceFile.fileName, textChanges: [{ + newText: superCall.getText(sourceFile), + span: { start: newPosition, length: 0 } + }, + { + newText: "", + span: { start: superCall.getStart(sourceFile), length: superCall.getWidth(sourceFile) } + }] + }]; + return [{ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Make_super_call_the_first_statement_in_the_constructor), + changes: changes + }]; + function findSuperCall(n) { + if (n.kind === 202 /* ExpressionStatement */ && ts.isSuperCall(n.expression)) { + return n; + } + if (ts.isFunctionLike(n)) { + return undefined; + } + return ts.forEachChild(n, findSuperCall); + } + } + }); + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +/// /// /// /// @@ -72498,13 +73088,15 @@ var ts; /// /// /// +/// +/// var ts; (function (ts) { /** The version of the language service API */ ts.servicesVersion = "0.5"; function createNode(kind, pos, end, parent) { var node = kind >= 139 /* FirstNode */ ? new NodeObject(kind, pos, end) : - kind === 69 /* Identifier */ ? new IdentifierObject(kind, pos, end) : + kind === 69 /* Identifier */ ? new IdentifierObject(69 /* Identifier */, pos, end) : new TokenObject(kind, pos, end); node.parent = parent; return node; @@ -72732,15 +73324,16 @@ var ts; var TokenObject = (function (_super) { __extends(TokenObject, _super); function TokenObject(kind, pos, end) { - _super.call(this, pos, end); - this.kind = kind; + var _this = _super.call(this, pos, end) || this; + _this.kind = kind; + return _this; } return TokenObject; }(TokenOrIdentifierObject)); var IdentifierObject = (function (_super) { __extends(IdentifierObject, _super); function IdentifierObject(kind, pos, end) { - _super.call(this, pos, end); + return _super.call(this, pos, end) || this; } return IdentifierObject; }(TokenOrIdentifierObject)); @@ -72816,7 +73409,7 @@ var ts; var SourceFileObject = (function (_super) { __extends(SourceFileObject, _super); function SourceFileObject(kind, pos, end) { - _super.call(this, kind, pos, end); + return _super.call(this, kind, pos, end) || this; } SourceFileObject.prototype.update = function (newText, textChangeRange) { return ts.updateSourceFile(this, newText, textChangeRange); @@ -72985,6 +73578,30 @@ var ts; getSignatureConstructor: function () { return SignatureObject; } }; } + function toEditorSettings(optionsAsMap) { + var allPropertiesAreCamelCased = true; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key) && !isCamelCase(key)) { + allPropertiesAreCamelCased = false; + break; + } + } + if (allPropertiesAreCamelCased) { + return optionsAsMap; + } + var settings = {}; + for (var key in optionsAsMap) { + if (ts.hasProperty(optionsAsMap, key)) { + var newKey = isCamelCase(key) ? key : key.charAt(0).toLowerCase() + key.substr(1); + settings[newKey] = optionsAsMap[key]; + } + } + return settings; + } + ts.toEditorSettings = toEditorSettings; + function isCamelCase(s) { + return !s.length || s.charAt(0) === s.charAt(0).toLowerCase(); + } function displayPartsToString(displayParts) { if (displayParts) { return ts.map(displayParts, function (displayPart) { return displayPart.text; }).join(""); @@ -73000,9 +73617,13 @@ var ts; }; } ts.getDefaultCompilerOptions = getDefaultCompilerOptions; - // Cache host information about script should be refreshed + function getSupportedCodeFixes() { + return ts.codefix.getSupportedErrorCodes(); + } + ts.getSupportedCodeFixes = getSupportedCodeFixes; + // Cache host information about script Should be refreshed // at each language service public entry point, since we don't know when - // set of scripts handled by the host changes. + // the set of scripts handled by the host changes. var HostCache = (function () { function HostCache(host, getCanonicalFileName) { this.host = host; @@ -73185,7 +73806,8 @@ var ts; var ruleProvider; var program; var lastProjectVersion; - var useCaseSensitivefileNames = false; + var lastTypesRootVersion = 0; + var useCaseSensitivefileNames = host.useCaseSensitiveFileNames && host.useCaseSensitiveFileNames(); var cancellationToken = new CancellationTokenObject(host.getCancellationToken && host.getCancellationToken()); var currentDirectory = host.getCurrentDirectory(); // Check if the localized messages json is set, otherwise query the host for it @@ -73224,6 +73846,12 @@ var ts; lastProjectVersion = hostProjectVersion; } } + var typeRootsVersion = host.getTypeRootsVersion ? host.getTypeRootsVersion() : 0; + if (lastTypesRootVersion !== typeRootsVersion) { + log("TypeRoots version has changed; provide new program"); + program = undefined; + lastTypesRootVersion = typeRootsVersion; + } // Get a fresh cache of the host information var hostCache = new HostCache(host, getCanonicalFileName); // If the program is already up-to-date, we can reuse it @@ -73553,12 +74181,12 @@ var ts; return ts.FindAllReferences.findReferencedSymbols(program.getTypeChecker(), cancellationToken, program.getSourceFiles(), getValidSourceFile(fileName), position, findInStrings, findInComments); } /// NavigateTo - function getNavigateToItems(searchValue, maxResultCount, fileName) { + function getNavigateToItems(searchValue, maxResultCount, fileName, excludeDtsFiles) { synchronizeHostData(); var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); - return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount); + return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName) { + function getEmitOutput(fileName, emitOnlyDtsFiles) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var outputFiles = []; @@ -73569,7 +74197,7 @@ var ts; text: data }); } - var emitOutput = program.emit(sourceFile, writeFile, cancellationToken); + var emitOutput = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles); return { outputFiles: outputFiles, emitSkipped: emitOutput.emitSkipped @@ -73647,14 +74275,28 @@ var ts; return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); } function getNavigationBarItems(fileName) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function getNavigationTree(fileName) { + return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function isTsOrTsxFile(fileName) { + var kind = ts.getScriptKind(fileName, host); + return kind === 3 /* TS */ || kind === 4 /* TSX */; } function getSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + // do not run semantic classification on non-ts-or-tsx files + return []; + } synchronizeHostData(); return ts.getSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } function getEncodedSemanticClassifications(fileName, span) { + if (!isTsOrTsxFile(fileName)) { + // do not run semantic classification on non-ts-or-tsx files + return { spans: [], endOfLineState: 0 /* None */ }; + } synchronizeHostData(); return ts.getEncodedSemanticClassifications(program.getTypeChecker(), cancellationToken, getValidSourceFile(fileName), program.getClassifiableNames(), span); } @@ -73715,34 +74357,60 @@ var ts; } function getIndentationAtPosition(fileName, position, editorOptions) { var start = ts.timestamp(); + var settings = toEditorSettings(editorOptions); var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); log("getIndentationAtPosition: getCurrentSourceFile: " + (ts.timestamp() - start)); start = ts.timestamp(); - var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, editorOptions); + var result = ts.formatting.SmartIndenter.getIndentation(position, sourceFile, settings); log("getIndentationAtPosition: computeIndentation : " + (ts.timestamp() - start)); return result; } function getFormattingEditsForRange(fileName, start, end, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatSelection(start, end, sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsForDocument(fileName, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.formatting.formatDocument(sourceFile, getRuleProvider(options), options); + var settings = toEditorSettings(options); + return ts.formatting.formatDocument(sourceFile, getRuleProvider(settings), settings); } function getFormattingEditsAfterKeystroke(fileName, position, key, options) { var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); + var settings = toEditorSettings(options); if (key === "}") { - return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnClosingCurly(position, sourceFile, getRuleProvider(settings), settings); } else if (key === ";") { - return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnSemicolon(position, sourceFile, getRuleProvider(settings), settings); } else if (key === "\n") { - return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(options), options); + return ts.formatting.formatOnEnter(position, sourceFile, getRuleProvider(settings), settings); } return []; } + function getCodeFixesAtPosition(fileName, start, end, errorCodes) { + synchronizeHostData(); + var sourceFile = getValidSourceFile(fileName); + var span = { start: start, length: end - start }; + var newLineChar = ts.getNewLineOrDefaultFromHost(host); + var allFixes = []; + ts.forEach(errorCodes, function (error) { + cancellationToken.throwIfCancellationRequested(); + var context = { + errorCode: error, + sourceFile: sourceFile, + span: span, + program: program, + newLineCharacter: newLineChar + }; + var fixes = ts.codefix.getFixes(context); + if (fixes) { + allFixes = allFixes.concat(fixes); + } + }); + return allFixes; + } function getDocCommentTemplateAtPosition(fileName, position) { return ts.JsDoc.getDocCommentTemplateAtPosition(ts.getNewLineOrDefaultFromHost(host), syntaxTreeCache.getCurrentSourceFile(fileName), position); } @@ -73926,6 +74594,7 @@ var ts; getRenameInfo: getRenameInfo, findRenameLocations: findRenameLocations, getNavigationBarItems: getNavigationBarItems, + getNavigationTree: getNavigationTree, getOutliningSpans: getOutliningSpans, getTodoComments: getTodoComments, getBraceMatchingAtPosition: getBraceMatchingAtPosition, @@ -73935,6 +74604,7 @@ var ts; getFormattingEditsAfterKeystroke: getFormattingEditsAfterKeystroke, getDocCommentTemplateAtPosition: getDocCommentTemplateAtPosition, isValidBraceCompletionAtPosition: isValidBraceCompletionAtPosition, + getCodeFixesAtPosition: getCodeFixesAtPosition, getEmitOutput: getEmitOutput, getNonBoundSourceFile: getNonBoundSourceFile, getSourceFile: getSourceFile, @@ -74624,7 +75294,7 @@ var ts; // /// /* @internal */ -var debugObjectHost = new Function("return this")(); +var debugObjectHost = (function () { return this; })(); // We need to use 'null' to interface with the managed side. /* tslint:disable:no-null-keyword */ /* tslint:disable:no-in-operator */ @@ -74712,6 +75382,12 @@ var ts; } return this.shimHost.getProjectVersion(); }; + LanguageServiceShimHostAdapter.prototype.getTypeRootsVersion = function () { + if (!this.shimHost.getTypeRootsVersion) { + return 0; + } + return this.shimHost.getTypeRootsVersion(); + }; LanguageServiceShimHostAdapter.prototype.useCaseSensitiveFileNames = function () { return this.shimHost.useCaseSensitiveFileNames ? this.shimHost.useCaseSensitiveFileNames() : false; }; @@ -74914,11 +75590,12 @@ var ts; var LanguageServiceShimObject = (function (_super) { __extends(LanguageServiceShimObject, _super); function LanguageServiceShimObject(factory, host, languageService) { - _super.call(this, factory); - this.host = host; - this.languageService = languageService; - this.logPerformance = false; - this.logger = this.host; + var _this = _super.call(this, factory) || this; + _this.host = host; + _this.languageService = languageService; + _this.logPerformance = false; + _this.logger = _this.host; + return _this; } LanguageServiceShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); @@ -75156,6 +75833,10 @@ var ts; var _this = this; return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; + LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); }); + }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); @@ -75182,10 +75863,11 @@ var ts; var ClassifierShimObject = (function (_super) { __extends(ClassifierShimObject, _super); function ClassifierShimObject(factory, logger) { - _super.call(this, factory); - this.logger = logger; - this.logPerformance = false; - this.classifier = ts.createClassifier(); + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.logPerformance = false; + _this.classifier = ts.createClassifier(); + return _this; } ClassifierShimObject.prototype.getEncodedLexicalClassifications = function (text, lexState, syntacticClassifierAbsent) { var _this = this; @@ -75208,10 +75890,11 @@ var ts; var CoreServicesShimObject = (function (_super) { __extends(CoreServicesShimObject, _super); function CoreServicesShimObject(factory, logger, host) { - _super.call(this, factory); - this.logger = logger; - this.host = host; - this.logPerformance = false; + var _this = _super.call(this, factory) || this; + _this.logger = logger; + _this.host = host; + _this.logPerformance = false; + return _this; } CoreServicesShimObject.prototype.forwardJSONCall = function (actionDescription, action) { return forwardJSONCall(this.logger, actionDescription, action, this.logPerformance); diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index b1248c700fa..577a8ee4fc9 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -72,7 +72,6 @@ var ts; (function (ts) { ts.timestamp = typeof performance !== "undefined" && performance.now ? function () { return performance.now(); } : Date.now ? Date.now : function () { return +(new Date()); }; })(ts || (ts = {})); -var ts; (function (ts) { var performance; (function (performance) { @@ -790,6 +789,56 @@ var ts; }; } ts.memoize = memoize; + function chain(a, b, c, d, e) { + if (e) { + var args_2 = []; + for (var i = 0; i < arguments.length; i++) { + args_2[i] = arguments[i]; + } + return function (t) { return compose.apply(void 0, map(args_2, function (f) { return f(t); })); }; + } + else if (d) { + return function (t) { return compose(a(t), b(t), c(t), d(t)); }; + } + else if (c) { + return function (t) { return compose(a(t), b(t), c(t)); }; + } + else if (b) { + return function (t) { return compose(a(t), b(t)); }; + } + else if (a) { + return function (t) { return compose(a(t)); }; + } + else { + return function (t) { return function (u) { return u; }; }; + } + } + ts.chain = chain; + function compose(a, b, c, d, e) { + if (e) { + var args_3 = []; + for (var i = 0; i < arguments.length; i++) { + args_3[i] = arguments[i]; + } + return function (t) { return reduceLeft(args_3, function (u, f) { return f(u); }, t); }; + } + else if (d) { + return function (t) { return d(c(b(a(t)))); }; + } + else if (c) { + return function (t) { return c(b(a(t))); }; + } + else if (b) { + return function (t) { return b(a(t)); }; + } + else if (a) { + return function (t) { return a(t); }; + } + else { + return function (t) { return t; }; + } + } + ts.compose = compose; function formatStringFromArgs(text, args, baseIndex) { baseIndex = baseIndex || 0; return text.replace(/{(\d+)}/g, function (match, index) { return args[+index + baseIndex]; }); @@ -1537,7 +1586,6 @@ var ts; this.transformFlags = 0; this.parent = undefined; this.original = undefined; - this.transformId = 0; } ts.objectAllocator = { getNodeConstructor: function () { return Node; }, @@ -1550,9 +1598,9 @@ var ts; }; var Debug; (function (Debug) { - var currentAssertionLevel; + Debug.currentAssertionLevel = 0; function shouldAssert(level) { - return getCurrentAssertionLevel() >= level; + return Debug.currentAssertionLevel >= level; } Debug.shouldAssert = shouldAssert; function assert(expression, message, verboseDebugInfo) { @@ -1570,30 +1618,7 @@ var ts; Debug.assert(false, message); } Debug.fail = fail; - function getCurrentAssertionLevel() { - if (currentAssertionLevel !== undefined) { - return currentAssertionLevel; - } - if (ts.sys === undefined) { - return 0; - } - var developmentMode = /^development$/i.test(getEnvironmentVariable("NODE_ENV")); - currentAssertionLevel = developmentMode - ? 1 - : 0; - return currentAssertionLevel; - } })(Debug = ts.Debug || (ts.Debug = {})); - function getEnvironmentVariable(name, host) { - if (host && host.getEnvironmentVariable) { - return host.getEnvironmentVariable(name); - } - if (ts.sys && ts.sys.getEnvironmentVariable) { - return ts.sys.getEnvironmentVariable(name); - } - return ""; - } - ts.getEnvironmentVariable = getEnvironmentVariable; function orderedRemoveItemAt(array, index) { for (var i = index; i < array.length - 1; i++) { array[i] = array[i + 1]; @@ -1624,6 +1649,60 @@ var ts; : (function (fileName) { return fileName.toLowerCase(); }); } ts.createGetCanonicalFileName = createGetCanonicalFileName; + function matchPatternOrExact(patternStrings, candidate) { + var patterns = []; + for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { + var patternString = patternStrings_1[_i]; + var pattern = tryParsePattern(patternString); + if (pattern) { + patterns.push(pattern); + } + else if (patternString === candidate) { + return patternString; + } + } + return findBestPatternMatch(patterns, function (_) { return _; }, candidate); + } + ts.matchPatternOrExact = matchPatternOrExact; + function patternText(_a) { + var prefix = _a.prefix, suffix = _a.suffix; + return prefix + "*" + suffix; + } + ts.patternText = patternText; + function matchedText(pattern, candidate) { + Debug.assert(isPatternMatch(pattern, candidate)); + return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); + } + ts.matchedText = matchedText; + function findBestPatternMatch(values, getPattern, candidate) { + var matchedValue = undefined; + var longestMatchPrefixLength = -1; + for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { + var v = values_1[_i]; + var pattern = getPattern(v); + if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { + longestMatchPrefixLength = pattern.prefix.length; + matchedValue = v; + } + } + return matchedValue; + } + ts.findBestPatternMatch = findBestPatternMatch; + function isPatternMatch(_a, candidate) { + var prefix = _a.prefix, suffix = _a.suffix; + return candidate.length >= prefix.length + suffix.length && + startsWith(candidate, prefix) && + endsWith(candidate, suffix); + } + function tryParsePattern(pattern) { + Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); + var indexOfStar = pattern.indexOf("*"); + return indexOfStar === -1 ? undefined : { + prefix: pattern.substr(0, indexOfStar), + suffix: pattern.substr(indexOfStar + 1) + }; + } + ts.tryParsePattern = tryParsePattern; function positionIsSynthesized(pos) { return !(pos >= 0); } @@ -1821,8 +1900,14 @@ var ts; function isNode4OrLater() { return parseInt(process.version.charAt(1)) >= 4; } + function isFileSystemCaseSensitive() { + if (platform === "win32" || platform === "win64") { + return false; + } + return !fileExists(__filename.toUpperCase()) || !fileExists(__filename.toLowerCase()); + } var platform = _os.platform(); - var useCaseSensitiveFileNames = platform !== "win32" && platform !== "win64" && platform !== "darwin"; + var useCaseSensitiveFileNames = isFileSystemCaseSensitive(); function readFile(fileName, encoding) { if (!fileExists(fileName)) { return undefined; @@ -1947,6 +2032,9 @@ var ts; }, watchDirectory: function (directoryName, callback, recursive) { var options; + if (!directoryExists(directoryName)) { + return; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -2090,6 +2178,11 @@ var ts; } return sys; })(); + if (ts.sys && ts.sys.getEnvironmentVariable) { + ts.Debug.currentAssertionLevel = /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV")) + ? 1 + : 0; + } })(ts || (ts = {})); var ts; (function (ts) { @@ -2414,7 +2507,7 @@ var ts; The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter: { code: 2407, category: ts.DiagnosticCategory.Error, key: "The_right_hand_side_of_a_for_in_statement_must_be_of_type_any_an_object_type_or_a_type_parameter_2407", message: "The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter." }, Setters_cannot_return_a_value: { code: 2408, category: ts.DiagnosticCategory.Error, key: "Setters_cannot_return_a_value_2408", message: "Setters cannot return a value." }, Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class: { code: 2409, category: ts.DiagnosticCategory.Error, key: "Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class_2409", message: "Return type of constructor signature must be assignable to the instance type of the class" }, - All_symbols_within_a_with_block_will_be_resolved_to_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "All_symbols_within_a_with_block_will_be_resolved_to_any_2410", message: "All symbols within a 'with' block will be resolved to 'any'." }, + The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any: { code: 2410, category: ts.DiagnosticCategory.Error, key: "The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any_2410", message: "The 'with' statement is not supported. All symbols in a 'with' block will have type 'any'." }, Property_0_of_type_1_is_not_assignable_to_string_index_type_2: { code: 2411, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411", message: "Property '{0}' of type '{1}' is not assignable to string index type '{2}'." }, Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2: { code: 2412, category: ts.DiagnosticCategory.Error, key: "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412", message: "Property '{0}' of type '{1}' is not assignable to numeric index type '{2}'." }, Numeric_index_type_0_is_not_assignable_to_string_index_type_1: { code: 2413, category: ts.DiagnosticCategory.Error, key: "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", message: "Numeric index type '{0}' is not assignable to string index type '{1}'." }, @@ -2575,7 +2668,7 @@ var ts; this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation: { code: 2683, category: ts.DiagnosticCategory.Error, key: "this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation_2683", message: "'this' implicitly has type 'any' because it does not have a type annotation." }, The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1: { code: 2684, category: ts.DiagnosticCategory.Error, key: "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684", message: "The 'this' context of type '{0}' is not assignable to method's 'this' of type '{1}'." }, The_this_types_of_each_signature_are_incompatible: { code: 2685, category: ts.DiagnosticCategory.Error, key: "The_this_types_of_each_signature_are_incompatible_2685", message: "The 'this' types of each signature are incompatible." }, - Identifier_0_must_be_imported_from_a_module: { code: 2686, category: ts.DiagnosticCategory.Error, key: "Identifier_0_must_be_imported_from_a_module_2686", message: "Identifier '{0}' must be imported from a module" }, + _0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead: { code: 2686, category: ts.DiagnosticCategory.Error, key: "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686", message: "'{0}' refers to a UMD global, but the current file is a module. Consider adding an import instead." }, All_declarations_of_0_must_have_identical_modifiers: { code: 2687, category: ts.DiagnosticCategory.Error, key: "All_declarations_of_0_must_have_identical_modifiers_2687", message: "All declarations of '{0}' must have identical modifiers." }, Cannot_find_type_definition_file_for_0: { code: 2688, category: ts.DiagnosticCategory.Error, key: "Cannot_find_type_definition_file_for_0_2688", message: "Cannot find type definition file for '{0}'." }, Cannot_extend_an_interface_0_Did_you_mean_implements: { code: 2689, category: ts.DiagnosticCategory.Error, key: "Cannot_extend_an_interface_0_Did_you_mean_implements_2689", message: "Cannot extend an interface '{0}'. Did you mean 'implements'?" }, @@ -2809,6 +2902,7 @@ var ts; Property_0_is_declared_but_never_used: { code: 6138, category: ts.DiagnosticCategory.Error, key: "Property_0_is_declared_but_never_used_6138", message: "Property '{0}' is declared but never used." }, Import_emit_helpers_from_tslib: { code: 6139, category: ts.DiagnosticCategory.Message, key: "Import_emit_helpers_from_tslib_6139", message: "Import emit helpers from 'tslib'." }, Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using_cache_location_2: { code: 6140, category: ts.DiagnosticCategory.Error, key: "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140", message: "Auto discovery for typings is enabled in project '{0}'. Running extra resolution pass for module '{1}' using cache location '{2}'." }, + Parse_in_strict_mode_and_emit_use_strict_for_each_source_file: { code: 6141, category: ts.DiagnosticCategory.Message, key: "Parse_in_strict_mode_and_emit_use_strict_for_each_source_file_6141", message: "Parse in strict mode and emit \"use strict\" for each source file" }, Variable_0_implicitly_has_an_1_type: { code: 7005, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_an_1_type_7005", message: "Variable '{0}' implicitly has an '{1}' type." }, Parameter_0_implicitly_has_an_1_type: { code: 7006, category: ts.DiagnosticCategory.Error, key: "Parameter_0_implicitly_has_an_1_type_7006", message: "Parameter '{0}' implicitly has an '{1}' type." }, Member_0_implicitly_has_an_1_type: { code: 7008, category: ts.DiagnosticCategory.Error, key: "Member_0_implicitly_has_an_1_type_7008", message: "Member '{0}' implicitly has an '{1}' type." }, @@ -2833,6 +2927,7 @@ var ts; Binding_element_0_implicitly_has_an_1_type: { code: 7031, category: ts.DiagnosticCategory.Error, key: "Binding_element_0_implicitly_has_an_1_type_7031", message: "Binding element '{0}' implicitly has an '{1}' type." }, Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation: { code: 7032, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032", message: "Property '{0}' implicitly has type 'any', because its set accessor lacks a parameter type annotation." }, Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation: { code: 7033, category: ts.DiagnosticCategory.Error, key: "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033", message: "Property '{0}' implicitly has type 'any', because its get accessor lacks a return type annotation." }, + Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined: { code: 7034, category: ts.DiagnosticCategory.Error, key: "Variable_0_implicitly_has_type_any_in_some_locations_where_its_type_cannot_be_determined_7034", message: "Variable '{0}' implicitly has type 'any' in some locations where its type cannot be determined." }, You_cannot_rename_this_element: { code: 8000, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_this_element_8000", message: "You cannot rename this element." }, You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: { code: 8001, category: ts.DiagnosticCategory.Error, key: "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", message: "You cannot rename elements that are defined in the standard TypeScript library." }, import_can_only_be_used_in_a_ts_file: { code: 8002, category: ts.DiagnosticCategory.Error, key: "import_can_only_be_used_in_a_ts_file_8002", message: "'import ... =' can only be used in a .ts file." }, @@ -2862,7 +2957,14 @@ var ts; super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class: { code: 17009, category: ts.DiagnosticCategory.Error, key: "super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class_17009", message: "'super' must be called before accessing 'this' in the constructor of a derived class." }, Unknown_typing_option_0: { code: 17010, category: ts.DiagnosticCategory.Error, key: "Unknown_typing_option_0_17010", message: "Unknown typing option '{0}'." }, Circularity_detected_while_resolving_configuration_Colon_0: { code: 18000, category: ts.DiagnosticCategory.Error, key: "Circularity_detected_while_resolving_configuration_Colon_0_18000", message: "Circularity detected while resolving configuration: {0}" }, - The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." } + The_path_in_an_extends_options_must_be_relative_or_rooted: { code: 18001, category: ts.DiagnosticCategory.Error, key: "The_path_in_an_extends_options_must_be_relative_or_rooted_18001", message: "The path in an 'extends' options must be relative or rooted." }, + Add_missing_super_call: { code: 90001, category: ts.DiagnosticCategory.Message, key: "Add_missing_super_call_90001", message: "Add missing 'super()' call." }, + Make_super_call_the_first_statement_in_the_constructor: { code: 90002, category: ts.DiagnosticCategory.Message, key: "Make_super_call_the_first_statement_in_the_constructor_90002", message: "Make 'super()' call the first statement in the constructor." }, + Change_extends_to_implements: { code: 90003, category: ts.DiagnosticCategory.Message, key: "Change_extends_to_implements_90003", message: "Change 'extends' to 'implements'" }, + Remove_unused_identifiers: { code: 90004, category: ts.DiagnosticCategory.Message, key: "Remove_unused_identifiers_90004", message: "Remove unused identifiers" }, + Implement_interface_on_reference: { code: 90005, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_reference_90005", message: "Implement interface on reference" }, + Implement_interface_on_class: { code: 90006, category: ts.DiagnosticCategory.Message, key: "Implement_interface_on_class_90006", message: "Implement interface on class" }, + Implement_inherited_abstract_class: { code: 90007, category: ts.DiagnosticCategory.Message, key: "Implement_inherited_abstract_class_90007", message: "Implement inherited abstract class" } }; })(ts || (ts = {})); var ts; @@ -3772,7 +3874,7 @@ var ts; return token = 69; } function scanBinaryOrOctalDigits(base) { - ts.Debug.assert(base !== 2 || base !== 8, "Expected either base 2 or base 8"); + ts.Debug.assert(base === 2 || base === 8, "Expected either base 2 or base 8"); var value = 0; var numberOfDigits = 0; while (true) { @@ -4844,6 +4946,11 @@ var ts; name: "importHelpers", type: "boolean", description: ts.Diagnostics.Import_emit_helpers_from_tslib + }, + { + name: "alwaysStrict", + type: "boolean", + description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file } ]; ts.typingOptionDeclarations = [ @@ -5294,7 +5401,7 @@ var ts; ts.convertTypingOptionsFromJson = convertTypingOptionsFromJson; function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) { var options = ts.getBaseFileName(configFileName) === "jsconfig.json" - ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true } + ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true } : {}; convertOptionsFromJson(ts.optionDeclarations, jsonOptions, basePath, options, ts.Diagnostics.Unknown_compiler_option_0, errors); return options; @@ -5704,7 +5811,7 @@ var ts; else if (host.getCurrentDirectory) { currentDirectory = host.getCurrentDirectory(); } - return currentDirectory && getDefaultTypeRoots(currentDirectory, host); + return currentDirectory !== undefined && getDefaultTypeRoots(currentDirectory, host); } ts.getEffectiveTypeRoots = getEffectiveTypeRoots; function getDefaultTypeRoots(currentDirectory, host) { @@ -5958,11 +6065,11 @@ var ts; if (state.traceEnabled) { trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName); } - matchedPattern = matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); + matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(state.compilerOptions.paths), moduleName); } if (matchedPattern) { - var matchedStar = typeof matchedPattern === "string" ? undefined : matchedText(matchedPattern, moduleName); - var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : patternText(matchedPattern); + var matchedStar = typeof matchedPattern === "string" ? undefined : ts.matchedText(matchedPattern, moduleName); + var matchedPatternText = typeof matchedPattern === "string" ? matchedPattern : ts.patternText(matchedPattern); if (state.traceEnabled) { trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText); } @@ -5988,57 +6095,6 @@ var ts; return loader(candidate, supportedExtensions, failedLookupLocations, !directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state); } } - function matchPatternOrExact(patternStrings, candidate) { - var patterns = []; - for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) { - var patternString = patternStrings_1[_i]; - var pattern = tryParsePattern(patternString); - if (pattern) { - patterns.push(pattern); - } - else if (patternString === candidate) { - return patternString; - } - } - return findBestPatternMatch(patterns, function (_) { return _; }, candidate); - } - function patternText(_a) { - var prefix = _a.prefix, suffix = _a.suffix; - return prefix + "*" + suffix; - } - function matchedText(pattern, candidate) { - ts.Debug.assert(isPatternMatch(pattern, candidate)); - return candidate.substr(pattern.prefix.length, candidate.length - pattern.suffix.length); - } - function findBestPatternMatch(values, getPattern, candidate) { - var matchedValue = undefined; - var longestMatchPrefixLength = -1; - for (var _i = 0, values_1 = values; _i < values_1.length; _i++) { - var v = values_1[_i]; - var pattern = getPattern(v); - if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) { - longestMatchPrefixLength = pattern.prefix.length; - matchedValue = v; - } - } - return matchedValue; - } - ts.findBestPatternMatch = findBestPatternMatch; - function isPatternMatch(_a, candidate) { - var prefix = _a.prefix, suffix = _a.suffix; - return candidate.length >= prefix.length + suffix.length && - ts.startsWith(candidate, prefix) && - ts.endsWith(candidate, suffix); - } - function tryParsePattern(pattern) { - ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); - var indexOfStar = pattern.indexOf("*"); - return indexOfStar === -1 ? undefined : { - prefix: pattern.substr(0, indexOfStar), - suffix: pattern.substr(indexOfStar + 1) - }; - } - ts.tryParsePattern = tryParsePattern; function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host) { var containingDirectory = ts.getDirectoryPath(containingFile); var supportedExtensions = ts.getSupportedExtensions(compilerOptions); @@ -6169,20 +6225,28 @@ var ts; } } function loadModuleFromNodeModules(moduleName, directory, failedLookupLocations, state, checkOneLevel) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, false); + } + ts.loadModuleFromNodeModules = loadModuleFromNodeModules; + function loadModuleFromNodeModulesAtTypes(moduleName, directory, failedLookupLocations, state) { + return loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, false, true); + } + function loadModuleFromNodeModulesWorker(moduleName, directory, failedLookupLocations, state, checkOneLevel, typesOnly) { directory = ts.normalizeSlashes(directory); while (true) { var baseName = ts.getBaseFileName(directory); if (baseName !== "node_modules") { - var packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); - if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { - return packageResult; - } - else { - var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); - if (typesResult || packageResult) { - return typesResult || packageResult; + var packageResult = void 0; + if (!typesOnly) { + packageResult = loadModuleFromNodeModulesFolder(moduleName, directory, failedLookupLocations, state); + if (packageResult && ts.hasTypeScriptFileExtension(packageResult)) { + return packageResult; } } + var typesResult = loadModuleFromNodeModulesFolder(ts.combinePaths("@types", moduleName), directory, failedLookupLocations, state); + if (typesResult || packageResult) { + return typesResult || packageResult; + } } var parentPath = ts.getDirectoryPath(directory); if (parentPath === directory || checkOneLevel) { @@ -6192,7 +6256,6 @@ var ts; } return undefined; } - ts.loadModuleFromNodeModules = loadModuleFromNodeModules; function classicNameResolver(moduleName, containingFile, compilerOptions, host) { var traceEnabled = isTraceEnabled(compilerOptions, host); var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, skipTsx: !compilerOptions.jsx }; @@ -6205,18 +6268,8 @@ var ts; } var referencedSourceFile; if (moduleHasNonRelativeName(moduleName)) { - while (true) { - var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); - referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); - if (referencedSourceFile) { - break; - } - var parentPath = ts.getDirectoryPath(containingDirectory); - if (parentPath === containingDirectory) { - break; - } - containingDirectory = parentPath; - } + referencedSourceFile = referencedSourceFile = loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) || + loadModuleFromNodeModulesAtTypes(moduleName, containingDirectory, failedLookupLocations, state); } else { var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); @@ -6227,6 +6280,20 @@ var ts; : { resolvedModule: undefined, failedLookupLocations: failedLookupLocations }; } ts.classicNameResolver = classicNameResolver; + function loadModuleFromAncestorDirectories(moduleName, containingDirectory, supportedExtensions, failedLookupLocations, state) { + while (true) { + var searchName = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName)); + var referencedSourceFile = loadModuleFromFile(searchName, supportedExtensions, failedLookupLocations, false, state); + if (referencedSourceFile) { + return referencedSourceFile; + } + var parentPath = ts.getDirectoryPath(containingDirectory); + if (parentPath === containingDirectory) { + return undefined; + } + containingDirectory = parentPath; + } + } })(ts || (ts = {})); var ts; (function (ts) { @@ -6242,6 +6309,36 @@ var ts; var result = ts.resolveModuleName(packageName, ts.combinePaths(cachePath, "index.d.ts"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, installTypingHost); return result.resolvedModule && result.resolvedModule.resolvedFileName; } + (function (PackageNameValidationResult) { + PackageNameValidationResult[PackageNameValidationResult["Ok"] = 0] = "Ok"; + PackageNameValidationResult[PackageNameValidationResult["ScopedPackagesNotSupported"] = 1] = "ScopedPackagesNotSupported"; + PackageNameValidationResult[PackageNameValidationResult["NameTooLong"] = 2] = "NameTooLong"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithDot"] = 3] = "NameStartsWithDot"; + PackageNameValidationResult[PackageNameValidationResult["NameStartsWithUnderscore"] = 4] = "NameStartsWithUnderscore"; + PackageNameValidationResult[PackageNameValidationResult["NameContainsNonURISafeCharacters"] = 5] = "NameContainsNonURISafeCharacters"; + })(typingsInstaller.PackageNameValidationResult || (typingsInstaller.PackageNameValidationResult = {})); + var PackageNameValidationResult = typingsInstaller.PackageNameValidationResult; + typingsInstaller.MaxPackageNameLength = 214; + function validatePackageName(packageName) { + ts.Debug.assert(!!packageName, "Package name is not specified"); + if (packageName.length > typingsInstaller.MaxPackageNameLength) { + return PackageNameValidationResult.NameTooLong; + } + if (packageName.charCodeAt(0) === 46) { + return PackageNameValidationResult.NameStartsWithDot; + } + if (packageName.charCodeAt(0) === 95) { + return PackageNameValidationResult.NameStartsWithUnderscore; + } + if (/^@[^/]+\/[^/]+$/.test(packageName)) { + return PackageNameValidationResult.ScopedPackagesNotSupported; + } + if (encodeURIComponent(packageName) !== packageName) { + return PackageNameValidationResult.NameContainsNonURISafeCharacters; + } + return PackageNameValidationResult.Ok; + } + typingsInstaller.validatePackageName = validatePackageName; typingsInstaller.NpmViewRequest = "npm view"; typingsInstaller.NpmInstallRequest = "npm install"; var TypingsInstaller = (function () { @@ -6364,15 +6461,54 @@ var ts; } this.knownCachesSet[cacheLocation] = true; }; + TypingsInstaller.prototype.filterTypings = function (typingsToInstall) { + if (typingsToInstall.length === 0) { + return typingsToInstall; + } + var result = []; + for (var _i = 0, typingsToInstall_1 = typingsToInstall; _i < typingsToInstall_1.length; _i++) { + var typing = typingsToInstall_1[_i]; + if (this.missingTypingsSet[typing]) { + continue; + } + var validationResult = validatePackageName(typing); + if (validationResult === PackageNameValidationResult.Ok) { + result.push(typing); + } + else { + this.missingTypingsSet[typing] = true; + if (this.log.isEnabled()) { + switch (validationResult) { + case PackageNameValidationResult.NameTooLong: + this.log.writeLine("Package name '" + typing + "' should be less than " + typingsInstaller.MaxPackageNameLength + " characters"); + break; + case PackageNameValidationResult.NameStartsWithDot: + this.log.writeLine("Package name '" + typing + "' cannot start with '.'"); + break; + case PackageNameValidationResult.NameStartsWithUnderscore: + this.log.writeLine("Package name '" + typing + "' cannot start with '_'"); + break; + case PackageNameValidationResult.ScopedPackagesNotSupported: + this.log.writeLine("Package '" + typing + "' is scoped and currently is not supported"); + break; + case PackageNameValidationResult.NameContainsNonURISafeCharacters: + this.log.writeLine("Package name '" + typing + "' contains non URI safe characters"); + break; + } + } + } + } + return result; + }; TypingsInstaller.prototype.installTypings = function (req, cachePath, currentlyCachedTypings, typingsToInstall) { var _this = this; if (this.log.isEnabled()) { this.log.writeLine("Installing typings " + JSON.stringify(typingsToInstall)); } - typingsToInstall = ts.filter(typingsToInstall, function (x) { return !_this.missingTypingsSet[x]; }); + typingsToInstall = this.filterTypings(typingsToInstall); if (typingsToInstall.length === 0) { if (this.log.isEnabled()) { - this.log.writeLine("All typings are known to be missing - no need to go any further"); + this.log.writeLine("All typings are known to be missing or invalid - no need to go any further"); } return; } @@ -6412,8 +6548,8 @@ var ts; if (_this.log.isEnabled()) { _this.log.writeLine("Installed typing files " + JSON.stringify(installedTypingFiles)); } - for (var _a = 0, typingsToInstall_1 = typingsToInstall; _a < typingsToInstall_1.length; _a++) { - var toInstall = typingsToInstall_1[_a]; + for (var _a = 0, typingsToInstall_2 = typingsToInstall; _a < typingsToInstall_2.length; _a++) { + var toInstall = typingsToInstall_2[_a]; if (!installedPackages[toInstall]) { if (_this.log.isEnabled()) { _this.log.writeLine("New missing typing package '" + toInstall + "'"); @@ -6429,8 +6565,8 @@ var ts; this.installRunCount++; var execInstallCmdCount = 0; var filteredTypings = []; - for (var _i = 0, typingsToInstall_2 = typingsToInstall; _i < typingsToInstall_2.length; _i++) { - var typing = typingsToInstall_2[_i]; + for (var _i = 0, typingsToInstall_3 = typingsToInstall; _i < typingsToInstall_3.length; _i++) { + var typing = typingsToInstall_3[_i]; execNpmViewTyping(this, typing); } function execNpmViewTyping(self, typing) { @@ -6553,13 +6689,14 @@ var ts; var NodeTypingsInstaller = (function (_super) { __extends(NodeTypingsInstaller, _super); function NodeTypingsInstaller(globalTypingsCacheLocation, throttleLimit, log) { - _super.call(this, globalTypingsCacheLocation, getNPMLocation(process.argv[0]), ts.toPath("typingSafeList.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), throttleLimit, log); - this.installTypingHost = ts.sys; - if (this.log.isEnabled()) { - this.log.writeLine("Process id: " + process.pid); + var _this = _super.call(this, globalTypingsCacheLocation, getNPMLocation(process.argv[0]), ts.toPath("typingSafeList.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), throttleLimit, log) || this; + _this.installTypingHost = ts.sys; + if (_this.log.isEnabled()) { + _this.log.writeLine("Process id: " + process.pid); } var exec = require("child_process").exec; - this.exec = exec; + _this.exec = exec; + return _this; } NodeTypingsInstaller.prototype.init = function () { var _this = this;