Skip to content

Commit

Permalink
[forgive] Init
Browse files Browse the repository at this point in the history
Init basic LSP. At the moment the extension doesn't do anything interesting, but it does compile successfully.
  • Loading branch information
poteto committed Dec 26, 2024
1 parent e21110e commit 36eefcc
Show file tree
Hide file tree
Showing 15 changed files with 664 additions and 23 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ chrome-user-data
.vscode
*.swp
*.swo
*.vsix

packages/react-devtools-core/dist
packages/react-devtools-extensions/chrome/build
Expand All @@ -37,3 +38,4 @@ packages/react-devtools-fusebox/dist
packages/react-devtools-inline/dist
packages/react-devtools-shell/dist
packages/react-devtools-timeline/dist

Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import terser from '@rollup/plugin-terser';
import prettier from 'rollup-plugin-prettier';
import banner2 from 'rollup-plugin-banner2';

const NO_INLINE = new Set(['@babel/types']);
const NO_INLINE = new Set([]);

const DEV_ROLLUP_CONFIG = {
input: 'src/index.ts',
Expand Down
3 changes: 3 additions & 0 deletions compiler/packages/react-forgive/.vscodeignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
**/node_modules
client
server
1 change: 1 addition & 0 deletions compiler/packages/react-forgive/.yarnrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
ignore-engines true
21 changes: 21 additions & 0 deletions compiler/packages/react-forgive/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) Meta Platforms, Inc. and affiliates.

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.
2 changes: 1 addition & 1 deletion compiler/packages/react-forgive/client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"repository": {
"type": "git",
"url": "git+https://github.com/facebook/react.git",
"directory": "compiler/packages/react-forgive-client"
"directory": "compiler/packages/react-forgive"
},
"dependencies": {
"vscode-languageclient": "^9.0.1"
Expand Down
62 changes: 62 additions & 0 deletions compiler/packages/react-forgive/client/src/extension.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import * as path from 'path';
import {ExtensionContext, window as Window} from 'vscode';

import {
LanguageClient,
LanguageClientOptions,
ServerOptions,
TransportKind,
} from 'vscode-languageclient/node';

let client: LanguageClient;

export function activate(context: ExtensionContext) {
const serverModule = context.asAbsolutePath(path.join('dist', 'server.js'));

// If the extension is launched in debug mode then the debug server options are used
// Otherwise the run options are used
const serverOptions: ServerOptions = {
run: {
module: serverModule,
transport: TransportKind.ipc,
options: {cwd: process.cwd()},
},
debug: {
module: serverModule,
transport: TransportKind.ipc,
options: {cwd: process.cwd()},
},
};

const clientOptions: LanguageClientOptions = {
documentSelector: [
{scheme: 'file', language: 'javascriptreact'},
{scheme: 'file', language: 'typescriptreact'},
],
progressOnInitialization: true,
};

// Create the language client and start the client.
try {
client = new LanguageClient(
'react-forgive',
'React Analyzer',
serverOptions,
clientOptions,
);
} catch {
Window.showErrorMessage(
`React Analyzer couldn't be started. See the output channel for details.`,
);
return;
}

client.registerProposedFeatures();
client.start();
}

export function deactivate(): Thenable<void> | undefined {
if (client !== undefined) {
return client.stop();
}
}
15 changes: 7 additions & 8 deletions compiler/packages/react-forgive/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,25 +35,24 @@
]
},
"scripts": {
"compile": "yarn run esbuild-base -- --sourcemap",
"compile": "rimraf dist && concurrently -n server,client \"yarn run esbuild:server --sourcemap\" \"yarn run esbuild:client --sourcemap\"",
"dev": "yarn run package && yarn run install-ext",
"esbuild-base": "esbuild ./src/extension.ts --bundle --outfile=dist/extension.js --external:vscode --format=cjs --platform=node",
"install-ext": "code --install-extension vscode-react-compiler-0.0.1.vsix",
"esbuild:client": "esbuild ./client/src/extension.ts --bundle --outfile=dist/extension.js --external:vscode --format=cjs --platform=node",
"esbuild:server": "esbuild ./server/src/index.ts --bundle --outfile=dist/server.js --external:vscode --format=cjs --platform=node",
"install-ext": "code --install-extension react-forgive-0.0.0.vsix",
"lint": "eslint src --ext ts",
"package": "vsce package",
"package": "rm -f react-forgive-0.0.0.vsix && vsce package --yarn",
"postinstall": "cd client && yarn install && cd ../server && yarn install && cd ..",
"pretest": "yarn run compile && yarn run lint",
"test": "vscode-test",
"test-compile": "tsc -p ./",
"vscode:prepublish": "yarn run esbuild-base -- --minify",
"watch": "yarn run esbuild-base -- --sourcemap --watch"
"vscode:prepublish": "yarn run compile",
"watch": "concurrently --kill-others -n server,client \"run esbuild:server --sourcemap --watch\" \"run esbuild:client --sourcemap --watch\""
},
"devDependencies": {
"@eslint/js": "^9.13.0",
"@types/node": "^20",
"esbuild": "^0.24.0",
"eslint": "^9.13.0",
"typescript": "^5.7.2",
"typescript-eslint": "^8.16.0"
}
}
11 changes: 9 additions & 2 deletions compiler/packages/react-forgive/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,23 @@
"version": "0.0.0",
"description": "Experimental LSP server",
"license": "MIT",
"main": "dist/index.js",
"scripts": {
"build": "echo 'no build'",
"build": "rimraf dist && rollup --config --bundleConfigAsCjs",
"test": "echo 'no tests'"
},
"repository": {
"type": "git",
"url": "git+https://github.com/facebook/react.git",
"directory": "compiler/packages/react-forgive-server"
"directory": "compiler/packages/react-forgive"
},
"dependencies": {
"@babel/core": "^7.26.0",
"@babel/parser": "^7.26.0",
"@babel/plugin-syntax-typescript": "^7.25.9",
"@babel/types": "^7.26.0",
"cosmiconfig": "^9.0.0",
"prettier": "^3.3.3",
"vscode-languageserver": "^9.0.1",
"vscode-languageserver-textdocument": "^1.0.12"
}
Expand Down
58 changes: 58 additions & 0 deletions compiler/packages/react-forgive/server/src/compiler/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import type * as BabelCore from '@babel/core';
import {parseAsync, transformFromAstAsync} from '@babel/core';
import BabelPluginReactCompiler, {
type PluginOptions,
} from 'babel-plugin-react-compiler/src';
import * as babelParser from 'prettier/plugins/babel.js';
import estreeParser from 'prettier/plugins/estree';
import * as typescriptParser from 'prettier/plugins/typescript';
import * as prettier from 'prettier/standalone';

type CompileOptions = {
text: string;
file: string;
options: PluginOptions | null;
};
export async function compile({
text,
file,
options,
}: CompileOptions): Promise<BabelCore.BabelFileResult> {
const ast = await parseAsync(text, {
sourceFileName: file,
parserOpts: {
plugins: ['typescript', 'jsx'],
},
sourceType: 'module',
});
const plugins =
options != null
? [[BabelPluginReactCompiler, options]]
: [[BabelPluginReactCompiler]];
const result = await transformFromAstAsync(ast, text, {
filename: file,
highlightCode: false,
retainLines: true,
plugins,
sourceType: 'module',
sourceFileName: file,
});
if (result?.code == null) {
throw new Error(
`Expected BabelPluginReactCompiler to compile successfully, got ${result}`,
);
}
result.code = await prettier.format(result.code, {
semi: false,
parser: 'babel-ts',
plugins: [babelParser, estreeParser, typescriptParser],
});
return result;
}
25 changes: 25 additions & 0 deletions compiler/packages/react-forgive/server/src/compiler/options.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import {
parsePluginOptions,
type PluginOptions,
} from 'babel-plugin-react-compiler/src';
import {cosmiconfigSync} from 'cosmiconfig';

export function resolveReactConfig(projectPath: string): PluginOptions | null {
const explorerSync = cosmiconfigSync('react', {
searchStrategy: 'project',
cache: true,
});
const result = explorerSync.search(projectPath);
if (result != null) {
return parsePluginOptions(result.config);
} else {
return null;
}
}
87 changes: 87 additions & 0 deletions compiler/packages/react-forgive/server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,90 @@
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import {TextDocument} from 'vscode-languageserver-textdocument';
import {
createConnection,
type InitializeParams,
type InitializeResult,
ProposedFeatures,
TextDocuments,
TextDocumentSyncKind,
} from 'vscode-languageserver/node';
import {compile} from './compiler';
import {type PluginOptions} from 'babel-plugin-react-compiler/src';
import {resolveReactConfig} from './compiler/options';

const SUPPORTED_LANGUAGE_IDS = new Set([
'javascript',
'javascriptreact',
'typescript',
'typescriptreact',
]);

const connection = createConnection(ProposedFeatures.all);
connection.console.info(`React Analyzer running in node ${process.version}`);

const compiledCache = new WeakMap<TextDocument, string>();

const documents = new TextDocuments(TextDocument);
documents.listen(connection);

let compilerOptions: PluginOptions | null = null;

connection.onInitialize((_params: InitializeParams) => {
// TODO(@poteto) get config fr
compilerOptions = resolveReactConfig('.');
const result: InitializeResult = {
capabilities: {
textDocumentSync: TextDocumentSyncKind.Full,
codeLensProvider: {resolveProvider: true},
},
};
return result;
});

connection.onInitialized(() => {
connection.console.log('initialized');
});

documents.onDidOpen(async event => {
if (SUPPORTED_LANGUAGE_IDS.has(event.document.languageId)) {
const result = await compile({
text: event.document.getText(),
file: event.document.uri,
options: compilerOptions,
});
if (result.code != null) {
compiledCache.set(event.document, result.code);
connection.console.log(result.code);
}
}
});

documents.onDidChangeContent(async event => {
if (SUPPORTED_LANGUAGE_IDS.has(event.document.languageId)) {
const result = await compile({
text: event.document.getText(),
file: event.document.uri,
options: compilerOptions,
});
if (result.code != null) {
compiledCache.set(event.document, result.code);
connection.console.log(result.code);
}
}
});

connection.onDidChangeWatchedFiles(change => {
connection.console.log(
change.changes.map(c => `File changed: ${c.uri}`).join('\n'),
);
});

connection.onCodeLens(params => {
connection.console.log(JSON.stringify(params, null, 2));
return [];
});

connection.listen();
16 changes: 10 additions & 6 deletions compiler/packages/react-forgive/server/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
{
"extends": "@tsconfig/strictest/tsconfig.json",
"compilerOptions": {
"module": "CommonJS",
"moduleResolution": "node",
"outDir": "dist",
"module": "ES2015",
"moduleResolution": "Bundler",
"rootDir": "../../..",
"noEmit": true,
"jsx": "react-jsxdev",
"lib": ["ES2020"],
"target": "ES2020",
"target": "ES2015",
"sourceMap": false,
"removeComments": true,

"strictNullChecks": false
},
"exclude": ["node_modules", ".vscode-test"],
"include": ["src/**/*.ts"],
"include": ["src/**/*.ts"]
}
Loading

0 comments on commit 36eefcc

Please sign in to comment.