Commit f5aa93a763

f5aa93a763f27832c35b4c184773f104c7c7d760

parent: 2ae621777b

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-20 18:29 UTC

Run js blocks as a CommonJS file and refuse more node-only js

Run the main script as a module function with this as module.exports.
Refuse import or export anywhere in a script that doesn't parse, import(),
__filename and __dirname, listing the global object, promise callbacks that
print or throw after a session block, and the source text of built-in
functions. Make the global object's enumerable names node's.

Layout: unified · split

Sources/OrgApp/JavaScriptBlocks.swift +144 −49
@@ -102,7 +102,7 @@ public enum JavaScriptBlocks {
102102 func engine(_ key: String) -> Engine {
103103 lock.withLock {
104104 if let engine = engines[key] { return engine }
105 let engine = Engine()
105 let engine = Engine(session: true)
106106 engines[key] = engine
107107 return engine
108108 }
@@ -126,18 +126,32 @@ public enum JavaScriptBlocks {
126126 private let output: Output
127127 private let lock = NSLock()
128128
129 init() {
129 /// A session's context has `require`, `module` and the rest of a module's names as
130 /// globals, as `node -e` has them.
131 init(session: Bool = false) {
130132 let output = Output()
131133 self.output = output
132134 context = JSContext()
133135 let write: @convention(block) (Int32, String) -> Void = { fd, text in
134136 if fd == 1 { output.stdout += text } else { output.stderr += text }
135137 }
138 // Runs a session's script as a script of its own, which the caller's call holds back
139 // the promise callbacks of: whether it threw, and its error or completion value.
140 let script: @convention(block) (String) -> JSValue = { source in
141 let context = JSContext.current()!
142 output.exception = nil
143 let completion = context.evaluateScript(source)
144 let result = JSValue(newArrayIn: context)!
145 result.setValue(output.exception != nil, at: 0)
146 result.setValue(output.exception ?? completion, at: 1)
147 output.exception = nil
148 return result
149 }
136150 context.exceptionHandler = { _, exception in output.exception = exception }
137 node = context.evaluateScript(Self.shim).call(withArguments: [write])
151 node = context.evaluateScript(Self.shim).call(withArguments: [write, script, session])
138152 }
139153
140 /// Runs `source` as node runs a script on standard input, then its timers.
154 /// Runs `source` as node runs a script file, as Emacs runs it, then its timers.
141155 func main(_ source: String, run: Run) throws -> BabelOutput {
142156 node.invokeMethod("main", withArguments: [source])
143157 runTimers(run)
@@ -146,28 +160,17 @@ public enum JavaScriptBlocks {
146160
147161 /// Runs `source` where the session's earlier scripts ran, as `vm.runInThisContext` does;
148162 /// with `value`, the result is its completion value as `util.inspect` prints it. A block
149 /// that leaves a timer is refused.
163 /// that leaves a timer, or a promise callback that prints or throws, is refused.
150164 func session(_ source: String, value: Bool, run: Run) throws -> BabelOutput {
151165 try lock.withLock {
152166 output.stdout = ""
153167 output.stderr = ""
154168 output.exception = nil
155 node.invokeMethod("begin", withArguments: [])
156 let completion = context.evaluateScript(source)
157 var result: String?
158 if let exception = output.exception {
159 node.invokeMethod("failed", withArguments: [exception])
160 } else if value, let completion {
161 let inspected = node.invokeMethod("inspect", withArguments: [completion])
162 if let exception = output.exception {
163 node.invokeMethod("failed", withArguments: [exception])
164 } else {
165 result = inspected?.toString()
166 }
167 }
168 // node's session returns before its timers run, and they print later.
169 node.invokeMethod("session", withArguments: [source, value])
170 // node's session returns before its timers and promise callbacks run, and they print later.
169171 node.invokeMethod("settle", withArguments: [])
170 return try finish(result: result)
172 let result = node.forProperty("result")
173 return try finish(result: result?.isString == true ? result?.toString() : nil)
171174 }
172175 }
173176
@@ -191,16 +194,22 @@ public enum JavaScriptBlocks {
191194 /// lib/internal/util/inspect.js (MIT License, Node.js contributors). It returns the
192195 /// runner's controls.
193196 static let shim = #"""
194 (function (write) {
197 (function shim(write, script, session) {
195198 'use strict';
196 const evaluate = eval;
197 const state = { dead: false, error: undefined, refused: '', timers: [], seq: 0, now: Date.now() };
199 const functionToString = Function.prototype.toString;
200 const state = { dead: false, error: undefined, refused: '', timers: [], seq: 0, now: Date.now(), draining: false, result: undefined };
201 const lateInSession = 'a promise callback that prints or throws in a session';
198202
199203 function refuse(what) {
200204 if (!state.refused) state.refused = what;
201205 throw new Error(`${what} isn't available`);
202206 }
203207 function out(fd, text) {
208 // node's session prints a promise callback's text after the block.
209 if (state.draining) {
210 if (!state.refused) state.refused = lateInSession;
211 return;
212 }
204213 if (!state.dead) write(fd, text.toWellFormed());
205214 }
206215 // Members a script may use, its own and those in `extra`; any other, and listing them, is
@@ -695,7 +704,7 @@ public enum JavaScriptBlocks {
695704 }
696705
697706 function getFunctionBase(ctx, value, constructor, tag) {
698 const stringified = Function.prototype.toString.call(value);
707 const stringified = functionToString.call(value);
699708 if (stringified.startsWith('class') && stringified[stringified.length - 1] === '}') {
700709 const slice = stringified.slice(5, -1);
701710 const bracketIndex = slice.indexOf('{');
@@ -1274,6 +1283,10 @@ public enum JavaScriptBlocks {
12741283 state.timers = state.timers.filter((t) => t !== timer);
12751284 }
12761285 function uncaught(error) {
1286 if (state.draining) {
1287 if (!state.refused) state.refused = lateInSession;
1288 return;
1289 }
12771290 if (state.error === undefined) state.error = describe(error);
12781291 state.dead = true;
12791292 }
@@ -1288,14 +1301,19 @@ public enum JavaScriptBlocks {
12881301 }
12891302
12901303 const AsyncFunction = (async function () {}).constructor;
1304 // A script that doesn't parse, which node may run as an ES module. Any `import` or `export`
1305 // counts, even in a string or comment.
12911306 function moduleOnly(source) {
1292 if (/^\s*(import\s*[\w{*'"]|export\s)|\bimport\s*\.\s*meta\b/m.test(source)) return true;
1307 if (/\b(import|export)\b/.test(source)) return true;
12931308 try { new AsyncFunction(source); } catch { return false; }
12941309 try { new Function(source); return false; } catch { return true; }
12951310 }
1311 // `import()`, which parses in a script and never settles here.
1312 const dynamicImport = /(?<![\w$.])import\s*(\(|\/[*\/])/;
12961313
1314 const module = guard({ exports: {} }, 'module');
12971315 const globals = {
1298 require, console, process, global: globalThis, Proxy: ProxyConstructor, module: guard({ exports: {} }, 'module'), __filename: '[stdin]', __dirname: '.',
1316 console, process, global: globalThis, Proxy: ProxyConstructor,
12991317 setTimeout: (callback, delay, ...args) => schedule(callback, delay, args, false),
13001318 setInterval: (callback, delay, ...args) => schedule(callback, delay, args, true),
13011319 clearTimeout: clear, clearInterval: clear,
@@ -1304,11 +1322,40 @@ public enum JavaScriptBlocks {
13041322 Promise.resolve().then(() => { try { callback(); } catch (error) { uncaught(error); } });
13051323 },
13061324 };
1307 globals.exports = globals.module.exports;
1325 // A promise callback that throws after a session's block ends its session in node.
1326 const then = Promise.prototype.then;
1327 const late = (callback) => typeof callback !== 'function' ? callback : function (value) {
1328 try {
1329 return callback(value);
1330 } catch (error) {
1331 if (state.draining && !state.refused) state.refused = lateInSession;
1332 throw error;
1333 }
1334 };
1335 Object.defineProperty(Promise.prototype, 'then', {
1336 value: { then(onFulfilled, onRejected) { return then.call(this, late(onFulfilled), late(onRejected)); } }.then,
1337 writable: true, configurable: true,
1338 });
1339 // Node's enumerable globals, in node's order; `node -e` adds a module's names after them.
1340 const enumerable = [
1341 'global', 'clearImmediate', 'setImmediate', 'clearInterval', 'clearTimeout', 'setInterval', 'setTimeout',
1342 'queueMicrotask', 'structuredClone', 'atob', 'btoa', 'performance', 'fetch', 'crypto', 'navigator', 'sessionStorage',
1343 ];
1344 const moduleScope = session ? { __filename: '[eval]', module, exports: module.exports, __dirname: '.', require } : {};
1345 for (const name of enumerable) {
1346 if (Object.prototype.hasOwnProperty.call(globals, name)) {
1347 Object.defineProperty(globalThis, name, { value: globals[name], writable: true, configurable: true, enumerable: true });
1348 } else {
1349 Object.defineProperty(globalThis, name, { get() { refuse(name); }, configurable: true, enumerable: true });
1350 }
1351 }
1352 for (const [name, value] of Object.entries(moduleScope)) {
1353 Object.defineProperty(globalThis, name, { value, writable: true, configurable: true, enumerable: true });
1354 }
13081355 for (const [name, value] of Object.entries(globals)) {
1309 Object.defineProperty(globalThis, name, { value, writable: true, configurable: true, enumerable: false });
1356 if (!enumerable.includes(name)) Object.defineProperty(globalThis, name, { value, writable: true, configurable: true, enumerable: false });
13101357 }
1311 // Node 26's globals that JavaScriptCore lacks.
1358 // Node 26's other globals that JavaScriptCore lacks.
13121359 for (const name of [
13131360 'AbortController', 'AbortSignal', 'AsyncDisposableStack', 'atob', 'Blob', 'BroadcastChannel', 'btoa', 'Buffer',
13141361 'ByteLengthQueuingStrategy', 'clearImmediate', 'CloseEvent', 'CompressionStream', 'CountQueuingStrategy', 'Crypto',
@@ -1340,53 +1387,101 @@ public enum JavaScriptBlocks {
13401387 configurable: true,
13411388 });
13421389 const errorLike = (v) => v === Error.prototype || isError(v);
1343 function refuseErrors(object, name, test) {
1390 // Calls `test` refuses, with what they use.
1391 function refuseCalls(object, name, test) {
13441392 object[name] = new RealProxy(object[name], {
13451393 apply(target, self, args) {
1346 if (test(self, args)) refuse("an error's own properties");
1394 const what = test(self, args);
1395 if (what) refuse(what);
13471396 return Reflect.apply(target, self, args);
13481397 },
13491398 });
13501399 }
1400 const errors = "an error's own properties";
1401 // The global object behind the script's proxies. Its enumerable names are node's, but
1402 // the order of all of them is JavaScriptCore's.
1403 const isGlobal = (v) => {
1404 for (let p = proxies.get(v); p; p = proxies.get(v)) v = p[0];
1405 return v === globalThis;
1406 };
1407 const listing = (v) => isGlobal(v) ? "a list of the global object's properties" : '';
13511408 for (const [object, name] of [[Object, 'getOwnPropertyNames'], [Object, 'getOwnPropertyDescriptors'], [Reflect, 'ownKeys']]) {
1352 refuseErrors(object, name, (self, [v]) => errorLike(v));
1409 refuseCalls(object, name, (self, [v]) => listing(v) || (errorLike(v) ? errors : ''));
13531410 }
1411 refuseCalls(Object, 'getOwnPropertySymbols', (self, [v]) => listing(v));
1412 // A session's `var`s come first in JavaScriptCore and last in node.
1413 if (session) refuseCalls(Object, 'keys', (self, [v]) => listing(v));
1414 const sessionListing = /\bfor\s*\([^)]*\bin\s+(globalThis|global|this)\s*\)/;
13541415 for (const [object, name] of [[Object, 'getOwnPropertyDescriptor'], [Object, 'hasOwn'], [Reflect, 'getOwnPropertyDescriptor']]) {
1355 refuseErrors(object, name, (self, [v, key]) => key === 'stack' && errorLike(v));
1416 refuseCalls(object, name, (self, [v, key]) => key === 'stack' && errorLike(v) ? errors : '');
13561417 }
13571418 for (const name of ['hasOwnProperty', 'propertyIsEnumerable']) {
1358 refuseErrors(Object.prototype, name, (self, [key]) => key === 'stack' && errorLike(self));
1419 refuseCalls(Object.prototype, name, (self, [key]) => key === 'stack' && errorLike(self) ? errors : '');
13591420 }
1421 // A built-in function's text is laid out differently from V8's, and the functions here
1422 // are native in node.
1423 const shimText = functionToString.call(shim);
1424 refuseCalls(Function.prototype, 'toString', (self) => {
1425 let text;
1426 try { text = functionToString.call(self); } catch { return ''; }
1427 return /\[native code\]\s*\}$/.test(text) || shimText.includes(text) ? "a built-in function's source text" : '';
1428 });
13601429
13611430 return {
1362 // A script run as `node` runs standard input; an uncaught error ends it.
1431 // A script run as `node` runs a CommonJS file; an uncaught error ends it. `__filename`
1432 // and `__dirname` name Emacs's temporary file.
13631433 main(source) {
1434 if (/\b__(filename|dirname)\b/.test(source)) {
1435 state.refused = '__filename or __dirname';
1436 return;
1437 }
1438 if (dynamicImport.test(source)) {
1439 state.refused = 'top-level await, import or export';
1440 return;
1441 }
1442 let body;
13641443 try {
1365 evaluate(source);
1444 body = new Function('exports', 'require', 'module', '__filename', '__dirname', source);
13661445 } catch (error) {
13671446 // node runs a script that doesn't parse as one as an ES module, when that parses.
1368 if (error instanceof SyntaxError && moduleOnly(source)) {
1369 if (!state.refused) state.refused = 'top-level await, import or export';
1370 } else {
1371 uncaught(error);
1372 }
1447 if (error instanceof SyntaxError && moduleOnly(source)) state.refused = 'top-level await, import or export';
1448 else uncaught(error);
1449 return;
1450 }
1451 try {
1452 body.call(module.exports, module.exports, require, module, undefined, undefined);
1453 } catch (error) {
1454 uncaught(error);
13731455 }
13741456 },
1375 begin() {
1376 state.dead = false;
1377 state.error = undefined;
1378 state.refused = '';
1379 state.now = Date.now();
1457 // A session's script, and its value as the session writes it. Promise callbacks run
1458 // after this returns.
1459 session(source, value) {
1460 Object.assign(state, { dead: false, error: undefined, refused: '', now: Date.now(), draining: false, result: undefined });
1461 if (dynamicImport.test(source)) {
1462 state.refused = 'top-level await, import or export';
1463 return;
1464 }
1465 if (sessionListing.test(source)) {
1466 state.refused = "a list of the global object's properties";
1467 return;
1468 }
1469 Promise.resolve().then(() => { state.draining = true; });
1470 const [failed, completion] = script(source);
1471 if (failed) {
1472 uncaught(completion);
1473 } else if (value) {
1474 try { state.result = inspect(completion); } catch (error) { uncaught(error); }
1475 }
13801476 },
1381 // After a session's script: its error, or its value as the session writes it.
1382 failed(error) { uncaught(error); },
13831477 // Drops a session's timers, which would print after the block in node, and refuses the block.
13841478 settle() {
1479 state.draining = false;
13851480 if (state.timers.length === 0) return;
13861481 state.timers = [];
13871482 if (!state.refused) state.refused = 'a timer in a session';
13881483 },
1389 inspect(value) { return inspect(value); },
1484 get result() { return state.result; },
13901485 // Runs the next timer that is due: the milliseconds until one is, 0 after running one,
13911486 // or -1 when none is left to wait for.
13921487 tick() {
Tests/OrgAppTests/JavaScriptBlocksTests.swift +62 −11
@@ -1,4 +1,5 @@
11import Foundation
2import JavaScriptCore
23import OrgCore
34import OrgDocument
45import Testing
@@ -16,19 +17,20 @@ struct JavaScriptBlocksTests {
1617 return job
1718 }
1819
19 /// `node` reading `input` on standard input, as BabelRunner starts it.
20 static func node(_ input: String, in folder: URL) throws -> (stdout: String, status: Int32) {
20 /// `node` running `input` from a file, as Emacs runs it.
21 static func node(_ input: String, in folder: URL, arguments: [String] = []) throws -> (stdout: String, status: Int32) {
22 let file = FileManager.default.temporaryDirectory.appendingPathComponent("js-script-\(UUID().uuidString)")
23 try input.write(to: file, atomically: true, encoding: .utf8)
24 defer { try? FileManager.default.removeItem(at: file) }
2125 let process = Process()
2226 process.executableURL = URL(fileURLWithPath: "/usr/bin/env")
23 process.arguments = ["node"]
27 process.arguments = ["node"] + arguments + [file.path]
2428 process.currentDirectoryURL = folder
25 let stdin = Pipe(), stdout = Pipe()
26 process.standardInput = stdin
29 let stdout = Pipe()
30 process.standardInput = FileHandle.nullDevice
2731 process.standardOutput = stdout
2832 process.standardError = FileHandle.nullDevice
2933 try process.run()
30 stdin.fileHandleForWriting.write(Data(input.utf8))
31 try stdin.fileHandleForWriting.close()
3234 let data = stdout.fileHandleForReading.readDataToEndOfFile()
3335 process.waitUntilExit()
3436 return (String(decoding: data, as: UTF8.self), process.terminationStatus)
@@ -64,10 +66,13 @@ struct JavaScriptBlocksTests {
6466 "console.log('before'); undefinedThing.x; console.log('after')",
6567 "Promise.resolve().then(() => console.log('not printed')); throw new Error('sync')",
6668 "setTimeout(() => { throw new TypeError('in timer'); }, 1); setTimeout(() => console.log('not reached'), 5)",
67 "var x = 5; console.log(globalThis.x, this === globalThis, typeof module, __filename, global === globalThis)",
69 "var x = 5; console.log(globalThis.x, this === globalThis, typeof module, global === globalThis)",
70 "console.log(this === module.exports, typeof exports, exports === module.exports, arguments.length); this.a = 1; console.log(module.exports)",
71 "console.log('top'); return; console.log('not reached')",
6872 "console.log(JSON.stringify({a: 1, b: [1, 2]}, null, 2), [3, 1, 2].sort(), 0.1 + 0.2)",
69 // Every global of node's is here or refused.
70 "console.log(Object.getOwnPropertyNames(globalThis).sort().join(' '))",
73 "globalThis.y = 1; z = 2; console.log(Object.keys(globalThis).join(' ')); for (const k in global) console.log(k)",
74 "console.log(Object.keys(new Proxy(globalThis, {})).length, 'require' in globalThis, 'module' in globalThis, typeof require)",
75 "console.log(Function.prototype.toString.call(function f(a) { return a; }), String(() => 1), `${class A {}}`)",
7176 "console.log(Object.prototype.toString.call(process), Object.prototype.toString.call(console), typeof require, require.name, require.length)",
7277 "module.exports = 5; console.log(module.exports, exports, typeof module)",
7378 "const e = new TypeError('x'); e.stack = 's'; console.log(e.stack, 'stack' in e, Object.keys(e), JSON.stringify(e), String(e))",
@@ -100,6 +105,7 @@ struct JavaScriptBlocksTests {
100105 "#+begin_src js :results output :epilogue console.log('end')\nconsole.log('body')\n#+end_src\n",
101106 "#+begin_src js\nreturn {a: 1, b: [1, 2]}\n#+end_src\n",
102107 "#+begin_src js :results output\nsetTimeout(() => console.log('later'), 10); console.log('now')\n#+end_src\n",
108 "#+begin_src js :results output\nconsole.log(this === module.exports, typeof exports)\n#+end_src\n",
103109 ]
104110
105111 /// The results the app inserts, as Emacs inserts them running the block with node.
@@ -144,6 +150,7 @@ struct JavaScriptBlocksTests {
144150 @Test func whatNodeAloneHasIsRefused() async throws {
145151 let folder = FileManager.default.temporaryDirectory
146152 let module = "top-level await, import or export", stack = "an error's own properties"
153 let listing = "a list of the global object's properties", source = "a built-in function's source text"
147154 for (header, body, what) in [
148155 ("", "return new Error('x')", "util.inspect of an Error"), ("", "return Promise.resolve(1)", "util.inspect of a Promise"),
149156 ("", "return Buffer.from('a')", "Buffer"), ("", "return process.env.HOME", "process.env"), ("", "console.table([1])", "console.table"),
@@ -163,13 +170,22 @@ struct JavaScriptBlocksTests {
163170 ("", "return require.cache", "require.cache"), ("", "return module.id", "module.id"), ("", "return typeof module.paths", "module.paths"),
164171 (" :results output", "console.log(globalThis)", "util.inspect of the global object"), ("", "return this", "util.inspect of the global object"),
165172 ("", "return require", "util.inspect of require"), ("", "return module", "util.inspect of module"),
173 (" :results output", "const a = 1; import util from 'util'; console.log(util.format('%d', 3))", module),
174 (" :results output", "/* c */ import util from 'util'; console.log(util.format('%d', 3))", module),
175 (" :results output", "import('util').then(m => console.log(typeof m.format))", module),
176 (" :results output", "console.log(__filename)", "__filename or __dirname"), ("", "return __dirname", "__filename or __dirname"),
177 ("", "return Object.getOwnPropertyNames(globalThis).length", listing), ("", "return Reflect.ownKeys(new Proxy(global, {}))", listing),
178 ("", "return Object.getOwnPropertyDescriptors(globalThis)", listing), ("", "return Object.getOwnPropertySymbols(globalThis)", listing),
179 ("", "return Object.values(globalThis)", "clearImmediate"),
180 ("", "return Function.prototype.toString.call(Object.prototype.propertyIsEnumerable)", source),
181 ("", "return String(Math.max)", source), ("", "return String(console.log)", source), ("", "return `${setTimeout}`", source),
166182 ] {
167183 await #expect(throws: Babel.Failure.message("This block uses \(what), which runs only in node."), "\(body)") {
168184 try await JavaScriptBlocks.run(Self.plan("#+begin_src js\(header)\n\(body)\n#+end_src\n"), directory: folder)
169185 }
170186 }
171187 // A syntax error that isn't a module's is reported, as node reports it.
172 #expect(try await JavaScriptBlocks.run(Self.plan("#+begin_src js :results output\nconsole.log(1); return 2\n#+end_src\n"), directory: folder)?.status == 1)
188 #expect(try await JavaScriptBlocks.run(Self.plan("#+begin_src js :results output\nconsole.log(1); )\n#+end_src\n"), directory: folder)?.status == 1)
173189 #expect(try await JavaScriptBlocks.run(Self.plan("#+begin_src python\n1\n#+end_src\n"), directory: folder) == nil)
174190 await #expect(throws: Babel.Failure.message("No folder \(folder.appendingPathComponent("nowhere").path) for :dir.")) {
175191 try await JavaScriptBlocks.run(Self.plan("#+begin_src js :dir nowhere\nreturn 1\n#+end_src\n"), directory: folder)
@@ -194,6 +210,26 @@ struct JavaScriptBlocksTests {
194210 try await run("", "setTimeout(() => {}, 1).unref(); 2")
195211 }
196212 #expect(try await run("", "const t = setTimeout(() => {}, 1); clearTimeout(t); z")?.resultFile == "1")
213 // Promise callbacks run after node's session returns: their text would go to the next block.
214 for body in ["Promise.resolve().then(() => console.log('late')); console.log('now')", "queueMicrotask(() => console.log('q'))",
215 "(async () => { await null; console.error('e'); })()", "Promise.resolve().then(() => { throw new Error('x'); })",
216 "throw (Promise.resolve().then(() => console.log('late')), new Error('x'))"] {
217 await #expect(throws: Babel.Failure.message("This block uses a promise callback that prints or throws in a session, which runs only in node."), "\(body)") {
218 try await run(" :results output", body)
219 }
220 }
221 // The value is printed before they run, and the next block sees what they did.
222 #expect(try await run("", "var o = {a: 1}; Promise.resolve().then(() => { o.a = 2; }); o")?.resultFile == "{ a: 1 }")
223 #expect(try await run("", "[o.a, this === globalThis, __filename, __dirname, exports === module.exports]")?.resultFile
224 == "[ 2, true, '[eval]', '.', true ]")
225 for body in ["Object.keys(globalThis)", "for (const k in global) console.log(k)"] {
226 await #expect(throws: Babel.Failure.message("This block uses a list of the global object's properties, which runs only in node."), "\(body)") {
227 try await run(" :results output", body)
228 }
229 }
230 await #expect(throws: Babel.Failure.message("This block uses top-level await, import or export, which runs only in node.")) {
231 try await run("", "import('util')")
232 }
197233 // An error while printing the value is reported, and there is no result.
198234 let thrown = try await run("", "({[Symbol.for('nodejs.util.inspect.custom')]() { throw new TypeError('boom') }})")
199235 #expect(thrown == BabelOutput(stdout: "", stderr: "TypeError: boom\n", status: 1))
@@ -201,6 +237,21 @@ struct JavaScriptBlocksTests {
201237 #expect(try await JavaScriptBlocks.run(Self.plan("#+begin_src js :session work\ntypeof x\n#+end_src\n"), directory: other.url)?.resultFile == "'undefined'")
202238 }
203239
240 /// Every global of node's is here, and no other, though listing them is refused.
241 @Test(.enabled(if: oracle && nodeInstalled))
242 func globalsAreNodes() async throws {
243 let folder = FileManager.default.temporaryDirectory
244 let theirs = try Self.node("console.log(JSON.stringify(Object.getOwnPropertyNames(globalThis).sort()))", in: folder)
245 let names = try #require(try JSONSerialization.jsonObject(with: Data(theirs.stdout.utf8)) as? [String])
246 let missing = try await JavaScriptBlocks.run(Self.plan("#+begin_src js\nreturn \(theirs.stdout.trimmingCharacters(in: .newlines)).filter(n => !(n in globalThis))\n#+end_src\n"), directory: folder)
247 #expect(missing?.stdout == "[]")
248 let context = try #require(JSContext())
249 context.evaluateScript("var names = Object.getOwnPropertyNames")
250 context.evaluateScript(JavaScriptBlocks.Engine.shim).call(withArguments: [{ (_: Int32, _: String) in } as @convention(block) (Int32, String) -> Void, NSNull(), false])
251 let ours = context.evaluateScript("names(globalThis).filter(n => n !== 'names').sort()").toArray() as? [String]
252 #expect(ours == names)
253 }
254
204255 @Test func cancelAndTimeoutEndTheRun() async throws {
205256 let folder = FileManager.default.temporaryDirectory
206257 // Spins for seconds, as an endless loop would, but ends so the test leaves no thread busy.
docs/manual/guide/11-code-blocks.org +3 −3
@@ -107,15 +107,15 @@ The [[file:../install.org][Mac App Store version]] starts no programs, so only E
107107
108108** JavaScript in JavaScriptCore
109109
110In the Mac App Store version and on iOS, =js= and =javascript= blocks run in JavaScriptCore, the JavaScript engine built into macOS and iOS. The download version uses it when =node=, or the program in =:cmd=, isn't installed; a =:cmd= with options, such as =node --no-warnings=, never runs in JavaScriptCore. A block runs as =node= runs a program on standard input, and its output and result are what node gives:
110In the Mac App Store version and on iOS, =js= and =javascript= blocks run in JavaScriptCore, the JavaScript engine built into macOS and iOS. The download version uses it when =node=, or the program in =:cmd=, isn't installed; a =:cmd= with options, such as =node --no-warnings=, never runs in JavaScriptCore. A block runs as Emacs runs it, with =node= reading it from a file as a CommonJS module, where =this= is =module.exports= and top-level =var= declarations stay in the block. Its output and result are what node gives:
111111
112112- =console.log=, =console.info= and =console.debug= write to the output, =console.warn= and =console.error= to the error output, and =console.dir= prints with =util.inspect=. =process.stdout.write= and =process.stderr.write= write text.
113113- =require('util')= has =inspect=, =format= and =formatWithOptions=, which print values as Node 26 prints them. =require('process')= has =stdout= and =stderr=.
114- =setTimeout=, =setInterval=, their =clear= functions and =queueMicrotask= work. Timers run after the program, in the order node runs them, and the run ends when none is left. In a =:session=, a block that leaves a timer set is refused, since node's session returns before the timer runs and prints its output later.
114- =setTimeout=, =setInterval=, their =clear= functions and =queueMicrotask= work. Timers run after the program, in the order node runs them, and the run ends when none is left. In a =:session=, a block that leaves a timer set, or whose promise callbacks print or throw, is refused, since node's session returns before they run and they print later.
115115- An uncaught error ends the run with status 1 and writes its name and message to the error output, such as "ReferenceError: hline is not defined".
116116- =require= of any other module fails as it does for a module node can't find: "Error: Cannot find module 'fs'".
117117
118A block that uses something only node has fails with "This block uses /name/, which runs only in node.", rather than giving a different result. That covers other members of =process=, =util=, =console=, =require= and =module= (=process.env=, =console.table=, =require.resolve=, =module.id=) and listing their members; Node's other globals (=Buffer=, =fetch=, =URL=, =TextEncoder=, =setImmediate=, =structuredClone=, =SharedArrayBuffer=, =Temporal=, =ReadableStream=); top-level =await= and =import= or =export= statements, which node runs as an ES module; an error's =stack=, =Error.stackTraceLimit=, =Error.captureStackTrace= and listing an error's own properties; and printing an =Error=, a =Promise=, an iterator or the global object with =util.inspect=, whose text in node comes from its own engine. There is no access to files, the network or other programs.
118A block that uses something only node has fails with "This block uses /name/, which runs only in node.", rather than giving a different result. That covers other members of =process=, =util=, =console=, =require= and =module= (=process.env=, =console.table=, =require.resolve=, =module.id=) and listing their members; Node's other globals (=Buffer=, =fetch=, =URL=, =TextEncoder=, =setImmediate=, =structuredClone=, =SharedArrayBuffer=, =Temporal=, =ReadableStream=); top-level =await=, =import= or =export= statements, which node runs as an ES module, and =import()=; =__filename= and =__dirname=, which name Emacs's temporary file; listing the global object's properties with =Object.getOwnPropertyNames= or =Reflect.ownKeys=, and in a =:session= with =Object.keys= or =for…in=; the source text of a built-in function; an error's =stack=, =Error.stackTraceLimit=, =Error.captureStackTrace= and listing an error's own properties; and printing an =Error=, a =Promise=, an iterator or the global object with =util.inspect=, whose text in node comes from its own engine. There is no access to files, the network or other programs.
119119
120120Some things still differ from node:
121121