UNPKG

tsreflect-ioc

Version:

Inversion of control and Dependency injection framework for typescript based on the tsreflect-compiler package.

82 lines (77 loc) 3.48 kB
/// <reference path="typings/tsreflect-compiler.d.ts" /> /// <reference path="string.ts" /> /// <reference path="array.ts" /> import cmp = require('tsreflect-compiler'); import helper = require('./helper'); var fs = require('fs'); var extend = require('extend'); var arrayExt = require('./array'); var stringExt = require('./string'); export module ioc { export interface ICompilerConfig { sourceFiles?: string[]; options?: cmp.CompilerOptions; searchForDefinitionFilesIn?: string; } export class StandardCompilerConfig implements ICompilerConfig { sourceFiles: string[] = []; searchForDefinitionFilesIn: string = 'typings'; options: { } } export class Compiler { defaultConfig: ICompilerConfig; constructor(defaultConfig?: ICompilerConfig) { this.defaultConfig = extend(true, defaultConfig || <ICompilerConfig>{}, new StandardCompilerConfig()); } public compile(config?: ICompilerConfig): cmp.Diagnostic[] { config = <any>(config || {}); var options = this.getCompilerOptions(config); var sourceFiles = this.getSourceFiles(config); var diags = cmp.compile(config.sourceFiles, options); // check if all modules where compiled config.sourceFiles = helper.getReflectionFileInfos(config.sourceFiles); if (diags.any()) { var str = ''; var diagStr = diags.forEach(diag => str += ' ' + diag.filename + ' at line ' + diag.line + ', Code: ' + diag.code + ' > ' + diag.messageText); // todo: throw custom error throw diagStr; } return diags; } private getCompilerOptions(config: ICompilerConfig) { var configured = config.options || {}; return extend(true, configured, {}); } private getSourceFiles(config: ICompilerConfig): string[] { var sourceFiles = config.sourceFiles === undefined || config.sourceFiles.length == 0 ? [] : config.sourceFiles; var readFiles = fs.readdirSync('.'); if (sourceFiles.length == 0) { var files = readFiles .where((file: string) => file.endsWith('.ts')) .forEach(file => sourceFiles.push(file)); } if (typeof config.searchForDefinitionFilesIn == 'string') { var searchRecursive = function (dir) { if (!fs.existsSync(dir)) { throw new ReferenceError('Configuration error: directory ' + dir + ' not found'); } fs.readdirSync(dir) .forEach(file => { var filepath = dir + '/' + file; var fi = fs.statSync(filepath); if (fi.isDirectory()) { searchRecursive(filepath) } else { if (file.endsWith('.d.ts')) { sourceFiles.push(filepath); } } }); } searchRecursive(config.searchForDefinitionFilesIn); } return sourceFiles; } } }