|
| 1 | +/** |
| 2 | + * Transform template html and css into executable code. |
| 3 | + * Intended to be used in a build step. |
| 4 | + */ |
| 5 | +import * as ts from 'typescript'; |
| 6 | +import * as path from 'path'; |
| 7 | + |
| 8 | +import * as compiler from 'angular2/compiler'; |
| 9 | +import {StaticReflector} from 'angular2/src/compiler/static_reflector'; |
| 10 | +import {CompileMetadataResolver} from 'angular2/src/compiler/metadata_resolver'; |
| 11 | +import {HtmlParser} from 'angular2/src/compiler/html_parser'; |
| 12 | +import {DirectiveNormalizer} from 'angular2/src/compiler/directive_normalizer'; |
| 13 | +import {Lexer} from 'angular2/src/compiler/expression_parser/lexer'; |
| 14 | +import {Parser} from 'angular2/src/compiler/expression_parser/parser'; |
| 15 | +import {TemplateParser} from 'angular2/src/compiler/template_parser'; |
| 16 | +import {DomElementSchemaRegistry} from 'angular2/src/compiler/schema/dom_element_schema_registry'; |
| 17 | +import {StyleCompiler} from 'angular2/src/compiler/style_compiler'; |
| 18 | +import {ViewCompiler} from 'angular2/src/compiler/view_compiler/view_compiler'; |
| 19 | +import {TypeScriptEmitter} from 'angular2/src/compiler/output/ts_emitter'; |
| 20 | +import {RouterLinkTransform} from 'angular2/src/router/directives/router_link_transform'; |
| 21 | +import {Parse5DomAdapter} from 'angular2/platform/server'; |
| 22 | + |
| 23 | +import {MetadataCollector} from 'ts-metadata-collector'; |
| 24 | +import {NodeReflectorHost} from './reflector_host'; |
| 25 | +import {wrapCompilerHost, CodeGeneratorHost} from './compiler_host'; |
| 26 | + |
| 27 | +const SOURCE_EXTENSION = /\.[jt]s$/; |
| 28 | +const PREAMBLE = `/** |
| 29 | + * This file is generated by the Angular 2 template compiler. |
| 30 | + * Do not edit. |
| 31 | + */ |
| 32 | +`; |
| 33 | + |
| 34 | +export interface AngularCompilerOptions { |
| 35 | + // Absolute path to a directory where generated file structure is written |
| 36 | + genDir: string; |
| 37 | +} |
| 38 | + |
| 39 | +export class CodeGenerator { |
| 40 | + constructor(private ngOptions: AngularCompilerOptions, private basePath: string, |
| 41 | + public program: ts.Program, public host: CodeGeneratorHost, |
| 42 | + private staticReflector: StaticReflector, private resolver: CompileMetadataResolver, |
| 43 | + private compiler: compiler.OfflineCompiler, |
| 44 | + private reflectorHost: NodeReflectorHost) {} |
| 45 | + |
| 46 | + private generateSource(metadatas: compiler.CompileDirectiveMetadata[]) { |
| 47 | + const normalize = (metadata: compiler.CompileDirectiveMetadata) => { |
| 48 | + const directiveType = metadata.type.runtime; |
| 49 | + const directives = this.resolver.getViewDirectivesMetadata(directiveType); |
| 50 | + const pipes = this.resolver.getViewPipesMetadata(directiveType); |
| 51 | + return new compiler.NormalizedComponentWithViewDirectives(metadata, directives, pipes); |
| 52 | + }; |
| 53 | + |
| 54 | + return this.compiler.compileTemplates(metadatas.map(normalize)); |
| 55 | + } |
| 56 | + |
| 57 | + private readComponents(absSourcePath: string) { |
| 58 | + const result: Promise<compiler.CompileDirectiveMetadata>[] = []; |
| 59 | + const metadata = this.staticReflector.getModuleMetadata(absSourcePath); |
| 60 | + if (!metadata) { |
| 61 | + console.log(`WARNING: no metadata found for ${absSourcePath}`); |
| 62 | + return result; |
| 63 | + } |
| 64 | + |
| 65 | + const symbols = Object.keys(metadata['metadata']); |
| 66 | + if (!symbols || !symbols.length) { |
| 67 | + return result; |
| 68 | + } |
| 69 | + for (const symbol of symbols) { |
| 70 | + const staticType = this.reflectorHost.findDeclaration(absSourcePath, symbol, absSourcePath); |
| 71 | + let directive: compiler.CompileDirectiveMetadata; |
| 72 | + directive = this.resolver.maybeGetDirectiveMetadata(<any>staticType); |
| 73 | + |
| 74 | + if (!directive || !directive.isComponent) { |
| 75 | + continue; |
| 76 | + } |
| 77 | + result.push(this.compiler.normalizeDirectiveMetadata(directive)); |
| 78 | + } |
| 79 | + return result; |
| 80 | + } |
| 81 | + |
| 82 | + codegen() { |
| 83 | + Parse5DomAdapter.makeCurrent(); |
| 84 | + const generateOneFile = (absSourcePath: string) => |
| 85 | + Promise.all(this.readComponents(absSourcePath)) |
| 86 | + .then((metadatas: compiler.CompileDirectiveMetadata[]) => { |
| 87 | + if (!metadatas || !metadatas.length) { |
| 88 | + return; |
| 89 | + } |
| 90 | + const generated = this.generateSource(metadatas); |
| 91 | + const sourceFile = this.program.getSourceFile(absSourcePath); |
| 92 | + |
| 93 | + // Write codegen in a directory structure matching the sources. |
| 94 | + // TODO(alexeagle): maybe use generated.moduleUrl instead of hardcoded ".ngfactory.ts" |
| 95 | + // TODO(alexeagle): relativize paths by the rootDirs option |
| 96 | + const emitPath = |
| 97 | + path.join(this.ngOptions.genDir, path.relative(this.basePath, absSourcePath)) |
| 98 | + .replace(SOURCE_EXTENSION, '.ngfactory.ts'); |
| 99 | + this.host.writeFile(emitPath, PREAMBLE + generated.source, false, () => {}, |
| 100 | + [sourceFile]); |
| 101 | + }) |
| 102 | + .catch((e) => { console.error(e.stack); }); |
| 103 | + |
| 104 | + return Promise.all(this.program.getRootFileNames() |
| 105 | + .filter(f => !/\.ngfactory\.ts$/.test(f)) |
| 106 | + .map(generateOneFile)); |
| 107 | + } |
| 108 | + |
| 109 | + static create(ngOptions: AngularCompilerOptions, parsed: ts.ParsedCommandLine, basePath: string, |
| 110 | + compilerHost: ts.CompilerHost): |
| 111 | + {errors?: ts.Diagnostic[], generator?: CodeGenerator} { |
| 112 | + const program = ts.createProgram(parsed.fileNames, parsed.options, compilerHost); |
| 113 | + const errors = program.getOptionsDiagnostics(); |
| 114 | + if (errors && errors.length) { |
| 115 | + return {errors}; |
| 116 | + } |
| 117 | + |
| 118 | + const metadataCollector = new MetadataCollector(); |
| 119 | + const reflectorHost = |
| 120 | + new NodeReflectorHost(program, metadataCollector, compilerHost, parsed.options); |
| 121 | + const xhr: compiler.XHR = {get: (s: string) => Promise.resolve(compilerHost.readFile(s))}; |
| 122 | + const urlResolver: compiler.UrlResolver = compiler.createOfflineCompileUrlResolver(); |
| 123 | + const staticReflector = new StaticReflector(reflectorHost); |
| 124 | + const htmlParser = new HtmlParser(); |
| 125 | + const normalizer = new DirectiveNormalizer(xhr, urlResolver, htmlParser); |
| 126 | + const parser = new Parser(new Lexer()); |
| 127 | + const tmplParser = new TemplateParser(parser, new DomElementSchemaRegistry(), htmlParser, |
| 128 | + /*console*/ null, [new RouterLinkTransform(parser)]); |
| 129 | + const offlineCompiler = new compiler.OfflineCompiler( |
| 130 | + normalizer, tmplParser, new StyleCompiler(urlResolver), |
| 131 | + new ViewCompiler(new compiler.CompilerConfig(true, true, true)), new TypeScriptEmitter()); |
| 132 | + const resolver = new CompileMetadataResolver( |
| 133 | + new compiler.DirectiveResolver(staticReflector), new compiler.PipeResolver(staticReflector), |
| 134 | + new compiler.ViewResolver(staticReflector), null, null, staticReflector); |
| 135 | + |
| 136 | + return { |
| 137 | + generator: new CodeGenerator(ngOptions, basePath, program, |
| 138 | + wrapCompilerHost(compilerHost, parsed.options), staticReflector, |
| 139 | + resolver, offlineCompiler, reflectorHost) |
| 140 | + }; |
| 141 | + } |
| 142 | +} |
0 commit comments