Compare commits

..

No commits in common. "main" and "v3.2.0" have entirely different histories.
main ... v3.2.0

35 changed files with 15582 additions and 3023 deletions

View file

@ -1,19 +1,24 @@
extends:
- remcohaszing
- remcohaszing/typechecking
extends: remcohaszing
rules:
class-methods-use-this: off
max-classes-per-file: off
no-console: off
no-restricted-globals: off
no-underscore-dangle: off
no-useless-constructor: off
'@typescript-eslint/no-misused-promises': off
'@typescript-eslint/naming-convention': off
'@typescript-eslint/no-parameter-properties': off
'@typescript-eslint/no-shadow': off
'@typescript-eslint/no-unnecessary-condition': off
'@typescript-eslint/prefer-optional-chain': off
import/extensions: off
import/no-extraneous-dependencies: off
import/no-unresolved: off
import/no-webpack-loader-syntax: off
jsdoc/require-jsdoc: off
node/no-extraneous-import: off
node/no-unpublished-import: off
node/no-unsupported-features/es-syntax: off
node/no-unsupported-features/node-builtins: off

View file

@ -16,16 +16,6 @@ jobs:
- run: npm ci
- run: npx eslint .
examples:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with: { node-version: 16 }
- run: npm ci
- run: npm run prepack
- run: npm run build --workspaces
pack:
runs-on: ubuntu-latest
steps:
@ -52,15 +42,16 @@ jobs:
with: { node-version: 16 }
- run: npm ci
- run: npx tsc
# release:
# runs-on: ubuntu-latest
# needs: [eslint, pack, prettier, tsc]
# if: startsWith(github.ref, 'refs/tags/')
# steps:
# - uses: actions/checkout@v2
# - uses: actions/setup-node@v2
# with: { node-version: 16 }
# - run: npm ci
# - run: npm publish
# env:
# NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
release:
runs-on: ubuntu-latest
needs: [eslint, pack, prettier, tsc]
if: startsWith(github.ref, 'refs/tags/')
steps:
- uses: actions/checkout@v2
- uses: actions/setup-node@v2
with: { node-version: 16 }
- run: npm ci
- run: npm publish
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

4
.gitignore vendored
View file

@ -1,7 +1,5 @@
dist/
node_modules/
/index.js
/yaml.worker.js
/lib/
*.log
*.map
*.tgz

1
.npmrc
View file

@ -1 +0,0 @@
lockfile-version = 3

View file

@ -1,3 +1,3 @@
dist/
/index.js
/yaml.worker.js
/dist/
/lib/
/out/

View file

@ -1,15 +1,5 @@
# Contributing
## Prerequisites
The following are required to start working on this project:
- [Git](https://git-scm.com)
- [NodeJS](https://nodejs.org) 16 or higher
- [npm](https://github.com/npm/cli) 8.1.2 or higher
## Getting started
To get started with contributing, clone the repository and install its dependencies.
```sh
@ -18,19 +8,16 @@ cd monaco-yaml
npm ci
```
## Building
To build the repository, run:
```sh
npm run prepack
npm prepack
```
## Running
To test it, run one of the
[examples](https://github.com/remcohaszing/monaco-yaml/tree/main/examples).
```sh
npm --workspace demo start
cd examples/webpack-worker-loader
npm start
```

101
README.md
View file

@ -16,7 +16,6 @@ files:
- Document Symbols
- Automatically load remote schema files (by enabling DiagnosticsOptions.enableSchemaRequest)
- Links from JSON references.
- Links and hover effects from YAML anchors.
Schemas can also be provided by configuration. See
[here](https://github.com/remcohaszing/monaco-yaml/blob/main/index.d.ts) for the API that the plugin
@ -32,7 +31,7 @@ npm install monaco-yaml
Import `monaco-yaml` and configure it before an editor instance is created.
```typescript
```ts
import { editor, Uri } from 'monaco-editor';
import { setDiagnosticsOptions } from 'monaco-yaml';
@ -86,43 +85,7 @@ editor.create(document.createElement('editor'), {
});
```
Also make sure to register the web worker. When using Webpack 5, this looks like the code below.
Other bundlers may use a different syntax, but the idea is the same. Languages you dont used can be
omitted.
```js
window.MonacoEnvironment = {
getWorker(moduleId, label) {
switch (label) {
case 'editorWorkerService':
return new Worker(new URL('monaco-editor/esm/vs/editor/editor.worker', import.meta.url));
case 'css':
case 'less':
case 'scss':
return new Worker(new URL('monaco-editor/esm/vs/language/css/css.worker', import.meta.url));
case 'handlebars':
case 'html':
case 'razor':
return new Worker(
new URL('monaco-editor/esm/vs/language/html/html.worker', import.meta.url),
);
case 'json':
return new Worker(
new URL('monaco-editor/esm/vs/language/json/json.worker', import.meta.url),
);
case 'javascript':
case 'typescript':
return new Worker(
new URL('monaco-editor/esm/vs/language/typescript/ts.worker', import.meta.url),
);
case 'yaml':
return new Worker(new URL('monaco-yaml/yaml.worker', import.meta.url));
default:
throw new Error(`Unknown label ${label}`);
}
},
};
```
Also make sure to register the web worker.
## Examples
@ -133,66 +96,6 @@ A running example: ![demo-image](test-demo.png)
Some usage examples can be found in the
[examples](https://github.com/remcohaszing/monaco-yaml/tree/main/examples) directory.
## FAQ
### Does this work with the Monaco UMD bundle?
No. Only ESM is supported.
### Does this work with Monaco Editor from a CDN?
No, because these use a UMD bundle, which isnt supported.
### Does this work with `@monaco-editor/loader` or `@monaco-editor/react`?
No. These packages pull in the Monaco UMD bundle from a CDN. Because UMD isnt supported, neither
are these packages.
### Is the web worker necessary?
Yes. The web worker provides the core functionality of `monaco-yaml`.
### Does it work without a bundler?
No. `monaco-yaml` uses dependencies from `node_modules`, so they can be deduped and your bundle size
is decreased. This comes at the cost of not being able to use it without a bundler.
### How do I integrate `monaco-yaml` with a framework? (Angular, React, Vue, etc.)
`monaco-yaml` only uses the Monaco Editor. Its not tied to a framework, all thats needed is a DOM
node to attach the Monaco Editor to. See the
[Monaco Editor examples](https://github.com/microsoft/monaco-editor/tree/main/monaco-editor-samples)
for examples on how to integrate Monaco Editor in your project, then configure `monaco-yaml` as
described above.
### Does `monaco-yaml` work with `create-react-app`?
Yes, but youll have to eject. See
[#92 (comment)](https://github.com/remcohaszing/monaco-yaml/issues/92#issuecomment-905836058) for
details.
### Why isnt `monaco-yaml` working? Official Monaco language extensions do work.
This is most likely due to the fact that `monaco-yaml` is using a different instance of the
`monaco-editor` package than you are. This is something youll want to avoid regardless of
`monaco-editor`, because it means your bundle is significantly larger than it needs to be. This is
likely caused by one of the following issues:
- A code splitting misconfiguration
To solve this, try inspecting your bundle using for example
[webpack-bundle-analyzer](https://github.com/webpack-contrib/webpack-bundle-analyzer). If
`monaco-editor` is in there twice, this is the issue. Its up to you to solve this, as its
project-specific.
- Youre using a package which imports `monaco-editor` for you, but its using a different version.
You can find out why the `monaco-editor` is installed using `npm ls monaco-editor` or
`yarn why monaco-editor`. It should exist only once, but its ok if its deduped.
You may be able to solve this by deleting your `node_modules` folder and `package-lock.json` or
`yarn.lock`, then running `npm install` or `yarn install` respectively.
## Contributing
Please see our [contributing guidelines](CONTRIBUTING.md)

121
build.js
View file

@ -1,58 +1,71 @@
const { promises: fs } = require('fs');
const { join } = require('path');
const { build } = require('esbuild');
const { dependencies, peerDependencies } = require('./package.json');
build({
entryPoints: ['src/index.ts', 'src/yaml.worker.ts'],
bundle: true,
external: Object.keys({ ...dependencies, ...peerDependencies }),
logLevel: 'info',
outdir: '.',
sourcemap: true,
format: 'esm',
target: ['es2019'],
plugins: [
{
name: 'alias',
setup({ onResolve }) {
// The file monaco-yaml/lib/esm/schemaSelectionHandlers.js imports code from the language
// server part that we dont want.
onResolve({ filter: /\/schemaSelectionHandlers$/ }, () => ({
path: require.resolve('./src/fillers/schemaSelectionHandlers.ts'),
}));
// The yaml language service only imports re-exports of vscode-languageserver-types from
// vscode-languageserver.
onResolve({ filter: /^vscode-languageserver(\/node|-protocol)?$/ }, () => ({
path: 'vscode-languageserver-types',
external: true,
}));
// The yaml language service uses path. We can stub it using path-browserify.
onResolve({ filter: /^path$/ }, () => ({
path: 'path-browserify',
external: true,
}));
// The main prettier entry point contains all of Prettier.
// The standalone bundle is smaller and works fine for us.
onResolve({ filter: /^prettier/ }, ({ path }) => ({
path: path === 'prettier' ? 'prettier/standalone.js' : `${path}.js`,
external: true,
}));
// This tiny filler implementation serves all our needs.
onResolve({ filter: /vscode-nls/ }, () => ({
path: require.resolve('./src/fillers/vscode-nls.ts'),
}));
// The language server dependencies tend to write both ESM and UMD output alongside each
// other, then use UMD for imports. We prefer ESM.
onResolve({ filter: /\/umd\// }, (args) => ({
path: require.resolve(args.path.replace(/\/umd\//, '/esm/'), {
paths: [args.resolveDir],
}),
}));
},
},
],
}).catch((error) => {
// eslint-disable-next-line no-console
console.error(error);
process.exit(1);
});
fs.rm(join(__dirname, 'lib'), { force: true, recursive: true })
.then(() =>
build({
entryPoints: ['src/monaco.contribution.ts', 'src/yaml.worker.ts'],
bundle: true,
external: Object.keys({ ...dependencies, ...peerDependencies }),
logLevel: 'info',
outdir: 'lib/esm',
sourcemap: true,
format: 'esm',
target: ['es2019'],
plugins: [
{
name: 'alias',
setup({ onResolve }) {
// The yaml language service only imports re-exports of vscode-languageserver-types from
// vscode-languageserver.
onResolve({ filter: /^vscode-languageserver-textdocument$/ }, () => ({
path: 'vscode-languageserver-textdocument/lib/esm/main.js',
external: true,
}));
// The yaml language service only imports re-exports of vscode-languageserver-types from
// vscode-languageserver.
onResolve({ filter: /^vscode-languageserver$/ }, () => ({
path: 'vscode-languageserver-types/lib/esm/main.js',
external: true,
}));
// The yaml language service only imports re-exports of vscode-languageserver-types from
// vscode-languageserver.
onResolve({ filter: /^vscode-languageserver-types$/ }, () => ({
path: 'vscode-languageserver-types/lib/esm/main.js',
external: true,
}));
// The yaml language service uses path. We can stub it using path-browserify.
onResolve({ filter: /^path$/ }, () => ({
path: 'path-browserify',
external: true,
}));
// The main prettier entry point contains all of Prettier.
// The standalone bundle is smaller and works fine for us.
onResolve({ filter: /^prettier$/ }, () => ({
path: 'prettier/standalone',
external: true,
}));
// This tiny filler implementation serves all our needs.
onResolve({ filter: /vscode-nls/ }, () => ({
path: require.resolve('./src/fillers/vscode-nls.ts'),
}));
// The language server dependencies tend to write both ESM and UMD output alongside each
// other, then use UMD for imports. We prefer ESM.
onResolve({ filter: /\/umd\// }, (args) => ({
path: require.resolve(args.path.replace(/\/umd\//, '/esm/'), {
paths: [args.resolveDir],
}),
}));
},
},
],
}),
)
.catch((error) => {
console.error(error);
process.exit(1);
});

View file

@ -2,30 +2,10 @@
This demo is deployed to [monaco-yaml.js.org](https://monaco-yaml.js.org). It shows how
`monaco-editor` and `monaco-yaml` can be used with
[Webpack 5](https://webpack.js.org/concepts/entry-points).
## Prerequisites
- [NodeJS](https://nodejs.org) 16 or higher
- [npm](https://github.com/npm/cli) 8.1.2 or higher
## Setup
To run the project locally, clone the repository and set it up:
[Webpack 5](https://webpack.js.org/concepts/entry-points). To start it, simply run:
```sh
git clone https://github.com/remcohaszing/monaco-yaml
cd monaco-yaml
npm ci
npm run prepack
```
## Running
To start it, simply run:
```sh
npm --workspace demo start
npm start
```
The demo will open in your browser.

View file

@ -7,13 +7,13 @@
"build": "webpack --mode production"
},
"dependencies": {
"@fortawesome/fontawesome-free": "^6.0.0",
"@fortawesome/fontawesome-free": "^5.0.0",
"@schemastore/schema-catalog": "^0.0.5",
"css-loader": "^6.0.0",
"css-minimizer-webpack-plugin": "^3.0.0",
"html-webpack-plugin": "^5.0.0",
"mini-css-extract-plugin": "^2.0.0",
"monaco-editor": "^0.31.0",
"monaco-editor": "^0.27.0",
"monaco-yaml": "file:../..",
"ts-loader": "^9.0.0",
"typescript": "^4.0.0",

View file

@ -31,7 +31,7 @@ window.MonacoEnvironment = {
case 'editorWorkerService':
return new Worker(new URL('monaco-editor/esm/vs/editor/editor.worker', import.meta.url));
case 'yaml':
return new Worker(new URL('monaco-yaml/yaml.worker', import.meta.url));
return new Worker(new URL('monaco-yaml/lib/esm/yaml.worker', import.meta.url));
default:
throw new Error(`Unknown label ${label}`);
}
@ -44,6 +44,11 @@ const defaultSchema: SchemasSettings = {
};
setDiagnosticsOptions({
validate: true,
enableSchemaRequest: true,
format: true,
hover: true,
completion: true,
schemas: [defaultSchema],
});
@ -64,10 +69,6 @@ markdown: hover me to get a markdown based description 😮
enum:
# Unused anchors will be reported
unused anchor: &unused anchor
# Of course numbers are supported!
number: 12
@ -99,14 +100,6 @@ pointer:
$ref: '#/array'
# This anchor can be referenced
anchorRef: &anchor can be clicked as well
# Press control while hovering over the anchor
anchorPointer: *anchor
formatting: Formatting is supported too! Under the hood this is powered by Prettier. Just press Ctrl+Shift+I or right click and press Format to format this document.
@ -128,7 +121,7 @@ fetch('https://www.schemastore.org/api/json/catalog.json').then(async (response)
if (!response.ok) {
return;
}
const catalog = (await response.json()) as JSONSchemaForSchemaStoreOrgCatalogFiles;
const catalog: JSONSchemaForSchemaStoreOrgCatalogFiles = await response.json();
const schemas = [defaultSchema];
catalog.schemas.sort((a, b) => a.name.localeCompare(b.name));
for (const { fileMatch, name, url } of catalog.schemas) {
@ -159,10 +152,7 @@ fetch('https://www.schemastore.org/api/json/catalog.json').then(async (response)
});
select.addEventListener('change', () => {
const oldModel = ed.getModel();
const newModel = editor.createModel(oldModel.getValue(), 'yaml', Uri.parse(select.value));
ed.setModel(newModel);
oldModel.dispose();
ed.setModel(editor.createModel(ed.getValue(), 'yaml', Uri.parse(select.value)));
});
function* iterateSymbols(
@ -188,7 +178,6 @@ ed.onDidChangeCursorPosition(async (event) => {
breadcrumb.setAttribute('role', 'button');
breadcrumb.classList.add('breadcrumb');
breadcrumb.textContent = symbol.name;
breadcrumb.title = symbol.detail;
if (symbol.kind === languages.SymbolKind.Array) {
breadcrumb.classList.add('array');
} else if (symbol.kind === languages.SymbolKind.Module) {

View file

@ -1,29 +1,4 @@
declare module 'monaco-editor/esm/vs/base/common/cancellation' {
export enum CancellationToken {
None,
}
}
declare module 'monaco-editor/esm/vs/editor/contrib/documentSymbols/documentSymbols' {
import { ITextModel, languages } from 'monaco-editor';
import { CancellationToken } from 'monaco-editor/esm/vs/base/common/cancellation';
export function getDocumentSymbols(
model: ITextModel,
flat: boolean,
token: CancellationToken,
): Promise<languages.DocumentSymbol[]>;
}
declare module 'monaco-editor/esm/vs/editor/editor.worker.js' {
import { worker } from 'monaco-editor/esm/vs/editor/editor.api';
export function initialize(
fn: (ctx: worker.IWorkerContext, createData: unknown) => unknown,
): void;
}
declare module '*.json' {
declare const uri: string;
declare const uri;
export default uri;
}

View file

@ -6,9 +6,12 @@ module.exports = {
output: {
filename: '[contenthash].js',
},
devtool: 'source-map',
resolve: {
extensions: ['.mjs', '.js', '.ts'],
fallback: {
// Yaml-ast-parser-custom-tags imports buffer. This can be omitted safely.
buffer: false,
},
},
module: {
rules: [

View file

@ -1,35 +0,0 @@
# Monaco Editor Webpack Loader Plugin Example
This demo demonstrates how bundle `monaco-editor` and `monaco-yaml` with
[monaco-editor-webpack-plugin](https://github.com/microsoft/monaco-editor/tree/main/webpack-plugin).
The build output is
[esm library](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules). Example is
based on
[link](https://github.com/microsoft/monaco-editor/tree/main/samples/browser-esm-webpack-monaco-plugin).
To start it, simply run:
## Prerequisites
- [NodeJS](https://nodejs.org) 16 or higher
- [npm](https://github.com/npm/cli) 8.1.2 or higher
## Setup
To run the project locally, clone the repository and set it up:
```sh
git clone https://github.com/remcohaszing/monaco-yaml
cd monaco-yaml
npm ci
npm run prepack
```
## Running
To start it, simply run:
```sh
npm --workspace monaco-editor-webpack-plugin-example start
```
The demo will open in your browser.

View file

@ -1,4 +0,0 @@
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api.js';
export { setDiagnosticsOptions } from 'monaco-yaml';
export default monaco;

View file

@ -1,20 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Monaco Editor Webpack Plugin Example</title>
<style>
.editor {
width: 800px;
height: 600px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div class="editor"></div>
<script src="index.js" type="module"></script>
</body>
</html>

View file

@ -1,37 +0,0 @@
const value = `
number: 0xfe
boolean: true
`;
async function create() {
// Dynamic import is possible
const { default: monaco } = await import('./main.js');
// Define schema first
monaco.languages.yaml.yamlDefaults.setDiagnosticsOptions({
schemas: [
{
fileMatch: ['*'],
uri: 'my-schema.json',
schema: {
type: 'object',
properties: {
number: {
description: 'number property',
type: 'number',
},
},
},
},
],
});
// Create editor
monaco.editor.create(document.querySelector('.editor'), {
language: 'yaml',
tabSize: 2,
value,
});
}
create();

View file

@ -1,20 +0,0 @@
{
"name": "monaco-editor-webpack-plugin-example",
"version": "1.0.0",
"private": true,
"type": "module",
"scripts": {
"start": "webpack serve --open --mode development",
"build": "webpack --mode production"
},
"dependencies": {
"css-loader": "^6.0.0",
"monaco-editor": "^0.31.0",
"monaco-editor-webpack-plugin": "^7.0.0",
"monaco-yaml": "file:../..",
"style-loader": "^3.0.0",
"webpack": "^5.0.0",
"webpack-cli": "^4.0.0",
"webpack-dev-server": "^4.0.0"
}
}

View file

@ -1,49 +0,0 @@
import MonacoWebpackPlugin from 'monaco-editor-webpack-plugin';
export default {
entry: './editor.js',
output: {
filename: '[name].js',
library: {
type: 'module',
},
clean: true,
},
target: 'es2020',
experiments: {
outputModule: true,
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.css$/,
use: ['style-loader', 'css-loader'],
},
{
test: /\.ttf$/,
type: 'asset',
},
],
},
plugins: [
new MonacoWebpackPlugin({
languages: [],
customLanguages: [
{
label: 'yaml',
entry: ['monaco-yaml', 'vs/basic-languages/yaml/yaml.contribution'],
worker: {
id: 'monaco-yaml/yamlWorker',
entry: 'monaco-yaml/yaml.worker',
},
},
],
}),
],
devServer: {
static: {
directory: './',
},
},
};

View file

@ -1,29 +0,0 @@
# Vite Example
This minimal example shows how `monaco-yaml` can be used with [Vite](https://vitejs.dev).
## Prerequisites
- [NodeJS](https://nodejs.org) 16 or higher
- [npm](https://github.com/npm/cli) 8.1.2 or higher
## Setup
To run the project locally, clone the repository and set it up:
```sh
git clone https://github.com/remcohaszing/monaco-yaml
cd monaco-yaml
npm ci
npm run prepack
```
## Running
To start it, simply run:
```sh
npm --workspace vite-example start
```
The demo will be available on http://localhost:3000.

View file

@ -1,11 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Monaco YAML</title>
</head>
<body>
<div id="editor" style="width: 800px; height: 600px;"></div>
<script type="module" src="/index.js"></script>
</body>
</html>

View file

@ -1,67 +0,0 @@
import { editor, Uri } from 'monaco-editor';
import EditorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';
import { setDiagnosticsOptions } from 'monaco-yaml';
import YamlWorker from 'monaco-yaml/yaml.worker?worker';
window.MonacoEnvironment = {
getWorker(moduleId, label) {
switch (label) {
case 'editorWorkerService':
return new EditorWorker();
case 'yaml':
return new YamlWorker();
default:
throw new Error(`Unknown label ${label}`);
}
},
};
// The uri is used for the schema file match.
const modelUri = Uri.parse('a://b/foo.yaml');
setDiagnosticsOptions({
enableSchemaRequest: true,
hover: true,
completion: true,
validate: true,
format: true,
schemas: [
{
// Id of the first schema
uri: 'http://myserver/foo-schema.json',
// Associate with our model
fileMatch: [String(modelUri)],
schema: {
type: 'object',
properties: {
p1: {
enum: ['v1', 'v2'],
},
p2: {
// Reference the second schema
$ref: 'http://myserver/bar-schema.json',
},
},
},
},
{
// Id of the first schema
uri: 'http://myserver/bar-schema.json',
schema: {
type: 'object',
properties: {
q1: {
enum: ['x1', 'x2'],
},
},
},
},
],
});
const value = 'p1: \np2: \n';
editor.create(document.getElementById('editor'), {
automaticLayout: true,
model: editor.createModel(value, 'yaml', modelUri),
});

View file

@ -1,14 +0,0 @@
{
"name": "vite-example",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "vite",
"build": "vite build"
},
"dependencies": {
"monaco-editor": "^0.31.0",
"monaco-yaml": "file:../..",
"vite": "^2.0.0"
}
}

68
index.d.ts vendored
View file

@ -29,68 +29,44 @@ declare module 'monaco-editor/esm/vs/editor/editor.api' {
export interface DiagnosticsOptions {
/**
* If set, enable schema based autocompletion.
*
* @default true
*/
readonly completion?: boolean;
/**
* A list of custom tags.
*
* @default []
*/
readonly customTags?: string[];
/**
* If set, the schema service would load schema content on-demand with 'fetch' if available
*
* @default false
*/
readonly enableSchemaRequest?: boolean;
/**
* If true, formatting using Prettier is enabled. Setting this to `false` does **not** exclude
* Prettier from the bundle.
*
* @default true
*/
readonly format?: boolean;
/**
* If set, enable hover typs based the JSON schema.
*
* @default true
*/
readonly hover?: boolean;
/**
* If true, a different diffing algorithm is used to generate error messages.
*
* @default false
*/
readonly isKubernetes?: boolean;
/**
* A list of known schemas and/or associations of schemas to file names.
*
* @default []
*/
readonly schemas?: SchemasSettings[];
/**
* If set, the validator will be enabled and perform syntax validation as well as schema
* based validation.
*
* @default true
*/
readonly validate?: boolean;
/**
* The YAML version to use for parsing.
*
* @default '1.2'
* A list of known schemas and/or associations of schemas to file names.
*/
readonly yamlVersion?: '1.1' | '1.2';
readonly schemas?: SchemasSettings[];
/**
* If set, the schema service would load schema content on-demand with 'fetch' if available
*/
readonly enableSchemaRequest?: boolean;
/**
* If specified, this prefix will be added to all on demand schema requests
*/
readonly prefix?: string;
/**
* Whether or not kubernetes yaml is supported
*/
readonly isKubernetes?: boolean;
/**
* A list of custom tags.
*/
readonly customTags?: string[];
readonly format?: boolean;
}
export interface LanguageServiceDefaults {

17600
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,17 +1,18 @@
{
"name": "monaco-yaml",
"version": "4.0.0-alpha.1",
"version": "3.2.0",
"description": "YAML plugin for the Monaco Editor",
"homepage": "https://monaco-yaml.js.org",
"scripts": {
"prepack": "node build.js",
"prepare": "husky install"
},
"main": "./lib/esm/monaco.contribution.js",
"module": "./lib/esm/monaco.contribution.js",
"typings": "./index.d.ts",
"files": [
"index.js",
"index.d.ts",
"yaml.worker.js"
"lib",
"index.d.ts"
],
"workspaces": [
"examples/*"
@ -38,28 +39,30 @@
],
"dependencies": {
"@types/json-schema": "^7.0.0",
"jsonc-parser": "^3.0.0",
"js-yaml": "^4.0.0",
"path-browserify": "^1.0.0",
"prettier": "2.0.5",
"vscode-languageserver-textdocument": "^1.0.0",
"vscode-languageserver-types": "^3.0.0",
"yaml": "2.0.0-10"
"yaml-language-server-parser": "^0.1.0"
},
"peerDependencies": {
"monaco-editor": ">=0.30"
"monaco-editor": ">=0.22"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^5.0.0",
"esbuild": "^0.14.0",
"@typescript-eslint/eslint-plugin": "^4.0.0",
"@typescript-eslint/parser": "^4.0.0",
"esbuild": "^0.12.0",
"eslint": "^7.0.0",
"eslint-config-remcohaszing": "^3.0.0",
"husky": "^7.0.0",
"lint-staged": "^12.0.0",
"monaco-editor": "^0.31.0",
"lint-staged": "^11.0.0",
"monaco-editor": "^0.27.0",
"type-fest": "^2.0.0",
"typescript": "^4.0.0",
"yaml-language-server": "^1.0.0"
"yaml-language-server": "^0.22.0"
},
"resolutions": {},
"lint-staged": {
"*.{css,json,md,html,yaml}": [
"prettier --write"

View file

@ -1 +0,0 @@
export const languageId = 'yaml';

View file

@ -1,5 +0,0 @@
/**
* This is a stub for `monaco-yaml/lib/esm/schemaSelectionHandlers.js`.
*/
// eslint-disable-next-line @typescript-eslint/no-empty-function
export function JSONSchemaSelection(): void {}

View file

@ -16,7 +16,7 @@ export type LoadFunc = (file?: string) => LocalizeFunc;
function format(message: string, args: string[]): string {
return args.length === 0
? message
: message.replace(/{(\d+)}/g, (match, rest: number[]) => {
: message.replace(/{(\d+)}/g, (match, rest) => {
const [index] = rest;
return typeof args[index] === 'undefined' ? match : args[index];
});

View file

@ -1,17 +1,16 @@
import {
editor,
IDisposable,
IMarkdownString,
languages,
MarkerSeverity,
MarkerTag,
Position,
Range,
Uri,
} from 'monaco-editor/esm/vs/editor/editor.api.js';
} from 'monaco-editor/esm/vs/editor/editor.api';
import * as ls from 'vscode-languageserver-types';
import { CustomFormatterOptions } from 'yaml-language-server/lib/esm/languageservice/yamlLanguageService.js';
import { CustomFormatterOptions } from 'yaml-language-server/lib/esm/languageservice/yamlLanguageService';
import { languageId } from './constants';
import { YAMLWorker } from './yamlWorker';
export type WorkerAccessor = (...more: Uri[]) => PromiseLike<YAMLWorker>;
@ -33,17 +32,9 @@ function toSeverity(lsSeverity: ls.DiagnosticSeverity): MarkerSeverity {
}
}
function toMarkerDataTag(tag: ls.DiagnosticTag): MarkerTag {
switch (tag) {
case ls.DiagnosticTag.Deprecated:
return MarkerTag.Deprecated;
case ls.DiagnosticTag.Unnecessary:
return MarkerTag.Unnecessary;
default:
}
}
function toDiagnostics(resource: Uri, diag: ls.Diagnostic): editor.IMarkerData {
const code = typeof diag.code === 'number' ? String(diag.code) : (diag.code as string);
function toDiagnostics(diag: ls.Diagnostic): editor.IMarkerData {
return {
severity: toSeverity(diag.severity),
startLineNumber: diag.range.start.line + 1,
@ -51,59 +42,55 @@ function toDiagnostics(diag: ls.Diagnostic): editor.IMarkerData {
endLineNumber: diag.range.end.line + 1,
endColumn: diag.range.end.character + 1,
message: diag.message,
code: String(diag.code),
code,
source: diag.source,
tags: diag.tags?.map(toMarkerDataTag),
};
}
export function createDiagnosticsAdapter(
languageId: string,
getWorker: WorkerAccessor,
defaults: languages.yaml.LanguageServiceDefaults,
): void {
const listeners = new Map<string, IDisposable>();
const listeners: Record<string, IDisposable> = Object.create(null);
const resetSchema = async (resource: Uri): Promise<void> => {
const worker = await getWorker();
worker.resetSchema(String(resource));
};
const doValidate = async (resource: Uri): Promise<void> => {
const doValidate = async (resource: Uri, languageId: string): Promise<void> => {
const worker = await getWorker(resource);
const diagnostics = await worker.doValidation(String(resource));
const markers = diagnostics.map(toDiagnostics);
const markers = diagnostics.map((d) => toDiagnostics(resource, d));
const model = editor.getModel(resource);
// Return value from getModel can be null if model not found
// (e.g. if user navigates away from editor)
if (model && model.getLanguageId() === languageId) {
if (model.getModeId() === languageId) {
editor.setModelMarkers(model, languageId, markers);
}
};
const onModelAdd = (model: editor.IModel): void => {
if (model.getLanguageId() !== languageId) {
const modeId = model.getModeId();
if (modeId !== languageId) {
return;
}
let handle: ReturnType<typeof setTimeout>;
listeners.set(
String(model.uri),
model.onDidChangeContent(() => {
clearTimeout(handle);
handle = setTimeout(() => doValidate(model.uri), 500);
}),
);
listeners[String(toString)] = model.onDidChangeContent(() => {
clearTimeout(handle);
handle = setTimeout(() => doValidate(model.uri, modeId), 500);
});
doValidate(model.uri);
doValidate(model.uri, modeId);
};
const onModelRemoved = (model: editor.IModel): void => {
editor.setModelMarkers(model, languageId, []);
const uriStr = String(model.uri);
const listener = listeners.get(uriStr);
const listener = listeners[uriStr];
if (listener) {
listener.dispose();
listeners.delete(uriStr);
delete listeners[uriStr];
}
};
@ -119,7 +106,7 @@ export function createDiagnosticsAdapter(
});
defaults.onDidChange(() => {
for (const model of editor.getModels()) {
if (model.getLanguageId() === languageId) {
if (model.getModeId() === languageId) {
onModelRemoved(model);
onModelAdd(model);
}
@ -152,7 +139,7 @@ function toRange(range: ls.Range): Range {
);
}
function toCompletionItemKind(kind: ls.CompletionItemKind): languages.CompletionItemKind {
function toCompletionItemKind(kind: languages.CompletionItemKind): languages.CompletionItemKind {
const mItemKind = languages.CompletionItemKind;
switch (kind) {
@ -264,24 +251,40 @@ export function createCompletionItemProvider(
};
}
// --- definition ------
function isMarkupContent(thing: unknown): thing is ls.MarkupContent {
return thing && typeof thing === 'object' && typeof (thing as ls.MarkupContent).kind === 'string';
}
export function createDefinitionProvider(getWorker: WorkerAccessor): languages.DefinitionProvider {
return {
async provideDefinition(model, position) {
const resource = model.uri;
function toMarkdownString(entry: ls.MarkedString | ls.MarkupContent): IMarkdownString {
if (typeof entry === 'string') {
return {
value: entry,
};
}
if (isMarkupContent(entry)) {
if (entry.kind === 'plaintext') {
return {
value: entry.value.replace(/[!#()*+.[\\\]_`{}-]/g, '\\$&'),
};
}
return {
value: entry.value,
};
}
const worker = await getWorker(resource);
const definitions = await worker.doDefinition(String(resource), fromPosition(position));
return { value: `\`\`\`${entry.language}\n${entry.value}\n\`\`\`\n` };
}
return definitions?.map((definition) => ({
originSelectionRange: definition.originSelectionRange,
range: toRange(definition.targetRange),
targetSelectionRange: definition.targetSelectionRange,
uri: Uri.parse(definition.targetUri),
}));
},
};
function toMarkedStringArray(
contents: ls.MarkedString | ls.MarkedString[] | ls.MarkupContent,
): IMarkdownString[] {
if (!contents) {
return;
}
if (Array.isArray(contents)) {
return contents.map(toMarkdownString);
}
return [toMarkdownString(contents)];
}
// --- hover ------
@ -298,7 +301,7 @@ export function createHoverProvider(getWorker: WorkerAccessor): languages.HoverP
}
return {
range: toRange(info.range),
contents: [{ value: (info.contents as ls.MarkupContent).value }],
contents: toMarkedStringArray(info.contents),
};
},
};
@ -353,12 +356,12 @@ function toSymbolKind(kind: ls.SymbolKind): languages.SymbolKind {
function toDocumentSymbol(item: ls.DocumentSymbol): languages.DocumentSymbol {
return {
detail: item.detail || '',
detail: '',
range: toRange(item.range),
name: item.name,
kind: toSymbolKind(item.kind),
selectionRange: toRange(item.selectionRange),
children: item.children.map(toDocumentSymbol),
children: item.children.map((child) => toDocumentSymbol(child)),
tags: [],
};
}
@ -375,7 +378,7 @@ export function createDocumentSymbolProvider(
if (!items) {
return;
}
return items.map(toDocumentSymbol);
return items.map((item) => toDocumentSymbol(item));
},
};
}

View file

@ -1,23 +1,11 @@
import { Emitter, languages } from 'monaco-editor/esm/vs/editor/editor.api.js';
import { Emitter, languages } from 'monaco-editor/esm/vs/editor/editor.api';
import { languageId } from './constants';
import { setupMode } from './yamlMode';
// --- YAML configuration and defaults ---------
const diagnosticDefault: languages.yaml.DiagnosticsOptions = {
completion: true,
customTags: [],
enableSchemaRequest: false,
format: true,
isKubernetes: false,
hover: true,
schemas: [],
validate: true,
yamlVersion: '1.2',
};
export function createLanguageServiceDefaults(
languageId: string,
initialDiagnosticsOptions: languages.yaml.DiagnosticsOptions,
): languages.yaml.LanguageServiceDefaults {
const onDidChange = new Emitter<languages.yaml.LanguageServiceDefaults>();
@ -37,7 +25,7 @@ export function createLanguageServiceDefaults(
},
setDiagnosticsOptions(options) {
diagnosticsOptions = { ...diagnosticDefault, ...options };
diagnosticsOptions = options || {};
onDidChange.fire(languageServiceDefaults);
},
};
@ -45,7 +33,13 @@ export function createLanguageServiceDefaults(
return languageServiceDefaults;
}
const yamlDefaults = createLanguageServiceDefaults(diagnosticDefault);
const diagnosticDefault: languages.yaml.DiagnosticsOptions = {
validate: true,
schemas: [],
enableSchemaRequest: false,
};
const yamlDefaults = createLanguageServiceDefaults('yaml', diagnosticDefault);
// Export API
function createAPI(): typeof languages.yaml {
@ -58,7 +52,7 @@ languages.yaml = createAPI();
// --- Registration to monaco editor ---
languages.register({
id: languageId,
id: 'yaml',
extensions: ['.yaml', '.yml'],
aliases: ['YAML', 'yaml', 'YML', 'yml'],
mimetypes: ['application/x-yaml'],

View file

@ -1,4 +1,4 @@
import { editor, languages } from 'monaco-editor/esm/vs/editor/editor.api.js';
import { editor, languages } from 'monaco-editor/esm/vs/editor/editor.api';
import { WorkerAccessor } from './languageFeatures';
import { YAMLWorker } from './yamlWorker';
@ -13,27 +13,18 @@ export function createWorkerManager(
let client: Promise<YAMLWorker>;
let lastUsedTime = 0;
const stopWorker = (): void => {
if (worker) {
worker.dispose();
worker = undefined;
}
client = undefined;
};
setInterval(() => {
if (!worker) {
return;
}
const timePassedSinceLastUsed = Date.now() - lastUsedTime;
if (timePassedSinceLastUsed > STOP_WHEN_IDLE_FOR) {
stopWorker();
worker.dispose();
worker = undefined;
client = undefined;
}
}, 30 * 1000);
// This is necessary to have updated language options take effect (e.g. schema changes)
defaults.onDidChange(() => stopWorker());
const getClient = (): Promise<YAMLWorker> => {
lastUsedTime = Date.now();
@ -47,7 +38,9 @@ export function createWorkerManager(
// Passed in to the create() method
createData: {
languageSettings: defaults.diagnosticsOptions,
languageId: defaults.languageId,
enableSchemaRequest: defaults.diagnosticsOptions.enableSchemaRequest,
prefix: defaults.diagnosticsOptions.prefix,
isKubernetes: defaults.diagnosticsOptions.isKubernetes,
customTags: defaults.diagnosticsOptions.customTags,
},

View file

@ -1,7 +1,7 @@
import { initialize } from 'monaco-editor/esm/vs/editor/editor.worker.js';
import { initialize } from 'monaco-editor/esm/vs/editor/editor.worker';
import { createYAMLWorker, ICreateData } from './yamlWorker';
import { createYAMLWorker } from './yamlWorker';
self.onmessage = () => {
initialize((ctx, createData: ICreateData) => Object.create(createYAMLWorker(ctx, createData)));
initialize((ctx, createData) => Object.create(createYAMLWorker(ctx, createData)));
};

View file

@ -1,9 +1,7 @@
import { languages } from 'monaco-editor/esm/vs/editor/editor.api.js';
import { languages } from 'monaco-editor/esm/vs/editor/editor.api';
import { languageId } from './constants';
import {
createCompletionItemProvider,
createDefinitionProvider,
createDiagnosticsAdapter,
createDocumentFormattingEditProvider,
createDocumentSymbolProvider,
@ -47,15 +45,16 @@ const richEditConfiguration: languages.LanguageConfiguration = {
export function setupMode(defaults: languages.yaml.LanguageServiceDefaults): void {
const worker = createWorkerManager(defaults);
const { languageId } = defaults;
languages.registerCompletionItemProvider(languageId, createCompletionItemProvider(worker));
languages.registerHoverProvider(languageId, createHoverProvider(worker));
languages.registerDefinitionProvider(languageId, createDefinitionProvider(worker));
languages.registerDocumentSymbolProvider(languageId, createDocumentSymbolProvider(worker));
languages.registerDocumentFormattingEditProvider(
languageId,
createDocumentFormattingEditProvider(worker),
);
languages.registerLinkProvider(languageId, createLinkProvider(worker));
createDiagnosticsAdapter(worker, defaults);
createDiagnosticsAdapter(languageId, worker, defaults);
languages.setLanguageConfiguration(languageId, richEditConfiguration);
}

View file

@ -1,4 +1,4 @@
import { worker } from 'monaco-editor/esm/vs/editor/editor.api.js';
import { worker } from 'monaco-editor/esm/vs/editor/editor.api';
import { Promisable } from 'type-fest';
import { TextDocument } from 'vscode-languageserver-textdocument';
import * as ls from 'vscode-languageserver-types';
@ -6,16 +6,12 @@ import {
CustomFormatterOptions,
getLanguageService,
LanguageSettings,
} from 'yaml-language-server/lib/esm/languageservice/yamlLanguageService.js';
} from 'yaml-language-server/lib/esm/languageservice/yamlLanguageService';
import { languageId } from './constants';
let defaultSchemaRequestService: (url: string) => Promise<string>;
async function schemaRequestService(uri: string): Promise<string> {
const response = await fetch(uri);
if (response.ok) {
return response.text();
}
throw new Error(`Schema request failed for ${uri}`);
if (typeof fetch !== 'undefined') {
defaultSchemaRequestService = (url) => fetch(url).then((response) => response.text());
}
export interface YAMLWorker {
@ -23,8 +19,6 @@ export interface YAMLWorker {
doComplete: (uri: string, position: ls.Position) => Promisable<ls.CompletionList>;
doDefinition: (uri: string, position: ls.Position) => Promisable<ls.LocationLink[]>;
doHover: (uri: string, position: ls.Position) => Promisable<ls.Hover>;
format: (uri: string, options: CustomFormatterOptions) => Promisable<ls.TextEdit[]>;
@ -38,16 +32,21 @@ export interface YAMLWorker {
export function createYAMLWorker(
ctx: worker.IWorkerContext,
{ enableSchemaRequest, languageSettings }: ICreateData,
{
enableSchemaRequest,
isKubernetes = false,
languageId,
languageSettings,
prefix = '',
}: ICreateData,
): YAMLWorker {
const languageService = getLanguageService(
enableSchemaRequest ? schemaRequestService : null,
null,
null,
null,
null,
);
languageService.configure(languageSettings);
const service = (url: string): Promise<string> => defaultSchemaRequestService(`${prefix}${url}`);
const languageService = getLanguageService(enableSchemaRequest && service, null, null, null);
languageService.configure({
...languageSettings,
hover: true,
isKubernetes,
});
const getTextDocument = (uri: string): TextDocument => {
const models = ctx.getMirrorModels();
@ -63,19 +62,14 @@ export function createYAMLWorker(
doValidation(uri) {
const document = getTextDocument(uri);
if (document) {
return languageService.doValidation(document, languageSettings.isKubernetes);
return languageService.doValidation(document, isKubernetes);
}
return [];
},
doComplete(uri, position) {
const document = getTextDocument(uri);
return languageService.doComplete(document, position, languageSettings.isKubernetes);
},
doDefinition(uri, position) {
const document = getTextDocument(uri);
return languageService.doDefinition(document, { position, textDocument: { uri } });
return languageService.doComplete(document, position, isKubernetes);
},
doHover(uri, position) {
@ -99,13 +93,15 @@ export function createYAMLWorker(
findLinks(uri) {
const document = getTextDocument(uri);
return languageService.findLinks(document);
return Promise.resolve(languageService.findLinks(document));
},
};
}
export interface ICreateData {
languageId: string;
languageSettings: LanguageSettings;
enableSchemaRequest: boolean;
prefix?: string;
isKubernetes?: boolean;
}