├── .gitignore
├── .npmignore
├── CONTRIBUTING.md
├── README.md
├── package.json
├── rollup.config.js
├── scripts
└── getDTS.js
├── src
├── index.ts
├── vendor
│ ├── playground.d.ts
│ ├── pluginUtils.d.ts
│ ├── sandbox.d.ts
│ ├── tsWorker.d.ts
│ ├── typescript-vfs.d.ts
│ └── utils.ts
└── vim-monaco
│ ├── cm
│ └── keymap_vim.ts
│ ├── cm_adapter.ts
│ ├── demo.ts
│ ├── index.ts
│ └── statusbar.ts
├── tsconfig.json
└── yarn.lock
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 |
8 | # Runtime data
9 | pids
10 | *.pid
11 | *.seed
12 | *.pid.lock
13 |
14 | # Directory for instrumented libs generated by jscoverage/JSCover
15 | lib-cov
16 |
17 | # Coverage directory used by tools like istanbul
18 | coverage
19 |
20 | # nyc test coverage
21 | .nyc_output
22 |
23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
24 | .grunt
25 |
26 | # Bower dependency directory (https://bower.io/)
27 | bower_components
28 |
29 | # node-waf configuration
30 | .lock-wscript
31 |
32 | # Compiled binary addons (http://nodejs.org/api/addons.html)
33 | build/Release
34 |
35 | # Dependency directories
36 | node_modules/
37 | jspm_packages/
38 |
39 | # Typescript v1 declaration files
40 | typings/
41 |
42 | # Optional npm cache directory
43 | .npm
44 |
45 | # Optional eslint cache
46 | .eslintcache
47 |
48 | # Optional REPL history
49 | .node_repl_history
50 |
51 | # Output of 'npm pack'
52 | *.tgz
53 |
54 | # dotenv environment variables file
55 | .env
56 |
57 | # gatsby files
58 | .cache/
59 | public
60 |
61 | # Mac files
62 | .DS_Store
63 |
64 | # Yarn
65 | yarn-error.log
66 | .pnp/
67 | .pnp.js
68 | # Yarn Integrity file
69 | .yarn-integrity
70 | dist
71 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | src
2 | .gitignore
3 | rollup.config.jss
4 | !dist
5 | scripts
6 | .vscode
7 | yarn*
8 | tsconfig.json
9 | rollup*
10 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | ## Contributing to a TypeScript Playground Plugin
2 |
3 | ## Contributing
4 |
5 | You can use `yarn start` to set up both a copy of Rollup to generate the JS, and Serve to host it.
6 |
7 | ```sh
8 | yarn start
9 | ```
10 |
11 | Then set up the TypeScript playground to connect to a dev plugin at `http://localhost:5000/`.
12 |
13 | #### Plugin API
14 |
15 | The plugin API is documented in the [interface PlaygroundPlugin in `./src/vendor/playground.d.ts`](src/vendor/playground.d.ts)
16 |
17 | Roughly:
18 |
19 | - There are a set of mounting and un-mounting functions which you can use to handle your UI in the sidebar
20 | - There are `modelChanged` methods, which are shortcuts to knowing when the code in monaco editor has changed
21 |
22 | ### Sandbox
23 |
24 | The plugins are passed copies of the TypeScript sandbox, which is a high level API wrapper to the [`monaco-editor`](https://microsoft.github.io/monaco-editor/). You can learn more about the sandbox on [the TypeScript website](http://www.typescriptlang.org/v2/dev/sandbox/
25 |
26 | #### Rollup
27 |
28 | [Rollup](https://rollupjs.org) is a JavaScript bundler, that will take all of the TypeScript + JavaScript code you reference and then create an AMD bundle for it all. AMD bundles are used in Monaco, TypeScript Sandbox and the Playground - so, this is used for consistency with the rest of the ecosystem.
29 |
30 | ## Adding a dependency
31 |
32 | Because most node_modules expect to be running in node, you might have to do some work to get the dependency working on the web.
33 |
34 | The route to handle this is via rollup:
35 |
36 | - add a new dependency via `yarn add xyz`
37 | - import it into your `index.ts`
38 | - run `yarn build` - did it provide some error messages?
39 | - If it did, you may need to edit your `rollup.config.js`.
40 | - You could probably start by taking the [rollup config from `playground-plugin-tsquery`](https://github.com/orta/playground-plugin-tsquery/blob/master/rollup.config.js) and by adding any extra externals and globals.
41 |
42 | #### Serve
43 |
44 | [Serve](https://github.com/zeit/serve) is used to make a web-server for the dist folder.
45 |
46 | ## Deployment
47 |
48 | This module should be deployed to npm when you would like the world to see it, this may mean making your code handle a staging vs production environment (because the URLs will be different.)
49 |
50 | For example, this is how you can handle getting the URL for a CSS file which is included in your `dist` folder:
51 |
52 | ```ts
53 | const isDev = document.location.host.includes('localhost')
54 | const unpkgURL = 'https://unpkg.com/typescript-playground-presentation-mode@latest/dist/slideshow.css'
55 | const cssHref = isDev ? 'http://localhost:5000/slideshow.css' : unpkgURL
56 | ```
57 |
58 | ### Post-Deploy
59 |
60 | Once this is deployed, you can test it on the TypeScript playground by passing in the name of your plugin on npm to the custom plugin box. This is effectively your staging environment.
61 |
62 | Once you're happy and it's polished, you can apply to have it in the default plugin list.
63 |
64 | ## Support
65 |
66 | Ask questions either on the TypeScript Website issues](https://github.com/microsoft/TypeScript-Website/issues), or in the [TypeScript Community Discord](https://discord.gg/typescript) - in the TypeScript Website channel.
67 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## TypeScript Playground Vim Plugin
2 |
3 | Provides Vim keybindings for TypeScript Playground editor.
4 |
5 | ## Running this plugin
6 |
7 | - [Click this link](https://www.typescriptlang.org/play?install-plugin=ts-playground-plugin-vim) to install
8 |
9 | or
10 |
11 | - Open up the TypeScript Playground
12 | - Go the "Options" in the sidebar
13 | - Look for "Plugins from npm"
14 | - Add "ts-playground-plugin-vim"
15 | - Reload the browser
16 |
17 | Then it will show up as a tab in the sidebar.
18 |
19 | ## Contributing
20 |
21 | See [CONTRIBUTING.md](./CONTRIBUTING.md) for the full details, however, TLDR:
22 |
23 | ```sh
24 | git clone ...
25 | yarn install
26 | yarn start
27 | ```
28 |
29 | Then tick the box for starting plugin development inside the TypeScript Playground.
30 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "ts-playground-plugin-vim",
3 | "version": "0.1.4",
4 | "main": "dist/index.js",
5 | "license": "MIT",
6 | "keywords": [
7 | "playground-plugin"
8 | ],
9 | "scripts": {
10 | "build": "rollup -c rollup.config.js;",
11 | "compile": "tsc",
12 | "start": "concurrently -p \"[{name}]\" -n \"ROLLUP,SITE\" -c \"bgBlue.bold,bgMagenta.bold\" \"yarn rollup -c rollup.config.js --watch\" \"yarn serve dist\""
13 | },
14 | "devDependencies": {
15 | "@rollup/plugin-commonjs": "^11.0.2",
16 | "@rollup/plugin-json": "^4.0.2",
17 | "@rollup/plugin-node-resolve": "^7.1.0",
18 | "@rollup/plugin-typescript": "^3.0.0",
19 | "@types/react": "^16.9.23",
20 | "concurrently": "^5.1.0",
21 | "monaco-editor": "^0.19.3",
22 | "node-fetch": "^2.6.1",
23 | "rollup": "^1.31.0",
24 | "serve": "^11.3.0",
25 | "typescript": "latest"
26 | },
27 | "dependencies": {
28 | "monaco-vim": "^0.1.7",
29 | "tslib": "^1.10.0"
30 | }
31 | }
32 |
--------------------------------------------------------------------------------
/rollup.config.js:
--------------------------------------------------------------------------------
1 | import typescript from '@rollup/plugin-typescript'
2 | import node from '@rollup/plugin-node-resolve'
3 | import commonjs from '@rollup/plugin-commonjs'
4 | import json from '@rollup/plugin-json'
5 |
6 | // You can have more root bundles by extending this array
7 | const rootFiles = ['index.ts']
8 |
9 | export default rootFiles.map(name => {
10 | /** @type { import("rollup").RollupOptions } */
11 | const options = {
12 | input: `src/${name}`,
13 | external: ['typescript', 'monaco-editor'],
14 | output: {
15 | name,
16 | dir: 'dist',
17 | format: 'amd',
18 | },
19 | plugins: [typescript({ tsconfig: 'tsconfig.json', noEmitOnError: false }), commonjs(), node(), json()],
20 | }
21 |
22 | return options
23 | })
24 |
25 | /** Note:
26 | * if you end up wanting to import a dependency which relies on typescript, you will need
27 | * settings which adds these extra options. It will re-use the window.ts for the typescript
28 | * dependency, and I've not figured a way to remove fs and path.
29 | *
30 | const options = {
31 | external: ['typescript', 'fs', 'path'],
32 | output: {
33 | paths: {
34 | "typescript":"typescript-sandbox/index",
35 | "fs":"typescript-sandbox/index",
36 | "path":"typescript-sandbox/index",
37 | },
38 | },
39 | plugins: [typescript({ tsconfig: "tsconfig.json" }), externalGlobals({ typescript: "window.ts" }), commonjs(), node(), json()]
40 | };
41 | *
42 | */
43 |
--------------------------------------------------------------------------------
/scripts/getDTS.js:
--------------------------------------------------------------------------------
1 | // @ts-check
2 |
3 | // Grab the DTS files from the TypeScript website
4 | // then do a bit of string manipulation in order to make it
5 | // compile without _all_ of the dependencies
6 |
7 | const nodeFetch = require('node-fetch').default
8 | const { writeFileSync, existsSync, mkdirSync } = require('fs')
9 | const { join } = require('path')
10 |
11 | const getFileAndStoreLocally = async (url, path, editFunc) => {
12 | const editingFunc = editFunc ? editFunc : text => text
13 | const packageJSON = await nodeFetch(url)
14 | const contents = await packageJSON.text()
15 | writeFileSync(join(__dirname, '..', path), editingFunc(contents), 'utf8')
16 | }
17 |
18 | const go = async () => {
19 | const vendor = join('src', 'vendor')
20 | if (!existsSync(vendor)) {
21 | mkdirSync(vendor)
22 | }
23 |
24 | const host = 'https://www.typescriptlang.org/v2'
25 | // const host = "http://localhost:8000";
26 |
27 | await getFileAndStoreLocally(host + '/js/sandbox/tsWorker.d.ts', join(vendor, 'tsWorker.d.ts'))
28 |
29 | await getFileAndStoreLocally(host + '/js/playground/pluginUtils.d.ts', join(vendor, 'pluginUtils.d.ts'))
30 |
31 | await getFileAndStoreLocally(
32 | host + '/js/sandbox/vendor/typescript-vfs.d.ts',
33 | join(vendor, 'typescript-vfs.d.ts'),
34 | text => {
35 | const removeImports = text.replace('/// ', '')
36 | const removedLZ = removeImports.replace('import("lz-string").LZStringStatic', 'any')
37 | return removedLZ
38 | }
39 | )
40 |
41 | await getFileAndStoreLocally(host + '/js/sandbox/index.d.ts', join(vendor, 'sandbox.d.ts'), text => {
42 | const removeImports = text.replace(/^import/g, '// import').replace(/\nimport/g, '\n// import')
43 | const replaceTSVFS = removeImports.replace(
44 | "// import * as tsvfs from './vendor/typescript-vfs'",
45 | "\nimport * as tsvfs from './typescript-vfs'"
46 | )
47 | const removedLZ = replaceTSVFS.replace('lzstring: typeof lzstring', '// lzstring: typeof lzstring')
48 | const addedTsWorkerImport = 'import { TypeScriptWorker } from "./tsWorker";' + removedLZ
49 | return addedTsWorkerImport
50 | })
51 |
52 | await getFileAndStoreLocally(host + '/js/playground/index.d.ts', join(vendor, '/playground.d.ts'), text => {
53 | const replaceSandbox = text.replace(/typescript-sandbox/g, './sandbox')
54 | const replaceTSVFS = replaceSandbox.replace(
55 | /typescriptlang-org\/static\/js\/sandbox\/vendor\/typescript-vfs/g,
56 | './typescript-vfs'
57 | )
58 | const removedLZ = replaceTSVFS.replace('lzstring: typeof', '// lzstring: typeof')
59 | const removedWorker = removedLZ.replace('getWorkerProcess', '// getWorkerProcess')
60 | const removedUI = removedWorker.replace('ui:', '// ui:')
61 | return removedUI
62 | })
63 | }
64 |
65 | go()
66 |
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | import type { PlaygroundPlugin, PluginUtils } from "./vendor/playground"
2 | import type { Sandbox } from "./vendor/sandbox";
3 | import { initVimMode } from "./vim-monaco";
4 |
5 | let vimMode;
6 | let vimStatus: HTMLDivElement;
7 |
8 | function startVimMode(sandbox: Sandbox) {
9 | const mainNode = document.querySelector('main');
10 | if (!vimStatus) {
11 | vimStatus = document.createElement("div");
12 | vimStatus.style.position = "absolute";
13 | vimStatus.style.bottom = ".4rem";
14 | vimStatus.style.left = "1rem";
15 | vimStatus.style.fontSize = "small";
16 | if (mainNode) {
17 | mainNode.appendChild(vimStatus);
18 | mainNode.style.position = "relative";
19 | }
20 | } else {
21 | vimStatus.style.display = "block";
22 | }
23 | if (!vimMode) {
24 | vimMode = initVimMode(sandbox.editor, vimStatus);
25 | }
26 | localStorage.setItem("tsplayvim", "activated");
27 | }
28 |
29 | function stopVimMode() {
30 | if (vimStatus) {
31 | vimStatus.style.display = "none";
32 | }
33 | if (vimMode) {
34 | vimMode.dispose();
35 | }
36 | vimMode = null;
37 | localStorage.removeItem("tsplayvim");
38 | }
39 |
40 | if ("sandbox" in globalThis && !!localStorage.getItem("tsplayvim")) {
41 | const sandbox = (globalThis as unknown as { sandbox: Sandbox }).sandbox;
42 | startVimMode(sandbox);
43 | }
44 |
45 | const makePlugin = (utils: PluginUtils) => {
46 | const customPlugin: PlaygroundPlugin = {
47 | id: 'ts-playground-vim',
48 | displayName: 'Vim',
49 | didMount: (sandbox, container) => {
50 |
51 | const p = (str: string) => utils.el(str, "p", container);
52 | p("This plugin provides Vim keybindings to the editor.")
53 |
54 | const startButton = document.createElement('button')
55 | startButton.style.fontSize = "16px";
56 | startButton.style.cursor = "pointer";
57 | startButton.style.padding = "4px 8px";
58 | startButton.innerText = "Use vim mode";
59 | container.appendChild(startButton)
60 |
61 | if (localStorage.getItem("tsplayvim")) {
62 | startVimMode(sandbox);
63 | startButton.innerText = "Stop Vim mode";
64 | }
65 |
66 | startButton.onclick = () => {
67 | if (!vimMode) {
68 | startVimMode(sandbox);
69 | startButton.innerText = "Stop Vim mode";
70 | } else {
71 | stopVimMode();
72 | startButton.innerText = "Use Vim mode";
73 | }
74 | }
75 | },
76 | }
77 |
78 | return customPlugin
79 | }
80 |
81 | export default makePlugin
82 |
--------------------------------------------------------------------------------
/src/vendor/playground.d.ts:
--------------------------------------------------------------------------------
1 | declare type Sandbox = import('./sandbox').Sandbox;
2 | import type React from 'react';
3 | export { PluginUtils } from './pluginUtils';
4 | export declare type PluginFactory = {
5 | (i: (key: string, components?: any) => string): PlaygroundPlugin;
6 | };
7 | /** The interface of all sidebar plugins */
8 | export interface PlaygroundPlugin {
9 | /** Not public facing, but used by the playground to uniquely identify plugins */
10 | id: string;
11 | /** To show in the tabs */
12 | displayName: string;
13 | /** Should this plugin be selected when the plugin is first loaded? Let's you check for query vars etc to load a particular plugin */
14 | shouldBeSelected?: () => boolean;
15 | /** Before we show the tab, use this to set up your HTML - it will all be removed by the playground when someone navigates off the tab */
16 | willMount?: (sandbox: Sandbox, container: HTMLDivElement) => void;
17 | /** After we show the tab */
18 | didMount?: (sandbox: Sandbox, container: HTMLDivElement) => void;
19 | /** Model changes while this plugin is actively selected */
20 | modelChanged?: (sandbox: Sandbox, model: import('monaco-editor').editor.ITextModel) => void;
21 | /** Delayed model changes while this plugin is actively selected, useful when you are working with the TS API because it won't run on every keypress */
22 | modelChangedDebounce?: (sandbox: Sandbox, model: import('monaco-editor').editor.ITextModel) => void;
23 | /** Before we remove the tab */
24 | willUnmount?: (sandbox: Sandbox, container: HTMLDivElement) => void;
25 | /** After we remove the tab */
26 | didUnmount?: (sandbox: Sandbox, container: HTMLDivElement) => void;
27 | /** An object you can use to keep data around in the scope of your plugin object */
28 | data?: any;
29 | }
30 | interface PlaygroundConfig {
31 | lang: string;
32 | prefix: string;
33 | }
34 | export declare const setupPlayground: (sandbox: {
35 | config: {
36 | text: string;
37 | useJavaScript: boolean;
38 | compilerOptions: import("monaco-editor").languages.typescript.CompilerOptions;
39 | monacoSettings?: import("monaco-editor").editor.IEditorOptions | undefined;
40 | acquireTypes: boolean;
41 | supportTwoslashCompilerOptions: boolean;
42 | suppressAutomaticallyGettingDefaultText?: true | undefined;
43 | suppressAutomaticallyGettingCompilerFlags?: true | undefined;
44 | logger: {
45 | log: (...args: any[]) => void;
46 | error: (...args: any[]) => void;
47 | groupCollapsed: (...args: any[]) => void;
48 | groupEnd: (...args: any[]) => void;
49 | };
50 | domID: string;
51 | };
52 | supportedVersions: readonly ["3.8.3", "3.8.2", "3.7.5", "3.6.3", "3.5.1", "3.3.3", "3.1.6", "3.0.1", "2.8.1", "2.7.2", "2.4.1"];
53 | editor: import("monaco-editor").editor.IStandaloneCodeEditor;
54 | language: string;
55 | monaco: typeof import("monaco-editor");
56 | // getWorkerProcess: () => Promise;
57 | tsvfs: typeof import("./typescript-vfs");
58 | getEmitResult: () => Promise;
59 | getRunnableJS: () => Promise;
60 | getDTSForCode: () => Promise;
61 | getDomNode: () => HTMLElement;
62 | getModel: () => import("monaco-editor").editor.ITextModel;
63 | getText: () => string;
64 | setText: (text: string) => void;
65 | getAST: () => Promise;
66 | ts: typeof import("typescript");
67 | createTSProgram: () => Promise;
68 | compilerDefaults: import("monaco-editor").languages.typescript.CompilerOptions;
69 | getCompilerOptions: () => import("monaco-editor").languages.typescript.CompilerOptions;
70 | setCompilerSettings: (opts: import("monaco-editor").languages.typescript.CompilerOptions) => void;
71 | updateCompilerSetting: (key: string | number, value: any) => void;
72 | updateCompilerSettings: (opts: import("monaco-editor").languages.typescript.CompilerOptions) => void;
73 | setDidUpdateCompilerSettings: (func: (opts: import("monaco-editor").languages.typescript.CompilerOptions) => void) => void;
74 | // lzstring: typeof import("typescriptlang-org/static/js/sandbox/vendor/lzstring.min");
75 | createURLQueryWithCompilerOptions: (sandbox: any, paramOverrides?: any) => string;
76 | getTwoSlashComplierOptions: (code: string) => any;
77 | languageServiceDefaults: import("monaco-editor").languages.typescript.LanguageServiceDefaults;
78 | }, monaco: typeof import("monaco-editor"), config: PlaygroundConfig, i: (key: string) => string, react: typeof React) => {
79 | exporter: {
80 | openProjectInStackBlitz: () => void;
81 | openProjectInCodeSandbox: () => void;
82 | reportIssue: () => Promise;
83 | copyAsMarkdownIssue: () => Promise;
84 | copyForChat: () => void;
85 | copyForChatWithPreview: () => void;
86 | openInTSAST: () => void;
87 | };
88 | // ui: import("./createUI").UI;
89 | registerPlugin: (plugin: PlaygroundPlugin) => void;
90 | };
91 | export declare type Playground = ReturnType;
92 |
--------------------------------------------------------------------------------
/src/vendor/pluginUtils.d.ts:
--------------------------------------------------------------------------------
1 | import type { Node } from "typescript";
2 | import type React from 'react';
3 | /** Creates a set of util functions which is exposed to Plugins to make it easier to build consistent UIs */
4 | export declare const createUtils: (sb: any, react: typeof React) => {
5 | /** Use this to make a few dumb element generation funcs */
6 | el: (str: string, el: string, container: Element) => void;
7 | /** Get a relative URL for something in your dist folder depending on if you're in dev mode or not */
8 | requireURL: (path: string) => string;
9 | /** Returns a div which has an interactive AST a TypeScript AST by passing in the root node */
10 | createASTTree: (node: Node) => HTMLDivElement;
11 | /** The Gatsby copy of React */
12 | react: typeof React;
13 | };
14 | export declare type PluginUtils = ReturnType;
15 |
--------------------------------------------------------------------------------
/src/vendor/sandbox.d.ts:
--------------------------------------------------------------------------------
1 | import { TypeScriptWorker } from "./tsWorker";// import { TypeScriptWorker } from './tsWorker';
2 | // import lzstring from './vendor/lzstring.min';
3 |
4 | import * as tsvfs from './typescript-vfs';
5 | declare type CompilerOptions = import('monaco-editor').languages.typescript.CompilerOptions;
6 | /**
7 | * These are settings for the playground which are the equivalent to props in React
8 | * any changes to it should require a new setup of the playground
9 | */
10 | export declare type PlaygroundConfig = {
11 | /** The default source code for the playground */
12 | text: string;
13 | /** Should it run the ts or js IDE services */
14 | useJavaScript: boolean;
15 | /** Compiler options which are automatically just forwarded on */
16 | compilerOptions: CompilerOptions;
17 | /** Optional monaco settings overrides */
18 | monacoSettings?: import('monaco-editor').editor.IEditorOptions;
19 | /** Acquire types via type acquisition */
20 | acquireTypes: boolean;
21 | /** Support twoslash compiler options */
22 | supportTwoslashCompilerOptions: boolean;
23 | /** Get the text via query params and local storage, useful when the editor is the main experience */
24 | suppressAutomaticallyGettingDefaultText?: true;
25 | /** Suppress setting compiler options from the compiler flags from query params */
26 | suppressAutomaticallyGettingCompilerFlags?: true;
27 | /** Logging system */
28 | logger: {
29 | log: (...args: any[]) => void;
30 | error: (...args: any[]) => void;
31 | groupCollapsed: (...args: any[]) => void;
32 | groupEnd: (...args: any[]) => void;
33 | };
34 | } & ({
35 | domID: string;
36 | } | {
37 | elementToAppend: HTMLElement;
38 | });
39 | /** The default settings which we apply a partial over */
40 | export declare function defaultPlaygroundSettings(): {
41 | /** The default source code for the playground */
42 | text: string;
43 | /** Should it run the ts or js IDE services */
44 | useJavaScript: boolean;
45 | /** Compiler options which are automatically just forwarded on */
46 | compilerOptions: import("monaco-editor").languages.typescript.CompilerOptions;
47 | /** Optional monaco settings overrides */
48 | monacoSettings?: import("monaco-editor").editor.IEditorOptions | undefined;
49 | /** Acquire types via type acquisition */
50 | acquireTypes: boolean;
51 | /** Support twoslash compiler options */
52 | supportTwoslashCompilerOptions: boolean;
53 | /** Get the text via query params and local storage, useful when the editor is the main experience */
54 | suppressAutomaticallyGettingDefaultText?: true | undefined;
55 | /** Suppress setting compiler options from the compiler flags from query params */
56 | suppressAutomaticallyGettingCompilerFlags?: true | undefined;
57 | /** Logging system */
58 | logger: {
59 | log: (...args: any[]) => void;
60 | error: (...args: any[]) => void;
61 | groupCollapsed: (...args: any[]) => void;
62 | groupEnd: (...args: any[]) => void;
63 | };
64 | } & {
65 | domID: string;
66 | };
67 | /** Creates a sandbox editor, and returns a set of useful functions and the editor */
68 | export declare const createTypeScriptSandbox: (partialConfig: Partial<{
69 | /** The default source code for the playground */
70 | text: string;
71 | /** Should it run the ts or js IDE services */
72 | useJavaScript: boolean;
73 | /** Compiler options which are automatically just forwarded on */
74 | compilerOptions: import("monaco-editor").languages.typescript.CompilerOptions;
75 | /** Optional monaco settings overrides */
76 | monacoSettings?: import("monaco-editor").editor.IEditorOptions | undefined;
77 | /** Acquire types via type acquisition */
78 | acquireTypes: boolean;
79 | /** Support twoslash compiler options */
80 | supportTwoslashCompilerOptions: boolean;
81 | /** Get the text via query params and local storage, useful when the editor is the main experience */
82 | suppressAutomaticallyGettingDefaultText?: true | undefined;
83 | /** Suppress setting compiler options from the compiler flags from query params */
84 | suppressAutomaticallyGettingCompilerFlags?: true | undefined;
85 | /** Logging system */
86 | logger: {
87 | log: (...args: any[]) => void;
88 | error: (...args: any[]) => void;
89 | groupCollapsed: (...args: any[]) => void;
90 | groupEnd: (...args: any[]) => void;
91 | };
92 | } & {
93 | domID: string;
94 | }> | Partial<{
95 | /** The default source code for the playground */
96 | text: string;
97 | /** Should it run the ts or js IDE services */
98 | useJavaScript: boolean;
99 | /** Compiler options which are automatically just forwarded on */
100 | compilerOptions: import("monaco-editor").languages.typescript.CompilerOptions;
101 | /** Optional monaco settings overrides */
102 | monacoSettings?: import("monaco-editor").editor.IEditorOptions | undefined;
103 | /** Acquire types via type acquisition */
104 | acquireTypes: boolean;
105 | /** Support twoslash compiler options */
106 | supportTwoslashCompilerOptions: boolean;
107 | /** Get the text via query params and local storage, useful when the editor is the main experience */
108 | suppressAutomaticallyGettingDefaultText?: true | undefined;
109 | /** Suppress setting compiler options from the compiler flags from query params */
110 | suppressAutomaticallyGettingCompilerFlags?: true | undefined;
111 | /** Logging system */
112 | logger: {
113 | log: (...args: any[]) => void;
114 | error: (...args: any[]) => void;
115 | groupCollapsed: (...args: any[]) => void;
116 | groupEnd: (...args: any[]) => void;
117 | };
118 | } & {
119 | elementToAppend: HTMLElement;
120 | }>, monaco: typeof import("monaco-editor"), ts: typeof import("typescript")) => {
121 | /** The same config you passed in */
122 | config: {
123 | text: string;
124 | useJavaScript: boolean;
125 | compilerOptions: import("monaco-editor").languages.typescript.CompilerOptions;
126 | monacoSettings?: import("monaco-editor").editor.IEditorOptions | undefined;
127 | acquireTypes: boolean;
128 | supportTwoslashCompilerOptions: boolean;
129 | suppressAutomaticallyGettingDefaultText?: true | undefined;
130 | suppressAutomaticallyGettingCompilerFlags?: true | undefined;
131 | logger: {
132 | log: (...args: any[]) => void;
133 | error: (...args: any[]) => void;
134 | groupCollapsed: (...args: any[]) => void;
135 | groupEnd: (...args: any[]) => void;
136 | };
137 | domID: string;
138 | };
139 | /** A list of TypeScript versions you can use with the TypeScript sandbox */
140 | supportedVersions: readonly ["3.8.3", "3.8.2", "3.7.5", "3.6.3", "3.5.1", "3.3.3", "3.1.6", "3.0.1", "2.8.1", "2.7.2", "2.4.1"];
141 | /** The monaco editor instance */
142 | editor: import("monaco-editor").editor.IStandaloneCodeEditor;
143 | /** Either "typescript" or "javascript" depending on your config */
144 | language: string;
145 | /** The outer monaco module, the result of require("monaco-editor") */
146 | monaco: typeof import("monaco-editor");
147 | /** Gets a monaco-typescript worker, this will give you access to a language server. Note: prefer this for language server work because it happens on a webworker . */
148 | getWorkerProcess: () => Promise;
149 | /** A copy of require("typescript-vfs") this can be used to quickly set up an in-memory compiler runs for ASTs, or to get complex language server results (anything above has to be serialized when passed)*/
150 | tsvfs: typeof tsvfs;
151 | /** Get all the different emitted files after TypeScript is run */
152 | getEmitResult: () => Promise;
153 | /** Gets just the JavaScript for your sandbox, will transpile if in TS only */
154 | getRunnableJS: () => Promise;
155 | /** Gets the DTS output of the main code in the editor */
156 | getDTSForCode: () => Promise;
157 | /** The monaco-editor dom node, used for showing/hiding the editor */
158 | getDomNode: () => HTMLElement;
159 | /** The model is an object which monaco uses to keep track of text in the editor. Use this to directly modify the text in the editor */
160 | getModel: () => import("monaco-editor").editor.ITextModel;
161 | /** Gets the text of the main model, which is the text in the editor */
162 | getText: () => string;
163 | /** Shortcut for setting the model's text content which would update the editor */
164 | setText: (text: string) => void;
165 | /** Gets the AST of the current text in monaco - uses `createTSProgram`, so the performance caveat applies there too */
166 | getAST: () => Promise;
167 | /** The module you get from require("typescript") */
168 | ts: typeof import("typescript");
169 | /** Create a new Program, a TypeScript data model which represents the entire project.
170 | *
171 | * The first time this is called it has to download all the DTS files which is needed for an exact compiler run. Which
172 | * at max is about 1.5MB - after that subsequent downloads of dts lib files come from localStorage.
173 | *
174 | * Try to use this sparingly as it can be computationally expensive, at the minimum you should be using the debounced setup.
175 | *
176 | * TODO: It would be good to create an easy way to have a single program instance which is updated for you
177 | * when the monaco model changes.
178 | */
179 | createTSProgram: () => Promise;
180 | /** The Sandbox's default compiler options */
181 | compilerDefaults: import("monaco-editor").languages.typescript.CompilerOptions;
182 | /** The Sandbox's current compiler options */
183 | getCompilerOptions: () => import("monaco-editor").languages.typescript.CompilerOptions;
184 | /** Replace the Sandbox's compiler options */
185 | setCompilerSettings: (opts: import("monaco-editor").languages.typescript.CompilerOptions) => void;
186 | /** Overwrite the Sandbox's compiler options */
187 | updateCompilerSetting: (key: string | number, value: any) => void;
188 | /** Update a single compiler option in the SAndbox */
189 | updateCompilerSettings: (opts: import("monaco-editor").languages.typescript.CompilerOptions) => void;
190 | /** A way to get callbacks when compiler settings have changed */
191 | setDidUpdateCompilerSettings: (func: (opts: import("monaco-editor").languages.typescript.CompilerOptions) => void) => void;
192 | /** A copy of lzstring, which is used to archive/unarchive code */
193 | // lzstring: typeof lzstring;
194 | /** Returns compiler options found in the params of the current page */
195 | createURLQueryWithCompilerOptions: (sandbox: any, paramOverrides?: any) => string;
196 | /** Returns compiler options in the source code using twoslash notation */
197 | getTwoSlashComplierOptions: (code: string) => any;
198 | /** Gets to the current monaco-language, this is how you talk to the background webworkers */
199 | languageServiceDefaults: import("monaco-editor").languages.typescript.LanguageServiceDefaults;
200 | };
201 | export declare type Sandbox = ReturnType;
202 | export {};
203 |
--------------------------------------------------------------------------------
/src/vendor/tsWorker.d.ts:
--------------------------------------------------------------------------------
1 | import ts from 'typescript';
2 | export declare class TypeScriptWorker implements ts.LanguageServiceHost {
3 | private _ctx;
4 | private _extraLibs;
5 | private _languageService;
6 | private _compilerOptions;
7 | constructor(ctx: any, createData: any);
8 | getCompilationSettings(): ts.CompilerOptions;
9 | getScriptFileNames(): string[];
10 | private _getModel;
11 | getScriptVersion(fileName: string): string;
12 | getScriptSnapshot(fileName: string): ts.IScriptSnapshot | undefined;
13 | getScriptKind?(fileName: string): ts.ScriptKind;
14 | getCurrentDirectory(): string;
15 | getDefaultLibFileName(options: ts.CompilerOptions): string;
16 | isDefaultLibFileName(fileName: string): boolean;
17 | private static clearFiles;
18 | getSyntacticDiagnostics(fileName: string): Promise;
19 | getSemanticDiagnostics(fileName: string): Promise;
20 | getSuggestionDiagnostics(fileName: string): Promise;
21 | getCompilerOptionsDiagnostics(fileName: string): Promise;
22 | getCompletionsAtPosition(fileName: string, position: number): Promise;
23 | getCompletionEntryDetails(fileName: string, position: number, entry: string): Promise;
24 | getSignatureHelpItems(fileName: string, position: number): Promise;
25 | getQuickInfoAtPosition(fileName: string, position: number): Promise;
26 | getOccurrencesAtPosition(fileName: string, position: number): Promise | undefined>;
27 | getDefinitionAtPosition(fileName: string, position: number): Promise | undefined>;
28 | getReferencesAtPosition(fileName: string, position: number): Promise;
29 | getNavigationBarItems(fileName: string): Promise;
30 | getFormattingEditsForDocument(fileName: string, options: ts.FormatCodeOptions): Promise;
31 | getFormattingEditsForRange(fileName: string, start: number, end: number, options: ts.FormatCodeOptions): Promise;
32 | getFormattingEditsAfterKeystroke(fileName: string, postion: number, ch: string, options: ts.FormatCodeOptions): Promise;
33 | findRenameLocations(fileName: string, positon: number, findInStrings: boolean, findInComments: boolean, providePrefixAndSuffixTextForRename: boolean): Promise;
34 | getRenameInfo(fileName: string, positon: number, options: ts.RenameInfoOptions): Promise;
35 | getEmitOutput(fileName: string): Promise;
36 | getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[], formatOptions: ts.FormatCodeOptions): Promise>;
37 | updateExtraLibs(extraLibs: IExtraLibs): void;
38 | }
39 | export interface IExtraLib {
40 | content: string;
41 | version: number;
42 | }
43 | export interface IExtraLibs {
44 | [path: string]: IExtraLib;
45 | }
46 |
--------------------------------------------------------------------------------
/src/vendor/typescript-vfs.d.ts:
--------------------------------------------------------------------------------
1 |
2 | declare type System = import('typescript').System;
3 | declare type CompilerOptions = import('typescript').CompilerOptions;
4 | declare type TS = typeof import('typescript');
5 | export interface VirtualTypeScriptEnvironment {
6 | sys: System;
7 | languageService: import('typescript').LanguageService;
8 | getSourceFile: (fileName: string) => import('typescript').SourceFile | undefined;
9 | createFile: (fileName: string, content: string) => void;
10 | updateFile: (fileName: string, content: string, replaceTextSpan?: import('typescript').TextSpan) => void;
11 | }
12 | /**
13 | * Makes a virtual copy of the TypeScript environment. This is the main API you want to be using with
14 | * typescript-vfs. A lot of the other exposed functions are used by this function to get set up.
15 | *
16 | * @param sys an object which conforms to the TS Sys (a shim over read/write access to the fs)
17 | * @param rootFiles a list of files which are considered inside the project
18 | * @param ts a copy pf the TypeScript module
19 | * @param compilerOptions the options for this compiler run
20 | */
21 | export declare function createVirtualTypeScriptEnvironment(sys: System, rootFiles: string[], ts: TS, compilerOptions?: CompilerOptions): VirtualTypeScriptEnvironment;
22 | /**
23 | * Grab the list of lib files for a particular target, will return a bit more than necessary (by including
24 | * the dom) but that's OK
25 | *
26 | * @param target The compiler settings target baseline
27 | * @param ts A copy of the TypeScript module
28 | */
29 | export declare const knownLibFilesForCompilerOptions: (compilerOptions: import("typescript").CompilerOptions, ts: typeof import("typescript")) => string[];
30 | /**
31 | * Sets up a Map with lib contents by grabbing the necessary files from
32 | * the local copy of typescript via the file system.
33 | */
34 | export declare const createDefaultMapFromNodeModules: (compilerOptions: import("typescript").CompilerOptions) => Map;
35 | /**
36 | * Create a virtual FS Map with the lib files from a particular TypeScript
37 | * version based on the target, Always includes dom ATM.
38 | *
39 | * @param options The compiler target, which dictates the libs to set up
40 | * @param version the versions of TypeScript which are supported
41 | * @param cache should the values be stored in local storage
42 | * @param ts a copy of the typescript import
43 | * @param lzstring an optional copy of the lz-string import
44 | * @param fetcher an optional replacement for the global fetch function (tests mainly)
45 | * @param storer an optional replacement for the localStorage global (tests mainly)
46 | */
47 | export declare const createDefaultMapFromCDN: (options: import("typescript").CompilerOptions, version: string, cache: boolean, ts: typeof import("typescript"), lzstring?: any | undefined, fetcher?: typeof fetch | undefined, storer?: Storage | undefined) => Promise