-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathindex.js
272 lines (238 loc) · 7.25 KB
/
index.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
var HTMLParser = require('htmlparser2').Parser
var through = require('through2')
var parseSelector = require('./selector')
module.exports = function hstream (updates) {
if (typeof updates !== 'object') throw new TypeError('hstream: updates must be object')
var parser = new HTMLParser({
onopentag: onopentag,
onprocessinginstruction: onprocessinginstruction,
oncomment: oncomment,
ontext: ontext,
onclosetag: onclosetag,
onend: onparseend,
onerror: onerror
}, { lowerCaseTags: true, decodeEntities: true })
var matchers = buildMatchers(updates)
// original html source, so we can slice from it
var source = ''
var savedIndex = 0
// parsed element stack
var stack = []
var selfClosingIndex = 0
// output chunks that were not yet written
var queued = []
// whether new output chunks should be queued
var queueWaiting = false
// true when we are replacing element contents
// → we should ignore results from the parser
var replacing = false
var stream = through(onchunk, onend)
return stream
function onqueueready () {
queueWaiting = false
push()
}
function onsourceforward (chunk) { stream.push(chunk) }
function push () {
if (queued.length === 0) return
var next = queued.shift()
if (isStream(next)) {
queueWaiting = true
next.on('end', onqueueready)
next.on('data', onsourceforward)
next.on('error', onerror)
next.resume()
} else {
stream.push(next)
push()
}
}
function queue (val) {
// tack this on to another queued string if it's there to save some `.push()` calls
if (typeof val === 'string' && queued.length > 0 && typeof queued[queued.length - 1] === 'string') {
queued[queued.length - 1] += val
} else {
// pause streams; so we don't miss any data events once we are ready
if (isStream(val)) {
// `.pause()` is advisory in node streams, so pipe it through `through()` which
// will always buffer
val = val.pipe(through())
val.pause()
}
queued.push(val)
// defer calling `push` until the end of this parse tick;
// this way a lot more strings can end up concatenated into one
if (!queueWaiting) {
queueWaiting = true
process.nextTick(onqueueready)
}
}
}
// Get the original source for the thing being parsed right now
function slice () {
source = source.slice(parser.startIndex - savedIndex)
savedIndex = parser.startIndex
return source.slice(0, parser.endIndex + 1 - savedIndex)
}
function sliceReplaced (start, end) {
var result = source.slice(start - savedIndex, end - savedIndex)
source = source.slice(end - savedIndex)
savedIndex = end
return result
}
// Check if the current element stack matches a selector
// If it does, return the update object for the matching selector
function matches () {
return matchers.find(function (o) {
return o.matches(stack)
})
}
function onchunk (chunk, enc, cb) {
source += chunk.toString()
parser.write(chunk.toString())
cb()
}
function onend () {
parser.end()
}
function onprocessinginstruction (name, data) {
if (replacing) return
// HACK to force htmlparser2 to update its startIndex and endIndex
// Hopefully this check is good enough to be future proof
if (parser.endIndex === null) parser.updatePosition(2)
queue(slice())
}
function onopentag (name, attrs) {
var el = { tagName: name, attrs: attrs }
stack.push(el)
selfClosingIndex = parser.startIndex
if (replacing) return
var match = matches()
var tag = slice()
if (match) {
// store the update object so we can use it in the close tag handler
el.update = match.update
// replacing the entire element; don't push the open tag
if (match.update._replaceHtml) {
replacing = true
el.replaceIndex = parser.startIndex
el.replaceOuter = true
return
}
if (hasAttrs(match.update)) {
addAttrs(tag, attrs, match.update).forEach(queue)
} else {
queue(tag)
}
if (match.update._prependHtml) {
queue(match.update._prependHtml)
}
if (match.update._html) {
replacing = true
el.replaceIndex = parser.endIndex + 1
el.replaceContents = true
}
} else {
queue(tag)
}
}
function oncomment (text) {
if (replacing) return
// just pass comments through unchanged
queue(slice())
}
function ontext (text) {
if (replacing) return
// just pass text through unchanged
queue(slice())
}
function onclosetag (name) {
var el = stack.pop()
// replaced the entire element; don't push the closing tag
if (el.replaceOuter) {
replacing = false
var replaceHtml = el.update._replaceHtml
if (typeof replaceHtml === 'function') {
replaceHtml = replaceHtml(sliceReplaced(el.replaceIndex, parser.endIndex + 1))
}
queue(replaceHtml)
return
}
if (el.replaceContents) {
replacing = false // stop replacing
var html = el.update._html
if (typeof html === 'function') {
html = html(sliceReplaced(el.replaceIndex, parser.startIndex))
}
queue(html)
}
if (selfClosingIndex === parser.startIndex) return
if (replacing) return
if (el.update) {
if (el.update._appendHtml) {
queue(el.update._appendHtml)
}
}
queue(slice())
}
function onparseend () {
// close the output stream
queue(null)
}
function onerror (error) {
stream.emit('error', error)
}
}
function buildMatchers (updates) {
var selectors = Object.keys(updates)
var matchers = []
for (var i = 0; i < selectors.length; i++) {
var update = updates[selectors[i]]
if (isStream(update) || typeof update !== 'object') update = { _html: update }
matchers.push({
matches: parseSelector(selectors[i]),
update: update
})
}
return matchers
}
// check if an update object has any attributes
// (properties starting with _ are not attributes)
function hasAttrs (update) {
var k = Object.keys(update)
for (var i = 0; i < k.length; i++) {
if (k[i][0] !== '_') return true
}
return false
}
// insert attributes into an html open tag string
//
// addAttrs('<div a="b">', { a: 'b' }, { c: 'd' })
// → <div a="b" c="d">
function addAttrs (str, existing, update) {
var attrs = []
// split the tag into two parts: `<tagname` and `>` (or `/>` for self closing)
var tagParts = str.match(/^(<\S+)(?:[\s\S]*?)(\/?>)$/)
attrs.push(tagParts[1])
var newAttrs = Object.assign({}, existing, update)
var k = Object.keys(newAttrs)
for (var i = 0; i < k.length; i++) {
if (k[i][0] === '_') continue
var attr = k[i]
var value = newAttrs[attr]
if (typeof value === 'function') value = value(existing[attr] || '')
if (value == null) continue
attrs.push(' ' + attr + '="')
if (typeof value === 'object' && !isStream(value)) {
if (value.prepend) attrs.push(value.prepend)
attrs.push(existing[attr])
if (value.append) attrs.push(value.append)
} else {
attrs.push(value)
}
attrs.push('"')
}
attrs.push(tagParts[2])
return attrs
}
function isStream (o) { return Boolean(typeof o === 'object' && o && o.pipe) }