From 13947f9dfc64d63fa8e1f8e5815da9249b855b63 Mon Sep 17 00:00:00 2001 From: Pedro Nauck Date: Sat, 15 Jun 2019 15:02:22 -0300 Subject: [PATCH] feat: add typescript support (need fix) --- core/docz-core/src/bundler/server.ts | 35 ++++++----- core/docz-core/src/config/paths.ts | 2 +- .../docz-core/src/machines/devServer/index.ts | 61 +++++++++---------- .../devServer/services/createResources.ts | 13 +--- core/docz-core/src/utils/docgen/typescript.ts | 38 +++++++----- core/docz-core/templates/gatsby-config.tpl.js | 15 ++++- core/docz-core/templates/gatsby-html.tpl.js | 48 --------------- core/docz-core/templates/gatsby-node.tpl.js | 12 ++-- core/docz-rollup/package.json | 2 +- .../src/components/ui/Playground/index.tsx | 2 +- core/docz/package.json | 4 +- core/docz/src/components/Props.tsx | 4 +- core/docz/src/utils/createState.tsx | 2 +- core/gatsby-theme-docz/package.json | 2 +- examples/gatsby/package.json | 2 +- examples/typescript/doczrc.js | 1 + examples/typescript/package.json | 2 +- examples/typescript/src/components/Alert.mdx | 12 ---- .../eslint-plugin-docz/package.json | 2 +- package.json | 6 +- yarn.lock | 49 ++++++++------- 21 files changed, 140 insertions(+), 174 deletions(-) delete mode 100644 core/docz-core/templates/gatsby-html.tpl.js diff --git a/core/docz-core/src/bundler/server.ts b/core/docz-core/src/bundler/server.ts index 4625d52b8..fe3e30b93 100644 --- a/core/docz-core/src/bundler/server.ts +++ b/core/docz-core/src/bundler/server.ts @@ -6,20 +6,25 @@ import { Config as Args } from '../config/argv' import { ServerHooks as Hooks } from '../lib/Bundler' import { devServerMachine } from '../machines/devServer' -export const server = (args: Args) => async (config: any, hooks: Hooks) => ({ - start: async () => { - const doczrcFilepath = await findUp(finds('docz')) - const machine = devServerMachine.withContext({ - args, - config, - doczrcFilepath, - }) +export const server = (args: Args) => async (config: any, hooks: Hooks) => { + const doczrcFilepath = await findUp(finds('docz')) + const machine = devServerMachine.withContext({ + args, + config, + doczrcFilepath, + }) - const service = interpret(machine).onTransition(state => { - args.debug && console.log(state.value) - }) + const service = interpret(machine).onTransition(state => { + args.debug && console.log(state.value) + }) - service.start() - service.send('INITIALIZE') - }, -}) + return { + start: async () => { + service.start() + service.send('START_MACHINE') + process.on('exit', () => { + service.stop() + }) + }, + } +} diff --git a/core/docz-core/src/config/paths.ts b/core/docz-core/src/config/paths.ts index 0c705fb53..16622344d 100644 --- a/core/docz-core/src/config/paths.ts +++ b/core/docz-core/src/config/paths.ts @@ -62,8 +62,8 @@ export const servedPath = (base: string) => ensureSlash(base, true) const IS_DOCZ_PROJECT = path.parse(root).base === '.docz' export const docz = resolveApp(IS_DOCZ_PROJECT ? './' : '.docz') +export const cache = path.resolve(docz, '.cache/') export const app = path.resolve(docz, 'app/') -export const cache = path.resolve(docz, 'cache/') export const appPublic = path.resolve(docz, 'public/') export const appNodeModules = resolveApp('node_modules') export const appPackageJson = resolveApp('package.json') diff --git a/core/docz-core/src/machines/devServer/index.ts b/core/docz-core/src/machines/devServer/index.ts index 012624612..235645948 100644 --- a/core/docz-core/src/machines/devServer/index.ts +++ b/core/docz-core/src/machines/devServer/index.ts @@ -4,6 +4,29 @@ import { ServerMachineCtx } from './context' import * as services from './services' import * as actions from './actions' +const asyncState = (src: string, onDoneTarget?: string) => ({ + initial: 'exec', + states: { + exec: { + invoke: { + src, + onDone: 'success', + onError: 'failure', + }, + }, + success: { + type: 'final', + }, + failure: { + actions: ['logError'], + type: 'final', + }, + }, + onDone: { + target: onDoneTarget || 'exit', + }, +}) + const machine = Machine({ id: 'devServer', type: 'parallel', @@ -18,43 +41,17 @@ const machine = Machine({ states: { idle: { on: { - INITIALIZE: { + START_MACHINE: { actions: ['assignFirstInstall', 'checkIsDoczRepo'], target: 'ensuringDirs', }, }, }, - ensuringDirs: { - invoke: { - src: 'ensureDirs', - onDone: 'creatingResources', - }, - }, - creatingResources: { - invoke: { - src: 'createResources', - onDone: 'installingDeps', - onError: 'exiting', - }, - }, - installingDeps: { - invoke: { - src: 'installDeps', - onDone: 'executingCommand', - onError: 'exiting', - }, - }, - executingCommand: { - invoke: { - src: 'execDevCommand', - // onDone: { - // actions: 'openBrowser', - // }, - onError: 'exiting', - }, - }, - exiting: { - onEntry: 'logError', + ensuringDirs: asyncState('ensureDirs', 'creatingResources'), + creatingResources: asyncState('createResources', 'installingDeps'), + installingDeps: asyncState('installDeps', 'executingCommand'), + executingCommand: asyncState('execDevCommand'), + exit: { type: 'final', }, }, diff --git a/core/docz-core/src/machines/devServer/services/createResources.ts b/core/docz-core/src/machines/devServer/services/createResources.ts index ab46346cc..bd05ae35a 100644 --- a/core/docz-core/src/machines/devServer/services/createResources.ts +++ b/core/docz-core/src/machines/devServer/services/createResources.ts @@ -11,7 +11,7 @@ import { ServerMachineCtx } from '../context' import { outputFileFromTemplate } from '../../../utils/template' const REQUIRED_DEPS = ['react', 'react-dom'] -const REQUIRED_DEV_DEPS = ['gatsby', 'gatsby-mdx'] +const REQUIRED_DEV_DEPS = ['gatsby', 'gatsby-mdx', 'gatsby-plugin-typescript'] const CORE_DEV_DEPS = ['docz', 'docz-theme-default', 'gatsby-theme-docz'] const LOCAL_DEV_DEPS = [ @@ -107,10 +107,7 @@ const writeConfigFile = async ({ args, isDoczRepo }: ServerMachineCtx) => { await outputFileFromTemplate('gatsby-config.tpl.js', outputPath, { isDoczRepo, - config: JSON.stringify({ - ...args, - root: paths.docz, - }), + config: JSON.stringify({ ...args, root: paths.docz }), }) } @@ -124,15 +121,9 @@ const writeGatsbyNode = async () => { await outputFileFromTemplate('gatsby-node.tpl.js', outputPath) } -const writeGatsbyHTML = async () => { - const outputPath = path.join(paths.docz, 'src/html.js') - await outputFileFromTemplate('gatsby-html.tpl.js', outputPath) -} - const fixDuplicatedReact = async ({ isDoczRepo }: ServerMachineCtx) => { if (!isDoczRepo) return await writeGatsbyNode() - await writeGatsbyHTML() } export const createResources = async (ctx: ServerMachineCtx) => { diff --git a/core/docz-core/src/utils/docgen/typescript.ts b/core/docz-core/src/utils/docgen/typescript.ts index 41aa39ce4..9c4f235bb 100644 --- a/core/docz-core/src/utils/docgen/typescript.ts +++ b/core/docz-core/src/utils/docgen/typescript.ts @@ -28,22 +28,26 @@ const digest = (str: string) => const cacheFilepath = path.join(paths.cache, 'propsParser.json') const readCacheFile = () => fs.readJSONSync(cacheFilepath, { throws: false }) -function checkFilesOnCache(files: string[]): string[] { +function checkFilesOnCache(files: string[], config: Config): string[] { const cache = readCacheFile() + const root = paths.getRootDir(config) if (_.isEmpty(cache)) return files return files.filter(filepath => { const normalized = path.normalize(filepath) - const hash = digest(fs.readFileSync(normalized, 'utf-8')) + const fullpath = path.resolve(root, normalized) + const hash = digest(fs.readFileSync(fullpath, 'utf-8')) const found = _.get(normalized, cache) return found && hash !== found.hash }) } -function writePropsOnCache(items: PropItem[]): void { +function writePropsOnCache(items: PropItem[], config: Config): void { const cache = readCacheFile() + const root = paths.getRootDir(config) const newCache = items.reduce((obj, { key: filepath, value }) => { const normalized = path.normalize(filepath) - const hash = digest(fs.readFileSync(normalized, 'utf-8')) + const fullpath = path.resolve(root, normalized) + const hash = digest(fs.readFileSync(fullpath, 'utf-8')) return { ...obj, [normalized]: { hash, props: value } } }, {}) @@ -108,12 +112,14 @@ function getTSConfigFile(tsconfigPath: string): ts.ParsedCommandLine { ) } -function loadFiles(filesToLoad: string[]): void { +function loadFiles(filesToLoad: string[], config: Config): void { + const root = paths.getRootDir(config) filesToLoad.forEach(filepath => { const normalized = path.normalize(filepath) + const fullpath = path.resolve(root, normalized) const found = filesMap.get(normalized) filesMap.set(normalized, { - text: fs.readFileSync(normalized, 'utf-8'), + text: fs.readFileSync(fullpath, 'utf-8'), version: found ? found.version + 1 : 0, }) }) @@ -121,8 +127,10 @@ function loadFiles(filesToLoad: string[]): void { function createServiceHost( compilerOptions: ts.CompilerOptions, - files: Map + files: Map, + config: Config ): ts.LanguageServiceHost { + const root = paths.getRootDir(config) return { getScriptFileNames: () => { return [...files.keys()] @@ -132,14 +140,14 @@ function createServiceHost( return (file && file.version.toString()) || '' }, getScriptSnapshot: fileName => { - if (!fs.existsSync(fileName)) { + const fullpath = path.resolve(root, fileName) + if (!fs.existsSync(fullpath)) { return undefined } let file = files.get(fileName) - if (file === undefined) { - const text = fs.readFileSync(fileName).toString() + const text = fs.readFileSync(fullpath).toString() file = { version: 0, text } files.set(fileName, file) @@ -147,7 +155,7 @@ function createServiceHost( return ts.ScriptSnapshot.fromString(file!.text!) }, - getCurrentDirectory: () => process.cwd(), + getCurrentDirectory: () => root, getCompilationSettings: () => compilerOptions, getDefaultLibFileName: options => ts.getDefaultLibFilePath(options), fileExists: ts.sys.fileExists, @@ -174,13 +182,13 @@ const parseFiles = (files: string[], config: Config, tsconfig: string) => { }, } - loadFiles(files) + loadFiles(files, config) const parser = reactDocgenTs.withCustomConfig(tsconfig, opts) const compilerOptions = _.get('options', getTSConfigFile(tsconfig)) const programProvider = () => { if (languageService) return languageService.getProgram()! - const servicesHost = createServiceHost(compilerOptions, filesMap) + const servicesHost = createServiceHost(compilerOptions, filesMap, config) const documentRegistry = ts.createDocumentRegistry() languageService = ts.createLanguageService(servicesHost, documentRegistry) return languageService.getProgram()! @@ -198,11 +206,11 @@ export const tsParser = ( tsconfig?: string ) => { if (!tsconfig) return null - const filesToLoad = checkFilesOnCache(files) + const filesToLoad = checkFilesOnCache(files, config) const propsOnCache = getPropsOnCache() if (!filesToLoad.length) return propsOnCache const next = parseFiles(filesToLoad, config, tsconfig) - writePropsOnCache(next) + writePropsOnCache(next, config) return mergeWithCache(propsOnCache, next) } diff --git a/core/docz-core/templates/gatsby-config.tpl.js b/core/docz-core/templates/gatsby-config.tpl.js index ba6d351bf..968fb1222 100644 --- a/core/docz-core/templates/gatsby-config.tpl.js +++ b/core/docz-core/templates/gatsby-config.tpl.js @@ -5,8 +5,9 @@ module.exports = { }, __experimentalThemes: [ { resolve: 'gatsby-theme-docz', options: <%- config %>} - ],<% if (isDoczRepo) {%> + ], plugins: [ + <% if (isDoczRepo) {%> { resolve: 'gatsby-plugin-eslint', options: { @@ -25,5 +26,15 @@ module.exports = { modules: ['docz', 'docz-theme-default'], }, }, - ],<%}%> + <%}%> + <% if (config.typescript) {%> + { + resolve: 'gatsby-plugin-typescript', + options: { + isTSX: true, + allExtensions: true + } + } + <%}%> + ], } diff --git a/core/docz-core/templates/gatsby-html.tpl.js b/core/docz-core/templates/gatsby-html.tpl.js deleted file mode 100644 index d86a13167..000000000 --- a/core/docz-core/templates/gatsby-html.tpl.js +++ /dev/null @@ -1,48 +0,0 @@ -import React from 'react' -import PropTypes from 'prop-types' - -export default function HTML(props) { - const bodyHTML = { __html: props.body } - return ( - - - - - - {props.headComponents} -