smartinject/ts/index.ts

75 lines
1.8 KiB
TypeScript
Raw Normal View History

2017-02-28 22:40:13 +00:00
import 'typings-global'
2017-07-28 18:44:24 +00:00
let Module = require('module')
import path = require('path')
import sourceMap = require('source-map-support')
import through2 = require('through2')
import vm = require('vm')
2017-02-28 22:40:13 +00:00
import { Transform } from 'stream'
sourceMap.install({
retrieveFile: function (path) {
if (cache[path]) {
2017-03-04 17:13:51 +00:00
return cache[path].contents.toString()
2017-07-28 18:44:24 +00:00
} else if (cache[path + '.js']) {
return cache[path + '.js'].contents.toString()
2017-02-28 22:40:13 +00:00
}
}
2017-03-04 17:13:51 +00:00
})
2017-02-28 22:40:13 +00:00
2017-07-28 18:44:24 +00:00
let cache = {}
2017-03-04 17:13:51 +00:00
let originalLoader = Module._extensions['.js']
2017-02-28 22:40:13 +00:00
Module._extensions['.js'] = function (module, filename) {
2017-03-04 17:13:51 +00:00
let file = cache[filename]
2017-07-28 18:44:24 +00:00
let file2 = cache[filename + '.js']
2017-02-28 22:40:13 +00:00
if (file) {
2017-03-04 17:13:51 +00:00
module._compile(file.contents.toString(), filename)
2017-07-28 18:44:24 +00:00
} else if (file2) {
module._compile(file2.contents.toString(), filename)
2017-02-28 22:40:13 +00:00
} else {
2017-03-04 17:13:51 +00:00
originalLoader.apply(this, arguments)
2017-02-28 22:40:13 +00:00
}
2017-03-04 17:13:51 +00:00
}
2017-02-28 22:40:13 +00:00
let originalModuleResolve = Module._resolveFilename
Module._resolveFilename = function (request, parent, isMain) {
2017-07-30 14:00:06 +00:00
let parsedIdDir = path.parse(parent.id).dir
let resolvedRequest: string
if (parent) {
resolvedRequest = path.join('/', parent.id, request)
} else {
resolvedRequest = request
}
2017-07-30 14:19:36 +00:00
// console.log('resolvedRequest:' + resolvedRequest)
2017-07-30 13:53:58 +00:00
let file = cache[resolvedRequest]
let file2 = cache[resolvedRequest + '.js']
2017-07-28 18:44:24 +00:00
if (file || file2) {
return request
2017-02-28 22:40:13 +00:00
} else {
return originalModuleResolve.apply(this, arguments)
}
2017-03-04 17:13:51 +00:00
}
2017-02-28 22:40:13 +00:00
export let gulpPipe = function () {
return through2.obj(function (file, enc, cb) {
2017-07-28 16:19:06 +00:00
cache[file.path] = file
return cb(null, file)
2017-03-04 17:13:51 +00:00
})
}
2017-02-28 22:40:13 +00:00
export interface fileObject {
path: string
contents: Buffer
}
export let injectFileArray = async (fileArray: fileObject[]) => {
for (let fileObject of fileArray) {
2017-07-30 14:19:36 +00:00
// console.log('injected:' + fileObject.path)
2017-02-28 22:40:13 +00:00
cache[fileObject.path] = fileObject
}
return fileArray
}