-
Notifications
You must be signed in to change notification settings - Fork 129
/
himalaya.js
728 lines (707 loc) · 20.8 KB
/
himalaya.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
(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.himalaya = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.arrayIncludes = arrayIncludes;
exports.endsWith = endsWith;
exports.isRealNaN = isRealNaN;
exports.startsWith = startsWith;
exports.stringIncludes = stringIncludes;
/*
We don't want to include babel-polyfill in our project.
- Library authors should be using babel-runtime for non-global polyfilling
- Adding babel-polyfill/-runtime increases bundle size significantly
We will include our polyfill instance methods as regular functions.
*/
function startsWith(str, searchString, position) {
return str.substr(position || 0, searchString.length) === searchString;
}
function endsWith(str, searchString, position) {
var index = (position || str.length) - searchString.length;
var lastIndex = str.lastIndexOf(searchString, index);
return lastIndex !== -1 && lastIndex === index;
}
function stringIncludes(str, searchString, position) {
return str.indexOf(searchString, position || 0) !== -1;
}
function isRealNaN(x) {
return typeof x === 'number' && isNaN(x);
}
function arrayIncludes(array, searchElement, position) {
var len = array.length;
if (len === 0) return false;
var lookupIndex = position | 0;
var isNaNElement = isRealNaN(searchElement);
var searchIndex = lookupIndex >= 0 ? lookupIndex : len + lookupIndex;
while (searchIndex < len) {
var element = array[searchIndex++];
if (element === searchElement) return true;
if (isNaNElement && isRealNaN(element)) return true;
}
return false;
}
},{}],2:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.format = format;
exports.formatAttributes = formatAttributes;
exports.splitHead = splitHead;
exports.unquote = unquote;
function splitHead(str, sep) {
var idx = str.indexOf(sep);
if (idx === -1) return [str];
return [str.slice(0, idx), str.slice(idx + sep.length)];
}
function unquote(str) {
var car = str.charAt(0);
var end = str.length - 1;
var isQuoteStart = car === '"' || car === "'";
if (isQuoteStart && car === str.charAt(end)) {
return str.slice(1, end);
}
return str;
}
function format(nodes, options) {
return nodes.map(function (node) {
var type = node.type;
var outputNode = type === 'element' ? {
type: type,
tagName: node.tagName.toLowerCase(),
attributes: formatAttributes(node.attributes),
children: format(node.children, options)
} : {
type: type,
content: node.content
};
if (options.includePositions) {
outputNode.position = node.position;
}
return outputNode;
});
}
function formatAttributes(attributes) {
return attributes.map(function (attribute) {
var parts = splitHead(attribute.trim(), '=');
var key = parts[0];
var value = typeof parts[1] === 'string' ? unquote(parts[1]) : null;
return {
key: key,
value: value
};
});
}
},{}],3:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parse = parse;
exports.parseDefaults = void 0;
exports.stringify = stringify;
var _lexer = _interopRequireDefault(require("./lexer"));
var _parser = _interopRequireDefault(require("./parser"));
var _format = require("./format");
var _stringify = require("./stringify");
var _tags = require("./tags");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var parseDefaults = {
voidTags: _tags.voidTags,
closingTags: _tags.closingTags,
childlessTags: _tags.childlessTags,
closingTagAncestorBreakers: _tags.closingTagAncestorBreakers,
includePositions: false
};
exports.parseDefaults = parseDefaults;
function parse(str) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : parseDefaults;
var tokens = (0, _lexer["default"])(str, options);
var nodes = (0, _parser["default"])(tokens, options);
return (0, _format.format)(nodes, options);
}
function stringify(ast) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : parseDefaults;
return (0, _stringify.toHTML)(ast, options);
}
},{"./format":2,"./lexer":4,"./parser":5,"./stringify":6,"./tags":7}],4:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.copyPosition = copyPosition;
exports["default"] = lexer;
exports.feedPosition = feedPosition;
exports.findTextEnd = findTextEnd;
exports.isWhitespaceChar = isWhitespaceChar;
exports.jumpPosition = jumpPosition;
exports.lex = lex;
exports.lexComment = lexComment;
exports.lexSkipTag = lexSkipTag;
exports.lexTag = lexTag;
exports.lexTagAttributes = lexTagAttributes;
exports.lexTagName = lexTagName;
exports.lexText = lexText;
exports.makeInitialPosition = makeInitialPosition;
var _compat = require("./compat");
function feedPosition(position, str, len) {
var start = position.index;
var end = position.index = start + len;
for (var i = start; i < end; i++) {
var _char = str.charAt(i);
if (_char === '\n') {
position.line++;
position.column = 0;
} else {
position.column++;
}
}
}
function jumpPosition(position, str, end) {
var len = end - position.index;
return feedPosition(position, str, len);
}
function makeInitialPosition() {
return {
index: 0,
column: 0,
line: 0
};
}
function copyPosition(position) {
return {
index: position.index,
line: position.line,
column: position.column
};
}
function lexer(str, options) {
var state = {
str: str,
options: options,
position: makeInitialPosition(),
tokens: []
};
lex(state);
return state.tokens;
}
function lex(state) {
var str = state.str,
childlessTags = state.options.childlessTags;
var len = str.length;
while (state.position.index < len) {
var start = state.position.index;
lexText(state);
if (state.position.index === start) {
var isComment = (0, _compat.startsWith)(str, '!--', start + 1);
if (isComment) {
lexComment(state);
} else {
var tagName = lexTag(state);
var safeTag = tagName.toLowerCase();
if ((0, _compat.arrayIncludes)(childlessTags, safeTag)) {
lexSkipTag(tagName, state);
}
}
}
}
}
var alphanumeric = /[A-Za-z0-9]/;
function findTextEnd(str, index) {
while (true) {
var textEnd = str.indexOf('<', index);
if (textEnd === -1) {
return textEnd;
}
var _char2 = str.charAt(textEnd + 1);
if (_char2 === '/' || _char2 === '!' || alphanumeric.test(_char2)) {
return textEnd;
}
index = textEnd + 1;
}
}
function lexText(state) {
var type = 'text';
var str = state.str,
position = state.position;
var textEnd = findTextEnd(str, position.index);
if (textEnd === position.index) return;
if (textEnd === -1) {
textEnd = str.length;
}
var start = copyPosition(position);
var content = str.slice(position.index, textEnd);
jumpPosition(position, str, textEnd);
var end = copyPosition(position);
state.tokens.push({
type: type,
content: content,
position: {
start: start,
end: end
}
});
}
function lexComment(state) {
var str = state.str,
position = state.position;
var start = copyPosition(position);
feedPosition(position, str, 4); // "<!--".length
var contentEnd = str.indexOf('-->', position.index);
var commentEnd = contentEnd + 3; // "-->".length
if (contentEnd === -1) {
contentEnd = commentEnd = str.length;
}
var content = str.slice(position.index, contentEnd);
jumpPosition(position, str, commentEnd);
state.tokens.push({
type: 'comment',
content: content,
position: {
start: start,
end: copyPosition(position)
}
});
}
function lexTag(state) {
var str = state.str,
position = state.position;
{
var secondChar = str.charAt(position.index + 1);
var close = secondChar === '/';
var start = copyPosition(position);
feedPosition(position, str, close ? 2 : 1);
state.tokens.push({
type: 'tag-start',
close: close,
position: {
start: start
}
});
}
var tagName = lexTagName(state);
lexTagAttributes(state);
{
var firstChar = str.charAt(position.index);
var _close = firstChar === '/';
feedPosition(position, str, _close ? 2 : 1);
var end = copyPosition(position);
state.tokens.push({
type: 'tag-end',
close: _close,
position: {
end: end
}
});
}
return tagName;
}
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#special-white-space
var whitespace = /\s/;
function isWhitespaceChar(_char3) {
return whitespace.test(_char3);
}
function lexTagName(state) {
var str = state.str,
position = state.position;
var len = str.length;
var start = position.index;
while (start < len) {
var _char4 = str.charAt(start);
var isTagChar = !(isWhitespaceChar(_char4) || _char4 === '/' || _char4 === '>');
if (isTagChar) break;
start++;
}
var end = start + 1;
while (end < len) {
var _char5 = str.charAt(end);
var _isTagChar = !(isWhitespaceChar(_char5) || _char5 === '/' || _char5 === '>');
if (!_isTagChar) break;
end++;
}
jumpPosition(position, str, end);
var tagName = str.slice(start, end);
state.tokens.push({
type: 'tag',
content: tagName
});
return tagName;
}
function lexTagAttributes(state) {
var str = state.str,
position = state.position,
tokens = state.tokens;
var cursor = position.index;
var quote = null; // null, single-, or double-quote
var wordBegin = cursor; // index of word start
var words = []; // "key", "key=value", "key='value'", etc
var len = str.length;
while (cursor < len) {
var _char6 = str.charAt(cursor);
if (quote) {
var isQuoteEnd = _char6 === quote;
if (isQuoteEnd) {
quote = null;
}
cursor++;
continue;
}
var isTagEnd = _char6 === '/' || _char6 === '>';
if (isTagEnd) {
if (cursor !== wordBegin) {
words.push(str.slice(wordBegin, cursor));
}
break;
}
var isWordEnd = isWhitespaceChar(_char6);
if (isWordEnd) {
if (cursor !== wordBegin) {
words.push(str.slice(wordBegin, cursor));
}
wordBegin = cursor + 1;
cursor++;
continue;
}
var isQuoteStart = _char6 === "'" || _char6 === '"';
if (isQuoteStart) {
quote = _char6;
cursor++;
continue;
}
cursor++;
}
jumpPosition(position, str, cursor);
var wLen = words.length;
var type = 'attribute';
for (var i = 0; i < wLen; i++) {
var word = words[i];
var isNotPair = word.indexOf('=') === -1;
if (isNotPair) {
var secondWord = words[i + 1];
if (secondWord && (0, _compat.startsWith)(secondWord, '=')) {
if (secondWord.length > 1) {
var newWord = word + secondWord;
tokens.push({
type: type,
content: newWord
});
i += 1;
continue;
}
var thirdWord = words[i + 2];
i += 1;
if (thirdWord) {
var _newWord = word + '=' + thirdWord;
tokens.push({
type: type,
content: _newWord
});
i += 1;
continue;
}
}
}
if ((0, _compat.endsWith)(word, '=')) {
var _secondWord = words[i + 1];
if (_secondWord && !(0, _compat.stringIncludes)(_secondWord, '=')) {
var _newWord2 = word + _secondWord;
tokens.push({
type: type,
content: _newWord2
});
i += 1;
continue;
}
var _newWord3 = word.slice(0, -1);
tokens.push({
type: type,
content: _newWord3
});
continue;
}
tokens.push({
type: type,
content: word
});
}
}
var push = [].push;
function lexSkipTag(tagName, state) {
var str = state.str,
position = state.position,
tokens = state.tokens;
var safeTagName = tagName.toLowerCase();
var len = str.length;
var index = position.index;
while (index < len) {
var nextTag = str.indexOf('</', index);
if (nextTag === -1) {
lexText(state);
break;
}
var tagStartPosition = copyPosition(position);
jumpPosition(tagStartPosition, str, nextTag);
var tagState = {
str: str,
position: tagStartPosition,
tokens: []
};
var name = lexTag(tagState);
if (safeTagName !== name.toLowerCase()) {
index = tagState.position.index;
continue;
}
if (nextTag !== position.index) {
var textStart = copyPosition(position);
jumpPosition(position, str, nextTag);
tokens.push({
type: 'text',
content: str.slice(textStart.index, nextTag),
position: {
start: textStart,
end: copyPosition(position)
}
});
}
push.apply(tokens, tagState.tokens);
jumpPosition(position, str, tagState.position.index);
break;
}
}
},{"./compat":1}],5:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = parser;
exports.hasTerminalParent = hasTerminalParent;
exports.parse = parse;
exports.rewindStack = rewindStack;
var _compat = require("./compat");
function parser(tokens, options) {
var root = {
tagName: null,
children: []
};
var state = {
tokens: tokens,
options: options,
cursor: 0,
stack: [root]
};
parse(state);
return root.children;
}
function hasTerminalParent(tagName, stack, terminals) {
var tagParents = terminals[tagName];
if (tagParents) {
var currentIndex = stack.length - 1;
while (currentIndex >= 0) {
var parentTagName = stack[currentIndex].tagName;
if (parentTagName === tagName) {
break;
}
if ((0, _compat.arrayIncludes)(tagParents, parentTagName)) {
return true;
}
currentIndex--;
}
}
return false;
}
function rewindStack(stack, newLength, childrenEndPosition, endPosition) {
stack[newLength].position.end = endPosition;
for (var i = newLength + 1, len = stack.length; i < len; i++) {
stack[i].position.end = childrenEndPosition;
}
stack.splice(newLength);
}
function parse(state) {
var tokens = state.tokens,
options = state.options;
var stack = state.stack;
var nodes = stack[stack.length - 1].children;
var len = tokens.length;
var cursor = state.cursor;
while (cursor < len) {
var token = tokens[cursor];
if (token.type !== 'tag-start') {
nodes.push(token);
cursor++;
continue;
}
var tagToken = tokens[++cursor];
cursor++;
var tagName = tagToken.content.toLowerCase();
if (token.close) {
var index = stack.length;
var shouldRewind = false;
while (--index > -1) {
if (stack[index].tagName === tagName) {
shouldRewind = true;
break;
}
}
while (cursor < len) {
var endToken = tokens[cursor];
if (endToken.type !== 'tag-end') break;
cursor++;
}
if (shouldRewind) {
rewindStack(stack, index, token.position.start, tokens[cursor - 1].position.end);
break;
} else {
continue;
}
}
var isClosingTag = (0, _compat.arrayIncludes)(options.closingTags, tagName);
var shouldRewindToAutoClose = isClosingTag;
if (shouldRewindToAutoClose) {
var terminals = options.closingTagAncestorBreakers;
shouldRewindToAutoClose = !hasTerminalParent(tagName, stack, terminals);
}
if (shouldRewindToAutoClose) {
// rewind the stack to just above the previous
// closing tag of the same name
var currentIndex = stack.length - 1;
while (currentIndex > 0) {
if (tagName === stack[currentIndex].tagName) {
rewindStack(stack, currentIndex, token.position.start, token.position.start);
var previousIndex = currentIndex - 1;
nodes = stack[previousIndex].children;
break;
}
currentIndex = currentIndex - 1;
}
}
var attributes = [];
var attrToken = void 0;
while (cursor < len) {
attrToken = tokens[cursor];
if (attrToken.type === 'tag-end') break;
attributes.push(attrToken.content);
cursor++;
}
cursor++;
var children = [];
var position = {
start: token.position.start,
end: attrToken.position.end
};
var elementNode = {
type: 'element',
tagName: tagToken.content,
attributes: attributes,
children: children,
position: position
};
nodes.push(elementNode);
var hasChildren = !(attrToken.close || (0, _compat.arrayIncludes)(options.voidTags, tagName));
if (hasChildren) {
var size = stack.push({
tagName: tagName,
children: children,
position: position
});
var innerState = {
tokens: tokens,
options: options,
cursor: cursor,
stack: stack
};
parse(innerState);
cursor = innerState.cursor;
var rewoundInElement = stack.length === size;
if (rewoundInElement) {
elementNode.position.end = tokens[cursor - 1].position.end;
}
}
}
state.cursor = cursor;
}
},{"./compat":1}],6:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
exports.formatAttributes = formatAttributes;
exports.toHTML = toHTML;
var _compat = require("./compat");
function formatAttributes(attributes) {
return attributes.reduce(function (attrs, attribute) {
var key = attribute.key,
value = attribute.value;
if (value === null) {
return "".concat(attrs, " ").concat(key);
}
var quoteEscape = value.indexOf("'") !== -1;
var quote = quoteEscape ? '"' : "'";
return "".concat(attrs, " ").concat(key, "=").concat(quote).concat(value).concat(quote);
}, '');
}
function toHTML(tree, options) {
return tree.map(function (node) {
if (node.type === 'text') {
return node.content;
}
if (node.type === 'comment') {
return "<!--".concat(node.content, "-->");
}
var tagName = node.tagName,
attributes = node.attributes,
children = node.children;
var isSelfClosing = (0, _compat.arrayIncludes)(options.voidTags, tagName.toLowerCase());
return isSelfClosing ? "<".concat(tagName).concat(formatAttributes(attributes), ">") : "<".concat(tagName).concat(formatAttributes(attributes), ">").concat(toHTML(children, options), "</").concat(tagName, ">");
}).join('');
}
var _default = {
toHTML: toHTML
};
exports["default"] = _default;
},{"./compat":1}],7:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.voidTags = exports.closingTags = exports.closingTagAncestorBreakers = exports.childlessTags = void 0;
/*
Tags which contain arbitary non-parsed content
For example: <script> JavaScript should not be parsed
*/
var childlessTags = ['style', 'script', 'template'];
/*
Tags which auto-close because they cannot be nested
For example: <p>Outer<p>Inner is <p>Outer</p><p>Inner</p>
*/
exports.childlessTags = childlessTags;
var closingTags = ['html', 'head', 'body', 'p', 'dt', 'dd', 'li', 'option', 'thead', 'th', 'tbody', 'tr', 'td', 'tfoot', 'colgroup'];
/*
Closing tags which have ancestor tags which
may exist within them which prevent the
closing tag from auto-closing.
For example: in <li><ul><li></ul></li>,
the top-level <li> should not auto-close.
*/
exports.closingTags = closingTags;
var closingTagAncestorBreakers = {
li: ['ul', 'ol', 'menu'],
dt: ['dl'],
dd: ['dl'],
tbody: ['table'],
thead: ['table'],
tfoot: ['table'],
tr: ['table'],
td: ['table']
};
/*
Tags which do not need the closing tag
For example: <img> does not need </img>
*/
exports.closingTagAncestorBreakers = closingTagAncestorBreakers;
var voidTags = ['!doctype', 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'keygen', 'link', 'meta', 'param', 'source', 'track', 'wbr'];
exports.voidTags = voidTags;
},{}]},{},[3])(3)
});
//# sourceMappingURL=himalaya.js.map