diff --git a/modules/aspnetcore-engine/README.md b/modules/aspnetcore-engine/README.md new file mode 100644 index 000000000..e3e57c9eb --- /dev/null +++ b/modules/aspnetcore-engine/README.md @@ -0,0 +1,342 @@ +# Angular & ASP.NET Core Engine + +This is an ASP.NET Core Engine for running Angular Apps on the server for server side rendering. + +--- + +## Example Application utilizing this Engine + +#### [Asp.net Core & Angular advanced starter application](https://github.com/MarkPieszak/aspnetcore-angular2-universal) + +# Usage + +> Things have changed since the previous ASP.NET Core & Angular Universal useage. We're no longer using TagHelpers, but now invoking the **boot-server** file from the **Home Controller** *itself*, and passing all the data down to .NET. + +Within our boot-server file, things haven't changed much, you still have your `createServerRenderer()` function that's being exported (this is what's called within the Node process) which is expecting a `Promise` to be returned. + +Within that promise we simply call the ngAspnetCoreEngine itself, passing in our providers Array (here we give it the current `url` from the Server, and also our Root application, which in our case is just ``). + + +```ts +// Polyfills +import 'es6-promise'; +import 'es6-shim'; +import 'reflect-metadata'; +import 'zone.js'; + +import { enableProdMode } from '@angular/core'; +import { INITIAL_CONFIG } from '@angular/platform-server'; +import { createServerRenderer, RenderResult } from 'aspnet-prerendering'; +// Grab the (Node) server-specific NgModule +import { AppServerModule } from './app/app.server.module'; +// ***** The ASPNETCore Angular Engine ***** +import { ngAspnetCoreEngine } from '@universal/ng-aspnetcore-engine'; + +enableProdMode(); // for faster server rendered builds + +export default createServerRenderer(params => { + + /* + * How can we access data we passed from .NET ? + * you'd access it directly from `params.data` under the name you passed it + * ie: params.data.WHATEVER_YOU_PASSED + * ------- + * We'll show in the next section WHERE you pass this Data in on the .NET side + */ + + // Platform-server provider configuration + const setupOptions: IEngineOptions = { + appSelector: '', + ngModule: ServerAppModule, + request: params, + providers: [ + /* Other providers you want to pass into the App would go here + * { provide: CookieService, useClass: ServerCookieService } + + * ie: Just an example of Dependency injecting a Class for providing Cookies (that you passed down from the server) + (Where on the browser you'd have a different class handling cookies normally) + */ + ] + }; + + // ***** Pass in those Providers & your Server NgModule, and that's it! + return ngAspnetCoreEngine(setupOptions).then(response => { + + // Want to transfer data from Server -> Client? + + // Add transferData to the response.globals Object, and call createTransferScript({}) passing in the Object key/values of data + // createTransferScript() will JSON Stringify it and return it as a + // That your browser can pluck and grab the data from + response.globals.transferData = createTransferScript({ + someData: 'Transfer this to the client on the window.TRANSFER_CACHE {} object', + fromDotnet: params.data.thisCameFromDotNET // example of data coming from dotnet, in HomeController + }); + + return ({ + html: response.html, + globals: response.globals + }); + + }); +}); + +``` + +# What about on the .NET side? + +Previously, this was all done with TagHelpers and you passed in your boot-server file to it: ``, but this hindered us from getting the SEO benefits of prerendering. + +Because .NET has control over the Html, using the ngAspnetCoreEngine, we're able to *pull out the important pieces*, and give them back to .NET to place them through out the View. + +Below is how you can invoke the boot-server file which gets everything started: + +> Hopefully in the future this will be cleaned up and less code as well. + +### HomeController.cs + +```csharp +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc; + +using Microsoft.AspNetCore.SpaServices.Prerendering; +using Microsoft.AspNetCore.NodeServices; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Http.Features; + +namespace WebApplicationBasic.Controllers +{ + public class HomeController : Controller + { + public async Task Index() + { + var nodeServices = Request.HttpContext.RequestServices.GetRequiredService(); + var hostEnv = Request.HttpContext.RequestServices.GetRequiredService(); + + var applicationBasePath = hostEnv.ContentRootPath; + var requestFeature = Request.HttpContext.Features.Get(); + var unencodedPathAndQuery = requestFeature.RawTarget; + var unencodedAbsoluteUrl = $"{Request.Scheme}://{Request.Host}{unencodedPathAndQuery}"; + + // ********************************* + // This parameter is where you'd pass in an Object of data you want passed down to Angular + // to be used in the Server-rendering + + // ** TransferData concept ** + // Here we can pass any Custom Data we want ! + + // By default we're passing down the REQUEST Object (Cookies, Headers, Host) from the Request object here + TransferData transferData = new TransferData(); + transferData.request = AbstractHttpContextRequestInfo(Request); // You can automatically grab things from the REQUEST object in Angular because of this + transferData.thisCameFromDotNET = "Hi Angular it's asp.net :)"; + // Add more customData here, add it to the TransferData class + + // Prerender / Serialize application (with Universal) + var prerenderResult = await Prerenderer.RenderToString( + "/", // baseURL + nodeServices, + new JavaScriptModuleExport(applicationBasePath + "/ClientApp/dist/main-server"), + unencodedAbsoluteUrl, + unencodedPathAndQuery, + // Our Transfer data here will be passed down to Angular (within the boot-server file) + // Available there via `params.data.yourData` + transferData, + 30000, // timeout duration + Request.PathBase.ToString() + ); + + // This is where everything is now spliced out, and given to .NET in pieces + ViewData["SpaHtml"] = prerenderResult.Html; + ViewData["Title"] = prerenderResult.Globals["title"]; + ViewData["Styles"] = prerenderResult.Globals["styles"]; + ViewData["Meta"] = prerenderResult.Globals["meta"]; + ViewData["Links"] = prerenderResult.Globals["links"]; + ViewData["TransferData"] = prerenderResult.Globals["transferData"]; // our transfer data set to window.TRANSFER_CACHE = {}; + + // Let's render that Home/Index view + return View(); + } + + private IRequest AbstractHttpContextRequestInfo(HttpRequest request) + { + + IRequest requestSimplified = new IRequest(); + requestSimplified.cookies = request.Cookies; + requestSimplified.headers = request.Headers; + requestSimplified.host = request.Host; + + return requestSimplified; + } + + } + + public class IRequest + { + public object cookies { get; set; } + public object headers { get; set; } + public object host { get; set; } + } + + public class TransferData + { + // By default we're expecting the REQUEST Object (in the aspnet engine), so leave this one here + public dynamic request { get; set; } + + // Your data here ? + public object thisCameFromDotNET { get; set; } + } +} +``` + +### Startup.cs : Make sure you add NodeServices to ConfigureServices: + +```csharp +public void ConfigureServices(IServiceCollection services) +{ + // ... other things ... + + services.AddNodeServices(); // <-- +} +``` + +# What updates do our Views need now? + +Now we have a whole assortment of SEO goodness we can spread around our .NET application. Not only do we have our serialized Application in a String... + +We also have ``, `<meta>`, `<link>'s`, and our applications `<styles>` + +In our _layout.cshtml, we're going to want to pass in our different `ViewData` pieces and place these where they needed to be. + +> Notice `ViewData[]` sprinkled through out. These came from our Angular application, but it returned an entire HTML document, we want to build up our document ourselves so .NET handles it! + +```html +<!DOCTYPE html> +<html> + <head> + <base href="/" /> + <!-- Title will be the one you set in your Angular application --> + <title>@ViewData["Title"] + + @Html.Raw(ViewData["Meta"]) + @Html.Raw(ViewData["Links"]) + @Html.Raw(ViewData["Styles"]) + + + + + @RenderBody() + + + @Html.Raw(ViewData["TransferData"]) + + @RenderSection("scripts", required: false) + + +``` + +--- + +# Your Home View - where the App gets displayed: + +You may have seen or used a TagHelper here in the past (that's where it used to invoke the Node process and everything), but now since we're doing everything +in the **Controller**, we only need to grab our `ViewData["SpaHtml"]` and inject it! + +This `SpaHtml` was set in our HomeController, and it's just a serialized string of your Angular application, but **only** the `/* inside is all serialized */` part, not the entire Html, since we split that up, and let .NET build out our Document. + +```html +@Html.Raw(ViewData["SpaHtml"]) + + + +@section scripts { + +} +``` + +--- + +# What happens after the App gets server rendered? + +Well now, your Client-side Angular will take over, and you'll have a fully functioning SPA. (With all these great SEO benefits of being server-rendered) ! + +:sparkles: + +--- + +## Bootstrap + +The engine also calls the ngOnBootstrap lifecycle hook of the module being bootstrapped, this is how the TransferData gets taken. +Check [https://github.com/MarkPieszak/aspnetcore-angular2-universal/tree/master/Client/modules](https://github.com/MarkPieszak/aspnetcore-angular2-universal/tree/master/Client/modules) to see how to setup your Transfer classes. + +```ts +@NgModule({ + bootstrap: [AppComponent] +}) +export class ServerAppModule { + // Make sure to define this an arrow function to keep the lexical scope + ngOnBootstrap = () => { + console.log('bootstrapped'); + } +} +``` + +# Tokens + +Along with the engine doing serializing and separating out the chunks of your Application (so we can let .NET handle it), you may have noticed we passed in the HttpRequest object from .NET into it as well. + +This was done so that we could take a few things from it, and using dependency injection, "provide" a few things to the Angular application. + +```typescript +ORIGIN_URL +// and +REQUEST + +// imported +import { ORIGIN_URL, REQUEST } from '@ng-universal/ng-aspnetcore-engine'; +``` + +Make sure in your BrowserModule you provide these tokens as well, if you're going to use them! + +```typescript +@NgModule({ + ..., + providers: [ + { + // We need this for our Http calls since they'll be using an ORIGIN_URL provided in main.server + // (Also remember the Server requires Absolute URLs) + provide: ORIGIN_URL, + useFactory: (getOriginUrl) + }, { + // The server provides these in main.server + provide: REQUEST, + useFactory: (getRequest) + } + ] +} export class BrowserAppModule() {} +``` + +Don't forget that the server needs Absolute URLs for paths when doing Http requests! So if your server api is at the same location as this Angular app, you can't just do `http.get('/api/whatever')` so use the ORIGIN_URL Injection Token. + +```typescript + import { ORIGIN_URL } from '@ng-universal/ng-aspnetcore-engine'; + + constructor(@Inject(ORIGIN_URL) private originUrl: string, private http: Http) { + this.http.get(`${this.originUrl}/api/whatever`) + } +``` + +As for the REQUEST object, you'll find Cookies, Headers, and Host (from .NET that we passed down in our HomeController. They'll all be accessible from that Injection Token as well. + +```typescript + import { REQUEST } from '@ng-universal/ng-aspnetcore-engine'; + + constructor(@Inject(REQUEST) private request) { + // this.request.cookies + // this.request.headers + // etc + } + +``` + + + diff --git a/modules/aspnetcore-engine/index.ts b/modules/aspnetcore-engine/index.ts new file mode 100644 index 000000000..0a23d586a --- /dev/null +++ b/modules/aspnetcore-engine/index.ts @@ -0,0 +1,8 @@ + +export { ngAspnetCoreEngine } from './src/main'; +export { createTransferScript } from './src/create-transfer-script'; + +export { REQUEST, ORIGIN_URL } from './src/tokens'; + +export { IEngineOptions } from './src/interfaces/engine-options'; +export { IRequestParams } from './src/interfaces/request-params'; diff --git a/modules/aspnetcore-engine/package.json b/modules/aspnetcore-engine/package.json new file mode 100644 index 000000000..cf3df18af --- /dev/null +++ b/modules/aspnetcore-engine/package.json @@ -0,0 +1,54 @@ +{ + "name": "@universal/ng-aspnetcore-engine", + "main": "dist/index.js", + "types": "dist/index.d.ts", + "version": "1.0.0-beta.0", + "description": "ASP.NET Core Engine for running Server Angular Apps", + "homepage": "https://github.com/angular/universal", + "license": "MIT", + "author": { + "name": "MarkPieszak", + "email": "mpieszak84@gmail.com", + "url": "github.com/markpieszak" + }, + "contributors": [ + "MarkPieszak" + ], + "repository": { + "type": "git", + "url": "https://github.com/angular/universal" + }, + "bugs": { + "url": "https://github.com/angular/universal/issues" + }, + "config": { + "engine-strict": true + }, + "engines": { + "node": ">= 5.4.1 <= 7", + "npm": ">= 3" + }, + "scripts": { + "build": "tsc", + "prebuild": "rimraf dist" + }, + "peerDependencies": { + "@angular/core": "^4.0.0", + "@angular/platform-server": "^4.0.0" + }, + "devDependencies": { + "@angular/common": "^4.0.0", + "@angular/compiler": "^4.0.0", + "@angular/core": "^4.0.0", + "@angular/http": "^4.0.0", + "@angular/platform-browser": "^4.0.0", + "@angular/platform-server": "^4.0.0", + "rimraf": "^2.6.1", + "rxjs": "^5.2.0", + "typescript": "^2.2.1", + "zone.js": "^0.8.4" + }, + "dependencies": { + "@types/node": "^7.0.13" + } +} diff --git a/modules/aspnetcore-engine/src/create-transfer-script.ts b/modules/aspnetcore-engine/src/create-transfer-script.ts new file mode 100644 index 000000000..15b299d07 --- /dev/null +++ b/modules/aspnetcore-engine/src/create-transfer-script.ts @@ -0,0 +1,3 @@ +export function createTransferScript(transferData: Object): string { + return ``; +} \ No newline at end of file diff --git a/modules/aspnetcore-engine/src/file-loader.ts b/modules/aspnetcore-engine/src/file-loader.ts new file mode 100644 index 000000000..430fc9174 --- /dev/null +++ b/modules/aspnetcore-engine/src/file-loader.ts @@ -0,0 +1,17 @@ +import * as fs from 'fs'; +import { ResourceLoader } from '@angular/compiler'; + +export class FileLoader implements ResourceLoader { + get(url: string): Promise { + return new Promise((resolve, reject) => { + // install node types + fs.readFile(url, (err: NodeJS.ErrnoException, buffer: Buffer) => { + if (err) { + return reject(err); + } + + resolve(buffer.toString()); + }); + }); + } +} diff --git a/modules/aspnetcore-engine/src/interfaces/engine-options.ts b/modules/aspnetcore-engine/src/interfaces/engine-options.ts new file mode 100644 index 000000000..8b9bd7355 --- /dev/null +++ b/modules/aspnetcore-engine/src/interfaces/engine-options.ts @@ -0,0 +1,9 @@ +import { IRequestParams } from "./request-params"; +import { Type, NgModuleFactory, Provider } from '@angular/core'; + +export interface IEngineOptions { + appSelector: string; + request: IRequestParams; + ngModule: Type<{}> | NgModuleFactory<{}>; + providers?: Provider[]; +}; diff --git a/modules/aspnetcore-engine/src/interfaces/request-params.ts b/modules/aspnetcore-engine/src/interfaces/request-params.ts new file mode 100644 index 000000000..2d989eca0 --- /dev/null +++ b/modules/aspnetcore-engine/src/interfaces/request-params.ts @@ -0,0 +1,9 @@ +export interface IRequestParams { + location: any; // e.g., Location object containing information '/some/path' + origin: string; // e.g., 'https://example.com:1234' + url: string; // e.g., '/some/path' + baseUrl: string; // e.g., '' or '/myVirtualDir' + absoluteUrl: string; // e.g., 'https://example.com:1234/some/path' + domainTasks: Promise; + data: any; // any custom object passed through from .NET +} \ No newline at end of file diff --git a/modules/aspnetcore-engine/src/main.ts b/modules/aspnetcore-engine/src/main.ts new file mode 100644 index 000000000..0c1afbd60 --- /dev/null +++ b/modules/aspnetcore-engine/src/main.ts @@ -0,0 +1,203 @@ +import { Type, NgModuleFactory, NgModuleRef, ApplicationRef, CompilerFactory, Compiler } from '@angular/core'; +import { platformServer, platformDynamicServer, PlatformState, INITIAL_CONFIG } from '@angular/platform-server'; +import { ResourceLoader } from '@angular/compiler'; + +import { REQUEST, ORIGIN_URL } from './tokens'; +import { FileLoader } from './file-loader'; + +import { IEngineOptions } from './interfaces/engine-options'; + +import 'rxjs/add/operator/filter'; +import 'rxjs/add/operator/first'; + +export function ngAspnetCoreEngine( + options: IEngineOptions +): Promise<{ html: string, globals: { styles: string, title: string, meta: string, transferData?: {}, [key: string]: any } }> { + + options.providers = options.providers || []; + + const compilerFactory: CompilerFactory = platformDynamicServer().injector.get(CompilerFactory); + const compiler: Compiler = compilerFactory.createCompiler([ + { + providers: [ + { provide: ResourceLoader, useClass: FileLoader } + ] + } + ]); + + return new Promise((resolve, reject) => { + + try { + const moduleOrFactory = options.ngModule; + if (!moduleOrFactory) { + throw new Error('You must pass in a NgModule or NgModuleFactory to be bootstrapped'); + } + + const extraProviders = options.providers.concat( + options.providers, + [ + { + provide: INITIAL_CONFIG, + useValue: { + document: options.appSelector, + url: options.request.url + } + }, + { + provide: ORIGIN_URL, + useValue: options.request.origin + }, { + provide: REQUEST, + useValue: options.request.data.request + } + ] + ); + + const platform = platformServer(extraProviders); + + getFactory(moduleOrFactory, compiler) + .then((factory: NgModuleFactory<{}>) => { + + return platform.bootstrapModuleFactory(factory).then((moduleRef: NgModuleRef<{}>) => { + + const state: PlatformState = moduleRef.injector.get(PlatformState); + const appRef: ApplicationRef = moduleRef.injector.get(ApplicationRef); + + appRef.isStable + .filter((isStable: boolean) => isStable) + .first() + .subscribe(() => { + + // Fire the TransferState Cache + const bootstrap = moduleRef.instance['ngOnBootstrap']; + bootstrap && bootstrap(); + + // The parse5 Document itself + const AST_DOCUMENT = state.getDocument(); + + // Strip out the Angular application + const htmlDoc = state.renderToString(); + + const APP_HTML = htmlDoc.substring( + htmlDoc.indexOf('') + 6, + htmlDoc.indexOf('') + ); + + // Strip out Styles / Meta-tags / Title + // const STYLES = []; + const META = []; + const LINKS = []; + let TITLE = ''; + + let STYLES_STRING = htmlDoc.substring( + htmlDoc.indexOf('`; + // STYLES.push(styleTag); + // } + + if (element.name === 'meta') { + count = count + 1; + let metaString = '\n`); + } + + if (element.name === 'link') { + let linkString = '\n`); + } + } + + // Return parsed App + resolve({ + html: APP_HTML, + globals: { + styles: STYLES_STRING, + title: TITLE, + meta: META.join(' '), + links: LINKS.join(' ') + } + }); + + moduleRef.destroy(); + + }, (err) => { + reject(err); + }); + + }); + }); + + } catch (ex) { + reject(ex); + } + + }); +} + +/* ********************** Private / Internal ****************** */ + +const factoryCacheMap = new Map, NgModuleFactory<{}>>(); +function getFactory( + moduleOrFactory: Type<{}> | NgModuleFactory<{}>, compiler: Compiler +): Promise> { + return new Promise>((resolve, reject) => { + // If module has been compiled AoT + if (moduleOrFactory instanceof NgModuleFactory) { + resolve(moduleOrFactory); + return; + } else { + let moduleFactory = factoryCacheMap.get(moduleOrFactory); + + // If module factory is cached + if (moduleFactory) { + resolve(moduleFactory); + return; + } + + // Compile the module and cache it + compiler.compileModuleAsync(moduleOrFactory) + .then((factory) => { + factoryCacheMap.set(moduleOrFactory, factory); + resolve(factory); + }, (err => { + reject(err); + })); + } + }); +} diff --git a/modules/aspnetcore-engine/src/tokens.ts b/modules/aspnetcore-engine/src/tokens.ts new file mode 100644 index 000000000..701e7670b --- /dev/null +++ b/modules/aspnetcore-engine/src/tokens.ts @@ -0,0 +1,4 @@ +import { InjectionToken } from '@angular/core'; + +export const REQUEST = new InjectionToken('REQUEST'); +export const ORIGIN_URL = new InjectionToken('ORIGIN_URL'); diff --git a/modules/aspnetcore-engine/tsconfig.json b/modules/aspnetcore-engine/tsconfig.json new file mode 100644 index 000000000..1b8e7f387 --- /dev/null +++ b/modules/aspnetcore-engine/tsconfig.json @@ -0,0 +1,36 @@ +{ + "compilerOptions": { + "target": "es6", + "module": "es2015", + "moduleResolution": "node", + "declaration": true, + "noImplicitAny": false, + "noUnusedLocals": true, + "noImplicitReturns": true, + "noImplicitThis": true, + "noUnusedParameters": true, + "removeComments": false, + "baseUrl": ".", + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "sourceMap": true, + "inlineSources": true, + "rootDir": ".", + "outDir": "dist", + "lib": [ + "dom", + "es6" + ], + "types": [ + "node" + ] + }, + "files": [ + "index.ts" + ], + "compileOnSave": false, + "buildOnSave": false, + "atom": { + "rewriteTsconfig": false + } +} \ No newline at end of file