2018-12-22 21:05:13 +00:00
|
|
|
import serialize from 'serialize-javascript'
|
|
|
|
|
2019-07-10 10:45:49 +00:00
|
|
|
export function normalizeFunctions (obj) {
|
2019-04-22 18:47:42 +00:00
|
|
|
if (typeof obj !== 'object' || Array.isArray(obj) || obj === null) {
|
|
|
|
return obj
|
|
|
|
}
|
|
|
|
for (const key in obj) {
|
|
|
|
if (key === '__proto__' || key === 'constructor') {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
const val = obj[key]
|
|
|
|
if (val !== null && typeof val === 'object' && !Array.isArray(obj)) {
|
|
|
|
obj[key] = normalizeFunctions(val)
|
|
|
|
}
|
|
|
|
if (typeof obj[key] === 'function') {
|
|
|
|
const asString = obj[key].toString()
|
2019-04-26 19:16:16 +00:00
|
|
|
const match = asString.match(/^([^{(]+)=>\s*([\0-\uFFFF]*)/)
|
2019-04-22 18:47:42 +00:00
|
|
|
if (match) {
|
2019-04-26 19:16:16 +00:00
|
|
|
const fullFunctionBody = match[2].match(/^{?(\s*return\s+)?([\0-\uFFFF]*?)}?$/)
|
2019-04-22 18:47:42 +00:00
|
|
|
let functionBody = fullFunctionBody[2].trim()
|
2019-04-26 19:16:16 +00:00
|
|
|
if (fullFunctionBody[1] || !match[2].trim().match(/^\s*{/)) {
|
2019-04-22 18:47:42 +00:00
|
|
|
functionBody = `return ${functionBody}`
|
|
|
|
}
|
|
|
|
// eslint-disable-next-line no-new-func
|
|
|
|
obj[key] = new Function(...match[1].split(',').map(arg => arg.trim()), functionBody)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return obj
|
|
|
|
}
|
|
|
|
|
2019-07-10 10:45:49 +00:00
|
|
|
export function serializeFunction (func) {
|
2018-12-22 21:05:13 +00:00
|
|
|
let open = false
|
2019-04-22 18:47:42 +00:00
|
|
|
func = normalizeFunctions(func)
|
2018-12-22 21:05:13 +00:00
|
|
|
return serialize(func)
|
|
|
|
.replace(serializeFunction.assignmentRE, (_, spaces) => {
|
2019-01-06 07:56:59 +00:00
|
|
|
return `${spaces}: function (`
|
2018-12-22 21:05:13 +00:00
|
|
|
})
|
|
|
|
.replace(serializeFunction.internalFunctionRE, (_, spaces, name, args) => {
|
|
|
|
if (open) {
|
2019-01-06 07:56:59 +00:00
|
|
|
return `${spaces}${name}: function (${args}) {`
|
2018-12-22 21:05:13 +00:00
|
|
|
} else {
|
|
|
|
open = true
|
|
|
|
return _
|
|
|
|
}
|
|
|
|
})
|
2019-02-01 13:31:16 +00:00
|
|
|
.replace(`${func.name || 'function'}(`, 'function (')
|
2019-05-19 18:50:52 +00:00
|
|
|
.replace(`function function`, `function`)
|
2018-12-22 21:05:13 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
serializeFunction.internalFunctionRE = /^(\s*)(?!(?:if)|(?:for)|(?:while)|(?:switch))(\w+)\s*\((.*?)\)\s*\{/gm
|
|
|
|
serializeFunction.assignmentRE = /^(\s*):(\w+)\(/gm
|