Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: start can now watch ts files (#246) #276

Merged
merged 3 commits into from
Oct 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,8 @@ test.sock
# test artifacts
test/workdir
test/fixtures/*.js
test/fixtures/*.ts
.vscode/launch.json

# ts compiled
dist
8 changes: 5 additions & 3 deletions args.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ module.exports = function parseArgs (args) {
},
number: ['port', 'inspect-port', 'body-limit', 'plugin-timeout'],
boolean: ['pretty-logs', 'options', 'watch', 'debug'],
string: ['log-level', 'address', 'socket', 'prefix', 'ignore-watch', 'logging-module', 'debug-host', 'lang'],
string: ['log-level', 'address', 'socket', 'prefix', 'ignore-watch', 'logging-module', 'debug-host', 'lang', 'tsconfig'],
envPrefix: 'FASTIFY_',
alias: {
port: ['p'],
Expand All @@ -35,7 +35,8 @@ module.exports = function parseArgs (args) {
'ignore-watch': 'node_modules build dist .git bower_components logs .swp',
options: false,
'plugin-timeout': 10 * 1000, // everything should load in 10 seconds
lang: 'js'
lang: 'js',
tsconfig: 'tsconfig.json'
}
})

Expand All @@ -61,6 +62,7 @@ module.exports = function parseArgs (args) {
socket: parsedArgs.socket,
prefix: parsedArgs.prefix,
loggingModule: parsedArgs.loggingModule,
lang: parsedArgs.lang
lang: parsedArgs.lang,
tsconfig: parsedArgs.tsconfig
}
}
10 changes: 10 additions & 0 deletions examples/plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { FastifyPluginAsync } from 'fastify'

const root: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
fastify.decorate('test', true)
fastify.get('/', async function (request, reply) {
return { hello: 'world' }
})
}

export default root;
3 changes: 1 addition & 2 deletions generate.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ const typescriptTemplate = {
test: 'npm run build:ts && tsc -p test/tsconfig.test.json && tap test/**/*.test.ts',
start: 'npm run build:ts && fastify start -l info dist/app.js',
'build:ts': 'tsc',
dev: 'tsc && concurrently -k -p "[{name}]" -n "TypeScript,App" -c "yellow.bold,cyan.bold" "tsc -w" "fastify start -w -l info -P dist/app.js"'
dev: 'fastify start -w -l info -P src/app.ts'
},
dependencies: {
fastify: cliPkg.dependencies.fastify,
Expand All @@ -58,7 +58,6 @@ const typescriptTemplate = {
devDependencies: {
'@types/node': cliPkg.devDependencies['@types/node'],
'@types/tap': cliPkg.devDependencies['@types/tap'],
concurrently: cliPkg.devDependencies.concurrently,
'fastify-tsconfig': cliPkg.devDependencies['fastify-tsconfig'],
tap: cliPkg.devDependencies.tap,
typescript: cliPkg.devDependencies.typescript
Expand Down
104 changes: 104 additions & 0 deletions lib/watch/tsc-watcher.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
'use strict'

const ts = require('typescript')
const { EventEmitter } = require('events')
const formatHost = {
getCanonicalFileName: path => path,
getCurrentDirectory: ts.sys.getCurrentDirectory,
getNewLine: () => ts.sys.newLine
}
const { resolve, join, basename, dirname } = require('path')
const cp = require('child_process')
const forkPath = join(__dirname, './fork.js')
const {
GRACEFUL_SHUT
} = require('./constants')
let child

const emitter = new EventEmitter()

function watchMain (args, opts) {
const configPath = ts.findConfigFile(
'./',
ts.sys.fileExists,
opts.tsconfig || 'tsconfig.json'
)

if (!configPath) {
throw new Error('Could not find a valid \'tsconfig.json\'.')
}

const createProgram = ts.createSemanticDiagnosticsBuilderProgram

const host = ts.createWatchCompilerHost(
configPath,
{},
ts.sys,
createProgram,
reportDiagnostic,
reportWatchStatusChanged
)

const origCreateProgram = host.createProgram
host.createProgram = (rootNames, options, host, oldProgram) => {
return origCreateProgram(rootNames, options, host, oldProgram)
}
const origPostProgramCreate = host.afterProgramCreate

const configFile = require(resolve(process.cwd(), configPath))

const appFile = join(resolve(dirname(configPath), configFile.compilerOptions.outDir), basename(opts._[0]).replace(/.ts$/, '.js'))
args.splice(args.length - 1, 1, appFile)

host.afterProgramCreate = program => {
if (child) {
child.send(GRACEFUL_SHUT)
}
origPostProgramCreate(program)

child = cp.fork(forkPath, args, {
cwd: process.cwd(),
encoding: 'utf8'
})
let readyEmitted = false

child.on('message', (event) => {
const { type, err } = event
if (err) {
child.emit('error', err)
return null
}

if (type === 'ready') {
if (readyEmitted) {
return
}

readyEmitted = true
}

emitter.emit(type, err)
})
}

ts.createWatchProgram(host)

return emitter
}

emitter.on('close', () => {
if (child) {
child.kill()
process.exit(0)
}
})

function reportDiagnostic (diagnostic) {
console.log('Error', diagnostic.code, ':', ts.flattenDiagnosticMessageText(diagnostic.messageText, formatHost.getNewLine()))
}

function reportWatchStatusChanged (diagnostic) {
console.info(ts.formatDiagnostic(diagnostic, formatHost))
}

module.exports = watchMain
8 changes: 7 additions & 1 deletion start.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ let Fastify = null

function loadModules (opts) {
try {
const { module: fastifyModule } = requireFastifyForModule(opts._[0])
const app = opts._[0]
const { module: fastifyModule } = requireFastifyForModule(app)

Fastify = fastifyModule
} catch (e) {
Expand All @@ -29,6 +30,7 @@ function loadModules (opts) {

async function start (args) {
const opts = parseArgs(args)

if (opts.help) {
return showHelpForCommand('start')
}
Expand All @@ -41,6 +43,10 @@ async function start (args) {
// we start crashing on unhandledRejection
require('make-promises-safe')

if (path.extname(opts._[0]) === '.ts') {
return require('./lib/watch/tsc-watcher')(args, opts)
}

loadModules(opts)

if (opts.watch) {
Expand Down
2 changes: 1 addition & 1 deletion templates/app-ts/src/routes/example/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { FastifyPluginAsync } from "fastify"

const example: FastifyPluginAsync =async (fastify, opts): Promise<void> => {
const example: FastifyPluginAsync = async (fastify, opts): Promise<void> => {
fastify.get('/', async function (request, reply) {
return 'this is an example'
})
Expand Down
1 change: 1 addition & 0 deletions templates/app-ts/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"extends": "fastify-tsconfig",
"compilerOptions": {
"esModuleInterop": true,
"outDir": "dist"
},
"include": ["src/**/*.ts"]
Expand Down
12 changes: 8 additions & 4 deletions test/args.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@ test('should parse args correctly', t => {
debugPort: 1111,
debugHost: '1.1.1.1',
loggingModule: './custom-logger.js',
lang: 'js'
lang: 'js',
tsconfig: 'tsconfig.json'
})
})

Expand Down Expand Up @@ -90,7 +91,8 @@ test('should parse args with = assignment correctly', t => {
debugPort: 1111,
debugHost: '1.1.1.1',
loggingModule: './custom-logger.js',
lang: 'js'
lang: 'js',
tsconfig: 'tsconfig.json'
})
})

Expand Down Expand Up @@ -151,7 +153,8 @@ test('should parse env vars correctly', t => {
debugPort: 1111,
debugHost: '1.1.1.1',
loggingModule: './custom-logger.js',
lang: 'js'
lang: 'js',
tsconfig: 'tsconfig.json'
})
})

Expand Down Expand Up @@ -230,6 +233,7 @@ test('should parse custom plugin options', t => {
debugPort: 1111,
debugHost: '1.1.1.1',
loggingModule: './custom-logger.js',
lang: 'js'
lang: 'js',
tsconfig: 'tsconfig.json'
})
})
5 changes: 2 additions & 3 deletions test/generate-typescript.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ function define (t) {
})

test('should finish succesfully with typescript template', async (t) => {
t.plan(21 + Object.keys(expected).length)
t.plan(20 + Object.keys(expected).length)
try {
await generate(workdir, typescriptTemplate)
await verifyPkg(t)
Expand Down Expand Up @@ -132,13 +132,12 @@ function define (t) {
t.equal(pkg.scripts.test, 'npm run build:ts && tsc -p test/tsconfig.test.json && tap test/**/*.test.ts')
t.equal(pkg.scripts.start, 'npm run build:ts && fastify start -l info dist/app.js')
t.equal(pkg.scripts['build:ts'], 'tsc')
t.equal(pkg.scripts.dev, 'tsc && concurrently -k -p "[{name}]" -n "TypeScript,App" -c "yellow.bold,cyan.bold" "tsc -w" "fastify start -w -l info -P dist/app.js"')
t.equal(pkg.scripts.dev, 'fastify start -w -l info -P src/app.ts')
t.equal(pkg.dependencies['fastify-cli'], '^' + cliPkg.version)
t.equal(pkg.dependencies.fastify, cliPkg.dependencies.fastify)
t.equal(pkg.dependencies['fastify-plugin'], cliPkg.devDependencies['fastify-plugin'] || cliPkg.dependencies['fastify-plugin'])
t.equal(pkg.dependencies['fastify-autoload'], cliPkg.devDependencies['fastify-autoload'])
t.equal(pkg.devDependencies['@types/node'], cliPkg.devDependencies['@types/node'])
t.equal(pkg.devDependencies.concurrently, cliPkg.devDependencies.concurrently)
t.equal(pkg.devDependencies.tap, cliPkg.devDependencies.tap)
t.equal(pkg.devDependencies.typescript, cliPkg.devDependencies.typescript)

Expand Down
54 changes: 54 additions & 0 deletions test/start-typescript.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
'use strict'

const util = require('util')
const { once } = require('events')
const fs = require('fs')
const crypto = require('crypto')
const { resolve, join } = require('path')
const baseFilename = `${__dirname}/fixtures/test_${crypto.randomBytes(16).toString('hex')}`
const root = join(__dirname, '..')
const t = require('tap')
const test = t.test
const { sgetOriginal } = require('./util')
const sget = util.promisify(sgetOriginal)
const start = require('../start')

test('should start the server with watch options and refresh app instance on directory change', async (t) => {
t.plan(5)

const writeFile = util.promisify(fs.writeFile)
const copyFile = util.promisify(fs.copyFile)
const readFile = util.promisify(fs.readFile)
const tmpts = baseFilename + '.ts'
const example = resolve(__dirname, join(root, 'examples', 'plugin.ts'))

await copyFile(example, tmpts)
t.pass('plugin copied to fixture')

const argv = ['-p', '5001', '-w', '--tsconfig', join(root, 'tsconfig.tswatch.json'), tmpts]
const fastifyEmitter = await start.start(argv)

await once(fastifyEmitter, 'ready')
t.pass('should receive ready event')

t.tearDown(() => {
if (fs.existsSync(tmpts)) {
fs.unlinkSync(tmpts)
}
fastifyEmitter.emit('close')
})

const data = await readFile(tmpts)

await writeFile(tmpts, data.toString().replace(/(world)/ig, 'fastify'))
t.pass('change tmpts')

await once(fastifyEmitter, 'ready')
t.pass('should receive ready after restart')

const { body } = await sget({
method: 'GET',
url: 'http://localhost:5001'
})
t.deepEqual(JSON.parse(body), { hello: 'fastify' })
})
Loading