-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathnunjucksCompiler.ts
173 lines (159 loc) · 5.34 KB
/
nunjucksCompiler.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import { Compiler, CompileResult } from './compiler';
import * as nunjucks from 'nunjucks';
import * as transformer from 'nunjucks/src/transformer';
import { inject, injectable, multiInject, named, optional } from 'inversify';
import { TYPES } from '@vulcan-sql/core/types';
import {
generateMetadata,
implementedOnAstVisit,
implementedProvideMetadata,
OnAstVisit,
ProvideMetadata,
walkAst,
} from './extension-utils';
import { IDataQueryBuilder } from '../data-query';
import {
Pagination,
TemplateEngineExtension,
RuntimeExtension,
CompileTimeExtension,
TagBuilder,
TagRunner,
FilterBuilder,
FilterRunner,
} from '@vulcan-sql/core/models';
@injectable()
export class NunjucksCompiler implements Compiler {
public name = 'nunjucks';
private runtimeEnv: nunjucks.Environment;
private compileTimeEnv: nunjucks.Environment;
private extensions: TemplateEngineExtension[];
private astVisitors: OnAstVisit[] = [];
private metadataProviders: ProvideMetadata[] = [];
private extensionsInitialized = false;
constructor(
@multiInject(TYPES.Extension_TemplateEngine)
@optional()
extensions: TemplateEngineExtension[] = [],
@inject(TYPES.CompilerEnvironment)
@named('runtime')
runtimeEnv: nunjucks.Environment,
@inject(TYPES.CompilerEnvironment)
@named('compileTime')
compileTimeEnv: nunjucks.Environment
) {
this.runtimeEnv = runtimeEnv;
this.compileTimeEnv = compileTimeEnv;
this.extensions = extensions;
this.loadAllExtensions();
}
public async compile(template: string): Promise<CompileResult> {
await this.initializeExtensions();
const compiler = new nunjucks.compiler.Compiler(
'main',
this.compileTimeEnv.opts.throwOnUndefined || false
);
const { ast, metadata } = this.generateAst(template);
compiler.compile(ast);
const code = compiler.getCode();
return { compiledData: `(() => {${code}})()`, metadata };
}
public generateAst(template: string) {
const ast = nunjucks.parser.parse(
template,
this.compileTimeEnv.extensionsList,
{}
);
this.traverseAst(ast);
const metadata = this.getMetadata();
const preProcessedAst = this.preProcess(ast);
return { ast: preProcessedAst, metadata };
}
public async execute<T extends object>(
templateName: string,
data: T,
pagination?: Pagination
): Promise<any> {
await this.initializeExtensions();
const builder = await this.renderAndGetMainBuilder(templateName, data);
if (pagination) builder.paginate(pagination);
return builder.value();
}
public loadExtension(extension: TemplateEngineExtension): void {
if (extension instanceof RuntimeExtension) {
this.loadRuntimeExtensions(extension);
} else if (extension instanceof CompileTimeExtension) {
this.loadCompileTimeExtensions(extension);
} else {
throw new Error(
`Extension must be of type RuntimeExtension or CompileTimeExtension`
);
}
}
private loadAllExtensions(): void {
this.extensions.forEach((ext) => this.loadExtension(ext));
}
private loadCompileTimeExtensions(extension: CompileTimeExtension): void {
// Extends
if (extension instanceof TagBuilder) {
this.compileTimeEnv.addExtension(extension.getName(), extension);
} else if (extension instanceof FilterBuilder) {
this.compileTimeEnv.addFilter(
extension.filterName,
// eslint-disable-next-line @typescript-eslint/no-empty-function
() => {}, // We don't need to implement transform function in compile time
true
);
}
// Implement
if (implementedOnAstVisit(extension)) {
this.astVisitors.push(extension);
}
if (implementedProvideMetadata(extension)) {
this.metadataProviders.push(extension);
}
}
private loadRuntimeExtensions(extension: RuntimeExtension): void {
if (extension instanceof TagRunner) {
this.runtimeEnv.addExtension(extension.getName(), extension);
} else if (extension instanceof FilterRunner) {
this.runtimeEnv.addFilter(
extension.filterName,
extension.__transform.bind(extension),
true
);
}
}
private traverseAst(ast: nunjucks.nodes.Node) {
walkAst(ast, this.astVisitors);
}
/** Get some metadata from the AST tree, e.g. the errors defined by templates.
* It'll help use to validate templates, validate schema ...etc. */
private getMetadata() {
return generateMetadata(this.metadataProviders);
}
/** Process the AST tree before compiling */
private preProcess(ast: nunjucks.nodes.Node): nunjucks.nodes.Node {
// Nunjucks'll handle the async filter via pre-process functions
return transformer.transform(ast, this.compileTimeEnv.asyncFilters);
}
private renderAndGetMainBuilder(templateName: string, data: any) {
const template = this.runtimeEnv.getTemplate(templateName, true);
return new Promise<IDataQueryBuilder>((resolve, reject) => {
template.getExported<{ FINAL_BUILDER: IDataQueryBuilder }>(
data,
(err, res) => {
if (err) return reject(err);
else resolve(res.FINAL_BUILDER);
}
);
});
}
private async initializeExtensions() {
if (this.extensionsInitialized) return;
for (const extension of this.extensions) {
if (extension.activate) await extension.activate();
}
this.extensionsInitialized = true;
}
}