1 | 'use strict'
|
2 |
|
3 | const vm = require('vm')
|
4 | const matchHelper = require('posthtml-match-helper')
|
5 | const { render } = require('posthtml-render')
|
6 | const { match } = require('posthtml/lib/api')
|
7 |
|
8 | const ctx = vm.createContext({ module })
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 |
|
15 |
|
16 |
|
17 |
|
18 |
|
19 | function scriptDataLocals (tree, options) {
|
20 | const locals = {}
|
21 | const localsAttr = options.localsAttr
|
22 | const localsContext = options.locals || {}
|
23 |
|
24 | match.call(tree, matchHelper(`script[${localsAttr}]`), node => {
|
25 | if (node.content) {
|
26 | const code = render(node.content)
|
27 |
|
28 | try {
|
29 | const parsedContext = vm.createContext({ ...ctx, locals: localsContext })
|
30 | const local = vm.runInContext(code, parsedContext)
|
31 |
|
32 | Object.assign(locals, local)
|
33 | } catch {};
|
34 | }
|
35 |
|
36 | if (options.removeScriptLocals) {
|
37 | return ''
|
38 | }
|
39 |
|
40 | return node
|
41 | })
|
42 |
|
43 | return {
|
44 | locals
|
45 | }
|
46 | }
|
47 |
|
48 | module.exports = scriptDataLocals
|