This repository has been archived by the owner on Mar 28, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
slowparse.js
2164 lines (1990 loc) · 78.5 KB
/
slowparse.js
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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Slowparse = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
// ### CSS Parsing
//
// `CSSParser` is our internal CSS token stream parser object. This object
// has references to the stream, as well as the HTML DOM builder that is
// used by the HTML parser.
module.exports = (function(){
"use strict";
var ParseError = require("./ParseError");
//Define a property checker for https page
var checkMixedContent = require("./checkMixedContent").mixedContent;
function CSSParser(stream, domBuilder, warnings) {
this.stream = stream;
// note: we do not actually use the domBuilder during CSS parsing
this.domBuilder = domBuilder;
this.warnings = warnings || [];
}
CSSParser.prototype = {
// We keep a list of all currently valid CSS properties (CSS1-CSS3).
// This list does not contain vendor prefixes.
cssProperties: [
"alignment-adjust","alignment-baseline","animation","animation-delay",
"animation-direction","animation-duration","animation-iteration-count",
"animation-name","animation-play-state","animation-timing-function",
"appearance","azimuth","backface-visibility","background",
"background-attachment","background-clip","background-color",
"background-image","background-origin","background-position",
"background-repeat","background-size","baseline-shift","binding",
"bleed","bookmark-label","bookmark-level","bookmark-state",
"bookmark-target","border","border-bottom","border-bottom-color",
"border-bottom-left-radius","border-bottom-right-radius",
"border-bottom-style","border-bottom-width","border-collapse",
"border-color","border-image","border-image-outset",
"border-image-repeat","border-image-slice","border-image-source",
"border-image-width","border-left","border-left-color",
"border-left-style","border-left-width","border-radius","border-right",
"border-right-color","border-right-style","border-right-width",
"border-spacing","border-style","border-top","border-top-color",
"border-top-left-radius","border-top-right-radius","border-top-style",
"border-top-width","border-width","bottom","box-decoration-break",
"box-shadow","box-sizing","break-after","break-before","break-inside",
"caption-side","clear","clip","color","color-profile","column-count",
"column-fill","column-gap","column-rule","column-rule-color",
"column-rule-style","column-rule-width","column-span","column-width",
"columns","content","counter-increment","counter-reset","crop","cue",
"cue-after","cue-before","cursor","direction","display",
"dominant-baseline","drop-initial-after-adjust",
"drop-initial-after-align","drop-initial-before-adjust",
"drop-initial-before-align","drop-initial-size","drop-initial-value",
"elevation","empty-cells","filter","fit","fit-position","flex-align",
"flex-flow","flex-line-pack","flex-order","flex-pack","float","float-offset",
"font","font-family","font-size","font-size-adjust","font-stretch",
"font-style","font-variant","font-weight","grid-columns","grid-rows",
"hanging-punctuation","height","hyphenate-after","hyphenate-before",
"hyphenate-character","hyphenate-lines","hyphenate-resource","hyphens",
"icon","image-orientation","image-rendering","image-resolution",
"inline-box-align","left","letter-spacing","line-break","line-height",
"line-stacking","line-stacking-ruby","line-stacking-shift",
"line-stacking-strategy","list-style","list-style-image",
"list-style-position","list-style-type","margin","margin-bottom",
"margin-left","margin-right","margin-top","marker-offset","marks",
"marquee-direction","marquee-loop","marquee-play-count","marquee-speed",
"marquee-style","max-height","max-width","min-height","min-width",
"move-to","nav-down","nav-index","nav-left","nav-right","nav-up",
"opacity","orphans","outline","outline-color","outline-offset",
"outline-style","outline-width","overflow","overflow-style",
"overflow-wrap","overflow-x","overflow-y","padding","padding-bottom",
"padding-left","padding-right","padding-top","page","page-break-after",
"page-break-before","page-break-inside","page-policy","pause",
"pause-after","pause-before","perspective","perspective-origin",
"phonemes","pitch","pitch-range","play-during","pointer-events",
"position",
"presentation-level","punctuation-trim","quotes","rendering-intent",
"resize","rest","rest-after","rest-before","richness","right",
"rotation","rotation-point","ruby-align","ruby-overhang",
"ruby-position","ruby-span","src","size","speak","speak-header",
"speak-numeral","speak-punctuation","speech-rate","stress","string-set",
"tab-size","table-layout","target","target-name","target-new",
"target-position","text-align","text-align-last","text-decoration",
"text-decoration-color","text-decoration-line","text-decoration-skip",
"text-decoration-style","text-emphasis","text-emphasis-color",
"text-emphasis-position","text-emphasis-style","text-height",
"text-indent","text-justify","text-outline","text-shadow",
"text-space-collapse","text-transform","text-underline-position",
"text-wrap","top","transform","transform-origin","transform-style",
"transition","transition-delay","transition-duration",
"transition-property","transition-timing-function","unicode-bidi",
"vertical-align","visibility","voice-balance","voice-duration",
"voice-family","voice-pitch","voice-pitch-range","voice-rate",
"voice-stress","voice-volume","volume","white-space","widows","width",
"word-break","word-spacing","word-wrap","z-index",
// flexbox:
"align-content", "align-items", "align-self", "flex", "flex-basis",
"flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap",
"justify-content"],
// This helper verifies that a specific string is a known CSS property.
// We include vendor-prefixed known CSS properties, like `-o-transition`.
_knownCSSProperty: function(propertyName) {
propertyName = propertyName.replace(/^-.+?-/,'');
return this.cssProperties.indexOf(propertyName) > -1;
},
// #### The CSS Master Parse Function
//
// Here we process the token stream, assumed to have its pointer inside a
// CSS element, and will try to parse the content inside it as CSS until
// we hit the end of the CSS element.
//
// Any parse errors along the way will result in a `ParseError`
// being thrown.
parse: function(standalone) {
// We'll use some instance variables to keep track of our parse
// state:
// * A list of the CSS rulesets for the CSS block.
this.rules = [];
// * A list of comment blocks inside the CSS.
this.comments = [];
// Parsing is based on finite states, and a call
// to `_parseBlockType()` will run through any number
// of states until it either throws an error,
// or terminates cleanly.
var sliceStart = this.stream.pos;
this.stream.markTokenStartAfterSpace();
this._parseBlockType();
var sliceEnd = this.stream.pos;
// If we get here, the CSS block has no errors,
// and we report the start/end of the CSS block
// in the stream, as well as the rules/comments
// for the calling `HTMLparser` instance to work with.
var cssBlock = {
value: this.stream.text.slice(sliceStart, sliceEnd),
parseInfo: {
start: sliceStart,
end: sliceEnd,
rules: this.rules,
comments: this.comments
}
};
this.rules = null;
this.comments = null;
return cssBlock;
},
// #### CSS Comment Parsing
//
// Here we record the position of comments in *term* in the instance's
// comment list, and return *term* with all its comments stripped.
stripComments: function(term, startPos) {
var pos,
last = term.length,
commentStart, commentEnd,
prev, next,
stripped = "";
for (pos=0; pos < last; pos++) {
if (term[pos] === '/' && pos<last-1 && term[pos+1] === '*') {
commentStart = startPos + pos;
pos += 3;
while(pos < last-1 && term.substr(pos-1,2) !== "*/") {
pos++;
}
if (pos >= last-1 && term.substr(pos-1,2) !== "*/")
throw new ParseError("UNTERMINATED_CSS_COMMENT", commentStart);
commentEnd = startPos + pos + 1;
this.comments.push({start: commentStart, end: commentEnd});
} else {
stripped += term[pos];
}
}
return stripped.trim();
},
// #### CSS Comment Filtering
//
// Here we filter a token so that its start and end positions
// point to the content without leading and trailing comments,
// with comments in the token.value completely removed.
filterComments: function(token) {
var text = token.value,
tsize = text.length,
ntsize,
stripped = this.stripComments(text, token.interval.start);
// strip leading comments
text = text.replace(/^\s+/,"");
text = text.replace(/^\/\*[\w\W]*?\*\/\s*/,'');
ntsize = text.length;
token.interval.start += tsize - ntsize;
// strip trailing comments (=reverse and repeat previous)
tsize = ntsize;
text = text.split('').reverse().join('');
text = text.replace(/^\s+/,"");
text = text.replace(/^\/\*[\w\W]*?\*\/\s*/,'');
// FIXME: this still fails comments like this: /* ... /* ... */,
// which is a single block. The problems is that in the
// reversed string this looks like /* ... */ ... */ which
// counts as one block plus left-over junk.
ntsize = text.length;
token.interval.end -= tsize - ntsize;
// commit text change
token.value = stripped;
},
_parseBlockType: function() {
// Depending on our state, we may be coming from having just parsed
// a rule. If that's the case, add it to our list of rules.
if (this.currentRule) {
this.rules.push(this.currentRule);
this.currentRule = null;
}
// skip over comments, if there is one at this position
this.stream.stripCommentBlock();
if (this.stream.peek() === "{") {
throw new ParseError("MISSING_CSS_SELECTOR", this, this.stream.pos-1, this.stream.pos);
}
// are we looking at an @block?
if (this.stream.peek() === "@") {
this.stream.eatCSSWhile(/[^\{]/);
var token = this.stream.makeToken(),
name = token.value.trim();
// we currently support @keyframes (with prefixes)
if(name.match(/@(-[^-]+-)?keyframes/)) {
this.stream.next();
this.nested = true;
return this._parseSelector();
}
// and media queries
if(name.match(/@media\s*\([^{)]+\)/)) {
this.stream.next();
this.nested = true;
return this._parseSelector();
}
// and @font-face
if(name === "@font-face") {
this.stream.rewind(token.value.length);
this.stream.markTokenStart();
return this._parseSelector();
}
// anything else is completely unknown
throw new ParseError("UNKOWN_CSS_KEYWORD", this, token.interval.start, token.interval.end, name);
}
this._parseSelector();
},
// #### CSS Selector Parsing
//
// A selector is a string, and terminates on `{`, which signals
// the start of a CSS property/value pair (which may be empty).
//
// There are a few characters in selectors that are an immediate error:
//
// * `;` Rule terminator (ERROR: missing block opener)
// * `}` End of css block (ERROR: missing block opener)
// * `<` End of `<style>` element, start of `</style>`
// (ERROR: css declaration has no body)
//
// Note that we cannot flag `:` as an error because pseudo-classes use
// it as their prefix.
_parseSelector: function() {
// Gobble all characters that could be part of the selector.
this.stream.eatCSSWhile(/[^\{;\}<]/);
var token = this.stream.makeToken(),
peek = this.stream.peek();
// if we encounter } we're actually inside a block, like
// @keyframes or the like, and need to try for a new block.
if (peek === "}") {
this.stream.next();
return this._parseBlockType();
}
// If there was nothing to select, we're either done,
// or an error occurred.
if (token === null) {
if (!this.stream.end() && this.stream.peek() === '<') {
// if this is the start of <!-- make sure to throw an error
if (this.stream.substream(2) !== "</") {
throw new ParseError("HTML_CODE_IN_CSS_BLOCK", this, this.stream.pos-1, this.stream.pos);
}
}
return;
}
// If we get here, we have a selector string.
// Filter the token for comments before continueing.
this.filterComments(token);
var selector = token.value,
selectorStart = token.interval.start,
selectorEnd = token.interval.end;
if (selector === '') {
this._parseBlockType();
return;
}
// Now we'll set up a ruleset object for this selector.
this.currentRule = {
selector: {
value: selector,
start: selectorStart,
end: selectorEnd
},
declarations: {
start: null,
end: null,
properties: []
}
};
// Now we start to analyse whether we can continue,
// or whether we're in a terminal state, based on the
// next character in the stream.
if (this.stream.end() || peek === '<') {
if(!this.nested) {
throw new ParseError("UNFINISHED_CSS_SELECTOR", this, selectorStart, selectorEnd, selector);
}
return;
}
if (!this.stream.end()) {
var next = this.stream.next(),
errorMsg = "[_parseBlockType] Expected {, }, ; or :, instead found " + next;
if (next === '{') {
// The only legal continuation after a selector is the opening
// `{` character. If that's the character we see, we can mark the
// start of the declarations block and start parsing them.
this.currentRule.declarations.start = this.stream.pos-1;
this._parseDeclaration(selector, selectorStart);
} else if (next === ';' || next === '}') {
// Otherwise, this is a parse error; we should have seen `{`
// instead.
throw new ParseError("MISSING_CSS_BLOCK_OPENER", this, selectorStart, selectorEnd, selector);
} else {
// We get here if an unexpected character was found.
throw new ParseError("UNCAUGHT_CSS_PARSE_ERROR", this, token.interval.start, token.interval.end, errorMsg);
}
} else {
// If the stream ended after the selector, we want the user to follow
// up with `{`.
throw new ParseError("MISSING_CSS_BLOCK_OPENER", this, selectorStart, selectorEnd, selector);
}
},
// #### CSS Declaration Parsing
//
// A declaration is a `property: value;` pair. It can be empty,
// in which case the next character must be `}`.
_parseDeclaration: function(selector, selectorStart, value) {
// First, we forward the stream to the next non-space character.
this.stream.markTokenStartAfterSpace();
var peek = this.stream.peek();
if (peek === '}') {
// If the next character is `}` then this is an empty block, and we
// should move on to trying to read a new selector ruleset.
this.stream.next();
this.currentRule.declarations.end = this.stream.pos;
this.stream.markTokenStartAfterSpace();
this._parseBlockType();
}
// Administratively important: there are two ways for this function
// to have been called. One is from `_parseBlockType()`, which is
// "the normal way", the other from `_parseValue()`, after finding a
// properly closed `property:value;` pair. In this case *value* will be
// the last declaration's value, which will let us throw a sensible
// debug error in case the stream is empty at this point, or points to
// `</style>`.
else if (value && (this.stream.end() || peek === '<')) {
throw new ParseError("MISSING_CSS_BLOCK_CLOSER", this, selectorStart, selectorStart+value.length, value);
}
// If we're still in this function at this point, all is well
// and we can move on to property parsing.
else {
this._parseProperty(selector, selectorStart);
}
},
// #### CSS Property Parsing
// There is a fixed list of CSS properties, and we must check two things:
//
// 1. Does the token string contain a syntax-legal property?
// 2. Is that property in the set of known ones?
//
// Properties are terminated by `:`, but we might also see the following
// characters, which should signal an error:
//
// * `;` rule terminator (ERROR: missing value)
// * `}` end of CSS block (ERROR: missing value)
// * `<` end of `<style>` element, start of `</style>`
// (ERROR: missing value)
_parseProperty: function(selector, selectorStart) {
this.stream.eatCSSWhile(/[^\{\}<;:]/);
var token = this.stream.makeToken();
if (token === null) {
throw new ParseError("MISSING_CSS_PROPERTY", this, selectorStart, selectorStart + selector.length, selector);
}
this.filterComments(token);
var property = token.value,
propertyStart = token.interval.start,
propertyEnd = token.interval.end;
if (property === '') {
this._parseDeclaration(selector, selectorStart);
return;
}
var next = this.stream.next(),
errorMsg = "[_parseProperty] Expected }, {, <, ; or :, instead found " + next;
if (next === '{') {
throw new ParseError("MISSING_CSS_BLOCK_CLOSER", this, selectorStart, propertyStart, selector);
}
if ((this.stream.end() && next !== ':') || next === '<' ||
next === '}') {
throw new ParseError("UNFINISHED_CSS_PROPERTY", this, propertyStart, propertyEnd, property);
}
// We record `property: value` pairs as we run through the stream,
// which are added to the set of `property: value` pairs in the
// instance's `rules.properties` array. The push happens when we have a
// clean run in `_parseValue()`.
this.currentProperty = {
name: {
value: property,
start: propertyStart,
end: propertyEnd
}
};
// If we find a colon, we have a property and now need a value to go
// along with it.
if (next === ':') {
// Before we continue, we must make sure the string we found is a real
// CSS property.
if (!( property && property.match(/^[a-z\-]+$/)) || !this._knownCSSProperty(property)) {
throw new ParseError("INVALID_CSS_PROPERTY_NAME", this, propertyStart, propertyEnd, property);
}
this.stream.markTokenStartAfterSpace();
this._parseValue(selector, selectorStart, property, propertyStart);
}
// Otherwise, anything else at this point constitutes an error.
else if (next === ';') {
throw new ParseError("MISSING_CSS_VALUE", this, propertyStart, propertyEnd, property);
}
else {
throw new ParseError("UNCAUGHT_CSS_PARSE_ERROR", this, token.interval.start, token.interval.end, errorMsg);
}
},
// #### CSS Value Parsing
//
// A value must end either in `;` or in `}`. However, we may also find:
//
// * `<` end of `<style>` element, start of `</style>`
// (ERROR: missing block closer)
_parseValue: function(selector, selectorStart, property, propertyStart) {
if(property === "content") {
this.stream.findContentEnd();
} else {
this.stream.eatCSSWhile(/[^}<;]/);
}
var token = this.stream.makeToken();
if(token === null) {
throw new ParseError("MISSING_CSS_VALUE", this, propertyStart, propertyStart+property.length, property);
}
var next = (!this.stream.end() ? this.stream.next() : "end of stream"),
errorMsg = "[_parseValue] Expected }, <, or ;, instead found "+next;
this.filterComments(token);
var value = token.value,
valueStart = token.interval.start,
valueEnd = token.interval.end;
if (value === '') {
throw new ParseError("MISSING_CSS_VALUE", this, this.stream.pos-1, this.stream.pos);
}
// At this point we can fill in the *value* part of the current
// `property: value;` pair. However, we hold off binding it until
// we are sure there are no parse errors.
this.currentProperty.value = {
value: value,
start: valueStart,
end: valueEnd
};
if ((this.stream.end() && next !== ';') || next === '<') {
throw new ParseError("UNFINISHED_CSS_VALUE", this, valueStart,valueEnd, value);
}
//Add a new validator to check if there is mixed active content in css value
if (checkMixedContent && value.match(/,?\s*url\(\s*['"]?http:\/\/.+\)/)) {
valueStart = valueStart + value.indexOf('url');
this.warnings.push(
new ParseError("CSS_MIXED_ACTIVECONTENT", this, property, propertyStart, value, valueStart, valueEnd)
);
}
if (next === ';') {
// This is normal CSS rule termination; try to read a new
// property/value pair.
this._bindCurrentRule();
this.stream.markTokenStartAfterSpace();
this._parseDeclaration(selector, valueStart, value);
}
else if (next === '}') {
// This is block level termination; try to read a new selector.
this.currentRule.declarations.end = this.stream.pos;
this._bindCurrentRule();
this.stream.markTokenStartAfterSpace();
this._parseBlockType();
}
else {
throw new ParseError("UNCAUGHT_CSS_PARSE_ERROR", this, token.interval.start, token.interval.end, errorMsg);
}
},
// This helper function binds the currrent `property: value` object
// in the current ruleset, and resets it for the next selector block.
_bindCurrentRule: function() {
this.currentRule.declarations.properties.push(this.currentProperty);
this.currentProperty = null;
}
};
return CSSParser;
}());
},{"./ParseError":6,"./checkMixedContent":9}],2:[function(require,module,exports){
// ### The DOM Builder
//
// The DOM builder is used to construct a DOM representation of the
// HTML/CSS being parsed. Each node contains a `parseInfo` expando
// property that contains information about the text extents of the
// original source code that the DOM element maps to.
//
// The DOM builder is given a single document DOM object that will
// be used to create all necessary DOM nodes.
module.exports = (function(){
"use strict";
var DocumentFragment = require("./DocumentFragment");
function DOMBuilder(disallowActiveAttributes) {
this.fragment = new DocumentFragment();
this.currentNode = this.fragment.node;
this.contexts = [];
this.disallowActiveAttributes = disallowActiveAttributes;
}
DOMBuilder.prototype = {
// This method pushes a new element onto the DOM builder's stack.
// The element is appended to the currently active element and is
// then made the new currently active element.
pushElement: function(tagName, parseInfo, nameSpace) {
var node = (nameSpace ? this.fragment.createElementNS(nameSpace, tagName)
: this.fragment.createElement(tagName));
node.parseInfo = parseInfo;
this.currentNode.appendChild(node);
this.currentNode = node;
},
// This method pops the current element off the DOM builder's stack,
// making its parent element the currently active element.
popElement: function() {
this.currentNode = this.currentNode.parentNode;
},
// record the cursor position for a context change (text/html/css/script)
pushContext: function(context, position) {
this.contexts.push({
context: context,
position: position
});
},
// This method appends an HTML comment node to the currently active
// element.
comment: function(data, parseInfo) {
var comment = this.fragment.createComment('');
comment.nodeValue = data;
comment.parseInfo = parseInfo;
this.currentNode.appendChild(comment);
},
// This method appends an attribute to the currently active element.
attribute: function(name, value, parseInfo) {
var attrNode = this.fragment.createAttribute(name);
attrNode.parseInfo = parseInfo;
if (this.disallowActiveAttributes && name.substring(0,2).toLowerCase() === "on") {
attrNode.nodeValue = "";
} else {
attrNode.nodeValue = value;
}
this.currentNode.attributes.push(attrNode);
this.currentNode._attributeMap[attrNode.nodeName] = attrNode.nodeValue;
},
// This method appends a text node to the currently active element.
text: function(text, parseInfo) {
var textNode = this.fragment.createTextNode(text);
textNode.parseInfo = parseInfo;
this.currentNode.appendChild(textNode);
}
};
return DOMBuilder;
}());
},{"./DocumentFragment":3}],3:[function(require,module,exports){
// ### DocumentFragment Shim
//
// A representation of a document fragment that can be normally generated
// by calling `document.createDocumentFragment`. Since the document fragment
// is itself a node, it inherits all properties of a node.
module.exports = (function(){
"use strict";
var Node = require("./Node");
function DocumentFragment() {
this.node = new Node(Node.DOCUMENT_FRAGMENT_NODE, "#document-fragment");
this.node._ownerDocument = this;
}
DocumentFragment.prototype = {
createTextNode: function(data) {
return new Node(Node.TEXT_NODE, "#text", data);
},
createElementNS: function(namespaceURI, qualifiedName) {
return new Node(Node.ELEMENT_NODE, qualifiedName, false, namespaceURI);
},
createElement: function(tagName) {
return this.createElementNS(false, tagName);
},
createComment: function(data) {
return new Node(Node.COMMENT_NODE, "#comment", data);
},
createAttribute: function(name) {
return new Node(Node.ATTRIBUTE_NODE, name);
}
};
return DocumentFragment;
}());
},{"./Node":5}],4:[function(require,module,exports){
// ### HTML Parsing
//
// The HTML token stream parser object has references to the stream,
// as well as a DOM builder that is used to construct the DOM while we
// run through the token stream.
module.exports = (function(){
"use strict";
var ParseError = require("./ParseError");
var CSSParser = require("./CSSParser");
var voidHtmlElements = require("./voidHtmlElements");
// ### Character Entity Parsing
//
// We currently only parse the most common named character entities.
var CHARACTER_ENTITY_REFS = {
lt: "<",
gt: ">",
apos: "'",
quot: '"',
amp: "&"
};
// HTML attribute parsing rules are based on
// http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#attr-data
// -> ref http://www.w3.org/TR/2011/WD-html5-20110525/infrastructure.html#xml-compatible
// -> ref http://www.w3.org/TR/REC-xml/#NT-NameChar
// note: this lacks the final \\u10000-\\uEFFFF in the startchar set, because JavaScript
// cannot cope with unciode characters with points over 0xFFFF.
var attributeNameStartChar = "A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
var nameStartChar = new RegExp("[" + attributeNameStartChar + "]");
var attributeNameChar = attributeNameStartChar + "0-9\\-\\.\\u00B7\\u0300-\\u036F\\u203F-\\u2040:";
var nameChar = new RegExp("[" + attributeNameChar + "]");
//Define a property checker for https page
var checkMixedContent = require("./checkMixedContent").mixedContent;
//Define activeContent with tag-attribute pairs
function isActiveContent (tagName, attrName) {
if (attrName === "href") {
return ["link"].indexOf(tagName) > -1;
}
if (attrName === "src") {
return ["script", "iframe"].indexOf(tagName) > -1;
}
if (attrName === "data") {
return ["object"].indexOf(tagName) > -1;
}
return false;
}
// the current active omittable html Element
var activeTagNode = false;
// the parent html Element for optional closing tag tags
var parentTagNode = false;
// 'foresee' if there is no more content in the parent element, and the
// parent element is not an a element in the case of activeTag is a p element.
function isNextTagParent(stream, parentTagName) {
return stream.findNext(/<\/([\w\-]+)\s*>/, 1) === parentTagName;
}
// 'foresee' if the next tag is a close tag
function isNextCloseTag(stream) {
return stream.findNext(/<\/([\w\-]+)\s*>/, 1);
}
// Check exception for Tag omission rules: for p tag, if there is no more
// content in the parent element and the parent element is not an a element.
function allowsOmmitedEndTag(parentTagName, tagName) {
if (tagName === "p") {
return ["a"].indexOf(parentTagName) > -1;
}
return false;
}
function HTMLParser(stream, domBuilder) {
this.warnings = [];
this.stream = stream;
this.domBuilder = domBuilder;
this.cssParser = new CSSParser(stream, domBuilder, this.warnings);
}
// `replaceEntityRefs()` will replace named character entity references
// (e.g. `<`) in the given text string and return the result. If an
// entity name is unrecognized, don't replace it at all. Writing HTML
// would be surprisingly painful without this forgiving behavior.
//
// This function does not currently replace numeric character entity
// references (e.g., ` `).
function replaceEntityRefs(text) {
return text.replace(/&([A-Za-z]+);/g, function(ref, name) {
name = name.toLowerCase();
if (name in CHARACTER_ENTITY_REFS)
return CHARACTER_ENTITY_REFS[name];
return ref;
});
};
HTMLParser.prototype = {
// since SVG requires a slightly different code path,
// we need to track whether we're in HTML or SVG mode.
parsingSVG: false,
// For SVG DOM elements, we need to know the SVG namespace.
svgNameSpace: "http://www.w3.org/2000/svg",
// HTML5 documents have a special doctype that we must use
html5Doctype: "<!DOCTYPE html>",
// Void HTML elements are the ones that don't need to have a closing tag.
voidHtmlElements: voidHtmlElements,
// Tag Omission Rules, based on the rules on optional tags as outlined in
// http://www.w3.org/TR/html5/syntax.html#optional-tags
// HTML elements that with omittable close tag
omittableCloseTagHtmlElements: ["p", "li", "td", "th"],
// HTML elements that paired with omittable close tag list
omittableCloseTags: {
"p": ["address", "article", "aside", "blockquote", "dir", "div", "dl",
"fieldset", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6",
"header", "hgroup", "hr", "main", "nav", "ol", "p", "pre",
"section", "table", "ul"],
"th": ["th", "td"],
"td": ["th", "td"],
"li": ["li"]
},
// We keep a list of all valid HTML5 elements.
htmlElements: ["a", "abbr", "address", "area", "article", "aside",
"audio", "b", "base", "bdi", "bdo", "bgsound", "blink",
"blockquote", "body", "br", "button", "canvas", "caption",
"cite", "code", "col", "colgroup", "command", "datalist",
"dd", "del", "details", "dfn", "div", "dl", "dt", "em",
"embed", "fieldset", "figcaption", "figure", "footer",
"form", "frame", "frameset", "h1", "h2", "h3", "h4", "h5",
"h6", "head", "header", "hgroup", "hr", "html", "i",
"iframe", "img", "input", "ins", "kbd", "keygen", "label",
"legend", "li", "link", "main", "map", "mark", "marquee", "menu",
"meta", "meter", "nav", "nobr", "noscript", "object", "ol",
"optgroup", "option", "output", "p", "param", "pre",
"progress", "q", "rp", "rt", "ruby", "samp", "script",
"section", "select", "small", "source", "spacer", "span",
"strong", "style", "sub", "summary", "sup", "svg", "table",
"tbody", "td", "textarea", "tfoot", "th", "thead", "time",
"title", "tr", "track", "u", "ul", "var", "video", "wbr"],
// HTML5 allows SVG elements
svgElements: ["a", "altglyph", "altglyphdef", "altglyphitem", "animate",
"animatecolor", "animatemotion", "animatetransform", "circle",
"clippath", "color-profile", "cursor", "defs", "desc",
"ellipse", "feblend", "fecolormatrix", "fecomponenttransfer",
"fecomposite", "feconvolvematrix", "fediffuselighting",
"fedisplacementmap", "fedistantlight", "feflood", "fefunca",
"fefuncb", "fefuncg", "fefuncr", "fegaussianblur", "feimage",
"femerge", "femergenode", "femorphology", "feoffset",
"fepointlight", "fespecularlighting", "fespotlight",
"fetile", "feturbulence", "filter", "font", "font-face",
"font-face-format", "font-face-name", "font-face-src",
"font-face-uri", "foreignobject", "g", "glyph", "glyphref",
"hkern", "image", "line", "lineargradient", "marker", "mask",
"metadata", "missing-glyph", "mpath", "path", "pattern",
"polygon", "polyline", "radialgradient", "rect", "script",
"set", "stop", "style", "svg", "switch", "symbol", "text",
"textpath", "title", "tref", "tspan", "use", "view", "vkern"],
// HTML5 doesn't use namespaces, but actually it does. These are supported:
attributeNamespaces: ["xlink", "xml"],
// We also keep a list of HTML elements that are now obsolete, but
// may still be encountered in the wild on popular sites.
obsoleteHtmlElements: ["acronym", "applet", "basefont", "big", "center",
"dir", "font", "isindex", "listing", "noframes",
"plaintext", "s", "strike", "tt", "xmp"],
webComponentElements: ["template", "shadow", "content"],
// This is a helper function to determine whether a given string
// is a custom HTML element as per Custom Elements spec
// (see http://www.w3.org/TR/2013/WD-custom-elements-20130514/#terminology).
_isCustomElement: function(tagName) {
return tagName.search(/^[\w\d]+-[\w\d]+$/) > -1;
},
// This is a helper function to determine whether a given string
// is a legal HTML5 element tag.
_knownHTMLElement: function(tagName) {
return this.voidHtmlElements.indexOf(tagName) > -1 ||
this.htmlElements.indexOf(tagName) > -1 ||
this.obsoleteHtmlElements.indexOf(tagName) > -1 ||
this.webComponentElements.indexOf(tagName) > -1;
},
// This is a helper function to determine whether a given string
// is a legal SVG element tag.
_knownSVGElement: function(tagName) {
return this.svgElements.indexOf(tagName) > -1;
},
// This is a helper function to determine whether a given string
// is a void HTML element tag.
_knownVoidHTMLElement: function(tagName) {
return this.voidHtmlElements.indexOf(tagName) > -1;
},
// This is a helper function to determine whether a given string
// is a HTML element tag which can optional omit its close tag.
_knownOmittableCloseTagHtmlElement: function(tagName) {
return this.omittableCloseTagHtmlElements.indexOf(tagName) > -1;
},
// This is a helper function to determine whether a given string
// is in the list of ommittableCloseTags which enable an active tag omit its close tag.
_knownOmittableCloseTags: function(activeTagName, foundTagName) {
return this.omittableCloseTags[activeTagName].indexOf(foundTagName) > -1;
},
// This is a helper function to determine whether an attribute namespace
// is supposed in the HTML spec. Currently these are "xlink" and "xml".
_supportedAttributeNameSpace: function(ns) {
return this.attributeNamespaces.indexOf(ns) !== -1;
},
// #### The HTML Master Parse Function
//
// The HTML master parse function works the same as the CSS
// parser: it takes the token stream and will try to parse
// the content as a sequence of HTML elements.
//
// Any parse errors along the way will result in the code
// throwing a `ParseError`.
parse: function() {
// First we check to see if the beginning of our stream is
// an HTML5 doctype tag. We're currently quite strict and don't
// parse XHTML or other doctypes.
if (this.stream.match(this.html5Doctype, true, true))
this.domBuilder.fragment.node.parseInfo = {
doctype: {
start: 0,
end: this.stream.pos
}
};
// Next, we parse "tag soup", creating text nodes and diving into
// tags as we find them.
while (!this.stream.end()) {
if (this.stream.peek() == '<') {
this._buildTextNode();
this._parseStartTag();
} else
this.stream.next();
}
this._buildTextNode();
// At the end, it's possible we're left with an open tag, so
// we test for that.
if (this.domBuilder.currentNode != this.domBuilder.fragment.node)
throw new ParseError("UNCLOSED_TAG", this);
return {
warnings: (this.warnings.length > 0 ? this.warnings : false)
};
},
// This is a helper to build a DOM text node.
_buildTextNode: function() {
var token = this.stream.makeToken();
if (token) {
this.domBuilder.text(replaceEntityRefs(token.value), token.interval);
}
},
// #### HTML Tag Parsing
//
// This is the entry point for parsing the beginning of an HTML tag.
// It assumes the stream is on a `<` character.
_parseStartTag: function() {
if (this.stream.next() != '<')
throw new Error('assertion failed, expected to be on "<"');
if (this.stream.match('!--', true)) {
this.domBuilder.pushContext("text", this.stream.pos);
this._parseComment();
this.domBuilder.pushContext("html", this.stream.pos);
return;
}
this.stream.eat(/\//);
this.stream.eatWhile(/[\w\d-]/);
var token = this.stream.makeToken();
var tagName = token.value.slice(1).toLowerCase();
if (tagName === "svg")
this.parsingSVG = true;
// If the character after the `<` is a `/`, we're on a closing tag.
// We want to report useful errors about whether the tag is unexpected
// or doesn't match with the most recent opening tag.
if (tagName[0] == '/') {
activeTagNode = false;
var closeTagName = tagName.slice(1).toLowerCase();
if (closeTagName === "svg")
this.parsingSVG = false;
if (this._knownVoidHTMLElement(closeTagName))
throw new ParseError("CLOSE_TAG_FOR_VOID_ELEMENT", this,
closeTagName, token);
if (!this.domBuilder.currentNode.parseInfo)
throw new ParseError("UNEXPECTED_CLOSE_TAG", this, closeTagName,
token);
this.domBuilder.currentNode.parseInfo.closeTag = {
start: token.interval.start
};
var openTagName = this.domBuilder.currentNode.nodeName.toLowerCase();
if (closeTagName != openTagName)
throw new ParseError("MISMATCHED_CLOSE_TAG", this, openTagName,
closeTagName, token);
this._parseEndCloseTag();
}
else {
if (tagName) {
var badSVG = this.parsingSVG && !this._knownSVGElement(tagName);
var badHTML = !this.parsingSVG && !this._knownHTMLElement(tagName) && !this._isCustomElement(tagName);
if (badSVG || badHTML) {
throw new ParseError("INVALID_TAG_NAME", tagName, token);
}
}
else {
throw new ParseError("INVALID_TAG_NAME", tagName, token);
}
var parseInfo = { openTag: { start: token.interval.start }};
var nameSpace = (this.parsingSVG ? this.svgNameSpace : undefined);
// If the preceding tag and the active tag is omittableCloseTag pairs,
// we tell our DOM builder that we're done.
if (activeTagNode && parentTagNode != this.domBuilder.fragment.node){
var activeTagName = activeTagNode.nodeName.toLowerCase();
if(this._knownOmittableCloseTags(activeTagName, tagName)) {