UNPKG

1.81 kBPlain TextView Raw
1import chalk = require('chalk');
2
3import {join} from 'path';
4
5import {Files} from '../static';
6import {OutputOptions} from './options';
7import {OutputProducer} from './producer';
8import {OutputException} from '../exception';
9import {fileFromString, pathFromString} from '../filesystem';
10import {Snapshot} from '../snapshot';
11import {log} from './log';
12import {pathFromUri} from '../route';
13import {transformInplace} from './transform';
14
15export class HtmlOutput implements OutputProducer {
16 constructor(private options: OutputOptions) {}
17
18 initialize() {
19 if (this.options.output == null) {
20 throw new OutputException('HTML output writer needs a path to write to');
21 }
22
23 if (this.options.output.exists() === false) {
24 try {
25 this.options.output.mkdir();
26 }
27 catch (exception) {
28 throw new OutputException(`Cannot create output folder: ${this.options.output.toString()}`, exception);
29 }
30
31 log.info(`Created output path: ${this.options.output.toString()}`);
32 }
33
34 return Promise.resolve();
35 }
36
37 async write<V>(snapshot: Snapshot<V>): Promise<void> {
38 const file = fileFromString(join(this.routedPathFromSnapshot(snapshot).toString(), Files.index));
39
40 transformInplace(file.parent(), snapshot, this.options);
41
42 log.info(`Rendered route ${pathFromUri(snapshot.uri)} to ${file}`);
43
44 file.create(snapshot.renderedDocument);
45
46 return Promise.resolve(void 0);
47 }
48
49 exception(exception: Error) {
50 log.error(`Fatal exception encountered: ${chalk.red(exception.toString())}`);
51
52 return Promise.resolve(void 0);
53 }
54
55 private routedPathFromSnapshot<V>(snapshot: Snapshot<V>) {
56 const routedPath = pathFromString(join(this.options.output.toString(), pathFromUri(snapshot.uri)));
57
58 routedPath.mkdir();
59
60 return routedPath;
61 }
62}