1 | 'use strict'
|
2 |
|
3 | const vm = require('vm')
|
4 | const { parser } = require('posthtml-parser')
|
5 | const { render } = require('posthtml-render')
|
6 |
|
7 | const getNextTag = require('./tags')
|
8 | const parseLoopStatement = require('./loops')
|
9 | const escapeRegexpString = require('./escape')
|
10 | const makeLocalsBackup = require('./backup').make
|
11 | const revertBackupedLocals = require('./backup').revert
|
12 | const placeholders = require('./placeholders')
|
13 | const scriptDataLocals = require('./locals')
|
14 |
|
15 | const delimitersSettings = []
|
16 | let conditionals, switches, loops, scopes, ignored, delimitersReplace, unescapeDelimitersReplace
|
17 |
|
18 |
|
19 |
|
20 |
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 | function executeLoop (params, p1, p2, locals, tree) {
|
32 |
|
33 |
|
34 |
|
35 | const scopes = locals
|
36 |
|
37 | scopes[params[0]] = p1
|
38 |
|
39 | if (params[1]) scopes[params[1]] = p2
|
40 |
|
41 | return walk({ locals: scopes }, JSON.parse(tree))
|
42 | }
|
43 |
|
44 |
|
45 |
|
46 |
|
47 |
|
48 |
|
49 |
|
50 |
|
51 |
|
52 |
|
53 |
|
54 |
|
55 | function executeScope (scope, locals, node) {
|
56 | scope = Object.assign(locals, scope)
|
57 |
|
58 | return walk({ locals: scope }, node.content)
|
59 | }
|
60 |
|
61 |
|
62 |
|
63 |
|
64 |
|
65 |
|
66 |
|
67 |
|
68 |
|
69 |
|
70 |
|
71 | function getLoopMeta (index, target) {
|
72 | index = Array.isArray(target) ? index : Object.keys(target).indexOf(index)
|
73 | const arr = Array.isArray(target) ? target : Object.keys(target)
|
74 |
|
75 | return {
|
76 | index: index,
|
77 | remaining: arr.length - index - 1,
|
78 | first: arr.indexOf(arr[index]) === 0,
|
79 | last: index + 1 === arr.length,
|
80 | length: arr.length
|
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 | module.exports = function postHTMLExpressions (options) {
|
107 |
|
108 | options = Object.assign({
|
109 | locals: {},
|
110 | delimiters: ['{{', '}}'],
|
111 | unescapeDelimiters: ['{{{', '}}}'],
|
112 | conditionalTags: ['if', 'elseif', 'else'],
|
113 | switchTags: ['switch', 'case', 'default'],
|
114 | loopTags: ['each'],
|
115 | scopeTags: ['scope'],
|
116 | ignoredTag: 'raw',
|
117 | strictMode: true,
|
118 | localsAttr: 'locals',
|
119 | removeScriptLocals: false
|
120 | }, options)
|
121 |
|
122 |
|
123 | loops = options.loopTags
|
124 | scopes = options.scopeTags
|
125 | conditionals = options.conditionalTags
|
126 | switches = options.switchTags
|
127 | ignored = options.ignoredTag
|
128 |
|
129 |
|
130 | let before = escapeRegexpString(options.delimiters[0])
|
131 | let after = escapeRegexpString(options.delimiters[1])
|
132 |
|
133 | const delimitersRegexp = new RegExp(`(?<!@)${before}(.+?)${after}`, 'g')
|
134 |
|
135 | before = escapeRegexpString(options.unescapeDelimiters[0])
|
136 | after = escapeRegexpString(options.unescapeDelimiters[1])
|
137 |
|
138 | const unescapeDelimitersRegexp = new RegExp(`(?<!@)${before}(.+?)${after}`, 'g')
|
139 |
|
140 |
|
141 | const delimiters = [
|
142 | { text: options.delimiters, regexp: delimitersRegexp, escape: true },
|
143 | { text: options.unescapeDelimiters, regexp: unescapeDelimitersRegexp, escape: false }
|
144 | ]
|
145 |
|
146 |
|
147 |
|
148 |
|
149 | if (options.delimiters.join().length > options.unescapeDelimiters.join().length) {
|
150 | delimitersSettings[0] = delimiters[0]
|
151 | delimitersSettings[1] = delimiters[1]
|
152 | } else {
|
153 | delimitersSettings[0] = delimiters[1]
|
154 | delimitersSettings[1] = delimiters[0]
|
155 | }
|
156 |
|
157 | delimitersReplace = new RegExp(`@${escapeRegexpString(delimitersSettings[1].text[0])}`, 'g')
|
158 | unescapeDelimitersReplace = new RegExp(`@${escapeRegexpString(delimitersSettings[0].text[0])}`, 'g')
|
159 |
|
160 |
|
161 | return function (tree) {
|
162 | const { locals } = scriptDataLocals(tree, options)
|
163 |
|
164 | return normalizeTree(clearRawTag(walk({ locals: { ...options.locals, ...locals }, strictMode: options.strictMode }, tree)), tree.options)
|
165 | }
|
166 | }
|
167 |
|
168 | function walk (opts, nodes) {
|
169 |
|
170 | const ctx = vm.createContext(opts.locals)
|
171 |
|
172 |
|
173 |
|
174 | let skip
|
175 |
|
176 |
|
177 | return [].concat(nodes).reduce((m, node, i) => {
|
178 |
|
179 | if (skip) { skip--; return m }
|
180 |
|
181 |
|
182 | if (node.tag === ignored) {
|
183 | m.push(node)
|
184 |
|
185 | return m
|
186 | }
|
187 |
|
188 |
|
189 | if (typeof node === 'string') {
|
190 | node = placeholders(node, ctx, delimitersSettings, opts)
|
191 | node = node
|
192 | .replace(unescapeDelimitersReplace, delimitersSettings[0].text[0])
|
193 | .replace(delimitersReplace, delimitersSettings[1].text[0])
|
194 |
|
195 | m.push(node)
|
196 |
|
197 | return m
|
198 | }
|
199 |
|
200 |
|
201 | if (node.attrs) {
|
202 | for (const key in node.attrs) {
|
203 | if (typeof node.attrs[key] === 'string') {
|
204 | node.attrs[key] = placeholders(node.attrs[key], ctx, delimitersSettings, opts)
|
205 | node.attrs[key] = node.attrs[key]
|
206 | .replace(unescapeDelimitersReplace, delimitersSettings[0].text[0])
|
207 | .replace(delimitersReplace, delimitersSettings[1].text[0])
|
208 | }
|
209 |
|
210 |
|
211 | const _key = placeholders(key, ctx, delimitersSettings, opts)
|
212 | if (key !== _key) {
|
213 | node.attrs[_key] = node.attrs[key]
|
214 | delete node.attrs[key]
|
215 | }
|
216 | }
|
217 | }
|
218 |
|
219 |
|
220 | if (node.content && loops.includes(node.tag) === false && node.tag !== scopes[0]) {
|
221 | node.content = walk(opts, node.content)
|
222 | }
|
223 |
|
224 |
|
225 |
|
226 | if (node.tag === conditionals[0]) {
|
227 |
|
228 | if (!(node.attrs && node.attrs.condition)) {
|
229 | throw new Error(`the "${conditionals[0]}" tag must have a "condition" attribute`)
|
230 | }
|
231 |
|
232 |
|
233 | let expressionIndex = 1
|
234 | let expression = `if (${node.attrs.condition}) { 0 } `
|
235 |
|
236 | const branches = [node.content]
|
237 |
|
238 |
|
239 |
|
240 | let computedNextTag = getNextTag(nodes, ++i)
|
241 |
|
242 | let current = computedNextTag[0]
|
243 | let nextTag = computedNextTag[1]
|
244 |
|
245 | while (conditionals.slice(1).indexOf(nextTag.tag) > -1) {
|
246 | let statement = nextTag.tag
|
247 | let condition = ''
|
248 |
|
249 |
|
250 |
|
251 | if (nextTag.tag === conditionals[2]) statement = 'else'
|
252 |
|
253 |
|
254 | if (nextTag.tag === conditionals[1]) {
|
255 |
|
256 | if (!(nextTag.attrs && nextTag.attrs.condition)) {
|
257 | throw new Error(`the "${conditionals[1]}" tag must have a "condition" attribute`)
|
258 | }
|
259 | condition = nextTag.attrs.condition
|
260 |
|
261 |
|
262 | statement = 'else if'
|
263 | }
|
264 | branches.push(nextTag.content)
|
265 |
|
266 |
|
267 | expression += statement + (condition ? ` (${condition})` : '') + ` { ${expressionIndex++} } `
|
268 |
|
269 | computedNextTag = getNextTag(nodes, ++current)
|
270 |
|
271 | current = computedNextTag[0]
|
272 | nextTag = computedNextTag[1]
|
273 | }
|
274 |
|
275 |
|
276 | let branch
|
277 | try {
|
278 | branch = branches[vm.runInContext(expression, ctx)]
|
279 | } catch (error) {
|
280 | if (opts.strictMode) {
|
281 | throw new SyntaxError(error)
|
282 | }
|
283 | }
|
284 |
|
285 |
|
286 |
|
287 |
|
288 | skip = current - i
|
289 |
|
290 |
|
291 | if (branch) Array.prototype.push.apply(m, walk(opts, branch))
|
292 |
|
293 | return m
|
294 | }
|
295 |
|
296 |
|
297 | if (node.tag === switches[0]) {
|
298 |
|
299 | if (!(node.attrs && node.attrs.expression)) {
|
300 | throw new Error(`the "${switches[0]}" tag must have a "expression" attribute`)
|
301 | }
|
302 |
|
303 |
|
304 | let expressionIndex = 0
|
305 | let expression = `switch(${node.attrs.expression}) {`
|
306 |
|
307 | const branches = []
|
308 |
|
309 | for (let i = 0; i < node.content.length; i++) {
|
310 | const currentNode = node.content[i]
|
311 | if (typeof currentNode === 'string') {
|
312 | continue
|
313 | }
|
314 |
|
315 | if (currentNode.tag === switches[1]) {
|
316 |
|
317 | if (!(currentNode.attrs && currentNode.attrs.n)) {
|
318 | throw new Error(`the "${switches[1]}" tag must have a "n" attribute`)
|
319 | }
|
320 | expression += `case ${currentNode.attrs.n}: {${expressionIndex++}}; break; `
|
321 | } else if (currentNode.tag === switches[2]) {
|
322 | expression += `default: {${expressionIndex++}}`
|
323 | } else {
|
324 | throw new Error(`the "${switches[0]}" tag can contain only "${switches[1]}" tags and one "${switches[2]}" tag`)
|
325 | }
|
326 | branches.push(currentNode)
|
327 | }
|
328 |
|
329 | expression += '}'
|
330 |
|
331 |
|
332 | const branch = branches[vm.runInContext(expression, ctx)]
|
333 |
|
334 |
|
335 | Array.prototype.push.apply(m, walk(opts, branch.content))
|
336 |
|
337 | return m
|
338 | }
|
339 |
|
340 |
|
341 | if (loops.includes(node.tag)) {
|
342 |
|
343 | if (!(node.attrs && node.attrs.loop)) {
|
344 | throw new Error(`the "${node.tag}" tag must have a "loop" attribute`)
|
345 | }
|
346 |
|
347 |
|
348 | const loopParams = parseLoopStatement(node.attrs.loop)
|
349 | let target = {}
|
350 | try {
|
351 | target = vm.runInContext(loopParams.expression, ctx)
|
352 | } catch (error) {
|
353 | if (opts.strictMode) {
|
354 | throw new SyntaxError(error)
|
355 | }
|
356 | }
|
357 |
|
358 |
|
359 | if (typeof target !== 'object' && opts.strictMode) {
|
360 | throw new Error('You must provide an array or object to loop through')
|
361 | }
|
362 |
|
363 | if (loopParams.keys.length < 1 || loopParams.keys[0] === '') {
|
364 | throw new Error('You must provide at least one loop argument')
|
365 | }
|
366 |
|
367 |
|
368 | const treeString = JSON.stringify(node.content)
|
369 | const keys = loopParams.keys
|
370 |
|
371 |
|
372 | const localsBackup = makeLocalsBackup(keys, opts.locals)
|
373 |
|
374 |
|
375 | if (Array.isArray(target)) {
|
376 | for (let index = 0; index < target.length; index++) {
|
377 | opts.locals.loop = getLoopMeta(index, target)
|
378 | m.push(executeLoop(keys, target[index], index, opts.locals, treeString))
|
379 | }
|
380 | } else {
|
381 | for (const key in target) {
|
382 | opts.locals.loop = getLoopMeta(key, target)
|
383 | m.push(executeLoop(keys, target[key], key, opts.locals, treeString))
|
384 | }
|
385 | }
|
386 |
|
387 |
|
388 | opts.locals = revertBackupedLocals(keys, opts.locals, localsBackup)
|
389 |
|
390 |
|
391 | return m
|
392 | }
|
393 |
|
394 |
|
395 | if (node.tag === scopes[0]) {
|
396 |
|
397 | if (!node.attrs || !node.attrs.with) {
|
398 | throw new Error(`the "${scopes[0]}" tag must have a "with" attribute`)
|
399 | }
|
400 |
|
401 | const target = vm.runInContext(node.attrs.with, ctx)
|
402 |
|
403 |
|
404 | if (typeof target !== 'object' || Array.isArray(target)) {
|
405 | throw new Error('You must provide an object to make scope')
|
406 | }
|
407 |
|
408 | const keys = Object.keys(target)
|
409 |
|
410 |
|
411 | const localsBackup = makeLocalsBackup(keys, opts.locals)
|
412 |
|
413 | m.push(executeScope(target, opts.locals, node))
|
414 |
|
415 |
|
416 | opts.locals = revertBackupedLocals(keys, opts.locals, localsBackup)
|
417 |
|
418 |
|
419 | return m
|
420 | }
|
421 |
|
422 |
|
423 | m.push(node)
|
424 |
|
425 | return m
|
426 | }, [])
|
427 | }
|
428 |
|
429 | function clearRawTag (tree) {
|
430 | return tree.reduce((m, node) => {
|
431 | if (node.content) {
|
432 | node.content = clearRawTag(node.content)
|
433 | }
|
434 |
|
435 | if (node.tag === ignored) {
|
436 | node.tag = false
|
437 | }
|
438 |
|
439 | m.push(node)
|
440 |
|
441 | return m
|
442 | }, [])
|
443 | }
|
444 | function normalizeTree (tree, options) {
|
445 | return parser(render(tree), options)
|
446 | }
|