1.0.0 • Published 6 years ago
make-code-sync v1.0.0
make-code-sync
Makes common async calls like setTimout sync.
This module takes an abstract syntax tree (AST) and transforms it so that all calls to e.g. setTimeout will be executed synchronously.
If your code does not use any other async funtions like fetch, it will be easy to do analyses on it or run it using vm.runInNewContext.
Caveats
- Right now only
setTimeoutworks, but I plan to supportsetImmediateas wellsetInterval. - The
setTimeoutmock is not spec-compatible. Actually, it is quite lacking.
Installing
npm install make-code-syncUsage
const parse = require('acorn').parse
const generate = require('escodegen').generate
const vm = require('vm')
const assert = require('assert')
const syncify = require('.')
// `now` filters out all calls to `setTimeout`.
// `defer`, running in the end, executes all `setTimeout` callbacks, ordered by delay.
const {now, defer} = require('./hooks')
const code = `
let x = 2
setTimeout(() => {
x += 1
}, 100)
x = 0
`
const parsed = parse(code, {ecmaVersion: 6})
const sync = syncify(parsed)
const transformed = generate(sync.ast)
+ '\nx' // to get the value of `x`s
const ctx = {setTimeout, [sync.nameOfNow]: now, [sync.nameOfDefer]: defer}
assert.strictEqual(vm.runInNewContext(transformed, ctx), 1)Contributing
If you have a question, found a bug or want to propose a feature, have a look at the issues page.