From 4c8b9796d904f87ffcc6e269f63380db7f2061cc Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Tue, 9 Jan 2018 13:09:15 -0800 Subject: [PATCH] Update LKG --- lib/enu/diagnosticMessages.generated.json.lcg | 62 +- lib/es/diagnosticMessages.generated.json | 2 +- lib/lib.d.ts | 135 +- lib/lib.dom.d.ts | 135 +- lib/lib.es2015.collection.d.ts | 8 +- lib/lib.es2015.core.d.ts | 5 +- lib/lib.es2016.full.d.ts | 135 +- lib/lib.es2017.full.d.ts | 135 +- lib/lib.es2017.object.d.ts | 4 +- lib/lib.es2018.d.ts | 2 +- lib/lib.es2018.full.d.ts | 136 +- lib/lib.es6.d.ts | 148 +- lib/lib.esnext.array.d.ts | 223 +++ lib/lib.esnext.d.ts | 1 + lib/lib.esnext.full.d.ts | 136 +- lib/lib.webworker.d.ts | 54 +- lib/protocol.d.ts | 12 + lib/tsc.js | 560 ++++-- lib/tsserver.js | 1312 +++++++++----- lib/tsserverlibrary.d.ts | 21 +- lib/tsserverlibrary.js | 1538 ++++++++++------- lib/typescript.d.ts | 9 +- lib/typescript.js | 1534 +++++++++------- lib/typescriptServices.d.ts | 9 +- lib/typescriptServices.js | 1534 +++++++++------- lib/typingsInstaller.js | 138 +- 26 files changed, 5332 insertions(+), 2656 deletions(-) create mode 100644 lib/lib.esnext.array.d.ts diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg index 1f3c74ec2a0..033c72ccc65 100644 --- a/lib/enu/diagnosticMessages.generated.json.lcg +++ b/lib/enu/diagnosticMessages.generated.json.lcg @@ -303,6 +303,12 @@ + + + + + + @@ -831,6 +837,18 @@ + + + + + + + + + + + + @@ -1191,6 +1209,24 @@ + + + + + + + + + + + + + + + + + + @@ -1875,6 +1911,12 @@ + + + + + + @@ -3603,6 +3645,12 @@ + + + + + + @@ -3837,6 +3885,12 @@ + + + + + + @@ -5181,6 +5235,12 @@ + + + + + + @@ -5513,7 +5573,7 @@ - + diff --git a/lib/es/diagnosticMessages.generated.json b/lib/es/diagnosticMessages.generated.json index 48518009502..351960fc67d 100644 --- a/lib/es/diagnosticMessages.generated.json +++ b/lib/es/diagnosticMessages.generated.json @@ -221,7 +221,7 @@ "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424": "La clase '{0}' define la función miembro de instancia como '{1}', pero la clase extendida '{2}' la define como propiedad de miembro de instancia.", "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425": "La clase '{0}' define la propiedad de miembro de instancia como '{1}', pero la clase extendida '{2}' la define como función miembro de instancia.", "Class_0_incorrectly_extends_base_class_1_2415": "La clase '{0}' extiende la clase base '{1}' de forma incorrecta.", - "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?", + "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720": "La clase \"{0}\" no implementa correctamente la clase \"{1}\". ¿Pretendía extender \"{1}\" y heredar sus miembros como una subclase?", "Class_0_incorrectly_implements_interface_1_2420": "La clase '{0}' implementa la interfaz '{1}' de forma incorrecta.", "Class_0_used_before_its_declaration_2449": "Se ha usado la clase \"{0}\" antes de declararla.", "Class_declarations_cannot_have_more_than_one_augments_or_extends_tag_8025": "Las declaraciones de clase no pueden tener más de una etiqueta \"@augments\" o \"@extends\".", diff --git a/lib/lib.d.ts b/lib/lib.d.ts index 0b7e46fb2d5..b3965fa0607 100644 --- a/lib/lib.d.ts +++ b/lib/lib.d.ts @@ -4879,7 +4879,7 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - applicationServerKey?: any; + applicationServerKey?: BufferSource | null; userVisibleOnly?: boolean; } @@ -4888,7 +4888,8 @@ interface RegistrationOptions { } interface RequestInit { - body?: any; + signal?: AbortSignal; + body?: Blob | BufferSource | FormData | string | null; cache?: RequestCache; credentials?: RequestCredentials; headers?: HeadersInit; @@ -5206,7 +5207,7 @@ interface RTCTransportStats extends RTCStats { } interface ScopedCredentialDescriptor { - id: any; + id: BufferSource; transports?: Transport[]; type: ScopedCredentialType; } @@ -7714,11 +7715,11 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNode(name: string): Attr; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; getAttributeNS(namespaceURI: string, localName: string): string; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: string): NodeListOf; @@ -7875,9 +7876,10 @@ declare var External: { }; interface File extends Blob { - readonly lastModifiedDate: any; + readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; + readonly lastModified: number; } declare var File: { @@ -9015,6 +9017,7 @@ interface HTMLFormElement extends HTMLElement { */ submit(): void; reportValidity(): boolean; + reportValidity(): boolean; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -9318,6 +9321,10 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; + /** + * Sets or retrives the content of the page that is to contain. + */ + srcdoc: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -9613,8 +9620,9 @@ interface HTMLInputElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start?: number, end?: number, direction?: string): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; /** * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. * @param n Value to decrement the value by. @@ -10175,6 +10183,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns whether an element will successfully validate based on forms validation rules and constraints. */ readonly willValidate: boolean; + typemustmatch: boolean; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -11076,8 +11085,9 @@ interface HTMLTextAreaElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start: number, end: number): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -11480,10 +11490,10 @@ declare var IntersectionObserver: { }; interface IntersectionObserverEntry { - readonly boundingClientRect: ClientRect; + readonly boundingClientRect: ClientRect | DOMRect; readonly intersectionRatio: number; - readonly intersectionRect: ClientRect; - readonly rootBounds: ClientRect; + readonly intersectionRect: ClientRect | DOMRect; + readonly rootBounds: ClientRect | DOMRect; readonly target: Element; readonly time: number; readonly isIntersecting: boolean; @@ -11652,7 +11662,7 @@ declare var MediaKeyMessageEvent: { interface MediaKeys { createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; + setServerCertificate(serverCertificate: BufferSource): Promise; } declare var MediaKeys: { @@ -11666,10 +11676,10 @@ interface MediaKeySession extends EventTarget { readonly keyStatuses: MediaKeyStatusMap; readonly sessionId: string; close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; + generateRequest(initDataType: string, initData: BufferSource): Promise; load(sessionId: string): Promise; remove(): Promise; - update(response: any): Promise; + update(response: BufferSource): Promise; } declare var MediaKeySession: { @@ -11680,8 +11690,8 @@ declare var MediaKeySession: { interface MediaKeyStatusMap { readonly size: number; forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; + get(keyId: BufferSource): MediaKeyStatus; + has(keyId: BufferSource): boolean; } declare var MediaKeyStatusMap: { @@ -13281,8 +13291,8 @@ interface Range { detach(): void; expand(Unit: ExpandGranularity): boolean; extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; insertNode(newNode: Node): void; selectNode(refNode: Node): void; selectNodeContents(refNode: Node): void; @@ -13345,6 +13355,7 @@ interface Request extends Object, Body { readonly referrerPolicy: ReferrerPolicy; readonly type: RequestType; readonly url: string; + readonly signal: AbortSignal; clone(): Request; } @@ -16331,7 +16342,7 @@ interface URL { declare var URL: { prototype: URL; - new(url: string, base?: string): URL; + new(url: string, base?: string | URL): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; }; @@ -16419,8 +16430,8 @@ declare var WaveShaperNode: { }; interface WebAuthentication { - getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: any, options?: ScopedCredentialOptions): Promise; + getAssertion(assertionChallenge: BufferSource, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: BufferSource, options?: ScopedCredentialOptions): Promise; } declare var WebAuthentication: { @@ -18775,6 +18786,23 @@ declare var HTMLSummaryElement: { new(): HTMLSummaryElement; }; +interface DOMRectReadOnly { + readonly bottom: number; + readonly height: number; + readonly left: number; + readonly right: number; + readonly top: number; + readonly width: number; + readonly x: number; + readonly y: number; +} + +declare var DOMRectReadOnly: { + prototype: DOMRectReadOnly; + new (x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly; + fromRect(rectangle?: DOMRectInit): DOMRectReadOnly; +}; + interface EXT_blend_minmax { readonly MIN_EXT: number; readonly MAX_EXT: number; @@ -18793,6 +18821,25 @@ interface EXT_sRGB { readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; } +interface DOMRect extends DOMRectReadOnly { + height: number; + width: number; + x: number; + y: number; +} + +declare var DOMRect: { + prototype: DOMRect; + new (x?: number, y?: number, width?: number, height?: number): DOMRect; + fromRect(rectangle?: DOMRectInit): DOMRect; +}; + +interface DOMRectList { + readonly length: number; + item(index: number): DOMRect | null; + [index: number]: DOMRect; +} + interface OES_vertex_array_object { readonly VERTEX_ARRAY_BINDING_OES: number; createVertexArrayOES(): WebGLVertexArrayObjectOES; @@ -18897,6 +18944,43 @@ interface WEBGL_lose_context { restoreContext(): void; } +interface AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: (ev: Event) => any; +} + +interface EventSource extends EventTarget { + readonly url: string; + readonly withCredentials: boolean; + readonly CONNECTING: number; + readonly OPEN: number; + readonly CLOSED: number; + readonly readyState: number; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -18909,7 +18993,7 @@ interface ErrorEventHandler { (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; } interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; + (keyId: BufferSource, status: MediaKeyStatus): void; } interface FrameRequestCallback { (time: number): void; @@ -19147,6 +19231,7 @@ interface SVGElementTagNameMap { "view": SVGViewElement; } +/** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } declare var Audio: { new(src?: string): HTMLAudioElement; }; @@ -19364,7 +19449,7 @@ declare function removeEventListener(type: K, li declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AAGUID = string; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = any; +type BodyInit = Blob | BufferSource | FormData | string; type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index 0c3292a3bbc..8e5af725a8e 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -781,7 +781,7 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - applicationServerKey?: any; + applicationServerKey?: BufferSource | null; userVisibleOnly?: boolean; } @@ -790,7 +790,8 @@ interface RegistrationOptions { } interface RequestInit { - body?: any; + signal?: AbortSignal; + body?: Blob | BufferSource | FormData | string | null; cache?: RequestCache; credentials?: RequestCredentials; headers?: HeadersInit; @@ -1108,7 +1109,7 @@ interface RTCTransportStats extends RTCStats { } interface ScopedCredentialDescriptor { - id: any; + id: BufferSource; transports?: Transport[]; type: ScopedCredentialType; } @@ -3616,11 +3617,11 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNode(name: string): Attr; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; getAttributeNS(namespaceURI: string, localName: string): string; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: string): NodeListOf; @@ -3777,9 +3778,10 @@ declare var External: { }; interface File extends Blob { - readonly lastModifiedDate: any; + readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; + readonly lastModified: number; } declare var File: { @@ -4917,6 +4919,7 @@ interface HTMLFormElement extends HTMLElement { */ submit(): void; reportValidity(): boolean; + reportValidity(): boolean; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5220,6 +5223,10 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; + /** + * Sets or retrives the content of the page that is to contain. + */ + srcdoc: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5515,8 +5522,9 @@ interface HTMLInputElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start?: number, end?: number, direction?: string): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; /** * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. * @param n Value to decrement the value by. @@ -6077,6 +6085,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns whether an element will successfully validate based on forms validation rules and constraints. */ readonly willValidate: boolean; + typemustmatch: boolean; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -6978,8 +6987,9 @@ interface HTMLTextAreaElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start: number, end: number): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -7382,10 +7392,10 @@ declare var IntersectionObserver: { }; interface IntersectionObserverEntry { - readonly boundingClientRect: ClientRect; + readonly boundingClientRect: ClientRect | DOMRect; readonly intersectionRatio: number; - readonly intersectionRect: ClientRect; - readonly rootBounds: ClientRect; + readonly intersectionRect: ClientRect | DOMRect; + readonly rootBounds: ClientRect | DOMRect; readonly target: Element; readonly time: number; readonly isIntersecting: boolean; @@ -7554,7 +7564,7 @@ declare var MediaKeyMessageEvent: { interface MediaKeys { createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; + setServerCertificate(serverCertificate: BufferSource): Promise; } declare var MediaKeys: { @@ -7568,10 +7578,10 @@ interface MediaKeySession extends EventTarget { readonly keyStatuses: MediaKeyStatusMap; readonly sessionId: string; close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; + generateRequest(initDataType: string, initData: BufferSource): Promise; load(sessionId: string): Promise; remove(): Promise; - update(response: any): Promise; + update(response: BufferSource): Promise; } declare var MediaKeySession: { @@ -7582,8 +7592,8 @@ declare var MediaKeySession: { interface MediaKeyStatusMap { readonly size: number; forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; + get(keyId: BufferSource): MediaKeyStatus; + has(keyId: BufferSource): boolean; } declare var MediaKeyStatusMap: { @@ -9183,8 +9193,8 @@ interface Range { detach(): void; expand(Unit: ExpandGranularity): boolean; extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; insertNode(newNode: Node): void; selectNode(refNode: Node): void; selectNodeContents(refNode: Node): void; @@ -9247,6 +9257,7 @@ interface Request extends Object, Body { readonly referrerPolicy: ReferrerPolicy; readonly type: RequestType; readonly url: string; + readonly signal: AbortSignal; clone(): Request; } @@ -12233,7 +12244,7 @@ interface URL { declare var URL: { prototype: URL; - new(url: string, base?: string): URL; + new(url: string, base?: string | URL): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; }; @@ -12321,8 +12332,8 @@ declare var WaveShaperNode: { }; interface WebAuthentication { - getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: any, options?: ScopedCredentialOptions): Promise; + getAssertion(assertionChallenge: BufferSource, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: BufferSource, options?: ScopedCredentialOptions): Promise; } declare var WebAuthentication: { @@ -14677,6 +14688,23 @@ declare var HTMLSummaryElement: { new(): HTMLSummaryElement; }; +interface DOMRectReadOnly { + readonly bottom: number; + readonly height: number; + readonly left: number; + readonly right: number; + readonly top: number; + readonly width: number; + readonly x: number; + readonly y: number; +} + +declare var DOMRectReadOnly: { + prototype: DOMRectReadOnly; + new (x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly; + fromRect(rectangle?: DOMRectInit): DOMRectReadOnly; +}; + interface EXT_blend_minmax { readonly MIN_EXT: number; readonly MAX_EXT: number; @@ -14695,6 +14723,25 @@ interface EXT_sRGB { readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; } +interface DOMRect extends DOMRectReadOnly { + height: number; + width: number; + x: number; + y: number; +} + +declare var DOMRect: { + prototype: DOMRect; + new (x?: number, y?: number, width?: number, height?: number): DOMRect; + fromRect(rectangle?: DOMRectInit): DOMRect; +}; + +interface DOMRectList { + readonly length: number; + item(index: number): DOMRect | null; + [index: number]: DOMRect; +} + interface OES_vertex_array_object { readonly VERTEX_ARRAY_BINDING_OES: number; createVertexArrayOES(): WebGLVertexArrayObjectOES; @@ -14799,6 +14846,43 @@ interface WEBGL_lose_context { restoreContext(): void; } +interface AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: (ev: Event) => any; +} + +interface EventSource extends EventTarget { + readonly url: string; + readonly withCredentials: boolean; + readonly CONNECTING: number; + readonly OPEN: number; + readonly CLOSED: number; + readonly readyState: number; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -14811,7 +14895,7 @@ interface ErrorEventHandler { (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; } interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; + (keyId: BufferSource, status: MediaKeyStatus): void; } interface FrameRequestCallback { (time: number): void; @@ -15049,6 +15133,7 @@ interface SVGElementTagNameMap { "view": SVGViewElement; } +/** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } declare var Audio: { new(src?: string): HTMLAudioElement; }; @@ -15266,7 +15351,7 @@ declare function removeEventListener(type: K, li declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AAGUID = string; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = any; +type BodyInit = Blob | BufferSource | FormData | string; type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; diff --git a/lib/lib.es2015.collection.d.ts b/lib/lib.es2015.collection.d.ts index 4d84af429be..33417297531 100644 --- a/lib/lib.es2015.collection.d.ts +++ b/lib/lib.es2015.collection.d.ts @@ -30,7 +30,7 @@ interface Map { interface MapConstructor { new (): Map; - new (entries?: [K, V][]): Map; + new (entries?: ReadonlyArray<[K, V]>): Map; readonly prototype: Map; } declare var Map: MapConstructor; @@ -51,7 +51,7 @@ interface WeakMap { interface WeakMapConstructor { new (): WeakMap; - new (entries?: [K, V][]): WeakMap; + new (entries?: ReadonlyArray<[K, V]>): WeakMap; readonly prototype: WeakMap; } declare var WeakMap: WeakMapConstructor; @@ -67,7 +67,7 @@ interface Set { interface SetConstructor { new (): Set; - new (values?: T[]): Set; + new (values?: ReadonlyArray): Set; readonly prototype: Set; } declare var Set: SetConstructor; @@ -86,7 +86,7 @@ interface WeakSet { interface WeakSetConstructor { new (): WeakSet; - new (values?: T[]): WeakSet; + new (values?: ReadonlyArray): WeakSet; readonly prototype: WeakSet; } declare var WeakSet: WeakSetConstructor; diff --git a/lib/lib.es2015.core.d.ts b/lib/lib.es2015.core.d.ts index f1734cedd8b..5e2788d2fd1 100644 --- a/lib/lib.es2015.core.d.ts +++ b/lib/lib.es2015.core.d.ts @@ -138,8 +138,9 @@ interface Math { log1p(x: number): number; /** - * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of - * the natural logarithms). + * Returns the result of (e^x - 1), which is an implementation-dependent approximation to + * subtracting 1 from the exponential function of x (e raised to the power of x, where e + * is the base of the natural logarithms). * @param x A numeric expression. */ expm1(x: number): number; diff --git a/lib/lib.es2016.full.d.ts b/lib/lib.es2016.full.d.ts index b8a7dae039d..d2ec81cecb5 100644 --- a/lib/lib.es2016.full.d.ts +++ b/lib/lib.es2016.full.d.ts @@ -784,7 +784,7 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - applicationServerKey?: any; + applicationServerKey?: BufferSource | null; userVisibleOnly?: boolean; } @@ -793,7 +793,8 @@ interface RegistrationOptions { } interface RequestInit { - body?: any; + signal?: AbortSignal; + body?: Blob | BufferSource | FormData | string | null; cache?: RequestCache; credentials?: RequestCredentials; headers?: HeadersInit; @@ -1111,7 +1112,7 @@ interface RTCTransportStats extends RTCStats { } interface ScopedCredentialDescriptor { - id: any; + id: BufferSource; transports?: Transport[]; type: ScopedCredentialType; } @@ -3619,11 +3620,11 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNode(name: string): Attr; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; getAttributeNS(namespaceURI: string, localName: string): string; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: string): NodeListOf; @@ -3780,9 +3781,10 @@ declare var External: { }; interface File extends Blob { - readonly lastModifiedDate: any; + readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; + readonly lastModified: number; } declare var File: { @@ -4920,6 +4922,7 @@ interface HTMLFormElement extends HTMLElement { */ submit(): void; reportValidity(): boolean; + reportValidity(): boolean; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5223,6 +5226,10 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; + /** + * Sets or retrives the content of the page that is to contain. + */ + srcdoc: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5518,8 +5525,9 @@ interface HTMLInputElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start?: number, end?: number, direction?: string): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; /** * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. * @param n Value to decrement the value by. @@ -6080,6 +6088,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns whether an element will successfully validate based on forms validation rules and constraints. */ readonly willValidate: boolean; + typemustmatch: boolean; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -6981,8 +6990,9 @@ interface HTMLTextAreaElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start: number, end: number): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -7385,10 +7395,10 @@ declare var IntersectionObserver: { }; interface IntersectionObserverEntry { - readonly boundingClientRect: ClientRect; + readonly boundingClientRect: ClientRect | DOMRect; readonly intersectionRatio: number; - readonly intersectionRect: ClientRect; - readonly rootBounds: ClientRect; + readonly intersectionRect: ClientRect | DOMRect; + readonly rootBounds: ClientRect | DOMRect; readonly target: Element; readonly time: number; readonly isIntersecting: boolean; @@ -7557,7 +7567,7 @@ declare var MediaKeyMessageEvent: { interface MediaKeys { createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; + setServerCertificate(serverCertificate: BufferSource): Promise; } declare var MediaKeys: { @@ -7571,10 +7581,10 @@ interface MediaKeySession extends EventTarget { readonly keyStatuses: MediaKeyStatusMap; readonly sessionId: string; close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; + generateRequest(initDataType: string, initData: BufferSource): Promise; load(sessionId: string): Promise; remove(): Promise; - update(response: any): Promise; + update(response: BufferSource): Promise; } declare var MediaKeySession: { @@ -7585,8 +7595,8 @@ declare var MediaKeySession: { interface MediaKeyStatusMap { readonly size: number; forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; + get(keyId: BufferSource): MediaKeyStatus; + has(keyId: BufferSource): boolean; } declare var MediaKeyStatusMap: { @@ -9186,8 +9196,8 @@ interface Range { detach(): void; expand(Unit: ExpandGranularity): boolean; extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; insertNode(newNode: Node): void; selectNode(refNode: Node): void; selectNodeContents(refNode: Node): void; @@ -9250,6 +9260,7 @@ interface Request extends Object, Body { readonly referrerPolicy: ReferrerPolicy; readonly type: RequestType; readonly url: string; + readonly signal: AbortSignal; clone(): Request; } @@ -12236,7 +12247,7 @@ interface URL { declare var URL: { prototype: URL; - new(url: string, base?: string): URL; + new(url: string, base?: string | URL): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; }; @@ -12324,8 +12335,8 @@ declare var WaveShaperNode: { }; interface WebAuthentication { - getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: any, options?: ScopedCredentialOptions): Promise; + getAssertion(assertionChallenge: BufferSource, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: BufferSource, options?: ScopedCredentialOptions): Promise; } declare var WebAuthentication: { @@ -14680,6 +14691,23 @@ declare var HTMLSummaryElement: { new(): HTMLSummaryElement; }; +interface DOMRectReadOnly { + readonly bottom: number; + readonly height: number; + readonly left: number; + readonly right: number; + readonly top: number; + readonly width: number; + readonly x: number; + readonly y: number; +} + +declare var DOMRectReadOnly: { + prototype: DOMRectReadOnly; + new (x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly; + fromRect(rectangle?: DOMRectInit): DOMRectReadOnly; +}; + interface EXT_blend_minmax { readonly MIN_EXT: number; readonly MAX_EXT: number; @@ -14698,6 +14726,25 @@ interface EXT_sRGB { readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; } +interface DOMRect extends DOMRectReadOnly { + height: number; + width: number; + x: number; + y: number; +} + +declare var DOMRect: { + prototype: DOMRect; + new (x?: number, y?: number, width?: number, height?: number): DOMRect; + fromRect(rectangle?: DOMRectInit): DOMRect; +}; + +interface DOMRectList { + readonly length: number; + item(index: number): DOMRect | null; + [index: number]: DOMRect; +} + interface OES_vertex_array_object { readonly VERTEX_ARRAY_BINDING_OES: number; createVertexArrayOES(): WebGLVertexArrayObjectOES; @@ -14802,6 +14849,43 @@ interface WEBGL_lose_context { restoreContext(): void; } +interface AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: (ev: Event) => any; +} + +interface EventSource extends EventTarget { + readonly url: string; + readonly withCredentials: boolean; + readonly CONNECTING: number; + readonly OPEN: number; + readonly CLOSED: number; + readonly readyState: number; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -14814,7 +14898,7 @@ interface ErrorEventHandler { (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; } interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; + (keyId: BufferSource, status: MediaKeyStatus): void; } interface FrameRequestCallback { (time: number): void; @@ -15052,6 +15136,7 @@ interface SVGElementTagNameMap { "view": SVGViewElement; } +/** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } declare var Audio: { new(src?: string): HTMLAudioElement; }; @@ -15269,7 +15354,7 @@ declare function removeEventListener(type: K, li declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AAGUID = string; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = any; +type BodyInit = Blob | BufferSource | FormData | string; type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; diff --git a/lib/lib.es2017.full.d.ts b/lib/lib.es2017.full.d.ts index 6e021331e37..896f46816b3 100644 --- a/lib/lib.es2017.full.d.ts +++ b/lib/lib.es2017.full.d.ts @@ -789,7 +789,7 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - applicationServerKey?: any; + applicationServerKey?: BufferSource | null; userVisibleOnly?: boolean; } @@ -798,7 +798,8 @@ interface RegistrationOptions { } interface RequestInit { - body?: any; + signal?: AbortSignal; + body?: Blob | BufferSource | FormData | string | null; cache?: RequestCache; credentials?: RequestCredentials; headers?: HeadersInit; @@ -1116,7 +1117,7 @@ interface RTCTransportStats extends RTCStats { } interface ScopedCredentialDescriptor { - id: any; + id: BufferSource; transports?: Transport[]; type: ScopedCredentialType; } @@ -3624,11 +3625,11 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNode(name: string): Attr; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; getAttributeNS(namespaceURI: string, localName: string): string; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: string): NodeListOf; @@ -3785,9 +3786,10 @@ declare var External: { }; interface File extends Blob { - readonly lastModifiedDate: any; + readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; + readonly lastModified: number; } declare var File: { @@ -4925,6 +4927,7 @@ interface HTMLFormElement extends HTMLElement { */ submit(): void; reportValidity(): boolean; + reportValidity(): boolean; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5228,6 +5231,10 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; + /** + * Sets or retrives the content of the page that is to contain. + */ + srcdoc: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5523,8 +5530,9 @@ interface HTMLInputElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start?: number, end?: number, direction?: string): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; /** * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. * @param n Value to decrement the value by. @@ -6085,6 +6093,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns whether an element will successfully validate based on forms validation rules and constraints. */ readonly willValidate: boolean; + typemustmatch: boolean; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -6986,8 +6995,9 @@ interface HTMLTextAreaElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start: number, end: number): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -7390,10 +7400,10 @@ declare var IntersectionObserver: { }; interface IntersectionObserverEntry { - readonly boundingClientRect: ClientRect; + readonly boundingClientRect: ClientRect | DOMRect; readonly intersectionRatio: number; - readonly intersectionRect: ClientRect; - readonly rootBounds: ClientRect; + readonly intersectionRect: ClientRect | DOMRect; + readonly rootBounds: ClientRect | DOMRect; readonly target: Element; readonly time: number; readonly isIntersecting: boolean; @@ -7562,7 +7572,7 @@ declare var MediaKeyMessageEvent: { interface MediaKeys { createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; + setServerCertificate(serverCertificate: BufferSource): Promise; } declare var MediaKeys: { @@ -7576,10 +7586,10 @@ interface MediaKeySession extends EventTarget { readonly keyStatuses: MediaKeyStatusMap; readonly sessionId: string; close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; + generateRequest(initDataType: string, initData: BufferSource): Promise; load(sessionId: string): Promise; remove(): Promise; - update(response: any): Promise; + update(response: BufferSource): Promise; } declare var MediaKeySession: { @@ -7590,8 +7600,8 @@ declare var MediaKeySession: { interface MediaKeyStatusMap { readonly size: number; forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; + get(keyId: BufferSource): MediaKeyStatus; + has(keyId: BufferSource): boolean; } declare var MediaKeyStatusMap: { @@ -9191,8 +9201,8 @@ interface Range { detach(): void; expand(Unit: ExpandGranularity): boolean; extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; insertNode(newNode: Node): void; selectNode(refNode: Node): void; selectNodeContents(refNode: Node): void; @@ -9255,6 +9265,7 @@ interface Request extends Object, Body { readonly referrerPolicy: ReferrerPolicy; readonly type: RequestType; readonly url: string; + readonly signal: AbortSignal; clone(): Request; } @@ -12241,7 +12252,7 @@ interface URL { declare var URL: { prototype: URL; - new(url: string, base?: string): URL; + new(url: string, base?: string | URL): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; }; @@ -12329,8 +12340,8 @@ declare var WaveShaperNode: { }; interface WebAuthentication { - getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: any, options?: ScopedCredentialOptions): Promise; + getAssertion(assertionChallenge: BufferSource, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: BufferSource, options?: ScopedCredentialOptions): Promise; } declare var WebAuthentication: { @@ -14685,6 +14696,23 @@ declare var HTMLSummaryElement: { new(): HTMLSummaryElement; }; +interface DOMRectReadOnly { + readonly bottom: number; + readonly height: number; + readonly left: number; + readonly right: number; + readonly top: number; + readonly width: number; + readonly x: number; + readonly y: number; +} + +declare var DOMRectReadOnly: { + prototype: DOMRectReadOnly; + new (x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly; + fromRect(rectangle?: DOMRectInit): DOMRectReadOnly; +}; + interface EXT_blend_minmax { readonly MIN_EXT: number; readonly MAX_EXT: number; @@ -14703,6 +14731,25 @@ interface EXT_sRGB { readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; } +interface DOMRect extends DOMRectReadOnly { + height: number; + width: number; + x: number; + y: number; +} + +declare var DOMRect: { + prototype: DOMRect; + new (x?: number, y?: number, width?: number, height?: number): DOMRect; + fromRect(rectangle?: DOMRectInit): DOMRect; +}; + +interface DOMRectList { + readonly length: number; + item(index: number): DOMRect | null; + [index: number]: DOMRect; +} + interface OES_vertex_array_object { readonly VERTEX_ARRAY_BINDING_OES: number; createVertexArrayOES(): WebGLVertexArrayObjectOES; @@ -14807,6 +14854,43 @@ interface WEBGL_lose_context { restoreContext(): void; } +interface AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: (ev: Event) => any; +} + +interface EventSource extends EventTarget { + readonly url: string; + readonly withCredentials: boolean; + readonly CONNECTING: number; + readonly OPEN: number; + readonly CLOSED: number; + readonly readyState: number; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -14819,7 +14903,7 @@ interface ErrorEventHandler { (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; } interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; + (keyId: BufferSource, status: MediaKeyStatus): void; } interface FrameRequestCallback { (time: number): void; @@ -15057,6 +15141,7 @@ interface SVGElementTagNameMap { "view": SVGViewElement; } +/** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } declare var Audio: { new(src?: string): HTMLAudioElement; }; @@ -15274,7 +15359,7 @@ declare function removeEventListener(type: K, li declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AAGUID = string; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = any; +type BodyInit = Blob | BufferSource | FormData | string; type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; diff --git a/lib/lib.es2017.object.d.ts b/lib/lib.es2017.object.d.ts index c0f782464ff..a806ae2bf05 100644 --- a/lib/lib.es2017.object.d.ts +++ b/lib/lib.es2017.object.d.ts @@ -29,7 +29,7 @@ interface ObjectConstructor { * Returns an array of values of the enumerable properties of an object * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - values(o: any): any[]; + values(o: {}): any[]; /** * Returns an array of key/values of the enumerable properties of an object @@ -41,7 +41,7 @@ interface ObjectConstructor { * Returns an array of key/values of the enumerable properties of an object * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - entries(o: any): [string, any][]; + entries(o: {}): [string, any][]; /** * Returns an object containing all own property descriptors of an object diff --git a/lib/lib.es2018.d.ts b/lib/lib.es2018.d.ts index c7ea194ecfd..820467445eb 100644 --- a/lib/lib.es2018.d.ts +++ b/lib/lib.es2018.d.ts @@ -18,4 +18,4 @@ and limitations under the License. /// -/// \ No newline at end of file +/// diff --git a/lib/lib.es2018.full.d.ts b/lib/lib.es2018.full.d.ts index 5333251034a..98b003616db 100644 --- a/lib/lib.es2018.full.d.ts +++ b/lib/lib.es2018.full.d.ts @@ -21,6 +21,7 @@ and limitations under the License. /// + ///////////////////////////// /// DOM APIs ///////////////////////////// @@ -783,7 +784,7 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - applicationServerKey?: any; + applicationServerKey?: BufferSource | null; userVisibleOnly?: boolean; } @@ -792,7 +793,8 @@ interface RegistrationOptions { } interface RequestInit { - body?: any; + signal?: AbortSignal; + body?: Blob | BufferSource | FormData | string | null; cache?: RequestCache; credentials?: RequestCredentials; headers?: HeadersInit; @@ -1110,7 +1112,7 @@ interface RTCTransportStats extends RTCStats { } interface ScopedCredentialDescriptor { - id: any; + id: BufferSource; transports?: Transport[]; type: ScopedCredentialType; } @@ -3618,11 +3620,11 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNode(name: string): Attr; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; getAttributeNS(namespaceURI: string, localName: string): string; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: string): NodeListOf; @@ -3779,9 +3781,10 @@ declare var External: { }; interface File extends Blob { - readonly lastModifiedDate: any; + readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; + readonly lastModified: number; } declare var File: { @@ -4919,6 +4922,7 @@ interface HTMLFormElement extends HTMLElement { */ submit(): void; reportValidity(): boolean; + reportValidity(): boolean; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5222,6 +5226,10 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; + /** + * Sets or retrives the content of the page that is to contain. + */ + srcdoc: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5517,8 +5525,9 @@ interface HTMLInputElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start?: number, end?: number, direction?: string): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; /** * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. * @param n Value to decrement the value by. @@ -6079,6 +6088,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns whether an element will successfully validate based on forms validation rules and constraints. */ readonly willValidate: boolean; + typemustmatch: boolean; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -6980,8 +6990,9 @@ interface HTMLTextAreaElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start: number, end: number): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -7384,10 +7395,10 @@ declare var IntersectionObserver: { }; interface IntersectionObserverEntry { - readonly boundingClientRect: ClientRect; + readonly boundingClientRect: ClientRect | DOMRect; readonly intersectionRatio: number; - readonly intersectionRect: ClientRect; - readonly rootBounds: ClientRect; + readonly intersectionRect: ClientRect | DOMRect; + readonly rootBounds: ClientRect | DOMRect; readonly target: Element; readonly time: number; readonly isIntersecting: boolean; @@ -7556,7 +7567,7 @@ declare var MediaKeyMessageEvent: { interface MediaKeys { createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; + setServerCertificate(serverCertificate: BufferSource): Promise; } declare var MediaKeys: { @@ -7570,10 +7581,10 @@ interface MediaKeySession extends EventTarget { readonly keyStatuses: MediaKeyStatusMap; readonly sessionId: string; close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; + generateRequest(initDataType: string, initData: BufferSource): Promise; load(sessionId: string): Promise; remove(): Promise; - update(response: any): Promise; + update(response: BufferSource): Promise; } declare var MediaKeySession: { @@ -7584,8 +7595,8 @@ declare var MediaKeySession: { interface MediaKeyStatusMap { readonly size: number; forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; + get(keyId: BufferSource): MediaKeyStatus; + has(keyId: BufferSource): boolean; } declare var MediaKeyStatusMap: { @@ -9185,8 +9196,8 @@ interface Range { detach(): void; expand(Unit: ExpandGranularity): boolean; extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; insertNode(newNode: Node): void; selectNode(refNode: Node): void; selectNodeContents(refNode: Node): void; @@ -9249,6 +9260,7 @@ interface Request extends Object, Body { readonly referrerPolicy: ReferrerPolicy; readonly type: RequestType; readonly url: string; + readonly signal: AbortSignal; clone(): Request; } @@ -12235,7 +12247,7 @@ interface URL { declare var URL: { prototype: URL; - new(url: string, base?: string): URL; + new(url: string, base?: string | URL): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; }; @@ -12323,8 +12335,8 @@ declare var WaveShaperNode: { }; interface WebAuthentication { - getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: any, options?: ScopedCredentialOptions): Promise; + getAssertion(assertionChallenge: BufferSource, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: BufferSource, options?: ScopedCredentialOptions): Promise; } declare var WebAuthentication: { @@ -14679,6 +14691,23 @@ declare var HTMLSummaryElement: { new(): HTMLSummaryElement; }; +interface DOMRectReadOnly { + readonly bottom: number; + readonly height: number; + readonly left: number; + readonly right: number; + readonly top: number; + readonly width: number; + readonly x: number; + readonly y: number; +} + +declare var DOMRectReadOnly: { + prototype: DOMRectReadOnly; + new (x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly; + fromRect(rectangle?: DOMRectInit): DOMRectReadOnly; +}; + interface EXT_blend_minmax { readonly MIN_EXT: number; readonly MAX_EXT: number; @@ -14697,6 +14726,25 @@ interface EXT_sRGB { readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; } +interface DOMRect extends DOMRectReadOnly { + height: number; + width: number; + x: number; + y: number; +} + +declare var DOMRect: { + prototype: DOMRect; + new (x?: number, y?: number, width?: number, height?: number): DOMRect; + fromRect(rectangle?: DOMRectInit): DOMRect; +}; + +interface DOMRectList { + readonly length: number; + item(index: number): DOMRect | null; + [index: number]: DOMRect; +} + interface OES_vertex_array_object { readonly VERTEX_ARRAY_BINDING_OES: number; createVertexArrayOES(): WebGLVertexArrayObjectOES; @@ -14801,6 +14849,43 @@ interface WEBGL_lose_context { restoreContext(): void; } +interface AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: (ev: Event) => any; +} + +interface EventSource extends EventTarget { + readonly url: string; + readonly withCredentials: boolean; + readonly CONNECTING: number; + readonly OPEN: number; + readonly CLOSED: number; + readonly readyState: number; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -14813,7 +14898,7 @@ interface ErrorEventHandler { (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; } interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; + (keyId: BufferSource, status: MediaKeyStatus): void; } interface FrameRequestCallback { (time: number): void; @@ -15051,6 +15136,7 @@ interface SVGElementTagNameMap { "view": SVGViewElement; } +/** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } declare var Audio: { new(src?: string): HTMLAudioElement; }; @@ -15268,7 +15354,7 @@ declare function removeEventListener(type: K, li declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AAGUID = string; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = any; +type BodyInit = Blob | BufferSource | FormData | string; type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; diff --git a/lib/lib.es6.d.ts b/lib/lib.es6.d.ts index 16703d62591..3751aaebc69 100644 --- a/lib/lib.es6.d.ts +++ b/lib/lib.es6.d.ts @@ -4236,8 +4236,9 @@ interface Math { log1p(x: number): number; /** - * Returns the result of (e^x - 1) of x (e raised to the power of x, where e is the base of - * the natural logarithms). + * Returns the result of (e^x - 1), which is an implementation-dependent approximation to + * subtracting 1 from the exponential function of x (e raised to the power of x, where e + * is the base of the natural logarithms). * @param x A numeric expression. */ expm1(x: number): number; @@ -4655,7 +4656,7 @@ interface Map { interface MapConstructor { new (): Map; - new (entries?: [K, V][]): Map; + new (entries?: ReadonlyArray<[K, V]>): Map; readonly prototype: Map; } declare var Map: MapConstructor; @@ -4676,7 +4677,7 @@ interface WeakMap { interface WeakMapConstructor { new (): WeakMap; - new (entries?: [K, V][]): WeakMap; + new (entries?: ReadonlyArray<[K, V]>): WeakMap; readonly prototype: WeakMap; } declare var WeakMap: WeakMapConstructor; @@ -4692,7 +4693,7 @@ interface Set { interface SetConstructor { new (): Set; - new (values?: T[]): Set; + new (values?: ReadonlyArray): Set; readonly prototype: Set; } declare var Set: SetConstructor; @@ -4711,7 +4712,7 @@ interface WeakSet { interface WeakSetConstructor { new (): WeakSet; - new (values?: T[]): WeakSet; + new (values?: ReadonlyArray): WeakSet; readonly prototype: WeakSet; } declare var WeakSet: WeakSetConstructor; @@ -6590,7 +6591,7 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - applicationServerKey?: any; + applicationServerKey?: BufferSource | null; userVisibleOnly?: boolean; } @@ -6599,7 +6600,8 @@ interface RegistrationOptions { } interface RequestInit { - body?: any; + signal?: AbortSignal; + body?: Blob | BufferSource | FormData | string | null; cache?: RequestCache; credentials?: RequestCredentials; headers?: HeadersInit; @@ -6917,7 +6919,7 @@ interface RTCTransportStats extends RTCStats { } interface ScopedCredentialDescriptor { - id: any; + id: BufferSource; transports?: Transport[]; type: ScopedCredentialType; } @@ -9425,11 +9427,11 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNode(name: string): Attr; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; getAttributeNS(namespaceURI: string, localName: string): string; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: string): NodeListOf; @@ -9586,9 +9588,10 @@ declare var External: { }; interface File extends Blob { - readonly lastModifiedDate: any; + readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; + readonly lastModified: number; } declare var File: { @@ -10726,6 +10729,7 @@ interface HTMLFormElement extends HTMLElement { */ submit(): void; reportValidity(): boolean; + reportValidity(): boolean; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -11029,6 +11033,10 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; + /** + * Sets or retrives the content of the page that is to contain. + */ + srcdoc: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -11324,8 +11332,9 @@ interface HTMLInputElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start?: number, end?: number, direction?: string): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; /** * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. * @param n Value to decrement the value by. @@ -11886,6 +11895,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns whether an element will successfully validate based on forms validation rules and constraints. */ readonly willValidate: boolean; + typemustmatch: boolean; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -12787,8 +12797,9 @@ interface HTMLTextAreaElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start: number, end: number): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -13191,10 +13202,10 @@ declare var IntersectionObserver: { }; interface IntersectionObserverEntry { - readonly boundingClientRect: ClientRect; + readonly boundingClientRect: ClientRect | DOMRect; readonly intersectionRatio: number; - readonly intersectionRect: ClientRect; - readonly rootBounds: ClientRect; + readonly intersectionRect: ClientRect | DOMRect; + readonly rootBounds: ClientRect | DOMRect; readonly target: Element; readonly time: number; readonly isIntersecting: boolean; @@ -13363,7 +13374,7 @@ declare var MediaKeyMessageEvent: { interface MediaKeys { createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; + setServerCertificate(serverCertificate: BufferSource): Promise; } declare var MediaKeys: { @@ -13377,10 +13388,10 @@ interface MediaKeySession extends EventTarget { readonly keyStatuses: MediaKeyStatusMap; readonly sessionId: string; close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; + generateRequest(initDataType: string, initData: BufferSource): Promise; load(sessionId: string): Promise; remove(): Promise; - update(response: any): Promise; + update(response: BufferSource): Promise; } declare var MediaKeySession: { @@ -13391,8 +13402,8 @@ declare var MediaKeySession: { interface MediaKeyStatusMap { readonly size: number; forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; + get(keyId: BufferSource): MediaKeyStatus; + has(keyId: BufferSource): boolean; } declare var MediaKeyStatusMap: { @@ -14992,8 +15003,8 @@ interface Range { detach(): void; expand(Unit: ExpandGranularity): boolean; extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; insertNode(newNode: Node): void; selectNode(refNode: Node): void; selectNodeContents(refNode: Node): void; @@ -15056,6 +15067,7 @@ interface Request extends Object, Body { readonly referrerPolicy: ReferrerPolicy; readonly type: RequestType; readonly url: string; + readonly signal: AbortSignal; clone(): Request; } @@ -18042,7 +18054,7 @@ interface URL { declare var URL: { prototype: URL; - new(url: string, base?: string): URL; + new(url: string, base?: string | URL): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; }; @@ -18130,8 +18142,8 @@ declare var WaveShaperNode: { }; interface WebAuthentication { - getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: any, options?: ScopedCredentialOptions): Promise; + getAssertion(assertionChallenge: BufferSource, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: BufferSource, options?: ScopedCredentialOptions): Promise; } declare var WebAuthentication: { @@ -20486,6 +20498,23 @@ declare var HTMLSummaryElement: { new(): HTMLSummaryElement; }; +interface DOMRectReadOnly { + readonly bottom: number; + readonly height: number; + readonly left: number; + readonly right: number; + readonly top: number; + readonly width: number; + readonly x: number; + readonly y: number; +} + +declare var DOMRectReadOnly: { + prototype: DOMRectReadOnly; + new (x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly; + fromRect(rectangle?: DOMRectInit): DOMRectReadOnly; +}; + interface EXT_blend_minmax { readonly MIN_EXT: number; readonly MAX_EXT: number; @@ -20504,6 +20533,25 @@ interface EXT_sRGB { readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; } +interface DOMRect extends DOMRectReadOnly { + height: number; + width: number; + x: number; + y: number; +} + +declare var DOMRect: { + prototype: DOMRect; + new (x?: number, y?: number, width?: number, height?: number): DOMRect; + fromRect(rectangle?: DOMRectInit): DOMRect; +}; + +interface DOMRectList { + readonly length: number; + item(index: number): DOMRect | null; + [index: number]: DOMRect; +} + interface OES_vertex_array_object { readonly VERTEX_ARRAY_BINDING_OES: number; createVertexArrayOES(): WebGLVertexArrayObjectOES; @@ -20608,6 +20656,43 @@ interface WEBGL_lose_context { restoreContext(): void; } +interface AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: (ev: Event) => any; +} + +interface EventSource extends EventTarget { + readonly url: string; + readonly withCredentials: boolean; + readonly CONNECTING: number; + readonly OPEN: number; + readonly CLOSED: number; + readonly readyState: number; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -20620,7 +20705,7 @@ interface ErrorEventHandler { (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; } interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; + (keyId: BufferSource, status: MediaKeyStatus): void; } interface FrameRequestCallback { (time: number): void; @@ -20858,6 +20943,7 @@ interface SVGElementTagNameMap { "view": SVGViewElement; } +/** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } declare var Audio: { new(src?: string): HTMLAudioElement; }; @@ -21075,7 +21161,7 @@ declare function removeEventListener(type: K, li declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AAGUID = string; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = any; +type BodyInit = Blob | BufferSource | FormData | string; type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; diff --git a/lib/lib.esnext.array.d.ts b/lib/lib.esnext.array.d.ts new file mode 100644 index 00000000000..ce26358d3d6 --- /dev/null +++ b/lib/lib.esnext.array.d.ts @@ -0,0 +1,223 @@ +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. All rights reserved. +Licensed under the Apache License, Version 2.0 (the "License"); you may not use +this file except in compliance with the License. You may obtain a copy of the +License at http://www.apache.org/licenses/LICENSE-2.0 + +THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED +WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, +MERCHANTABLITY OR NON-INFRINGEMENT. + +See the Apache Version 2.0 License for specific language governing permissions +and limitations under the License. +***************************************************************************** */ + + + +/// + + +interface ReadonlyArray { + + /** + * Calls a defined callback function on each element of an array. Then, flattens the result into + * a new array. + * This is identical to a map followed by a flatten of depth 1. + * + * @param callback A function that accepts up to three arguments. The flatMap method calls the + * callback function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callback function. If + * thisArg is omitted, undefined is used as the this value. + */ + flatMap ( + callback: (this: This, value: T, index: number, array: T[]) => U|U[], + thisArg?: This + ): U[] + + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: + ReadonlyArray | + + ReadonlyArray> | + ReadonlyArray[]> | + ReadonlyArray[][]> | + ReadonlyArray[][][]> | + + ReadonlyArray>> | + ReadonlyArray[][]>> | + ReadonlyArray>[][]> | + ReadonlyArray[]>[]> | + ReadonlyArray>[]> | + ReadonlyArray[]>> | + + ReadonlyArray>>> | + ReadonlyArray[]>>> | + ReadonlyArray>[]>> | + ReadonlyArray>>[]> | + + ReadonlyArray>>>>, + depth: 4): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: + ReadonlyArray | + + ReadonlyArray[][]> | + ReadonlyArray[]> | + ReadonlyArray> | + + ReadonlyArray>> | + ReadonlyArray[]>> | + ReadonlyArray>[]> | + + ReadonlyArray>>>, + depth: 3): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: + ReadonlyArray | + + ReadonlyArray> | + ReadonlyArray[]> | + + ReadonlyArray>>, + depth: 2): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: + ReadonlyArray | + ReadonlyArray>, + depth?: 1 + ): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: + ReadonlyArray, + depth: 0 + ): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. If no depth is provided, flatten method defaults to the depth of 1. + * + * @param depth The maximum recursion depth + */ + flatten(depth?: number): any[]; + } + +interface Array { + + /** + * Calls a defined callback function on each element of an array. Then, flattens the result into + * a new array. + * This is identical to a map followed by a flatten of depth 1. + * + * @param callback A function that accepts up to three arguments. The flatMap method calls the + * callback function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callback function. If + * thisArg is omitted, undefined is used as the this value. + */ + flatMap ( + callback: (this: This, value: T, index: number, array: T[]) => U|U[], + thisArg?: This + ): U[] + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[][][][][][][][], depth: 7): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[][][][][][][], depth: 6): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[][][][][][], depth: 5): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[][][][][], depth: 4): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[][][][], depth: 3): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[][][], depth: 2): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[][], depth?: 1): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. + * + * @param depth The maximum recursion depth + */ + flatten(this: U[], depth: 0): U[]; + + /** + * Returns a new array with all sub-array elements concatenated into it recursively up to the + * specified depth. If no depth is provided, flatten method defaults to the depth of 1. + * + * @param depth The maximum recursion depth + */ + flatten(depth?: number): any[]; +} diff --git a/lib/lib.esnext.d.ts b/lib/lib.esnext.d.ts index d3936e062c6..0947f078418 100644 --- a/lib/lib.esnext.d.ts +++ b/lib/lib.esnext.d.ts @@ -20,4 +20,5 @@ and limitations under the License. /// /// +/// /// diff --git a/lib/lib.esnext.full.d.ts b/lib/lib.esnext.full.d.ts index 58aff2f48be..4e822ccab78 100644 --- a/lib/lib.esnext.full.d.ts +++ b/lib/lib.esnext.full.d.ts @@ -20,6 +20,7 @@ and limitations under the License. /// /// +/// /// @@ -786,7 +787,7 @@ interface ProgressEventInit extends EventInit { } interface PushSubscriptionOptionsInit { - applicationServerKey?: any; + applicationServerKey?: BufferSource | null; userVisibleOnly?: boolean; } @@ -795,7 +796,8 @@ interface RegistrationOptions { } interface RequestInit { - body?: any; + signal?: AbortSignal; + body?: Blob | BufferSource | FormData | string | null; cache?: RequestCache; credentials?: RequestCredentials; headers?: HeadersInit; @@ -1113,7 +1115,7 @@ interface RTCTransportStats extends RTCStats { } interface ScopedCredentialDescriptor { - id: any; + id: BufferSource; transports?: Transport[]; type: ScopedCredentialType; } @@ -3621,11 +3623,11 @@ interface Element extends Node, GlobalEventHandlers, ElementTraversal, NodeSelec slot: string; readonly shadowRoot: ShadowRoot | null; getAttribute(name: string): string | null; - getAttributeNode(name: string): Attr; - getAttributeNodeNS(namespaceURI: string, localName: string): Attr; + getAttributeNode(name: string): Attr | null; + getAttributeNodeNS(namespaceURI: string, localName: string): Attr | null; getAttributeNS(namespaceURI: string, localName: string): string; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: K): NodeListOf; getElementsByTagName(name: string): NodeListOf; @@ -3782,9 +3784,10 @@ declare var External: { }; interface File extends Blob { - readonly lastModifiedDate: any; + readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; + readonly lastModified: number; } declare var File: { @@ -4922,6 +4925,7 @@ interface HTMLFormElement extends HTMLElement { */ submit(): void; reportValidity(): boolean; + reportValidity(): boolean; addEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLFormElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5225,6 +5229,10 @@ interface HTMLIFrameElement extends HTMLElement, GetSVGDocument { * Sets or retrieves the width of the object. */ width: string; + /** + * Sets or retrives the content of the page that is to contain. + */ + srcdoc: string; addEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLIFrameElement, ev: HTMLIFrameElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -5520,8 +5528,9 @@ interface HTMLInputElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start?: number, end?: number, direction?: string): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; /** * Decrements a range input control's value by the value given by the Step attribute. If the optional parameter is used, it will decrement the input control's step value multiplied by the parameter's value. * @param n Value to decrement the value by. @@ -6082,6 +6091,7 @@ interface HTMLObjectElement extends HTMLElement, GetSVGDocument { * Returns whether an element will successfully validate based on forms validation rules and constraints. */ readonly willValidate: boolean; + typemustmatch: boolean; /** * Returns whether a form will validate when it is submitted, without having to submit it. */ @@ -6983,8 +6993,9 @@ interface HTMLTextAreaElement extends HTMLElement { * Sets the start and end positions of a selection in a text field. * @param start The offset into the text field for the start of the selection. * @param end The offset into the text field for the end of the selection. + * @param direction The direction in which the selection is performed. */ - setSelectionRange(start: number, end: number): void; + setSelectionRange(start: number, end: number, direction?: "forward" | "backward" | "none"): void; addEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: HTMLTextAreaElement, ev: HTMLElementEventMap[K]) => any, options?: boolean | EventListenerOptions): void; @@ -7387,10 +7398,10 @@ declare var IntersectionObserver: { }; interface IntersectionObserverEntry { - readonly boundingClientRect: ClientRect; + readonly boundingClientRect: ClientRect | DOMRect; readonly intersectionRatio: number; - readonly intersectionRect: ClientRect; - readonly rootBounds: ClientRect; + readonly intersectionRect: ClientRect | DOMRect; + readonly rootBounds: ClientRect | DOMRect; readonly target: Element; readonly time: number; readonly isIntersecting: boolean; @@ -7559,7 +7570,7 @@ declare var MediaKeyMessageEvent: { interface MediaKeys { createSession(sessionType?: MediaKeySessionType): MediaKeySession; - setServerCertificate(serverCertificate: any): Promise; + setServerCertificate(serverCertificate: BufferSource): Promise; } declare var MediaKeys: { @@ -7573,10 +7584,10 @@ interface MediaKeySession extends EventTarget { readonly keyStatuses: MediaKeyStatusMap; readonly sessionId: string; close(): Promise; - generateRequest(initDataType: string, initData: any): Promise; + generateRequest(initDataType: string, initData: BufferSource): Promise; load(sessionId: string): Promise; remove(): Promise; - update(response: any): Promise; + update(response: BufferSource): Promise; } declare var MediaKeySession: { @@ -7587,8 +7598,8 @@ declare var MediaKeySession: { interface MediaKeyStatusMap { readonly size: number; forEach(callback: ForEachCallback): void; - get(keyId: any): MediaKeyStatus; - has(keyId: any): boolean; + get(keyId: BufferSource): MediaKeyStatus; + has(keyId: BufferSource): boolean; } declare var MediaKeyStatusMap: { @@ -9188,8 +9199,8 @@ interface Range { detach(): void; expand(Unit: ExpandGranularity): boolean; extractContents(): DocumentFragment; - getBoundingClientRect(): ClientRect; - getClientRects(): ClientRectList; + getBoundingClientRect(): ClientRect | DOMRect; + getClientRects(): ClientRectList | DOMRectList; insertNode(newNode: Node): void; selectNode(refNode: Node): void; selectNodeContents(refNode: Node): void; @@ -9252,6 +9263,7 @@ interface Request extends Object, Body { readonly referrerPolicy: ReferrerPolicy; readonly type: RequestType; readonly url: string; + readonly signal: AbortSignal; clone(): Request; } @@ -12238,7 +12250,7 @@ interface URL { declare var URL: { prototype: URL; - new(url: string, base?: string): URL; + new(url: string, base?: string | URL): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; }; @@ -12326,8 +12338,8 @@ declare var WaveShaperNode: { }; interface WebAuthentication { - getAssertion(assertionChallenge: any, options?: AssertionOptions): Promise; - makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: any, options?: ScopedCredentialOptions): Promise; + getAssertion(assertionChallenge: BufferSource, options?: AssertionOptions): Promise; + makeCredential(accountInformation: Account, cryptoParameters: ScopedCredentialParameters[], attestationChallenge: BufferSource, options?: ScopedCredentialOptions): Promise; } declare var WebAuthentication: { @@ -14682,6 +14694,23 @@ declare var HTMLSummaryElement: { new(): HTMLSummaryElement; }; +interface DOMRectReadOnly { + readonly bottom: number; + readonly height: number; + readonly left: number; + readonly right: number; + readonly top: number; + readonly width: number; + readonly x: number; + readonly y: number; +} + +declare var DOMRectReadOnly: { + prototype: DOMRectReadOnly; + new (x?: number, y?: number, width?: number, height?: number): DOMRectReadOnly; + fromRect(rectangle?: DOMRectInit): DOMRectReadOnly; +}; + interface EXT_blend_minmax { readonly MIN_EXT: number; readonly MAX_EXT: number; @@ -14700,6 +14729,25 @@ interface EXT_sRGB { readonly FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT: number; } +interface DOMRect extends DOMRectReadOnly { + height: number; + width: number; + x: number; + y: number; +} + +declare var DOMRect: { + prototype: DOMRect; + new (x?: number, y?: number, width?: number, height?: number): DOMRect; + fromRect(rectangle?: DOMRectInit): DOMRect; +}; + +interface DOMRectList { + readonly length: number; + item(index: number): DOMRect | null; + [index: number]: DOMRect; +} + interface OES_vertex_array_object { readonly VERTEX_ARRAY_BINDING_OES: number; createVertexArrayOES(): WebGLVertexArrayObjectOES; @@ -14804,6 +14852,43 @@ interface WEBGL_lose_context { restoreContext(): void; } +interface AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: (ev: Event) => any; +} + +interface EventSource extends EventTarget { + readonly url: string; + readonly withCredentials: boolean; + readonly CONNECTING: number; + readonly OPEN: number; + readonly CLOSED: number; + readonly readyState: number; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -14816,7 +14901,7 @@ interface ErrorEventHandler { (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; } interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; + (keyId: BufferSource, status: MediaKeyStatus): void; } interface FrameRequestCallback { (time: number): void; @@ -15054,6 +15139,7 @@ interface SVGElementTagNameMap { "view": SVGViewElement; } +/** @deprecated Directly use HTMLElementTagNameMap or SVGElementTagNameMap as appropriate, instead. */ interface ElementTagNameMap extends HTMLElementTagNameMap, SVGElementTagNameMap { } declare var Audio: { new(src?: string): HTMLAudioElement; }; @@ -15271,7 +15357,7 @@ declare function removeEventListener(type: K, li declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AAGUID = string; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = any; +type BodyInit = Blob | BufferSource | FormData | string; type ByteString = string; type ConstrainBoolean = boolean | ConstrainBooleanParameters; type ConstrainDOMString = string | string[] | ConstrainDOMStringParameters; diff --git a/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index cf7eea74c3c..8f292280708 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -86,12 +86,13 @@ interface ObjectURLOptions { } interface PushSubscriptionOptionsInit { - applicationServerKey?: any; + applicationServerKey?: BufferSource | null; userVisibleOnly?: boolean; } interface RequestInit { - body?: any; + signal?: AbortSignal; + body?: Blob | BufferSource | FormData | string | null; cache?: RequestCache; credentials?: RequestCredentials; headers?: HeadersInit; @@ -139,7 +140,7 @@ interface NotificationEventInit extends ExtendableEventInit { } interface PushEventInit extends ExtendableEventInit { - data?: any; + data?: BufferSource | USVString; } interface SyncEventInit extends ExtendableEventInit { @@ -434,9 +435,10 @@ declare var EventTarget: { }; interface File extends Blob { - readonly lastModifiedDate: any; + readonly lastModifiedDate: Date; readonly name: string; readonly webkitRelativePath: string; + readonly lastModified: number; } declare var File: { @@ -979,6 +981,7 @@ interface Request extends Object, Body { readonly referrerPolicy: ReferrerPolicy; readonly type: RequestType; readonly url: string; + readonly signal: AbortSignal; clone(): Request; } @@ -1081,7 +1084,7 @@ interface URL { declare var URL: { prototype: URL; - new(url: string, base?: string): URL; + new(url: string, base?: string | URL): URL; createObjectURL(object: any, options?: ObjectURLOptions): string; revokeObjectURL(url: string): void; }; @@ -1841,6 +1844,43 @@ interface AddEventListenerOptions extends EventListenerOptions { once?: boolean; } +interface AbortController { + readonly signal: AbortSignal; + abort(): void; +} + +declare var AbortController: { + prototype: AbortController; + new(): AbortController; +}; + +interface AbortSignal extends EventTarget { + readonly aborted: boolean; + onabort: (ev: Event) => any; +} + +interface EventSource extends EventTarget { + readonly url: string; + readonly withCredentials: boolean; + readonly CONNECTING: number; + readonly OPEN: number; + readonly CLOSED: number; + readonly readyState: number; + onopen: (evt: MessageEvent) => any; + onmessage: (evt: MessageEvent) => any; + onerror: (evt: MessageEvent) => any; + close(): void; +} + +declare var EventSource: { + prototype: EventSource; + new(url: string, eventSourceInitDict?: EventSourceInit): EventSource; +}; + +interface EventSourceInit { + readonly withCredentials: boolean; +} + declare type EventListenerOrEventListenerObject = EventListener | EventListenerObject; interface DecodeErrorCallback { @@ -1853,7 +1893,7 @@ interface ErrorEventHandler { (message: string, filename?: string, lineno?: number, colno?: number, error?: Error): void; } interface ForEachCallback { - (keyId: any, status: MediaKeyStatus): void; + (keyId: BufferSource, status: MediaKeyStatus): void; } interface FunctionStringCallback { (data: string): void; @@ -1903,7 +1943,7 @@ declare function addEventListener(type: string, listener: EventListenerOrEventLi declare function removeEventListener(type: K, listener: (this: DedicatedWorkerGlobalScope, ev: DedicatedWorkerGlobalScopeEventMap[K]) => any, options?: boolean | EventListenerOptions): void; declare function removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; type AlgorithmIdentifier = string | Algorithm; -type BodyInit = any; +type BodyInit = Blob | BufferSource | FormData | string; type IDBKeyPath = string; type RequestInfo = Request | string; type USVString = string; diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index 3ac940f0eef..a6578991e44 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -1237,6 +1237,11 @@ declare namespace ts.server.protocol { * This affects lone identifier completions but not completions on the right hand side of `obj.`. */ includeExternalModuleExports: boolean; + /** + * If enabled, the completion list will include completions with invalid identifier names. + * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. + */ + includeInsertTextCompletions: boolean; } /** * Completions request; value of command field is "completions". @@ -1305,6 +1310,12 @@ declare namespace ts.server.protocol { * is often the same as the name but may be different in certain circumstances. */ sortText: string; + /** + * Text to insert instead of `name`. + * This is used to support bracketed completions; If `name` might be "a-b" but `insertText` would be `["a-b"]`, + * coupled with `replacementSpan` to replace a dotted access with a bracket access. + */ + insertText?: 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. @@ -1978,6 +1989,7 @@ declare namespace ts.server.protocol { insertSpaceBeforeFunctionParenthesis?: boolean; placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } interface CompilerOptions { allowJs?: boolean; diff --git a/lib/tsc.js b/lib/tsc.js index 5d81b4031c0..8394604267c 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -415,17 +415,6 @@ var ts; return false; } ts.contains = contains; - function indexOf(array, value) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (array[i] === value) { - return i; - } - } - } - return -1; - } - ts.indexOf = indexOf; function indexOfAnyCharCode(text, charCodes, start) { for (var i = start || 0; i < text.length; i++) { if (contains(charCodes, text.charCodeAt(i))) { @@ -1709,7 +1698,9 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop + ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 + : moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getStrictOptionValue(compilerOptions, flag) { @@ -3342,6 +3333,8 @@ var ts; unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), + An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."), + An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -3456,6 +3449,7 @@ var ts; Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."), Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), @@ -3510,7 +3504,7 @@ var ts; Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), - const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."), A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), @@ -3677,6 +3671,9 @@ var ts; Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"), + Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), + Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), + Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -3991,6 +3988,8 @@ var ts; Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), + A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime: diag(7038, ts.DiagnosticCategory.Error, "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038", "A namespace-style import cannot be called or constructed, and will cause a failure at runtime."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -4080,6 +4079,8 @@ var ts; Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), + Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), + Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), }; })(ts || (ts = {})); var ts; @@ -5628,7 +5629,7 @@ var ts; break; } } - tokenValue += text.substr(firstCharPosition, pos - firstCharPosition); + tokenValue += text.substring(firstCharPosition, pos); } return token; } @@ -5650,6 +5651,7 @@ var ts; startPos = pos; tokenPos = pos; var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 9: case 11: @@ -5660,55 +5662,30 @@ var ts; } return token = 5; case 64: - pos++; return token = 57; case 10: case 13: - pos++; return token = 4; case 42: - pos++; return token = 39; case 123: - pos++; return token = 17; case 125: - pos++; return token = 18; case 91: - pos++; return token = 21; case 93: - pos++; return token = 22; case 60: - pos++; return token = 27; - case 62: - pos++; - return token = 29; case 61: - pos++; return token = 58; case 44: - pos++; return token = 26; case 46: - pos++; - if (text.substr(tokenPos, pos + 2) === "...") { - pos += 2; - return token = 24; - } return token = 23; - case 33: - pos++; - return token = 51; - case 63: - pos++; - return token = 55; } if (isIdentifierStart(ch, 6)) { - pos++; while (isIdentifierPart(text.charCodeAt(pos), 6) && pos < end) { pos++; } @@ -5716,7 +5693,7 @@ var ts; return token = 71; } else { - return pos += 1, token = 0; + return token = 0; } } function speculationHelper(callback, isLookahead) { @@ -6447,7 +6424,7 @@ var ts; return node === parent.type; case 182: case 183: - return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; + return ts.contains(parent.typeArguments, node); case 184: return false; } @@ -7592,6 +7569,10 @@ var ts; return "__@" + symbolName; } ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + function isKnownSymbol(symbol) { + return ts.startsWith(symbol.escapedName, "__@"); + } + ts.isKnownSymbol = isKnownSymbol; function isESSymbolIdentifier(node) { return node.kind === 71 && node.escapedText === "Symbol"; } @@ -10588,6 +10569,21 @@ var ts; return hasInitializer(node) && !ts.isForStatement(node) && !ts.isForInStatement(node) && !ts.isForOfStatement(node) && !ts.isJsxAttribute(node); } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; + function isObjectLiteralElement(node) { + switch (node.kind) { + case 257: + case 259: + case 265: + case 266: + case 152: + case 154: + case 155: + return true; + default: + return false; + } + } + ts.isObjectLiteralElement = isObjectLiteralElement; })(ts || (ts = {})); var ts; (function (ts) { @@ -11651,9 +11647,12 @@ var ts; return token() === 26 || token() === 24 || isIdentifierOrPattern(); case 18: return isIdentifier(); - case 11: case 15: - return token() === 26 || token() === 24 || isStartOfExpression(); + if (token() === 26) { + return true; + } + case 11: + return token() === 24 || isStartOfExpression(); case 16: return isStartOfParameter(); case 19: @@ -11813,6 +11812,9 @@ var ts; if (!canReuseNode(node, parsingContext)) { return undefined; } + if (node.jsDocCache) { + node.jsDocCache = undefined; + } return node; } function consumeNode(node) { @@ -13056,7 +13058,9 @@ var ts; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); node.colonToken = parseExpectedToken(56, false, ts.Diagnostics._0_expected, ts.tokenToString(56)); - node.whenFalse = parseAssignmentExpressionOrHigher(); + node.whenFalse = ts.nodeIsPresent(node.colonToken) + ? parseAssignmentExpressionOrHigher() + : createMissingNode(71, false, ts.Diagnostics._0_expected, ts.tokenToString(56)); return finishNode(node); } function parseBinaryExpressionOrHigher(precedence) { @@ -15063,17 +15067,17 @@ var ts; comments.push(text); indent += text.length; } - nextJSDocToken(); - while (token() === 5) { - nextJSDocToken(); + var t = nextJSDocToken(); + while (t === 5) { + t = nextJSDocToken(); } - if (token() === 4) { + if (t === 4) { state = 0; indent = 0; - nextJSDocToken(); + t = nextJSDocToken(); } - while (token() !== 1) { - switch (token()) { + loop: while (true) { + switch (t) { case 57: if (state === 0 || state === 1) { removeTrailingNewlines(comments); @@ -15118,17 +15122,18 @@ var ts; indent += whitespace.length; break; case 1: - break; + break loop; default: state = 2; pushComment(scanner.getTokenText()); break; } if (advanceToken) { - nextJSDocToken(); + t = nextJSDocToken(); } else { advanceToken = true; + t = currentToken; } } removeLeadingNewlines(comments); @@ -15226,8 +15231,9 @@ var ts; comments.push(text); indent += text.length; } - while (token() !== 57 && token() !== 1) { - switch (token()) { + var tok = token(); + loop: while (true) { + switch (tok) { case 4: if (state >= 1) { state = 0; @@ -15236,7 +15242,8 @@ var ts; indent = 0; break; case 57: - break; + case 1: + break loop; case 5: if (state === 2) { pushComment(scanner.getTokenText()); @@ -15260,10 +15267,7 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (token() === 57) { - break; - } - nextJSDocToken(); + tok = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); @@ -15500,8 +15504,7 @@ var ts; var canParseTag = true; var seenAsterisk = false; while (true) { - nextJSDocToken(); - switch (token()) { + switch (nextJSDocToken()) { case 57: if (canParseTag) { var child = tryParseChildTag(target); @@ -16118,7 +16121,7 @@ var ts; case 147: ts.Debug.assert(node.parent.kind === 277); var functionType = node.parent; - var index = ts.indexOf(functionType.parameters, node); + var index = functionType.parameters.indexOf(node); return "arg" + index; case 288: var name_2 = ts.getNameOfJSDocTypedef(node); @@ -16452,10 +16455,10 @@ var ts; return false; } function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 190 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; + return expr1.kind === 190 && isNarrowableOperand(expr1.expression) && (expr2.kind === 9 || expr2.kind === 13); } function isNarrowableInOperands(left, right) { - return left.kind === 9 && isNarrowingExpression(right); + return (left.kind === 9 || left.kind === 13) && isNarrowingExpression(right); } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { @@ -17842,7 +17845,7 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (ts.isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, 1, "__" + ts.indexOf(node.parent.parameters, node)); + bindAnonymousDeclaration(node, 1, "__" + node.parent.parameters.indexOf(node)); } else { declareSymbolAndAddToSymbolTable(node, 1, 107455); @@ -19819,6 +19822,7 @@ var ts; }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, getAccessibleSymbolChain: getAccessibleSymbolChain, + resolveExternalModuleSymbol: resolveExternalModuleSymbol, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -20222,7 +20226,7 @@ var ts; return true; } var sourceFiles = host.getSourceFiles(); - return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); + return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); } if (declaration.pos <= usage.pos) { if (declaration.kind === 177) { @@ -20443,7 +20447,7 @@ var ts; } break; } - if (location.kind !== 208) { + if (isNonBlockLocation(location)) { lastNonBlockLocation = location; } lastLocation = location; @@ -20507,6 +20511,20 @@ var ts; } return result; } + function isNonBlockLocation(_a) { + var kind = _a.kind; + switch (kind) { + case 208: + case 235: + case 222: + case 236: + case 261: + case 262: + return false; + default: + return true; + } + } function diagnosticName(nameArg) { return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); } @@ -20662,6 +20680,30 @@ var ts; } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); } + function resolveExportByName(moduleSymbol, name, dontResolveAlias) { + var exportValue = moduleSymbol.exports.get("export="); + return exportValue + ? getPropertyOfType(getTypeOfSymbol(exportValue), name) + : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); + } + function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { + if (!allowSyntheticDefaultImports) { + return false; + } + if (!file || file.isDeclarationFile) { + if (resolveExportByName(moduleSymbol, "default", dontResolveAlias)) { + return false; + } + if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias)) { + return false; + } + return true; + } + if (!ts.isSourceFileJavaScript(file)) { + return hasExportAssignmentSymbol(moduleSymbol); + } + return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias); + } function getTargetOfImportClause(node, dontResolveAlias) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { @@ -20670,15 +20712,14 @@ var ts; exportDefaultSymbol = moduleSymbol; } else { - var exportValue = moduleSymbol.exports.get("export="); - exportDefaultSymbol = exportValue - ? getPropertyOfType(getTypeOfSymbol(exportValue), "default") - : resolveSymbol(moduleSymbol.exports.get("default"), dontResolveAlias); + exportDefaultSymbol = resolveExportByName(moduleSymbol, "default", dontResolveAlias); } - if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { + var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); + if (!exportDefaultSymbol && !hasSyntheticDefault) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } - else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + else if (!exportDefaultSymbol && hasSyntheticDefault) { return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } return exportDefaultSymbol; @@ -20984,8 +21025,41 @@ var ts; } function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression, dontResolveAlias) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); - if (!dontResolveAlias && symbol && !(symbol.flags & (1536 | 3))) { - error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + if (!dontResolveAlias && symbol) { + if (!(symbol.flags & (1536 | 3))) { + error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + return symbol; + } + if (compilerOptions.esModuleInterop) { + var referenceParent = moduleReferenceExpression.parent; + if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || + ts.isImportCall(referenceParent)) { + var type = getTypeOfSymbol(symbol); + var sigs = getSignaturesOfStructuredType(type, 0); + if (!sigs || !sigs.length) { + sigs = getSignaturesOfStructuredType(type, 1); + } + if (sigs && sigs.length) { + var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol); + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + result.target = symbol; + result.originatingImport = referenceParent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + var resolvedModuleType = resolveStructuredTypeMembers(moduleType); + result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo); + return result; + } + } + } } return symbol; } @@ -22981,7 +23055,7 @@ var ts; type = createArrayType(elementType); } else { - var propName = "" + ts.indexOf(pattern.elements, declaration); + var propName = "" + pattern.elements.indexOf(declaration); type = isTupleLikeType(parentType) ? getTypeOfPropertyOfType(parentType, propName) : elementType; @@ -24910,7 +24984,7 @@ var ts; if (node.initializer) { var signatureDeclaration = node.parent; var signature = getSignatureFromDeclaration(signatureDeclaration); - var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); + var parameterIndex = signatureDeclaration.parameters.indexOf(node); ts.Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } @@ -24918,7 +24992,7 @@ var ts; if (iife) { return !node.type && !node.dotDotDotToken && - ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; + node.parent.parameters.indexOf(node) >= iife.arguments.length; } return false; } @@ -26009,7 +26083,7 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.escapedName, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.isKnownSymbol(prop) ? neverType : getLiteralType(ts.symbolName(prop)); } @@ -26058,6 +26132,7 @@ var ts; var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { + markPropertyAsReferenced(prop, accessExpression, accessExpression.expression.kind === 99); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); return unknownType; @@ -26505,7 +26580,7 @@ var ts; return createTypeMapper(sources, undefined); } function createBackreferenceMapper(typeParameters, index) { - return function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; + return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; }; } function isInferenceContext(mapper) { return !!mapper.signature; @@ -27072,10 +27147,22 @@ var ts; } else if (errorInfo) { if (containingMessageChain) { - errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); + var chain_1 = containingMessageChain(); + if (chain_1) { + errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo); + } } diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } + if (headMessage && errorNode && !result && source.symbol) { + var links = getSymbolLinks(source.symbol); + if (links.originatingImport && !ts.isImportCall(links.originatingImport)) { + var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, undefined); + if (helpfulRetry) { + diagnostics.add(ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime)); + } + } + } return result !== 0; function reportError(message, arg0, arg1, arg2) { ts.Debug.assert(!!errorNode); @@ -27973,7 +28060,7 @@ var ts; for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { var t = _a[_i]; if (isUnconstrainedTypeParameter(t)) { - var index = ts.indexOf(typeParameters, t); + var index = typeParameters.indexOf(t); if (index < 0) { index = typeParameters.length; typeParameters.push(t); @@ -29257,7 +29344,7 @@ var ts; parent.parent.kind === 217 && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { - return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); + return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); } function getAssignedTypeOfSpreadExpression(node) { return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); @@ -29296,7 +29383,7 @@ var ts; var type = pattern.kind === 175 ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? - getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : + getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : getTypeOfDestructuredSpreadExpression(parentType); return getTypeWithDefault(type, node.initializer); } @@ -29841,10 +29928,10 @@ var ts; var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 190 && right_1.kind === 9) { + if (left_1.kind === 190 && (right_1.kind === 9 || right_1.kind === 13)) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 190 && left_1.kind === 9) { + if (right_1.kind === 190 && (left_1.kind === 9 || left_1.kind === 13)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -29867,7 +29954,7 @@ var ts; return narrowTypeByInstanceof(type, expr, assumeTrue); case 92: var target = getReferenceCandidate(expr.right); - if (expr.left.kind === 9 && isMatchingReference(reference, target)) { + if ((expr.left.kind === 9 || expr.left.kind === 13) && isMatchingReference(reference, target)) { return narrowByInKeyword(type, expr.left, assumeTrue); } break; @@ -30237,12 +30324,13 @@ var ts; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; + var isSpreadDestructuringAsignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); while (flowContainer !== declarationContainer && (flowContainer.kind === 187 || flowContainer.kind === 188 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } - var assumeInitialized = isParameter || isAlias || isOuterVariable || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAsignmentTarget || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1) !== 0 || isInTypeQuery(node) || node.parent.kind === 247) || node.parent.kind === 204 || @@ -30621,7 +30709,7 @@ var ts; if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { var iife = ts.getImmediatelyInvokedFunctionExpression(func); if (iife && iife.arguments) { - var indexOfParameter = ts.indexOf(func.parameters, parameter); + var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { var restTypes = []; for (var i = indexOfParameter; i < iife.arguments.length; i++) { @@ -30642,7 +30730,7 @@ var ts; if (contextualSignature) { var funcHasRestParameters = ts.hasRestParameter(func); var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = ts.indexOf(func.parameters, parameter); + var indexOfParameter = func.parameters.indexOf(parameter); if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { ts.Debug.assert(indexOfParameter !== 0); indexOfParameter -= 1; @@ -30745,7 +30833,7 @@ var ts; } function getContextualTypeForArgument(callTarget, arg) { var args = getEffectiveCallArguments(callTarget); - var argIndex = ts.indexOf(args, arg); + var argIndex = args.indexOf(arg); if (argIndex >= 0) { var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); return getTypeAtPosition(signature, argIndex); @@ -31086,7 +31174,7 @@ var ts; if (patternElement.kind !== 201) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } - elementTypes.push(unknownType); + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); } } } @@ -31940,16 +32028,16 @@ var ts; return propKind !== 152 && propKind !== 151; }); } - function checkNonNullExpression(node) { - return checkNonNullType(checkExpression(node), node); + function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); } - function checkNonNullType(type, errorNode) { + function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 12288; if (kind) { - error(errorNode, kind & 4096 ? kind & 8192 ? - ts.Diagnostics.Object_is_possibly_null_or_undefined : - ts.Diagnostics.Object_is_possibly_undefined : - ts.Diagnostics.Object_is_possibly_null); + error(node, kind & 4096 ? kind & 8192 ? + (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : + (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : + (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); var t = getNonNullableType(type); return t.flags & (12288 | 16384) ? unknownType : t; } @@ -32542,7 +32630,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (!constraint) continue; - var errorInfo = reportErrors && headMessage && ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + var errorInfo = reportErrors && headMessage && (function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }); var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; if (!mapper) { mapper = createTypeMapper(typeParameters, typeArgumentTypes); @@ -32942,7 +33030,7 @@ var ts; } excludeCount--; if (excludeCount > 0) { - excludeArgument[ts.indexOf(excludeArgument, true)] = false; + excludeArgument[excludeArgument.indexOf(true)] = false; } else { excludeArgument = undefined; @@ -32979,7 +33067,7 @@ var ts; } return resolveUntypedCall(node); } - var funcType = checkNonNullExpression(node.expression); + var funcType = checkNonNullExpression(node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -33000,7 +33088,7 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + invocationError(node, apparentType, 0); } return resolveErrorCall(node); } @@ -33054,7 +33142,7 @@ var ts; } return signature; } - error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); + invocationError(node, expressionType, 1); return resolveErrorCall(node); } function isConstructorAccessible(node, signature) { @@ -33092,6 +33180,24 @@ var ts; } return true; } + function invocationError(node, apparentType, kind) { + error(node, kind === 0 + ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures + : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind); + } + function invocationErrorRecovery(apparentType, kind) { + if (!apparentType.symbol) { + return; + } + var importNode = getSymbolLinks(apparentType.symbol).originatingImport; + if (importNode && !ts.isImportCall(importNode)) { + var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); + if (!sigs || !sigs.length) + return; + error(importNode, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime); + } + } function resolveTaggedTemplateExpression(node, candidatesOutArray) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); @@ -33104,7 +33210,7 @@ var ts; return resolveUntypedCall(node); } if (!callSignatures.length) { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + invocationError(node, apparentType, 0); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray); @@ -33146,6 +33252,7 @@ var ts; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + invocationErrorRecovery(apparentType, 0); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray, headMessage); @@ -33312,16 +33419,18 @@ var ts; if (moduleSymbol) { var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, true); if (esModuleSymbol) { - return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol)); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol)); } } return createPromiseReturnType(node, anyType); } - function getTypeWithSyntheticDefaultImportType(type, symbol) { + function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { if (allowSyntheticDefaultImports && type && type !== unknownType) { var synthType = type; if (!synthType.syntheticType) { - if (!getPropertyOfType(type, "default")) { + var file = ts.find(originalSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, false); + if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); var newSymbol = createSymbol(2097152, "default"); newSymbol.target = resolveSymbol(symbol); @@ -33329,7 +33438,7 @@ var ts; var anonymousSymbol = createSymbol(2048, "__type"); var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, undefined, undefined); anonymousSymbol.type = defaultContainingObject; - synthType.syntheticType = getIntersectionType([type, defaultContainingObject]); + synthType.syntheticType = (type.flags & 458752 && type.symbol.flags & (1536 | 3)) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, 0) : defaultContainingObject; } else { synthType.syntheticType = type; @@ -34542,9 +34651,10 @@ var ts; if (isConstEnumObjectType(type)) { var ok = (node.parent.kind === 180 && node.parent.expression === node) || (node.parent.kind === 181 && node.parent.expression === node) || - ((node.kind === 71 || node.kind === 144) && isInRightSideOfImportOrExportAssignment(node)); + ((node.kind === 71 || node.kind === 144) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 163 && node.parent.exprName === node)); if (!ok) { - error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } } return type; @@ -34682,7 +34792,7 @@ var ts; error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); } if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { - if (ts.indexOf(func.parameters, node) !== 0) { + if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } if (func.kind === 153 || func.kind === 157 || func.kind === 162) { @@ -34725,7 +34835,7 @@ var ts; error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { - var leadingError = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); + var leadingError = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, undefined, leadingError); } } @@ -35011,22 +35121,6 @@ var ts; if (!produceDiagnostics) { return; } - function containsSuperCallAsComputedPropertyName(n) { - var name = ts.getNameOfDeclaration(n); - return name && containsSuperCall(name); - } - function containsSuperCall(n) { - if (ts.isSuperCall(n)) { - return true; - } - else if (ts.isFunctionLike(n)) { - return false; - } - else if (ts.isClassLike(n)) { - return ts.forEach(n.members, containsSuperCallAsComputedPropertyName); - } - return ts.forEachChild(n, containsSuperCall); - } function isInstancePropertyWithInitializer(n) { return n.kind === 150 && !ts.hasModifier(n, 32) && @@ -35550,7 +35644,7 @@ var ts; } var promisedType = getPromisedTypeOfPromise(type); if (promisedType) { - if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) { + if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) { if (errorNode) { error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); } @@ -35656,7 +35750,7 @@ var ts; expectedReturnType = getUnionType([descriptorType, voidType]); break; } - checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); } function markTypeNodeAsReferenced(node) { markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); @@ -35969,34 +36063,33 @@ var ts; } function checkUnusedClassMembers(node) { if (compilerOptions.noUnusedLocals && !(node.flags & 2097152)) { - if (node.members) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - switch (member.kind) { - case 152: - case 150: - case 154: - case 155: - if (member.kind === 155 && member.symbol.flags & 32768) { - break; - } - if (!member.symbol.isReferenced && ts.hasModifier(member, 8)) { - error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(member.symbol)); - } + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 152: + case 150: + case 154: + case 155: + if (member.kind === 155 && member.symbol.flags & 32768) { break; - case 153: - for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { - var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8)) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)); - } + } + var symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && ts.hasModifier(member, 8)) { + error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)); + } + break; + case 153: + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8)) { + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)); } - break; - case 158: - break; - default: - ts.Debug.fail(); - } + } + break; + case 158: + break; + default: + ts.Debug.fail(); } } } @@ -37049,7 +37142,10 @@ var ts; } } } - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + } checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); if (baseConstructorType.flags & 1081344 && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); @@ -37075,9 +37171,13 @@ var ts; var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { if (isValidBaseType(t)) { - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, t.symbol && t.symbol.flags & 32 ? + var genericDiag = t.symbol && t.symbol.flags & 32 ? ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : - ts.Diagnostics.Class_0_incorrectly_implements_interface_1); + ts.Diagnostics.Class_0_incorrectly_implements_interface_1; + var baseWithThis = getTypeWithThisArgument(t, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag); + } } else { error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); @@ -37092,6 +37192,32 @@ var ts; checkPropertyInitialization(node); } } + function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { + var issuedMemberError = false; + var _loop_5 = function (member) { + if (ts.hasStaticModifier(member)) { + return "continue"; + } + var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (declaredProp) { + var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); + var baseProp_1 = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp_1) { + var rootChain = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(getTypeOfSymbol(baseProp_1))); }; + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp_1), member.name || member, undefined, rootChain)) { + issuedMemberError = true; + } + } + } + }; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + _loop_5(member); + } + if (!issuedMemberError) { + checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); + } + } function checkBaseTypeAccessibility(type, node) { var signatures = getSignaturesOfType(type, 1); if (signatures.length) { @@ -38547,7 +38673,7 @@ var ts; ts.Debug.assert(expr.parent.kind === 178); var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, false, false) || unknownType; - return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || unknownType); } function getPropertySymbolOfDestructuringAssignment(location) { var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); @@ -39551,6 +39677,13 @@ var ts; return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } if (parameter.type.kind !== 136 && parameter.type.kind !== 133) { + var type = getTypeFromTypeNode(parameter.type); + if (type.flags & 2 || type.flags & 4) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); + } + if (allTypesAssignableToKind(type, 32, true)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); + } return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { @@ -44065,7 +44198,7 @@ var ts; case 216: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 217: - return ts.updateForOf(node, node.awaitModifier, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 218: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); case 219: @@ -44803,6 +44936,7 @@ var ts; var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues); var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); if (externalHelpersImportDeclaration) { + ts.addEmitFlags(externalHelpersImportDeclaration, 67108864); externalImports.unshift(externalHelpersImportDeclaration); } return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; @@ -48512,7 +48646,7 @@ var ts; } function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { if (extendsClauseElement) { - statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getLocalName(node))), extendsClauseElement)); + statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getInternalName(node))), extendsClauseElement)); } } function addConstructor(statements, node, extendsClauseElement) { @@ -51846,7 +51980,7 @@ var ts; var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); var _a = collectAsynchronousDependencies(node, true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createStatement(ts.createCall(define, undefined, (moduleName ? [moduleName] : []).concat([ ts.createArrayLiteral([ ts.createLiteral("require"), @@ -51858,6 +51992,8 @@ var ts; ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) ]))) ]), node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; } function transformUMDModule(node) { var _a = collectAsynchronousDependencies(node, false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; @@ -51881,7 +52017,7 @@ var ts; ]))) ]))) ], true), undefined)); - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createStatement(ts.createCall(umdHeader, undefined, [ ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ ts.createParameter(undefined, undefined, undefined, "require"), @@ -51889,6 +52025,8 @@ var ts; ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) ])) ]), node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; } function collectAsynchronousDependencies(node, includeNonAmdDependencies) { var aliasedModuleNames = []; @@ -51921,6 +52059,17 @@ var ts; } return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; } + function getAMDImportExpressionForImport(node) { + if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) { + return undefined; + } + var name = ts.getLocalNameForExternalImport(node, currentSourceFile); + var expr = getHelperExpressionForImport(node, name); + if (expr === name) { + return undefined; + } + return ts.createStatement(ts.createAssignment(name, expr)); + } function transformAsynchronousModuleBody(node) { startLexicalEnvironment(); var statements = []; @@ -51929,6 +52078,9 @@ var ts; ts.append(statements, createUnderscoreUnderscoreESModule()); } ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); + if (moduleKind === ts.ModuleKind.AMD) { + ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport)); + } ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, true); ts.addRange(statements, endLexicalEnvironment()); @@ -52039,11 +52191,20 @@ var ts; ts.setEmitFlags(func, 8); } } - return ts.createNew(ts.createIdentifier("Promise"), undefined, [func]); + var promise = ts.createNew(ts.createIdentifier("Promise"), undefined, [func]); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), undefined, [ts.getHelperName("__importStar")]); + } + return promise; } function createImportCallExpressionCommonJS(arg, containsLexicalThis) { var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), undefined, []); var requireCall = ts.createCall(ts.createIdentifier("require"), undefined, arg ? [arg] : []); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + requireCall = ts.createCall(ts.getHelperName("__importStar"), undefined, [requireCall]); + } var func; if (languageVersion >= 2) { func = ts.createArrowFunction(undefined, undefined, [], undefined, undefined, requireCall); @@ -52056,6 +52217,20 @@ var ts; } return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), undefined, [func]); } + function getHelperExpressionForImport(node, innerExpr) { + if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864) { + return innerExpr; + } + if (ts.getNamespaceDeclarationNode(node)) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.getHelperName("__importStar"), undefined, [innerExpr]); + } + if (ts.isDefaultImport(node)) { + context.requestEmitHelper(importDefaultHelper); + return ts.createCall(ts.getHelperName("__importDefault"), undefined, [innerExpr]); + } + return innerExpr; + } function visitImportDeclaration(node) { var statements; var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); @@ -52066,10 +52241,10 @@ var ts; else { var variables = []; if (namespaceDeclaration && !ts.isDefaultImport(node)) { - variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, createRequireCall(node))); + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, getHelperExpressionForImport(node, createRequireCall(node)))); } else { - variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), undefined, createRequireCall(node))); + variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), undefined, getHelperExpressionForImport(node, createRequireCall(node)))); if (namespaceDeclaration && ts.isDefaultImport(node)) { variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node))); } @@ -52531,6 +52706,16 @@ var ts; scoped: true, text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" }; + var importStarHelper = { + name: "typescript:commonjsimportstar", + scoped: false, + text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n}" + }; + var importDefaultHelper = { + name: "typescript:commonjsimportdefault", + scoped: false, + text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n}" + }; })(ts || (ts = {})); var ts; (function (ts) { @@ -53385,7 +53570,9 @@ var ts; if (externalHelpersModuleName) { var statements = []; var statementOffset = ts.addPrologue(statements, node.statements); - ts.append(statements, ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText))); + var tslibImport = ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + ts.addEmitFlags(tslibImport, 67108864); + ts.append(statements, tslibImport); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -53901,7 +54088,7 @@ var ts; currentSourceText = currentSource.text; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSource.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); - sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); + sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(source); if (sourceMapSourceIndex === -1) { sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); @@ -54381,7 +54568,7 @@ var ts; allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); moduleElementDeclarationEmitInfo = []; } - if (!isBundledEmit && ts.isExternalModule(sourceFile) && sourceFile.moduleAugmentations.length && !resultHasExternalModuleIndicator) { + if (!isBundledEmit && ts.isExternalModule(sourceFile) && !resultHasExternalModuleIndicator) { write("export {};"); writeLine(); } @@ -54792,6 +54979,9 @@ var ts; return tempVarName; } function emitExportAssignment(node) { + if (ts.isSourceFile(node.parent)) { + resultHasExternalModuleIndicator = true; + } if (node.expression.kind === 71) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); @@ -54874,6 +55064,7 @@ var ts; if (node.parent.kind === 269) { var modifiers = ts.getModifierFlags(node); if (modifiers & 1) { + resultHasExternalModuleIndicator = true; write("export "); } if (modifiers & 512) { @@ -55006,6 +55197,7 @@ var ts; writeAsynchronousModuleElements(nodes); } function emitExportDeclaration(node) { + resultHasExternalModuleIndicator = true; emitJsDocComments(node); write("export "); if (node.exportClause) { @@ -59963,6 +60155,7 @@ var ts; && !file.isDeclarationFile) { var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); var importDecl = ts.createImportDeclaration(undefined, undefined, undefined); + ts.addEmitFlags(importDecl, 67108864); externalHelpersModuleReference.parent = importDecl; importDecl.parent = file; imports = [externalHelpersModuleReference]; @@ -60461,12 +60654,12 @@ var ts; if (emitFileName) { var emitFilePath = toPath(emitFileName); if (filesByName.has(emitFilePath)) { - var chain_1; + var chain_2; if (!options.configFilePath) { - chain_1 = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + chain_2 = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); } - chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); - blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_1)); + chain_2 = ts.chainDiagnosticMessages(chain_2, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_2)); } var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; if (emitFilesSeen.has(emitFileKey)) { @@ -61660,6 +61853,7 @@ var ts; "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", + "esnext.array": "lib.esnext.array.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", "esnext.promise": "lib.esnext.promise.d.ts", }), @@ -61907,6 +62101,13 @@ var ts; category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, + { + name: "esModuleInterop", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports + }, { name: "preserveSymlinks", type: "boolean", @@ -62187,7 +62388,8 @@ var ts; ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, target: 1, - strict: true + strict: true, + esModuleInterop: true }; var optionNameMapCache; function convertEnableAutoDiscoveryToEnable(typeAcquisition) { @@ -62609,7 +62811,7 @@ var ts; function serializeCompilerOptions(options) { var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_5 = function (name) { + var _loop_6 = function (name) { if (ts.hasProperty(options, name)) { if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { return "continue"; @@ -62633,7 +62835,7 @@ var ts; } }; for (var name in options) { - _loop_5(name); + _loop_6(name); } return result; } diff --git a/lib/tsserver.js b/lib/tsserver.js index d5e5e12dd28..84d76fb43d8 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -1117,6 +1117,7 @@ var ts; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; + EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); var ExternalEmitHelpers; (function (ExternalEmitHelpers) { @@ -1479,17 +1480,6 @@ var ts; return false; } ts.contains = contains; - function indexOf(array, value) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (array[i] === value) { - return i; - } - } - } - return -1; - } - ts.indexOf = indexOf; function indexOfAnyCharCode(text, charCodes, start) { for (var i = start || 0; i < text.length; i++) { if (contains(charCodes, text.charCodeAt(i))) { @@ -2773,7 +2763,9 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop + ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 + : moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getStrictOptionValue(compilerOptions, flag) { @@ -4425,6 +4417,8 @@ var ts; unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), + An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."), + An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -4539,6 +4533,7 @@ var ts; Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."), Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), @@ -4593,7 +4588,7 @@ var ts; Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), - const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."), A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), @@ -4760,6 +4755,9 @@ var ts; Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"), + Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), + Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), + Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5074,6 +5072,8 @@ var ts; Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), + A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime: diag(7038, ts.DiagnosticCategory.Error, "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038", "A namespace-style import cannot be called or constructed, and will cause a failure at runtime."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5163,6 +5163,8 @@ var ts; Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), + Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), + Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), }; })(ts || (ts = {})); var ts; @@ -6655,7 +6657,7 @@ var ts; return node === parent.type; case 182: case 183: - return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; + return ts.contains(parent.typeArguments, node); case 184: return false; } @@ -7814,6 +7816,10 @@ var ts; return "__@" + symbolName; } ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + function isKnownSymbol(symbol) { + return ts.startsWith(symbol.escapedName, "__@"); + } + ts.isKnownSymbol = isKnownSymbol; function isESSymbolIdentifier(node) { return node.kind === 71 && node.escapedText === "Symbol"; } @@ -10821,6 +10827,21 @@ var ts; return hasInitializer(node) && !ts.isForStatement(node) && !ts.isForInStatement(node) && !ts.isForOfStatement(node) && !ts.isJsxAttribute(node); } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; + function isObjectLiteralElement(node) { + switch (node.kind) { + case 257: + case 259: + case 265: + case 266: + case 152: + case 154: + case 155: + return true; + default: + return false; + } + } + ts.isObjectLiteralElement = isObjectLiteralElement; })(ts || (ts = {})); var ts; (function (ts) { @@ -12368,7 +12389,7 @@ var ts; break; } } - tokenValue += text.substr(firstCharPosition, pos - firstCharPosition); + tokenValue += text.substring(firstCharPosition, pos); } return token; } @@ -12390,6 +12411,7 @@ var ts; startPos = pos; tokenPos = pos; var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 9: case 11: @@ -12400,55 +12422,30 @@ var ts; } return token = 5; case 64: - pos++; return token = 57; case 10: case 13: - pos++; return token = 4; case 42: - pos++; return token = 39; case 123: - pos++; return token = 17; case 125: - pos++; return token = 18; case 91: - pos++; return token = 21; case 93: - pos++; return token = 22; case 60: - pos++; return token = 27; - case 62: - pos++; - return token = 29; case 61: - pos++; return token = 58; case 44: - pos++; return token = 26; case 46: - pos++; - if (text.substr(tokenPos, pos + 2) === "...") { - pos += 2; - return token = 24; - } return token = 23; - case 33: - pos++; - return token = 51; - case 63: - pos++; - return token = 55; } if (isIdentifierStart(ch, 6)) { - pos++; while (isIdentifierPart(text.charCodeAt(pos), 6) && pos < end) { pos++; } @@ -12456,7 +12453,7 @@ var ts; return token = 71; } else { - return pos += 1, token = 0; + return token = 0; } } function speculationHelper(callback, isLookahead) { @@ -13603,9 +13600,12 @@ var ts; return token() === 26 || token() === 24 || isIdentifierOrPattern(); case 18: return isIdentifier(); - case 11: case 15: - return token() === 26 || token() === 24 || isStartOfExpression(); + if (token() === 26) { + return true; + } + case 11: + return token() === 24 || isStartOfExpression(); case 16: return isStartOfParameter(); case 19: @@ -13765,6 +13765,9 @@ var ts; if (!canReuseNode(node, parsingContext)) { return undefined; } + if (node.jsDocCache) { + node.jsDocCache = undefined; + } return node; } function consumeNode(node) { @@ -15008,7 +15011,9 @@ var ts; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); node.colonToken = parseExpectedToken(56, false, ts.Diagnostics._0_expected, ts.tokenToString(56)); - node.whenFalse = parseAssignmentExpressionOrHigher(); + node.whenFalse = ts.nodeIsPresent(node.colonToken) + ? parseAssignmentExpressionOrHigher() + : createMissingNode(71, false, ts.Diagnostics._0_expected, ts.tokenToString(56)); return finishNode(node); } function parseBinaryExpressionOrHigher(precedence) { @@ -17059,17 +17064,17 @@ var ts; comments.push(text); indent += text.length; } - nextJSDocToken(); - while (token() === 5) { - nextJSDocToken(); + var t = nextJSDocToken(); + while (t === 5) { + t = nextJSDocToken(); } - if (token() === 4) { + if (t === 4) { state = 0; indent = 0; - nextJSDocToken(); + t = nextJSDocToken(); } - while (token() !== 1) { - switch (token()) { + loop: while (true) { + switch (t) { case 57: if (state === 0 || state === 1) { removeTrailingNewlines(comments); @@ -17114,17 +17119,18 @@ var ts; indent += whitespace.length; break; case 1: - break; + break loop; default: state = 2; pushComment(scanner.getTokenText()); break; } if (advanceToken) { - nextJSDocToken(); + t = nextJSDocToken(); } else { advanceToken = true; + t = currentToken; } } removeLeadingNewlines(comments); @@ -17222,8 +17228,9 @@ var ts; comments.push(text); indent += text.length; } - while (token() !== 57 && token() !== 1) { - switch (token()) { + var tok = token(); + loop: while (true) { + switch (tok) { case 4: if (state >= 1) { state = 0; @@ -17232,7 +17239,8 @@ var ts; indent = 0; break; case 57: - break; + case 1: + break loop; case 5: if (state === 2) { pushComment(scanner.getTokenText()); @@ -17256,10 +17264,7 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (token() === 57) { - break; - } - nextJSDocToken(); + tok = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); @@ -17496,8 +17501,7 @@ var ts; var canParseTag = true; var seenAsterisk = false; while (true) { - nextJSDocToken(); - switch (token()) { + switch (nextJSDocToken()) { case 57: if (canParseTag) { var child = tryParseChildTag(target); @@ -18136,7 +18140,7 @@ var ts; case 147: ts.Debug.assert(node.parent.kind === 277); var functionType = node.parent; - var index = ts.indexOf(functionType.parameters, node); + var index = functionType.parameters.indexOf(node); return "arg" + index; case 288: var name_2 = ts.getNameOfJSDocTypedef(node); @@ -18470,10 +18474,10 @@ var ts; return false; } function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 190 && isNarrowableOperand(expr1.expression) && expr2.kind === 9; + return expr1.kind === 190 && isNarrowableOperand(expr1.expression) && (expr2.kind === 9 || expr2.kind === 13); } function isNarrowableInOperands(left, right) { - return left.kind === 9 && isNarrowingExpression(right); + return (left.kind === 9 || left.kind === 13) && isNarrowingExpression(right); } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { @@ -19865,7 +19869,7 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (ts.isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, 1, "__" + ts.indexOf(node.parent.parameters, node)); + bindAnonymousDeclaration(node, 1, "__" + node.parent.parameters.indexOf(node)); } else { declareSymbolAndAddToSymbolTable(node, 1, 107455); @@ -21008,6 +21012,7 @@ var ts; }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, getAccessibleSymbolChain: getAccessibleSymbolChain, + resolveExternalModuleSymbol: resolveExternalModuleSymbol, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -21508,7 +21513,7 @@ var ts; return true; } var sourceFiles = host.getSourceFiles(); - return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); + return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); } if (declaration.pos <= usage.pos) { if (declaration.kind === 177) { @@ -21729,7 +21734,7 @@ var ts; } break; } - if (location.kind !== 208) { + if (isNonBlockLocation(location)) { lastNonBlockLocation = location; } lastLocation = location; @@ -21793,6 +21798,20 @@ var ts; } return result; } + function isNonBlockLocation(_a) { + var kind = _a.kind; + switch (kind) { + case 208: + case 235: + case 222: + case 236: + case 261: + case 262: + return false; + default: + return true; + } + } function diagnosticName(nameArg) { return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); } @@ -21948,6 +21967,30 @@ var ts; } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); } + function resolveExportByName(moduleSymbol, name, dontResolveAlias) { + var exportValue = moduleSymbol.exports.get("export="); + return exportValue + ? getPropertyOfType(getTypeOfSymbol(exportValue), name) + : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); + } + function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { + if (!allowSyntheticDefaultImports) { + return false; + } + if (!file || file.isDeclarationFile) { + if (resolveExportByName(moduleSymbol, "default", dontResolveAlias)) { + return false; + } + if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias)) { + return false; + } + return true; + } + if (!ts.isSourceFileJavaScript(file)) { + return hasExportAssignmentSymbol(moduleSymbol); + } + return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias); + } function getTargetOfImportClause(node, dontResolveAlias) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { @@ -21956,15 +21999,14 @@ var ts; exportDefaultSymbol = moduleSymbol; } else { - var exportValue = moduleSymbol.exports.get("export="); - exportDefaultSymbol = exportValue - ? getPropertyOfType(getTypeOfSymbol(exportValue), "default") - : resolveSymbol(moduleSymbol.exports.get("default"), dontResolveAlias); + exportDefaultSymbol = resolveExportByName(moduleSymbol, "default", dontResolveAlias); } - if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { + var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); + if (!exportDefaultSymbol && !hasSyntheticDefault) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } - else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + else if (!exportDefaultSymbol && hasSyntheticDefault) { return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } return exportDefaultSymbol; @@ -22270,8 +22312,41 @@ var ts; } function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression, dontResolveAlias) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); - if (!dontResolveAlias && symbol && !(symbol.flags & (1536 | 3))) { - error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + if (!dontResolveAlias && symbol) { + if (!(symbol.flags & (1536 | 3))) { + error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + return symbol; + } + if (compilerOptions.esModuleInterop) { + var referenceParent = moduleReferenceExpression.parent; + if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || + ts.isImportCall(referenceParent)) { + var type = getTypeOfSymbol(symbol); + var sigs = getSignaturesOfStructuredType(type, 0); + if (!sigs || !sigs.length) { + sigs = getSignaturesOfStructuredType(type, 1); + } + if (sigs && sigs.length) { + var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol); + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + result.target = symbol; + result.originatingImport = referenceParent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + var resolvedModuleType = resolveStructuredTypeMembers(moduleType); + result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo); + return result; + } + } + } } return symbol; } @@ -24267,7 +24342,7 @@ var ts; type = createArrayType(elementType); } else { - var propName = "" + ts.indexOf(pattern.elements, declaration); + var propName = "" + pattern.elements.indexOf(declaration); type = isTupleLikeType(parentType) ? getTypeOfPropertyOfType(parentType, propName) : elementType; @@ -26196,7 +26271,7 @@ var ts; if (node.initializer) { var signatureDeclaration = node.parent; var signature = getSignatureFromDeclaration(signatureDeclaration); - var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); + var parameterIndex = signatureDeclaration.parameters.indexOf(node); ts.Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } @@ -26204,7 +26279,7 @@ var ts; if (iife) { return !node.type && !node.dotDotDotToken && - ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; + node.parent.parameters.indexOf(node) >= iife.arguments.length; } return false; } @@ -27295,7 +27370,7 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.startsWith(prop.escapedName, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 || ts.isKnownSymbol(prop) ? neverType : getLiteralType(ts.symbolName(prop)); } @@ -27344,6 +27419,7 @@ var ts; var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { + markPropertyAsReferenced(prop, accessExpression, accessExpression.expression.kind === 99); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); return unknownType; @@ -27791,7 +27867,7 @@ var ts; return createTypeMapper(sources, undefined); } function createBackreferenceMapper(typeParameters, index) { - return function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; + return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; }; } function isInferenceContext(mapper) { return !!mapper.signature; @@ -28358,10 +28434,22 @@ var ts; } else if (errorInfo) { if (containingMessageChain) { - errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); + var chain_1 = containingMessageChain(); + if (chain_1) { + errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo); + } } diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } + if (headMessage && errorNode && !result && source.symbol) { + var links = getSymbolLinks(source.symbol); + if (links.originatingImport && !ts.isImportCall(links.originatingImport)) { + var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, undefined); + if (helpfulRetry) { + diagnostics.add(ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime)); + } + } + } return result !== 0; function reportError(message, arg0, arg1, arg2) { ts.Debug.assert(!!errorNode); @@ -29259,7 +29347,7 @@ var ts; for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { var t = _a[_i]; if (isUnconstrainedTypeParameter(t)) { - var index = ts.indexOf(typeParameters, t); + var index = typeParameters.indexOf(t); if (index < 0) { index = typeParameters.length; typeParameters.push(t); @@ -30543,7 +30631,7 @@ var ts; parent.parent.kind === 217 && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { - return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); + return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); } function getAssignedTypeOfSpreadExpression(node) { return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); @@ -30582,7 +30670,7 @@ var ts; var type = pattern.kind === 175 ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? - getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : + getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : getTypeOfDestructuredSpreadExpression(parentType); return getTypeWithDefault(type, node.initializer); } @@ -31127,10 +31215,10 @@ var ts; var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 190 && right_1.kind === 9) { + if (left_1.kind === 190 && (right_1.kind === 9 || right_1.kind === 13)) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 190 && left_1.kind === 9) { + if (right_1.kind === 190 && (left_1.kind === 9 || left_1.kind === 13)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -31153,7 +31241,7 @@ var ts; return narrowTypeByInstanceof(type, expr, assumeTrue); case 92: var target = getReferenceCandidate(expr.right); - if (expr.left.kind === 9 && isMatchingReference(reference, target)) { + if ((expr.left.kind === 9 || expr.left.kind === 13) && isMatchingReference(reference, target)) { return narrowByInKeyword(type, expr.left, assumeTrue); } break; @@ -31523,12 +31611,13 @@ var ts; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; + var isSpreadDestructuringAsignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); while (flowContainer !== declarationContainer && (flowContainer.kind === 187 || flowContainer.kind === 188 || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) && (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) { flowContainer = getControlFlowContainer(flowContainer); } - var assumeInitialized = isParameter || isAlias || isOuterVariable || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAsignmentTarget || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1) !== 0 || isInTypeQuery(node) || node.parent.kind === 247) || node.parent.kind === 204 || @@ -31907,7 +31996,7 @@ var ts; if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { var iife = ts.getImmediatelyInvokedFunctionExpression(func); if (iife && iife.arguments) { - var indexOfParameter = ts.indexOf(func.parameters, parameter); + var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { var restTypes = []; for (var i = indexOfParameter; i < iife.arguments.length; i++) { @@ -31928,7 +32017,7 @@ var ts; if (contextualSignature) { var funcHasRestParameters = ts.hasRestParameter(func); var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = ts.indexOf(func.parameters, parameter); + var indexOfParameter = func.parameters.indexOf(parameter); if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { ts.Debug.assert(indexOfParameter !== 0); indexOfParameter -= 1; @@ -32031,7 +32120,7 @@ var ts; } function getContextualTypeForArgument(callTarget, arg) { var args = getEffectiveCallArguments(callTarget); - var argIndex = ts.indexOf(args, arg); + var argIndex = args.indexOf(arg); if (argIndex >= 0) { var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); return getTypeAtPosition(signature, argIndex); @@ -32372,7 +32461,7 @@ var ts; if (patternElement.kind !== 201) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } - elementTypes.push(unknownType); + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); } } } @@ -33226,16 +33315,16 @@ var ts; return propKind !== 152 && propKind !== 151; }); } - function checkNonNullExpression(node) { - return checkNonNullType(checkExpression(node), node); + function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); } - function checkNonNullType(type, errorNode) { + function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 12288; if (kind) { - error(errorNode, kind & 4096 ? kind & 8192 ? - ts.Diagnostics.Object_is_possibly_null_or_undefined : - ts.Diagnostics.Object_is_possibly_undefined : - ts.Diagnostics.Object_is_possibly_null); + error(node, kind & 4096 ? kind & 8192 ? + (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : + (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : + (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); var t = getNonNullableType(type); return t.flags & (12288 | 16384) ? unknownType : t; } @@ -33828,7 +33917,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (!constraint) continue; - var errorInfo = reportErrors && headMessage && ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + var errorInfo = reportErrors && headMessage && (function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }); var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; if (!mapper) { mapper = createTypeMapper(typeParameters, typeArgumentTypes); @@ -34228,7 +34317,7 @@ var ts; } excludeCount--; if (excludeCount > 0) { - excludeArgument[ts.indexOf(excludeArgument, true)] = false; + excludeArgument[excludeArgument.indexOf(true)] = false; } else { excludeArgument = undefined; @@ -34265,7 +34354,7 @@ var ts; } return resolveUntypedCall(node); } - var funcType = checkNonNullExpression(node.expression); + var funcType = checkNonNullExpression(node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -34286,7 +34375,7 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + invocationError(node, apparentType, 0); } return resolveErrorCall(node); } @@ -34340,7 +34429,7 @@ var ts; } return signature; } - error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); + invocationError(node, expressionType, 1); return resolveErrorCall(node); } function isConstructorAccessible(node, signature) { @@ -34378,6 +34467,24 @@ var ts; } return true; } + function invocationError(node, apparentType, kind) { + error(node, kind === 0 + ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures + : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind); + } + function invocationErrorRecovery(apparentType, kind) { + if (!apparentType.symbol) { + return; + } + var importNode = getSymbolLinks(apparentType.symbol).originatingImport; + if (importNode && !ts.isImportCall(importNode)) { + var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); + if (!sigs || !sigs.length) + return; + error(importNode, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime); + } + } function resolveTaggedTemplateExpression(node, candidatesOutArray) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); @@ -34390,7 +34497,7 @@ var ts; return resolveUntypedCall(node); } if (!callSignatures.length) { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + invocationError(node, apparentType, 0); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray); @@ -34432,6 +34539,7 @@ var ts; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + invocationErrorRecovery(apparentType, 0); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray, headMessage); @@ -34598,16 +34706,18 @@ var ts; if (moduleSymbol) { var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, true); if (esModuleSymbol) { - return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol)); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol)); } } return createPromiseReturnType(node, anyType); } - function getTypeWithSyntheticDefaultImportType(type, symbol) { + function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { if (allowSyntheticDefaultImports && type && type !== unknownType) { var synthType = type; if (!synthType.syntheticType) { - if (!getPropertyOfType(type, "default")) { + var file = ts.find(originalSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, false); + if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); var newSymbol = createSymbol(2097152, "default"); newSymbol.target = resolveSymbol(symbol); @@ -34615,7 +34725,7 @@ var ts; var anonymousSymbol = createSymbol(2048, "__type"); var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, undefined, undefined); anonymousSymbol.type = defaultContainingObject; - synthType.syntheticType = getIntersectionType([type, defaultContainingObject]); + synthType.syntheticType = (type.flags & 458752 && type.symbol.flags & (1536 | 3)) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, 0) : defaultContainingObject; } else { synthType.syntheticType = type; @@ -35828,9 +35938,10 @@ var ts; if (isConstEnumObjectType(type)) { var ok = (node.parent.kind === 180 && node.parent.expression === node) || (node.parent.kind === 181 && node.parent.expression === node) || - ((node.kind === 71 || node.kind === 144) && isInRightSideOfImportOrExportAssignment(node)); + ((node.kind === 71 || node.kind === 144) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 163 && node.parent.exprName === node)); if (!ok) { - error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } } return type; @@ -35968,7 +36079,7 @@ var ts; error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); } if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { - if (ts.indexOf(func.parameters, node) !== 0) { + if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } if (func.kind === 153 || func.kind === 157 || func.kind === 162) { @@ -36011,7 +36122,7 @@ var ts; error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { - var leadingError = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); + var leadingError = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, undefined, leadingError); } } @@ -36304,22 +36415,6 @@ var ts; if (!produceDiagnostics) { return; } - function containsSuperCallAsComputedPropertyName(n) { - var name = ts.getNameOfDeclaration(n); - return name && containsSuperCall(name); - } - function containsSuperCall(n) { - if (ts.isSuperCall(n)) { - return true; - } - else if (ts.isFunctionLike(n)) { - return false; - } - else if (ts.isClassLike(n)) { - return ts.forEach(n.members, containsSuperCallAsComputedPropertyName); - } - return ts.forEachChild(n, containsSuperCall); - } function isInstancePropertyWithInitializer(n) { return n.kind === 150 && !ts.hasModifier(n, 32) && @@ -36850,7 +36945,7 @@ var ts; } var promisedType = getPromisedTypeOfPromise(type); if (promisedType) { - if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) { + if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) { if (errorNode) { error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method); } @@ -36956,7 +37051,7 @@ var ts; expectedReturnType = getUnionType([descriptorType, voidType]); break; } - checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); } function markTypeNodeAsReferenced(node) { markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node)); @@ -37269,34 +37364,33 @@ var ts; } function checkUnusedClassMembers(node) { if (compilerOptions.noUnusedLocals && !(node.flags & 2097152)) { - if (node.members) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - switch (member.kind) { - case 152: - case 150: - case 154: - case 155: - if (member.kind === 155 && member.symbol.flags & 32768) { - break; - } - if (!member.symbol.isReferenced && ts.hasModifier(member, 8)) { - error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(member.symbol)); - } + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 152: + case 150: + case 154: + case 155: + if (member.kind === 155 && member.symbol.flags & 32768) { break; - case 153: - for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { - var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8)) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)); - } + } + var symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && ts.hasModifier(member, 8)) { + error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)); + } + break; + case 153: + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8)) { + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)); } - break; - case 158: - break; - default: - ts.Debug.fail(); - } + } + break; + case 158: + break; + default: + ts.Debug.fail(); } } } @@ -38349,7 +38443,10 @@ var ts; } } } - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + } checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); if (baseConstructorType.flags & 1081344 && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); @@ -38375,9 +38472,13 @@ var ts; var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { if (isValidBaseType(t)) { - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, t.symbol && t.symbol.flags & 32 ? + var genericDiag = t.symbol && t.symbol.flags & 32 ? ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : - ts.Diagnostics.Class_0_incorrectly_implements_interface_1); + ts.Diagnostics.Class_0_incorrectly_implements_interface_1; + var baseWithThis = getTypeWithThisArgument(t, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag); + } } else { error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); @@ -38392,6 +38493,32 @@ var ts; checkPropertyInitialization(node); } } + function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { + var issuedMemberError = false; + var _loop_5 = function (member) { + if (ts.hasStaticModifier(member)) { + return "continue"; + } + var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (declaredProp) { + var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); + var baseProp_1 = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp_1) { + var rootChain = function () { return ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(getTypeOfSymbol(baseProp_1))); }; + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp_1), member.name || member, undefined, rootChain)) { + issuedMemberError = true; + } + } + } + }; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + _loop_5(member); + } + if (!issuedMemberError) { + checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); + } + } function checkBaseTypeAccessibility(type, node) { var signatures = getSignaturesOfType(type, 1); if (signatures.length) { @@ -39847,7 +39974,7 @@ var ts; ts.Debug.assert(expr.parent.kind === 178); var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, false, false) || unknownType; - return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || unknownType); } function getPropertySymbolOfDestructuringAssignment(location) { var typeOfObjectLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(location.parent.parent); @@ -40851,6 +40978,13 @@ var ts; return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } if (parameter.type.kind !== 136 && parameter.type.kind !== 133) { + var type = getTypeFromTypeNode(parameter.type); + if (type.flags & 2 || type.flags & 4) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); + } + if (allTypesAssignableToKind(type, 32, true)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); + } return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { @@ -45379,7 +45513,7 @@ var ts; case 216: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 217: - return ts.updateForOf(node, node.awaitModifier, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 218: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); case 219: @@ -46117,6 +46251,7 @@ var ts; var externalHelpersModuleName = ts.getOrCreateExternalHelpersModuleNameIfNeeded(sourceFile, compilerOptions, hasExportStarsToExportValues); var externalHelpersImportDeclaration = externalHelpersModuleName && ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); if (externalHelpersImportDeclaration) { + ts.addEmitFlags(externalHelpersImportDeclaration, 67108864); externalImports.unshift(externalHelpersImportDeclaration); } return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; @@ -49930,7 +50065,7 @@ var ts; } function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { if (extendsClauseElement) { - statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getLocalName(node))), extendsClauseElement)); + statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getInternalName(node))), extendsClauseElement)); } } function addConstructor(statements, node, extendsClauseElement) { @@ -53309,7 +53444,7 @@ var ts; var define = ts.createIdentifier("define"); var moduleName = ts.tryGetModuleNameFromFile(node, host, compilerOptions); var _a = collectAsynchronousDependencies(node, true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createStatement(ts.createCall(define, undefined, (moduleName ? [moduleName] : []).concat([ ts.createArrayLiteral([ ts.createLiteral("require"), @@ -53321,6 +53456,8 @@ var ts; ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) ]))) ]), node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; } function transformUMDModule(node) { var _a = collectAsynchronousDependencies(node, false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames; @@ -53344,7 +53481,7 @@ var ts; ]))) ]))) ], true), undefined)); - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createStatement(ts.createCall(umdHeader, undefined, [ ts.createFunctionExpression(undefined, undefined, undefined, undefined, [ ts.createParameter(undefined, undefined, undefined, "require"), @@ -53352,6 +53489,8 @@ var ts; ].concat(importAliasNames), undefined, transformAsynchronousModuleBody(node)) ])) ]), node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; } function collectAsynchronousDependencies(node, includeNonAmdDependencies) { var aliasedModuleNames = []; @@ -53384,6 +53523,17 @@ var ts; } return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; } + function getAMDImportExpressionForImport(node) { + if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) { + return undefined; + } + var name = ts.getLocalNameForExternalImport(node, currentSourceFile); + var expr = getHelperExpressionForImport(node, name); + if (expr === name) { + return undefined; + } + return ts.createStatement(ts.createAssignment(name, expr)); + } function transformAsynchronousModuleBody(node) { startLexicalEnvironment(); var statements = []; @@ -53392,6 +53542,9 @@ var ts; ts.append(statements, createUnderscoreUnderscoreESModule()); } ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); + if (moduleKind === ts.ModuleKind.AMD) { + ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport)); + } ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); addExportEqualsIfNeeded(statements, true); ts.addRange(statements, endLexicalEnvironment()); @@ -53502,11 +53655,20 @@ var ts; ts.setEmitFlags(func, 8); } } - return ts.createNew(ts.createIdentifier("Promise"), undefined, [func]); + var promise = ts.createNew(ts.createIdentifier("Promise"), undefined, [func]); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), undefined, [ts.getHelperName("__importStar")]); + } + return promise; } function createImportCallExpressionCommonJS(arg, containsLexicalThis) { var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), undefined, []); var requireCall = ts.createCall(ts.createIdentifier("require"), undefined, arg ? [arg] : []); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + requireCall = ts.createCall(ts.getHelperName("__importStar"), undefined, [requireCall]); + } var func; if (languageVersion >= 2) { func = ts.createArrowFunction(undefined, undefined, [], undefined, undefined, requireCall); @@ -53519,6 +53681,20 @@ var ts; } return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), undefined, [func]); } + function getHelperExpressionForImport(node, innerExpr) { + if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864) { + return innerExpr; + } + if (ts.getNamespaceDeclarationNode(node)) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.getHelperName("__importStar"), undefined, [innerExpr]); + } + if (ts.isDefaultImport(node)) { + context.requestEmitHelper(importDefaultHelper); + return ts.createCall(ts.getHelperName("__importDefault"), undefined, [innerExpr]); + } + return innerExpr; + } function visitImportDeclaration(node) { var statements; var namespaceDeclaration = ts.getNamespaceDeclarationNode(node); @@ -53529,10 +53705,10 @@ var ts; else { var variables = []; if (namespaceDeclaration && !ts.isDefaultImport(node)) { - variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, createRequireCall(node))); + variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, getHelperExpressionForImport(node, createRequireCall(node)))); } else { - variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), undefined, createRequireCall(node))); + variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), undefined, getHelperExpressionForImport(node, createRequireCall(node)))); if (namespaceDeclaration && ts.isDefaultImport(node)) { variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), undefined, ts.getGeneratedNameForNode(node))); } @@ -53994,6 +54170,16 @@ var ts; scoped: true, text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" }; + var importStarHelper = { + name: "typescript:commonjsimportstar", + scoped: false, + text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n}" + }; + var importDefaultHelper = { + name: "typescript:commonjsimportdefault", + scoped: false, + text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n}" + }; })(ts || (ts = {})); var ts; (function (ts) { @@ -54848,7 +55034,9 @@ var ts; if (externalHelpersModuleName) { var statements = []; var statementOffset = ts.addPrologue(statements, node.statements); - ts.append(statements, ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText))); + var tslibImport = ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + ts.addEmitFlags(tslibImport, 67108864); + ts.append(statements, tslibImport); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -55243,7 +55431,7 @@ var ts; allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); moduleElementDeclarationEmitInfo = []; } - if (!isBundledEmit && ts.isExternalModule(sourceFile) && sourceFile.moduleAugmentations.length && !resultHasExternalModuleIndicator) { + if (!isBundledEmit && ts.isExternalModule(sourceFile) && !resultHasExternalModuleIndicator) { write("export {};"); writeLine(); } @@ -55654,6 +55842,9 @@ var ts; return tempVarName; } function emitExportAssignment(node) { + if (ts.isSourceFile(node.parent)) { + resultHasExternalModuleIndicator = true; + } if (node.expression.kind === 71) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); @@ -55736,6 +55927,7 @@ var ts; if (node.parent.kind === 269) { var modifiers = ts.getModifierFlags(node); if (modifiers & 1) { + resultHasExternalModuleIndicator = true; write("export "); } if (modifiers & 512) { @@ -55868,6 +56060,7 @@ var ts; writeAsynchronousModuleElements(nodes); } function emitExportDeclaration(node) { + resultHasExternalModuleIndicator = true; emitJsDocComments(node); write("export "); if (node.exportClause) { @@ -57034,7 +57227,7 @@ var ts; currentSourceText = currentSource.text; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSource.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, true); - sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); + sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(source); if (sourceMapSourceIndex === -1) { sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); @@ -61403,6 +61596,7 @@ var ts; && !file.isDeclarationFile) { var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); var importDecl = ts.createImportDeclaration(undefined, undefined, undefined); + ts.addEmitFlags(importDecl, 67108864); externalHelpersModuleReference.parent = importDecl; importDecl.parent = file; imports = [externalHelpersModuleReference]; @@ -61901,12 +62095,12 @@ var ts; if (emitFileName) { var emitFilePath = toPath(emitFileName); if (filesByName.has(emitFilePath)) { - var chain_1; + var chain_2; if (!options.configFilePath) { - chain_1 = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + chain_2 = ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); } - chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); - blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_1)); + chain_2 = ts.chainDiagnosticMessages(chain_2, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_2)); } var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; if (emitFilesSeen.has(emitFileKey)) { @@ -62172,6 +62366,7 @@ var ts; "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", + "esnext.array": "lib.esnext.array.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", "esnext.promise": "lib.esnext.promise.d.ts", }), @@ -62419,6 +62614,13 @@ var ts; category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, + { + name: "esModuleInterop", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports + }, { name: "preserveSymlinks", type: "boolean", @@ -62699,7 +62901,8 @@ var ts; ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, target: 1, - strict: true + strict: true, + esModuleInterop: true }; var optionNameMapCache; function convertEnableAutoDiscoveryToEnable(typeAcquisition) { @@ -63121,7 +63324,7 @@ var ts; function serializeCompilerOptions(options) { var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_5 = function (name) { + var _loop_6 = function (name) { if (ts.hasProperty(options, name)) { if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) { return "continue"; @@ -63145,7 +63348,7 @@ var ts; } }; for (var name in options) { - _loop_5(name); + _loop_6(name); } return result; } @@ -65061,14 +65264,6 @@ var ts; }); } ts.signatureToDisplayParts = signatureToDisplayParts; - function getDeclaredName(typeChecker, symbol, location) { - if (isImportOrExportSpecifierName(location) || ts.isStringOrNumericLiteral(location) && location.parent.kind === 145) { - return ts.getTextOfIdentifierOrLiteral(location); - } - var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); - return typeChecker.symbolToString(localExportDefaultSymbol || symbol); - } - ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && (location.parent.kind === 243 || location.parent.kind === 247) && @@ -65077,12 +65272,16 @@ var ts; ts.isImportOrExportSpecifierName = isImportOrExportSpecifierName; function stripQuotes(name) { var length = name.length; - if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && ts.isSingleOrDoubleQuote(name.charCodeAt(0))) { + if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && startsWithQuote(name)) { return name.substring(1, length - 1); } return name; } ts.stripQuotes = stripQuotes; + function startsWithQuote(name) { + return ts.isSingleOrDoubleQuote(name.charCodeAt(0)); + } + ts.startsWithQuote = startsWithQuote; function scriptKindIs(fileName, host) { var scriptKinds = []; for (var _i = 2; _i < arguments.length; _i++) { @@ -65429,8 +65628,9 @@ var ts; } else { var functionDeclaration = parameter.parent; - var indexOfParameter = ts.indexOf(functionDeclaration.parameters, parameter); - if (indexOfParameter) { + var indexOfParameter = functionDeclaration.parameters.indexOf(parameter); + ts.Debug.assert(indexOfParameter !== -1); + if (indexOfParameter !== 0) { return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]); } else { @@ -66374,11 +66574,11 @@ var ts; (function (Completions) { var PathCompletions; (function (PathCompletions) { - function getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker) { + function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { var literalValue = ts.normalizeSlashes(node.text); var scriptPath = node.getSourceFile().path; var scriptDirectory = ts.getDirectoryPath(scriptPath); - var span = getDirectoryFragmentTextSpan(node.text, node.getStart() + 1); + var span = getDirectoryFragmentTextSpan(node.text, node.getStart(sourceFile) + 1); if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { var extensions = ts.getSupportedExtensions(compilerOptions); if (compilerOptions.rootDirs) { @@ -66463,36 +66663,19 @@ var ts; var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, false, span, host, undefined, result); - var _loop_6 = function (path) { - if (!paths.hasOwnProperty(path)) - return "continue"; - var patterns = paths[path]; - if (!patterns) - return "continue"; - if (path === "*") { - for (var _i = 0, patterns_1 = patterns; _i < patterns_1.length; _i++) { - var pattern = patterns_1[_i]; - var _loop_7 = function (match) { - if (result.some(function (entry) { return entry.name === match; })) - return "continue"; - result.push(createCompletionEntryForModule(match, "external module name", span)); - }; - for (var _a = 0, _b = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host); _a < _b.length; _a++) { - var match = _b[_a]; - _loop_7(match); - } - } - } - else if (ts.startsWith(path, fragment)) { - if (patterns.length === 1) { - if (result.some(function (entry) { return entry.name === path; })) - return "continue"; - result.push(createCompletionEntryForModule(path, "external module name", span)); - } - } - }; for (var path in paths) { - _loop_6(path); + var patterns = paths[path]; + if (paths.hasOwnProperty(path) && patterns) { + var _loop_7 = function (pathCompletion) { + if (!result.some(function (entry) { return entry.name === pathCompletion; })) { + result.push(createCompletionEntryForModule(pathCompletion, "external module name", span)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { + var pathCompletion = _a[_i]; + _loop_7(pathCompletion); + } + } } } if (compilerOptions.moduleResolution === ts.ModuleResolutionKind.NodeJs) { @@ -66504,43 +66687,50 @@ var ts; }); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); - for (var _i = 0, _a = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _i < _a.length; _i++) { - var moduleName = _a[_i]; + for (var _b = 0, _c = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _b < _c.length; _b++) { + var moduleName = _c[_b]; result.push(createCompletionEntryForModule(moduleName, "external module name", span)); } return result; } - function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { - if (host.readDirectory) { - var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; - if (parsed) { - var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); - var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); - var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); - var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); - var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; - var normalizedSuffix = ts.normalizePath(parsed.suffix); - var baseDirectory = ts.combinePaths(baseUrl, expandedPrefixDirectory); - var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; - var includeGlob = normalizedSuffix ? "**/*" : "./*"; - var matches = tryReadDirectory(host, baseDirectory, fileExtensions, undefined, [includeGlob]); - if (matches) { - var result = []; - for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { - var match = matches_1[_i]; - var normalizedMatch = ts.normalizePath(match); - if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { - continue; - } - var start = completePrefix.length; - var length_7 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); - } - return result; - } - } + function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { + if (!ts.endsWith(path, "*")) { + return !ts.stringContains(path, "*") && ts.startsWith(path, fragment) ? [path] : ts.emptyArray; } - return undefined; + var pathPrefix = path.slice(0, path.length - 1); + if (!ts.startsWith(fragment, pathPrefix)) { + return ts.emptyArray; + } + var remainingFragment = fragment.slice(pathPrefix.length); + return ts.flatMap(patterns, function (pattern) { return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); }); + } + function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { + if (!host.readDirectory) { + return undefined; + } + var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; + if (!parsed) { + return undefined; + } + var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); + var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); + var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); + var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); + var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; + var normalizedSuffix = ts.normalizePath(parsed.suffix); + var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); + var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; + var includeGlob = normalizedSuffix ? "**/*" : "./*"; + var matches = tryReadDirectory(host, baseDirectory, fileExtensions, undefined, [includeGlob]); + return ts.mapDefined(matches, function (match) { + var normalizedMatch = ts.normalizePath(match); + if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { + return; + } + var start = completePrefix.length; + var length = normalizedMatch.length - start - normalizedSuffix.length; + return ts.removeFileExtension(normalizedMatch.substr(start, length)); + }); } function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) { var isNestedModule = ts.stringContains(fragment, ts.directorySeparator); @@ -66766,8 +66956,8 @@ var ts; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, options) { if (ts.isInReferenceComment(sourceFile, position)) { - var entries_2 = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); - return entries_2 && pathCompletionsInfo(entries_2); + var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); + return entries && pathCompletionsInfo(entries); } if (ts.isInString(sourceFile, position)) { return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log); @@ -66781,9 +66971,26 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion; - if (sourceFile.languageVariant === 1 && - location && location.parent && location.parent.kind === 253) { + switch (completionData.kind) { + case 0: + return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, options.includeInsertTextCompletions); + case 1: + return jsdocCompletionInfo(ts.JsDoc.getJSDocTagNameCompletions()); + case 2: + return jsdocCompletionInfo(ts.JsDoc.getJSDocTagCompletions()); + case 3: + return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag)); + default: + throw ts.Debug.assertNever(completionData); + } + } + Completions.getCompletionsAtPosition = getCompletionsAtPosition; + function jsdocCompletionInfo(entries) { + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; + } + function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, includeInsertTextCompletions) { + var symbols = completionData.symbols, completionKind = completionData.completionKind, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion; + if (sourceFile.languageVariant === 1 && location && location.parent && ts.isJsxClosingElement(location.parent)) { var tagName = location.parent.parent.openingElement.tagName; return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [{ @@ -66793,45 +67000,42 @@ var ts; sortText: "0", }] }; } - if (request) { - var entries_3 = request.kind === "JsDocTagName" - ? ts.JsDoc.getJSDocTagNameCompletions() - : request.kind === "JsDocTag" - ? ts.JsDoc.getJSDocTagCompletions() - : ts.JsDoc.getJSDocParameterNameCompletions(request.tag); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_3 }; - } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, recommendedCompletion, symbolToOriginInfoMap); getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, true, typeChecker, compilerOptions.target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap); + getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, recommendedCompletion, symbolToOriginInfoMap); } + var isMemberCompletion = isMemberCompletionKind(completionKind); if (keywordFilters !== 0 || !isMemberCompletion) { ts.addRange(entries, getKeywordCompletions(keywordFilters)); } - return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: completionKind === 1, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + } + function isMemberCompletionKind(kind) { + switch (kind) { + case 0: + case 3: + case 2: + return true; + default: + return false; + } } - Completions.getCompletionsAtPosition = getCompletionsAtPosition; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { if (pos === position) { return; } var realName = ts.unescapeLeadingUnderscores(name); - if (uniqueNames.has(realName) || ts.isStringANonContextualKeyword(realName)) { - return; - } - uniqueNames.set(realName, true); - var displayName = getCompletionEntryDisplayName(realName, target, true, false); - if (displayName) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { entries.push({ - name: displayName, + name: realName, kind: "warning", kindModifiers: "", sortText: "1" @@ -66839,18 +67043,27 @@ var ts; } }); } - function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion) { - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin); - if (!displayName) { + function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, includeInsertTextCompletions) { + var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind); + if (!info) { + return undefined; + } + var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; + ts.Debug.assert(!(needsConvertPropertyAccess && !propertyAccessToConvert)); + if (needsConvertPropertyAccess && !includeInsertTextCompletions) { return undefined; } return { - name: displayName, + name: name, kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", source: getSourceFromOrigin(origin), - hasAction: trueOrUndefined(origin !== undefined), + insertText: needsConvertPropertyAccess ? "[\"" + name + "\"]" : undefined, + replacementSpan: needsConvertPropertyAccess + ? ts.createTextSpanFromBounds(ts.findChildOfKind(propertyAccessToConvert, 23, sourceFile).getStart(sourceFile), propertyAccessToConvert.name.end) + : undefined, + hasAction: trueOrUndefined(needsConvertPropertyAccess || origin !== undefined), isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), }; } @@ -66864,13 +67077,13 @@ var ts; function getSourceFromOrigin(origin) { return origin && ts.stripQuotes(origin.moduleSymbol.name); } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap) { + function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, includeInsertTextCompletions, propertyAccessToConvert, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); var uniques = ts.createMap(); for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { var symbol = symbols_4[_i]; var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; - var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion); + var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, includeInsertTextCompletions); if (!entry) { continue; } @@ -66900,21 +67113,21 @@ var ts; if (node.parent.kind === 265 && node.parent.parent.kind === 179 && node.parent.name === node) { - return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, typeChecker, compilerOptions.target, log); + return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, sourceFile, typeChecker, compilerOptions.target, log); } else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { var type = typeChecker.getTypeAtLocation(node.parent.expression); - return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, type, typeChecker, compilerOptions.target, log); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); } else if (node.parent.kind === 239 || node.parent.kind === 245 || ts.isRequireCall(node.parent, false) || ts.isImportCall(node.parent) || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) { - var entries = Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker); + var entries = Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker); return pathCompletionsInfo(entries); } else if (ts.isIndexedAccessTypeNode(node.parent.parent)) { var type = typeChecker.getTypeFromTypeNode(node.parent.parent.objectType); - return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, type, typeChecker, compilerOptions.target, log); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); } else { var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); @@ -66932,11 +67145,11 @@ var ts; entries: entries, }; } - function getStringLiteralCompletionEntriesFromPropertyAssignment(element, typeChecker, target, log) { + function getStringLiteralCompletionEntriesFromPropertyAssignment(element, sourceFile, typeChecker, target, log) { var type = typeChecker.getContextualType(element.parent); var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, false, typeChecker, target, log, true); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, sourceFile, typeChecker, target, log, 4); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -66956,10 +67169,10 @@ var ts; } return undefined; } - function getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(stringLiteralNode, type, typeChecker, target, log) { + function getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(stringLiteralNode, sourceFile, type, typeChecker, target, log) { var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, stringLiteralNode, false, typeChecker, target, log, true); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, stringLiteralNode, sourceFile, typeChecker, target, log, 4); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -67029,20 +67242,19 @@ var ts; } function getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, _a, allSourceFiles) { var name = _a.name, source = _a.source; - var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true }, compilerOptions.target); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true, includeInsertTextCompletions: true }, compilerOptions.target); if (!completionData) { return { type: "none" }; } - var symbols = completionData.symbols, location = completionData.location, allowStringLiteral = completionData.allowStringLiteral, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, request = completionData.request, previousToken = completionData.previousToken; - if (request) { - return { type: "request", request: request }; + if (completionData.kind !== 0) { + return { type: "request", request: completionData }; } - var symbol = ts.find(symbols, function (s) { - var origin = symbolToOriginInfoMap[ts.getSymbolId(s)]; - return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, false, allowStringLiteral, origin) === name - && getSourceFromOrigin(origin) === source; - }); - return symbol ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken } : { type: "none" }; + var symbols = completionData.symbols, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken; + return ts.firstDefined(symbols, function (symbol) { + var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind); + return info && info.name === name && getSourceFromOrigin(origin) === source ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken } : undefined; + }) || { type: "none" }; } function getSymbolName(symbol, origin, target) { return origin && origin.isDefaultExport && symbol.escapedName === "default" @@ -67058,11 +67270,11 @@ var ts; case "request": { var request = symbolCompletion.request; switch (request.kind) { - case "JsDocTagName": + case 1: return ts.JsDoc.getJSDocTagNameCompletionDetails(name); - case "JsDocTag": + case 2: return ts.JsDoc.getJSDocTagCompletionDetails(name); - case "JsDocParameterName": + case 3: return ts.JsDoc.getJSDocParameterNameCompletionDetails(name); default: return ts.Debug.assertNever(request); @@ -67095,9 +67307,11 @@ var ts; Completions.getCompletionEntryDetails = getCompletionEntryDetails; function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - if (!symbolOriginInfo) { - return { codeActions: undefined, sourceDisplay: undefined }; - } + return symbolOriginInfo + ? getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) + : { codeActions: undefined, sourceDisplay: undefined }; + } + function getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { var moduleSymbol = symbolOriginInfo.moduleSymbol, isDefaultExport = symbolOriginInfo.isDefaultExport; var exportedSymbol = ts.skipAlias(symbol.exportSymbol || symbol, checker); var moduleSymbols = getAllReExportingModules(exportedSymbol, checker, allSourceFiles); @@ -67135,6 +67349,22 @@ var ts; return completion.type === "symbol" ? completion.symbol : undefined; } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; + var CompletionDataKind; + (function (CompletionDataKind) { + CompletionDataKind[CompletionDataKind["Data"] = 0] = "Data"; + CompletionDataKind[CompletionDataKind["JsDocTagName"] = 1] = "JsDocTagName"; + CompletionDataKind[CompletionDataKind["JsDocTag"] = 2] = "JsDocTag"; + CompletionDataKind[CompletionDataKind["JsDocParameterName"] = 3] = "JsDocParameterName"; + })(CompletionDataKind || (CompletionDataKind = {})); + var CompletionKind; + (function (CompletionKind) { + CompletionKind[CompletionKind["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration"; + CompletionKind[CompletionKind["Global"] = 1] = "Global"; + CompletionKind[CompletionKind["PropertyAccess"] = 2] = "PropertyAccess"; + CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike"; + CompletionKind[CompletionKind["String"] = 4] = "String"; + CompletionKind[CompletionKind["None"] = 5] = "None"; + })(CompletionKind || (CompletionKind = {})); function getRecommendedCompletion(currentToken, checker) { var ty = getContextualType(currentToken, checker); var symbol = ty && ty.symbol; @@ -67190,7 +67420,6 @@ var ts; return symbol.declarations.some(function (d) { return d.kind === 269; }); } function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, target) { - var request; var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position, false); log("getCompletionData: Get current token: " + (ts.timestamp() - start)); @@ -67201,19 +67430,19 @@ var ts; if (insideComment) { if (ts.hasDocComment(sourceFile, position)) { if (sourceFile.text.charCodeAt(position - 1) === 64) { - request = { kind: "JsDocTagName" }; + return { kind: 1 }; } else { var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); if (!(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/))) { - request = { kind: "JsDocTag" }; + return { kind: 2 }; } } } var tag = getJsDocTagAtPosition(currentToken, position); if (tag) { if (tag.tagName.pos <= position && position <= tag.tagName.end) { - request = { kind: "JsDocTagName" }; + return { kind: 1 }; } if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 271) { currentToken = ts.getTokenAtPosition(sourceFile, position, true); @@ -67225,25 +67454,9 @@ var ts; } } if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { - request = { kind: "JsDocParameterName", tag: tag }; + return { kind: 3, tag: tag }; } } - if (request) { - return { - symbols: ts.emptyArray, - isGlobalCompletion: false, - isMemberCompletion: false, - allowStringLiteral: false, - isNewIdentifierLocation: false, - location: undefined, - isRightOfDot: false, - request: request, - keywordFilters: 0, - symbolToOriginInfoMap: undefined, - recommendedCompletion: undefined, - previousToken: undefined, - }; - } if (!insideJsDocTagTypeExpression) { log("Returning an empty list because completion was inside a regular comment or plain text part of a JsDoc comment."); return undefined; @@ -67259,6 +67472,7 @@ var ts; log("getCompletionData: Get previous token 2: " + (ts.timestamp() - start_4)); } var node = currentToken; + var propertyAccessToConvert; var isRightOfDot = false; var isRightOfOpenTag = false; var isStartingCloseTag = false; @@ -67270,16 +67484,17 @@ var ts; } var parent = contextToken.parent; if (contextToken.kind === 23) { - if (parent.kind === 180) { - node = contextToken.parent.expression; - isRightOfDot = true; - } - else if (parent.kind === 144) { - node = contextToken.parent.left; - isRightOfDot = true; - } - else { - return undefined; + isRightOfDot = true; + switch (parent.kind) { + case 180: + propertyAccessToConvert = parent; + node = propertyAccessToConvert.expression; + break; + case 144: + node = parent.left; + break; + default: + return undefined; } } else if (sourceFile.languageVariant === 1) { @@ -67310,10 +67525,8 @@ var ts; } } var semanticStart = ts.timestamp(); - var isGlobalCompletion = false; - var isMemberCompletion; - var allowStringLiteral = false; - var isNewIdentifierLocation; + var completionKind = 5; + var isNewIdentifierLocation = false; var keywordFilters = 0; var symbols = []; var symbolToOriginInfoMap = []; @@ -67328,8 +67541,7 @@ var ts; else { symbols = tagSymbols; } - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 3; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -67337,8 +67549,7 @@ var ts; if (!typeChecker.isUnknownSymbol(tagSymbol)) { symbols = [tagSymbol]; } - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 3; } else { if (!tryGetGlobalSymbols()) { @@ -67347,7 +67558,7 @@ var ts; } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); var recommendedCompletion = previousToken && getRecommendedCompletion(previousToken, typeChecker); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken }; + return { kind: 0, symbols: symbols, completionKind: completionKind, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 284: @@ -67359,9 +67570,7 @@ var ts; } } function getTypeScriptMemberSymbols() { - isGlobalCompletion = false; - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 2; var isTypeLocation = insideJsDocTagTypeExpression || ts.isPartOfTypeNode(node.parent); var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); if (ts.isEntityName(node)) { @@ -67417,7 +67626,7 @@ var ts; return tryGetImportOrExportClauseCompletionSymbols(namedImportsOrExports); } if (tryGetConstructorLikeCompletionContainer(contextToken)) { - isMemberCompletion = false; + completionKind = 5; isNewIdentifierLocation = true; keywordFilters = 2; return true; @@ -67432,13 +67641,13 @@ var ts; attrsType = typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties); - isMemberCompletion = true; + completionKind = 3; isNewIdentifierLocation = false; return true; } } } - isMemberCompletion = false; + completionKind = 5; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); if (previousToken !== contextToken) { ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); @@ -67447,13 +67656,8 @@ var ts; previousToken.getStart() : position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; - if (scopeNode) { - isGlobalCompletion = - scopeNode.kind === 269 || - scopeNode.kind === 197 || - scopeNode.kind === 260 || - scopeNode.kind === 208 || - ts.isStatement(scopeNode); + if (isGlobalCompletionScope(scopeNode)) { + completionKind = 1; } var symbolMeanings = 793064 | 107455 | 1920 | 2097152; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); @@ -67463,6 +67667,17 @@ var ts; filterGlobalCompletion(symbols); return true; } + function isGlobalCompletionScope(scopeNode) { + switch (scopeNode.kind) { + case 269: + case 197: + case 260: + case 208: + return true; + default: + return ts.isStatement(scopeNode); + } + } function filterGlobalCompletion(symbols) { ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { @@ -67522,7 +67737,8 @@ var ts; ts.codefix.forEachExternalModuleToImportFrom(typeChecker, sourceFile, allSourceFiles, function (moduleSymbol) { for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; - if (symbol.parent !== moduleSymbol || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { + if (symbol.parent !== typeChecker.resolveExternalModuleSymbol(moduleSymbol) + || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { continue; } var isDefaultExport = symbol.name === "default"; @@ -67648,8 +67864,7 @@ var ts; return false; } function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { - isMemberCompletion = true; - allowStringLiteral = true; + completionKind = 0; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 179) { @@ -67697,7 +67912,7 @@ var ts; if (!moduleSpecifier) { return false; } - isMemberCompletion = true; + completionKind = 3; isNewIdentifierLocation = false; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); if (!moduleSpecifierSymbol) { @@ -67709,7 +67924,7 @@ var ts; return true; } function getGetClassLikeCompletionSymbols(classLikeDeclaration) { - isMemberCompletion = true; + completionKind = 3; isNewIdentifierLocation = true; keywordFilters = 1; var baseTypeNode = ts.getClassExtendsHeritageClauseElement(classLikeDeclaration); @@ -68092,32 +68307,30 @@ var ts; return node.getStart() <= position && position <= node.getEnd(); } } - function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin) { + function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind) { var name = getSymbolName(symbol, origin, target); - if (!name) + if (name === undefined + || symbol.flags & 1536 && ts.startsWithQuote(name) + || ts.isKnownSymbol(symbol)) { return undefined; - if (symbol.flags & 1920) { - var firstCharCode = name.charCodeAt(0); - if (ts.isSingleOrDoubleQuote(firstCharCode)) { + } + var validIdentiferResult = { name: name, needsConvertPropertyAccess: false }; + if (ts.isIdentifierText(name, target)) + return validIdentiferResult; + switch (kind) { + case 5: + case 1: + case 3: return undefined; - } + case 0: + return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; + case 2: + return name.charCodeAt(0) === 32 ? undefined : { name: name, needsConvertPropertyAccess: true }; + case 4: + return validIdentiferResult; + default: + ts.Debug.assertNever(kind); } - if (symbol.flags & 106500) { - var escapedName = symbol.escapedName; - if (escapedName.length >= 3 && - escapedName.charCodeAt(0) === 95 && - escapedName.charCodeAt(1) === 95 && - escapedName.charCodeAt(2) === 64) { - return undefined; - } - } - return getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral); - } - function getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral) { - if (performCharacterChecks && !ts.isIdentifierText(name, target)) { - return allowStringLiteral ? JSON.stringify(name) : undefined; - } - return name; } var _keywordCompletions = []; function getKeywordCompletions(keywordFilter) { @@ -68134,6 +68347,8 @@ var ts; return getFilteredKeywordCompletions(isClassMemberCompletionKeywordText); case 2: return getFilteredKeywordCompletions(isConstructorParameterCompletionKeywordText); + default: + ts.Debug.assertNever(keywordFilter); } } function getAllKeywordCompletions() { @@ -68241,10 +68456,7 @@ var ts; (function (DocumentHighlights) { function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { var node = ts.getTouchingWord(sourceFile, position, true); - if (node === sourceFile) - return undefined; - ts.Debug.assert(node.parent !== undefined); - if (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent)) { + if (node.parent && (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent))) { var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; var highlightSpans = [openingElement, closingElement].map(function (_a) { var tagName = _a.tagName; @@ -68252,7 +68464,7 @@ var ts; }); return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; } - return getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); + return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { @@ -68262,8 +68474,8 @@ var ts; kind: "none" }; } - function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { - var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); + function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) { + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } function convertReferencedSymbols(referenceEntries) { @@ -69293,12 +69505,12 @@ var ts; FindAllReferences.findReferencedSymbols = findReferencedSymbols; function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position, false); - var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; - function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { if (node.kind === 269) { return undefined; } @@ -69313,7 +69525,7 @@ var ts; return symbol.valueDeclaration && [nodeEntry(symbol.valueDeclaration)]; } else { - return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { @@ -69321,14 +69533,14 @@ var ts; return ts.map(x, toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; - function getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, options) { + function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position, true); - return FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); + return FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); @@ -69463,10 +69675,11 @@ var ts; (function (FindAllReferences) { var Core; (function (Core) { - function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { + function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - if (node.kind === 269) { - return undefined; + if (ts.isSourceFile(node)) { + var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); + return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles); } if (!options.implementations) { var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); @@ -69477,10 +69690,7 @@ var ts; var checker = program.getTypeChecker(); var symbol = checker.getSymbolAtLocation(node); if (!symbol) { - if (!options.implementations && node.kind === 9) { - return getReferencesForStringLiteral(node, sourceFiles, cancellationToken); - } - return undefined; + return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } if (symbol.flags & 1536 && isModuleReferenceLocation(node)) { return getReferencedSymbolsForModule(program, symbol, sourceFiles); @@ -70571,18 +70781,9 @@ var ts; var GoToDefinition; (function (GoToDefinition) { function getDefinitionAtPosition(program, sourceFile, position) { - var comment = findReferenceInPosition(sourceFile.referencedFiles, position); - if (comment) { - var referenceFile = ts.tryResolveScriptReference(program, sourceFile, comment); - if (referenceFile) { - return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)]; - } - } - var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); - if (typeReferenceDirective) { - var referenceFile = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); - return referenceFile && referenceFile.resolvedFileName && - [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; + var reference = getReferenceAtPosition(sourceFile, position, program); + if (reference) { + return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)]; } var node = ts.getTouchingPropertyName(sourceFile, position, true); if (node === sourceFile) { @@ -70638,6 +70839,21 @@ var ts; return getDefinitionFromSymbol(typeChecker, symbol, node); } GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; + function getReferenceAtPosition(sourceFile, position, program) { + var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); + if (referencePath) { + var file = ts.tryResolveScriptReference(program, sourceFile, referencePath); + return file && { fileName: referencePath.fileName, file: file }; + } + var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + if (typeReferenceDirective) { + var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); + var file = reference && program.getSourceFile(reference.resolvedFileName); + return file && { fileName: typeReferenceDirective.fileName, file: file }; + } + return undefined; + } + GoToDefinition.getReferenceAtPosition = getReferenceAtPosition; function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position, true); if (node === sourceFile) { @@ -70797,6 +71013,7 @@ var ts; } return undefined; } + GoToDefinition.findReferenceInPosition = findReferenceInPosition; function getDefinitionInfoForFileReference(name, targetFileName) { return { fileName: targetFileName, @@ -70929,7 +71146,7 @@ var ts; function forEachUnique(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { - if (ts.indexOf(array, array[i]) === i) { + if (array.indexOf(array[i]) === i) { var result = callback(array[i], i); if (result) { return result; @@ -71393,8 +71610,8 @@ var ts; } function allMatchesAreCaseSensitive(matches) { ts.Debug.assert(matches.length > 0); - for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { - var match = matches_2[_i]; + for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { + var match = matches_1[_i]; if (!match.isCaseSensitive) { return false; } @@ -71456,8 +71673,8 @@ var ts; function bestMatchKind(matches) { ts.Debug.assert(matches.length > 0); var bestMatchKind = ts.PatternMatchKind.camelCase; - for (var _i = 0, matches_3 = matches; _i < matches_3.length; _i++) { - var match = matches_3[_i]; + for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { + var match = matches_2[_i]; var kind = match.kind; if (kind < bestMatchKind) { bestMatchKind = kind; @@ -72922,9 +73139,16 @@ var ts; symbol.parent.flags & 1536) { return undefined; } - var displayName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - return kind ? getRenameInfoSuccess(displayName, typeChecker.getFullyQualifiedName(symbol), kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile) : undefined; + if (!kind) { + return undefined; + } + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 145) + ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) + : undefined; + var displayName = specifierName || typeChecker.symbolToString(symbol); + var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); + return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } } else if (node.kind === 9) { @@ -73382,7 +73606,7 @@ var ts; return nodeModifiers && symbolModifiers ? nodeModifiers + "," + symbolModifiers : nodeModifiers || symbolModifiers; } SymbolDisplay.getSymbolModifiers = getSymbolModifiers; - function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning) { + function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning, alias) { if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } var displayParts = []; var documentation; @@ -73392,6 +73616,7 @@ var ts; var hasAddedSymbolInfo; var isThisExpression = location.kind === 99 && ts.isExpression(location); var type; + var documentationFromAlias; if (symbolKind !== "" || symbolFlags & 32 || symbolFlags & 2097152) { if (symbolKind === "getter" || symbolKind === "setter") { symbolKind = "property"; @@ -73494,6 +73719,7 @@ var ts; } } if (symbolFlags & 32 && !hasAddedSymbolInfo && !isThisExpression) { + addAliasPrefixIfNecessary(); if (ts.getDeclarationOfKind(symbol, 200)) { pushTypePart("local class"); } @@ -73505,14 +73731,14 @@ var ts; writeTypeParametersOfSymbol(symbol, sourceFile); } if ((symbolFlags & 64) && (semanticMeaning & 2)) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(109)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } if (symbolFlags & 524288) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(138)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); @@ -73523,7 +73749,7 @@ var ts; ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 1024)); } if (symbolFlags & 384) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { displayParts.push(ts.keywordPart(76)); displayParts.push(ts.spacePart()); @@ -73533,7 +73759,7 @@ var ts; addFullSymbolName(symbol); } if (symbolFlags & 1536) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); var declaration = ts.getDeclarationOfKind(symbol, 234); var isNamespace = declaration && declaration.name && declaration.name.kind === 71; displayParts.push(ts.keywordPart(isNamespace ? 129 : 128)); @@ -73541,7 +73767,7 @@ var ts; addFullSymbolName(symbol); } if ((symbolFlags & 262144) && (semanticMeaning & 2)) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.punctuationPart(19)); displayParts.push(ts.textPart("type parameter")); displayParts.push(ts.punctuationPart(20)); @@ -73594,7 +73820,23 @@ var ts; } } if (symbolFlags & 2097152) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); + if (!hasAddedSymbolInfo) { + var resolvedSymbol = typeChecker.getAliasedSymbol(symbol); + if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) { + var resolvedNode = resolvedSymbol.declarations[0]; + var declarationName = ts.getNameOfDeclaration(resolvedNode); + if (declarationName) { + var isExternalModuleDeclaration = ts.isModuleWithStringLiteralName(resolvedNode) && + ts.hasModifier(resolvedNode, 2); + var shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; + var resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, resolvedSymbol, ts.getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, semanticMeaning, shouldUseAliasName ? symbol : resolvedSymbol); + displayParts.push.apply(displayParts, resolvedInfo.displayParts); + displayParts.push(ts.lineBreakPart()); + documentationFromAlias = resolvedInfo.documentation; + } + } + } switch (symbol.declarations[0].kind) { case 237: displayParts.push(ts.keywordPart(84)); @@ -73640,7 +73882,7 @@ var ts; if (symbolKind !== "") { if (type) { if (isThisExpression) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(99)); } else { @@ -73703,23 +73945,36 @@ var ts; } } } + if (documentation.length === 0 && documentationFromAlias) { + documentation = documentationFromAlias; + } return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; - function addNewLineIfDisplayPartsExist() { + function prefixNextMeaning() { if (displayParts.length) { displayParts.push(ts.lineBreakPart()); } + addAliasPrefixIfNecessary(); + } + function addAliasPrefixIfNecessary() { + if (alias) { + pushTypePart("alias"); + displayParts.push(ts.spacePart()); + } } function addInPrefix() { displayParts.push(ts.spacePart()); displayParts.push(ts.keywordPart(92)); displayParts.push(ts.spacePart()); } - function addFullSymbolName(symbol, enclosingDeclaration) { - var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, undefined, 1 | 2); + function addFullSymbolName(symbolToDisplay, enclosingDeclaration) { + if (alias && symbolToDisplay === symbol) { + symbolToDisplay = alias; + } + var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, undefined, 1 | 2); ts.addRange(displayParts, fullSymbolDisplayParts); } function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); if (symbolKind) { pushTypePart(symbolKind); if (symbol && !ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) { @@ -74240,7 +74495,7 @@ var ts; var highPriorityCommonRules = [ rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1), rule("IgnoreAfterLineComment", 2, anyToken, formatting.anyContext, 1), - rule("NoSpaceBeforeColon", anyToken, 56, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8), + rule("NotSpaceBeforeColon", anyToken, 56, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 8), rule("SpaceAfterColon", 56, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2), rule("NoSpaceBeforeQuestionMark", anyToken, 55, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8), rule("SpaceAfterQuestionMarkInConditionalOperator", 55, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 2), @@ -74389,6 +74644,8 @@ var ts; rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4, 1), rule("SpaceAfterTypeAssertion", 29, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2), rule("NoSpaceAfterTypeAssertion", 29, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8), + rule("SpaceBeforeTypeAnnotation", anyToken, 56, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 2), + rule("NoSpaceBeforeTypeAnnotation", anyToken, 56, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 8), ]; var lowPriorityCommonRules = [ rule("NoSpaceBeforeSemicolon", anyToken, 25, [isNonJsxSameLineTokenContext], 8), @@ -74477,6 +74734,17 @@ var ts; function isNotBinaryOpContext(context) { return !isBinaryOpContext(context); } + function isNotTypeAnnotationContext(context) { + return !isTypeAnnotationContext(context); + } + function isTypeAnnotationContext(context) { + var contextKind = context.contextNode.kind; + return contextKind === 150 || + contextKind === 149 || + contextKind === 147 || + contextKind === 227 || + ts.isFunctionLikeKind(contextKind); + } function isConditionalOperatorContext(context) { return context.contextNode.kind === 196; } @@ -75884,11 +76152,13 @@ var ts; SmartIndenter.getContainingList = getContainingList; function getActualIndentationForListItem(node, sourceFile, options) { var containingList = getContainingList(node, sourceFile); - return containingList ? getActualIndentationFromList(containingList) : -1; - function getActualIndentationFromList(list) { - var index = ts.indexOf(list, node); - return index !== -1 ? deriveActualIndentationFromList(list, index, sourceFile, options) : -1; + if (containingList) { + var index = containingList.indexOf(node); + if (index !== -1) { + return deriveActualIndentationFromList(containingList, index, sourceFile, options); + } } + return -1; } function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) { if (node.kind === 20) { @@ -77991,6 +78261,9 @@ var ts; return [fromPaths]; } } + if (isPathRelativeToParent(relativeToBaseUrl)) { + return [relativePath]; + } var pathFromSourceToBaseUrl = getRelativePath(baseUrl, sourceDirectory, getCanonicalFileName); var relativeFirst = getRelativePathNParents(pathFromSourceToBaseUrl) < getRelativePathNParents(relativePath); return relativeFirst ? [relativePath, importRelativeToBaseUrl] : [importRelativeToBaseUrl, relativePath]; @@ -78021,10 +78294,11 @@ var ts; return decl.name.text; } } - function tryGetModuleNameFromPaths(relativeNameWithIndex, relativeName, paths) { + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { for (var key in paths) { for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); var indexOfStar = pattern.indexOf("*"); if (indexOfStar === 0 && pattern.length === 1) { continue; @@ -78032,14 +78306,14 @@ var ts; else if (indexOfStar !== -1) { var prefix = pattern.substr(0, indexOfStar); var suffix = pattern.substr(indexOfStar + 1); - if (relativeName.length >= prefix.length + suffix.length && - ts.startsWith(relativeName, prefix) && - ts.endsWith(relativeName, suffix)) { - var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); - return key.replace("\*", matchedStar); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); } } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { return key; } } @@ -78155,7 +78429,10 @@ var ts; return state > 1 ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; } function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { - return ts.firstDefined(rootDirs, function (rootDir) { return getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); }); + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); } function removeExtensionAndIndexPostFix(fileName, options, addJsExtension) { var noExtension = ts.removeFileExtension(fileName); @@ -78167,7 +78444,10 @@ var ts; } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); } function getRelativePath(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, false); @@ -78289,8 +78569,9 @@ var ts; var defaultExport = checker.tryGetMemberInModuleExports("default", moduleSymbol); if (defaultExport) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if ((localSymbol && localSymbol.escapedName === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, context.compilerOptions.target) === symbolName) - && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { + if ((localSymbol && localSymbol.escapedName === symbolName || + getEscapedNameForExportDefault(defaultExport) === symbolName || + moduleSymbolToValidIdentifier(moduleSymbol, context.compilerOptions.target) === symbolName) && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { var symbolId = ts.getUniqueSymbolId(localSymbol || defaultExport, checker); symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 1 }))); } @@ -78300,6 +78581,21 @@ var ts; var symbolId = ts.getUniqueSymbolId(exportSymbolWithIdenticalName, checker); symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 0 }))); } + function getEscapedNameForExportDefault(symbol) { + return ts.firstDefined(symbol.declarations, function (declaration) { + if (ts.isExportAssignment(declaration)) { + if (ts.isIdentifier(declaration.expression)) { + return declaration.expression.escapedText; + } + } + else if (ts.isExportSpecifier(declaration)) { + ts.Debug.assert(declaration.name.escapedText === "default"); + if (declaration.propertyName) { + return declaration.propertyName.escapedText; + } + } + }); + } }); return symbolIdActionMap.getAllActions(); } @@ -79107,6 +79403,83 @@ var ts; })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime.code], + getCodeActions: getActionsForInvalidImport + }); + function getActionsForInvalidImport(context) { + var sourceFile = context.sourceFile; + var node = ts.getTokenAtPosition(sourceFile, context.span.start, false).parent; + if (!ts.isImportDeclaration(node)) { + return []; + } + return getCodeFixesForImportDeclaration(context, node); + } + function getCodeFixesForImportDeclaration(context, node) { + var sourceFile = ts.getSourceFileOfNode(node); + var namespace = ts.getNamespaceDeclarationNode(node); + var opts = context.program.getCompilerOptions(); + var variations = []; + var replacement = ts.createImportDeclaration(undefined, undefined, ts.createImportClause(namespace.name, undefined), node.moduleSpecifier); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, node, replacement, { useNonAdjustedEndPosition: true }); + var changes = changeTracker.getChanges(); + variations.push({ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Replace_import_with_0), [changes[0].textChanges[0].newText]), + changes: changes + }); + if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { + var replacement_1 = ts.createImportEqualsDeclaration(undefined, undefined, namespace.name, ts.createExternalModuleReference(node.moduleSpecifier)); + var changeTracker_1 = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker_1.replaceNode(sourceFile, node, replacement_1, { useNonAdjustedEndPosition: true }); + var changes_1 = changeTracker_1.getChanges(); + variations.push({ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Replace_import_with_0), [changes_1[0].textChanges[0].newText]), + changes: changes_1 + }); + } + return variations; + } + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code, + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature.code, + ], + getCodeActions: getActionsForUsageOfInvalidImport + }); + function getActionsForUsageOfInvalidImport(context) { + var sourceFile = context.sourceFile; + var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 182 : 183; + var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start, false), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); + if (!node) { + return []; + } + var expr = node.expression; + var type = context.program.getTypeChecker().getTypeAtLocation(expr); + if (!(type.symbol && type.symbol.originatingImport)) { + return []; + } + var fixes = []; + var relatedImport = type.symbol.originatingImport; + if (!ts.isImportCall(relatedImport)) { + ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); + } + var propertyAccess = ts.createPropertyAccess(expr, "default"); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, expr, propertyAccess, {}); + var changes = changeTracker.getChanges(); + fixes.push({ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Use_synthetic_default_member), + changes: changes + }); + return fixes; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var refactor; (function (refactor) { @@ -82014,7 +82387,7 @@ var ts; return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } function getCompletionsAtPosition(fileName, position, options) { - if (options === void 0) { options = { includeExternalModuleExports: false }; } + if (options === void 0) { options = { includeExternalModuleExports: false, includeInsertTextCompletions: false }; } synchronizeHostData(); return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles(), options); } @@ -82567,28 +82940,15 @@ var ts; isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } - function isObjectLiteralElement(node) { - switch (node.kind) { - case 257: - case 259: - case 265: - case 266: - case 152: - case 154: - case 155: - return true; - } - return false; - } function getContainingObjectLiteralElement(node) { switch (node.kind) { case 9: case 8: if (node.parent.kind === 145) { - return isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; + return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } case 71: - return isObjectLiteralElement(node.parent) && + return ts.isObjectLiteralElement(node.parent) && (node.parent.parent.kind === 179 || node.parent.parent.kind === 258) && node.parent.name === node ? node.parent : undefined; } @@ -88604,9 +88964,9 @@ var ts; if (simplifiedResult) { return ts.mapDefined(completions && completions.entries, function (entry) { if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { - var name = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended; + var name = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended; var convertedSpan = replacementSpan ? _this.toLocationTextSpan(replacementSpan, scriptInfo) : undefined; - return { name: name, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended }; + return { name: name, kind: kind, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended }; } }).sort(function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); }); } @@ -89132,8 +89492,8 @@ var ts; continue; } for (var i = textChanges_3.length - 1; i >= 0; i--) { - var _b = textChanges_3[i], newText = _b.newText, _c = _b.span, start = _c.start, length_8 = _c.length; - text = text.slice(0, start) + newText + text.slice(start + length_8); + var _b = textChanges_3[i], newText = _b.newText, _c = _b.span, start = _c.start, length_7 = _c.length; + text = text.slice(0, start) + newText + text.slice(start + length_7); } } return text; diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 633c499e985..b0dc9e3b6eb 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -59,6 +59,7 @@ declare namespace ts { pos: number; end: number; } + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.Unknown; enum SyntaxKind { Unknown = 0, EndOfFileToken = 1, @@ -2295,6 +2296,7 @@ declare namespace ts { types?: string[]; /** Paths used to compute primary types search locations */ typeRoots?: string[]; + esModuleInterop?: boolean; [option: string]: CompilerOptionsValue | JsonSourceFile | undefined; } interface TypeAcquisition { @@ -3104,6 +3106,7 @@ declare namespace ts { function isJSDocCommentContainingNode(node: Node): boolean; function isSetAccessor(node: Node): node is SetAccessorDeclaration; function isGetAccessor(node: Node): node is GetAccessorDeclaration; + function isObjectLiteralElement(node: Node): node is ObjectLiteralElement; } declare namespace ts { type ErrorCallback = (message: DiagnosticMessage, length: number) => void; @@ -3126,7 +3129,7 @@ declare namespace ts { scanJsxAttributeValue(): SyntaxKind; reScanJsxToken(): SyntaxKind; scanJsxToken(): SyntaxKind; - scanJSDocToken(): SyntaxKind; + scanJSDocToken(): JsDocSyntaxKind; scan(): SyntaxKind; getText(): string; setText(text: string, start?: number, length?: number): void; @@ -3998,6 +4001,7 @@ declare namespace ts { } interface GetCompletionsAtPositionOptions { includeExternalModuleExports: boolean; + includeInsertTextCompletions: boolean; } interface ApplyCodeActionCommandResult { successMessage: string; @@ -4208,6 +4212,7 @@ declare namespace ts { InsertSpaceBeforeFunctionParenthesis?: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } interface FormatCodeSettings extends EditorSettings { insertSpaceAfterCommaDelimiter?: boolean; @@ -4225,6 +4230,7 @@ declare namespace ts { insertSpaceBeforeFunctionParenthesis?: boolean; placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } interface DefinitionInfo { fileName: string; @@ -4340,6 +4346,7 @@ declare namespace ts { kind: ScriptElementKind; kindModifiers: string; sortText: string; + insertText?: 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. @@ -6103,6 +6110,11 @@ declare namespace ts.server.protocol { * This affects lone identifier completions but not completions on the right hand side of `obj.`. */ includeExternalModuleExports: boolean; + /** + * If enabled, the completion list will include completions with invalid identifier names. + * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. + */ + includeInsertTextCompletions: boolean; } /** * Completions request; value of command field is "completions". @@ -6171,6 +6183,12 @@ declare namespace ts.server.protocol { * is often the same as the name but may be different in certain circumstances. */ sortText: string; + /** + * Text to insert instead of `name`. + * This is used to support bracketed completions; If `name` might be "a-b" but `insertText` would be `["a-b"]`, + * coupled with `replacementSpan` to replace a dotted access with a bracket access. + */ + insertText?: 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. @@ -6844,6 +6862,7 @@ declare namespace ts.server.protocol { insertSpaceBeforeFunctionParenthesis?: boolean; placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } interface CompilerOptions { allowJs?: boolean; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 16140340c54..23dd2e0451f 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -610,9 +610,9 @@ var ts; (function (SymbolFormatFlags) { SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; // Write symbols's type argument if it is instantiated symbol - // eg. class C { p: T } <-- Show p as C.p here + // eg. class C { p: T } <-- Show p as C.p here // var a: C; - // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p + // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; // Use only external alias information to get the symbol name in the given context // eg. module m { export class c { } } import x = m.c; @@ -1258,6 +1258,7 @@ var ts; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; + /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); /** * Used by the checker, this enum keeps track of external emit helpers that should be type @@ -1703,17 +1704,6 @@ var ts; return false; } ts.contains = contains; - function indexOf(array, value) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (array[i] === value) { - return i; - } - } - } - return -1; - } - ts.indexOf = indexOf; function indexOfAnyCharCode(text, charCodes, start) { for (var i = start || 0; i < text.length; i++) { if (contains(charCodes, text.charCodeAt(i))) { @@ -3231,7 +3221,9 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop + ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 + : moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getStrictOptionValue(compilerOptions, flag) { @@ -3291,7 +3283,7 @@ var ts; ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents; function getNormalizedPathComponentsOfUrl(url) { // Get root length of http://www.website.com/folder1/folder2/ - // In this example the root is: http://www.website.com/ + // In this example the root is: http://www.website.com/ // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] var urlLength = url.length; // Initial root length is http:// part @@ -3321,7 +3313,7 @@ var ts; } else { // Can't find the host assume the rest of the string as component - // but make sure we append "/" to it as root is not joined using "/" + // but make sure we append "/" to it as root is not joined using "/" // eg. if url passed in was http://website.com we want to use root as [http://website.com/] // so that other path manipulations will be correct and it can be merged with relative paths correctly return [url + ts.directorySeparator]; @@ -3340,7 +3332,7 @@ var ts; var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name - // that is ["test", "cases", ""] needs to be actually ["test", "cases"] + // that is ["test", "cases", ""] needs to be actually ["test", "cases"] directoryComponents.pop(); } // Find the component that differs @@ -5079,6 +5071,8 @@ var ts; unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), + An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."), + An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5193,6 +5187,7 @@ var ts; Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."), Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), @@ -5247,7 +5242,7 @@ var ts; Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), - const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."), A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), @@ -5414,6 +5409,9 @@ var ts; Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"), + Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), + Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), + Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5728,6 +5726,8 @@ var ts; Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), + A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime: diag(7038, ts.DiagnosticCategory.Error, "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038", "A namespace-style import cannot be called or constructed, and will cause a failure at runtime."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5817,6 +5817,8 @@ var ts; Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), + Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), + Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), }; })(ts || (ts = {})); /// @@ -6571,7 +6573,7 @@ var ts; return node === parent.type; case 182 /* CallExpression */: case 183 /* NewExpression */: - return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; + return ts.contains(parent.typeArguments, node); case 184 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; @@ -7844,6 +7846,10 @@ var ts; return "__@" + symbolName; } ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + function isKnownSymbol(symbol) { + return ts.startsWith(symbol.escapedName, "__@"); + } + ts.isKnownSymbol = isKnownSymbol; /** * Includes the word "Symbol" with unicode escapes */ @@ -9496,8 +9502,8 @@ var ts; // // { // oldStart3: Min(oldStart1, oldStart2), - // oldEnd3 : Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), - // newEnd3 : Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) + // oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), + // newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) // } var oldStart1 = oldStartN; var oldEnd1 = oldEndN; @@ -11319,6 +11325,21 @@ var ts; return hasInitializer(node) && !ts.isForStatement(node) && !ts.isForInStatement(node) && !ts.isForOfStatement(node) && !ts.isJsxAttribute(node); } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; + function isObjectLiteralElement(node) { + switch (node.kind) { + case 257 /* JsxAttribute */: + case 259 /* JsxSpreadAttribute */: + case 265 /* PropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + return true; + default: + return false; + } + } + ts.isObjectLiteralElement = isObjectLiteralElement; })(ts || (ts = {})); /// /// @@ -11465,7 +11486,7 @@ var ts; /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: - Can contain Unicode 3.0.0 categories: + Can contain Unicode 3.0.0 categories: Uppercase letter (Lu), Lowercase letter (Ll), Titlecase letter (Lt), @@ -11473,7 +11494,7 @@ var ts; Other letter (Lo), or Letter number (Nl). IdentifierPart :: = - Can contain IdentifierStart + Unicode 3.0.0 categories: + Can contain IdentifierStart + Unicode 3.0.0 categories: Non-spacing mark (Mn), Combining spacing mark (Mc), Decimal number (Nd), or @@ -11487,7 +11508,7 @@ var ts; /* As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers IdentifierStart :: - Can contain Unicode 6.2 categories: + Can contain Unicode 6.2 categories: Uppercase letter (Lu), Lowercase letter (Ll), Titlecase letter (Lt), @@ -11495,7 +11516,7 @@ var ts; Other letter (Lo), or Letter number (Nl). IdentifierPart :: - Can contain IdentifierStart + Unicode 6.2 categories: + Can contain IdentifierStart + Unicode 6.2 categories: Non-spacing mark (Mn), Combining spacing mark (Mc), Decimal number (Nd), @@ -13051,7 +13072,7 @@ var ts; break; } } - tokenValue += text.substr(firstCharPosition, pos - firstCharPosition); + tokenValue += text.substring(firstCharPosition, pos); } return token; } @@ -13074,6 +13095,7 @@ var ts; startPos = pos; tokenPos = pos; var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 9 /* tab */: case 11 /* verticalTab */: @@ -13084,55 +13106,30 @@ var ts; } return token = 5 /* WhitespaceTrivia */; case 64 /* at */: - pos++; return token = 57 /* AtToken */; case 10 /* lineFeed */: case 13 /* carriageReturn */: - pos++; return token = 4 /* NewLineTrivia */; case 42 /* asterisk */: - pos++; return token = 39 /* AsteriskToken */; case 123 /* openBrace */: - pos++; return token = 17 /* OpenBraceToken */; case 125 /* closeBrace */: - pos++; return token = 18 /* CloseBraceToken */; case 91 /* openBracket */: - pos++; return token = 21 /* OpenBracketToken */; case 93 /* closeBracket */: - pos++; return token = 22 /* CloseBracketToken */; case 60 /* lessThan */: - pos++; return token = 27 /* LessThanToken */; - case 62 /* greaterThan */: - pos++; - return token = 29 /* GreaterThanToken */; case 61 /* equals */: - pos++; return token = 58 /* EqualsToken */; case 44 /* comma */: - pos++; return token = 26 /* CommaToken */; case 46 /* dot */: - pos++; - if (text.substr(tokenPos, pos + 2) === "...") { - pos += 2; - return token = 24 /* DotDotDotToken */; - } return token = 23 /* DotToken */; - case 33 /* exclamation */: - pos++; - return token = 51 /* ExclamationToken */; - case 63 /* question */: - pos++; - return token = 55 /* QuestionToken */; } if (isIdentifierStart(ch, 6 /* Latest */)) { - pos++; while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { pos++; } @@ -13140,7 +13137,7 @@ var ts; return token = 71 /* Identifier */; } else { - return pos += 1, token = 0 /* Unknown */; + return token = 0 /* Unknown */; } } function speculationHelper(callback, isLookahead) { @@ -13796,7 +13793,7 @@ var ts; // 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost // all nodes would need extra state on them to store this info. // - // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 + // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 // grammar specification. // // An important thing about these context concepts. By default they are effectively inherited @@ -14519,9 +14516,13 @@ var ts; return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern(); case 18 /* TypeParameters */: return isIdentifier(); - case 11 /* ArgumentExpressions */: case 15 /* ArrayLiteralMembers */: - return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isStartOfExpression(); + if (token() === 26 /* CommaToken */) { + return true; + } + // falls through + case 11 /* ArgumentExpressions */: + return token() === 24 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: return isStartOfParameter(); case 19 /* TypeArguments */: @@ -14541,7 +14542,7 @@ var ts; function isValidHeritageClauseObjectLiteral() { ts.Debug.assert(token() === 17 /* OpenBraceToken */); if (nextToken() === 18 /* CloseBraceToken */) { - // if we see "extends {}" then only treat the {} as what we're extending (and not + // if we see "extends {}" then only treat the {} as what we're extending (and not // the class body) if we have: // // extends {} { @@ -14625,7 +14626,7 @@ var ts; } function isVariableDeclaratorListTerminator() { // If we can consume a semicolon (either explicitly, or with ASI), then consider us done - // with parsing the list of variable declarators. + // with parsing the list of variable declarators. if (canParseSemicolon()) { return true; } @@ -14730,6 +14731,10 @@ var ts; if (!canReuseNode(node, parsingContext)) { return undefined; } + if (node.jsDocCache) { + // jsDocCache may include tags from parent nodes, which might have been modified. + node.jsDocCache = undefined; + } return node; } function consumeNode(node) { @@ -15238,7 +15243,7 @@ var ts; // // // - // We do *not* want to consume the > as we're consuming the expression for "". + // We do *not* want to consume the `>` as we're consuming the expression for "". node.expression = parseUnaryExpressionOrHigher(); } } @@ -15978,7 +15983,7 @@ var ts; // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression". // // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is - // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done + // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done // with AssignmentExpression if we see one. var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); if (arrowExpression) { @@ -16005,7 +16010,7 @@ var ts; // we're in '2' or '3'. Consume the assignment and return. // // Note: we call reScanGreaterToken so that we get an appropriately merged token - // for cases like > > = becoming >>= + // for cases like `> > =` becoming `>>=` if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); } @@ -16136,7 +16141,7 @@ var ts; var second = nextToken(); if (first === 19 /* OpenParenToken */) { if (second === 20 /* CloseParenToken */) { - // Simple cases: "() =>", "(): ", and "() {". + // Simple cases: "() =>", "(): ", and "() {". // This is an arrow function with no parameters. // The last one is not actually an arrow function, // but this is probably what the user intended. @@ -16337,7 +16342,9 @@ var ts; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); node.colonToken = parseExpectedToken(56 /* ColonToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); - node.whenFalse = parseAssignmentExpressionOrHigher(); + node.whenFalse = ts.nodeIsPresent(node.colonToken) + ? parseAssignmentExpressionOrHigher() + : createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); return finishNode(node); } function parseBinaryExpressionOrHigher(precedence) { @@ -16699,7 +16706,8 @@ var ts; // We don't want to eagerly consume all import keyword as import call expression so we look a head to find "(" // For example: // var foo3 = require("subfolder - // import * as foo1 from "module-from-node -> we want this import to be a statement rather than import call expression + // import * as foo1 from "module-from-node + // We want this import to be a statement rather than import call expression sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; expression = parseTokenNode(); } @@ -16747,7 +16755,7 @@ var ts; // treated as the invocation of "new Foo". We disambiguate that in code (to match // the original grammar) by making sure that if we see an ObjectCreationExpression // we always consume arguments if they are there. So we treat "new Foo()" as an - // object creation only, and not at all as an invocation) Another way to think + // object creation only, and not at all as an invocation. Another way to think // about this is that for every "new" that we see, we will consume an argument list if // it is there as part of the *associated* object creation node. Any additional // argument lists we see, will become invocation expressions. @@ -17111,7 +17119,7 @@ var ts; } var typeArguments = parseDelimitedList(19 /* TypeArguments */, parseType); if (!parseExpected(29 /* GreaterThanToken */)) { - // If it doesn't have the closing > then it's definitely not an type argument list. + // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; } // If we have a '<', then only parse this as a argument list if the type arguments @@ -18025,8 +18033,8 @@ var ts; // off. The grammar would look something like this: // // MemberVariableDeclaration[Yield]: - // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; - // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; + // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; + // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; // // The checker may still error in the static case to explicitly disallow the yield expression. node.initializer = ts.hasModifier(node, 32 /* Static */) @@ -18800,17 +18808,17 @@ var ts; comments.push(text); indent += text.length; } - nextJSDocToken(); - while (token() === 5 /* WhitespaceTrivia */) { - nextJSDocToken(); + var t = nextJSDocToken(); + while (t === 5 /* WhitespaceTrivia */) { + t = nextJSDocToken(); } - if (token() === 4 /* NewLineTrivia */) { + if (t === 4 /* NewLineTrivia */) { state = 0 /* BeginningOfLine */; indent = 0; - nextJSDocToken(); + t = nextJSDocToken(); } - while (token() !== 1 /* EndOfFileToken */) { - switch (token()) { + loop: while (true) { + switch (t) { case 57 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingNewlines(comments); @@ -18864,7 +18872,7 @@ var ts; indent += whitespace.length; break; case 1 /* EndOfFileToken */: - break; + break loop; default: // anything other than whitespace or asterisk at the beginning of the line starts the comment text state = 2 /* SavingComments */; @@ -18872,10 +18880,11 @@ var ts; break; } if (advanceToken) { - nextJSDocToken(); + t = nextJSDocToken(); } else { advanceToken = true; + t = currentToken; } } removeLeadingNewlines(comments); @@ -18974,8 +18983,9 @@ var ts; comments.push(text); indent += text.length; } - while (token() !== 57 /* AtToken */ && token() !== 1 /* EndOfFileToken */) { - switch (token()) { + var tok = token(); + loop: while (true) { + switch (tok) { case 4 /* NewLineTrivia */: if (state >= 1 /* SawAsterisk */) { state = 0 /* BeginningOfLine */; @@ -18984,8 +18994,9 @@ var ts; indent = 0; break; case 57 /* AtToken */: + case 1 /* EndOfFileToken */: // Done - break; + break loop; case 5 /* WhitespaceTrivia */: if (state === 2 /* SavingComments */) { pushComment(scanner.getTokenText()); @@ -19013,11 +19024,7 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (token() === 57 /* AtToken */) { - // Done - break; - } - nextJSDocToken(); + tok = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); @@ -19258,8 +19265,7 @@ var ts; var canParseTag = true; var seenAsterisk = false; while (true) { - nextJSDocToken(); - switch (token()) { + switch (nextJSDocToken()) { case 57 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target); @@ -19523,7 +19529,7 @@ var ts; // We may need to update both the 'pos' and the 'end' of the element. // If the 'pos' is before the start of the change, then we don't need to touch it. // If it isn't, then the 'pos' must be inside the change. How we update it will - // depend if delta is positive or negative. If delta is positive then we have + // depend if delta is positive or negative. If delta is positive then we have // something like: // // -------------------AAA----------------- @@ -19547,7 +19553,7 @@ var ts; element.pos = Math.min(element.pos, changeRangeNewEnd); // If the 'end' is after the change range, then we always adjust it by the delta // amount. However, if the end is in the change range, then how we adjust it - // will depend on if delta is positive or negative. If delta is positive then we + // will depend on if delta is positive or negative. If delta is positive then we // have something like: // // -------------------AAA----------------- @@ -20011,6 +20017,7 @@ var ts; "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", + "esnext.array": "lib.esnext.array.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", "esnext.promise": "lib.esnext.promise.d.ts", }), @@ -20265,6 +20272,13 @@ var ts; category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, + { + name: "esModuleInterop", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports + }, { name: "preserveSymlinks", type: "boolean", @@ -20555,7 +20569,8 @@ var ts; ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, target: 1 /* ES5 */, - strict: true + strict: true, + esModuleInterop: true }; var optionNameMapCache; /* @internal */ @@ -23168,7 +23183,7 @@ var ts; // without names can only come from JSDocFunctionTypes. ts.Debug.assert(node.parent.kind === 277 /* JSDocFunctionType */); var functionType = node.parent; - var index = ts.indexOf(functionType.parameters, node); + var index = functionType.parameters.indexOf(node); return "arg" + index; case 288 /* JSDocTypedefTag */: var name_2 = ts.getNameOfJSDocTypedef(node); @@ -23591,10 +23606,10 @@ var ts; return false; } function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 190 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; + return expr1.kind === 190 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && (expr2.kind === 9 /* StringLiteral */ || expr2.kind === 13 /* NoSubstitutionTemplateLiteral */); } function isNarrowableInOperands(left, right) { - return left.kind === 9 /* StringLiteral */ && isNarrowingExpression(right); + return (left.kind === 9 /* StringLiteral */ || left.kind === 13 /* NoSubstitutionTemplateLiteral */) && isNarrowingExpression(right); } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { @@ -24401,7 +24416,7 @@ var ts; // to the one we would get for: { <...>(...): T } // // We do that by making an anonymous type literal symbol, and then setting the function - // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable + // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable // from an actual type literal symbol you would have gotten had you used the long form. var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); addDeclarationToSymbol(symbol, node, 131072 /* Signature */); @@ -25212,7 +25227,7 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (ts.isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + ts.indexOf(node.parent.parameters, node)); + bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); @@ -26548,6 +26563,7 @@ var ts; }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, getAccessibleSymbolChain: getAccessibleSymbolChain, + resolveExternalModuleSymbol: resolveExternalModuleSymbol, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -27089,7 +27105,7 @@ var ts; return true; } var sourceFiles = host.getSourceFiles(); - return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); + return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); } if (declaration.pos <= usage.pos) { // declaration is before usage @@ -27396,14 +27412,14 @@ var ts; } break; } - if (location.kind !== 208 /* Block */) { + if (isNonBlockLocation(location)) { lastNonBlockLocation = location; } lastLocation = location; location = location.parent; } // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. - // If `result === lastLocation.symbol`, that means that we are somewhere inside `lastLocation` looking up a name, and resolving to `lastLocation` itself. + // If `result === lastNonBlockLocation.symbol`, that means that we are somewhere inside `lastNonBlockLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastNonBlockLocation.symbol) { result.isReferenced = true; @@ -27478,6 +27494,20 @@ var ts; } return result; } + function isNonBlockLocation(_a) { + var kind = _a.kind; + switch (kind) { + case 208 /* Block */: + case 235 /* ModuleBlock */: + case 222 /* SwitchStatement */: + case 236 /* CaseBlock */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + return false; + default: + return true; + } + } function diagnosticName(nameArg) { return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); } @@ -27646,6 +27676,41 @@ var ts; } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); } + function resolveExportByName(moduleSymbol, name, dontResolveAlias) { + var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */); + return exportValue + ? getPropertyOfType(getTypeOfSymbol(exportValue), name) + : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); + } + function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { + if (!allowSyntheticDefaultImports) { + return false; + } + // Declaration files (and ambient modules) + if (!file || file.isDeclarationFile) { + // Definitely cannot have a synthetic default if they have a default member specified + if (resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias)) { + return false; + } + // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member + // So we check a bit more, + if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias)) { + // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code), + // it definitely is a module and does not have a synthetic default + return false; + } + // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set + // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member + // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm + return true; + } + // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement + if (!ts.isSourceFileJavaScript(file)) { + return hasExportAssignmentSymbol(moduleSymbol); + } + // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker + return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias); + } function getTargetOfImportClause(node, dontResolveAlias) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { @@ -27654,15 +27719,15 @@ var ts; exportDefaultSymbol = moduleSymbol; } else { - var exportValue = moduleSymbol.exports.get("export="); - exportDefaultSymbol = exportValue - ? getPropertyOfType(getTypeOfSymbol(exportValue), "default" /* Default */) - : resolveSymbol(moduleSymbol.exports.get("default" /* Default */), dontResolveAlias); + exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias); } - if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { + var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); + if (!exportDefaultSymbol && !hasSyntheticDefault) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } - else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + else if (!exportDefaultSymbol && hasSyntheticDefault) { + // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } return exportDefaultSymbol; @@ -28029,8 +28094,42 @@ var ts; // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable). function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression, dontResolveAlias) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); - if (!dontResolveAlias && symbol && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { - error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + if (!dontResolveAlias && symbol) { + if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { + error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + return symbol; + } + if (compilerOptions.esModuleInterop) { + var referenceParent = moduleReferenceExpression.parent; + if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || + ts.isImportCall(referenceParent)) { + var type = getTypeOfSymbol(symbol); + var sigs = getSignaturesOfStructuredType(type, 0 /* Call */); + if (!sigs || !sigs.length) { + sigs = getSignaturesOfStructuredType(type, 1 /* Construct */); + } + if (sigs && sigs.length) { + var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol); + // Create a new symbol which has the module's type less the call and construct signatures + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + result.target = symbol; + result.originatingImport = referenceParent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above + result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo); + return result; + } + } + } } return symbol; } @@ -30240,7 +30339,7 @@ var ts; } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var propName = "" + ts.indexOf(pattern.elements, declaration); + var propName = "" + pattern.elements.indexOf(declaration); type = isTupleLikeType(parentType) ? getTypeOfPropertyOfType(parentType, propName) : elementType; @@ -32502,7 +32601,7 @@ var ts; if (node.initializer) { var signatureDeclaration = node.parent; var signature = getSignatureFromDeclaration(signatureDeclaration); - var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); + var parameterIndex = signatureDeclaration.parameters.indexOf(node); ts.Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } @@ -32510,7 +32609,7 @@ var ts; if (iife) { return !node.type && !node.dotDotDotToken && - ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; + node.parent.parameters.indexOf(node) >= iife.arguments.length; } return false; } @@ -33725,7 +33824,7 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.escapedName, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.isKnownSymbol(prop) ? neverType : getLiteralType(ts.symbolName(prop)); } @@ -33774,6 +33873,7 @@ var ts; var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { + markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); return unknownType; @@ -34261,7 +34361,7 @@ var ts; * This is used during inference when instantiating type parameter defaults. */ function createBackreferenceMapper(typeParameters, index) { - return function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; + return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; }; } function isInferenceContext(mapper) { return !!mapper.signature; @@ -34926,10 +35026,24 @@ var ts; } else if (errorInfo) { if (containingMessageChain) { - errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); + var chain_1 = containingMessageChain(); + if (chain_1) { + errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo); + } } diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } + // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement + if (headMessage && errorNode && !result && source.symbol) { + var links = getSymbolLinks(source.symbol); + if (links.originatingImport && !ts.isImportCall(links.originatingImport)) { + var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined); + if (helpfulRetry) { + // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import + diagnostics.add(ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime)); + } + } + } return result !== 0 /* False */; function reportError(message, arg0, arg1, arg2) { ts.Debug.assert(!!errorNode); @@ -35986,7 +36100,7 @@ var ts; for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { var t = _a[_i]; if (isUnconstrainedTypeParameter(t)) { - var index = ts.indexOf(typeParameters, t); + var index = typeParameters.indexOf(t); if (index < 0) { index = typeParameters.length; typeParameters.push(t); @@ -37449,7 +37563,7 @@ var ts; parent.parent.kind === 217 /* ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { - return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); + return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); } function getAssignedTypeOfSpreadExpression(node) { return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); @@ -37488,7 +37602,7 @@ var ts; var type = pattern.kind === 175 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? - getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : + getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : getTypeOfDestructuredSpreadExpression(parentType); return getTypeWithDefault(type, node.initializer); } @@ -38040,7 +38154,7 @@ var ts; firstAntecedentType = flowType; } var type = getTypeFromFlowType(flowType); - // If we see a value appear in the cache it is a sign that control flow analysis + // If we see a value appear in the cache it is a sign that control flow analysis // was restarted and completed by checkExpressionCached. We can simply pick up // the resulting type and bail out. var cached_1 = cache.get(key); @@ -38122,10 +38236,10 @@ var ts; var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 190 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { + if (left_1.kind === 190 /* TypeOfExpression */ && (right_1.kind === 9 /* StringLiteral */ || right_1.kind === 13 /* NoSubstitutionTemplateLiteral */)) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 190 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { + if (right_1.kind === 190 /* TypeOfExpression */ && (left_1.kind === 9 /* StringLiteral */ || left_1.kind === 13 /* NoSubstitutionTemplateLiteral */)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -38148,7 +38262,7 @@ var ts; return narrowTypeByInstanceof(type, expr, assumeTrue); case 92 /* InKeyword */: var target = getReferenceCandidate(expr.right); - if (expr.left.kind === 9 /* StringLiteral */ && isMatchingReference(reference, target)) { + if ((expr.left.kind === 9 /* StringLiteral */ || expr.left.kind === 13 /* NoSubstitutionTemplateLiteral */) && isMatchingReference(reference, target)) { return narrowByInKeyword(type, expr.left, assumeTrue); } break; @@ -38575,6 +38689,7 @@ var ts; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; + var isSpreadDestructuringAsignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. @@ -38586,7 +38701,7 @@ var ts; // 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 = isParameter || isAlias || isOuterVariable || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAsignmentTarget || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isInTypeQuery(node) || node.parent.kind === 247 /* ExportSpecifier */) || node.parent.kind === 204 /* NonNullExpression */ || @@ -39101,7 +39216,7 @@ var ts; if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { var iife = ts.getImmediatelyInvokedFunctionExpression(func); if (iife && iife.arguments) { - var indexOfParameter = ts.indexOf(func.parameters, parameter); + var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { var restTypes = []; for (var i = indexOfParameter; i < iife.arguments.length; i++) { @@ -39122,7 +39237,7 @@ var ts; if (contextualSignature) { var funcHasRestParameters = ts.hasRestParameter(func); var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = ts.indexOf(func.parameters, parameter); + var indexOfParameter = func.parameters.indexOf(parameter); if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { ts.Debug.assert(indexOfParameter !== 0); // Otherwise we should not have called `getContextuallyTypedParameterType`. indexOfParameter -= 1; @@ -39239,7 +39354,7 @@ var ts; // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { var args = getEffectiveCallArguments(callTarget); - var argIndex = ts.indexOf(args, arg); + var argIndex = args.indexOf(arg); if (argIndex >= 0) { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. @@ -39662,7 +39777,7 @@ var ts; if (patternElement.kind !== 201 /* OmittedExpression */) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } - elementTypes.push(unknownType); + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); } } } @@ -40791,16 +40906,16 @@ var ts; return propKind !== 152 /* MethodDeclaration */ && propKind !== 151 /* MethodSignature */; }); } - function checkNonNullExpression(node) { - return checkNonNullType(checkExpression(node), node); + function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); } - function checkNonNullType(type, errorNode) { + function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 12288 /* Nullable */; if (kind) { - error(errorNode, kind & 4096 /* Undefined */ ? kind & 8192 /* Null */ ? - ts.Diagnostics.Object_is_possibly_null_or_undefined : - ts.Diagnostics.Object_is_possibly_undefined : - ts.Diagnostics.Object_is_possibly_null); + error(node, kind & 4096 /* Undefined */ ? kind & 8192 /* Null */ ? + (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : + (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : + (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); var t = getNonNullableType(type); return t.flags & (12288 /* Nullable */ | 16384 /* Never */) ? unknownType : t; } @@ -41515,7 +41630,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (!constraint) continue; - var errorInfo = reportErrors && headMessage && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + var errorInfo = reportErrors && headMessage && (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }); var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; if (!mapper) { mapper = createTypeMapper(typeParameters, typeArgumentTypes); @@ -42124,7 +42239,7 @@ var ts; } excludeCount--; if (excludeCount > 0) { - excludeArgument[ts.indexOf(excludeArgument, /*value*/ true)] = false; + excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; } else { excludeArgument = undefined; @@ -42163,7 +42278,7 @@ var ts; } return resolveUntypedCall(node); } - var funcType = checkNonNullExpression(node.expression); + var funcType = checkNonNullExpression(node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -42197,7 +42312,7 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + invocationError(node, apparentType, 0 /* Call */); } return resolveErrorCall(node); } @@ -42278,7 +42393,7 @@ var ts; } return signature; } - error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); + invocationError(node, expressionType, 1 /* Construct */); return resolveErrorCall(node); } function isConstructorAccessible(node, signature) { @@ -42318,6 +42433,26 @@ var ts; } return true; } + function invocationError(node, apparentType, kind) { + error(node, kind === 0 /* Call */ + ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures + : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind); + } + function invocationErrorRecovery(apparentType, kind) { + if (!apparentType.symbol) { + return; + } + var importNode = getSymbolLinks(apparentType.symbol).originatingImport; + // Create a diagnostic on the originating import if possible onto which we can attach a quickfix + // An import call expression cannot be rewritten into another form to correct the error - the only solution is to use `.default` at the use-site + if (importNode && !ts.isImportCall(importNode)) { + var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); + if (!sigs || !sigs.length) + return; + error(importNode, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime); + } + } function resolveTaggedTemplateExpression(node, candidatesOutArray) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); @@ -42331,7 +42466,7 @@ var ts; return resolveUntypedCall(node); } if (!callSignatures.length) { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + invocationError(node, apparentType, 0 /* Call */); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray); @@ -42379,6 +42514,7 @@ var ts; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + invocationErrorRecovery(apparentType, 0 /* Call */); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray, headMessage); @@ -42608,16 +42744,18 @@ var ts; if (moduleSymbol) { var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true); if (esModuleSymbol) { - return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol)); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol)); } } return createPromiseReturnType(node, anyType); } - function getTypeWithSyntheticDefaultImportType(type, symbol) { + function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { if (allowSyntheticDefaultImports && type && type !== unknownType) { var synthType = type; if (!synthType.syntheticType) { - if (!getPropertyOfType(type, "default" /* Default */)) { + var file = ts.find(originalSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false); + if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); newSymbol.target = resolveSymbol(symbol); @@ -42625,7 +42763,7 @@ var ts; var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); anonymousSymbol.type = defaultContainingObject; - synthType.syntheticType = getIntersectionType([type, defaultContainingObject]); + synthType.syntheticType = (type.flags & 458752 /* StructuredType */ && type.symbol.flags & (1536 /* Module */ | 3 /* Variable */)) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*propegatedFlags*/ 0) : defaultContainingObject; } else { synthType.syntheticType = type; @@ -44026,9 +44164,10 @@ var ts; // - target in rhs of import statement var ok = (node.parent.kind === 180 /* PropertyAccessExpression */ && node.parent.expression === node) || (node.parent.kind === 181 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 71 /* Identifier */ || node.kind === 144 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); + ((node.kind === 71 /* Identifier */ || node.kind === 144 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 163 /* TypeQuery */ && node.parent.exprName === node)); if (!ok) { - error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } } return type; @@ -44173,7 +44312,7 @@ var ts; error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); } if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { - if (ts.indexOf(func.parameters, node) !== 0) { + if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } if (func.kind === 153 /* Constructor */ || func.kind === 157 /* ConstructSignature */ || func.kind === 162 /* ConstructorType */) { @@ -44219,7 +44358,7 @@ var ts; error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { - var leadingError = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); + var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, /*headMessage*/ undefined, leadingError); } @@ -44550,22 +44689,6 @@ var ts; if (!produceDiagnostics) { return; } - function containsSuperCallAsComputedPropertyName(n) { - var name = ts.getNameOfDeclaration(n); - return name && containsSuperCall(name); - } - function containsSuperCall(n) { - if (ts.isSuperCall(n)) { - return true; - } - else if (ts.isFunctionLike(n)) { - return false; - } - else if (ts.isClassLike(n)) { - return ts.forEach(n.members, containsSuperCallAsComputedPropertyName); - } - return ts.forEachChild(n, containsSuperCall); - } function isInstancePropertyWithInitializer(n) { return n.kind === 150 /* PropertyDeclaration */ && !ts.hasModifier(n, 32 /* Static */) && @@ -45181,7 +45304,7 @@ var ts; } var promisedType = getPromisedTypeOfPromise(type); if (promisedType) { - if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) { + if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) { // Verify that we don't have a bad actor in the form of a promise whose // promised type is the same as the promise type, or a mutually recursive // promise. If so, we return undefined as we cannot guess the shape. If this @@ -45381,7 +45504,7 @@ var ts; expectedReturnType = getUnionType([descriptorType, voidType]); break; } - checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); } /** * If a TypeNode can be resolved to a value symbol imported from an external module, it is @@ -45738,36 +45861,35 @@ var ts; } function checkUnusedClassMembers(node) { if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { - if (node.members) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - switch (member.kind) { - case 152 /* MethodDeclaration */: - case 150 /* PropertyDeclaration */: - case 154 /* GetAccessor */: - case 155 /* SetAccessor */: - if (member.kind === 155 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { - // Already would have reported an error on the getter. - break; - } - if (!member.symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { - error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(member.symbol)); - } + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 152 /* MethodDeclaration */: + case 150 /* PropertyDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + if (member.kind === 155 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + // Already would have reported an error on the getter. break; - case 153 /* Constructor */: - for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { - var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)); - } + } + var symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { + error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)); + } + break; + case 153 /* Constructor */: + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)); } - break; - case 158 /* IndexSignature */: - // Can't be private - break; - default: - ts.Debug.fail(); - } + } + break; + case 158 /* IndexSignature */: + // Can't be private + break; + default: + ts.Debug.fail(); } } } @@ -46336,7 +46458,7 @@ var ts; // Grammar checking checkGrammarForInOrForOfStatement(node); var rightType = checkNonNullExpression(node.expression); - // TypeScript 1.0 spec (April 2014): 5.4 + // TypeScript 1.0 spec (April 2014): 5.4 // In a 'for-in' statement of the form // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, @@ -47087,7 +47209,10 @@ var ts; } } } - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + } checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); if (baseConstructorType.flags & 1081344 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); @@ -47117,9 +47242,13 @@ var ts; var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { if (isValidBaseType(t)) { - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, t.symbol && t.symbol.flags & 32 /* Class */ ? + var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : - ts.Diagnostics.Class_0_incorrectly_implements_interface_1); + ts.Diagnostics.Class_0_incorrectly_implements_interface_1; + var baseWithThis = getTypeWithThisArgument(t, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag); + } } else { error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); @@ -47134,6 +47263,35 @@ var ts; checkPropertyInitialization(node); } } + function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { + // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible + var issuedMemberError = false; + var _loop_6 = function (member) { + if (ts.hasStaticModifier(member)) { + return "continue"; + } + var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (declaredProp) { + var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); + var baseProp_1 = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp_1) { + var rootChain = function () { return ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(getTypeOfSymbol(baseProp_1))); }; + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp_1), member.name || member, /*message*/ undefined, rootChain)) { + issuedMemberError = true; + } + } + } + }; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + _loop_6(member); + } + if (!issuedMemberError) { + // check again with diagnostics to generate a less-specific error + checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); + } + } function checkBaseTypeAccessibility(type, node) { var signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length) { @@ -48788,7 +48946,7 @@ var ts; // [{ property1: p1, property2 }] = elems; var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; - return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || unknownType); } // Gets the property symbol corresponding to the property in destructuring assignment // 'property1' from @@ -48964,7 +49122,7 @@ var ts; // AND // - binding is not declared in loop, should be renamed to avoid name reuse across siblings // let a, b - // { let x = 1; a = () => x; } + // { let x = 1; a = () => x; } // { let x = 100; b = () => x; } // console.log(a()); // should print '1' // console.log(b()); // should print '100' @@ -49903,6 +50061,13 @@ var ts; return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } if (parameter.type.kind !== 136 /* StringKeyword */ && parameter.type.kind !== 133 /* NumberKeyword */) { + var type = getTypeFromTypeNode(parameter.type); + if (type.flags & 2 /* String */ || type.flags & 4 /* Number */) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); + } + if (allTypesAssignableToKind(type, 32 /* StringLiteral */, /*strict*/ true)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); + } return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { @@ -54042,13 +54207,13 @@ var ts; if (isLeftSideOfBinary) { // No need to parenthesize the left operand when the binary operator is // left associative: - // (a*b)/x -> a*b/x - // (a**b)/x -> a**b/x + // (a*b)/x -> a*b/x + // (a**b)/x -> a**b/x // // Parentheses are needed for the left operand when the binary operator is // right associative: - // (a/b)**x -> (a/b)**x - // (a**b)**x -> (a**b)**x + // (a/b)**x -> (a/b)**x + // (a**b)**x -> (a**b)**x return binaryOperatorAssociativity === 1 /* Right */; } else { @@ -55079,7 +55244,7 @@ var ts; case 216 /* ForInStatement */: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 217 /* ForOfStatement */: - return ts.updateForOf(node, node.awaitModifier, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 218 /* ContinueStatement */: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); case 219 /* BreakStatement */: @@ -55903,6 +56068,7 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); if (externalHelpersImportDeclaration) { + ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */); externalImports.unshift(externalHelpersImportDeclaration); } return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; @@ -56461,7 +56627,7 @@ var ts; */ var classAliases; /** - * Keeps track of whether we are within any containing namespaces when performing + * Keeps track of whether we are within any containing namespaces when performing * just-in-time substitution while printing an expression identifier. */ var applicableSubstitutions; @@ -61468,7 +61634,7 @@ var ts; */ function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { if (extendsClauseElement) { - statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getLocalName(node))), + statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getInternalName(node))), /*location*/ extendsClauseElement)); } } @@ -66456,8 +66622,8 @@ var ts; // `throw` methods that step through the generator when invoked. // // parameters: - // thisArg The value to use as the `this` binding for the transformed generator body. - // body A function that acts as the transformed generator body. + // @param thisArg The value to use as the `this` binding for the transformed generator body. + // @param body A function that acts as the transformed generator body. // // variables: // _ Persistent state for the generator that is shared between the helper and the @@ -66749,7 +66915,7 @@ var ts; // Create an updated SourceFile: // // define(moduleName?, ["module1", "module2"], function ... - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createStatement(ts.createCall(define, /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ // Add the dependency array argument: @@ -66774,6 +66940,8 @@ var ts; ]))) ]), /*location*/ node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; } /** * Transforms a SourceFile into a UMD module. @@ -66824,7 +66992,7 @@ var ts; // define(["require", "exports"], factory); // } // })(function ...) - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createStatement(ts.createCall(umdHeader, /*typeArguments*/ undefined, [ // Add the module body function argument: @@ -66842,6 +67010,8 @@ var ts; ])) ]), /*location*/ node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; } /** * Collect the additional asynchronous dependencies for the module. @@ -66893,6 +67063,17 @@ var ts; } return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; } + function getAMDImportExpressionForImport(node) { + if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) { + return undefined; + } + var name = ts.getLocalNameForExternalImport(node, currentSourceFile); + var expr = getHelperExpressionForImport(node, name); + if (expr === name) { + return undefined; + } + return ts.createStatement(ts.createAssignment(name, expr)); + } /** * Transforms a SourceFile into an AMD or UMD module body. * @@ -66907,6 +67088,9 @@ var ts; } // Visit each statement of the module body. ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); + if (moduleKind === ts.ModuleKind.AMD) { + ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport)); + } ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); // Append the 'export =' statement if provided. addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); @@ -67078,7 +67262,12 @@ var ts; ts.setEmitFlags(func, 8 /* CapturesThis */); } } - return ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); + var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]); + } + return promise; } function createImportCallExpressionCommonJS(arg, containsLexicalThis) { // import("./blah") @@ -67088,6 +67277,10 @@ var ts; // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]); + } var func; if (languageVersion >= 2 /* ES2015 */) { func = ts.createArrowFunction( @@ -67114,6 +67307,20 @@ var ts; } return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); } + function getHelperExpressionForImport(node, innerExpr) { + if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) { + return innerExpr; + } + if (ts.getNamespaceDeclarationNode(node)) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]); + } + if (ts.isDefaultImport(node)) { + context.requestEmitHelper(importDefaultHelper); + return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]); + } + return innerExpr; + } /** * Visits an ImportDeclaration node. * @@ -67132,7 +67339,7 @@ var ts; if (namespaceDeclaration && !ts.isDefaultImport(node)) { // import * as n from "mod"; variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), - /*type*/ undefined, createRequireCall(node))); + /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node)))); } else { // import d from "mod"; @@ -67140,7 +67347,7 @@ var ts; // import d, { x, y } from "mod"; // import d, * as n from "mod"; variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), - /*type*/ undefined, createRequireCall(node))); + /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node)))); if (namespaceDeclaration && ts.isDefaultImport(node)) { variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), /*type*/ undefined, ts.getGeneratedNameForNode(node))); @@ -67873,6 +68080,18 @@ var ts; scoped: true, text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" }; + // emit helper for `import * as Name from "foo"` + var importStarHelper = { + name: "typescript:commonjsimportstar", + scoped: false, + text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n}" + }; + // emit helper for `import Name from "foo"` + var importDefaultHelper = { + name: "typescript:commonjsimportdefault", + scoped: false, + text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n}" + }; })(ts || (ts = {})); /// /// @@ -69313,9 +69532,11 @@ var ts; if (externalHelpersModuleName) { var statements = []; var statementOffset = ts.addPrologue(statements, node.statements); - ts.append(statements, ts.createImportDeclaration( + var tslibImport = ts.createImportDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText))); + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + ts.addEmitFlags(tslibImport, 67108864 /* NeverApplyImportHelper */); + ts.append(statements, tslibImport); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -69830,8 +70051,8 @@ var ts; allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); moduleElementDeclarationEmitInfo = []; } - if (!isBundledEmit && ts.isExternalModule(sourceFile) && sourceFile.moduleAugmentations.length && !resultHasExternalModuleIndicator) { - // if file was external module with augmentations - this fact should be preserved in .d.ts as well. + if (!isBundledEmit && ts.isExternalModule(sourceFile) && !resultHasExternalModuleIndicator) { + // if file was external module this fact should be preserved in .d.ts as well. // in case if we didn't write any external module specifiers in .d.ts we need to emit something // that will force compiler to think that this file is an external module - 'export {}' is a reasonable choice here. write("export {};"); @@ -70269,6 +70490,9 @@ var ts; return tempVarName; } function emitExportAssignment(node) { + if (ts.isSourceFile(node.parent)) { + resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators + } if (node.expression.kind === 71 /* Identifier */) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); @@ -70356,6 +70580,7 @@ var ts; var modifiers = ts.getModifierFlags(node); // If the node is exported if (modifiers & 1 /* Export */) { + resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators write("export "); } if (modifiers & 512 /* Default */) { @@ -70497,6 +70722,7 @@ var ts; writeAsynchronousModuleElements(nodes); } function emitExportDeclaration(node) { + resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators emitJsDocComments(node); write("export "); if (node.exportClause) { @@ -71381,6 +71607,7 @@ var ts; // it allows emitSeparatedList to write separator appropriately) // Example: // original: function foo([, x, ,]) {} + // tslint:disable-next-line no-double-space // emit : function foo([ , x, , ]) {} write(" "); } @@ -71824,7 +72051,7 @@ var ts; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSource.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, /*isAbsolutePathAnUrl*/ true); - sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); + sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(source); if (sourceMapSourceIndex === -1) { sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); @@ -76791,6 +77018,7 @@ var ts; // synthesize 'import "tslib"' declaration var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined); + ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */); externalHelpersModuleReference.parent = importDecl; importDecl.parent = file; imports = [externalHelpersModuleReference]; @@ -77344,13 +77572,13 @@ var ts; var emitFilePath = toPath(emitFileName); // Report error if the output overwrites input file if (filesByName.has(emitFilePath)) { - var chain_1; + var chain_2; if (!options.configFilePath) { // The program is from either an inferred project or an external project - chain_1 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + chain_2 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); } - chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); - blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_1)); + chain_2 = ts.chainDiagnosticMessages(chain_2, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_2)); } var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; // Report error if multiple files write into same file @@ -78912,18 +79140,6 @@ var ts; }); } ts.signatureToDisplayParts = signatureToDisplayParts; - function getDeclaredName(typeChecker, symbol, location) { - // If this is an export or import specifier it could have been renamed using the 'as' syntax. - // If so we want to search for whatever is under the cursor. - if (isImportOrExportSpecifierName(location) || ts.isStringOrNumericLiteral(location) && location.parent.kind === 145 /* ComputedPropertyName */) { - return ts.getTextOfIdentifierOrLiteral(location); - } - // Try to get the local symbol if we're dealing with an 'export default' - // since that symbol has the "true" name. - var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); - return typeChecker.symbolToString(localExportDefaultSymbol || symbol); - } - ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && (location.parent.kind === 243 /* ImportSpecifier */ || location.parent.kind === 247 /* ExportSpecifier */) && @@ -78937,12 +79153,16 @@ var ts; */ function stripQuotes(name) { var length = name.length; - if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && ts.isSingleOrDoubleQuote(name.charCodeAt(0))) { + if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && startsWithQuote(name)) { return name.substring(1, length - 1); } return name; } ts.stripQuotes = stripQuotes; + function startsWithQuote(name) { + return ts.isSingleOrDoubleQuote(name.charCodeAt(0)); + } + ts.startsWithQuote = startsWithQuote; function scriptKindIs(fileName, host) { var scriptKinds = []; for (var _i = 2; _i < arguments.length; _i++) { @@ -79242,8 +79462,8 @@ var ts; return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node); } // Set breakpoint on identifier element of destructuring pattern - // a or ...c or d: x from - // [a, b, ...c] or { a, b } or { d: x } from destructuring pattern + // `a` or `...c` or `d: x` from + // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern if ((node.kind === 71 /* Identifier */ || node.kind === 199 /* SpreadElement */ || node.kind === 265 /* PropertyAssignment */ || @@ -79385,8 +79605,9 @@ var ts; } else { var functionDeclaration = parameter.parent; - var indexOfParameter = ts.indexOf(functionDeclaration.parameters, parameter); - if (indexOfParameter) { + var indexOfParameter = functionDeclaration.parameters.indexOf(parameter); + ts.Debug.assert(indexOfParameter !== -1); + if (indexOfParameter !== 0) { // Not a first parameter, go to previous parameter return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]); } @@ -80397,7 +80618,7 @@ var ts; if (ts.isKeyword(tokenKind)) { return 3 /* keyword */; } - // Special case < and > If they appear in a generic context they are punctuation, + // Special case `<` and `>`: If they appear in a generic context they are punctuation, // not operators. if (tokenKind === 27 /* LessThanToken */ || tokenKind === 29 /* GreaterThanToken */) { // If the node owning the token has a type argument list or type parameter list, then @@ -80507,11 +80728,11 @@ var ts; (function (Completions) { var PathCompletions; (function (PathCompletions) { - function getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker) { + function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { var literalValue = ts.normalizeSlashes(node.text); var scriptPath = node.getSourceFile().path; var scriptDirectory = ts.getDirectoryPath(scriptPath); - var span = getDirectoryFragmentTextSpan(node.text, node.getStart() + 1); + var span = getDirectoryFragmentTextSpan(node.text, node.getStart(sourceFile) + 1); if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { var extensions = ts.getSupportedExtensions(compilerOptions); if (compilerOptions.rootDirs) { @@ -80626,37 +80847,20 @@ var ts; var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, span, host, /*exclude*/ undefined, result); - var _loop_6 = function (path) { - if (!paths.hasOwnProperty(path)) - return "continue"; - var patterns = paths[path]; - if (!patterns) - return "continue"; - if (path === "*") { - for (var _i = 0, patterns_1 = patterns; _i < patterns_1.length; _i++) { - var pattern = patterns_1[_i]; - var _loop_7 = function (match) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (result.some(function (entry) { return entry.name === match; })) - return "continue"; - result.push(createCompletionEntryForModule(match, "external module name" /* externalModuleName */, span)); - }; - for (var _a = 0, _b = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host); _a < _b.length; _a++) { - var match = _b[_a]; - _loop_7(match); - } - } - } - else if (ts.startsWith(path, fragment)) { - if (patterns.length === 1) { - if (result.some(function (entry) { return entry.name === path; })) - return "continue"; - result.push(createCompletionEntryForModule(path, "external module name" /* externalModuleName */, span)); - } - } - }; for (var path in paths) { - _loop_6(path); + var patterns = paths[path]; + if (paths.hasOwnProperty(path) && patterns) { + var _loop_7 = function (pathCompletion) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === pathCompletion; })) { + result.push(createCompletionEntryForModule(pathCompletion, "external module name" /* externalModuleName */, span)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { + var pathCompletion = _a[_i]; + _loop_7(pathCompletion); + } + } } } if (compilerOptions.moduleResolution === ts.ModuleResolutionKind.NodeJs) { @@ -80668,50 +80872,59 @@ var ts; }); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); - for (var _i = 0, _a = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _i < _a.length; _i++) { - var moduleName = _a[_i]; + for (var _b = 0, _c = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _b < _c.length; _b++) { + var moduleName = _c[_b]; result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); } return result; } - function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { - if (host.readDirectory) { - var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; - if (parsed) { - // The prefix has two effective parts: the directory path and the base component after the filepath that is not a - // full directory component. For example: directory/path/of/prefix/base* - var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); - var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); - var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); - var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); - // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call - var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; - var normalizedSuffix = ts.normalizePath(parsed.suffix); - var baseDirectory = ts.combinePaths(baseUrl, expandedPrefixDirectory); - var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; - // If we have a suffix, then we need to read the directory all the way down. We could create a glob - // that encodes the suffix, but we would have to escape the character "?" which readDirectory - // doesn't support. For now, this is safer but slower - var includeGlob = normalizedSuffix ? "**/*" : "./*"; - var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]); - if (matches) { - var result = []; - // Trim away prefix and suffix - for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { - var match = matches_1[_i]; - var normalizedMatch = ts.normalizePath(match); - if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { - continue; - } - var start = completePrefix.length; - var length_7 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); - } - return result; - } - } + function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { + if (!ts.endsWith(path, "*")) { + // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. + return !ts.stringContains(path, "*") && ts.startsWith(path, fragment) ? [path] : ts.emptyArray; } - return undefined; + var pathPrefix = path.slice(0, path.length - 1); + if (!ts.startsWith(fragment, pathPrefix)) { + return ts.emptyArray; + } + var remainingFragment = fragment.slice(pathPrefix.length); + return ts.flatMap(patterns, function (pattern) { return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); }); + } + function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { + if (!host.readDirectory) { + return undefined; + } + var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; + if (!parsed) { + return undefined; + } + // The prefix has two effective parts: the directory path and the base component after the filepath that is not a + // full directory component. For example: directory/path/of/prefix/base* + var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); + var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); + var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); + var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); + // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call + var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; + var normalizedSuffix = ts.normalizePath(parsed.suffix); + // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". + var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); + var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; + // If we have a suffix, then we need to read the directory all the way down. We could create a glob + // that encodes the suffix, but we would have to escape the character "?" which readDirectory + // doesn't support. For now, this is safer but slower + var includeGlob = normalizedSuffix ? "**/*" : "./*"; + var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]); + // Trim away prefix and suffix + return ts.mapDefined(matches, function (match) { + var normalizedMatch = ts.normalizePath(match); + if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { + return; + } + var start = completePrefix.length; + var length = normalizedMatch.length - start - normalizedSuffix.length; + return ts.removeFileExtension(normalizedMatch.substr(start, length)); + }); } function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) { // Check If this is a nested module @@ -80963,8 +81176,8 @@ var ts; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, options) { if (ts.isInReferenceComment(sourceFile, position)) { - var entries_2 = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); - return entries_2 && pathCompletionsInfo(entries_2); + var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); + return entries && pathCompletionsInfo(entries); } if (ts.isInString(sourceFile, position)) { return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log); @@ -80978,13 +81191,33 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion; - if (sourceFile.languageVariant === 1 /* JSX */ && - location && location.parent && location.parent.kind === 253 /* JsxClosingElement */) { + switch (completionData.kind) { + case 0 /* Data */: + return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, options.includeInsertTextCompletions); + case 1 /* JsDocTagName */: + // If the current position is a jsDoc tag name, only tag names should be provided for completion + return jsdocCompletionInfo(ts.JsDoc.getJSDocTagNameCompletions()); + case 2 /* JsDocTag */: + // If the current position is a jsDoc tag, only tags should be provided for completion + return jsdocCompletionInfo(ts.JsDoc.getJSDocTagCompletions()); + case 3 /* JsDocParameterName */: + return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag)); + default: + throw ts.Debug.assertNever(completionData); + } + } + Completions.getCompletionsAtPosition = getCompletionsAtPosition; + function jsdocCompletionInfo(entries) { + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; + } + function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, includeInsertTextCompletions) { + var symbols = completionData.symbols, completionKind = completionData.completionKind, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion; + if (sourceFile.languageVariant === 1 /* JSX */ && location && location.parent && ts.isJsxClosingElement(location.parent)) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. // For example: - // var x =
completion list at "1" will contain "div" with type any + // var x =
+ // The completion list at "1" will contain "div" with type any var tagName = location.parent.parent.openingElement.tagName; return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [{ @@ -80994,37 +81227,37 @@ var ts; sortText: "0", }] }; } - if (request) { - var entries_3 = request.kind === "JsDocTagName" - // If the current position is a jsDoc tag name, only tag names should be provided for completion - ? ts.JsDoc.getJSDocTagNameCompletions() - : request.kind === "JsDocTag" - // If the current position is a jsDoc tag, only tags should be provided for completion - ? ts.JsDoc.getJSDocTagCompletions() - : ts.JsDoc.getJSDocParameterNameCompletions(request.tag); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_3 }; - } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, recommendedCompletion, symbolToOriginInfoMap); getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap); + getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, recommendedCompletion, symbolToOriginInfoMap); } // TODO add filter for keyword based on type/value/namespace and also location // Add all keywords if // - this is not a member completion list (all the keywords) // - other filters are enabled in required scenario so add those keywords + var isMemberCompletion = isMemberCompletionKind(completionKind); if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { ts.addRange(entries, getKeywordCompletions(keywordFilters)); } - return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: completionKind === 1 /* Global */, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + } + function isMemberCompletionKind(kind) { + switch (kind) { + case 0 /* ObjectPropertyDeclaration */: + case 3 /* MemberLike */: + case 2 /* PropertyAccess */: + return true; + default: + return false; + } } - Completions.getCompletionsAtPosition = getCompletionsAtPosition; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location @@ -81032,14 +81265,9 @@ var ts; return; } var realName = ts.unescapeLeadingUnderscores(name); - if (uniqueNames.has(realName) || ts.isStringANonContextualKeyword(realName)) { - return; - } - uniqueNames.set(realName, true); - var displayName = getCompletionEntryDisplayName(realName, target, /*performCharacterChecks*/ true, /*allowStringLiteral*/ false); - if (displayName) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { entries.push({ - name: displayName, + name: realName, kind: "warning" /* warning */, kindModifiers: "", sortText: "1" @@ -81047,12 +81275,14 @@ var ts; } }); } - function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion) { - // Try to get a valid display name for this symbol, if we could not find one, then ignore it. - // We would like to only show things that can be added after a dot, so for instance numeric properties can - // not be accessed with a dot (a.1 <- invalid) - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin); - if (!displayName) { + function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, includeInsertTextCompletions) { + var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind); + if (!info) { + return undefined; + } + var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; + ts.Debug.assert(!(needsConvertPropertyAccess && !propertyAccessToConvert)); + if (needsConvertPropertyAccess && !includeInsertTextCompletions) { return undefined; } // TODO(drosen): Right now we just permit *all* semantic meanings when calling @@ -81063,12 +81293,17 @@ var ts; // Use a 'sortText' of 0' so that all symbol completion entries come before any other // entries (like JavaScript identifier entries). return { - name: displayName, + name: name, kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", source: getSourceFromOrigin(origin), - hasAction: trueOrUndefined(origin !== undefined), + // TODO: GH#20619 Use configured quote style + insertText: needsConvertPropertyAccess ? "[\"" + name + "\"]" : undefined, + replacementSpan: needsConvertPropertyAccess + ? ts.createTextSpanFromBounds(ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile).getStart(sourceFile), propertyAccessToConvert.name.end) + : undefined, + hasAction: trueOrUndefined(needsConvertPropertyAccess || origin !== undefined), isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), }; } @@ -81082,7 +81317,7 @@ var ts; function getSourceFromOrigin(origin) { return origin && ts.stripQuotes(origin.moduleSymbol.name); } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap) { + function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, includeInsertTextCompletions, propertyAccessToConvert, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); // Tracks unique names. // We don't set this for global variables or completions from external module exports, because we can have multiple of those. @@ -81092,7 +81327,7 @@ var ts; for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { var symbol = symbols_4[_i]; var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; - var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion); + var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, includeInsertTextCompletions); if (!entry) { continue; } @@ -81135,7 +81370,7 @@ var ts; // foo({ // '/*completion position*/' // }); - return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, typeChecker, compilerOptions.target, log); + return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, sourceFile, typeChecker, compilerOptions.target, log); } else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { // Get all names of properties on the expression @@ -81145,7 +81380,7 @@ var ts; // let a: A; // a['/*completion position*/'] var type = typeChecker.getTypeAtLocation(node.parent.expression); - return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, type, typeChecker, compilerOptions.target, log); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); } else if (node.parent.kind === 239 /* ImportDeclaration */ || node.parent.kind === 245 /* ExportDeclaration */ || ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent) @@ -81156,7 +81391,7 @@ var ts; // import x = require("/*completion position*/"); // var y = require("/*completion position*/"); // export * from "/*completion position*/"; - var entries = Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker); + var entries = Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker); return pathCompletionsInfo(entries); } else if (ts.isIndexedAccessTypeNode(node.parent.parent)) { @@ -81167,7 +81402,7 @@ var ts; // } // let x: Foo["/*completion position*/"] var type = typeChecker.getTypeFromTypeNode(node.parent.parent.objectType); - return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, type, typeChecker, compilerOptions.target, log); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); } else { var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); @@ -81193,11 +81428,11 @@ var ts; entries: entries, }; } - function getStringLiteralCompletionEntriesFromPropertyAssignment(element, typeChecker, target, log) { + function getStringLiteralCompletionEntriesFromPropertyAssignment(element, sourceFile, typeChecker, target, log) { var type = typeChecker.getContextualType(element.parent); var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false, typeChecker, target, log, /*allowStringLiteral*/ true); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, sourceFile, typeChecker, target, log, 4 /* String */); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -81217,10 +81452,10 @@ var ts; } return undefined; } - function getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(stringLiteralNode, type, typeChecker, target, log) { + function getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(stringLiteralNode, sourceFile, type, typeChecker, target, log) { var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, stringLiteralNode, /*performCharacterChecks*/ false, typeChecker, target, log, /*allowStringLiteral*/ true); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, stringLiteralNode, sourceFile, typeChecker, target, log, 4 /* String */); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -81290,24 +81525,23 @@ var ts; } function getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, _a, allSourceFiles) { var name = _a.name, source = _a.source; - var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true }, compilerOptions.target); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true, includeInsertTextCompletions: true }, compilerOptions.target); if (!completionData) { return { type: "none" }; } - var symbols = completionData.symbols, location = completionData.location, allowStringLiteral = completionData.allowStringLiteral, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, request = completionData.request, previousToken = completionData.previousToken; - if (request) { - return { type: "request", request: request }; + if (completionData.kind !== 0 /* Data */) { + return { type: "request", request: completionData }; } + var symbols = completionData.symbols, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken; // Find the symbol with the matching entry name. // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - var symbol = ts.find(symbols, function (s) { - var origin = symbolToOriginInfoMap[ts.getSymbolId(s)]; - return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral, origin) === name - && getSourceFromOrigin(origin) === source; - }); - return symbol ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken } : { type: "none" }; + return ts.firstDefined(symbols, function (symbol) { + var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind); + return info && info.name === name && getSourceFromOrigin(origin) === source ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken } : undefined; + }) || { type: "none" }; } function getSymbolName(symbol, origin, target) { return origin && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ @@ -81325,11 +81559,11 @@ var ts; case "request": { var request = symbolCompletion.request; switch (request.kind) { - case "JsDocTagName": + case 1 /* JsDocTagName */: return ts.JsDoc.getJSDocTagNameCompletionDetails(name); - case "JsDocTag": + case 2 /* JsDocTag */: return ts.JsDoc.getJSDocTagCompletionDetails(name); - case "JsDocParameterName": + case 3 /* JsDocParameterName */: return ts.JsDoc.getJSDocParameterNameCompletionDetails(name); default: return ts.Debug.assertNever(request); @@ -81363,9 +81597,11 @@ var ts; Completions.getCompletionEntryDetails = getCompletionEntryDetails; function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - if (!symbolOriginInfo) { - return { codeActions: undefined, sourceDisplay: undefined }; - } + return symbolOriginInfo + ? getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) + : { codeActions: undefined, sourceDisplay: undefined }; + } + function getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { var moduleSymbol = symbolOriginInfo.moduleSymbol, isDefaultExport = symbolOriginInfo.isDefaultExport; var exportedSymbol = ts.skipAlias(symbol.exportSymbol || symbol, checker); var moduleSymbols = getAllReExportingModules(exportedSymbol, checker, allSourceFiles); @@ -81403,6 +81639,22 @@ var ts; return completion.type === "symbol" ? completion.symbol : undefined; } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; + var CompletionDataKind; + (function (CompletionDataKind) { + CompletionDataKind[CompletionDataKind["Data"] = 0] = "Data"; + CompletionDataKind[CompletionDataKind["JsDocTagName"] = 1] = "JsDocTagName"; + CompletionDataKind[CompletionDataKind["JsDocTag"] = 2] = "JsDocTag"; + CompletionDataKind[CompletionDataKind["JsDocParameterName"] = 3] = "JsDocParameterName"; + })(CompletionDataKind || (CompletionDataKind = {})); + var CompletionKind; + (function (CompletionKind) { + CompletionKind[CompletionKind["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration"; + CompletionKind[CompletionKind["Global"] = 1] = "Global"; + CompletionKind[CompletionKind["PropertyAccess"] = 2] = "PropertyAccess"; + CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike"; + CompletionKind[CompletionKind["String"] = 4] = "String"; + CompletionKind[CompletionKind["None"] = 5] = "None"; + })(CompletionKind || (CompletionKind = {})); function getRecommendedCompletion(currentToken, checker) { var ty = getContextualType(currentToken, checker); var symbol = ty && ty.symbol; @@ -81460,7 +81712,6 @@ var ts; return symbol.declarations.some(function (d) { return d.kind === 269 /* SourceFile */; }); } function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, target) { - var request; var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) @@ -81475,7 +81726,7 @@ var ts; if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { // The current position is next to the '@' sign, when no tag name being provided yet. // Provide a full list of tag names - request = { kind: "JsDocTagName" }; + return { kind: 1 /* JsDocTagName */ }; } else { // When completion is requested without "@", we will have check to make sure that @@ -81496,7 +81747,7 @@ var ts; // */ var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); if (!(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/))) { - request = { kind: "JsDocTag" }; + return { kind: 2 /* JsDocTag */ }; } } } @@ -81506,7 +81757,7 @@ var ts; var tag = getJsDocTagAtPosition(currentToken, position); if (tag) { if (tag.tagName.pos <= position && position <= tag.tagName.end) { - request = { kind: "JsDocTagName" }; + return { kind: 1 /* JsDocTagName */ }; } if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 271 /* JSDocTypeExpression */) { currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true); @@ -81519,25 +81770,9 @@ var ts; } } if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { - request = { kind: "JsDocParameterName", tag: tag }; + return { kind: 3 /* JsDocParameterName */, tag: tag }; } } - if (request) { - return { - symbols: ts.emptyArray, - isGlobalCompletion: false, - isMemberCompletion: false, - allowStringLiteral: false, - isNewIdentifierLocation: false, - location: undefined, - isRightOfDot: false, - request: request, - keywordFilters: 0 /* None */, - symbolToOriginInfoMap: undefined, - recommendedCompletion: undefined, - previousToken: undefined, - }; - } if (!insideJsDocTagTypeExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal // comment or the plain text part of a jsDoc comment, so no completion should be available @@ -81562,6 +81797,7 @@ var ts; // Also determine whether we are trying to complete with members of that node // or attributes of a JSX tag. var node = currentToken; + var propertyAccessToConvert; var isRightOfDot = false; var isRightOfOpenTag = false; var isStartingCloseTag = false; @@ -81574,18 +81810,19 @@ var ts; } var parent = contextToken.parent; if (contextToken.kind === 23 /* DotToken */) { - if (parent.kind === 180 /* PropertyAccessExpression */) { - node = contextToken.parent.expression; - isRightOfDot = true; - } - else if (parent.kind === 144 /* QualifiedName */) { - node = contextToken.parent.left; - isRightOfDot = true; - } - else { - // There is nothing that precedes the dot, so this likely just a stray character - // or leading into a '...' token. Just bail out instead. - return undefined; + isRightOfDot = true; + switch (parent.kind) { + case 180 /* PropertyAccessExpression */: + propertyAccessToConvert = parent; + node = propertyAccessToConvert.expression; + break; + case 144 /* QualifiedName */: + node = parent.left; + break; + default: + // There is nothing that precedes the dot, so this likely just a stray character + // or leading into a '...' token. Just bail out instead. + return undefined; } } else if (sourceFile.languageVariant === 1 /* JSX */) { @@ -81621,10 +81858,8 @@ var ts; } } var semanticStart = ts.timestamp(); - var isGlobalCompletion = false; - var isMemberCompletion; - var allowStringLiteral = false; - var isNewIdentifierLocation; + var completionKind = 5 /* None */; + var isNewIdentifierLocation = false; var keywordFilters = 0 /* None */; var symbols = []; var symbolToOriginInfoMap = []; @@ -81639,8 +81874,7 @@ var ts; else { symbols = tagSymbols; } - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 3 /* MemberLike */; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -81648,8 +81882,7 @@ var ts; if (!typeChecker.isUnknownSymbol(tagSymbol)) { symbols = [tagSymbol]; } - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 3 /* MemberLike */; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -81661,7 +81894,7 @@ var ts; } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); var recommendedCompletion = previousToken && getRecommendedCompletion(previousToken, typeChecker); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken }; + return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 284 /* JSDocParameterTag */: @@ -81674,9 +81907,7 @@ var ts; } function getTypeScriptMemberSymbols() { // Right of dot member completion list - isGlobalCompletion = false; - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 2 /* PropertyAccess */; // Since this is qualified name check its a type node location var isTypeLocation = insideJsDocTagTypeExpression || ts.isPartOfTypeNode(node.parent); var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); @@ -81744,7 +81975,7 @@ var ts; } if (tryGetConstructorLikeCompletionContainer(contextToken)) { // no members, only keywords - isMemberCompletion = false; + completionKind = 5 /* None */; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter @@ -81763,14 +81994,14 @@ var ts; attrsType = typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties); - isMemberCompletion = true; + completionKind = 3 /* MemberLike */; isNewIdentifierLocation = false; return true; } } } // Get all entities in the current scope. - isMemberCompletion = false; + completionKind = 5 /* None */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); if (previousToken !== contextToken) { ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); @@ -81804,13 +82035,8 @@ var ts; previousToken.getStart() : position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; - if (scopeNode) { - isGlobalCompletion = - scopeNode.kind === 269 /* SourceFile */ || - scopeNode.kind === 197 /* TemplateExpression */ || - scopeNode.kind === 260 /* JsxExpression */ || - scopeNode.kind === 208 /* Block */ || // Some blocks aren't statements, but all get global completions - ts.isStatement(scopeNode); + if (isGlobalCompletionScope(scopeNode)) { + completionKind = 1 /* Global */; } var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); @@ -81820,6 +82046,17 @@ var ts; filterGlobalCompletion(symbols); return true; } + function isGlobalCompletionScope(scopeNode) { + switch (scopeNode.kind) { + case 269 /* SourceFile */: + case 197 /* TemplateExpression */: + case 260 /* JsxExpression */: + case 208 /* Block */: + return true; + default: + return ts.isStatement(scopeNode); + } + } function filterGlobalCompletion(symbols) { ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { @@ -81888,9 +82125,10 @@ var ts; for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; // Don't add a completion for a re-export, only for the original. - // If `symbol.parent !== moduleSymbol`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. + // If `symbol.parent !== ...`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. // If `some(...)`, this comes from an `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). - if (symbol.parent !== moduleSymbol || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { + if (symbol.parent !== typeChecker.resolveExternalModuleSymbol(moduleSymbol) + || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { continue; } var isDefaultExport = symbol.name === "default" /* Default */; @@ -82038,8 +82276,7 @@ var ts; */ function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { // We're looking up possible property names from contextual/inferred/declared type. - isMemberCompletion = true; - allowStringLiteral = true; + completionKind = 0 /* ObjectPropertyDeclaration */; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 179 /* ObjectLiteralExpression */) { @@ -82112,7 +82349,7 @@ var ts; if (!moduleSpecifier) { return false; } - isMemberCompletion = true; + completionKind = 3 /* MemberLike */; isNewIdentifierLocation = false; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); if (!moduleSpecifierSymbol) { @@ -82129,7 +82366,7 @@ var ts; */ function getGetClassLikeCompletionSymbols(classLikeDeclaration) { // We're looking up possible property names from parent type. - isMemberCompletion = true; + completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for class elements @@ -82611,51 +82848,35 @@ var ts; return node.getStart() <= position && position <= node.getEnd(); } } - /** - * Get the name to be display in completion from a given symbol. - * - * @return undefined if the name is of external module - */ - function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin) { + function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind) { var name = getSymbolName(symbol, origin, target); - if (!name) + if (name === undefined + // If the symbol is external module, don't show it in the completion list + // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) + || symbol.flags & 1536 /* Module */ && ts.startsWithQuote(name) + // If the symbol is the internal name of an ES symbol, it is not a valid entry. Internal names for ES symbols start with "__@" + || ts.isKnownSymbol(symbol)) { return undefined; - // First check of the displayName is not external module; if it is an external module, it is not valid entry - if (symbol.flags & 1920 /* Namespace */) { - var firstCharCode = name.charCodeAt(0); - if (ts.isSingleOrDoubleQuote(firstCharCode)) { - // If the symbol is external module, don't show it in the completion list - // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) + } + var validIdentiferResult = { name: name, needsConvertPropertyAccess: false }; + if (ts.isIdentifierText(name, target)) + return validIdentiferResult; + switch (kind) { + case 5 /* None */: + case 1 /* Global */: + case 3 /* MemberLike */: return undefined; - } + case 0 /* ObjectPropertyDeclaration */: + // TODO: GH#18169 + return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; + case 2 /* PropertyAccess */: + // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547 + return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true }; + case 4 /* String */: + return validIdentiferResult; + default: + ts.Debug.assertNever(kind); } - // If the symbol is for a member of an object type and is the internal name of an ES - // symbol, it is not a valid entry. Internal names for ES symbols start with "__@" - if (symbol.flags & 106500 /* ClassMember */) { - var escapedName = symbol.escapedName; - if (escapedName.length >= 3 && - escapedName.charCodeAt(0) === 95 /* _ */ && - escapedName.charCodeAt(1) === 95 /* _ */ && - escapedName.charCodeAt(2) === 64 /* at */) { - return undefined; - } - } - return getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral); - } - /** - * Get a displayName from a given for completion list, performing any necessary quotes stripping - * and checking whether the name is valid identifier name. - */ - function getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral) { - // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an - // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. - // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. - // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. - if (performCharacterChecks && !ts.isIdentifierText(name, target)) { - // TODO: GH#18169 - return allowStringLiteral ? JSON.stringify(name) : undefined; - } - return name; } // A cache of completion entries for keywords, these do not change between sessions var _keywordCompletions = []; @@ -82673,6 +82894,8 @@ var ts; return getFilteredKeywordCompletions(isClassMemberCompletionKeywordText); case 2 /* ConstructorParameterKeywords */: return getFilteredKeywordCompletions(isConstructorParameterCompletionKeywordText); + default: + ts.Debug.assertNever(keywordFilter); } } function getAllKeywordCompletions() { @@ -82789,11 +83012,7 @@ var ts; (function (DocumentHighlights) { function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); - // Note that getTouchingWord indicates failure by returning the sourceFile node. - if (node === sourceFile) - return undefined; - ts.Debug.assert(node.parent !== undefined); - if (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent)) { + if (node.parent && (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent))) { // For a JSX element, just highlight the matching tag, not all references. var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; var highlightSpans = [openingElement, closingElement].map(function (_a) { @@ -82802,7 +83021,7 @@ var ts; }); return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; } - return getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); + return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { @@ -82812,8 +83031,8 @@ var ts; kind: "none" /* none */ }; } - function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { - var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); + function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) { + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } function convertReferencedSymbols(referenceEntries) { @@ -83896,7 +84115,7 @@ var ts; } /** If at an export specifier, go to the symbol it refers to. */ function skipExportSpecifierSymbol(symbol, checker) { - // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. + // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. if (symbol.declarations) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; @@ -83953,12 +84172,12 @@ var ts; function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { // A node in a JSDoc comment can't have an implementation anyway. var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); - var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; - function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { if (node.kind === 269 /* SourceFile */) { return undefined; } @@ -83978,7 +84197,7 @@ var ts; } else { // Perform "Find all References" and retrieve only those that are implementations - return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { @@ -83986,14 +84205,14 @@ var ts; return ts.map(x, toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; - function getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, options) { + function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); - return FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); + return FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); @@ -84132,10 +84351,11 @@ var ts; var Core; (function (Core) { /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ - function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { + function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - if (node.kind === 269 /* SourceFile */) { - return undefined; + if (ts.isSourceFile(node)) { + var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); + return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles); } if (!options.implementations) { var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); @@ -84148,11 +84368,7 @@ var ts; // Could not find a symbol e.g. unknown identifier if (!symbol) { // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. - if (!options.implementations && node.kind === 9 /* StringLiteral */) { - return getReferencesForStringLiteral(node, sourceFiles, cancellationToken); - } - // Can't have references to something that we have no symbol for. - return undefined; + return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) { return getReferencedSymbolsForModule(program, symbol, sourceFiles); @@ -84347,6 +84563,9 @@ var ts; State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { if (searchOptions === void 0) { searchOptions = {}; } // Note: if this is an external module symbol, the name doesn't include quotes. + // Note: getLocalSymbolForExportDefault handles `export default class C {}`, but not `export default C` or `export { C as default }`. + // The other two forms seem to be handled downstream (e.g. in `skipPastExportOrImportSpecifier`), so special-casing the first form + // here appears to be intentional). var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; var escapedText = ts.escapeLeadingUnderscores(text); var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); @@ -85502,21 +85721,9 @@ var ts; var GoToDefinition; (function (GoToDefinition) { function getDefinitionAtPosition(program, sourceFile, position) { - /// Triple slash reference comments - var comment = findReferenceInPosition(sourceFile.referencedFiles, position); - if (comment) { - var referenceFile = ts.tryResolveScriptReference(program, sourceFile, comment); - if (referenceFile) { - return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)]; - } - // Might still be on jsdoc, so keep looking. - } - // Type reference directives - var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); - if (typeReferenceDirective) { - var referenceFile = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); - return referenceFile && referenceFile.resolvedFileName && - [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; + var reference = getReferenceAtPosition(sourceFile, position, program); + if (reference) { + return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)]; } var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { @@ -85604,6 +85811,21 @@ var ts; return getDefinitionFromSymbol(typeChecker, symbol, node); } GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; + function getReferenceAtPosition(sourceFile, position, program) { + var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); + if (referencePath) { + var file = ts.tryResolveScriptReference(program, sourceFile, referencePath); + return file && { fileName: referencePath.fileName, file: file }; + } + var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + if (typeReferenceDirective) { + var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); + var file = reference && program.getSourceFile(reference.resolvedFileName); + return file && { fileName: typeReferenceDirective.fileName, file: file }; + } + return undefined; + } + GoToDefinition.getReferenceAtPosition = getReferenceAtPosition; /// Goto type function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); @@ -85776,6 +85998,7 @@ var ts; } return undefined; } + GoToDefinition.findReferenceInPosition = findReferenceInPosition; function getDefinitionInfoForFileReference(name, targetFileName) { return { fileName: targetFileName, @@ -85923,7 +86146,7 @@ var ts; function forEachUnique(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { - if (ts.indexOf(array, array[i]) === i) { + if (array.indexOf(array[i]) === i) { var result = callback(array[i], i); if (result) { return result; @@ -86457,7 +86680,7 @@ var ts; if (!shouldKeepItem(declaration, checker)) { continue; } - // It was a match! If the pattern has dots in it, then also see if the + // It was a match! If the pattern has dots in it, then also see if the // declaration container matches as well. var containerMatches = matches; if (patternMatcher.patternContainsDots) { @@ -86486,8 +86709,8 @@ var ts; function allMatchesAreCaseSensitive(matches) { ts.Debug.assert(matches.length > 0); // This is a case sensitive match, only if all the submatches were case sensitive. - for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { - var match = matches_2[_i]; + for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { + var match = matches_1[_i]; if (!match.isCaseSensitive) { return false; } @@ -86556,8 +86779,8 @@ var ts; function bestMatchKind(matches) { ts.Debug.assert(matches.length > 0); var bestMatchKind = ts.PatternMatchKind.camelCase; - for (var _i = 0, matches_3 = matches; _i < matches_3.length; _i++) { - var match = matches_3[_i]; + for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { + var match = matches_2[_i]; var kind = match.kind; if (kind < bestMatchKind) { bestMatchKind = kind; @@ -88202,7 +88425,7 @@ var ts; // import "mod"; // import d from "mod" // import {a as A } from "mod"; - // import * as NS from "mod" + // import * as NS from "mod" // import d, {a, b as B} from "mod" // import i = require("mod"); // import("mod"); @@ -88302,9 +88525,16 @@ var ts; symbol.parent.flags & 1536 /* Module */) { return undefined; } - var displayName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - return kind ? getRenameInfoSuccess(displayName, typeChecker.getFullyQualifiedName(symbol), kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile) : undefined; + if (!kind) { + return undefined; + } + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 145 /* ComputedPropertyName */) + ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) + : undefined; + var displayName = specifierName || typeChecker.symbolToString(symbol); + var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); + return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } } else if (node.kind === 9 /* StringLiteral */) { @@ -88538,7 +88768,7 @@ var ts; function getArgumentIndex(argumentsList, node) { // The list we got back can include commas. In the presence of errors it may // also just have nodes without commas. For example "Foo(a b c)" will have 3 - // args without commas. We want to find what index we're at. So we count + // args without commas. We want to find what index we're at. So we count // forward until we hit ourselves, only incrementing the index if it isn't a // comma. // @@ -88564,12 +88794,12 @@ var ts; // The argument count for a list is normally the number of non-comma children it has. // For example, if you have "Foo(a,b)" then there will be three children of the arg // list 'a' '' 'b'. So, in this case the arg count will be 2. However, there - // is a small subtlety. If you have "Foo(a,)", then the child list will just have + // is a small subtlety. If you have "Foo(a,)", then the child list will just have // 'a' ''. So, in the case where the last child is a comma, we increase the // arg count by one to compensate. // - // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then - // we'll have: 'a' '' '' + // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then + // we'll have: 'a' '' '' // That will give us 2 non-commas. We then add one for the last comma, giving us an // arg count of 3. var listChildren = argumentsList.getChildren(); @@ -88590,9 +88820,11 @@ var ts; // not enough to put us in the substitution expression; we should consider ourselves part of // the *next* span's expression by offsetting the index (argIndex = (spanIndex + 1) + 1). // + // tslint:disable no-double-space // Example: f `# abcd $#{# 1 + 1# }# efghi ${ #"#hello"# } # ` // ^ ^ ^ ^ ^ ^ ^ ^ ^ // Case: 1 1 3 2 1 3 2 2 1 + // tslint:enable no-double-space ts.Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node."); if (ts.isTemplateLiteralKind(node.kind)) { if (ts.isInsideTemplateLiteral(node, position)) { @@ -88639,9 +88871,8 @@ var ts; // Otherwise, we will not show signature help past the expression. // For example, // - // ` ${ 1 + 1 foo(10) - // | | - // + // ` ${ 1 + 1 foo(10) + // | | // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. if (template.kind === 197 /* TemplateExpression */) { @@ -88870,7 +89101,7 @@ var ts; } SymbolDisplay.getSymbolModifiers = getSymbolModifiers; // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location - function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning) { + function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning, alias) { if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } var displayParts = []; var documentation; @@ -88880,6 +89111,7 @@ var ts; var hasAddedSymbolInfo; var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); var type; + var documentationFromAlias; // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -88995,6 +89227,7 @@ var ts; } } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { + addAliasPrefixIfNecessary(); if (ts.getDeclarationOfKind(symbol, 200 /* ClassExpression */)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) @@ -89010,14 +89243,14 @@ var ts; writeTypeParametersOfSymbol(symbol, sourceFile); } if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(109 /* InterfaceKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } if (symbolFlags & 524288 /* TypeAlias */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(138 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); @@ -89028,7 +89261,7 @@ var ts; ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 1024 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { displayParts.push(ts.keywordPart(76 /* ConstKeyword */)); displayParts.push(ts.spacePart()); @@ -89038,7 +89271,7 @@ var ts; addFullSymbolName(symbol); } if (symbolFlags & 1536 /* Module */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); var declaration = ts.getDeclarationOfKind(symbol, 234 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 71 /* Identifier */; displayParts.push(ts.keywordPart(isNamespace ? 129 /* NamespaceKeyword */ : 128 /* ModuleKeyword */)); @@ -89046,7 +89279,7 @@ var ts; addFullSymbolName(symbol); } if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); displayParts.push(ts.textPart("type parameter")); displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); @@ -89079,7 +89312,7 @@ var ts; else if (declaration.kind === 232 /* TypeAliasDeclaration */) { // Type alias type parameter // For example - // type list = T[]; // Both T will go through same code path + // type list = T[]; // Both T will go through same code path addInPrefix(); displayParts.push(ts.keywordPart(138 /* TypeKeyword */)); displayParts.push(ts.spacePart()); @@ -89104,7 +89337,23 @@ var ts; } } if (symbolFlags & 2097152 /* Alias */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); + if (!hasAddedSymbolInfo) { + var resolvedSymbol = typeChecker.getAliasedSymbol(symbol); + if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) { + var resolvedNode = resolvedSymbol.declarations[0]; + var declarationName = ts.getNameOfDeclaration(resolvedNode); + if (declarationName) { + var isExternalModuleDeclaration = ts.isModuleWithStringLiteralName(resolvedNode) && + ts.hasModifier(resolvedNode, 2 /* Ambient */); + var shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; + var resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, resolvedSymbol, ts.getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, semanticMeaning, shouldUseAliasName ? symbol : resolvedSymbol); + displayParts.push.apply(displayParts, resolvedInfo.displayParts); + displayParts.push(ts.lineBreakPart()); + documentationFromAlias = resolvedInfo.documentation; + } + } + } switch (symbol.declarations[0].kind) { case 237 /* NamespaceExportDeclaration */: displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); @@ -89150,7 +89399,7 @@ var ts; if (symbolKind !== "" /* unknown */) { if (type) { if (isThisExpression) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(99 /* ThisKeyword */)); } else { @@ -89218,23 +89467,36 @@ var ts; } } } + if (documentation.length === 0 && documentationFromAlias) { + documentation = documentationFromAlias; + } return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; - function addNewLineIfDisplayPartsExist() { + function prefixNextMeaning() { if (displayParts.length) { displayParts.push(ts.lineBreakPart()); } + addAliasPrefixIfNecessary(); + } + function addAliasPrefixIfNecessary() { + if (alias) { + pushTypePart("alias" /* alias */); + displayParts.push(ts.spacePart()); + } } function addInPrefix() { displayParts.push(ts.spacePart()); displayParts.push(ts.keywordPart(92 /* InKeyword */)); displayParts.push(ts.spacePart()); } - function addFullSymbolName(symbol, enclosingDeclaration) { - var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */); + function addFullSymbolName(symbolToDisplay, enclosingDeclaration) { + if (alias && symbolToDisplay === symbol) { + symbolToDisplay = alias; + } + var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */); ts.addRange(displayParts, fullSymbolDisplayParts); } function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); if (symbolKind) { pushTypePart(symbolKind); if (symbol && !ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) { @@ -89820,7 +90082,7 @@ var ts; // Leave comments alone rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1 /* Ignore */), rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, formatting.anyContext, 1 /* Ignore */), - rule("NoSpaceBeforeColon", anyToken, 56 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("NotSpaceBeforeColon", anyToken, 56 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 8 /* Delete */), rule("SpaceAfterColon", 56 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2 /* Space */), rule("NoSpaceBeforeQuestionMark", anyToken, 55 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), // insert space after '?' only when it is used in conditional operator @@ -89838,10 +90100,10 @@ var ts; rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), // More unary operator special-casing. - // DevDiv 181814: Be careful when removing leading whitespace + // DevDiv 181814: Be careful when removing leading whitespace // around unary operators. Examples: - // 1 - -2 --X--> 1--2 - // a + ++b --X--> a+++b + // 1 - -2 --X--> 1--2 + // a + ++b --X--> a+++b rule("SpaceAfterPostincrementWhenFollowedByAdd", 43 /* PlusPlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterAddWhenFollowedByUnaryPlus", 37 /* PlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterAddWhenFollowedByPreincrement", 37 /* PlusToken */, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), @@ -90017,6 +90279,8 @@ var ts; rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), rule("SpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2 /* Space */), rule("NoSpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8 /* Delete */), + rule("SpaceBeforeTypeAnnotation", anyToken, 56 /* ColonToken */, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 2 /* Space */), + rule("NoSpaceBeforeTypeAnnotation", anyToken, 56 /* ColonToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 8 /* Delete */), ]; // These rules are lower in priority than user-configurable. Rules earlier in this list have priority over rules later in the list. var lowPriorityCommonRules = [ @@ -90122,6 +90386,17 @@ var ts; function isNotBinaryOpContext(context) { return !isBinaryOpContext(context); } + function isNotTypeAnnotationContext(context) { + return !isTypeAnnotationContext(context); + } + function isTypeAnnotationContext(context) { + var contextKind = context.contextNode.kind; + return contextKind === 150 /* PropertyDeclaration */ || + contextKind === 149 /* PropertySignature */ || + contextKind === 147 /* Parameter */ || + contextKind === 227 /* VariableDeclaration */ || + ts.isFunctionLikeKind(contextKind); + } function isConditionalOperatorContext(context) { return context.contextNode.kind === 196 /* ConditionalExpression */; } @@ -91811,11 +92086,13 @@ var ts; SmartIndenter.getContainingList = getContainingList; function getActualIndentationForListItem(node, sourceFile, options) { var containingList = getContainingList(node, sourceFile); - return containingList ? getActualIndentationFromList(containingList) : -1 /* Unknown */; - function getActualIndentationFromList(list) { - var index = ts.indexOf(list, node); - return index !== -1 ? deriveActualIndentationFromList(list, index, sourceFile, options) : -1 /* Unknown */; + if (containingList) { + var index = containingList.indexOf(node); + if (index !== -1) { + return deriveActualIndentationFromList(containingList, index, sourceFile, options); + } } + return -1 /* Unknown */; } function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) { // actual indentation should not be used when: @@ -94135,6 +94412,9 @@ var ts; return [fromPaths]; } } + if (isPathRelativeToParent(relativeToBaseUrl)) { + return [relativePath]; + } /* Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. @@ -94197,10 +94477,11 @@ var ts; return decl.name.text; } } - function tryGetModuleNameFromPaths(relativeNameWithIndex, relativeName, paths) { + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { for (var key in paths) { for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); var indexOfStar = pattern.indexOf("*"); if (indexOfStar === 0 && pattern.length === 1) { continue; @@ -94208,14 +94489,14 @@ var ts; else if (indexOfStar !== -1) { var prefix = pattern.substr(0, indexOfStar); var suffix = pattern.substr(indexOfStar + 1); - if (relativeName.length >= prefix.length + suffix.length && - ts.startsWith(relativeName, prefix) && - ts.endsWith(relativeName, suffix)) { - var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); - return key.replace("\*", matchedStar); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); } } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { return key; } } @@ -94343,7 +94624,10 @@ var ts; return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; } function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { - return ts.firstDefined(rootDirs, function (rootDir) { return getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); }); + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); } function removeExtensionAndIndexPostFix(fileName, options, addJsExtension) { var noExtension = ts.removeFileExtension(fileName); @@ -94355,7 +94639,10 @@ var ts; } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); } function getRelativePath(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -94495,8 +94782,9 @@ var ts; var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); if (defaultExport) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if ((localSymbol && localSymbol.escapedName === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, context.compilerOptions.target) === symbolName) - && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { + if ((localSymbol && localSymbol.escapedName === symbolName || + getEscapedNameForExportDefault(defaultExport) === symbolName || + moduleSymbolToValidIdentifier(moduleSymbol, context.compilerOptions.target) === symbolName) && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { // check if this symbol is already used var symbolId = ts.getUniqueSymbolId(localSymbol || defaultExport, checker); symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 1 /* Default */ }))); @@ -94508,6 +94796,21 @@ var ts; var symbolId = ts.getUniqueSymbolId(exportSymbolWithIdenticalName, checker); symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 0 /* Named */ }))); } + function getEscapedNameForExportDefault(symbol) { + return ts.firstDefined(symbol.declarations, function (declaration) { + if (ts.isExportAssignment(declaration)) { + if (ts.isIdentifier(declaration.expression)) { + return declaration.expression.escapedText; + } + } + else if (ts.isExportSpecifier(declaration)) { + ts.Debug.assert(declaration.name.escapedText === "default" /* Default */); + if (declaration.propertyName) { + return declaration.propertyName.escapedText; + } + } + }); + } }); return symbolIdActionMap.getAllActions(); } @@ -95401,6 +95704,94 @@ var ts; })(InferFromReference || (InferFromReference = {})); })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime.code], + getCodeActions: getActionsForInvalidImport + }); + function getActionsForInvalidImport(context) { + var sourceFile = context.sourceFile; + // This is the whole import statement, eg: + // import * as Bluebird from 'bluebird'; + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false).parent; + if (!ts.isImportDeclaration(node)) { + // No import quick fix for import calls + return []; + } + return getCodeFixesForImportDeclaration(context, node); + } + function getCodeFixesForImportDeclaration(context, node) { + var sourceFile = ts.getSourceFileOfNode(node); + var namespace = ts.getNamespaceDeclarationNode(node); + var opts = context.program.getCompilerOptions(); + var variations = []; + // import Bluebird from "bluebird"; + var replacement = ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(namespace.name, /*namedBindings*/ undefined), node.moduleSpecifier); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, node, replacement, { useNonAdjustedEndPosition: true }); + var changes = changeTracker.getChanges(); + variations.push({ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Replace_import_with_0), [changes[0].textChanges[0].newText]), + changes: changes + }); + if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { + // import Bluebird = require("bluebird"); + var replacement_1 = ts.createImportEqualsDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, namespace.name, ts.createExternalModuleReference(node.moduleSpecifier)); + var changeTracker_1 = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker_1.replaceNode(sourceFile, node, replacement_1, { useNonAdjustedEndPosition: true }); + var changes_1 = changeTracker_1.getChanges(); + variations.push({ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Replace_import_with_0), [changes_1[0].textChanges[0].newText]), + changes: changes_1 + }); + } + return variations; + } + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code, + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature.code, + ], + getCodeActions: getActionsForUsageOfInvalidImport + }); + function getActionsForUsageOfInvalidImport(context) { + var sourceFile = context.sourceFile; + var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 182 /* CallExpression */ : 183 /* NewExpression */; + var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); + if (!node) { + return []; + } + var expr = node.expression; + var type = context.program.getTypeChecker().getTypeAtLocation(expr); + if (!(type.symbol && type.symbol.originatingImport)) { + return []; + } + var fixes = []; + var relatedImport = type.symbol.originatingImport; + if (!ts.isImportCall(relatedImport)) { + ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); + } + var propertyAccess = ts.createPropertyAccess(expr, "default"); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, expr, propertyAccess, {}); + var changes = changeTracker.getChanges(); + fixes.push({ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Use_synthetic_default_member), + changes: changes + }); + return fixes; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); /// /// /// @@ -95418,6 +95809,7 @@ var ts; /// /// /// +/// /* @internal */ var ts; (function (ts) { @@ -98763,7 +99155,7 @@ var ts; return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } function getCompletionsAtPosition(fileName, position, options) { - if (options === void 0) { options = { includeExternalModuleExports: false }; } + if (options === void 0) { options = { includeExternalModuleExports: false, includeInsertTextCompletions: false }; } synchronizeHostData(); return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles(), options); } @@ -99253,7 +99645,7 @@ var ts; return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); } function getTodoCommentsRegExp() { - // NOTE: ?: means 'non-capture group'. It allows us to have groups without having to + // NOTE: `?:` means 'non-capture group'. It allows us to have groups without having to // filter them out later in the final result array. // TODO comments can appear in one of the following forms: // @@ -99428,19 +99820,6 @@ var ts; isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } - function isObjectLiteralElement(node) { - switch (node.kind) { - case 257 /* JsxAttribute */: - case 259 /* JsxSpreadAttribute */: - case 265 /* PropertyAssignment */: - case 266 /* ShorthandPropertyAssignment */: - case 152 /* MethodDeclaration */: - case 154 /* GetAccessor */: - case 155 /* SetAccessor */: - return true; - } - return false; - } /** * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 } */ @@ -99450,11 +99829,11 @@ var ts; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: if (node.parent.kind === 145 /* ComputedPropertyName */) { - return isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; + return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } // falls through case 71 /* Identifier */: - return isObjectLiteralElement(node.parent) && + return ts.isObjectLiteralElement(node.parent) && (node.parent.parent.kind === 179 /* ObjectLiteralExpression */ || node.parent.parent.kind === 258 /* JsxAttributes */) && node.parent.name === node ? node.parent : undefined; } @@ -101267,10 +101646,10 @@ var ts; if (simplifiedResult) { return ts.mapDefined(completions && completions.entries, function (entry) { if (completions.isMemberCompletion || ts.startsWith(entry.name.toLowerCase(), prefix.toLowerCase())) { - var name = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended; + var name = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, insertText = entry.insertText, replacementSpan = entry.replacementSpan, hasAction = entry.hasAction, source = entry.source, isRecommended = entry.isRecommended; var convertedSpan = replacementSpan ? _this.toLocationTextSpan(replacementSpan, scriptInfo) : undefined; // Use `hasAction || undefined` to avoid serializing `false`. - return { name: name, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended }; + return { name: name, kind: kind, kindModifiers: kindModifiers, sortText: sortText, insertText: insertText, replacementSpan: convertedSpan, hasAction: hasAction || undefined, source: source, isRecommended: isRecommended }; } }).sort(function (a, b) { return ts.compareStringsCaseSensitiveUI(a.name, b.name); }); } @@ -101809,8 +102188,8 @@ var ts; continue; } for (var i = textChanges_3.length - 1; i >= 0; i--) { - var _b = textChanges_3[i], newText = _b.newText, _c = _b.span, start = _c.start, length_8 = _c.length; - text = text.slice(0, start) + newText + text.slice(start + length_8); + var _b = textChanges_3[i], newText = _b.newText, _c = _b.span, start = _c.start, length_7 = _c.length; + text = text.slice(0, start) + newText + text.slice(start + length_7); } } return text; @@ -107454,7 +107833,6 @@ var ts; return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + options + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, options); }); }; /** Get a string based representation of a completion list entry details */ - // tslint:disable-next-line type-operator-spacing (false positive) LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options, source) { var _this = this; return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index ddc3ebee14b..f839deabcfb 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -59,6 +59,7 @@ declare namespace ts { pos: number; end: number; } + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.Unknown; enum SyntaxKind { Unknown = 0, EndOfFileToken = 1, @@ -2295,6 +2296,7 @@ declare namespace ts { types?: string[]; /** Paths used to compute primary types search locations */ typeRoots?: string[]; + esModuleInterop?: boolean; [option: string]: CompilerOptionsValue | JsonSourceFile | undefined; } interface TypeAcquisition { @@ -2788,7 +2790,7 @@ declare namespace ts { scanJsxAttributeValue(): SyntaxKind; reScanJsxToken(): SyntaxKind; scanJsxToken(): SyntaxKind; - scanJSDocToken(): SyntaxKind; + scanJSDocToken(): JsDocSyntaxKind; scan(): SyntaxKind; getText(): string; setText(text: string, start?: number, length?: number): void; @@ -3157,6 +3159,7 @@ declare namespace ts { function isJSDocCommentContainingNode(node: Node): boolean; function isSetAccessor(node: Node): node is SetAccessorDeclaration; function isGetAccessor(node: Node): node is GetAccessorDeclaration; + function isObjectLiteralElement(node: Node): node is ObjectLiteralElement; } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; @@ -3998,6 +4001,7 @@ declare namespace ts { } interface GetCompletionsAtPositionOptions { includeExternalModuleExports: boolean; + includeInsertTextCompletions: boolean; } interface ApplyCodeActionCommandResult { successMessage: string; @@ -4208,6 +4212,7 @@ declare namespace ts { InsertSpaceBeforeFunctionParenthesis?: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } interface FormatCodeSettings extends EditorSettings { insertSpaceAfterCommaDelimiter?: boolean; @@ -4225,6 +4230,7 @@ declare namespace ts { insertSpaceBeforeFunctionParenthesis?: boolean; placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } interface DefinitionInfo { fileName: string; @@ -4340,6 +4346,7 @@ declare namespace ts { kind: ScriptElementKind; kindModifiers: string; sortText: string; + insertText?: 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. diff --git a/lib/typescript.js b/lib/typescript.js index d5f0becf4ab..91962b22cfe 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -610,9 +610,9 @@ var ts; (function (SymbolFormatFlags) { SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; // Write symbols's type argument if it is instantiated symbol - // eg. class C { p: T } <-- Show p as C.p here + // eg. class C { p: T } <-- Show p as C.p here // var a: C; - // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p + // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; // Use only external alias information to get the symbol name in the given context // eg. module m { export class c { } } import x = m.c; @@ -1258,6 +1258,7 @@ var ts; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; + /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); /** * Used by the checker, this enum keeps track of external emit helpers that should be type @@ -1703,17 +1704,6 @@ var ts; return false; } ts.contains = contains; - function indexOf(array, value) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (array[i] === value) { - return i; - } - } - } - return -1; - } - ts.indexOf = indexOf; function indexOfAnyCharCode(text, charCodes, start) { for (var i = start || 0; i < text.length; i++) { if (contains(charCodes, text.charCodeAt(i))) { @@ -3231,7 +3221,9 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop + ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 + : moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getStrictOptionValue(compilerOptions, flag) { @@ -3291,7 +3283,7 @@ var ts; ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents; function getNormalizedPathComponentsOfUrl(url) { // Get root length of http://www.website.com/folder1/folder2/ - // In this example the root is: http://www.website.com/ + // In this example the root is: http://www.website.com/ // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] var urlLength = url.length; // Initial root length is http:// part @@ -3321,7 +3313,7 @@ var ts; } else { // Can't find the host assume the rest of the string as component - // but make sure we append "/" to it as root is not joined using "/" + // but make sure we append "/" to it as root is not joined using "/" // eg. if url passed in was http://website.com we want to use root as [http://website.com/] // so that other path manipulations will be correct and it can be merged with relative paths correctly return [url + ts.directorySeparator]; @@ -3340,7 +3332,7 @@ var ts; var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name - // that is ["test", "cases", ""] needs to be actually ["test", "cases"] + // that is ["test", "cases", ""] needs to be actually ["test", "cases"] directoryComponents.pop(); } // Find the component that differs @@ -5079,6 +5071,8 @@ var ts; unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), + An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."), + An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5193,6 +5187,7 @@ var ts; Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."), Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), @@ -5247,7 +5242,7 @@ var ts; Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), - const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."), A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), @@ -5414,6 +5409,9 @@ var ts; Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"), + Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), + Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), + Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5728,6 +5726,8 @@ var ts; Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), + A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime: diag(7038, ts.DiagnosticCategory.Error, "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038", "A namespace-style import cannot be called or constructed, and will cause a failure at runtime."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5817,6 +5817,8 @@ var ts; Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), + Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), + Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), }; })(ts || (ts = {})); /// @@ -5964,7 +5966,7 @@ var ts; /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: - Can contain Unicode 3.0.0 categories: + Can contain Unicode 3.0.0 categories: Uppercase letter (Lu), Lowercase letter (Ll), Titlecase letter (Lt), @@ -5972,7 +5974,7 @@ var ts; Other letter (Lo), or Letter number (Nl). IdentifierPart :: = - Can contain IdentifierStart + Unicode 3.0.0 categories: + Can contain IdentifierStart + Unicode 3.0.0 categories: Non-spacing mark (Mn), Combining spacing mark (Mc), Decimal number (Nd), or @@ -5986,7 +5988,7 @@ var ts; /* As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers IdentifierStart :: - Can contain Unicode 6.2 categories: + Can contain Unicode 6.2 categories: Uppercase letter (Lu), Lowercase letter (Ll), Titlecase letter (Lt), @@ -5994,7 +5996,7 @@ var ts; Other letter (Lo), or Letter number (Nl). IdentifierPart :: - Can contain IdentifierStart + Unicode 6.2 categories: + Can contain IdentifierStart + Unicode 6.2 categories: Non-spacing mark (Mn), Combining spacing mark (Mc), Decimal number (Nd), @@ -7550,7 +7552,7 @@ var ts; break; } } - tokenValue += text.substr(firstCharPosition, pos - firstCharPosition); + tokenValue += text.substring(firstCharPosition, pos); } return token; } @@ -7573,6 +7575,7 @@ var ts; startPos = pos; tokenPos = pos; var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 9 /* tab */: case 11 /* verticalTab */: @@ -7583,55 +7586,30 @@ var ts; } return token = 5 /* WhitespaceTrivia */; case 64 /* at */: - pos++; return token = 57 /* AtToken */; case 10 /* lineFeed */: case 13 /* carriageReturn */: - pos++; return token = 4 /* NewLineTrivia */; case 42 /* asterisk */: - pos++; return token = 39 /* AsteriskToken */; case 123 /* openBrace */: - pos++; return token = 17 /* OpenBraceToken */; case 125 /* closeBrace */: - pos++; return token = 18 /* CloseBraceToken */; case 91 /* openBracket */: - pos++; return token = 21 /* OpenBracketToken */; case 93 /* closeBracket */: - pos++; return token = 22 /* CloseBracketToken */; case 60 /* lessThan */: - pos++; return token = 27 /* LessThanToken */; - case 62 /* greaterThan */: - pos++; - return token = 29 /* GreaterThanToken */; case 61 /* equals */: - pos++; return token = 58 /* EqualsToken */; case 44 /* comma */: - pos++; return token = 26 /* CommaToken */; case 46 /* dot */: - pos++; - if (text.substr(tokenPos, pos + 2) === "...") { - pos += 2; - return token = 24 /* DotDotDotToken */; - } return token = 23 /* DotToken */; - case 33 /* exclamation */: - pos++; - return token = 51 /* ExclamationToken */; - case 63 /* question */: - pos++; - return token = 55 /* QuestionToken */; } if (isIdentifierStart(ch, 6 /* Latest */)) { - pos++; while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { pos++; } @@ -7639,7 +7617,7 @@ var ts; return token = 71 /* Identifier */; } else { - return pos += 1, token = 0 /* Unknown */; + return token = 0 /* Unknown */; } } function speculationHelper(callback, isLookahead) { @@ -8468,7 +8446,7 @@ var ts; return node === parent.type; case 182 /* CallExpression */: case 183 /* NewExpression */: - return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; + return ts.contains(parent.typeArguments, node); case 184 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; @@ -9741,6 +9719,10 @@ var ts; return "__@" + symbolName; } ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + function isKnownSymbol(symbol) { + return ts.startsWith(symbol.escapedName, "__@"); + } + ts.isKnownSymbol = isKnownSymbol; /** * Includes the word "Symbol" with unicode escapes */ @@ -11393,8 +11375,8 @@ var ts; // // { // oldStart3: Min(oldStart1, oldStart2), - // oldEnd3 : Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), - // newEnd3 : Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) + // oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), + // newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) // } var oldStart1 = oldStartN; var oldEnd1 = oldEndN; @@ -13216,6 +13198,21 @@ var ts; return hasInitializer(node) && !ts.isForStatement(node) && !ts.isForInStatement(node) && !ts.isForOfStatement(node) && !ts.isJsxAttribute(node); } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; + function isObjectLiteralElement(node) { + switch (node.kind) { + case 257 /* JsxAttribute */: + case 259 /* JsxSpreadAttribute */: + case 265 /* PropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + return true; + default: + return false; + } + } + ts.isObjectLiteralElement = isObjectLiteralElement; })(ts || (ts = {})); /// /// @@ -13796,7 +13793,7 @@ var ts; // 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost // all nodes would need extra state on them to store this info. // - // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 + // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 // grammar specification. // // An important thing about these context concepts. By default they are effectively inherited @@ -14519,9 +14516,13 @@ var ts; return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern(); case 18 /* TypeParameters */: return isIdentifier(); - case 11 /* ArgumentExpressions */: case 15 /* ArrayLiteralMembers */: - return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isStartOfExpression(); + if (token() === 26 /* CommaToken */) { + return true; + } + // falls through + case 11 /* ArgumentExpressions */: + return token() === 24 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: return isStartOfParameter(); case 19 /* TypeArguments */: @@ -14541,7 +14542,7 @@ var ts; function isValidHeritageClauseObjectLiteral() { ts.Debug.assert(token() === 17 /* OpenBraceToken */); if (nextToken() === 18 /* CloseBraceToken */) { - // if we see "extends {}" then only treat the {} as what we're extending (and not + // if we see "extends {}" then only treat the {} as what we're extending (and not // the class body) if we have: // // extends {} { @@ -14625,7 +14626,7 @@ var ts; } function isVariableDeclaratorListTerminator() { // If we can consume a semicolon (either explicitly, or with ASI), then consider us done - // with parsing the list of variable declarators. + // with parsing the list of variable declarators. if (canParseSemicolon()) { return true; } @@ -14730,6 +14731,10 @@ var ts; if (!canReuseNode(node, parsingContext)) { return undefined; } + if (node.jsDocCache) { + // jsDocCache may include tags from parent nodes, which might have been modified. + node.jsDocCache = undefined; + } return node; } function consumeNode(node) { @@ -15238,7 +15243,7 @@ var ts; // // // - // We do *not* want to consume the > as we're consuming the expression for "". + // We do *not* want to consume the `>` as we're consuming the expression for "". node.expression = parseUnaryExpressionOrHigher(); } } @@ -15978,7 +15983,7 @@ var ts; // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression". // // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is - // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done + // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done // with AssignmentExpression if we see one. var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); if (arrowExpression) { @@ -16005,7 +16010,7 @@ var ts; // we're in '2' or '3'. Consume the assignment and return. // // Note: we call reScanGreaterToken so that we get an appropriately merged token - // for cases like > > = becoming >>= + // for cases like `> > =` becoming `>>=` if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); } @@ -16136,7 +16141,7 @@ var ts; var second = nextToken(); if (first === 19 /* OpenParenToken */) { if (second === 20 /* CloseParenToken */) { - // Simple cases: "() =>", "(): ", and "() {". + // Simple cases: "() =>", "(): ", and "() {". // This is an arrow function with no parameters. // The last one is not actually an arrow function, // but this is probably what the user intended. @@ -16337,7 +16342,9 @@ var ts; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); node.colonToken = parseExpectedToken(56 /* ColonToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); - node.whenFalse = parseAssignmentExpressionOrHigher(); + node.whenFalse = ts.nodeIsPresent(node.colonToken) + ? parseAssignmentExpressionOrHigher() + : createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); return finishNode(node); } function parseBinaryExpressionOrHigher(precedence) { @@ -16699,7 +16706,8 @@ var ts; // We don't want to eagerly consume all import keyword as import call expression so we look a head to find "(" // For example: // var foo3 = require("subfolder - // import * as foo1 from "module-from-node -> we want this import to be a statement rather than import call expression + // import * as foo1 from "module-from-node + // We want this import to be a statement rather than import call expression sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; expression = parseTokenNode(); } @@ -16747,7 +16755,7 @@ var ts; // treated as the invocation of "new Foo". We disambiguate that in code (to match // the original grammar) by making sure that if we see an ObjectCreationExpression // we always consume arguments if they are there. So we treat "new Foo()" as an - // object creation only, and not at all as an invocation) Another way to think + // object creation only, and not at all as an invocation. Another way to think // about this is that for every "new" that we see, we will consume an argument list if // it is there as part of the *associated* object creation node. Any additional // argument lists we see, will become invocation expressions. @@ -17111,7 +17119,7 @@ var ts; } var typeArguments = parseDelimitedList(19 /* TypeArguments */, parseType); if (!parseExpected(29 /* GreaterThanToken */)) { - // If it doesn't have the closing > then it's definitely not an type argument list. + // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; } // If we have a '<', then only parse this as a argument list if the type arguments @@ -18025,8 +18033,8 @@ var ts; // off. The grammar would look something like this: // // MemberVariableDeclaration[Yield]: - // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; - // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; + // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; + // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; // // The checker may still error in the static case to explicitly disallow the yield expression. node.initializer = ts.hasModifier(node, 32 /* Static */) @@ -18800,17 +18808,17 @@ var ts; comments.push(text); indent += text.length; } - nextJSDocToken(); - while (token() === 5 /* WhitespaceTrivia */) { - nextJSDocToken(); + var t = nextJSDocToken(); + while (t === 5 /* WhitespaceTrivia */) { + t = nextJSDocToken(); } - if (token() === 4 /* NewLineTrivia */) { + if (t === 4 /* NewLineTrivia */) { state = 0 /* BeginningOfLine */; indent = 0; - nextJSDocToken(); + t = nextJSDocToken(); } - while (token() !== 1 /* EndOfFileToken */) { - switch (token()) { + loop: while (true) { + switch (t) { case 57 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingNewlines(comments); @@ -18864,7 +18872,7 @@ var ts; indent += whitespace.length; break; case 1 /* EndOfFileToken */: - break; + break loop; default: // anything other than whitespace or asterisk at the beginning of the line starts the comment text state = 2 /* SavingComments */; @@ -18872,10 +18880,11 @@ var ts; break; } if (advanceToken) { - nextJSDocToken(); + t = nextJSDocToken(); } else { advanceToken = true; + t = currentToken; } } removeLeadingNewlines(comments); @@ -18974,8 +18983,9 @@ var ts; comments.push(text); indent += text.length; } - while (token() !== 57 /* AtToken */ && token() !== 1 /* EndOfFileToken */) { - switch (token()) { + var tok = token(); + loop: while (true) { + switch (tok) { case 4 /* NewLineTrivia */: if (state >= 1 /* SawAsterisk */) { state = 0 /* BeginningOfLine */; @@ -18984,8 +18994,9 @@ var ts; indent = 0; break; case 57 /* AtToken */: + case 1 /* EndOfFileToken */: // Done - break; + break loop; case 5 /* WhitespaceTrivia */: if (state === 2 /* SavingComments */) { pushComment(scanner.getTokenText()); @@ -19013,11 +19024,7 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (token() === 57 /* AtToken */) { - // Done - break; - } - nextJSDocToken(); + tok = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); @@ -19258,8 +19265,7 @@ var ts; var canParseTag = true; var seenAsterisk = false; while (true) { - nextJSDocToken(); - switch (token()) { + switch (nextJSDocToken()) { case 57 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target); @@ -19523,7 +19529,7 @@ var ts; // We may need to update both the 'pos' and the 'end' of the element. // If the 'pos' is before the start of the change, then we don't need to touch it. // If it isn't, then the 'pos' must be inside the change. How we update it will - // depend if delta is positive or negative. If delta is positive then we have + // depend if delta is positive or negative. If delta is positive then we have // something like: // // -------------------AAA----------------- @@ -19547,7 +19553,7 @@ var ts; element.pos = Math.min(element.pos, changeRangeNewEnd); // If the 'end' is after the change range, then we always adjust it by the delta // amount. However, if the end is in the change range, then how we adjust it - // will depend on if delta is positive or negative. If delta is positive then we + // will depend on if delta is positive or negative. If delta is positive then we // have something like: // // -------------------AAA----------------- @@ -20133,7 +20139,7 @@ var ts; // without names can only come from JSDocFunctionTypes. ts.Debug.assert(node.parent.kind === 277 /* JSDocFunctionType */); var functionType = node.parent; - var index = ts.indexOf(functionType.parameters, node); + var index = functionType.parameters.indexOf(node); return "arg" + index; case 288 /* JSDocTypedefTag */: var name_2 = ts.getNameOfJSDocTypedef(node); @@ -20556,10 +20562,10 @@ var ts; return false; } function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 190 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; + return expr1.kind === 190 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && (expr2.kind === 9 /* StringLiteral */ || expr2.kind === 13 /* NoSubstitutionTemplateLiteral */); } function isNarrowableInOperands(left, right) { - return left.kind === 9 /* StringLiteral */ && isNarrowingExpression(right); + return (left.kind === 9 /* StringLiteral */ || left.kind === 13 /* NoSubstitutionTemplateLiteral */) && isNarrowingExpression(right); } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { @@ -21366,7 +21372,7 @@ var ts; // to the one we would get for: { <...>(...): T } // // We do that by making an anonymous type literal symbol, and then setting the function - // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable + // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable // from an actual type literal symbol you would have gotten had you used the long form. var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); addDeclarationToSymbol(symbol, node, 131072 /* Signature */); @@ -22177,7 +22183,7 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (ts.isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + ts.indexOf(node.parent.parameters, node)); + bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); @@ -24517,6 +24523,7 @@ var ts; }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, getAccessibleSymbolChain: getAccessibleSymbolChain, + resolveExternalModuleSymbol: resolveExternalModuleSymbol, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -25058,7 +25065,7 @@ var ts; return true; } var sourceFiles = host.getSourceFiles(); - return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); + return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); } if (declaration.pos <= usage.pos) { // declaration is before usage @@ -25365,14 +25372,14 @@ var ts; } break; } - if (location.kind !== 208 /* Block */) { + if (isNonBlockLocation(location)) { lastNonBlockLocation = location; } lastLocation = location; location = location.parent; } // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. - // If `result === lastLocation.symbol`, that means that we are somewhere inside `lastLocation` looking up a name, and resolving to `lastLocation` itself. + // If `result === lastNonBlockLocation.symbol`, that means that we are somewhere inside `lastNonBlockLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastNonBlockLocation.symbol) { result.isReferenced = true; @@ -25447,6 +25454,20 @@ var ts; } return result; } + function isNonBlockLocation(_a) { + var kind = _a.kind; + switch (kind) { + case 208 /* Block */: + case 235 /* ModuleBlock */: + case 222 /* SwitchStatement */: + case 236 /* CaseBlock */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + return false; + default: + return true; + } + } function diagnosticName(nameArg) { return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); } @@ -25615,6 +25636,41 @@ var ts; } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); } + function resolveExportByName(moduleSymbol, name, dontResolveAlias) { + var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */); + return exportValue + ? getPropertyOfType(getTypeOfSymbol(exportValue), name) + : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); + } + function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { + if (!allowSyntheticDefaultImports) { + return false; + } + // Declaration files (and ambient modules) + if (!file || file.isDeclarationFile) { + // Definitely cannot have a synthetic default if they have a default member specified + if (resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias)) { + return false; + } + // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member + // So we check a bit more, + if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias)) { + // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code), + // it definitely is a module and does not have a synthetic default + return false; + } + // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set + // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member + // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm + return true; + } + // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement + if (!ts.isSourceFileJavaScript(file)) { + return hasExportAssignmentSymbol(moduleSymbol); + } + // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker + return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias); + } function getTargetOfImportClause(node, dontResolveAlias) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { @@ -25623,15 +25679,15 @@ var ts; exportDefaultSymbol = moduleSymbol; } else { - var exportValue = moduleSymbol.exports.get("export="); - exportDefaultSymbol = exportValue - ? getPropertyOfType(getTypeOfSymbol(exportValue), "default" /* Default */) - : resolveSymbol(moduleSymbol.exports.get("default" /* Default */), dontResolveAlias); + exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias); } - if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { + var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); + if (!exportDefaultSymbol && !hasSyntheticDefault) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } - else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + else if (!exportDefaultSymbol && hasSyntheticDefault) { + // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } return exportDefaultSymbol; @@ -25998,8 +26054,42 @@ var ts; // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable). function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression, dontResolveAlias) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); - if (!dontResolveAlias && symbol && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { - error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + if (!dontResolveAlias && symbol) { + if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { + error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + return symbol; + } + if (compilerOptions.esModuleInterop) { + var referenceParent = moduleReferenceExpression.parent; + if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || + ts.isImportCall(referenceParent)) { + var type = getTypeOfSymbol(symbol); + var sigs = getSignaturesOfStructuredType(type, 0 /* Call */); + if (!sigs || !sigs.length) { + sigs = getSignaturesOfStructuredType(type, 1 /* Construct */); + } + if (sigs && sigs.length) { + var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol); + // Create a new symbol which has the module's type less the call and construct signatures + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + result.target = symbol; + result.originatingImport = referenceParent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above + result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo); + return result; + } + } + } } return symbol; } @@ -28209,7 +28299,7 @@ var ts; } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var propName = "" + ts.indexOf(pattern.elements, declaration); + var propName = "" + pattern.elements.indexOf(declaration); type = isTupleLikeType(parentType) ? getTypeOfPropertyOfType(parentType, propName) : elementType; @@ -30471,7 +30561,7 @@ var ts; if (node.initializer) { var signatureDeclaration = node.parent; var signature = getSignatureFromDeclaration(signatureDeclaration); - var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); + var parameterIndex = signatureDeclaration.parameters.indexOf(node); ts.Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } @@ -30479,7 +30569,7 @@ var ts; if (iife) { return !node.type && !node.dotDotDotToken && - ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; + node.parent.parameters.indexOf(node) >= iife.arguments.length; } return false; } @@ -31694,7 +31784,7 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.escapedName, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.isKnownSymbol(prop) ? neverType : getLiteralType(ts.symbolName(prop)); } @@ -31743,6 +31833,7 @@ var ts; var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { + markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); return unknownType; @@ -32230,7 +32321,7 @@ var ts; * This is used during inference when instantiating type parameter defaults. */ function createBackreferenceMapper(typeParameters, index) { - return function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; + return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; }; } function isInferenceContext(mapper) { return !!mapper.signature; @@ -32895,10 +32986,24 @@ var ts; } else if (errorInfo) { if (containingMessageChain) { - errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); + var chain_1 = containingMessageChain(); + if (chain_1) { + errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo); + } } diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } + // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement + if (headMessage && errorNode && !result && source.symbol) { + var links = getSymbolLinks(source.symbol); + if (links.originatingImport && !ts.isImportCall(links.originatingImport)) { + var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined); + if (helpfulRetry) { + // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import + diagnostics.add(ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime)); + } + } + } return result !== 0 /* False */; function reportError(message, arg0, arg1, arg2) { ts.Debug.assert(!!errorNode); @@ -33955,7 +34060,7 @@ var ts; for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { var t = _a[_i]; if (isUnconstrainedTypeParameter(t)) { - var index = ts.indexOf(typeParameters, t); + var index = typeParameters.indexOf(t); if (index < 0) { index = typeParameters.length; typeParameters.push(t); @@ -35418,7 +35523,7 @@ var ts; parent.parent.kind === 217 /* ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { - return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); + return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); } function getAssignedTypeOfSpreadExpression(node) { return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); @@ -35457,7 +35562,7 @@ var ts; var type = pattern.kind === 175 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? - getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : + getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : getTypeOfDestructuredSpreadExpression(parentType); return getTypeWithDefault(type, node.initializer); } @@ -36009,7 +36114,7 @@ var ts; firstAntecedentType = flowType; } var type = getTypeFromFlowType(flowType); - // If we see a value appear in the cache it is a sign that control flow analysis + // If we see a value appear in the cache it is a sign that control flow analysis // was restarted and completed by checkExpressionCached. We can simply pick up // the resulting type and bail out. var cached_1 = cache.get(key); @@ -36091,10 +36196,10 @@ var ts; var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 190 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { + if (left_1.kind === 190 /* TypeOfExpression */ && (right_1.kind === 9 /* StringLiteral */ || right_1.kind === 13 /* NoSubstitutionTemplateLiteral */)) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 190 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { + if (right_1.kind === 190 /* TypeOfExpression */ && (left_1.kind === 9 /* StringLiteral */ || left_1.kind === 13 /* NoSubstitutionTemplateLiteral */)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -36117,7 +36222,7 @@ var ts; return narrowTypeByInstanceof(type, expr, assumeTrue); case 92 /* InKeyword */: var target = getReferenceCandidate(expr.right); - if (expr.left.kind === 9 /* StringLiteral */ && isMatchingReference(reference, target)) { + if ((expr.left.kind === 9 /* StringLiteral */ || expr.left.kind === 13 /* NoSubstitutionTemplateLiteral */) && isMatchingReference(reference, target)) { return narrowByInKeyword(type, expr.left, assumeTrue); } break; @@ -36544,6 +36649,7 @@ var ts; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; + var isSpreadDestructuringAsignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. @@ -36555,7 +36661,7 @@ var ts; // 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 = isParameter || isAlias || isOuterVariable || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAsignmentTarget || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isInTypeQuery(node) || node.parent.kind === 247 /* ExportSpecifier */) || node.parent.kind === 204 /* NonNullExpression */ || @@ -37070,7 +37176,7 @@ var ts; if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { var iife = ts.getImmediatelyInvokedFunctionExpression(func); if (iife && iife.arguments) { - var indexOfParameter = ts.indexOf(func.parameters, parameter); + var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { var restTypes = []; for (var i = indexOfParameter; i < iife.arguments.length; i++) { @@ -37091,7 +37197,7 @@ var ts; if (contextualSignature) { var funcHasRestParameters = ts.hasRestParameter(func); var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = ts.indexOf(func.parameters, parameter); + var indexOfParameter = func.parameters.indexOf(parameter); if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { ts.Debug.assert(indexOfParameter !== 0); // Otherwise we should not have called `getContextuallyTypedParameterType`. indexOfParameter -= 1; @@ -37208,7 +37314,7 @@ var ts; // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { var args = getEffectiveCallArguments(callTarget); - var argIndex = ts.indexOf(args, arg); + var argIndex = args.indexOf(arg); if (argIndex >= 0) { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. @@ -37631,7 +37737,7 @@ var ts; if (patternElement.kind !== 201 /* OmittedExpression */) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } - elementTypes.push(unknownType); + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); } } } @@ -38760,16 +38866,16 @@ var ts; return propKind !== 152 /* MethodDeclaration */ && propKind !== 151 /* MethodSignature */; }); } - function checkNonNullExpression(node) { - return checkNonNullType(checkExpression(node), node); + function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); } - function checkNonNullType(type, errorNode) { + function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 12288 /* Nullable */; if (kind) { - error(errorNode, kind & 4096 /* Undefined */ ? kind & 8192 /* Null */ ? - ts.Diagnostics.Object_is_possibly_null_or_undefined : - ts.Diagnostics.Object_is_possibly_undefined : - ts.Diagnostics.Object_is_possibly_null); + error(node, kind & 4096 /* Undefined */ ? kind & 8192 /* Null */ ? + (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : + (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : + (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); var t = getNonNullableType(type); return t.flags & (12288 /* Nullable */ | 16384 /* Never */) ? unknownType : t; } @@ -39484,7 +39590,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (!constraint) continue; - var errorInfo = reportErrors && headMessage && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + var errorInfo = reportErrors && headMessage && (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }); var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; if (!mapper) { mapper = createTypeMapper(typeParameters, typeArgumentTypes); @@ -40093,7 +40199,7 @@ var ts; } excludeCount--; if (excludeCount > 0) { - excludeArgument[ts.indexOf(excludeArgument, /*value*/ true)] = false; + excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; } else { excludeArgument = undefined; @@ -40132,7 +40238,7 @@ var ts; } return resolveUntypedCall(node); } - var funcType = checkNonNullExpression(node.expression); + var funcType = checkNonNullExpression(node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -40166,7 +40272,7 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + invocationError(node, apparentType, 0 /* Call */); } return resolveErrorCall(node); } @@ -40247,7 +40353,7 @@ var ts; } return signature; } - error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); + invocationError(node, expressionType, 1 /* Construct */); return resolveErrorCall(node); } function isConstructorAccessible(node, signature) { @@ -40287,6 +40393,26 @@ var ts; } return true; } + function invocationError(node, apparentType, kind) { + error(node, kind === 0 /* Call */ + ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures + : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind); + } + function invocationErrorRecovery(apparentType, kind) { + if (!apparentType.symbol) { + return; + } + var importNode = getSymbolLinks(apparentType.symbol).originatingImport; + // Create a diagnostic on the originating import if possible onto which we can attach a quickfix + // An import call expression cannot be rewritten into another form to correct the error - the only solution is to use `.default` at the use-site + if (importNode && !ts.isImportCall(importNode)) { + var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); + if (!sigs || !sigs.length) + return; + error(importNode, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime); + } + } function resolveTaggedTemplateExpression(node, candidatesOutArray) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); @@ -40300,7 +40426,7 @@ var ts; return resolveUntypedCall(node); } if (!callSignatures.length) { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + invocationError(node, apparentType, 0 /* Call */); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray); @@ -40348,6 +40474,7 @@ var ts; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + invocationErrorRecovery(apparentType, 0 /* Call */); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray, headMessage); @@ -40577,16 +40704,18 @@ var ts; if (moduleSymbol) { var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true); if (esModuleSymbol) { - return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol)); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol)); } } return createPromiseReturnType(node, anyType); } - function getTypeWithSyntheticDefaultImportType(type, symbol) { + function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { if (allowSyntheticDefaultImports && type && type !== unknownType) { var synthType = type; if (!synthType.syntheticType) { - if (!getPropertyOfType(type, "default" /* Default */)) { + var file = ts.find(originalSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false); + if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); newSymbol.target = resolveSymbol(symbol); @@ -40594,7 +40723,7 @@ var ts; var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); anonymousSymbol.type = defaultContainingObject; - synthType.syntheticType = getIntersectionType([type, defaultContainingObject]); + synthType.syntheticType = (type.flags & 458752 /* StructuredType */ && type.symbol.flags & (1536 /* Module */ | 3 /* Variable */)) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*propegatedFlags*/ 0) : defaultContainingObject; } else { synthType.syntheticType = type; @@ -41995,9 +42124,10 @@ var ts; // - target in rhs of import statement var ok = (node.parent.kind === 180 /* PropertyAccessExpression */ && node.parent.expression === node) || (node.parent.kind === 181 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 71 /* Identifier */ || node.kind === 144 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); + ((node.kind === 71 /* Identifier */ || node.kind === 144 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 163 /* TypeQuery */ && node.parent.exprName === node)); if (!ok) { - error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } } return type; @@ -42142,7 +42272,7 @@ var ts; error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); } if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { - if (ts.indexOf(func.parameters, node) !== 0) { + if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } if (func.kind === 153 /* Constructor */ || func.kind === 157 /* ConstructSignature */ || func.kind === 162 /* ConstructorType */) { @@ -42188,7 +42318,7 @@ var ts; error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { - var leadingError = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); + var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, /*headMessage*/ undefined, leadingError); } @@ -42519,22 +42649,6 @@ var ts; if (!produceDiagnostics) { return; } - function containsSuperCallAsComputedPropertyName(n) { - var name = ts.getNameOfDeclaration(n); - return name && containsSuperCall(name); - } - function containsSuperCall(n) { - if (ts.isSuperCall(n)) { - return true; - } - else if (ts.isFunctionLike(n)) { - return false; - } - else if (ts.isClassLike(n)) { - return ts.forEach(n.members, containsSuperCallAsComputedPropertyName); - } - return ts.forEachChild(n, containsSuperCall); - } function isInstancePropertyWithInitializer(n) { return n.kind === 150 /* PropertyDeclaration */ && !ts.hasModifier(n, 32 /* Static */) && @@ -43150,7 +43264,7 @@ var ts; } var promisedType = getPromisedTypeOfPromise(type); if (promisedType) { - if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) { + if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) { // Verify that we don't have a bad actor in the form of a promise whose // promised type is the same as the promise type, or a mutually recursive // promise. If so, we return undefined as we cannot guess the shape. If this @@ -43350,7 +43464,7 @@ var ts; expectedReturnType = getUnionType([descriptorType, voidType]); break; } - checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); } /** * If a TypeNode can be resolved to a value symbol imported from an external module, it is @@ -43707,36 +43821,35 @@ var ts; } function checkUnusedClassMembers(node) { if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { - if (node.members) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - switch (member.kind) { - case 152 /* MethodDeclaration */: - case 150 /* PropertyDeclaration */: - case 154 /* GetAccessor */: - case 155 /* SetAccessor */: - if (member.kind === 155 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { - // Already would have reported an error on the getter. - break; - } - if (!member.symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { - error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(member.symbol)); - } + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 152 /* MethodDeclaration */: + case 150 /* PropertyDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + if (member.kind === 155 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + // Already would have reported an error on the getter. break; - case 153 /* Constructor */: - for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { - var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)); - } + } + var symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { + error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)); + } + break; + case 153 /* Constructor */: + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)); } - break; - case 158 /* IndexSignature */: - // Can't be private - break; - default: - ts.Debug.fail(); - } + } + break; + case 158 /* IndexSignature */: + // Can't be private + break; + default: + ts.Debug.fail(); } } } @@ -44305,7 +44418,7 @@ var ts; // Grammar checking checkGrammarForInOrForOfStatement(node); var rightType = checkNonNullExpression(node.expression); - // TypeScript 1.0 spec (April 2014): 5.4 + // TypeScript 1.0 spec (April 2014): 5.4 // In a 'for-in' statement of the form // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, @@ -45056,7 +45169,10 @@ var ts; } } } - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + } checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); if (baseConstructorType.flags & 1081344 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); @@ -45086,9 +45202,13 @@ var ts; var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { if (isValidBaseType(t)) { - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, t.symbol && t.symbol.flags & 32 /* Class */ ? + var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : - ts.Diagnostics.Class_0_incorrectly_implements_interface_1); + ts.Diagnostics.Class_0_incorrectly_implements_interface_1; + var baseWithThis = getTypeWithThisArgument(t, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag); + } } else { error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); @@ -45103,6 +45223,35 @@ var ts; checkPropertyInitialization(node); } } + function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { + // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible + var issuedMemberError = false; + var _loop_5 = function (member) { + if (ts.hasStaticModifier(member)) { + return "continue"; + } + var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (declaredProp) { + var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); + var baseProp_1 = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp_1) { + var rootChain = function () { return ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(getTypeOfSymbol(baseProp_1))); }; + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp_1), member.name || member, /*message*/ undefined, rootChain)) { + issuedMemberError = true; + } + } + } + }; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + _loop_5(member); + } + if (!issuedMemberError) { + // check again with diagnostics to generate a less-specific error + checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); + } + } function checkBaseTypeAccessibility(type, node) { var signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length) { @@ -46757,7 +46906,7 @@ var ts; // [{ property1: p1, property2 }] = elems; var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; - return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || unknownType); } // Gets the property symbol corresponding to the property in destructuring assignment // 'property1' from @@ -46933,7 +47082,7 @@ var ts; // AND // - binding is not declared in loop, should be renamed to avoid name reuse across siblings // let a, b - // { let x = 1; a = () => x; } + // { let x = 1; a = () => x; } // { let x = 100; b = () => x; } // console.log(a()); // should print '1' // console.log(b()); // should print '100' @@ -47872,6 +48021,13 @@ var ts; return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } if (parameter.type.kind !== 136 /* StringKeyword */ && parameter.type.kind !== 133 /* NumberKeyword */) { + var type = getTypeFromTypeNode(parameter.type); + if (type.flags & 2 /* String */ || type.flags & 4 /* Number */) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); + } + if (allTypesAssignableToKind(type, 32 /* StringLiteral */, /*strict*/ true)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); + } return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { @@ -52011,13 +52167,13 @@ var ts; if (isLeftSideOfBinary) { // No need to parenthesize the left operand when the binary operator is // left associative: - // (a*b)/x -> a*b/x - // (a**b)/x -> a**b/x + // (a*b)/x -> a*b/x + // (a**b)/x -> a**b/x // // Parentheses are needed for the left operand when the binary operator is // right associative: - // (a/b)**x -> (a/b)**x - // (a**b)**x -> (a**b)**x + // (a/b)**x -> (a/b)**x + // (a**b)**x -> (a**b)**x return binaryOperatorAssociativity === 1 /* Right */; } else { @@ -53048,7 +53204,7 @@ var ts; case 216 /* ForInStatement */: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 217 /* ForOfStatement */: - return ts.updateForOf(node, node.awaitModifier, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 218 /* ContinueStatement */: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); case 219 /* BreakStatement */: @@ -53872,6 +54028,7 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); if (externalHelpersImportDeclaration) { + ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */); externalImports.unshift(externalHelpersImportDeclaration); } return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; @@ -54430,7 +54587,7 @@ var ts; */ var classAliases; /** - * Keeps track of whether we are within any containing namespaces when performing + * Keeps track of whether we are within any containing namespaces when performing * just-in-time substitution while printing an expression identifier. */ var applicableSubstitutions; @@ -59437,7 +59594,7 @@ var ts; */ function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { if (extendsClauseElement) { - statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getLocalName(node))), + statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getInternalName(node))), /*location*/ extendsClauseElement)); } } @@ -64537,8 +64694,8 @@ var ts; // `throw` methods that step through the generator when invoked. // // parameters: - // thisArg The value to use as the `this` binding for the transformed generator body. - // body A function that acts as the transformed generator body. + // @param thisArg The value to use as the `this` binding for the transformed generator body. + // @param body A function that acts as the transformed generator body. // // variables: // _ Persistent state for the generator that is shared between the helper and the @@ -64718,7 +64875,7 @@ var ts; // Create an updated SourceFile: // // define(moduleName?, ["module1", "module2"], function ... - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createStatement(ts.createCall(define, /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ // Add the dependency array argument: @@ -64743,6 +64900,8 @@ var ts; ]))) ]), /*location*/ node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; } /** * Transforms a SourceFile into a UMD module. @@ -64793,7 +64952,7 @@ var ts; // define(["require", "exports"], factory); // } // })(function ...) - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createStatement(ts.createCall(umdHeader, /*typeArguments*/ undefined, [ // Add the module body function argument: @@ -64811,6 +64970,8 @@ var ts; ])) ]), /*location*/ node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; } /** * Collect the additional asynchronous dependencies for the module. @@ -64862,6 +65023,17 @@ var ts; } return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; } + function getAMDImportExpressionForImport(node) { + if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) { + return undefined; + } + var name = ts.getLocalNameForExternalImport(node, currentSourceFile); + var expr = getHelperExpressionForImport(node, name); + if (expr === name) { + return undefined; + } + return ts.createStatement(ts.createAssignment(name, expr)); + } /** * Transforms a SourceFile into an AMD or UMD module body. * @@ -64876,6 +65048,9 @@ var ts; } // Visit each statement of the module body. ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); + if (moduleKind === ts.ModuleKind.AMD) { + ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport)); + } ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); // Append the 'export =' statement if provided. addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); @@ -65047,7 +65222,12 @@ var ts; ts.setEmitFlags(func, 8 /* CapturesThis */); } } - return ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); + var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]); + } + return promise; } function createImportCallExpressionCommonJS(arg, containsLexicalThis) { // import("./blah") @@ -65057,6 +65237,10 @@ var ts; // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]); + } var func; if (languageVersion >= 2 /* ES2015 */) { func = ts.createArrowFunction( @@ -65083,6 +65267,20 @@ var ts; } return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); } + function getHelperExpressionForImport(node, innerExpr) { + if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) { + return innerExpr; + } + if (ts.getNamespaceDeclarationNode(node)) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]); + } + if (ts.isDefaultImport(node)) { + context.requestEmitHelper(importDefaultHelper); + return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]); + } + return innerExpr; + } /** * Visits an ImportDeclaration node. * @@ -65101,7 +65299,7 @@ var ts; if (namespaceDeclaration && !ts.isDefaultImport(node)) { // import * as n from "mod"; variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), - /*type*/ undefined, createRequireCall(node))); + /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node)))); } else { // import d from "mod"; @@ -65109,7 +65307,7 @@ var ts; // import d, { x, y } from "mod"; // import d, * as n from "mod"; variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), - /*type*/ undefined, createRequireCall(node))); + /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node)))); if (namespaceDeclaration && ts.isDefaultImport(node)) { variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), /*type*/ undefined, ts.getGeneratedNameForNode(node))); @@ -65842,6 +66040,18 @@ var ts; scoped: true, text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" }; + // emit helper for `import * as Name from "foo"` + var importStarHelper = { + name: "typescript:commonjsimportstar", + scoped: false, + text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n}" + }; + // emit helper for `import Name from "foo"` + var importDefaultHelper = { + name: "typescript:commonjsimportdefault", + scoped: false, + text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n}" + }; })(ts || (ts = {})); /// /// @@ -67282,9 +67492,11 @@ var ts; if (externalHelpersModuleName) { var statements = []; var statementOffset = ts.addPrologue(statements, node.statements); - ts.append(statements, ts.createImportDeclaration( + var tslibImport = ts.createImportDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText))); + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + ts.addEmitFlags(tslibImport, 67108864 /* NeverApplyImportHelper */); + ts.append(statements, tslibImport); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -67994,7 +68206,7 @@ var ts; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSource.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, /*isAbsolutePathAnUrl*/ true); - sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); + sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(source); if (sourceMapSourceIndex === -1) { sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); @@ -68535,8 +68747,8 @@ var ts; allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); moduleElementDeclarationEmitInfo = []; } - if (!isBundledEmit && ts.isExternalModule(sourceFile) && sourceFile.moduleAugmentations.length && !resultHasExternalModuleIndicator) { - // if file was external module with augmentations - this fact should be preserved in .d.ts as well. + if (!isBundledEmit && ts.isExternalModule(sourceFile) && !resultHasExternalModuleIndicator) { + // if file was external module this fact should be preserved in .d.ts as well. // in case if we didn't write any external module specifiers in .d.ts we need to emit something // that will force compiler to think that this file is an external module - 'export {}' is a reasonable choice here. write("export {};"); @@ -68974,6 +69186,9 @@ var ts; return tempVarName; } function emitExportAssignment(node) { + if (ts.isSourceFile(node.parent)) { + resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators + } if (node.expression.kind === 71 /* Identifier */) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); @@ -69061,6 +69276,7 @@ var ts; var modifiers = ts.getModifierFlags(node); // If the node is exported if (modifiers & 1 /* Export */) { + resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators write("export "); } if (modifiers & 512 /* Default */) { @@ -69202,6 +69418,7 @@ var ts; writeAsynchronousModuleElements(nodes); } function emitExportDeclaration(node) { + resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators emitJsDocComments(node); write("export "); if (node.exportClause) { @@ -70086,6 +70303,7 @@ var ts; // it allows emitSeparatedList to write separator appropriately) // Example: // original: function foo([, x, ,]) {} + // tslint:disable-next-line no-double-space // emit : function foo([ , x, , ]) {} write(" "); } @@ -74760,6 +74978,7 @@ var ts; // synthesize 'import "tslib"' declaration var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined); + ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */); externalHelpersModuleReference.parent = importDecl; importDecl.parent = file; imports = [externalHelpersModuleReference]; @@ -75313,13 +75532,13 @@ var ts; var emitFilePath = toPath(emitFileName); // Report error if the output overwrites input file if (filesByName.has(emitFilePath)) { - var chain_1; + var chain_2; if (!options.configFilePath) { // The program is from either an inferred project or an external project - chain_1 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + chain_2 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); } - chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); - blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_1)); + chain_2 = ts.chainDiagnosticMessages(chain_2, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_2)); } var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; // Report error if multiple files write into same file @@ -75607,6 +75826,7 @@ var ts; "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", + "esnext.array": "lib.esnext.array.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", "esnext.promise": "lib.esnext.promise.d.ts", }), @@ -75861,6 +76081,13 @@ var ts; category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, + { + name: "esModuleInterop", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports + }, { name: "preserveSymlinks", type: "boolean", @@ -76151,7 +76378,8 @@ var ts; ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, target: 1 /* ES5 */, - strict: true + strict: true, + esModuleInterop: true }; var optionNameMapCache; /* @internal */ @@ -76625,7 +76853,7 @@ var ts; function serializeCompilerOptions(options) { var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_5 = function (name) { + var _loop_6 = function (name) { if (ts.hasProperty(options, name)) { // tsconfig only options cannot be specified via command line, // so we can assume that only types that can appear here string | number | boolean @@ -76654,7 +76882,7 @@ var ts; } }; for (var name in options) { - _loop_5(name); + _loop_6(name); } return result; } @@ -78912,18 +79140,6 @@ var ts; }); } ts.signatureToDisplayParts = signatureToDisplayParts; - function getDeclaredName(typeChecker, symbol, location) { - // If this is an export or import specifier it could have been renamed using the 'as' syntax. - // If so we want to search for whatever is under the cursor. - if (isImportOrExportSpecifierName(location) || ts.isStringOrNumericLiteral(location) && location.parent.kind === 145 /* ComputedPropertyName */) { - return ts.getTextOfIdentifierOrLiteral(location); - } - // Try to get the local symbol if we're dealing with an 'export default' - // since that symbol has the "true" name. - var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); - return typeChecker.symbolToString(localExportDefaultSymbol || symbol); - } - ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && (location.parent.kind === 243 /* ImportSpecifier */ || location.parent.kind === 247 /* ExportSpecifier */) && @@ -78937,12 +79153,16 @@ var ts; */ function stripQuotes(name) { var length = name.length; - if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && ts.isSingleOrDoubleQuote(name.charCodeAt(0))) { + if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && startsWithQuote(name)) { return name.substring(1, length - 1); } return name; } ts.stripQuotes = stripQuotes; + function startsWithQuote(name) { + return ts.isSingleOrDoubleQuote(name.charCodeAt(0)); + } + ts.startsWithQuote = startsWithQuote; function scriptKindIs(fileName, host) { var scriptKinds = []; for (var _i = 2; _i < arguments.length; _i++) { @@ -79793,7 +80013,7 @@ var ts; if (ts.isKeyword(tokenKind)) { return 3 /* keyword */; } - // Special case < and > If they appear in a generic context they are punctuation, + // Special case `<` and `>`: If they appear in a generic context they are punctuation, // not operators. if (tokenKind === 27 /* LessThanToken */ || tokenKind === 29 /* GreaterThanToken */) { // If the node owning the token has a type argument list or type parameter list, then @@ -79903,11 +80123,11 @@ var ts; (function (Completions) { var PathCompletions; (function (PathCompletions) { - function getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker) { + function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { var literalValue = ts.normalizeSlashes(node.text); var scriptPath = node.getSourceFile().path; var scriptDirectory = ts.getDirectoryPath(scriptPath); - var span = getDirectoryFragmentTextSpan(node.text, node.getStart() + 1); + var span = getDirectoryFragmentTextSpan(node.text, node.getStart(sourceFile) + 1); if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { var extensions = ts.getSupportedExtensions(compilerOptions); if (compilerOptions.rootDirs) { @@ -80022,37 +80242,20 @@ var ts; var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, span, host, /*exclude*/ undefined, result); - var _loop_6 = function (path) { - if (!paths.hasOwnProperty(path)) - return "continue"; - var patterns = paths[path]; - if (!patterns) - return "continue"; - if (path === "*") { - for (var _i = 0, patterns_1 = patterns; _i < patterns_1.length; _i++) { - var pattern = patterns_1[_i]; - var _loop_7 = function (match) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (result.some(function (entry) { return entry.name === match; })) - return "continue"; - result.push(createCompletionEntryForModule(match, "external module name" /* externalModuleName */, span)); - }; - for (var _a = 0, _b = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host); _a < _b.length; _a++) { - var match = _b[_a]; - _loop_7(match); - } - } - } - else if (ts.startsWith(path, fragment)) { - if (patterns.length === 1) { - if (result.some(function (entry) { return entry.name === path; })) - return "continue"; - result.push(createCompletionEntryForModule(path, "external module name" /* externalModuleName */, span)); - } - } - }; for (var path in paths) { - _loop_6(path); + var patterns = paths[path]; + if (paths.hasOwnProperty(path) && patterns) { + var _loop_7 = function (pathCompletion) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === pathCompletion; })) { + result.push(createCompletionEntryForModule(pathCompletion, "external module name" /* externalModuleName */, span)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { + var pathCompletion = _a[_i]; + _loop_7(pathCompletion); + } + } } } if (compilerOptions.moduleResolution === ts.ModuleResolutionKind.NodeJs) { @@ -80064,50 +80267,59 @@ var ts; }); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); - for (var _i = 0, _a = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _i < _a.length; _i++) { - var moduleName = _a[_i]; + for (var _b = 0, _c = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _b < _c.length; _b++) { + var moduleName = _c[_b]; result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); } return result; } - function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { - if (host.readDirectory) { - var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; - if (parsed) { - // The prefix has two effective parts: the directory path and the base component after the filepath that is not a - // full directory component. For example: directory/path/of/prefix/base* - var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); - var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); - var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); - var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); - // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call - var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; - var normalizedSuffix = ts.normalizePath(parsed.suffix); - var baseDirectory = ts.combinePaths(baseUrl, expandedPrefixDirectory); - var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; - // If we have a suffix, then we need to read the directory all the way down. We could create a glob - // that encodes the suffix, but we would have to escape the character "?" which readDirectory - // doesn't support. For now, this is safer but slower - var includeGlob = normalizedSuffix ? "**/*" : "./*"; - var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]); - if (matches) { - var result = []; - // Trim away prefix and suffix - for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { - var match = matches_1[_i]; - var normalizedMatch = ts.normalizePath(match); - if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { - continue; - } - var start = completePrefix.length; - var length_7 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); - } - return result; - } - } + function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { + if (!ts.endsWith(path, "*")) { + // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. + return !ts.stringContains(path, "*") && ts.startsWith(path, fragment) ? [path] : ts.emptyArray; } - return undefined; + var pathPrefix = path.slice(0, path.length - 1); + if (!ts.startsWith(fragment, pathPrefix)) { + return ts.emptyArray; + } + var remainingFragment = fragment.slice(pathPrefix.length); + return ts.flatMap(patterns, function (pattern) { return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); }); + } + function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { + if (!host.readDirectory) { + return undefined; + } + var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; + if (!parsed) { + return undefined; + } + // The prefix has two effective parts: the directory path and the base component after the filepath that is not a + // full directory component. For example: directory/path/of/prefix/base* + var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); + var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); + var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); + var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); + // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call + var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; + var normalizedSuffix = ts.normalizePath(parsed.suffix); + // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". + var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); + var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; + // If we have a suffix, then we need to read the directory all the way down. We could create a glob + // that encodes the suffix, but we would have to escape the character "?" which readDirectory + // doesn't support. For now, this is safer but slower + var includeGlob = normalizedSuffix ? "**/*" : "./*"; + var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]); + // Trim away prefix and suffix + return ts.mapDefined(matches, function (match) { + var normalizedMatch = ts.normalizePath(match); + if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { + return; + } + var start = completePrefix.length; + var length = normalizedMatch.length - start - normalizedSuffix.length; + return ts.removeFileExtension(normalizedMatch.substr(start, length)); + }); } function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) { // Check If this is a nested module @@ -80359,8 +80571,8 @@ var ts; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, options) { if (ts.isInReferenceComment(sourceFile, position)) { - var entries_2 = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); - return entries_2 && pathCompletionsInfo(entries_2); + var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); + return entries && pathCompletionsInfo(entries); } if (ts.isInString(sourceFile, position)) { return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log); @@ -80374,13 +80586,33 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion; - if (sourceFile.languageVariant === 1 /* JSX */ && - location && location.parent && location.parent.kind === 253 /* JsxClosingElement */) { + switch (completionData.kind) { + case 0 /* Data */: + return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, options.includeInsertTextCompletions); + case 1 /* JsDocTagName */: + // If the current position is a jsDoc tag name, only tag names should be provided for completion + return jsdocCompletionInfo(ts.JsDoc.getJSDocTagNameCompletions()); + case 2 /* JsDocTag */: + // If the current position is a jsDoc tag, only tags should be provided for completion + return jsdocCompletionInfo(ts.JsDoc.getJSDocTagCompletions()); + case 3 /* JsDocParameterName */: + return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag)); + default: + throw ts.Debug.assertNever(completionData); + } + } + Completions.getCompletionsAtPosition = getCompletionsAtPosition; + function jsdocCompletionInfo(entries) { + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; + } + function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, includeInsertTextCompletions) { + var symbols = completionData.symbols, completionKind = completionData.completionKind, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion; + if (sourceFile.languageVariant === 1 /* JSX */ && location && location.parent && ts.isJsxClosingElement(location.parent)) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. // For example: - // var x =
completion list at "1" will contain "div" with type any + // var x =
+ // The completion list at "1" will contain "div" with type any var tagName = location.parent.parent.openingElement.tagName; return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [{ @@ -80390,37 +80622,37 @@ var ts; sortText: "0", }] }; } - if (request) { - var entries_3 = request.kind === "JsDocTagName" - // If the current position is a jsDoc tag name, only tag names should be provided for completion - ? ts.JsDoc.getJSDocTagNameCompletions() - : request.kind === "JsDocTag" - // If the current position is a jsDoc tag, only tags should be provided for completion - ? ts.JsDoc.getJSDocTagCompletions() - : ts.JsDoc.getJSDocParameterNameCompletions(request.tag); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_3 }; - } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, recommendedCompletion, symbolToOriginInfoMap); getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap); + getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, recommendedCompletion, symbolToOriginInfoMap); } // TODO add filter for keyword based on type/value/namespace and also location // Add all keywords if // - this is not a member completion list (all the keywords) // - other filters are enabled in required scenario so add those keywords + var isMemberCompletion = isMemberCompletionKind(completionKind); if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { ts.addRange(entries, getKeywordCompletions(keywordFilters)); } - return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: completionKind === 1 /* Global */, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + } + function isMemberCompletionKind(kind) { + switch (kind) { + case 0 /* ObjectPropertyDeclaration */: + case 3 /* MemberLike */: + case 2 /* PropertyAccess */: + return true; + default: + return false; + } } - Completions.getCompletionsAtPosition = getCompletionsAtPosition; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location @@ -80428,14 +80660,9 @@ var ts; return; } var realName = ts.unescapeLeadingUnderscores(name); - if (uniqueNames.has(realName) || ts.isStringANonContextualKeyword(realName)) { - return; - } - uniqueNames.set(realName, true); - var displayName = getCompletionEntryDisplayName(realName, target, /*performCharacterChecks*/ true, /*allowStringLiteral*/ false); - if (displayName) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { entries.push({ - name: displayName, + name: realName, kind: "warning" /* warning */, kindModifiers: "", sortText: "1" @@ -80443,12 +80670,14 @@ var ts; } }); } - function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion) { - // Try to get a valid display name for this symbol, if we could not find one, then ignore it. - // We would like to only show things that can be added after a dot, so for instance numeric properties can - // not be accessed with a dot (a.1 <- invalid) - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin); - if (!displayName) { + function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, includeInsertTextCompletions) { + var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind); + if (!info) { + return undefined; + } + var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; + ts.Debug.assert(!(needsConvertPropertyAccess && !propertyAccessToConvert)); + if (needsConvertPropertyAccess && !includeInsertTextCompletions) { return undefined; } // TODO(drosen): Right now we just permit *all* semantic meanings when calling @@ -80459,12 +80688,17 @@ var ts; // Use a 'sortText' of 0' so that all symbol completion entries come before any other // entries (like JavaScript identifier entries). return { - name: displayName, + name: name, kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", source: getSourceFromOrigin(origin), - hasAction: trueOrUndefined(origin !== undefined), + // TODO: GH#20619 Use configured quote style + insertText: needsConvertPropertyAccess ? "[\"" + name + "\"]" : undefined, + replacementSpan: needsConvertPropertyAccess + ? ts.createTextSpanFromBounds(ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile).getStart(sourceFile), propertyAccessToConvert.name.end) + : undefined, + hasAction: trueOrUndefined(needsConvertPropertyAccess || origin !== undefined), isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), }; } @@ -80478,7 +80712,7 @@ var ts; function getSourceFromOrigin(origin) { return origin && ts.stripQuotes(origin.moduleSymbol.name); } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap) { + function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, includeInsertTextCompletions, propertyAccessToConvert, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); // Tracks unique names. // We don't set this for global variables or completions from external module exports, because we can have multiple of those. @@ -80488,7 +80722,7 @@ var ts; for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { var symbol = symbols_4[_i]; var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; - var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion); + var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, includeInsertTextCompletions); if (!entry) { continue; } @@ -80531,7 +80765,7 @@ var ts; // foo({ // '/*completion position*/' // }); - return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, typeChecker, compilerOptions.target, log); + return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, sourceFile, typeChecker, compilerOptions.target, log); } else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { // Get all names of properties on the expression @@ -80541,7 +80775,7 @@ var ts; // let a: A; // a['/*completion position*/'] var type = typeChecker.getTypeAtLocation(node.parent.expression); - return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, type, typeChecker, compilerOptions.target, log); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); } else if (node.parent.kind === 239 /* ImportDeclaration */ || node.parent.kind === 245 /* ExportDeclaration */ || ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent) @@ -80552,7 +80786,7 @@ var ts; // import x = require("/*completion position*/"); // var y = require("/*completion position*/"); // export * from "/*completion position*/"; - var entries = Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker); + var entries = Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker); return pathCompletionsInfo(entries); } else if (ts.isIndexedAccessTypeNode(node.parent.parent)) { @@ -80563,7 +80797,7 @@ var ts; // } // let x: Foo["/*completion position*/"] var type = typeChecker.getTypeFromTypeNode(node.parent.parent.objectType); - return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, type, typeChecker, compilerOptions.target, log); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); } else { var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); @@ -80589,11 +80823,11 @@ var ts; entries: entries, }; } - function getStringLiteralCompletionEntriesFromPropertyAssignment(element, typeChecker, target, log) { + function getStringLiteralCompletionEntriesFromPropertyAssignment(element, sourceFile, typeChecker, target, log) { var type = typeChecker.getContextualType(element.parent); var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false, typeChecker, target, log, /*allowStringLiteral*/ true); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, sourceFile, typeChecker, target, log, 4 /* String */); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -80613,10 +80847,10 @@ var ts; } return undefined; } - function getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(stringLiteralNode, type, typeChecker, target, log) { + function getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(stringLiteralNode, sourceFile, type, typeChecker, target, log) { var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, stringLiteralNode, /*performCharacterChecks*/ false, typeChecker, target, log, /*allowStringLiteral*/ true); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, stringLiteralNode, sourceFile, typeChecker, target, log, 4 /* String */); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -80686,24 +80920,23 @@ var ts; } function getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, _a, allSourceFiles) { var name = _a.name, source = _a.source; - var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true }, compilerOptions.target); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true, includeInsertTextCompletions: true }, compilerOptions.target); if (!completionData) { return { type: "none" }; } - var symbols = completionData.symbols, location = completionData.location, allowStringLiteral = completionData.allowStringLiteral, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, request = completionData.request, previousToken = completionData.previousToken; - if (request) { - return { type: "request", request: request }; + if (completionData.kind !== 0 /* Data */) { + return { type: "request", request: completionData }; } + var symbols = completionData.symbols, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken; // Find the symbol with the matching entry name. // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - var symbol = ts.find(symbols, function (s) { - var origin = symbolToOriginInfoMap[ts.getSymbolId(s)]; - return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral, origin) === name - && getSourceFromOrigin(origin) === source; - }); - return symbol ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken } : { type: "none" }; + return ts.firstDefined(symbols, function (symbol) { + var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind); + return info && info.name === name && getSourceFromOrigin(origin) === source ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken } : undefined; + }) || { type: "none" }; } function getSymbolName(symbol, origin, target) { return origin && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ @@ -80721,11 +80954,11 @@ var ts; case "request": { var request = symbolCompletion.request; switch (request.kind) { - case "JsDocTagName": + case 1 /* JsDocTagName */: return ts.JsDoc.getJSDocTagNameCompletionDetails(name); - case "JsDocTag": + case 2 /* JsDocTag */: return ts.JsDoc.getJSDocTagCompletionDetails(name); - case "JsDocParameterName": + case 3 /* JsDocParameterName */: return ts.JsDoc.getJSDocParameterNameCompletionDetails(name); default: return ts.Debug.assertNever(request); @@ -80759,9 +80992,11 @@ var ts; Completions.getCompletionEntryDetails = getCompletionEntryDetails; function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - if (!symbolOriginInfo) { - return { codeActions: undefined, sourceDisplay: undefined }; - } + return symbolOriginInfo + ? getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) + : { codeActions: undefined, sourceDisplay: undefined }; + } + function getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { var moduleSymbol = symbolOriginInfo.moduleSymbol, isDefaultExport = symbolOriginInfo.isDefaultExport; var exportedSymbol = ts.skipAlias(symbol.exportSymbol || symbol, checker); var moduleSymbols = getAllReExportingModules(exportedSymbol, checker, allSourceFiles); @@ -80799,6 +81034,22 @@ var ts; return completion.type === "symbol" ? completion.symbol : undefined; } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; + var CompletionDataKind; + (function (CompletionDataKind) { + CompletionDataKind[CompletionDataKind["Data"] = 0] = "Data"; + CompletionDataKind[CompletionDataKind["JsDocTagName"] = 1] = "JsDocTagName"; + CompletionDataKind[CompletionDataKind["JsDocTag"] = 2] = "JsDocTag"; + CompletionDataKind[CompletionDataKind["JsDocParameterName"] = 3] = "JsDocParameterName"; + })(CompletionDataKind || (CompletionDataKind = {})); + var CompletionKind; + (function (CompletionKind) { + CompletionKind[CompletionKind["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration"; + CompletionKind[CompletionKind["Global"] = 1] = "Global"; + CompletionKind[CompletionKind["PropertyAccess"] = 2] = "PropertyAccess"; + CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike"; + CompletionKind[CompletionKind["String"] = 4] = "String"; + CompletionKind[CompletionKind["None"] = 5] = "None"; + })(CompletionKind || (CompletionKind = {})); function getRecommendedCompletion(currentToken, checker) { var ty = getContextualType(currentToken, checker); var symbol = ty && ty.symbol; @@ -80856,7 +81107,6 @@ var ts; return symbol.declarations.some(function (d) { return d.kind === 269 /* SourceFile */; }); } function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, target) { - var request; var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) @@ -80871,7 +81121,7 @@ var ts; if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { // The current position is next to the '@' sign, when no tag name being provided yet. // Provide a full list of tag names - request = { kind: "JsDocTagName" }; + return { kind: 1 /* JsDocTagName */ }; } else { // When completion is requested without "@", we will have check to make sure that @@ -80892,7 +81142,7 @@ var ts; // */ var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); if (!(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/))) { - request = { kind: "JsDocTag" }; + return { kind: 2 /* JsDocTag */ }; } } } @@ -80902,7 +81152,7 @@ var ts; var tag = getJsDocTagAtPosition(currentToken, position); if (tag) { if (tag.tagName.pos <= position && position <= tag.tagName.end) { - request = { kind: "JsDocTagName" }; + return { kind: 1 /* JsDocTagName */ }; } if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 271 /* JSDocTypeExpression */) { currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true); @@ -80915,25 +81165,9 @@ var ts; } } if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { - request = { kind: "JsDocParameterName", tag: tag }; + return { kind: 3 /* JsDocParameterName */, tag: tag }; } } - if (request) { - return { - symbols: ts.emptyArray, - isGlobalCompletion: false, - isMemberCompletion: false, - allowStringLiteral: false, - isNewIdentifierLocation: false, - location: undefined, - isRightOfDot: false, - request: request, - keywordFilters: 0 /* None */, - symbolToOriginInfoMap: undefined, - recommendedCompletion: undefined, - previousToken: undefined, - }; - } if (!insideJsDocTagTypeExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal // comment or the plain text part of a jsDoc comment, so no completion should be available @@ -80958,6 +81192,7 @@ var ts; // Also determine whether we are trying to complete with members of that node // or attributes of a JSX tag. var node = currentToken; + var propertyAccessToConvert; var isRightOfDot = false; var isRightOfOpenTag = false; var isStartingCloseTag = false; @@ -80970,18 +81205,19 @@ var ts; } var parent = contextToken.parent; if (contextToken.kind === 23 /* DotToken */) { - if (parent.kind === 180 /* PropertyAccessExpression */) { - node = contextToken.parent.expression; - isRightOfDot = true; - } - else if (parent.kind === 144 /* QualifiedName */) { - node = contextToken.parent.left; - isRightOfDot = true; - } - else { - // There is nothing that precedes the dot, so this likely just a stray character - // or leading into a '...' token. Just bail out instead. - return undefined; + isRightOfDot = true; + switch (parent.kind) { + case 180 /* PropertyAccessExpression */: + propertyAccessToConvert = parent; + node = propertyAccessToConvert.expression; + break; + case 144 /* QualifiedName */: + node = parent.left; + break; + default: + // There is nothing that precedes the dot, so this likely just a stray character + // or leading into a '...' token. Just bail out instead. + return undefined; } } else if (sourceFile.languageVariant === 1 /* JSX */) { @@ -81017,10 +81253,8 @@ var ts; } } var semanticStart = ts.timestamp(); - var isGlobalCompletion = false; - var isMemberCompletion; - var allowStringLiteral = false; - var isNewIdentifierLocation; + var completionKind = 5 /* None */; + var isNewIdentifierLocation = false; var keywordFilters = 0 /* None */; var symbols = []; var symbolToOriginInfoMap = []; @@ -81035,8 +81269,7 @@ var ts; else { symbols = tagSymbols; } - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 3 /* MemberLike */; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -81044,8 +81277,7 @@ var ts; if (!typeChecker.isUnknownSymbol(tagSymbol)) { symbols = [tagSymbol]; } - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 3 /* MemberLike */; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -81057,7 +81289,7 @@ var ts; } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); var recommendedCompletion = previousToken && getRecommendedCompletion(previousToken, typeChecker); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken }; + return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 284 /* JSDocParameterTag */: @@ -81070,9 +81302,7 @@ var ts; } function getTypeScriptMemberSymbols() { // Right of dot member completion list - isGlobalCompletion = false; - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 2 /* PropertyAccess */; // Since this is qualified name check its a type node location var isTypeLocation = insideJsDocTagTypeExpression || ts.isPartOfTypeNode(node.parent); var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); @@ -81140,7 +81370,7 @@ var ts; } if (tryGetConstructorLikeCompletionContainer(contextToken)) { // no members, only keywords - isMemberCompletion = false; + completionKind = 5 /* None */; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter @@ -81159,14 +81389,14 @@ var ts; attrsType = typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties); - isMemberCompletion = true; + completionKind = 3 /* MemberLike */; isNewIdentifierLocation = false; return true; } } } // Get all entities in the current scope. - isMemberCompletion = false; + completionKind = 5 /* None */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); if (previousToken !== contextToken) { ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); @@ -81200,13 +81430,8 @@ var ts; previousToken.getStart() : position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; - if (scopeNode) { - isGlobalCompletion = - scopeNode.kind === 269 /* SourceFile */ || - scopeNode.kind === 197 /* TemplateExpression */ || - scopeNode.kind === 260 /* JsxExpression */ || - scopeNode.kind === 208 /* Block */ || // Some blocks aren't statements, but all get global completions - ts.isStatement(scopeNode); + if (isGlobalCompletionScope(scopeNode)) { + completionKind = 1 /* Global */; } var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); @@ -81216,6 +81441,17 @@ var ts; filterGlobalCompletion(symbols); return true; } + function isGlobalCompletionScope(scopeNode) { + switch (scopeNode.kind) { + case 269 /* SourceFile */: + case 197 /* TemplateExpression */: + case 260 /* JsxExpression */: + case 208 /* Block */: + return true; + default: + return ts.isStatement(scopeNode); + } + } function filterGlobalCompletion(symbols) { ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { @@ -81284,9 +81520,10 @@ var ts; for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; // Don't add a completion for a re-export, only for the original. - // If `symbol.parent !== moduleSymbol`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. + // If `symbol.parent !== ...`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. // If `some(...)`, this comes from an `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). - if (symbol.parent !== moduleSymbol || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { + if (symbol.parent !== typeChecker.resolveExternalModuleSymbol(moduleSymbol) + || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { continue; } var isDefaultExport = symbol.name === "default" /* Default */; @@ -81434,8 +81671,7 @@ var ts; */ function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { // We're looking up possible property names from contextual/inferred/declared type. - isMemberCompletion = true; - allowStringLiteral = true; + completionKind = 0 /* ObjectPropertyDeclaration */; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 179 /* ObjectLiteralExpression */) { @@ -81508,7 +81744,7 @@ var ts; if (!moduleSpecifier) { return false; } - isMemberCompletion = true; + completionKind = 3 /* MemberLike */; isNewIdentifierLocation = false; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); if (!moduleSpecifierSymbol) { @@ -81525,7 +81761,7 @@ var ts; */ function getGetClassLikeCompletionSymbols(classLikeDeclaration) { // We're looking up possible property names from parent type. - isMemberCompletion = true; + completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for class elements @@ -82007,51 +82243,35 @@ var ts; return node.getStart() <= position && position <= node.getEnd(); } } - /** - * Get the name to be display in completion from a given symbol. - * - * @return undefined if the name is of external module - */ - function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin) { + function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind) { var name = getSymbolName(symbol, origin, target); - if (!name) + if (name === undefined + // If the symbol is external module, don't show it in the completion list + // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) + || symbol.flags & 1536 /* Module */ && ts.startsWithQuote(name) + // If the symbol is the internal name of an ES symbol, it is not a valid entry. Internal names for ES symbols start with "__@" + || ts.isKnownSymbol(symbol)) { return undefined; - // First check of the displayName is not external module; if it is an external module, it is not valid entry - if (symbol.flags & 1920 /* Namespace */) { - var firstCharCode = name.charCodeAt(0); - if (ts.isSingleOrDoubleQuote(firstCharCode)) { - // If the symbol is external module, don't show it in the completion list - // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) + } + var validIdentiferResult = { name: name, needsConvertPropertyAccess: false }; + if (ts.isIdentifierText(name, target)) + return validIdentiferResult; + switch (kind) { + case 5 /* None */: + case 1 /* Global */: + case 3 /* MemberLike */: return undefined; - } + case 0 /* ObjectPropertyDeclaration */: + // TODO: GH#18169 + return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; + case 2 /* PropertyAccess */: + // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547 + return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true }; + case 4 /* String */: + return validIdentiferResult; + default: + ts.Debug.assertNever(kind); } - // If the symbol is for a member of an object type and is the internal name of an ES - // symbol, it is not a valid entry. Internal names for ES symbols start with "__@" - if (symbol.flags & 106500 /* ClassMember */) { - var escapedName = symbol.escapedName; - if (escapedName.length >= 3 && - escapedName.charCodeAt(0) === 95 /* _ */ && - escapedName.charCodeAt(1) === 95 /* _ */ && - escapedName.charCodeAt(2) === 64 /* at */) { - return undefined; - } - } - return getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral); - } - /** - * Get a displayName from a given for completion list, performing any necessary quotes stripping - * and checking whether the name is valid identifier name. - */ - function getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral) { - // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an - // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. - // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. - // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. - if (performCharacterChecks && !ts.isIdentifierText(name, target)) { - // TODO: GH#18169 - return allowStringLiteral ? JSON.stringify(name) : undefined; - } - return name; } // A cache of completion entries for keywords, these do not change between sessions var _keywordCompletions = []; @@ -82069,6 +82289,8 @@ var ts; return getFilteredKeywordCompletions(isClassMemberCompletionKeywordText); case 2 /* ConstructorParameterKeywords */: return getFilteredKeywordCompletions(isConstructorParameterCompletionKeywordText); + default: + ts.Debug.assertNever(keywordFilter); } } function getAllKeywordCompletions() { @@ -82185,11 +82407,7 @@ var ts; (function (DocumentHighlights) { function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); - // Note that getTouchingWord indicates failure by returning the sourceFile node. - if (node === sourceFile) - return undefined; - ts.Debug.assert(node.parent !== undefined); - if (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent)) { + if (node.parent && (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent))) { // For a JSX element, just highlight the matching tag, not all references. var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; var highlightSpans = [openingElement, closingElement].map(function (_a) { @@ -82198,7 +82416,7 @@ var ts; }); return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; } - return getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); + return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { @@ -82208,8 +82426,8 @@ var ts; kind: "none" /* none */ }; } - function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { - var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); + function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) { + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } function convertReferencedSymbols(referenceEntries) { @@ -83292,7 +83510,7 @@ var ts; } /** If at an export specifier, go to the symbol it refers to. */ function skipExportSpecifierSymbol(symbol, checker) { - // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. + // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. if (symbol.declarations) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; @@ -83349,12 +83567,12 @@ var ts; function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { // A node in a JSDoc comment can't have an implementation anyway. var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); - var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; - function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { if (node.kind === 269 /* SourceFile */) { return undefined; } @@ -83374,7 +83592,7 @@ var ts; } else { // Perform "Find all References" and retrieve only those that are implementations - return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { @@ -83382,14 +83600,14 @@ var ts; return ts.map(x, toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; - function getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, options) { + function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); - return FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); + return FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); @@ -83528,10 +83746,11 @@ var ts; var Core; (function (Core) { /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ - function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { + function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - if (node.kind === 269 /* SourceFile */) { - return undefined; + if (ts.isSourceFile(node)) { + var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); + return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles); } if (!options.implementations) { var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); @@ -83544,11 +83763,7 @@ var ts; // Could not find a symbol e.g. unknown identifier if (!symbol) { // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. - if (!options.implementations && node.kind === 9 /* StringLiteral */) { - return getReferencesForStringLiteral(node, sourceFiles, cancellationToken); - } - // Can't have references to something that we have no symbol for. - return undefined; + return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) { return getReferencedSymbolsForModule(program, symbol, sourceFiles); @@ -83743,6 +83958,9 @@ var ts; State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { if (searchOptions === void 0) { searchOptions = {}; } // Note: if this is an external module symbol, the name doesn't include quotes. + // Note: getLocalSymbolForExportDefault handles `export default class C {}`, but not `export default C` or `export { C as default }`. + // The other two forms seem to be handled downstream (e.g. in `skipPastExportOrImportSpecifier`), so special-casing the first form + // here appears to be intentional). var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; var escapedText = ts.escapeLeadingUnderscores(text); var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); @@ -84898,21 +85116,9 @@ var ts; var GoToDefinition; (function (GoToDefinition) { function getDefinitionAtPosition(program, sourceFile, position) { - /// Triple slash reference comments - var comment = findReferenceInPosition(sourceFile.referencedFiles, position); - if (comment) { - var referenceFile = ts.tryResolveScriptReference(program, sourceFile, comment); - if (referenceFile) { - return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)]; - } - // Might still be on jsdoc, so keep looking. - } - // Type reference directives - var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); - if (typeReferenceDirective) { - var referenceFile = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); - return referenceFile && referenceFile.resolvedFileName && - [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; + var reference = getReferenceAtPosition(sourceFile, position, program); + if (reference) { + return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)]; } var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { @@ -85000,6 +85206,21 @@ var ts; return getDefinitionFromSymbol(typeChecker, symbol, node); } GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; + function getReferenceAtPosition(sourceFile, position, program) { + var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); + if (referencePath) { + var file = ts.tryResolveScriptReference(program, sourceFile, referencePath); + return file && { fileName: referencePath.fileName, file: file }; + } + var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + if (typeReferenceDirective) { + var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); + var file = reference && program.getSourceFile(reference.resolvedFileName); + return file && { fileName: typeReferenceDirective.fileName, file: file }; + } + return undefined; + } + GoToDefinition.getReferenceAtPosition = getReferenceAtPosition; /// Goto type function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); @@ -85172,6 +85393,7 @@ var ts; } return undefined; } + GoToDefinition.findReferenceInPosition = findReferenceInPosition; function getDefinitionInfoForFileReference(name, targetFileName) { return { fileName: targetFileName, @@ -85319,7 +85541,7 @@ var ts; function forEachUnique(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { - if (ts.indexOf(array, array[i]) === i) { + if (array.indexOf(array[i]) === i) { var result = callback(array[i], i); if (result) { return result; @@ -85853,7 +86075,7 @@ var ts; if (!shouldKeepItem(declaration, checker)) { continue; } - // It was a match! If the pattern has dots in it, then also see if the + // It was a match! If the pattern has dots in it, then also see if the // declaration container matches as well. var containerMatches = matches; if (patternMatcher.patternContainsDots) { @@ -85882,8 +86104,8 @@ var ts; function allMatchesAreCaseSensitive(matches) { ts.Debug.assert(matches.length > 0); // This is a case sensitive match, only if all the submatches were case sensitive. - for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { - var match = matches_2[_i]; + for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { + var match = matches_1[_i]; if (!match.isCaseSensitive) { return false; } @@ -85952,8 +86174,8 @@ var ts; function bestMatchKind(matches) { ts.Debug.assert(matches.length > 0); var bestMatchKind = ts.PatternMatchKind.camelCase; - for (var _i = 0, matches_3 = matches; _i < matches_3.length; _i++) { - var match = matches_3[_i]; + for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { + var match = matches_2[_i]; var kind = match.kind; if (kind < bestMatchKind) { bestMatchKind = kind; @@ -87598,7 +87820,7 @@ var ts; // import "mod"; // import d from "mod" // import {a as A } from "mod"; - // import * as NS from "mod" + // import * as NS from "mod" // import d, {a, b as B} from "mod" // import i = require("mod"); // import("mod"); @@ -87698,9 +87920,16 @@ var ts; symbol.parent.flags & 1536 /* Module */) { return undefined; } - var displayName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - return kind ? getRenameInfoSuccess(displayName, typeChecker.getFullyQualifiedName(symbol), kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile) : undefined; + if (!kind) { + return undefined; + } + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 145 /* ComputedPropertyName */) + ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) + : undefined; + var displayName = specifierName || typeChecker.symbolToString(symbol); + var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); + return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } } else if (node.kind === 9 /* StringLiteral */) { @@ -87934,7 +88163,7 @@ var ts; function getArgumentIndex(argumentsList, node) { // The list we got back can include commas. In the presence of errors it may // also just have nodes without commas. For example "Foo(a b c)" will have 3 - // args without commas. We want to find what index we're at. So we count + // args without commas. We want to find what index we're at. So we count // forward until we hit ourselves, only incrementing the index if it isn't a // comma. // @@ -87960,12 +88189,12 @@ var ts; // The argument count for a list is normally the number of non-comma children it has. // For example, if you have "Foo(a,b)" then there will be three children of the arg // list 'a' '' 'b'. So, in this case the arg count will be 2. However, there - // is a small subtlety. If you have "Foo(a,)", then the child list will just have + // is a small subtlety. If you have "Foo(a,)", then the child list will just have // 'a' ''. So, in the case where the last child is a comma, we increase the // arg count by one to compensate. // - // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then - // we'll have: 'a' '' '' + // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then + // we'll have: 'a' '' '' // That will give us 2 non-commas. We then add one for the last comma, giving us an // arg count of 3. var listChildren = argumentsList.getChildren(); @@ -87986,9 +88215,11 @@ var ts; // not enough to put us in the substitution expression; we should consider ourselves part of // the *next* span's expression by offsetting the index (argIndex = (spanIndex + 1) + 1). // + // tslint:disable no-double-space // Example: f `# abcd $#{# 1 + 1# }# efghi ${ #"#hello"# } # ` // ^ ^ ^ ^ ^ ^ ^ ^ ^ // Case: 1 1 3 2 1 3 2 2 1 + // tslint:enable no-double-space ts.Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node."); if (ts.isTemplateLiteralKind(node.kind)) { if (ts.isInsideTemplateLiteral(node, position)) { @@ -88035,9 +88266,8 @@ var ts; // Otherwise, we will not show signature help past the expression. // For example, // - // ` ${ 1 + 1 foo(10) - // | | - // + // ` ${ 1 + 1 foo(10) + // | | // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. if (template.kind === 197 /* TemplateExpression */) { @@ -88266,7 +88496,7 @@ var ts; } SymbolDisplay.getSymbolModifiers = getSymbolModifiers; // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location - function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning) { + function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning, alias) { if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } var displayParts = []; var documentation; @@ -88276,6 +88506,7 @@ var ts; var hasAddedSymbolInfo; var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); var type; + var documentationFromAlias; // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -88391,6 +88622,7 @@ var ts; } } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { + addAliasPrefixIfNecessary(); if (ts.getDeclarationOfKind(symbol, 200 /* ClassExpression */)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) @@ -88406,14 +88638,14 @@ var ts; writeTypeParametersOfSymbol(symbol, sourceFile); } if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(109 /* InterfaceKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } if (symbolFlags & 524288 /* TypeAlias */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(138 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); @@ -88424,7 +88656,7 @@ var ts; ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 1024 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { displayParts.push(ts.keywordPart(76 /* ConstKeyword */)); displayParts.push(ts.spacePart()); @@ -88434,7 +88666,7 @@ var ts; addFullSymbolName(symbol); } if (symbolFlags & 1536 /* Module */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); var declaration = ts.getDeclarationOfKind(symbol, 234 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 71 /* Identifier */; displayParts.push(ts.keywordPart(isNamespace ? 129 /* NamespaceKeyword */ : 128 /* ModuleKeyword */)); @@ -88442,7 +88674,7 @@ var ts; addFullSymbolName(symbol); } if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); displayParts.push(ts.textPart("type parameter")); displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); @@ -88475,7 +88707,7 @@ var ts; else if (declaration.kind === 232 /* TypeAliasDeclaration */) { // Type alias type parameter // For example - // type list = T[]; // Both T will go through same code path + // type list = T[]; // Both T will go through same code path addInPrefix(); displayParts.push(ts.keywordPart(138 /* TypeKeyword */)); displayParts.push(ts.spacePart()); @@ -88500,7 +88732,23 @@ var ts; } } if (symbolFlags & 2097152 /* Alias */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); + if (!hasAddedSymbolInfo) { + var resolvedSymbol = typeChecker.getAliasedSymbol(symbol); + if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) { + var resolvedNode = resolvedSymbol.declarations[0]; + var declarationName = ts.getNameOfDeclaration(resolvedNode); + if (declarationName) { + var isExternalModuleDeclaration = ts.isModuleWithStringLiteralName(resolvedNode) && + ts.hasModifier(resolvedNode, 2 /* Ambient */); + var shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; + var resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, resolvedSymbol, ts.getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, semanticMeaning, shouldUseAliasName ? symbol : resolvedSymbol); + displayParts.push.apply(displayParts, resolvedInfo.displayParts); + displayParts.push(ts.lineBreakPart()); + documentationFromAlias = resolvedInfo.documentation; + } + } + } switch (symbol.declarations[0].kind) { case 237 /* NamespaceExportDeclaration */: displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); @@ -88546,7 +88794,7 @@ var ts; if (symbolKind !== "" /* unknown */) { if (type) { if (isThisExpression) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(99 /* ThisKeyword */)); } else { @@ -88614,23 +88862,36 @@ var ts; } } } + if (documentation.length === 0 && documentationFromAlias) { + documentation = documentationFromAlias; + } return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; - function addNewLineIfDisplayPartsExist() { + function prefixNextMeaning() { if (displayParts.length) { displayParts.push(ts.lineBreakPart()); } + addAliasPrefixIfNecessary(); + } + function addAliasPrefixIfNecessary() { + if (alias) { + pushTypePart("alias" /* alias */); + displayParts.push(ts.spacePart()); + } } function addInPrefix() { displayParts.push(ts.spacePart()); displayParts.push(ts.keywordPart(92 /* InKeyword */)); displayParts.push(ts.spacePart()); } - function addFullSymbolName(symbol, enclosingDeclaration) { - var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */); + function addFullSymbolName(symbolToDisplay, enclosingDeclaration) { + if (alias && symbolToDisplay === symbol) { + symbolToDisplay = alias; + } + var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */); ts.addRange(displayParts, fullSymbolDisplayParts); } function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); if (symbolKind) { pushTypePart(symbolKind); if (symbol && !ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) { @@ -89216,7 +89477,7 @@ var ts; // Leave comments alone rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1 /* Ignore */), rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, formatting.anyContext, 1 /* Ignore */), - rule("NoSpaceBeforeColon", anyToken, 56 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("NotSpaceBeforeColon", anyToken, 56 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 8 /* Delete */), rule("SpaceAfterColon", 56 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2 /* Space */), rule("NoSpaceBeforeQuestionMark", anyToken, 55 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), // insert space after '?' only when it is used in conditional operator @@ -89234,10 +89495,10 @@ var ts; rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), // More unary operator special-casing. - // DevDiv 181814: Be careful when removing leading whitespace + // DevDiv 181814: Be careful when removing leading whitespace // around unary operators. Examples: - // 1 - -2 --X--> 1--2 - // a + ++b --X--> a+++b + // 1 - -2 --X--> 1--2 + // a + ++b --X--> a+++b rule("SpaceAfterPostincrementWhenFollowedByAdd", 43 /* PlusPlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterAddWhenFollowedByUnaryPlus", 37 /* PlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterAddWhenFollowedByPreincrement", 37 /* PlusToken */, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), @@ -89413,6 +89674,8 @@ var ts; rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), rule("SpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2 /* Space */), rule("NoSpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8 /* Delete */), + rule("SpaceBeforeTypeAnnotation", anyToken, 56 /* ColonToken */, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 2 /* Space */), + rule("NoSpaceBeforeTypeAnnotation", anyToken, 56 /* ColonToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 8 /* Delete */), ]; // These rules are lower in priority than user-configurable. Rules earlier in this list have priority over rules later in the list. var lowPriorityCommonRules = [ @@ -89518,6 +89781,17 @@ var ts; function isNotBinaryOpContext(context) { return !isBinaryOpContext(context); } + function isNotTypeAnnotationContext(context) { + return !isTypeAnnotationContext(context); + } + function isTypeAnnotationContext(context) { + var contextKind = context.contextNode.kind; + return contextKind === 150 /* PropertyDeclaration */ || + contextKind === 149 /* PropertySignature */ || + contextKind === 147 /* Parameter */ || + contextKind === 227 /* VariableDeclaration */ || + ts.isFunctionLikeKind(contextKind); + } function isConditionalOperatorContext(context) { return context.contextNode.kind === 196 /* ConditionalExpression */; } @@ -91207,11 +91481,13 @@ var ts; SmartIndenter.getContainingList = getContainingList; function getActualIndentationForListItem(node, sourceFile, options) { var containingList = getContainingList(node, sourceFile); - return containingList ? getActualIndentationFromList(containingList) : -1 /* Unknown */; - function getActualIndentationFromList(list) { - var index = ts.indexOf(list, node); - return index !== -1 ? deriveActualIndentationFromList(list, index, sourceFile, options) : -1 /* Unknown */; + if (containingList) { + var index = containingList.indexOf(node); + if (index !== -1) { + return deriveActualIndentationFromList(containingList, index, sourceFile, options); + } } + return -1 /* Unknown */; } function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) { // actual indentation should not be used when: @@ -93531,6 +93807,9 @@ var ts; return [fromPaths]; } } + if (isPathRelativeToParent(relativeToBaseUrl)) { + return [relativePath]; + } /* Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. @@ -93593,10 +93872,11 @@ var ts; return decl.name.text; } } - function tryGetModuleNameFromPaths(relativeNameWithIndex, relativeName, paths) { + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { for (var key in paths) { for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); var indexOfStar = pattern.indexOf("*"); if (indexOfStar === 0 && pattern.length === 1) { continue; @@ -93604,14 +93884,14 @@ var ts; else if (indexOfStar !== -1) { var prefix = pattern.substr(0, indexOfStar); var suffix = pattern.substr(indexOfStar + 1); - if (relativeName.length >= prefix.length + suffix.length && - ts.startsWith(relativeName, prefix) && - ts.endsWith(relativeName, suffix)) { - var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); - return key.replace("\*", matchedStar); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); } } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { return key; } } @@ -93739,7 +94019,10 @@ var ts; return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; } function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { - return ts.firstDefined(rootDirs, function (rootDir) { return getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); }); + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); } function removeExtensionAndIndexPostFix(fileName, options, addJsExtension) { var noExtension = ts.removeFileExtension(fileName); @@ -93751,7 +94034,10 @@ var ts; } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); } function getRelativePath(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -93891,8 +94177,9 @@ var ts; var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); if (defaultExport) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if ((localSymbol && localSymbol.escapedName === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, context.compilerOptions.target) === symbolName) - && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { + if ((localSymbol && localSymbol.escapedName === symbolName || + getEscapedNameForExportDefault(defaultExport) === symbolName || + moduleSymbolToValidIdentifier(moduleSymbol, context.compilerOptions.target) === symbolName) && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { // check if this symbol is already used var symbolId = ts.getUniqueSymbolId(localSymbol || defaultExport, checker); symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 1 /* Default */ }))); @@ -93904,6 +94191,21 @@ var ts; var symbolId = ts.getUniqueSymbolId(exportSymbolWithIdenticalName, checker); symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 0 /* Named */ }))); } + function getEscapedNameForExportDefault(symbol) { + return ts.firstDefined(symbol.declarations, function (declaration) { + if (ts.isExportAssignment(declaration)) { + if (ts.isIdentifier(declaration.expression)) { + return declaration.expression.escapedText; + } + } + else if (ts.isExportSpecifier(declaration)) { + ts.Debug.assert(declaration.name.escapedText === "default" /* Default */); + if (declaration.propertyName) { + return declaration.propertyName.escapedText; + } + } + }); + } }); return symbolIdActionMap.getAllActions(); } @@ -94797,6 +95099,94 @@ var ts; })(InferFromReference || (InferFromReference = {})); })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime.code], + getCodeActions: getActionsForInvalidImport + }); + function getActionsForInvalidImport(context) { + var sourceFile = context.sourceFile; + // This is the whole import statement, eg: + // import * as Bluebird from 'bluebird'; + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false).parent; + if (!ts.isImportDeclaration(node)) { + // No import quick fix for import calls + return []; + } + return getCodeFixesForImportDeclaration(context, node); + } + function getCodeFixesForImportDeclaration(context, node) { + var sourceFile = ts.getSourceFileOfNode(node); + var namespace = ts.getNamespaceDeclarationNode(node); + var opts = context.program.getCompilerOptions(); + var variations = []; + // import Bluebird from "bluebird"; + var replacement = ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(namespace.name, /*namedBindings*/ undefined), node.moduleSpecifier); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, node, replacement, { useNonAdjustedEndPosition: true }); + var changes = changeTracker.getChanges(); + variations.push({ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Replace_import_with_0), [changes[0].textChanges[0].newText]), + changes: changes + }); + if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { + // import Bluebird = require("bluebird"); + var replacement_1 = ts.createImportEqualsDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, namespace.name, ts.createExternalModuleReference(node.moduleSpecifier)); + var changeTracker_1 = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker_1.replaceNode(sourceFile, node, replacement_1, { useNonAdjustedEndPosition: true }); + var changes_1 = changeTracker_1.getChanges(); + variations.push({ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Replace_import_with_0), [changes_1[0].textChanges[0].newText]), + changes: changes_1 + }); + } + return variations; + } + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code, + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature.code, + ], + getCodeActions: getActionsForUsageOfInvalidImport + }); + function getActionsForUsageOfInvalidImport(context) { + var sourceFile = context.sourceFile; + var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 182 /* CallExpression */ : 183 /* NewExpression */; + var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); + if (!node) { + return []; + } + var expr = node.expression; + var type = context.program.getTypeChecker().getTypeAtLocation(expr); + if (!(type.symbol && type.symbol.originatingImport)) { + return []; + } + var fixes = []; + var relatedImport = type.symbol.originatingImport; + if (!ts.isImportCall(relatedImport)) { + ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); + } + var propertyAccess = ts.createPropertyAccess(expr, "default"); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, expr, propertyAccess, {}); + var changes = changeTracker.getChanges(); + fixes.push({ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Use_synthetic_default_member), + changes: changes + }); + return fixes; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); /// /// /// @@ -94814,6 +95204,7 @@ var ts; /// /// /// +/// /* @internal */ var ts; (function (ts) { @@ -98159,7 +98550,7 @@ var ts; return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } function getCompletionsAtPosition(fileName, position, options) { - if (options === void 0) { options = { includeExternalModuleExports: false }; } + if (options === void 0) { options = { includeExternalModuleExports: false, includeInsertTextCompletions: false }; } synchronizeHostData(); return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles(), options); } @@ -98649,7 +99040,7 @@ var ts; return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); } function getTodoCommentsRegExp() { - // NOTE: ?: means 'non-capture group'. It allows us to have groups without having to + // NOTE: `?:` means 'non-capture group'. It allows us to have groups without having to // filter them out later in the final result array. // TODO comments can appear in one of the following forms: // @@ -98824,19 +99215,6 @@ var ts; isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } - function isObjectLiteralElement(node) { - switch (node.kind) { - case 257 /* JsxAttribute */: - case 259 /* JsxSpreadAttribute */: - case 265 /* PropertyAssignment */: - case 266 /* ShorthandPropertyAssignment */: - case 152 /* MethodDeclaration */: - case 154 /* GetAccessor */: - case 155 /* SetAccessor */: - return true; - } - return false; - } /** * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 } */ @@ -98846,11 +99224,11 @@ var ts; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: if (node.parent.kind === 145 /* ComputedPropertyName */) { - return isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; + return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } // falls through case 71 /* Identifier */: - return isObjectLiteralElement(node.parent) && + return ts.isObjectLiteralElement(node.parent) && (node.parent.parent.kind === 179 /* ObjectLiteralExpression */ || node.parent.parent.kind === 258 /* JsxAttributes */) && node.parent.name === node ? node.parent : undefined; } @@ -99118,8 +99496,8 @@ var ts; return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node); } // Set breakpoint on identifier element of destructuring pattern - // a or ...c or d: x from - // [a, b, ...c] or { a, b } or { d: x } from destructuring pattern + // `a` or `...c` or `d: x` from + // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern if ((node.kind === 71 /* Identifier */ || node.kind === 199 /* SpreadElement */ || node.kind === 265 /* PropertyAssignment */ || @@ -99261,8 +99639,9 @@ var ts; } else { var functionDeclaration = parameter.parent; - var indexOfParameter = ts.indexOf(functionDeclaration.parameters, parameter); - if (indexOfParameter) { + var indexOfParameter = functionDeclaration.parameters.indexOf(parameter); + ts.Debug.assert(indexOfParameter !== -1); + if (indexOfParameter !== 0) { // Not a first parameter, go to previous parameter return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]); } @@ -100020,7 +100399,6 @@ var ts; return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + options + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, options); }); }; /** Get a string based representation of a completion list entry details */ - // tslint:disable-next-line type-operator-spacing (false positive) LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options, source) { var _this = this; return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index b17b978d042..34b115e106f 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -59,6 +59,7 @@ declare namespace ts { pos: number; end: number; } + type JsDocSyntaxKind = SyntaxKind.EndOfFileToken | SyntaxKind.WhitespaceTrivia | SyntaxKind.AtToken | SyntaxKind.NewLineTrivia | SyntaxKind.AsteriskToken | SyntaxKind.OpenBraceToken | SyntaxKind.CloseBraceToken | SyntaxKind.LessThanToken | SyntaxKind.OpenBracketToken | SyntaxKind.CloseBracketToken | SyntaxKind.EqualsToken | SyntaxKind.CommaToken | SyntaxKind.DotToken | SyntaxKind.Identifier | SyntaxKind.Unknown; enum SyntaxKind { Unknown = 0, EndOfFileToken = 1, @@ -2295,6 +2296,7 @@ declare namespace ts { types?: string[]; /** Paths used to compute primary types search locations */ typeRoots?: string[]; + esModuleInterop?: boolean; [option: string]: CompilerOptionsValue | JsonSourceFile | undefined; } interface TypeAcquisition { @@ -2788,7 +2790,7 @@ declare namespace ts { scanJsxAttributeValue(): SyntaxKind; reScanJsxToken(): SyntaxKind; scanJsxToken(): SyntaxKind; - scanJSDocToken(): SyntaxKind; + scanJSDocToken(): JsDocSyntaxKind; scan(): SyntaxKind; getText(): string; setText(text: string, start?: number, length?: number): void; @@ -3157,6 +3159,7 @@ declare namespace ts { function isJSDocCommentContainingNode(node: Node): boolean; function isSetAccessor(node: Node): node is SetAccessorDeclaration; function isGetAccessor(node: Node): node is GetAccessorDeclaration; + function isObjectLiteralElement(node: Node): node is ObjectLiteralElement; } declare namespace ts { function createNode(kind: SyntaxKind, pos?: number, end?: number): Node; @@ -3998,6 +4001,7 @@ declare namespace ts { } interface GetCompletionsAtPositionOptions { includeExternalModuleExports: boolean; + includeInsertTextCompletions: boolean; } interface ApplyCodeActionCommandResult { successMessage: string; @@ -4208,6 +4212,7 @@ declare namespace ts { InsertSpaceBeforeFunctionParenthesis?: boolean; PlaceOpenBraceOnNewLineForFunctions: boolean; PlaceOpenBraceOnNewLineForControlBlocks: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } interface FormatCodeSettings extends EditorSettings { insertSpaceAfterCommaDelimiter?: boolean; @@ -4225,6 +4230,7 @@ declare namespace ts { insertSpaceBeforeFunctionParenthesis?: boolean; placeOpenBraceOnNewLineForFunctions?: boolean; placeOpenBraceOnNewLineForControlBlocks?: boolean; + insertSpaceBeforeTypeAnnotation?: boolean; } interface DefinitionInfo { fileName: string; @@ -4340,6 +4346,7 @@ declare namespace ts { kind: ScriptElementKind; kindModifiers: string; sortText: string; + insertText?: 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. diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index d5f0becf4ab..91962b22cfe 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -610,9 +610,9 @@ var ts; (function (SymbolFormatFlags) { SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; // Write symbols's type argument if it is instantiated symbol - // eg. class C { p: T } <-- Show p as C.p here + // eg. class C { p: T } <-- Show p as C.p here // var a: C; - // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p + // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; // Use only external alias information to get the symbol name in the given context // eg. module m { export class c { } } import x = m.c; @@ -1258,6 +1258,7 @@ var ts; EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator"; EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping"; /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper"; + /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper"; })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {})); /** * Used by the checker, this enum keeps track of external emit helpers that should be type @@ -1703,17 +1704,6 @@ var ts; return false; } ts.contains = contains; - function indexOf(array, value) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (array[i] === value) { - return i; - } - } - } - return -1; - } - ts.indexOf = indexOf; function indexOfAnyCharCode(text, charCodes, start) { for (var i = start || 0; i < text.length; i++) { if (contains(charCodes, text.charCodeAt(i))) { @@ -3231,7 +3221,9 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop + ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 + : moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getStrictOptionValue(compilerOptions, flag) { @@ -3291,7 +3283,7 @@ var ts; ts.getNormalizedPathFromPathComponents = getNormalizedPathFromPathComponents; function getNormalizedPathComponentsOfUrl(url) { // Get root length of http://www.website.com/folder1/folder2/ - // In this example the root is: http://www.website.com/ + // In this example the root is: http://www.website.com/ // normalized path components should be ["http://www.website.com/", "folder1", "folder2"] var urlLength = url.length; // Initial root length is http:// part @@ -3321,7 +3313,7 @@ var ts; } else { // Can't find the host assume the rest of the string as component - // but make sure we append "/" to it as root is not joined using "/" + // but make sure we append "/" to it as root is not joined using "/" // eg. if url passed in was http://website.com we want to use root as [http://website.com/] // so that other path manipulations will be correct and it can be merged with relative paths correctly return [url + ts.directorySeparator]; @@ -3340,7 +3332,7 @@ var ts; var directoryComponents = getNormalizedPathOrUrlComponents(directoryPathOrUrl, currentDirectory); if (directoryComponents.length > 1 && lastOrUndefined(directoryComponents) === "") { // If the directory path given was of type test/cases/ then we really need components of directory to be only till its name - // that is ["test", "cases", ""] needs to be actually ["test", "cases"] + // that is ["test", "cases", ""] needs to be actually ["test", "cases"] directoryComponents.pop(); } // Find the component that differs @@ -5079,6 +5071,8 @@ var ts; unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), + An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."), + An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -5193,6 +5187,7 @@ var ts; Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."), Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), @@ -5247,7 +5242,7 @@ var ts; Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), - const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."), A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), @@ -5414,6 +5409,9 @@ var ts; Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"), + Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), + Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), + Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -5728,6 +5726,8 @@ var ts; Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), + A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime: diag(7038, ts.DiagnosticCategory.Error, "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038", "A namespace-style import cannot be called or constructed, and will cause a failure at runtime."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -5817,6 +5817,8 @@ var ts; Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), + Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), + Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), }; })(ts || (ts = {})); /// @@ -5964,7 +5966,7 @@ var ts; /* As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers IdentifierStart :: - Can contain Unicode 3.0.0 categories: + Can contain Unicode 3.0.0 categories: Uppercase letter (Lu), Lowercase letter (Ll), Titlecase letter (Lt), @@ -5972,7 +5974,7 @@ var ts; Other letter (Lo), or Letter number (Nl). IdentifierPart :: = - Can contain IdentifierStart + Unicode 3.0.0 categories: + Can contain IdentifierStart + Unicode 3.0.0 categories: Non-spacing mark (Mn), Combining spacing mark (Mc), Decimal number (Nd), or @@ -5986,7 +5988,7 @@ var ts; /* As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers IdentifierStart :: - Can contain Unicode 6.2 categories: + Can contain Unicode 6.2 categories: Uppercase letter (Lu), Lowercase letter (Ll), Titlecase letter (Lt), @@ -5994,7 +5996,7 @@ var ts; Other letter (Lo), or Letter number (Nl). IdentifierPart :: - Can contain IdentifierStart + Unicode 6.2 categories: + Can contain IdentifierStart + Unicode 6.2 categories: Non-spacing mark (Mn), Combining spacing mark (Mc), Decimal number (Nd), @@ -7550,7 +7552,7 @@ var ts; break; } } - tokenValue += text.substr(firstCharPosition, pos - firstCharPosition); + tokenValue += text.substring(firstCharPosition, pos); } return token; } @@ -7573,6 +7575,7 @@ var ts; startPos = pos; tokenPos = pos; var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 9 /* tab */: case 11 /* verticalTab */: @@ -7583,55 +7586,30 @@ var ts; } return token = 5 /* WhitespaceTrivia */; case 64 /* at */: - pos++; return token = 57 /* AtToken */; case 10 /* lineFeed */: case 13 /* carriageReturn */: - pos++; return token = 4 /* NewLineTrivia */; case 42 /* asterisk */: - pos++; return token = 39 /* AsteriskToken */; case 123 /* openBrace */: - pos++; return token = 17 /* OpenBraceToken */; case 125 /* closeBrace */: - pos++; return token = 18 /* CloseBraceToken */; case 91 /* openBracket */: - pos++; return token = 21 /* OpenBracketToken */; case 93 /* closeBracket */: - pos++; return token = 22 /* CloseBracketToken */; case 60 /* lessThan */: - pos++; return token = 27 /* LessThanToken */; - case 62 /* greaterThan */: - pos++; - return token = 29 /* GreaterThanToken */; case 61 /* equals */: - pos++; return token = 58 /* EqualsToken */; case 44 /* comma */: - pos++; return token = 26 /* CommaToken */; case 46 /* dot */: - pos++; - if (text.substr(tokenPos, pos + 2) === "...") { - pos += 2; - return token = 24 /* DotDotDotToken */; - } return token = 23 /* DotToken */; - case 33 /* exclamation */: - pos++; - return token = 51 /* ExclamationToken */; - case 63 /* question */: - pos++; - return token = 55 /* QuestionToken */; } if (isIdentifierStart(ch, 6 /* Latest */)) { - pos++; while (isIdentifierPart(text.charCodeAt(pos), 6 /* Latest */) && pos < end) { pos++; } @@ -7639,7 +7617,7 @@ var ts; return token = 71 /* Identifier */; } else { - return pos += 1, token = 0 /* Unknown */; + return token = 0 /* Unknown */; } } function speculationHelper(callback, isLookahead) { @@ -8468,7 +8446,7 @@ var ts; return node === parent.type; case 182 /* CallExpression */: case 183 /* NewExpression */: - return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; + return ts.contains(parent.typeArguments, node); case 184 /* TaggedTemplateExpression */: // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments. return false; @@ -9741,6 +9719,10 @@ var ts; return "__@" + symbolName; } ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + function isKnownSymbol(symbol) { + return ts.startsWith(symbol.escapedName, "__@"); + } + ts.isKnownSymbol = isKnownSymbol; /** * Includes the word "Symbol" with unicode escapes */ @@ -11393,8 +11375,8 @@ var ts; // // { // oldStart3: Min(oldStart1, oldStart2), - // oldEnd3 : Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), - // newEnd3 : Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) + // oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)), + // newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2)) // } var oldStart1 = oldStartN; var oldEnd1 = oldEndN; @@ -13216,6 +13198,21 @@ var ts; return hasInitializer(node) && !ts.isForStatement(node) && !ts.isForInStatement(node) && !ts.isForOfStatement(node) && !ts.isJsxAttribute(node); } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; + function isObjectLiteralElement(node) { + switch (node.kind) { + case 257 /* JsxAttribute */: + case 259 /* JsxSpreadAttribute */: + case 265 /* PropertyAssignment */: + case 266 /* ShorthandPropertyAssignment */: + case 152 /* MethodDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + return true; + default: + return false; + } + } + ts.isObjectLiteralElement = isObjectLiteralElement; })(ts || (ts = {})); /// /// @@ -13796,7 +13793,7 @@ var ts; // 'disallow-in' set to 'false'. Otherwise, if we had 'allowsIn' set to 'true', then almost // all nodes would need extra state on them to store this info. // - // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 + // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6 // grammar specification. // // An important thing about these context concepts. By default they are effectively inherited @@ -14519,9 +14516,13 @@ var ts; return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isIdentifierOrPattern(); case 18 /* TypeParameters */: return isIdentifier(); - case 11 /* ArgumentExpressions */: case 15 /* ArrayLiteralMembers */: - return token() === 26 /* CommaToken */ || token() === 24 /* DotDotDotToken */ || isStartOfExpression(); + if (token() === 26 /* CommaToken */) { + return true; + } + // falls through + case 11 /* ArgumentExpressions */: + return token() === 24 /* DotDotDotToken */ || isStartOfExpression(); case 16 /* Parameters */: return isStartOfParameter(); case 19 /* TypeArguments */: @@ -14541,7 +14542,7 @@ var ts; function isValidHeritageClauseObjectLiteral() { ts.Debug.assert(token() === 17 /* OpenBraceToken */); if (nextToken() === 18 /* CloseBraceToken */) { - // if we see "extends {}" then only treat the {} as what we're extending (and not + // if we see "extends {}" then only treat the {} as what we're extending (and not // the class body) if we have: // // extends {} { @@ -14625,7 +14626,7 @@ var ts; } function isVariableDeclaratorListTerminator() { // If we can consume a semicolon (either explicitly, or with ASI), then consider us done - // with parsing the list of variable declarators. + // with parsing the list of variable declarators. if (canParseSemicolon()) { return true; } @@ -14730,6 +14731,10 @@ var ts; if (!canReuseNode(node, parsingContext)) { return undefined; } + if (node.jsDocCache) { + // jsDocCache may include tags from parent nodes, which might have been modified. + node.jsDocCache = undefined; + } return node; } function consumeNode(node) { @@ -15238,7 +15243,7 @@ var ts; // // // - // We do *not* want to consume the > as we're consuming the expression for "". + // We do *not* want to consume the `>` as we're consuming the expression for "". node.expression = parseUnaryExpressionOrHigher(); } } @@ -15978,7 +15983,7 @@ var ts; // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression". // // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is - // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done + // not a LeftHandSideExpression, nor does it start a ConditionalExpression. So we are done // with AssignmentExpression if we see one. var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression(); if (arrowExpression) { @@ -16005,7 +16010,7 @@ var ts; // we're in '2' or '3'. Consume the assignment and return. // // Note: we call reScanGreaterToken so that we get an appropriately merged token - // for cases like > > = becoming >>= + // for cases like `> > =` becoming `>>=` if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) { return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher()); } @@ -16136,7 +16141,7 @@ var ts; var second = nextToken(); if (first === 19 /* OpenParenToken */) { if (second === 20 /* CloseParenToken */) { - // Simple cases: "() =>", "(): ", and "() {". + // Simple cases: "() =>", "(): ", and "() {". // This is an arrow function with no parameters. // The last one is not actually an arrow function, // but this is probably what the user intended. @@ -16337,7 +16342,9 @@ var ts; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); node.colonToken = parseExpectedToken(56 /* ColonToken */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); - node.whenFalse = parseAssignmentExpressionOrHigher(); + node.whenFalse = ts.nodeIsPresent(node.colonToken) + ? parseAssignmentExpressionOrHigher() + : createMissingNode(71 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(56 /* ColonToken */)); return finishNode(node); } function parseBinaryExpressionOrHigher(precedence) { @@ -16699,7 +16706,8 @@ var ts; // We don't want to eagerly consume all import keyword as import call expression so we look a head to find "(" // For example: // var foo3 = require("subfolder - // import * as foo1 from "module-from-node -> we want this import to be a statement rather than import call expression + // import * as foo1 from "module-from-node + // We want this import to be a statement rather than import call expression sourceFile.flags |= 524288 /* PossiblyContainsDynamicImport */; expression = parseTokenNode(); } @@ -16747,7 +16755,7 @@ var ts; // treated as the invocation of "new Foo". We disambiguate that in code (to match // the original grammar) by making sure that if we see an ObjectCreationExpression // we always consume arguments if they are there. So we treat "new Foo()" as an - // object creation only, and not at all as an invocation) Another way to think + // object creation only, and not at all as an invocation. Another way to think // about this is that for every "new" that we see, we will consume an argument list if // it is there as part of the *associated* object creation node. Any additional // argument lists we see, will become invocation expressions. @@ -17111,7 +17119,7 @@ var ts; } var typeArguments = parseDelimitedList(19 /* TypeArguments */, parseType); if (!parseExpected(29 /* GreaterThanToken */)) { - // If it doesn't have the closing > then it's definitely not an type argument list. + // If it doesn't have the closing `>` then it's definitely not an type argument list. return undefined; } // If we have a '<', then only parse this as a argument list if the type arguments @@ -18025,8 +18033,8 @@ var ts; // off. The grammar would look something like this: // // MemberVariableDeclaration[Yield]: - // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; - // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; + // AccessibilityModifier_opt PropertyName TypeAnnotation_opt Initializer_opt[In]; + // AccessibilityModifier_opt static_opt PropertyName TypeAnnotation_opt Initializer_opt[In, ?Yield]; // // The checker may still error in the static case to explicitly disallow the yield expression. node.initializer = ts.hasModifier(node, 32 /* Static */) @@ -18800,17 +18808,17 @@ var ts; comments.push(text); indent += text.length; } - nextJSDocToken(); - while (token() === 5 /* WhitespaceTrivia */) { - nextJSDocToken(); + var t = nextJSDocToken(); + while (t === 5 /* WhitespaceTrivia */) { + t = nextJSDocToken(); } - if (token() === 4 /* NewLineTrivia */) { + if (t === 4 /* NewLineTrivia */) { state = 0 /* BeginningOfLine */; indent = 0; - nextJSDocToken(); + t = nextJSDocToken(); } - while (token() !== 1 /* EndOfFileToken */) { - switch (token()) { + loop: while (true) { + switch (t) { case 57 /* AtToken */: if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) { removeTrailingNewlines(comments); @@ -18864,7 +18872,7 @@ var ts; indent += whitespace.length; break; case 1 /* EndOfFileToken */: - break; + break loop; default: // anything other than whitespace or asterisk at the beginning of the line starts the comment text state = 2 /* SavingComments */; @@ -18872,10 +18880,11 @@ var ts; break; } if (advanceToken) { - nextJSDocToken(); + t = nextJSDocToken(); } else { advanceToken = true; + t = currentToken; } } removeLeadingNewlines(comments); @@ -18974,8 +18983,9 @@ var ts; comments.push(text); indent += text.length; } - while (token() !== 57 /* AtToken */ && token() !== 1 /* EndOfFileToken */) { - switch (token()) { + var tok = token(); + loop: while (true) { + switch (tok) { case 4 /* NewLineTrivia */: if (state >= 1 /* SawAsterisk */) { state = 0 /* BeginningOfLine */; @@ -18984,8 +18994,9 @@ var ts; indent = 0; break; case 57 /* AtToken */: + case 1 /* EndOfFileToken */: // Done - break; + break loop; case 5 /* WhitespaceTrivia */: if (state === 2 /* SavingComments */) { pushComment(scanner.getTokenText()); @@ -19013,11 +19024,7 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (token() === 57 /* AtToken */) { - // Done - break; - } - nextJSDocToken(); + tok = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); @@ -19258,8 +19265,7 @@ var ts; var canParseTag = true; var seenAsterisk = false; while (true) { - nextJSDocToken(); - switch (token()) { + switch (nextJSDocToken()) { case 57 /* AtToken */: if (canParseTag) { var child = tryParseChildTag(target); @@ -19523,7 +19529,7 @@ var ts; // We may need to update both the 'pos' and the 'end' of the element. // If the 'pos' is before the start of the change, then we don't need to touch it. // If it isn't, then the 'pos' must be inside the change. How we update it will - // depend if delta is positive or negative. If delta is positive then we have + // depend if delta is positive or negative. If delta is positive then we have // something like: // // -------------------AAA----------------- @@ -19547,7 +19553,7 @@ var ts; element.pos = Math.min(element.pos, changeRangeNewEnd); // If the 'end' is after the change range, then we always adjust it by the delta // amount. However, if the end is in the change range, then how we adjust it - // will depend on if delta is positive or negative. If delta is positive then we + // will depend on if delta is positive or negative. If delta is positive then we // have something like: // // -------------------AAA----------------- @@ -20133,7 +20139,7 @@ var ts; // without names can only come from JSDocFunctionTypes. ts.Debug.assert(node.parent.kind === 277 /* JSDocFunctionType */); var functionType = node.parent; - var index = ts.indexOf(functionType.parameters, node); + var index = functionType.parameters.indexOf(node); return "arg" + index; case 288 /* JSDocTypedefTag */: var name_2 = ts.getNameOfJSDocTypedef(node); @@ -20556,10 +20562,10 @@ var ts; return false; } function isNarrowingTypeofOperands(expr1, expr2) { - return expr1.kind === 190 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && expr2.kind === 9 /* StringLiteral */; + return expr1.kind === 190 /* TypeOfExpression */ && isNarrowableOperand(expr1.expression) && (expr2.kind === 9 /* StringLiteral */ || expr2.kind === 13 /* NoSubstitutionTemplateLiteral */); } function isNarrowableInOperands(left, right) { - return left.kind === 9 /* StringLiteral */ && isNarrowingExpression(right); + return (left.kind === 9 /* StringLiteral */ || left.kind === 13 /* NoSubstitutionTemplateLiteral */) && isNarrowingExpression(right); } function isNarrowingBinaryExpression(expr) { switch (expr.operatorToken.kind) { @@ -21366,7 +21372,7 @@ var ts; // to the one we would get for: { <...>(...): T } // // We do that by making an anonymous type literal symbol, and then setting the function - // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable + // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable // from an actual type literal symbol you would have gotten had you used the long form. var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); addDeclarationToSymbol(symbol, node, 131072 /* Signature */); @@ -22177,7 +22183,7 @@ var ts; checkStrictModeEvalOrArguments(node, node.name); } if (ts.isBindingPattern(node.name)) { - bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + ts.indexOf(node.parent.parameters, node)); + bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node)); } else { declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 107455 /* ParameterExcludes */); @@ -24517,6 +24523,7 @@ var ts; }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, getAccessibleSymbolChain: getAccessibleSymbolChain, + resolveExternalModuleSymbol: resolveExternalModuleSymbol, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -25058,7 +25065,7 @@ var ts; return true; } var sourceFiles = host.getSourceFiles(); - return ts.indexOf(sourceFiles, declarationFile) <= ts.indexOf(sourceFiles, useFile); + return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile); } if (declaration.pos <= usage.pos) { // declaration is before usage @@ -25365,14 +25372,14 @@ var ts; } break; } - if (location.kind !== 208 /* Block */) { + if (isNonBlockLocation(location)) { lastNonBlockLocation = location; } lastLocation = location; location = location.parent; } // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`. - // If `result === lastLocation.symbol`, that means that we are somewhere inside `lastLocation` looking up a name, and resolving to `lastLocation` itself. + // If `result === lastNonBlockLocation.symbol`, that means that we are somewhere inside `lastNonBlockLocation` looking up a name, and resolving to `lastLocation` itself. // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used. if (isUse && result && nameNotFoundMessage && noUnusedIdentifiers && result !== lastNonBlockLocation.symbol) { result.isReferenced = true; @@ -25447,6 +25454,20 @@ var ts; } return result; } + function isNonBlockLocation(_a) { + var kind = _a.kind; + switch (kind) { + case 208 /* Block */: + case 235 /* ModuleBlock */: + case 222 /* SwitchStatement */: + case 236 /* CaseBlock */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + return false; + default: + return true; + } + } function diagnosticName(nameArg) { return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg); } @@ -25615,6 +25636,41 @@ var ts; } return getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias); } + function resolveExportByName(moduleSymbol, name, dontResolveAlias) { + var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */); + return exportValue + ? getPropertyOfType(getTypeOfSymbol(exportValue), name) + : resolveSymbol(moduleSymbol.exports.get(name), dontResolveAlias); + } + function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) { + if (!allowSyntheticDefaultImports) { + return false; + } + // Declaration files (and ambient modules) + if (!file || file.isDeclarationFile) { + // Definitely cannot have a synthetic default if they have a default member specified + if (resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias)) { + return false; + } + // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member + // So we check a bit more, + if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias)) { + // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code), + // it definitely is a module and does not have a synthetic default + return false; + } + // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set + // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member + // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm + return true; + } + // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement + if (!ts.isSourceFileJavaScript(file)) { + return hasExportAssignmentSymbol(moduleSymbol); + } + // JS files have a synthetic default if they do not contain ES2015+ module syntax (export = is not valid in js) _and_ do not have an __esModule marker + return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), dontResolveAlias); + } function getTargetOfImportClause(node, dontResolveAlias) { var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier); if (moduleSymbol) { @@ -25623,15 +25679,15 @@ var ts; exportDefaultSymbol = moduleSymbol; } else { - var exportValue = moduleSymbol.exports.get("export="); - exportDefaultSymbol = exportValue - ? getPropertyOfType(getTypeOfSymbol(exportValue), "default" /* Default */) - : resolveSymbol(moduleSymbol.exports.get("default" /* Default */), dontResolveAlias); + exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, dontResolveAlias); } - if (!exportDefaultSymbol && !allowSyntheticDefaultImports) { + var file = ts.find(moduleSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias); + if (!exportDefaultSymbol && !hasSyntheticDefault) { error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); } - else if (!exportDefaultSymbol && allowSyntheticDefaultImports) { + else if (!exportDefaultSymbol && hasSyntheticDefault) { + // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present return resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias); } return exportDefaultSymbol; @@ -25998,8 +26054,42 @@ var ts; // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable). function resolveESModuleSymbol(moduleSymbol, moduleReferenceExpression, dontResolveAlias) { var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias); - if (!dontResolveAlias && symbol && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { - error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + if (!dontResolveAlias && symbol) { + if (!(symbol.flags & (1536 /* Module */ | 3 /* Variable */))) { + error(moduleReferenceExpression, ts.Diagnostics.Module_0_resolves_to_a_non_module_entity_and_cannot_be_imported_using_this_construct, symbolToString(moduleSymbol)); + return symbol; + } + if (compilerOptions.esModuleInterop) { + var referenceParent = moduleReferenceExpression.parent; + if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) || + ts.isImportCall(referenceParent)) { + var type = getTypeOfSymbol(symbol); + var sigs = getSignaturesOfStructuredType(type, 0 /* Call */); + if (!sigs || !sigs.length) { + sigs = getSignaturesOfStructuredType(type, 1 /* Construct */); + } + if (sigs && sigs.length) { + var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol); + // Create a new symbol which has the module's type less the call and construct signatures + var result = createSymbol(symbol.flags, symbol.escapedName); + result.declarations = symbol.declarations ? symbol.declarations.slice() : []; + result.parent = symbol.parent; + result.target = symbol; + result.originatingImport = referenceParent; + if (symbol.valueDeclaration) + result.valueDeclaration = symbol.valueDeclaration; + if (symbol.constEnumOnlyModule) + result.constEnumOnlyModule = true; + if (symbol.members) + result.members = ts.cloneMap(symbol.members); + if (symbol.exports) + result.exports = ts.cloneMap(symbol.exports); + var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above + result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo); + return result; + } + } + } } return symbol; } @@ -28209,7 +28299,7 @@ var ts; } else { // Use specific property type when parent is a tuple or numeric index type when parent is an array - var propName = "" + ts.indexOf(pattern.elements, declaration); + var propName = "" + pattern.elements.indexOf(declaration); type = isTupleLikeType(parentType) ? getTypeOfPropertyOfType(parentType, propName) : elementType; @@ -30471,7 +30561,7 @@ var ts; if (node.initializer) { var signatureDeclaration = node.parent; var signature = getSignatureFromDeclaration(signatureDeclaration); - var parameterIndex = ts.indexOf(signatureDeclaration.parameters, node); + var parameterIndex = signatureDeclaration.parameters.indexOf(node); ts.Debug.assert(parameterIndex >= 0); return parameterIndex >= signature.minArgumentCount; } @@ -30479,7 +30569,7 @@ var ts; if (iife) { return !node.type && !node.dotDotDotToken && - ts.indexOf(node.parent.parameters, node) >= iife.arguments.length; + node.parent.parameters.indexOf(node) >= iife.arguments.length; } return false; } @@ -31694,7 +31784,7 @@ var ts; return type.resolvedIndexType; } function getLiteralTypeFromPropertyName(prop) { - return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.startsWith(prop.escapedName, "__@") ? + return ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */ || ts.isKnownSymbol(prop) ? neverType : getLiteralType(ts.symbolName(prop)); } @@ -31743,6 +31833,7 @@ var ts; var prop = getPropertyOfType(objectType, propName); if (prop) { if (accessExpression) { + markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 99 /* ThisKeyword */); if (ts.isAssignmentTarget(accessExpression) && (isReferenceToReadonlyEntity(accessExpression, prop) || isReferenceThroughNamespaceImport(accessExpression))) { error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant_or_a_read_only_property, symbolToString(prop)); return unknownType; @@ -32230,7 +32321,7 @@ var ts; * This is used during inference when instantiating type parameter defaults. */ function createBackreferenceMapper(typeParameters, index) { - return function (t) { return ts.indexOf(typeParameters, t) >= index ? emptyObjectType : t; }; + return function (t) { return typeParameters.indexOf(t) >= index ? emptyObjectType : t; }; } function isInferenceContext(mapper) { return !!mapper.signature; @@ -32895,10 +32986,24 @@ var ts; } else if (errorInfo) { if (containingMessageChain) { - errorInfo = ts.concatenateDiagnosticMessageChains(containingMessageChain, errorInfo); + var chain_1 = containingMessageChain(); + if (chain_1) { + errorInfo = ts.concatenateDiagnosticMessageChains(chain_1, errorInfo); + } } diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } + // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement + if (headMessage && errorNode && !result && source.symbol) { + var links = getSymbolLinks(source.symbol); + if (links.originatingImport && !ts.isImportCall(links.originatingImport)) { + var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined); + if (helpfulRetry) { + // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import + diagnostics.add(ts.createDiagnosticForNode(links.originatingImport, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime)); + } + } + } return result !== 0 /* False */; function reportError(message, arg0, arg1, arg2) { ts.Debug.assert(!!errorNode); @@ -33955,7 +34060,7 @@ var ts; for (var _i = 0, _a = type.typeArguments; _i < _a.length; _i++) { var t = _a[_i]; if (isUnconstrainedTypeParameter(t)) { - var index = ts.indexOf(typeParameters, t); + var index = typeParameters.indexOf(t); if (index < 0) { index = typeParameters.length; typeParameters.push(t); @@ -35418,7 +35523,7 @@ var ts; parent.parent.kind === 217 /* ForOfStatement */ && parent.parent.initializer === parent; } function getAssignedTypeOfArrayLiteralElement(node, element) { - return getTypeOfDestructuredArrayElement(getAssignedType(node), ts.indexOf(node.elements, element)); + return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element)); } function getAssignedTypeOfSpreadExpression(node) { return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent)); @@ -35457,7 +35562,7 @@ var ts; var type = pattern.kind === 175 /* ObjectBindingPattern */ ? getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) : !node.dotDotDotToken ? - getTypeOfDestructuredArrayElement(parentType, ts.indexOf(pattern.elements, node)) : + getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) : getTypeOfDestructuredSpreadExpression(parentType); return getTypeWithDefault(type, node.initializer); } @@ -36009,7 +36114,7 @@ var ts; firstAntecedentType = flowType; } var type = getTypeFromFlowType(flowType); - // If we see a value appear in the cache it is a sign that control flow analysis + // If we see a value appear in the cache it is a sign that control flow analysis // was restarted and completed by checkExpressionCached. We can simply pick up // the resulting type and bail out. var cached_1 = cache.get(key); @@ -36091,10 +36196,10 @@ var ts; var operator_1 = expr.operatorToken.kind; var left_1 = getReferenceCandidate(expr.left); var right_1 = getReferenceCandidate(expr.right); - if (left_1.kind === 190 /* TypeOfExpression */ && right_1.kind === 9 /* StringLiteral */) { + if (left_1.kind === 190 /* TypeOfExpression */ && (right_1.kind === 9 /* StringLiteral */ || right_1.kind === 13 /* NoSubstitutionTemplateLiteral */)) { return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue); } - if (right_1.kind === 190 /* TypeOfExpression */ && left_1.kind === 9 /* StringLiteral */) { + if (right_1.kind === 190 /* TypeOfExpression */ && (left_1.kind === 9 /* StringLiteral */ || left_1.kind === 13 /* NoSubstitutionTemplateLiteral */)) { return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue); } if (isMatchingReference(reference, left_1)) { @@ -36117,7 +36222,7 @@ var ts; return narrowTypeByInstanceof(type, expr, assumeTrue); case 92 /* InKeyword */: var target = getReferenceCandidate(expr.right); - if (expr.left.kind === 9 /* StringLiteral */ && isMatchingReference(reference, target)) { + if ((expr.left.kind === 9 /* StringLiteral */ || expr.left.kind === 13 /* NoSubstitutionTemplateLiteral */) && isMatchingReference(reference, target)) { return narrowByInKeyword(type, expr.left, assumeTrue); } break; @@ -36544,6 +36649,7 @@ var ts; var declarationContainer = getControlFlowContainer(declaration); var flowContainer = getControlFlowContainer(node); var isOuterVariable = flowContainer !== declarationContainer; + var isSpreadDestructuringAsignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent); // When the control flow originates in a function expression or arrow function and we are referencing // a const variable or parameter from an outer function, we extend the origin of the control flow // analysis to include the immediately enclosing function. @@ -36555,7 +36661,7 @@ var ts; // 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 = isParameter || isAlias || isOuterVariable || + var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAsignmentTarget || type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & 1 /* Any */) !== 0 || isInTypeQuery(node) || node.parent.kind === 247 /* ExportSpecifier */) || node.parent.kind === 204 /* NonNullExpression */ || @@ -37070,7 +37176,7 @@ var ts; if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) { var iife = ts.getImmediatelyInvokedFunctionExpression(func); if (iife && iife.arguments) { - var indexOfParameter = ts.indexOf(func.parameters, parameter); + var indexOfParameter = func.parameters.indexOf(parameter); if (parameter.dotDotDotToken) { var restTypes = []; for (var i = indexOfParameter; i < iife.arguments.length; i++) { @@ -37091,7 +37197,7 @@ var ts; if (contextualSignature) { var funcHasRestParameters = ts.hasRestParameter(func); var len = func.parameters.length - (funcHasRestParameters ? 1 : 0); - var indexOfParameter = ts.indexOf(func.parameters, parameter); + var indexOfParameter = func.parameters.indexOf(parameter); if (ts.getThisParameter(func) !== undefined && !contextualSignature.thisParameter) { ts.Debug.assert(indexOfParameter !== 0); // Otherwise we should not have called `getContextuallyTypedParameterType`. indexOfParameter -= 1; @@ -37208,7 +37314,7 @@ var ts; // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. function getContextualTypeForArgument(callTarget, arg) { var args = getEffectiveCallArguments(callTarget); - var argIndex = ts.indexOf(args, arg); + var argIndex = args.indexOf(arg); if (argIndex >= 0) { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. @@ -37631,7 +37737,7 @@ var ts; if (patternElement.kind !== 201 /* OmittedExpression */) { error(patternElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value); } - elementTypes.push(unknownType); + elementTypes.push(strictNullChecks ? implicitNeverType : undefinedWideningType); } } } @@ -38760,16 +38866,16 @@ var ts; return propKind !== 152 /* MethodDeclaration */ && propKind !== 151 /* MethodSignature */; }); } - function checkNonNullExpression(node) { - return checkNonNullType(checkExpression(node), node); + function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); } - function checkNonNullType(type, errorNode) { + function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 12288 /* Nullable */; if (kind) { - error(errorNode, kind & 4096 /* Undefined */ ? kind & 8192 /* Null */ ? - ts.Diagnostics.Object_is_possibly_null_or_undefined : - ts.Diagnostics.Object_is_possibly_undefined : - ts.Diagnostics.Object_is_possibly_null); + error(node, kind & 4096 /* Undefined */ ? kind & 8192 /* Null */ ? + (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : + (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : + (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); var t = getNonNullableType(type); return t.flags & (12288 /* Nullable */ | 16384 /* Never */) ? unknownType : t; } @@ -39484,7 +39590,7 @@ var ts; var constraint = getConstraintOfTypeParameter(typeParameters[i]); if (!constraint) continue; - var errorInfo = reportErrors && headMessage && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); + var errorInfo = reportErrors && headMessage && (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }); var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1; if (!mapper) { mapper = createTypeMapper(typeParameters, typeArgumentTypes); @@ -40093,7 +40199,7 @@ var ts; } excludeCount--; if (excludeCount > 0) { - excludeArgument[ts.indexOf(excludeArgument, /*value*/ true)] = false; + excludeArgument[excludeArgument.indexOf(/*value*/ true)] = false; } else { excludeArgument = undefined; @@ -40132,7 +40238,7 @@ var ts; } return resolveUntypedCall(node); } - var funcType = checkNonNullExpression(node.expression); + var funcType = checkNonNullExpression(node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -40166,7 +40272,7 @@ var ts; error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType)); } else { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + invocationError(node, apparentType, 0 /* Call */); } return resolveErrorCall(node); } @@ -40247,7 +40353,7 @@ var ts; } return signature; } - error(node, ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature); + invocationError(node, expressionType, 1 /* Construct */); return resolveErrorCall(node); } function isConstructorAccessible(node, signature) { @@ -40287,6 +40393,26 @@ var ts; } return true; } + function invocationError(node, apparentType, kind) { + error(node, kind === 0 /* Call */ + ? ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures + : ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature, typeToString(apparentType)); + invocationErrorRecovery(apparentType, kind); + } + function invocationErrorRecovery(apparentType, kind) { + if (!apparentType.symbol) { + return; + } + var importNode = getSymbolLinks(apparentType.symbol).originatingImport; + // Create a diagnostic on the originating import if possible onto which we can attach a quickfix + // An import call expression cannot be rewritten into another form to correct the error - the only solution is to use `.default` at the use-site + if (importNode && !ts.isImportCall(importNode)) { + var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind); + if (!sigs || !sigs.length) + return; + error(importNode, ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime); + } + } function resolveTaggedTemplateExpression(node, candidatesOutArray) { var tagType = checkExpression(node.tag); var apparentType = getApparentType(tagType); @@ -40300,7 +40426,7 @@ var ts; return resolveUntypedCall(node); } if (!callSignatures.length) { - error(node, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); + invocationError(node, apparentType, 0 /* Call */); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray); @@ -40348,6 +40474,7 @@ var ts; errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures, typeToString(apparentType)); errorInfo = ts.chainDiagnosticMessages(errorInfo, headMessage); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(node, errorInfo)); + invocationErrorRecovery(apparentType, 0 /* Call */); return resolveErrorCall(node); } return resolveCall(node, callSignatures, candidatesOutArray, headMessage); @@ -40577,16 +40704,18 @@ var ts; if (moduleSymbol) { var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true); if (esModuleSymbol) { - return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol)); + return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol)); } } return createPromiseReturnType(node, anyType); } - function getTypeWithSyntheticDefaultImportType(type, symbol) { + function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) { if (allowSyntheticDefaultImports && type && type !== unknownType) { var synthType = type; if (!synthType.syntheticType) { - if (!getPropertyOfType(type, "default" /* Default */)) { + var file = ts.find(originalSymbol.declarations, ts.isSourceFile); + var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false); + if (hasSyntheticDefault) { var memberTable = ts.createSymbolTable(); var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */); newSymbol.target = resolveSymbol(symbol); @@ -40594,7 +40723,7 @@ var ts; var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */); var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined); anonymousSymbol.type = defaultContainingObject; - synthType.syntheticType = getIntersectionType([type, defaultContainingObject]); + synthType.syntheticType = (type.flags & 458752 /* StructuredType */ && type.symbol.flags & (1536 /* Module */ | 3 /* Variable */)) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*propegatedFlags*/ 0) : defaultContainingObject; } else { synthType.syntheticType = type; @@ -41995,9 +42124,10 @@ var ts; // - target in rhs of import statement var ok = (node.parent.kind === 180 /* PropertyAccessExpression */ && node.parent.expression === node) || (node.parent.kind === 181 /* ElementAccessExpression */ && node.parent.expression === node) || - ((node.kind === 71 /* Identifier */ || node.kind === 144 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node)); + ((node.kind === 71 /* Identifier */ || node.kind === 144 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) || + (node.parent.kind === 163 /* TypeQuery */ && node.parent.exprName === node)); if (!ok) { - error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment); + error(node, ts.Diagnostics.const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query); } } return type; @@ -42142,7 +42272,7 @@ var ts; error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature); } if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) { - if (ts.indexOf(func.parameters, node) !== 0) { + if (func.parameters.indexOf(node) !== 0) { error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText); } if (func.kind === 153 /* Constructor */ || func.kind === 157 /* ConstructSignature */ || func.kind === 162 /* ConstructorType */) { @@ -42188,7 +42318,7 @@ var ts; error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { - var leadingError = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); + var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); }; checkTypeAssignableTo(typePredicate.type, getTypeOfNode(parent.parameters[typePredicate.parameterIndex]), node.type, /*headMessage*/ undefined, leadingError); } @@ -42519,22 +42649,6 @@ var ts; if (!produceDiagnostics) { return; } - function containsSuperCallAsComputedPropertyName(n) { - var name = ts.getNameOfDeclaration(n); - return name && containsSuperCall(name); - } - function containsSuperCall(n) { - if (ts.isSuperCall(n)) { - return true; - } - else if (ts.isFunctionLike(n)) { - return false; - } - else if (ts.isClassLike(n)) { - return ts.forEach(n.members, containsSuperCallAsComputedPropertyName); - } - return ts.forEachChild(n, containsSuperCall); - } function isInstancePropertyWithInitializer(n) { return n.kind === 150 /* PropertyDeclaration */ && !ts.hasModifier(n, 32 /* Static */) && @@ -43150,7 +43264,7 @@ var ts; } var promisedType = getPromisedTypeOfPromise(type); if (promisedType) { - if (type.id === promisedType.id || ts.indexOf(awaitedTypeStack, promisedType.id) >= 0) { + if (type.id === promisedType.id || awaitedTypeStack.indexOf(promisedType.id) >= 0) { // Verify that we don't have a bad actor in the form of a promise whose // promised type is the same as the promise type, or a mutually recursive // promise. If so, we return undefined as we cannot guess the shape. If this @@ -43350,7 +43464,7 @@ var ts; expectedReturnType = getUnionType([descriptorType, voidType]); break; } - checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, errorInfo); + checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; }); } /** * If a TypeNode can be resolved to a value symbol imported from an external module, it is @@ -43707,36 +43821,35 @@ var ts; } function checkUnusedClassMembers(node) { if (compilerOptions.noUnusedLocals && !(node.flags & 2097152 /* Ambient */)) { - if (node.members) { - for (var _i = 0, _a = node.members; _i < _a.length; _i++) { - var member = _a[_i]; - switch (member.kind) { - case 152 /* MethodDeclaration */: - case 150 /* PropertyDeclaration */: - case 154 /* GetAccessor */: - case 155 /* SetAccessor */: - if (member.kind === 155 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { - // Already would have reported an error on the getter. - break; - } - if (!member.symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { - error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(member.symbol)); - } + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + switch (member.kind) { + case 152 /* MethodDeclaration */: + case 150 /* PropertyDeclaration */: + case 154 /* GetAccessor */: + case 155 /* SetAccessor */: + if (member.kind === 155 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) { + // Already would have reported an error on the getter. break; - case 153 /* Constructor */: - for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { - var parameter = _c[_b]; - if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { - error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)); - } + } + var symbol = getSymbolOfNode(member); + if (!symbol.isReferenced && ts.hasModifier(member, 8 /* Private */)) { + error(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)); + } + break; + case 153 /* Constructor */: + for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) { + var parameter = _c[_b]; + if (!parameter.symbol.isReferenced && ts.hasModifier(parameter, 8 /* Private */)) { + error(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)); } - break; - case 158 /* IndexSignature */: - // Can't be private - break; - default: - ts.Debug.fail(); - } + } + break; + case 158 /* IndexSignature */: + // Can't be private + break; + default: + ts.Debug.fail(); } } } @@ -44305,7 +44418,7 @@ var ts; // Grammar checking checkGrammarForInOrForOfStatement(node); var rightType = checkNonNullExpression(node.expression); - // TypeScript 1.0 spec (April 2014): 5.4 + // TypeScript 1.0 spec (April 2014): 5.4 // In a 'for-in' statement of the form // for (let VarDecl in Expr) Statement // VarDecl must be a variable declaration without a type annotation that declares a variable of type Any, @@ -45056,7 +45169,10 @@ var ts; } } } - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType_1, type.thisType), node.name || node, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1); + } checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1); if (baseConstructorType.flags & 1081344 /* TypeVariable */ && !isMixinConstructorType(staticType)) { error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any); @@ -45086,9 +45202,13 @@ var ts; var t = getTypeFromTypeNode(typeRefNode); if (t !== unknownType) { if (isValidBaseType(t)) { - checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(t, type.thisType), node.name || node, t.symbol && t.symbol.flags & 32 /* Class */ ? + var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ? ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass : - ts.Diagnostics.Class_0_incorrectly_implements_interface_1); + ts.Diagnostics.Class_0_incorrectly_implements_interface_1; + var baseWithThis = getTypeWithThisArgument(t, type.thisType); + if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) { + issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag); + } } else { error(typeRefNode, ts.Diagnostics.A_class_may_only_implement_another_class_or_interface); @@ -45103,6 +45223,35 @@ var ts; checkPropertyInitialization(node); } } + function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) { + // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible + var issuedMemberError = false; + var _loop_5 = function (member) { + if (ts.hasStaticModifier(member)) { + return "continue"; + } + var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member); + if (declaredProp) { + var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName); + var baseProp_1 = getPropertyOfType(baseWithThis, declaredProp.escapedName); + if (prop && baseProp_1) { + var rootChain = function () { return ts.chainDiagnosticMessages( + /*details*/ undefined, ts.Diagnostics.Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2, ts.unescapeLeadingUnderscores(declaredProp.escapedName), typeToString(typeWithThis), typeToString(getTypeOfSymbol(baseProp_1))); }; + if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp_1), member.name || member, /*message*/ undefined, rootChain)) { + issuedMemberError = true; + } + } + } + }; + for (var _i = 0, _a = node.members; _i < _a.length; _i++) { + var member = _a[_i]; + _loop_5(member); + } + if (!issuedMemberError) { + // check again with diagnostics to generate a less-specific error + checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag); + } + } function checkBaseTypeAccessibility(type, node) { var signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length) { @@ -46757,7 +46906,7 @@ var ts; // [{ property1: p1, property2 }] = elems; var typeOfArrayLiteral = getTypeOfArrayLiteralOrObjectLiteralDestructuringAssignment(expr.parent); var elementType = checkIteratedTypeOrElementType(typeOfArrayLiteral || unknownType, expr.parent, /*allowStringInput*/ false, /*allowAsyncIterables*/ false) || unknownType; - return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, ts.indexOf(expr.parent.elements, expr), elementType || unknownType); + return checkArrayLiteralDestructuringElementAssignment(expr.parent, typeOfArrayLiteral, expr.parent.elements.indexOf(expr), elementType || unknownType); } // Gets the property symbol corresponding to the property in destructuring assignment // 'property1' from @@ -46933,7 +47082,7 @@ var ts; // AND // - binding is not declared in loop, should be renamed to avoid name reuse across siblings // let a, b - // { let x = 1; a = () => x; } + // { let x = 1; a = () => x; } // { let x = 100; b = () => x; } // console.log(a()); // should print '1' // console.log(b()); // should print '100' @@ -47872,6 +48021,13 @@ var ts; return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation); } if (parameter.type.kind !== 136 /* StringKeyword */ && parameter.type.kind !== 133 /* NumberKeyword */) { + var type = getTypeFromTypeNode(parameter.type); + if (type.flags & 2 /* String */ || type.flags & 4 /* Number */) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(getTypeFromTypeNode(node.type))); + } + if (allTypesAssignableToKind(type, 32 /* StringLiteral */, /*strict*/ true)) { + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); + } return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); } if (!node.type) { @@ -52011,13 +52167,13 @@ var ts; if (isLeftSideOfBinary) { // No need to parenthesize the left operand when the binary operator is // left associative: - // (a*b)/x -> a*b/x - // (a**b)/x -> a**b/x + // (a*b)/x -> a*b/x + // (a**b)/x -> a**b/x // // Parentheses are needed for the left operand when the binary operator is // right associative: - // (a/b)**x -> (a/b)**x - // (a**b)**x -> (a**b)**x + // (a/b)**x -> (a/b)**x + // (a**b)**x -> (a**b)**x return binaryOperatorAssociativity === 1 /* Right */; } else { @@ -53048,7 +53204,7 @@ var ts; case 216 /* ForInStatement */: return ts.updateForIn(node, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 217 /* ForOfStatement */: - return ts.updateForOf(node, node.awaitModifier, visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); + return ts.updateForOf(node, visitNode(node.awaitModifier, visitor, ts.isToken), visitNode(node.initializer, visitor, ts.isForInitializer), visitNode(node.expression, visitor, ts.isExpression), visitNode(node.statement, visitor, ts.isStatement, ts.liftToBlock)); case 218 /* ContinueStatement */: return ts.updateContinue(node, visitNode(node.label, visitor, ts.isIdentifier)); case 219 /* BreakStatement */: @@ -53872,6 +54028,7 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); if (externalHelpersImportDeclaration) { + ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */); externalImports.unshift(externalHelpersImportDeclaration); } return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration }; @@ -54430,7 +54587,7 @@ var ts; */ var classAliases; /** - * Keeps track of whether we are within any containing namespaces when performing + * Keeps track of whether we are within any containing namespaces when performing * just-in-time substitution while printing an expression identifier. */ var applicableSubstitutions; @@ -59437,7 +59594,7 @@ var ts; */ function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) { if (extendsClauseElement) { - statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getLocalName(node))), + statements.push(ts.setTextRange(ts.createStatement(createExtendsHelper(context, ts.getInternalName(node))), /*location*/ extendsClauseElement)); } } @@ -64537,8 +64694,8 @@ var ts; // `throw` methods that step through the generator when invoked. // // parameters: - // thisArg The value to use as the `this` binding for the transformed generator body. - // body A function that acts as the transformed generator body. + // @param thisArg The value to use as the `this` binding for the transformed generator body. + // @param body A function that acts as the transformed generator body. // // variables: // _ Persistent state for the generator that is shared between the helper and the @@ -64718,7 +64875,7 @@ var ts; // Create an updated SourceFile: // // define(moduleName?, ["module1", "module2"], function ... - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createStatement(ts.createCall(define, /*typeArguments*/ undefined, (moduleName ? [moduleName] : []).concat([ // Add the dependency array argument: @@ -64743,6 +64900,8 @@ var ts; ]))) ]), /*location*/ node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; } /** * Transforms a SourceFile into a UMD module. @@ -64793,7 +64952,7 @@ var ts; // define(["require", "exports"], factory); // } // })(function ...) - return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ + var updated = ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray([ ts.createStatement(ts.createCall(umdHeader, /*typeArguments*/ undefined, [ // Add the module body function argument: @@ -64811,6 +64970,8 @@ var ts; ])) ]), /*location*/ node.statements)); + ts.addEmitHelpers(updated, context.readEmitHelpers()); + return updated; } /** * Collect the additional asynchronous dependencies for the module. @@ -64862,6 +65023,17 @@ var ts; } return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames }; } + function getAMDImportExpressionForImport(node) { + if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(node, currentSourceFile, host, resolver, compilerOptions)) { + return undefined; + } + var name = ts.getLocalNameForExternalImport(node, currentSourceFile); + var expr = getHelperExpressionForImport(node, name); + if (expr === name) { + return undefined; + } + return ts.createStatement(ts.createAssignment(name, expr)); + } /** * Transforms a SourceFile into an AMD or UMD module body. * @@ -64876,6 +65048,9 @@ var ts; } // Visit each statement of the module body. ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement)); + if (moduleKind === ts.ModuleKind.AMD) { + ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport)); + } ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset)); // Append the 'export =' statement if provided. addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true); @@ -65047,7 +65222,12 @@ var ts; ts.setEmitFlags(func, 8 /* CapturesThis */); } } - return ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); + var promise = ts.createNew(ts.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.createPropertyAccess(promise, ts.createIdentifier("then")), /*typeArguments*/ undefined, [ts.getHelperName("__importStar")]); + } + return promise; } function createImportCallExpressionCommonJS(arg, containsLexicalThis) { // import("./blah") @@ -65057,6 +65237,10 @@ var ts; // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately var promiseResolveCall = ts.createCall(ts.createPropertyAccess(ts.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []); var requireCall = ts.createCall(ts.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []); + if (compilerOptions.esModuleInterop) { + context.requestEmitHelper(importStarHelper); + requireCall = ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [requireCall]); + } var func; if (languageVersion >= 2 /* ES2015 */) { func = ts.createArrowFunction( @@ -65083,6 +65267,20 @@ var ts; } return ts.createCall(ts.createPropertyAccess(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]); } + function getHelperExpressionForImport(node, innerExpr) { + if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) { + return innerExpr; + } + if (ts.getNamespaceDeclarationNode(node)) { + context.requestEmitHelper(importStarHelper); + return ts.createCall(ts.getHelperName("__importStar"), /*typeArguments*/ undefined, [innerExpr]); + } + if (ts.isDefaultImport(node)) { + context.requestEmitHelper(importDefaultHelper); + return ts.createCall(ts.getHelperName("__importDefault"), /*typeArguments*/ undefined, [innerExpr]); + } + return innerExpr; + } /** * Visits an ImportDeclaration node. * @@ -65101,7 +65299,7 @@ var ts; if (namespaceDeclaration && !ts.isDefaultImport(node)) { // import * as n from "mod"; variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), - /*type*/ undefined, createRequireCall(node))); + /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node)))); } else { // import d from "mod"; @@ -65109,7 +65307,7 @@ var ts; // import d, { x, y } from "mod"; // import d, * as n from "mod"; variables.push(ts.createVariableDeclaration(ts.getGeneratedNameForNode(node), - /*type*/ undefined, createRequireCall(node))); + /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node)))); if (namespaceDeclaration && ts.isDefaultImport(node)) { variables.push(ts.createVariableDeclaration(ts.getSynthesizedClone(namespaceDeclaration.name), /*type*/ undefined, ts.getGeneratedNameForNode(node))); @@ -65842,6 +66040,18 @@ var ts; scoped: true, text: "\n var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";" }; + // emit helper for `import * as Name from "foo"` + var importStarHelper = { + name: "typescript:commonjsimportstar", + scoped: false, + text: "\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\n result[\"default\"] = mod;\n return result;\n}" + }; + // emit helper for `import Name from "foo"` + var importDefaultHelper = { + name: "typescript:commonjsimportdefault", + scoped: false, + text: "\nvar __importDefault = (this && this.__importDefault) || function (mod) {\n return (mod && mod.__esModule) ? mod : { \"default\": mod };\n}" + }; })(ts || (ts = {})); /// /// @@ -67282,9 +67492,11 @@ var ts; if (externalHelpersModuleName) { var statements = []; var statementOffset = ts.addPrologue(statements, node.statements); - ts.append(statements, ts.createImportDeclaration( + var tslibImport = ts.createImportDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText))); + /*modifiers*/ undefined, ts.createImportClause(/*name*/ undefined, ts.createNamespaceImport(externalHelpersModuleName)), ts.createLiteral(ts.externalHelpersModuleNameText)); + ts.addEmitFlags(tslibImport, 67108864 /* NeverApplyImportHelper */); + ts.append(statements, tslibImport); ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset)); return ts.updateSourceFileNode(node, ts.setTextRange(ts.createNodeArray(statements), node.statements)); } @@ -67994,7 +68206,7 @@ var ts; var sourcesDirectoryPath = compilerOptions.sourceRoot ? host.getCommonSourceDirectory() : sourceMapDir; var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, currentSource.fileName, host.getCurrentDirectory(), host.getCanonicalFileName, /*isAbsolutePathAnUrl*/ true); - sourceMapSourceIndex = ts.indexOf(sourceMapData.sourceMapSources, source); + sourceMapSourceIndex = sourceMapData.sourceMapSources.indexOf(source); if (sourceMapSourceIndex === -1) { sourceMapSourceIndex = sourceMapData.sourceMapSources.length; sourceMapData.sourceMapSources.push(source); @@ -68535,8 +68747,8 @@ var ts; allSourcesModuleElementDeclarationEmitInfo = allSourcesModuleElementDeclarationEmitInfo.concat(moduleElementDeclarationEmitInfo); moduleElementDeclarationEmitInfo = []; } - if (!isBundledEmit && ts.isExternalModule(sourceFile) && sourceFile.moduleAugmentations.length && !resultHasExternalModuleIndicator) { - // if file was external module with augmentations - this fact should be preserved in .d.ts as well. + if (!isBundledEmit && ts.isExternalModule(sourceFile) && !resultHasExternalModuleIndicator) { + // if file was external module this fact should be preserved in .d.ts as well. // in case if we didn't write any external module specifiers in .d.ts we need to emit something // that will force compiler to think that this file is an external module - 'export {}' is a reasonable choice here. write("export {};"); @@ -68974,6 +69186,9 @@ var ts; return tempVarName; } function emitExportAssignment(node) { + if (ts.isSourceFile(node.parent)) { + resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators + } if (node.expression.kind === 71 /* Identifier */) { write(node.isExportEquals ? "export = " : "export default "); writeTextOfNode(currentText, node.expression); @@ -69061,6 +69276,7 @@ var ts; var modifiers = ts.getModifierFlags(node); // If the node is exported if (modifiers & 1 /* Export */) { + resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators write("export "); } if (modifiers & 512 /* Default */) { @@ -69202,6 +69418,7 @@ var ts; writeAsynchronousModuleElements(nodes); } function emitExportDeclaration(node) { + resultHasExternalModuleIndicator = true; // Top-level exports are external module indicators emitJsDocComments(node); write("export "); if (node.exportClause) { @@ -70086,6 +70303,7 @@ var ts; // it allows emitSeparatedList to write separator appropriately) // Example: // original: function foo([, x, ,]) {} + // tslint:disable-next-line no-double-space // emit : function foo([ , x, , ]) {} write(" "); } @@ -74760,6 +74978,7 @@ var ts; // synthesize 'import "tslib"' declaration var externalHelpersModuleReference = ts.createLiteral(ts.externalHelpersModuleNameText); var importDecl = ts.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined); + ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */); externalHelpersModuleReference.parent = importDecl; importDecl.parent = file; imports = [externalHelpersModuleReference]; @@ -75313,13 +75532,13 @@ var ts; var emitFilePath = toPath(emitFileName); // Report error if the output overwrites input file if (filesByName.has(emitFilePath)) { - var chain_1; + var chain_2; if (!options.configFilePath) { // The program is from either an inferred project or an external project - chain_1 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); + chain_2 = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript_files_Learn_more_at_https_Colon_Slash_Slashaka_ms_Slashtsconfig); } - chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); - blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_1)); + chain_2 = ts.chainDiagnosticMessages(chain_2, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName); + blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain_2)); } var emitFileKey = !host.useCaseSensitiveFileNames() ? emitFilePath.toLocaleLowerCase() : emitFilePath; // Report error if multiple files write into same file @@ -75607,6 +75826,7 @@ var ts; "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", + "esnext.array": "lib.esnext.array.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", "esnext.promise": "lib.esnext.promise.d.ts", }), @@ -75861,6 +76081,13 @@ var ts; category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, + { + name: "esModuleInterop", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports + }, { name: "preserveSymlinks", type: "boolean", @@ -76151,7 +76378,8 @@ var ts; ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, target: 1 /* ES5 */, - strict: true + strict: true, + esModuleInterop: true }; var optionNameMapCache; /* @internal */ @@ -76625,7 +76853,7 @@ var ts; function serializeCompilerOptions(options) { var result = ts.createMap(); var optionsNameMap = getOptionNameMap().optionNameMap; - var _loop_5 = function (name) { + var _loop_6 = function (name) { if (ts.hasProperty(options, name)) { // tsconfig only options cannot be specified via command line, // so we can assume that only types that can appear here string | number | boolean @@ -76654,7 +76882,7 @@ var ts; } }; for (var name in options) { - _loop_5(name); + _loop_6(name); } return result; } @@ -78912,18 +79140,6 @@ var ts; }); } ts.signatureToDisplayParts = signatureToDisplayParts; - function getDeclaredName(typeChecker, symbol, location) { - // If this is an export or import specifier it could have been renamed using the 'as' syntax. - // If so we want to search for whatever is under the cursor. - if (isImportOrExportSpecifierName(location) || ts.isStringOrNumericLiteral(location) && location.parent.kind === 145 /* ComputedPropertyName */) { - return ts.getTextOfIdentifierOrLiteral(location); - } - // Try to get the local symbol if we're dealing with an 'export default' - // since that symbol has the "true" name. - var localExportDefaultSymbol = ts.getLocalSymbolForExportDefault(symbol); - return typeChecker.symbolToString(localExportDefaultSymbol || symbol); - } - ts.getDeclaredName = getDeclaredName; function isImportOrExportSpecifierName(location) { return location.parent && (location.parent.kind === 243 /* ImportSpecifier */ || location.parent.kind === 247 /* ExportSpecifier */) && @@ -78937,12 +79153,16 @@ var ts; */ function stripQuotes(name) { var length = name.length; - if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && ts.isSingleOrDoubleQuote(name.charCodeAt(0))) { + if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && startsWithQuote(name)) { return name.substring(1, length - 1); } return name; } ts.stripQuotes = stripQuotes; + function startsWithQuote(name) { + return ts.isSingleOrDoubleQuote(name.charCodeAt(0)); + } + ts.startsWithQuote = startsWithQuote; function scriptKindIs(fileName, host) { var scriptKinds = []; for (var _i = 2; _i < arguments.length; _i++) { @@ -79793,7 +80013,7 @@ var ts; if (ts.isKeyword(tokenKind)) { return 3 /* keyword */; } - // Special case < and > If they appear in a generic context they are punctuation, + // Special case `<` and `>`: If they appear in a generic context they are punctuation, // not operators. if (tokenKind === 27 /* LessThanToken */ || tokenKind === 29 /* GreaterThanToken */) { // If the node owning the token has a type argument list or type parameter list, then @@ -79903,11 +80123,11 @@ var ts; (function (Completions) { var PathCompletions; (function (PathCompletions) { - function getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker) { + function getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker) { var literalValue = ts.normalizeSlashes(node.text); var scriptPath = node.getSourceFile().path; var scriptDirectory = ts.getDirectoryPath(scriptPath); - var span = getDirectoryFragmentTextSpan(node.text, node.getStart() + 1); + var span = getDirectoryFragmentTextSpan(node.text, node.getStart(sourceFile) + 1); if (isPathRelativeToScript(literalValue) || ts.isRootedDiskPath(literalValue)) { var extensions = ts.getSupportedExtensions(compilerOptions); if (compilerOptions.rootDirs) { @@ -80022,37 +80242,20 @@ var ts; var projectDir = compilerOptions.project || host.getCurrentDirectory(); var absolute = ts.isRootedDiskPath(baseUrl) ? baseUrl : ts.combinePaths(projectDir, baseUrl); getCompletionEntriesForDirectoryFragment(fragment, ts.normalizePath(absolute), fileExtensions, /*includeExtensions*/ false, span, host, /*exclude*/ undefined, result); - var _loop_6 = function (path) { - if (!paths.hasOwnProperty(path)) - return "continue"; - var patterns = paths[path]; - if (!patterns) - return "continue"; - if (path === "*") { - for (var _i = 0, patterns_1 = patterns; _i < patterns_1.length; _i++) { - var pattern = patterns_1[_i]; - var _loop_7 = function (match) { - // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. - if (result.some(function (entry) { return entry.name === match; })) - return "continue"; - result.push(createCompletionEntryForModule(match, "external module name" /* externalModuleName */, span)); - }; - for (var _a = 0, _b = getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host); _a < _b.length; _a++) { - var match = _b[_a]; - _loop_7(match); - } - } - } - else if (ts.startsWith(path, fragment)) { - if (patterns.length === 1) { - if (result.some(function (entry) { return entry.name === path; })) - return "continue"; - result.push(createCompletionEntryForModule(path, "external module name" /* externalModuleName */, span)); - } - } - }; for (var path in paths) { - _loop_6(path); + var patterns = paths[path]; + if (paths.hasOwnProperty(path) && patterns) { + var _loop_7 = function (pathCompletion) { + // Path mappings may provide a duplicate way to get to something we've already added, so don't add again. + if (!result.some(function (entry) { return entry.name === pathCompletion; })) { + result.push(createCompletionEntryForModule(pathCompletion, "external module name" /* externalModuleName */, span)); + } + }; + for (var _i = 0, _a = getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host); _i < _a.length; _i++) { + var pathCompletion = _a[_i]; + _loop_7(pathCompletion); + } + } } } if (compilerOptions.moduleResolution === ts.ModuleResolutionKind.NodeJs) { @@ -80064,50 +80267,59 @@ var ts; }); } getCompletionEntriesFromTypings(host, compilerOptions, scriptPath, span, result); - for (var _i = 0, _a = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _i < _a.length; _i++) { - var moduleName = _a[_i]; + for (var _b = 0, _c = enumeratePotentialNonRelativeModules(fragment, scriptPath, compilerOptions, typeChecker, host); _b < _c.length; _b++) { + var moduleName = _c[_b]; result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); } return result; } - function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { - if (host.readDirectory) { - var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; - if (parsed) { - // The prefix has two effective parts: the directory path and the base component after the filepath that is not a - // full directory component. For example: directory/path/of/prefix/base* - var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); - var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); - var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); - var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); - // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call - var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; - var normalizedSuffix = ts.normalizePath(parsed.suffix); - var baseDirectory = ts.combinePaths(baseUrl, expandedPrefixDirectory); - var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; - // If we have a suffix, then we need to read the directory all the way down. We could create a glob - // that encodes the suffix, but we would have to escape the character "?" which readDirectory - // doesn't support. For now, this is safer but slower - var includeGlob = normalizedSuffix ? "**/*" : "./*"; - var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]); - if (matches) { - var result = []; - // Trim away prefix and suffix - for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { - var match = matches_1[_i]; - var normalizedMatch = ts.normalizePath(match); - if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { - continue; - } - var start = completePrefix.length; - var length_7 = normalizedMatch.length - start - normalizedSuffix.length; - result.push(ts.removeFileExtension(normalizedMatch.substr(start, length_7))); - } - return result; - } - } + function getCompletionsForPathMapping(path, patterns, fragment, baseUrl, fileExtensions, host) { + if (!ts.endsWith(path, "*")) { + // For a path mapping "foo": ["/x/y/z.ts"], add "foo" itself as a completion. + return !ts.stringContains(path, "*") && ts.startsWith(path, fragment) ? [path] : ts.emptyArray; } - return undefined; + var pathPrefix = path.slice(0, path.length - 1); + if (!ts.startsWith(fragment, pathPrefix)) { + return ts.emptyArray; + } + var remainingFragment = fragment.slice(pathPrefix.length); + return ts.flatMap(patterns, function (pattern) { return getModulesForPathsPattern(remainingFragment, baseUrl, pattern, fileExtensions, host); }); + } + function getModulesForPathsPattern(fragment, baseUrl, pattern, fileExtensions, host) { + if (!host.readDirectory) { + return undefined; + } + var parsed = ts.hasZeroOrOneAsteriskCharacter(pattern) ? ts.tryParsePattern(pattern) : undefined; + if (!parsed) { + return undefined; + } + // The prefix has two effective parts: the directory path and the base component after the filepath that is not a + // full directory component. For example: directory/path/of/prefix/base* + var normalizedPrefix = normalizeAndPreserveTrailingSlash(parsed.prefix); + var normalizedPrefixDirectory = ts.getDirectoryPath(normalizedPrefix); + var normalizedPrefixBase = ts.getBaseFileName(normalizedPrefix); + var fragmentHasPath = ts.stringContains(fragment, ts.directorySeparator); + // Try and expand the prefix to include any path from the fragment so that we can limit the readDirectory call + var expandedPrefixDirectory = fragmentHasPath ? ts.combinePaths(normalizedPrefixDirectory, normalizedPrefixBase + ts.getDirectoryPath(fragment)) : normalizedPrefixDirectory; + var normalizedSuffix = ts.normalizePath(parsed.suffix); + // Need to normalize after combining: If we combinePaths("a", "../b"), we want "b" and not "a/../b". + var baseDirectory = ts.normalizePath(ts.combinePaths(baseUrl, expandedPrefixDirectory)); + var completePrefix = fragmentHasPath ? baseDirectory : ts.ensureTrailingDirectorySeparator(baseDirectory) + normalizedPrefixBase; + // If we have a suffix, then we need to read the directory all the way down. We could create a glob + // that encodes the suffix, but we would have to escape the character "?" which readDirectory + // doesn't support. For now, this is safer but slower + var includeGlob = normalizedSuffix ? "**/*" : "./*"; + var matches = tryReadDirectory(host, baseDirectory, fileExtensions, /*exclude*/ undefined, [includeGlob]); + // Trim away prefix and suffix + return ts.mapDefined(matches, function (match) { + var normalizedMatch = ts.normalizePath(match); + if (!ts.endsWith(normalizedMatch, normalizedSuffix) || !ts.startsWith(normalizedMatch, completePrefix)) { + return; + } + var start = completePrefix.length; + var length = normalizedMatch.length - start - normalizedSuffix.length; + return ts.removeFileExtension(normalizedMatch.substr(start, length)); + }); } function enumeratePotentialNonRelativeModules(fragment, scriptPath, options, typeChecker, host) { // Check If this is a nested module @@ -80359,8 +80571,8 @@ var ts; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, options) { if (ts.isInReferenceComment(sourceFile, position)) { - var entries_2 = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); - return entries_2 && pathCompletionsInfo(entries_2); + var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); + return entries && pathCompletionsInfo(entries); } if (ts.isInString(sourceFile, position)) { return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log); @@ -80374,13 +80586,33 @@ var ts; if (!completionData) { return undefined; } - var symbols = completionData.symbols, isGlobalCompletion = completionData.isGlobalCompletion, isMemberCompletion = completionData.isMemberCompletion, allowStringLiteral = completionData.allowStringLiteral, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, request = completionData.request, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion; - if (sourceFile.languageVariant === 1 /* JSX */ && - location && location.parent && location.parent.kind === 253 /* JsxClosingElement */) { + switch (completionData.kind) { + case 0 /* Data */: + return completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, options.includeInsertTextCompletions); + case 1 /* JsDocTagName */: + // If the current position is a jsDoc tag name, only tag names should be provided for completion + return jsdocCompletionInfo(ts.JsDoc.getJSDocTagNameCompletions()); + case 2 /* JsDocTag */: + // If the current position is a jsDoc tag, only tags should be provided for completion + return jsdocCompletionInfo(ts.JsDoc.getJSDocTagCompletions()); + case 3 /* JsDocParameterName */: + return jsdocCompletionInfo(ts.JsDoc.getJSDocParameterNameCompletions(completionData.tag)); + default: + throw ts.Debug.assertNever(completionData); + } + } + Completions.getCompletionsAtPosition = getCompletionsAtPosition; + function jsdocCompletionInfo(entries) { + return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; + } + function completionInfoFromData(sourceFile, typeChecker, compilerOptions, log, completionData, includeInsertTextCompletions) { + var symbols = completionData.symbols, completionKind = completionData.completionKind, isNewIdentifierLocation = completionData.isNewIdentifierLocation, location = completionData.location, propertyAccessToConvert = completionData.propertyAccessToConvert, keywordFilters = completionData.keywordFilters, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, recommendedCompletion = completionData.recommendedCompletion; + if (sourceFile.languageVariant === 1 /* JSX */ && location && location.parent && ts.isJsxClosingElement(location.parent)) { // In the TypeScript JSX element, if such element is not defined. When users query for completion at closing tag, // instead of simply giving unknown value, the completion will return the tag-name of an associated opening-element. // For example: - // var x =
completion list at "1" will contain "div" with type any + // var x =
+ // The completion list at "1" will contain "div" with type any var tagName = location.parent.parent.openingElement.tagName; return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: false, entries: [{ @@ -80390,37 +80622,37 @@ var ts; sortText: "0", }] }; } - if (request) { - var entries_3 = request.kind === "JsDocTagName" - // If the current position is a jsDoc tag name, only tag names should be provided for completion - ? ts.JsDoc.getJSDocTagNameCompletions() - : request.kind === "JsDocTag" - // If the current position is a jsDoc tag, only tags should be provided for completion - ? ts.JsDoc.getJSDocTagCompletions() - : ts.JsDoc.getJSDocParameterNameCompletions(request.tag); - return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries_3 }; - } var entries = []; if (ts.isSourceFileJavaScript(sourceFile)) { - var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap); + var uniqueNames = getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, recommendedCompletion, symbolToOriginInfoMap); getJavaScriptCompletionEntries(sourceFile, location.pos, uniqueNames, compilerOptions.target, entries); } else { if ((!symbols || symbols.length === 0) && keywordFilters === 0 /* None */) { return undefined; } - getCompletionEntriesFromSymbols(symbols, entries, location, /*performCharacterChecks*/ true, typeChecker, compilerOptions.target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap); + getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, compilerOptions.target, log, completionKind, includeInsertTextCompletions, propertyAccessToConvert, recommendedCompletion, symbolToOriginInfoMap); } // TODO add filter for keyword based on type/value/namespace and also location // Add all keywords if // - this is not a member completion list (all the keywords) // - other filters are enabled in required scenario so add those keywords + var isMemberCompletion = isMemberCompletionKind(completionKind); if (keywordFilters !== 0 /* None */ || !isMemberCompletion) { ts.addRange(entries, getKeywordCompletions(keywordFilters)); } - return { isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + return { isGlobalCompletion: completionKind === 1 /* Global */, isMemberCompletion: isMemberCompletion, isNewIdentifierLocation: isNewIdentifierLocation, entries: entries }; + } + function isMemberCompletionKind(kind) { + switch (kind) { + case 0 /* ObjectPropertyDeclaration */: + case 3 /* MemberLike */: + case 2 /* PropertyAccess */: + return true; + default: + return false; + } } - Completions.getCompletionsAtPosition = getCompletionsAtPosition; function getJavaScriptCompletionEntries(sourceFile, position, uniqueNames, target, entries) { ts.getNameTable(sourceFile).forEach(function (pos, name) { // Skip identifiers produced only from the current location @@ -80428,14 +80660,9 @@ var ts; return; } var realName = ts.unescapeLeadingUnderscores(name); - if (uniqueNames.has(realName) || ts.isStringANonContextualKeyword(realName)) { - return; - } - uniqueNames.set(realName, true); - var displayName = getCompletionEntryDisplayName(realName, target, /*performCharacterChecks*/ true, /*allowStringLiteral*/ false); - if (displayName) { + if (ts.addToSeen(uniqueNames, realName) && ts.isIdentifierText(realName, target) && !ts.isStringANonContextualKeyword(realName)) { entries.push({ - name: displayName, + name: realName, kind: "warning" /* warning */, kindModifiers: "", sortText: "1" @@ -80443,12 +80670,14 @@ var ts; } }); } - function createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion) { - // Try to get a valid display name for this symbol, if we could not find one, then ignore it. - // We would like to only show things that can be added after a dot, so for instance numeric properties can - // not be accessed with a dot (a.1 <- invalid) - var displayName = getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin); - if (!displayName) { + function createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, includeInsertTextCompletions) { + var info = getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind); + if (!info) { + return undefined; + } + var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; + ts.Debug.assert(!(needsConvertPropertyAccess && !propertyAccessToConvert)); + if (needsConvertPropertyAccess && !includeInsertTextCompletions) { return undefined; } // TODO(drosen): Right now we just permit *all* semantic meanings when calling @@ -80459,12 +80688,17 @@ var ts; // Use a 'sortText' of 0' so that all symbol completion entries come before any other // entries (like JavaScript identifier entries). return { - name: displayName, + name: name, kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", source: getSourceFromOrigin(origin), - hasAction: trueOrUndefined(origin !== undefined), + // TODO: GH#20619 Use configured quote style + insertText: needsConvertPropertyAccess ? "[\"" + name + "\"]" : undefined, + replacementSpan: needsConvertPropertyAccess + ? ts.createTextSpanFromBounds(ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile).getStart(sourceFile), propertyAccessToConvert.name.end) + : undefined, + hasAction: trueOrUndefined(needsConvertPropertyAccess || origin !== undefined), isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), }; } @@ -80478,7 +80712,7 @@ var ts; function getSourceFromOrigin(origin) { return origin && ts.stripQuotes(origin.moduleSymbol.name); } - function getCompletionEntriesFromSymbols(symbols, entries, location, performCharacterChecks, typeChecker, target, log, allowStringLiteral, recommendedCompletion, symbolToOriginInfoMap) { + function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, includeInsertTextCompletions, propertyAccessToConvert, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); // Tracks unique names. // We don't set this for global variables or completions from external module exports, because we can have multiple of those. @@ -80488,7 +80722,7 @@ var ts; for (var _i = 0, symbols_4 = symbols; _i < symbols_4.length; _i++) { var symbol = symbols_4[_i]; var origin = symbolToOriginInfoMap ? symbolToOriginInfoMap[ts.getSymbolId(symbol)] : undefined; - var entry = createCompletionEntry(symbol, location, performCharacterChecks, typeChecker, target, allowStringLiteral, origin, recommendedCompletion); + var entry = createCompletionEntry(symbol, location, sourceFile, typeChecker, target, kind, origin, recommendedCompletion, propertyAccessToConvert, includeInsertTextCompletions); if (!entry) { continue; } @@ -80531,7 +80765,7 @@ var ts; // foo({ // '/*completion position*/' // }); - return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, typeChecker, compilerOptions.target, log); + return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, sourceFile, typeChecker, compilerOptions.target, log); } else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { // Get all names of properties on the expression @@ -80541,7 +80775,7 @@ var ts; // let a: A; // a['/*completion position*/'] var type = typeChecker.getTypeAtLocation(node.parent.expression); - return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, type, typeChecker, compilerOptions.target, log); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); } else if (node.parent.kind === 239 /* ImportDeclaration */ || node.parent.kind === 245 /* ExportDeclaration */ || ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent) @@ -80552,7 +80786,7 @@ var ts; // import x = require("/*completion position*/"); // var y = require("/*completion position*/"); // export * from "/*completion position*/"; - var entries = Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(node, compilerOptions, host, typeChecker); + var entries = Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker); return pathCompletionsInfo(entries); } else if (ts.isIndexedAccessTypeNode(node.parent.parent)) { @@ -80563,7 +80797,7 @@ var ts; // } // let x: Foo["/*completion position*/"] var type = typeChecker.getTypeFromTypeNode(node.parent.parent.objectType); - return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, type, typeChecker, compilerOptions.target, log); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); } else { var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); @@ -80589,11 +80823,11 @@ var ts; entries: entries, }; } - function getStringLiteralCompletionEntriesFromPropertyAssignment(element, typeChecker, target, log) { + function getStringLiteralCompletionEntriesFromPropertyAssignment(element, sourceFile, typeChecker, target, log) { var type = typeChecker.getContextualType(element.parent); var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, /*performCharacterChecks*/ false, typeChecker, target, log, /*allowStringLiteral*/ true); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, element, sourceFile, typeChecker, target, log, 4 /* String */); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -80613,10 +80847,10 @@ var ts; } return undefined; } - function getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(stringLiteralNode, type, typeChecker, target, log) { + function getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(stringLiteralNode, sourceFile, type, typeChecker, target, log) { var entries = []; if (type) { - getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, stringLiteralNode, /*performCharacterChecks*/ false, typeChecker, target, log, /*allowStringLiteral*/ true); + getCompletionEntriesFromSymbols(type.getApparentProperties(), entries, stringLiteralNode, sourceFile, typeChecker, target, log, 4 /* String */); if (entries.length) { return { isGlobalCompletion: false, isMemberCompletion: true, isNewIdentifierLocation: true, entries: entries }; } @@ -80686,24 +80920,23 @@ var ts; } function getSymbolCompletionFromEntryId(typeChecker, log, compilerOptions, sourceFile, position, _a, allSourceFiles) { var name = _a.name, source = _a.source; - var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true }, compilerOptions.target); + var completionData = getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, { includeExternalModuleExports: true, includeInsertTextCompletions: true }, compilerOptions.target); if (!completionData) { return { type: "none" }; } - var symbols = completionData.symbols, location = completionData.location, allowStringLiteral = completionData.allowStringLiteral, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, request = completionData.request, previousToken = completionData.previousToken; - if (request) { - return { type: "request", request: request }; + if (completionData.kind !== 0 /* Data */) { + return { type: "request", request: completionData }; } + var symbols = completionData.symbols, location = completionData.location, completionKind = completionData.completionKind, symbolToOriginInfoMap = completionData.symbolToOriginInfoMap, previousToken = completionData.previousToken; // Find the symbol with the matching entry name. // We don't need to perform character checks here because we're only comparing the // name against 'entryName' (which is known to be good), not building a new // completion entry. - var symbol = ts.find(symbols, function (s) { - var origin = symbolToOriginInfoMap[ts.getSymbolId(s)]; - return getCompletionEntryDisplayNameForSymbol(s, compilerOptions.target, /*performCharacterChecks*/ false, allowStringLiteral, origin) === name - && getSourceFromOrigin(origin) === source; - }); - return symbol ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken } : { type: "none" }; + return ts.firstDefined(symbols, function (symbol) { + var origin = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; + var info = getCompletionEntryDisplayNameForSymbol(symbol, compilerOptions.target, origin, completionKind); + return info && info.name === name && getSourceFromOrigin(origin) === source ? { type: "symbol", symbol: symbol, location: location, symbolToOriginInfoMap: symbolToOriginInfoMap, previousToken: previousToken } : undefined; + }) || { type: "none" }; } function getSymbolName(symbol, origin, target) { return origin && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ @@ -80721,11 +80954,11 @@ var ts; case "request": { var request = symbolCompletion.request; switch (request.kind) { - case "JsDocTagName": + case 1 /* JsDocTagName */: return ts.JsDoc.getJSDocTagNameCompletionDetails(name); - case "JsDocTag": + case 2 /* JsDocTag */: return ts.JsDoc.getJSDocTagCompletionDetails(name); - case "JsDocParameterName": + case 3 /* JsDocParameterName */: return ts.JsDoc.getJSDocParameterNameCompletionDetails(name); default: return ts.Debug.assertNever(request); @@ -80759,9 +80992,11 @@ var ts; Completions.getCompletionEntryDetails = getCompletionEntryDetails; function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - if (!symbolOriginInfo) { - return { codeActions: undefined, sourceDisplay: undefined }; - } + return symbolOriginInfo + ? getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) + : { codeActions: undefined, sourceDisplay: undefined }; + } + function getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { var moduleSymbol = symbolOriginInfo.moduleSymbol, isDefaultExport = symbolOriginInfo.isDefaultExport; var exportedSymbol = ts.skipAlias(symbol.exportSymbol || symbol, checker); var moduleSymbols = getAllReExportingModules(exportedSymbol, checker, allSourceFiles); @@ -80799,6 +81034,22 @@ var ts; return completion.type === "symbol" ? completion.symbol : undefined; } Completions.getCompletionEntrySymbol = getCompletionEntrySymbol; + var CompletionDataKind; + (function (CompletionDataKind) { + CompletionDataKind[CompletionDataKind["Data"] = 0] = "Data"; + CompletionDataKind[CompletionDataKind["JsDocTagName"] = 1] = "JsDocTagName"; + CompletionDataKind[CompletionDataKind["JsDocTag"] = 2] = "JsDocTag"; + CompletionDataKind[CompletionDataKind["JsDocParameterName"] = 3] = "JsDocParameterName"; + })(CompletionDataKind || (CompletionDataKind = {})); + var CompletionKind; + (function (CompletionKind) { + CompletionKind[CompletionKind["ObjectPropertyDeclaration"] = 0] = "ObjectPropertyDeclaration"; + CompletionKind[CompletionKind["Global"] = 1] = "Global"; + CompletionKind[CompletionKind["PropertyAccess"] = 2] = "PropertyAccess"; + CompletionKind[CompletionKind["MemberLike"] = 3] = "MemberLike"; + CompletionKind[CompletionKind["String"] = 4] = "String"; + CompletionKind[CompletionKind["None"] = 5] = "None"; + })(CompletionKind || (CompletionKind = {})); function getRecommendedCompletion(currentToken, checker) { var ty = getContextualType(currentToken, checker); var symbol = ty && ty.symbol; @@ -80856,7 +81107,6 @@ var ts; return symbol.declarations.some(function (d) { return d.kind === 269 /* SourceFile */; }); } function getCompletionData(typeChecker, log, sourceFile, position, allSourceFiles, options, target) { - var request; var start = ts.timestamp(); var currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); // TODO: GH#15853 // We will check for jsdoc comments with insideComment and getJsDocTagAtPosition. (TODO: that seems rather inefficient to check the same thing so many times.) @@ -80871,7 +81121,7 @@ var ts; if (sourceFile.text.charCodeAt(position - 1) === 64 /* at */) { // The current position is next to the '@' sign, when no tag name being provided yet. // Provide a full list of tag names - request = { kind: "JsDocTagName" }; + return { kind: 1 /* JsDocTagName */ }; } else { // When completion is requested without "@", we will have check to make sure that @@ -80892,7 +81142,7 @@ var ts; // */ var lineStart = ts.getLineStartPositionForPosition(position, sourceFile); if (!(sourceFile.text.substring(lineStart, position).match(/[^\*|\s|(/\*\*)]/))) { - request = { kind: "JsDocTag" }; + return { kind: 2 /* JsDocTag */ }; } } } @@ -80902,7 +81152,7 @@ var ts; var tag = getJsDocTagAtPosition(currentToken, position); if (tag) { if (tag.tagName.pos <= position && position <= tag.tagName.end) { - request = { kind: "JsDocTagName" }; + return { kind: 1 /* JsDocTagName */ }; } if (isTagWithTypeExpression(tag) && tag.typeExpression && tag.typeExpression.kind === 271 /* JSDocTypeExpression */) { currentToken = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ true); @@ -80915,25 +81165,9 @@ var ts; } } if (ts.isJSDocParameterTag(tag) && (ts.nodeIsMissing(tag.name) || tag.name.pos <= position && position <= tag.name.end)) { - request = { kind: "JsDocParameterName", tag: tag }; + return { kind: 3 /* JsDocParameterName */, tag: tag }; } } - if (request) { - return { - symbols: ts.emptyArray, - isGlobalCompletion: false, - isMemberCompletion: false, - allowStringLiteral: false, - isNewIdentifierLocation: false, - location: undefined, - isRightOfDot: false, - request: request, - keywordFilters: 0 /* None */, - symbolToOriginInfoMap: undefined, - recommendedCompletion: undefined, - previousToken: undefined, - }; - } if (!insideJsDocTagTypeExpression) { // Proceed if the current position is in jsDoc tag expression; otherwise it is a normal // comment or the plain text part of a jsDoc comment, so no completion should be available @@ -80958,6 +81192,7 @@ var ts; // Also determine whether we are trying to complete with members of that node // or attributes of a JSX tag. var node = currentToken; + var propertyAccessToConvert; var isRightOfDot = false; var isRightOfOpenTag = false; var isStartingCloseTag = false; @@ -80970,18 +81205,19 @@ var ts; } var parent = contextToken.parent; if (contextToken.kind === 23 /* DotToken */) { - if (parent.kind === 180 /* PropertyAccessExpression */) { - node = contextToken.parent.expression; - isRightOfDot = true; - } - else if (parent.kind === 144 /* QualifiedName */) { - node = contextToken.parent.left; - isRightOfDot = true; - } - else { - // There is nothing that precedes the dot, so this likely just a stray character - // or leading into a '...' token. Just bail out instead. - return undefined; + isRightOfDot = true; + switch (parent.kind) { + case 180 /* PropertyAccessExpression */: + propertyAccessToConvert = parent; + node = propertyAccessToConvert.expression; + break; + case 144 /* QualifiedName */: + node = parent.left; + break; + default: + // There is nothing that precedes the dot, so this likely just a stray character + // or leading into a '...' token. Just bail out instead. + return undefined; } } else if (sourceFile.languageVariant === 1 /* JSX */) { @@ -81017,10 +81253,8 @@ var ts; } } var semanticStart = ts.timestamp(); - var isGlobalCompletion = false; - var isMemberCompletion; - var allowStringLiteral = false; - var isNewIdentifierLocation; + var completionKind = 5 /* None */; + var isNewIdentifierLocation = false; var keywordFilters = 0 /* None */; var symbols = []; var symbolToOriginInfoMap = []; @@ -81035,8 +81269,7 @@ var ts; else { symbols = tagSymbols; } - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 3 /* MemberLike */; } else if (isStartingCloseTag) { var tagName = contextToken.parent.parent.openingElement.tagName; @@ -81044,8 +81277,7 @@ var ts; if (!typeChecker.isUnknownSymbol(tagSymbol)) { symbols = [tagSymbol]; } - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 3 /* MemberLike */; } else { // For JavaScript or TypeScript, if we're not after a dot, then just try to get the @@ -81057,7 +81289,7 @@ var ts; } log("getCompletionData: Semantic work: " + (ts.timestamp() - semanticStart)); var recommendedCompletion = previousToken && getRecommendedCompletion(previousToken, typeChecker); - return { symbols: symbols, isGlobalCompletion: isGlobalCompletion, isMemberCompletion: isMemberCompletion, allowStringLiteral: allowStringLiteral, isNewIdentifierLocation: isNewIdentifierLocation, location: location, isRightOfDot: (isRightOfDot || isRightOfOpenTag), request: request, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken }; + return { kind: 0 /* Data */, symbols: symbols, completionKind: completionKind, propertyAccessToConvert: propertyAccessToConvert, isNewIdentifierLocation: isNewIdentifierLocation, location: location, keywordFilters: keywordFilters, symbolToOriginInfoMap: symbolToOriginInfoMap, recommendedCompletion: recommendedCompletion, previousToken: previousToken }; function isTagWithTypeExpression(tag) { switch (tag.kind) { case 284 /* JSDocParameterTag */: @@ -81070,9 +81302,7 @@ var ts; } function getTypeScriptMemberSymbols() { // Right of dot member completion list - isGlobalCompletion = false; - isMemberCompletion = true; - isNewIdentifierLocation = false; + completionKind = 2 /* PropertyAccess */; // Since this is qualified name check its a type node location var isTypeLocation = insideJsDocTagTypeExpression || ts.isPartOfTypeNode(node.parent); var isRhsOfImportDeclaration = ts.isInRightSideOfInternalImportEqualsDeclaration(node); @@ -81140,7 +81370,7 @@ var ts; } if (tryGetConstructorLikeCompletionContainer(contextToken)) { // no members, only keywords - isMemberCompletion = false; + completionKind = 5 /* None */; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for constructor parameter @@ -81159,14 +81389,14 @@ var ts; attrsType = typeChecker.getAllAttributesTypeFromJsxOpeningLikeElement(jsxContainer); if (attrsType) { symbols = filterJsxAttributes(typeChecker.getPropertiesOfType(attrsType), jsxContainer.attributes.properties); - isMemberCompletion = true; + completionKind = 3 /* MemberLike */; isNewIdentifierLocation = false; return true; } } } // Get all entities in the current scope. - isMemberCompletion = false; + completionKind = 5 /* None */; isNewIdentifierLocation = isNewIdentifierDefinitionLocation(contextToken); if (previousToken !== contextToken) { ts.Debug.assert(!!previousToken, "Expected 'contextToken' to be defined when different from 'previousToken'."); @@ -81200,13 +81430,8 @@ var ts; previousToken.getStart() : position; var scopeNode = getScopeNode(contextToken, adjustedPosition, sourceFile) || sourceFile; - if (scopeNode) { - isGlobalCompletion = - scopeNode.kind === 269 /* SourceFile */ || - scopeNode.kind === 197 /* TemplateExpression */ || - scopeNode.kind === 260 /* JsxExpression */ || - scopeNode.kind === 208 /* Block */ || // Some blocks aren't statements, but all get global completions - ts.isStatement(scopeNode); + if (isGlobalCompletionScope(scopeNode)) { + completionKind = 1 /* Global */; } var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); @@ -81216,6 +81441,17 @@ var ts; filterGlobalCompletion(symbols); return true; } + function isGlobalCompletionScope(scopeNode) { + switch (scopeNode.kind) { + case 269 /* SourceFile */: + case 197 /* TemplateExpression */: + case 260 /* JsxExpression */: + case 208 /* Block */: + return true; + default: + return ts.isStatement(scopeNode); + } + } function filterGlobalCompletion(symbols) { ts.filterMutate(symbols, function (symbol) { if (!ts.isSourceFile(location)) { @@ -81284,9 +81520,10 @@ var ts; for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; // Don't add a completion for a re-export, only for the original. - // If `symbol.parent !== moduleSymbol`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. + // If `symbol.parent !== ...`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. // If `some(...)`, this comes from an `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). - if (symbol.parent !== moduleSymbol || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { + if (symbol.parent !== typeChecker.resolveExternalModuleSymbol(moduleSymbol) + || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { continue; } var isDefaultExport = symbol.name === "default" /* Default */; @@ -81434,8 +81671,7 @@ var ts; */ function tryGetObjectLikeCompletionSymbols(objectLikeContainer) { // We're looking up possible property names from contextual/inferred/declared type. - isMemberCompletion = true; - allowStringLiteral = true; + completionKind = 0 /* ObjectPropertyDeclaration */; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 179 /* ObjectLiteralExpression */) { @@ -81508,7 +81744,7 @@ var ts; if (!moduleSpecifier) { return false; } - isMemberCompletion = true; + completionKind = 3 /* MemberLike */; isNewIdentifierLocation = false; var moduleSpecifierSymbol = typeChecker.getSymbolAtLocation(moduleSpecifier); if (!moduleSpecifierSymbol) { @@ -81525,7 +81761,7 @@ var ts; */ function getGetClassLikeCompletionSymbols(classLikeDeclaration) { // We're looking up possible property names from parent type. - isMemberCompletion = true; + completionKind = 3 /* MemberLike */; // Declaring new property/method/accessor isNewIdentifierLocation = true; // Has keywords for class elements @@ -82007,51 +82243,35 @@ var ts; return node.getStart() <= position && position <= node.getEnd(); } } - /** - * Get the name to be display in completion from a given symbol. - * - * @return undefined if the name is of external module - */ - function getCompletionEntryDisplayNameForSymbol(symbol, target, performCharacterChecks, allowStringLiteral, origin) { + function getCompletionEntryDisplayNameForSymbol(symbol, target, origin, kind) { var name = getSymbolName(symbol, origin, target); - if (!name) + if (name === undefined + // If the symbol is external module, don't show it in the completion list + // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) + || symbol.flags & 1536 /* Module */ && ts.startsWithQuote(name) + // If the symbol is the internal name of an ES symbol, it is not a valid entry. Internal names for ES symbols start with "__@" + || ts.isKnownSymbol(symbol)) { return undefined; - // First check of the displayName is not external module; if it is an external module, it is not valid entry - if (symbol.flags & 1920 /* Namespace */) { - var firstCharCode = name.charCodeAt(0); - if (ts.isSingleOrDoubleQuote(firstCharCode)) { - // If the symbol is external module, don't show it in the completion list - // (i.e declare module "http" { const x; } | // <= request completion here, "http" should not be there) + } + var validIdentiferResult = { name: name, needsConvertPropertyAccess: false }; + if (ts.isIdentifierText(name, target)) + return validIdentiferResult; + switch (kind) { + case 5 /* None */: + case 1 /* Global */: + case 3 /* MemberLike */: return undefined; - } + case 0 /* ObjectPropertyDeclaration */: + // TODO: GH#18169 + return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; + case 2 /* PropertyAccess */: + // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547 + return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true }; + case 4 /* String */: + return validIdentiferResult; + default: + ts.Debug.assertNever(kind); } - // If the symbol is for a member of an object type and is the internal name of an ES - // symbol, it is not a valid entry. Internal names for ES symbols start with "__@" - if (symbol.flags & 106500 /* ClassMember */) { - var escapedName = symbol.escapedName; - if (escapedName.length >= 3 && - escapedName.charCodeAt(0) === 95 /* _ */ && - escapedName.charCodeAt(1) === 95 /* _ */ && - escapedName.charCodeAt(2) === 64 /* at */) { - return undefined; - } - } - return getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral); - } - /** - * Get a displayName from a given for completion list, performing any necessary quotes stripping - * and checking whether the name is valid identifier name. - */ - function getCompletionEntryDisplayName(name, target, performCharacterChecks, allowStringLiteral) { - // If the user entered name for the symbol was quoted, removing the quotes is not enough, as the name could be an - // invalid identifier name. We need to check if whatever was inside the quotes is actually a valid identifier name. - // e.g "b a" is valid quoted name but when we strip off the quotes, it is invalid. - // We, thus, need to check if whatever was inside the quotes is actually a valid identifier name. - if (performCharacterChecks && !ts.isIdentifierText(name, target)) { - // TODO: GH#18169 - return allowStringLiteral ? JSON.stringify(name) : undefined; - } - return name; } // A cache of completion entries for keywords, these do not change between sessions var _keywordCompletions = []; @@ -82069,6 +82289,8 @@ var ts; return getFilteredKeywordCompletions(isClassMemberCompletionKeywordText); case 2 /* ConstructorParameterKeywords */: return getFilteredKeywordCompletions(isConstructorParameterCompletionKeywordText); + default: + ts.Debug.assertNever(keywordFilter); } } function getAllKeywordCompletions() { @@ -82185,11 +82407,7 @@ var ts; (function (DocumentHighlights) { function getDocumentHighlights(program, cancellationToken, sourceFile, position, sourceFilesToSearch) { var node = ts.getTouchingWord(sourceFile, position, /*includeJsDocComment*/ true); - // Note that getTouchingWord indicates failure by returning the sourceFile node. - if (node === sourceFile) - return undefined; - ts.Debug.assert(node.parent !== undefined); - if (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent)) { + if (node.parent && (ts.isJsxOpeningElement(node.parent) && node.parent.tagName === node || ts.isJsxClosingElement(node.parent))) { // For a JSX element, just highlight the matching tag, not all references. var _a = node.parent.parent, openingElement = _a.openingElement, closingElement = _a.closingElement; var highlightSpans = [openingElement, closingElement].map(function (_a) { @@ -82198,7 +82416,7 @@ var ts; }); return [{ fileName: sourceFile.fileName, highlightSpans: highlightSpans }]; } - return getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); + return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile); } DocumentHighlights.getDocumentHighlights = getDocumentHighlights; function getHighlightSpanForNode(node, sourceFile) { @@ -82208,8 +82426,8 @@ var ts; kind: "none" /* none */ }; } - function getSemanticDocumentHighlights(node, program, cancellationToken, sourceFilesToSearch) { - var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(node, program, sourceFilesToSearch, cancellationToken); + function getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) { + var referenceEntries = ts.FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken); return referenceEntries && convertReferencedSymbols(referenceEntries); } function convertReferencedSymbols(referenceEntries) { @@ -83292,7 +83510,7 @@ var ts; } /** If at an export specifier, go to the symbol it refers to. */ function skipExportSpecifierSymbol(symbol, checker) { - // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. + // For `export { foo } from './bar", there's nothing to skip, because it does not create a new alias. But `export { foo } does. if (symbol.declarations) { for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) { var declaration = _a[_i]; @@ -83349,12 +83567,12 @@ var ts; function getImplementationsAtPosition(program, cancellationToken, sourceFiles, sourceFile, position) { // A node in a JSDoc comment can't have an implementation anyway. var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ false); - var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node); + var referenceEntries = getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position); var checker = program.getTypeChecker(); return ts.map(referenceEntries, function (entry) { return toImplementationLocation(entry, checker); }); } FindAllReferences.getImplementationsAtPosition = getImplementationsAtPosition; - function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node) { + function getImplementationReferenceEntries(program, cancellationToken, sourceFiles, node, position) { if (node.kind === 269 /* SourceFile */) { return undefined; } @@ -83374,7 +83592,7 @@ var ts; } else { // Perform "Find all References" and retrieve only those that are implementations - return getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, { implementations: true }); + return getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, { implementations: true }); } } function findReferencedEntries(program, cancellationToken, sourceFiles, sourceFile, position, options) { @@ -83382,14 +83600,14 @@ var ts; return ts.map(x, toReferenceEntry); } FindAllReferences.findReferencedEntries = findReferencedEntries; - function getReferenceEntriesForNode(node, program, sourceFiles, cancellationToken, options) { + function getReferenceEntriesForNode(position, node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options)); + return flattenEntries(FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options)); } FindAllReferences.getReferenceEntriesForNode = getReferenceEntriesForNode; function findAllReferencedSymbols(program, cancellationToken, sourceFiles, sourceFile, position, options) { var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); - return FindAllReferences.Core.getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options); + return FindAllReferences.Core.getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options); } function flattenEntries(referenceSymbols) { return referenceSymbols && ts.flatMap(referenceSymbols, function (r) { return r.references; }); @@ -83528,10 +83746,11 @@ var ts; var Core; (function (Core) { /** Core find-all-references algorithm. Handles special cases before delegating to `getReferencedSymbolsForSymbol`. */ - function getReferencedSymbolsForNode(node, program, sourceFiles, cancellationToken, options) { + function getReferencedSymbolsForNode(position, node, program, sourceFiles, cancellationToken, options) { if (options === void 0) { options = {}; } - if (node.kind === 269 /* SourceFile */) { - return undefined; + if (ts.isSourceFile(node)) { + var reference = ts.GoToDefinition.getReferenceAtPosition(node, position, program); + return reference && getReferencedSymbolsForModule(program, program.getTypeChecker().getMergedSymbol(reference.file.symbol), sourceFiles); } if (!options.implementations) { var special = getReferencedSymbolsSpecial(node, sourceFiles, cancellationToken); @@ -83544,11 +83763,7 @@ var ts; // Could not find a symbol e.g. unknown identifier if (!symbol) { // String literal might be a property (and thus have a symbol), so do this here rather than in getReferencedSymbolsSpecial. - if (!options.implementations && node.kind === 9 /* StringLiteral */) { - return getReferencesForStringLiteral(node, sourceFiles, cancellationToken); - } - // Can't have references to something that we have no symbol for. - return undefined; + return !options.implementations && ts.isStringLiteral(node) ? getReferencesForStringLiteral(node, sourceFiles, cancellationToken) : undefined; } if (symbol.flags & 1536 /* Module */ && isModuleReferenceLocation(node)) { return getReferencedSymbolsForModule(program, symbol, sourceFiles); @@ -83743,6 +83958,9 @@ var ts; State.prototype.createSearch = function (location, symbol, comingFrom, searchOptions) { if (searchOptions === void 0) { searchOptions = {}; } // Note: if this is an external module symbol, the name doesn't include quotes. + // Note: getLocalSymbolForExportDefault handles `export default class C {}`, but not `export default C` or `export { C as default }`. + // The other two forms seem to be handled downstream (e.g. in `skipPastExportOrImportSpecifier`), so special-casing the first form + // here appears to be intentional). var _a = searchOptions.text, text = _a === void 0 ? ts.stripQuotes(ts.unescapeLeadingUnderscores((ts.getLocalSymbolForExportDefault(symbol) || symbol).escapedName)) : _a, _b = searchOptions.allSearchSymbols, allSearchSymbols = _b === void 0 ? undefined : _b; var escapedText = ts.escapeLeadingUnderscores(text); var parents = this.options.implementations && getParentSymbolsOfPropertyAccess(location, symbol, this.checker); @@ -84898,21 +85116,9 @@ var ts; var GoToDefinition; (function (GoToDefinition) { function getDefinitionAtPosition(program, sourceFile, position) { - /// Triple slash reference comments - var comment = findReferenceInPosition(sourceFile.referencedFiles, position); - if (comment) { - var referenceFile = ts.tryResolveScriptReference(program, sourceFile, comment); - if (referenceFile) { - return [getDefinitionInfoForFileReference(comment.fileName, referenceFile.fileName)]; - } - // Might still be on jsdoc, so keep looking. - } - // Type reference directives - var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); - if (typeReferenceDirective) { - var referenceFile = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); - return referenceFile && referenceFile.resolvedFileName && - [getDefinitionInfoForFileReference(typeReferenceDirective.fileName, referenceFile.resolvedFileName)]; + var reference = getReferenceAtPosition(sourceFile, position, program); + if (reference) { + return [getDefinitionInfoForFileReference(reference.fileName, reference.file.fileName)]; } var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); if (node === sourceFile) { @@ -85000,6 +85206,21 @@ var ts; return getDefinitionFromSymbol(typeChecker, symbol, node); } GoToDefinition.getDefinitionAtPosition = getDefinitionAtPosition; + function getReferenceAtPosition(sourceFile, position, program) { + var referencePath = findReferenceInPosition(sourceFile.referencedFiles, position); + if (referencePath) { + var file = ts.tryResolveScriptReference(program, sourceFile, referencePath); + return file && { fileName: referencePath.fileName, file: file }; + } + var typeReferenceDirective = findReferenceInPosition(sourceFile.typeReferenceDirectives, position); + if (typeReferenceDirective) { + var reference = program.getResolvedTypeReferenceDirectives().get(typeReferenceDirective.fileName); + var file = reference && program.getSourceFile(reference.resolvedFileName); + return file && { fileName: typeReferenceDirective.fileName, file: file }; + } + return undefined; + } + GoToDefinition.getReferenceAtPosition = getReferenceAtPosition; /// Goto type function getTypeDefinitionAtPosition(typeChecker, sourceFile, position) { var node = ts.getTouchingPropertyName(sourceFile, position, /*includeJsDocComment*/ true); @@ -85172,6 +85393,7 @@ var ts; } return undefined; } + GoToDefinition.findReferenceInPosition = findReferenceInPosition; function getDefinitionInfoForFileReference(name, targetFileName) { return { fileName: targetFileName, @@ -85319,7 +85541,7 @@ var ts; function forEachUnique(array, callback) { if (array) { for (var i = 0; i < array.length; i++) { - if (ts.indexOf(array, array[i]) === i) { + if (array.indexOf(array[i]) === i) { var result = callback(array[i], i); if (result) { return result; @@ -85853,7 +86075,7 @@ var ts; if (!shouldKeepItem(declaration, checker)) { continue; } - // It was a match! If the pattern has dots in it, then also see if the + // It was a match! If the pattern has dots in it, then also see if the // declaration container matches as well. var containerMatches = matches; if (patternMatcher.patternContainsDots) { @@ -85882,8 +86104,8 @@ var ts; function allMatchesAreCaseSensitive(matches) { ts.Debug.assert(matches.length > 0); // This is a case sensitive match, only if all the submatches were case sensitive. - for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { - var match = matches_2[_i]; + for (var _i = 0, matches_1 = matches; _i < matches_1.length; _i++) { + var match = matches_1[_i]; if (!match.isCaseSensitive) { return false; } @@ -85952,8 +86174,8 @@ var ts; function bestMatchKind(matches) { ts.Debug.assert(matches.length > 0); var bestMatchKind = ts.PatternMatchKind.camelCase; - for (var _i = 0, matches_3 = matches; _i < matches_3.length; _i++) { - var match = matches_3[_i]; + for (var _i = 0, matches_2 = matches; _i < matches_2.length; _i++) { + var match = matches_2[_i]; var kind = match.kind; if (kind < bestMatchKind) { bestMatchKind = kind; @@ -87598,7 +87820,7 @@ var ts; // import "mod"; // import d from "mod" // import {a as A } from "mod"; - // import * as NS from "mod" + // import * as NS from "mod" // import d, {a, b as B} from "mod" // import i = require("mod"); // import("mod"); @@ -87698,9 +87920,16 @@ var ts; symbol.parent.flags & 1536 /* Module */) { return undefined; } - var displayName = ts.stripQuotes(ts.getDeclaredName(typeChecker, symbol, node)); var kind = ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, node); - return kind ? getRenameInfoSuccess(displayName, typeChecker.getFullyQualifiedName(symbol), kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile) : undefined; + if (!kind) { + return undefined; + } + var specifierName = (ts.isImportOrExportSpecifierName(node) || ts.isStringOrNumericLiteral(node) && node.parent.kind === 145 /* ComputedPropertyName */) + ? ts.stripQuotes(ts.getTextOfIdentifierOrLiteral(node)) + : undefined; + var displayName = specifierName || typeChecker.symbolToString(symbol); + var fullDisplayName = specifierName || typeChecker.getFullyQualifiedName(symbol); + return getRenameInfoSuccess(displayName, fullDisplayName, kind, ts.SymbolDisplay.getSymbolModifiers(symbol), node, sourceFile); } } else if (node.kind === 9 /* StringLiteral */) { @@ -87934,7 +88163,7 @@ var ts; function getArgumentIndex(argumentsList, node) { // The list we got back can include commas. In the presence of errors it may // also just have nodes without commas. For example "Foo(a b c)" will have 3 - // args without commas. We want to find what index we're at. So we count + // args without commas. We want to find what index we're at. So we count // forward until we hit ourselves, only incrementing the index if it isn't a // comma. // @@ -87960,12 +88189,12 @@ var ts; // The argument count for a list is normally the number of non-comma children it has. // For example, if you have "Foo(a,b)" then there will be three children of the arg // list 'a' '' 'b'. So, in this case the arg count will be 2. However, there - // is a small subtlety. If you have "Foo(a,)", then the child list will just have + // is a small subtlety. If you have "Foo(a,)", then the child list will just have // 'a' ''. So, in the case where the last child is a comma, we increase the // arg count by one to compensate. // - // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then - // we'll have: 'a' '' '' + // Note: this subtlety only applies to the last comma. If you had "Foo(a,," then + // we'll have: 'a' '' '' // That will give us 2 non-commas. We then add one for the last comma, giving us an // arg count of 3. var listChildren = argumentsList.getChildren(); @@ -87986,9 +88215,11 @@ var ts; // not enough to put us in the substitution expression; we should consider ourselves part of // the *next* span's expression by offsetting the index (argIndex = (spanIndex + 1) + 1). // + // tslint:disable no-double-space // Example: f `# abcd $#{# 1 + 1# }# efghi ${ #"#hello"# } # ` // ^ ^ ^ ^ ^ ^ ^ ^ ^ // Case: 1 1 3 2 1 3 2 2 1 + // tslint:enable no-double-space ts.Debug.assert(position >= node.getStart(), "Assumed 'position' could not occur before node."); if (ts.isTemplateLiteralKind(node.kind)) { if (ts.isInsideTemplateLiteral(node, position)) { @@ -88035,9 +88266,8 @@ var ts; // Otherwise, we will not show signature help past the expression. // For example, // - // ` ${ 1 + 1 foo(10) - // | | - // + // ` ${ 1 + 1 foo(10) + // | | // This is because a Missing node has no width. However, what we actually want is to include trivia // leading up to the next token in case the user is about to type in a TemplateMiddle or TemplateTail. if (template.kind === 197 /* TemplateExpression */) { @@ -88266,7 +88496,7 @@ var ts; } SymbolDisplay.getSymbolModifiers = getSymbolModifiers; // TODO(drosen): Currently completion entry details passes the SemanticMeaning.All instead of using semanticMeaning of location - function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning) { + function getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, symbol, sourceFile, enclosingDeclaration, location, semanticMeaning, alias) { if (semanticMeaning === void 0) { semanticMeaning = ts.getMeaningFromLocation(location); } var displayParts = []; var documentation; @@ -88276,6 +88506,7 @@ var ts; var hasAddedSymbolInfo; var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); var type; + var documentationFromAlias; // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { // If it is accessor they are allowed only if location is at name of the accessor @@ -88391,6 +88622,7 @@ var ts; } } if (symbolFlags & 32 /* Class */ && !hasAddedSymbolInfo && !isThisExpression) { + addAliasPrefixIfNecessary(); if (ts.getDeclarationOfKind(symbol, 200 /* ClassExpression */)) { // Special case for class expressions because we would like to indicate that // the class name is local to the class body (similar to function expression) @@ -88406,14 +88638,14 @@ var ts; writeTypeParametersOfSymbol(symbol, sourceFile); } if ((symbolFlags & 64 /* Interface */) && (semanticMeaning & 2 /* Type */)) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(109 /* InterfaceKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); writeTypeParametersOfSymbol(symbol, sourceFile); } if (symbolFlags & 524288 /* TypeAlias */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(138 /* TypeKeyword */)); displayParts.push(ts.spacePart()); addFullSymbolName(symbol); @@ -88424,7 +88656,7 @@ var ts; ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 1024 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); if (ts.forEach(symbol.declarations, ts.isConstEnumDeclaration)) { displayParts.push(ts.keywordPart(76 /* ConstKeyword */)); displayParts.push(ts.spacePart()); @@ -88434,7 +88666,7 @@ var ts; addFullSymbolName(symbol); } if (symbolFlags & 1536 /* Module */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); var declaration = ts.getDeclarationOfKind(symbol, 234 /* ModuleDeclaration */); var isNamespace = declaration && declaration.name && declaration.name.kind === 71 /* Identifier */; displayParts.push(ts.keywordPart(isNamespace ? 129 /* NamespaceKeyword */ : 128 /* ModuleKeyword */)); @@ -88442,7 +88674,7 @@ var ts; addFullSymbolName(symbol); } if ((symbolFlags & 262144 /* TypeParameter */) && (semanticMeaning & 2 /* Type */)) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); displayParts.push(ts.textPart("type parameter")); displayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); @@ -88475,7 +88707,7 @@ var ts; else if (declaration.kind === 232 /* TypeAliasDeclaration */) { // Type alias type parameter // For example - // type list = T[]; // Both T will go through same code path + // type list = T[]; // Both T will go through same code path addInPrefix(); displayParts.push(ts.keywordPart(138 /* TypeKeyword */)); displayParts.push(ts.spacePart()); @@ -88500,7 +88732,23 @@ var ts; } } if (symbolFlags & 2097152 /* Alias */) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); + if (!hasAddedSymbolInfo) { + var resolvedSymbol = typeChecker.getAliasedSymbol(symbol); + if (resolvedSymbol !== symbol && resolvedSymbol.declarations && resolvedSymbol.declarations.length > 0) { + var resolvedNode = resolvedSymbol.declarations[0]; + var declarationName = ts.getNameOfDeclaration(resolvedNode); + if (declarationName) { + var isExternalModuleDeclaration = ts.isModuleWithStringLiteralName(resolvedNode) && + ts.hasModifier(resolvedNode, 2 /* Ambient */); + var shouldUseAliasName = symbol.name !== "default" && !isExternalModuleDeclaration; + var resolvedInfo = getSymbolDisplayPartsDocumentationAndSymbolKind(typeChecker, resolvedSymbol, ts.getSourceFileOfNode(resolvedNode), resolvedNode, declarationName, semanticMeaning, shouldUseAliasName ? symbol : resolvedSymbol); + displayParts.push.apply(displayParts, resolvedInfo.displayParts); + displayParts.push(ts.lineBreakPart()); + documentationFromAlias = resolvedInfo.documentation; + } + } + } switch (symbol.declarations[0].kind) { case 237 /* NamespaceExportDeclaration */: displayParts.push(ts.keywordPart(84 /* ExportKeyword */)); @@ -88546,7 +88794,7 @@ var ts; if (symbolKind !== "" /* unknown */) { if (type) { if (isThisExpression) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); displayParts.push(ts.keywordPart(99 /* ThisKeyword */)); } else { @@ -88614,23 +88862,36 @@ var ts; } } } + if (documentation.length === 0 && documentationFromAlias) { + documentation = documentationFromAlias; + } return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; - function addNewLineIfDisplayPartsExist() { + function prefixNextMeaning() { if (displayParts.length) { displayParts.push(ts.lineBreakPart()); } + addAliasPrefixIfNecessary(); + } + function addAliasPrefixIfNecessary() { + if (alias) { + pushTypePart("alias" /* alias */); + displayParts.push(ts.spacePart()); + } } function addInPrefix() { displayParts.push(ts.spacePart()); displayParts.push(ts.keywordPart(92 /* InKeyword */)); displayParts.push(ts.spacePart()); } - function addFullSymbolName(symbol, enclosingDeclaration) { - var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */); + function addFullSymbolName(symbolToDisplay, enclosingDeclaration) { + if (alias && symbolToDisplay === symbol) { + symbolToDisplay = alias; + } + var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */); ts.addRange(displayParts, fullSymbolDisplayParts); } function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { - addNewLineIfDisplayPartsExist(); + prefixNextMeaning(); if (symbolKind) { pushTypePart(symbolKind); if (symbol && !ts.some(symbol.declarations, function (d) { return ts.isArrowFunction(d) || (ts.isFunctionExpression(d) || ts.isClassExpression(d)) && !d.name; })) { @@ -89216,7 +89477,7 @@ var ts; // Leave comments alone rule("IgnoreBeforeComment", anyToken, comments, formatting.anyContext, 1 /* Ignore */), rule("IgnoreAfterLineComment", 2 /* SingleLineCommentTrivia */, anyToken, formatting.anyContext, 1 /* Ignore */), - rule("NoSpaceBeforeColon", anyToken, 56 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), + rule("NotSpaceBeforeColon", anyToken, 56 /* ColonToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext, isNotTypeAnnotationContext], 8 /* Delete */), rule("SpaceAfterColon", 56 /* ColonToken */, anyToken, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 2 /* Space */), rule("NoSpaceBeforeQuestionMark", anyToken, 55 /* QuestionToken */, [isNonJsxSameLineTokenContext, isNotBinaryOpContext], 8 /* Delete */), // insert space after '?' only when it is used in conditional operator @@ -89234,10 +89495,10 @@ var ts; rule("NoSpaceBeforeUnaryPostincrementOperator", unaryPostincrementExpressions, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), rule("NoSpaceBeforeUnaryPostdecrementOperator", unaryPostdecrementExpressions, 44 /* MinusMinusToken */, [isNonJsxSameLineTokenContext], 8 /* Delete */), // More unary operator special-casing. - // DevDiv 181814: Be careful when removing leading whitespace + // DevDiv 181814: Be careful when removing leading whitespace // around unary operators. Examples: - // 1 - -2 --X--> 1--2 - // a + ++b --X--> a+++b + // 1 - -2 --X--> 1--2 + // a + ++b --X--> a+++b rule("SpaceAfterPostincrementWhenFollowedByAdd", 43 /* PlusPlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterAddWhenFollowedByUnaryPlus", 37 /* PlusToken */, 37 /* PlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), rule("SpaceAfterAddWhenFollowedByPreincrement", 37 /* PlusToken */, 43 /* PlusPlusToken */, [isNonJsxSameLineTokenContext, isBinaryOpContext], 2 /* Space */), @@ -89413,6 +89674,8 @@ var ts; rule("NewLineBeforeOpenBraceInTypeScriptDeclWithBlock", typeScriptOpenBraceLeftTokenRange, 17 /* OpenBraceToken */, [isOptionEnabled("placeOpenBraceOnNewLineForFunctions"), isTypeScriptDeclWithBlockContext, isBeforeMultilineBlockContext], 4 /* NewLine */, 1 /* CanDeleteNewLines */), rule("SpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionEnabled("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 2 /* Space */), rule("NoSpaceAfterTypeAssertion", 29 /* GreaterThanToken */, anyToken, [isOptionDisabledOrUndefined("insertSpaceAfterTypeAssertion"), isNonJsxSameLineTokenContext, isTypeAssertionContext], 8 /* Delete */), + rule("SpaceBeforeTypeAnnotation", anyToken, 56 /* ColonToken */, [isOptionEnabled("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 2 /* Space */), + rule("NoSpaceBeforeTypeAnnotation", anyToken, 56 /* ColonToken */, [isOptionDisabledOrUndefined("insertSpaceBeforeTypeAnnotation"), isNonJsxSameLineTokenContext, isTypeAnnotationContext], 8 /* Delete */), ]; // These rules are lower in priority than user-configurable. Rules earlier in this list have priority over rules later in the list. var lowPriorityCommonRules = [ @@ -89518,6 +89781,17 @@ var ts; function isNotBinaryOpContext(context) { return !isBinaryOpContext(context); } + function isNotTypeAnnotationContext(context) { + return !isTypeAnnotationContext(context); + } + function isTypeAnnotationContext(context) { + var contextKind = context.contextNode.kind; + return contextKind === 150 /* PropertyDeclaration */ || + contextKind === 149 /* PropertySignature */ || + contextKind === 147 /* Parameter */ || + contextKind === 227 /* VariableDeclaration */ || + ts.isFunctionLikeKind(contextKind); + } function isConditionalOperatorContext(context) { return context.contextNode.kind === 196 /* ConditionalExpression */; } @@ -91207,11 +91481,13 @@ var ts; SmartIndenter.getContainingList = getContainingList; function getActualIndentationForListItem(node, sourceFile, options) { var containingList = getContainingList(node, sourceFile); - return containingList ? getActualIndentationFromList(containingList) : -1 /* Unknown */; - function getActualIndentationFromList(list) { - var index = ts.indexOf(list, node); - return index !== -1 ? deriveActualIndentationFromList(list, index, sourceFile, options) : -1 /* Unknown */; + if (containingList) { + var index = containingList.indexOf(node); + if (index !== -1) { + return deriveActualIndentationFromList(containingList, index, sourceFile, options); + } } + return -1 /* Unknown */; } function getLineIndentationWhenExpressionIsInMultiLine(node, sourceFile, options) { // actual indentation should not be used when: @@ -93531,6 +93807,9 @@ var ts; return [fromPaths]; } } + if (isPathRelativeToParent(relativeToBaseUrl)) { + return [relativePath]; + } /* Prefer a relative import over a baseUrl import if it doesn't traverse up to baseUrl. @@ -93593,10 +93872,11 @@ var ts; return decl.name.text; } } - function tryGetModuleNameFromPaths(relativeNameWithIndex, relativeName, paths) { + function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) { for (var key in paths) { for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) { - var pattern = _a[_i]; + var patternText_1 = _a[_i]; + var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1)); var indexOfStar = pattern.indexOf("*"); if (indexOfStar === 0 && pattern.length === 1) { continue; @@ -93604,14 +93884,14 @@ var ts; else if (indexOfStar !== -1) { var prefix = pattern.substr(0, indexOfStar); var suffix = pattern.substr(indexOfStar + 1); - if (relativeName.length >= prefix.length + suffix.length && - ts.startsWith(relativeName, prefix) && - ts.endsWith(relativeName, suffix)) { - var matchedStar = relativeName.substr(prefix.length, relativeName.length - suffix.length); - return key.replace("\*", matchedStar); + if (relativeToBaseUrl.length >= prefix.length + suffix.length && + ts.startsWith(relativeToBaseUrl, prefix) && + ts.endsWith(relativeToBaseUrl, suffix)) { + var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length); + return key.replace("*", matchedStar); } } - else if (pattern === relativeName || pattern === relativeNameWithIndex) { + else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) { return key; } } @@ -93739,7 +94019,10 @@ var ts; return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined; } function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) { - return ts.firstDefined(rootDirs, function (rootDir) { return getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); }); + return ts.firstDefined(rootDirs, function (rootDir) { + var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); + return isPathRelativeToParent(relativePath) ? undefined : relativePath; + }); } function removeExtensionAndIndexPostFix(fileName, options, addJsExtension) { var noExtension = ts.removeFileExtension(fileName); @@ -93751,7 +94034,10 @@ var ts; } function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - return ts.isRootedDiskPath(relativePath) || ts.startsWith(relativePath, "..") ? undefined : relativePath; + return ts.isRootedDiskPath(relativePath) ? undefined : relativePath; + } + function isPathRelativeToParent(path) { + return ts.startsWith(path, ".."); } function getRelativePath(path, directoryPath, getCanonicalFileName) { var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); @@ -93891,8 +94177,9 @@ var ts; var defaultExport = checker.tryGetMemberInModuleExports("default" /* Default */, moduleSymbol); if (defaultExport) { var localSymbol = ts.getLocalSymbolForExportDefault(defaultExport); - if ((localSymbol && localSymbol.escapedName === symbolName || moduleSymbolToValidIdentifier(moduleSymbol, context.compilerOptions.target) === symbolName) - && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { + if ((localSymbol && localSymbol.escapedName === symbolName || + getEscapedNameForExportDefault(defaultExport) === symbolName || + moduleSymbolToValidIdentifier(moduleSymbol, context.compilerOptions.target) === symbolName) && checkSymbolHasMeaning(localSymbol || defaultExport, currentTokenMeaning)) { // check if this symbol is already used var symbolId = ts.getUniqueSymbolId(localSymbol || defaultExport, checker); symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 1 /* Default */ }))); @@ -93904,6 +94191,21 @@ var ts; var symbolId = ts.getUniqueSymbolId(exportSymbolWithIdenticalName, checker); symbolIdActionMap.addActions(symbolId, getCodeActionForImport(moduleSymbol, __assign({}, context, { kind: 0 /* Named */ }))); } + function getEscapedNameForExportDefault(symbol) { + return ts.firstDefined(symbol.declarations, function (declaration) { + if (ts.isExportAssignment(declaration)) { + if (ts.isIdentifier(declaration.expression)) { + return declaration.expression.escapedText; + } + } + else if (ts.isExportSpecifier(declaration)) { + ts.Debug.assert(declaration.name.escapedText === "default" /* Default */); + if (declaration.propertyName) { + return declaration.propertyName.escapedText; + } + } + }); + } }); return symbolIdActionMap.getAllActions(); } @@ -94797,6 +95099,94 @@ var ts; })(InferFromReference || (InferFromReference = {})); })(codefix = ts.codefix || (ts.codefix = {})); })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + var codefix; + (function (codefix) { + codefix.registerCodeFix({ + errorCodes: [ts.Diagnostics.A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime.code], + getCodeActions: getActionsForInvalidImport + }); + function getActionsForInvalidImport(context) { + var sourceFile = context.sourceFile; + // This is the whole import statement, eg: + // import * as Bluebird from 'bluebird'; + // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + var node = ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false).parent; + if (!ts.isImportDeclaration(node)) { + // No import quick fix for import calls + return []; + } + return getCodeFixesForImportDeclaration(context, node); + } + function getCodeFixesForImportDeclaration(context, node) { + var sourceFile = ts.getSourceFileOfNode(node); + var namespace = ts.getNamespaceDeclarationNode(node); + var opts = context.program.getCompilerOptions(); + var variations = []; + // import Bluebird from "bluebird"; + var replacement = ts.createImportDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, ts.createImportClause(namespace.name, /*namedBindings*/ undefined), node.moduleSpecifier); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, node, replacement, { useNonAdjustedEndPosition: true }); + var changes = changeTracker.getChanges(); + variations.push({ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Replace_import_with_0), [changes[0].textChanges[0].newText]), + changes: changes + }); + if (ts.getEmitModuleKind(opts) === ts.ModuleKind.CommonJS) { + // import Bluebird = require("bluebird"); + var replacement_1 = ts.createImportEqualsDeclaration( + /*decorators*/ undefined, + /*modifiers*/ undefined, namespace.name, ts.createExternalModuleReference(node.moduleSpecifier)); + var changeTracker_1 = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker_1.replaceNode(sourceFile, node, replacement_1, { useNonAdjustedEndPosition: true }); + var changes_1 = changeTracker_1.getChanges(); + variations.push({ + description: ts.formatStringFromArgs(ts.getLocaleSpecificMessage(ts.Diagnostics.Replace_import_with_0), [changes_1[0].textChanges[0].newText]), + changes: changes_1 + }); + } + return variations; + } + codefix.registerCodeFix({ + errorCodes: [ + ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code, + ts.Diagnostics.Cannot_use_new_with_an_expression_whose_type_lacks_a_call_or_construct_signature.code, + ], + getCodeActions: getActionsForUsageOfInvalidImport + }); + function getActionsForUsageOfInvalidImport(context) { + var sourceFile = context.sourceFile; + var targetKind = ts.Diagnostics.Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatures.code === context.errorCode ? 182 /* CallExpression */ : 183 /* NewExpression */; + var node = ts.findAncestor(ts.getTokenAtPosition(sourceFile, context.span.start, /*includeJsDocComment*/ false), function (a) { return a.kind === targetKind && a.getStart() === context.span.start && a.getEnd() === (context.span.start + context.span.length); }); + if (!node) { + return []; + } + var expr = node.expression; + var type = context.program.getTypeChecker().getTypeAtLocation(expr); + if (!(type.symbol && type.symbol.originatingImport)) { + return []; + } + var fixes = []; + var relatedImport = type.symbol.originatingImport; + if (!ts.isImportCall(relatedImport)) { + ts.addRange(fixes, getCodeFixesForImportDeclaration(context, relatedImport)); + } + var propertyAccess = ts.createPropertyAccess(expr, "default"); + var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); + changeTracker.replaceNode(sourceFile, expr, propertyAccess, {}); + var changes = changeTracker.getChanges(); + fixes.push({ + description: ts.getLocaleSpecificMessage(ts.Diagnostics.Use_synthetic_default_member), + changes: changes + }); + return fixes; + } + })(codefix = ts.codefix || (ts.codefix = {})); +})(ts || (ts = {})); /// /// /// @@ -94814,6 +95204,7 @@ var ts; /// /// /// +/// /* @internal */ var ts; (function (ts) { @@ -98159,7 +98550,7 @@ var ts; return program.getOptionsDiagnostics(cancellationToken).concat(program.getGlobalDiagnostics(cancellationToken)); } function getCompletionsAtPosition(fileName, position, options) { - if (options === void 0) { options = { includeExternalModuleExports: false }; } + if (options === void 0) { options = { includeExternalModuleExports: false, includeInsertTextCompletions: false }; } synchronizeHostData(); return ts.Completions.getCompletionsAtPosition(host, program.getTypeChecker(), log, program.getCompilerOptions(), getValidSourceFile(fileName), position, program.getSourceFiles(), options); } @@ -98649,7 +99040,7 @@ var ts; return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"); } function getTodoCommentsRegExp() { - // NOTE: ?: means 'non-capture group'. It allows us to have groups without having to + // NOTE: `?:` means 'non-capture group'. It allows us to have groups without having to // filter them out later in the final result array. // TODO comments can appear in one of the following forms: // @@ -98824,19 +99215,6 @@ var ts; isArgumentOfElementAccessExpression(node) || ts.isLiteralComputedPropertyDeclarationName(node); } - function isObjectLiteralElement(node) { - switch (node.kind) { - case 257 /* JsxAttribute */: - case 259 /* JsxSpreadAttribute */: - case 265 /* PropertyAssignment */: - case 266 /* ShorthandPropertyAssignment */: - case 152 /* MethodDeclaration */: - case 154 /* GetAccessor */: - case 155 /* SetAccessor */: - return true; - } - return false; - } /** * Returns the containing object literal property declaration given a possible name node, e.g. "a" in x = { "a": 1 } */ @@ -98846,11 +99224,11 @@ var ts; case 9 /* StringLiteral */: case 8 /* NumericLiteral */: if (node.parent.kind === 145 /* ComputedPropertyName */) { - return isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; + return ts.isObjectLiteralElement(node.parent.parent) ? node.parent.parent : undefined; } // falls through case 71 /* Identifier */: - return isObjectLiteralElement(node.parent) && + return ts.isObjectLiteralElement(node.parent) && (node.parent.parent.kind === 179 /* ObjectLiteralExpression */ || node.parent.parent.kind === 258 /* JsxAttributes */) && node.parent.name === node ? node.parent : undefined; } @@ -99118,8 +99496,8 @@ var ts; return spanInArrayLiteralOrObjectLiteralDestructuringPattern(node); } // Set breakpoint on identifier element of destructuring pattern - // a or ...c or d: x from - // [a, b, ...c] or { a, b } or { d: x } from destructuring pattern + // `a` or `...c` or `d: x` from + // `[a, b, ...c]` or `{ a, b }` or `{ d: x }` from destructuring pattern if ((node.kind === 71 /* Identifier */ || node.kind === 199 /* SpreadElement */ || node.kind === 265 /* PropertyAssignment */ || @@ -99261,8 +99639,9 @@ var ts; } else { var functionDeclaration = parameter.parent; - var indexOfParameter = ts.indexOf(functionDeclaration.parameters, parameter); - if (indexOfParameter) { + var indexOfParameter = functionDeclaration.parameters.indexOf(parameter); + ts.Debug.assert(indexOfParameter !== -1); + if (indexOfParameter !== 0) { // Not a first parameter, go to previous parameter return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]); } @@ -100020,7 +100399,6 @@ var ts; return this.forwardJSONCall("getCompletionsAtPosition('" + fileName + "', " + position + ", " + options + ")", function () { return _this.languageService.getCompletionsAtPosition(fileName, position, options); }); }; /** Get a string based representation of a completion list entry details */ - // tslint:disable-next-line type-operator-spacing (false positive) LanguageServiceShimObject.prototype.getCompletionEntryDetails = function (fileName, position, entryName, options, source) { var _this = this; return this.forwardJSONCall("getCompletionEntryDetails('" + fileName + "', " + position + ", '" + entryName + "')", function () { diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index b307aba6e8a..ead7d59877d 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -425,17 +425,6 @@ var ts; return false; } ts.contains = contains; - function indexOf(array, value) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (array[i] === value) { - return i; - } - } - } - return -1; - } - ts.indexOf = indexOf; function indexOfAnyCharCode(text, charCodes, start) { for (var i = start || 0; i < text.length; i++) { if (contains(charCodes, text.charCodeAt(i))) { @@ -1719,7 +1708,9 @@ var ts; var moduleKind = getEmitModuleKind(compilerOptions); return compilerOptions.allowSyntheticDefaultImports !== undefined ? compilerOptions.allowSyntheticDefaultImports - : moduleKind === ts.ModuleKind.System; + : compilerOptions.esModuleInterop + ? moduleKind !== ts.ModuleKind.None && moduleKind < ts.ModuleKind.ES2015 + : moduleKind === ts.ModuleKind.System; } ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports; function getStrictOptionValue(compilerOptions, flag) { @@ -3352,6 +3343,8 @@ var ts; unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name: diag(1333, ts.DiagnosticCategory.Error, "unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name_1333", "'unique symbol' types may not be used on a variable declaration with a binding name."), unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement: diag(1334, ts.DiagnosticCategory.Error, "unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement_1334", "'unique symbol' types are only allowed on variables in a variable statement."), unique_symbol_types_are_not_allowed_here: diag(1335, ts.DiagnosticCategory.Error, "unique_symbol_types_are_not_allowed_here_1335", "'unique symbol' types are not allowed here."), + An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead: diag(1336, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336", "An index signature parameter type cannot be a type alias. Consider writing '[{0}: {1}]: {2}' instead."), + An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead: diag(1337, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337", "An index signature parameter type cannot be a union type. Consider using a mapped object type instead."), Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."), Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor: diag(2301, ts.DiagnosticCategory.Error, "Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor_2301", "Initializer of instance member variable '{0}' cannot reference identifier '{1}' declared in the constructor."), Static_members_cannot_reference_class_type_parameters: diag(2302, ts.DiagnosticCategory.Error, "Static_members_cannot_reference_class_type_parameters_2302", "Static members cannot reference class type parameters."), @@ -3466,6 +3459,7 @@ var ts; Numeric_index_type_0_is_not_assignable_to_string_index_type_1: diag(2413, ts.DiagnosticCategory.Error, "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413", "Numeric index type '{0}' is not assignable to string index type '{1}'."), Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."), Class_0_incorrectly_extends_base_class_1: diag(2415, ts.DiagnosticCategory.Error, "Class_0_incorrectly_extends_base_class_1_2415", "Class '{0}' incorrectly extends base class '{1}'."), + Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2: diag(2416, ts.DiagnosticCategory.Error, "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416", "Property '{0}' in type '{1}' is not assignable to the same property in base type '{2}'."), Class_static_side_0_incorrectly_extends_base_class_static_side_1: diag(2417, ts.DiagnosticCategory.Error, "Class_static_side_0_incorrectly_extends_base_class_static_side_1_2417", "Class static side '{0}' incorrectly extends base class static side '{1}'."), Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_may_only_implement_another_class_or_interface: diag(2422, ts.DiagnosticCategory.Error, "A_class_may_only_implement_another_class_or_interface_2422", "A class may only implement another class or interface."), @@ -3520,7 +3514,7 @@ var ts; Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher: diag(2472, ts.DiagnosticCategory.Error, "Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher_2472", "Spread operator in 'new' expressions is only available when targeting ECMAScript 5 and higher."), Enum_declarations_must_all_be_const_or_non_const: diag(2473, ts.DiagnosticCategory.Error, "Enum_declarations_must_all_be_const_or_non_const_2473", "Enum declarations must all be const or non-const."), In_const_enum_declarations_member_initializer_must_be_constant_expression: diag(2474, ts.DiagnosticCategory.Error, "In_const_enum_declarations_member_initializer_must_be_constant_expression_2474", "In 'const' enum declarations member initializer must be constant expression."), - const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment."), + const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_import_declaration_or_export_assignment_or_type_query: diag(2475, ts.DiagnosticCategory.Error, "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475", "'const' enums can only be used in property or index access expressions or the right hand side of an import declaration or export assignment or type query."), A_const_enum_member_can_only_be_accessed_using_a_string_literal: diag(2476, ts.DiagnosticCategory.Error, "A_const_enum_member_can_only_be_accessed_using_a_string_literal_2476", "A const enum member can only be accessed using a string literal."), const_enum_member_initializer_was_evaluated_to_a_non_finite_value: diag(2477, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477", "'const' enum member initializer was evaluated to a non-finite value."), const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN: diag(2478, ts.DiagnosticCategory.Error, "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478", "'const' enum member initializer was evaluated to disallowed value 'NaN'."), @@ -3687,6 +3681,9 @@ var ts; Duplicate_declaration_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_declaration_0_2718", "Duplicate declaration '{0}'."), Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated: diag(2719, ts.DiagnosticCategory.Error, "Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated_2719", "Type '{0}' is not assignable to type '{1}'. Two different types with this name exist, but they are unrelated."), Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass: diag(2720, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclas_2720", "Class '{0}' incorrectly implements class '{1}'. Did you mean to extend '{1}' and inherit its members as a subclass?"), + Cannot_invoke_an_object_which_is_possibly_null: diag(2721, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_2721", "Cannot invoke an object which is possibly 'null'."), + Cannot_invoke_an_object_which_is_possibly_undefined: diag(2722, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_undefined_2722", "Cannot invoke an object which is possibly 'undefined'."), + Cannot_invoke_an_object_which_is_possibly_null_or_undefined: diag(2723, ts.DiagnosticCategory.Error, "Cannot_invoke_an_object_which_is_possibly_null_or_undefined_2723", "Cannot invoke an object which is possibly 'null' or 'undefined'."), Import_declaration_0_is_using_private_name_1: diag(4000, ts.DiagnosticCategory.Error, "Import_declaration_0_is_using_private_name_1_4000", "Import declaration '{0}' is using private name '{1}'."), Type_parameter_0_of_exported_class_has_or_is_using_private_name_1: diag(4002, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_class_has_or_is_using_private_name_1_4002", "Type parameter '{0}' of exported class has or is using private name '{1}'."), Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1: diag(4004, ts.DiagnosticCategory.Error, "Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1_4004", "Type parameter '{0}' of exported interface has or is using private name '{1}'."), @@ -4001,6 +3998,8 @@ var ts; Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined: diag(7034, ts.DiagnosticCategory.Error, "Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined_7034", "Variable '{0}' implicitly has type '{1}' in some locations where its type cannot be determined."), Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0: diag(7035, ts.DiagnosticCategory.Error, "Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_mod_7035", "Try `npm install @types/{0}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"), Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0: diag(7036, ts.DiagnosticCategory.Error, "Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0_7036", "Dynamic import's specifier must be of type 'string', but here has type '{0}'."), + Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports: diag(7037, ts.DiagnosticCategory.Message, "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037", "Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'."), + A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime: diag(7038, ts.DiagnosticCategory.Error, "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038", "A namespace-style import cannot be called or constructed, and will cause a failure at runtime."), You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."), You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library: diag(8001, ts.DiagnosticCategory.Error, "You_cannot_rename_elements_that_are_defined_in_the_standard_TypeScript_library_8001", "You cannot rename elements that are defined in the standard TypeScript library."), import_can_only_be_used_in_a_ts_file: diag(8002, ts.DiagnosticCategory.Error, "import_can_only_be_used_in_a_ts_file_8002", "'import ... =' can only be used in a .ts file."), @@ -4090,6 +4089,8 @@ var ts; Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"), Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"), Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"), + Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."), + Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."), }; })(ts || (ts = {})); var ts; @@ -4748,7 +4749,7 @@ var ts; return node === parent.type; case 182: case 183: - return parent.typeArguments && ts.indexOf(parent.typeArguments, node) >= 0; + return ts.contains(parent.typeArguments, node); case 184: return false; } @@ -5893,6 +5894,10 @@ var ts; return "__@" + symbolName; } ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName; + function isKnownSymbol(symbol) { + return ts.startsWith(symbol.escapedName, "__@"); + } + ts.isKnownSymbol = isKnownSymbol; function isESSymbolIdentifier(node) { return node.kind === 71 && node.escapedText === "Symbol"; } @@ -8889,6 +8894,21 @@ var ts; return hasInitializer(node) && !ts.isForStatement(node) && !ts.isForInStatement(node) && !ts.isForOfStatement(node) && !ts.isJsxAttribute(node); } ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer; + function isObjectLiteralElement(node) { + switch (node.kind) { + case 257: + case 259: + case 265: + case 266: + case 152: + case 154: + case 155: + return true; + default: + return false; + } + } + ts.isObjectLiteralElement = isObjectLiteralElement; })(ts || (ts = {})); var ts; (function (ts) { @@ -10436,7 +10456,7 @@ var ts; break; } } - tokenValue += text.substr(firstCharPosition, pos - firstCharPosition); + tokenValue += text.substring(firstCharPosition, pos); } return token; } @@ -10458,6 +10478,7 @@ var ts; startPos = pos; tokenPos = pos; var ch = text.charCodeAt(pos); + pos++; switch (ch) { case 9: case 11: @@ -10468,55 +10489,30 @@ var ts; } return token = 5; case 64: - pos++; return token = 57; case 10: case 13: - pos++; return token = 4; case 42: - pos++; return token = 39; case 123: - pos++; return token = 17; case 125: - pos++; return token = 18; case 91: - pos++; return token = 21; case 93: - pos++; return token = 22; case 60: - pos++; return token = 27; - case 62: - pos++; - return token = 29; case 61: - pos++; return token = 58; case 44: - pos++; return token = 26; case 46: - pos++; - if (text.substr(tokenPos, pos + 2) === "...") { - pos += 2; - return token = 24; - } return token = 23; - case 33: - pos++; - return token = 51; - case 63: - pos++; - return token = 55; } if (isIdentifierStart(ch, 6)) { - pos++; while (isIdentifierPart(text.charCodeAt(pos), 6) && pos < end) { pos++; } @@ -10524,7 +10520,7 @@ var ts; return token = 71; } else { - return pos += 1, token = 0; + return token = 0; } } function speculationHelper(callback, isLookahead) { @@ -11661,9 +11657,12 @@ var ts; return token() === 26 || token() === 24 || isIdentifierOrPattern(); case 18: return isIdentifier(); - case 11: case 15: - return token() === 26 || token() === 24 || isStartOfExpression(); + if (token() === 26) { + return true; + } + case 11: + return token() === 24 || isStartOfExpression(); case 16: return isStartOfParameter(); case 19: @@ -11823,6 +11822,9 @@ var ts; if (!canReuseNode(node, parsingContext)) { return undefined; } + if (node.jsDocCache) { + node.jsDocCache = undefined; + } return node; } function consumeNode(node) { @@ -13066,7 +13068,9 @@ var ts; node.questionToken = questionToken; node.whenTrue = doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher); node.colonToken = parseExpectedToken(56, false, ts.Diagnostics._0_expected, ts.tokenToString(56)); - node.whenFalse = parseAssignmentExpressionOrHigher(); + node.whenFalse = ts.nodeIsPresent(node.colonToken) + ? parseAssignmentExpressionOrHigher() + : createMissingNode(71, false, ts.Diagnostics._0_expected, ts.tokenToString(56)); return finishNode(node); } function parseBinaryExpressionOrHigher(precedence) { @@ -15073,17 +15077,17 @@ var ts; comments.push(text); indent += text.length; } - nextJSDocToken(); - while (token() === 5) { - nextJSDocToken(); + var t = nextJSDocToken(); + while (t === 5) { + t = nextJSDocToken(); } - if (token() === 4) { + if (t === 4) { state = 0; indent = 0; - nextJSDocToken(); + t = nextJSDocToken(); } - while (token() !== 1) { - switch (token()) { + loop: while (true) { + switch (t) { case 57: if (state === 0 || state === 1) { removeTrailingNewlines(comments); @@ -15128,17 +15132,18 @@ var ts; indent += whitespace.length; break; case 1: - break; + break loop; default: state = 2; pushComment(scanner.getTokenText()); break; } if (advanceToken) { - nextJSDocToken(); + t = nextJSDocToken(); } else { advanceToken = true; + t = currentToken; } } removeLeadingNewlines(comments); @@ -15236,8 +15241,9 @@ var ts; comments.push(text); indent += text.length; } - while (token() !== 57 && token() !== 1) { - switch (token()) { + var tok = token(); + loop: while (true) { + switch (tok) { case 4: if (state >= 1) { state = 0; @@ -15246,7 +15252,8 @@ var ts; indent = 0; break; case 57: - break; + case 1: + break loop; case 5: if (state === 2) { pushComment(scanner.getTokenText()); @@ -15270,10 +15277,7 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (token() === 57) { - break; - } - nextJSDocToken(); + tok = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); @@ -15510,8 +15514,7 @@ var ts; var canParseTag = true; var seenAsterisk = false; while (true) { - nextJSDocToken(); - switch (token()) { + switch (nextJSDocToken()) { case 57: if (canParseTag) { var child = tryParseChildTag(target); @@ -16057,6 +16060,7 @@ var ts; "es2017.string": "lib.es2017.string.d.ts", "es2017.intl": "lib.es2017.intl.d.ts", "es2017.typedarrays": "lib.es2017.typedarrays.d.ts", + "esnext.array": "lib.esnext.array.d.ts", "esnext.asynciterable": "lib.esnext.asynciterable.d.ts", "esnext.promise": "lib.esnext.promise.d.ts", }), @@ -16304,6 +16308,13 @@ var ts; category: ts.Diagnostics.Module_Resolution_Options, description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking }, + { + name: "esModuleInterop", + type: "boolean", + showInSimplifiedHelpView: true, + category: ts.Diagnostics.Module_Resolution_Options, + description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports + }, { name: "preserveSymlinks", type: "boolean", @@ -16584,7 +16595,8 @@ var ts; ts.defaultInitCompilerOptions = { module: ts.ModuleKind.CommonJS, target: 1, - strict: true + strict: true, + esModuleInterop: true }; var optionNameMapCache; function convertEnableAutoDiscoveryToEnable(typeAcquisition) {