diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts new file mode 100644 index 0000000000000..603ee14effd5b --- /dev/null +++ b/lib/protocol.d.ts @@ -0,0 +1,1700 @@ +/** + * Declaration module describing the TypeScript Server protocol + */ +declare namespace ts.server.protocol { + namespace CommandTypes { + type Brace = "brace"; + type BraceCompletion = "braceCompletion"; + type Change = "change"; + type Close = "close"; + type Completions = "completions"; + type CompletionDetails = "completionEntryDetails"; + type CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; + type CompileOnSaveEmitFile = "compileOnSaveEmitFile"; + type Configure = "configure"; + type Definition = "definition"; + type Exit = "exit"; + type Format = "format"; + type Formatonkey = "formatonkey"; + type Geterr = "geterr"; + type GeterrForProject = "geterrForProject"; + type SemanticDiagnosticsSync = "semanticDiagnosticsSync"; + type SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; + type NavBar = "navbar"; + type Navto = "navto"; + type NavTree = "navtree"; + type NavTreeFull = "navtree-full"; + type Occurrences = "occurrences"; + type DocumentHighlights = "documentHighlights"; + type Open = "open"; + type Quickinfo = "quickinfo"; + type References = "references"; + type Reload = "reload"; + type Rename = "rename"; + type Saveto = "saveto"; + type SignatureHelp = "signatureHelp"; + type TypeDefinition = "typeDefinition"; + type ProjectInfo = "projectInfo"; + type ReloadProjects = "reloadProjects"; + type Unknown = "unknown"; + type OpenExternalProject = "openExternalProject"; + type OpenExternalProjects = "openExternalProjects"; + type CloseExternalProject = "closeExternalProject"; + type TodoComments = "todoComments"; + type Indentation = "indentation"; + type DocCommentTemplate = "docCommentTemplate"; + type CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; + } + /** + * A TypeScript Server message + */ + interface Message { + /** + * Sequence number of the message + */ + seq: number; + /** + * One of "request", "response", or "event" + */ + type: "request" | "response" | "event"; + } + /** + * Client-initiated request message + */ + interface Request extends Message { + /** + * The command to execute + */ + command: string; + /** + * Object containing arguments for the command + */ + arguments?: any; + } + /** + * Request to reload the project structure for all the opened files + */ + interface ReloadProjectsRequest extends Message { + command: CommandTypes.ReloadProjects; + } + /** + * Server-initiated event message + */ + interface Event extends Message { + /** + * Name of event + */ + event: string; + /** + * Event-specific information + */ + body?: any; + } + /** + * Response by server to client request message. + */ + interface Response extends Message { + /** + * Sequence number of the request message. + */ + request_seq: number; + /** + * Outcome of the request. + */ + success: boolean; + /** + * The command requested. + */ + command: string; + /** + * Contains error message if success === false. + */ + message?: string; + /** + * Contains message body if success === true. + */ + body?: any; + } + /** + * Arguments for FileRequest messages. + */ + interface FileRequestArgs { + /** + * The file for the request (absolute pathname required). + */ + file: string; + projectFileName?: string; + } + /** + * Requests a JS Doc comment template for a given position + */ + interface DocCommentTemplateRequest extends FileLocationRequest { + command: CommandTypes.DocCommentTemplate; + } + /** + * Response to DocCommentTemplateRequest + */ + interface DocCommandTemplateResponse extends Response { + body?: TextInsertion; + } + /** + * A request to get TODO comments from the file + */ + interface TodoCommentRequest extends FileRequest { + command: CommandTypes.TodoComments; + arguments: TodoCommentRequestArgs; + } + /** + * Arguments for TodoCommentRequest request. + */ + interface TodoCommentRequestArgs extends FileRequestArgs { + /** + * Array of target TodoCommentDescriptors that describes TODO comments to be found + */ + descriptors: TodoCommentDescriptor[]; + } + /** + * Response for TodoCommentRequest request. + */ + interface TodoCommentsResponse extends Response { + body?: TodoComment[]; + } + /** + * A request to get indentation for a location in file + */ + interface IndentationRequest extends FileLocationRequest { + command: CommandTypes.Indentation; + arguments: IndentationRequestArgs; + } + /** + * Response for IndentationRequest request. + */ + interface IndentationResponse extends Response { + body?: IndentationResult; + } + /** + * Indentation result representing where indentation should be placed + */ + interface IndentationResult { + /** + * The base position in the document that the indent should be relative to + */ + position: number; + /** + * The number of columns the indent should be at relative to the position's column. + */ + indentation: number; + } + /** + * Arguments for IndentationRequest request. + */ + interface IndentationRequestArgs extends FileLocationRequestArgs { + /** + * An optional set of settings to be used when computing indentation. + * If argument is omitted - then it will use settings for file that were previously set via 'configure' request or global settings. + */ + options?: EditorSettings; + } + /** + * Arguments for ProjectInfoRequest request. + */ + interface ProjectInfoRequestArgs extends FileRequestArgs { + /** + * Indicate if the file name list of the project is needed + */ + needFileNameList: boolean; + } + /** + * A request to get the project information of the current file. + */ + interface ProjectInfoRequest extends Request { + command: CommandTypes.ProjectInfo; + arguments: ProjectInfoRequestArgs; + } + /** + * A request to retrieve compiler options diagnostics for a project + */ + interface CompilerOptionsDiagnosticsRequest extends Request { + arguments: CompilerOptionsDiagnosticsRequestArgs; + } + /** + * Arguments for CompilerOptionsDiagnosticsRequest request. + */ + interface CompilerOptionsDiagnosticsRequestArgs { + /** + * Name of the project to retrieve compiler options diagnostics. + */ + projectFileName: string; + } + /** + * Response message body for "projectInfo" request + */ + interface ProjectInfo { + /** + * For configured project, this is the normalized path of the 'tsconfig.json' file + * For inferred project, this is undefined + */ + configFileName: string; + /** + * The list of normalized file name in the project, including 'lib.d.ts' + */ + fileNames?: string[]; + /** + * Indicates if the project has a active language service instance + */ + languageServiceDisabled?: boolean; + } + /** + * Represents diagnostic info that includes location of diagnostic in two forms + * - start position and length of the error span + * - startLocation and endLocation - a pair of Location objects that store start/end line and offset of the error span. + */ + interface DiagnosticWithLinePosition { + message: string; + start: number; + length: number; + startLocation: Location; + endLocation: Location; + category: string; + code: number; + } + /** + * Response message for "projectInfo" request + */ + interface ProjectInfoResponse extends Response { + body?: ProjectInfo; + } + /** + * Request whose sole parameter is a file name. + */ + interface FileRequest extends Request { + arguments: FileRequestArgs; + } + /** + * Instances of this interface specify a location in a source file: + * (file, line, character offset), where line and character offset are 1-based. + */ + interface FileLocationRequestArgs extends FileRequestArgs { + /** + * The line number for the request (1-based). + */ + line: number; + /** + * The character offset (on the line) for the request (1-based). + */ + offset: number; + } + /** + * A request whose arguments specify a file location (file, line, col). + */ + interface FileLocationRequest extends FileRequest { + arguments: FileLocationRequestArgs; + } + /** + * Arguments for EncodedSemanticClassificationsRequest request. + */ + interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { + /** + * Start position of the span. + */ + start: number; + /** + * Length of the span. + */ + length: number; + } + /** + * Arguments in document highlight request; include: filesToSearch, file, + * line, offset. + */ + interface DocumentHighlightsRequestArgs extends FileLocationRequestArgs { + /** + * List of files to search for document highlights. + */ + filesToSearch: string[]; + } + /** + * Go to definition request; value of command field is + * "definition". Return response giving the file locations that + * define the symbol found in file at location line, col. + */ + interface DefinitionRequest extends FileLocationRequest { + command: CommandTypes.Definition; + } + /** + * Go to type request; value of command field is + * "typeDefinition". Return response giving the file locations that + * define the type for the symbol found in file at location line, col. + */ + interface TypeDefinitionRequest extends FileLocationRequest { + command: CommandTypes.TypeDefinition; + } + /** + * Location in source code expressed as (one-based) line and character offset. + */ + interface Location { + line: number; + offset: number; + } + /** + * Object found in response messages defining a span of text in source code. + */ + interface TextSpan { + /** + * First character of the definition. + */ + start: Location; + /** + * One character past last character of the definition. + */ + end: Location; + } + /** + * Object found in response messages defining a span of text in a specific source file. + */ + interface FileSpan extends TextSpan { + /** + * File containing text span. + */ + file: string; + } + /** + * Definition response message. Gives text range for definition. + */ + interface DefinitionResponse extends Response { + body?: FileSpan[]; + } + /** + * Definition response message. Gives text range for definition. + */ + interface TypeDefinitionResponse extends Response { + body?: FileSpan[]; + } + /** + * Implementation response message. Gives text range for implementations. + */ + interface ImplementationResponse extends Response { + body?: FileSpan[]; + } + /** + * Request to get brace completion for a location in the file. + */ + interface BraceCompletionRequest extends FileLocationRequest { + command: CommandTypes.BraceCompletion; + arguments: BraceCompletionRequestArgs; + } + /** + * Argument for BraceCompletionRequest request. + */ + interface BraceCompletionRequestArgs extends FileLocationRequestArgs { + /** + * Kind of opening brace + */ + openingBrace: string; + } + /** + * Get occurrences request; value of command field is + * "occurrences". Return response giving spans that are relevant + * in the file at a given line and column. + */ + interface OccurrencesRequest extends FileLocationRequest { + command: CommandTypes.Occurrences; + } + interface OccurrencesResponseItem extends FileSpan { + /** + * True if the occurrence is a write location, false otherwise. + */ + isWriteAccess: boolean; + } + interface OccurrencesResponse extends Response { + body?: OccurrencesResponseItem[]; + } + /** + * Get document highlights request; value of command field is + * "documentHighlights". Return response giving spans that are relevant + * in the file at a given line and column. + */ + interface DocumentHighlightsRequest extends FileLocationRequest { + command: CommandTypes.DocumentHighlights; + arguments: DocumentHighlightsRequestArgs; + } + /** + * Span augmented with extra information that denotes the kind of the highlighting to be used for span. + * Kind is taken from HighlightSpanKind type. + */ + interface HighlightSpan extends TextSpan { + kind: string; + } + /** + * Represents a set of highligh spans for a give name + */ + interface DocumentHighlightsItem { + /** + * File containing highlight spans. + */ + file: string; + /** + * Spans to highlight in file. + */ + highlightSpans: HighlightSpan[]; + } + /** + * Response for a DocumentHighlightsRequest request. + */ + interface DocumentHighlightsResponse extends Response { + body?: DocumentHighlightsItem[]; + } + /** + * Find references request; value of command field is + * "references". Return response giving the file locations that + * reference the symbol found in file at location line, col. + */ + interface ReferencesRequest extends FileLocationRequest { + command: CommandTypes.References; + } + interface ReferencesResponseItem extends FileSpan { + /** Text of line containing the reference. Including this + * with the response avoids latency of editor loading files + * to show text of reference line (the server already has + * loaded the referencing files). + */ + lineText: string; + /** + * True if reference is a write location, false otherwise. + */ + isWriteAccess: boolean; + /** + * True if reference is a definition, false otherwise. + */ + isDefinition: boolean; + } + /** + * The body of a "references" response message. + */ + interface ReferencesResponseBody { + /** + * The file locations referencing the symbol. + */ + refs: ReferencesResponseItem[]; + /** + * The name of the symbol. + */ + symbolName: string; + /** + * The start character offset of the symbol (on the line provided by the references request). + */ + symbolStartOffset: number; + /** + * The full display name of the symbol. + */ + symbolDisplayString: string; + } + /** + * Response to "references" request. + */ + interface ReferencesResponse extends Response { + body?: ReferencesResponseBody; + } + /** + * Argument for RenameRequest request. + */ + interface RenameRequestArgs extends FileLocationRequestArgs { + /** + * Should text at specified location be found/changed in comments? + */ + findInComments?: boolean; + /** + * Should text at specified location be found/changed in strings? + */ + findInStrings?: boolean; + } + /** + * Rename request; value of command field is "rename". Return + * response giving the file locations that reference the symbol + * found in file at location line, col. Also return full display + * name of the symbol so that client can print it unambiguously. + */ + interface RenameRequest extends FileLocationRequest { + command: CommandTypes.Rename; + arguments: RenameRequestArgs; + } + /** + * Information about the item to be renamed. + */ + interface RenameInfo { + /** + * True if item can be renamed. + */ + canRename: boolean; + /** + * Error message if item can not be renamed. + */ + localizedErrorMessage?: string; + /** + * Display name of the item to be renamed. + */ + displayName: string; + /** + * Full display name of item to be renamed. + */ + fullDisplayName: string; + /** + * The items's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + } + /** + * A group of text spans, all in 'file'. + */ + interface SpanGroup { + /** The file to which the spans apply */ + file: string; + /** The text spans in this group */ + locs: TextSpan[]; + } + interface RenameResponseBody { + /** + * Information about the item to be renamed. + */ + info: RenameInfo; + /** + * An array of span groups (one per file) that refer to the item to be renamed. + */ + locs: SpanGroup[]; + } + /** + * Rename response message. + */ + interface RenameResponse extends Response { + body?: RenameResponseBody; + } + /** + * Represents a file in external project. + * External project is project whose set of files, compilation options and open\close state + * is maintained by the client (i.e. if all this data come from .csproj file in Visual Studio). + * External project will exist even if all files in it are closed and should be closed explicity. + * If external project includes one or more tsconfig.json/jsconfig.json files then tsserver will + * create configured project for every config file but will maintain a link that these projects were created + * as a result of opening external project so they should be removed once external project is closed. + */ + interface ExternalFile { + /** + * Name of file file + */ + fileName: string; + /** + * Script kind of the file + */ + scriptKind?: ScriptKindName | ts.ScriptKind; + /** + * Whether file has mixed content (i.e. .cshtml file that combines html markup with C#/JavaScript) + */ + hasMixedContent?: boolean; + /** + * Content of the file + */ + content?: string; + } + /** + * Represent an external project + */ + interface ExternalProject { + /** + * Project name + */ + projectFileName: string; + /** + * List of root files in project + */ + rootFiles: ExternalFile[]; + /** + * Compiler options for the project + */ + options: ExternalProjectCompilerOptions; + /** + * Explicitly specified typing options for the project + */ + typingOptions?: TypingOptions; + } + interface CompileOnSaveMixin { + /** + * If compile on save is enabled for the project + */ + compileOnSave?: boolean; + } + /** + * For external projects, some of the project settings are sent together with + * compiler settings. + */ + type ExternalProjectCompilerOptions = CompilerOptions & CompileOnSaveMixin; + /** + * Represents a set of changes that happen in project + */ + interface ProjectChanges { + /** + * List of added files + */ + added: string[]; + /** + * List of removed files + */ + removed: string[]; + } + /** + * Information found in a configure request. + */ + interface ConfigureRequestArguments { + /** + * Information about the host, for example 'Emacs 24.4' or + * 'Sublime Text version 3075' + */ + hostInfo?: string; + /** + * If present, tab settings apply only to this file. + */ + file?: string; + /** + * The format options to use during formatting and other code editing features. + */ + formatOptions?: FormatCodeSettings; + } + /** + * Configure request; value of command field is "configure". Specifies + * host information, such as host type, tab size, and indent size. + */ + interface ConfigureRequest extends Request { + command: CommandTypes.Configure; + arguments: ConfigureRequestArguments; + } + /** + * Response to "configure" request. This is just an acknowledgement, so + * no body field is required. + */ + interface ConfigureResponse extends Response { + } + /** + * Information found in an "open" request. + */ + interface OpenRequestArgs extends FileRequestArgs { + /** + * Used when a version of the file content is known to be more up to date than the one on disk. + * Then the known content will be used upon opening instead of the disk copy + */ + fileContent?: string; + /** + * Used to specify the script kind of the file explicitly. It could be one of the following: + * "TS", "JS", "TSX", "JSX" + */ + scriptKindName?: ScriptKindName; + } + type ScriptKindName = "TS" | "JS" | "TSX" | "JSX"; + /** + * Open request; value of command field is "open". Notify the + * server that the client has file open. The server will not + * monitor the filesystem for changes in this file and will assume + * that the client is updating the server (using the change and/or + * reload messages) when the file changes. Server does not currently + * send a response to an open request. + */ + interface OpenRequest extends Request { + command: CommandTypes.Open; + arguments: OpenRequestArgs; + } + /** + * Request to open or update external project + */ + interface OpenExternalProjectRequest extends Request { + command: CommandTypes.OpenExternalProject; + arguments: OpenExternalProjectArgs; + } + /** + * Arguments to OpenExternalProjectRequest request + */ + type OpenExternalProjectArgs = ExternalProject; + /** + * Request to open multiple external projects + */ + interface OpenExternalProjectsRequest extends Request { + command: CommandTypes.OpenExternalProjects; + arguments: OpenExternalProjectsArgs; + } + /** + * Arguments to OpenExternalProjectsRequest + */ + interface OpenExternalProjectsArgs { + /** + * List of external projects to open or update + */ + projects: ExternalProject[]; + } + /** + * Response to OpenExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface OpenExternalProjectResponse extends Response { + } + /** + * Response to OpenExternalProjectsRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface OpenExternalProjectsResponse extends Response { + } + /** + * Request to close external project. + */ + interface CloseExternalProjectRequest extends Request { + command: CommandTypes.CloseExternalProject; + arguments: CloseExternalProjectRequestArgs; + } + /** + * Arguments to CloseExternalProjectRequest request + */ + interface CloseExternalProjectRequestArgs { + /** + * Name of the project to close + */ + projectFileName: string; + } + /** + * Response to CloseExternalProjectRequest request. This is just an acknowledgement, so + * no body field is required. + */ + interface CloseExternalProjectResponse extends Response { + } + /** + * Request to set compiler options for inferred projects. + * External projects are opened / closed explicitly. + * Configured projects are opened when user opens loose file that has 'tsconfig.json' or 'jsconfig.json' anywhere in one of containing folders. + * This configuration file will be used to obtain a list of files and configuration settings for the project. + * Inferred projects are created when user opens a loose file that is not the part of external project + * or configured project and will contain only open file and transitive closure of referenced files if 'useOneInferredProject' is false, + * or all open loose files and its transitive closure of referenced files if 'useOneInferredProject' is true. + */ + interface SetCompilerOptionsForInferredProjectsRequest extends Request { + command: CommandTypes.CompilerOptionsForInferredProjects; + arguments: SetCompilerOptionsForInferredProjectsArgs; + } + /** + * Argument for SetCompilerOptionsForInferredProjectsRequest request. + */ + interface SetCompilerOptionsForInferredProjectsArgs { + /** + * Compiler options to be used with inferred projects. + */ + options: ExternalProjectCompilerOptions; + } + /** + * Response to SetCompilerOptionsForInferredProjectsResponse request. This is just an acknowledgement, so + * no body field is required. + */ + interface SetCompilerOptionsForInferredProjectsResponse extends Response { + } + /** + * Exit request; value of command field is "exit". Ask the server process + * to exit. + */ + interface ExitRequest extends Request { + command: CommandTypes.Exit; + } + /** + * Close request; value of command field is "close". Notify the + * server that the client has closed a previously open file. If + * file is still referenced by open files, the server will resume + * monitoring the filesystem for changes to file. Server does not + * currently send a response to a close request. + */ + interface CloseRequest extends FileRequest { + command: CommandTypes.Close; + } + /** + * Request to obtain the list of files that should be regenerated if target file is recompiled. + * NOTE: this us query-only operation and does not generate any output on disk. + */ + interface CompileOnSaveAffectedFileListRequest extends FileRequest { + command: CommandTypes.CompileOnSaveAffectedFileList; + } + /** + * Contains a list of files that should be regenerated in a project + */ + interface CompileOnSaveAffectedFileListSingleProject { + /** + * Project name + */ + projectFileName: string; + /** + * List of files names that should be recompiled + */ + fileNames: string[]; + } + /** + * Response for CompileOnSaveAffectedFileListRequest request; + */ + interface CompileOnSaveAffectedFileListResponse extends Response { + body: CompileOnSaveAffectedFileListSingleProject[]; + } + /** + * Request to recompile the file. All generated outputs (.js, .d.ts or .js.map files) is written on disk. + */ + interface CompileOnSaveEmitFileRequest extends FileRequest { + command: CommandTypes.CompileOnSaveEmitFile; + arguments: CompileOnSaveEmitFileRequestArgs; + } + /** + * Arguments for CompileOnSaveEmitFileRequest + */ + interface CompileOnSaveEmitFileRequestArgs extends FileRequestArgs { + /** + * if true - then file should be recompiled even if it does not have any changes. + */ + forced?: boolean; + } + /** + * Quickinfo request; value of command field is + * "quickinfo". Return response giving a quick type and + * documentation string for the symbol found in file at location + * line, col. + */ + interface QuickInfoRequest extends FileLocationRequest { + command: CommandTypes.Quickinfo; + } + /** + * Body of QuickInfoResponse. + */ + interface QuickInfoResponseBody { + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * Starting file location of symbol. + */ + start: Location; + /** + * One past last character of symbol. + */ + end: Location; + /** + * Type and kind of symbol. + */ + displayString: string; + /** + * Documentation associated with symbol. + */ + documentation: string; + } + /** + * Quickinfo response message. + */ + interface QuickInfoResponse extends Response { + body?: QuickInfoResponseBody; + } + /** + * Arguments for format messages. + */ + interface FormatRequestArgs extends FileLocationRequestArgs { + /** + * Last line of range for which to format text in file. + */ + endLine: number; + /** + * Character offset on last line of range for which to format text in file. + */ + endOffset: number; + /** + * Format options to be used. + */ + options?: FormatCodeSettings; + } + /** + * Format request; value of command field is "format". Return + * response giving zero or more edit instructions. The edit + * instructions will be sorted in file order. Applying the edit + * instructions in reverse to file will result in correctly + * reformatted text. + */ + interface FormatRequest extends FileLocationRequest { + command: CommandTypes.Format; + arguments: FormatRequestArgs; + } + /** + * Object found in response messages defining an editing + * instruction for a span of text in source code. The effect of + * this instruction is to replace the text starting at start and + * ending one character before end with newText. For an insertion, + * the text span is empty. For a deletion, newText is empty. + */ + interface CodeEdit { + /** + * First character of the text span to edit. + */ + start: Location; + /** + * One character past last character of the text span to edit. + */ + end: Location; + /** + * Replace the span defined above with this string (may be + * the empty string). + */ + newText: string; + } + /** + * Format and format on key response message. + */ + interface FormatResponse extends Response { + body?: CodeEdit[]; + } + /** + * Arguments for format on key messages. + */ + interface FormatOnKeyRequestArgs extends FileLocationRequestArgs { + /** + * Key pressed (';', '\n', or '}'). + */ + key: string; + options?: FormatCodeSettings; + } + /** + * Format on key request; value of command field is + * "formatonkey". Given file location and key typed (as string), + * return response giving zero or more edit instructions. The + * edit instructions will be sorted in file order. Applying the + * edit instructions in reverse to file will result in correctly + * reformatted text. + */ + interface FormatOnKeyRequest extends FileLocationRequest { + command: CommandTypes.Formatonkey; + arguments: FormatOnKeyRequestArgs; + } + /** + * Arguments for completions messages. + */ + interface CompletionsRequestArgs extends FileLocationRequestArgs { + /** + * Optional prefix to apply to possible completions. + */ + prefix?: string; + } + /** + * Completions request; value of command field is "completions". + * Given a file location (file, line, col) and a prefix (which may + * be the empty string), return the possible completions that + * begin with prefix. + */ + interface CompletionsRequest extends FileLocationRequest { + command: CommandTypes.Completions; + arguments: CompletionsRequestArgs; + } + /** + * Arguments for completion details request. + */ + interface CompletionDetailsRequestArgs extends FileLocationRequestArgs { + /** + * Names of one or more entries for which to obtain details. + */ + entryNames: string[]; + } + /** + * Completion entry details request; value of command field is + * "completionEntryDetails". Given a file location (file, line, + * col) and an array of completion entry names return more + * detailed information for each completion entry. + */ + interface CompletionDetailsRequest extends FileLocationRequest { + command: CommandTypes.CompletionDetails; + arguments: CompletionDetailsRequestArgs; + } + /** + * Part of a symbol description. + */ + interface SymbolDisplayPart { + /** + * Text of an item describing the symbol. + */ + text: string; + /** + * The symbol's kind (such as 'className' or 'parameterName' or plain 'text'). + */ + kind: string; + } + /** + * An item found in a completion response. + */ + interface CompletionEntry { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * A string that is used for comparing completion items so that they can be ordered. This + * is often the same as the name but may be different in certain circumstances. + */ + sortText: string; + /** + * An optional span that indicates the text to be replaced by this completion item. If present, + * this span should be used instead of the default one. + */ + replacementSpan?: TextSpan; + } + /** + * Additional completion entry details, available on demand + */ + interface CompletionEntryDetails { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers: string; + /** + * Display parts of the symbol (similar to quick info). + */ + displayParts: SymbolDisplayPart[]; + /** + * Documentation strings for the symbol. + */ + documentation: SymbolDisplayPart[]; + } + interface CompletionsResponse extends Response { + body?: CompletionEntry[]; + } + interface CompletionDetailsResponse extends Response { + body?: CompletionEntryDetails[]; + } + /** + * Signature help information for a single parameter + */ + interface SignatureHelpParameter { + /** + * The parameter's name + */ + name: string; + /** + * Documentation of the parameter. + */ + documentation: SymbolDisplayPart[]; + /** + * Display parts of the parameter. + */ + displayParts: SymbolDisplayPart[]; + /** + * Whether the parameter is optional or not. + */ + isOptional: boolean; + } + /** + * Represents a single signature to show in signature help. + */ + interface SignatureHelpItem { + /** + * Whether the signature accepts a variable number of arguments. + */ + isVariadic: boolean; + /** + * The prefix display parts. + */ + prefixDisplayParts: SymbolDisplayPart[]; + /** + * The suffix display parts. + */ + suffixDisplayParts: SymbolDisplayPart[]; + /** + * The separator display parts. + */ + separatorDisplayParts: SymbolDisplayPart[]; + /** + * The signature helps items for the parameters. + */ + parameters: SignatureHelpParameter[]; + /** + * The signature's documentation + */ + documentation: SymbolDisplayPart[]; + } + /** + * Signature help items found in the response of a signature help request. + */ + interface SignatureHelpItems { + /** + * The signature help items. + */ + items: SignatureHelpItem[]; + /** + * The span for which signature help should appear on a signature + */ + applicableSpan: TextSpan; + /** + * The item selected in the set of available help items. + */ + selectedItemIndex: number; + /** + * The argument selected in the set of parameters. + */ + argumentIndex: number; + /** + * The argument count + */ + argumentCount: number; + } + /** + * Arguments of a signature help request. + */ + interface SignatureHelpRequestArgs extends FileLocationRequestArgs { + } + /** + * Signature help request; value of command field is "signatureHelp". + * Given a file location (file, line, col), return the signature + * help. + */ + interface SignatureHelpRequest extends FileLocationRequest { + command: CommandTypes.SignatureHelp; + arguments: SignatureHelpRequestArgs; + } + /** + * Response object for a SignatureHelpRequest. + */ + interface SignatureHelpResponse extends Response { + body?: SignatureHelpItems; + } + /** + * Synchronous request for semantic diagnostics of one file. + */ + interface SemanticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SemanticDiagnosticsSync; + arguments: SemanticDiagnosticsSyncRequestArgs; + } + interface SemanticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + /** + * Response object for synchronous sematic diagnostics request. + */ + interface SemanticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + /** + * Synchronous request for syntactic diagnostics of one file. + */ + interface SyntacticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SyntacticDiagnosticsSync; + arguments: SyntacticDiagnosticsSyncRequestArgs; + } + interface SyntacticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + /** + * Response object for synchronous syntactic diagnostics request. + */ + interface SyntacticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + /** + * Arguments for GeterrForProject request. + */ + interface GeterrForProjectRequestArgs { + /** + * the file requesting project error list + */ + file: string; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ + delay: number; + } + /** + * GeterrForProjectRequest request; value of command field is + * "geterrForProject". It works similarly with 'Geterr', only + * it request for every file in this project. + */ + interface GeterrForProjectRequest extends Request { + command: CommandTypes.GeterrForProject; + arguments: GeterrForProjectRequestArgs; + } + /** + * Arguments for geterr messages. + */ + interface GeterrRequestArgs { + /** + * List of file names for which to compute compiler errors. + * The files will be checked in list order. + */ + files: string[]; + /** + * Delay in milliseconds to wait before starting to compute + * errors for the files in the file list + */ + delay: number; + } + /** + * Geterr request; value of command field is "geterr". Wait for + * delay milliseconds and then, if during the wait no change or + * reload messages have arrived for the first file in the files + * list, get the syntactic errors for the file, field requests, + * and then get the semantic errors for the file. Repeat with a + * smaller delay for each subsequent file on the files list. Best + * practice for an editor is to send a file list containing each + * file that is currently visible, in most-recently-used order. + */ + interface GeterrRequest extends Request { + command: CommandTypes.Geterr; + arguments: GeterrRequestArgs; + } + /** + * Item of diagnostic information found in a DiagnosticEvent message. + */ + interface Diagnostic { + /** + * Starting file location at which text applies. + */ + start: Location; + /** + * The last file location at which the text applies. + */ + end: Location; + /** + * Text of diagnostic message. + */ + text: string; + } + interface DiagnosticEventBody { + /** + * The file for which diagnostic information is reported. + */ + file: string; + /** + * An array of diagnostic information items. + */ + diagnostics: Diagnostic[]; + } + /** + * Event message for "syntaxDiag" and "semanticDiag" event types. + * These events provide syntactic and semantic errors for a file. + */ + interface DiagnosticEvent extends Event { + body?: DiagnosticEventBody; + } + interface ConfigFileDiagnosticEventBody { + /** + * The file which trigged the searching and error-checking of the config file + */ + triggerFile: string; + /** + * The name of the found config file. + */ + configFile: string; + /** + * An arry of diagnostic information items for the found config file. + */ + diagnostics: Diagnostic[]; + } + /** + * Event message for "configFileDiag" event type. + * This event provides errors for a found config file. + */ + interface ConfigFileDiagnosticEvent extends Event { + body?: ConfigFileDiagnosticEventBody; + event: "configFileDiag"; + } + /** + * Arguments for reload request. + */ + interface ReloadRequestArgs extends FileRequestArgs { + /** + * Name of temporary file from which to reload file + * contents. May be same as file. + */ + tmpfile: string; + } + /** + * Reload request message; value of command field is "reload". + * Reload contents of file with name given by the 'file' argument + * from temporary file with name given by the 'tmpfile' argument. + * The two names can be identical. + */ + interface ReloadRequest extends FileRequest { + command: CommandTypes.Reload; + arguments: ReloadRequestArgs; + } + /** + * Response to "reload" request. This is just an acknowledgement, so + * no body field is required. + */ + interface ReloadResponse extends Response { + } + /** + * Arguments for saveto request. + */ + interface SavetoRequestArgs extends FileRequestArgs { + /** + * Name of temporary file into which to save server's view of + * file contents. + */ + tmpfile: string; + } + /** + * Saveto request message; value of command field is "saveto". + * For debugging purposes, save to a temporaryfile (named by + * argument 'tmpfile') the contents of file named by argument + * 'file'. The server does not currently send a response to a + * "saveto" request. + */ + interface SavetoRequest extends FileRequest { + command: CommandTypes.Saveto; + arguments: SavetoRequestArgs; + } + /** + * Arguments for navto request message. + */ + interface NavtoRequestArgs extends FileRequestArgs { + /** + * Search term to navigate to from current location; term can + * be '.*' or an identifier prefix. + */ + searchValue: string; + /** + * Optional limit on the number of items to return. + */ + maxResultCount?: number; + projectFileName?: string; + } + /** + * Navto request message; value of command field is "navto". + * Return list of objects giving file locations and symbols that + * match the search term given in argument 'searchTerm'. The + * context for the search is given by the named file. + */ + interface NavtoRequest extends FileRequest { + command: CommandTypes.Navto; + arguments: NavtoRequestArgs; + } + /** + * An item found in a navto response. + */ + interface NavtoItem { + /** + * The symbol's name. + */ + name: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: string; + /** + * exact, substring, or prefix. + */ + matchKind?: string; + /** + * If this was a case sensitive or insensitive match. + */ + isCaseSensitive?: boolean; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + /** + * The file in which the symbol is found. + */ + file: string; + /** + * The location within file at which the symbol is found. + */ + start: Location; + /** + * One past the last character of the symbol. + */ + end: Location; + /** + * Name of symbol's container symbol (if any); for example, + * the class name if symbol is a class member. + */ + containerName?: string; + /** + * Kind of symbol's container symbol (if any). + */ + containerKind?: string; + } + /** + * Navto response message. Body is an array of navto items. Each + * item gives a symbol that matched the search term. + */ + interface NavtoResponse extends Response { + body?: NavtoItem[]; + } + /** + * Arguments for change request message. + */ + interface ChangeRequestArgs extends FormatRequestArgs { + /** + * Optional string to insert at location (file, line, offset). + */ + insertString?: string; + } + /** + * Change request message; value of command field is "change". + * Update the server's view of the file named by argument 'file'. + * Server does not currently send a response to a change request. + */ + interface ChangeRequest extends FileLocationRequest { + command: CommandTypes.Change; + arguments: ChangeRequestArgs; + } + /** + * Response to "brace" request. + */ + interface BraceResponse extends Response { + body?: TextSpan[]; + } + /** + * Brace matching request; value of command field is "brace". + * Return response giving the file locations of matching braces + * found in file at location line, offset. + */ + interface BraceRequest extends FileLocationRequest { + command: CommandTypes.Brace; + } + /** + * NavBar items request; value of command field is "navbar". + * Return response giving the list of navigation bar entries + * extracted from the requested file. + */ + interface NavBarRequest extends FileRequest { + command: CommandTypes.NavBar; + } + /** + * NavTree request; value of command field is "navtree". + * Return response giving the navigation tree of the requested file. + */ + interface NavTreeRequest extends FileRequest { + command: CommandTypes.NavTree; + } + interface NavigationBarItem { + /** + * The item's display text. + */ + text: string; + /** + * The symbol's kind (such as 'className' or 'parameterName'). + */ + kind: string; + /** + * Optional modifiers for the kind (such as 'public'). + */ + kindModifiers?: string; + /** + * The definition locations of the item. + */ + spans: TextSpan[]; + /** + * Optional children. + */ + childItems?: NavigationBarItem[]; + /** + * Number of levels deep this item should appear. + */ + indent: number; + } + /** protocol.NavigationTree is identical to ts.NavigationTree, except using protocol.TextSpan instead of ts.TextSpan */ + interface NavigationTree { + text: string; + kind: string; + kindModifiers: string; + spans: TextSpan[]; + childItems?: NavigationTree[]; + } + interface NavBarResponse extends Response { + body?: NavigationBarItem[]; + } + interface NavTreeResponse extends Response { + body?: NavigationTree; + } + namespace IndentStyle { + type None = "None"; + type Block = "Block"; + type Smart = "Smart"; + } + type IndentStyle = IndentStyle.None | IndentStyle.Block | IndentStyle.Smart; + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle | ts.IndentStyle; + } + interface FormatCodeSettings extends EditorSettings { + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; + } + interface CompilerOptions { + allowJs?: boolean; + allowSyntheticDefaultImports?: boolean; + allowUnreachableCode?: boolean; + allowUnusedLabels?: boolean; + baseUrl?: string; + charset?: string; + declaration?: boolean; + declarationDir?: string; + disableSizeLimit?: boolean; + emitBOM?: boolean; + emitDecoratorMetadata?: boolean; + experimentalDecorators?: boolean; + forceConsistentCasingInFileNames?: boolean; + inlineSourceMap?: boolean; + inlineSources?: boolean; + isolatedModules?: boolean; + jsx?: JsxEmit | ts.JsxEmit; + lib?: string[]; + locale?: string; + mapRoot?: string; + maxNodeModuleJsDepth?: number; + module?: ModuleKind | ts.ModuleKind; + moduleResolution?: ModuleResolutionKind | ts.ModuleResolutionKind; + newLine?: NewLineKind | ts.NewLineKind; + noEmit?: boolean; + noEmitHelpers?: boolean; + noEmitOnError?: boolean; + noErrorTruncation?: boolean; + noFallthroughCasesInSwitch?: boolean; + noImplicitAny?: boolean; + noImplicitReturns?: boolean; + noImplicitThis?: boolean; + noUnusedLocals?: boolean; + noUnusedParameters?: boolean; + noImplicitUseStrict?: boolean; + noLib?: boolean; + noResolve?: boolean; + out?: string; + outDir?: string; + outFile?: string; + paths?: MapLike; + preserveConstEnums?: boolean; + project?: string; + reactNamespace?: string; + removeComments?: boolean; + rootDir?: string; + rootDirs?: string[]; + skipLibCheck?: boolean; + skipDefaultLibCheck?: boolean; + sourceMap?: boolean; + sourceRoot?: string; + strictNullChecks?: boolean; + suppressExcessPropertyErrors?: boolean; + suppressImplicitAnyIndexErrors?: boolean; + target?: ScriptTarget | ts.ScriptTarget; + traceResolution?: boolean; + types?: string[]; + /** Paths used to used to compute primary types search locations */ + typeRoots?: string[]; + [option: string]: CompilerOptionsValue | undefined; + } + namespace JsxEmit { + type None = "None"; + type Preserve = "Preserve"; + type React = "React"; + } + type JsxEmit = JsxEmit.None | JsxEmit.Preserve | JsxEmit.React; + namespace ModuleKind { + type None = "None"; + type CommonJS = "CommonJS"; + type AMD = "AMD"; + type UMD = "UMD"; + type System = "System"; + type ES6 = "ES6"; + type ES2015 = "ES2015"; + } + type ModuleKind = ModuleKind.None | ModuleKind.CommonJS | ModuleKind.AMD | ModuleKind.UMD | ModuleKind.System | ModuleKind.ES6 | ModuleKind.ES2015; + namespace ModuleResolutionKind { + type Classic = "Classic"; + type Node = "Node"; + } + type ModuleResolutionKind = ModuleResolutionKind.Classic | ModuleResolutionKind.Node; + namespace NewLineKind { + type Crlf = "Crlf"; + type Lf = "Lf"; + } + type NewLineKind = NewLineKind.Crlf | NewLineKind.Lf; + namespace ScriptTarget { + type ES3 = "ES3"; + type ES5 = "ES5"; + type ES6 = "ES6"; + type ES2015 = "ES2015"; + } + type ScriptTarget = ScriptTarget.ES3 | ScriptTarget.ES5 | ScriptTarget.ES6 | ScriptTarget.ES2015; +} +declare namespace ts.server.protocol { + + interface TextInsertion { + newText: string; + /** The position in newText the caret should point to after the insertion. */ + caretOffset: number; + } + + interface TodoCommentDescriptor { + text: string; + priority: number; + } + + interface TodoComment { + descriptor: TodoCommentDescriptor; + message: string; + position: number; + } + + interface TypingOptions { + enableAutoDiscovery?: boolean; + include?: string[]; + exclude?: string[]; + [option: string]: string[] | boolean | undefined; + } + + interface MapLike { + [index: string]: T; + } + + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike; +} +declare namespace ts { + // these types are empty stubs for types from services and should not be used directly + export type ScriptKind = never; + export type IndentStyle = never; + export type JsxEmit = never; + export type ModuleKind = never; + export type ModuleResolutionKind = never; + export type NewLineKind = never; + export type ScriptTarget = never; +} +import protocol = ts.server.protocol; +export = protocol; +export as namespace protocol; \ No newline at end of file diff --git a/lib/tsc.js b/lib/tsc.js index 2bf31e4d4aa44..9d72acfbf0fe3 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -125,6 +125,7 @@ var ts; var ts; (function (ts) { var createObject = Object.create; + ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; function createMap(template) { var map = createObject(null); map["__"] = undefined; @@ -682,7 +683,7 @@ var ts; if (b === undefined) return 1; if (ignoreCase) { - if (String.prototype.localeCompare) { + if (ts.collator && String.prototype.localeCompare) { var result = a.localeCompare(b, undefined, { usage: "sort", sensitivity: "accent" }); return result < 0 ? -1 : result > 0 ? 1 : 0; } @@ -1710,6 +1711,9 @@ var ts; }, watchDirectory: function (directoryName, callback, recursive) { var options; + if (!directoryExists(directoryName)) { + return; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -14986,14 +14990,14 @@ var ts; } return false; } - function isSymbolAccessible(symbol, enclosingDeclaration, meaning) { + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { if (symbol && enclosingDeclaration && !(symbol.flags & 262144)) { var initialSymbol = symbol; var meaningToLook = meaning; while (symbol) { var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, false); if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0]); + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); if (!hasAccessibleDeclarations) { return { accessibility: 1, @@ -15034,7 +15038,7 @@ var ts; function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 256 && ts.isExternalOrCommonJsModule(declaration)); } - function hasVisibleDeclarations(symbol) { + function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { return undefined; @@ -15046,14 +15050,16 @@ var ts; if (anyImportSyntax && !(anyImportSyntax.flags & 1) && isDeclarationVisible(anyImportSyntax.parent)) { - getNodeLinks(declaration).isVisible = true; - if (aliasesToMakeVisible) { - if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { - aliasesToMakeVisible.push(anyImportSyntax); + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + if (aliasesToMakeVisible) { + if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { + aliasesToMakeVisible.push(anyImportSyntax); + } + } + else { + aliasesToMakeVisible = [anyImportSyntax]; } - } - else { - aliasesToMakeVisible = [anyImportSyntax]; } return true; } @@ -15076,7 +15082,7 @@ var ts; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.text, meaning, undefined, undefined); - return (symbol && hasVisibleDeclarations(symbol)) || { + return (symbol && hasVisibleDeclarations(symbol, true)) || { accessibility: 1, errorSymbolName: ts.getTextOfNode(firstIdentifier), errorNode: firstIdentifier @@ -15293,14 +15299,10 @@ var ts; else if (type.flags & (32768 | 65536 | 16 | 16384)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } - else if (!(flags & 512) && type.flags & (2097152 | 1572864) && type.aliasSymbol) { - if (type.flags & 2097152 || !(flags & 1024)) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); - } - else { - writeUnionOrIntersectionType(type, nextFlags); - } + else if (!(flags & 512) && ((type.flags & 2097152 && !type.target) || type.flags & 1572864) && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { + var typeArguments = type.aliasTypeArguments; + writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); } else if (type.flags & 1572864) { writeUnionOrIntersectionType(type, nextFlags); @@ -29589,7 +29591,7 @@ var ts; } } function trackSymbol(symbol, enclosingDeclaration, meaning) { - handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning)); + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportInaccessibleThisError() { @@ -29606,7 +29608,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 | 1024, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2, writer); errorNameNode = undefined; } } @@ -29618,7 +29620,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 | 1024, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2, writer); errorNameNode = undefined; } } @@ -29811,7 +29813,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -30216,7 +30218,7 @@ var ts; } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2, writer); } function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; @@ -32295,14 +32297,14 @@ var ts; write(" = "); emitObjectLiteralBody(node, firstComputedPropertyIndex); for (var i = firstComputedPropertyIndex, n = properties.length; i < n; i++) { - writeComma(); var property = properties[i]; - emitStart(property); if (property.kind === 149 || property.kind === 150) { var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property !== accessors.firstAccessor) { continue; } + writeComma(); + emitStart(property); write("Object.defineProperty("); emit(tempVar); write(", "); @@ -32343,6 +32345,8 @@ var ts; emitEnd(property); } else { + writeComma(); + emitStart(property); emitLeadingComments(property); emitStart(property.name); emit(tempVar); @@ -32361,8 +32365,8 @@ var ts; else { ts.Debug.fail("ObjectLiteralElement type not accounted for: " + property.kind); } + emitEnd(property); } - emitEnd(property); } writeComma(); emit(tempVar); @@ -32806,7 +32810,11 @@ var ts; if (modulekind === ts.ModuleKind.System || node.kind !== 69 || ts.nodeIsSynthesized(node)) { return false; } - return !exportEquals && exportSpecifiers && node.text in exportSpecifiers; + if (exportEquals || !exportSpecifiers || !(node.text in exportSpecifiers)) { + return false; + } + var declaration = resolver.getReferencedValueDeclaration(node); + return declaration && ts.getEnclosingBlockScopeContainer(declaration).kind === 256; } function emitPrefixUnaryExpression(node) { var isPlusPlusOrMinusMinus = (node.operator === 41 diff --git a/lib/tsserver.js b/lib/tsserver.js index 1b330902d1ed8..63f1b11a67b14 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -130,6 +130,7 @@ var ts; var ts; (function (ts) { var createObject = Object.create; + ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; function createMap(template) { var map = createObject(null); map["__"] = undefined; @@ -687,7 +688,7 @@ var ts; if (b === undefined) return 1; if (ignoreCase) { - if (String.prototype.localeCompare) { + if (ts.collator && String.prototype.localeCompare) { var result = a.localeCompare(b, undefined, { usage: "sort", sensitivity: "accent" }); return result < 0 ? -1 : result > 0 ? 1 : 0; } @@ -1715,6 +1716,9 @@ var ts; }, watchDirectory: function (directoryName, callback, recursive) { var options; + if (!directoryExists(directoryName)) { + return; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -5187,10 +5191,12 @@ var ts; } } function getTypingNamesFromJson(jsonPath, filesToWatch) { + if (host.fileExists(jsonPath)) { + filesToWatch.push(jsonPath); + } var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); if (result.config) { var jsonConfig = result.config; - filesToWatch.push(jsonPath); if (jsonConfig.dependencies) { mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); } @@ -5391,43 +5397,44 @@ var ts; throw new Error("LanguageService is disabled"); } server.nullLanguageService = { - cleanupSemanticCache: function () { return throwLanguageServiceIsDisabledError(); }, - getSyntacticDiagnostics: function () { return throwLanguageServiceIsDisabledError(); }, - getSemanticDiagnostics: function () { return throwLanguageServiceIsDisabledError(); }, - getCompilerOptionsDiagnostics: function () { return throwLanguageServiceIsDisabledError(); }, - getSyntacticClassifications: function () { return throwLanguageServiceIsDisabledError(); }, - getEncodedSyntacticClassifications: function () { return throwLanguageServiceIsDisabledError(); }, - getSemanticClassifications: function () { return throwLanguageServiceIsDisabledError(); }, - getEncodedSemanticClassifications: function () { return throwLanguageServiceIsDisabledError(); }, - getCompletionsAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - findReferences: function () { return throwLanguageServiceIsDisabledError(); }, - getCompletionEntryDetails: function () { return throwLanguageServiceIsDisabledError(); }, - getQuickInfoAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - findRenameLocations: function () { return throwLanguageServiceIsDisabledError(); }, - getNameOrDottedNameSpan: function () { return throwLanguageServiceIsDisabledError(); }, - getBreakpointStatementAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getBraceMatchingAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getSignatureHelpItems: function () { return throwLanguageServiceIsDisabledError(); }, - getDefinitionAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getRenameInfo: function () { return throwLanguageServiceIsDisabledError(); }, - getTypeDefinitionAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getReferencesAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getDocumentHighlights: function () { return throwLanguageServiceIsDisabledError(); }, - getOccurrencesAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getNavigateToItems: function () { return throwLanguageServiceIsDisabledError(); }, - getNavigationBarItems: function () { return throwLanguageServiceIsDisabledError(); }, - getOutliningSpans: function () { return throwLanguageServiceIsDisabledError(); }, - getTodoComments: function () { return throwLanguageServiceIsDisabledError(); }, - getIndentationAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getFormattingEditsForRange: function () { return throwLanguageServiceIsDisabledError(); }, - getFormattingEditsForDocument: function () { return throwLanguageServiceIsDisabledError(); }, - getFormattingEditsAfterKeystroke: function () { return throwLanguageServiceIsDisabledError(); }, - getDocCommentTemplateAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - isValidBraceCompletionAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getEmitOutput: function () { return throwLanguageServiceIsDisabledError(); }, - getProgram: function () { return throwLanguageServiceIsDisabledError(); }, - getNonBoundSourceFile: function () { return throwLanguageServiceIsDisabledError(); }, - dispose: function () { return throwLanguageServiceIsDisabledError(); } + cleanupSemanticCache: throwLanguageServiceIsDisabledError, + getSyntacticDiagnostics: throwLanguageServiceIsDisabledError, + getSemanticDiagnostics: throwLanguageServiceIsDisabledError, + getCompilerOptionsDiagnostics: throwLanguageServiceIsDisabledError, + getSyntacticClassifications: throwLanguageServiceIsDisabledError, + getEncodedSyntacticClassifications: throwLanguageServiceIsDisabledError, + getSemanticClassifications: throwLanguageServiceIsDisabledError, + getEncodedSemanticClassifications: throwLanguageServiceIsDisabledError, + getCompletionsAtPosition: throwLanguageServiceIsDisabledError, + findReferences: throwLanguageServiceIsDisabledError, + getCompletionEntryDetails: throwLanguageServiceIsDisabledError, + getQuickInfoAtPosition: throwLanguageServiceIsDisabledError, + findRenameLocations: throwLanguageServiceIsDisabledError, + getNameOrDottedNameSpan: throwLanguageServiceIsDisabledError, + getBreakpointStatementAtPosition: throwLanguageServiceIsDisabledError, + getBraceMatchingAtPosition: throwLanguageServiceIsDisabledError, + getSignatureHelpItems: throwLanguageServiceIsDisabledError, + getDefinitionAtPosition: throwLanguageServiceIsDisabledError, + getRenameInfo: throwLanguageServiceIsDisabledError, + getTypeDefinitionAtPosition: throwLanguageServiceIsDisabledError, + getReferencesAtPosition: throwLanguageServiceIsDisabledError, + getDocumentHighlights: throwLanguageServiceIsDisabledError, + getOccurrencesAtPosition: throwLanguageServiceIsDisabledError, + getNavigateToItems: throwLanguageServiceIsDisabledError, + getNavigationBarItems: throwLanguageServiceIsDisabledError, + getNavigationTree: throwLanguageServiceIsDisabledError, + getOutliningSpans: throwLanguageServiceIsDisabledError, + getTodoComments: throwLanguageServiceIsDisabledError, + getIndentationAtPosition: throwLanguageServiceIsDisabledError, + getFormattingEditsForRange: throwLanguageServiceIsDisabledError, + getFormattingEditsForDocument: throwLanguageServiceIsDisabledError, + getFormattingEditsAfterKeystroke: throwLanguageServiceIsDisabledError, + getDocCommentTemplateAtPosition: throwLanguageServiceIsDisabledError, + isValidBraceCompletionAtPosition: throwLanguageServiceIsDisabledError, + getEmitOutput: throwLanguageServiceIsDisabledError, + getProgram: throwLanguageServiceIsDisabledError, + getNonBoundSourceFile: throwLanguageServiceIsDisabledError, + dispose: throwLanguageServiceIsDisabledError }; server.nullLanguageServiceHost = { setCompilationSettings: function () { return undefined; }, @@ -16372,14 +16379,14 @@ var ts; } return false; } - function isSymbolAccessible(symbol, enclosingDeclaration, meaning) { + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { if (symbol && enclosingDeclaration && !(symbol.flags & 262144)) { var initialSymbol = symbol; var meaningToLook = meaning; while (symbol) { var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, false); if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0]); + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); if (!hasAccessibleDeclarations) { return { accessibility: 1, @@ -16420,7 +16427,7 @@ var ts; function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 256 && ts.isExternalOrCommonJsModule(declaration)); } - function hasVisibleDeclarations(symbol) { + function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { return undefined; @@ -16432,14 +16439,16 @@ var ts; if (anyImportSyntax && !(anyImportSyntax.flags & 1) && isDeclarationVisible(anyImportSyntax.parent)) { - getNodeLinks(declaration).isVisible = true; - if (aliasesToMakeVisible) { - if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { - aliasesToMakeVisible.push(anyImportSyntax); + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + if (aliasesToMakeVisible) { + if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { + aliasesToMakeVisible.push(anyImportSyntax); + } + } + else { + aliasesToMakeVisible = [anyImportSyntax]; } - } - else { - aliasesToMakeVisible = [anyImportSyntax]; } return true; } @@ -16462,7 +16471,7 @@ var ts; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.text, meaning, undefined, undefined); - return (symbol && hasVisibleDeclarations(symbol)) || { + return (symbol && hasVisibleDeclarations(symbol, true)) || { accessibility: 1, errorSymbolName: ts.getTextOfNode(firstIdentifier), errorNode: firstIdentifier @@ -16679,14 +16688,10 @@ var ts; else if (type.flags & (32768 | 65536 | 16 | 16384)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } - else if (!(flags & 512) && type.flags & (2097152 | 1572864) && type.aliasSymbol) { - if (type.flags & 2097152 || !(flags & 1024)) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); - } - else { - writeUnionOrIntersectionType(type, nextFlags); - } + else if (!(flags & 512) && ((type.flags & 2097152 && !type.target) || type.flags & 1572864) && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { + var typeArguments = type.aliasTypeArguments; + writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); } else if (type.flags & 1572864) { writeUnionOrIntersectionType(type, nextFlags); @@ -30975,7 +30980,7 @@ var ts; } } function trackSymbol(symbol, enclosingDeclaration, meaning) { - handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning)); + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportInaccessibleThisError() { @@ -30992,7 +30997,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 | 1024, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2, writer); errorNameNode = undefined; } } @@ -31004,7 +31009,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 | 1024, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2, writer); errorNameNode = undefined; } } @@ -31197,7 +31202,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -31602,7 +31607,7 @@ var ts; } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2, writer); } function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; @@ -33681,14 +33686,14 @@ var ts; write(" = "); emitObjectLiteralBody(node, firstComputedPropertyIndex); for (var i = firstComputedPropertyIndex, n = properties.length; i < n; i++) { - writeComma(); var property = properties[i]; - emitStart(property); if (property.kind === 149 || property.kind === 150) { var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property !== accessors.firstAccessor) { continue; } + writeComma(); + emitStart(property); write("Object.defineProperty("); emit(tempVar); write(", "); @@ -33729,6 +33734,8 @@ var ts; emitEnd(property); } else { + writeComma(); + emitStart(property); emitLeadingComments(property); emitStart(property.name); emit(tempVar); @@ -33747,8 +33754,8 @@ var ts; else { ts.Debug.fail("ObjectLiteralElement type not accounted for: " + property.kind); } + emitEnd(property); } - emitEnd(property); } writeComma(); emit(tempVar); @@ -34192,7 +34199,11 @@ var ts; if (modulekind === ts.ModuleKind.System || node.kind !== 69 || ts.nodeIsSynthesized(node)) { return false; } - return !exportEquals && exportSpecifiers && node.text in exportSpecifiers; + if (exportEquals || !exportSpecifiers || !(node.text in exportSpecifiers)) { + return false; + } + var declaration = resolver.getReferencedValueDeclaration(node); + return declaration && ts.getEnclosingBlockScopeContainer(declaration).kind === 256; } function emitPrefixUnaryExpression(node) { var isPlusPlusOrMinusMinus = (node.operator === 41 @@ -40506,7 +40517,6 @@ var ts; function getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount, excludeDts) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - var baseSensitivity = { sensitivity: "base" }; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); @@ -40638,8 +40648,8 @@ var ts; } function compareNavigateToItems(i1, i2) { return i1.matchKind - i2.matchKind || - i1.name.localeCompare(i2.name, undefined, baseSensitivity) || - i1.name.localeCompare(i2.name); + ts.compareStringsCaseInsensitive(i1.name, i2.name) || + ts.compareStrings(i1.name, i2.name); } function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; @@ -40671,6 +40681,13 @@ var ts; return result; } NavigationBar.getNavigationBarItems = getNavigationBarItems; + function getNavigationTree(sourceFile) { + curSourceFile = sourceFile; + var result = convertToTree(rootNavigationBarNode(sourceFile)); + curSourceFile = undefined; + return result; + } + NavigationBar.getNavigationTree = getNavigationTree; var curSourceFile; function nodeText(node) { return node.getText(curSourceFile); @@ -40920,9 +40937,8 @@ var ts; return name1 ? 1 : name2 ? -1 : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); } } - var collator = typeof Intl !== "undefined" && Intl && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; - var localeCompareIsCorrect = collator && collator.compare("a", "B") < 0; - var localeCompareFix = localeCompareIsCorrect ? collator.compare : function (a, b) { + var localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; + var localeCompareFix = localeCompareIsCorrect ? ts.collator.compare : function (a, b) { for (var i = 0; i < Math.min(a.length, b.length); i++) { var chA = a.charAt(i), chB = b.charAt(i); if (chA === "\"" && chB === "'") { @@ -40931,7 +40947,7 @@ var ts; if (chA === "'" && chB === "\"") { return -1; } - var cmp = chA.toLocaleLowerCase().localeCompare(chB.toLocaleLowerCase()); + var cmp = ts.compareStrings(chA.toLocaleLowerCase(), chB.toLocaleLowerCase()); if (cmp !== 0) { return cmp; } @@ -41075,6 +41091,15 @@ var ts; } } var emptyChildItemArray = []; + function convertToTree(n) { + return { + text: getItemName(n.node), + kind: ts.getNodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToTree) + }; + } function convertToTopLevelItem(n) { return { text: getItemName(n.node), @@ -41098,16 +41123,16 @@ var ts; grayed: false }; } - function getSpans(n) { - var spans = [getNodeSpan(n.node)]; - if (n.additionalNodes) { - for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { - var node = _a[_i]; - spans.push(getNodeSpan(node)); - } + } + function getSpans(n) { + var spans = [getNodeSpan(n.node)]; + if (n.additionalNodes) { + for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { + var node = _a[_i]; + spans.push(getNodeSpan(node)); } - return spans; } + return spans; } function getModuleName(moduleDeclaration) { if (ts.isAmbientModule(moduleDeclaration)) { @@ -50365,8 +50390,10 @@ var ts; return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); } function getNavigationBarItems(fileName) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function getNavigationTree(fileName) { + return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName)); } function getSemanticClassifications(fileName, span) { return convertClassifications(getEncodedSemanticClassifications(fileName, span)); @@ -51132,6 +51159,7 @@ var ts; getRenameInfo: getRenameInfo, findRenameLocations: findRenameLocations, getNavigationBarItems: getNavigationBarItems, + getNavigationTree: getNavigationTree, getOutliningSpans: getOutliningSpans, getTodoComments: getTodoComments, getBraceMatchingAtPosition: getBraceMatchingAtPosition, @@ -51645,12 +51673,12 @@ var ts; var snap = this.snap(); this.host.writeFile(fileName, snap.getText(0, snap.getLength())); }; - ScriptInfo.prototype.reloadFromFile = function () { + ScriptInfo.prototype.reloadFromFile = function (tempFileName) { if (this.hasMixedContent) { this.reload(""); } else { - this.svc.reloadFromFile(this.fileName); + this.svc.reloadFromFile(tempFileName || this.fileName); this.markContainingProjectsAsDirty(); } }; @@ -52558,11 +52586,11 @@ var ts; this.markAsDirty(); } }; - Project.prototype.reloadScript = function (filename) { + Project.prototype.reloadScript = function (filename, tempFileName) { var script = this.projectService.getScriptInfoForNormalizedPath(filename); if (script) { ts.Debug.assert(script.isAttached(this)); - script.reloadFromFile(); + script.reloadFromFile(tempFileName); return true; } return false; @@ -52850,6 +52878,66 @@ var ts; var server; (function (server) { server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; + function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions) { + var map = ts.createMap(); + for (var _i = 0, commandLineOptions_1 = commandLineOptions; _i < commandLineOptions_1.length; _i++) { + var option = commandLineOptions_1[_i]; + if (typeof option.type === "object") { + var optionMap = option.type; + for (var id in optionMap) { + ts.Debug.assert(typeof optionMap[id] === "number"); + } + map[option.name] = optionMap; + } + } + return map; + } + var compilerOptionConverters = prepareConvertersForEnumLikeCompilerOptions(ts.optionDeclarations); + var indentStyle = ts.createMap({ + "none": ts.IndentStyle.None, + "block": ts.IndentStyle.Block, + "smart": ts.IndentStyle.Smart + }); + function convertFormatOptions(protocolOptions) { + if (typeof protocolOptions.indentStyle === "string") { + protocolOptions.indentStyle = indentStyle[protocolOptions.indentStyle.toLowerCase()]; + ts.Debug.assert(protocolOptions.indentStyle !== undefined); + } + return protocolOptions; + } + server.convertFormatOptions = convertFormatOptions; + function convertCompilerOptions(protocolOptions) { + for (var id in compilerOptionConverters) { + var propertyValue = protocolOptions[id]; + if (typeof propertyValue === "string") { + var mappedValues = compilerOptionConverters[id]; + protocolOptions[id] = mappedValues[propertyValue.toLowerCase()]; + } + } + return protocolOptions; + } + server.convertCompilerOptions = convertCompilerOptions; + function tryConvertScriptKindName(scriptKindName) { + return typeof scriptKindName === "string" + ? convertScriptKindName(scriptKindName) + : scriptKindName; + } + server.tryConvertScriptKindName = tryConvertScriptKindName; + function convertScriptKindName(scriptKindName) { + switch (scriptKindName) { + case "JS": + return 1; + case "JSX": + return 2; + case "TS": + return 3; + case "TSX": + return 4; + default: + return 0; + } + } + server.convertScriptKindName = convertScriptKindName; function combineProjectOutput(projects, action, comparer, areEqual) { var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer); return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; @@ -52862,7 +52950,7 @@ var ts; }; var externalFilePropertyReader = { getFileName: function (x) { return x.fileName; }, - getScriptKind: function (x) { return x.scriptKind; }, + getScriptKind: function (x) { return tryConvertScriptKindName(x.scriptKind); }, hasMixedContent: function (x) { return x.hasMixedContent; } }; function findProjectByName(projectName, projects) { @@ -52947,6 +53035,9 @@ var ts; ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () { this.ensureInferredProjectsUpToDate(); }; + ProjectService.prototype.getCompilerOptionsForInferredProjects = function () { + return this.compilerOptionsForInferredProjects; + }; ProjectService.prototype.updateTypingsForProject = function (response) { var project = this.findProject(response.projectName); if (!project) { @@ -52963,11 +53054,11 @@ var ts; } }; ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions) { - this.compilerOptionsForInferredProjects = projectCompilerOptions; + this.compilerOptionsForInferredProjects = convertCompilerOptions(projectCompilerOptions); this.compileOnSaveForInferredProjects = projectCompilerOptions.compileOnSave; for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var proj = _a[_i]; - proj.setCompilerOptions(projectCompilerOptions); + proj.setCompilerOptions(this.compilerOptionsForInferredProjects); proj.compileOnSaveEnabled = projectCompilerOptions.compileOnSave; } this.updateProjectGraphs(this.inferredProjects); @@ -53313,7 +53404,7 @@ var ts; } ts.Debug.assert(!!parsedCommandLine.fileNames); if (parsedCommandLine.fileNames.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); + (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); return { success: false, configFileErrors: errors }; } var projectOptions = { @@ -53345,18 +53436,20 @@ var ts; return false; }; ProjectService.prototype.createAndAddExternalProject = function (projectFileName, files, options, typingOptions) { - var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, options, !this.exceededTotalSizeLimitForNonTsFiles(options, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); + var compilerOptions = convertCompilerOptions(options); + var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, !this.exceededTotalSizeLimitForNonTsFiles(compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, undefined, typingOptions, undefined); this.externalProjects.push(project); return project; }; ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) { - if (diagnostics && diagnostics.length > 0) { - this.eventHandler({ - eventName: "configFileDiag", - data: { configFileName: configFileName, diagnostics: diagnostics, triggerFile: triggerFile } - }); + if (!this.eventHandler) { + return; } + this.eventHandler({ + eventName: "configFileDiag", + data: { configFileName: configFileName, diagnostics: diagnostics || [], triggerFile: triggerFile } + }); }; ProjectService.prototype.createAndAddConfiguredProject = function (configFileName, projectOptions, configFileErrors, clientFileName) { var _this = this; @@ -53563,7 +53656,7 @@ var ts; if (args.file) { var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file)); if (info) { - info.setFormatOptions(args.formatOptions); + info.setFormatOptions(convertFormatOptions(args.formatOptions)); this.logger.info("Host configuration update for file " + args.file); } } @@ -53573,7 +53666,7 @@ var ts; this.logger.info("Host information " + args.hostInfo); } if (args.formatOptions) { - server.mergeMaps(this.hostConfiguration.formatCodeOptions, args.formatOptions); + server.mergeMaps(this.hostConfiguration.formatCodeOptions, convertFormatOptions(args.formatOptions)); this.logger.info("Format host information updated"); } } @@ -53664,7 +53757,7 @@ var ts; var scriptInfo = this.getScriptInfo(file.fileName); ts.Debug.assert(!scriptInfo || !scriptInfo.isOpen); var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName); - this.openClientFileWithNormalizedPath(normalizedPath, file.content, file.scriptKind, file.hasMixedContent); + this.openClientFileWithNormalizedPath(normalizedPath, file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent); } } if (changedFiles) { @@ -53749,7 +53842,7 @@ var ts; var exisingConfigFiles; if (externalProject) { if (!tsConfigFiles) { - this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, proj.options, proj.typingOptions, proj.options.compileOnSave, undefined); + this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, convertCompilerOptions(proj.options), proj.typingOptions, proj.options.compileOnSave, undefined); return; } this.closeExternalProject(proj.projectFileName, true); @@ -53887,6 +53980,8 @@ var ts; CommandNames.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; CommandNames.NavBar = "navbar"; CommandNames.NavBarFull = "navbar-full"; + CommandNames.NavTree = "navtree"; + CommandNames.NavTreeFull = "navtree-full"; CommandNames.Navto = "navto"; CommandNames.NavtoFull = "navto-full"; CommandNames.Occurrences = "occurrences"; @@ -53935,7 +54030,7 @@ var ts; } server.formatMessage = formatMessage; var Session = (function () { - function Session(host, cancellationToken, useSingleInferredProject, typingsInstaller, byteLength, hrtime, logger, canUseEvents) { + function Session(host, cancellationToken, useSingleInferredProject, typingsInstaller, byteLength, hrtime, logger, canUseEvents, eventHandler) { var _this = this; this.host = host; this.typingsInstaller = typingsInstaller; @@ -54012,23 +54107,7 @@ var ts; return _this.requiredResponse(_this.getRenameInfo(request.arguments)); }, _a[CommandNames.Open] = function (request) { - var openArgs = request.arguments; - var scriptKind; - switch (openArgs.scriptKindName) { - case "TS": - scriptKind = 3; - break; - case "JS": - scriptKind = 1; - break; - case "TSX": - scriptKind = 4; - break; - case "JSX": - scriptKind = 2; - break; - } - _this.openClientFile(server.toNormalizedPath(openArgs.file), openArgs.fileContent, scriptKind); + _this.openClientFile(server.toNormalizedPath(request.arguments.file), request.arguments.fileContent, server.convertScriptKindName(request.arguments.scriptKindName)); return _this.notRequired(); }, _a[CommandNames.Quickinfo] = function (request) { @@ -54159,6 +54238,12 @@ var ts; _a[CommandNames.NavBarFull] = function (request) { return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, false)); }, + _a[CommandNames.NavTree] = function (request) { + return _this.requiredResponse(_this.getNavigationTree(request.arguments, true)); + }, + _a[CommandNames.NavTreeFull] = function (request) { + return _this.requiredResponse(_this.getNavigationTree(request.arguments, false)); + }, _a[CommandNames.Occurrences] = function (request) { return _this.requiredResponse(_this.getOccurrences(request.arguments)); }, @@ -54169,7 +54254,8 @@ var ts; return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, false)); }, _a[CommandNames.CompilerOptionsForInferredProjects] = function (request) { - return _this.requiredResponse(_this.setCompilerOptionsForInferredProjects(request.arguments)); + _this.setCompilerOptionsForInferredProjects(request.arguments); + return _this.requiredResponse(true); }, _a[CommandNames.ProjectInfo] = function (request) { return _this.requiredResponse(_this.getProjectInfo(request.arguments)); @@ -54180,14 +54266,14 @@ var ts; }, _a )); - var eventHandler = canUseEvents - ? function (event) { return _this.handleEvent(event); } + this.eventHander = canUseEvents + ? eventHandler || (function (event) { return _this.defaultEventHandler(event); }) : undefined; - this.projectService = new server.ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, eventHandler); + this.projectService = new server.ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, this.eventHander); this.gcTimer = new server.GcTimer(host, 7000, logger); var _a; } - Session.prototype.handleEvent = function (event) { + Session.prototype.defaultEventHandler = function (event) { var _this = this; switch (event.eventName) { case "context": @@ -54653,8 +54739,11 @@ var ts; }; Session.prototype.openClientFile = function (fileName, fileContent, scriptKind) { var _a = this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; - if (configFileErrors) { - this.configFileDiagnosticEvent(fileName, configFileName, configFileErrors); + if (this.eventHander) { + this.eventHander({ + eventName: "configFileDiag", + data: { fileName: fileName, configFileName: configFileName, diagnostics: configFileErrors || [] } + }); } }; Session.prototype.getPosition = function (args, scriptInfo) { @@ -54693,7 +54782,7 @@ var ts; Session.prototype.getIndentation = function (args) { var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); - var options = args.options || this.projectService.getFormatCodeOptions(file); + var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); var indentation = project.getLanguageService(false).getIndentationAtPosition(file, position, options); return { position: position, indentation: indentation }; }; @@ -54754,17 +54843,17 @@ var ts; }; Session.prototype.getFormattingEditsForRangeFull = function (args) { var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var options = args.options || this.projectService.getFormatCodeOptions(file); + var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); return project.getLanguageService(false).getFormattingEditsForRange(file, args.position, args.endPosition, options); }; Session.prototype.getFormattingEditsForDocumentFull = function (args) { var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var options = args.options || this.projectService.getFormatCodeOptions(file); + var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); return project.getLanguageService(false).getFormattingEditsForDocument(file, options); }; Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) { var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var options = args.options || this.projectService.getFormatCodeOptions(file); + var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); return project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, args.position, args.key, options); }; Session.prototype.getFormattingEditsAfterKeystroke = function (args) { @@ -54814,6 +54903,7 @@ var ts; }); }; Session.prototype.getCompletions = function (args, simplifiedResult) { + var _this = this; var prefix = args.prefix || ""; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); @@ -54826,17 +54916,11 @@ var ts; return completions.entries.reduce(function (result, entry) { if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { var name_44 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; - var convertedSpan = undefined; - if (replacementSpan) { - convertedSpan = { - start: scriptInfo.positionToLineOffset(replacementSpan.start), - end: scriptInfo.positionToLineOffset(replacementSpan.start + replacementSpan.length) - }; - } + var convertedSpan = replacementSpan ? _this.decorateSpan(replacementSpan, scriptInfo) : undefined; result.push({ name: name_44, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }); } return result; - }, []).sort(function (a, b) { return a.name.localeCompare(b.name); }); + }, []).sort(function (a, b) { return ts.compareStrings(a.name, b.name); }); } else { return completions; @@ -54936,10 +55020,11 @@ var ts; }; Session.prototype.reload = function (args, reqSeq) { var file = server.toNormalizedPath(args.file); + var tempFileName = args.tmpfile && server.toNormalizedPath(args.tmpfile); var project = this.projectService.getDefaultProjectForFile(file, true); if (project) { this.changeSeq++; - if (project.reloadScript(file)) { + if (project.reloadScript(file, tempFileName)) { this.output(undefined, CommandNames.Reload, reqSeq); } } @@ -54957,33 +55042,50 @@ var ts; var file = ts.normalizePath(fileName); this.projectService.closeClientFile(file); }; - Session.prototype.decorateNavigationBarItem = function (project, fileName, items) { + Session.prototype.decorateNavigationBarItems = function (items, scriptInfo) { var _this = this; - if (!items) { - return undefined; - } - var scriptInfo = project.getScriptInfoForNormalizedPath(fileName); - return items.map(function (item) { return ({ + return ts.map(items, function (item) { return ({ text: item.text, kind: item.kind, kindModifiers: item.kindModifiers, - spans: item.spans.map(function (span) { return ({ - start: scriptInfo.positionToLineOffset(span.start), - end: scriptInfo.positionToLineOffset(ts.textSpanEnd(span)) - }); }), - childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems), + spans: item.spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }), + childItems: _this.decorateNavigationBarItems(item.childItems, scriptInfo), indent: item.indent }); }); }; Session.prototype.getNavigationBarItems = function (args, simplifiedResult) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var items = project.getLanguageService().getNavigationBarItems(file); - if (!items) { - return undefined; - } - return simplifiedResult - ? this.decorateNavigationBarItem(project, file, items) - : items; + var items = project.getLanguageService(false).getNavigationBarItems(file); + return !items + ? undefined + : simplifiedResult + ? this.decorateNavigationBarItems(items, project.getScriptInfoForNormalizedPath(file)) + : items; + }; + Session.prototype.decorateNavigationTree = function (tree, scriptInfo) { + var _this = this; + return { + text: tree.text, + kind: tree.kind, + kindModifiers: tree.kindModifiers, + spans: tree.spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }), + childItems: ts.map(tree.childItems, function (item) { return _this.decorateNavigationTree(item, scriptInfo); }) + }; + }; + Session.prototype.decorateSpan = function (span, scriptInfo) { + return { + start: scriptInfo.positionToLineOffset(span.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(span)) + }; + }; + Session.prototype.getNavigationTree = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var tree = project.getLanguageService(false).getNavigationTree(file); + return !tree + ? undefined + : simplifiedResult + ? this.decorateNavigationTree(tree, project.getScriptInfoForNormalizedPath(file)) + : tree; }; Session.prototype.getNavigateToItems = function (args, simplifiedResult) { var projects = this.getProjects(args); @@ -55051,22 +55153,16 @@ var ts; } }; Session.prototype.getBraceMatching = function (args, simplifiedResult) { + var _this = this; var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); var spans = project.getLanguageService(false).getBraceMatchingAtPosition(file, position); - if (!spans) { - return undefined; - } - if (simplifiedResult) { - return spans.map(function (span) { return ({ - start: scriptInfo.positionToLineOffset(span.start), - end: scriptInfo.positionToLineOffset(span.start + span.length) - }); }); - } - else { - return spans; - } + return !spans + ? undefined + : simplifiedResult + ? spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }) + : spans; }; Session.prototype.getDiagnosticsForProject = function (delay, fileName) { var _this = this; @@ -56187,8 +56283,10 @@ var ts; }()); var IOSession = (function (_super) { __extends(IOSession, _super); - function IOSession(host, cancellationToken, installerEventPort, canUseEvents, useSingleInferredProject, globalTypingsCacheLocation, logger) { - _super.call(this, host, cancellationToken, useSingleInferredProject, new NodeTypingsInstaller(logger, installerEventPort, globalTypingsCacheLocation, host.newLine), Buffer.byteLength, process.hrtime, logger, canUseEvents); + function IOSession(host, cancellationToken, installerEventPort, canUseEvents, useSingleInferredProject, disableAutomaticTypingAcquisition, globalTypingsCacheLocation, logger) { + _super.call(this, host, cancellationToken, useSingleInferredProject, disableAutomaticTypingAcquisition + ? server.nullTypingsInstaller + : new NodeTypingsInstaller(logger, installerEventPort, globalTypingsCacheLocation, host.newLine), Buffer.byteLength, process.hrtime, logger, canUseEvents); } IOSession.prototype.exit = function () { this.logger.info("Exiting..."); @@ -56377,7 +56475,8 @@ var ts; } } var useSingleInferredProject = sys.args.indexOf("--useSingleInferredProject") >= 0; - var ioSession = new IOSession(sys, cancellationToken, eventPort, eventPort === undefined, useSingleInferredProject, getGlobalTypingsCacheLocation(), logger); + var disableAutomaticTypingAcquisition = sys.args.indexOf("--disableAutomaticTypingAcquisition") >= 0; + var ioSession = new IOSession(sys, cancellationToken, eventPort, eventPort === undefined, useSingleInferredProject, disableAutomaticTypingAcquisition, getGlobalTypingsCacheLocation(), logger); process.on("uncaughtException", function (err) { ioSession.logError(err, "unknown"); }); @@ -56828,6 +56927,10 @@ var ts; var _this = this; return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; + LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); }); + }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 02962d87a75a2..3104e2410169f 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -1,6 +1,780 @@ /// -/// /// +declare namespace ts.server.protocol { + namespace CommandTypes { + type Brace = "brace"; + type BraceFull = "brace-full"; + type BraceCompletion = "braceCompletion"; + type Change = "change"; + type Close = "close"; + type Completions = "completions"; + type CompletionsFull = "completions-full"; + type CompletionDetails = "completionEntryDetails"; + type CompileOnSaveAffectedFileList = "compileOnSaveAffectedFileList"; + type CompileOnSaveEmitFile = "compileOnSaveEmitFile"; + type Configure = "configure"; + type Definition = "definition"; + type DefinitionFull = "definition-full"; + type Exit = "exit"; + type Format = "format"; + type Formatonkey = "formatonkey"; + type FormatFull = "format-full"; + type FormatonkeyFull = "formatonkey-full"; + type FormatRangeFull = "formatRange-full"; + type Geterr = "geterr"; + type GeterrForProject = "geterrForProject"; + type SemanticDiagnosticsSync = "semanticDiagnosticsSync"; + type SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; + type NavBar = "navbar"; + type NavBarFull = "navbar-full"; + type Navto = "navto"; + type NavtoFull = "navto-full"; + type NavTree = "navtree"; + type NavTreeFull = "navtree-full"; + type Occurrences = "occurrences"; + type DocumentHighlights = "documentHighlights"; + type DocumentHighlightsFull = "documentHighlights-full"; + type Open = "open"; + type Quickinfo = "quickinfo"; + type QuickinfoFull = "quickinfo-full"; + type References = "references"; + type ReferencesFull = "references-full"; + type Reload = "reload"; + type Rename = "rename"; + type RenameInfoFull = "rename-full"; + type RenameLocationsFull = "renameLocations-full"; + type Saveto = "saveto"; + type SignatureHelp = "signatureHelp"; + type SignatureHelpFull = "signatureHelp-full"; + type TypeDefinition = "typeDefinition"; + type ProjectInfo = "projectInfo"; + type ReloadProjects = "reloadProjects"; + type Unknown = "unknown"; + type OpenExternalProject = "openExternalProject"; + type OpenExternalProjects = "openExternalProjects"; + type CloseExternalProject = "closeExternalProject"; + type SynchronizeProjectList = "synchronizeProjectList"; + type ApplyChangedToOpenFiles = "applyChangedToOpenFiles"; + type EncodedSemanticClassificationsFull = "encodedSemanticClassifications-full"; + type Cleanup = "cleanup"; + type OutliningSpans = "outliningSpans"; + type TodoComments = "todoComments"; + type Indentation = "indentation"; + type DocCommentTemplate = "docCommentTemplate"; + type CompilerOptionsDiagnosticsFull = "compilerOptionsDiagnostics-full"; + type NameOrDottedNameSpan = "nameOrDottedNameSpan"; + type BreakpointStatement = "breakpointStatement"; + type CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects"; + } + interface Message { + seq: number; + type: "request" | "response" | "event"; + } + interface Request extends Message { + command: string; + arguments?: any; + } + interface ReloadProjectsRequest extends Message { + command: CommandTypes.ReloadProjects; + } + interface Event extends Message { + event: string; + body?: any; + } + interface Response extends Message { + request_seq: number; + success: boolean; + command: string; + message?: string; + body?: any; + } + interface FileRequestArgs { + file: string; + projectFileName?: string; + } + interface DocCommentTemplateRequest extends FileLocationRequest { + command: CommandTypes.DocCommentTemplate; + } + interface DocCommandTemplateResponse extends Response { + body?: TextInsertion; + } + interface TodoCommentRequest extends FileRequest { + command: CommandTypes.TodoComments; + arguments: TodoCommentRequestArgs; + } + interface TodoCommentRequestArgs extends FileRequestArgs { + descriptors: TodoCommentDescriptor[]; + } + interface TodoCommentsResponse extends Response { + body?: TodoComment[]; + } + interface OutliningSpansRequest extends FileRequest { + command: CommandTypes.OutliningSpans; + } + interface OutliningSpansResponse extends Response { + body?: OutliningSpan[]; + } + interface IndentationRequest extends FileLocationRequest { + command: CommandTypes.Indentation; + arguments: IndentationRequestArgs; + } + interface IndentationResponse extends Response { + body?: IndentationResult; + } + interface IndentationResult { + position: number; + indentation: number; + } + interface IndentationRequestArgs extends FileLocationRequestArgs { + options?: EditorSettings; + } + interface ProjectInfoRequestArgs extends FileRequestArgs { + needFileNameList: boolean; + } + interface ProjectInfoRequest extends Request { + command: CommandTypes.ProjectInfo; + arguments: ProjectInfoRequestArgs; + } + interface CompilerOptionsDiagnosticsRequest extends Request { + arguments: CompilerOptionsDiagnosticsRequestArgs; + } + interface CompilerOptionsDiagnosticsRequestArgs { + projectFileName: string; + } + interface ProjectInfo { + configFileName: string; + fileNames?: string[]; + languageServiceDisabled?: boolean; + } + interface DiagnosticWithLinePosition { + message: string; + start: number; + length: number; + startLocation: Location; + endLocation: Location; + category: string; + code: number; + } + interface ProjectInfoResponse extends Response { + body?: ProjectInfo; + } + interface FileRequest extends Request { + arguments: FileRequestArgs; + } + interface FileLocationRequestArgs extends FileRequestArgs { + line: number; + offset: number; + position?: number; + } + interface FileLocationRequest extends FileRequest { + arguments: FileLocationRequestArgs; + } + interface EncodedSemanticClassificationsRequest extends FileRequest { + arguments: EncodedSemanticClassificationsRequestArgs; + } + interface EncodedSemanticClassificationsRequestArgs extends FileRequestArgs { + start: number; + length: number; + } + interface DocumentHighlightsRequestArgs extends FileLocationRequestArgs { + filesToSearch: string[]; + } + interface DefinitionRequest extends FileLocationRequest { + command: CommandTypes.Definition; + } + interface TypeDefinitionRequest extends FileLocationRequest { + command: CommandTypes.TypeDefinition; + } + interface Location { + line: number; + offset: number; + } + interface TextSpan { + start: Location; + end: Location; + } + interface FileSpan extends TextSpan { + file: string; + } + interface DefinitionResponse extends Response { + body?: FileSpan[]; + } + interface TypeDefinitionResponse extends Response { + body?: FileSpan[]; + } + interface ImplementationResponse extends Response { + body?: FileSpan[]; + } + interface BraceCompletionRequest extends FileLocationRequest { + command: CommandTypes.BraceCompletion; + arguments: BraceCompletionRequestArgs; + } + interface BraceCompletionRequestArgs extends FileLocationRequestArgs { + openingBrace: string; + } + interface OccurrencesRequest extends FileLocationRequest { + command: CommandTypes.Occurrences; + } + interface OccurrencesResponseItem extends FileSpan { + isWriteAccess: boolean; + } + interface OccurrencesResponse extends Response { + body?: OccurrencesResponseItem[]; + } + interface DocumentHighlightsRequest extends FileLocationRequest { + command: CommandTypes.DocumentHighlights; + arguments: DocumentHighlightsRequestArgs; + } + interface HighlightSpan extends TextSpan { + kind: string; + } + interface DocumentHighlightsItem { + file: string; + highlightSpans: HighlightSpan[]; + } + interface DocumentHighlightsResponse extends Response { + body?: DocumentHighlightsItem[]; + } + interface ReferencesRequest extends FileLocationRequest { + command: CommandTypes.References; + } + interface ReferencesResponseItem extends FileSpan { + lineText: string; + isWriteAccess: boolean; + isDefinition: boolean; + } + interface ReferencesResponseBody { + refs: ReferencesResponseItem[]; + symbolName: string; + symbolStartOffset: number; + symbolDisplayString: string; + } + interface ReferencesResponse extends Response { + body?: ReferencesResponseBody; + } + interface RenameRequestArgs extends FileLocationRequestArgs { + findInComments?: boolean; + findInStrings?: boolean; + } + interface RenameRequest extends FileLocationRequest { + command: CommandTypes.Rename; + arguments: RenameRequestArgs; + } + interface RenameInfo { + canRename: boolean; + localizedErrorMessage?: string; + displayName: string; + fullDisplayName: string; + kind: string; + kindModifiers: string; + } + interface SpanGroup { + file: string; + locs: TextSpan[]; + } + interface RenameResponseBody { + info: RenameInfo; + locs: SpanGroup[]; + } + interface RenameResponse extends Response { + body?: RenameResponseBody; + } + interface ExternalFile { + fileName: string; + scriptKind?: ScriptKindName | ts.ScriptKind; + hasMixedContent?: boolean; + content?: string; + } + interface ExternalProject { + projectFileName: string; + rootFiles: ExternalFile[]; + options: ExternalProjectCompilerOptions; + typingOptions?: TypingOptions; + } + interface CompileOnSaveMixin { + compileOnSave?: boolean; + } + type ExternalProjectCompilerOptions = CompilerOptions & CompileOnSaveMixin; + interface ProjectVersionInfo { + projectName: string; + isInferred: boolean; + version: number; + options: ts.CompilerOptions; + } + interface ProjectChanges { + added: string[]; + removed: string[]; + } + interface ProjectFiles { + info?: ProjectVersionInfo; + files?: string[]; + changes?: ProjectChanges; + } + interface ProjectFilesWithDiagnostics extends ProjectFiles { + projectErrors: DiagnosticWithLinePosition[]; + } + interface ChangedOpenFile { + fileName: string; + changes: ts.TextChange[]; + } + interface ConfigureRequestArguments { + hostInfo?: string; + file?: string; + formatOptions?: FormatCodeSettings; + } + interface ConfigureRequest extends Request { + command: CommandTypes.Configure; + arguments: ConfigureRequestArguments; + } + interface ConfigureResponse extends Response { + } + interface OpenRequestArgs extends FileRequestArgs { + fileContent?: string; + scriptKindName?: ScriptKindName; + } + type ScriptKindName = "TS" | "JS" | "TSX" | "JSX"; + interface OpenRequest extends Request { + command: CommandTypes.Open; + arguments: OpenRequestArgs; + } + interface OpenExternalProjectRequest extends Request { + command: CommandTypes.OpenExternalProject; + arguments: OpenExternalProjectArgs; + } + type OpenExternalProjectArgs = ExternalProject; + interface OpenExternalProjectsRequest extends Request { + command: CommandTypes.OpenExternalProjects; + arguments: OpenExternalProjectsArgs; + } + interface OpenExternalProjectsArgs { + projects: ExternalProject[]; + } + interface OpenExternalProjectResponse extends Response { + } + interface OpenExternalProjectsResponse extends Response { + } + interface CloseExternalProjectRequest extends Request { + command: CommandTypes.CloseExternalProject; + arguments: CloseExternalProjectRequestArgs; + } + interface CloseExternalProjectRequestArgs { + projectFileName: string; + } + interface CloseExternalProjectResponse extends Response { + } + interface SynchronizeProjectListRequest extends Request { + arguments: SynchronizeProjectListRequestArgs; + } + interface SynchronizeProjectListRequestArgs { + knownProjects: protocol.ProjectVersionInfo[]; + } + interface ApplyChangedToOpenFilesRequest extends Request { + arguments: ApplyChangedToOpenFilesRequestArgs; + } + interface ApplyChangedToOpenFilesRequestArgs { + openFiles?: ExternalFile[]; + changedFiles?: ChangedOpenFile[]; + closedFiles?: string[]; + } + interface SetCompilerOptionsForInferredProjectsRequest extends Request { + command: CommandTypes.CompilerOptionsForInferredProjects; + arguments: SetCompilerOptionsForInferredProjectsArgs; + } + interface SetCompilerOptionsForInferredProjectsArgs { + options: ExternalProjectCompilerOptions; + } + interface SetCompilerOptionsForInferredProjectsResponse extends Response { + } + interface ExitRequest extends Request { + command: CommandTypes.Exit; + } + interface CloseRequest extends FileRequest { + command: CommandTypes.Close; + } + interface CompileOnSaveAffectedFileListRequest extends FileRequest { + command: CommandTypes.CompileOnSaveAffectedFileList; + } + interface CompileOnSaveAffectedFileListSingleProject { + projectFileName: string; + fileNames: string[]; + } + interface CompileOnSaveAffectedFileListResponse extends Response { + body: CompileOnSaveAffectedFileListSingleProject[]; + } + interface CompileOnSaveEmitFileRequest extends FileRequest { + command: CommandTypes.CompileOnSaveEmitFile; + arguments: CompileOnSaveEmitFileRequestArgs; + } + interface CompileOnSaveEmitFileRequestArgs extends FileRequestArgs { + forced?: boolean; + } + interface QuickInfoRequest extends FileLocationRequest { + command: CommandTypes.Quickinfo; + } + interface QuickInfoResponseBody { + kind: string; + kindModifiers: string; + start: Location; + end: Location; + displayString: string; + documentation: string; + } + interface QuickInfoResponse extends Response { + body?: QuickInfoResponseBody; + } + interface FormatRequestArgs extends FileLocationRequestArgs { + endLine: number; + endOffset: number; + endPosition?: number; + options?: FormatCodeSettings; + } + interface FormatRequest extends FileLocationRequest { + command: CommandTypes.Format; + arguments: FormatRequestArgs; + } + interface CodeEdit { + start: Location; + end: Location; + newText: string; + } + interface FormatResponse extends Response { + body?: CodeEdit[]; + } + interface FormatOnKeyRequestArgs extends FileLocationRequestArgs { + key: string; + options?: FormatCodeSettings; + } + interface FormatOnKeyRequest extends FileLocationRequest { + command: CommandTypes.Formatonkey; + arguments: FormatOnKeyRequestArgs; + } + interface CompletionsRequestArgs extends FileLocationRequestArgs { + prefix?: string; + } + interface CompletionsRequest extends FileLocationRequest { + command: CommandTypes.Completions; + arguments: CompletionsRequestArgs; + } + interface CompletionDetailsRequestArgs extends FileLocationRequestArgs { + entryNames: string[]; + } + interface CompletionDetailsRequest extends FileLocationRequest { + command: CommandTypes.CompletionDetails; + arguments: CompletionDetailsRequestArgs; + } + interface SymbolDisplayPart { + text: string; + kind: string; + } + interface CompletionEntry { + name: string; + kind: string; + kindModifiers: string; + sortText: string; + replacementSpan?: TextSpan; + } + interface CompletionEntryDetails { + name: string; + kind: string; + kindModifiers: string; + displayParts: SymbolDisplayPart[]; + documentation: SymbolDisplayPart[]; + } + interface CompletionsResponse extends Response { + body?: CompletionEntry[]; + } + interface CompletionDetailsResponse extends Response { + body?: CompletionEntryDetails[]; + } + interface SignatureHelpParameter { + name: string; + documentation: SymbolDisplayPart[]; + displayParts: SymbolDisplayPart[]; + isOptional: boolean; + } + interface SignatureHelpItem { + isVariadic: boolean; + prefixDisplayParts: SymbolDisplayPart[]; + suffixDisplayParts: SymbolDisplayPart[]; + separatorDisplayParts: SymbolDisplayPart[]; + parameters: SignatureHelpParameter[]; + documentation: SymbolDisplayPart[]; + } + interface SignatureHelpItems { + items: SignatureHelpItem[]; + applicableSpan: TextSpan; + selectedItemIndex: number; + argumentIndex: number; + argumentCount: number; + } + interface SignatureHelpRequestArgs extends FileLocationRequestArgs { + } + interface SignatureHelpRequest extends FileLocationRequest { + command: CommandTypes.SignatureHelp; + arguments: SignatureHelpRequestArgs; + } + interface SignatureHelpResponse extends Response { + body?: SignatureHelpItems; + } + interface SemanticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SemanticDiagnosticsSync; + arguments: SemanticDiagnosticsSyncRequestArgs; + } + interface SemanticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + interface SemanticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + interface SyntacticDiagnosticsSyncRequest extends FileRequest { + command: CommandTypes.SyntacticDiagnosticsSync; + arguments: SyntacticDiagnosticsSyncRequestArgs; + } + interface SyntacticDiagnosticsSyncRequestArgs extends FileRequestArgs { + includeLinePosition?: boolean; + } + interface SyntacticDiagnosticsSyncResponse extends Response { + body?: Diagnostic[] | DiagnosticWithLinePosition[]; + } + interface GeterrForProjectRequestArgs { + file: string; + delay: number; + } + interface GeterrForProjectRequest extends Request { + command: CommandTypes.GeterrForProject; + arguments: GeterrForProjectRequestArgs; + } + interface GeterrRequestArgs { + files: string[]; + delay: number; + } + interface GeterrRequest extends Request { + command: CommandTypes.Geterr; + arguments: GeterrRequestArgs; + } + interface Diagnostic { + start: Location; + end: Location; + text: string; + } + interface DiagnosticEventBody { + file: string; + diagnostics: Diagnostic[]; + } + interface DiagnosticEvent extends Event { + body?: DiagnosticEventBody; + } + interface ConfigFileDiagnosticEventBody { + triggerFile: string; + configFile: string; + diagnostics: Diagnostic[]; + } + interface ConfigFileDiagnosticEvent extends Event { + body?: ConfigFileDiagnosticEventBody; + event: "configFileDiag"; + } + interface ReloadRequestArgs extends FileRequestArgs { + tmpfile: string; + } + interface ReloadRequest extends FileRequest { + command: CommandTypes.Reload; + arguments: ReloadRequestArgs; + } + interface ReloadResponse extends Response { + } + interface SavetoRequestArgs extends FileRequestArgs { + tmpfile: string; + } + interface SavetoRequest extends FileRequest { + command: CommandTypes.Saveto; + arguments: SavetoRequestArgs; + } + interface NavtoRequestArgs extends FileRequestArgs { + searchValue: string; + maxResultCount?: number; + projectFileName?: string; + } + interface NavtoRequest extends FileRequest { + command: CommandTypes.Navto; + arguments: NavtoRequestArgs; + } + interface NavtoItem { + name: string; + kind: string; + matchKind?: string; + isCaseSensitive?: boolean; + kindModifiers?: string; + file: string; + start: Location; + end: Location; + containerName?: string; + containerKind?: string; + } + interface NavtoResponse extends Response { + body?: NavtoItem[]; + } + interface ChangeRequestArgs extends FormatRequestArgs { + insertString?: string; + } + interface ChangeRequest extends FileLocationRequest { + command: CommandTypes.Change; + arguments: ChangeRequestArgs; + } + interface BraceResponse extends Response { + body?: TextSpan[]; + } + interface BraceRequest extends FileLocationRequest { + command: CommandTypes.Brace; + } + interface NavBarRequest extends FileRequest { + command: CommandTypes.NavBar; + } + interface NavTreeRequest extends FileRequest { + command: CommandTypes.NavTree; + } + interface NavigationBarItem { + text: string; + kind: string; + kindModifiers?: string; + spans: TextSpan[]; + childItems?: NavigationBarItem[]; + indent: number; + } + interface NavigationTree { + text: string; + kind: string; + kindModifiers: string; + spans: TextSpan[]; + childItems?: NavigationTree[]; + } + interface NavBarResponse extends Response { + body?: NavigationBarItem[]; + } + interface NavTreeResponse extends Response { + body?: NavigationTree; + } + namespace IndentStyle { + type None = "None"; + type Block = "Block"; + type Smart = "Smart"; + } + type IndentStyle = IndentStyle.None | IndentStyle.Block | IndentStyle.Smart; + interface EditorSettings { + baseIndentSize?: number; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle | ts.IndentStyle; + } + interface FormatCodeSettings extends EditorSettings { + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; + } + interface CompilerOptions { + allowJs?: boolean; + allowSyntheticDefaultImports?: boolean; + allowUnreachableCode?: boolean; + allowUnusedLabels?: boolean; + baseUrl?: string; + charset?: string; + declaration?: boolean; + declarationDir?: string; + disableSizeLimit?: boolean; + emitBOM?: boolean; + emitDecoratorMetadata?: boolean; + experimentalDecorators?: boolean; + forceConsistentCasingInFileNames?: boolean; + inlineSourceMap?: boolean; + inlineSources?: boolean; + isolatedModules?: boolean; + jsx?: JsxEmit | ts.JsxEmit; + lib?: string[]; + locale?: string; + mapRoot?: string; + maxNodeModuleJsDepth?: number; + module?: ModuleKind | ts.ModuleKind; + moduleResolution?: ModuleResolutionKind | ts.ModuleResolutionKind; + newLine?: NewLineKind | ts.NewLineKind; + noEmit?: boolean; + noEmitHelpers?: boolean; + noEmitOnError?: boolean; + noErrorTruncation?: boolean; + noFallthroughCasesInSwitch?: boolean; + noImplicitAny?: boolean; + noImplicitReturns?: boolean; + noImplicitThis?: boolean; + noUnusedLocals?: boolean; + noUnusedParameters?: boolean; + noImplicitUseStrict?: boolean; + noLib?: boolean; + noResolve?: boolean; + out?: string; + outDir?: string; + outFile?: string; + paths?: MapLike; + preserveConstEnums?: boolean; + project?: string; + reactNamespace?: string; + removeComments?: boolean; + rootDir?: string; + rootDirs?: string[]; + skipLibCheck?: boolean; + skipDefaultLibCheck?: boolean; + sourceMap?: boolean; + sourceRoot?: string; + strictNullChecks?: boolean; + suppressExcessPropertyErrors?: boolean; + suppressImplicitAnyIndexErrors?: boolean; + target?: ScriptTarget | ts.ScriptTarget; + traceResolution?: boolean; + types?: string[]; + typeRoots?: string[]; + [option: string]: CompilerOptionsValue | undefined; + } + namespace JsxEmit { + type None = "None"; + type Preserve = "Preserve"; + type React = "React"; + } + type JsxEmit = JsxEmit.None | JsxEmit.Preserve | JsxEmit.React; + namespace ModuleKind { + type None = "None"; + type CommonJS = "CommonJS"; + type AMD = "AMD"; + type UMD = "UMD"; + type System = "System"; + type ES6 = "ES6"; + type ES2015 = "ES2015"; + } + type ModuleKind = ModuleKind.None | ModuleKind.CommonJS | ModuleKind.AMD | ModuleKind.UMD | ModuleKind.System | ModuleKind.ES6 | ModuleKind.ES2015; + namespace ModuleResolutionKind { + type Classic = "Classic"; + type Node = "Node"; + } + type ModuleResolutionKind = ModuleResolutionKind.Classic | ModuleResolutionKind.Node; + namespace NewLineKind { + type Crlf = "Crlf"; + type Lf = "Lf"; + } + type NewLineKind = NewLineKind.Crlf | NewLineKind.Lf; + namespace ScriptTarget { + type ES3 = "ES3"; + type ES5 = "ES5"; + type ES6 = "ES6"; + type ES2015 = "ES2015"; + } + type ScriptTarget = ScriptTarget.ES3 | ScriptTarget.ES5 | ScriptTarget.ES6 | ScriptTarget.ES2015; +} declare namespace ts { interface MapLike { [index: string]: T; @@ -1324,7 +2098,6 @@ declare namespace ts { UseFullyQualifiedType = 128, InFirstTypeArgument = 256, InTypeAlias = 512, - UseTypeAliasValue = 1024, } const enum SymbolFormatFlags { None = 0, @@ -1391,7 +2164,7 @@ declare namespace ts { writeReturnTypeOfSignatureDeclaration(signatureDeclaration: SignatureDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; writeTypeOfExpression(expr: Expression, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; writeBaseConstructorTypeOfClass(node: ClassLikeDeclaration, enclosingDeclaration: Node, flags: TypeFormatFlags, writer: SymbolWriter): void; - isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags): SymbolAccessibilityResult; + isSymbolAccessible(symbol: Symbol, enclosingDeclaration: Node, meaning: SymbolFlags, shouldComputeAliasToMarkVisible: boolean): SymbolAccessibilityResult; isEntityNameVisible(entityName: EntityNameOrEntityNameExpression, enclosingDeclaration: Node): SymbolVisibilityResult; getConstantValue(node: EnumMember | PropertyAccessExpression | ElementAccessExpression): number; getReferencedValueDeclaration(reference: Identifier): Declaration; @@ -1767,10 +2540,7 @@ declare namespace ts { Classic = 1, NodeJs = 2, } - type RootPaths = string[]; - type PathSubstitutions = MapLike; - type TsConfigOnlyOptions = RootPaths | PathSubstitutions; - type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions; + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike; interface CompilerOptions { allowJs?: boolean; allowNonTsExtensions?: boolean; @@ -1820,14 +2590,14 @@ declare namespace ts { out?: string; outDir?: string; outFile?: string; - paths?: PathSubstitutions; + paths?: MapLike; preserveConstEnums?: boolean; project?: string; pretty?: DiagnosticStyle; reactNamespace?: string; removeComments?: boolean; rootDir?: string; - rootDirs?: RootPaths; + rootDirs?: string[]; skipLibCheck?: boolean; skipDefaultLibCheck?: boolean; sourceMap?: boolean; @@ -2147,6 +2917,9 @@ declare namespace ts { Maybe = 1, True = -1, } + const collator: { + compare(a: string, b: string): number; + }; function createMap(template?: MapLike): Map; function createFileMap(keyMapper?: (key: string) => string): FileMap; function toPath(fileName: string, basePath: string, getCanonicalFileName: (path: string) => string): Path; @@ -7486,6 +8259,7 @@ declare namespace ts.NavigateTo { } declare namespace ts.NavigationBar { function getNavigationBarItems(sourceFile: SourceFile): NavigationBarItem[]; + function getNavigationTree(sourceFile: SourceFile): NavigationTree; } declare namespace ts { enum PatternMatchKind { @@ -8137,6 +8911,7 @@ declare namespace ts { getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; getNavigateToItems(searchValue: string, maxResultCount?: number, excludeDts?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; + getNavigationTree(fileName: string): NavigationTree; getOutliningSpans(fileName: string): OutliningSpan[]; getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; @@ -8169,6 +8944,13 @@ declare namespace ts { bolded: boolean; grayed: boolean; } + interface NavigationTree { + text: string; + kind: string; + kindModifiers: string; + spans: TextSpan[]; + childItems?: NavigationTree[]; + } interface TodoCommentDescriptor { text: string; priority: number; @@ -8232,11 +9014,11 @@ declare namespace ts { } interface EditorSettings { baseIndentSize?: number; - indentSize: number; - tabSize: number; - newLineCharacter: string; - convertTabsToSpaces: boolean; - indentStyle: IndentStyle; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle; } enum IndentStyle { None = 0, @@ -8257,17 +9039,17 @@ declare namespace ts { PlaceOpenBraceOnNewLineForControlBlocks: boolean; } interface FormatCodeSettings extends EditorSettings { - insertSpaceAfterCommaDelimiter: boolean; - insertSpaceAfterSemicolonInForStatements: boolean; - insertSpaceBeforeAndAfterBinaryOperators: boolean; - insertSpaceAfterKeywordsInControlFlowStatements: boolean; - insertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean; - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: boolean; - placeOpenBraceOnNewLineForFunctions: boolean; - placeOpenBraceOnNewLineForControlBlocks: boolean; + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; } function toEditorSettings(options: FormatCodeOptions | FormatCodeSettings): FormatCodeSettings; function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; @@ -8580,13 +9362,13 @@ declare namespace ts.server { detachFromProject(project: Project): void; detachAllProjects(): void; getDefaultProject(): Project; - setFormatOptions(formatSettings: protocol.FormatOptions): void; + setFormatOptions(formatSettings: FormatCodeSettings): void; setWatcher(watcher: FileWatcher): void; stopWatcher(): void; getLatestVersion(): string; reload(script: string): void; saveTo(fileName: string): void; - reloadFromFile(): void; + reloadFromFile(tempFileName?: NormalizedPath): void; snap(): LineIndexSnapshot; getLineInfo(line: number): ILineInfo; editContent(start: number, end: number, newText: string): void; @@ -8741,7 +9523,7 @@ declare namespace ts.server { getScriptInfo(uncheckedFileName: string): ScriptInfo; filesToString(): string; setCompilerOptions(compilerOptions: CompilerOptions): void; - reloadScript(filename: NormalizedPath): boolean; + reloadScript(filename: NormalizedPath, tempFileName?: NormalizedPath): boolean; getChangesSinceVersion(lastKnownVersion?: number): ProjectFilesWithTSDiagnostics; getReferencedFiles(path: Path): Path[]; private removeRootFileIfNecessary(info); @@ -8772,9 +9554,7 @@ declare namespace ts.server { setProjectErrors(projectErrors: Diagnostic[]): void; setTypingOptions(newTypingOptions: TypingOptions): void; getTypingOptions(): TypingOptions; - getProjectName(): string & { - __normalizedPathTag: any; - }; + getProjectName(): NormalizedPath; watchConfigFile(callback: (project: ConfiguredProject) => void): void; watchTypeRoots(callback: (project: ConfiguredProject, path: string) => void): void; watchConfigDirectory(callback: (project: ConfiguredProject, path: string) => void): void; @@ -8817,6 +9597,10 @@ declare namespace ts.server { interface ProjectServiceEventHandler { (event: ProjectServiceEvent): void; } + function convertFormatOptions(protocolOptions: protocol.FormatCodeSettings): FormatCodeSettings; + function convertCompilerOptions(protocolOptions: protocol.ExternalProjectCompilerOptions): CompilerOptions & protocol.CompileOnSaveMixin; + function tryConvertScriptKindName(scriptKindName: protocol.ScriptKindName | ScriptKind): ScriptKind; + function convertScriptKindName(scriptKindName: protocol.ScriptKindName): ScriptKind; function combineProjectOutput(projects: Project[], action: (project: Project) => T[], comparer?: (a: T, b: T) => number, areEqual?: (a: T, b: T) => boolean): T[]; interface HostConfiguration { formatCodeOptions: FormatCodeSettings; @@ -8851,6 +9635,7 @@ declare namespace ts.server { constructor(host: ServerHost, logger: Logger, cancellationToken: HostCancellationToken, useSingleInferredProject: boolean, typingsInstaller?: ITypingsInstaller, eventHandler?: ProjectServiceEventHandler); getChangedFiles_TestOnly(): ScriptInfo[]; ensureInferredProjectsUpToDate_TestOnly(): void; + getCompilerOptionsForInferredProjects(): CompilerOptions; updateTypingsForProject(response: SetTypings | InvalidateCachedTypings): void; setCompilerOptionsForInferredProjects(projectCompilerOptions: protocol.ExternalProjectCompilerOptions): void; stopWatchingDirectory(directory: string): void; @@ -8912,67 +9697,69 @@ declare namespace ts.server { project: Project; } namespace CommandNames { - const Brace: string; - const BraceFull: string; - const BraceCompletion: string; - const Change: string; - const Close: string; - const Completions: string; - const CompletionsFull: string; - const CompletionDetails: string; - const CompileOnSaveAffectedFileList: string; - const CompileOnSaveEmitFile: string; - const Configure: string; - const Definition: string; - const DefinitionFull: string; - const Exit: string; - const Format: string; - const Formatonkey: string; - const FormatFull: string; - const FormatonkeyFull: string; - const FormatRangeFull: string; - const Geterr: string; - const GeterrForProject: string; - const SemanticDiagnosticsSync: string; - const SyntacticDiagnosticsSync: string; - const NavBar: string; - const NavBarFull: string; - const Navto: string; - const NavtoFull: string; - const Occurrences: string; - const DocumentHighlights: string; - const DocumentHighlightsFull: string; - const Open: string; - const Quickinfo: string; - const QuickinfoFull: string; - const References: string; - const ReferencesFull: string; - const Reload: string; - const Rename: string; - const RenameInfoFull: string; - const RenameLocationsFull: string; - const Saveto: string; - const SignatureHelp: string; - const SignatureHelpFull: string; - const TypeDefinition: string; - const ProjectInfo: string; - const ReloadProjects: string; - const Unknown: string; - const OpenExternalProject: string; - const OpenExternalProjects: string; - const CloseExternalProject: string; - const SynchronizeProjectList: string; - const ApplyChangedToOpenFiles: string; - const EncodedSemanticClassificationsFull: string; - const Cleanup: string; - const OutliningSpans: string; - const TodoComments: string; - const Indentation: string; - const DocCommentTemplate: string; - const CompilerOptionsDiagnosticsFull: string; - const NameOrDottedNameSpan: string; - const BreakpointStatement: string; - const CompilerOptionsForInferredProjects: string; + const Brace: protocol.CommandTypes.Brace; + const BraceFull: protocol.CommandTypes.BraceFull; + const BraceCompletion: protocol.CommandTypes.BraceCompletion; + const Change: protocol.CommandTypes.Change; + const Close: protocol.CommandTypes.Close; + const Completions: protocol.CommandTypes.Completions; + const CompletionsFull: protocol.CommandTypes.CompletionsFull; + const CompletionDetails: protocol.CommandTypes.CompletionDetails; + const CompileOnSaveAffectedFileList: protocol.CommandTypes.CompileOnSaveAffectedFileList; + const CompileOnSaveEmitFile: protocol.CommandTypes.CompileOnSaveEmitFile; + const Configure: protocol.CommandTypes.Configure; + const Definition: protocol.CommandTypes.Definition; + const DefinitionFull: protocol.CommandTypes.DefinitionFull; + const Exit: protocol.CommandTypes.Exit; + const Format: protocol.CommandTypes.Format; + const Formatonkey: protocol.CommandTypes.Formatonkey; + const FormatFull: protocol.CommandTypes.FormatFull; + const FormatonkeyFull: protocol.CommandTypes.FormatonkeyFull; + const FormatRangeFull: protocol.CommandTypes.FormatRangeFull; + const Geterr: protocol.CommandTypes.Geterr; + const GeterrForProject: protocol.CommandTypes.GeterrForProject; + const SemanticDiagnosticsSync: protocol.CommandTypes.SemanticDiagnosticsSync; + const SyntacticDiagnosticsSync: protocol.CommandTypes.SyntacticDiagnosticsSync; + const NavBar: protocol.CommandTypes.NavBar; + const NavBarFull: protocol.CommandTypes.NavBarFull; + const NavTree: protocol.CommandTypes.NavTree; + const NavTreeFull: protocol.CommandTypes.NavTreeFull; + const Navto: protocol.CommandTypes.Navto; + const NavtoFull: protocol.CommandTypes.NavtoFull; + const Occurrences: protocol.CommandTypes.Occurrences; + const DocumentHighlights: protocol.CommandTypes.DocumentHighlights; + const DocumentHighlightsFull: protocol.CommandTypes.DocumentHighlightsFull; + const Open: protocol.CommandTypes.Open; + const Quickinfo: protocol.CommandTypes.Quickinfo; + const QuickinfoFull: protocol.CommandTypes.QuickinfoFull; + const References: protocol.CommandTypes.References; + const ReferencesFull: protocol.CommandTypes.ReferencesFull; + const Reload: protocol.CommandTypes.Reload; + const Rename: protocol.CommandTypes.Rename; + const RenameInfoFull: protocol.CommandTypes.RenameInfoFull; + const RenameLocationsFull: protocol.CommandTypes.RenameLocationsFull; + const Saveto: protocol.CommandTypes.Saveto; + const SignatureHelp: protocol.CommandTypes.SignatureHelp; + const SignatureHelpFull: protocol.CommandTypes.SignatureHelpFull; + const TypeDefinition: protocol.CommandTypes.TypeDefinition; + const ProjectInfo: protocol.CommandTypes.ProjectInfo; + const ReloadProjects: protocol.CommandTypes.ReloadProjects; + const Unknown: protocol.CommandTypes.Unknown; + const OpenExternalProject: protocol.CommandTypes.OpenExternalProject; + const OpenExternalProjects: protocol.CommandTypes.OpenExternalProjects; + const CloseExternalProject: protocol.CommandTypes.CloseExternalProject; + const SynchronizeProjectList: protocol.CommandTypes.SynchronizeProjectList; + const ApplyChangedToOpenFiles: protocol.CommandTypes.ApplyChangedToOpenFiles; + const EncodedSemanticClassificationsFull: protocol.CommandTypes.EncodedSemanticClassificationsFull; + const Cleanup: protocol.CommandTypes.Cleanup; + const OutliningSpans: protocol.CommandTypes.OutliningSpans; + const TodoComments: protocol.CommandTypes.TodoComments; + const Indentation: protocol.CommandTypes.Indentation; + const DocCommentTemplate: protocol.CommandTypes.DocCommentTemplate; + const CompilerOptionsDiagnosticsFull: protocol.CommandTypes.CompilerOptionsDiagnosticsFull; + const NameOrDottedNameSpan: protocol.CommandTypes.NameOrDottedNameSpan; + const BreakpointStatement: protocol.CommandTypes.BreakpointStatement; + const CompilerOptionsForInferredProjects: protocol.CommandTypes.CompilerOptionsForInferredProjects; } function formatMessage(msg: T, logger: server.Logger, byteLength: (s: string, encoding: string) => number, newLine: string): string; class Session { @@ -8987,8 +9774,9 @@ declare namespace ts.server { private errorTimer; private immediateId; private changeSeq; - constructor(host: ServerHost, cancellationToken: HostCancellationToken, useSingleInferredProject: boolean, typingsInstaller: ITypingsInstaller, byteLength: (buf: string, encoding?: string) => number, hrtime: (start?: number[]) => number[], logger: Logger, canUseEvents: boolean); - private handleEvent(event); + private eventHander; + constructor(host: ServerHost, cancellationToken: HostCancellationToken, useSingleInferredProject: boolean, typingsInstaller: ITypingsInstaller, byteLength: (buf: string, encoding?: string) => number, hrtime: (start?: number[]) => number[], logger: Logger, canUseEvents: boolean, eventHandler?: ProjectServiceEventHandler); + private defaultEventHandler(event); logError(err: Error, cmd: string): void; send(msg: protocol.Message): void; configFileDiagnosticEvent(triggerFile: string, configFile: string, diagnostics: ts.Diagnostic[]): void; @@ -9046,8 +9834,11 @@ declare namespace ts.server { private reload(args, reqSeq); private saveToTmp(fileName, tempFileName); private closeClientFile(fileName); - private decorateNavigationBarItem(project, fileName, items); + private decorateNavigationBarItems(items, scriptInfo); private getNavigationBarItems(args, simplifiedResult); + private decorateNavigationTree(tree, scriptInfo); + private decorateSpan(span, scriptInfo); + private getNavigationTree(args, simplifiedResult); private getNavigateToItems(args, simplifiedResult); private getBraceMatching(args, simplifiedResult); getDiagnosticsForProject(delay: number, fileName: string): void; @@ -9278,6 +10069,7 @@ declare namespace ts { getDocumentHighlights(fileName: string, position: number, filesToSearch: string): string; getNavigateToItems(searchValue: string, maxResultCount?: number): string; getNavigationBarItems(fileName: string): string; + getNavigationTree(fileName: string): string; getOutliningSpans(fileName: string): string; getTodoComments(fileName: string, todoCommentDescriptors: string): string; getBraceMatchingAtPosition(fileName: string, position: number): string; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 4692ec08b05b1..2dfa6f7eef302 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -130,6 +130,7 @@ var ts; var ts; (function (ts) { var createObject = Object.create; + ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; function createMap(template) { var map = createObject(null); map["__"] = undefined; @@ -687,7 +688,7 @@ var ts; if (b === undefined) return 1; if (ignoreCase) { - if (String.prototype.localeCompare) { + if (ts.collator && String.prototype.localeCompare) { var result = a.localeCompare(b, undefined, { usage: "sort", sensitivity: "accent" }); return result < 0 ? -1 : result > 0 ? 1 : 0; } @@ -1715,6 +1716,9 @@ var ts; }, watchDirectory: function (directoryName, callback, recursive) { var options; + if (!directoryExists(directoryName)) { + return; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -5187,10 +5191,12 @@ var ts; } } function getTypingNamesFromJson(jsonPath, filesToWatch) { + if (host.fileExists(jsonPath)) { + filesToWatch.push(jsonPath); + } var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); if (result.config) { var jsonConfig = result.config; - filesToWatch.push(jsonPath); if (jsonConfig.dependencies) { mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); } @@ -5391,43 +5397,44 @@ var ts; throw new Error("LanguageService is disabled"); } server.nullLanguageService = { - cleanupSemanticCache: function () { return throwLanguageServiceIsDisabledError(); }, - getSyntacticDiagnostics: function () { return throwLanguageServiceIsDisabledError(); }, - getSemanticDiagnostics: function () { return throwLanguageServiceIsDisabledError(); }, - getCompilerOptionsDiagnostics: function () { return throwLanguageServiceIsDisabledError(); }, - getSyntacticClassifications: function () { return throwLanguageServiceIsDisabledError(); }, - getEncodedSyntacticClassifications: function () { return throwLanguageServiceIsDisabledError(); }, - getSemanticClassifications: function () { return throwLanguageServiceIsDisabledError(); }, - getEncodedSemanticClassifications: function () { return throwLanguageServiceIsDisabledError(); }, - getCompletionsAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - findReferences: function () { return throwLanguageServiceIsDisabledError(); }, - getCompletionEntryDetails: function () { return throwLanguageServiceIsDisabledError(); }, - getQuickInfoAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - findRenameLocations: function () { return throwLanguageServiceIsDisabledError(); }, - getNameOrDottedNameSpan: function () { return throwLanguageServiceIsDisabledError(); }, - getBreakpointStatementAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getBraceMatchingAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getSignatureHelpItems: function () { return throwLanguageServiceIsDisabledError(); }, - getDefinitionAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getRenameInfo: function () { return throwLanguageServiceIsDisabledError(); }, - getTypeDefinitionAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getReferencesAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getDocumentHighlights: function () { return throwLanguageServiceIsDisabledError(); }, - getOccurrencesAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getNavigateToItems: function () { return throwLanguageServiceIsDisabledError(); }, - getNavigationBarItems: function () { return throwLanguageServiceIsDisabledError(); }, - getOutliningSpans: function () { return throwLanguageServiceIsDisabledError(); }, - getTodoComments: function () { return throwLanguageServiceIsDisabledError(); }, - getIndentationAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getFormattingEditsForRange: function () { return throwLanguageServiceIsDisabledError(); }, - getFormattingEditsForDocument: function () { return throwLanguageServiceIsDisabledError(); }, - getFormattingEditsAfterKeystroke: function () { return throwLanguageServiceIsDisabledError(); }, - getDocCommentTemplateAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - isValidBraceCompletionAtPosition: function () { return throwLanguageServiceIsDisabledError(); }, - getEmitOutput: function () { return throwLanguageServiceIsDisabledError(); }, - getProgram: function () { return throwLanguageServiceIsDisabledError(); }, - getNonBoundSourceFile: function () { return throwLanguageServiceIsDisabledError(); }, - dispose: function () { return throwLanguageServiceIsDisabledError(); } + cleanupSemanticCache: throwLanguageServiceIsDisabledError, + getSyntacticDiagnostics: throwLanguageServiceIsDisabledError, + getSemanticDiagnostics: throwLanguageServiceIsDisabledError, + getCompilerOptionsDiagnostics: throwLanguageServiceIsDisabledError, + getSyntacticClassifications: throwLanguageServiceIsDisabledError, + getEncodedSyntacticClassifications: throwLanguageServiceIsDisabledError, + getSemanticClassifications: throwLanguageServiceIsDisabledError, + getEncodedSemanticClassifications: throwLanguageServiceIsDisabledError, + getCompletionsAtPosition: throwLanguageServiceIsDisabledError, + findReferences: throwLanguageServiceIsDisabledError, + getCompletionEntryDetails: throwLanguageServiceIsDisabledError, + getQuickInfoAtPosition: throwLanguageServiceIsDisabledError, + findRenameLocations: throwLanguageServiceIsDisabledError, + getNameOrDottedNameSpan: throwLanguageServiceIsDisabledError, + getBreakpointStatementAtPosition: throwLanguageServiceIsDisabledError, + getBraceMatchingAtPosition: throwLanguageServiceIsDisabledError, + getSignatureHelpItems: throwLanguageServiceIsDisabledError, + getDefinitionAtPosition: throwLanguageServiceIsDisabledError, + getRenameInfo: throwLanguageServiceIsDisabledError, + getTypeDefinitionAtPosition: throwLanguageServiceIsDisabledError, + getReferencesAtPosition: throwLanguageServiceIsDisabledError, + getDocumentHighlights: throwLanguageServiceIsDisabledError, + getOccurrencesAtPosition: throwLanguageServiceIsDisabledError, + getNavigateToItems: throwLanguageServiceIsDisabledError, + getNavigationBarItems: throwLanguageServiceIsDisabledError, + getNavigationTree: throwLanguageServiceIsDisabledError, + getOutliningSpans: throwLanguageServiceIsDisabledError, + getTodoComments: throwLanguageServiceIsDisabledError, + getIndentationAtPosition: throwLanguageServiceIsDisabledError, + getFormattingEditsForRange: throwLanguageServiceIsDisabledError, + getFormattingEditsForDocument: throwLanguageServiceIsDisabledError, + getFormattingEditsAfterKeystroke: throwLanguageServiceIsDisabledError, + getDocCommentTemplateAtPosition: throwLanguageServiceIsDisabledError, + isValidBraceCompletionAtPosition: throwLanguageServiceIsDisabledError, + getEmitOutput: throwLanguageServiceIsDisabledError, + getProgram: throwLanguageServiceIsDisabledError, + getNonBoundSourceFile: throwLanguageServiceIsDisabledError, + dispose: throwLanguageServiceIsDisabledError }; server.nullLanguageServiceHost = { setCompilationSettings: function () { return undefined; }, @@ -16372,14 +16379,14 @@ var ts; } return false; } - function isSymbolAccessible(symbol, enclosingDeclaration, meaning) { + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { if (symbol && enclosingDeclaration && !(symbol.flags & 262144)) { var initialSymbol = symbol; var meaningToLook = meaning; while (symbol) { var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, false); if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0]); + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); if (!hasAccessibleDeclarations) { return { accessibility: 1, @@ -16420,7 +16427,7 @@ var ts; function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 256 && ts.isExternalOrCommonJsModule(declaration)); } - function hasVisibleDeclarations(symbol) { + function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { return undefined; @@ -16432,14 +16439,16 @@ var ts; if (anyImportSyntax && !(anyImportSyntax.flags & 1) && isDeclarationVisible(anyImportSyntax.parent)) { - getNodeLinks(declaration).isVisible = true; - if (aliasesToMakeVisible) { - if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { - aliasesToMakeVisible.push(anyImportSyntax); + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + if (aliasesToMakeVisible) { + if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { + aliasesToMakeVisible.push(anyImportSyntax); + } + } + else { + aliasesToMakeVisible = [anyImportSyntax]; } - } - else { - aliasesToMakeVisible = [anyImportSyntax]; } return true; } @@ -16462,7 +16471,7 @@ var ts; } var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.text, meaning, undefined, undefined); - return (symbol && hasVisibleDeclarations(symbol)) || { + return (symbol && hasVisibleDeclarations(symbol, true)) || { accessibility: 1, errorSymbolName: ts.getTextOfNode(firstIdentifier), errorNode: firstIdentifier @@ -16679,14 +16688,10 @@ var ts; else if (type.flags & (32768 | 65536 | 16 | 16384)) { buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); } - else if (!(flags & 512) && type.flags & (2097152 | 1572864) && type.aliasSymbol) { - if (type.flags & 2097152 || !(flags & 1024)) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); - } - else { - writeUnionOrIntersectionType(type, nextFlags); - } + else if (!(flags & 512) && ((type.flags & 2097152 && !type.target) || type.flags & 1572864) && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064, false).accessibility === 0) { + var typeArguments = type.aliasTypeArguments; + writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); } else if (type.flags & 1572864) { writeUnionOrIntersectionType(type, nextFlags); @@ -30975,7 +30980,7 @@ var ts; } } function trackSymbol(symbol, enclosingDeclaration, meaning) { - handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning)); + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportInaccessibleThisError() { @@ -30992,7 +30997,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 | 1024, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2, writer); errorNameNode = undefined; } } @@ -31004,7 +31009,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 | 1024, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2, writer); errorNameNode = undefined; } } @@ -31197,7 +31202,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 | 1024, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -31602,7 +31607,7 @@ var ts; } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 | 1024, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2, writer); } function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; @@ -33681,14 +33686,14 @@ var ts; write(" = "); emitObjectLiteralBody(node, firstComputedPropertyIndex); for (var i = firstComputedPropertyIndex, n = properties.length; i < n; i++) { - writeComma(); var property = properties[i]; - emitStart(property); if (property.kind === 149 || property.kind === 150) { var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property !== accessors.firstAccessor) { continue; } + writeComma(); + emitStart(property); write("Object.defineProperty("); emit(tempVar); write(", "); @@ -33729,6 +33734,8 @@ var ts; emitEnd(property); } else { + writeComma(); + emitStart(property); emitLeadingComments(property); emitStart(property.name); emit(tempVar); @@ -33747,8 +33754,8 @@ var ts; else { ts.Debug.fail("ObjectLiteralElement type not accounted for: " + property.kind); } + emitEnd(property); } - emitEnd(property); } writeComma(); emit(tempVar); @@ -34192,7 +34199,11 @@ var ts; if (modulekind === ts.ModuleKind.System || node.kind !== 69 || ts.nodeIsSynthesized(node)) { return false; } - return !exportEquals && exportSpecifiers && node.text in exportSpecifiers; + if (exportEquals || !exportSpecifiers || !(node.text in exportSpecifiers)) { + return false; + } + var declaration = resolver.getReferencedValueDeclaration(node); + return declaration && ts.getEnclosingBlockScopeContainer(declaration).kind === 256; } function emitPrefixUnaryExpression(node) { var isPlusPlusOrMinusMinus = (node.operator === 41 @@ -40506,7 +40517,6 @@ var ts; function getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount, excludeDts) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - var baseSensitivity = { sensitivity: "base" }; ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); var nameToDeclarations = sourceFile.getNamedDeclarations(); @@ -40638,8 +40648,8 @@ var ts; } function compareNavigateToItems(i1, i2) { return i1.matchKind - i2.matchKind || - i1.name.localeCompare(i2.name, undefined, baseSensitivity) || - i1.name.localeCompare(i2.name); + ts.compareStringsCaseInsensitive(i1.name, i2.name) || + ts.compareStrings(i1.name, i2.name); } function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; @@ -40671,6 +40681,13 @@ var ts; return result; } NavigationBar.getNavigationBarItems = getNavigationBarItems; + function getNavigationTree(sourceFile) { + curSourceFile = sourceFile; + var result = convertToTree(rootNavigationBarNode(sourceFile)); + curSourceFile = undefined; + return result; + } + NavigationBar.getNavigationTree = getNavigationTree; var curSourceFile; function nodeText(node) { return node.getText(curSourceFile); @@ -40920,9 +40937,8 @@ var ts; return name1 ? 1 : name2 ? -1 : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); } } - var collator = typeof Intl !== "undefined" && Intl && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; - var localeCompareIsCorrect = collator && collator.compare("a", "B") < 0; - var localeCompareFix = localeCompareIsCorrect ? collator.compare : function (a, b) { + var localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; + var localeCompareFix = localeCompareIsCorrect ? ts.collator.compare : function (a, b) { for (var i = 0; i < Math.min(a.length, b.length); i++) { var chA = a.charAt(i), chB = b.charAt(i); if (chA === "\"" && chB === "'") { @@ -40931,7 +40947,7 @@ var ts; if (chA === "'" && chB === "\"") { return -1; } - var cmp = chA.toLocaleLowerCase().localeCompare(chB.toLocaleLowerCase()); + var cmp = ts.compareStrings(chA.toLocaleLowerCase(), chB.toLocaleLowerCase()); if (cmp !== 0) { return cmp; } @@ -41075,6 +41091,15 @@ var ts; } } var emptyChildItemArray = []; + function convertToTree(n) { + return { + text: getItemName(n.node), + kind: ts.getNodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToTree) + }; + } function convertToTopLevelItem(n) { return { text: getItemName(n.node), @@ -41098,16 +41123,16 @@ var ts; grayed: false }; } - function getSpans(n) { - var spans = [getNodeSpan(n.node)]; - if (n.additionalNodes) { - for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { - var node = _a[_i]; - spans.push(getNodeSpan(node)); - } + } + function getSpans(n) { + var spans = [getNodeSpan(n.node)]; + if (n.additionalNodes) { + for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { + var node = _a[_i]; + spans.push(getNodeSpan(node)); } - return spans; } + return spans; } function getModuleName(moduleDeclaration) { if (ts.isAmbientModule(moduleDeclaration)) { @@ -50365,8 +50390,10 @@ var ts; return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); } function getNavigationBarItems(fileName) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function getNavigationTree(fileName) { + return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName)); } function getSemanticClassifications(fileName, span) { return convertClassifications(getEncodedSemanticClassifications(fileName, span)); @@ -51132,6 +51159,7 @@ var ts; getRenameInfo: getRenameInfo, findRenameLocations: findRenameLocations, getNavigationBarItems: getNavigationBarItems, + getNavigationTree: getNavigationTree, getOutliningSpans: getOutliningSpans, getTodoComments: getTodoComments, getBraceMatchingAtPosition: getBraceMatchingAtPosition, @@ -51645,12 +51673,12 @@ var ts; var snap = this.snap(); this.host.writeFile(fileName, snap.getText(0, snap.getLength())); }; - ScriptInfo.prototype.reloadFromFile = function () { + ScriptInfo.prototype.reloadFromFile = function (tempFileName) { if (this.hasMixedContent) { this.reload(""); } else { - this.svc.reloadFromFile(this.fileName); + this.svc.reloadFromFile(tempFileName || this.fileName); this.markContainingProjectsAsDirty(); } }; @@ -52558,11 +52586,11 @@ var ts; this.markAsDirty(); } }; - Project.prototype.reloadScript = function (filename) { + Project.prototype.reloadScript = function (filename, tempFileName) { var script = this.projectService.getScriptInfoForNormalizedPath(filename); if (script) { ts.Debug.assert(script.isAttached(this)); - script.reloadFromFile(); + script.reloadFromFile(tempFileName); return true; } return false; @@ -52850,6 +52878,66 @@ var ts; var server; (function (server) { server.maxProgramSizeForNonTsFiles = 20 * 1024 * 1024; + function prepareConvertersForEnumLikeCompilerOptions(commandLineOptions) { + var map = ts.createMap(); + for (var _i = 0, commandLineOptions_1 = commandLineOptions; _i < commandLineOptions_1.length; _i++) { + var option = commandLineOptions_1[_i]; + if (typeof option.type === "object") { + var optionMap = option.type; + for (var id in optionMap) { + ts.Debug.assert(typeof optionMap[id] === "number"); + } + map[option.name] = optionMap; + } + } + return map; + } + var compilerOptionConverters = prepareConvertersForEnumLikeCompilerOptions(ts.optionDeclarations); + var indentStyle = ts.createMap({ + "none": ts.IndentStyle.None, + "block": ts.IndentStyle.Block, + "smart": ts.IndentStyle.Smart + }); + function convertFormatOptions(protocolOptions) { + if (typeof protocolOptions.indentStyle === "string") { + protocolOptions.indentStyle = indentStyle[protocolOptions.indentStyle.toLowerCase()]; + ts.Debug.assert(protocolOptions.indentStyle !== undefined); + } + return protocolOptions; + } + server.convertFormatOptions = convertFormatOptions; + function convertCompilerOptions(protocolOptions) { + for (var id in compilerOptionConverters) { + var propertyValue = protocolOptions[id]; + if (typeof propertyValue === "string") { + var mappedValues = compilerOptionConverters[id]; + protocolOptions[id] = mappedValues[propertyValue.toLowerCase()]; + } + } + return protocolOptions; + } + server.convertCompilerOptions = convertCompilerOptions; + function tryConvertScriptKindName(scriptKindName) { + return typeof scriptKindName === "string" + ? convertScriptKindName(scriptKindName) + : scriptKindName; + } + server.tryConvertScriptKindName = tryConvertScriptKindName; + function convertScriptKindName(scriptKindName) { + switch (scriptKindName) { + case "JS": + return 1; + case "JSX": + return 2; + case "TS": + return 3; + case "TSX": + return 4; + default: + return 0; + } + } + server.convertScriptKindName = convertScriptKindName; function combineProjectOutput(projects, action, comparer, areEqual) { var result = projects.reduce(function (previous, current) { return ts.concatenate(previous, action(current)); }, []).sort(comparer); return projects.length > 1 ? ts.deduplicate(result, areEqual) : result; @@ -52862,7 +52950,7 @@ var ts; }; var externalFilePropertyReader = { getFileName: function (x) { return x.fileName; }, - getScriptKind: function (x) { return x.scriptKind; }, + getScriptKind: function (x) { return tryConvertScriptKindName(x.scriptKind); }, hasMixedContent: function (x) { return x.hasMixedContent; } }; function findProjectByName(projectName, projects) { @@ -52947,6 +53035,9 @@ var ts; ProjectService.prototype.ensureInferredProjectsUpToDate_TestOnly = function () { this.ensureInferredProjectsUpToDate(); }; + ProjectService.prototype.getCompilerOptionsForInferredProjects = function () { + return this.compilerOptionsForInferredProjects; + }; ProjectService.prototype.updateTypingsForProject = function (response) { var project = this.findProject(response.projectName); if (!project) { @@ -52963,11 +53054,11 @@ var ts; } }; ProjectService.prototype.setCompilerOptionsForInferredProjects = function (projectCompilerOptions) { - this.compilerOptionsForInferredProjects = projectCompilerOptions; + this.compilerOptionsForInferredProjects = convertCompilerOptions(projectCompilerOptions); this.compileOnSaveForInferredProjects = projectCompilerOptions.compileOnSave; for (var _i = 0, _a = this.inferredProjects; _i < _a.length; _i++) { var proj = _a[_i]; - proj.setCompilerOptions(projectCompilerOptions); + proj.setCompilerOptions(this.compilerOptionsForInferredProjects); proj.compileOnSaveEnabled = projectCompilerOptions.compileOnSave; } this.updateProjectGraphs(this.inferredProjects); @@ -53313,7 +53404,7 @@ var ts; } ts.Debug.assert(!!parsedCommandLine.fileNames); if (parsedCommandLine.fileNames.length === 0) { - errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); + (errors || (errors = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.The_config_file_0_found_doesn_t_contain_any_source_files, configFilename)); return { success: false, configFileErrors: errors }; } var projectOptions = { @@ -53345,18 +53436,20 @@ var ts; return false; }; ProjectService.prototype.createAndAddExternalProject = function (projectFileName, files, options, typingOptions) { - var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, options, !this.exceededTotalSizeLimitForNonTsFiles(options, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); + var compilerOptions = convertCompilerOptions(options); + var project = new server.ExternalProject(projectFileName, this, this.documentRegistry, compilerOptions, !this.exceededTotalSizeLimitForNonTsFiles(compilerOptions, files, externalFilePropertyReader), options.compileOnSave === undefined ? true : options.compileOnSave); this.addFilesToProjectAndUpdateGraph(project, files, externalFilePropertyReader, undefined, typingOptions, undefined); this.externalProjects.push(project); return project; }; ProjectService.prototype.reportConfigFileDiagnostics = function (configFileName, diagnostics, triggerFile) { - if (diagnostics && diagnostics.length > 0) { - this.eventHandler({ - eventName: "configFileDiag", - data: { configFileName: configFileName, diagnostics: diagnostics, triggerFile: triggerFile } - }); + if (!this.eventHandler) { + return; } + this.eventHandler({ + eventName: "configFileDiag", + data: { configFileName: configFileName, diagnostics: diagnostics || [], triggerFile: triggerFile } + }); }; ProjectService.prototype.createAndAddConfiguredProject = function (configFileName, projectOptions, configFileErrors, clientFileName) { var _this = this; @@ -53563,7 +53656,7 @@ var ts; if (args.file) { var info = this.getScriptInfoForNormalizedPath(server.toNormalizedPath(args.file)); if (info) { - info.setFormatOptions(args.formatOptions); + info.setFormatOptions(convertFormatOptions(args.formatOptions)); this.logger.info("Host configuration update for file " + args.file); } } @@ -53573,7 +53666,7 @@ var ts; this.logger.info("Host information " + args.hostInfo); } if (args.formatOptions) { - server.mergeMaps(this.hostConfiguration.formatCodeOptions, args.formatOptions); + server.mergeMaps(this.hostConfiguration.formatCodeOptions, convertFormatOptions(args.formatOptions)); this.logger.info("Format host information updated"); } } @@ -53664,7 +53757,7 @@ var ts; var scriptInfo = this.getScriptInfo(file.fileName); ts.Debug.assert(!scriptInfo || !scriptInfo.isOpen); var normalizedPath = scriptInfo ? scriptInfo.fileName : server.toNormalizedPath(file.fileName); - this.openClientFileWithNormalizedPath(normalizedPath, file.content, file.scriptKind, file.hasMixedContent); + this.openClientFileWithNormalizedPath(normalizedPath, file.content, tryConvertScriptKindName(file.scriptKind), file.hasMixedContent); } } if (changedFiles) { @@ -53749,7 +53842,7 @@ var ts; var exisingConfigFiles; if (externalProject) { if (!tsConfigFiles) { - this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, proj.options, proj.typingOptions, proj.options.compileOnSave, undefined); + this.updateNonInferredProject(externalProject, proj.rootFiles, externalFilePropertyReader, convertCompilerOptions(proj.options), proj.typingOptions, proj.options.compileOnSave, undefined); return; } this.closeExternalProject(proj.projectFileName, true); @@ -53887,6 +53980,8 @@ var ts; CommandNames.SyntacticDiagnosticsSync = "syntacticDiagnosticsSync"; CommandNames.NavBar = "navbar"; CommandNames.NavBarFull = "navbar-full"; + CommandNames.NavTree = "navtree"; + CommandNames.NavTreeFull = "navtree-full"; CommandNames.Navto = "navto"; CommandNames.NavtoFull = "navto-full"; CommandNames.Occurrences = "occurrences"; @@ -53935,7 +54030,7 @@ var ts; } server.formatMessage = formatMessage; var Session = (function () { - function Session(host, cancellationToken, useSingleInferredProject, typingsInstaller, byteLength, hrtime, logger, canUseEvents) { + function Session(host, cancellationToken, useSingleInferredProject, typingsInstaller, byteLength, hrtime, logger, canUseEvents, eventHandler) { var _this = this; this.host = host; this.typingsInstaller = typingsInstaller; @@ -54012,23 +54107,7 @@ var ts; return _this.requiredResponse(_this.getRenameInfo(request.arguments)); }, _a[CommandNames.Open] = function (request) { - var openArgs = request.arguments; - var scriptKind; - switch (openArgs.scriptKindName) { - case "TS": - scriptKind = 3; - break; - case "JS": - scriptKind = 1; - break; - case "TSX": - scriptKind = 4; - break; - case "JSX": - scriptKind = 2; - break; - } - _this.openClientFile(server.toNormalizedPath(openArgs.file), openArgs.fileContent, scriptKind); + _this.openClientFile(server.toNormalizedPath(request.arguments.file), request.arguments.fileContent, server.convertScriptKindName(request.arguments.scriptKindName)); return _this.notRequired(); }, _a[CommandNames.Quickinfo] = function (request) { @@ -54159,6 +54238,12 @@ var ts; _a[CommandNames.NavBarFull] = function (request) { return _this.requiredResponse(_this.getNavigationBarItems(request.arguments, false)); }, + _a[CommandNames.NavTree] = function (request) { + return _this.requiredResponse(_this.getNavigationTree(request.arguments, true)); + }, + _a[CommandNames.NavTreeFull] = function (request) { + return _this.requiredResponse(_this.getNavigationTree(request.arguments, false)); + }, _a[CommandNames.Occurrences] = function (request) { return _this.requiredResponse(_this.getOccurrences(request.arguments)); }, @@ -54169,7 +54254,8 @@ var ts; return _this.requiredResponse(_this.getDocumentHighlights(request.arguments, false)); }, _a[CommandNames.CompilerOptionsForInferredProjects] = function (request) { - return _this.requiredResponse(_this.setCompilerOptionsForInferredProjects(request.arguments)); + _this.setCompilerOptionsForInferredProjects(request.arguments); + return _this.requiredResponse(true); }, _a[CommandNames.ProjectInfo] = function (request) { return _this.requiredResponse(_this.getProjectInfo(request.arguments)); @@ -54180,14 +54266,14 @@ var ts; }, _a )); - var eventHandler = canUseEvents - ? function (event) { return _this.handleEvent(event); } + this.eventHander = canUseEvents + ? eventHandler || (function (event) { return _this.defaultEventHandler(event); }) : undefined; - this.projectService = new server.ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, eventHandler); + this.projectService = new server.ProjectService(host, logger, cancellationToken, useSingleInferredProject, typingsInstaller, this.eventHander); this.gcTimer = new server.GcTimer(host, 7000, logger); var _a; } - Session.prototype.handleEvent = function (event) { + Session.prototype.defaultEventHandler = function (event) { var _this = this; switch (event.eventName) { case "context": @@ -54653,8 +54739,11 @@ var ts; }; Session.prototype.openClientFile = function (fileName, fileContent, scriptKind) { var _a = this.projectService.openClientFileWithNormalizedPath(fileName, fileContent, scriptKind), configFileName = _a.configFileName, configFileErrors = _a.configFileErrors; - if (configFileErrors) { - this.configFileDiagnosticEvent(fileName, configFileName, configFileErrors); + if (this.eventHander) { + this.eventHander({ + eventName: "configFileDiag", + data: { fileName: fileName, configFileName: configFileName, diagnostics: configFileErrors || [] } + }); } }; Session.prototype.getPosition = function (args, scriptInfo) { @@ -54693,7 +54782,7 @@ var ts; Session.prototype.getIndentation = function (args) { var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; var position = this.getPosition(args, project.getScriptInfoForNormalizedPath(file)); - var options = args.options || this.projectService.getFormatCodeOptions(file); + var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); var indentation = project.getLanguageService(false).getIndentationAtPosition(file, position, options); return { position: position, indentation: indentation }; }; @@ -54754,17 +54843,17 @@ var ts; }; Session.prototype.getFormattingEditsForRangeFull = function (args) { var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var options = args.options || this.projectService.getFormatCodeOptions(file); + var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); return project.getLanguageService(false).getFormattingEditsForRange(file, args.position, args.endPosition, options); }; Session.prototype.getFormattingEditsForDocumentFull = function (args) { var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var options = args.options || this.projectService.getFormatCodeOptions(file); + var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); return project.getLanguageService(false).getFormattingEditsForDocument(file, options); }; Session.prototype.getFormattingEditsAfterKeystrokeFull = function (args) { var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; - var options = args.options || this.projectService.getFormatCodeOptions(file); + var options = args.options ? server.convertFormatOptions(args.options) : this.projectService.getFormatCodeOptions(file); return project.getLanguageService(false).getFormattingEditsAfterKeystroke(file, args.position, args.key, options); }; Session.prototype.getFormattingEditsAfterKeystroke = function (args) { @@ -54814,6 +54903,7 @@ var ts; }); }; Session.prototype.getCompletions = function (args, simplifiedResult) { + var _this = this; var prefix = args.prefix || ""; var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); @@ -54826,17 +54916,11 @@ var ts; return completions.entries.reduce(function (result, entry) { if (completions.isMemberCompletion || (entry.name.toLowerCase().indexOf(prefix.toLowerCase()) === 0)) { var name_44 = entry.name, kind = entry.kind, kindModifiers = entry.kindModifiers, sortText = entry.sortText, replacementSpan = entry.replacementSpan; - var convertedSpan = undefined; - if (replacementSpan) { - convertedSpan = { - start: scriptInfo.positionToLineOffset(replacementSpan.start), - end: scriptInfo.positionToLineOffset(replacementSpan.start + replacementSpan.length) - }; - } + var convertedSpan = replacementSpan ? _this.decorateSpan(replacementSpan, scriptInfo) : undefined; result.push({ name: name_44, kind: kind, kindModifiers: kindModifiers, sortText: sortText, replacementSpan: convertedSpan }); } return result; - }, []).sort(function (a, b) { return a.name.localeCompare(b.name); }); + }, []).sort(function (a, b) { return ts.compareStrings(a.name, b.name); }); } else { return completions; @@ -54936,10 +55020,11 @@ var ts; }; Session.prototype.reload = function (args, reqSeq) { var file = server.toNormalizedPath(args.file); + var tempFileName = args.tmpfile && server.toNormalizedPath(args.tmpfile); var project = this.projectService.getDefaultProjectForFile(file, true); if (project) { this.changeSeq++; - if (project.reloadScript(file)) { + if (project.reloadScript(file, tempFileName)) { this.output(undefined, CommandNames.Reload, reqSeq); } } @@ -54957,33 +55042,50 @@ var ts; var file = ts.normalizePath(fileName); this.projectService.closeClientFile(file); }; - Session.prototype.decorateNavigationBarItem = function (project, fileName, items) { + Session.prototype.decorateNavigationBarItems = function (items, scriptInfo) { var _this = this; - if (!items) { - return undefined; - } - var scriptInfo = project.getScriptInfoForNormalizedPath(fileName); - return items.map(function (item) { return ({ + return ts.map(items, function (item) { return ({ text: item.text, kind: item.kind, kindModifiers: item.kindModifiers, - spans: item.spans.map(function (span) { return ({ - start: scriptInfo.positionToLineOffset(span.start), - end: scriptInfo.positionToLineOffset(ts.textSpanEnd(span)) - }); }), - childItems: _this.decorateNavigationBarItem(project, fileName, item.childItems), + spans: item.spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }), + childItems: _this.decorateNavigationBarItems(item.childItems, scriptInfo), indent: item.indent }); }); }; Session.prototype.getNavigationBarItems = function (args, simplifiedResult) { var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; - var items = project.getLanguageService().getNavigationBarItems(file); - if (!items) { - return undefined; - } - return simplifiedResult - ? this.decorateNavigationBarItem(project, file, items) - : items; + var items = project.getLanguageService(false).getNavigationBarItems(file); + return !items + ? undefined + : simplifiedResult + ? this.decorateNavigationBarItems(items, project.getScriptInfoForNormalizedPath(file)) + : items; + }; + Session.prototype.decorateNavigationTree = function (tree, scriptInfo) { + var _this = this; + return { + text: tree.text, + kind: tree.kind, + kindModifiers: tree.kindModifiers, + spans: tree.spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }), + childItems: ts.map(tree.childItems, function (item) { return _this.decorateNavigationTree(item, scriptInfo); }) + }; + }; + Session.prototype.decorateSpan = function (span, scriptInfo) { + return { + start: scriptInfo.positionToLineOffset(span.start), + end: scriptInfo.positionToLineOffset(ts.textSpanEnd(span)) + }; + }; + Session.prototype.getNavigationTree = function (args, simplifiedResult) { + var _a = this.getFileAndProject(args), file = _a.file, project = _a.project; + var tree = project.getLanguageService(false).getNavigationTree(file); + return !tree + ? undefined + : simplifiedResult + ? this.decorateNavigationTree(tree, project.getScriptInfoForNormalizedPath(file)) + : tree; }; Session.prototype.getNavigateToItems = function (args, simplifiedResult) { var projects = this.getProjects(args); @@ -55051,22 +55153,16 @@ var ts; } }; Session.prototype.getBraceMatching = function (args, simplifiedResult) { + var _this = this; var _a = this.getFileAndProjectWithoutRefreshingInferredProjects(args), file = _a.file, project = _a.project; var scriptInfo = project.getScriptInfoForNormalizedPath(file); var position = this.getPosition(args, scriptInfo); var spans = project.getLanguageService(false).getBraceMatchingAtPosition(file, position); - if (!spans) { - return undefined; - } - if (simplifiedResult) { - return spans.map(function (span) { return ({ - start: scriptInfo.positionToLineOffset(span.start), - end: scriptInfo.positionToLineOffset(span.start + span.length) - }); }); - } - else { - return spans; - } + return !spans + ? undefined + : simplifiedResult + ? spans.map(function (span) { return _this.decorateSpan(span, scriptInfo); }) + : spans; }; Session.prototype.getDiagnosticsForProject = function (delay, fileName) { var _this = this; @@ -56463,6 +56559,10 @@ var ts; var _this = this; return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; + LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); }); + }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 712e95ce7659e..ab4ffc4e48d73 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -1330,7 +1330,6 @@ declare namespace ts { UseFullyQualifiedType = 128, InFirstTypeArgument = 256, InTypeAlias = 512, - UseTypeAliasValue = 1024, } enum SymbolFormatFlags { None = 0, @@ -1570,10 +1569,7 @@ declare namespace ts { Classic = 1, NodeJs = 2, } - type RootPaths = string[]; - type PathSubstitutions = MapLike; - type TsConfigOnlyOptions = RootPaths | PathSubstitutions; - type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions; + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike; interface CompilerOptions { allowJs?: boolean; allowSyntheticDefaultImports?: boolean; @@ -1615,13 +1611,13 @@ declare namespace ts { out?: string; outDir?: string; outFile?: string; - paths?: PathSubstitutions; + paths?: MapLike; preserveConstEnums?: boolean; project?: string; reactNamespace?: string; removeComments?: boolean; rootDir?: string; - rootDirs?: RootPaths; + rootDirs?: string[]; skipLibCheck?: boolean; skipDefaultLibCheck?: boolean; sourceMap?: boolean; @@ -2119,6 +2115,7 @@ declare namespace ts { getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; getNavigateToItems(searchValue: string, maxResultCount?: number, excludeDts?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; + getNavigationTree(fileName: string): NavigationTree; getOutliningSpans(fileName: string): OutliningSpan[]; getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; @@ -2140,6 +2137,12 @@ declare namespace ts { textSpan: TextSpan; classificationType: string; } + /** + * Navigation bar interface designed for visual studio's dual-column layout. + * This does not form a proper tree. + * The navbar is returned as a list of top-level items, each of which has a list of child items. + * Child items always have an empty array for their `childItems`. + */ interface NavigationBarItem { text: string; kind: string; @@ -2150,6 +2153,25 @@ declare namespace ts { bolded: boolean; grayed: boolean; } + /** + * Node in a tree of nested declarations in a file. + * The top node is always a script or module node. + */ + interface NavigationTree { + /** Name of the declaration, or a short description, e.g. "". */ + text: string; + /** A ScriptElementKind */ + kind: string; + /** ScriptElementKindModifier separated by commas, e.g. "public,abstract" */ + kindModifiers: string; + /** + * Spans of the nodes that generated this declaration. + * There will be more than one if this is the result of merging. + */ + spans: TextSpan[]; + /** Present if non-empty */ + childItems?: NavigationTree[]; + } interface TodoCommentDescriptor { text: string; priority: number; @@ -2214,11 +2236,11 @@ declare namespace ts { } interface EditorSettings { baseIndentSize?: number; - indentSize: number; - tabSize: number; - newLineCharacter: string; - convertTabsToSpaces: boolean; - indentStyle: IndentStyle; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle; } enum IndentStyle { None = 0, @@ -2239,17 +2261,17 @@ declare namespace ts { PlaceOpenBraceOnNewLineForControlBlocks: boolean; } interface FormatCodeSettings extends EditorSettings { - insertSpaceAfterCommaDelimiter: boolean; - insertSpaceAfterSemicolonInForStatements: boolean; - insertSpaceBeforeAndAfterBinaryOperators: boolean; - insertSpaceAfterKeywordsInControlFlowStatements: boolean; - insertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean; - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: boolean; - placeOpenBraceOnNewLineForFunctions: boolean; - placeOpenBraceOnNewLineForControlBlocks: boolean; + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; } function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; interface DefinitionInfo { diff --git a/lib/typescript.js b/lib/typescript.js index 1ce53ee9023a6..2fa3e8a97c15e 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -480,7 +480,6 @@ var ts; TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 128] = "UseFullyQualifiedType"; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 256] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 512] = "InTypeAlias"; - TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 1024] = "UseTypeAliasValue"; })(ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var TypeFormatFlags = ts.TypeFormatFlags; (function (SymbolFormatFlags) { @@ -1024,6 +1023,8 @@ var ts; })(ts.Ternary || (ts.Ternary = {})); var Ternary = ts.Ternary; var createObject = Object.create; + // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. + ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; function createMap(template) { var map = createObject(null); // tslint:disable-line:no-null-keyword // Using 'delete' on an object causes V8 to put the object in dictionary mode. @@ -1692,7 +1693,8 @@ var ts; if (b === undefined) return 1 /* GreaterThan */; if (ignoreCase) { - if (String.prototype.localeCompare) { + if (ts.collator && String.prototype.localeCompare) { + // accent means a ≠ b, a ≠ á, a = A var result = a.localeCompare(b, /*locales*/ undefined, { usage: "sort", sensitivity: "accent" }); return result < 0 ? -1 /* LessThan */ : result > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; } @@ -2867,6 +2869,9 @@ var ts; // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) var options; + if (!directoryExists(directoryName)) { + return; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -18689,7 +18694,15 @@ var ts; } return false; } - function isSymbolAccessible(symbol, enclosingDeclaration, meaning) { + /** + * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested + * + * @param symbol a Symbol to check if accessible + * @param enclosingDeclaration a Node containing reference to the symbol + * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible + * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible + */ + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { if (symbol && enclosingDeclaration && !(symbol.flags & 262144 /* TypeParameter */)) { var initialSymbol = symbol; var meaningToLook = meaning; @@ -18697,7 +18710,7 @@ var ts; // Symbol is accessible if it by itself is accessible var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0]); + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); if (!hasAccessibleDeclarations) { return { accessibility: 1 /* NotAccessible */, @@ -18754,7 +18767,7 @@ var ts; function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 256 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } - function hasVisibleDeclarations(symbol) { + function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { return undefined; @@ -18768,14 +18781,19 @@ var ts; if (anyImportSyntax && !(anyImportSyntax.flags & 1 /* Export */) && isDeclarationVisible(anyImportSyntax.parent)) { - getNodeLinks(declaration).isVisible = true; - if (aliasesToMakeVisible) { - if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { - aliasesToMakeVisible.push(anyImportSyntax); + // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types, + // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time + // since we will do the emitting later in trackSymbol. + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + if (aliasesToMakeVisible) { + if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { + aliasesToMakeVisible.push(anyImportSyntax); + } + } + else { + aliasesToMakeVisible = [anyImportSyntax]; } - } - else { - aliasesToMakeVisible = [anyImportSyntax]; } return true; } @@ -18805,7 +18823,7 @@ var ts; var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.text, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); // Verify if the symbol is accessible - return (symbol && hasVisibleDeclarations(symbol)) || { + return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { accessibility: 1 /* NotAccessible */, errorSymbolName: ts.getTextOfNode(firstIdentifier), errorNode: firstIdentifier @@ -19052,14 +19070,16 @@ var ts; // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); } - else if (!(flags & 512 /* InTypeAlias */) && type.flags & (2097152 /* Anonymous */ | 1572864 /* UnionOrIntersection */) && type.aliasSymbol) { - if (type.flags & 2097152 /* Anonymous */ || !(flags & 1024 /* UseTypeAliasValue */)) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); - } - else { - writeUnionOrIntersectionType(type, nextFlags); - } + else if (!(flags & 512 /* InTypeAlias */) && ((type.flags & 2097152 /* Anonymous */ && !type.target) || type.flags & 1572864 /* UnionOrIntersection */) && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { + // We emit inferred type as type-alias at the current location if all the following is true + // the input type is has alias symbol that is accessible + // the input type is a union, intersection or anonymous type that is fully instantiated (if not we want to keep dive into) + // e.g.: export type Bar = () => [X, Y]; + // export type Foo = Bar; + // export const y = (x: Foo) => 1 // we want to emit as ...x: () => [any, string]) + var typeArguments = type.aliasTypeArguments; + writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); } else if (type.flags & 1572864 /* UnionOrIntersection */) { writeUnionOrIntersectionType(type, nextFlags); @@ -35905,7 +35925,7 @@ var ts; } } function trackSymbol(symbol, enclosingDeclaration, meaning) { - handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning)); + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportInaccessibleThisError() { @@ -35923,7 +35943,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); errorNameNode = undefined; } } @@ -35936,7 +35956,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); errorNameNode = undefined; } } @@ -36138,7 +36158,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -36559,7 +36579,7 @@ var ts; } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); } function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; @@ -38898,15 +38918,15 @@ var ts; write(" = "); emitObjectLiteralBody(node, firstComputedPropertyIndex); for (var i = firstComputedPropertyIndex, n = properties.length; i < n; i++) { - writeComma(); var property = properties[i]; - emitStart(property); if (property.kind === 149 /* GetAccessor */ || property.kind === 150 /* SetAccessor */) { // TODO (drosen): Reconcile with 'emitMemberFunctions'. var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property !== accessors.firstAccessor) { continue; } + writeComma(); + emitStart(property); write("Object.defineProperty("); emit(tempVar); write(", "); @@ -38947,6 +38967,8 @@ var ts; emitEnd(property); } else { + writeComma(); + emitStart(property); emitLeadingComments(property); emitStart(property.name); emit(tempVar); @@ -38965,8 +38987,8 @@ var ts; else { ts.Debug.fail("ObjectLiteralElement type not accounted for: " + property.kind); } + emitEnd(property); } - emitEnd(property); } writeComma(); emit(tempVar); @@ -39498,7 +39520,12 @@ var ts; if (modulekind === ts.ModuleKind.System || node.kind !== 69 /* Identifier */ || ts.nodeIsSynthesized(node)) { return false; } - return !exportEquals && exportSpecifiers && node.text in exportSpecifiers; + if (exportEquals || !exportSpecifiers || !(node.text in exportSpecifiers)) { + return false; + } + // check that referenced declaration is declared on source file level + var declaration = resolver.getReferencedValueDeclaration(node); + return declaration && ts.getEnclosingBlockScopeContainer(declaration).kind === 256 /* SourceFile */; } function emitPrefixUnaryExpression(node) { var isPlusPlusOrMinusMinus = (node.operator === 41 /* PlusPlusToken */ @@ -47554,8 +47581,6 @@ var ts; function getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount, excludeDts) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - // This means "compare in a case insensitive manner." - var baseSensitivity = { sensitivity: "base" }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); @@ -47705,8 +47730,8 @@ var ts; // We first sort case insensitively. So "Aaa" will come before "bar". // Then we sort case sensitively, so "aaa" will come before "Aaa". return i1.matchKind - i2.matchKind || - i1.name.localeCompare(i2.name, undefined, baseSensitivity) || - i1.name.localeCompare(i2.name); + ts.compareStringsCaseInsensitive(i1.name, i2.name) || + ts.compareStrings(i1.name, i2.name); } function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; @@ -47741,6 +47766,13 @@ var ts; return result; } NavigationBar.getNavigationBarItems = getNavigationBarItems; + function getNavigationTree(sourceFile) { + curSourceFile = sourceFile; + var result = convertToTree(rootNavigationBarNode(sourceFile)); + curSourceFile = undefined; + return result; + } + NavigationBar.getNavigationTree = getNavigationTree; // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`. var curSourceFile; function nodeText(node) { @@ -48018,11 +48050,9 @@ var ts; return name1 ? 1 : name2 ? -1 : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); } } - // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. - var collator = typeof Intl !== "undefined" && Intl && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; // Intl is missing in Safari, and node 0.10 treats "a" as greater than "B". - var localeCompareIsCorrect = collator && collator.compare("a", "B") < 0; - var localeCompareFix = localeCompareIsCorrect ? collator.compare : function (a, b) { + var localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; + var localeCompareFix = localeCompareIsCorrect ? ts.collator.compare : function (a, b) { // This isn't perfect, but it passes all of our tests. for (var i = 0; i < Math.min(a.length, b.length); i++) { var chA = a.charAt(i), chB = b.charAt(i); @@ -48032,7 +48062,7 @@ var ts; if (chA === "'" && chB === "\"") { return -1; } - var cmp = chA.toLocaleLowerCase().localeCompare(chB.toLocaleLowerCase()); + var cmp = ts.compareStrings(chA.toLocaleLowerCase(), chB.toLocaleLowerCase()); if (cmp !== 0) { return cmp; } @@ -48183,6 +48213,15 @@ var ts; } // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance. var emptyChildItemArray = []; + function convertToTree(n) { + return { + text: getItemName(n.node), + kind: ts.getNodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToTree) + }; + } function convertToTopLevelItem(n) { return { text: getItemName(n.node), @@ -48206,16 +48245,16 @@ var ts; grayed: false }; } - function getSpans(n) { - var spans = [getNodeSpan(n.node)]; - if (n.additionalNodes) { - for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { - var node = _a[_i]; - spans.push(getNodeSpan(node)); - } + } + function getSpans(n) { + var spans = [getNodeSpan(n.node)]; + if (n.additionalNodes) { + for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { + var node = _a[_i]; + spans.push(getNodeSpan(node)); } - return spans; } + return spans; } function getModuleName(moduleDeclaration) { // We want to maintain quotation marks. @@ -50417,10 +50456,12 @@ var ts; * Get the typing info from common package manager json files like package.json or bower.json */ function getTypingNamesFromJson(jsonPath, filesToWatch) { + if (host.fileExists(jsonPath)) { + filesToWatch.push(jsonPath); + } var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); if (result.config) { var jsonConfig = result.config; - filesToWatch.push(jsonPath); if (jsonConfig.dependencies) { mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); } @@ -59516,8 +59557,10 @@ var ts; return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); } function getNavigationBarItems(fileName) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function getNavigationTree(fileName) { + return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName)); } function getSemanticClassifications(fileName, span) { return convertClassifications(getEncodedSemanticClassifications(fileName, span)); @@ -60461,6 +60504,7 @@ var ts; getRenameInfo: getRenameInfo, findRenameLocations: findRenameLocations, getNavigationBarItems: getNavigationBarItems, + getNavigationTree: getNavigationTree, getOutliningSpans: getOutliningSpans, getTodoComments: getTodoComments, getBraceMatchingAtPosition: getBraceMatchingAtPosition, @@ -62100,6 +62144,10 @@ var ts; var _this = this; return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; + LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); }); + }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 65cb83be7877d..5aa16737b6759 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -1330,7 +1330,6 @@ declare namespace ts { UseFullyQualifiedType = 128, InFirstTypeArgument = 256, InTypeAlias = 512, - UseTypeAliasValue = 1024, } enum SymbolFormatFlags { None = 0, @@ -1570,10 +1569,7 @@ declare namespace ts { Classic = 1, NodeJs = 2, } - type RootPaths = string[]; - type PathSubstitutions = MapLike; - type TsConfigOnlyOptions = RootPaths | PathSubstitutions; - type CompilerOptionsValue = string | number | boolean | (string | number)[] | TsConfigOnlyOptions; + type CompilerOptionsValue = string | number | boolean | (string | number)[] | string[] | MapLike; interface CompilerOptions { allowJs?: boolean; allowSyntheticDefaultImports?: boolean; @@ -1615,13 +1611,13 @@ declare namespace ts { out?: string; outDir?: string; outFile?: string; - paths?: PathSubstitutions; + paths?: MapLike; preserveConstEnums?: boolean; project?: string; reactNamespace?: string; removeComments?: boolean; rootDir?: string; - rootDirs?: RootPaths; + rootDirs?: string[]; skipLibCheck?: boolean; skipDefaultLibCheck?: boolean; sourceMap?: boolean; @@ -2119,6 +2115,7 @@ declare namespace ts { getOccurrencesAtPosition(fileName: string, position: number): ReferenceEntry[]; getNavigateToItems(searchValue: string, maxResultCount?: number, excludeDts?: boolean): NavigateToItem[]; getNavigationBarItems(fileName: string): NavigationBarItem[]; + getNavigationTree(fileName: string): NavigationTree; getOutliningSpans(fileName: string): OutliningSpan[]; getTodoComments(fileName: string, descriptors: TodoCommentDescriptor[]): TodoComment[]; getBraceMatchingAtPosition(fileName: string, position: number): TextSpan[]; @@ -2140,6 +2137,12 @@ declare namespace ts { textSpan: TextSpan; classificationType: string; } + /** + * Navigation bar interface designed for visual studio's dual-column layout. + * This does not form a proper tree. + * The navbar is returned as a list of top-level items, each of which has a list of child items. + * Child items always have an empty array for their `childItems`. + */ interface NavigationBarItem { text: string; kind: string; @@ -2150,6 +2153,25 @@ declare namespace ts { bolded: boolean; grayed: boolean; } + /** + * Node in a tree of nested declarations in a file. + * The top node is always a script or module node. + */ + interface NavigationTree { + /** Name of the declaration, or a short description, e.g. "". */ + text: string; + /** A ScriptElementKind */ + kind: string; + /** ScriptElementKindModifier separated by commas, e.g. "public,abstract" */ + kindModifiers: string; + /** + * Spans of the nodes that generated this declaration. + * There will be more than one if this is the result of merging. + */ + spans: TextSpan[]; + /** Present if non-empty */ + childItems?: NavigationTree[]; + } interface TodoCommentDescriptor { text: string; priority: number; @@ -2214,11 +2236,11 @@ declare namespace ts { } interface EditorSettings { baseIndentSize?: number; - indentSize: number; - tabSize: number; - newLineCharacter: string; - convertTabsToSpaces: boolean; - indentStyle: IndentStyle; + indentSize?: number; + tabSize?: number; + newLineCharacter?: string; + convertTabsToSpaces?: boolean; + indentStyle?: IndentStyle; } enum IndentStyle { None = 0, @@ -2239,17 +2261,17 @@ declare namespace ts { PlaceOpenBraceOnNewLineForControlBlocks: boolean; } interface FormatCodeSettings extends EditorSettings { - insertSpaceAfterCommaDelimiter: boolean; - insertSpaceAfterSemicolonInForStatements: boolean; - insertSpaceBeforeAndAfterBinaryOperators: boolean; - insertSpaceAfterKeywordsInControlFlowStatements: boolean; - insertSpaceAfterFunctionKeywordForAnonymousFunctions: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: boolean; - insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: boolean; - insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: boolean; - insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces: boolean; - placeOpenBraceOnNewLineForFunctions: boolean; - placeOpenBraceOnNewLineForControlBlocks: boolean; + insertSpaceAfterCommaDelimiter?: boolean; + insertSpaceAfterSemicolonInForStatements?: boolean; + insertSpaceBeforeAndAfterBinaryOperators?: boolean; + insertSpaceAfterKeywordsInControlFlowStatements?: boolean; + insertSpaceAfterFunctionKeywordForAnonymousFunctions?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis?: boolean; + insertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets?: boolean; + insertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces?: boolean; + insertSpaceAfterOpeningAndBeforeClosingJsxExpressionBraces?: boolean; + placeOpenBraceOnNewLineForFunctions?: boolean; + placeOpenBraceOnNewLineForControlBlocks?: boolean; } function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; interface DefinitionInfo { diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 1ce53ee9023a6..2fa3e8a97c15e 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -480,7 +480,6 @@ var ts; TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 128] = "UseFullyQualifiedType"; TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 256] = "InFirstTypeArgument"; TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 512] = "InTypeAlias"; - TypeFormatFlags[TypeFormatFlags["UseTypeAliasValue"] = 1024] = "UseTypeAliasValue"; })(ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var TypeFormatFlags = ts.TypeFormatFlags; (function (SymbolFormatFlags) { @@ -1024,6 +1023,8 @@ var ts; })(ts.Ternary || (ts.Ternary = {})); var Ternary = ts.Ternary; var createObject = Object.create; + // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. + ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; function createMap(template) { var map = createObject(null); // tslint:disable-line:no-null-keyword // Using 'delete' on an object causes V8 to put the object in dictionary mode. @@ -1692,7 +1693,8 @@ var ts; if (b === undefined) return 1 /* GreaterThan */; if (ignoreCase) { - if (String.prototype.localeCompare) { + if (ts.collator && String.prototype.localeCompare) { + // accent means a ≠ b, a ≠ á, a = A var result = a.localeCompare(b, /*locales*/ undefined, { usage: "sort", sensitivity: "accent" }); return result < 0 ? -1 /* LessThan */ : result > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */; } @@ -2867,6 +2869,9 @@ var ts; // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643) var options; + if (!directoryExists(directoryName)) { + return; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -18689,7 +18694,15 @@ var ts; } return false; } - function isSymbolAccessible(symbol, enclosingDeclaration, meaning) { + /** + * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested + * + * @param symbol a Symbol to check if accessible + * @param enclosingDeclaration a Node containing reference to the symbol + * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible + * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible + */ + function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { if (symbol && enclosingDeclaration && !(symbol.flags & 262144 /* TypeParameter */)) { var initialSymbol = symbol; var meaningToLook = meaning; @@ -18697,7 +18710,7 @@ var ts; // Symbol is accessible if it by itself is accessible var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaningToLook, /*useOnlyExternalAliasing*/ false); if (accessibleSymbolChain) { - var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0]); + var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible); if (!hasAccessibleDeclarations) { return { accessibility: 1 /* NotAccessible */, @@ -18754,7 +18767,7 @@ var ts; function hasExternalModuleSymbol(declaration) { return ts.isAmbientModule(declaration) || (declaration.kind === 256 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration)); } - function hasVisibleDeclarations(symbol) { + function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) { var aliasesToMakeVisible; if (ts.forEach(symbol.declarations, function (declaration) { return !getIsDeclarationVisible(declaration); })) { return undefined; @@ -18768,14 +18781,19 @@ var ts; if (anyImportSyntax && !(anyImportSyntax.flags & 1 /* Export */) && isDeclarationVisible(anyImportSyntax.parent)) { - getNodeLinks(declaration).isVisible = true; - if (aliasesToMakeVisible) { - if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { - aliasesToMakeVisible.push(anyImportSyntax); + // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types, + // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time + // since we will do the emitting later in trackSymbol. + if (shouldComputeAliasToMakeVisible) { + getNodeLinks(declaration).isVisible = true; + if (aliasesToMakeVisible) { + if (!ts.contains(aliasesToMakeVisible, anyImportSyntax)) { + aliasesToMakeVisible.push(anyImportSyntax); + } + } + else { + aliasesToMakeVisible = [anyImportSyntax]; } - } - else { - aliasesToMakeVisible = [anyImportSyntax]; } return true; } @@ -18805,7 +18823,7 @@ var ts; var firstIdentifier = getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.text, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined); // Verify if the symbol is accessible - return (symbol && hasVisibleDeclarations(symbol)) || { + return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { accessibility: 1 /* NotAccessible */, errorSymbolName: ts.getTextOfNode(firstIdentifier), errorNode: firstIdentifier @@ -19052,14 +19070,16 @@ var ts; // The specified symbol flags need to be reinterpreted as type flags buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); } - else if (!(flags & 512 /* InTypeAlias */) && type.flags & (2097152 /* Anonymous */ | 1572864 /* UnionOrIntersection */) && type.aliasSymbol) { - if (type.flags & 2097152 /* Anonymous */ || !(flags & 1024 /* UseTypeAliasValue */)) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); - } - else { - writeUnionOrIntersectionType(type, nextFlags); - } + else if (!(flags & 512 /* InTypeAlias */) && ((type.flags & 2097152 /* Anonymous */ && !type.target) || type.flags & 1572864 /* UnionOrIntersection */) && type.aliasSymbol && + isSymbolAccessible(type.aliasSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility === 0 /* Accessible */) { + // We emit inferred type as type-alias at the current location if all the following is true + // the input type is has alias symbol that is accessible + // the input type is a union, intersection or anonymous type that is fully instantiated (if not we want to keep dive into) + // e.g.: export type Bar = () => [X, Y]; + // export type Foo = Bar; + // export const y = (x: Foo) => 1 // we want to emit as ...x: () => [any, string]) + var typeArguments = type.aliasTypeArguments; + writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, typeArguments ? typeArguments.length : 0, nextFlags); } else if (type.flags & 1572864 /* UnionOrIntersection */) { writeUnionOrIntersectionType(type, nextFlags); @@ -35905,7 +35925,7 @@ var ts; } } function trackSymbol(symbol, enclosingDeclaration, meaning) { - handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning)); + handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true)); recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning)); } function reportInaccessibleThisError() { @@ -35923,7 +35943,7 @@ var ts; } else { errorNameNode = declaration.name; - resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); errorNameNode = undefined; } } @@ -35936,7 +35956,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); errorNameNode = undefined; } } @@ -36138,7 +36158,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = getDefaultExportAccessibilityDiagnostic; - resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + resolver.writeTypeOfExpression(node.expression, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); write(";"); writeLine(); write(node.isExportEquals ? "export = " : "export default "); @@ -36559,7 +36579,7 @@ var ts; } else { writer.getSymbolAccessibilityDiagnostic = getHeritageClauseVisibilityError; - resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */ | 1024 /* UseTypeAliasValue */, writer); + resolver.writeBaseConstructorTypeOfClass(enclosingDeclaration, enclosingDeclaration, 2 /* UseTypeOfFunction */, writer); } function getHeritageClauseVisibilityError(symbolAccessibilityResult) { var diagnosticMessage; @@ -38898,15 +38918,15 @@ var ts; write(" = "); emitObjectLiteralBody(node, firstComputedPropertyIndex); for (var i = firstComputedPropertyIndex, n = properties.length; i < n; i++) { - writeComma(); var property = properties[i]; - emitStart(property); if (property.kind === 149 /* GetAccessor */ || property.kind === 150 /* SetAccessor */) { // TODO (drosen): Reconcile with 'emitMemberFunctions'. var accessors = ts.getAllAccessorDeclarations(node.properties, property); if (property !== accessors.firstAccessor) { continue; } + writeComma(); + emitStart(property); write("Object.defineProperty("); emit(tempVar); write(", "); @@ -38947,6 +38967,8 @@ var ts; emitEnd(property); } else { + writeComma(); + emitStart(property); emitLeadingComments(property); emitStart(property.name); emit(tempVar); @@ -38965,8 +38987,8 @@ var ts; else { ts.Debug.fail("ObjectLiteralElement type not accounted for: " + property.kind); } + emitEnd(property); } - emitEnd(property); } writeComma(); emit(tempVar); @@ -39498,7 +39520,12 @@ var ts; if (modulekind === ts.ModuleKind.System || node.kind !== 69 /* Identifier */ || ts.nodeIsSynthesized(node)) { return false; } - return !exportEquals && exportSpecifiers && node.text in exportSpecifiers; + if (exportEquals || !exportSpecifiers || !(node.text in exportSpecifiers)) { + return false; + } + // check that referenced declaration is declared on source file level + var declaration = resolver.getReferencedValueDeclaration(node); + return declaration && ts.getEnclosingBlockScopeContainer(declaration).kind === 256 /* SourceFile */; } function emitPrefixUnaryExpression(node) { var isPlusPlusOrMinusMinus = (node.operator === 41 /* PlusPlusToken */ @@ -47554,8 +47581,6 @@ var ts; function getNavigateToItems(program, checker, cancellationToken, searchValue, maxResultCount, excludeDts) { var patternMatcher = ts.createPatternMatcher(searchValue); var rawItems = []; - // This means "compare in a case insensitive manner." - var baseSensitivity = { sensitivity: "base" }; // Search the declarations in all files and output matched NavigateToItem into array of NavigateToItem[] ts.forEach(program.getSourceFiles(), function (sourceFile) { cancellationToken.throwIfCancellationRequested(); @@ -47705,8 +47730,8 @@ var ts; // We first sort case insensitively. So "Aaa" will come before "bar". // Then we sort case sensitively, so "aaa" will come before "Aaa". return i1.matchKind - i2.matchKind || - i1.name.localeCompare(i2.name, undefined, baseSensitivity) || - i1.name.localeCompare(i2.name); + ts.compareStringsCaseInsensitive(i1.name, i2.name) || + ts.compareStrings(i1.name, i2.name); } function createNavigateToItem(rawItem) { var declaration = rawItem.declaration; @@ -47741,6 +47766,13 @@ var ts; return result; } NavigationBar.getNavigationBarItems = getNavigationBarItems; + function getNavigationTree(sourceFile) { + curSourceFile = sourceFile; + var result = convertToTree(rootNavigationBarNode(sourceFile)); + curSourceFile = undefined; + return result; + } + NavigationBar.getNavigationTree = getNavigationTree; // Keep sourceFile handy so we don't have to search for it every time we need to call `getText`. var curSourceFile; function nodeText(node) { @@ -48018,11 +48050,9 @@ var ts; return name1 ? 1 : name2 ? -1 : navigationBarNodeKind(child1) - navigationBarNodeKind(child2); } } - // More efficient to create a collator once and use its `compare` than to call `a.localeCompare(b)` many times. - var collator = typeof Intl !== "undefined" && Intl && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; // Intl is missing in Safari, and node 0.10 treats "a" as greater than "B". - var localeCompareIsCorrect = collator && collator.compare("a", "B") < 0; - var localeCompareFix = localeCompareIsCorrect ? collator.compare : function (a, b) { + var localeCompareIsCorrect = ts.collator && ts.collator.compare("a", "B") < 0; + var localeCompareFix = localeCompareIsCorrect ? ts.collator.compare : function (a, b) { // This isn't perfect, but it passes all of our tests. for (var i = 0; i < Math.min(a.length, b.length); i++) { var chA = a.charAt(i), chB = b.charAt(i); @@ -48032,7 +48062,7 @@ var ts; if (chA === "'" && chB === "\"") { return -1; } - var cmp = chA.toLocaleLowerCase().localeCompare(chB.toLocaleLowerCase()); + var cmp = ts.compareStrings(chA.toLocaleLowerCase(), chB.toLocaleLowerCase()); if (cmp !== 0) { return cmp; } @@ -48183,6 +48213,15 @@ var ts; } // NavigationBarItem requires an array, but will not mutate it, so just give it this for performance. var emptyChildItemArray = []; + function convertToTree(n) { + return { + text: getItemName(n.node), + kind: ts.getNodeKind(n.node), + kindModifiers: ts.getNodeModifiers(n.node), + spans: getSpans(n), + childItems: ts.map(n.children, convertToTree) + }; + } function convertToTopLevelItem(n) { return { text: getItemName(n.node), @@ -48206,16 +48245,16 @@ var ts; grayed: false }; } - function getSpans(n) { - var spans = [getNodeSpan(n.node)]; - if (n.additionalNodes) { - for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { - var node = _a[_i]; - spans.push(getNodeSpan(node)); - } + } + function getSpans(n) { + var spans = [getNodeSpan(n.node)]; + if (n.additionalNodes) { + for (var _i = 0, _a = n.additionalNodes; _i < _a.length; _i++) { + var node = _a[_i]; + spans.push(getNodeSpan(node)); } - return spans; } + return spans; } function getModuleName(moduleDeclaration) { // We want to maintain quotation marks. @@ -50417,10 +50456,12 @@ var ts; * Get the typing info from common package manager json files like package.json or bower.json */ function getTypingNamesFromJson(jsonPath, filesToWatch) { + if (host.fileExists(jsonPath)) { + filesToWatch.push(jsonPath); + } var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); if (result.config) { var jsonConfig = result.config; - filesToWatch.push(jsonPath); if (jsonConfig.dependencies) { mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); } @@ -59516,8 +59557,10 @@ var ts; return ts.BreakpointResolver.spanInSourceFileAtLocation(sourceFile, position); } function getNavigationBarItems(fileName) { - var sourceFile = syntaxTreeCache.getCurrentSourceFile(fileName); - return ts.NavigationBar.getNavigationBarItems(sourceFile); + return ts.NavigationBar.getNavigationBarItems(syntaxTreeCache.getCurrentSourceFile(fileName)); + } + function getNavigationTree(fileName) { + return ts.NavigationBar.getNavigationTree(syntaxTreeCache.getCurrentSourceFile(fileName)); } function getSemanticClassifications(fileName, span) { return convertClassifications(getEncodedSemanticClassifications(fileName, span)); @@ -60461,6 +60504,7 @@ var ts; getRenameInfo: getRenameInfo, findRenameLocations: findRenameLocations, getNavigationBarItems: getNavigationBarItems, + getNavigationTree: getNavigationTree, getOutliningSpans: getOutliningSpans, getTodoComments: getTodoComments, getBraceMatchingAtPosition: getBraceMatchingAtPosition, @@ -62100,6 +62144,10 @@ var ts; var _this = this; return this.forwardJSONCall("getNavigationBarItems('" + fileName + "')", function () { return _this.languageService.getNavigationBarItems(fileName); }); }; + LanguageServiceShimObject.prototype.getNavigationTree = function (fileName) { + var _this = this; + return this.forwardJSONCall("getNavigationTree('" + fileName + "')", function () { return _this.languageService.getNavigationTree(fileName); }); + }; LanguageServiceShimObject.prototype.getOutliningSpans = function (fileName) { var _this = this; return this.forwardJSONCall("getOutliningSpans('" + fileName + "')", function () { return _this.languageService.getOutliningSpans(fileName); }); diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 84eb778159375..94e6f803099a0 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -130,6 +130,7 @@ var ts; var ts; (function (ts) { var createObject = Object.create; + ts.collator = typeof Intl === "object" && typeof Intl.Collator === "function" ? new Intl.Collator() : undefined; function createMap(template) { var map = createObject(null); map["__"] = undefined; @@ -687,7 +688,7 @@ var ts; if (b === undefined) return 1; if (ignoreCase) { - if (String.prototype.localeCompare) { + if (ts.collator && String.prototype.localeCompare) { var result = a.localeCompare(b, undefined, { usage: "sort", sensitivity: "accent" }); return result < 0 ? -1 : result > 0 ? 1 : 0; } @@ -1715,6 +1716,9 @@ var ts; }, watchDirectory: function (directoryName, callback, recursive) { var options; + if (!directoryExists(directoryName)) { + return; + } if (isNode4OrLater() && (process.platform === "win32" || process.platform === "darwin")) { options = { persistent: true, recursive: !!recursive }; } @@ -5187,10 +5191,12 @@ var ts; } } function getTypingNamesFromJson(jsonPath, filesToWatch) { + if (host.fileExists(jsonPath)) { + filesToWatch.push(jsonPath); + } var result = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }); if (result.config) { var jsonConfig = result.config; - filesToWatch.push(jsonPath); if (jsonConfig.dependencies) { mergeTypings(ts.getOwnKeys(jsonConfig.dependencies)); } @@ -5730,10 +5736,9 @@ var ts; typingsInstaller.NpmViewRequest = "npm view"; typingsInstaller.NpmInstallRequest = "npm install"; var TypingsInstaller = (function () { - function TypingsInstaller(globalCachePath, npmPath, safeListPath, throttleLimit, log) { + function TypingsInstaller(globalCachePath, safeListPath, throttleLimit, log) { if (log === void 0) { log = nullLog; } this.globalCachePath = globalCachePath; - this.npmPath = npmPath; this.safeListPath = safeListPath; this.throttleLimit = throttleLimit; this.log = log; @@ -5955,12 +5960,11 @@ var ts; var filteredTypings = []; for (var _i = 0, typingsToInstall_3 = typingsToInstall; _i < typingsToInstall_3.length; _i++) { var typing = typingsToInstall_3[_i]; - execNpmViewTyping(this, typing); + filterExistingTypings(this, typing); } - function execNpmViewTyping(self, typing) { - var command = self.npmPath + " view @types/" + typing + " --silent name"; - self.execAsync(typingsInstaller.NpmViewRequest, requestId, command, cachePath, function (err, stdout, stderr) { - if (stdout) { + function filterExistingTypings(self, typing) { + self.execAsync(typingsInstaller.NpmViewRequest, requestId, [typing], cachePath, function (ok) { + if (ok) { filteredTypings.push(typing); } execInstallCmdCount++; @@ -5975,9 +5979,8 @@ var ts; return; } var scopedTypings = filteredTypings.map(function (t) { return "@types/" + t; }); - var command = self.npmPath + " install " + scopedTypings.join(" ") + " --save-dev"; - self.execAsync(typingsInstaller.NpmInstallRequest, requestId, command, cachePath, function (err, stdout, stderr) { - postInstallAction(stdout ? scopedTypings : []); + self.execAsync(typingsInstaller.NpmInstallRequest, requestId, scopedTypings, cachePath, function (ok) { + postInstallAction(ok ? scopedTypings : []); }); } }; @@ -6004,8 +6007,10 @@ var ts; if (_this.log.isEnabled()) { _this.log.writeLine("Got FS notification for " + f + ", handler is already invoked '" + isInvoked + "'"); } - _this.sendResponse({ projectName: projectName, kind: "invalidate" }); - isInvoked = true; + if (!isInvoked) { + _this.sendResponse({ projectName: projectName, kind: "invalidate" }); + isInvoked = true; + } }); watchers.push(w); } @@ -6020,8 +6025,8 @@ var ts; kind: "set" }; }; - TypingsInstaller.prototype.execAsync = function (requestKind, requestId, command, cwd, onRequestCompleted) { - this.pendingRunRequests.unshift({ requestKind: requestKind, requestId: requestId, command: command, cwd: cwd, onRequestCompleted: onRequestCompleted }); + TypingsInstaller.prototype.execAsync = function (requestKind, requestId, args, cwd, onRequestCompleted) { + this.pendingRunRequests.unshift({ requestKind: requestKind, requestId: requestId, args: args, cwd: cwd, onRequestCompleted: onRequestCompleted }); this.executeWithThrottling(); }; TypingsInstaller.prototype.executeWithThrottling = function () { @@ -6029,9 +6034,9 @@ var ts; var _loop_1 = function() { this_1.inFlightRequestCount++; var request = this_1.pendingRunRequests.pop(); - this_1.runCommand(request.requestKind, request.requestId, request.command, request.cwd, function (err, stdout, stderr) { + this_1.executeRequest(request.requestKind, request.requestId, request.args, request.cwd, function (ok) { _this.inFlightRequestCount--; - request.onRequestCompleted(err, stdout, stderr); + request.onRequestCompleted(ok); _this.executeWithThrottling(); }); }; @@ -6077,13 +6082,14 @@ var ts; var NodeTypingsInstaller = (function (_super) { __extends(NodeTypingsInstaller, _super); function NodeTypingsInstaller(globalTypingsCacheLocation, throttleLimit, log) { - _super.call(this, globalTypingsCacheLocation, getNPMLocation(process.argv[0]), ts.toPath("typingSafeList.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), throttleLimit, log); + _super.call(this, globalTypingsCacheLocation, ts.toPath("typingSafeList.json", __dirname, ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)), throttleLimit, log); this.installTypingHost = ts.sys; if (this.log.isEnabled()) { this.log.writeLine("Process id: " + process.pid); } - var exec = require("child_process").exec; - this.exec = exec; + this.npmPath = getNPMLocation(process.argv[0]); + this.exec = require("child_process").exec; + this.httpGet = require("http").get; } NodeTypingsInstaller.prototype.init = function () { var _this = this; @@ -6107,18 +6113,54 @@ var ts; this.log.writeLine("Response has been sent."); } }; - NodeTypingsInstaller.prototype.runCommand = function (requestKind, requestId, command, cwd, onRequestCompleted) { + NodeTypingsInstaller.prototype.executeRequest = function (requestKind, requestId, args, cwd, onRequestCompleted) { var _this = this; if (this.log.isEnabled()) { - this.log.writeLine("#" + requestId + " running command '" + command + "'."); + this.log.writeLine("#" + requestId + " executing " + requestKind + ", arguments'" + JSON.stringify(args) + "'."); + } + switch (requestKind) { + case typingsInstaller.NpmViewRequest: + { + ts.Debug.assert(args.length === 1); + var url_1 = "http://registry.npmjs.org/@types%2f" + args[0]; + var start_2 = Date.now(); + this.httpGet(url_1, function (response) { + var ok = false; + if (_this.log.isEnabled()) { + _this.log.writeLine(requestKind + " #" + requestId + " request to " + url_1 + ":: status code " + response.statusCode + ", status message '" + response.statusMessage + "', took " + (Date.now() - start_2) + " ms"); + } + switch (response.statusCode) { + case 200: + case 301: + case 302: + ok = true; + break; + } + response.destroy(); + onRequestCompleted(ok); + }).on("error", function (err) { + if (_this.log.isEnabled()) { + _this.log.writeLine(requestKind + " #" + requestId + " query to npm registry failed with error " + err.message + ", stack " + err.stack); + } + onRequestCompleted(false); + }); + } + break; + case typingsInstaller.NpmInstallRequest: + { + var command = this.npmPath + " install " + args.join(" ") + " --save-dev"; + var start_3 = Date.now(); + this.exec(command, { cwd: cwd }, function (err, stdout, stderr) { + if (_this.log.isEnabled()) { + _this.log.writeLine(requestKind + " #" + requestId + " took: " + (Date.now() - start_3) + " ms" + ts.sys.newLine + "stdout: " + stdout + ts.sys.newLine + "stderr: " + stderr); + } + onRequestCompleted(!!stdout); + }); + } + break; + default: + ts.Debug.assert(false, "Unknown request kind " + requestKind); } - this.exec(command, { cwd: cwd }, function (err, stdout, stderr) { - if (_this.log.isEnabled()) { - _this.log.writeLine(requestKind + " #" + requestId + " stdout: " + stdout); - _this.log.writeLine(requestKind + " #" + requestId + " stderr: " + stderr); - } - onRequestCompleted(err, stdout, stderr); - }); }; return NodeTypingsInstaller; }(typingsInstaller.TypingsInstaller));