-
Notifications
You must be signed in to change notification settings - Fork 2
/
ChunkVisitorMinifyingMvcRazorHost.cs
304 lines (272 loc) · 12.4 KB
/
ChunkVisitorMinifyingMvcRazorHost.cs
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.Razor.Directives;
using Microsoft.AspNetCore.Razor;
using Microsoft.AspNetCore.Razor.Chunks;
using Microsoft.AspNetCore.Razor.CodeGenerators;
using Microsoft.AspNetCore.Razor.Parser;
using Microsoft.AspNetCore.Razor.CodeGenerators.Visitors;
using Microsoft.AspNetCore.Razor.Compilation.TagHelpers;
using System.Text;
using System.Text.RegularExpressions;
namespace GuardRex.MinifyingMvcRazorHost
{
public class ChunkVisitorMinifyingMvcRazorHost : IMvcRazorHost
{
private readonly MvcRazorHost _host;
public static bool HasOnlySeenOpenBracket = false;
public string DefaultNamespace => _host.DefaultNamespace;
public string MainClassNamePrefix => _host.DefaultClassName;
private ChunkInheritanceUtility _chunkInheritanceUtility;
private readonly IChunkTreeCache _chunkTreeCache;
private const string ModelExpressionProviderProperty = "ModelExpressionProvider";
private const string ViewDataProperty = "ViewData";
public ChunkVisitorMinifyingMvcRazorHost(IChunkTreeCache chunkTreeCache, ITagHelperDescriptorResolver descriptorResolver)
{
_chunkTreeCache = chunkTreeCache;
_host = new MvcRazorHost(chunkTreeCache, descriptorResolver);
}
public GeneratorResults GenerateCode(string rootRelativePath, Stream inputStream)
{
var className = MainClassNamePrefix + ParserHelpers.SanitizeClassName(rootRelativePath);
var engine = new CustomRazorTemplateEngine(this, _host);
return engine.GenerateCode(inputStream, className, DefaultNamespace, rootRelativePath);
}
public CodeGenerator DecorateCodeGenerator(CodeGenerator incomingGenerator, CodeGeneratorContext context)
{
var inheritedChunkTrees = GetInheritedChunkTrees(context.SourceFile);
ChunkInheritanceUtility.MergeInheritedChunkTrees(
context.ChunkTreeBuilder.Root,
inheritedChunkTrees,
_host.DefaultModel);
return new CustomCSharpCodeGenerator(
context,
_host.DefaultModel,
_host.InjectAttribute,
new GeneratedTagHelperAttributeContext
{
ModelExpressionTypeName = _host.ModelExpressionType,
CreateModelExpressionMethodName = _host.CreateModelExpressionMethod,
ModelExpressionProviderPropertyName = ModelExpressionProviderProperty,
ViewDataPropertyName = ViewDataProperty
});
}
public virtual string ModelExpressionProvider
{
get { return ModelExpressionProviderProperty; }
}
public virtual string ViewDataPropertyName
{
get { return ViewDataProperty; }
}
internal ChunkInheritanceUtility ChunkInheritanceUtility
{
get
{
if (_chunkInheritanceUtility == null)
{
_chunkInheritanceUtility = new ChunkInheritanceUtility(_host, _chunkTreeCache, _host.DefaultInheritedChunks);
}
return _chunkInheritanceUtility;
}
set
{
_chunkInheritanceUtility = value;
}
}
private IReadOnlyList<ChunkTree> GetInheritedChunkTrees(string sourceFileName)
{
var inheritedChunkTrees = _host.GetInheritedChunkTreeResults(sourceFileName)
.Select(result => result.ChunkTree)
.ToList();
return inheritedChunkTrees;
}
}
public class CustomRazorTemplateEngine : RazorTemplateEngine
{
private ChunkVisitorMinifyingMvcRazorHost _myHost;
public CustomRazorTemplateEngine(ChunkVisitorMinifyingMvcRazorHost myHost, MvcRazorHost host) : base(host)
{
_myHost = myHost;
}
protected override CodeGenerator CreateCodeGenerator(CodeGeneratorContext context)
{
return _myHost.DecorateCodeGenerator(Host.CodeLanguage.CreateCodeGenerator(context), context);
}
}
public class CustomCSharpCodeGenerator : MvcCSharpCodeGenerator
{
private GeneratedTagHelperAttributeContext _tagHelperAttributeContext;
public CustomCSharpCodeGenerator(CodeGeneratorContext context, string defaultModel, string injectAttribute, GeneratedTagHelperAttributeContext tagHelperAttributeContext) : base(context, defaultModel, injectAttribute, tagHelperAttributeContext)
{
_tagHelperAttributeContext = tagHelperAttributeContext;
}
protected override CSharpCodeVisitor CreateCSharpCodeVisitor(CSharpCodeWriter writer, CodeGeneratorContext context)
{
var csharpCodeVisitor = new CustomCSharpCodeVisitor(writer, context);
csharpCodeVisitor.TagHelperRenderer.AttributeValueCodeRenderer = new MvcTagHelperAttributeValueCodeRenderer(_tagHelperAttributeContext);
return csharpCodeVisitor;
}
}
public class CustomCSharpCodeVisitor : CSharpCodeVisitor
{
public CustomCSharpCodeVisitor(CSharpCodeWriter writer, CodeGeneratorContext context) : base(writer, context)
{ }
private bool _outsideOfElement = true;
private bool _comingOffHyperlink = false;
private StringBuilder chunkStringBuilder = new StringBuilder();
private StringBuilder chunkCharactersStringBuilder = new StringBuilder();
private const int MaxStringLiteralLength = 1024;
protected override void Visit(ParentLiteralChunk chunk)
{
if (Context.Host.DesignTimeMode)
{
// Skip generating the chunk if we're in design time or if the chunk is empty.
return;
}
var text = chunk.GetText();
if (Context.Host.EnableInstrumentation)
{
var start = chunk.Start.AbsoluteIndex;
Writer.WriteStartInstrumentationContext(Context, start, text.Length, isLiteral: true);
}
RenderStartWriteLiteral(MinifyChunk(text));
if (Context.Host.EnableInstrumentation)
{
Writer.WriteEndInstrumentationContext(Context);
}
}
protected override void Visit(LiteralChunk chunk)
{
if (Context.Host.DesignTimeMode || string.IsNullOrEmpty(chunk.Text))
{
// Skip generating the chunk if we're in design time or if the chunk is empty.
return;
}
if (Context.Host.EnableInstrumentation)
{
Writer.WriteStartInstrumentationContext(Context, chunk.Association, isLiteral: true);
}
RenderStartWriteLiteral(MinifyChunk(chunk.Text));
if (Context.Host.EnableInstrumentation)
{
Writer.WriteEndInstrumentationContext(Context);
}
}
protected override void Visit(TagHelperChunk chunk)
{
if (chunk.TagName == "a")
{
Writer.Write(@"WriteLiteral("" "");");
TagHelperRenderer.RenderTagHelper(chunk);
_comingOffHyperlink = true;
}
else
{
TagHelperRenderer.RenderTagHelper(chunk);
}
}
private void RenderStartWriteLiteral(string text)
{
var charactersRendered = 0;
// Render the string in pieces to avoid Roslyn OOM exceptions at compile time:
// https://github.com/aspnet/External/issues/54
while (charactersRendered < text.Length)
{
if (Context.ExpressionRenderingMode == ExpressionRenderingMode.WriteToOutput)
{
if (!string.IsNullOrEmpty(Context.TargetWriterName))
{
Writer.WriteStartMethodInvocation(Context.Host.GeneratedClassContext.WriteLiteralToMethodName)
.Write(Context.TargetWriterName)
.WriteParameterSeparator();
}
else
{
Writer.WriteStartMethodInvocation(Context.Host.GeneratedClassContext.WriteLiteralMethodName);
}
}
string textToRender;
if (text.Length <= MaxStringLiteralLength)
{
textToRender = text;
}
else
{
int charRemaining = text.Length - charactersRendered;
if (charRemaining < MaxStringLiteralLength)
{
textToRender = text.Substring(charactersRendered, charRemaining);
}
else
{
textToRender = text.Substring(charactersRendered, MaxStringLiteralLength);
}
}
Writer.WriteStringLiteral(textToRender);
charactersRendered += textToRender.Length;
if (Context.ExpressionRenderingMode == ExpressionRenderingMode.WriteToOutput)
{
Writer.WriteEndMethodInvocation();
}
}
}
private string MinifyChunk(string chunkText)
{
chunkStringBuilder.Clear();
chunkCharactersStringBuilder.Clear();
foreach (char c in chunkText)
{
if (_outsideOfElement)
{
if (!c.Equals('<'))
{
// Collect this inter-element character for processing later
chunkCharactersStringBuilder.Append(c);
}
else
{
// We just came to the end of an inter-element sequence of characters ... process these characters now
_outsideOfElement = false;
chunkStringBuilder.Append(MinifyCharacters(chunkCharactersStringBuilder.ToString()) + c);
chunkCharactersStringBuilder.Clear();
}
}
else
{
// Accumulate this element character to the output chunk
chunkStringBuilder.Append(c);
if (c.Equals('>'))
{
// Time to start collecting and processing characters again
_outsideOfElement = true;
}
}
}
// Minify and add any leftover characters b/c we didn't reach the end of an inter-element sequence in this chunk
chunkStringBuilder.Append(MinifyCharacters(chunkCharactersStringBuilder.ToString()));
// Look around here and see if we can add a space back around inline elements that are inside the chunk
// This assumes the inline element is next to the text IN THE SAME chunk. [That might be a bad assumption!]
if (_comingOffHyperlink)
{
_comingOffHyperlink = false;
var chunkStringBuilderVal = chunkStringBuilder.ToString();
if (chunkStringBuilderVal.Length > 0 && Regex.IsMatch(chunkStringBuilderVal.Substring(0, 1), "[A-Za-z0-9]"))
{
return " " + AddSpaceBack(chunkStringBuilderVal);
}
}
return AddSpaceBack(chunkStringBuilder.ToString());
}
private string MinifyCharacters(string inputString)
{
return inputString.Replace("\t", string.Empty).Replace("\r", string.Empty).Replace("\n", string.Empty).Trim(' ');
}
private string AddSpaceBack(string inputString)
{
return Regex.Replace(inputString, "((?<=\\S)(?=(<a|<b|<big|<i|<small|<tt|<abbr|<acronym|<cite|<code|<dfn|<em|<kbd|<strong|<samp|<time|<var|<bdo|<br|<img|<map|<object|<q|<span|<sub|<sup|<button|<input|<label|<select|<textarea)))|((?<=(/a>|/b>|/big>|/i>|/small>|/tt>|/abbr>|/acronym>|/cite>|/code>|/dfn>|/em>|/kbd>|/strong>|/samp>|/time>|/var>|/bdo>|/br>|/map>|/object>|/q>|/span>|/sub>|/sup>|/button>|/input>|/label>|/select>|/textarea>))(?=[A-Za-z0-9]))", " ");
}
}
}