Skip to content

Commit

Permalink
feat: configs and stuff i dunno
Browse files Browse the repository at this point in the history
  • Loading branch information
timkinnane committed Sep 14, 2022
1 parent c50a495 commit d488958
Show file tree
Hide file tree
Showing 11 changed files with 141 additions and 39 deletions.
9 changes: 3 additions & 6 deletions bin/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,8 @@ const config = esbuild.config({
'src/esbuild/index.ts',
'src/jest/index.ts',
'src/utils/index.ts'
],

]
})

utils.clearPath(config.outdir)
esbuild.build(config).then(() => {
utils.typegen(config.entryPoints)
})
utils.clearPath(config.outdir!)
esbuild.build(config)
45 changes: 29 additions & 16 deletions src/esbuild/build.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,34 @@
import { build as _build, analyzeMetafile, BuildOptions } from 'esbuild'
import { build as _build, analyzeMetafile, BuildOptions, WatchMode } from 'esbuild'
import { mapEntries, writeDefinition } from './definitions'

const watch = process.argv.includes('--watch') || process.argv.includes('-w')
/** Watch mode handler for adding actions on rebuild. */
const handleRebuild: WatchMode['onRebuild'] = async (error, result) => {
if (error) {
console.error('👀❎ Watch build failed:', error)
} else {
const meta = await analyzeMetafile(result!.metafile!)
console.log('👀✅ Watch build succeeded', meta)
}
}

/** Build project with Esbuild. */
export const build = async (opts: BuildOptions = {}) =>
_build({
watch: watch
? {
onRebuild: (error, result) => error
? console.error('👀❎ Watch build failed:', error)
: analyzeMetafile(result!.metafile!).then(
(meta) => console.log('👀✅ Watch build succeeded', meta)
)
}
: false,
...opts
})
/** Build project with ES Build, adds reload handler in watch mode. */
export const build = async (options: BuildOptions = {}) => {
const entries = mapEntries(options)
const writeDefinitions = () => Promise.all(entries.map(writeDefinition))
const watchEnabled =
options.watch ||
process.argv.includes('--watch') ||
process.argv.includes('-w')
const watch: BuildOptions['watch'] = {
onRebuild: async (error, result) => {
await writeDefinitions()
return handleRebuild(error, result)
}
}

return _build({...options, watch: watchEnabled ? watch : undefined })
.then(({ metafile }) => analyzeMetafile(metafile!))
.then(console.log)
.then(writeDefinitions)
.catch(_ => process.exit(1))
}
3 changes: 2 additions & 1 deletion src/esbuild/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ export const defaults: Partial<BuildOptions> = {
target: 'node14',
outdir: 'dist',
bundle: true,
metafile: true
metafile: true,
outExtension: { '.js': '.mjs' }
}

/** Generate ESbuild config, finding dependencies from package. */
Expand Down
36 changes: 36 additions & 0 deletions src/esbuild/definitions.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { mapEntries } from './definitions'

describe('Cogs » esbuild » definitions', () => {
describe('.mapEntries', () => {
it('maps an array of entry points to js out files', () => {
expect(mapEntries({
outdir: 'dist',
entryPoints: [
'src/one/index.ts',
'src/two/index.ts',
]
})/* ? */).toEqual([{
entry: 'src/one/index.ts',
outFile: 'dist/one/index.js'
}, {
entry: 'src/two/index.ts',
outFile: 'dist/two/index.js'
}])
})
it('maps an entry point object to js out files', () => {
expect(mapEntries({
outdir: 'dist',
entryPoints: {
one: 'src/one/index.ts',
two: 'src/two/index.ts'
}
})).toEqual([{
entry: 'src/one/index.ts',
outFile: 'dist/one.js'
}, {
entry: 'src/two/index.ts',
outFile: 'dist/two.js'
}])
})
})
})
43 changes: 43 additions & 0 deletions src/esbuild/definitions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { BuildOptions } from 'esbuild'
import { exec } from 'child_process'

type EntryMap = { entry: string, outFile: string }

/** Map entry points to js out files. */
export const mapEntries = (options: BuildOptions, baseUrl: string = 'src') => {
if (typeof options.entryPoints === 'undefined') return [] as EntryMap[]

const { entryPoints, outExtension, outdir = 'dist' } = options
const entries = [] as EntryMap[]
const ext = outExtension?.ext || 'js'

const getOutFile = (entry: string) =>
`${outdir}/${entry.replace(new RegExp(`^${baseUrl}/`), '').replace(/\.ts$/, '')}.${ext}`

if (Array.isArray(entryPoints)) {
for (const entry of entryPoints) {
entries.push({ entry, outFile: getOutFile(entry) })
}
} else {
for (const [out, entry] of Object.entries(entryPoints)) {
entries.push({ entry, outFile: getOutFile(out) })
}
}
return entries
}

/** Write type definitions for entry points with js out files. */
export const writeDefinition = ({ entry, outFile }: EntryMap) =>
new Promise<string>((resolve, reject) =>
exec(
`yarn tsc ${entry} --outFile ${outFile} --declaration --emitDeclarationOnly -p .`,
(error, stdout, stderr) => {
if (error) {
console.error(`❎ Writing definition for ${entry} failed:`, error)
reject(stderr)
} else {
console.log(`✅ Writing definition for ${entry} succeeded`)
resolve(stdout)
}
})
)
5 changes: 5 additions & 0 deletions src/typescript/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import ts from 'typescript'

const host: ts.ParseConfigFileHost = ts.sys as any;

ts.getParsedCommandLineOfConfigFile('tsconfig.json', {}, host)
3 changes: 1 addition & 2 deletions src/utils/clear.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import { rmdirSync, mkdirSync } from 'fs'

export const clearPath = (path?: string) => {
if (!path) return
export const clearPath = (path: string) => {
rmdirSync(path, { recursive: true })
mkdirSync(path)
}
7 changes: 6 additions & 1 deletion src/utils/package.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { fileURLToPath } from 'url'
import { readFileSync } from 'fs'
import { createRequire } from 'module'
import { resolve } from 'path'
import { dirname, resolve } from 'path'

export const resolvePath = (path: string) =>
resolve(dirname(fileURLToPath(import.meta.url)), path)

export const readPackage = (path: string) =>
JSON.parse(readFileSync(resolve(path, 'package.json'), { encoding: 'utf-8' }))
Expand All @@ -10,3 +14,4 @@ export const requirePackage = (path: string) =>

export const readDependencies = (path: string) =>
Object.keys(readPackage(path).dependencies)

4 changes: 2 additions & 2 deletions test/package/jest.config.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
import { configure } from '@nested-code/cogs/jest/index.js'
import jest from '@nested-code/cogs/jest'

export default configure()
export default jest.configure()
12 changes: 12 additions & 0 deletions tsconfig.build.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"extends": "./tsconfig.json",
"exclude": ["!./src"],
"include": ["./src/jest"],
"compilerOptions": {
"declaration": true,
"declarationDir": "dist",
"declarationMap": true,
"emitDeclarationOnly": true,
"outFile": "./dist/jest/index.js",
}
}
13 changes: 2 additions & 11 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,6 @@
"forceConsistentCasingInFileNames": true,
"isolatedModules": true,
"skipLibCheck": true,
"strict": true,
"declaration": true
},
"exclude": [
"**/*.test.ts",
"**/mocks",
"**/coverage"
],
"include": [
"**/*.ts"
]
"strict": true
}
}

0 comments on commit d488958

Please sign in to comment.