Skip to content

Commit

Permalink
feat: program creation, files emitting, diagnostics logging and forma…
Browse files Browse the repository at this point in the history
…tting
  • Loading branch information
jeremyben committed Jul 17, 2019
0 parents commit a27dc50
Show file tree
Hide file tree
Showing 21 changed files with 5,560 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Tells Github UI to allow comments in json files
*.json linguist-language=JSON-with-Comments

# Tells Github to not take js config root files into acccount for language statistics
/*.js linguist-detectable=false
36 changes: 36 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Build output
dist

# Environment variables file
.env

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Dependencies directory
node_modules/

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# Optional npm cache directory
.npm

# OS files
.DS_Store
Thumbs.db
[Dd]esktop.ini

# Vscode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
15 changes: 15 additions & 0 deletions .huskyrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/**
* @see https://github.com/typicode/husky/blob/master/DOCS.md
* @see https://git-scm.com/docs/githooks
*
* @type {{hooks: {[key in GitHook]?: string}}}
*
* @typedef {'pre-commit' | 'prepare-commit-msg' | 'commit-msg' | 'post-commit' | 'pre-rebase' | 'post-checkout' | 'post-merge' | 'pre-push' | 'applypatch-msg' | 'pre-applypatch' | 'post-applypatch' | 'post-rewrite' | 'post-index-change'} GitHook
*/
const config = {
hooks: {
'commit-msg': 'commitlint -E HUSKY_GIT_PARAMS',
},
}

module.exports = config
12 changes: 12 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"printWidth": 120,
"tabWidth": 2,
"useTabs": true,
"semi": false,
"singleQuote": true,
"trailingComma": "es5",
"bracketSpacing": true,
"arrowParens": "always",
"proseWrap": "preserve",
"endOfLine": "lf"
}
6 changes: 6 additions & 0 deletions .vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"recommendations": [
"esbenp.prettier-vscode",
"ms-vscode.vscode-typescript-tslint-plugin"
]
}
8 changes: 8 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"editor.formatOnSave": true,
"npm.packageManager": "yarn",
"prettier.requireConfig": true,
"files.associations": {
"tslint.json": "jsonc"
}
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 Jeremy Bensimon

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
59 changes: 59 additions & 0 deletions README.MD
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# tsc-prog

Build your TypeScript projects programmatically.

## Get started

```bash
npm i -D tsc-prog
yarn add -D tsc-prog
```

_Tsc-prog has no dependency. You just need typescript as a peer dependency._

## Usage

### You simply need to build

Use **`tsc.build`**.

```js
const tsc = require('tsc-prog')

tsc.build({
basePath: __dirname,
configFilePath: 'tsconfig.json',
compilerOptions: {
rootDir: 'src',
outDir: 'dist',
declaration: true,
skipLibCheck: true,
},
include: ['src/**/*.ts'],
exclude: ['**/*.test.ts', '**/*.spec.ts']
})
```

You can have a look at the parameters **[here](./src/interfaces.ts)**.

### You need more access

The `tsc.build` function is made of the two following steps, which you can have access to :

- [Program](https://github.com/microsoft/TypeScript/wiki/Architectural-Overview#data-structures) creation with **`tsc.createProgramFromConfig`**.
- Emitting files from program with **`tsc.emit`**.

```js
const tsc = require('tsc-prog')

// Create the program
const program = tsc.createProgramFromConfig({
basePath: process.cwd(),
configFilePath: 'tsconfig.json'
})

// Do what you want with the program

// Actually compile typescript files
tsc.emit(program, { betterDiagnostics: true })
```
24 changes: 24 additions & 0 deletions commitlint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* @see https://commitlint.js.org/#/reference-configuration
*
* @type {Config}
*
* @typedef Config
* @property {string[]=} extends Resolveable ids to commitlint configurations to extend.
* @property {string=} parserPreset Resolveable id to conventional-changelog parser preset to import and use.
* @property {string=} formatter Resolveable id to package, from node_modules, which formats the output.
* @property {{[key in RuleName]?: Rule | ((...args) => Rule)}=} rules Rules to check against.
* @property {((message: string) => boolean)[]=} ignores Functions that return true if commitlint should ignore the given message.
* @property {boolean=} defaultIgnores Whether commitlint uses the default ignore rules.
*
* @typedef {[0 | 1 | 2, 'always' | 'never', number | string | string[]]} Rule
* @typedef {'body-leading-blank' | 'body-max-length' | 'body-min-length' | 'footer-leading-blank' | 'footer-max-length' | 'footer-max-line-length' | 'footer-min-length' | 'header-case' | 'header-full-stop' | 'header-max-length' | 'header-min-length' | 'references-empty' | 'scope-enum' | 'scope-case' | 'scope-empty' | 'scope-max-length' | 'scope-min-length' | 'subject-case' | 'subject-empty' | 'subject-full-stop' | 'subject-max-length' | 'subject-min-length' | 'type-enum' | 'type-case' | 'type-empty' | 'type-max-length' | 'type-min-length' | 'signed-off-by'} RuleName
*/
const config = {
extends: ['@commitlint/config-conventional'],
rules: {
'header-max-length': [2, 'always', 100],
},
}

module.exports = config
15 changes: 15 additions & 0 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
/** @type {jest.InitialOptions} */
const config = {
preset: 'ts-jest',
testEnvironment: 'node',
testPathIgnorePatterns: ['/node_modules/', '/__fixtures__/'],
globals: {
'ts-jest': {
diagnostics: {
warnOnly: true, // https://kulshekhar.github.io/ts-jest/user/config/diagnostics
},
},
},
}

module.exports = config
42 changes: 42 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"name": "tsc-prog",
"version": "1.0.0",
"author": "Jeremy Bensimon",
"repository": "github:jeremyben/tsc-prog",
"license": "MIT",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"engines": {
"node": ">=8.10"
},
"engineStrict": true,
"scripts": {
"build": "rimraf dist && tsc -p tsconfig.build.json",
"prepublishOnly": "yarn build",
"release": "standard-version",
"test": "jest --runInBand",
"test:watch": "jest --runInBand --watch --verbose false"
},
"dependencies": {},
"peerDependencies": {
"typescript": ">=3"
},
"devDependencies": {
"@commitlint/cli": "^8.0.0",
"@commitlint/config-conventional": "^8.0.0",
"@types/jest": "^24.0.15",
"@types/node": "^10",
"husky": "^3.0.0",
"jest": "^24.8.0",
"standard-version": "^6.0.1",
"ts-jest": "^24.0.2",
"ts-node": "^8.3.0",
"tslint": "^5.18.0",
"tslint-config-prettier": "^1.18.0",
"typescript": "^3.5.3",
"typescript-tslint-plugin": "^0.5.4"
}
}
3 changes: 3 additions & 0 deletions src/__fixtures__/src/excluded/other.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { pseudoRandomBytes } from 'crypto'

const pseudoRandom = pseudoRandomBytes(32).toString('utf8')
3 changes: 3 additions & 0 deletions src/__fixtures__/src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { randomBytes } from 'crypto'

const random = randomBytes(32).toString('utf8')
13 changes: 13 additions & 0 deletions src/__fixtures__/tsconfig.fixture.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"compilerOptions": {
"target": "es2017",
"module": "commonjs",
"lib": ["es2017"],
"outDir": "./dist",
"rootDir": ".",
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true,
"resolveJsonModule": true
}
}
55 changes: 55 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { createProgramFromConfig, build } from '.'
import { join } from 'path'
import { existsSync, unlinkSync } from 'fs'

const basePath = join(__dirname, '__fixtures__')

test('Override config file and create program', async () => {
const consoleWarnSpy = spyOn(console, 'warn')

const program = createProgramFromConfig({
basePath,
configFilePath: 'tsconfig.fixture.json',
compilerOptions: {
rootDir: 'src',
outDir: 'dist',
declaration: 'true' as any,
skipLibCheck: true,
},
exclude: ['**/excluded'],
})

const options = program.getCompilerOptions()
expect(options).toMatchObject({
strict: true,
rootDir: join(basePath, 'src').replace(/\\/g, '/'),
declaration: undefined,
})

expect(consoleWarnSpy).toHaveBeenCalledWith(expect.stringContaining("'declaration' requires a value of type boolean"))

const rootFileNames = program.getRootFileNames()
expect(rootFileNames).toHaveLength(1)
})

test('Build without errors', async () => {
const consoleWarnSpy = spyOn(console, 'warn')

build({
basePath,
compilerOptions: {
rootDir: 'src',
outDir: 'dist',
declaration: false,
strict: true,
skipLibCheck: true,
},
exclude: ['**/excluded'],
})

expect(consoleWarnSpy).not.toHaveBeenCalledWith(expect.stringContaining('error'))

const distMainFile = join(basePath, 'dist', 'main.js')
expect(existsSync(distMainFile)).toBe(true)
unlinkSync(distMainFile)
})
Loading

0 comments on commit a27dc50

Please sign in to comment.