2016-10-12 12:07:54 +00:00
|
|
|
import 'typings-global'
|
2016-10-06 21:00:29 +00:00
|
|
|
|
2016-10-12 13:41:09 +00:00
|
|
|
import * as path from 'path'
|
2017-06-30 16:51:41 +00:00
|
|
|
import * as smartq from 'smartq'
|
2016-10-11 23:41:30 +00:00
|
|
|
import { Objectmap } from 'lik'
|
|
|
|
|
|
|
|
class Smartsystem {
|
2017-06-30 16:51:41 +00:00
|
|
|
lazyModules = new Objectmap<LazyModule<any>>()
|
2016-10-11 23:41:30 +00:00
|
|
|
|
2017-06-30 16:51:41 +00:00
|
|
|
/**
|
|
|
|
* add lazyModule to Smartsystem
|
|
|
|
*/
|
|
|
|
addLazyModule (lazyModuleArg: LazyModule<any>) {
|
|
|
|
this.lazyModules.add(lazyModuleArg)
|
|
|
|
}
|
2016-10-11 23:41:30 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// create the internal smartsystem
|
|
|
|
let smartsystem = new Smartsystem()
|
|
|
|
|
|
|
|
/**
|
|
|
|
* defines a LazyModule
|
|
|
|
*/
|
2016-10-14 01:07:37 +00:00
|
|
|
|
|
|
|
export type TLoader = 'npm' | 'systemjs'
|
|
|
|
|
2016-10-11 23:41:30 +00:00
|
|
|
export class LazyModule<T> {
|
2017-06-30 16:51:41 +00:00
|
|
|
name: string
|
|
|
|
cwd: string
|
|
|
|
whenLoaded: Promise<T>
|
2017-07-31 13:16:10 +00:00
|
|
|
private nameIsPath: boolean
|
2017-06-30 16:51:41 +00:00
|
|
|
private whenLoadedDeferred: smartq.Deferred<T>
|
2017-07-31 13:16:10 +00:00
|
|
|
constructor (nameArg: string, cwdArg: string) {
|
2017-06-30 16:51:41 +00:00
|
|
|
if (!cwdArg) {
|
|
|
|
throw new Error('You must specify a directory to resolve from!')
|
2016-10-11 23:41:30 +00:00
|
|
|
}
|
2017-06-30 16:51:41 +00:00
|
|
|
this.name = nameArg
|
|
|
|
this.cwd = cwdArg
|
|
|
|
smartsystem.addLazyModule(this) // add module to smartsystem instance
|
|
|
|
this.nameIsPath = /\.\//.test(this.name) // figure out if name is path
|
|
|
|
if (this.nameIsPath) {
|
|
|
|
this.name = path.join(this.cwd, this.name)
|
2016-10-14 01:07:37 +00:00
|
|
|
}
|
2017-06-30 16:51:41 +00:00
|
|
|
this.whenLoadedDeferred = smartq.defer<T>()
|
|
|
|
this.whenLoaded = this.whenLoadedDeferred.promise
|
|
|
|
}
|
2016-10-14 01:07:37 +00:00
|
|
|
|
2017-06-30 16:51:41 +00:00
|
|
|
/**
|
|
|
|
* loads the module
|
|
|
|
*/
|
2017-07-31 13:16:10 +00:00
|
|
|
async load (): Promise<T> {
|
|
|
|
let loadedModule: T = require(this.name)
|
|
|
|
this.whenLoadedDeferred.resolve(loadedModule)
|
|
|
|
return loadedModule
|
2017-06-30 16:51:41 +00:00
|
|
|
}
|
2016-10-14 01:24:29 +00:00
|
|
|
}
|