Skip to content
This repository has been archived by the owner on Jan 24, 2025. It is now read-only.

Commit

Permalink
feat: add typescript support (need fix)
Browse files Browse the repository at this point in the history
  • Loading branch information
pedronauck committed Jun 15, 2019
1 parent 112f4c2 commit 13947f9
Show file tree
Hide file tree
Showing 21 changed files with 140 additions and 174 deletions.
35 changes: 20 additions & 15 deletions core/docz-core/src/bundler/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})
},
}
}
2 changes: 1 addition & 1 deletion core/docz-core/src/config/paths.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
61 changes: 29 additions & 32 deletions core/docz-core/src/machines/devServer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ServerMachineCtx>({
id: 'devServer',
type: 'parallel',
Expand All @@ -18,43 +41,17 @@ const machine = Machine<ServerMachineCtx>({
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',
},
},
Expand Down
13 changes: 2 additions & 11 deletions core/docz-core/src/machines/devServer/services/createResources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down Expand Up @@ -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 }),
})
}

Expand All @@ -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) => {
Expand Down
38 changes: 23 additions & 15 deletions core/docz-core/src/utils/docgen/typescript.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 } }
}, {})

Expand Down Expand Up @@ -108,21 +112,25 @@ 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,
})
})
}

function createServiceHost(
compilerOptions: ts.CompilerOptions,
files: Map<string, TSFile>
files: Map<string, TSFile>,
config: Config
): ts.LanguageServiceHost {
const root = paths.getRootDir(config)
return {
getScriptFileNames: () => {
return [...files.keys()]
Expand All @@ -132,22 +140,22 @@ 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)
}

return ts.ScriptSnapshot.fromString(file!.text!)
},
getCurrentDirectory: () => process.cwd(),
getCurrentDirectory: () => root,
getCompilationSettings: () => compilerOptions,
getDefaultLibFileName: options => ts.getDefaultLibFilePath(options),
fileExists: ts.sys.fileExists,
Expand All @@ -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()!
Expand All @@ -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)
}
15 changes: 13 additions & 2 deletions core/docz-core/templates/gatsby-config.tpl.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ module.exports = {
},
__experimentalThemes: [
{ resolve: 'gatsby-theme-docz', options: <%- config %>}
],<% if (isDoczRepo) {%>
],
plugins: [
<% if (isDoczRepo) {%>
{
resolve: 'gatsby-plugin-eslint',
options: {
Expand All @@ -25,5 +26,15 @@ module.exports = {
modules: ['docz', 'docz-theme-default'],
},
},
],<%}%>
<%}%>
<% if (config.typescript) {%>
{
resolve: 'gatsby-plugin-typescript',
options: {
isTSX: true,
allExtensions: true
}
}
<%}%>
],
}
48 changes: 0 additions & 48 deletions core/docz-core/templates/gatsby-html.tpl.js

This file was deleted.

12 changes: 8 additions & 4 deletions core/docz-core/templates/gatsby-node.tpl.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
const path = require('path')

exports.onCreateWebpackConfig = ({ stage, actions }) => {
if (stage === 'develop') {
actions.setWebpackConfig({
externals: {
react: 'React',
'react-dom': 'ReactDOM',
},
resolve: {
modules: [
path.resolve(__dirname, 'node_modules'),
path.resolve(__dirname, '../../../node_modules'),
]
}
})
}
}
2 changes: 1 addition & 1 deletion core/docz-rollup/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"gzip-size": "^5.1.1",
"lodash": "^4.17.11",
"log-update": "^3.2.0",
"rollup": "^1.15.3",
"rollup": "^1.15.5",
"rollup-plugin-alias": "^1.5.2",
"rollup-plugin-babel": "^4.3.2",
"rollup-plugin-commonjs": "^10.0.0",
Expand Down
Loading

0 comments on commit 13947f9

Please sign in to comment.