Tengo REPL de JavaScript . He preguntado antes ¿Cómo crear REPL de JavaScript que funcione con let y const? . Pude resolver mi problema con el módulo VM Node que está integrado en browserify y node-falafel (JS AST transformer).
El REPL funciona bien, pero tengo problema al evaluar:
document.querySelectorAll('div');La máquina virtual devuelve una lista de nodos vacía. Pero si llamo a jQuery $('div') obtengo todos los divs de la página.
Parte relevante del código:
// before script tags: var window_names = Object.getOwnPropertyNames(window); function globals() { return Object.fromEntries(window_names.map(name => { const value = window[name]; return [name, value]; })); } const context = { __$$__: {}, ...globals(), // the same is with window here $, console: { log(...args) { console.log(...args); term.echo(args.map(repr).join(' ')); } } }; function unset(context, name) { delete context[name]; } // main interpreter funtion function exec(code, ctx = context) { ctx = {...ctx}; code = patch(code, ctx) return vm.runInNewContext(code, ctx); } function is_scoped(name, context) { return name in context.__$$__; } function patch(code, context) { let patching = []; let result = falafel(code, function(node) { if (node.type == 'VariableDeclaration') { node.declarations.forEach(declaration => { const name = declaration.id.name; if (is_scoped(name, context)) { unset(context, name); } patching.push(`__$$__.${name} = ${name}`); }); } else if (node.type === 'Identifier' && is_scoped(node.name, context) && node.parent.type !== 'VariableDeclarator') { const name = node.name; node.update(`__$$__.${name}`); } }); result = result.toString(); if (patching.length) { result += ';' + patching.join(';'); } return result; }¿Alguien sabe por qué document.querySelector no funciona en vm.runInNewContext?
Solo para estar seguro de que estaba probando usando un documento fuera de contexto:
var x = document x.querySelectorAll('div');pero, por supuesto, el documento no es una función, por lo que no tiene su propio contexto como objeto de ventana. Entonces, ¿por qué no funciona?