New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

fib-typify

Package Overview
Dependencies
Maintainers
1
Versions
33
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

fib-typify - npm Package Compare versions

Comparing version 0.8.2 to 0.8.3

.all-contributorsrc

81

bin/fib-typify.js
#!/usr/bin/env fibjs
'use strict';

@@ -12,3 +13,2 @@ const fs = require('fs')

const extendCompilerConfigFromTSConfig = require('../core/_utils').extendCompilerConfigFromTSConfig
const replaceSuffix = require('../core/_utils').replaceSuffix

@@ -18,5 +18,7 @@

const { generateLoaderbox } = require('../core/loader-box')
const { createCompilerHost } = require('../core/ts-apis/program')
const { resolveCwdTsProject } = require('../core/ts-apis/compilerOptions')
const defaultCompilerOptions = require('../core/_utils').defaultCompilerOptions
const cli = require('@fxjs/cli')(pkgJson.name)
const cli = require('@fxjs/cli')('fib-typify')

@@ -29,3 +31,2 @@ cli

.option('-o, --out [target]', 'output target', {})
// .command('compile [...compileSource]', 'source files to compile')
.action(function (files, options) {

@@ -35,38 +36,47 @@ const [srcpath] = files

const outputValue = typeof options.o === 'string' ? options.o : ''
const outputExisted = getArgIdxFromArgs(cli.rawArgs, argFlags.output) > -1
const outputMode = getArgIdxFromArgs(cli.rawArgs, argFlags.output) > -1
let tsCompilerOptions = JSON.parse(JSON.stringify(defaultCompilerOptions))
const cwd = process.cwd()
/* collect params :start */
tsCompilerOptions = mergeCompilerConfigFromCustomConfig(options.c, tsCompilerOptions, cwd)
tsCompilerOptions = extendCompilerConfigFromTSConfig(tsCompilerOptions)
tsCompilerOptions.outDir = tsCompilerOptions.outDir || outputValue
if (!outputMode) {
tsCompilerOptions.outDir = ''
} else if (fs.exists(outputValue)) {
const stat = fs.stat(outputValue)
if (stat.isDirectory()) tsCompilerOptions.outDir = outputValue
else if (stat.isFile()) tsCompilerOptions.outDir = path.dirname(outputValue)
} else {
tsCompilerOptions.outDir = outputValue
}
const CWD = process.cwd()
const parsedTsConfig = resolveCwdTsProject(options.c, {
compilerHost: createCompilerHost(tsCompilerOptions),
files,
cwd: CWD
})
if (parsedTsConfig.errors.length)
throw new Error(parsedTsConfig.errors[0].messageText)
tsCompilerOptions = parsedTsConfig.options
is_debug() && console.notice('tsCompilerOptions', tsCompilerOptions);
/* collect params :end */
const topTsSandbox = generateLoaderbox(tsCompilerOptions)
const topTsSandbox = generateLoaderbox(parsedTsConfig.options)
is_debug() && console.notice('tsCompilerOptions.outDir', tsCompilerOptions.outDir)
// finalParams
const fP = {
cwd,
srcpath,
entryPoint: resolveExistedEntry(topTsSandbox, srcpath, cwd)
}
is_debug() && console.notice('finalParams', fP)
const entryPoint = resolveExistedEntry(topTsSandbox, srcpath, CWD)
if (outputExisted) {
if (outputMode) {
// compile mode
const baseDir = path.resolve(fP.cwd, fP.srcpath)
const distDir = path.resolve(fP.cwd, outputValue || replaceSuffix(fP.srcpath))
const baseDir = path.resolve(CWD, srcpath)
const distDir = path.resolve(CWD, outputValue || replaceSuffix(srcpath))
if (!fs.exists(baseDir)) {
quit(errCode["invalidArg:input"], 1)
}
if (!fs.exists(baseDir)) quit(errCode["invalidArg:input"], 1)
compileDirectoryTo(baseDir, distDir, { compilerOptions: tsCompilerOptions })
} else if (fP.entryPoint) {
} else if (entryPoint) {
// run mode
topTsSandbox.require(fP.entryPoint, __dirname)
topTsSandbox.require(entryPoint, __dirname)
} else

@@ -90,23 +100,2 @@ quit(errCode["noArg:output"], 1)

function mergeCompilerConfigFromCustomConfig (configFilePath = null, origConfig = {}, cwd) {
configFilePath = configFilePath ? path.resolve(cwd, configFilePath) : null
if (configFilePath && fs.exists(configFilePath)) {
let config = {}
if (['.json', '.js', '.jsc'].some(ext => configFilePath.endsWith(ext))) {
config = require(configFilePath)
is_debug() && console.notice('internal extension', config)
} else {
try {
config = JSON.parse(fs.readTextFile(configFilePath))
} catch (e) {
console.warn(`error occured when trying to parse config file: ${configFilePath}`)
}
}
origConfig = util.extend({}, origConfig, config)
}
return origConfig
}
function resolveExistedEntry (vbox, entryPoint, cwd = __dirname) {

@@ -113,0 +102,0 @@ // always allow existed file

#!/usr/bin/env fibjs
'use strict';
const path = require('path')
const util = require('util')

@@ -18,32 +18,13 @@ const fs = require('fs')

const { createProgram, createCompilerHost } = require('../core/ts-apis/program')
const { getParseConfigHost } = require('../core/ts-apis/compilerOptions')
const { resolveCwdTsProject } = require('../core/ts-apis/compilerOptions')
const runProgram = (fileNames, compilerOptions, cmdLineOptions) => {
const host = createCompilerHost(compilerOptions)
const runProgram = (fileNames, compilerOptions) => {
const parsedTsConfig = resolveCwdTsProject(compilerOptions.project, {
compilerHost: createCompilerHost(compilerOptions),
files: fileNames,
cwd: CWD
})
if (parsedTsConfig.errors.length)
throw new Error(parsedTsConfig.errors[0].messageText)
let parsedTSConfig
// make compilerOptions.project absolute path.
compilerOptions.project = fixNonAbsolutePath(compilerOptions.project || 'tsconfig.json', CWD)
let tsconfigContent = JSON.stringify({})
try {
tsconfigContent = fs.readTextFile(compilerOptions.project)
} catch (error) {}
const configParsedResult = ts.parseConfigFileTextToJson(compilerOptions.project, tsconfigContent)
if (configParsedResult.error)
throw new Error(configParsedResult.error)
inputTSConfig = configParsedResult.config
inputTSConfig.files = fileNames
// TODO: learn about ts.ParsedTsConfig, why its real value is augument of its declartion(in types)
parsedTSConfig = ts.parseJsonConfigFileContent(
inputTSConfig,
/* parseConfigHost */getParseConfigHost(host, CWD),
/* basePath */CWD,
compilerOptions
)
const program = createProgram(fileNames, {

@@ -53,5 +34,5 @@ "noEmitOnError": true,

...compilerOptions,
...parsedTSConfig && parsedTSConfig.options
...parsedTsConfig && parsedTsConfig.options
})
const emitResult = program.emit();

@@ -58,0 +39,0 @@

@@ -7,6 +7,5 @@ const fs = require('fs')

const { filterCompilerOptions } = require('./ts-apis/compilerOptions')
const CORE = require('./core')
const { createCompilerHostForSandboxRegister } = require('./vm/sandbox')
const { getInternalVMTSFilename, createCompilerHostForSandboxRegister } = require('./vm/sandbox')
const { createProgram } = require('./ts-apis/program')

@@ -42,20 +41,4 @@

exports.defaultCompilerOptions = require('../tsconfig.dft.json').compilerOptions
exports.extendCompilerConfigFromTSConfig = function (origConfig = {}) {
let tsConfigFilepath = path.resolve(process.cwd(), 'tsconfig.json')
if (tsConfigFilepath && fs.exists(tsConfigFilepath) && fs.stat(tsConfigFilepath).isFile()) {
let tsConfig = require(tsConfigFilepath) || {}
origConfig = util.extend({}, origConfig, tsConfig.compilerOptions)
}
return origConfig
}
exports.defaultCompilerOptions = require('../tsconfig.dft.json')
exports.getCwdTsCompilerOptions = function () {
return exports.extendCompilerConfigFromTSConfig(util.extend({}, exports.defaultCompilerOptions))
}
const TS_SUFFIX = exports.TS_SUFFIX = '.ts'

@@ -68,9 +51,5 @@

tsCompilerOptions = {},
moduleOptions = {},
) => {
moduleOptions.compilerOptions = util.extend({}, tsCompilerOptions, moduleOptions.compilerOptions)
const host = createCompilerHostForSandboxRegister(tsCompilerOptions, sandbox)
filterCompilerOptions(moduleOptions.compilerOptions)
const { host, getByFilename } = createCompilerHostForSandboxRegister(tsCompilerOptions)
;[

@@ -81,6 +60,7 @@ TS_SUFFIX,

sandbox.setModuleCompiler(tsSuffix, (buf, args) => {
const filename = path.normalize(args.filename)
let result = getByFilename(filename)
if (!result) {
const program = createProgram([ filename ], {
const tsFilename = path.normalize(args.filename)
const vmtsFilename = getInternalVMTSFilename(tsFilename)
if (!sandbox.has(vmtsFilename)) {
const program = createProgram([ tsFilename ], {
...tsCompilerOptions,

@@ -90,7 +70,5 @@ }, host)

program.emit()
result = getByFilename(filename)
}
return result
return sandbox.require(vmtsFilename, __dirname).js
})

@@ -97,0 +75,0 @@ })

@@ -9,3 +9,3 @@ /**

function generateLoaderbox (tsCompilerOptions) {
const generateLoaderbox = exports.generateLoaderbox = function (tsCompilerOptions) {
const tsSandbox = new vm.SandBox(UTILs.builtModules)

@@ -22,3 +22,2 @@

exports.generateLoaderbox = generateLoaderbox
exports.defaultBox = generateLoaderbox()

@@ -0,1 +1,2 @@

const fs = require('fs')
const path = require('path')

@@ -12,14 +13,6 @@

exports.filterCompilerOptions = function (compilerOptions) {
if (compilerOptions.sourceMap) {
console.warn(`[fib-typify] don't support sourceMap now, tranform to 'inlineSourceMap' automatically.`)
compilerOptions.sourceMap = false
compilerOptions.inlineSourceMap = true
}
}
/**
* @description return one ts.ParseConfigHost
*/
exports.getParseConfigHost = (compilerHost, cwd) => {
const getParseConfigHost = exports.getParseConfigHost = (compilerHost, cwd) => {
// this API is from typescript, not documented

@@ -29,12 +22,24 @@ return ts.createCachedDirectoryStructureHost(compilerHost, cwd, process.platform !== 'win32')

exports.resolveCwdTsProject = function (projectName = 'tsconfig.json') {
projectName = path.isAbsolute(projectName) ? projectName : path.resolve(process.cwd(), projectName)
exports.resolveCwdTsProject = function (projectName = 'tsconfig.json', {
/**
* @why for ts 3.9, files/inputs are required.
*/
files = [],
compilerHost,
cwd = process.cwd(),
}) {
projectName = path.isAbsolute(projectName) ? projectName : path.resolve(cwd, projectName)
const configParsedResult = ts.parseConfigFileTextToJson(projectName, fs.readTextFile(projectName))
let tsconfigContent = JSON.stringify({})
try {
tsconfigContent = fs.readTextFile(projectName)
} catch (error) {}
const configParsedResult = ts.parseConfigFileTextToJson(projectName, tsconfigContent)
if (configParsedResult.error)
throw new Error(configParsedResult.error)
throw new Error(configParsedResult.error.messageText)
inputTSConfig = configParsedResult.config
inputTSConfig.files = fileNames
const inputTSConfig = configParsedResult.config
inputTSConfig.files = files

@@ -44,4 +49,4 @@ // TODO: learn about ts.ParsedTsConfig, why its real value is augument of its declartion(in types)

inputTSConfig,
/* parseConfigHost */getParseConfigHost(host, CWD),
/* basePath */CWD,
/* parseConfigHost */getParseConfigHost(compilerHost, cwd),
/* basePath */cwd,
compilerOptions

@@ -48,0 +53,0 @@ )

@@ -8,3 +8,3 @@ const ts = require('typescript')

*/
const { filterCompilerOptions, getDefaultCompilerOptions } = require('./compilerOptions')
const { getDefaultCompilerOptions } = require('./compilerOptions')

@@ -21,4 +21,2 @@ function _getOptions(options, locals) {

return (input, locals) => {
compilerOptions && filterCompilerOptions(compilerOptions)
return ts.transpile(input, _getOptions(compilerOptions, locals), fileName, diagnostics, moduleName)

@@ -30,5 +28,2 @@ }

return (input, locals) => {
if (moduleOptions.compilerOptions)
filterCompilerOptions(moduleOptions.compilerOptions)
moduleOptions.compilerOptions = _getOptions(moduleOptions.compilerOptions, locals)

@@ -35,0 +30,0 @@

@@ -6,8 +6,33 @@ const ts = require('typescript')

exports.createCompilerHostForSandboxRegister = function (compilerOptions) {
const TS_INTERNAL_PROTOCOL = 'vmts:'
const getInternalVMTSFilename = exports.getInternalVMTSFilename = (jsOrFilename) => {
jsOrFilename = jsOrFilename.replace(/\.tsx?/, '.js')
return `${TS_INTERNAL_PROTOCOL}${path.normalize(jsOrFilename)}`
}
exports.createCompilerHostForSandboxRegister = function (compilerOptions, sandbox) {
const host = ts.createCompilerHost(compilerOptions);
const compiledContents = {};
sandbox.compiledContents = sandbox.compiledContents || {};
host.writeFile = (fileName, contents, writeByteOrderMark, onError, sourceFiles) => {
compiledContents[path.normalize(fileName)] = contents;
host.writeFile = (filename, contents, writeByteOrderMark, onError, sourceFiles) => {
let targetFilename = getInternalVMTSFilename(filename)
/**
* @description `.originalFilename` is un-type-declared field but valid in reality
*/
const originalFilename = sourceFiles[0] && (sourceFiles[0].originalFilename || sourceFiles[0].fileName) || filename
if (originalFilename) {
targetFilename = getInternalVMTSFilename(originalFilename)
}
let key = 'js'
if (filename.endsWith('.js')) {
key = 'js'
} else if (filename.endsWith('.map')) {
key = 'map'
}
sandbox.addScript(
targetFilename,
`module.exports = ${JSON.stringify({
[key]: contents
})}`
)

@@ -17,10 +42,3 @@ return contents;

return {
host,
getByFilename: (fileName) => {
fileName = path.normalize(fileName)
return compiledContents[fileName.replace(/\.tsx?/, '.js')]
}
}
return host
}
v0.8.2 / 2020-05-25
v0.8.3 / 2020-05-25
==================
* chore: code clean
* fix: fix compilation error on ts@3.9. (#17)
* Merge branch 'master' of github.com:richardo2016/fib-typify
* chore: delight all contributors.
* docs: add richardo2016 as a contributor (#16)
* chore: delight contributors section
* chore: fixup crash when `outDir` set in runmode.
* chore: robust change.
* chore: code clean.
* chore: update README.md
v0.8.2 / 2020-05-25
===================
* Release v0.8.2
v0.8.1 / 2020-05-25

@@ -8,0 +22,0 @@ ===================

"use strict";
/// <reference types="@fibjs/types" />
Object.defineProperty(exports, "__esModule", { value: true });
exports.loader = exports.generateLoaderbox = exports.loaderBox = exports.compileDirectoryTo = exports.compileFileToSandBox = exports.compileFileTo = exports.compileFile = exports.compileRawToSandBox = exports.compileRawToFile = exports.compileRaw = exports.compileModule = exports.defaultCompilerOptions = exports.registerTsCompiler = exports.builtModules = exports.createProgram = exports.createCompilerHost = exports.ChainLoader = void 0;
const vm = require("vm");

@@ -5,0 +6,0 @@ const compileModule = require('../core/transpile/module').compileModule;

{
"name": "fib-typify",
"version": "0.8.2",
"version": "0.8.3",
"description": "just write fibjs with typescript : )",

@@ -41,3 +41,3 @@ "main": "./lib",

"source-map-support": "^0.5.12",
"typescript": "^3.5.1"
"typescript": "^3.7.x"
},

@@ -61,4 +61,4 @@ "ci": {

"engines": {
"fibjs": ">=0.24.0"
"fibjs": ">=0.27.0"
}
}

@@ -7,6 +7,11 @@ # fib-typify

just write fibjs with typescript : )
🚀 Just coding fibjs program with typescript
## Introduction**
`fib-typify` allows you to write fibjs with [typescript] at compilation or at runtime. It depends on official [typescript]'s [internal compiler API](https://github.com/microsoft/TypeScript/wiki/Using-the-Compiler-API).
## Pre-requisite
As typescript is written with **nodejs**, it's not restricted in nodejs runtime only --- you can also compile typescript in browser or _ANY_ other pure Javascript runtime. That is, you can use it in fibjs also.
## Pre-requisites
- fibjs `>= 0.27.0`

@@ -16,2 +21,9 @@

```bash
# locally
npm i -S fib-typify
# or globally
npm i -g fib-typify
```
**Via Javascript**

@@ -42,16 +54,42 @@

Command above means compiling directory `src` to directory `lib` with configuration file `.typify.json`, which would be passed to `typescript.transpileModule(input, moduleOptions)` as 2nd param.
```bash
# compile, source directory(such as `src` above) is required
# compile, source directory(such as `src/*` below) is required
./node_modules/.bin/ftsc src/* --outDir lib
```
#### `fib-typify`
Most general options of `tsc` are supported:
run .ts script directly.
- `--target`
- `--module`
- `--moduleResolution`
- **`--jsx`**
- **`--declaration`**
- `--declarationDir`
- `--emitDeclarationOnly`
- **`--outDir`**
- `--allowJs`
- `--noEmit`
- ...
You can just pass those options to `ftsc` as arguments(flags), just like what you did with `tsc`.
```bash
# compile your project's source to `lib` directory, with dts files emitted 🚀
ftsc ./src/* \
--outDir ./lib \
--declaration \
--declarationDir ./typings
--allowJs \
```
#### `fib-typify`(deprecated)
Run .ts script directly.
```bash
./node_modules/.bin/fib-typify ./src/index.ts
```
Command above means compiling directory `src` to directory `lib` with configuration file `.typify.json`, which would be passed to `typescript.transpileModule(input, moduleOptions)` as 2nd param `moduleOptions`.
<!-- Or compile it to same directory with corresponding filename

@@ -87,15 +125,2 @@ ```bash

**Introduction**
`fib-typify` allows you to write fibjs with [typescript] in compilation or in runtime. It depends on original [typescript] stable version. As typescript is written with **nodejs**, it's not restricted in nodejs runtime: you can also compile typescript in browser or _ANY_ other pure Javascript runtime. That is, you can use it in fibjs also.
**Usage**
```bash
# locally
npm i -S fib-typify
# or globally
npm i -g fib-typify
```
## default tsCompilerOptions

@@ -112,12 +137,2 @@

### `tsconfig.json`
Start from `0.4.0`, `compilerOptions` from `CWD/tsconfig.json` would overwrite built-in default compilerOptions.
### priority of overwriting
1. compilerOptions passed to `function params`
1. compilerOptions in `tsconfig.json`
1. internal default compilerOptions
### Baisc Usage

@@ -140,28 +155,2 @@

* `compileRaw: (tsRaw: string, tsCompilerOptions: TSCompilerOptions) => string`
compile `tsRaw` to javascript.
* `compileRawToFile: (tsRaw: string, targetpath: string, tsCompilerOptions: TSCompilerOptions) => void`
compile `tsRaw` to javascript, then write to `targetpath`.
* `compileFile: (filepath?: string, tsCompilerOptions: TSCompilerOptions) => string`
compile content in `filepath` to javascript.
* `compileFileTo: (srcpath?: string, targetpath: string, tsCompilerOptions: TSCompilerOptions) => void`
compile content in `filepath` to javascript, then write to `targetpath`.
* `compileDirectoryTo: (baseDir: string, distDir: string, directoryCompilationOptions: any) => void`
| Param | Type | Required/Default |
| -------- | -------- | -------- |
| baseDir | string | Y / - |
| distDir | string | Y / - |
| directoryCompilationOptions | [directoryCompilationOptions] | N / - |
compile files in directory `baseDir` recursively to `distDir`, view options in view [directoryCompilationOptions].
* `generateLoaderbox(tsCompilerOptions: TSCompilerOptions, basedir: string)`

@@ -185,11 +174,2 @@

### directoryCompilationOptions
| Field | Type | Required/Default | Explanation |
| -------- | -------- | -------- | --------- |
| compilerOptions | boolean | Y / `false` | typescript's [compilerOptions] |
| fileglobsToCopy | Array, '*' | N / `['*.js', '*.jsc', '*.json']` | whitelist for extensions of globnames to copy when recursive walk to one
| includeLeveledGlobs | string | string[] | N / `['*', '!node_modules', '!.ts']` | glob descriptor list to exclude on walk to every directory level, view detail in [micromatch] |
| filterFileName | (filename: string): boolean | N / - | whether compile File, file would be compiled if returning `true` |
## loaderBox

@@ -227,13 +207,2 @@

### File Filter Priority
High -> Low:
1. includeLeveledGlobs
1. fileglobsToCopy
1. filterFileName
### File Writing Priority
1. [compileResult]
1. fileglobsToCopy
## Warning

@@ -243,5 +212,5 @@

**NOTE** it's not recommended to use fib-typify in fibjs <= 0.26.x.
**NOTE** it's **NOT** recommended to use fib-typify in fibjs <= 0.26.x.
From fibjs `0.26.0`, fibjs supports `setModuleCompiler` API to customize compiler for specified extension, so we can require typescript file directly by providing compiler for `.ts` file, which provided by fib-typify's `loaderBox`.
From fibjs `0.26.0`, fibjs supports `setModuleCompiler` API which allow to customize compiler for module with explicit extension, so we can require typescript file directly by providing compiler for `.ts` file, which provided by fib-typify's `loaderBox`.

@@ -256,3 +225,3 @@ fib-typify also support `loaderBox` feature in lower version fibjs(`< 0.25.0`), but not full-feature support, so there are some advices for your application depending on fib-typify in fibjs(`< 0.25.0`):

### compile `.ts` to `.js` before your deploy
### compile `.ts` to `.js` before your deployment

@@ -264,6 +233,19 @@ By the way, although I have tested in some cases, but it's not enough to improve "fib-typify's loaderBox can run in production directly". In my own work, I use fib-typify's loaderBox to load all source code when app's in developing stage, but I would

## Contributions
## Contributors ✨
If you wanna contribute to this package, just learn about [fibjs] first, then fork this repo :)
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
<tr>
<td align="center"><a href="http://js.chenlei.me"><img src="https://avatars0.githubusercontent.com/u/6339390?v=4" width="100px;" alt=""/><br /><sub><b>Ray</b></sub></a></td>
</tr>
</table>
<!-- markdownlint-enable -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
[typescript]:https://github.com/Microsoft/TypeScript

@@ -270,0 +252,0 @@ [fibjs]:http://fibjs.org/

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc