Upload original JAVA语言程序设计 course files (part 23)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-html-languageservice/README.md+69-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-html-languageservice/SECURITY.md+41-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-html-languageservice/node_modules/vscode-uri/LICENSE.md+9-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-html-languageservice/node_modules/vscode-uri/README.md+67-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-html-languageservice/node_modules/vscode-uri/SECURITY.md+41-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-html-languageservice/node_modules/vscode-uri/lib/umd/utils.d.ts+58-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-html-languageservice/node_modules/vscode-uri/lib/umd/utils.js+123-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-html-languageservice/node_modules/vscode-uri/package.json+43-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-html-languageservice/package.json+50-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-html-languageservice/thirdpartynotices.txt+49-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/dist/node/jsonServerMain.js
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/@vscode/l10n/README.md+42-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/@vscode/l10n/dist/browser.js+103-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/@vscode/l10n/dist/main.d.ts+130-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/@vscode/l10n/dist/main.js+151-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/@vscode/l10n/dist/tsdoc-metadata.json+11-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/@vscode/l10n/package.json+50-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/CHANGELOG.md+72-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/LICENSE.md+21-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/README.md+362-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/SECURITY.md+41-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/esm/impl/edit.js+185-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/esm/impl/format.js+261-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/esm/impl/parser.js+632-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/esm/impl/scanner.js+443-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/esm/impl/string-intern.js+29-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/esm/main.d.ts+349-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/esm/main.js+178-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/umd/impl/edit.js+201-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/umd/impl/format.js+275-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/umd/impl/parser.js+655-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/umd/impl/scanner.js+456-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/umd/impl/string-intern.js+42-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/umd/main.d.ts+349-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/umd/main.js+194-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/package.json+37-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/License.txt+11-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/README.md+69-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/browser.d.ts+6-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/browser.js+7-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/lib/browser/main.d.ts+17-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/lib/browser/main.js+76-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/lib/browser/ril.d.ts+12-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/lib/browser/ril.js+156-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/lib/common/api.d.ts+14-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/lib/common/api.js+82-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/lib/common/cancellation.d.ts+32-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/lib/common/cancellation.js+96-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/lib/common/connection.d.ts+365-3
- Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/lib/common/connection.js+1220-3
123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869version https://git-lfs.github.com/spec/v1oid sha256:e856292613701611e5ed2bc8833ca457af6901dab5eb340e93eadf7d2b828c0bsize 3397# vscode-html-languageserviceHTML language service extracted from VSCode to be reused, e.g in the Monaco editor.
[](https://www.npmjs.org/package/vscode-html-languageservice)[](https://npmjs.org/package/vscode-html-languageservice)[](https://github.com/microsoft/vscode-html-languageservice/actions)[](https://opensource.org/licenses/MIT)
Why?----
The _vscode-html-languageservice_ contains the language smarts behind the HTML editing experience of Visual Studio Codeand the Monaco editor.
- *doComplete* / *doComplete2* (async) provide completion proposals for a given location. - *setCompletionParticipants* allows participant to provide suggestions for specific tokens. - *doHover* provides hover information at a given location.
- *format* formats the code at the given range. - *findDocumentLinks* finds all links in the document. - *findDocumentSymbols* finds all the symbols in the document. - *getFoldingRanges* return folding ranges for the given document. - *getSelectionRanges* return the selection ranges for the given document. ...
For the complete API see [htmlLanguageService.ts](./src/htmlLanguageService.ts) and [htmlLanguageTypes.ts](./src/htmlLanguageTypes.ts)
Installation------------
npm install --save vscode-html-languageservice
Development-----------
- clone this repo, run `npm i``- `npm test` to compile and run tests
How can I run and debug the service?
- open the folder in VSCode.- set breakpoints, e.g. in `htmlCompletion.ts`- run the Unit tests from the run viewlet and wait until a breakpoint is hit:
How can I run and debug the service inside an instance of VSCode?
- run VSCode out of sources setup as described here: https://github.com/Microsoft/vscode/wiki/How-to-Contribute- link the folder of the `vscode-html-languageservice` repo to `vscode/extensions/html-language-features/server` to run VSCode with the latest changes from that folder: - cd `vscode-html-languageservice`, `npm link` - cd `vscode/extensions/html-language-features/server`, `npm link vscode-html-languageservice`- run VSCode out of source (`vscode/scripts/code.sh|bat`) and open a `.html` file- in VSCode window that is open on the `vscode-html-languageservice` sources, run command `Debug: Attach to Node process` and pick the `code-oss` process with the `html-language-features` path- set breakpoints, e.g. in `htmlCompletion.ts`- in the instance run from sources, invoke code completion in the `.html` file
License-------
(MIT License)
Copyright 2016-2023, Microsoft
`src/languageFacts/data/webCustomData.ts` (shipped as `lib/esm/languageFacts/data/webCustomData.ts` and `lib/umd/languageFacts/data/webCustomData.ts`)are built upon content from [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web) and distributed under CC BY-SA 2.5.1231234567891011121314151617181920212223242526272829303132333435363738394041version https://git-lfs.github.com/spec/v1oid sha256:430987b8c5f30c366ecd501bc344c8b29b6280e8a10174376a769f7443a187cdsize 2757<!-- BEGIN MICROSOFT SECURITY.MD V0.0.8 BLOCK -->
## Security
Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/).
If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/opensource/security/definition), please report it to us as described below.
## Reporting Security Issues
**Please do not report security vulnerabilities through public GitHub issues.**
Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/opensource/security/create-report).
If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/opensource/security/pgpkey).
You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://aka.ms/opensource/security/msrc).
Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
* Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) * Full paths of source file(s) related to the manifestation of the issue * The location of the affected source code (tag/branch/commit or direct URL) * Any special configuration required to reproduce the issue * Step-by-step instructions to reproduce the issue * Proof-of-concept or exploit code (if possible) * Impact of the issue, including how an attacker might exploit the issue
This information will help us triage your report more quickly.
If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/opensource/security/bounty) page for more details about our active programs.
## Preferred Languages
We prefer all communications to be in English.
## Policy
Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/opensource/security/cvd).
<!-- END MICROSOFT SECURITY.MD BLOCK -->123123456789version https://git-lfs.github.com/spec/v1oid sha256:c669138cb1eb01fbb745e8e460b291e4f2869c14a40061390b6095d845ed4c82size 1070The MIT License (MIT)
Copyright (c) Microsoft
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.12312345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667version https://git-lfs.github.com/spec/v1oid sha256:39ad66715504e292bd71b6b258d0bdba95be22e3a539a280ef2534be0525218esize 2475## vscode-uri
[](https://travis-ci.org/Microsoft/vscode-uri)
This module contains the URI implementation that is used by VS Code and its extensions. It has support for parsing a string into `scheme`, `authority`, `path`, `query`, and`fragment` URI components as defined in: http://tools.ietf.org/html/rfc3986
``` foo://example.com:8042/over/there?name=ferret#nose \_/ \______________/\_________/ \_________/ \__/ | | | | |scheme authority path query fragment | _____________________|__ / \ / \ urn:example:animal:ferret:nose```
## Usage
```jsimport { URI } from 'vscode-uri'
// parse an URI from string
let uri = URI.parse('https://code.visualstudio.com/docs/extensions/overview#frag')
assert.ok(uri.scheme === 'https');assert.ok(uri.authority === 'code.visualstudio.com');assert.ok(uri.path === '/docs/extensions/overview');assert.ok(uri.query === '');assert.ok(uri.fragment === 'frag');assert.ok(uri.toString() === 'https://code.visualstudio.com/docs/extensions/overview#frag')
// create an URI from a fs path
let uri = URI.file('/users/me/c#-projects/');
assert.ok(uri.scheme === 'file');assert.ok(uri.authority === '');assert.ok(uri.path === '/users/me/c#-projects/');assert.ok(uri.query === '');assert.ok(uri.fragment === '');assert.ok(uri.toString() === 'file:///users/me/c%23-projects/')```
## Usage: Util
This module also exports a `Utils` package which is an extension, not part of `vscode.Uri`, and useful for path-math. There is:
* `Utils.joinPath(URI, paths): URI`* `Utils.resolvePath(URI, paths): URI`* `Utils.dirname(URI): string`* `Utils.basename(URI): string`* `Utils.extname(URI): string`
All util use posix path-math as defined by the node.js path module.
## Contributing
The source of this module is taken straight from the [vscode](https://github.com/microsoft/vscode)-sources and because of that issues and pull request should be created in that repository. Thanks and Happy Coding!
## Code of Conduct
This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments.1231234567891011121314151617181920212223242526272829303132333435363738394041version https://git-lfs.github.com/spec/v1oid sha256:430987b8c5f30c366ecd501bc344c8b29b6280e8a10174376a769f7443a187cdsize 2757<!-- BEGIN MICROSOFT SECURITY.MD V0.0.8 BLOCK -->
## Security
Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/).
If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/opensource/security/definition), please report it to us as described below.
## Reporting Security Issues
**Please do not report security vulnerabilities through public GitHub issues.**
Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/opensource/security/create-report).
If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/opensource/security/pgpkey).
You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://aka.ms/opensource/security/msrc).
Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
* Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) * Full paths of source file(s) related to the manifestation of the issue * The location of the affected source code (tag/branch/commit or direct URL) * Any special configuration required to reproduce the issue * Step-by-step instructions to reproduce the issue * Proof-of-concept or exploit code (if possible) * Impact of the issue, including how an attacker might exploit the issue
This information will help us triage your report more quickly.
If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/opensource/security/bounty) page for more details about our active programs.
## Preferred Languages
We prefer all communications to be in English.
## Policy
Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/opensource/security/cvd).
<!-- END MICROSOFT SECURITY.MD BLOCK -->12312345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758version https://git-lfs.github.com/spec/v1oid sha256:bad1bc59cf9ba7f2b8efc0f7342b141843cbf3d3d791fa13df4ff9b86db26df9size 2861import { URI } from './uri';export declare namespace Utils { /** * Joins one or more input paths to the path of URI. * '/' is used as the directory separation character. * * The resolved path will be normalized. That means: * - all '..' and '.' segments are resolved. * - multiple, sequential occurences of '/' are replaced by a single instance of '/'. * - trailing separators are preserved. * * @param uri The input URI. * @param paths The paths to be joined with the path of URI. * @returns A URI with the joined path. All other properties of the URI (scheme, authority, query, fragments, ...) will be taken from the input URI. */ function joinPath(uri: URI, ...paths: string[]): URI; /** * Resolves one or more paths against the path of a URI. * '/' is used as the directory separation character. * * The resolved path will be normalized. That means: * - all '..' and '.' segments are resolved. * - multiple, sequential occurences of '/' are replaced by a single instance of '/'. * - trailing separators are removed. * * @param uri The input URI. * @param paths The paths to resolve against the path of URI. * @returns A URI with the resolved path. All other properties of the URI (scheme, authority, query, fragments, ...) will be taken from the input URI. */ function resolvePath(uri: URI, ...paths: string[]): URI; /** * Returns a URI where the path is the directory name of the input uri, similar to the Unix dirname command. * In the path, '/' is recognized as the directory separation character. Trailing directory separators are ignored. * The orignal URI is returned if the URIs path is empty or does not contain any path segments. * * @param uri The input URI. * @return The last segment of the URIs path. */ function dirname(uri: URI): URI; /** * Returns the last segment of the path of a URI, similar to the Unix basename command. * In the path, '/' is recognized as the directory separation character. Trailing directory separators are ignored. * The empty string is returned if the URIs path is empty or does not contain any path segments. * * @param uri The input URI. * @return The base name of the URIs path. */ function basename(uri: URI): string; /** * Returns the extension name of the path of a URI, similar to the Unix extname command. * In the path, '/' is recognized as the directory separation character. Trailing directory separators are ignored. * The empty string is returned if the URIs path is empty or does not contain any path segments. * * @param uri The input URI. * @return The extension name of the URIs path. */ function extname(uri: URI): string;}123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123version https://git-lfs.github.com/spec/v1oid sha256:9f9b8f431890c158e48c2d7d2eb509898efb88d2d20d46351f015dbce4439ed9size 5552/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/'use strict';var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc);}) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k];}));var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v });}) : function(o, v) { o["default"] = v;});var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result;};Object.defineProperty(exports, "__esModule", { value: true });exports.Utils = void 0;const nodePath = __importStar(require("path"));const posixPath = nodePath.posix || nodePath;const slash = '/';var Utils;(function (Utils) { /** * Joins one or more input paths to the path of URI. * '/' is used as the directory separation character. * * The resolved path will be normalized. That means: * - all '..' and '.' segments are resolved. * - multiple, sequential occurences of '/' are replaced by a single instance of '/'. * - trailing separators are preserved. * * @param uri The input URI. * @param paths The paths to be joined with the path of URI. * @returns A URI with the joined path. All other properties of the URI (scheme, authority, query, fragments, ...) will be taken from the input URI. */ function joinPath(uri, ...paths) { return uri.with({ path: posixPath.join(uri.path, ...paths) }); } Utils.joinPath = joinPath; /** * Resolves one or more paths against the path of a URI. * '/' is used as the directory separation character. * * The resolved path will be normalized. That means: * - all '..' and '.' segments are resolved. * - multiple, sequential occurences of '/' are replaced by a single instance of '/'. * - trailing separators are removed. * * @param uri The input URI. * @param paths The paths to resolve against the path of URI. * @returns A URI with the resolved path. All other properties of the URI (scheme, authority, query, fragments, ...) will be taken from the input URI. */ function resolvePath(uri, ...paths) { let path = uri.path; let slashAdded = false; if (path[0] !== slash) { path = slash + path; // make the path abstract: for posixPath.resolve the first segments has to be absolute or cwd is used. slashAdded = true; } let resolvedPath = posixPath.resolve(path, ...paths); if (slashAdded && resolvedPath[0] === slash && !uri.authority) { resolvedPath = resolvedPath.substring(1); } return uri.with({ path: resolvedPath }); } Utils.resolvePath = resolvePath; /** * Returns a URI where the path is the directory name of the input uri, similar to the Unix dirname command. * In the path, '/' is recognized as the directory separation character. Trailing directory separators are ignored. * The orignal URI is returned if the URIs path is empty or does not contain any path segments. * * @param uri The input URI. * @return The last segment of the URIs path. */ function dirname(uri) { if (uri.path.length === 0 || uri.path === slash) { return uri; } let path = posixPath.dirname(uri.path); if (path.length === 1 && path.charCodeAt(0) === 46 /* CharCode.Period */) { path = ''; } return uri.with({ path }); } Utils.dirname = dirname; /** * Returns the last segment of the path of a URI, similar to the Unix basename command. * In the path, '/' is recognized as the directory separation character. Trailing directory separators are ignored. * The empty string is returned if the URIs path is empty or does not contain any path segments. * * @param uri The input URI. * @return The base name of the URIs path. */ function basename(uri) { return posixPath.basename(uri.path); } Utils.basename = basename; /** * Returns the extension name of the path of a URI, similar to the Unix extname command. * In the path, '/' is recognized as the directory separation character. Trailing directory separators are ignored. * The empty string is returned if the URIs path is empty or does not contain any path segments. * * @param uri The input URI. * @return The extension name of the URIs path. */ function extname(uri) { return posixPath.extname(uri.path); } Utils.extname = extname;})(Utils || (exports.Utils = Utils = {}));12312345678910111213141516171819202122232425262728293031323334353637383940414243version https://git-lfs.github.com/spec/v1oid sha256:d09b69a9f81addcaf2e162ab64bba0496726b7dd7cca17985163795eb7601633size 1214{ "name": "vscode-uri", "author": "Microsoft", "version": "3.0.8", "description": "The URI implementation that is used by VS Code and its extensions", "main": "./lib/umd/index.js", "typings": "./lib/umd/index", "exports": { "import": "./lib/esm/index.mjs", "require": "./lib/umd/index.js", "types": "./lib/umd/index.d.ts", "browser": "./lib/esm/index.mjs" }, "sideEffects": false, "scripts": { "clean": "rimraf lib", "pack-production": "webpack --mode=production", "pack-dev": "webpack", "compile": "tsc -p ./src", "prepublish": "npm run pack-production", "test": "tsc -p ./src && npm run pack-dev && mocha" }, "repository": { "type": "git", "url": "git+https://github.com/microsoft/vscode-uri.git" }, "license": "MIT", "bugs": { "url": "https://github.com/microsoft/vscode-uri/issues" }, "homepage": "https://github.com/microsoft/vscode-uri#readme", "devDependencies": { "@types/mocha": "^10.0.2", "@types/node": "16.x", "mocha": "^10.2.0", "path-browserify": "^1.0.1", "rimraf": "^5.0.5", "ts-loader": "^9.4.4", "typescript": "^5.2.2", "webpack": "^5.88.2", "webpack-cli": "^5.1.4" }}1231234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950version https://git-lfs.github.com/spec/v1oid sha256:d69d368802bc08f580d26738c1c61c8afeec5656f61dddce8335ddf09ff4304dsize 2007{ "name": "vscode-html-languageservice", "version": "5.2.0", "description": "Language service for HTML", "main": "./lib/umd/htmlLanguageService.js", "typings": "./lib/umd/htmlLanguageService", "module": "./lib/esm/htmlLanguageService.js", "author": "Microsoft Corporation", "repository": { "type": "git", "url": "https://github.com/Microsoft/vscode-html-languageservice" }, "license": "MIT", "bugs": { "url": "https://github.com/Microsoft/vscode-html-languageservice" }, "devDependencies": { "@types/mocha": "^10.0.6", "@types/node": "16.x", "@typescript-eslint/eslint-plugin": "^6.21.0", "@typescript-eslint/parser": "^6.21.0", "@vscode/web-custom-data": "^0.4.9", "eslint": "^8.57.0", "js-beautify": "^1.15.1", "mocha": "^10.3.0", "rimraf": "^5.0.5", "typescript": "^5.3.3" }, "dependencies": { "@vscode/l10n": "^0.0.18", "vscode-languageserver-textdocument": "^1.0.11", "vscode-languageserver-types": "^3.17.5", "vscode-uri": "^3.0.8" }, "scripts": { "prepack": "npm run clean && npm run compile-esm && npm run test && npm run remove-sourcemap-refs", "compile": "tsc -p ./src && npm run copy-jsbeautify", "compile-esm": "tsc -p ./src/tsconfig.esm.json", "watch": "tsc -w -p ./src && npm run copy-jsbeautify", "clean": "rimraf lib", "remove-sourcemap-refs": "node ./build/remove-sourcemap-refs.js", "test": "npm run compile && mocha --timeout 5000 ./lib/umd/test/*.js && npm run lint", "lint": "eslint src/**/*.ts", "install-types-next": "npm i vscode-languageserver-types@next -f -S && npm i vscode-languageserver-textdocument@next -f -S", "copy-jsbeautify": "node ./build/copy-jsbeautify.js", "update-jsbeautify": "npm i js-beautify && node ./build/update-jsbeautify.js", "update-jsbeautify-next": "npm i js-beautify@next && node ./build/update-jsbeautify.js", "update-data": "npm i @vscode/web-custom-data -D && node ./build/generateData.js" }}12312345678910111213141516171819202122232425262728293031323334353637383940414243444546474849version https://git-lfs.github.com/spec/v1oid sha256:6fac688548f02e656a57234c7f0cb4a74bd8645b4ef2c7a33f5117861b9f3de0size 2961THIRD-PARTY SOFTWARE NOTICES AND INFORMATION
vscode-html-languageservice incorporates third party material from the projects listed below. The original copyrightnotice and the license under which Microsoft received such third party material are set forth below. Microsoftreserves all other rights not expressly granted, whether by implication, estoppel or otherwise. 1. JS Beautifier (https://github.com/beautify-web/js-beautify)
The MIT License (MIT)
Copyright (c) 2007-2017 Einar Lielmanis, Liam Newman, and contributors.
Permission is hereby granted, free of charge, to any person obtaining a copyof this software and associated documentation files (the "Software"), to dealin the Software without restriction, including without limitation the rightsto use, copy, modify, merge, publish, distribute, sublicense, and/or sellcopies of the Software, and to permit persons to whom the Software isfurnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included inall copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS ORIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THEAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHERLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS INTHE SOFTWARE.
2. HTML 5.1 W3C Working Draft version 08 October 2015 (http://www.w3.org/TR/2015/WD-html51-20151008/)
%% HTML 5.1 W3C Working Draft NOTICES AND INFORMATION BEGIN HERE=========================================Copyright © 2015 W3C® (MIT, ERCIM, Keio, Beihang). This software or document includes material copiedfrom or derived from HTML 5.1 W3C Working Draft (http://www.w3.org/TR/2015/WD-html51-20151008/.)
THIS DOCUMENT IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING, BUTNOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, OR TITLE; THAT THE CONTENTS OFTHE DOCUMENT ARE SUITABLE FOR ANY PURPOSE; NOR THAT THE IMPLEMENTATION OF SUCH CONTENTS WILL NOT INFRINGE ANY THIRD PARTYPATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS.
COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THEDOCUMENT OR THE PERFORMANCE OR IMPLEMENTATION OF THE CONTENTS THEREOF.
The name and trademarks of copyright holders may NOT be used in advertising or publicity pertaining to this document or its contentswithout specific, written prior permission. Title to copyright in this document will at all times remain with copyright holders.=========================================END OF HTML 5.1 W3C Working Draft NOTICES AND INFORMATION123123456789101112131415161718192021222324252627282930313233343536373839404142version https://git-lfs.github.com/spec/v1oid sha256:4aaa859447a3db374692b940cef70bb380160524db1203c26a969b2849e077f2size 1423# @vscode/l10n
Library used for loading the translations into subprocesses of your extension. These usages also get picked up by [l10n-dev](https://github.com/microsoft/vscode-l10n/tree/main/l10n-dev) string extraction tooling.
> **Note**>> You should _NOT_ use this library in your extension's main process. The translations are loaded into the main process by VS Code itself.
## Usage
```typescriptimport * as l10n from '@vscode/l10n';
// Load the translations for the current localel10n.config({ contents: JSON.parse(process.env.BUNDLE_FROM_EXTENSION)});// orl10n.config({ fsPath: process.env.FSPATH_TO_BUNDLE_FROM_EXTENSION});// or (warning, this is async)await l10n.config({ uri: JSON.parse(process.env.BUNDLE_URI_FROM_EXTENSION)});
// returns the translated string or the original string if no translation is availablel10n.t('Hello World');
// supports arguments just like the vscode APIl10n.t('Hello {0}', 'John');
// supports comments for translatorsl10n.t({ message: 'Hello {0}', args: ['John'], comment: ['This is a comment']});```
The input for `l10n.config` pairs nicely with the `bundle` and `uri` properties on the `l10n` namespace that are provided by the [VS Code API](https://code.visualstudio.com/api/references/vscode-api#l10n).You should send the value of one of these properties from your extension to your subprocess that is consuming `@vscode/l10n`.123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103version https://git-lfs.github.com/spec/v1oid sha256:7e74b4963b59a7c5e380699233d7aa7cc94fb095706fb34e8ad88bf825cc78d5size 2969// src/browser/reader.tsasync function readFileFromUri(uri) { if (uri.protocol === "http:" || uri.protocol === "https:") { const res = await fetch(uri); return await res.text(); } throw new Error("Unsupported protocol");}function readFileFromFsPath(_) { throw new Error("Unsupported in browser");}
// src/main.tsvar bundle;function config(config2) { if ("contents" in config2) { if (typeof config2.contents === "string") { bundle = JSON.parse(config2.contents); } else { bundle = config2.contents; } return; } if ("fsPath" in config2) { const fileContent = readFileFromFsPath(config2.fsPath); const content = JSON.parse(fileContent); bundle = isBuiltinExtension(content) ? content.contents.bundle : content; return; } if (config2.uri) { let uri = config2.uri; if (typeof config2.uri === "string") { uri = new URL(config2.uri); } return new Promise((resolve, reject) => { readFileFromUri(uri).then((uriContent) => { try { const content = JSON.parse(uriContent); bundle = isBuiltinExtension(content) ? content.contents.bundle : content; resolve(); } catch (err) { reject(err); } }).catch((err) => { reject(err); }); }); }}function t(...args) { const firstArg = args[0]; let key; let message; let formatArgs; if (typeof firstArg === "string") { key = firstArg; message = firstArg; args.splice(0, 1); formatArgs = !args || typeof args[0] !== "object" ? args : args[0]; } else if (firstArg instanceof Array) { const replacements = args.slice(1); if (firstArg.length !== replacements.length + 1) { throw new Error("expected a string as the first argument to l10n.t"); } let str = firstArg[0]; for (let i = 1; i < firstArg.length; i++) { str += `{${i - 1}}` + firstArg[i]; } return t(str, ...replacements); } else { message = firstArg.message; key = message; if (firstArg.comment && firstArg.comment.length > 0) { key += `/${Array.isArray(firstArg.comment) ? firstArg.comment.join("") : firstArg.comment}`; } formatArgs = firstArg.args ?? {}; } const messageFromBundle = bundle?.[key]; if (!messageFromBundle) { return format(message, formatArgs); } if (typeof messageFromBundle === "string") { return format(messageFromBundle, formatArgs); } if (messageFromBundle.comment) { return format(messageFromBundle.message, formatArgs); } return format(message, formatArgs);}var _format2Regexp = /{([^}]+)}/g;function format(template, values) { if (Object.keys(values).length === 0) { return template; } return template.replace(_format2Regexp, (match, group) => values[group] ?? match);}function isBuiltinExtension(json) { return !!(typeof json?.contents?.bundle === "object" && typeof json?.version === "string");}export { config, t};123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130version https://git-lfs.github.com/spec/v1oid sha256:026930c0ed50d369cfc92dac7cc62a46672d15856f5ede6f5437ac917669ff9dsize 5601/**
* @public
* Loads the bundle from the given contents. Must be run before the first call to any `l10n.t()` variant.
* **Note** The best way to set this is to pass the value of the VS Code API `vscode.l10n.contents`
* to the process that uses `@vscode/l10n`.
* @param config - An object that contains one property, contents, which should contain the contents of the bundle.
*/
export declare function config(config: {
contents: string | l10nJsonFormat;
}): void;
/**
* @public
* Loads the bundle from the given fsPath. Must be run before the first call to any `l10n.t()` variant.
* **Warning** This is not implemented in the browser and will throw an Error.
* **Note** The best way to set this is to pass the value of the VS Code API `vscode.l10n.uri.fsPath`
* to the process that uses `@vscode/l10n`.
* @param config - An object that contains one property, fsPath, which should be a path to a file that contains the bundle.
*/
export declare function config(config: {
fsPath: string;
}): void;
/**
* @public
* Loads the bundle from the given URI using an asynchronous fetch request.
* **Warning** Since this is an asynchronous API, you need to ensure that it resolves before
* the first call to any `l10n.t()` variant.
* **Note** The best way to set this is to pass the value of the VS Code API `vscode.l10n.uri.toString()`
* to the process that uses `@vscode/l10n`.
* @param config - An object that contains one property, uri, which should be a URL to the bundle.
*/
export declare function config(config: {
uri: string | URL;
}): Promise<void>;
/**
* @public
* The format of package.nls.json and l10n bundle files.
*/
export declare interface l10nJsonFormat {
[key: string]: l10nJsonMessageFormat;
}
/**
* @public
* The format of a message in a bundle.
*/
export declare type l10nJsonMessageFormat = string | {
message: string;
comment: string[];
};
/**
* @public
* Type that can be used as replacements in `l10n.t()` calls.
*/
export declare type L10nReplacement = string | number | boolean;
/**
* @public
* Marks a string for localization. If the bundle has a localized value for this message, then that localized
* value will be returned (with injected `args` values for any templated values).
* @param message - The message to localize. Supports index templating where strings like `{0}` and `{1}` are
* replaced by the item at that index in the `args` array.
* @param args - The arguments to be used in the localized string. The index of the argument is used to
* match the template placeholder in the localized string.
* @returns localized string with injected arguments.
* @example `l10n.localize('hello', 'Hello {0}!', 'World');`
*/
export declare function t(message: string, ...args: Array<L10nReplacement>): string;
/**
* @public
* Marks a string for localization. If the bundle has a localized value for this message, then that localized
* value will be returned (with injected `args` values for any templated values).
* @param message - The message to localize. Supports named templating where strings like `{foo}` and `{bar}` are
* replaced by the value in the Record for that key (foo, bar, etc).
* @param args - The arguments to be used in the localized string. The name of the key in the record is used to
* match the template placeholder in the localized string.
* @returns localized string with injected arguments.
* @example `l10n.t('Hello {name}', { name: 'Erich' });`
*/
export declare function t(message: string, args: Record<string, L10nReplacement>): string;
/**
* @public
* Marks a string for localization. This function signature is made for usage
* with tagged template literals.
*
* The more verbose overload should still be used if comments are required.
* @example
* ```
* l10n.t`Hello ${name}!`
* ```
* @param message - String message components
* @param args - Replacement components in the string
* @returns localized string with injected arguments.
*/
export declare function t(strs: TemplateStringsArray, ...replacements: L10nReplacement[]): string;
/**
* @public
* Marks a string for localization. If the bundle has a localized value for this message, then that localized
* value will be returned (with injected args values for any templated values).
* @param options - The options to use when localizing the message.
* @returns localized string with injected arguments.
* @example `l10n.t({ message: 'Hello {0}', args: ['Erich'], comment: 'This is a comment' } );`
*/
export declare function t(options: {
/**
* The message to localize. If `args` is an array, this message supports index templating where strings like
* `{0}` and `{1}` are replaced by the item at that index in the `args` array. If `args` is a `Record<string, any>`,
* this supports named templating where strings like `{foo}` and `{bar}` are replaced by the value in
* the Record for that key (foo, bar, etc).
*/
message: string;
/**
* The arguments to be used in the localized string. As an array, the index of the argument is used to
* match the template placeholder in the localized string. As a Record, the key is used to match the template
* placeholder in the localized string.
*/
args?: Array<string | number | boolean> | Record<string, any>;
/**
* A comment to help translators understand the context of the message.
*/
comment: string | string[];
}): string;
export { }123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151version https://git-lfs.github.com/spec/v1oid sha256:acb4bd2bcbfc029a6744f475151a9c188890cd0dca00c15b739d2371497909cbsize 4582"use strict";var __defProp = Object.defineProperty;var __getOwnPropDesc = Object.getOwnPropertyDescriptor;var __getOwnPropNames = Object.getOwnPropertyNames;var __hasOwnProp = Object.prototype.hasOwnProperty;var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true });};var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to;};var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/main.tsvar main_exports = {};__export(main_exports, { config: () => config, t: () => t});module.exports = __toCommonJS(main_exports);
// src/node/reader.tsvar import_fs = require("fs");var import_promises = require("fs/promises");async function readFileFromUri(uri) { if (uri.protocol === "file:") { return await (0, import_promises.readFile)(uri, "utf8"); } if (uri.protocol === "http:" || uri.protocol === "https:") { const res = await fetch(uri.toString(), { headers: { "Accept-Encoding": "gzip, deflate", "Accept": "application/json" }, redirect: "follow" }); if (!res.ok) { let error = `Unexpected ${res.status} response while trying to read ${uri}`; try { error += `: ${await res.text()}`; } catch { } throw new Error(error); } const decoded = await res.text(); return decoded; } throw new Error("Unsupported protocol");}function readFileFromFsPath(fsPath) { return (0, import_fs.readFileSync)(fsPath, "utf8");}
// src/main.tsvar bundle;function config(config2) { if ("contents" in config2) { if (typeof config2.contents === "string") { bundle = JSON.parse(config2.contents); } else { bundle = config2.contents; } return; } if ("fsPath" in config2) { const fileContent = readFileFromFsPath(config2.fsPath); const content = JSON.parse(fileContent); bundle = isBuiltinExtension(content) ? content.contents.bundle : content; return; } if (config2.uri) { let uri = config2.uri; if (typeof config2.uri === "string") { uri = new URL(config2.uri); } return new Promise((resolve, reject) => { readFileFromUri(uri).then((uriContent) => { try { const content = JSON.parse(uriContent); bundle = isBuiltinExtension(content) ? content.contents.bundle : content; resolve(); } catch (err) { reject(err); } }).catch((err) => { reject(err); }); }); }}function t(...args) { const firstArg = args[0]; let key; let message; let formatArgs; if (typeof firstArg === "string") { key = firstArg; message = firstArg; args.splice(0, 1); formatArgs = !args || typeof args[0] !== "object" ? args : args[0]; } else if (firstArg instanceof Array) { const replacements = args.slice(1); if (firstArg.length !== replacements.length + 1) { throw new Error("expected a string as the first argument to l10n.t"); } let str = firstArg[0]; for (let i = 1; i < firstArg.length; i++) { str += `{${i - 1}}` + firstArg[i]; } return t(str, ...replacements); } else { message = firstArg.message; key = message; if (firstArg.comment && firstArg.comment.length > 0) { key += `/${Array.isArray(firstArg.comment) ? firstArg.comment.join("") : firstArg.comment}`; } formatArgs = firstArg.args ?? {}; } const messageFromBundle = bundle?.[key]; if (!messageFromBundle) { return format(message, formatArgs); } if (typeof messageFromBundle === "string") { return format(messageFromBundle, formatArgs); } if (messageFromBundle.comment) { return format(messageFromBundle.message, formatArgs); } return format(message, formatArgs);}var _format2Regexp = /{([^}]+)}/g;function format(template, values) { if (Object.keys(values).length === 0) { return template; } return template.replace(_format2Regexp, (match, group) => values[group] ?? match);}function isBuiltinExtension(json) { return !!(typeof json?.contents?.bundle === "object" && typeof json?.version === "string");}// Annotate the CommonJS export names for ESM import in node:0 && (module.exports = { config, t});1231234567891011version https://git-lfs.github.com/spec/v1oid sha256:edd0e881410dfe96bc8b53a2081f01f936318c850e502af3e3980fbbe2211501size 340// This file is read by tools that parse documentation comments conforming to the TSDoc standard.
// It should be published with your NPM package. It should not be tracked by Git.
{
"tsdocVersion": "0.12",
"toolPackages": [
{
"packageName": "@microsoft/api-extractor",
"packageVersion": "7.36.3"
}
]
}1231234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950version https://git-lfs.github.com/spec/v1oid sha256:293375e8e1de0d54c2437079fdc47e6ee4f55a125ca346ac58e61cbd602e959asize 1504{ "name": "@vscode/l10n", "version": "0.0.18", "description": "A helper library to assist in localizing subprocesses spun up by VS Code extensions", "author": "Microsoft Corporation", "license": "MIT", "repository": { "type": "git", "url": "https://github.com/Microsoft/vscode-l10n.git" }, "bugs": { "url": "https://github.com/Microsoft/vscode-l10n/issues" }, "main": "./dist/main.js", "sideEffects": false, "browser": { "./dist/main.js": "./dist/browser.js", "./src/node/reader": "./src/browser/reader" }, "types": "dist/main.d.ts", "files": [ "dist/*" ], "devDependencies": { "@jest/globals": "^29.7.0", "@microsoft/api-extractor": "^7.32.1", "@types/mock-fs": "^4.13.1", "@types/node": "^18", "@typescript-eslint/eslint-plugin": "^6.13.2", "@typescript-eslint/parser": "^6.13.2", "esbuild": "^0.15.5", "eslint": "^7.29.0", "http-proxy-agent": "^5.0.0", "https-proxy-agent": "^5.0.1", "jest": "^29.7.0", "jest-fetch-mock": "^3.0.3", "mock-fs": "^5.1.4", "rimraf": "^3.0.2", "ts-jest": "^29.1.1", "typescript": "^4.7.4" }, "scripts": { "clean": "rimraf dist && rimraf lib", "compile": "npm run clean && tsc --emitDeclarationOnly --outDir lib && node .esbuild.config.js", "lint": "eslint src --ext ts", "watch": "node .esbuild.config.js --watch", "test": "jest --preset ts-jest", "prepublishOnly": "npm run lint && npm run compile && npm run test" }}123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172version https://git-lfs.github.com/spec/v1oid sha256:ce508d6b9a2e11c03f60aa3b9519e4b919ddbfe96e869dbe454dc483d26cd9fasize 2723
3.2.0 2022-08-30=================- update the version of the bundled Javascript files to `es2020`.- include all `const enum` values in the bundled JavaScript files (`ScanError`, `SyntaxKind`, `ParseErrorCode`).
3.1.0 2022-07-07================== * added new API `FormattingOptions.keepLines` : It leaves the initial line positions in the formatting.
3.0.0 2020-11-13================== * fixed API spec for `parseTree`. Can return `undefine` for empty input. * added new API `FormattingOptions.insertFinalNewline`.
2.3.0 2020-07-03================== * new API `ModificationOptions.isArrayInsertion`: If `JSONPath` refers to an index of an array and `isArrayInsertion` is `true`, then `modify` will insert a new item at that location instead of overwriting its contents. * `ModificationOptions.formattingOptions` is now optional. If not set, newly inserted content will not be formatted.
2.2.0 2019-10-25================== * added `ParseOptions.allowEmptyContent`. Default is `false`. * new API `getNodeType`: Returns the type of a value returned by parse. * `parse`: Fix issue with empty property name
2.1.0 2019-03-29================== * `JSONScanner` and `JSONVisitor` return lineNumber / character.
2.0.0 2018-04-12================== * renamed `Node.columnOffset` to `Node.colonOffset` * new API `getNodePath`: Gets the JSON path of the given JSON DOM node * new API `findNodeAtOffset`: Finds the most inner node at the given offset. If `includeRightBound` is set, also finds nodes that end at the given offset.
1.0.3 2018-03-07================== * provide ems modules
1.0.2 2018-03-05================== * added the `visit.onComment` API, reported when comments are allowed. * added the `ParseErrorCode.InvalidCommentToken` enum value, reported when comments are disallowed.
1.0.1================== * added the `format` API: computes edits to format a JSON document. * added the `modify` API: computes edits to insert, remove or replace a property or value in a JSON document. * added the `allyEdits` API: applies edits to a document
1.0.0================== * remove nls dependency (remove `getParseErrorMessage`)
0.4.2 / 2017-05-05================== * added `ParseError.offset` & `ParseError.length`
0.4.1 / 2017-04-02================== * added `ParseOptions.allowTrailingComma`
0.4.0 / 2017-02-23================== * fix for `getLocation`. Now `getLocation` inside an object will always return a property from inside that property. Can be empty string if the object has no properties or if the offset is before a actual property `{ "a": { | }} will return location ['a', ' ']`
0.3.0 / 2017-01-17================== * Updating to typescript 2.0123123456789101112131415161718192021version https://git-lfs.github.com/spec/v1oid sha256:c3a24c02d678e5f0711623dcf3ab3f243b273c2633f638a1fa8e35fb7c7f8e4dsize 1092The MIT License (MIT)
Copyright (c) Microsoft
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362version https://git-lfs.github.com/spec/v1oid sha256:7f3bbe33967c25f1974ac93a4c9c2c2bde59c79da517d27bb575dcbc10a259dbsize 14129# jsonc-parserScanner and parser for JSON with comments.
[](https://www.npmjs.org/package/jsonc-parser)[](https://npmjs.org/package/jsonc-parser)[](https://github.com/microsoft/node-jsonc-parser/workflows/Tests)[](https://opensource.org/licenses/MIT)
Why?----JSONC is JSON with JavaScript style comments. This node module provides a scanner and fault tolerant parser that can process JSONC but is also useful for standard JSON. - the *scanner* tokenizes the input string into tokens and token offsets - the *visit* function implements a 'SAX' style parser with callbacks for the encountered properties and values. - the *parseTree* function computes a hierarchical DOM with offsets representing the encountered properties and values. - the *parse* function evaluates the JavaScript object represented by JSON string in a fault tolerant fashion. - the *getLocation* API returns a location object that describes the property or value located at a given offset in a JSON document. - the *findNodeAtLocation* API finds the node at a given location path in a JSON DOM. - the *format* API computes edits to format a JSON document. - the *modify* API computes edits to insert, remove or replace a property or value in a JSON document. - the *applyEdits* API applies edits to a document.
Installation------------
```npm install --save jsonc-parser```
API---
### Scanner:```typescript
/** * Creates a JSON scanner on the given text. * If ignoreTrivia is set, whitespaces or comments are ignored. */export function createScanner(text: string, ignoreTrivia: boolean = false): JSONScanner; /** * The scanner object, representing a JSON scanner at a position in the input string. */export interface JSONScanner { /** * Sets the scan position to a new offset. A call to 'scan' is needed to get the first token. */ setPosition(pos: number): any; /** * Read the next token. Returns the token code. */ scan(): SyntaxKind; /** * Returns the zero-based current scan position, which is after the last read token. */ getPosition(): number; /** * Returns the last read token. */ getToken(): SyntaxKind; /** * Returns the last read token value. The value for strings is the decoded string content. For numbers it's of type number, for boolean it's true or false. */ getTokenValue(): string; /** * The zero-based start offset of the last read token. */ getTokenOffset(): number; /** * The length of the last read token. */ getTokenLength(): number; /** * The zero-based start line number of the last read token. */ getTokenStartLine(): number; /** * The zero-based start character (column) of the last read token. */ getTokenStartCharacter(): number; /** * An error code of the last scan. */ getTokenError(): ScanError;}```
### Parser:```typescript
export interface ParseOptions { disallowComments?: boolean; allowTrailingComma?: boolean; allowEmptyContent?: boolean;}/** * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. * Therefore always check the errors list to find out if the input was valid. */export declare function parse(text: string, errors?: {error: ParseErrorCode;}[], options?: ParseOptions): any;
/** * Parses the given text and invokes the visitor functions for each object, array and literal reached. */export declare function visit(text: string, visitor: JSONVisitor, options?: ParseOptions): any;
/** * Visitor called by {@linkcode visit} when parsing JSON. * * The visitor functions have the following common parameters: * - `offset`: Global offset within the JSON document, starting at 0 * - `startLine`: Line number, starting at 0 * - `startCharacter`: Start character (column) within the current line, starting at 0 * * Additionally some functions have a `pathSupplier` parameter which can be used to obtain the * current `JSONPath` within the document. */export interface JSONVisitor { /** * Invoked when an open brace is encountered and an object is started. The offset and length represent the location of the open brace. */ onObjectBegin?: (offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void;
/** * Invoked when a property is encountered. The offset and length represent the location of the property name. * The `JSONPath` created by the `pathSupplier` refers to the enclosing JSON object, it does not include the * property name yet. */ onObjectProperty?: (property: string, offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; /** * Invoked when a closing brace is encountered and an object is completed. The offset and length represent the location of the closing brace. */ onObjectEnd?: (offset: number, length: number, startLine: number, startCharacter: number) => void; /** * Invoked when an open bracket is encountered. The offset and length represent the location of the open bracket. */ onArrayBegin?: (offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; /** * Invoked when a closing bracket is encountered. The offset and length represent the location of the closing bracket. */ onArrayEnd?: (offset: number, length: number, startLine: number, startCharacter: number) => void; /** * Invoked when a literal value is encountered. The offset and length represent the location of the literal value. */ onLiteralValue?: (value: any, offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; /** * Invoked when a comma or colon separator is encountered. The offset and length represent the location of the separator. */ onSeparator?: (character: string, offset: number, length: number, startLine: number, startCharacter: number) => void; /** * When comments are allowed, invoked when a line or block comment is encountered. The offset and length represent the location of the comment. */ onComment?: (offset: number, length: number, startLine: number, startCharacter: number) => void; /** * Invoked on an error. */ onError?: (error: ParseErrorCode, offset: number, length: number, startLine: number, startCharacter: number) => void;}
/** * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. */export declare function parseTree(text: string, errors?: ParseError[], options?: ParseOptions): Node | undefined;
export declare type NodeType = "object" | "array" | "property" | "string" | "number" | "boolean" | "null";export interface Node { type: NodeType; value?: any; offset: number; length: number; colonOffset?: number; parent?: Node; children?: Node[];}
```
### Utilities:```typescript/** * Takes JSON with JavaScript-style comments and remove * them. Optionally replaces every none-newline character * of comments with a replaceCharacter */export declare function stripComments(text: string, replaceCh?: string): string;
/** * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index. */export declare function getLocation(text: string, position: number): Location;
/** * A {@linkcode JSONPath} segment. Either a string representing an object property name * or a number (starting at 0) for array indices. */export declare type Segment = string | number;export declare type JSONPath = Segment[];export interface Location { /** * The previous property key or literal value (string, number, boolean or null) or undefined. */ previousNode?: Node; /** * The path describing the location in the JSON document. The path consists of a sequence strings * representing an object property or numbers for array indices. */ path: JSONPath; /** * Matches the locations path against a pattern consisting of strings (for properties) and numbers (for array indices). * '*' will match a single segment, of any property name or index. * '**' will match a sequence of segments or no segment, of any property name or index. */ matches: (patterns: JSONPath) => boolean; /** * If set, the location's offset is at a property key. */ isAtPropertyKey: boolean;}
/** * Finds the node at the given path in a JSON DOM. */export function findNodeAtLocation(root: Node, path: JSONPath): Node | undefined;
/** * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset. */export function findNodeAtOffset(root: Node, offset: number, includeRightBound?: boolean) : Node | undefined;
/** * Gets the JSON path of the given JSON DOM node */export function getNodePath(node: Node): JSONPath;
/** * Evaluates the JavaScript object of the given JSON DOM node */export function getNodeValue(node: Node): any;
/** * Computes the edit operations needed to format a JSON document. * * @param documentText The input text * @param range The range to format or `undefined` to format the full content * @param options The formatting options * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}. * To apply the edit operations to the input, use {@linkcode applyEdits}. */export function format(documentText: string, range: Range, options: FormattingOptions): EditResult;
/** * Computes the edit operations needed to modify a value in the JSON document. * * @param documentText The input text * @param path The path of the value to change. The path represents either to the document root, a property or an array item. * If the path points to an non-existing property or item, it will be created. * @param value The new value for the specified property or item. If the value is undefined, * the property or item will be removed. * @param options Options * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}. * To apply the edit operations to the input, use {@linkcode applyEdits}. */export function modify(text: string, path: JSONPath, value: any, options: ModificationOptions): EditResult;
/** * Applies edits to an input string. * @param text The input text * @param edits Edit operations following the format described in {@linkcode EditResult}. * @returns The text with the applied edits. * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}. */export function applyEdits(text: string, edits: EditResult): string;
/** * An edit result describes a textual edit operation. It is the result of a {@linkcode format} and {@linkcode modify} operation. * It consist of one or more edits describing insertions, replacements or removals of text segments. * * The offsets of the edits refer to the original state of the document. * * No two edits change or remove the same range of text in the original document. * * Multiple edits can have the same offset if they are multiple inserts, or an insert followed by a remove or replace. * * The order in the array defines which edit is applied first. * To apply an edit result use {@linkcode applyEdits}. * In general multiple EditResults must not be concatenated because they might impact each other, producing incorrect or malformed JSON data. */export type EditResult = Edit[];
/** * Represents a text modification */export interface Edit { /** * The start offset of the modification. */ offset: number; /** * The length of the modification. Must not be negative. Empty length represents an *insert*. */ length: number; /** * The new content. Empty content represents a *remove*. */ content: string;}
/** * A text range in the document*/export interface Range { /** * The start offset of the range. */ offset: number; /** * The length of the range. Must not be negative. */ length: number;}
/** * Options used by {@linkcode format} when computing the formatting edit operations */export interface FormattingOptions { /** * If indentation is based on spaces (`insertSpaces` = true), then what is the number of spaces that make an indent? */ tabSize: number; /** * Is indentation based on spaces? */ insertSpaces: boolean; /** * The default 'end of line' character */ eol: string;}
/** * Options used by {@linkcode modify} when computing the modification edit operations */export interface ModificationOptions { /** * Formatting options. If undefined, the newly inserted code will be inserted unformatted. */ formattingOptions?: FormattingOptions; /** * Default false. If `JSONPath` refers to an index of an array and `isArrayInsertion` is `true`, then * {@linkcode modify} will insert a new item at that location instead of overwriting its contents. */ isArrayInsertion?: boolean; /** * Optional function to define the insertion index given an existing list of properties. */ getInsertionIndex?: (properties: string[]) => number;}```
License-------
(MIT License)
Copyright 2018, Microsoft1231234567891011121314151617181920212223242526272829303132333435363738394041version https://git-lfs.github.com/spec/v1oid sha256:830e94b83c3b6f45ceee5609de6249b2125927f95532e68427f09c99eed5e663size 2780<!-- BEGIN MICROSOFT SECURITY.MD V0.0.5 BLOCK -->
## Security
Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/).
If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://docs.microsoft.com/en-us/previous-versions/tn-archive/cc751383(v=technet.10)), please report it to us as described below.
## Reporting Security Issues
**Please do not report security vulnerabilities through public GitHub issues.**
Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://msrc.microsoft.com/create-report).
If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://www.microsoft.com/en-us/msrc/pgp-key-msrc).
You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc).
Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue:
* Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) * Full paths of source file(s) related to the manifestation of the issue * The location of the affected source code (tag/branch/commit or direct URL) * Any special configuration required to reproduce the issue * Step-by-step instructions to reproduce the issue * Proof-of-concept or exploit code (if possible) * Impact of the issue, including how an attacker might exploit the issue
This information will help us triage your report more quickly.
If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://microsoft.com/msrc/bounty) page for more details about our active programs.
## Preferred Languages
We prefer all communications to be in English.
## Policy
Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://www.microsoft.com/en-us/msrc/cvd).
<!-- END MICROSOFT SECURITY.MD BLOCK -->123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185version https://git-lfs.github.com/spec/v1oid sha256:7e7bf98e740f560026df079056d3b0f5f34628124a8d34e2765fb101dde12911size 8613/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/'use strict';import { format, isEOL } from './format';import { parseTree, findNodeAtLocation } from './parser';export function removeProperty(text, path, options) { return setProperty(text, path, void 0, options);}export function setProperty(text, originalPath, value, options) { const path = originalPath.slice(); const errors = []; const root = parseTree(text, errors); let parent = void 0; let lastSegment = void 0; while (path.length > 0) { lastSegment = path.pop(); parent = findNodeAtLocation(root, path); if (parent === void 0 && value !== void 0) { if (typeof lastSegment === 'string') { value = { [lastSegment]: value }; } else { value = [value]; } } else { break; } } if (!parent) { // empty document if (value === void 0) { // delete throw new Error('Can not delete in empty document'); } return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options); } else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) { const existing = findNodeAtLocation(parent, [lastSegment]); if (existing !== void 0) { if (value === void 0) { // delete if (!existing.parent) { throw new Error('Malformed AST'); } const propertyIndex = parent.children.indexOf(existing.parent); let removeBegin; let removeEnd = existing.parent.offset + existing.parent.length; if (propertyIndex > 0) { // remove the comma of the previous node let previous = parent.children[propertyIndex - 1]; removeBegin = previous.offset + previous.length; } else { removeBegin = parent.offset + 1; if (parent.children.length > 1) { // remove the comma of the next node let next = parent.children[1]; removeEnd = next.offset; } } return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, options); } else { // set value of existing property return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options); } } else { if (value === void 0) { // delete return []; // property does not exist, nothing to do } const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`; const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map(p => p.children[0].value)) : parent.children.length; let edit; if (index > 0) { let previous = parent.children[index - 1]; edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; } else if (parent.children.length === 0) { edit = { offset: parent.offset + 1, length: 0, content: newProperty }; } else { edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' }; } return withFormatting(text, edit, options); } } else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) { const insertIndex = lastSegment; if (insertIndex === -1) { // Insert const newProperty = `${JSON.stringify(value)}`; let edit; if (parent.children.length === 0) { edit = { offset: parent.offset + 1, length: 0, content: newProperty }; } else { const previous = parent.children[parent.children.length - 1]; edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; } return withFormatting(text, edit, options); } else if (value === void 0 && parent.children.length >= 0) { // Removal const removalIndex = lastSegment; const toRemove = parent.children[removalIndex]; let edit; if (parent.children.length === 1) { // only item edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' }; } else if (parent.children.length - 1 === removalIndex) { // last item let previous = parent.children[removalIndex - 1]; let offset = previous.offset + previous.length; let parentEndOffset = parent.offset + parent.length; edit = { offset, length: parentEndOffset - 2 - offset, content: '' }; } else { edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' }; } return withFormatting(text, edit, options); } else if (value !== void 0) { let edit; const newProperty = `${JSON.stringify(value)}`; if (!options.isArrayInsertion && parent.children.length > lastSegment) { const toModify = parent.children[lastSegment]; edit = { offset: toModify.offset, length: toModify.length, content: newProperty }; } else if (parent.children.length === 0 || lastSegment === 0) { edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + ',' }; } else { const index = lastSegment > parent.children.length ? parent.children.length : lastSegment; const previous = parent.children[index - 1]; edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; } return withFormatting(text, edit, options); } else { throw new Error(`Can not ${value === void 0 ? 'remove' : (options.isArrayInsertion ? 'insert' : 'modify')} Array index ${insertIndex} as length is not sufficient`); } } else { throw new Error(`Can not add ${typeof lastSegment !== 'number' ? 'index' : 'property'} to parent of type ${parent.type}`); }}function withFormatting(text, edit, options) { if (!options.formattingOptions) { return [edit]; } // apply the edit let newText = applyEdit(text, edit); // format the new text let begin = edit.offset; let end = edit.offset + edit.content.length; if (edit.length === 0 || edit.content.length === 0) { // insert or remove while (begin > 0 && !isEOL(newText, begin - 1)) { begin--; } while (end < newText.length && !isEOL(newText, end)) { end++; } } const edits = format(newText, { offset: begin, length: end - begin }, { ...options.formattingOptions, keepLines: false }); // apply the formatting edits and track the begin and end offsets of the changes for (let i = edits.length - 1; i >= 0; i--) { const edit = edits[i]; newText = applyEdit(newText, edit); begin = Math.min(begin, edit.offset); end = Math.max(end, edit.offset + edit.length); end += edit.content.length - edit.length; } // create a single edit with all changes const editLength = text.length - (newText.length - end) - begin; return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }];}export function applyEdit(text, edit) { return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length);}export function isWS(text, offset) { return '\r\n \t'.indexOf(text.charAt(offset)) !== -1;}123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261version https://git-lfs.github.com/spec/v1oid sha256:e57dee56700a844b18dea11548f9ba42b17bc857bde5bcd39554af06ca95bb1fsize 11098/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/'use strict';import { createScanner } from './scanner';import { cachedSpaces, cachedBreakLinesWithSpaces, supportedEols } from './string-intern';export function format(documentText, range, options) { let initialIndentLevel; let formatText; let formatTextStart; let rangeStart; let rangeEnd; if (range) { rangeStart = range.offset; rangeEnd = rangeStart + range.length; formatTextStart = rangeStart; while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) { formatTextStart--; } let endOffset = rangeEnd; while (endOffset < documentText.length && !isEOL(documentText, endOffset)) { endOffset++; } formatText = documentText.substring(formatTextStart, endOffset); initialIndentLevel = computeIndentLevel(formatText, options); } else { formatText = documentText; initialIndentLevel = 0; formatTextStart = 0; rangeStart = 0; rangeEnd = documentText.length; } const eol = getEOL(options, documentText); const eolFastPathSupported = supportedEols.includes(eol); let numberLineBreaks = 0; let indentLevel = 0; let indentValue; if (options.insertSpaces) { indentValue = cachedSpaces[options.tabSize || 4] ?? repeat(cachedSpaces[1], options.tabSize || 4); } else { indentValue = '\t'; } const indentType = indentValue === '\t' ? '\t' : ' '; let scanner = createScanner(formatText, false); let hasError = false; function newLinesAndIndent() { if (numberLineBreaks > 1) { return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel); } const amountOfSpaces = indentValue.length * (initialIndentLevel + indentLevel); if (!eolFastPathSupported || amountOfSpaces > cachedBreakLinesWithSpaces[indentType][eol].length) { return eol + repeat(indentValue, initialIndentLevel + indentLevel); } if (amountOfSpaces <= 0) { return eol; } return cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces]; } function scanNext() { let token = scanner.scan(); numberLineBreaks = 0; while (token === 15 /* SyntaxKind.Trivia */ || token === 14 /* SyntaxKind.LineBreakTrivia */) { if (token === 14 /* SyntaxKind.LineBreakTrivia */ && options.keepLines) { numberLineBreaks += 1; } else if (token === 14 /* SyntaxKind.LineBreakTrivia */) { numberLineBreaks = 1; } token = scanner.scan(); } hasError = token === 16 /* SyntaxKind.Unknown */ || scanner.getTokenError() !== 0 /* ScanError.None */; return token; } const editOperations = []; function addEdit(text, startOffset, endOffset) { if (!hasError && (!range || (startOffset < rangeEnd && endOffset > rangeStart)) && documentText.substring(startOffset, endOffset) !== text) { editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text }); } } let firstToken = scanNext(); if (options.keepLines && numberLineBreaks > 0) { addEdit(repeat(eol, numberLineBreaks), 0, 0); } if (firstToken !== 17 /* SyntaxKind.EOF */) { let firstTokenStart = scanner.getTokenOffset() + formatTextStart; let initialIndent = (indentValue.length * initialIndentLevel < 20) && options.insertSpaces ? cachedSpaces[indentValue.length * initialIndentLevel] : repeat(indentValue, initialIndentLevel); addEdit(initialIndent, formatTextStart, firstTokenStart); } while (firstToken !== 17 /* SyntaxKind.EOF */) { let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart; let secondToken = scanNext(); let replaceContent = ''; let needsLineBreak = false; while (numberLineBreaks === 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) { let commentTokenStart = scanner.getTokenOffset() + formatTextStart; addEdit(cachedSpaces[1], firstTokenEnd, commentTokenStart); firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart; needsLineBreak = secondToken === 12 /* SyntaxKind.LineCommentTrivia */; replaceContent = needsLineBreak ? newLinesAndIndent() : ''; secondToken = scanNext(); } if (secondToken === 2 /* SyntaxKind.CloseBraceToken */) { if (firstToken !== 1 /* SyntaxKind.OpenBraceToken */) { indentLevel--; } ; if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1 /* SyntaxKind.OpenBraceToken */) { replaceContent = newLinesAndIndent(); } else if (options.keepLines) { replaceContent = cachedSpaces[1]; } } else if (secondToken === 4 /* SyntaxKind.CloseBracketToken */) { if (firstToken !== 3 /* SyntaxKind.OpenBracketToken */) { indentLevel--; } ; if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3 /* SyntaxKind.OpenBracketToken */) { replaceContent = newLinesAndIndent(); } else if (options.keepLines) { replaceContent = cachedSpaces[1]; } } else { switch (firstToken) { case 3 /* SyntaxKind.OpenBracketToken */: case 1 /* SyntaxKind.OpenBraceToken */: indentLevel++; if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) { replaceContent = newLinesAndIndent(); } else { replaceContent = cachedSpaces[1]; } break; case 5 /* SyntaxKind.CommaToken */: if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) { replaceContent = newLinesAndIndent(); } else { replaceContent = cachedSpaces[1]; } break; case 12 /* SyntaxKind.LineCommentTrivia */: replaceContent = newLinesAndIndent(); break; case 13 /* SyntaxKind.BlockCommentTrivia */: if (numberLineBreaks > 0) { replaceContent = newLinesAndIndent(); } else if (!needsLineBreak) { replaceContent = cachedSpaces[1]; } break; case 6 /* SyntaxKind.ColonToken */: if (options.keepLines && numberLineBreaks > 0) { replaceContent = newLinesAndIndent(); } else if (!needsLineBreak) { replaceContent = cachedSpaces[1]; } break; case 10 /* SyntaxKind.StringLiteral */: if (options.keepLines && numberLineBreaks > 0) { replaceContent = newLinesAndIndent(); } else if (secondToken === 6 /* SyntaxKind.ColonToken */ && !needsLineBreak) { replaceContent = ''; } break; case 7 /* SyntaxKind.NullKeyword */: case 8 /* SyntaxKind.TrueKeyword */: case 9 /* SyntaxKind.FalseKeyword */: case 11 /* SyntaxKind.NumericLiteral */: case 2 /* SyntaxKind.CloseBraceToken */: case 4 /* SyntaxKind.CloseBracketToken */: if (options.keepLines && numberLineBreaks > 0) { replaceContent = newLinesAndIndent(); } else { if ((secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */) && !needsLineBreak) { replaceContent = cachedSpaces[1]; } else if (secondToken !== 5 /* SyntaxKind.CommaToken */ && secondToken !== 17 /* SyntaxKind.EOF */) { hasError = true; } } break; case 16 /* SyntaxKind.Unknown */: hasError = true; break; } if (numberLineBreaks > 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) { replaceContent = newLinesAndIndent(); } } if (secondToken === 17 /* SyntaxKind.EOF */) { if (options.keepLines && numberLineBreaks > 0) { replaceContent = newLinesAndIndent(); } else { replaceContent = options.insertFinalNewline ? eol : ''; } } const secondTokenStart = scanner.getTokenOffset() + formatTextStart; addEdit(replaceContent, firstTokenEnd, secondTokenStart); firstToken = secondToken; } return editOperations;}function repeat(s, count) { let result = ''; for (let i = 0; i < count; i++) { result += s; } return result;}function computeIndentLevel(content, options) { let i = 0; let nChars = 0; const tabSize = options.tabSize || 4; while (i < content.length) { let ch = content.charAt(i); if (ch === cachedSpaces[1]) { nChars++; } else if (ch === '\t') { nChars += tabSize; } else { break; } i++; } return Math.floor(nChars / tabSize);}function getEOL(options, text) { for (let i = 0; i < text.length; i++) { const ch = text.charAt(i); if (ch === '\r') { if (i + 1 < text.length && text.charAt(i + 1) === '\n') { return '\r\n'; } return '\r'; } else if (ch === '\n') { return '\n'; } } return (options && options.eol) || '\n';}export function isEOL(text, offset) { return '\r\n'.indexOf(text.charAt(offset)) !== -1;}123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632version https://git-lfs.github.com/spec/v1oid sha256:cd3807c61549999adfec191a4131c71f628284e63c85e8dad2b642f283e64ba5size 24708/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/'use strict';import { createScanner } from './scanner';var ParseOptions;(function (ParseOptions) { ParseOptions.DEFAULT = { allowTrailingComma: false };})(ParseOptions || (ParseOptions = {}));/** * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index. */export function getLocation(text, position) { const segments = []; // strings or numbers const earlyReturnException = new Object(); let previousNode = undefined; const previousNodeInst = { value: {}, offset: 0, length: 0, type: 'object', parent: undefined }; let isAtPropertyKey = false; function setPreviousNode(value, offset, length, type) { previousNodeInst.value = value; previousNodeInst.offset = offset; previousNodeInst.length = length; previousNodeInst.type = type; previousNodeInst.colonOffset = undefined; previousNode = previousNodeInst; } try { visit(text, { onObjectBegin: (offset, length) => { if (position <= offset) { throw earlyReturnException; } previousNode = undefined; isAtPropertyKey = position > offset; segments.push(''); // push a placeholder (will be replaced) }, onObjectProperty: (name, offset, length) => { if (position < offset) { throw earlyReturnException; } setPreviousNode(name, offset, length, 'property'); segments[segments.length - 1] = name; if (position <= offset + length) { throw earlyReturnException; } }, onObjectEnd: (offset, length) => { if (position <= offset) { throw earlyReturnException; } previousNode = undefined; segments.pop(); }, onArrayBegin: (offset, length) => { if (position <= offset) { throw earlyReturnException; } previousNode = undefined; segments.push(0); }, onArrayEnd: (offset, length) => { if (position <= offset) { throw earlyReturnException; } previousNode = undefined; segments.pop(); }, onLiteralValue: (value, offset, length) => { if (position < offset) { throw earlyReturnException; } setPreviousNode(value, offset, length, getNodeType(value)); if (position <= offset + length) { throw earlyReturnException; } }, onSeparator: (sep, offset, length) => { if (position <= offset) { throw earlyReturnException; } if (sep === ':' && previousNode && previousNode.type === 'property') { previousNode.colonOffset = offset; isAtPropertyKey = false; previousNode = undefined; } else if (sep === ',') { const last = segments[segments.length - 1]; if (typeof last === 'number') { segments[segments.length - 1] = last + 1; } else { isAtPropertyKey = true; segments[segments.length - 1] = ''; } previousNode = undefined; } } }); } catch (e) { if (e !== earlyReturnException) { throw e; } } return { path: segments, previousNode, isAtPropertyKey, matches: (pattern) => { let k = 0; for (let i = 0; k < pattern.length && i < segments.length; i++) { if (pattern[k] === segments[i] || pattern[k] === '*') { k++; } else if (pattern[k] !== '**') { return false; } } return k === pattern.length; } };}/** * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. * Therefore always check the errors list to find out if the input was valid. */export function parse(text, errors = [], options = ParseOptions.DEFAULT) { let currentProperty = null; let currentParent = []; const previousParents = []; function onValue(value) { if (Array.isArray(currentParent)) { currentParent.push(value); } else if (currentProperty !== null) { currentParent[currentProperty] = value; } } const visitor = { onObjectBegin: () => { const object = {}; onValue(object); previousParents.push(currentParent); currentParent = object; currentProperty = null; }, onObjectProperty: (name) => { currentProperty = name; }, onObjectEnd: () => { currentParent = previousParents.pop(); }, onArrayBegin: () => { const array = []; onValue(array); previousParents.push(currentParent); currentParent = array; currentProperty = null; }, onArrayEnd: () => { currentParent = previousParents.pop(); }, onLiteralValue: onValue, onError: (error, offset, length) => { errors.push({ error, offset, length }); } }; visit(text, visitor, options); return currentParent[0];}/** * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. */export function parseTree(text, errors = [], options = ParseOptions.DEFAULT) { let currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root function ensurePropertyComplete(endOffset) { if (currentParent.type === 'property') { currentParent.length = endOffset - currentParent.offset; currentParent = currentParent.parent; } } function onValue(valueNode) { currentParent.children.push(valueNode); return valueNode; } const visitor = { onObjectBegin: (offset) => { currentParent = onValue({ type: 'object', offset, length: -1, parent: currentParent, children: [] }); }, onObjectProperty: (name, offset, length) => { currentParent = onValue({ type: 'property', offset, length: -1, parent: currentParent, children: [] }); currentParent.children.push({ type: 'string', value: name, offset, length, parent: currentParent }); }, onObjectEnd: (offset, length) => { ensurePropertyComplete(offset + length); // in case of a missing value for a property: make sure property is complete currentParent.length = offset + length - currentParent.offset; currentParent = currentParent.parent; ensurePropertyComplete(offset + length); }, onArrayBegin: (offset, length) => { currentParent = onValue({ type: 'array', offset, length: -1, parent: currentParent, children: [] }); }, onArrayEnd: (offset, length) => { currentParent.length = offset + length - currentParent.offset; currentParent = currentParent.parent; ensurePropertyComplete(offset + length); }, onLiteralValue: (value, offset, length) => { onValue({ type: getNodeType(value), offset, length, parent: currentParent, value }); ensurePropertyComplete(offset + length); }, onSeparator: (sep, offset, length) => { if (currentParent.type === 'property') { if (sep === ':') { currentParent.colonOffset = offset; } else if (sep === ',') { ensurePropertyComplete(offset); } } }, onError: (error, offset, length) => { errors.push({ error, offset, length }); } }; visit(text, visitor, options); const result = currentParent.children[0]; if (result) { delete result.parent; } return result;}/** * Finds the node at the given path in a JSON DOM. */export function findNodeAtLocation(root, path) { if (!root) { return undefined; } let node = root; for (let segment of path) { if (typeof segment === 'string') { if (node.type !== 'object' || !Array.isArray(node.children)) { return undefined; } let found = false; for (const propertyNode of node.children) { if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) { node = propertyNode.children[1]; found = true; break; } } if (!found) { return undefined; } } else { const index = segment; if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) { return undefined; } node = node.children[index]; } } return node;}/** * Gets the JSON path of the given JSON DOM node */export function getNodePath(node) { if (!node.parent || !node.parent.children) { return []; } const path = getNodePath(node.parent); if (node.parent.type === 'property') { const key = node.parent.children[0].value; path.push(key); } else if (node.parent.type === 'array') { const index = node.parent.children.indexOf(node); if (index !== -1) { path.push(index); } } return path;}/** * Evaluates the JavaScript object of the given JSON DOM node */export function getNodeValue(node) { switch (node.type) { case 'array': return node.children.map(getNodeValue); case 'object': const obj = Object.create(null); for (let prop of node.children) { const valueNode = prop.children[1]; if (valueNode) { obj[prop.children[0].value] = getNodeValue(valueNode); } } return obj; case 'null': case 'string': case 'number': case 'boolean': return node.value; default: return undefined; }}export function contains(node, offset, includeRightBound = false) { return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length));}/** * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset. */export function findNodeAtOffset(node, offset, includeRightBound = false) { if (contains(node, offset, includeRightBound)) { const children = node.children; if (Array.isArray(children)) { for (let i = 0; i < children.length && children[i].offset <= offset; i++) { const item = findNodeAtOffset(children[i], offset, includeRightBound); if (item) { return item; } } } return node; } return undefined;}/** * Parses the given text and invokes the visitor functions for each object, array and literal reached. */export function visit(text, visitor, options = ParseOptions.DEFAULT) { const _scanner = createScanner(text, false); // Important: Only pass copies of this to visitor functions to prevent accidental modification, and // to not affect visitor functions which stored a reference to a previous JSONPath const _jsonPath = []; function toNoArgVisit(visitFunction) { return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true; } function toNoArgVisitWithPath(visitFunction) { return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true; } function toOneArgVisit(visitFunction) { return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true; } function toOneArgVisitWithPath(visitFunction) { return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true; } const onObjectBegin = toNoArgVisitWithPath(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisitWithPath(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError); const disallowComments = options && options.disallowComments; const allowTrailingComma = options && options.allowTrailingComma; function scanNext() { while (true) { const token = _scanner.scan(); switch (_scanner.getTokenError()) { case 4 /* ScanError.InvalidUnicode */: handleError(14 /* ParseErrorCode.InvalidUnicode */); break; case 5 /* ScanError.InvalidEscapeCharacter */: handleError(15 /* ParseErrorCode.InvalidEscapeCharacter */); break; case 3 /* ScanError.UnexpectedEndOfNumber */: handleError(13 /* ParseErrorCode.UnexpectedEndOfNumber */); break; case 1 /* ScanError.UnexpectedEndOfComment */: if (!disallowComments) { handleError(11 /* ParseErrorCode.UnexpectedEndOfComment */); } break; case 2 /* ScanError.UnexpectedEndOfString */: handleError(12 /* ParseErrorCode.UnexpectedEndOfString */); break; case 6 /* ScanError.InvalidCharacter */: handleError(16 /* ParseErrorCode.InvalidCharacter */); break; } switch (token) { case 12 /* SyntaxKind.LineCommentTrivia */: case 13 /* SyntaxKind.BlockCommentTrivia */: if (disallowComments) { handleError(10 /* ParseErrorCode.InvalidCommentToken */); } else { onComment(); } break; case 16 /* SyntaxKind.Unknown */: handleError(1 /* ParseErrorCode.InvalidSymbol */); break; case 15 /* SyntaxKind.Trivia */: case 14 /* SyntaxKind.LineBreakTrivia */: break; default: return token; } } } function handleError(error, skipUntilAfter = [], skipUntil = []) { onError(error); if (skipUntilAfter.length + skipUntil.length > 0) { let token = _scanner.getToken(); while (token !== 17 /* SyntaxKind.EOF */) { if (skipUntilAfter.indexOf(token) !== -1) { scanNext(); break; } else if (skipUntil.indexOf(token) !== -1) { break; } token = scanNext(); } } } function parseString(isValue) { const value = _scanner.getTokenValue(); if (isValue) { onLiteralValue(value); } else { onObjectProperty(value); // add property name afterwards _jsonPath.push(value); } scanNext(); return true; } function parseLiteral() { switch (_scanner.getToken()) { case 11 /* SyntaxKind.NumericLiteral */: const tokenValue = _scanner.getTokenValue(); let value = Number(tokenValue); if (isNaN(value)) { handleError(2 /* ParseErrorCode.InvalidNumberFormat */); value = 0; } onLiteralValue(value); break; case 7 /* SyntaxKind.NullKeyword */: onLiteralValue(null); break; case 8 /* SyntaxKind.TrueKeyword */: onLiteralValue(true); break; case 9 /* SyntaxKind.FalseKeyword */: onLiteralValue(false); break; default: return false; } scanNext(); return true; } function parseProperty() { if (_scanner.getToken() !== 10 /* SyntaxKind.StringLiteral */) { handleError(3 /* ParseErrorCode.PropertyNameExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); return false; } parseString(false); if (_scanner.getToken() === 6 /* SyntaxKind.ColonToken */) { onSeparator(':'); scanNext(); // consume colon if (!parseValue()) { handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); } } else { handleError(5 /* ParseErrorCode.ColonExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); } _jsonPath.pop(); // remove processed property name return true; } function parseObject() { onObjectBegin(); scanNext(); // consume open brace let needsComma = false; while (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) { if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) { if (!needsComma) { handleError(4 /* ParseErrorCode.ValueExpected */, [], []); } onSeparator(','); scanNext(); // consume comma if (_scanner.getToken() === 2 /* SyntaxKind.CloseBraceToken */ && allowTrailingComma) { break; } } else if (needsComma) { handleError(6 /* ParseErrorCode.CommaExpected */, [], []); } if (!parseProperty()) { handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); } needsComma = true; } onObjectEnd(); if (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */) { handleError(7 /* ParseErrorCode.CloseBraceExpected */, [2 /* SyntaxKind.CloseBraceToken */], []); } else { scanNext(); // consume close brace } return true; } function parseArray() { onArrayBegin(); scanNext(); // consume open bracket let isFirstElement = true; let needsComma = false; while (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) { if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) { if (!needsComma) { handleError(4 /* ParseErrorCode.ValueExpected */, [], []); } onSeparator(','); scanNext(); // consume comma if (_scanner.getToken() === 4 /* SyntaxKind.CloseBracketToken */ && allowTrailingComma) { break; } } else if (needsComma) { handleError(6 /* ParseErrorCode.CommaExpected */, [], []); } if (isFirstElement) { _jsonPath.push(0); isFirstElement = false; } else { _jsonPath[_jsonPath.length - 1]++; } if (!parseValue()) { handleError(4 /* ParseErrorCode.ValueExpected */, [], [4 /* SyntaxKind.CloseBracketToken */, 5 /* SyntaxKind.CommaToken */]); } needsComma = true; } onArrayEnd(); if (!isFirstElement) { _jsonPath.pop(); // remove array index } if (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */) { handleError(8 /* ParseErrorCode.CloseBracketExpected */, [4 /* SyntaxKind.CloseBracketToken */], []); } else { scanNext(); // consume close bracket } return true; } function parseValue() { switch (_scanner.getToken()) { case 3 /* SyntaxKind.OpenBracketToken */: return parseArray(); case 1 /* SyntaxKind.OpenBraceToken */: return parseObject(); case 10 /* SyntaxKind.StringLiteral */: return parseString(true); default: return parseLiteral(); } } scanNext(); if (_scanner.getToken() === 17 /* SyntaxKind.EOF */) { if (options.allowEmptyContent) { return true; } handleError(4 /* ParseErrorCode.ValueExpected */, [], []); return false; } if (!parseValue()) { handleError(4 /* ParseErrorCode.ValueExpected */, [], []); return false; } if (_scanner.getToken() !== 17 /* SyntaxKind.EOF */) { handleError(9 /* ParseErrorCode.EndOfFileExpected */, [], []); } return true;}/** * Takes JSON with JavaScript-style comments and remove * them. Optionally replaces every none-newline character * of comments with a replaceCharacter */export function stripComments(text, replaceCh) { let _scanner = createScanner(text), parts = [], kind, offset = 0, pos; do { pos = _scanner.getPosition(); kind = _scanner.scan(); switch (kind) { case 12 /* SyntaxKind.LineCommentTrivia */: case 13 /* SyntaxKind.BlockCommentTrivia */: case 17 /* SyntaxKind.EOF */: if (offset !== pos) { parts.push(text.substring(offset, pos)); } if (replaceCh !== undefined) { parts.push(_scanner.getTokenValue().replace(/[^\r\n]/g, replaceCh)); } offset = _scanner.getPosition(); break; } } while (kind !== 17 /* SyntaxKind.EOF */); return parts.join('');}export function getNodeType(value) { switch (typeof value) { case 'boolean': return 'boolean'; case 'number': return 'number'; case 'string': return 'string'; case 'object': { if (!value) { return 'null'; } else if (Array.isArray(value)) { return 'array'; } return 'object'; } default: return 'null'; }}123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443version https://git-lfs.github.com/spec/v1oid sha256:e737e1774f87ca88d85d73e3bafff688b78cac06b81c53b96c54da8b3ca86cd9size 19188/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/'use strict';/** * Creates a JSON scanner on the given text. * If ignoreTrivia is set, whitespaces or comments are ignored. */export function createScanner(text, ignoreTrivia = false) { const len = text.length; let pos = 0, value = '', tokenOffset = 0, token = 16 /* SyntaxKind.Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* ScanError.None */; function scanHexDigits(count, exact) { let digits = 0; let value = 0; while (digits < count || !exact) { let ch = text.charCodeAt(pos); if (ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */) { value = value * 16 + ch - 48 /* CharacterCodes._0 */; } else if (ch >= 65 /* CharacterCodes.A */ && ch <= 70 /* CharacterCodes.F */) { value = value * 16 + ch - 65 /* CharacterCodes.A */ + 10; } else if (ch >= 97 /* CharacterCodes.a */ && ch <= 102 /* CharacterCodes.f */) { value = value * 16 + ch - 97 /* CharacterCodes.a */ + 10; } else { break; } pos++; digits++; } if (digits < count) { value = -1; } return value; } function setPosition(newPosition) { pos = newPosition; value = ''; tokenOffset = 0; token = 16 /* SyntaxKind.Unknown */; scanError = 0 /* ScanError.None */; } function scanNumber() { let start = pos; if (text.charCodeAt(pos) === 48 /* CharacterCodes._0 */) { pos++; } else { pos++; while (pos < text.length && isDigit(text.charCodeAt(pos))) { pos++; } } if (pos < text.length && text.charCodeAt(pos) === 46 /* CharacterCodes.dot */) { pos++; if (pos < text.length && isDigit(text.charCodeAt(pos))) { pos++; while (pos < text.length && isDigit(text.charCodeAt(pos))) { pos++; } } else { scanError = 3 /* ScanError.UnexpectedEndOfNumber */; return text.substring(start, pos); } } let end = pos; if (pos < text.length && (text.charCodeAt(pos) === 69 /* CharacterCodes.E */ || text.charCodeAt(pos) === 101 /* CharacterCodes.e */)) { pos++; if (pos < text.length && text.charCodeAt(pos) === 43 /* CharacterCodes.plus */ || text.charCodeAt(pos) === 45 /* CharacterCodes.minus */) { pos++; } if (pos < text.length && isDigit(text.charCodeAt(pos))) { pos++; while (pos < text.length && isDigit(text.charCodeAt(pos))) { pos++; } end = pos; } else { scanError = 3 /* ScanError.UnexpectedEndOfNumber */; } } return text.substring(start, end); } function scanString() { let result = '', start = pos; while (true) { if (pos >= len) { result += text.substring(start, pos); scanError = 2 /* ScanError.UnexpectedEndOfString */; break; } const ch = text.charCodeAt(pos); if (ch === 34 /* CharacterCodes.doubleQuote */) { result += text.substring(start, pos); pos++; break; } if (ch === 92 /* CharacterCodes.backslash */) { result += text.substring(start, pos); pos++; if (pos >= len) { scanError = 2 /* ScanError.UnexpectedEndOfString */; break; } const ch2 = text.charCodeAt(pos++); switch (ch2) { case 34 /* CharacterCodes.doubleQuote */: result += '\"'; break; case 92 /* CharacterCodes.backslash */: result += '\\'; break; case 47 /* CharacterCodes.slash */: result += '/'; break; case 98 /* CharacterCodes.b */: result += '\b'; break; case 102 /* CharacterCodes.f */: result += '\f'; break; case 110 /* CharacterCodes.n */: result += '\n'; break; case 114 /* CharacterCodes.r */: result += '\r'; break; case 116 /* CharacterCodes.t */: result += '\t'; break; case 117 /* CharacterCodes.u */: const ch3 = scanHexDigits(4, true); if (ch3 >= 0) { result += String.fromCharCode(ch3); } else { scanError = 4 /* ScanError.InvalidUnicode */; } break; default: scanError = 5 /* ScanError.InvalidEscapeCharacter */; } start = pos; continue; } if (ch >= 0 && ch <= 0x1f) { if (isLineBreak(ch)) { result += text.substring(start, pos); scanError = 2 /* ScanError.UnexpectedEndOfString */; break; } else { scanError = 6 /* ScanError.InvalidCharacter */; // mark as error but continue with string } } pos++; } return result; } function scanNext() { value = ''; scanError = 0 /* ScanError.None */; tokenOffset = pos; lineStartOffset = lineNumber; prevTokenLineStartOffset = tokenLineStartOffset; if (pos >= len) { // at the end tokenOffset = len; return token = 17 /* SyntaxKind.EOF */; } let code = text.charCodeAt(pos); // trivia: whitespace if (isWhiteSpace(code)) { do { pos++; value += String.fromCharCode(code); code = text.charCodeAt(pos); } while (isWhiteSpace(code)); return token = 15 /* SyntaxKind.Trivia */; } // trivia: newlines if (isLineBreak(code)) { pos++; value += String.fromCharCode(code); if (code === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) { pos++; value += '\n'; } lineNumber++; tokenLineStartOffset = pos; return token = 14 /* SyntaxKind.LineBreakTrivia */; } switch (code) { // tokens: []{}:, case 123 /* CharacterCodes.openBrace */: pos++; return token = 1 /* SyntaxKind.OpenBraceToken */; case 125 /* CharacterCodes.closeBrace */: pos++; return token = 2 /* SyntaxKind.CloseBraceToken */; case 91 /* CharacterCodes.openBracket */: pos++; return token = 3 /* SyntaxKind.OpenBracketToken */; case 93 /* CharacterCodes.closeBracket */: pos++; return token = 4 /* SyntaxKind.CloseBracketToken */; case 58 /* CharacterCodes.colon */: pos++; return token = 6 /* SyntaxKind.ColonToken */; case 44 /* CharacterCodes.comma */: pos++; return token = 5 /* SyntaxKind.CommaToken */; // strings case 34 /* CharacterCodes.doubleQuote */: pos++; value = scanString(); return token = 10 /* SyntaxKind.StringLiteral */; // comments case 47 /* CharacterCodes.slash */: const start = pos - 1; // Single-line comment if (text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) { pos += 2; while (pos < len) { if (isLineBreak(text.charCodeAt(pos))) { break; } pos++; } value = text.substring(start, pos); return token = 12 /* SyntaxKind.LineCommentTrivia */; } // Multi-line comment if (text.charCodeAt(pos + 1) === 42 /* CharacterCodes.asterisk */) { pos += 2; const safeLength = len - 1; // For lookahead. let commentClosed = false; while (pos < safeLength) { const ch = text.charCodeAt(pos); if (ch === 42 /* CharacterCodes.asterisk */ && text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) { pos += 2; commentClosed = true; break; } pos++; if (isLineBreak(ch)) { if (ch === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) { pos++; } lineNumber++; tokenLineStartOffset = pos; } } if (!commentClosed) { pos++; scanError = 1 /* ScanError.UnexpectedEndOfComment */; } value = text.substring(start, pos); return token = 13 /* SyntaxKind.BlockCommentTrivia */; } // just a single slash value += String.fromCharCode(code); pos++; return token = 16 /* SyntaxKind.Unknown */; // numbers case 45 /* CharacterCodes.minus */: value += String.fromCharCode(code); pos++; if (pos === len || !isDigit(text.charCodeAt(pos))) { return token = 16 /* SyntaxKind.Unknown */; } // found a minus, followed by a number so // we fall through to proceed with scanning // numbers case 48 /* CharacterCodes._0 */: case 49 /* CharacterCodes._1 */: case 50 /* CharacterCodes._2 */: case 51 /* CharacterCodes._3 */: case 52 /* CharacterCodes._4 */: case 53 /* CharacterCodes._5 */: case 54 /* CharacterCodes._6 */: case 55 /* CharacterCodes._7 */: case 56 /* CharacterCodes._8 */: case 57 /* CharacterCodes._9 */: value += scanNumber(); return token = 11 /* SyntaxKind.NumericLiteral */; // literals and unknown symbols default: // is a literal? Read the full word. while (pos < len && isUnknownContentCharacter(code)) { pos++; code = text.charCodeAt(pos); } if (tokenOffset !== pos) { value = text.substring(tokenOffset, pos); // keywords: true, false, null switch (value) { case 'true': return token = 8 /* SyntaxKind.TrueKeyword */; case 'false': return token = 9 /* SyntaxKind.FalseKeyword */; case 'null': return token = 7 /* SyntaxKind.NullKeyword */; } return token = 16 /* SyntaxKind.Unknown */; } // some value += String.fromCharCode(code); pos++; return token = 16 /* SyntaxKind.Unknown */; } } function isUnknownContentCharacter(code) { if (isWhiteSpace(code) || isLineBreak(code)) { return false; } switch (code) { case 125 /* CharacterCodes.closeBrace */: case 93 /* CharacterCodes.closeBracket */: case 123 /* CharacterCodes.openBrace */: case 91 /* CharacterCodes.openBracket */: case 34 /* CharacterCodes.doubleQuote */: case 58 /* CharacterCodes.colon */: case 44 /* CharacterCodes.comma */: case 47 /* CharacterCodes.slash */: return false; } return true; } function scanNextNonTrivia() { let result; do { result = scanNext(); } while (result >= 12 /* SyntaxKind.LineCommentTrivia */ && result <= 15 /* SyntaxKind.Trivia */); return result; } return { setPosition: setPosition, getPosition: () => pos, scan: ignoreTrivia ? scanNextNonTrivia : scanNext, getToken: () => token, getTokenValue: () => value, getTokenOffset: () => tokenOffset, getTokenLength: () => pos - tokenOffset, getTokenStartLine: () => lineStartOffset, getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset, getTokenError: () => scanError, };}function isWhiteSpace(ch) { return ch === 32 /* CharacterCodes.space */ || ch === 9 /* CharacterCodes.tab */;}function isLineBreak(ch) { return ch === 10 /* CharacterCodes.lineFeed */ || ch === 13 /* CharacterCodes.carriageReturn */;}function isDigit(ch) { return ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */;}var CharacterCodes;(function (CharacterCodes) { CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; CharacterCodes[CharacterCodes["space"] = 32] = "space"; CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; CharacterCodes[CharacterCodes["a"] = 97] = "a"; CharacterCodes[CharacterCodes["b"] = 98] = "b"; CharacterCodes[CharacterCodes["c"] = 99] = "c"; CharacterCodes[CharacterCodes["d"] = 100] = "d"; CharacterCodes[CharacterCodes["e"] = 101] = "e"; CharacterCodes[CharacterCodes["f"] = 102] = "f"; CharacterCodes[CharacterCodes["g"] = 103] = "g"; CharacterCodes[CharacterCodes["h"] = 104] = "h"; CharacterCodes[CharacterCodes["i"] = 105] = "i"; CharacterCodes[CharacterCodes["j"] = 106] = "j"; CharacterCodes[CharacterCodes["k"] = 107] = "k"; CharacterCodes[CharacterCodes["l"] = 108] = "l"; CharacterCodes[CharacterCodes["m"] = 109] = "m"; CharacterCodes[CharacterCodes["n"] = 110] = "n"; CharacterCodes[CharacterCodes["o"] = 111] = "o"; CharacterCodes[CharacterCodes["p"] = 112] = "p"; CharacterCodes[CharacterCodes["q"] = 113] = "q"; CharacterCodes[CharacterCodes["r"] = 114] = "r"; CharacterCodes[CharacterCodes["s"] = 115] = "s"; CharacterCodes[CharacterCodes["t"] = 116] = "t"; CharacterCodes[CharacterCodes["u"] = 117] = "u"; CharacterCodes[CharacterCodes["v"] = 118] = "v"; CharacterCodes[CharacterCodes["w"] = 119] = "w"; CharacterCodes[CharacterCodes["x"] = 120] = "x"; CharacterCodes[CharacterCodes["y"] = 121] = "y"; CharacterCodes[CharacterCodes["z"] = 122] = "z"; CharacterCodes[CharacterCodes["A"] = 65] = "A"; CharacterCodes[CharacterCodes["B"] = 66] = "B"; CharacterCodes[CharacterCodes["C"] = 67] = "C"; CharacterCodes[CharacterCodes["D"] = 68] = "D"; CharacterCodes[CharacterCodes["E"] = 69] = "E"; CharacterCodes[CharacterCodes["F"] = 70] = "F"; CharacterCodes[CharacterCodes["G"] = 71] = "G"; CharacterCodes[CharacterCodes["H"] = 72] = "H"; CharacterCodes[CharacterCodes["I"] = 73] = "I"; CharacterCodes[CharacterCodes["J"] = 74] = "J"; CharacterCodes[CharacterCodes["K"] = 75] = "K"; CharacterCodes[CharacterCodes["L"] = 76] = "L"; CharacterCodes[CharacterCodes["M"] = 77] = "M"; CharacterCodes[CharacterCodes["N"] = 78] = "N"; CharacterCodes[CharacterCodes["O"] = 79] = "O"; CharacterCodes[CharacterCodes["P"] = 80] = "P"; CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; CharacterCodes[CharacterCodes["R"] = 82] = "R"; CharacterCodes[CharacterCodes["S"] = 83] = "S"; CharacterCodes[CharacterCodes["T"] = 84] = "T"; CharacterCodes[CharacterCodes["U"] = 85] = "U"; CharacterCodes[CharacterCodes["V"] = 86] = "V"; CharacterCodes[CharacterCodes["W"] = 87] = "W"; CharacterCodes[CharacterCodes["X"] = 88] = "X"; CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; CharacterCodes[CharacterCodes["tab"] = 9] = "tab";})(CharacterCodes || (CharacterCodes = {}));1231234567891011121314151617181920212223242526272829version https://git-lfs.github.com/spec/v1oid sha256:3a0aad3f56c3e0728812c7584568c0ff200bce1ca58cf40e946f01fdb54c5752size 1034export const cachedSpaces = new Array(20).fill(0).map((_, index) => { return ' '.repeat(index);});const maxCachedValues = 200;export const cachedBreakLinesWithSpaces = { ' ': { '\n': new Array(maxCachedValues).fill(0).map((_, index) => { return '\n' + ' '.repeat(index); }), '\r': new Array(maxCachedValues).fill(0).map((_, index) => { return '\r' + ' '.repeat(index); }), '\r\n': new Array(maxCachedValues).fill(0).map((_, index) => { return '\r\n' + ' '.repeat(index); }), }, '\t': { '\n': new Array(maxCachedValues).fill(0).map((_, index) => { return '\n' + '\t'.repeat(index); }), '\r': new Array(maxCachedValues).fill(0).map((_, index) => { return '\r' + '\t'.repeat(index); }), '\r\n': new Array(maxCachedValues).fill(0).map((_, index) => { return '\r\n' + '\t'.repeat(index); }), }};export const supportedEols = ['\n', '\r', '\r\n'];123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349version https://git-lfs.github.com/spec/v1oid sha256:4d82dad8d8a312706a9bc240c805088fef713bc71eaa622e55970e251b6c1a0fsize 14314/** * Creates a JSON scanner on the given text. * If ignoreTrivia is set, whitespaces or comments are ignored. */export declare const createScanner: (text: string, ignoreTrivia?: boolean) => JSONScanner;export declare const enum ScanError { None = 0, UnexpectedEndOfComment = 1, UnexpectedEndOfString = 2, UnexpectedEndOfNumber = 3, InvalidUnicode = 4, InvalidEscapeCharacter = 5, InvalidCharacter = 6}export declare const enum SyntaxKind { OpenBraceToken = 1, CloseBraceToken = 2, OpenBracketToken = 3, CloseBracketToken = 4, CommaToken = 5, ColonToken = 6, NullKeyword = 7, TrueKeyword = 8, FalseKeyword = 9, StringLiteral = 10, NumericLiteral = 11, LineCommentTrivia = 12, BlockCommentTrivia = 13, LineBreakTrivia = 14, Trivia = 15, Unknown = 16, EOF = 17}/** * The scanner object, representing a JSON scanner at a position in the input string. */export interface JSONScanner { /** * Sets the scan position to a new offset. A call to 'scan' is needed to get the first token. */ setPosition(pos: number): void; /** * Read the next token. Returns the token code. */ scan(): SyntaxKind; /** * Returns the zero-based current scan position, which is after the last read token. */ getPosition(): number; /** * Returns the last read token. */ getToken(): SyntaxKind; /** * Returns the last read token value. The value for strings is the decoded string content. For numbers it's of type number, for boolean it's true or false. */ getTokenValue(): string; /** * The zero-based start offset of the last read token. */ getTokenOffset(): number; /** * The length of the last read token. */ getTokenLength(): number; /** * The zero-based start line number of the last read token. */ getTokenStartLine(): number; /** * The zero-based start character (column) of the last read token. */ getTokenStartCharacter(): number; /** * An error code of the last scan. */ getTokenError(): ScanError;}/** * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index. */export declare const getLocation: (text: string, position: number) => Location;/** * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. * Therefore, always check the errors list to find out if the input was valid. */export declare const parse: (text: string, errors?: ParseError[], options?: ParseOptions) => any;/** * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. */export declare const parseTree: (text: string, errors?: ParseError[], options?: ParseOptions) => Node | undefined;/** * Finds the node at the given path in a JSON DOM. */export declare const findNodeAtLocation: (root: Node, path: JSONPath) => Node | undefined;/** * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset. */export declare const findNodeAtOffset: (root: Node, offset: number, includeRightBound?: boolean) => Node | undefined;/** * Gets the JSON path of the given JSON DOM node */export declare const getNodePath: (node: Node) => JSONPath;/** * Evaluates the JavaScript object of the given JSON DOM node */export declare const getNodeValue: (node: Node) => any;/** * Parses the given text and invokes the visitor functions for each object, array and literal reached. */export declare const visit: (text: string, visitor: JSONVisitor, options?: ParseOptions) => any;/** * Takes JSON with JavaScript-style comments and remove * them. Optionally replaces every none-newline character * of comments with a replaceCharacter */export declare const stripComments: (text: string, replaceCh?: string) => string;export interface ParseError { error: ParseErrorCode; offset: number; length: number;}export declare const enum ParseErrorCode { InvalidSymbol = 1, InvalidNumberFormat = 2, PropertyNameExpected = 3, ValueExpected = 4, ColonExpected = 5, CommaExpected = 6, CloseBraceExpected = 7, CloseBracketExpected = 8, EndOfFileExpected = 9, InvalidCommentToken = 10, UnexpectedEndOfComment = 11, UnexpectedEndOfString = 12, UnexpectedEndOfNumber = 13, InvalidUnicode = 14, InvalidEscapeCharacter = 15, InvalidCharacter = 16}export declare function printParseErrorCode(code: ParseErrorCode): "InvalidSymbol" | "InvalidNumberFormat" | "PropertyNameExpected" | "ValueExpected" | "ColonExpected" | "CommaExpected" | "CloseBraceExpected" | "CloseBracketExpected" | "EndOfFileExpected" | "InvalidCommentToken" | "UnexpectedEndOfComment" | "UnexpectedEndOfString" | "UnexpectedEndOfNumber" | "InvalidUnicode" | "InvalidEscapeCharacter" | "InvalidCharacter" | "<unknown ParseErrorCode>";export type NodeType = 'object' | 'array' | 'property' | 'string' | 'number' | 'boolean' | 'null';export interface Node { readonly type: NodeType; readonly value?: any; readonly offset: number; readonly length: number; readonly colonOffset?: number; readonly parent?: Node; readonly children?: Node[];}/** * A {@linkcode JSONPath} segment. Either a string representing an object property name * or a number (starting at 0) for array indices. */export type Segment = string | number;export type JSONPath = Segment[];export interface Location { /** * The previous property key or literal value (string, number, boolean or null) or undefined. */ previousNode?: Node; /** * The path describing the location in the JSON document. The path consists of a sequence of strings * representing an object property or numbers for array indices. */ path: JSONPath; /** * Matches the locations path against a pattern consisting of strings (for properties) and numbers (for array indices). * '*' will match a single segment of any property name or index. * '**' will match a sequence of segments of any property name or index, or no segment. */ matches: (patterns: JSONPath) => boolean; /** * If set, the location's offset is at a property key. */ isAtPropertyKey: boolean;}export interface ParseOptions { disallowComments?: boolean; allowTrailingComma?: boolean; allowEmptyContent?: boolean;}/** * Visitor called by {@linkcode visit} when parsing JSON. * * The visitor functions have the following common parameters: * - `offset`: Global offset within the JSON document, starting at 0 * - `startLine`: Line number, starting at 0 * - `startCharacter`: Start character (column) within the current line, starting at 0 * * Additionally some functions have a `pathSupplier` parameter which can be used to obtain the * current `JSONPath` within the document. */export interface JSONVisitor { /** * Invoked when an open brace is encountered and an object is started. The offset and length represent the location of the open brace. */ onObjectBegin?: (offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; /** * Invoked when a property is encountered. The offset and length represent the location of the property name. * The `JSONPath` created by the `pathSupplier` refers to the enclosing JSON object, it does not include the * property name yet. */ onObjectProperty?: (property: string, offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; /** * Invoked when a closing brace is encountered and an object is completed. The offset and length represent the location of the closing brace. */ onObjectEnd?: (offset: number, length: number, startLine: number, startCharacter: number) => void; /** * Invoked when an open bracket is encountered. The offset and length represent the location of the open bracket. */ onArrayBegin?: (offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; /** * Invoked when a closing bracket is encountered. The offset and length represent the location of the closing bracket. */ onArrayEnd?: (offset: number, length: number, startLine: number, startCharacter: number) => void; /** * Invoked when a literal value is encountered. The offset and length represent the location of the literal value. */ onLiteralValue?: (value: any, offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; /** * Invoked when a comma or colon separator is encountered. The offset and length represent the location of the separator. */ onSeparator?: (character: string, offset: number, length: number, startLine: number, startCharacter: number) => void; /** * When comments are allowed, invoked when a line or block comment is encountered. The offset and length represent the location of the comment. */ onComment?: (offset: number, length: number, startLine: number, startCharacter: number) => void; /** * Invoked on an error. */ onError?: (error: ParseErrorCode, offset: number, length: number, startLine: number, startCharacter: number) => void;}/** * An edit result describes a textual edit operation. It is the result of a {@linkcode format} and {@linkcode modify} operation. * It consist of one or more edits describing insertions, replacements or removals of text segments. * * The offsets of the edits refer to the original state of the document. * * No two edits change or remove the same range of text in the original document. * * Multiple edits can have the same offset if they are multiple inserts, or an insert followed by a remove or replace. * * The order in the array defines which edit is applied first. * To apply an edit result use {@linkcode applyEdits}. * In general multiple EditResults must not be concatenated because they might impact each other, producing incorrect or malformed JSON data. */export type EditResult = Edit[];/** * Represents a text modification */export interface Edit { /** * The start offset of the modification. */ offset: number; /** * The length of the modification. Must not be negative. Empty length represents an *insert*. */ length: number; /** * The new content. Empty content represents a *remove*. */ content: string;}/** * A text range in the document*/export interface Range { /** * The start offset of the range. */ offset: number; /** * The length of the range. Must not be negative. */ length: number;}/** * Options used by {@linkcode format} when computing the formatting edit operations */export interface FormattingOptions { /** * If indentation is based on spaces (`insertSpaces` = true), the number of spaces that make an indent. */ tabSize?: number; /** * Is indentation based on spaces? */ insertSpaces?: boolean; /** * The default 'end of line' character. If not set, '\n' is used as default. */ eol?: string; /** * If set, will add a new line at the end of the document. */ insertFinalNewline?: boolean; /** * If true, will keep line positions as is in the formatting */ keepLines?: boolean;}/** * Computes the edit operations needed to format a JSON document. * * @param documentText The input text * @param range The range to format or `undefined` to format the full content * @param options The formatting options * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}. * To apply the edit operations to the input, use {@linkcode applyEdits}. */export declare function format(documentText: string, range: Range | undefined, options: FormattingOptions): EditResult;/** * Options used by {@linkcode modify} when computing the modification edit operations */export interface ModificationOptions { /** * Formatting options. If undefined, the newly inserted code will be inserted unformatted. */ formattingOptions?: FormattingOptions; /** * Default false. If `JSONPath` refers to an index of an array and `isArrayInsertion` is `true`, then * {@linkcode modify} will insert a new item at that location instead of overwriting its contents. */ isArrayInsertion?: boolean; /** * Optional function to define the insertion index given an existing list of properties. */ getInsertionIndex?: (properties: string[]) => number;}/** * Computes the edit operations needed to modify a value in the JSON document. * * @param documentText The input text * @param path The path of the value to change. The path represents either to the document root, a property or an array item. * If the path points to an non-existing property or item, it will be created. * @param value The new value for the specified property or item. If the value is undefined, * the property or item will be removed. * @param options Options * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}. * To apply the edit operations to the input, use {@linkcode applyEdits}. */export declare function modify(text: string, path: JSONPath, value: any, options: ModificationOptions): EditResult;/** * Applies edits to an input string. * @param text The input text * @param edits Edit operations following the format described in {@linkcode EditResult}. * @returns The text with the applied edits. * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}. */export declare function applyEdits(text: string, edits: EditResult): string;123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178version https://git-lfs.github.com/spec/v1oid sha256:72ff182105e158a1505ca3ecbf3f30359abb138a3980edaef1db7f4010ffb7dcsize 9363/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/'use strict';import * as formatter from './impl/format';import * as edit from './impl/edit';import * as scanner from './impl/scanner';import * as parser from './impl/parser';/** * Creates a JSON scanner on the given text. * If ignoreTrivia is set, whitespaces or comments are ignored. */export const createScanner = scanner.createScanner;export var ScanError;(function (ScanError) { ScanError[ScanError["None"] = 0] = "None"; ScanError[ScanError["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment"; ScanError[ScanError["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString"; ScanError[ScanError["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber"; ScanError[ScanError["InvalidUnicode"] = 4] = "InvalidUnicode"; ScanError[ScanError["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter"; ScanError[ScanError["InvalidCharacter"] = 6] = "InvalidCharacter";})(ScanError || (ScanError = {}));export var SyntaxKind;(function (SyntaxKind) { SyntaxKind[SyntaxKind["OpenBraceToken"] = 1] = "OpenBraceToken"; SyntaxKind[SyntaxKind["CloseBraceToken"] = 2] = "CloseBraceToken"; SyntaxKind[SyntaxKind["OpenBracketToken"] = 3] = "OpenBracketToken"; SyntaxKind[SyntaxKind["CloseBracketToken"] = 4] = "CloseBracketToken"; SyntaxKind[SyntaxKind["CommaToken"] = 5] = "CommaToken"; SyntaxKind[SyntaxKind["ColonToken"] = 6] = "ColonToken"; SyntaxKind[SyntaxKind["NullKeyword"] = 7] = "NullKeyword"; SyntaxKind[SyntaxKind["TrueKeyword"] = 8] = "TrueKeyword"; SyntaxKind[SyntaxKind["FalseKeyword"] = 9] = "FalseKeyword"; SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral"; SyntaxKind[SyntaxKind["NumericLiteral"] = 11] = "NumericLiteral"; SyntaxKind[SyntaxKind["LineCommentTrivia"] = 12] = "LineCommentTrivia"; SyntaxKind[SyntaxKind["BlockCommentTrivia"] = 13] = "BlockCommentTrivia"; SyntaxKind[SyntaxKind["LineBreakTrivia"] = 14] = "LineBreakTrivia"; SyntaxKind[SyntaxKind["Trivia"] = 15] = "Trivia"; SyntaxKind[SyntaxKind["Unknown"] = 16] = "Unknown"; SyntaxKind[SyntaxKind["EOF"] = 17] = "EOF";})(SyntaxKind || (SyntaxKind = {}));/** * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index. */export const getLocation = parser.getLocation;/** * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. * Therefore, always check the errors list to find out if the input was valid. */export const parse = parser.parse;/** * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. */export const parseTree = parser.parseTree;/** * Finds the node at the given path in a JSON DOM. */export const findNodeAtLocation = parser.findNodeAtLocation;/** * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset. */export const findNodeAtOffset = parser.findNodeAtOffset;/** * Gets the JSON path of the given JSON DOM node */export const getNodePath = parser.getNodePath;/** * Evaluates the JavaScript object of the given JSON DOM node */export const getNodeValue = parser.getNodeValue;/** * Parses the given text and invokes the visitor functions for each object, array and literal reached. */export const visit = parser.visit;/** * Takes JSON with JavaScript-style comments and remove * them. Optionally replaces every none-newline character * of comments with a replaceCharacter */export const stripComments = parser.stripComments;export var ParseErrorCode;(function (ParseErrorCode) { ParseErrorCode[ParseErrorCode["InvalidSymbol"] = 1] = "InvalidSymbol"; ParseErrorCode[ParseErrorCode["InvalidNumberFormat"] = 2] = "InvalidNumberFormat"; ParseErrorCode[ParseErrorCode["PropertyNameExpected"] = 3] = "PropertyNameExpected"; ParseErrorCode[ParseErrorCode["ValueExpected"] = 4] = "ValueExpected"; ParseErrorCode[ParseErrorCode["ColonExpected"] = 5] = "ColonExpected"; ParseErrorCode[ParseErrorCode["CommaExpected"] = 6] = "CommaExpected"; ParseErrorCode[ParseErrorCode["CloseBraceExpected"] = 7] = "CloseBraceExpected"; ParseErrorCode[ParseErrorCode["CloseBracketExpected"] = 8] = "CloseBracketExpected"; ParseErrorCode[ParseErrorCode["EndOfFileExpected"] = 9] = "EndOfFileExpected"; ParseErrorCode[ParseErrorCode["InvalidCommentToken"] = 10] = "InvalidCommentToken"; ParseErrorCode[ParseErrorCode["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment"; ParseErrorCode[ParseErrorCode["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString"; ParseErrorCode[ParseErrorCode["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber"; ParseErrorCode[ParseErrorCode["InvalidUnicode"] = 14] = "InvalidUnicode"; ParseErrorCode[ParseErrorCode["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter"; ParseErrorCode[ParseErrorCode["InvalidCharacter"] = 16] = "InvalidCharacter";})(ParseErrorCode || (ParseErrorCode = {}));export function printParseErrorCode(code) { switch (code) { case 1 /* ParseErrorCode.InvalidSymbol */: return 'InvalidSymbol'; case 2 /* ParseErrorCode.InvalidNumberFormat */: return 'InvalidNumberFormat'; case 3 /* ParseErrorCode.PropertyNameExpected */: return 'PropertyNameExpected'; case 4 /* ParseErrorCode.ValueExpected */: return 'ValueExpected'; case 5 /* ParseErrorCode.ColonExpected */: return 'ColonExpected'; case 6 /* ParseErrorCode.CommaExpected */: return 'CommaExpected'; case 7 /* ParseErrorCode.CloseBraceExpected */: return 'CloseBraceExpected'; case 8 /* ParseErrorCode.CloseBracketExpected */: return 'CloseBracketExpected'; case 9 /* ParseErrorCode.EndOfFileExpected */: return 'EndOfFileExpected'; case 10 /* ParseErrorCode.InvalidCommentToken */: return 'InvalidCommentToken'; case 11 /* ParseErrorCode.UnexpectedEndOfComment */: return 'UnexpectedEndOfComment'; case 12 /* ParseErrorCode.UnexpectedEndOfString */: return 'UnexpectedEndOfString'; case 13 /* ParseErrorCode.UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber'; case 14 /* ParseErrorCode.InvalidUnicode */: return 'InvalidUnicode'; case 15 /* ParseErrorCode.InvalidEscapeCharacter */: return 'InvalidEscapeCharacter'; case 16 /* ParseErrorCode.InvalidCharacter */: return 'InvalidCharacter'; } return '<unknown ParseErrorCode>';}/** * Computes the edit operations needed to format a JSON document. * * @param documentText The input text * @param range The range to format or `undefined` to format the full content * @param options The formatting options * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}. * To apply the edit operations to the input, use {@linkcode applyEdits}. */export function format(documentText, range, options) { return formatter.format(documentText, range, options);}/** * Computes the edit operations needed to modify a value in the JSON document. * * @param documentText The input text * @param path The path of the value to change. The path represents either to the document root, a property or an array item. * If the path points to an non-existing property or item, it will be created. * @param value The new value for the specified property or item. If the value is undefined, * the property or item will be removed. * @param options Options * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}. * To apply the edit operations to the input, use {@linkcode applyEdits}. */export function modify(text, path, value, options) { return edit.setProperty(text, path, value, options);}/** * Applies edits to an input string. * @param text The input text * @param edits Edit operations following the format described in {@linkcode EditResult}. * @returns The text with the applied edits. * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}. */export function applyEdits(text, edits) { let sortedEdits = edits.slice(0).sort((a, b) => { const diff = a.offset - b.offset; if (diff === 0) { return a.length - b.length; } return diff; }); let lastModifiedOffset = text.length; for (let i = sortedEdits.length - 1; i >= 0; i--) { let e = sortedEdits[i]; if (e.offset + e.length <= lastModifiedOffset) { text = edit.applyEdit(text, e); } else { throw new Error('Overlapping edit'); } lastModifiedOffset = e.offset; } return text;}123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201version https://git-lfs.github.com/spec/v1oid sha256:9ecd115039cf7a478f223e4a9649170c7f5e8fd8016df1b267723b57553f9483size 10061(function (factory) { if (typeof module === "object" && typeof module.exports === "object") { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === "function" && define.amd) { define(["require", "exports", "./format", "./parser"], factory); }})(function (require, exports) { /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.isWS = exports.applyEdit = exports.setProperty = exports.removeProperty = void 0; const format_1 = require("./format"); const parser_1 = require("./parser"); function removeProperty(text, path, options) { return setProperty(text, path, void 0, options); } exports.removeProperty = removeProperty; function setProperty(text, originalPath, value, options) { const path = originalPath.slice(); const errors = []; const root = (0, parser_1.parseTree)(text, errors); let parent = void 0; let lastSegment = void 0; while (path.length > 0) { lastSegment = path.pop(); parent = (0, parser_1.findNodeAtLocation)(root, path); if (parent === void 0 && value !== void 0) { if (typeof lastSegment === 'string') { value = { [lastSegment]: value }; } else { value = [value]; } } else { break; } } if (!parent) { // empty document if (value === void 0) { // delete throw new Error('Can not delete in empty document'); } return withFormatting(text, { offset: root ? root.offset : 0, length: root ? root.length : 0, content: JSON.stringify(value) }, options); } else if (parent.type === 'object' && typeof lastSegment === 'string' && Array.isArray(parent.children)) { const existing = (0, parser_1.findNodeAtLocation)(parent, [lastSegment]); if (existing !== void 0) { if (value === void 0) { // delete if (!existing.parent) { throw new Error('Malformed AST'); } const propertyIndex = parent.children.indexOf(existing.parent); let removeBegin; let removeEnd = existing.parent.offset + existing.parent.length; if (propertyIndex > 0) { // remove the comma of the previous node let previous = parent.children[propertyIndex - 1]; removeBegin = previous.offset + previous.length; } else { removeBegin = parent.offset + 1; if (parent.children.length > 1) { // remove the comma of the next node let next = parent.children[1]; removeEnd = next.offset; } } return withFormatting(text, { offset: removeBegin, length: removeEnd - removeBegin, content: '' }, options); } else { // set value of existing property return withFormatting(text, { offset: existing.offset, length: existing.length, content: JSON.stringify(value) }, options); } } else { if (value === void 0) { // delete return []; // property does not exist, nothing to do } const newProperty = `${JSON.stringify(lastSegment)}: ${JSON.stringify(value)}`; const index = options.getInsertionIndex ? options.getInsertionIndex(parent.children.map(p => p.children[0].value)) : parent.children.length; let edit; if (index > 0) { let previous = parent.children[index - 1]; edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; } else if (parent.children.length === 0) { edit = { offset: parent.offset + 1, length: 0, content: newProperty }; } else { edit = { offset: parent.offset + 1, length: 0, content: newProperty + ',' }; } return withFormatting(text, edit, options); } } else if (parent.type === 'array' && typeof lastSegment === 'number' && Array.isArray(parent.children)) { const insertIndex = lastSegment; if (insertIndex === -1) { // Insert const newProperty = `${JSON.stringify(value)}`; let edit; if (parent.children.length === 0) { edit = { offset: parent.offset + 1, length: 0, content: newProperty }; } else { const previous = parent.children[parent.children.length - 1]; edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; } return withFormatting(text, edit, options); } else if (value === void 0 && parent.children.length >= 0) { // Removal const removalIndex = lastSegment; const toRemove = parent.children[removalIndex]; let edit; if (parent.children.length === 1) { // only item edit = { offset: parent.offset + 1, length: parent.length - 2, content: '' }; } else if (parent.children.length - 1 === removalIndex) { // last item let previous = parent.children[removalIndex - 1]; let offset = previous.offset + previous.length; let parentEndOffset = parent.offset + parent.length; edit = { offset, length: parentEndOffset - 2 - offset, content: '' }; } else { edit = { offset: toRemove.offset, length: parent.children[removalIndex + 1].offset - toRemove.offset, content: '' }; } return withFormatting(text, edit, options); } else if (value !== void 0) { let edit; const newProperty = `${JSON.stringify(value)}`; if (!options.isArrayInsertion && parent.children.length > lastSegment) { const toModify = parent.children[lastSegment]; edit = { offset: toModify.offset, length: toModify.length, content: newProperty }; } else if (parent.children.length === 0 || lastSegment === 0) { edit = { offset: parent.offset + 1, length: 0, content: parent.children.length === 0 ? newProperty : newProperty + ',' }; } else { const index = lastSegment > parent.children.length ? parent.children.length : lastSegment; const previous = parent.children[index - 1]; edit = { offset: previous.offset + previous.length, length: 0, content: ',' + newProperty }; } return withFormatting(text, edit, options); } else { throw new Error(`Can not ${value === void 0 ? 'remove' : (options.isArrayInsertion ? 'insert' : 'modify')} Array index ${insertIndex} as length is not sufficient`); } } else { throw new Error(`Can not add ${typeof lastSegment !== 'number' ? 'index' : 'property'} to parent of type ${parent.type}`); } } exports.setProperty = setProperty; function withFormatting(text, edit, options) { if (!options.formattingOptions) { return [edit]; } // apply the edit let newText = applyEdit(text, edit); // format the new text let begin = edit.offset; let end = edit.offset + edit.content.length; if (edit.length === 0 || edit.content.length === 0) { // insert or remove while (begin > 0 && !(0, format_1.isEOL)(newText, begin - 1)) { begin--; } while (end < newText.length && !(0, format_1.isEOL)(newText, end)) { end++; } } const edits = (0, format_1.format)(newText, { offset: begin, length: end - begin }, { ...options.formattingOptions, keepLines: false }); // apply the formatting edits and track the begin and end offsets of the changes for (let i = edits.length - 1; i >= 0; i--) { const edit = edits[i]; newText = applyEdit(newText, edit); begin = Math.min(begin, edit.offset); end = Math.max(end, edit.offset + edit.length); end += edit.content.length - edit.length; } // create a single edit with all changes const editLength = text.length - (newText.length - end) - begin; return [{ offset: begin, length: editLength, content: newText.substring(begin, end) }]; } function applyEdit(text, edit) { return text.substring(0, edit.offset) + edit.content + text.substring(edit.offset + edit.length); } exports.applyEdit = applyEdit; function isWS(text, offset) { return '\r\n \t'.indexOf(text.charAt(offset)) !== -1; } exports.isWS = isWS;});123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275version https://git-lfs.github.com/spec/v1oid sha256:f9e468e436bf1014a4395b1ac70374edb918739ba90b19e6e6a22ca0214564a9size 12888(function (factory) { if (typeof module === "object" && typeof module.exports === "object") { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === "function" && define.amd) { define(["require", "exports", "./scanner", "./string-intern"], factory); }})(function (require, exports) { /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.isEOL = exports.format = void 0; const scanner_1 = require("./scanner"); const string_intern_1 = require("./string-intern"); function format(documentText, range, options) { let initialIndentLevel; let formatText; let formatTextStart; let rangeStart; let rangeEnd; if (range) { rangeStart = range.offset; rangeEnd = rangeStart + range.length; formatTextStart = rangeStart; while (formatTextStart > 0 && !isEOL(documentText, formatTextStart - 1)) { formatTextStart--; } let endOffset = rangeEnd; while (endOffset < documentText.length && !isEOL(documentText, endOffset)) { endOffset++; } formatText = documentText.substring(formatTextStart, endOffset); initialIndentLevel = computeIndentLevel(formatText, options); } else { formatText = documentText; initialIndentLevel = 0; formatTextStart = 0; rangeStart = 0; rangeEnd = documentText.length; } const eol = getEOL(options, documentText); const eolFastPathSupported = string_intern_1.supportedEols.includes(eol); let numberLineBreaks = 0; let indentLevel = 0; let indentValue; if (options.insertSpaces) { indentValue = string_intern_1.cachedSpaces[options.tabSize || 4] ?? repeat(string_intern_1.cachedSpaces[1], options.tabSize || 4); } else { indentValue = '\t'; } const indentType = indentValue === '\t' ? '\t' : ' '; let scanner = (0, scanner_1.createScanner)(formatText, false); let hasError = false; function newLinesAndIndent() { if (numberLineBreaks > 1) { return repeat(eol, numberLineBreaks) + repeat(indentValue, initialIndentLevel + indentLevel); } const amountOfSpaces = indentValue.length * (initialIndentLevel + indentLevel); if (!eolFastPathSupported || amountOfSpaces > string_intern_1.cachedBreakLinesWithSpaces[indentType][eol].length) { return eol + repeat(indentValue, initialIndentLevel + indentLevel); } if (amountOfSpaces <= 0) { return eol; } return string_intern_1.cachedBreakLinesWithSpaces[indentType][eol][amountOfSpaces]; } function scanNext() { let token = scanner.scan(); numberLineBreaks = 0; while (token === 15 /* SyntaxKind.Trivia */ || token === 14 /* SyntaxKind.LineBreakTrivia */) { if (token === 14 /* SyntaxKind.LineBreakTrivia */ && options.keepLines) { numberLineBreaks += 1; } else if (token === 14 /* SyntaxKind.LineBreakTrivia */) { numberLineBreaks = 1; } token = scanner.scan(); } hasError = token === 16 /* SyntaxKind.Unknown */ || scanner.getTokenError() !== 0 /* ScanError.None */; return token; } const editOperations = []; function addEdit(text, startOffset, endOffset) { if (!hasError && (!range || (startOffset < rangeEnd && endOffset > rangeStart)) && documentText.substring(startOffset, endOffset) !== text) { editOperations.push({ offset: startOffset, length: endOffset - startOffset, content: text }); } } let firstToken = scanNext(); if (options.keepLines && numberLineBreaks > 0) { addEdit(repeat(eol, numberLineBreaks), 0, 0); } if (firstToken !== 17 /* SyntaxKind.EOF */) { let firstTokenStart = scanner.getTokenOffset() + formatTextStart; let initialIndent = (indentValue.length * initialIndentLevel < 20) && options.insertSpaces ? string_intern_1.cachedSpaces[indentValue.length * initialIndentLevel] : repeat(indentValue, initialIndentLevel); addEdit(initialIndent, formatTextStart, firstTokenStart); } while (firstToken !== 17 /* SyntaxKind.EOF */) { let firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart; let secondToken = scanNext(); let replaceContent = ''; let needsLineBreak = false; while (numberLineBreaks === 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) { let commentTokenStart = scanner.getTokenOffset() + formatTextStart; addEdit(string_intern_1.cachedSpaces[1], firstTokenEnd, commentTokenStart); firstTokenEnd = scanner.getTokenOffset() + scanner.getTokenLength() + formatTextStart; needsLineBreak = secondToken === 12 /* SyntaxKind.LineCommentTrivia */; replaceContent = needsLineBreak ? newLinesAndIndent() : ''; secondToken = scanNext(); } if (secondToken === 2 /* SyntaxKind.CloseBraceToken */) { if (firstToken !== 1 /* SyntaxKind.OpenBraceToken */) { indentLevel--; } ; if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 1 /* SyntaxKind.OpenBraceToken */) { replaceContent = newLinesAndIndent(); } else if (options.keepLines) { replaceContent = string_intern_1.cachedSpaces[1]; } } else if (secondToken === 4 /* SyntaxKind.CloseBracketToken */) { if (firstToken !== 3 /* SyntaxKind.OpenBracketToken */) { indentLevel--; } ; if (options.keepLines && numberLineBreaks > 0 || !options.keepLines && firstToken !== 3 /* SyntaxKind.OpenBracketToken */) { replaceContent = newLinesAndIndent(); } else if (options.keepLines) { replaceContent = string_intern_1.cachedSpaces[1]; } } else { switch (firstToken) { case 3 /* SyntaxKind.OpenBracketToken */: case 1 /* SyntaxKind.OpenBraceToken */: indentLevel++; if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) { replaceContent = newLinesAndIndent(); } else { replaceContent = string_intern_1.cachedSpaces[1]; } break; case 5 /* SyntaxKind.CommaToken */: if (options.keepLines && numberLineBreaks > 0 || !options.keepLines) { replaceContent = newLinesAndIndent(); } else { replaceContent = string_intern_1.cachedSpaces[1]; } break; case 12 /* SyntaxKind.LineCommentTrivia */: replaceContent = newLinesAndIndent(); break; case 13 /* SyntaxKind.BlockCommentTrivia */: if (numberLineBreaks > 0) { replaceContent = newLinesAndIndent(); } else if (!needsLineBreak) { replaceContent = string_intern_1.cachedSpaces[1]; } break; case 6 /* SyntaxKind.ColonToken */: if (options.keepLines && numberLineBreaks > 0) { replaceContent = newLinesAndIndent(); } else if (!needsLineBreak) { replaceContent = string_intern_1.cachedSpaces[1]; } break; case 10 /* SyntaxKind.StringLiteral */: if (options.keepLines && numberLineBreaks > 0) { replaceContent = newLinesAndIndent(); } else if (secondToken === 6 /* SyntaxKind.ColonToken */ && !needsLineBreak) { replaceContent = ''; } break; case 7 /* SyntaxKind.NullKeyword */: case 8 /* SyntaxKind.TrueKeyword */: case 9 /* SyntaxKind.FalseKeyword */: case 11 /* SyntaxKind.NumericLiteral */: case 2 /* SyntaxKind.CloseBraceToken */: case 4 /* SyntaxKind.CloseBracketToken */: if (options.keepLines && numberLineBreaks > 0) { replaceContent = newLinesAndIndent(); } else { if ((secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */) && !needsLineBreak) { replaceContent = string_intern_1.cachedSpaces[1]; } else if (secondToken !== 5 /* SyntaxKind.CommaToken */ && secondToken !== 17 /* SyntaxKind.EOF */) { hasError = true; } } break; case 16 /* SyntaxKind.Unknown */: hasError = true; break; } if (numberLineBreaks > 0 && (secondToken === 12 /* SyntaxKind.LineCommentTrivia */ || secondToken === 13 /* SyntaxKind.BlockCommentTrivia */)) { replaceContent = newLinesAndIndent(); } } if (secondToken === 17 /* SyntaxKind.EOF */) { if (options.keepLines && numberLineBreaks > 0) { replaceContent = newLinesAndIndent(); } else { replaceContent = options.insertFinalNewline ? eol : ''; } } const secondTokenStart = scanner.getTokenOffset() + formatTextStart; addEdit(replaceContent, firstTokenEnd, secondTokenStart); firstToken = secondToken; } return editOperations; } exports.format = format; function repeat(s, count) { let result = ''; for (let i = 0; i < count; i++) { result += s; } return result; } function computeIndentLevel(content, options) { let i = 0; let nChars = 0; const tabSize = options.tabSize || 4; while (i < content.length) { let ch = content.charAt(i); if (ch === string_intern_1.cachedSpaces[1]) { nChars++; } else if (ch === '\t') { nChars += tabSize; } else { break; } i++; } return Math.floor(nChars / tabSize); } function getEOL(options, text) { for (let i = 0; i < text.length; i++) { const ch = text.charAt(i); if (ch === '\r') { if (i + 1 < text.length && text.charAt(i + 1) === '\n') { return '\r\n'; } return '\r'; } else if (ch === '\n') { return '\n'; } } return (options && options.eol) || '\n'; } function isEOL(text, offset) { return '\r\n'.indexOf(text.charAt(offset)) !== -1; } exports.isEOL = isEOL;});123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655version https://git-lfs.github.com/spec/v1oid sha256:c75be447c5ebcd16b212ae7089b1d2438f037c709c6b1784d22c25b8a35fde48size 28290(function (factory) { if (typeof module === "object" && typeof module.exports === "object") { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === "function" && define.amd) { define(["require", "exports", "./scanner"], factory); }})(function (require, exports) { /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.getNodeType = exports.stripComments = exports.visit = exports.findNodeAtOffset = exports.contains = exports.getNodeValue = exports.getNodePath = exports.findNodeAtLocation = exports.parseTree = exports.parse = exports.getLocation = void 0; const scanner_1 = require("./scanner"); var ParseOptions; (function (ParseOptions) { ParseOptions.DEFAULT = { allowTrailingComma: false }; })(ParseOptions || (ParseOptions = {})); /** * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index. */ function getLocation(text, position) { const segments = []; // strings or numbers const earlyReturnException = new Object(); let previousNode = undefined; const previousNodeInst = { value: {}, offset: 0, length: 0, type: 'object', parent: undefined }; let isAtPropertyKey = false; function setPreviousNode(value, offset, length, type) { previousNodeInst.value = value; previousNodeInst.offset = offset; previousNodeInst.length = length; previousNodeInst.type = type; previousNodeInst.colonOffset = undefined; previousNode = previousNodeInst; } try { visit(text, { onObjectBegin: (offset, length) => { if (position <= offset) { throw earlyReturnException; } previousNode = undefined; isAtPropertyKey = position > offset; segments.push(''); // push a placeholder (will be replaced) }, onObjectProperty: (name, offset, length) => { if (position < offset) { throw earlyReturnException; } setPreviousNode(name, offset, length, 'property'); segments[segments.length - 1] = name; if (position <= offset + length) { throw earlyReturnException; } }, onObjectEnd: (offset, length) => { if (position <= offset) { throw earlyReturnException; } previousNode = undefined; segments.pop(); }, onArrayBegin: (offset, length) => { if (position <= offset) { throw earlyReturnException; } previousNode = undefined; segments.push(0); }, onArrayEnd: (offset, length) => { if (position <= offset) { throw earlyReturnException; } previousNode = undefined; segments.pop(); }, onLiteralValue: (value, offset, length) => { if (position < offset) { throw earlyReturnException; } setPreviousNode(value, offset, length, getNodeType(value)); if (position <= offset + length) { throw earlyReturnException; } }, onSeparator: (sep, offset, length) => { if (position <= offset) { throw earlyReturnException; } if (sep === ':' && previousNode && previousNode.type === 'property') { previousNode.colonOffset = offset; isAtPropertyKey = false; previousNode = undefined; } else if (sep === ',') { const last = segments[segments.length - 1]; if (typeof last === 'number') { segments[segments.length - 1] = last + 1; } else { isAtPropertyKey = true; segments[segments.length - 1] = ''; } previousNode = undefined; } } }); } catch (e) { if (e !== earlyReturnException) { throw e; } } return { path: segments, previousNode, isAtPropertyKey, matches: (pattern) => { let k = 0; for (let i = 0; k < pattern.length && i < segments.length; i++) { if (pattern[k] === segments[i] || pattern[k] === '*') { k++; } else if (pattern[k] !== '**') { return false; } } return k === pattern.length; } }; } exports.getLocation = getLocation; /** * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. * Therefore always check the errors list to find out if the input was valid. */ function parse(text, errors = [], options = ParseOptions.DEFAULT) { let currentProperty = null; let currentParent = []; const previousParents = []; function onValue(value) { if (Array.isArray(currentParent)) { currentParent.push(value); } else if (currentProperty !== null) { currentParent[currentProperty] = value; } } const visitor = { onObjectBegin: () => { const object = {}; onValue(object); previousParents.push(currentParent); currentParent = object; currentProperty = null; }, onObjectProperty: (name) => { currentProperty = name; }, onObjectEnd: () => { currentParent = previousParents.pop(); }, onArrayBegin: () => { const array = []; onValue(array); previousParents.push(currentParent); currentParent = array; currentProperty = null; }, onArrayEnd: () => { currentParent = previousParents.pop(); }, onLiteralValue: onValue, onError: (error, offset, length) => { errors.push({ error, offset, length }); } }; visit(text, visitor, options); return currentParent[0]; } exports.parse = parse; /** * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. */ function parseTree(text, errors = [], options = ParseOptions.DEFAULT) { let currentParent = { type: 'array', offset: -1, length: -1, children: [], parent: undefined }; // artificial root function ensurePropertyComplete(endOffset) { if (currentParent.type === 'property') { currentParent.length = endOffset - currentParent.offset; currentParent = currentParent.parent; } } function onValue(valueNode) { currentParent.children.push(valueNode); return valueNode; } const visitor = { onObjectBegin: (offset) => { currentParent = onValue({ type: 'object', offset, length: -1, parent: currentParent, children: [] }); }, onObjectProperty: (name, offset, length) => { currentParent = onValue({ type: 'property', offset, length: -1, parent: currentParent, children: [] }); currentParent.children.push({ type: 'string', value: name, offset, length, parent: currentParent }); }, onObjectEnd: (offset, length) => { ensurePropertyComplete(offset + length); // in case of a missing value for a property: make sure property is complete currentParent.length = offset + length - currentParent.offset; currentParent = currentParent.parent; ensurePropertyComplete(offset + length); }, onArrayBegin: (offset, length) => { currentParent = onValue({ type: 'array', offset, length: -1, parent: currentParent, children: [] }); }, onArrayEnd: (offset, length) => { currentParent.length = offset + length - currentParent.offset; currentParent = currentParent.parent; ensurePropertyComplete(offset + length); }, onLiteralValue: (value, offset, length) => { onValue({ type: getNodeType(value), offset, length, parent: currentParent, value }); ensurePropertyComplete(offset + length); }, onSeparator: (sep, offset, length) => { if (currentParent.type === 'property') { if (sep === ':') { currentParent.colonOffset = offset; } else if (sep === ',') { ensurePropertyComplete(offset); } } }, onError: (error, offset, length) => { errors.push({ error, offset, length }); } }; visit(text, visitor, options); const result = currentParent.children[0]; if (result) { delete result.parent; } return result; } exports.parseTree = parseTree; /** * Finds the node at the given path in a JSON DOM. */ function findNodeAtLocation(root, path) { if (!root) { return undefined; } let node = root; for (let segment of path) { if (typeof segment === 'string') { if (node.type !== 'object' || !Array.isArray(node.children)) { return undefined; } let found = false; for (const propertyNode of node.children) { if (Array.isArray(propertyNode.children) && propertyNode.children[0].value === segment && propertyNode.children.length === 2) { node = propertyNode.children[1]; found = true; break; } } if (!found) { return undefined; } } else { const index = segment; if (node.type !== 'array' || index < 0 || !Array.isArray(node.children) || index >= node.children.length) { return undefined; } node = node.children[index]; } } return node; } exports.findNodeAtLocation = findNodeAtLocation; /** * Gets the JSON path of the given JSON DOM node */ function getNodePath(node) { if (!node.parent || !node.parent.children) { return []; } const path = getNodePath(node.parent); if (node.parent.type === 'property') { const key = node.parent.children[0].value; path.push(key); } else if (node.parent.type === 'array') { const index = node.parent.children.indexOf(node); if (index !== -1) { path.push(index); } } return path; } exports.getNodePath = getNodePath; /** * Evaluates the JavaScript object of the given JSON DOM node */ function getNodeValue(node) { switch (node.type) { case 'array': return node.children.map(getNodeValue); case 'object': const obj = Object.create(null); for (let prop of node.children) { const valueNode = prop.children[1]; if (valueNode) { obj[prop.children[0].value] = getNodeValue(valueNode); } } return obj; case 'null': case 'string': case 'number': case 'boolean': return node.value; default: return undefined; } } exports.getNodeValue = getNodeValue; function contains(node, offset, includeRightBound = false) { return (offset >= node.offset && offset < (node.offset + node.length)) || includeRightBound && (offset === (node.offset + node.length)); } exports.contains = contains; /** * Finds the most inner node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset. */ function findNodeAtOffset(node, offset, includeRightBound = false) { if (contains(node, offset, includeRightBound)) { const children = node.children; if (Array.isArray(children)) { for (let i = 0; i < children.length && children[i].offset <= offset; i++) { const item = findNodeAtOffset(children[i], offset, includeRightBound); if (item) { return item; } } } return node; } return undefined; } exports.findNodeAtOffset = findNodeAtOffset; /** * Parses the given text and invokes the visitor functions for each object, array and literal reached. */ function visit(text, visitor, options = ParseOptions.DEFAULT) { const _scanner = (0, scanner_1.createScanner)(text, false); // Important: Only pass copies of this to visitor functions to prevent accidental modification, and // to not affect visitor functions which stored a reference to a previous JSONPath const _jsonPath = []; function toNoArgVisit(visitFunction) { return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true; } function toNoArgVisitWithPath(visitFunction) { return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true; } function toOneArgVisit(visitFunction) { return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true; } function toOneArgVisitWithPath(visitFunction) { return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true; } const onObjectBegin = toNoArgVisitWithPath(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisitWithPath(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError); const disallowComments = options && options.disallowComments; const allowTrailingComma = options && options.allowTrailingComma; function scanNext() { while (true) { const token = _scanner.scan(); switch (_scanner.getTokenError()) { case 4 /* ScanError.InvalidUnicode */: handleError(14 /* ParseErrorCode.InvalidUnicode */); break; case 5 /* ScanError.InvalidEscapeCharacter */: handleError(15 /* ParseErrorCode.InvalidEscapeCharacter */); break; case 3 /* ScanError.UnexpectedEndOfNumber */: handleError(13 /* ParseErrorCode.UnexpectedEndOfNumber */); break; case 1 /* ScanError.UnexpectedEndOfComment */: if (!disallowComments) { handleError(11 /* ParseErrorCode.UnexpectedEndOfComment */); } break; case 2 /* ScanError.UnexpectedEndOfString */: handleError(12 /* ParseErrorCode.UnexpectedEndOfString */); break; case 6 /* ScanError.InvalidCharacter */: handleError(16 /* ParseErrorCode.InvalidCharacter */); break; } switch (token) { case 12 /* SyntaxKind.LineCommentTrivia */: case 13 /* SyntaxKind.BlockCommentTrivia */: if (disallowComments) { handleError(10 /* ParseErrorCode.InvalidCommentToken */); } else { onComment(); } break; case 16 /* SyntaxKind.Unknown */: handleError(1 /* ParseErrorCode.InvalidSymbol */); break; case 15 /* SyntaxKind.Trivia */: case 14 /* SyntaxKind.LineBreakTrivia */: break; default: return token; } } } function handleError(error, skipUntilAfter = [], skipUntil = []) { onError(error); if (skipUntilAfter.length + skipUntil.length > 0) { let token = _scanner.getToken(); while (token !== 17 /* SyntaxKind.EOF */) { if (skipUntilAfter.indexOf(token) !== -1) { scanNext(); break; } else if (skipUntil.indexOf(token) !== -1) { break; } token = scanNext(); } } } function parseString(isValue) { const value = _scanner.getTokenValue(); if (isValue) { onLiteralValue(value); } else { onObjectProperty(value); // add property name afterwards _jsonPath.push(value); } scanNext(); return true; } function parseLiteral() { switch (_scanner.getToken()) { case 11 /* SyntaxKind.NumericLiteral */: const tokenValue = _scanner.getTokenValue(); let value = Number(tokenValue); if (isNaN(value)) { handleError(2 /* ParseErrorCode.InvalidNumberFormat */); value = 0; } onLiteralValue(value); break; case 7 /* SyntaxKind.NullKeyword */: onLiteralValue(null); break; case 8 /* SyntaxKind.TrueKeyword */: onLiteralValue(true); break; case 9 /* SyntaxKind.FalseKeyword */: onLiteralValue(false); break; default: return false; } scanNext(); return true; } function parseProperty() { if (_scanner.getToken() !== 10 /* SyntaxKind.StringLiteral */) { handleError(3 /* ParseErrorCode.PropertyNameExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); return false; } parseString(false); if (_scanner.getToken() === 6 /* SyntaxKind.ColonToken */) { onSeparator(':'); scanNext(); // consume colon if (!parseValue()) { handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); } } else { handleError(5 /* ParseErrorCode.ColonExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); } _jsonPath.pop(); // remove processed property name return true; } function parseObject() { onObjectBegin(); scanNext(); // consume open brace let needsComma = false; while (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) { if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) { if (!needsComma) { handleError(4 /* ParseErrorCode.ValueExpected */, [], []); } onSeparator(','); scanNext(); // consume comma if (_scanner.getToken() === 2 /* SyntaxKind.CloseBraceToken */ && allowTrailingComma) { break; } } else if (needsComma) { handleError(6 /* ParseErrorCode.CommaExpected */, [], []); } if (!parseProperty()) { handleError(4 /* ParseErrorCode.ValueExpected */, [], [2 /* SyntaxKind.CloseBraceToken */, 5 /* SyntaxKind.CommaToken */]); } needsComma = true; } onObjectEnd(); if (_scanner.getToken() !== 2 /* SyntaxKind.CloseBraceToken */) { handleError(7 /* ParseErrorCode.CloseBraceExpected */, [2 /* SyntaxKind.CloseBraceToken */], []); } else { scanNext(); // consume close brace } return true; } function parseArray() { onArrayBegin(); scanNext(); // consume open bracket let isFirstElement = true; let needsComma = false; while (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */ && _scanner.getToken() !== 17 /* SyntaxKind.EOF */) { if (_scanner.getToken() === 5 /* SyntaxKind.CommaToken */) { if (!needsComma) { handleError(4 /* ParseErrorCode.ValueExpected */, [], []); } onSeparator(','); scanNext(); // consume comma if (_scanner.getToken() === 4 /* SyntaxKind.CloseBracketToken */ && allowTrailingComma) { break; } } else if (needsComma) { handleError(6 /* ParseErrorCode.CommaExpected */, [], []); } if (isFirstElement) { _jsonPath.push(0); isFirstElement = false; } else { _jsonPath[_jsonPath.length - 1]++; } if (!parseValue()) { handleError(4 /* ParseErrorCode.ValueExpected */, [], [4 /* SyntaxKind.CloseBracketToken */, 5 /* SyntaxKind.CommaToken */]); } needsComma = true; } onArrayEnd(); if (!isFirstElement) { _jsonPath.pop(); // remove array index } if (_scanner.getToken() !== 4 /* SyntaxKind.CloseBracketToken */) { handleError(8 /* ParseErrorCode.CloseBracketExpected */, [4 /* SyntaxKind.CloseBracketToken */], []); } else { scanNext(); // consume close bracket } return true; } function parseValue() { switch (_scanner.getToken()) { case 3 /* SyntaxKind.OpenBracketToken */: return parseArray(); case 1 /* SyntaxKind.OpenBraceToken */: return parseObject(); case 10 /* SyntaxKind.StringLiteral */: return parseString(true); default: return parseLiteral(); } } scanNext(); if (_scanner.getToken() === 17 /* SyntaxKind.EOF */) { if (options.allowEmptyContent) { return true; } handleError(4 /* ParseErrorCode.ValueExpected */, [], []); return false; } if (!parseValue()) { handleError(4 /* ParseErrorCode.ValueExpected */, [], []); return false; } if (_scanner.getToken() !== 17 /* SyntaxKind.EOF */) { handleError(9 /* ParseErrorCode.EndOfFileExpected */, [], []); } return true; } exports.visit = visit; /** * Takes JSON with JavaScript-style comments and remove * them. Optionally replaces every none-newline character * of comments with a replaceCharacter */ function stripComments(text, replaceCh) { let _scanner = (0, scanner_1.createScanner)(text), parts = [], kind, offset = 0, pos; do { pos = _scanner.getPosition(); kind = _scanner.scan(); switch (kind) { case 12 /* SyntaxKind.LineCommentTrivia */: case 13 /* SyntaxKind.BlockCommentTrivia */: case 17 /* SyntaxKind.EOF */: if (offset !== pos) { parts.push(text.substring(offset, pos)); } if (replaceCh !== undefined) { parts.push(_scanner.getTokenValue().replace(/[^\r\n]/g, replaceCh)); } offset = _scanner.getPosition(); break; } } while (kind !== 17 /* SyntaxKind.EOF */); return parts.join(''); } exports.stripComments = stripComments; function getNodeType(value) { switch (typeof value) { case 'boolean': return 'boolean'; case 'number': return 'number'; case 'string': return 'string'; case 'object': { if (!value) { return 'null'; } else if (Array.isArray(value)) { return 'array'; } return 'object'; } default: return 'null'; } } exports.getNodeType = getNodeType;});123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456version https://git-lfs.github.com/spec/v1oid sha256:581d82c4f1aa84b0605369c01f414fb0164ee462e03daa298cb960076a2a9e82size 21446(function (factory) { if (typeof module === "object" && typeof module.exports === "object") { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === "function" && define.amd) { define(["require", "exports"], factory); }})(function (require, exports) { /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.createScanner = void 0; /** * Creates a JSON scanner on the given text. * If ignoreTrivia is set, whitespaces or comments are ignored. */ function createScanner(text, ignoreTrivia = false) { const len = text.length; let pos = 0, value = '', tokenOffset = 0, token = 16 /* SyntaxKind.Unknown */, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0 /* ScanError.None */; function scanHexDigits(count, exact) { let digits = 0; let value = 0; while (digits < count || !exact) { let ch = text.charCodeAt(pos); if (ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */) { value = value * 16 + ch - 48 /* CharacterCodes._0 */; } else if (ch >= 65 /* CharacterCodes.A */ && ch <= 70 /* CharacterCodes.F */) { value = value * 16 + ch - 65 /* CharacterCodes.A */ + 10; } else if (ch >= 97 /* CharacterCodes.a */ && ch <= 102 /* CharacterCodes.f */) { value = value * 16 + ch - 97 /* CharacterCodes.a */ + 10; } else { break; } pos++; digits++; } if (digits < count) { value = -1; } return value; } function setPosition(newPosition) { pos = newPosition; value = ''; tokenOffset = 0; token = 16 /* SyntaxKind.Unknown */; scanError = 0 /* ScanError.None */; } function scanNumber() { let start = pos; if (text.charCodeAt(pos) === 48 /* CharacterCodes._0 */) { pos++; } else { pos++; while (pos < text.length && isDigit(text.charCodeAt(pos))) { pos++; } } if (pos < text.length && text.charCodeAt(pos) === 46 /* CharacterCodes.dot */) { pos++; if (pos < text.length && isDigit(text.charCodeAt(pos))) { pos++; while (pos < text.length && isDigit(text.charCodeAt(pos))) { pos++; } } else { scanError = 3 /* ScanError.UnexpectedEndOfNumber */; return text.substring(start, pos); } } let end = pos; if (pos < text.length && (text.charCodeAt(pos) === 69 /* CharacterCodes.E */ || text.charCodeAt(pos) === 101 /* CharacterCodes.e */)) { pos++; if (pos < text.length && text.charCodeAt(pos) === 43 /* CharacterCodes.plus */ || text.charCodeAt(pos) === 45 /* CharacterCodes.minus */) { pos++; } if (pos < text.length && isDigit(text.charCodeAt(pos))) { pos++; while (pos < text.length && isDigit(text.charCodeAt(pos))) { pos++; } end = pos; } else { scanError = 3 /* ScanError.UnexpectedEndOfNumber */; } } return text.substring(start, end); } function scanString() { let result = '', start = pos; while (true) { if (pos >= len) { result += text.substring(start, pos); scanError = 2 /* ScanError.UnexpectedEndOfString */; break; } const ch = text.charCodeAt(pos); if (ch === 34 /* CharacterCodes.doubleQuote */) { result += text.substring(start, pos); pos++; break; } if (ch === 92 /* CharacterCodes.backslash */) { result += text.substring(start, pos); pos++; if (pos >= len) { scanError = 2 /* ScanError.UnexpectedEndOfString */; break; } const ch2 = text.charCodeAt(pos++); switch (ch2) { case 34 /* CharacterCodes.doubleQuote */: result += '\"'; break; case 92 /* CharacterCodes.backslash */: result += '\\'; break; case 47 /* CharacterCodes.slash */: result += '/'; break; case 98 /* CharacterCodes.b */: result += '\b'; break; case 102 /* CharacterCodes.f */: result += '\f'; break; case 110 /* CharacterCodes.n */: result += '\n'; break; case 114 /* CharacterCodes.r */: result += '\r'; break; case 116 /* CharacterCodes.t */: result += '\t'; break; case 117 /* CharacterCodes.u */: const ch3 = scanHexDigits(4, true); if (ch3 >= 0) { result += String.fromCharCode(ch3); } else { scanError = 4 /* ScanError.InvalidUnicode */; } break; default: scanError = 5 /* ScanError.InvalidEscapeCharacter */; } start = pos; continue; } if (ch >= 0 && ch <= 0x1f) { if (isLineBreak(ch)) { result += text.substring(start, pos); scanError = 2 /* ScanError.UnexpectedEndOfString */; break; } else { scanError = 6 /* ScanError.InvalidCharacter */; // mark as error but continue with string } } pos++; } return result; } function scanNext() { value = ''; scanError = 0 /* ScanError.None */; tokenOffset = pos; lineStartOffset = lineNumber; prevTokenLineStartOffset = tokenLineStartOffset; if (pos >= len) { // at the end tokenOffset = len; return token = 17 /* SyntaxKind.EOF */; } let code = text.charCodeAt(pos); // trivia: whitespace if (isWhiteSpace(code)) { do { pos++; value += String.fromCharCode(code); code = text.charCodeAt(pos); } while (isWhiteSpace(code)); return token = 15 /* SyntaxKind.Trivia */; } // trivia: newlines if (isLineBreak(code)) { pos++; value += String.fromCharCode(code); if (code === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) { pos++; value += '\n'; } lineNumber++; tokenLineStartOffset = pos; return token = 14 /* SyntaxKind.LineBreakTrivia */; } switch (code) { // tokens: []{}:, case 123 /* CharacterCodes.openBrace */: pos++; return token = 1 /* SyntaxKind.OpenBraceToken */; case 125 /* CharacterCodes.closeBrace */: pos++; return token = 2 /* SyntaxKind.CloseBraceToken */; case 91 /* CharacterCodes.openBracket */: pos++; return token = 3 /* SyntaxKind.OpenBracketToken */; case 93 /* CharacterCodes.closeBracket */: pos++; return token = 4 /* SyntaxKind.CloseBracketToken */; case 58 /* CharacterCodes.colon */: pos++; return token = 6 /* SyntaxKind.ColonToken */; case 44 /* CharacterCodes.comma */: pos++; return token = 5 /* SyntaxKind.CommaToken */; // strings case 34 /* CharacterCodes.doubleQuote */: pos++; value = scanString(); return token = 10 /* SyntaxKind.StringLiteral */; // comments case 47 /* CharacterCodes.slash */: const start = pos - 1; // Single-line comment if (text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) { pos += 2; while (pos < len) { if (isLineBreak(text.charCodeAt(pos))) { break; } pos++; } value = text.substring(start, pos); return token = 12 /* SyntaxKind.LineCommentTrivia */; } // Multi-line comment if (text.charCodeAt(pos + 1) === 42 /* CharacterCodes.asterisk */) { pos += 2; const safeLength = len - 1; // For lookahead. let commentClosed = false; while (pos < safeLength) { const ch = text.charCodeAt(pos); if (ch === 42 /* CharacterCodes.asterisk */ && text.charCodeAt(pos + 1) === 47 /* CharacterCodes.slash */) { pos += 2; commentClosed = true; break; } pos++; if (isLineBreak(ch)) { if (ch === 13 /* CharacterCodes.carriageReturn */ && text.charCodeAt(pos) === 10 /* CharacterCodes.lineFeed */) { pos++; } lineNumber++; tokenLineStartOffset = pos; } } if (!commentClosed) { pos++; scanError = 1 /* ScanError.UnexpectedEndOfComment */; } value = text.substring(start, pos); return token = 13 /* SyntaxKind.BlockCommentTrivia */; } // just a single slash value += String.fromCharCode(code); pos++; return token = 16 /* SyntaxKind.Unknown */; // numbers case 45 /* CharacterCodes.minus */: value += String.fromCharCode(code); pos++; if (pos === len || !isDigit(text.charCodeAt(pos))) { return token = 16 /* SyntaxKind.Unknown */; } // found a minus, followed by a number so // we fall through to proceed with scanning // numbers case 48 /* CharacterCodes._0 */: case 49 /* CharacterCodes._1 */: case 50 /* CharacterCodes._2 */: case 51 /* CharacterCodes._3 */: case 52 /* CharacterCodes._4 */: case 53 /* CharacterCodes._5 */: case 54 /* CharacterCodes._6 */: case 55 /* CharacterCodes._7 */: case 56 /* CharacterCodes._8 */: case 57 /* CharacterCodes._9 */: value += scanNumber(); return token = 11 /* SyntaxKind.NumericLiteral */; // literals and unknown symbols default: // is a literal? Read the full word. while (pos < len && isUnknownContentCharacter(code)) { pos++; code = text.charCodeAt(pos); } if (tokenOffset !== pos) { value = text.substring(tokenOffset, pos); // keywords: true, false, null switch (value) { case 'true': return token = 8 /* SyntaxKind.TrueKeyword */; case 'false': return token = 9 /* SyntaxKind.FalseKeyword */; case 'null': return token = 7 /* SyntaxKind.NullKeyword */; } return token = 16 /* SyntaxKind.Unknown */; } // some value += String.fromCharCode(code); pos++; return token = 16 /* SyntaxKind.Unknown */; } } function isUnknownContentCharacter(code) { if (isWhiteSpace(code) || isLineBreak(code)) { return false; } switch (code) { case 125 /* CharacterCodes.closeBrace */: case 93 /* CharacterCodes.closeBracket */: case 123 /* CharacterCodes.openBrace */: case 91 /* CharacterCodes.openBracket */: case 34 /* CharacterCodes.doubleQuote */: case 58 /* CharacterCodes.colon */: case 44 /* CharacterCodes.comma */: case 47 /* CharacterCodes.slash */: return false; } return true; } function scanNextNonTrivia() { let result; do { result = scanNext(); } while (result >= 12 /* SyntaxKind.LineCommentTrivia */ && result <= 15 /* SyntaxKind.Trivia */); return result; } return { setPosition: setPosition, getPosition: () => pos, scan: ignoreTrivia ? scanNextNonTrivia : scanNext, getToken: () => token, getTokenValue: () => value, getTokenOffset: () => tokenOffset, getTokenLength: () => pos - tokenOffset, getTokenStartLine: () => lineStartOffset, getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset, getTokenError: () => scanError, }; } exports.createScanner = createScanner; function isWhiteSpace(ch) { return ch === 32 /* CharacterCodes.space */ || ch === 9 /* CharacterCodes.tab */; } function isLineBreak(ch) { return ch === 10 /* CharacterCodes.lineFeed */ || ch === 13 /* CharacterCodes.carriageReturn */; } function isDigit(ch) { return ch >= 48 /* CharacterCodes._0 */ && ch <= 57 /* CharacterCodes._9 */; } var CharacterCodes; (function (CharacterCodes) { CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed"; CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn"; CharacterCodes[CharacterCodes["space"] = 32] = "space"; CharacterCodes[CharacterCodes["_0"] = 48] = "_0"; CharacterCodes[CharacterCodes["_1"] = 49] = "_1"; CharacterCodes[CharacterCodes["_2"] = 50] = "_2"; CharacterCodes[CharacterCodes["_3"] = 51] = "_3"; CharacterCodes[CharacterCodes["_4"] = 52] = "_4"; CharacterCodes[CharacterCodes["_5"] = 53] = "_5"; CharacterCodes[CharacterCodes["_6"] = 54] = "_6"; CharacterCodes[CharacterCodes["_7"] = 55] = "_7"; CharacterCodes[CharacterCodes["_8"] = 56] = "_8"; CharacterCodes[CharacterCodes["_9"] = 57] = "_9"; CharacterCodes[CharacterCodes["a"] = 97] = "a"; CharacterCodes[CharacterCodes["b"] = 98] = "b"; CharacterCodes[CharacterCodes["c"] = 99] = "c"; CharacterCodes[CharacterCodes["d"] = 100] = "d"; CharacterCodes[CharacterCodes["e"] = 101] = "e"; CharacterCodes[CharacterCodes["f"] = 102] = "f"; CharacterCodes[CharacterCodes["g"] = 103] = "g"; CharacterCodes[CharacterCodes["h"] = 104] = "h"; CharacterCodes[CharacterCodes["i"] = 105] = "i"; CharacterCodes[CharacterCodes["j"] = 106] = "j"; CharacterCodes[CharacterCodes["k"] = 107] = "k"; CharacterCodes[CharacterCodes["l"] = 108] = "l"; CharacterCodes[CharacterCodes["m"] = 109] = "m"; CharacterCodes[CharacterCodes["n"] = 110] = "n"; CharacterCodes[CharacterCodes["o"] = 111] = "o"; CharacterCodes[CharacterCodes["p"] = 112] = "p"; CharacterCodes[CharacterCodes["q"] = 113] = "q"; CharacterCodes[CharacterCodes["r"] = 114] = "r"; CharacterCodes[CharacterCodes["s"] = 115] = "s"; CharacterCodes[CharacterCodes["t"] = 116] = "t"; CharacterCodes[CharacterCodes["u"] = 117] = "u"; CharacterCodes[CharacterCodes["v"] = 118] = "v"; CharacterCodes[CharacterCodes["w"] = 119] = "w"; CharacterCodes[CharacterCodes["x"] = 120] = "x"; CharacterCodes[CharacterCodes["y"] = 121] = "y"; CharacterCodes[CharacterCodes["z"] = 122] = "z"; CharacterCodes[CharacterCodes["A"] = 65] = "A"; CharacterCodes[CharacterCodes["B"] = 66] = "B"; CharacterCodes[CharacterCodes["C"] = 67] = "C"; CharacterCodes[CharacterCodes["D"] = 68] = "D"; CharacterCodes[CharacterCodes["E"] = 69] = "E"; CharacterCodes[CharacterCodes["F"] = 70] = "F"; CharacterCodes[CharacterCodes["G"] = 71] = "G"; CharacterCodes[CharacterCodes["H"] = 72] = "H"; CharacterCodes[CharacterCodes["I"] = 73] = "I"; CharacterCodes[CharacterCodes["J"] = 74] = "J"; CharacterCodes[CharacterCodes["K"] = 75] = "K"; CharacterCodes[CharacterCodes["L"] = 76] = "L"; CharacterCodes[CharacterCodes["M"] = 77] = "M"; CharacterCodes[CharacterCodes["N"] = 78] = "N"; CharacterCodes[CharacterCodes["O"] = 79] = "O"; CharacterCodes[CharacterCodes["P"] = 80] = "P"; CharacterCodes[CharacterCodes["Q"] = 81] = "Q"; CharacterCodes[CharacterCodes["R"] = 82] = "R"; CharacterCodes[CharacterCodes["S"] = 83] = "S"; CharacterCodes[CharacterCodes["T"] = 84] = "T"; CharacterCodes[CharacterCodes["U"] = 85] = "U"; CharacterCodes[CharacterCodes["V"] = 86] = "V"; CharacterCodes[CharacterCodes["W"] = 87] = "W"; CharacterCodes[CharacterCodes["X"] = 88] = "X"; CharacterCodes[CharacterCodes["Y"] = 89] = "Y"; CharacterCodes[CharacterCodes["Z"] = 90] = "Z"; CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk"; CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash"; CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace"; CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket"; CharacterCodes[CharacterCodes["colon"] = 58] = "colon"; CharacterCodes[CharacterCodes["comma"] = 44] = "comma"; CharacterCodes[CharacterCodes["dot"] = 46] = "dot"; CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote"; CharacterCodes[CharacterCodes["minus"] = 45] = "minus"; CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace"; CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket"; CharacterCodes[CharacterCodes["plus"] = 43] = "plus"; CharacterCodes[CharacterCodes["slash"] = 47] = "slash"; CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed"; CharacterCodes[CharacterCodes["tab"] = 9] = "tab"; })(CharacterCodes || (CharacterCodes = {}));});123123456789101112131415161718192021222324252627282930313233343536373839404142version https://git-lfs.github.com/spec/v1oid sha256:e590d27909a7c132382fbf9b8c4668054ab425734c1e0789753063356826c30fsize 1663(function (factory) { if (typeof module === "object" && typeof module.exports === "object") { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === "function" && define.amd) { define(["require", "exports"], factory); }})(function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.supportedEols = exports.cachedBreakLinesWithSpaces = exports.cachedSpaces = void 0; exports.cachedSpaces = new Array(20).fill(0).map((_, index) => { return ' '.repeat(index); }); const maxCachedValues = 200; exports.cachedBreakLinesWithSpaces = { ' ': { '\n': new Array(maxCachedValues).fill(0).map((_, index) => { return '\n' + ' '.repeat(index); }), '\r': new Array(maxCachedValues).fill(0).map((_, index) => { return '\r' + ' '.repeat(index); }), '\r\n': new Array(maxCachedValues).fill(0).map((_, index) => { return '\r\n' + ' '.repeat(index); }), }, '\t': { '\n': new Array(maxCachedValues).fill(0).map((_, index) => { return '\n' + '\t'.repeat(index); }), '\r': new Array(maxCachedValues).fill(0).map((_, index) => { return '\r' + '\t'.repeat(index); }), '\r\n': new Array(maxCachedValues).fill(0).map((_, index) => { return '\r\n' + '\t'.repeat(index); }), } }; exports.supportedEols = ['\n', '\r', '\r\n'];});123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349version https://git-lfs.github.com/spec/v1oid sha256:4d82dad8d8a312706a9bc240c805088fef713bc71eaa622e55970e251b6c1a0fsize 14314/** * Creates a JSON scanner on the given text. * If ignoreTrivia is set, whitespaces or comments are ignored. */export declare const createScanner: (text: string, ignoreTrivia?: boolean) => JSONScanner;export declare const enum ScanError { None = 0, UnexpectedEndOfComment = 1, UnexpectedEndOfString = 2, UnexpectedEndOfNumber = 3, InvalidUnicode = 4, InvalidEscapeCharacter = 5, InvalidCharacter = 6}export declare const enum SyntaxKind { OpenBraceToken = 1, CloseBraceToken = 2, OpenBracketToken = 3, CloseBracketToken = 4, CommaToken = 5, ColonToken = 6, NullKeyword = 7, TrueKeyword = 8, FalseKeyword = 9, StringLiteral = 10, NumericLiteral = 11, LineCommentTrivia = 12, BlockCommentTrivia = 13, LineBreakTrivia = 14, Trivia = 15, Unknown = 16, EOF = 17}/** * The scanner object, representing a JSON scanner at a position in the input string. */export interface JSONScanner { /** * Sets the scan position to a new offset. A call to 'scan' is needed to get the first token. */ setPosition(pos: number): void; /** * Read the next token. Returns the token code. */ scan(): SyntaxKind; /** * Returns the zero-based current scan position, which is after the last read token. */ getPosition(): number; /** * Returns the last read token. */ getToken(): SyntaxKind; /** * Returns the last read token value. The value for strings is the decoded string content. For numbers it's of type number, for boolean it's true or false. */ getTokenValue(): string; /** * The zero-based start offset of the last read token. */ getTokenOffset(): number; /** * The length of the last read token. */ getTokenLength(): number; /** * The zero-based start line number of the last read token. */ getTokenStartLine(): number; /** * The zero-based start character (column) of the last read token. */ getTokenStartCharacter(): number; /** * An error code of the last scan. */ getTokenError(): ScanError;}/** * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index. */export declare const getLocation: (text: string, position: number) => Location;/** * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. * Therefore, always check the errors list to find out if the input was valid. */export declare const parse: (text: string, errors?: ParseError[], options?: ParseOptions) => any;/** * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. */export declare const parseTree: (text: string, errors?: ParseError[], options?: ParseOptions) => Node | undefined;/** * Finds the node at the given path in a JSON DOM. */export declare const findNodeAtLocation: (root: Node, path: JSONPath) => Node | undefined;/** * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset. */export declare const findNodeAtOffset: (root: Node, offset: number, includeRightBound?: boolean) => Node | undefined;/** * Gets the JSON path of the given JSON DOM node */export declare const getNodePath: (node: Node) => JSONPath;/** * Evaluates the JavaScript object of the given JSON DOM node */export declare const getNodeValue: (node: Node) => any;/** * Parses the given text and invokes the visitor functions for each object, array and literal reached. */export declare const visit: (text: string, visitor: JSONVisitor, options?: ParseOptions) => any;/** * Takes JSON with JavaScript-style comments and remove * them. Optionally replaces every none-newline character * of comments with a replaceCharacter */export declare const stripComments: (text: string, replaceCh?: string) => string;export interface ParseError { error: ParseErrorCode; offset: number; length: number;}export declare const enum ParseErrorCode { InvalidSymbol = 1, InvalidNumberFormat = 2, PropertyNameExpected = 3, ValueExpected = 4, ColonExpected = 5, CommaExpected = 6, CloseBraceExpected = 7, CloseBracketExpected = 8, EndOfFileExpected = 9, InvalidCommentToken = 10, UnexpectedEndOfComment = 11, UnexpectedEndOfString = 12, UnexpectedEndOfNumber = 13, InvalidUnicode = 14, InvalidEscapeCharacter = 15, InvalidCharacter = 16}export declare function printParseErrorCode(code: ParseErrorCode): "InvalidSymbol" | "InvalidNumberFormat" | "PropertyNameExpected" | "ValueExpected" | "ColonExpected" | "CommaExpected" | "CloseBraceExpected" | "CloseBracketExpected" | "EndOfFileExpected" | "InvalidCommentToken" | "UnexpectedEndOfComment" | "UnexpectedEndOfString" | "UnexpectedEndOfNumber" | "InvalidUnicode" | "InvalidEscapeCharacter" | "InvalidCharacter" | "<unknown ParseErrorCode>";export type NodeType = 'object' | 'array' | 'property' | 'string' | 'number' | 'boolean' | 'null';export interface Node { readonly type: NodeType; readonly value?: any; readonly offset: number; readonly length: number; readonly colonOffset?: number; readonly parent?: Node; readonly children?: Node[];}/** * A {@linkcode JSONPath} segment. Either a string representing an object property name * or a number (starting at 0) for array indices. */export type Segment = string | number;export type JSONPath = Segment[];export interface Location { /** * The previous property key or literal value (string, number, boolean or null) or undefined. */ previousNode?: Node; /** * The path describing the location in the JSON document. The path consists of a sequence of strings * representing an object property or numbers for array indices. */ path: JSONPath; /** * Matches the locations path against a pattern consisting of strings (for properties) and numbers (for array indices). * '*' will match a single segment of any property name or index. * '**' will match a sequence of segments of any property name or index, or no segment. */ matches: (patterns: JSONPath) => boolean; /** * If set, the location's offset is at a property key. */ isAtPropertyKey: boolean;}export interface ParseOptions { disallowComments?: boolean; allowTrailingComma?: boolean; allowEmptyContent?: boolean;}/** * Visitor called by {@linkcode visit} when parsing JSON. * * The visitor functions have the following common parameters: * - `offset`: Global offset within the JSON document, starting at 0 * - `startLine`: Line number, starting at 0 * - `startCharacter`: Start character (column) within the current line, starting at 0 * * Additionally some functions have a `pathSupplier` parameter which can be used to obtain the * current `JSONPath` within the document. */export interface JSONVisitor { /** * Invoked when an open brace is encountered and an object is started. The offset and length represent the location of the open brace. */ onObjectBegin?: (offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; /** * Invoked when a property is encountered. The offset and length represent the location of the property name. * The `JSONPath` created by the `pathSupplier` refers to the enclosing JSON object, it does not include the * property name yet. */ onObjectProperty?: (property: string, offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; /** * Invoked when a closing brace is encountered and an object is completed. The offset and length represent the location of the closing brace. */ onObjectEnd?: (offset: number, length: number, startLine: number, startCharacter: number) => void; /** * Invoked when an open bracket is encountered. The offset and length represent the location of the open bracket. */ onArrayBegin?: (offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; /** * Invoked when a closing bracket is encountered. The offset and length represent the location of the closing bracket. */ onArrayEnd?: (offset: number, length: number, startLine: number, startCharacter: number) => void; /** * Invoked when a literal value is encountered. The offset and length represent the location of the literal value. */ onLiteralValue?: (value: any, offset: number, length: number, startLine: number, startCharacter: number, pathSupplier: () => JSONPath) => void; /** * Invoked when a comma or colon separator is encountered. The offset and length represent the location of the separator. */ onSeparator?: (character: string, offset: number, length: number, startLine: number, startCharacter: number) => void; /** * When comments are allowed, invoked when a line or block comment is encountered. The offset and length represent the location of the comment. */ onComment?: (offset: number, length: number, startLine: number, startCharacter: number) => void; /** * Invoked on an error. */ onError?: (error: ParseErrorCode, offset: number, length: number, startLine: number, startCharacter: number) => void;}/** * An edit result describes a textual edit operation. It is the result of a {@linkcode format} and {@linkcode modify} operation. * It consist of one or more edits describing insertions, replacements or removals of text segments. * * The offsets of the edits refer to the original state of the document. * * No two edits change or remove the same range of text in the original document. * * Multiple edits can have the same offset if they are multiple inserts, or an insert followed by a remove or replace. * * The order in the array defines which edit is applied first. * To apply an edit result use {@linkcode applyEdits}. * In general multiple EditResults must not be concatenated because they might impact each other, producing incorrect or malformed JSON data. */export type EditResult = Edit[];/** * Represents a text modification */export interface Edit { /** * The start offset of the modification. */ offset: number; /** * The length of the modification. Must not be negative. Empty length represents an *insert*. */ length: number; /** * The new content. Empty content represents a *remove*. */ content: string;}/** * A text range in the document*/export interface Range { /** * The start offset of the range. */ offset: number; /** * The length of the range. Must not be negative. */ length: number;}/** * Options used by {@linkcode format} when computing the formatting edit operations */export interface FormattingOptions { /** * If indentation is based on spaces (`insertSpaces` = true), the number of spaces that make an indent. */ tabSize?: number; /** * Is indentation based on spaces? */ insertSpaces?: boolean; /** * The default 'end of line' character. If not set, '\n' is used as default. */ eol?: string; /** * If set, will add a new line at the end of the document. */ insertFinalNewline?: boolean; /** * If true, will keep line positions as is in the formatting */ keepLines?: boolean;}/** * Computes the edit operations needed to format a JSON document. * * @param documentText The input text * @param range The range to format or `undefined` to format the full content * @param options The formatting options * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}. * To apply the edit operations to the input, use {@linkcode applyEdits}. */export declare function format(documentText: string, range: Range | undefined, options: FormattingOptions): EditResult;/** * Options used by {@linkcode modify} when computing the modification edit operations */export interface ModificationOptions { /** * Formatting options. If undefined, the newly inserted code will be inserted unformatted. */ formattingOptions?: FormattingOptions; /** * Default false. If `JSONPath` refers to an index of an array and `isArrayInsertion` is `true`, then * {@linkcode modify} will insert a new item at that location instead of overwriting its contents. */ isArrayInsertion?: boolean; /** * Optional function to define the insertion index given an existing list of properties. */ getInsertionIndex?: (properties: string[]) => number;}/** * Computes the edit operations needed to modify a value in the JSON document. * * @param documentText The input text * @param path The path of the value to change. The path represents either to the document root, a property or an array item. * If the path points to an non-existing property or item, it will be created. * @param value The new value for the specified property or item. If the value is undefined, * the property or item will be removed. * @param options Options * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}. * To apply the edit operations to the input, use {@linkcode applyEdits}. */export declare function modify(text: string, path: JSONPath, value: any, options: ModificationOptions): EditResult;/** * Applies edits to an input string. * @param text The input text * @param edits Edit operations following the format described in {@linkcode EditResult}. * @returns The text with the applied edits. * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}. */export declare function applyEdits(text: string, edits: EditResult): string;123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194version https://git-lfs.github.com/spec/v1oid sha256:6dc132e2e792a9616688ff93d10dd671c1fbcfa3301d76bff3e81193d049337dsize 11059(function (factory) { if (typeof module === "object" && typeof module.exports === "object") { var v = factory(require, exports); if (v !== undefined) module.exports = v; } else if (typeof define === "function" && define.amd) { define(["require", "exports", "./impl/format", "./impl/edit", "./impl/scanner", "./impl/parser"], factory); }})(function (require, exports) { /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.applyEdits = exports.modify = exports.format = exports.printParseErrorCode = exports.ParseErrorCode = exports.stripComments = exports.visit = exports.getNodeValue = exports.getNodePath = exports.findNodeAtOffset = exports.findNodeAtLocation = exports.parseTree = exports.parse = exports.getLocation = exports.SyntaxKind = exports.ScanError = exports.createScanner = void 0; const formatter = require("./impl/format"); const edit = require("./impl/edit"); const scanner = require("./impl/scanner"); const parser = require("./impl/parser"); /** * Creates a JSON scanner on the given text. * If ignoreTrivia is set, whitespaces or comments are ignored. */ exports.createScanner = scanner.createScanner; var ScanError; (function (ScanError) { ScanError[ScanError["None"] = 0] = "None"; ScanError[ScanError["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment"; ScanError[ScanError["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString"; ScanError[ScanError["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber"; ScanError[ScanError["InvalidUnicode"] = 4] = "InvalidUnicode"; ScanError[ScanError["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter"; ScanError[ScanError["InvalidCharacter"] = 6] = "InvalidCharacter"; })(ScanError || (exports.ScanError = ScanError = {})); var SyntaxKind; (function (SyntaxKind) { SyntaxKind[SyntaxKind["OpenBraceToken"] = 1] = "OpenBraceToken"; SyntaxKind[SyntaxKind["CloseBraceToken"] = 2] = "CloseBraceToken"; SyntaxKind[SyntaxKind["OpenBracketToken"] = 3] = "OpenBracketToken"; SyntaxKind[SyntaxKind["CloseBracketToken"] = 4] = "CloseBracketToken"; SyntaxKind[SyntaxKind["CommaToken"] = 5] = "CommaToken"; SyntaxKind[SyntaxKind["ColonToken"] = 6] = "ColonToken"; SyntaxKind[SyntaxKind["NullKeyword"] = 7] = "NullKeyword"; SyntaxKind[SyntaxKind["TrueKeyword"] = 8] = "TrueKeyword"; SyntaxKind[SyntaxKind["FalseKeyword"] = 9] = "FalseKeyword"; SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral"; SyntaxKind[SyntaxKind["NumericLiteral"] = 11] = "NumericLiteral"; SyntaxKind[SyntaxKind["LineCommentTrivia"] = 12] = "LineCommentTrivia"; SyntaxKind[SyntaxKind["BlockCommentTrivia"] = 13] = "BlockCommentTrivia"; SyntaxKind[SyntaxKind["LineBreakTrivia"] = 14] = "LineBreakTrivia"; SyntaxKind[SyntaxKind["Trivia"] = 15] = "Trivia"; SyntaxKind[SyntaxKind["Unknown"] = 16] = "Unknown"; SyntaxKind[SyntaxKind["EOF"] = 17] = "EOF"; })(SyntaxKind || (exports.SyntaxKind = SyntaxKind = {})); /** * For a given offset, evaluate the location in the JSON document. Each segment in the location path is either a property name or an array index. */ exports.getLocation = parser.getLocation; /** * Parses the given text and returns the object the JSON content represents. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. * Therefore, always check the errors list to find out if the input was valid. */ exports.parse = parser.parse; /** * Parses the given text and returns a tree representation the JSON content. On invalid input, the parser tries to be as fault tolerant as possible, but still return a result. */ exports.parseTree = parser.parseTree; /** * Finds the node at the given path in a JSON DOM. */ exports.findNodeAtLocation = parser.findNodeAtLocation; /** * Finds the innermost node at the given offset. If includeRightBound is set, also finds nodes that end at the given offset. */ exports.findNodeAtOffset = parser.findNodeAtOffset; /** * Gets the JSON path of the given JSON DOM node */ exports.getNodePath = parser.getNodePath; /** * Evaluates the JavaScript object of the given JSON DOM node */ exports.getNodeValue = parser.getNodeValue; /** * Parses the given text and invokes the visitor functions for each object, array and literal reached. */ exports.visit = parser.visit; /** * Takes JSON with JavaScript-style comments and remove * them. Optionally replaces every none-newline character * of comments with a replaceCharacter */ exports.stripComments = parser.stripComments; var ParseErrorCode; (function (ParseErrorCode) { ParseErrorCode[ParseErrorCode["InvalidSymbol"] = 1] = "InvalidSymbol"; ParseErrorCode[ParseErrorCode["InvalidNumberFormat"] = 2] = "InvalidNumberFormat"; ParseErrorCode[ParseErrorCode["PropertyNameExpected"] = 3] = "PropertyNameExpected"; ParseErrorCode[ParseErrorCode["ValueExpected"] = 4] = "ValueExpected"; ParseErrorCode[ParseErrorCode["ColonExpected"] = 5] = "ColonExpected"; ParseErrorCode[ParseErrorCode["CommaExpected"] = 6] = "CommaExpected"; ParseErrorCode[ParseErrorCode["CloseBraceExpected"] = 7] = "CloseBraceExpected"; ParseErrorCode[ParseErrorCode["CloseBracketExpected"] = 8] = "CloseBracketExpected"; ParseErrorCode[ParseErrorCode["EndOfFileExpected"] = 9] = "EndOfFileExpected"; ParseErrorCode[ParseErrorCode["InvalidCommentToken"] = 10] = "InvalidCommentToken"; ParseErrorCode[ParseErrorCode["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment"; ParseErrorCode[ParseErrorCode["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString"; ParseErrorCode[ParseErrorCode["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber"; ParseErrorCode[ParseErrorCode["InvalidUnicode"] = 14] = "InvalidUnicode"; ParseErrorCode[ParseErrorCode["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter"; ParseErrorCode[ParseErrorCode["InvalidCharacter"] = 16] = "InvalidCharacter"; })(ParseErrorCode || (exports.ParseErrorCode = ParseErrorCode = {})); function printParseErrorCode(code) { switch (code) { case 1 /* ParseErrorCode.InvalidSymbol */: return 'InvalidSymbol'; case 2 /* ParseErrorCode.InvalidNumberFormat */: return 'InvalidNumberFormat'; case 3 /* ParseErrorCode.PropertyNameExpected */: return 'PropertyNameExpected'; case 4 /* ParseErrorCode.ValueExpected */: return 'ValueExpected'; case 5 /* ParseErrorCode.ColonExpected */: return 'ColonExpected'; case 6 /* ParseErrorCode.CommaExpected */: return 'CommaExpected'; case 7 /* ParseErrorCode.CloseBraceExpected */: return 'CloseBraceExpected'; case 8 /* ParseErrorCode.CloseBracketExpected */: return 'CloseBracketExpected'; case 9 /* ParseErrorCode.EndOfFileExpected */: return 'EndOfFileExpected'; case 10 /* ParseErrorCode.InvalidCommentToken */: return 'InvalidCommentToken'; case 11 /* ParseErrorCode.UnexpectedEndOfComment */: return 'UnexpectedEndOfComment'; case 12 /* ParseErrorCode.UnexpectedEndOfString */: return 'UnexpectedEndOfString'; case 13 /* ParseErrorCode.UnexpectedEndOfNumber */: return 'UnexpectedEndOfNumber'; case 14 /* ParseErrorCode.InvalidUnicode */: return 'InvalidUnicode'; case 15 /* ParseErrorCode.InvalidEscapeCharacter */: return 'InvalidEscapeCharacter'; case 16 /* ParseErrorCode.InvalidCharacter */: return 'InvalidCharacter'; } return '<unknown ParseErrorCode>'; } exports.printParseErrorCode = printParseErrorCode; /** * Computes the edit operations needed to format a JSON document. * * @param documentText The input text * @param range The range to format or `undefined` to format the full content * @param options The formatting options * @returns The edit operations describing the formatting changes to the original document following the format described in {@linkcode EditResult}. * To apply the edit operations to the input, use {@linkcode applyEdits}. */ function format(documentText, range, options) { return formatter.format(documentText, range, options); } exports.format = format; /** * Computes the edit operations needed to modify a value in the JSON document. * * @param documentText The input text * @param path The path of the value to change. The path represents either to the document root, a property or an array item. * If the path points to an non-existing property or item, it will be created. * @param value The new value for the specified property or item. If the value is undefined, * the property or item will be removed. * @param options Options * @returns The edit operations describing the changes to the original document, following the format described in {@linkcode EditResult}. * To apply the edit operations to the input, use {@linkcode applyEdits}. */ function modify(text, path, value, options) { return edit.setProperty(text, path, value, options); } exports.modify = modify; /** * Applies edits to an input string. * @param text The input text * @param edits Edit operations following the format described in {@linkcode EditResult}. * @returns The text with the applied edits. * @throws An error if the edit operations are not well-formed as described in {@linkcode EditResult}. */ function applyEdits(text, edits) { let sortedEdits = edits.slice(0).sort((a, b) => { const diff = a.offset - b.offset; if (diff === 0) { return a.length - b.length; } return diff; }); let lastModifiedOffset = text.length; for (let i = sortedEdits.length - 1; i >= 0; i--) { let e = sortedEdits[i]; if (e.offset + e.length <= lastModifiedOffset) { text = edit.applyEdit(text, e); } else { throw new Error('Overlapping edit'); } lastModifiedOffset = e.offset; } return text; } exports.applyEdits = applyEdits;});12312345678910111213141516171819202122232425262728293031323334353637version https://git-lfs.github.com/spec/v1oid sha256:6442d10a23718191adbedd34448552cea97a8ff9c67ee71292a9e1ab5d9a140dsize 1180{ "name": "jsonc-parser", "version": "3.2.1", "description": "Scanner and parser for JSON with comments.", "main": "./lib/umd/main.js", "typings": "./lib/umd/main.d.ts", "module": "./lib/esm/main.js", "author": "Microsoft Corporation", "repository": { "type": "git", "url": "https://github.com/microsoft/node-jsonc-parser" }, "license": "MIT", "bugs": { "url": "https://github.com/microsoft/node-jsonc-parser/issues" }, "devDependencies": { "mocha": "^10.2.0", "typescript": "^5.3.3", "@types/node": "^16.x", "@types/mocha": "^10.0.6", "@typescript-eslint/eslint-plugin": "^6.19.1", "@typescript-eslint/parser": "^6.19.1", "eslint": "^8.56.0", "rimraf": "^5.0.5" }, "scripts": { "prepack": "npm run clean && npm run compile-esm && npm run test && npm run remove-sourcemap-refs", "compile": "tsc -p ./src && npm run lint", "compile-esm": "tsc -p ./src/tsconfig.esm.json", "remove-sourcemap-refs": "node ./build/remove-sourcemap-refs.js", "clean": "rimraf lib", "watch": "tsc -w -p ./src", "test": "npm run compile && mocha ./lib/umd/test", "lint": "eslint src/**/*.ts" }}1231234567891011version https://git-lfs.github.com/spec/v1oid sha256:ec9ee83580841e8eb687aca9867f221503809ba6426c7f876ede17d91b9fcfd0size 1095Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869version https://git-lfs.github.com/spec/v1oid sha256:5d797b2750ce6671ac696a964ca10062d81af394803fa782b4c1368bb461c589size 2292# VSCode JSON RPC
[](https://npmjs.org/package/vscode-jsonrpc)[](https://npmjs.org/package/vscode-jsonrpc)[](https://dev.azure.com/ms/vscode-languageserver-node/_build/latest?definitionId=439&branchName=main)
This npm module implements the base messaging protocol spoken between a VSCode language server and a VSCode language client.
The npm module can also be used standalone to establish a [JSON-RPC](http://www.jsonrpc.org/) channel betweena client and a server. Below an example how to setup a JSON-RPC connection. First the client side.
```tsimport * as cp from 'child_process';import * as rpc from 'vscode-jsonrpc/node';
let childProcess = cp.spawn(...);
// Use stdin and stdout for communication:let connection = rpc.createMessageConnection( new rpc.StreamMessageReader(childProcess.stdout), new rpc.StreamMessageWriter(childProcess.stdin));
let notification = new rpc.NotificationType<string, void>('testNotification');
connection.listen();
connection.sendNotification(notification, 'Hello World');```
The server side looks very symmetrical:
```tsimport * as rpc from 'vscode-jsonrpc/node';
let connection = rpc.createMessageConnection( new rpc.StreamMessageReader(process.stdin), new rpc.StreamMessageWriter(process.stdout));
let notification = new rpc.NotificationType<string, void>('testNotification');connection.onNotification(notification, (param: string) => { console.log(param); // This prints Hello World});
connection.listen();```
# History
### 5.0.0
- add progress support- move JS target to ES2017
### 4.0.0
- move JS target to ES6.
### 3.0.0:
- converted the NPM module to use TypeScript 2.0.3.- added strict null support.- support for passing more than one parameter to a request or notification.- Breaking changes: - due to the use of TypeScript 2.0.3 and differences in d.ts generation users of the new version need to move to TypeScript 2.0.3 as well.
## License[MIT](https://github.com/Microsoft/vscode-languageserver-node/blob/master/License.txt)123123456version https://git-lfs.github.com/spec/v1oid sha256:99170b7257d895bb2594d7db9c255a4b0029a1363fe5e89849fda830b5c997cesize 385/* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ----------------------------------------------------------------------------------------- */
export * from './lib/browser/main';1231234567version https://git-lfs.github.com/spec/v1oid sha256:9406802db032558d3cd8bde9f68d20c067f3a7eca251ad7d0e4473da8d457adasize 411/* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ----------------------------------------------------------------------------------------- */'use strict';
module.exports = require('./lib/browser/main');1231234567891011121314151617version https://git-lfs.github.com/spec/v1oid sha256:fbbdb0baaade3505088d8eeaee2e57468ccd5fb08189cb5dfc58ec9c571f3191size 994import { AbstractMessageReader, DataCallback, AbstractMessageWriter, Message, Disposable, ConnectionStrategy, ConnectionOptions, MessageReader, MessageWriter, Logger, MessageConnection } from '../common/api';export * from '../common/api';export declare class BrowserMessageReader extends AbstractMessageReader implements MessageReader { private _onData; private _messageListener; constructor(port: MessagePort | Worker | DedicatedWorkerGlobalScope); listen(callback: DataCallback): Disposable;}export declare class BrowserMessageWriter extends AbstractMessageWriter implements MessageWriter { private port; private errorCount; constructor(port: MessagePort | Worker | DedicatedWorkerGlobalScope); write(msg: Message): Promise<void>; private handleError; end(): void;}export declare function createMessageConnection(reader: MessageReader, writer: MessageWriter, logger?: Logger, options?: ConnectionStrategy | ConnectionOptions): MessageConnection;12312345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576version https://git-lfs.github.com/spec/v1oid sha256:b8a81be90adb2c0ee8309509685068c74b96870ffba6e8dc664a8ce94fadc168size 2964"use strict";/* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc);}) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k];}));var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);};Object.defineProperty(exports, "__esModule", { value: true });exports.createMessageConnection = exports.BrowserMessageWriter = exports.BrowserMessageReader = void 0;const ril_1 = require("./ril");// Install the browser runtime abstract.ril_1.default.install();const api_1 = require("../common/api");__exportStar(require("../common/api"), exports);class BrowserMessageReader extends api_1.AbstractMessageReader { constructor(port) { super(); this._onData = new api_1.Emitter(); this._messageListener = (event) => { this._onData.fire(event.data); }; port.addEventListener('error', (event) => this.fireError(event)); port.onmessage = this._messageListener; } listen(callback) { return this._onData.event(callback); }}exports.BrowserMessageReader = BrowserMessageReader;class BrowserMessageWriter extends api_1.AbstractMessageWriter { constructor(port) { super(); this.port = port; this.errorCount = 0; port.addEventListener('error', (event) => this.fireError(event)); } write(msg) { try { this.port.postMessage(msg); return Promise.resolve(); } catch (error) { this.handleError(error, msg); return Promise.reject(error); } } handleError(error, msg) { this.errorCount++; this.fireError(error, msg, this.errorCount); } end() { }}exports.BrowserMessageWriter = BrowserMessageWriter;function createMessageConnection(reader, writer, logger, options) { if (logger === undefined) { logger = api_1.NullLogger; } if (api_1.ConnectionStrategy.is(options)) { options = { connectionStrategy: options }; } return (0, api_1.createMessageConnection)(reader, writer, logger, options);}exports.createMessageConnection = createMessageConnection;123123456789101112version https://git-lfs.github.com/spec/v1oid sha256:a9994d282573b31ac3b09bb94c88868edd6530c06d77e99379d4fd9e91d90dc6size 358import { RAL } from '../common/api';interface RIL extends RAL { readonly stream: { readonly asReadableStream: (stream: WebSocket) => RAL.ReadableStream; readonly asWritableStream: (stream: WebSocket) => RAL.WritableStream; };}declare function RIL(): RIL;declare namespace RIL { function install(): void;}export default RIL;123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156version https://git-lfs.github.com/spec/v1oid sha256:e636b0a5c6513a6adb5b1a7814128904a39c6fe285019dbfa75d9c44cdb4d262size 5643"use strict";/* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */Object.defineProperty(exports, "__esModule", { value: true });const api_1 = require("../common/api");class MessageBuffer extends api_1.AbstractMessageBuffer { constructor(encoding = 'utf-8') { super(encoding); this.asciiDecoder = new TextDecoder('ascii'); } emptyBuffer() { return MessageBuffer.emptyBuffer; } fromString(value, _encoding) { return (new TextEncoder()).encode(value); } toString(value, encoding) { if (encoding === 'ascii') { return this.asciiDecoder.decode(value); } else { return (new TextDecoder(encoding)).decode(value); } } asNative(buffer, length) { if (length === undefined) { return buffer; } else { return buffer.slice(0, length); } } allocNative(length) { return new Uint8Array(length); }}MessageBuffer.emptyBuffer = new Uint8Array(0);class ReadableStreamWrapper { constructor(socket) { this.socket = socket; this._onData = new api_1.Emitter(); this._messageListener = (event) => { const blob = event.data; blob.arrayBuffer().then((buffer) => { this._onData.fire(new Uint8Array(buffer)); }, () => { (0, api_1.RAL)().console.error(`Converting blob to array buffer failed.`); }); }; this.socket.addEventListener('message', this._messageListener); } onClose(listener) { this.socket.addEventListener('close', listener); return api_1.Disposable.create(() => this.socket.removeEventListener('close', listener)); } onError(listener) { this.socket.addEventListener('error', listener); return api_1.Disposable.create(() => this.socket.removeEventListener('error', listener)); } onEnd(listener) { this.socket.addEventListener('end', listener); return api_1.Disposable.create(() => this.socket.removeEventListener('end', listener)); } onData(listener) { return this._onData.event(listener); }}class WritableStreamWrapper { constructor(socket) { this.socket = socket; } onClose(listener) { this.socket.addEventListener('close', listener); return api_1.Disposable.create(() => this.socket.removeEventListener('close', listener)); } onError(listener) { this.socket.addEventListener('error', listener); return api_1.Disposable.create(() => this.socket.removeEventListener('error', listener)); } onEnd(listener) { this.socket.addEventListener('end', listener); return api_1.Disposable.create(() => this.socket.removeEventListener('end', listener)); } write(data, encoding) { if (typeof data === 'string') { if (encoding !== undefined && encoding !== 'utf-8') { throw new Error(`In a Browser environments only utf-8 text encoding is supported. But got encoding: ${encoding}`); } this.socket.send(data); } else { this.socket.send(data); } return Promise.resolve(); } end() { this.socket.close(); }}const _textEncoder = new TextEncoder();const _ril = Object.freeze({ messageBuffer: Object.freeze({ create: (encoding) => new MessageBuffer(encoding) }), applicationJson: Object.freeze({ encoder: Object.freeze({ name: 'application/json', encode: (msg, options) => { if (options.charset !== 'utf-8') { throw new Error(`In a Browser environments only utf-8 text encoding is supported. But got encoding: ${options.charset}`); } return Promise.resolve(_textEncoder.encode(JSON.stringify(msg, undefined, 0))); } }), decoder: Object.freeze({ name: 'application/json', decode: (buffer, options) => { if (!(buffer instanceof Uint8Array)) { throw new Error(`In a Browser environments only Uint8Arrays are supported.`); } return Promise.resolve(JSON.parse(new TextDecoder(options.charset).decode(buffer))); } }) }), stream: Object.freeze({ asReadableStream: (socket) => new ReadableStreamWrapper(socket), asWritableStream: (socket) => new WritableStreamWrapper(socket) }), console: console, timer: Object.freeze({ setTimeout(callback, ms, ...args) { const handle = setTimeout(callback, ms, ...args); return { dispose: () => clearTimeout(handle) }; }, setImmediate(callback, ...args) { const handle = setTimeout(callback, 0, ...args); return { dispose: () => clearTimeout(handle) }; }, setInterval(callback, ms, ...args) { const handle = setInterval(callback, ms, ...args); return { dispose: () => clearInterval(handle) }; }, })});function RIL() { return _ril;}(function (RIL) { function install() { api_1.RAL.install(_ril); } RIL.install = install;})(RIL || (RIL = {}));exports.default = RIL;1231234567891011121314version https://git-lfs.github.com/spec/v1oid sha256:c0241916cf44e700edc1cdac8d48b2a9cf4658cf624788da59b3d29c7769a966size 4464/// <reference path="../../typings/thenable.d.ts" />import { Message, MessageSignature, RequestMessage, RequestType, RequestType0, RequestType1, RequestType2, RequestType3, RequestType4, RequestType5, RequestType6, RequestType7, RequestType8, RequestType9, ResponseError, ErrorCodes, NotificationMessage, NotificationType, NotificationType0, NotificationType1, NotificationType2, NotificationType3, NotificationType4, NotificationType5, NotificationType6, NotificationType7, NotificationType8, NotificationType9, ResponseMessage, ParameterStructures, _EM } from './messages';import { LinkedMap, LRUCache, Touch } from './linkedMap';import { Disposable } from './disposable';import { Event, Emitter } from './events';import { AbstractCancellationTokenSource, CancellationTokenSource, CancellationToken } from './cancellation';import { SharedArraySenderStrategy, SharedArrayReceiverStrategy } from './sharedArrayCancellation';import { MessageReader, AbstractMessageReader, ReadableStreamMessageReader, DataCallback, MessageReaderOptions, PartialMessageInfo } from './messageReader';import { MessageWriter, AbstractMessageWriter, WriteableStreamMessageWriter, MessageWriterOptions } from './messageWriter';import { AbstractMessageBuffer } from './messageBuffer';import { ContentTypeEncoderOptions, ContentEncoder, ContentTypeEncoder, ContentTypeDecoderOptions, ContentDecoder, ContentTypeDecoder } from './encoding';import { Logger, ConnectionStrategy, ConnectionOptions, MessageConnection, NullLogger, createMessageConnection, ProgressToken, ProgressType, HandlerResult, StarRequestHandler, GenericRequestHandler, RequestHandler0, RequestHandler, RequestHandler1, RequestHandler2, RequestHandler3, RequestHandler4, RequestHandler5, RequestHandler6, RequestHandler7, RequestHandler8, RequestHandler9, StarNotificationHandler, GenericNotificationHandler, NotificationHandler0, NotificationHandler, NotificationHandler1, NotificationHandler2, NotificationHandler3, NotificationHandler4, NotificationHandler5, NotificationHandler6, NotificationHandler7, NotificationHandler8, NotificationHandler9, Trace, TraceValue, TraceFormat, TraceOptions, SetTraceParams, SetTraceNotification, LogTraceParams, LogTraceNotification, Tracer, ConnectionErrors, ConnectionError, CancellationId, CancellationReceiverStrategy, CancellationSenderStrategy, CancellationStrategy, MessageStrategy, TraceValues } from './connection';import RAL from './ral';export { RAL, Message, MessageSignature, RequestMessage, RequestType, RequestType0, RequestType1, RequestType2, RequestType3, RequestType4, RequestType5, RequestType6, RequestType7, RequestType8, RequestType9, ResponseError, ErrorCodes, NotificationMessage, NotificationType, NotificationType0, NotificationType1, NotificationType2, NotificationType3, NotificationType4, NotificationType5, NotificationType6, NotificationType7, NotificationType8, NotificationType9, ResponseMessage, ParameterStructures, _EM, LinkedMap, Touch, LRUCache, Disposable, Event, Emitter, AbstractCancellationTokenSource, CancellationTokenSource, CancellationToken, SharedArraySenderStrategy, SharedArrayReceiverStrategy, MessageReader, AbstractMessageReader, ReadableStreamMessageReader, DataCallback, MessageReaderOptions, PartialMessageInfo, MessageWriter, AbstractMessageWriter, WriteableStreamMessageWriter, MessageWriterOptions, AbstractMessageBuffer, ContentTypeEncoderOptions, ContentEncoder, ContentTypeEncoder, ContentTypeDecoderOptions, ContentDecoder, ContentTypeDecoder, Logger, ConnectionStrategy, ConnectionOptions, MessageConnection, NullLogger, createMessageConnection, ProgressToken, ProgressType, HandlerResult, StarRequestHandler, GenericRequestHandler, RequestHandler0, RequestHandler, RequestHandler1, RequestHandler2, RequestHandler3, RequestHandler4, RequestHandler5, RequestHandler6, RequestHandler7, RequestHandler8, RequestHandler9, StarNotificationHandler, GenericNotificationHandler, NotificationHandler0, NotificationHandler, NotificationHandler1, NotificationHandler2, NotificationHandler3, NotificationHandler4, NotificationHandler5, NotificationHandler6, NotificationHandler7, NotificationHandler8, NotificationHandler9, Trace, TraceValue, TraceValues, TraceFormat, TraceOptions, SetTraceParams, SetTraceNotification, LogTraceParams, LogTraceNotification, Tracer, ConnectionErrors, ConnectionError, CancellationId, CancellationReceiverStrategy, CancellationSenderStrategy, CancellationStrategy, MessageStrategy };12312345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182version https://git-lfs.github.com/spec/v1oid sha256:c142c5e45d2a62092c2db2aab7c1ac1f805dca8036e2f1d1b05e9284494bf894size 10754"use strict";/* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ *//// <reference path="../../typings/thenable.d.ts" />Object.defineProperty(exports, "__esModule", { value: true });exports.ProgressType = exports.ProgressToken = exports.createMessageConnection = exports.NullLogger = exports.ConnectionOptions = exports.ConnectionStrategy = exports.AbstractMessageBuffer = exports.WriteableStreamMessageWriter = exports.AbstractMessageWriter = exports.MessageWriter = exports.ReadableStreamMessageReader = exports.AbstractMessageReader = exports.MessageReader = exports.SharedArrayReceiverStrategy = exports.SharedArraySenderStrategy = exports.CancellationToken = exports.CancellationTokenSource = exports.Emitter = exports.Event = exports.Disposable = exports.LRUCache = exports.Touch = exports.LinkedMap = exports.ParameterStructures = exports.NotificationType9 = exports.NotificationType8 = exports.NotificationType7 = exports.NotificationType6 = exports.NotificationType5 = exports.NotificationType4 = exports.NotificationType3 = exports.NotificationType2 = exports.NotificationType1 = exports.NotificationType0 = exports.NotificationType = exports.ErrorCodes = exports.ResponseError = exports.RequestType9 = exports.RequestType8 = exports.RequestType7 = exports.RequestType6 = exports.RequestType5 = exports.RequestType4 = exports.RequestType3 = exports.RequestType2 = exports.RequestType1 = exports.RequestType0 = exports.RequestType = exports.Message = exports.RAL = void 0;exports.MessageStrategy = exports.CancellationStrategy = exports.CancellationSenderStrategy = exports.CancellationReceiverStrategy = exports.ConnectionError = exports.ConnectionErrors = exports.LogTraceNotification = exports.SetTraceNotification = exports.TraceFormat = exports.TraceValues = exports.TraceValue = exports.Trace = void 0;const messages_1 = require("./messages");Object.defineProperty(exports, "Message", { enumerable: true, get: function () { return messages_1.Message; } });Object.defineProperty(exports, "RequestType", { enumerable: true, get: function () { return messages_1.RequestType; } });Object.defineProperty(exports, "RequestType0", { enumerable: true, get: function () { return messages_1.RequestType0; } });Object.defineProperty(exports, "RequestType1", { enumerable: true, get: function () { return messages_1.RequestType1; } });Object.defineProperty(exports, "RequestType2", { enumerable: true, get: function () { return messages_1.RequestType2; } });Object.defineProperty(exports, "RequestType3", { enumerable: true, get: function () { return messages_1.RequestType3; } });Object.defineProperty(exports, "RequestType4", { enumerable: true, get: function () { return messages_1.RequestType4; } });Object.defineProperty(exports, "RequestType5", { enumerable: true, get: function () { return messages_1.RequestType5; } });Object.defineProperty(exports, "RequestType6", { enumerable: true, get: function () { return messages_1.RequestType6; } });Object.defineProperty(exports, "RequestType7", { enumerable: true, get: function () { return messages_1.RequestType7; } });Object.defineProperty(exports, "RequestType8", { enumerable: true, get: function () { return messages_1.RequestType8; } });Object.defineProperty(exports, "RequestType9", { enumerable: true, get: function () { return messages_1.RequestType9; } });Object.defineProperty(exports, "ResponseError", { enumerable: true, get: function () { return messages_1.ResponseError; } });Object.defineProperty(exports, "ErrorCodes", { enumerable: true, get: function () { return messages_1.ErrorCodes; } });Object.defineProperty(exports, "NotificationType", { enumerable: true, get: function () { return messages_1.NotificationType; } });Object.defineProperty(exports, "NotificationType0", { enumerable: true, get: function () { return messages_1.NotificationType0; } });Object.defineProperty(exports, "NotificationType1", { enumerable: true, get: function () { return messages_1.NotificationType1; } });Object.defineProperty(exports, "NotificationType2", { enumerable: true, get: function () { return messages_1.NotificationType2; } });Object.defineProperty(exports, "NotificationType3", { enumerable: true, get: function () { return messages_1.NotificationType3; } });Object.defineProperty(exports, "NotificationType4", { enumerable: true, get: function () { return messages_1.NotificationType4; } });Object.defineProperty(exports, "NotificationType5", { enumerable: true, get: function () { return messages_1.NotificationType5; } });Object.defineProperty(exports, "NotificationType6", { enumerable: true, get: function () { return messages_1.NotificationType6; } });Object.defineProperty(exports, "NotificationType7", { enumerable: true, get: function () { return messages_1.NotificationType7; } });Object.defineProperty(exports, "NotificationType8", { enumerable: true, get: function () { return messages_1.NotificationType8; } });Object.defineProperty(exports, "NotificationType9", { enumerable: true, get: function () { return messages_1.NotificationType9; } });Object.defineProperty(exports, "ParameterStructures", { enumerable: true, get: function () { return messages_1.ParameterStructures; } });const linkedMap_1 = require("./linkedMap");Object.defineProperty(exports, "LinkedMap", { enumerable: true, get: function () { return linkedMap_1.LinkedMap; } });Object.defineProperty(exports, "LRUCache", { enumerable: true, get: function () { return linkedMap_1.LRUCache; } });Object.defineProperty(exports, "Touch", { enumerable: true, get: function () { return linkedMap_1.Touch; } });const disposable_1 = require("./disposable");Object.defineProperty(exports, "Disposable", { enumerable: true, get: function () { return disposable_1.Disposable; } });const events_1 = require("./events");Object.defineProperty(exports, "Event", { enumerable: true, get: function () { return events_1.Event; } });Object.defineProperty(exports, "Emitter", { enumerable: true, get: function () { return events_1.Emitter; } });const cancellation_1 = require("./cancellation");Object.defineProperty(exports, "CancellationTokenSource", { enumerable: true, get: function () { return cancellation_1.CancellationTokenSource; } });Object.defineProperty(exports, "CancellationToken", { enumerable: true, get: function () { return cancellation_1.CancellationToken; } });const sharedArrayCancellation_1 = require("./sharedArrayCancellation");Object.defineProperty(exports, "SharedArraySenderStrategy", { enumerable: true, get: function () { return sharedArrayCancellation_1.SharedArraySenderStrategy; } });Object.defineProperty(exports, "SharedArrayReceiverStrategy", { enumerable: true, get: function () { return sharedArrayCancellation_1.SharedArrayReceiverStrategy; } });const messageReader_1 = require("./messageReader");Object.defineProperty(exports, "MessageReader", { enumerable: true, get: function () { return messageReader_1.MessageReader; } });Object.defineProperty(exports, "AbstractMessageReader", { enumerable: true, get: function () { return messageReader_1.AbstractMessageReader; } });Object.defineProperty(exports, "ReadableStreamMessageReader", { enumerable: true, get: function () { return messageReader_1.ReadableStreamMessageReader; } });const messageWriter_1 = require("./messageWriter");Object.defineProperty(exports, "MessageWriter", { enumerable: true, get: function () { return messageWriter_1.MessageWriter; } });Object.defineProperty(exports, "AbstractMessageWriter", { enumerable: true, get: function () { return messageWriter_1.AbstractMessageWriter; } });Object.defineProperty(exports, "WriteableStreamMessageWriter", { enumerable: true, get: function () { return messageWriter_1.WriteableStreamMessageWriter; } });const messageBuffer_1 = require("./messageBuffer");Object.defineProperty(exports, "AbstractMessageBuffer", { enumerable: true, get: function () { return messageBuffer_1.AbstractMessageBuffer; } });const connection_1 = require("./connection");Object.defineProperty(exports, "ConnectionStrategy", { enumerable: true, get: function () { return connection_1.ConnectionStrategy; } });Object.defineProperty(exports, "ConnectionOptions", { enumerable: true, get: function () { return connection_1.ConnectionOptions; } });Object.defineProperty(exports, "NullLogger", { enumerable: true, get: function () { return connection_1.NullLogger; } });Object.defineProperty(exports, "createMessageConnection", { enumerable: true, get: function () { return connection_1.createMessageConnection; } });Object.defineProperty(exports, "ProgressToken", { enumerable: true, get: function () { return connection_1.ProgressToken; } });Object.defineProperty(exports, "ProgressType", { enumerable: true, get: function () { return connection_1.ProgressType; } });Object.defineProperty(exports, "Trace", { enumerable: true, get: function () { return connection_1.Trace; } });Object.defineProperty(exports, "TraceValue", { enumerable: true, get: function () { return connection_1.TraceValue; } });Object.defineProperty(exports, "TraceFormat", { enumerable: true, get: function () { return connection_1.TraceFormat; } });Object.defineProperty(exports, "SetTraceNotification", { enumerable: true, get: function () { return connection_1.SetTraceNotification; } });Object.defineProperty(exports, "LogTraceNotification", { enumerable: true, get: function () { return connection_1.LogTraceNotification; } });Object.defineProperty(exports, "ConnectionErrors", { enumerable: true, get: function () { return connection_1.ConnectionErrors; } });Object.defineProperty(exports, "ConnectionError", { enumerable: true, get: function () { return connection_1.ConnectionError; } });Object.defineProperty(exports, "CancellationReceiverStrategy", { enumerable: true, get: function () { return connection_1.CancellationReceiverStrategy; } });Object.defineProperty(exports, "CancellationSenderStrategy", { enumerable: true, get: function () { return connection_1.CancellationSenderStrategy; } });Object.defineProperty(exports, "CancellationStrategy", { enumerable: true, get: function () { return connection_1.CancellationStrategy; } });Object.defineProperty(exports, "MessageStrategy", { enumerable: true, get: function () { return connection_1.MessageStrategy; } });Object.defineProperty(exports, "TraceValues", { enumerable: true, get: function () { return connection_1.TraceValues; } });const ral_1 = require("./ral");exports.RAL = ral_1.default;1231234567891011121314151617181920212223242526272829303132version https://git-lfs.github.com/spec/v1oid sha256:392dd7b1117b588cba36c04909efd24b0458980506e8e8c1966114f8989058e2size 1030import { Event } from './events';import { Disposable } from './disposable';/** * Defines a CancellationToken. This interface is not * intended to be implemented. A CancellationToken must * be created via a CancellationTokenSource. */export interface CancellationToken { /** * Is `true` when the token has been cancelled, `false` otherwise. */ readonly isCancellationRequested: boolean; /** * An {@link Event event} which fires upon cancellation. */ readonly onCancellationRequested: Event<any>;}export declare namespace CancellationToken { const None: CancellationToken; const Cancelled: CancellationToken; function is(value: any): value is CancellationToken;}export interface AbstractCancellationTokenSource extends Disposable { token: CancellationToken; cancel(): void;}export declare class CancellationTokenSource implements AbstractCancellationTokenSource { private _token; get token(): CancellationToken; cancel(): void; dispose(): void;}123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596version https://git-lfs.github.com/spec/v1oid sha256:bddf9e8f3bf2db7907d3c2551a690328cc6f978b1342432105dcbd072080e935size 3288"use strict";/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/Object.defineProperty(exports, "__esModule", { value: true });exports.CancellationTokenSource = exports.CancellationToken = void 0;const ral_1 = require("./ral");const Is = require("./is");const events_1 = require("./events");var CancellationToken;(function (CancellationToken) { CancellationToken.None = Object.freeze({ isCancellationRequested: false, onCancellationRequested: events_1.Event.None }); CancellationToken.Cancelled = Object.freeze({ isCancellationRequested: true, onCancellationRequested: events_1.Event.None }); function is(value) { const candidate = value; return candidate && (candidate === CancellationToken.None || candidate === CancellationToken.Cancelled || (Is.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested)); } CancellationToken.is = is;})(CancellationToken || (exports.CancellationToken = CancellationToken = {}));const shortcutEvent = Object.freeze(function (callback, context) { const handle = (0, ral_1.default)().timer.setTimeout(callback.bind(context), 0); return { dispose() { handle.dispose(); } };});class MutableToken { constructor() { this._isCancelled = false; } cancel() { if (!this._isCancelled) { this._isCancelled = true; if (this._emitter) { this._emitter.fire(undefined); this.dispose(); } } } get isCancellationRequested() { return this._isCancelled; } get onCancellationRequested() { if (this._isCancelled) { return shortcutEvent; } if (!this._emitter) { this._emitter = new events_1.Emitter(); } return this._emitter.event; } dispose() { if (this._emitter) { this._emitter.dispose(); this._emitter = undefined; } }}class CancellationTokenSource { get token() { if (!this._token) { // be lazy and create the token only when // actually needed this._token = new MutableToken(); } return this._token; } cancel() { if (!this._token) { // save an object by returning the default // cancelled token when cancellation happens // before someone asks for the token this._token = CancellationToken.Cancelled; } else { this._token.cancel(); } } dispose() { if (!this._token) { // ensure to initialize with an empty token if we had none this._token = CancellationToken.None; } else if (this._token instanceof MutableToken) { // actually dispose this._token.dispose(); } }}exports.CancellationTokenSource = CancellationTokenSource;123123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365version https://git-lfs.github.com/spec/v1oid sha256:d9c2b7ccd24031cb91d67e7f046c66f2cdfa7caf512ccbb365654fb7eb7ae05esize 18312import { Message, RequestMessage, RequestType, RequestType0, RequestType1, RequestType2, RequestType3, RequestType4, RequestType5, RequestType6, RequestType7, RequestType8, RequestType9, ResponseMessage, ResponseError, NotificationMessage, NotificationType, NotificationType0, NotificationType1, NotificationType2, NotificationType3, NotificationType4, NotificationType5, NotificationType6, NotificationType7, NotificationType8, NotificationType9, _EM, ParameterStructures } from './messages';import type { Disposable } from './disposable';import { Event } from './events';import { CancellationToken, AbstractCancellationTokenSource } from './cancellation';import { MessageReader } from './messageReader';import { MessageWriter } from './messageWriter';export type ProgressToken = number | string;export declare namespace ProgressToken { function is(value: any): value is number | string;}interface ProgressParams<T> { /** * The progress token provided by the client or server. */ token: ProgressToken; /** * The progress data. */ value: T;}export declare class ProgressType<PR> { /** * Clients must not use these properties. They are here to ensure correct typing. * in TypeScript */ readonly __: [PR, _EM] | undefined; readonly _pr: PR | undefined; constructor();}export type HandlerResult<R, E> = R | ResponseError<E> | Thenable<R> | Thenable<ResponseError<E>> | Thenable<R | ResponseError<E>>;export interface StarRequestHandler { (method: string, params: any[] | object | undefined, token: CancellationToken): HandlerResult<any, any>;}export interface GenericRequestHandler<R, E> { (...params: any[]): HandlerResult<R, E>;}export interface RequestHandler0<R, E> { (token: CancellationToken): HandlerResult<R, E>;}export interface RequestHandler<P, R, E> { (params: P, token: CancellationToken): HandlerResult<R, E>;}export interface RequestHandler1<P1, R, E> { (p1: P1, token: CancellationToken): HandlerResult<R, E>;}export interface RequestHandler2<P1, P2, R, E> { (p1: P1, p2: P2, token: CancellationToken): HandlerResult<R, E>;}export interface RequestHandler3<P1, P2, P3, R, E> { (p1: P1, p2: P2, p3: P3, token: CancellationToken): HandlerResult<R, E>;}export interface RequestHandler4<P1, P2, P3, P4, R, E> { (p1: P1, p2: P2, p3: P3, p4: P4, token: CancellationToken): HandlerResult<R, E>;}export interface RequestHandler5<P1, P2, P3, P4, P5, R, E> { (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, token: CancellationToken): HandlerResult<R, E>;}export interface RequestHandler6<P1, P2, P3, P4, P5, P6, R, E> { (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, token: CancellationToken): HandlerResult<R, E>;}export interface RequestHandler7<P1, P2, P3, P4, P5, P6, P7, R, E> { (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, token: CancellationToken): HandlerResult<R, E>;}export interface RequestHandler8<P1, P2, P3, P4, P5, P6, P7, P8, R, E> { (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, token: CancellationToken): HandlerResult<R, E>;}export interface RequestHandler9<P1, P2, P3, P4, P5, P6, P7, P8, P9, R, E> { (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, token: CancellationToken): HandlerResult<R, E>;}export type NotificationResult = void | Promise<void>;export interface StarNotificationHandler { (method: string, params: any[] | object | undefined): NotificationResult;}export interface GenericNotificationHandler { (...params: any[]): NotificationResult;}export interface NotificationHandler0 { (): NotificationResult;}export interface NotificationHandler<P> { (params: P): NotificationResult;}export interface NotificationHandler1<P1> { (p1: P1): NotificationResult;}export interface NotificationHandler2<P1, P2> { (p1: P1, p2: P2): NotificationResult;}export interface NotificationHandler3<P1, P2, P3> { (p1: P1, p2: P2, p3: P3): NotificationResult;}export interface NotificationHandler4<P1, P2, P3, P4> { (p1: P1, p2: P2, p3: P3, p4: P4): NotificationResult;}export interface NotificationHandler5<P1, P2, P3, P4, P5> { (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5): NotificationResult;}export interface NotificationHandler6<P1, P2, P3, P4, P5, P6> { (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6): NotificationResult;}export interface NotificationHandler7<P1, P2, P3, P4, P5, P6, P7> { (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7): NotificationResult;}export interface NotificationHandler8<P1, P2, P3, P4, P5, P6, P7, P8> { (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8): NotificationResult;}export interface NotificationHandler9<P1, P2, P3, P4, P5, P6, P7, P8, P9> { (p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9): NotificationResult;}export interface Logger { error(message: string): void; warn(message: string): void; info(message: string): void; log(message: string): void;}export declare const NullLogger: Logger;export declare enum Trace { Off = 0, Messages = 1, Compact = 2, Verbose = 3}export declare namespace TraceValue { /** * Turn tracing off. */ const Off: 'off'; /** * Trace messages only. */ const Messages: 'messages'; /** * Compact message tracing. */ const Compact: 'compact'; /** * Verbose message tracing. */ const Verbose: 'verbose';}export type TraceValue = 'off' | 'messages' | 'compact' | 'verbose';/** * @deprecated Use TraceValue instead */export declare const TraceValues: typeof TraceValue;export type TraceValues = TraceValue;export declare namespace Trace { function fromString(value: string): Trace; function toString(value: Trace): TraceValue;}export declare enum TraceFormat { Text = "text", JSON = "json"}export declare namespace TraceFormat { function fromString(value: string): TraceFormat;}export interface TraceOptions { sendNotification?: boolean; traceFormat?: TraceFormat;}export interface SetTraceParams { value: TraceValue;}export declare namespace SetTraceNotification { const type: NotificationType<SetTraceParams>;}export interface LogTraceParams { message: string; verbose?: string;}export declare namespace LogTraceNotification { const type: NotificationType<LogTraceParams>;}export interface Tracer { log(dataObject: any): void; log(message: string, data?: string): void;}export declare enum ConnectionErrors { /** * The connection is closed. */ Closed = 1, /** * The connection got disposed. */ Disposed = 2, /** * The connection is already in listening mode. */ AlreadyListening = 3}export declare class ConnectionError extends Error { readonly code: ConnectionErrors; constructor(code: ConnectionErrors, message: string);}export type ConnectionStrategy = { cancelUndispatched?: (message: Message, next: (message: Message) => ResponseMessage | undefined) => ResponseMessage | undefined;};export declare namespace ConnectionStrategy { function is(value: any): value is ConnectionStrategy;}export type CancellationId = number | string;export interface IdCancellationReceiverStrategy { kind?: 'id'; /** * Creates a CancellationTokenSource from a cancellation id. * * @param id The cancellation id. */ createCancellationTokenSource(id: CancellationId): AbstractCancellationTokenSource; /** * An optional method to dispose the strategy. */ dispose?(): void;}export declare namespace IdCancellationReceiverStrategy { function is(value: any): value is IdCancellationReceiverStrategy;}export interface RequestCancellationReceiverStrategy { kind: 'request'; /** * Create a cancellation token source from a given request message. * * @param requestMessage The request message. */ createCancellationTokenSource(requestMessage: RequestMessage): AbstractCancellationTokenSource; /** * An optional method to dispose the strategy. */ dispose?(): void;}export declare namespace RequestCancellationReceiverStrategy { function is(value: any): value is RequestCancellationReceiverStrategy;}export type CancellationReceiverStrategy = IdCancellationReceiverStrategy | RequestCancellationReceiverStrategy;export declare namespace CancellationReceiverStrategy { const Message: CancellationReceiverStrategy; function is(value: any): value is CancellationReceiverStrategy;}export interface CancellationSenderStrategy { /** * Hook to enable cancellation for the given request. * * @param request The request to enable cancellation for. */ enableCancellation?(request: RequestMessage): void; /** * Send cancellation for the given cancellation id * * @param conn The connection used. * @param id The cancellation id. */ sendCancellation(conn: MessageConnection, id: CancellationId): Promise<void>; /** * Cleanup any cancellation state for the given cancellation id. After this * method has been call no cancellation will be sent anymore for the given id. * * @param id The cancellation id. */ cleanup(id: CancellationId): void; /** * An optional method to dispose the strategy. */ dispose?(): void;}export declare namespace CancellationSenderStrategy { const Message: CancellationSenderStrategy; function is(value: any): value is CancellationSenderStrategy;}export interface CancellationStrategy { receiver: CancellationReceiverStrategy | RequestCancellationReceiverStrategy; sender: CancellationSenderStrategy;}export declare namespace CancellationStrategy { const Message: CancellationStrategy; function is(value: any): value is CancellationStrategy;}export interface MessageStrategy { handleMessage(message: Message, next: (message: Message) => NotificationResult): NotificationResult;}export declare namespace MessageStrategy { function is(value: any): value is MessageStrategy;}/** * Connection options. A valid connection option must have at least a * `CancellationStrategy` or a `MessageStrategy` or a `ConnectionStrategy`. */export interface ConnectionOptions { cancellationStrategy?: CancellationStrategy; connectionStrategy?: ConnectionStrategy; messageStrategy?: MessageStrategy; maxParallelism?: number;}export declare namespace ConnectionOptions { function is(value: any): value is ConnectionOptions;}export interface MessageConnection { sendRequest<R, E>(type: RequestType0<R, E>, token?: CancellationToken): Promise<R>; sendRequest<P, R, E>(type: RequestType<P, R, E>, params: P, token?: CancellationToken): Promise<R>; sendRequest<P1, R, E>(type: RequestType1<P1, R, E>, p1: P1, token?: CancellationToken): Promise<R>; sendRequest<P1, P2, R, E>(type: RequestType2<P1, P2, R, E>, p1: P1, p2: P2, token?: CancellationToken): Promise<R>; sendRequest<P1, P2, P3, R, E>(type: RequestType3<P1, P2, P3, R, E>, p1: P1, p2: P2, p3: P3, token?: CancellationToken): Promise<R>; sendRequest<P1, P2, P3, P4, R, E>(type: RequestType4<P1, P2, P3, P4, R, E>, p1: P1, p2: P2, p3: P3, p4: P4, token?: CancellationToken): Promise<R>; sendRequest<P1, P2, P3, P4, P5, R, E>(type: RequestType5<P1, P2, P3, P4, P5, R, E>, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, token?: CancellationToken): Promise<R>; sendRequest<P1, P2, P3, P4, P5, P6, R, E>(type: RequestType6<P1, P2, P3, P4, P5, P6, R, E>, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, token?: CancellationToken): Promise<R>; sendRequest<P1, P2, P3, P4, P5, P6, P7, R, E>(type: RequestType7<P1, P2, P3, P4, P5, P6, P7, R, E>, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, token?: CancellationToken): Promise<R>; sendRequest<P1, P2, P3, P4, P5, P6, P7, P8, R, E>(type: RequestType8<P1, P2, P3, P4, P5, P6, P7, P8, R, E>, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, token?: CancellationToken): Promise<R>; sendRequest<P1, P2, P3, P4, P5, P6, P7, P8, P9, R, E>(type: RequestType9<P1, P2, P3, P4, P5, P6, P7, P8, P9, R, E>, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9, token?: CancellationToken): Promise<R>; sendRequest<R>(method: string, r0?: ParameterStructures | any, ...rest: any[]): Promise<R>; onRequest<R, E>(type: RequestType0<R, E>, handler: RequestHandler0<R, E>): Disposable; onRequest<P, R, E>(type: RequestType<P, R, E>, handler: RequestHandler<P, R, E>): Disposable; onRequest<P1, R, E>(type: RequestType1<P1, R, E>, handler: RequestHandler1<P1, R, E>): Disposable; onRequest<P1, P2, R, E>(type: RequestType2<P1, P2, R, E>, handler: RequestHandler2<P1, P2, R, E>): Disposable; onRequest<P1, P2, P3, R, E>(type: RequestType3<P1, P2, P3, R, E>, handler: RequestHandler3<P1, P2, P3, R, E>): Disposable; onRequest<P1, P2, P3, P4, R, E>(type: RequestType4<P1, P2, P3, P4, R, E>, handler: RequestHandler4<P1, P2, P3, P4, R, E>): Disposable; onRequest<P1, P2, P3, P4, P5, R, E>(type: RequestType5<P1, P2, P3, P4, P5, R, E>, handler: RequestHandler5<P1, P2, P3, P4, P5, R, E>): Disposable; onRequest<P1, P2, P3, P4, P5, P6, R, E>(type: RequestType6<P1, P2, P3, P4, P5, P6, R, E>, handler: RequestHandler6<P1, P2, P3, P4, P5, P6, R, E>): Disposable; onRequest<P1, P2, P3, P4, P5, P6, P7, R, E>(type: RequestType7<P1, P2, P3, P4, P5, P6, P7, R, E>, handler: RequestHandler7<P1, P2, P3, P4, P5, P6, P7, R, E>): Disposable; onRequest<P1, P2, P3, P4, P5, P6, P7, P8, R, E>(type: RequestType8<P1, P2, P3, P4, P5, P6, P7, P8, R, E>, handler: RequestHandler8<P1, P2, P3, P4, P5, P6, P7, P8, R, E>): Disposable; onRequest<P1, P2, P3, P4, P5, P6, P7, P8, P9, R, E>(type: RequestType9<P1, P2, P3, P4, P5, P6, P7, P8, P9, R, E>, handler: RequestHandler9<P1, P2, P3, P4, P5, P6, P7, P8, P9, R, E>): Disposable; onRequest<R, E>(method: string, handler: GenericRequestHandler<R, E>): Disposable; onRequest(handler: StarRequestHandler): Disposable; hasPendingResponse(): boolean; sendNotification(type: NotificationType0): Promise<void>; sendNotification<P>(type: NotificationType<P>, params?: P): Promise<void>; sendNotification<P1>(type: NotificationType1<P1>, p1: P1): Promise<void>; sendNotification<P1, P2>(type: NotificationType2<P1, P2>, p1: P1, p2: P2): Promise<void>; sendNotification<P1, P2, P3>(type: NotificationType3<P1, P2, P3>, p1: P1, p2: P2, p3: P3): Promise<void>; sendNotification<P1, P2, P3, P4>(type: NotificationType4<P1, P2, P3, P4>, p1: P1, p2: P2, p3: P3, p4: P4): Promise<void>; sendNotification<P1, P2, P3, P4, P5>(type: NotificationType5<P1, P2, P3, P4, P5>, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5): Promise<void>; sendNotification<P1, P2, P3, P4, P5, P6>(type: NotificationType6<P1, P2, P3, P4, P5, P6>, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6): Promise<void>; sendNotification<P1, P2, P3, P4, P5, P6, P7>(type: NotificationType7<P1, P2, P3, P4, P5, P6, P7>, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7): Promise<void>; sendNotification<P1, P2, P3, P4, P5, P6, P7, P8>(type: NotificationType8<P1, P2, P3, P4, P5, P6, P7, P8>, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8): Promise<void>; sendNotification<P1, P2, P3, P4, P5, P6, P7, P8, P9>(type: NotificationType9<P1, P2, P3, P4, P5, P6, P7, P8, P9>, p1: P1, p2: P2, p3: P3, p4: P4, p5: P5, p6: P6, p7: P7, p8: P8, p9: P9): Promise<void>; sendNotification(method: string, r0?: ParameterStructures | any, ...rest: any[]): Promise<void>; onNotification(type: NotificationType0, handler: NotificationHandler0): Disposable; onNotification<P>(type: NotificationType<P>, handler: NotificationHandler<P>): Disposable; onNotification<P1>(type: NotificationType1<P1>, handler: NotificationHandler1<P1>): Disposable; onNotification<P1, P2>(type: NotificationType2<P1, P2>, handler: NotificationHandler2<P1, P2>): Disposable; onNotification<P1, P2, P3>(type: NotificationType3<P1, P2, P3>, handler: NotificationHandler3<P1, P2, P3>): Disposable; onNotification<P1, P2, P3, P4>(type: NotificationType4<P1, P2, P3, P4>, handler: NotificationHandler4<P1, P2, P3, P4>): Disposable; onNotification<P1, P2, P3, P4, P5>(type: NotificationType5<P1, P2, P3, P4, P5>, handler: NotificationHandler5<P1, P2, P3, P4, P5>): Disposable; onNotification<P1, P2, P3, P4, P5, P6>(type: NotificationType6<P1, P2, P3, P4, P5, P6>, handler: NotificationHandler6<P1, P2, P3, P4, P5, P6>): Disposable; onNotification<P1, P2, P3, P4, P5, P6, P7>(type: NotificationType7<P1, P2, P3, P4, P5, P6, P7>, handler: NotificationHandler7<P1, P2, P3, P4, P5, P6, P7>): Disposable; onNotification<P1, P2, P3, P4, P5, P6, P7, P8>(type: NotificationType8<P1, P2, P3, P4, P5, P6, P7, P8>, handler: NotificationHandler8<P1, P2, P3, P4, P5, P6, P7, P8>): Disposable; onNotification<P1, P2, P3, P4, P5, P6, P7, P8, P9>(type: NotificationType9<P1, P2, P3, P4, P5, P6, P7, P8, P9>, handler: NotificationHandler9<P1, P2, P3, P4, P5, P6, P7, P8, P9>): Disposable; onNotification(method: string, handler: GenericNotificationHandler): Disposable; onNotification(handler: StarNotificationHandler): Disposable; onUnhandledNotification: Event<NotificationMessage>; onProgress<P>(type: ProgressType<P>, token: string | number, handler: NotificationHandler<P>): Disposable; sendProgress<P>(type: ProgressType<P>, token: string | number, value: P): Promise<void>; onUnhandledProgress: Event<ProgressParams<any>>; trace(value: Trace, tracer: Tracer, sendNotification?: boolean): Promise<void>; trace(value: Trace, tracer: Tracer, traceOptions?: TraceOptions): Promise<void>; onError: Event<[Error, Message | undefined, number | undefined]>; onClose: Event<void>; listen(): void; end(): void; onDispose: Event<void>; dispose(): void; inspect(): void;}export declare function createMessageConnection(messageReader: MessageReader, messageWriter: MessageWriter, _logger?: Logger, options?: ConnectionOptions): MessageConnection;export {};12312345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220version https://git-lfs.github.com/spec/v1oid sha256:1725210c7c2aba1d9ac0d094be8e93a3635ba4c26bfc4ea10624f38717177394size 50857"use strict";/* -------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. * ------------------------------------------------------------------------------------------ */Object.defineProperty(exports, "__esModule", { value: true });exports.createMessageConnection = exports.ConnectionOptions = exports.MessageStrategy = exports.CancellationStrategy = exports.CancellationSenderStrategy = exports.CancellationReceiverStrategy = exports.RequestCancellationReceiverStrategy = exports.IdCancellationReceiverStrategy = exports.ConnectionStrategy = exports.ConnectionError = exports.ConnectionErrors = exports.LogTraceNotification = exports.SetTraceNotification = exports.TraceFormat = exports.TraceValues = exports.TraceValue = exports.Trace = exports.NullLogger = exports.ProgressType = exports.ProgressToken = void 0;const ral_1 = require("./ral");const Is = require("./is");const messages_1 = require("./messages");const linkedMap_1 = require("./linkedMap");const events_1 = require("./events");const cancellation_1 = require("./cancellation");var CancelNotification;(function (CancelNotification) { CancelNotification.type = new messages_1.NotificationType('$/cancelRequest');})(CancelNotification || (CancelNotification = {}));var ProgressToken;(function (ProgressToken) { function is(value) { return typeof value === 'string' || typeof value === 'number'; } ProgressToken.is = is;})(ProgressToken || (exports.ProgressToken = ProgressToken = {}));var ProgressNotification;(function (ProgressNotification) { ProgressNotification.type = new messages_1.NotificationType('$/progress');})(ProgressNotification || (ProgressNotification = {}));class ProgressType { constructor() { }}exports.ProgressType = ProgressType;var StarRequestHandler;(function (StarRequestHandler) { function is(value) { return Is.func(value); } StarRequestHandler.is = is;})(StarRequestHandler || (StarRequestHandler = {}));exports.NullLogger = Object.freeze({ error: () => { }, warn: () => { }, info: () => { }, log: () => { }});var Trace;(function (Trace) { Trace[Trace["Off"] = 0] = "Off"; Trace[Trace["Messages"] = 1] = "Messages"; Trace[Trace["Compact"] = 2] = "Compact"; Trace[Trace["Verbose"] = 3] = "Verbose";})(Trace || (exports.Trace = Trace = {}));var TraceValue;(function (TraceValue) { /** * Turn tracing off. */ TraceValue.Off = 'off'; /** * Trace messages only. */ TraceValue.Messages = 'messages'; /** * Compact message tracing. */ TraceValue.Compact = 'compact'; /** * Verbose message tracing. */ TraceValue.Verbose = 'verbose';})(TraceValue || (exports.TraceValue = TraceValue = {}));/** * @deprecated Use TraceValue instead */exports.TraceValues = TraceValue;(function (Trace) { function fromString(value) { if (!Is.string(value)) { return Trace.Off; } value = value.toLowerCase(); switch (value) { case 'off': return Trace.Off; case 'messages': return Trace.Messages; case 'compact': return Trace.Compact; case 'verbose': return Trace.Verbose; default: return Trace.Off; } } Trace.fromString = fromString; function toString(value) { switch (value) { case Trace.Off: return 'off'; case Trace.Messages: return 'messages'; case Trace.Compact: return 'compact'; case Trace.Verbose: return 'verbose'; default: return 'off'; } } Trace.toString = toString;})(Trace || (exports.Trace = Trace = {}));var TraceFormat;(function (TraceFormat) { TraceFormat["Text"] = "text"; TraceFormat["JSON"] = "json";})(TraceFormat || (exports.TraceFormat = TraceFormat = {}));(function (TraceFormat) { function fromString(value) { if (!Is.string(value)) { return TraceFormat.Text; } value = value.toLowerCase(); if (value === 'json') { return TraceFormat.JSON; } else { return TraceFormat.Text; } } TraceFormat.fromString = fromString;})(TraceFormat || (exports.TraceFormat = TraceFormat = {}));var SetTraceNotification;(function (SetTraceNotification) { SetTraceNotification.type = new messages_1.NotificationType('$/setTrace');})(SetTraceNotification || (exports.SetTraceNotification = SetTraceNotification = {}));var LogTraceNotification;(function (LogTraceNotification) { LogTraceNotification.type = new messages_1.NotificationType('$/logTrace');})(LogTraceNotification || (exports.LogTraceNotification = LogTraceNotification = {}));var ConnectionErrors;(function (ConnectionErrors) { /** * The connection is closed. */ ConnectionErrors[ConnectionErrors["Closed"] = 1] = "Closed"; /** * The connection got disposed. */ ConnectionErrors[ConnectionErrors["Disposed"] = 2] = "Disposed"; /** * The connection is already in listening mode. */ ConnectionErrors[ConnectionErrors["AlreadyListening"] = 3] = "AlreadyListening";})(ConnectionErrors || (exports.ConnectionErrors = ConnectionErrors = {}));class ConnectionError extends Error { constructor(code, message) { super(message); this.code = code; Object.setPrototypeOf(this, ConnectionError.prototype); }}exports.ConnectionError = ConnectionError;var ConnectionStrategy;(function (ConnectionStrategy) { function is(value) { const candidate = value; return candidate && Is.func(candidate.cancelUndispatched); } ConnectionStrategy.is = is;})(ConnectionStrategy || (exports.ConnectionStrategy = ConnectionStrategy = {}));var IdCancellationReceiverStrategy;(function (IdCancellationReceiverStrategy) { function is(value) { const candidate = value; return candidate && (candidate.kind === undefined || candidate.kind === 'id') && Is.func(candidate.createCancellationTokenSource) && (candidate.dispose === undefined || Is.func(candidate.dispose)); } IdCancellationReceiverStrategy.is = is;})(IdCancellationReceiverStrategy || (exports.IdCancellationReceiverStrategy = IdCancellationReceiverStrategy = {}));var RequestCancellationReceiverStrategy;(function (RequestCancellationReceiverStrategy) { function is(value) { const candidate = value; return candidate && candidate.kind === 'request' && Is.func(candidate.createCancellationTokenSource) && (candidate.dispose === undefined || Is.func(candidate.dispose)); } RequestCancellationReceiverStrategy.is = is;})(RequestCancellationReceiverStrategy || (exports.RequestCancellationReceiverStrategy = RequestCancellationReceiverStrategy = {}));var CancellationReceiverStrategy;(function (CancellationReceiverStrategy) { CancellationReceiverStrategy.Message = Object.freeze({ createCancellationTokenSource(_) { return new cancellation_1.CancellationTokenSource(); } }); function is(value) { return IdCancellationReceiverStrategy.is(value) || RequestCancellationReceiverStrategy.is(value); } CancellationReceiverStrategy.is = is;})(CancellationReceiverStrategy || (exports.CancellationReceiverStrategy = CancellationReceiverStrategy = {}));var CancellationSenderStrategy;(function (CancellationSenderStrategy) { CancellationSenderStrategy.Message = Object.freeze({ sendCancellation(conn, id) { return conn.sendNotification(CancelNotification.type, { id }); }, cleanup(_) { } }); function is(value) { const candidate = value; return candidate && Is.func(candidate.sendCancellation) && Is.func(candidate.cleanup); } CancellationSenderStrategy.is = is;})(CancellationSenderStrategy || (exports.CancellationSenderStrategy = CancellationSenderStrategy = {}));var CancellationStrategy;(function (CancellationStrategy) { CancellationStrategy.Message = Object.freeze({ receiver: CancellationReceiverStrategy.Message, sender: CancellationSenderStrategy.Message }); function is(value) { const candidate = value; return candidate && CancellationReceiverStrategy.is(candidate.receiver) && CancellationSenderStrategy.is(candidate.sender); } CancellationStrategy.is = is;})(CancellationStrategy || (exports.CancellationStrategy = CancellationStrategy = {}));var MessageStrategy;(function (MessageStrategy) { function is(value) { const candidate = value; return candidate && Is.func(candidate.handleMessage); } MessageStrategy.is = is;})(MessageStrategy || (exports.MessageStrategy = MessageStrategy = {}));var ConnectionOptions;(function (ConnectionOptions) { function is(value) { const candidate = value; return candidate && (CancellationStrategy.is(candidate.cancellationStrategy) || ConnectionStrategy.is(candidate.connectionStrategy) || MessageStrategy.is(candidate.messageStrategy) || Is.number(candidate.maxParallelism)); } ConnectionOptions.is = is;})(ConnectionOptions || (exports.ConnectionOptions = ConnectionOptions = {}));var ConnectionState;(function (ConnectionState) { ConnectionState[ConnectionState["New"] = 1] = "New"; ConnectionState[ConnectionState["Listening"] = 2] = "Listening"; ConnectionState[ConnectionState["Closed"] = 3] = "Closed"; ConnectionState[ConnectionState["Disposed"] = 4] = "Disposed";})(ConnectionState || (ConnectionState = {}));function createMessageConnection(messageReader, messageWriter, _logger, options) { const logger = _logger !== undefined ? _logger : exports.NullLogger; let sequenceNumber = 0; let notificationSequenceNumber = 0; let unknownResponseSequenceNumber = 0; const version = '2.0'; const maxParallelism = options?.maxParallelism ?? -1; let inFlight = 0; let starRequestHandler = undefined; const requestHandlers = new Map(); let starNotificationHandler = undefined; const notificationHandlers = new Map(); const progressHandlers = new Map(); let timer; let messageQueue = new linkedMap_1.LinkedMap(); let responsePromises = new Map(); let knownCanceledRequests = new Set(); let requestTokens = new Map(); let trace = Trace.Off; let traceFormat = TraceFormat.Text; let tracer; let state = ConnectionState.New; const errorEmitter = new events_1.Emitter(); const closeEmitter = new events_1.Emitter(); const unhandledNotificationEmitter = new events_1.Emitter(); const unhandledProgressEmitter = new events_1.Emitter(); const disposeEmitter = new events_1.Emitter(); const cancellationStrategy = (options && options.cancellationStrategy) ? options.cancellationStrategy : CancellationStrategy.Message; function cancelUndispatched(_message) { return undefined; } function isListening() { return state === ConnectionState.Listening; } function isClosed() { return state === ConnectionState.Closed; } function isDisposed() { return state === ConnectionState.Disposed; } function closeHandler() { if (state === ConnectionState.New || state === ConnectionState.Listening) { state = ConnectionState.Closed; closeEmitter.fire(undefined); } // If the connection is disposed don't sent close events. } function readErrorHandler(error) { errorEmitter.fire([error, undefined, undefined]); } function writeErrorHandler(data) { errorEmitter.fire(data); } messageReader.onClose(closeHandler); messageReader.onError(readErrorHandler); messageWriter.onClose(closeHandler); messageWriter.onError(writeErrorHandler); function createRequestQueueKey(id) { if (id === null) { throw new Error(`Can't send requests with id null since the response can't be correlated.`); } return 'req-' + id.toString(); } function createResponseQueueKey(id) { if (id === null) { return 'res-unknown-' + (++unknownResponseSequenceNumber).toString(); } else { return 'res-' + id.toString(); } } function createNotificationQueueKey() { return 'not-' + (++notificationSequenceNumber).toString(); } function addMessageToQueue(queue, message) { if (messages_1.Message.isRequest(message)) { queue.set(createRequestQueueKey(message.id), message); } else if (messages_1.Message.isResponse(message)) { // If we have unlimited parallelism we queue the response to keep // the previous semantics. if (maxParallelism === -1) { queue.set(createResponseQueueKey(message.id), message); } else { // If we have limited parallelism we resolve responses to avoid // dead locks. handleResponse(message); } } else { queue.set(createNotificationQueueKey(), message); } } function triggerMessageQueue() { if (timer || messageQueue.size === 0) { return; } if (maxParallelism !== -1 && inFlight >= maxParallelism) { return; } timer = (0, ral_1.default)().timer.setImmediate(async () => { timer = undefined; if (messageQueue.size === 0) { return; } if (maxParallelism !== -1 && inFlight >= maxParallelism) { return; } const message = messageQueue.shift(); let result; try { inFlight++; const messageStrategy = options?.messageStrategy; if (MessageStrategy.is(messageStrategy)) { result = messageStrategy.handleMessage(message, handleMessage); } else { result = handleMessage(message); } } catch (error) { logger.error(`Processing message queue failed: ${error.toString()}`); } finally { if (result instanceof Promise) { result.then(() => { inFlight--; triggerMessageQueue(); }).catch((error) => { logger.error(`Processing message queue failed: ${error.toString()}`); }); } else { inFlight--; } triggerMessageQueue(); } }); } async function handleMessage(message) { if (messages_1.Message.isRequest(message)) { return handleRequest(message); } else if (messages_1.Message.isNotification(message)) { return handleNotification(message); } else if (messages_1.Message.isResponse(message)) { return handleResponse(message); } else { return handleInvalidMessage(message); } } const callback = (message) => { try { // We have received a cancellation message. Check if the message is still in the queue // and cancel it if allowed to do so. if (messages_1.Message.isNotification(message) && message.method === CancelNotification.type.method) { const cancelId = message.params.id; const key = createRequestQueueKey(cancelId); const toCancel = messageQueue.get(key); if (messages_1.Message.isRequest(toCancel)) { const strategy = options?.connectionStrategy; const response = (strategy && strategy.cancelUndispatched) ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel); if (response && (response.error !== undefined || response.result !== undefined)) { messageQueue.delete(key); requestTokens.delete(cancelId); response.id = toCancel.id; traceSendingResponse(response, message.method, Date.now()); messageWriter.write(response).catch(() => logger.error(`Sending response for canceled message failed.`)); return; } } const cancellationToken = requestTokens.get(cancelId); // The request is already running. Cancel the token if (cancellationToken !== undefined) { cancellationToken.cancel(); traceReceivedNotification(message); return; } else { // Remember the cancel but still queue the message to // clean up state in process message. knownCanceledRequests.add(cancelId); } } addMessageToQueue(messageQueue, message); } finally { triggerMessageQueue(); } }; async function handleRequest(requestMessage) { if (isDisposed()) { // we return here silently since we fired an event when the // connection got disposed. return Promise.resolve(); } function reply(resultOrError, method, startTime) { const message = { jsonrpc: version, id: requestMessage.id }; if (resultOrError instanceof messages_1.ResponseError) { message.error = resultOrError.toJson(); } else { message.result = resultOrError === undefined ? null : resultOrError; } traceSendingResponse(message, method, startTime); return messageWriter.write(message); } function replyError(error, method, startTime) { const message = { jsonrpc: version, id: requestMessage.id, error: error.toJson() }; traceSendingResponse(message, method, startTime); return messageWriter.write(message); } traceReceivedRequest(requestMessage); const element = requestHandlers.get(requestMessage.method); let type; let requestHandler; if (element) { type = element.type; requestHandler = element.handler; } const startTime = Date.now(); if (requestHandler || starRequestHandler) { const tokenKey = requestMessage.id ?? String(Date.now()); // const cancellationSource = IdCancellationReceiverStrategy.is(cancellationStrategy.receiver) ? cancellationStrategy.receiver.createCancellationTokenSource(tokenKey) : cancellationStrategy.receiver.createCancellationTokenSource(requestMessage); if (requestMessage.id !== null && knownCanceledRequests.has(requestMessage.id)) { cancellationSource.cancel(); } if (requestMessage.id !== null) { requestTokens.set(tokenKey, cancellationSource); } try { let handlerResult; if (requestHandler) { if (requestMessage.params === undefined) { if (type !== undefined && type.numberOfParams !== 0) { return replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines ${type.numberOfParams} params but received none.`), requestMessage.method, startTime); } handlerResult = requestHandler(cancellationSource.token); } else if (Array.isArray(requestMessage.params)) { if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byName) { return replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by name but received parameters by position`), requestMessage.method, startTime); } handlerResult = requestHandler(...requestMessage.params, cancellationSource.token); } else { if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byPosition) { return replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by position but received parameters by name`), requestMessage.method, startTime); } handlerResult = requestHandler(requestMessage.params, cancellationSource.token); } } else if (starRequestHandler) { handlerResult = starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token); } const resultOrError = await handlerResult; await reply(resultOrError, requestMessage.method, startTime); } catch (error) { if (error instanceof messages_1.ResponseError) { await reply(error, requestMessage.method, startTime); } else if (error && Is.string(error.message)) { await replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime); } else { await replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime); } } finally { requestTokens.delete(tokenKey); } } else { await replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime); } } function handleResponse(responseMessage) { if (isDisposed()) { // See handle request. return; } if (responseMessage.id === null) { if (responseMessage.error) { logger.error(`Received response message without id: Error is: \n${JSON.stringify(responseMessage.error, undefined, 4)}`); } else { logger.error(`Received response message without id. No further error information provided.`); } } else { const key = responseMessage.id; const responsePromise = responsePromises.get(key); traceReceivedResponse(responseMessage, responsePromise); if (responsePromise !== undefined) { responsePromises.delete(key); try { if (responseMessage.error) { const error = responseMessage.error; responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data)); } else if (responseMessage.result !== undefined) { responsePromise.resolve(responseMessage.result); } else { throw new Error('Should never happen.'); } } catch (error) { if (error.message) { logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`); } else { logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`); } } } } } async function handleNotification(message) { if (isDisposed()) { // See handle request. return; } let type = undefined; let notificationHandler; if (message.method === CancelNotification.type.method) { const cancelId = message.params.id; knownCanceledRequests.delete(cancelId); traceReceivedNotification(message); return; } else { const element = notificationHandlers.get(message.method); if (element) { notificationHandler = element.handler; type = element.type; } } if (notificationHandler || starNotificationHandler) { try { traceReceivedNotification(message); if (notificationHandler) { if (message.params === undefined) { if (type !== undefined) { if (type.numberOfParams !== 0 && type.parameterStructures !== messages_1.ParameterStructures.byName) { logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received none.`); } } await notificationHandler(); } else if (Array.isArray(message.params)) { // There are JSON-RPC libraries that send progress message as positional params although // specified as named. So convert them if this is the case. const params = message.params; if (message.method === ProgressNotification.type.method && params.length === 2 && ProgressToken.is(params[0])) { await notificationHandler({ token: params[0], value: params[1] }); } else { if (type !== undefined) { if (type.parameterStructures === messages_1.ParameterStructures.byName) { logger.error(`Notification ${message.method} defines parameters by name but received parameters by position`); } if (type.numberOfParams !== message.params.length) { logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received ${params.length} arguments`); } } await notificationHandler(...params); } } else { if (type !== undefined && type.parameterStructures === messages_1.ParameterStructures.byPosition) { logger.error(`Notification ${message.method} defines parameters by position but received parameters by name`); } await notificationHandler(message.params); } } else if (starNotificationHandler) { await starNotificationHandler(message.method, message.params); } } catch (error) { if (error.message) { logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`); } else { logger.error(`Notification handler '${message.method}' failed unexpectedly.`); } } } else { unhandledNotificationEmitter.fire(message); } } function handleInvalidMessage(message) { if (!message) { logger.error('Received empty message.'); return; } logger.error(`Received message which is neither a response nor a notification message:\n${JSON.stringify(message, null, 4)}`); // Test whether we find an id to reject the promise const responseMessage = message; if (Is.string(responseMessage.id) || Is.number(responseMessage.id)) { const key = responseMessage.id; const responseHandler = responsePromises.get(key); if (responseHandler) { responseHandler.reject(new Error('The received response has neither a result nor an error property.')); } } } function stringifyTrace(params) { if (params === undefined || params === null) { return undefined; } switch (trace) { case Trace.Verbose: return JSON.stringify(params, null, 4); case Trace.Compact: return JSON.stringify(params); default: return undefined; } } function traceSendingRequest(message) { if (trace === Trace.Off || !tracer) { return; } if (traceFormat === TraceFormat.Text) { let data = undefined; if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) { data = `Params: ${stringifyTrace(message.params)}\n\n`; } tracer.log(`Sending request '${message.method} - (${message.id})'.`, data); } else { logLSPMessage('send-request', message); } } function traceSendingNotification(message) { if (trace === Trace.Off || !tracer) { return; } if (traceFormat === TraceFormat.Text) { let data = undefined; if (trace === Trace.Verbose || trace === Trace.Compact) { if (message.params) { data = `Params: ${stringifyTrace(message.params)}\n\n`; } else { data = 'No parameters provided.\n\n'; } } tracer.log(`Sending notification '${message.method}'.`, data); } else { logLSPMessage('send-notification', message); } } function traceSendingResponse(message, method, startTime) { if (trace === Trace.Off || !tracer) { return; } if (traceFormat === TraceFormat.Text) { let data = undefined; if (trace === Trace.Verbose || trace === Trace.Compact) { if (message.error && message.error.data) { data = `Error data: ${stringifyTrace(message.error.data)}\n\n`; } else { if (message.result) { data = `Result: ${stringifyTrace(message.result)}\n\n`; } else if (message.error === undefined) { data = 'No result returned.\n\n'; } } } tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data); } else { logLSPMessage('send-response', message); } } function traceReceivedRequest(message) { if (trace === Trace.Off || !tracer) { return; } if (traceFormat === TraceFormat.Text) { let data = undefined; if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) { data = `Params: ${stringifyTrace(message.params)}\n\n`; } tracer.log(`Received request '${message.method} - (${message.id})'.`, data); } else { logLSPMessage('receive-request', message); } } function traceReceivedNotification(message) { if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) { return; } if (traceFormat === TraceFormat.Text) { let data = undefined; if (trace === Trace.Verbose || trace === Trace.Compact) { if (message.params) { data = `Params: ${stringifyTrace(message.params)}\n\n`; } else { data = 'No parameters provided.\n\n'; } } tracer.log(`Received notification '${message.method}'.`, data); } else { logLSPMessage('receive-notification', message); } } function traceReceivedResponse(message, responsePromise) { if (trace === Trace.Off || !tracer) { return; } if (traceFormat === TraceFormat.Text) { let data = undefined; if (trace === Trace.Verbose || trace === Trace.Compact) { if (message.error && message.error.data) { data = `Error data: ${stringifyTrace(message.error.data)}\n\n`; } else { if (message.result) { data = `Result: ${stringifyTrace(message.result)}\n\n`; } else if (message.error === undefined) { data = 'No result returned.\n\n'; } } } if (responsePromise) { const error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : ''; tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data); } else { tracer.log(`Received response ${message.id} without active response promise.`, data); } } else { logLSPMessage('receive-response', message); } } function logLSPMessage(type, message) { if (!tracer || trace === Trace.Off) { return; } const lspMessage = { isLSPMessage: true, type, message, timestamp: Date.now() }; tracer.log(lspMessage); } function throwIfClosedOrDisposed() { if (isClosed()) { throw new ConnectionError(ConnectionErrors.Closed, 'Connection is closed.'); } if (isDisposed()) { throw new ConnectionError(ConnectionErrors.Disposed, 'Connection is disposed.'); } } function throwIfListening() { if (isListening()) { throw new ConnectionError(ConnectionErrors.AlreadyListening, 'Connection is already listening'); } } function throwIfNotListening() { if (!isListening()) { throw new Error('Call listen() first.'); } } function undefinedToNull(param) { if (param === undefined) { return null; } else { return param; } } function nullToUndefined(param) { if (param === null) { return undefined; } else { return param; } } function isNamedParam(param) { return param !== undefined && param !== null && !Array.isArray(param) && typeof param === 'object'; } function computeSingleParam(parameterStructures, param) { switch (parameterStructures) { case messages_1.ParameterStructures.auto: if (isNamedParam(param)) { return nullToUndefined(param); } else { return [undefinedToNull(param)]; } case messages_1.ParameterStructures.byName: if (!isNamedParam(param)) { throw new Error(`Received parameters by name but param is not an object literal.`); } return nullToUndefined(param); case messages_1.ParameterStructures.byPosition: return [undefinedToNull(param)]; default: throw new Error(`Unknown parameter structure ${parameterStructures.toString()}`); } } function computeMessageParams(type, params) { let result; const numberOfParams = type.numberOfParams; switch (numberOfParams) { case 0: result = undefined; break; case 1: result = computeSingleParam(type.parameterStructures, params[0]); break; default: result = []; for (let i = 0; i < params.length && i < numberOfParams; i++) { result.push(undefinedToNull(params[i])); } if (params.length < numberOfParams) { for (let i = params.length; i < numberOfParams; i++) { result.push(null); } } break; } return result; } const connection = { sendNotification: (type, ...args) => { throwIfClosedOrDisposed(); let method; let messageParams; if (Is.string(type)) { method = type; const first = args[0]; let paramStart = 0; let parameterStructures = messages_1.ParameterStructures.auto; if (messages_1.ParameterStructures.is(first)) { paramStart = 1; parameterStructures = first; } const paramEnd = args.length; const numberOfParams = paramEnd - paramStart; switch (numberOfParams) { case 0: messageParams = undefined; break; case 1: messageParams = computeSingleParam(parameterStructures, args[paramStart]); break; default: if (parameterStructures === messages_1.ParameterStructures.byName) { throw new Error(`Received ${numberOfParams} parameters for 'by Name' notification parameter structure.`); } messageParams = args.slice(paramStart, paramEnd).map(value => undefinedToNull(value)); break; } } else { const params = args; method = type.method; messageParams = computeMessageParams(type, params); } const notificationMessage = { jsonrpc: version, method: method, params: messageParams }; traceSendingNotification(notificationMessage); return messageWriter.write(notificationMessage).catch((error) => { logger.error(`Sending notification failed.`); throw error; }); }, onNotification: (type, handler) => { throwIfClosedOrDisposed(); let method; if (Is.func(type)) { starNotificationHandler = type; } else if (handler) { if (Is.string(type)) { method = type; notificationHandlers.set(type, { type: undefined, handler }); } else { method = type.method; notificationHandlers.set(type.method, { type, handler }); } } return { dispose: () => { if (method !== undefined) { notificationHandlers.delete(method); } else { starNotificationHandler = undefined; } } }; }, onProgress: (_type, token, handler) => { if (progressHandlers.has(token)) { throw new Error(`Progress handler for token ${token} already registered`); } progressHandlers.set(token, handler); return { dispose: () => { progressHandlers.delete(token); } }; }, sendProgress: (_type, token, value) => { // This should not await but simple return to ensure that we don't have another // async scheduling. Otherwise one send could overtake another send. return connection.sendNotification(ProgressNotification.type, { token, value }); }, onUnhandledProgress: unhandledProgressEmitter.event, sendRequest: (type, ...args) => { throwIfClosedOrDisposed(); throwIfNotListening(); function sendCancellation(connection, id) { const p = cancellationStrategy.sender.sendCancellation(connection, id); if (p === undefined) { logger.log(`Received no promise from cancellation strategy when cancelling id ${id}`); } else { p.catch(() => { logger.log(`Sending cancellation messages for id ${id} failed.`); }); } } let method; let messageParams; let token = undefined; if (Is.string(type)) { method = type; const first = args[0]; const last = args[args.length - 1]; let paramStart = 0; let parameterStructures = messages_1.ParameterStructures.auto; if (messages_1.ParameterStructures.is(first)) { paramStart = 1; parameterStructures = first; } let paramEnd = args.length; if (cancellation_1.CancellationToken.is(last)) { paramEnd = paramEnd - 1; token = last; } const numberOfParams = paramEnd - paramStart; switch (numberOfParams) { case 0: messageParams = undefined; break; case 1: messageParams = computeSingleParam(parameterStructures, args[paramStart]); break; default: if (parameterStructures === messages_1.ParameterStructures.byName) { throw new Error(`Received ${numberOfParams} parameters for 'by Name' request parameter structure.`); } messageParams = args.slice(paramStart, paramEnd).map(value => undefinedToNull(value)); break; } } else { const params = args; method = type.method; messageParams = computeMessageParams(type, params); const numberOfParams = type.numberOfParams; token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : undefined; } const id = sequenceNumber++; let disposable; let tokenWasCancelled = false; if (token !== undefined) { if (token.isCancellationRequested) { tokenWasCancelled = true; } else { disposable = token.onCancellationRequested(() => { sendCancellation(connection, id); }); } } const requestMessage = { jsonrpc: version, id: id, method: method, params: messageParams }; traceSendingRequest(requestMessage); if (typeof cancellationStrategy.sender.enableCancellation === 'function') { cancellationStrategy.sender.enableCancellation(requestMessage); } // eslint-disable-next-line no-async-promise-executor return new Promise(async (resolve, reject) => { const resolveWithCleanup = (r) => { resolve(r); cancellationStrategy.sender.cleanup(id); disposable?.dispose(); }; const rejectWithCleanup = (r) => { reject(r); cancellationStrategy.sender.cleanup(id); disposable?.dispose(); }; const responsePromise = { method: method, timerStart: Date.now(), resolve: resolveWithCleanup, reject: rejectWithCleanup }; try { await messageWriter.write(requestMessage); responsePromises.set(id, responsePromise); if (tokenWasCancelled) { sendCancellation(connection, id); } } catch (error) { logger.error(`Sending request failed.`); // Writing the message failed. So we need to reject the promise. responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, error.message ? error.message : 'Unknown reason')); throw error; } }); }, onRequest: (type, handler) => { throwIfClosedOrDisposed(); let method = null; if (StarRequestHandler.is(type)) { method = undefined; starRequestHandler = type; } else if (Is.string(type)) { method = null; if (handler !== undefined) { method = type; requestHandlers.set(type, { handler: handler, type: undefined }); } } else { if (handler !== undefined) { method = type.method; requestHandlers.set(type.method, { type, handler }); } } return { dispose: () => { if (method === null) { return; } if (method !== undefined) { requestHandlers.delete(method); } else { starRequestHandler = undefined; } } }; }, hasPendingResponse: () => { return responsePromises.size > 0; }, trace: async (_value, _tracer, sendNotificationOrTraceOptions) => { let _sendNotification = false; let _traceFormat = TraceFormat.Text; if (sendNotificationOrTraceOptions !== undefined) { if (Is.boolean(sendNotificationOrTraceOptions)) { _sendNotification = sendNotificationOrTraceOptions; } else { _sendNotification = sendNotificationOrTraceOptions.sendNotification || false; _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text; } } trace = _value; traceFormat = _traceFormat; if (trace === Trace.Off) { tracer = undefined; } else { tracer = _tracer; } if (_sendNotification && !isClosed() && !isDisposed()) { await connection.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) }); } }, onError: errorEmitter.event, onClose: closeEmitter.event, onUnhandledNotification: unhandledNotificationEmitter.event, onDispose: disposeEmitter.event, end: () => { messageWriter.end(); }, dispose: () => { if (isDisposed()) { return; } state = ConnectionState.Disposed; disposeEmitter.fire(undefined); const error = new messages_1.ResponseError(messages_1.ErrorCodes.PendingResponseRejected, 'Pending response rejected since connection got disposed'); for (const promise of responsePromises.values()) { promise.reject(error); } responsePromises = new Map(); requestTokens = new Map(); knownCanceledRequests = new Set(); messageQueue = new linkedMap_1.LinkedMap(); // Test for backwards compatibility if (Is.func(messageWriter.dispose)) { messageWriter.dispose(); } if (Is.func(messageReader.dispose)) { messageReader.dispose(); } }, listen: () => { throwIfClosedOrDisposed(); throwIfListening(); state = ConnectionState.Listening; messageReader.listen(callback); }, inspect: () => { // eslint-disable-next-line no-console (0, ral_1.default)().console.log('inspect'); } }; connection.onNotification(LogTraceNotification.type, (params) => { if (trace === Trace.Off || !tracer) { return; } const verbose = trace === Trace.Verbose || trace === Trace.Compact; tracer.log(params.message, verbose ? params.verbose : undefined); }); connection.onNotification(ProgressNotification.type, async (params) => { const handler = progressHandlers.get(params.token); if (handler) { await handler(params.value); } else { unhandledProgressEmitter.fire(params); } }); return connection;}exports.createMessageConnection = createMessageConnection;Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-html-languageservice/README.md+69-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-html-languageservice/SECURITY.md+41-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-html-languageservice/node_modules/vscode-uri/LICENSE.md+9-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-html-languageservice/node_modules/vscode-uri/README.md+67-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-html-languageservice/node_modules/vscode-uri/SECURITY.md+41-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-html-languageservice/node_modules/vscode-uri/lib/umd/utils.d.ts+58-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-html-languageservice/node_modules/vscode-uri/lib/umd/utils.js+123-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-html-languageservice/node_modules/vscode-uri/package.json+43-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-html-languageservice/package.json+50-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-html-languageservice/thirdpartynotices.txt+49-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/dist/node/jsonServerMain.js
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/@vscode/l10n/README.md+42-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/@vscode/l10n/dist/browser.js+103-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/@vscode/l10n/dist/main.d.ts+130-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/@vscode/l10n/dist/main.js+151-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/@vscode/l10n/dist/tsdoc-metadata.json+11-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/@vscode/l10n/package.json+50-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/CHANGELOG.md+72-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/LICENSE.md+21-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/README.md+362-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/SECURITY.md+41-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/esm/impl/edit.js+185-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/esm/impl/format.js+261-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/esm/impl/parser.js+632-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/esm/impl/scanner.js+443-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/esm/impl/string-intern.js+29-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/esm/main.d.ts+349-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/esm/main.js+178-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/umd/impl/edit.js+201-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/umd/impl/format.js+275-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/umd/impl/parser.js+655-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/umd/impl/scanner.js+456-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/umd/impl/string-intern.js+42-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/umd/main.d.ts+349-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/lib/umd/main.js+194-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/jsonc-parser/package.json+37-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/License.txt+11-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/README.md+69-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/browser.d.ts+6-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/browser.js+7-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/lib/browser/main.d.ts+17-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/lib/browser/main.js+76-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/lib/browser/ril.d.ts+12-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/lib/browser/ril.js+156-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/lib/common/api.d.ts+14-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/lib/common/api.js+82-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/lib/common/cancellation.d.ts+32-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/lib/common/cancellation.js+96-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/lib/common/connection.d.ts+365-3
Java开发环境安装/eclipse-jee-2024-06-R-win32-x86_64/eclipse/plugins/org.eclipse.wildwebdeveloper_1.2.2.202405280856/node_modules/vscode-json-languageserver/node_modules/vscode-jsonrpc/lib/common/connection.js+1220-3