├── packages ├── utools-json2dts │ ├── index.js │ ├── .env │ ├── src │ │ ├── react-app-env.d.ts │ │ ├── edtor │ │ │ ├── editor.css │ │ │ └── index.tsx │ │ ├── setupTests.ts │ │ ├── toolbar │ │ │ ├── toolbar.css │ │ │ └── index.tsx │ │ ├── reportWebVitals.ts │ │ ├── index.tsx │ │ ├── useUpdateEffect.ts │ │ ├── prefix-switch │ │ │ └── index.tsx │ │ ├── App.css │ │ ├── ClipboardButton.tsx │ │ ├── useDebounceFn.ts │ │ └── App.tsx │ ├── public │ │ ├── robots.txt │ │ ├── logo.png │ │ ├── iconfont.ttf │ │ ├── iconfont.woff │ │ ├── iconfont.woff2 │ │ ├── plugin.json │ │ ├── manifest.json │ │ └── index.html │ ├── tsconfig.json │ ├── config-overrides.js │ ├── package.json │ └── README.md ├── vscode │ ├── global.d.ts │ ├── dev.md │ ├── images │ │ ├── logo.png │ │ ├── dep.svg │ │ └── typescript.svg │ ├── .vscode │ │ ├── extensions.json │ │ ├── settings.json │ │ ├── tasks.json │ │ └── launch.json │ ├── scripts │ │ ├── build.js │ │ ├── dev.js │ │ ├── init.js │ │ └── config.js │ ├── src │ │ ├── utils.ts │ │ ├── extension.ts │ │ └── Json2DtsWebViewPanel.ts │ ├── README.MD │ ├── tsconfig.json │ └── package.json └── json2dts-gen │ ├── global.d.ts │ ├── .babelrc │ ├── README.MD │ ├── jest.config.js │ ├── tsup.config.ts │ ├── tsconfig.json │ ├── src │ ├── log.ts │ ├── lib.ts │ ├── index.ts │ └── dts-dom.ts │ ├── test │ ├── parsejson.test.js │ └── gen.test.js │ └── package.json ├── pnpm-workspace.yaml ├── .gitignore ├── .vscode └── launch.json ├── package.json └── README.MD /packages/utools-json2dts/index.js: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /packages/vscode/global.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'json2dts-gen' -------------------------------------------------------------------------------- /pnpm-workspace.yaml: -------------------------------------------------------------------------------- 1 | packages: 2 | - 'packages/**' 3 | -------------------------------------------------------------------------------- /packages/json2dts-gen/global.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'json-fixer-browser'; -------------------------------------------------------------------------------- /packages/utools-json2dts/.env: -------------------------------------------------------------------------------- 1 | GENERATE_SOURCEMAP=false 2 | RUNTIME=VSCODE -------------------------------------------------------------------------------- /packages/vscode/dev.md: -------------------------------------------------------------------------------- 1 | # release 2 | ```vsce package --no-dependencies``` -------------------------------------------------------------------------------- /packages/json2dts-gen/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "@babel/preset-env" 4 | ] 5 | } -------------------------------------------------------------------------------- /packages/utools-json2dts/src/react-app-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | -------------------------------------------------------------------------------- /packages/utools-json2dts/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /packages/vscode/images/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zenotsai/json2dts-gen/HEAD/packages/vscode/images/logo.png -------------------------------------------------------------------------------- /packages/utools-json2dts/public/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zenotsai/json2dts-gen/HEAD/packages/utools-json2dts/public/logo.png -------------------------------------------------------------------------------- /packages/json2dts-gen/README.MD: -------------------------------------------------------------------------------- 1 | # JS2DTS 2 | 3 | 4 | Click [here](https://github.com/zenotsai/json2dts-gen) for detailed instructions 5 | -------------------------------------------------------------------------------- /packages/utools-json2dts/public/iconfont.ttf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zenotsai/json2dts-gen/HEAD/packages/utools-json2dts/public/iconfont.ttf -------------------------------------------------------------------------------- /packages/utools-json2dts/public/iconfont.woff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zenotsai/json2dts-gen/HEAD/packages/utools-json2dts/public/iconfont.woff -------------------------------------------------------------------------------- /packages/utools-json2dts/public/iconfont.woff2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/zenotsai/json2dts-gen/HEAD/packages/utools-json2dts/public/iconfont.woff2 -------------------------------------------------------------------------------- /packages/json2dts-gen/jest.config.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | 3 | module.exports = { 4 | testEnvironment: "node", 5 | testMatch: ["/**/*.test.js"], 6 | testPathIgnorePatterns: ["/src/", "node_modules"], 7 | }; 8 | -------------------------------------------------------------------------------- /packages/json2dts-gen/tsup.config.ts: -------------------------------------------------------------------------------- 1 | import { Options } from 'tsup' 2 | 3 | export default { 4 | entryPoints: [ 5 | 'src/*.ts', 6 | ], 7 | clean: true, 8 | format: ['cjs', 'esm'], 9 | dts: true, 10 | } -------------------------------------------------------------------------------- /packages/vscode/.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // See http://go.microsoft.com/fwlink/?LinkId=827846 3 | // for the documentation about the extensions.json format 4 | "recommendations": [ 5 | "dbaeumer.vscode-eslint" 6 | ] 7 | } -------------------------------------------------------------------------------- /packages/utools-json2dts/public/plugin.json: -------------------------------------------------------------------------------- 1 | { 2 | "main": "./index.html", 3 | "logo": "./logo.png", 4 | "features": [ 5 | { 6 | "code": "json2ts", 7 | "cmds":["dts", "json2ts", "json2dts", "2dts", "2ts"] 8 | } 9 | ] 10 | } -------------------------------------------------------------------------------- /packages/utools-json2dts/src/edtor/editor.css: -------------------------------------------------------------------------------- 1 | .monaco-placeholder { 2 | position: absolute; 3 | top: 0px; 4 | left: 70px; 5 | font-size: 16px; 6 | color: #fff; 7 | } 8 | 9 | .editor { 10 | height: 100%; 11 | position: relative; 12 | } -------------------------------------------------------------------------------- /packages/vscode/scripts/build.js: -------------------------------------------------------------------------------- 1 | const webpack = require('webpack'); 2 | const getWebpackConfig = require('./config'); 3 | const config = getWebpackConfig(false); 4 | const compiler = webpack(config); 5 | 6 | compiler.run(() => { 7 | console.log('Compiled successfully'); 8 | 9 | }) -------------------------------------------------------------------------------- /packages/utools-json2dts/src/setupTests.ts: -------------------------------------------------------------------------------- 1 | // jest-dom adds custom jest matchers for asserting on DOM nodes. 2 | // allows you to do things like: 3 | // expect(element).toHaveTextContent(/react/i) 4 | // learn more: https://github.com/testing-library/jest-dom 5 | import '@testing-library/jest-dom'; 6 | -------------------------------------------------------------------------------- /packages/vscode/scripts/dev.js: -------------------------------------------------------------------------------- 1 | const webpack = require('webpack'); 2 | const getWebpackConfig = require('./config'); 3 | const config = getWebpackConfig(true); 4 | const compiler = webpack(config); 5 | 6 | compiler.watch({ 7 | ignored: /node_modules/, 8 | }, (err, stats) => { 9 | if (err) { 10 | console.error(err); 11 | return; 12 | } 13 | console.log('Compiled successfully'); 14 | 15 | }) -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | out 11 | # production 12 | build 13 | dist 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | .idea 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | *.vsix 25 | static -------------------------------------------------------------------------------- /packages/utools-json2dts/src/toolbar/toolbar.css: -------------------------------------------------------------------------------- 1 | .toolbar { 2 | display: flex; 3 | align-items: center; 4 | height: 40px; 5 | background-color: rgb(30, 30, 30); 6 | } 7 | .toolbar-item { 8 | margin-left: 20px; 9 | } 10 | .icon { 11 | color: #18b6ea; 12 | font-size: 30px; 13 | 14 | } 15 | 16 | .btn { 17 | color: #fff; 18 | margin-left: 20px; 19 | cursor: pointer; 20 | font-size: 14px; 21 | font-weight: 500; 22 | 23 | } 24 | 25 | .btn:hover { 26 | color: #29b7e8 27 | } -------------------------------------------------------------------------------- /packages/vscode/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | // Place your settings in this file to overwrite default and user settings. 2 | { 3 | "files.exclude": { 4 | "out": false // set this to true to hide the "out" folder with the compiled JS files 5 | }, 6 | "search.exclude": { 7 | "out": true // set this to false to include "out" folder in search results 8 | }, 9 | // Turn off tsc task auto detection since we have the necessary tasks as npm scripts 10 | "typescript.tsc.autoDetect": "off" 11 | } -------------------------------------------------------------------------------- /packages/vscode/.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | // See https://go.microsoft.com/fwlink/?LinkId=733558 2 | // for the documentation about the tasks.json format 3 | { 4 | "version": "2.0.0", 5 | "tasks": [ 6 | { 7 | "type": "npm", 8 | "script": "watch", 9 | "problemMatcher": "$tsc-watch", 10 | "isBackground": true, 11 | "presentation": { 12 | "reveal": "never" 13 | }, 14 | "group": { 15 | "kind": "build", 16 | "isDefault": true 17 | } 18 | } 19 | ] 20 | } -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | "version": "0.2.0", 6 | "configurations": [ 7 | { 8 | "name": "Launch Program", 9 | "program": "${workspaceFolder}/index.js", 10 | "request": "launch", 11 | "skipFiles": [ 12 | "/**" 13 | ], 14 | "type": "node" 15 | } 16 | ] 17 | } -------------------------------------------------------------------------------- /packages/utools-json2dts/src/reportWebVitals.ts: -------------------------------------------------------------------------------- 1 | import { ReportHandler } from 'web-vitals'; 2 | 3 | const reportWebVitals = (onPerfEntry?: ReportHandler) => { 4 | if (onPerfEntry && onPerfEntry instanceof Function) { 5 | import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { 6 | getCLS(onPerfEntry); 7 | getFID(onPerfEntry); 8 | getFCP(onPerfEntry); 9 | getLCP(onPerfEntry); 10 | getTTFB(onPerfEntry); 11 | }); 12 | } 13 | }; 14 | 15 | export default reportWebVitals; 16 | -------------------------------------------------------------------------------- /packages/json2dts-gen/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2017", 4 | "module": "esnext", 5 | "lib": [ 6 | "esnext", 7 | "DOM" 8 | ], 9 | "types": [ 10 | "node", 11 | "jest" 12 | ], 13 | "moduleResolution": "node", 14 | "esModuleInterop": true, 15 | "strict": true, 16 | "strictNullChecks": true, 17 | "resolveJsonModule": true 18 | }, 19 | "include": [ 20 | "src/**/*.ts", 21 | "global.d.ts" 22 | ] 23 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "json-dts", 3 | "version": "1.0.0", 4 | "main": "./dist/index.js", 5 | "license": "MIT", 6 | "scripts": { 7 | "build": "tsup", 8 | "dev": "tsup --watch src" 9 | }, 10 | "bin": { 11 | "js2dts": "./dist/bin.js" 12 | }, 13 | "dependencies": { 14 | "@types/npmlog": "^4.1.4", 15 | "commander": "^9.1.0", 16 | "dts-dom": "^3.6.0", 17 | "npmlog": "^6.0.1" 18 | }, 19 | "devDependencies": { 20 | "@types/commander": "^2.12.2", 21 | "tsup": "^5.12.1", 22 | "typescript": "^4.6.2" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /packages/utools-json2dts/src/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom'; 3 | import App from './App'; 4 | import reportWebVitals from './reportWebVitals'; 5 | 6 | 7 | ReactDOM.render( 8 | 9 | 10 | , 11 | document.getElementById('root') 12 | ); 13 | 14 | // If you want to start measuring performance in your app, pass a function 15 | // to log results (for example: reportWebVitals(console.log)) 16 | // or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals 17 | reportWebVitals(); 18 | -------------------------------------------------------------------------------- /packages/utools-json2dts/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /packages/utools-json2dts/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": [ 5 | "dom", 6 | "dom.iterable", 7 | "esnext" 8 | ], 9 | "allowJs": true, 10 | "skipLibCheck": true, 11 | "esModuleInterop": true, 12 | "allowSyntheticDefaultImports": true, 13 | "strict": true, 14 | "forceConsistentCasingInFileNames": true, 15 | "noFallthroughCasesInSwitch": true, 16 | "module": "esnext", 17 | "moduleResolution": "node", 18 | "resolveJsonModule": true, 19 | "isolatedModules": true, 20 | "noEmit": true, 21 | "jsx": "react-jsx" 22 | }, 23 | "include": [ 24 | "src" 25 | ] 26 | } 27 | -------------------------------------------------------------------------------- /packages/utools-json2dts/src/useUpdateEffect.ts: -------------------------------------------------------------------------------- 1 | import { useRef, useEffect } from 'react'; 2 | import type { useLayoutEffect } from 'react'; 3 | 4 | type effectHookType = typeof useEffect | typeof useLayoutEffect; 5 | 6 | export const createUpdateEffect: (hook: effectHookType) => effectHookType = 7 | (hook) => (effect, deps) => { 8 | const isMounted = useRef(false); 9 | 10 | // for react-refresh 11 | hook(() => { 12 | return () => { 13 | isMounted.current = false; 14 | }; 15 | }, []); 16 | 17 | hook(() => { 18 | if (!isMounted.current) { 19 | isMounted.current = true; 20 | } else { 21 | return effect(); 22 | } 23 | }, deps); 24 | }; 25 | 26 | 27 | export default createUpdateEffect(useEffect) -------------------------------------------------------------------------------- /packages/vscode/src/utils.ts: -------------------------------------------------------------------------------- 1 | import * as vscode from 'vscode'; 2 | import generateDeclaration from "json2dts-gen"; 3 | 4 | 5 | export const convertTs2EditorSelected = (text: string) => { 6 | const textEditor = vscode.window.activeTextEditor; 7 | if (!textEditor) { 8 | return; 9 | } 10 | var selection = textEditor.selection; 11 | textEditor.edit(function (editBuilder) { 12 | const config = vscode.workspace.getConfiguration('JSON2dts'); 13 | const res = generateDeclaration(text.toString(), { 14 | propertyKeyCamelcase: config.propertyKeyCamelcase, 15 | objectSeparate: config.objectSeparate, 16 | interfacePrefix: config.interfacePrefix ? 'I' : '' 17 | }); 18 | // @ts-ignore 19 | editBuilder.replace(selection, res); 20 | }); 21 | } -------------------------------------------------------------------------------- /packages/json2dts-gen/src/log.ts: -------------------------------------------------------------------------------- 1 | import npmlog from 'npmlog' 2 | import PkgJson from '../package.json'; 3 | 4 | const envs = ['verbose', 'info', 'error', 'warn']; 5 | 6 | const envLogLevel = process.env.LOG_LEVEL as string 7 | const logLevel = 8 | envs.indexOf(envLogLevel) !== -1 ? envLogLevel : 'info'; 9 | 10 | npmlog.level = logLevel; 11 | 12 | const prefix = PkgJson.name; 13 | 14 | type LogFn = (message: string) => void; 15 | const logUtils: { 16 | verbose: LogFn 17 | info: LogFn 18 | error: LogFn 19 | warn: LogFn 20 | } = envs.reduce((pre, current) => { 21 | if (npmlog[current]) { 22 | return { 23 | ...pre, 24 | [current]: (message: string) => npmlog[current](prefix, message) 25 | } 26 | } 27 | return pre; 28 | }, Object.create(null)) 29 | export default logUtils -------------------------------------------------------------------------------- /packages/json2dts-gen/test/parsejson.test.js: -------------------------------------------------------------------------------- 1 | import { parseJson } from "../dist/index.js"; 2 | describe("parseLooseJson", () => { 3 | it("Nested Object", () => { 4 | expect( 5 | parseJson(` 6 | name:"jordan" 7 | sons: { 8 | "j1": 1 9 | "j2": 2 10 | } 11 | `) 12 | ).toEqual({ 13 | name: "jordan", 14 | sons: { 15 | j1: 1, 16 | j2: 2, 17 | }, 18 | }); 19 | }); 20 | it("Array", () => { 21 | expect( 22 | parseJson(` 23 | [ 24 | "aaa" 25 | ] 26 | `) 27 | ).toEqual(["aaa"]); 28 | }); 29 | it("Object", () => { 30 | expect( 31 | parseJson(` 32 | name:"jordan" 33 | age: 123 34 | `) 35 | ).toEqual({ 36 | name: "jordan", 37 | age: 123, 38 | }); 39 | }); 40 | }); 41 | -------------------------------------------------------------------------------- /packages/utools-json2dts/src/prefix-switch/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | 3 | interface ISwitchProps { 4 | active: boolean; 5 | onChange: (active: boolean) => void; 6 | children: React.ReactNode 7 | localKey: string; 8 | } 9 | 10 | const Switch: React.FC = ({ active,localKey, onChange, children }) => { 11 | 12 | return
{ 14 | onChange(!active) 15 | if (active) { 16 | window.localStorage.setItem(localKey, '1'); 17 | } else { 18 | window.localStorage.setItem(localKey, '0'); 19 | } 20 | }} 21 | className="iconfont icon" style={{ 22 | color: active ? '#18b6ea' : '#fff2' 23 | }}> 24 | { children } 25 |
26 | } 27 | 28 | 29 | 30 | export default Switch; 31 | -------------------------------------------------------------------------------- /packages/utools-json2dts/config-overrides.js: -------------------------------------------------------------------------------- 1 | /* config-overrides.js */ 2 | const MonacoWebpackPlugin = require("monaco-editor-webpack-plugin"); 3 | 4 | module.exports = { 5 | webpack: function (config, env) { 6 | const vscodeRuntime = process.argv[2] === 'RUNTIME=VSCODE' 7 | config.plugins.push( 8 | new MonacoWebpackPlugin({ 9 | languages: ["javascript", "typescript"], 10 | }) 11 | ); 12 | if (env !== "production") { 13 | return config; 14 | } 15 | config.output.publicPath = vscodeRuntime ? "https://file+.vscode-resource.vscode-cdn.net/" : './'; 16 | return config; 17 | }, 18 | devServer: function (configFunction) { 19 | return function (proxy, allowedHost) { 20 | const config = configFunction(proxy, allowedHost); 21 | config.devMiddleware.writeToDisk = true; 22 | return config; 23 | }; 24 | }, 25 | }; 26 | -------------------------------------------------------------------------------- /packages/vscode/README.MD: -------------------------------------------------------------------------------- 1 | # Introduction 2 | Generate TypeScript type definitions from JSON 3 | 4 | 5 | # Feature 6 | * JSON to typescript 7 | * JSON auto correction 8 | * Automatic I prefix addition, multi-level object support 9 | 10 | 11 | # Usage 12 | 13 | 1, Right-click to convert the selected text, clipboard in 14 | 15 | 2, You can use ***CMD + Alt + V*** or ***CTRL + Alt +V*** to convert JSON from the clipboard to the TypeScript interface. 16 | 17 | 3, Open panel UI 18 | 19 | Mac: **command+shift+p** 20 | Windows: **Ctrl + Shift + P** 21 | 22 | Use the **2dts** command to quickly open the panel 23 | 24 | 25 | **Setting** 26 | - On Windows/Linux - File > Preferences > Settings > JSON2dts 27 | - On macOS - Code > Preferences > Settings > JSON2dts 28 | 29 | ![alt 属性文本](https://github.com/zenotsai/image-hosting/blob/master/frontend/json2dts.gif?raw=true) 30 | 31 | 32 | # Question Feedback 33 | https://github.com/zenotsai/json2dts-gen/issues -------------------------------------------------------------------------------- /packages/utools-json2dts/src/App.css: -------------------------------------------------------------------------------- 1 | * { 2 | margin: 0; 3 | padding: 0; 4 | } 5 | 6 | .App { 7 | display: flex; 8 | align-items: center; 9 | } 10 | 11 | .result { 12 | width: 100%; 13 | color: #fff; 14 | font-size: 16px; 15 | background-color: #1e1e1e; 16 | } 17 | 18 | .panel { 19 | height: 100%; 20 | width: 50%; 21 | position: relative; 22 | } 23 | 24 | 25 | .copyBtn { 26 | position: absolute; 27 | cursor: pointer; 28 | border: 0; 29 | right: 0; 30 | background-color: #3d4d56; 31 | color: #fff; 32 | top: 0; 33 | z-index: 9; 34 | height: 40px; 35 | border-radius: 4px; 36 | padding: 0 8px; 37 | } 38 | 39 | html,body,#root,.App { 40 | height: 100%; 41 | } 42 | 43 | 44 | 45 | 46 | .formatIcon::after { 47 | content: '\e60f'; 48 | font-family: "iconfont"; 49 | } 50 | .clearIcon::after { 51 | content: '\e62f'; 52 | font-family: "iconfont"; 53 | font-size: 21px; 54 | position: relative; 55 | top: -4px; 56 | } -------------------------------------------------------------------------------- /packages/vscode/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "target": "ES2020", 5 | "outDir": "out", 6 | "baseUrl": ".", 7 | "skipLibCheck": true, 8 | "allowSyntheticDefaultImports": true, 9 | "lib": [ 10 | "ES2020" 11 | ], 12 | "sourceMap": true, 13 | "rootDir": "src", 14 | "strict": true /* enable all strict type-checking options */ 15 | /* Additional Checks */ 16 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 17 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 18 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 19 | }, 20 | "include": [ 21 | "src/**/*.ts", 22 | "src/**/*.tsx", 23 | "src/**/*.js", 24 | "src/**/*.jsx", 25 | "global.d.ts" 26 | ], 27 | "exclude": [ 28 | "out", 29 | "typings", 30 | "helpers.d.ts", 31 | "node_modules", 32 | "build", 33 | "scripts" 34 | ] 35 | } -------------------------------------------------------------------------------- /packages/utools-json2dts/src/ClipboardButton.tsx: -------------------------------------------------------------------------------- 1 | import { FC, useEffect, useMemo } from 'react'; 2 | import ClipboardJS from 'clipboard'; 3 | 4 | interface IClipboardButtonProps { 5 | text: string; 6 | className?: string; 7 | } 8 | 9 | const ClipboardButton: FC = ({ className, text }) => { 10 | 11 | const showBtn = useMemo(() => { 12 | return text && text.trim().length > 0; 13 | }, [text]) 14 | 15 | useEffect(() => { 16 | const btnId = '#copyBtn' 17 | const clipboard = new ClipboardJS(btnId); 18 | clipboard.on('success', function (e) { 19 | e.clearSelection(); 20 | const ele = document.querySelector(btnId); 21 | ele!.textContent = 'Copied' 22 | setTimeout(() => { 23 | ele!.textContent = 'Copy' 24 | }, 300) 25 | 26 | }); 27 | }, []) 28 | 29 | if (!showBtn) { 30 | return <> 31 | } 32 | 33 | return 40 | } 41 | 42 | export default ClipboardButton; 43 | -------------------------------------------------------------------------------- /packages/utools-json2dts/src/toolbar/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactTooltip from 'react-tooltip'; 3 | import cn from 'classnames' 4 | import './toolbar.css' 5 | 6 | interface IToolbarProps { 7 | options: { 8 | key: string; 9 | label: string; 10 | component?: React.ReactNode; 11 | className?: string; 12 | onClick?: () => void; 13 | }[] 14 | } 15 | // 16 | 17 | const Toolbar: React.FC = ({ options}) => { 18 | return
19 | { 20 | (options || []).map((i) => { 21 | return
22 | { i.component ? 23 | { i.component } 24 | : 25 | } 26 | 27 | { i.label } 28 | 29 |
30 | }) 31 | } 32 |
33 | } 34 | 35 | export default Toolbar; 36 | -------------------------------------------------------------------------------- /packages/utools-json2dts/src/useDebounceFn.ts: -------------------------------------------------------------------------------- 1 | import debounce from 'lodash-es/debounce'; 2 | import { useRef, useEffect, useMemo } from 'react'; 3 | 4 | function useLatest(value: T) { 5 | const ref = useRef(value); 6 | ref.current = value; 7 | 8 | return ref; 9 | } 10 | 11 | interface IDebounceOptions { 12 | wait?: number; 13 | leading?: boolean; 14 | trailing?: boolean; 15 | maxWait?: number; 16 | } 17 | type noop = (...args: any) => any; 18 | 19 | 20 | function useDebounceFn(fn: T, options?: IDebounceOptions) { 21 | const fnRef = useLatest(fn); 22 | 23 | const wait = options?.wait ?? 1000; 24 | 25 | const debounced = useMemo(() => { 26 | return debounce( 27 | ((...args: Parameters): ReturnType => { 28 | return fnRef.current(...args); 29 | }), 30 | wait, 31 | options, 32 | ) 33 | }, []) 34 | 35 | useEffect( 36 | () => () => { 37 | debounced.cancel(); 38 | }, 39 | [], 40 | ); 41 | return { 42 | run: debounced, 43 | cancel: debounced.cancel, 44 | flush: debounced.flush, 45 | }; 46 | } 47 | 48 | 49 | export default useDebounceFn; -------------------------------------------------------------------------------- /packages/vscode/.vscode/launch.json: -------------------------------------------------------------------------------- 1 | // A launch configuration that compiles the extension and then opens it inside a new window 2 | // Use IntelliSense to learn about possible attributes. 3 | // Hover to view descriptions of existing attributes. 4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 5 | { 6 | "version": "0.2.0", 7 | "configurations": [ 8 | { 9 | "name": "Run Extension", 10 | "type": "extensionHost", 11 | "request": "launch", 12 | "args": [ 13 | "--extensionDevelopmentPath=${workspaceFolder}" 14 | ], 15 | "outFiles": [ 16 | "${workspaceFolder}/out/**/*.js" 17 | ], 18 | "preLaunchTask": "${defaultBuildTask}" 19 | }, 20 | { 21 | "name": "Extension Tests", 22 | "type": "extensionHost", 23 | "request": "launch", 24 | "args": [ 25 | "--extensionDevelopmentPath=${workspaceFolder}", 26 | "--extensionTestsPath=${workspaceFolder}/out/test/suite/index" 27 | ], 28 | "outFiles": [ 29 | "${workspaceFolder}/out/test/**/*.js" 30 | ], 31 | "preLaunchTask": "${defaultBuildTask}" 32 | } 33 | ] 34 | } -------------------------------------------------------------------------------- /README.MD: -------------------------------------------------------------------------------- 1 | 2 | Generate typeScript type definitions from JSON 3 | 4 | 5 | 6 | # Feature 7 | * JSON to typescript 8 | * Loose json specification with automatic formatting error repair 9 | * Provides vscode and utools plugins, cli 10 | 11 | 12 | # vscode 13 | search for **JSON2DTS** install 14 | 15 | ![alt](https://github.com/zenotsai/image-hosting/blob/master/frontend/json2dts.gif?raw=true) 16 | 17 | 18 | 19 | # Cli 20 | 21 | ```js 22 | // install 23 | npm i json2dts-gen 24 | 25 | // cli 26 | js2dts -f ./package.json 27 | 28 | // or 29 | 30 | import generateDeclaration from 'json2dts-gen'; 31 | const value = `{ 32 | "name": "vscode" 33 | }` 34 | const res = generateDeclaration(value, { 35 | objectSeparate: true 36 | interfacePrefix: 'I' 37 | }); 38 | ``` 39 | 40 | ## params 41 | 42 | | param | describe | default | 43 | | :-----| ----: | :----: | 44 | | -c | json content | -- | 45 | | -f | file path | -- | 46 | | -sep | Object types are defined individually | true | 47 | | -prefix | interface prefix | -- | 48 | | -camelcase | property camelcase | -- | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | # UTools 57 | search for **Json2Ts** install 58 | 59 | ## Test 60 | 61 | ```npm run test ``` -------------------------------------------------------------------------------- /packages/vscode/scripts/init.js: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const path = require('path'); 3 | const { exec } = require('child_process'); 4 | const appDirectory = fs.realpathSync(process.cwd()) 5 | const resolveApp = (relativePath) => path.resolve(appDirectory, relativePath); 6 | const staticBuildDir = resolveApp('static') 7 | const staticProjectDir = resolveApp('../utools-json2dts'); 8 | function clean(dir) { 9 | const files = fs.readdirSync(dir); 10 | for (let i = 0; i < files.length; i++) { 11 | const filePath = path.join(dir, files[i]); 12 | const stat = fs.statSync(filePath); 13 | if (stat.isDirectory()) { 14 | clean(filePath); 15 | } else { 16 | fs.unlinkSync(filePath) 17 | } 18 | } 19 | fs.rmdirSync(dir) 20 | } 21 | 22 | if (fs.existsSync(staticBuildDir)) { 23 | console.log('clean...') 24 | clean(staticBuildDir); 25 | } 26 | console.log('build static files...') 27 | exec(`pnpm run build:vs`, { 28 | cwd: staticProjectDir 29 | }, (err, stdout, stderr ) => { 30 | if (!err) { 31 | fs.renameSync(path.resolve(staticProjectDir, 'build'),staticBuildDir,function(err){ 32 | if(err){ 33 | console.log(err) 34 | } else { 35 | console.log('copied') 36 | } 37 | }) 38 | } 39 | 40 | 41 | }) 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /packages/json2dts-gen/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "json2dts-gen", 3 | "version": "1.1.11", 4 | "description": "generate dts from json", 5 | "main": "./dist/index.js", 6 | "license": "MIT", 7 | "types": "./dist/index.d.ts", 8 | "keywords": [ 9 | "json2ts", 10 | "js2ts", 11 | "dts" 12 | ], 13 | "bugs": { 14 | "url": "https://github.com/zenotsai/json2dts-gen/issues" 15 | }, 16 | "repository": { 17 | "type": "git", 18 | "url": "https://github.com/zenotsai/json2dts-gen.git" 19 | }, 20 | "files": [ 21 | "dist" 22 | ], 23 | "scripts": { 24 | "preinstall": "npx only-allow pnpm", 25 | "build": "tsup", 26 | "test": "jest", 27 | "prepublishOnly": "npm run build", 28 | "dev": "tsup --watch src" 29 | }, 30 | "author": "zeno", 31 | "bin": { 32 | "js2dts": "./dist/bin.js" 33 | }, 34 | "dependencies": { 35 | "@babel/core": "^7.17.9", 36 | "@babel/preset-env": "^7.16.11", 37 | "camelcase": "^6.3.0", 38 | "commander": "^9.1.0", 39 | "dts-dom": "^3.6.0", 40 | "jest": "^27.5.1", 41 | "json-fixer-browser": "1.6.14", 42 | "npmlog": "^6.0.1" 43 | }, 44 | "devDependencies": { 45 | "@types/commander": "^2.12.2", 46 | "@types/npmlog": "^4.1.4", 47 | "tsup": "^5.12.1", 48 | "typescript": "^4.6.2" 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /packages/vscode/scripts/config.js: -------------------------------------------------------------------------------- 1 | 2 | 'use strict'; 3 | const fs = require('fs'); 4 | const path = require('path'); 5 | const appDirectory = fs.realpathSync(process.cwd()) 6 | const resolveApp = (relativePath) => path.resolve(appDirectory, relativePath); 7 | module.exports = function (isDevelopment) { 8 | /**@type {import('webpack').Configuration}*/ 9 | const config = { 10 | target: 'node', 11 | mode: isDevelopment ? 'development': 'production', 12 | entry: resolveApp('/src/extension.ts'), 13 | output: { 14 | path: resolveApp('dist'), 15 | filename: 'extension.js', 16 | libraryTarget: "commonjs2", 17 | }, 18 | cache: { 19 | type: "filesystem", 20 | name: 'json2dts', 21 | cacheDirectory: resolveApp('node_modules/.cache'), 22 | store: "pack", 23 | buildDependencies: { 24 | defaultWebpack: ["webpack/lib/"], 25 | config: [__filename], 26 | tsconfig: [resolveApp('tsconfig.json')].filter((f) => fs.existsSync(f)), 27 | }, 28 | }, 29 | devtool: isDevelopment ? "cheap-module-source-map" : false, 30 | externals: { 31 | vscode: "commonjs vscode" 32 | }, 33 | resolve: { 34 | extensions: ['.ts', '.js'] 35 | }, 36 | module: { 37 | rules: [{ 38 | test: /\.ts$/, 39 | exclude: /node_modules/, 40 | use: [{ 41 | loader: 'ts-loader' 42 | }] 43 | }] 44 | }, 45 | } 46 | return config; 47 | } 48 | 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /packages/utools-json2dts/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 11 | 12 | json2dts 13 | 29 | 30 | 31 | 32 |
33 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /packages/json2dts-gen/test/gen.test.js: -------------------------------------------------------------------------------- 1 | import generateDeclaration from "../dist/index.js"; 2 | describe("dts-gen", () => { 3 | it("Simple Object", () => { 4 | 5 | expect( 6 | generateDeclaration(`{ 7 | name: "jordan", 8 | }`) 9 | ).toEqual('interface CustomType {\r\n name: string;\r\n}\r\n\r\n') 10 | }) 11 | 12 | it("property camelcase", () => { 13 | expect( 14 | generateDeclaration(`{ 15 | my-key: "jordan" 16 | }`, { 17 | propertyKeyCamelcase: true 18 | }) 19 | ).toEqual('interface CustomType {\r\n myKey: string;\r\n}\r\n\r\n') 20 | }) 21 | 22 | 23 | it("Array", () => { 24 | expect( 25 | generateDeclaration((`[ 26 | "aaa" 27 | ]`)) 28 | ).toEqual('type CustomType = string[]\r\n\r\n') 29 | }) 30 | 31 | it("Array Object", () => { 32 | expect( 33 | generateDeclaration((`[ 34 | { 35 | "age": 123, 36 | "name": "jordan" 37 | } 38 | ]`)) 39 | ).toEqual('type CustomType = {\r\n age: number;\r\n name: string;\r\n}[]\r\n\r\n') 40 | }) 41 | 42 | it("Nested Object", () => { 43 | expect( 44 | generateDeclaration((`{ 45 | name: "jordan", 46 | info: { 47 | age: 123, 48 | gender: 'man' 49 | } 50 | }`), { 51 | objectSeparate: false 52 | }) 53 | ).toEqual('interface CustomType {\r\n' + 54 | ' name: string;\r\n' + 55 | ' info: {\r\n' + 56 | ' age: number;\r\n' + 57 | ' gender: string;\r\n' + 58 | ' };\r\n' + 59 | '}\r\n' + 60 | '\r\n') 61 | }) 62 | }); 63 | -------------------------------------------------------------------------------- /packages/vscode/src/extension.ts: -------------------------------------------------------------------------------- 1 | 2 | 3 | import * as vscode from 'vscode'; 4 | 5 | 6 | import Json2DtsWebViewPanel from './Json2DtsWebViewPanel'; 7 | import { convertTs2EditorSelected } from './utils'; 8 | 9 | 10 | export function activate(context: vscode.ExtensionContext) { 11 | 12 | context.subscriptions.push( 13 | vscode.commands.registerCommand('json2dts.open', () => { 14 | Json2DtsWebViewPanel.createOrShow(context.extensionUri); 15 | }) 16 | ); 17 | context.subscriptions.push( 18 | vscode.commands.registerCommand('json2dts.convertFromSelected', async () => { 19 | const textEditor = vscode.window.activeTextEditor; 20 | if (!textEditor) { 21 | return; 22 | } 23 | const selection = textEditor.selection; 24 | const selectedText = textEditor?.document.getText(selection); 25 | if (!selectedText) { 26 | return; 27 | } 28 | try { 29 | convertTs2EditorSelected(selectedText); 30 | } catch (e) { 31 | vscode.window.showErrorMessage('JSON2dts: Convert Fail'); 32 | } 33 | 34 | }) 35 | ); 36 | 37 | context.subscriptions.push( 38 | vscode.commands.registerCommand('json2dts.convertFromClipboard', async () => { 39 | 40 | try { 41 | let clipboardContent = await vscode.env.clipboard.readText(); 42 | if (!clipboardContent) { 43 | return; 44 | } 45 | convertTs2EditorSelected(clipboardContent); 46 | } catch (e) { 47 | console.error(e); 48 | vscode.window.showErrorMessage('JSON2dts: Convert Fail'); 49 | } 50 | }) 51 | ); 52 | 53 | 54 | 55 | 56 | } 57 | 58 | // this method is called when your extension is deactivated 59 | export function deactivate() { } 60 | -------------------------------------------------------------------------------- /packages/utools-json2dts/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "utools-json2dts", 3 | "version": "0.1.1", 4 | "private": true, 5 | "dependencies": { 6 | "@testing-library/jest-dom": "^5.16.2", 7 | "@testing-library/react": "^12.1.4", 8 | "@testing-library/user-event": "^13.5.0", 9 | "@types/jest": "^27.4.1", 10 | "@types/node": "^16.11.26", 11 | "@types/react": "^17.0.41", 12 | "@types/react-dom": "^17.0.14", 13 | "classnames": "^2.3.1", 14 | "clipboard": "^2.0.10", 15 | "cross-env": "^7.0.3", 16 | "json2dts-gen": "workspace:1.1.11", 17 | "lodash-es": "^4.17.21", 18 | "monaco-editor": "^0.33.0", 19 | "monaco-editor-webpack-plugin": "^7.0.1", 20 | "react": "^17.0.2", 21 | "react-app-rewired": "^2.2.1", 22 | "react-dom": "^17.0.2", 23 | "react-monaco-editor": "^0.47.0", 24 | "react-scripts": "5.0.0", 25 | "react-tooltip": "^4.2.21", 26 | "typescript": "^4.6.2", 27 | "web-vitals": "^2.1.4" 28 | }, 29 | "scripts": { 30 | "start": "react-app-rewired start", 31 | "build": "react-app-rewired build", 32 | "build:vs": "react-app-rewired build RUNTIME=VSCODE", 33 | "test": "react-app-rewired test", 34 | "eject": "react-scripts eject" 35 | }, 36 | "eslintConfig": { 37 | "extends": [ 38 | "react-app", 39 | "react-app/jest" 40 | ] 41 | }, 42 | "browserslist": { 43 | "production": [ 44 | ">0.2%", 45 | "not dead", 46 | "not op_mini all" 47 | ], 48 | "development": [ 49 | "last 1 chrome version", 50 | "last 1 firefox version", 51 | "last 1 safari version" 52 | ] 53 | }, 54 | "devDependencies": { 55 | "@types/jsoneditor": "^9.5.1", 56 | "@types/lodash-es": "^4.17.6" 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /packages/json2dts-gen/src/lib.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | import log from './log' 3 | import { Command } from 'commander'; 4 | import PkgJson from '../package.json'; 5 | import fs from 'fs'; 6 | import path from 'path'; 7 | import generateDeclarationFile, { parseJson } from './' 8 | const program = new Command(); 9 | 10 | 11 | 12 | program 13 | .option('-c, --content ', 'json content') 14 | .option('-sep, --objectSeparate', 'Object types are defined individually', true) 15 | .option('-prefix, --prefix ', 'interface prefix') 16 | .option('-f, --file ', 'json file') 17 | .option('-camelcase, --camelcase', 'property camelcase', false) 18 | .version(PkgJson.version) 19 | .parse(); 20 | 21 | program.parse(process.argv); 22 | 23 | function isExistSync(filePath: string) { 24 | if (!filePath) { 25 | return false; 26 | } 27 | try { 28 | return !Boolean(fs.accessSync(filePath)); 29 | } catch (e) { 30 | return false; 31 | } 32 | } 33 | 34 | const options = program.opts<{ 35 | content: string; 36 | file: string; 37 | objectSeparate: boolean; 38 | prefix: string; 39 | camelcase?: boolean; 40 | }>(); 41 | (() => { 42 | const { content, file, objectSeparate, camelcase, prefix } = options; 43 | if (!content && !file) { 44 | log.warn('Missing required parameter --content or --file') 45 | return; 46 | } 47 | let targetObj; 48 | 49 | if (content) { 50 | targetObj = parseJson(content); 51 | } else { 52 | 53 | const filePath = path.resolve(process.cwd(), file); 54 | if (!isExistSync(filePath)) { 55 | log.warn(`file does not exist:${filePath}`) 56 | return; 57 | } 58 | targetObj = fs.readFileSync(filePath, { encoding: 'utf-8' }); 59 | } 60 | 61 | console.log(generateDeclarationFile(targetObj, { 62 | objectSeparate, 63 | propertyKeyCamelcase: camelcase, 64 | interfacePrefix: prefix 65 | })) 66 | })() 67 | -------------------------------------------------------------------------------- /packages/utools-json2dts/src/edtor/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import MonacoEditor, { MonacoEditorProps } from 'react-monaco-editor'; 3 | import { editor } from 'monaco-editor' 4 | import './editor.css' 5 | 6 | interface IEditorProps { 7 | value?: string; 8 | options?: MonacoEditorProps['options']; 9 | language?: string; 10 | onChange: (v: string) => void; 11 | placeholder?: string; 12 | } 13 | 14 | const PLACEHOLDER_SELECTOR = ".monaco-placeholder"; 15 | 16 | 17 | const Editor: React.FC = (props) => { 18 | const refs = React.useRef(); 19 | const { value, placeholder, onChange, language = "javascript", options = {} } = props; 20 | 21 | function hidePlaceholder() { 22 | const dom: HTMLDivElement | null = document.querySelector(PLACEHOLDER_SELECTOR); 23 | if (dom) { 24 | dom.style.display = "none"; 25 | } 26 | } 27 | 28 | 29 | 30 | function showPlaceholder(value: string) { 31 | if (value === "") { 32 | const dom: HTMLDivElement | null = document.querySelector(PLACEHOLDER_SELECTOR); 33 | if (dom) { 34 | dom.style.display = "initial"; 35 | } 36 | 37 | } 38 | } 39 | const editorDidMount = (instance: editor.ICodeEditor) => { 40 | 41 | instance.onDidBlurEditorWidget(() => { 42 | showPlaceholder(instance.getValue()); 43 | }); 44 | 45 | instance.onDidFocusEditorWidget(() => { 46 | hidePlaceholder(); 47 | }); 48 | } 49 | return
50 | 66 |
{ placeholder }
67 |
68 | 69 | 70 | } 71 | 72 | export default Editor; 73 | -------------------------------------------------------------------------------- /packages/utools-json2dts/README.md: -------------------------------------------------------------------------------- 1 | # Getting Started with Create React App 2 | 3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 4 | 5 | ## Available Scripts 6 | 7 | In the project directory, you can run: 8 | 9 | ### `npm start` 10 | 11 | Runs the app in the development mode.\ 12 | Open [http://localhost:3000](http://localhost:3000) to view it in the browser. 13 | 14 | The page will reload if you make edits.\ 15 | You will also see any lint errors in the console. 16 | 17 | ### `npm test` 18 | 19 | Launches the test runner in the interactive watch mode.\ 20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 21 | 22 | ### `npm run build` 23 | 24 | Builds the app for production to the `build` folder.\ 25 | It correctly bundles React in production mode and optimizes the build for the best performance. 26 | 27 | The build is minified and the filenames include the hashes.\ 28 | Your app is ready to be deployed! 29 | 30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 31 | 32 | ### `npm run eject` 33 | 34 | **Note: this is a one-way operation. Once you `eject`, you can’t go back!** 35 | 36 | If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 37 | 38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own. 39 | 40 | You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. 41 | 42 | ## Learn More 43 | 44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 45 | 46 | To learn React, check out the [React documentation](https://reactjs.org/). 47 | -------------------------------------------------------------------------------- /packages/utools-json2dts/src/App.tsx: -------------------------------------------------------------------------------- 1 | import './App.css'; 2 | import generateDeclarationFile, { parseJson } from 'json2dts-gen'; 3 | import { useState } from 'react' 4 | import ClipboardButton from './ClipboardButton'; 5 | import useDebounceFn from './useDebounceFn'; 6 | import Toolbar from './toolbar' 7 | import Editor from './edtor' 8 | import useUpdateEffect from './useUpdateEffect'; 9 | import PrefixSwitch from './prefix-switch'; 10 | 11 | 12 | const LOCAL_KEY_INTERFACE_PREFIX = "001"; 13 | const LOCAL_KEY_SEPARATE_PREFIX = "002"; 14 | 15 | 16 | function getDefaultValue (key: string, defaultValue: boolean) { 17 | const value = window.localStorage.getItem(key); 18 | if (!value) { 19 | return defaultValue; 20 | } 21 | return value === '1'; 22 | } 23 | function App() { 24 | const [result, setResult] = useState(''); 25 | const [json, setJson] = useState(); 26 | const [option, setOption] = useState({ 27 | interfacePrefix: getDefaultValue(LOCAL_KEY_INTERFACE_PREFIX, false), 28 | objectSeparate: getDefaultValue(LOCAL_KEY_SEPARATE_PREFIX, true) 29 | }); 30 | 31 | const { run: onChange } = useDebounceFn( 32 | (value: string) => { 33 | try { 34 | setJson(value); 35 | const res = generateDeclarationFile(value, { 36 | ...option, 37 | interfacePrefix: option.interfacePrefix ? 'I' : '' 38 | }); 39 | setResult(res) 40 | } catch (e: any) { 41 | setResult(e.message) 42 | } 43 | }, 44 | { 45 | wait: 500, 46 | }, 47 | ); 48 | 49 | useUpdateEffect(() => { 50 | if (json) { 51 | onChange(json) 52 | } 53 | 54 | }, [option]) 55 | 56 | 57 | 58 | return ( 59 |
60 |
61 | { 67 | setJson(JSON.stringify(parseJson(json!), null, 2)); 68 | } 69 | }, 70 | { 71 | label: 'clear', 72 | className: 'clearIcon', 73 | key: 'clear', 74 | onClick: () => { 75 | setJson(''); 76 | } 77 | } 78 | ]}/> 79 | 83 | 84 |
85 |
86 | 87 | { 93 | setOption({ 94 | ...option, 95 | interfacePrefix: active 96 | }) 97 | }}> 98 |  99 | 100 | }, 101 | { 102 | label: 'Object generates a separate interface', 103 | key: 'separate', 104 | component: { 105 | setOption({ 106 | ...option, 107 | objectSeparate: active 108 | }) 109 | }}> 110 |  111 | 112 | } 113 | ]} 114 | /> 115 | 123 |
124 | 125 |
126 | ); 127 | } 128 | 129 | export default App; 130 | -------------------------------------------------------------------------------- /packages/vscode/images/dep.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Slice 5 | Created with Sketch. 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /packages/vscode/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "JSON2dts", 3 | "displayName": "JSON2dts", 4 | "description": "JSON to typescript", 5 | "version": "0.0.9", 6 | "bugs": { 7 | "url": "https://github.com/zenotsai/json2dts-gen/issues" 8 | }, 9 | "keywords": [ 10 | "json2ts", 11 | "vscode", 12 | "json", 13 | "plugin", 14 | "typescript" 15 | ], 16 | "repository": { 17 | "type": "git", 18 | "url": "https://github.com/zenotsai/json2dts-gen.git" 19 | }, 20 | "icon": "images/logo.png", 21 | "publisher": "JSON2dts", 22 | "engines": { 23 | "vscode": "^1.67.0" 24 | }, 25 | "categories": [ 26 | "Languages", 27 | "Snippets" 28 | ], 29 | "extensionKind": [ 30 | "ui", 31 | "workspace" 32 | ], 33 | "private": true, 34 | "activationEvents": [ 35 | "onCommand:json2dts.open", 36 | "onCommand:json2dts.convertFromClipboard", 37 | "onCommand:json2dts.convertFromSelected" 38 | ], 39 | "main": "./dist/extension.js", 40 | "capabilities": { 41 | "untrustedWorkspaces": { 42 | "supported": true 43 | } 44 | }, 45 | "contributes": { 46 | "configuration": { 47 | "title": "JSON2dts", 48 | "properties": { 49 | "JSON2dts.interfacePrefix": { 50 | "type": "boolean", 51 | "default": true, 52 | "description": "Add an 'I' prefix to the interface when formatting" 53 | }, 54 | "JSON2dts.objectSeparate": { 55 | "type": "boolean", 56 | "default": true, 57 | "description": "Object generates a separate interface" 58 | }, 59 | "JSON2dts.propertyKeyCamelcase": { 60 | "type": "boolean", 61 | "default": false, 62 | "description": "Formatting Object Properties to Camelcase" 63 | } 64 | } 65 | }, 66 | "menus": { 67 | "editor/context": [ 68 | { 69 | "command": "json2dts.convertFromSelected", 70 | "alt": "json2dts.convertFromSelected", 71 | "group": "navigation", 72 | "when": "resourceExtname =~ /.ts|tsx|vue|md$/i" 73 | }, 74 | { 75 | "command": "json2dts.convertFromClipboard", 76 | "alt": "json2dts.convertFromClipboard", 77 | "group": "navigation", 78 | "when": "resourceExtname =~ /.ts|tsx|vue|md$/i" 79 | } 80 | ] 81 | }, 82 | "keybindings": [ 83 | { 84 | "command": "json2dts.convertFromClipboard", 85 | "key": "ctrl+alt+V" 86 | }, 87 | { 88 | "command": "json2dts.convertFromSelected", 89 | "key": "ctrl+alt+S" 90 | } 91 | ], 92 | "commands": [ 93 | { 94 | "command": "json2dts.convertFromSelected", 95 | "title": "2dts From Selected", 96 | "category": "Convert from selected text" 97 | }, 98 | { 99 | "command": "json2dts.convertFromClipboard", 100 | "title": "2dts From Clipboard", 101 | "category": "Convert from clipboard" 102 | }, 103 | { 104 | "command": "json2dts.open", 105 | "title": "2dts", 106 | "category": "Open JSON2TS panel" 107 | } 108 | ] 109 | }, 110 | "scripts": { 111 | "vscode:prepublish": "yarn run compile", 112 | "compile": "node scripts/init.js && node scripts/build.js", 113 | "dev": "node scripts/dev.js", 114 | "watch": "tsc -watch -p ./", 115 | "pretest": "yarn run compile ", 116 | "test": "node ./out/test/runTest.js" 117 | }, 118 | "devDependencies": { 119 | "@types/glob": "^7.2.0", 120 | "@types/mocha": "^9.1.1", 121 | "@types/node": "16.x", 122 | "@types/vscode": "1.67.0", 123 | "@typescript-eslint/eslint-plugin": "^5.31.0", 124 | "@typescript-eslint/parser": "^5.31.0", 125 | "@vscode/test-electron": "^2.1.5", 126 | "eslint": "^8.20.0", 127 | "glob": "^8.0.3", 128 | "mocha": "^10.0.0", 129 | "ts-loader": "^9.3.1", 130 | "typescript": "^4.7.4" 131 | }, 132 | "dependencies": { 133 | "json2dts-gen": "workspace:1.1.11", 134 | "pathe": "^0.3.3", 135 | "webpack": "^5.74.0", 136 | "webpack-cli": "^4.10.0" 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /packages/vscode/src/Json2DtsWebViewPanel.ts: -------------------------------------------------------------------------------- 1 | 2 | 3 | import * as vscode from 'vscode'; 4 | import * as fs from 'fs'; 5 | import { resolve } from 'pathe' 6 | 7 | 8 | function getWebviewOptions(extensionUri: vscode.Uri): vscode.WebviewOptions { 9 | return { 10 | // Enable javascript in the webview 11 | enableScripts: true, 12 | // And restrict the webview to only loading content from our extension's `media` directory. 13 | localResourceRoots: [vscode.Uri.joinPath(extensionUri, 'static')] 14 | }; 15 | } 16 | 17 | export default class Json2DtsWebViewPanel { 18 | public static readonly viewType = 'json2dts.view'; 19 | public static currentPanel: Json2DtsWebViewPanel | undefined; 20 | private readonly _extensionUri: vscode.Uri; 21 | private readonly _panel: vscode.WebviewPanel; 22 | 23 | constructor(panel: vscode.WebviewPanel, extensionUri: vscode.Uri) { 24 | this._panel = panel; 25 | this._extensionUri = extensionUri; 26 | const webview = this._panel.webview; 27 | this._panel.webview.html = this._getHtmlForWebview(webview); 28 | this._panel.onDidDispose(() => this.dispose(), null); 29 | 30 | } 31 | 32 | public dispose() { 33 | Json2DtsWebViewPanel.currentPanel = undefined; 34 | 35 | this._panel.dispose(); 36 | 37 | } 38 | 39 | public static createOrShow(extensionUri: vscode.Uri) { 40 | const column = vscode.window.activeTextEditor 41 | ? vscode.window.activeTextEditor.viewColumn 42 | : undefined; 43 | if (Json2DtsWebViewPanel.currentPanel) { 44 | Json2DtsWebViewPanel.currentPanel._panel.reveal(column); 45 | return; 46 | } 47 | 48 | const panel = vscode.window.createWebviewPanel( 49 | Json2DtsWebViewPanel.viewType, 50 | 'json2dts', 51 | column || vscode.ViewColumn.One, 52 | getWebviewOptions(extensionUri), 53 | ); 54 | Json2DtsWebViewPanel.currentPanel = new Json2DtsWebViewPanel(panel, extensionUri); 55 | 56 | } 57 | 58 | private _getAssetsUri(webview: vscode.Webview, filePath: string) { 59 | const scriptPathOnDisk = vscode.Uri.joinPath(this._extensionUri, 'static', filePath); 60 | const scriptUri = webview.asWebviewUri(scriptPathOnDisk); 61 | const stylesResetUri = webview.asWebviewUri(scriptUri); 62 | return stylesResetUri; 63 | } 64 | 65 | private __handlerPublicPath(webview: vscode.Webview) { 66 | try { 67 | const files = fs.readdirSync(resolve(this._extensionUri.path, 'static/static/js')).map((i) => { 68 | return resolve(vscode.Uri.joinPath(this._extensionUri, 'static/static/js').path, i); 69 | }); 70 | const publicPath = `https://file+.vscode-resource.vscode-cdn.net${vscode.Uri.joinPath(this._extensionUri, 'static').path}`; 71 | for (let i = 0; i < files.length; i++) { 72 | let bundle = fs.readFileSync(files[i], 'utf-8'); 73 | if (bundle.startsWith('//done')) { 74 | continue; 75 | } 76 | bundle = `//done \r\n ${bundle.replace(/https:\/\/file\+\.vscode-resource\.vscode-cdn\.net/g, `${publicPath}/`)}`; 77 | fs.writeFileSync(files[i], bundle); 78 | } 79 | } catch (e) { 80 | console.error(e); 81 | } 82 | } 83 | 84 | private _getHtmlForWebview(webview: vscode.Webview) { 85 | this.__handlerPublicPath(webview); 86 | const jsonPath = resolve(this._extensionUri.path, 'static', 'asset-manifest.json'); 87 | const obj = JSON.parse(fs.readFileSync(jsonPath).toString()); 88 | const mainJSUri = this._getAssetsUri(webview, obj.entrypoints[1]); 89 | const mainCSSUri = this._getAssetsUri(webview, obj.entrypoints[0]); 90 | 91 | const getIconFontUrl = (suffix: string) => { 92 | return this._getAssetsUri(webview, `iconfont.${suffix}`); 93 | } 94 | 95 | return ` 96 | 97 | 98 | 99 | 100 | 101 | 102 | 104 | json2dts 105 | 118 | 119 | 120 | 121 | 122 | 125 |
126 | 127 | 128 | ` 129 | } 130 | } -------------------------------------------------------------------------------- /packages/json2dts-gen/src/index.ts: -------------------------------------------------------------------------------- 1 | import type { ObjectType, InterfaceDeclaration, ArrayTypeReference, PrimitiveType } from './dts-dom'; 2 | import * as dtsDom from './dts-dom'; 3 | import jsonFixerBrowser from 'json-fixer-browser'; 4 | import camelcase from 'camelcase'; 5 | 6 | 7 | export type IOptions = { 8 | objectSeparate?: boolean; 9 | interfacePrefix?: string; 10 | propertyKeyCamelcase?: boolean; 11 | } 12 | 13 | function jsonFixer(value: string) { 14 | try { 15 | const { data } = jsonFixerBrowser(value); 16 | return data; 17 | } catch (e) { 18 | console.error(e) 19 | } 20 | return undefined 21 | } 22 | 23 | function jsonFn(value: string) { 24 | try { 25 | return new Function(`return ${value}`)(); 26 | } catch (e) { 27 | return null; 28 | } 29 | 30 | } 31 | 32 | /** 33 | * TODO: 在 json-fixer 中拓展 34 | * @param value 35 | * @returns 36 | */ 37 | function jsonFixerObject(value: string) { 38 | if (!/^{.+}$/.test(value)) { 39 | try { 40 | const parts = value.split(/\n/).filter(item => Boolean(item.trim())).map((item) => { 41 | const res = item.trim(); 42 | if (res.endsWith(',') || res.endsWith('{')) { 43 | return res; 44 | } 45 | return res + ',' 46 | }) 47 | const newValue = `{${parts.join('')}}` 48 | return new Function(`return ${newValue}`)(); 49 | } catch (e) { 50 | } 51 | } 52 | return null 53 | } 54 | function looseParseJson(value: string): object { 55 | let result = jsonFn(value); 56 | if (!result) { 57 | result = jsonFixerObject(value); 58 | } 59 | if (!result) { 60 | result = jsonFixer(value); 61 | } 62 | return result; 63 | } 64 | 65 | export function parseJson(value: string) { 66 | try { 67 | return JSON.parse(value); 68 | } catch (e: any) { 69 | return looseParseJson(value); 70 | } 71 | } 72 | 73 | 74 | 75 | 76 | function generateDeclarationTypeScript(json: string, options: IOptions = Object.create(null)): string { 77 | const { objectSeparate = true, interfacePrefix = '', propertyKeyCamelcase } = options; 78 | const value = parseJson(json); 79 | if (!value) { 80 | throw new Error('json2dts: conversion failure'); 81 | } 82 | const intf = dtsDom.create.interface(generateInterfaceName("CustomType")); 83 | const standaloneType: InterfaceDeclaration[] = []; 84 | const result: string[] = []; 85 | function generateInterfaceName(name: string) { 86 | return interfacePrefix + name; 87 | } 88 | function getTypeOfValue(value: any, propertyKey?: string): ObjectType | InterfaceDeclaration | PrimitiveType | ArrayTypeReference { 89 | const type = typeof value; 90 | 91 | if (Array.isArray(value)) { 92 | if (value.length > 0) return dtsDom.create.array(getTypeOfValue(value[0], propertyKey)); 93 | return dtsDom.create.array(dtsDom.type.any); 94 | } 95 | switch (type) { 96 | case "string": 97 | case "number": 98 | case "boolean": 99 | return type; 100 | case "undefined": 101 | return dtsDom.type.any; 102 | case "object": 103 | if (!value) { 104 | return dtsDom.type.any; 105 | } 106 | const keys = getObjectKeys(value); 107 | const members = keys.map((key: string) => { 108 | return dtsDom.create.property(propertyKeyCamelcase ? camelcase(key) : key, getTypeOfValue(value[key], key)); 109 | }); 110 | if (!propertyKey) { 111 | const objType = dtsDom.create.objectType(members); 112 | return objType; 113 | } 114 | 115 | if (objectSeparate) { 116 | const interfaceName = camelcase(propertyKey, { pascalCase: true, preserveConsecutiveUppercase: true }); 117 | 118 | const inter = dtsDom.create.interface(generateInterfaceName(interfaceName)); 119 | inter.members = members; 120 | standaloneType.push(inter); 121 | return inter; 122 | } 123 | const objType = dtsDom.create.objectType(members); 124 | return objType; 125 | 126 | default: 127 | return dtsDom.type.any; 128 | } 129 | } 130 | 131 | function generateObjectDeclaration(value: object) { 132 | const obj = getTypeOfValue(value) as InterfaceDeclaration; 133 | obj.members.forEach((m) => intf.members.push(m)); 134 | standaloneType.forEach((e) => 135 | result.push(dtsDom.emit(e, { rootFlags: dtsDom.ContextFlags.Module })) 136 | ); 137 | result.push(dtsDom.emit(intf, { rootFlags: dtsDom.ContextFlags.Module })) 138 | return obj; 139 | } 140 | 141 | if (Array.isArray(value) && value.length > 0) { 142 | const obj = getTypeOfValue(value[0]) as InterfaceDeclaration; 143 | standaloneType.forEach((e) => 144 | result.push(dtsDom.emit(e, { rootFlags: dtsDom.ContextFlags.Module })) 145 | ); 146 | const customType = dtsDom.create.type(generateInterfaceName("CustomType"), dtsDom.create.array(obj)); 147 | result.push(dtsDom.emit(customType, { rootFlags: dtsDom.ContextFlags.Module })) 148 | } else { 149 | generateObjectDeclaration(value); 150 | } 151 | return result.join('\n'); 152 | } 153 | 154 | 155 | 156 | 157 | function getObjectKeys(value: object) { 158 | const names = Object.getOwnPropertyNames(value); 159 | return names; 160 | } 161 | 162 | export default generateDeclarationTypeScript; -------------------------------------------------------------------------------- /packages/json2dts-gen/src/dts-dom.ts: -------------------------------------------------------------------------------- 1 | export interface DeclarationBase { 2 | jsDocComment?: string; 3 | comment?: string; 4 | flags?: DeclarationFlags; 5 | } 6 | 7 | export interface EnumMemberDeclaration extends DeclarationBase { 8 | kind: "enum-value"; 9 | name: string; 10 | value?: string | number; 11 | } 12 | 13 | export interface EnumDeclaration extends DeclarationBase { 14 | kind: "enum"; 15 | name: string; 16 | members: EnumMemberDeclaration[]; 17 | constant: boolean; 18 | } 19 | 20 | export interface PropertyDeclaration extends DeclarationBase { 21 | kind: "property"; 22 | name: string; 23 | type: Type; 24 | } 25 | 26 | export interface Parameter { 27 | kind: "parameter"; 28 | name: string; 29 | type: Type; 30 | flags?: ParameterFlags; 31 | } 32 | 33 | export interface TypeParameter { 34 | kind: "type-parameter"; 35 | name: string; 36 | baseType?: ObjectTypeReference | TypeReference | UnionType | IntersectionType | PrimitiveType | ObjectType | TypeofReference | FunctionType | TypeParameter; 37 | defaultType?: Type; 38 | } 39 | 40 | export interface IndexSignature extends DeclarationBase { 41 | kind: "index-signature"; 42 | name: string; 43 | indexType: ("string" | "number"); 44 | valueType: Type; 45 | } 46 | 47 | export interface CallSignature extends DeclarationBase { 48 | kind: "call-signature"; 49 | parameters: Parameter[]; 50 | returnType: Type; 51 | typeParameters: TypeParameter[]; 52 | } 53 | 54 | export interface MethodDeclaration extends DeclarationBase { 55 | kind: "method"; 56 | name: string; 57 | parameters: Parameter[]; 58 | returnType: Type; 59 | typeParameters: TypeParameter[]; 60 | } 61 | 62 | export interface FunctionDeclaration extends DeclarationBase { 63 | kind: "function"; 64 | name: string; 65 | parameters: Parameter[]; 66 | returnType: Type; 67 | typeParameters: TypeParameter[]; 68 | } 69 | 70 | export interface ConstructorDeclaration extends DeclarationBase { 71 | kind: "constructor"; 72 | parameters: Parameter[]; 73 | } 74 | 75 | export interface ClassDeclaration extends DeclarationBase { 76 | kind: "class"; 77 | name: string; 78 | members: ClassMember[]; 79 | implements: InterfaceDeclaration[]; 80 | typeParameters: TypeParameter[]; 81 | baseType?: ObjectTypeReference; 82 | } 83 | 84 | export interface InterfaceDeclaration extends DeclarationBase { 85 | kind: "interface"; 86 | name: string; 87 | members: ObjectTypeMember[]; 88 | typeParameters: TypeParameter[]; 89 | baseTypes?: ObjectTypeReference[]; 90 | } 91 | 92 | 93 | export interface TypeDeclaration extends DeclarationBase { 94 | kind: "type"; 95 | // TODO: memeber 96 | name: string; 97 | type: Type; 98 | } 99 | 100 | export interface ArrayDeclaration extends DeclarationBase { 101 | kind: "array"; 102 | name: string; 103 | type: Type; 104 | } 105 | 106 | export interface ImportAllDeclaration extends DeclarationBase { 107 | kind: "importAll"; 108 | name: string; 109 | from: string; 110 | } 111 | 112 | export interface ImportNamedDeclaration extends DeclarationBase { 113 | kind: "importNamed"; 114 | name: string; 115 | as?: string; 116 | from: string; 117 | } 118 | 119 | export interface ImportDefaultDeclaration extends DeclarationBase { 120 | kind: "importDefault"; 121 | name: string; 122 | from: string; 123 | } 124 | 125 | export interface ImportEqualsDeclaration extends DeclarationBase { 126 | kind: "import="; 127 | name: string; 128 | from: string; 129 | } 130 | 131 | export interface ImportDeclaration extends DeclarationBase { 132 | kind: "import"; 133 | from: string; 134 | } 135 | 136 | export interface NamespaceDeclaration extends DeclarationBase { 137 | kind: "namespace"; 138 | name: string; 139 | members: NamespaceMember[]; 140 | } 141 | 142 | export interface ConstDeclaration extends DeclarationBase { 143 | kind: "const"; 144 | name: string; 145 | type: Type; 146 | } 147 | 148 | export interface VariableDeclaration extends DeclarationBase { 149 | kind: "var"; 150 | name: string; 151 | type: Type; 152 | } 153 | 154 | export interface ExportEqualsDeclaration extends DeclarationBase { 155 | kind: "export="; 156 | target: string; 157 | } 158 | 159 | export interface ExportDefaultDeclaration extends DeclarationBase { 160 | kind: "exportDefault"; 161 | name: string; 162 | } 163 | 164 | export interface ExportNameDeclaration extends DeclarationBase { 165 | kind: "exportName"; 166 | name: string; 167 | as?: string; 168 | } 169 | 170 | export interface ModuleDeclaration extends DeclarationBase { 171 | kind: "module"; 172 | name: string; 173 | members: ModuleMember[]; 174 | } 175 | 176 | export interface ObjectType { 177 | kind: "object"; 178 | members: ObjectTypeMember[]; 179 | } 180 | 181 | export interface UnionType { 182 | kind: "union"; 183 | members: Type[]; 184 | } 185 | 186 | export interface IntersectionType { 187 | kind: "intersection"; 188 | members: Type[]; 189 | } 190 | 191 | export interface FunctionType { 192 | kind: "function-type"; 193 | parameters: Parameter[]; 194 | returnType: Type; 195 | typeParameters: TypeParameter[]; 196 | } 197 | 198 | export interface TypeAliasDeclaration extends DeclarationBase { 199 | kind: "alias"; 200 | name: string; 201 | type: Type; 202 | typeParameters: TypeParameter[]; 203 | } 204 | 205 | export interface TypeTypeReference { 206 | kind: "type"; 207 | type: Type; 208 | } 209 | export interface ArrayTypeReference { 210 | kind: "array"; 211 | type: Type; 212 | } 213 | 214 | export interface NamedTypeReference { 215 | kind: "name"; 216 | name: string; 217 | typeArguments: Type[]; 218 | } 219 | 220 | export interface TypeofReference { 221 | kind: "typeof"; 222 | type: NamedTypeReference; 223 | } 224 | 225 | export interface StringLiteral { 226 | kind: "string-literal"; 227 | value: string; 228 | } 229 | 230 | export interface NumberLiteral { 231 | kind: "number-literal"; 232 | value: number; 233 | } 234 | 235 | export interface TripleSlashReferencePathDirective { 236 | kind: "triple-slash-reference-path", 237 | path: string; 238 | } 239 | 240 | export interface TripleSlashReferenceTypesDirective { 241 | kind: "triple-slash-reference-types", 242 | types: string; 243 | } 244 | 245 | export interface TripleSlashReferenceNoDefaultLibDirective { 246 | kind: "triple-slash-reference-no-default-lib", 247 | value: boolean; 248 | } 249 | 250 | export interface TripleSlashAmdModuleDirective { 251 | kind: "triple-slash-amd-module", 252 | name?: string; 253 | } 254 | 255 | export type PrimitiveType = "string" | "number" | "boolean" | "any" | "void" | "object" | "null" | "undefined" | "true" | "false" | StringLiteral | NumberLiteral; 256 | 257 | export function isPrimitiveType(x: Type): x is PrimitiveType { 258 | switch (x) { 259 | case "string": 260 | case "number": 261 | case "boolean": 262 | case "any": 263 | case "void": 264 | case "object": 265 | case "null": 266 | case "undefined": 267 | case "true": 268 | case "false": 269 | return true; 270 | } 271 | // StringLiteral 272 | if (typeof x === 'string') { 273 | return true; 274 | } 275 | // NumberLiteral 276 | if (typeof x === 'number') { 277 | return true; 278 | } 279 | return false; 280 | } 281 | 282 | export type ThisType = "this"; 283 | 284 | export type TripleSlashDirective = TripleSlashReferencePathDirective | TripleSlashReferenceTypesDirective | TripleSlashReferenceNoDefaultLibDirective | TripleSlashAmdModuleDirective; 285 | 286 | export type TypeReference = TopLevelDeclaration | NamedTypeReference | ArrayTypeReference | PrimitiveType; 287 | 288 | export type ObjectTypeReference = ClassDeclaration | InterfaceDeclaration; 289 | export type ObjectTypeMember = PropertyDeclaration | MethodDeclaration | IndexSignature | CallSignature; 290 | export type ClassMember = PropertyDeclaration | MethodDeclaration | IndexSignature | ConstructorDeclaration; 291 | 292 | export type Type = TypeReference | UnionType | IntersectionType | PrimitiveType | ObjectType | TypeofReference | FunctionType | TypeParameter | ThisType; 293 | 294 | export type Import = ImportAllDeclaration | ImportDefaultDeclaration | ImportNamedDeclaration | ImportEqualsDeclaration | ImportDeclaration; 295 | 296 | export type NamespaceMember = InterfaceDeclaration | TypeAliasDeclaration | ClassDeclaration | NamespaceDeclaration | ConstDeclaration | VariableDeclaration | FunctionDeclaration | EnumDeclaration; 297 | export type ModuleMember = InterfaceDeclaration | TypeAliasDeclaration | ClassDeclaration | NamespaceDeclaration | ConstDeclaration | VariableDeclaration | FunctionDeclaration | Import | ExportEqualsDeclaration | ExportDefaultDeclaration | EnumDeclaration; 298 | export type TopLevelDeclaration = TypeDeclaration | NamespaceMember | ExportEqualsDeclaration | ExportDefaultDeclaration | ExportNameDeclaration | ModuleDeclaration | EnumDeclaration | Import; 299 | 300 | export enum DeclarationFlags { 301 | None = 0, 302 | Private = 1 << 0, 303 | Protected = 1 << 1, 304 | Static = 1 << 2, 305 | Optional = 1 << 3, 306 | Export = 1 << 4, 307 | Abstract = 1 << 5, 308 | ExportDefault = 1 << 6, 309 | ReadOnly = 1 << 7, 310 | } 311 | 312 | export enum ParameterFlags { 313 | None = 0, 314 | Optional = 1 << 0, 315 | Rest = 1 << 1 316 | } 317 | 318 | export const config = { 319 | wrapJsDocComments: true, 320 | outputEol: '\r\n', 321 | }; 322 | 323 | export const create = { 324 | interface(name: string, flags = DeclarationFlags.None): InterfaceDeclaration { 325 | return { 326 | name, 327 | baseTypes: [], 328 | typeParameters: [], 329 | kind: "interface", 330 | members: [], 331 | flags 332 | }; 333 | }, 334 | 335 | class(name: string, flags = DeclarationFlags.None): ClassDeclaration { 336 | return { 337 | kind: 'class', 338 | name, 339 | members: [], 340 | implements: [], 341 | typeParameters: [], 342 | flags 343 | }; 344 | }, 345 | 346 | typeParameter(name: string, baseType?: TypeParameter['baseType']): TypeParameter { 347 | return { 348 | kind: 'type-parameter', 349 | name, baseType, defaultType: undefined 350 | }; 351 | }, 352 | 353 | enum(name: string, constant: boolean = false, flags = DeclarationFlags.None): EnumDeclaration { 354 | return { 355 | kind: 'enum', 356 | name, constant, 357 | members: [], 358 | flags 359 | }; 360 | }, 361 | 362 | enumValue(name: string, value?: string | number): EnumMemberDeclaration { 363 | return { 364 | kind: 'enum-value', 365 | name, 366 | value 367 | }; 368 | }, 369 | 370 | property(name: string, type: Type, flags = DeclarationFlags.None): PropertyDeclaration { 371 | return { 372 | kind: "property", 373 | name, type, flags 374 | }; 375 | }, 376 | 377 | method(name: string, parameters: Parameter[], returnType: Type, flags = DeclarationFlags.None): MethodDeclaration { 378 | return { 379 | kind: "method", 380 | typeParameters: [], 381 | name, parameters, returnType, flags 382 | }; 383 | }, 384 | 385 | callSignature(parameters: Parameter[], returnType: Type): CallSignature { 386 | return { 387 | kind: "call-signature", 388 | typeParameters: [], 389 | parameters, returnType 390 | }; 391 | }, 392 | 393 | function(name: string, parameters: Parameter[], returnType: Type, flags = DeclarationFlags.None): FunctionDeclaration { 394 | return { 395 | kind: "function", 396 | typeParameters: [], 397 | name, parameters, returnType, flags 398 | }; 399 | }, 400 | 401 | functionType(parameters: Parameter[], returnType: Type): FunctionType { 402 | return { 403 | kind: "function-type", 404 | typeParameters: [], 405 | parameters, returnType 406 | }; 407 | }, 408 | 409 | parameter(name: string, type: Type, flags = ParameterFlags.None): Parameter { 410 | return { 411 | kind: "parameter", 412 | name, type, flags 413 | }; 414 | }, 415 | 416 | constructor(parameters: Parameter[], flags = DeclarationFlags.None): ConstructorDeclaration { 417 | return { 418 | kind: "constructor", 419 | parameters, 420 | flags 421 | }; 422 | }, 423 | 424 | const(name: string, type: Type, flags = DeclarationFlags.None): ConstDeclaration { 425 | return { 426 | kind: "const", name, type, flags 427 | }; 428 | }, 429 | 430 | variable(name: string, type: Type): VariableDeclaration { 431 | return { 432 | kind: "var", name, type 433 | }; 434 | }, 435 | 436 | alias(name: string, type: Type, flags = DeclarationFlags.None): TypeAliasDeclaration { 437 | return { 438 | kind: "alias", name, type, 439 | typeParameters: [], flags 440 | }; 441 | }, 442 | 443 | namespace(name: string): NamespaceDeclaration { 444 | return { 445 | kind: "namespace", name, 446 | members: [] 447 | }; 448 | }, 449 | 450 | objectType(members: ObjectTypeMember[]): ObjectType { 451 | return { 452 | kind: "object", 453 | members 454 | }; 455 | }, 456 | 457 | indexSignature(name: string, indexType: ('string' | 'number'), valueType: Type): IndexSignature { 458 | return { 459 | kind: 'index-signature', 460 | name, indexType, valueType 461 | } 462 | }, 463 | 464 | array(type: Type): ArrayTypeReference { 465 | return { 466 | kind: "array", 467 | type 468 | }; 469 | }, 470 | 471 | arrayDec(name: string, type: Type): ArrayDeclaration { 472 | return { 473 | kind: "array", 474 | type, name 475 | }; 476 | }, 477 | type(name: string, type: Type): TypeDeclaration { 478 | return { 479 | kind: "type", 480 | type, name 481 | }; 482 | }, 483 | 484 | namedTypeReference(name: string): NamedTypeReference { 485 | return { 486 | kind: 'name', 487 | name, 488 | typeArguments: [] 489 | }; 490 | }, 491 | 492 | exportEquals(target: string): ExportEqualsDeclaration { 493 | return { 494 | kind: 'export=', 495 | target 496 | }; 497 | }, 498 | 499 | exportDefault(name: string): ExportDefaultDeclaration { 500 | return { 501 | kind: 'exportDefault', 502 | name 503 | }; 504 | }, 505 | 506 | exportName(name: string, as?: string): ExportNameDeclaration { 507 | return { 508 | kind: "exportName", 509 | name, 510 | as 511 | }; 512 | }, 513 | 514 | module(name: string): ModuleDeclaration { 515 | return { 516 | kind: 'module', 517 | name, 518 | members: [] 519 | }; 520 | }, 521 | 522 | importAll(name: string, from: string): ImportAllDeclaration { 523 | return { 524 | kind: 'importAll', 525 | name, 526 | from 527 | }; 528 | }, 529 | 530 | importDefault(name: string, from: string): ImportDefaultDeclaration { 531 | return { 532 | kind: 'importDefault', 533 | name, 534 | from 535 | }; 536 | }, 537 | 538 | importNamed(name: string, as: string, from?: string): ImportNamedDeclaration { 539 | return { 540 | kind: 'importNamed', 541 | name, 542 | as: typeof from !== 'undefined' ? as : undefined, 543 | from: typeof from !== 'undefined' ? from : as 544 | }; 545 | }, 546 | 547 | importEquals(name: string, from: string): ImportEqualsDeclaration { 548 | return { 549 | kind: 'import=', 550 | name, 551 | from 552 | }; 553 | }, 554 | 555 | import(from: string): ImportDeclaration { 556 | return { 557 | kind: 'import', 558 | from 559 | }; 560 | }, 561 | 562 | union(members: Type[]): UnionType { 563 | return { 564 | kind: 'union', 565 | members 566 | }; 567 | }, 568 | 569 | intersection(members: Type[]): IntersectionType { 570 | return { 571 | kind: 'intersection', 572 | members 573 | }; 574 | }, 575 | 576 | typeof(type: NamedTypeReference): TypeofReference { 577 | return { 578 | kind: 'typeof', 579 | type 580 | }; 581 | }, 582 | 583 | tripleSlashReferencePathDirective(path: string): TripleSlashReferencePathDirective { 584 | return { 585 | kind: "triple-slash-reference-path", 586 | path 587 | }; 588 | }, 589 | 590 | tripleSlashReferenceTypesDirective(types: string): TripleSlashReferenceTypesDirective { 591 | return { 592 | kind: "triple-slash-reference-types", 593 | types 594 | }; 595 | }, 596 | 597 | tripleSlashReferenceNoDefaultLibDirective(value: boolean = true): TripleSlashReferenceNoDefaultLibDirective { 598 | return { 599 | kind: "triple-slash-reference-no-default-lib", 600 | value 601 | }; 602 | }, 603 | 604 | tripleSlashAmdModuleDirective(name?: string): TripleSlashAmdModuleDirective { 605 | return { 606 | kind: "triple-slash-amd-module", 607 | name 608 | }; 609 | } 610 | }; 611 | 612 | export const type = { 613 | array(type: Type): ArrayTypeReference { 614 | return { 615 | kind: "array", 616 | type 617 | } 618 | }, 619 | stringLiteral(string: string): PrimitiveType { 620 | return { 621 | kind: "string-literal", 622 | value: string 623 | } 624 | }, 625 | numberLiteral(number: number): PrimitiveType { 626 | return { 627 | kind: "number-literal", 628 | value: number 629 | } 630 | }, 631 | string: "string", 632 | number: "number", 633 | boolean: "boolean", 634 | any: "any", 635 | void: "void", 636 | object: "object", 637 | null: "null", 638 | undefined: "undefined", 639 | true: "true", 640 | false: "false", 641 | this: "this" 642 | }; 643 | 644 | export const reservedWords = ['abstract', 'await', 'boolean', 'break', 'byte', 'case', 645 | 'catch', 'char', 'class', 'const', 'continue', 'debugger', 'default', 646 | 'delete', 'do', 'double', 'else', 'enum', 'export', 'extends', 'false', 647 | 'final', 'finally', 'float', 'for', 'function', 'goto', 'if', 'implements', 648 | 'import', 'in', 'instanceof', 'int', 'interface', 'let', 'long', 'native', 649 | 'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'short', 650 | 'static', 'super', 'switch', 'synchronized', 'this', 'throw', 'throws', 651 | 'transient', 'true', 'try', 'typeof', 'var', 'void', 'volatile', 'while', 'with', 'yield']; 652 | 653 | /** IdentifierName can be written as unquoted property names, but may be reserved words. */ 654 | export function isIdentifierName(s: string) { 655 | return /^[$A-Z_][0-9A-Z_$]*$/i.test(s); 656 | } 657 | 658 | /** Identifiers are e.g. legal variable names. They may not be reserved words */ 659 | export function isIdentifier(s: string) { 660 | return isIdentifierName(s) && reservedWords.indexOf(s) < 0; 661 | } 662 | 663 | function quoteIfNeeded(s: string) { 664 | if (isIdentifierName(s)) { 665 | return s; 666 | } else { 667 | // JSON.stringify handles escaping quotes for us. Handy! 668 | return JSON.stringify(s); 669 | } 670 | } 671 | 672 | export enum ContextFlags { 673 | None = 0, 674 | Module = 1 << 0, 675 | InAmbientNamespace = 1 << 1 676 | } 677 | 678 | export function never(x: never, err: string): never { 679 | throw new Error(err); 680 | } 681 | 682 | export interface EmitOptions { 683 | rootFlags?: ContextFlags; 684 | tripleSlashDirectives?: TripleSlashDirective[]; 685 | singleLineJsDocComments?: boolean; 686 | } 687 | 688 | export function emit(rootDecl: TopLevelDeclaration, { rootFlags = ContextFlags.None, tripleSlashDirectives = [], singleLineJsDocComments = false }: EmitOptions = {}): string { 689 | let output = ""; 690 | let indentLevel = 0; 691 | const isModuleWithModuleFlag = rootDecl.kind === 'module' && rootFlags === ContextFlags.Module; 692 | // For a module root declaration we must omit the module flag. 693 | const contextStack: ContextFlags[] = isModuleWithModuleFlag ? [] : [rootFlags]; 694 | 695 | tripleSlashDirectives.forEach(writeTripleSlashDirective); 696 | 697 | writeDeclaration(rootDecl); 698 | newline(); 699 | return output; 700 | 701 | function getContextFlags() { 702 | return contextStack.reduce((a, b) => a | b, ContextFlags.None); 703 | } 704 | 705 | function tab() { 706 | for (let i = 0; i < indentLevel; i++) { 707 | output = output + ' '; 708 | } 709 | } 710 | 711 | function print(s: string) { 712 | output = output + s; 713 | } 714 | 715 | function start(s: string) { 716 | tab(); 717 | print(s); 718 | } 719 | 720 | function classFlagsToString(flags: DeclarationFlags | undefined = DeclarationFlags.None): string { 721 | let out = ''; 722 | 723 | if (flags && flags & DeclarationFlags.Abstract) { 724 | out += 'abstract '; 725 | } 726 | 727 | return out; 728 | } 729 | 730 | function memberFlagsToString(flags: DeclarationFlags | undefined = DeclarationFlags.None): string { 731 | let out = ''; 732 | 733 | if (flags & DeclarationFlags.Private) { 734 | out += 'private '; 735 | } 736 | else if (flags & DeclarationFlags.Protected) { 737 | out += 'protected '; 738 | } 739 | 740 | if (flags & DeclarationFlags.Static) { 741 | out += 'static '; 742 | } 743 | 744 | if (flags & DeclarationFlags.Abstract) { 745 | out += 'abstract '; 746 | } 747 | 748 | if (flags & DeclarationFlags.ReadOnly) { 749 | out += 'readonly '; 750 | } 751 | 752 | return out; 753 | } 754 | 755 | function startWithDeclareOrExport(s: string, flags: DeclarationFlags | undefined = DeclarationFlags.None) { 756 | if (getContextFlags() & ContextFlags.InAmbientNamespace) { 757 | // Already in an all-export context 758 | start(s); 759 | } else if (flags & DeclarationFlags.Export) { 760 | start(`export ${s}`); 761 | } else if (flags & DeclarationFlags.ExportDefault) { 762 | start(`export default ${s}`); 763 | } else if (getContextFlags() & ContextFlags.Module) { 764 | start(s); 765 | } else { 766 | start(`declare ${s}`); 767 | } 768 | } 769 | 770 | function newline() { 771 | output = output + config.outputEol; 772 | } 773 | 774 | function needsParens(d: Type) { 775 | if (typeof d === 'string') { 776 | return false; 777 | } 778 | switch (d.kind) { 779 | case "array": 780 | case "alias": 781 | case "interface": 782 | case "class": 783 | case "union": 784 | return true; 785 | default: 786 | return false; 787 | } 788 | } 789 | 790 | function printDeclarationComments(decl: DeclarationBase) { 791 | if (decl.comment) { 792 | start(`// ${decl.comment}`); 793 | newline(); 794 | } 795 | 796 | 797 | if (decl.jsDocComment) { 798 | if (singleLineJsDocComments && decl.jsDocComment.split(/\r?\n/g).length === 1) { 799 | start('/** '); 800 | print(decl.jsDocComment.split(/\r?\n/g)[0]); 801 | print(' */'); 802 | } 803 | else if (config.wrapJsDocComments) { 804 | start('/**'); 805 | newline(); 806 | for (const line of decl.jsDocComment.split(/\r?\n/g)) { 807 | start(` * ${line}`); 808 | newline(); 809 | } 810 | start(' */'); 811 | } 812 | else { 813 | start(decl.jsDocComment); 814 | } 815 | 816 | newline(); 817 | } 818 | } 819 | 820 | function hasFlag(haystack: T | undefined, needle: T): boolean; 821 | function hasFlag(haystack: number | undefined, needle: number) { 822 | if (haystack === undefined) { 823 | return false; 824 | } 825 | return !!(needle & haystack); 826 | } 827 | 828 | function printObjectTypeMembers(members: ObjectTypeMember[]) { 829 | print('{'); 830 | newline(); 831 | indentLevel++; 832 | for (const member of members) { 833 | printMember(member); 834 | } 835 | indentLevel--; 836 | tab(); 837 | print('}'); 838 | 839 | function printMember(member: ObjectTypeMember) { 840 | switch (member.kind) { 841 | case 'index-signature': 842 | printDeclarationComments(member); 843 | tab(); 844 | print(`[${member.name}: `); 845 | writeReference(member.indexType); 846 | print(']: '); 847 | writeReference(member.valueType); 848 | print(';'); 849 | newline(); 850 | return; 851 | case "call-signature": { 852 | printDeclarationComments(member); 853 | tab(); 854 | writeTypeParameters(member.typeParameters); 855 | print("("); 856 | writeDelimited(member.parameters, ', ', writeParameter); 857 | print("): "); 858 | writeReference(member.returnType); 859 | print(";"); 860 | newline(); 861 | return; 862 | } 863 | case 'method': 864 | printDeclarationComments(member); 865 | tab(); 866 | print(quoteIfNeeded(member.name)); 867 | if (hasFlag(member.flags, DeclarationFlags.Optional)) print('?'); 868 | writeTypeParameters(member.typeParameters); 869 | print('('); 870 | let first = true; 871 | for (const param of member.parameters) { 872 | if (!first) print(', '); 873 | first = false; 874 | writeParameter(param); 875 | } 876 | print('): '); 877 | writeReference(member.returnType); 878 | print(';'); 879 | newline(); 880 | return; 881 | case 'property': 882 | printDeclarationComments(member); 883 | tab(); 884 | if (hasFlag(member.flags, DeclarationFlags.ReadOnly)) print('readonly '); 885 | print(quoteIfNeeded(member.name)); 886 | if (hasFlag(member.flags, DeclarationFlags.Optional)) print('?'); 887 | print(': '); 888 | writeReference(member.type); 889 | print(';'); 890 | newline(); 891 | return; 892 | } 893 | } 894 | } 895 | 896 | function writeUnionReference(d: Type) { 897 | if (typeof d !== "string" && d.kind === "function-type") { 898 | print('(') 899 | writeReference(d) 900 | print(')') 901 | } else { 902 | writeReference(d) 903 | } 904 | } 905 | 906 | function writeReference(d: Type) { 907 | if (typeof d === 'string') { 908 | print(d); 909 | } else { 910 | const e = d; 911 | switch (e.kind) { 912 | case "type-parameter": 913 | case "class": 914 | case "interface": 915 | case "alias": 916 | print(e.name); 917 | break; 918 | 919 | case "name": 920 | print(e.name); 921 | writeTypeArguments(e.typeArguments); 922 | break; 923 | 924 | case "array": 925 | if (needsParens(e.type)) print('('); 926 | writeReference(e.type); 927 | if (needsParens(e.type)) print(')'); 928 | print('[]'); 929 | break; 930 | 931 | case "object": 932 | printObjectTypeMembers(e.members); 933 | break; 934 | 935 | case "string-literal": 936 | print(JSON.stringify(e.value)); 937 | break; 938 | 939 | case "number-literal": 940 | if (isNaN(e.value)) print("typeof NaN"); 941 | else if (!isFinite(e.value)) print("typeof Infinity"); 942 | else print(e.value.toString()); 943 | break; 944 | 945 | case "function-type": 946 | writeFunctionType(e); 947 | break; 948 | 949 | case "union": 950 | writeDelimited(e.members, ' | ', writeUnionReference); 951 | break; 952 | 953 | case "intersection": 954 | writeDelimited(e.members, ' & ', writeUnionReference) 955 | break; 956 | 957 | case "typeof": 958 | print("typeof "); 959 | writeReference(e.type); 960 | break; 961 | 962 | default: 963 | throw new Error(`Unknown kind ${d.kind}`); 964 | } 965 | 966 | } 967 | } 968 | 969 | function writeTypeParameters(params: TypeParameter[]) { 970 | if (params.length === 0) return; 971 | 972 | print('<'); 973 | 974 | let first = true; 975 | 976 | for (const p of params) { 977 | if (!first) print(', '); 978 | 979 | print(p.name); 980 | 981 | if (p.baseType) { 982 | print(' extends '); 983 | 984 | if (isPrimitiveType(p.baseType)) 985 | print(String(p.baseType)); 986 | else if (p.baseType.kind === 'type-parameter') 987 | print(p.baseType.name); 988 | else 989 | writeReference(p.baseType); 990 | } 991 | 992 | if (p.defaultType) { 993 | print(' = '); 994 | writeReference(p.defaultType); 995 | } 996 | 997 | first = false; 998 | } 999 | 1000 | print('>'); 1001 | } 1002 | 1003 | function writeTypeArguments(args: Type[]) { 1004 | if (args.length === 0) return; 1005 | 1006 | print('<'); 1007 | 1008 | let first = true; 1009 | 1010 | for (const p of args) { 1011 | if (!first) print(', '); 1012 | 1013 | writeReference(p); 1014 | 1015 | first = false; 1016 | } 1017 | 1018 | print('>'); 1019 | } 1020 | 1021 | 1022 | 1023 | function writeType(d: TypeDeclaration) { 1024 | startWithDeclareOrExport(`type `); 1025 | print(d.name); 1026 | print(' = '); 1027 | writeReference(d.type) 1028 | newline(); 1029 | } 1030 | 1031 | function writeInterface(d: InterfaceDeclaration) { 1032 | printDeclarationComments(d); 1033 | 1034 | startWithDeclareOrExport(`interface `, d.flags); 1035 | print(d.name); 1036 | writeTypeParameters(d.typeParameters); 1037 | if (d.baseTypes && d.baseTypes.length) { 1038 | print(`extends `); 1039 | let first = true; 1040 | for (const baseType of d.baseTypes) { 1041 | if (!first) print(', '); 1042 | writeReference(baseType); 1043 | first = false; 1044 | } 1045 | } 1046 | print(" "); 1047 | printObjectTypeMembers(d.members); 1048 | newline(); 1049 | } 1050 | 1051 | function writeFunctionType(f: FunctionType) { 1052 | writeTypeParameters(f.typeParameters); 1053 | print('('); 1054 | writeDelimited(f.parameters, ', ', writeParameter); 1055 | print(')'); 1056 | print('=>'); 1057 | writeReference(f.returnType); 1058 | } 1059 | 1060 | function writeFunction(f: FunctionDeclaration) { 1061 | printDeclarationComments(f); 1062 | if (!isIdentifier(f.name)) { 1063 | start(`/* Illegal function name '${f.name}' can't be used here`); 1064 | newline(); 1065 | } 1066 | 1067 | startWithDeclareOrExport(`function ${f.name}`, f.flags); 1068 | writeTypeParameters(f.typeParameters); 1069 | print('(') 1070 | writeDelimited(f.parameters, ', ', writeParameter); 1071 | print('): '); 1072 | writeReference(f.returnType); 1073 | print(';'); 1074 | newline(); 1075 | 1076 | if (!isIdentifier(f.name)) { 1077 | start(`*/`); 1078 | newline(); 1079 | } 1080 | } 1081 | 1082 | function writeParameter(p: Parameter) { 1083 | const flags = p.flags || DeclarationFlags.None; 1084 | print(`${flags & ParameterFlags.Rest ? '...' : ''}${p.name}${flags & ParameterFlags.Optional ? '?' : ''}: `); 1085 | writeReference(p.type); 1086 | } 1087 | 1088 | function writeDelimited(arr: T[], sep: string, printer: (x: T) => void) { 1089 | let first = true; 1090 | for (const el of arr) { 1091 | if (!first) { 1092 | print(sep); 1093 | } 1094 | printer(el); 1095 | first = false; 1096 | } 1097 | } 1098 | 1099 | function writeClass(c: ClassDeclaration) { 1100 | printDeclarationComments(c); 1101 | startWithDeclareOrExport(`${classFlagsToString(c.flags)}class ${c.name}`, c.flags); 1102 | writeTypeParameters(c.typeParameters); 1103 | if (c.baseType) { 1104 | print(' extends '); 1105 | writeReference(c.baseType); 1106 | } 1107 | if (c.implements && c.implements.length) { 1108 | print(' implements '); 1109 | let first = true; 1110 | for (const impl of c.implements) { 1111 | if (!first) print(', '); 1112 | writeReference(impl); 1113 | first = false; 1114 | } 1115 | } 1116 | print(' {'); 1117 | newline(); 1118 | indentLevel++; 1119 | for (const m of c.members) { 1120 | writeClassMember(m); 1121 | newline(); 1122 | } 1123 | indentLevel--; 1124 | start('}'); 1125 | newline(); 1126 | } 1127 | 1128 | function writeClassMember(c: ClassMember) { 1129 | switch (c.kind) { 1130 | case "property": 1131 | return writePropertyDeclaration(c); 1132 | case "method": 1133 | return writeMethodDeclaration(c); 1134 | case "constructor": 1135 | return writeConstructorDeclaration(c); 1136 | } 1137 | } 1138 | 1139 | function writeConstructorDeclaration(ctor: ConstructorDeclaration) { 1140 | printDeclarationComments(ctor); 1141 | start('constructor('); 1142 | writeDelimited(ctor.parameters, ', ', writeParameter); 1143 | print(');') 1144 | newline(); 1145 | } 1146 | 1147 | function writePropertyDeclaration(p: PropertyDeclaration) { 1148 | printDeclarationComments(p); 1149 | start(`${memberFlagsToString(p.flags)}${quoteIfNeeded(p.name)}: `); 1150 | writeReference(p.type); 1151 | print(';'); 1152 | newline(); 1153 | } 1154 | 1155 | function writeMethodDeclaration(m: MethodDeclaration) { 1156 | printDeclarationComments(m); 1157 | start(`${memberFlagsToString(m.flags)}${quoteIfNeeded(m.name)}`); 1158 | writeTypeParameters(m.typeParameters); 1159 | print('('); 1160 | writeDelimited(m.parameters, ', ', writeParameter); 1161 | print('): '); 1162 | writeReference(m.returnType); 1163 | print(';'); 1164 | newline(); 1165 | } 1166 | 1167 | function writeNamespace(ns: NamespaceDeclaration) { 1168 | printDeclarationComments(ns); 1169 | startWithDeclareOrExport(`namespace ${ns.name} {`, ns.flags); 1170 | contextStack.push(ContextFlags.InAmbientNamespace); 1171 | newline(); 1172 | indentLevel++; 1173 | for (const member of ns.members) { 1174 | writeDeclaration(member); 1175 | newline(); 1176 | } 1177 | indentLevel--; 1178 | start(`}`); 1179 | contextStack.pop(); 1180 | newline(); 1181 | } 1182 | 1183 | function writeConst(c: ConstDeclaration) { 1184 | printDeclarationComments(c); 1185 | startWithDeclareOrExport(`const ${c.name}: `, c.flags); 1186 | writeReference(c.type); 1187 | print(';'); 1188 | newline(); 1189 | } 1190 | 1191 | function writeVar(c: VariableDeclaration) { 1192 | printDeclarationComments(c); 1193 | startWithDeclareOrExport(`var ${c.name}: `, c.flags); 1194 | writeReference(c.type); 1195 | print(';'); 1196 | newline(); 1197 | } 1198 | 1199 | function writeAlias(a: TypeAliasDeclaration) { 1200 | printDeclarationComments(a); 1201 | startWithDeclareOrExport(`type ${a.name}`, a.flags); 1202 | writeTypeParameters(a.typeParameters); 1203 | print(' = '); 1204 | writeReference(a.type); 1205 | print(';'); 1206 | newline(); 1207 | } 1208 | 1209 | function writeExportEquals(e: ExportEqualsDeclaration) { 1210 | start(`export = ${e.target};`); 1211 | newline(); 1212 | } 1213 | 1214 | function writeExportDefault(e: ExportDefaultDeclaration) { 1215 | start(`export default ${e.name};`); 1216 | newline(); 1217 | } 1218 | 1219 | function writeExportName(e: ExportNameDeclaration) { 1220 | start(`export { ${e.name}`); 1221 | if (e.as) { 1222 | print(` as ${e.as}`); 1223 | } 1224 | print(' };'); 1225 | newline(); 1226 | } 1227 | 1228 | function writeModule(m: ModuleDeclaration) { 1229 | printDeclarationComments(m); 1230 | startWithDeclareOrExport(`module '${m.name}' {`, m.flags); 1231 | contextStack.push(ContextFlags.Module); 1232 | newline(); 1233 | indentLevel++; 1234 | for (const member of m.members) { 1235 | writeDeclaration(member); 1236 | newline(); 1237 | } 1238 | indentLevel--; 1239 | start(`}`); 1240 | contextStack.pop(); 1241 | newline(); 1242 | } 1243 | 1244 | function writeImportAll(i: ImportAllDeclaration) { 1245 | start(`import * as ${i.name} from '${i.from}';`); 1246 | newline(); 1247 | } 1248 | 1249 | function writeImportDefault(i: ImportDefaultDeclaration) { 1250 | start(`import ${i.name} from '${i.from}';`); 1251 | newline(); 1252 | } 1253 | 1254 | function writeImportNamed(i: ImportNamedDeclaration) { 1255 | start(`import {${i.name}`); 1256 | if (i.as) { 1257 | print(` as ${i.as}`); 1258 | } 1259 | print(`} from '${i.from}';`); 1260 | newline(); 1261 | } 1262 | 1263 | function writeImportEquals(i: ImportEqualsDeclaration) { 1264 | start(`import ${i.name} = require('${i.from}');`); 1265 | newline(); 1266 | } 1267 | 1268 | function writeImport(i: ImportDeclaration) { 1269 | start(`import '${i.from}';`); 1270 | newline(); 1271 | } 1272 | 1273 | 1274 | function writeEnum(e: EnumDeclaration) { 1275 | printDeclarationComments(e); 1276 | startWithDeclareOrExport(`${e.constant ? 'const ' : ''}enum ${e.name} {`, e.flags); 1277 | newline(); 1278 | indentLevel++; 1279 | for (const member of e.members) { 1280 | writeEnumValue(member); 1281 | } 1282 | indentLevel--; 1283 | start(`}`); 1284 | newline(); 1285 | } 1286 | 1287 | function writeEnumValue(e: EnumMemberDeclaration) { 1288 | printDeclarationComments(e); 1289 | start(e.name); 1290 | 1291 | if (e.value !== undefined) { 1292 | if (typeof e.value === 'string') { 1293 | print(` = "${e.value}"`); 1294 | } else { 1295 | print(` = ${e.value}`); 1296 | } 1297 | } 1298 | 1299 | print(','); 1300 | newline(); 1301 | } 1302 | 1303 | function writeTripleSlashDirective(t: TripleSlashDirective) { 1304 | const type = t.kind === "triple-slash-amd-module" ? "amd-module" : "reference"; 1305 | start(`/// <${type}`); 1306 | 1307 | switch (t.kind) { 1308 | case "triple-slash-reference-path": 1309 | print(` path="${t.path}"`); 1310 | break; 1311 | case "triple-slash-reference-types": 1312 | print(` types="${t.types}"`); 1313 | break; 1314 | case "triple-slash-reference-no-default-lib": 1315 | print(` no-default-lib="${t.value}"`); 1316 | break; 1317 | case "triple-slash-amd-module": 1318 | if (t.name) { 1319 | print(` name="${t.name}"`); 1320 | } 1321 | break; 1322 | default: 1323 | never(t, `Unknown triple slash directive kind ${(t as TripleSlashDirective).kind}`); 1324 | } 1325 | 1326 | print(" />"); 1327 | newline(); 1328 | } 1329 | 1330 | function writeDeclaration(d: TopLevelDeclaration) { 1331 | if (typeof d === 'string') { 1332 | return print(d); 1333 | } else { 1334 | switch (d.kind) { 1335 | case "interface": 1336 | return writeInterface(d); 1337 | case "function": 1338 | return writeFunction(d); 1339 | case "class": 1340 | return writeClass(d); 1341 | case "namespace": 1342 | return writeNamespace(d); 1343 | case "const": 1344 | return writeConst(d); 1345 | case "var": 1346 | return writeVar(d); 1347 | case "alias": 1348 | return writeAlias(d); 1349 | case "export=": 1350 | return writeExportEquals(d); 1351 | case "exportDefault": 1352 | return writeExportDefault(d); 1353 | case "exportName": 1354 | return writeExportName(d); 1355 | case "module": 1356 | return writeModule(d); 1357 | case "importAll": 1358 | return writeImportAll(d); 1359 | case "importDefault": 1360 | return writeImportDefault(d); 1361 | case "importNamed": 1362 | return writeImportNamed(d); 1363 | case "import=": 1364 | return writeImportEquals(d); 1365 | case "import": 1366 | return writeImport(d); 1367 | case "enum": 1368 | return writeEnum(d); 1369 | case "type": 1370 | return writeType(d); 1371 | // case "array": 1372 | // return writeArray(d); 1373 | default: 1374 | return never(d, `Unknown declaration kind ${(d as TopLevelDeclaration).kind}`); 1375 | } 1376 | } 1377 | } 1378 | } 1379 | -------------------------------------------------------------------------------- /packages/vscode/images/typescript.svg: -------------------------------------------------------------------------------- 1 | --------------------------------------------------------------------------------