Commit 2ae621777b

2ae621777bacad86f9d4aceeb33ed24f29300c56

parent: 702b2432b0

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-20 17:37 UTC

Refuse more node-only js in JavaScriptCore

Refuse top-level await and import/export, Error.stack, node's remaining
globals, unknown members of require and module, listing guarded objects,
inspecting the global object, and timers left by a session block. Report
an error thrown while inspecting a session's value. Leave a :cmd with
arguments to the runner.

Layout: unified · split

Sources/OrgApp/JavaScriptBlocks.swift +102 −21
@@ -145,7 +145,8 @@ public enum JavaScriptBlocks {
145 } 145 }
146 146
147 /// Runs `source` where the session's earlier scripts ran, as `vm.runInThisContext` does; 147 /// Runs `source` where the session's earlier scripts ran, as `vm.runInThisContext` does;
148 /// with `value`, the result is its completion value as `util.inspect` prints it. 148 /// with `value`, the result is its completion value as `util.inspect` prints it. A block
149 /// that leaves a timer is refused.
149 func session(_ source: String, value: Bool, run: Run) throws -> BabelOutput { 150 func session(_ source: String, value: Bool, run: Run) throws -> BabelOutput {
150 try lock.withLock { 151 try lock.withLock {
151 output.stdout = "" 152 output.stdout = ""
@@ -157,9 +158,15 @@ public enum JavaScriptBlocks {
157 if let exception = output.exception { 158 if let exception = output.exception {
158 node.invokeMethod("failed", withArguments: [exception]) 159 node.invokeMethod("failed", withArguments: [exception])
159 } else if value, let completion { 160 } else if value, let completion {
160 result = node.invokeMethod("inspect", withArguments: [completion]).toString() 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 }
161 } 167 }
162 runTimers(run) 168 // node's session returns before its timers run, and they print later.
169 node.invokeMethod("settle", withArguments: [])
163 return try finish(result: result) 170 return try finish(result: result)
164 } 171 }
165 } 172 }
@@ -196,16 +203,25 @@ public enum JavaScriptBlocks {
196 function out(fd, text) { 203 function out(fd, text) {
197 if (!state.dead) write(fd, text.toWellFormed()); 204 if (!state.dead) write(fd, text.toWellFormed());
198 } 205 }
199 // Members a script may use; any other is refused rather than answered differently. 206 // Members a script may use, its own and those in `extra`; any other, and listing them, is
200 const guarded = new WeakSet(); 207 // refused rather than answered differently.
201 function guard(target, name) { 208 const ownProperty = Function.prototype.call.bind(Object.prototype.hasOwnProperty);
209 const guarded = new WeakMap();
210 function guard(target, name, extra = []) {
211 const known = (t, key) => typeof key === 'symbol' || ownProperty(t, key) || extra.includes(key);
212 const member = (t, key) => { if (!known(t, key)) refuse(`${name}.${String(key)}`); };
202 const proxy = new Proxy(target, { 213 const proxy = new Proxy(target, {
203 get(t, key, receiver) { 214 get(t, key, receiver) { member(t, key); return Reflect.get(t, key, receiver); },
204 if (typeof key === 'symbol' || key in t) return Reflect.get(t, key, receiver); 215 has(t, key) { member(t, key); return Reflect.has(t, key); },
205 refuse(`${name}.${key}`); 216 set(t, key, value, receiver) { member(t, key); return Reflect.set(t, key, value, receiver); },
206 }, 217 defineProperty(t, key, descriptor) { member(t, key); return Reflect.defineProperty(t, key, descriptor); },
218 deleteProperty(t, key) { member(t, key); return Reflect.deleteProperty(t, key); },
219 getOwnPropertyDescriptor(t, key) { member(t, key); return Reflect.getOwnPropertyDescriptor(t, key); },
220 ownKeys() { refuse(`the members of ${name}`); },
221 getPrototypeOf() { refuse(`the prototype of ${name}`); },
222 setPrototypeOf() { refuse(`the prototype of ${name}`); },
207 }); 223 });
208 guarded.add(proxy); 224 guarded.set(proxy, name);
209 return proxy; 225 return proxy;
210 } 226 }
211 // The script's proxies, target and handler, or null once revoked: JavaScriptCore can't tell 227 // The script's proxies, target and handler, or null once revoked: JavaScriptCore can't tell
@@ -339,7 +355,8 @@ public enum JavaScriptBlocks {
339 function formatValue(ctx, value, recurseTimes, typedArray) { 355 function formatValue(ctx, value, recurseTimes, typedArray) {
340 if (typeof value !== 'object' && typeof value !== 'function') return formatPrimitive(value, ctx); 356 if (typeof value !== 'object' && typeof value !== 'function') return formatPrimitive(value, ctx);
341 if (value === null) return 'null'; 357 if (value === null) return 'null';
342 if (guarded.has(value)) refuse('util.inspect of console, process or util'); 358 if (guarded.has(value)) refuse(`util.inspect of ${guarded.get(value)}`);
359 if (value === globalThis) refuse('util.inspect of the global object');
343 const context = value; 360 const context = value;
344 let proxyCount = 0; 361 let proxyCount = 0;
345 let proxy = proxies.get(value); 362 let proxy = proxies.get(value);
@@ -1207,24 +1224,25 @@ public enum JavaScriptBlocks {
1207 }, 1224 },
1208 }, name); 1225 }, name);
1209 } 1226 }
1210 const process = guard({ stdout: stream(1, 'process.stdout'), stderr: stream(2, 'process.stderr') }, 'process'); 1227 const process = guard({ stdout: stream(1, 'process.stdout'), stderr: stream(2, 'process.stderr'), [Symbol.toStringTag]: 'process' }, 'process');
1211 const util = guard({ 1228 const util = guard({
1212 inspect, 1229 inspect,
1213 format: (...args) => formatWithOptions(undefined, args), 1230 format: (...args) => formatWithOptions(undefined, args),
1214 formatWithOptions: (options, ...args) => formatWithOptions(options, args), 1231 formatWithOptions: (options, ...args) => formatWithOptions(options, args),
1215 }, 'util'); 1232 }, 'util');
1216 const modules = { process, util }; 1233 const modules = { process, util };
1217 function require(id) { 1234 const require = guard(function require(id) {
1218 const name = typeof id === 'string' && id.startsWith('node:') ? id.slice(5) : id; 1235 const name = typeof id === 'string' && id.startsWith('node:') ? id.slice(5) : id;
1219 if (Object.prototype.hasOwnProperty.call(modules, name)) return modules[name]; 1236 if (Object.prototype.hasOwnProperty.call(modules, name)) return modules[name];
1220 const error = new Error(`Cannot find module '${id}'`); 1237 const error = new Error(`Cannot find module '${id}'`);
1221 error.code = 'MODULE_NOT_FOUND'; 1238 error.code = 'MODULE_NOT_FOUND';
1222 throw error; 1239 throw error;
1223 } 1240 }, 'require', ['call', 'apply', 'bind']);
1224 const print = (fd) => (...args) => out(fd, formatWithOptions(undefined, args) + '\n'); 1241 const print = (fd) => (...args) => out(fd, formatWithOptions(undefined, args) + '\n');
1225 const console = guard({ 1242 const console = guard({
1226 log: print(1), info: print(1), debug: print(1), warn: print(2), error: print(2), 1243 log: print(1), info: print(1), debug: print(1), warn: print(2), error: print(2),
1227 dir(object, options) { out(1, inspect(object, { customInspect: false, ...options }) + '\n'); }, 1244 dir(object, options) { out(1, inspect(object, { customInspect: false, ...options }) + '\n'); },
1245 [Symbol.toStringTag]: 'console',
1228 }, 'console'); 1246 }, 'console');
1229 1247
1230 // Timers run after the script, in order of when they are due, as Node's event loop runs them. 1248 // Timers run after the script, in order of when they are due, as Node's event loop runs them.
@@ -1269,8 +1287,15 @@ public enum JavaScriptBlocks {
1269 try { return `Uncaught ${inspect(error)}`; } catch { return 'Uncaught exception'; } 1287 try { return `Uncaught ${inspect(error)}`; } catch { return 'Uncaught exception'; }
1270 } 1288 }
1271 1289
1290 const AsyncFunction = (async function () {}).constructor;
1291 function moduleOnly(source) {
1292 if (/^\s*(import\s*[\w{*'"]|export\s)|\bimport\s*\.\s*meta\b/m.test(source)) return true;
1293 try { new AsyncFunction(source); } catch { return false; }
1294 try { new Function(source); return false; } catch { return true; }
1295 }
1296
1272 const globals = { 1297 const globals = {
1273 require, console, process, global: globalThis, Proxy: ProxyConstructor, module: { exports: {} }, __filename: '[stdin]', __dirname: '.', 1298 require, console, process, global: globalThis, Proxy: ProxyConstructor, module: guard({ exports: {} }, 'module'), __filename: '[stdin]', __dirname: '.',
1274 setTimeout: (callback, delay, ...args) => schedule(callback, delay, args, false), 1299 setTimeout: (callback, delay, ...args) => schedule(callback, delay, args, false),
1275 setInterval: (callback, delay, ...args) => schedule(callback, delay, args, true), 1300 setInterval: (callback, delay, ...args) => schedule(callback, delay, args, true),
1276 clearTimeout: clear, clearInterval: clear, 1301 clearTimeout: clear, clearInterval: clear,
@@ -1283,19 +1308,69 @@ public enum JavaScriptBlocks {
1283 for (const [name, value] of Object.entries(globals)) { 1308 for (const [name, value] of Object.entries(globals)) {
1284 Object.defineProperty(globalThis, name, { value, writable: true, configurable: true, enumerable: false }); 1309 Object.defineProperty(globalThis, name, { value, writable: true, configurable: true, enumerable: false });
1285 } 1310 }
1286 for (const name of ['Buffer', 'setImmediate', 'clearImmediate', 'structuredClone', 'atob', 'btoa', 'performance', 'fetch', 1311 // Node 26's globals that JavaScriptCore lacks.
1287 'crypto', 'navigator', 'URL', 'URLSearchParams', 'TextEncoder', 'TextDecoder', 'AbortController', 'AbortSignal', 1312 for (const name of [
1288 'Event', 'EventTarget', 'Blob', 'Headers', 'Request', 'Response', 'FormData', 'WebSocket', 'MessageChannel', 1313 'AbortController', 'AbortSignal', 'AsyncDisposableStack', 'atob', 'Blob', 'BroadcastChannel', 'btoa', 'Buffer',
1289 'BroadcastChannel']) { 1314 'ByteLengthQueuingStrategy', 'clearImmediate', 'CloseEvent', 'CompressionStream', 'CountQueuingStrategy', 'Crypto',
1315 'crypto', 'CryptoKey', 'CustomEvent', 'DecompressionStream', 'DisposableStack', 'DOMException', 'ErrorEvent', 'Event',
1316 'EventTarget', 'fetch', 'File', 'FormData', 'Headers', 'localStorage', 'MessageChannel', 'MessageEvent', 'MessagePort',
1317 'Navigator', 'navigator', 'Performance', 'performance', 'PerformanceEntry', 'PerformanceMark', 'PerformanceMeasure',
1318 'PerformanceObserver', 'PerformanceObserverEntryList', 'PerformanceResourceTiming', 'QuotaExceededError',
1319 'ReadableByteStreamController', 'ReadableStream', 'ReadableStreamBYOBReader', 'ReadableStreamBYOBRequest',
1320 'ReadableStreamDefaultController', 'ReadableStreamDefaultReader', 'Request', 'Response', 'sessionStorage',
1321 'setImmediate', 'SharedArrayBuffer', 'Storage', 'structuredClone', 'SubtleCrypto', 'SuppressedError', 'Temporal',
1322 'TextDecoder', 'TextDecoderStream', 'TextEncoder', 'TextEncoderStream', 'TransformStream',
1323 'TransformStreamDefaultController', 'URL', 'URLPattern', 'URLSearchParams', 'WebSocket', 'WritableStream',
1324 'WritableStreamDefaultController', 'WritableStreamDefaultWriter'
1325 ]) {
1290 if (!(name in globalThis)) { 1326 if (!(name in globalThis)) {
1291 Object.defineProperty(globalThis, name, { get() { refuse(name); }, configurable: true }); 1327 Object.defineProperty(globalThis, name, { get() { refuse(name); }, configurable: true });
1292 } 1328 }
1293 } 1329 }
1294 1330
1331 // JavaScriptCore's stack text isn't V8's, so errors get none and reading one is refused. In
1332 // node an error's own keys include `stack`.
1333 Error.stackTraceLimit = 0;
1334 const refusing = (name) => ({ get() { refuse(name); }, set() { refuse(name); }, configurable: true });
1335 Object.defineProperty(Error, 'stackTraceLimit', { ...refusing('Error.stackTraceLimit'), enumerable: true });
1336 Object.defineProperty(Error, 'captureStackTrace', refusing('Error.captureStackTrace'));
1337 Object.defineProperty(Error.prototype, 'stack', {
1338 get() { refuse('Error.stack'); },
1339 set(value) { Object.defineProperty(this, 'stack', { value, writable: true, configurable: true }); },
1340 configurable: true,
1341 });
1342 const errorLike = (v) => v === Error.prototype || isError(v);
1343 function refuseErrors(object, name, test) {
1344 object[name] = new RealProxy(object[name], {
1345 apply(target, self, args) {
1346 if (test(self, args)) refuse("an error's own properties");
1347 return Reflect.apply(target, self, args);
1348 },
1349 });
1350 }
1351 for (const [object, name] of [[Object, 'getOwnPropertyNames'], [Object, 'getOwnPropertyDescriptors'], [Reflect, 'ownKeys']]) {
1352 refuseErrors(object, name, (self, [v]) => errorLike(v));
1353 }
1354 for (const [object, name] of [[Object, 'getOwnPropertyDescriptor'], [Object, 'hasOwn'], [Reflect, 'getOwnPropertyDescriptor']]) {
1355 refuseErrors(object, name, (self, [v, key]) => key === 'stack' && errorLike(v));
1356 }
1357 for (const name of ['hasOwnProperty', 'propertyIsEnumerable']) {
1358 refuseErrors(Object.prototype, name, (self, [key]) => key === 'stack' && errorLike(self));
1359 }
1360
1295 return { 1361 return {
1296 // A script run as `node` runs standard input; an uncaught error ends it. 1362 // A script run as `node` runs standard input; an uncaught error ends it.
1297 main(source) { 1363 main(source) {
1298 try { evaluate(source); } catch (error) { uncaught(error); } 1364 try {
1365 evaluate(source);
1366 } catch (error) {
1367 // 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 }
1373 }
1299 }, 1374 },
1300 begin() { 1375 begin() {
1301 state.dead = false; 1376 state.dead = false;
@@ -1305,6 +1380,12 @@ public enum JavaScriptBlocks {
1305 }, 1380 },
1306 // After a session's script: its error, or its value as the session writes it. 1381 // After a session's script: its error, or its value as the session writes it.
1307 failed(error) { uncaught(error); }, 1382 failed(error) { uncaught(error); },
1383 // Drops a session's timers, which would print after the block in node, and refuses the block.
1384 settle() {
1385 if (state.timers.length === 0) return;
1386 state.timers = [];
1387 if (!state.refused) state.refused = 'a timer in a session';
1388 },
1308 inspect(value) { return inspect(value); }, 1389 inspect(value) { return inspect(value); },
1309 // Runs the next timer that is due: the milliseconds until one is, 0 after running one, 1390 // Runs the next timer that is due: the milliseconds until one is, 0 after running one,
1310 // or -1 when none is left to wait for. 1391 // or -1 when none is left to wait for.
Sources/OrgPrograms/Programs.swift +3 −2
@@ -8,10 +8,11 @@ public struct Programs: ProgramRunning {
8 public init() {} 8 public init() {}
9 9
10 public func runBabel(_ job: BabelJob, fileDirectory: URL) async throws -> BabelOutput { 10 public func runBabel(_ job: BabelJob, fileDirectory: URL) async throws -> BabelOutput {
11 // js in JavaScriptCore when node (or `:cmd`) isn't installed. 11 // js in JavaScriptCore when node (or `:cmd`) isn't installed. A `:cmd` with arguments runs
12 // as written, since JavaScriptCore can't take node's options.
12 switch job.runner { 13 switch job.runner {
13 case .process(let executable, _), .session(_, let executable, _): 14 case .process(let executable, _), .session(_, let executable, _):
14 if !BabelRunner.installed(executable), let output = try await JavaScriptBlocks.run(job, directory: fileDirectory) { return output } 15 if !executable.contains(where: \.isWhitespace), !BabelRunner.installed(executable), let output = try await JavaScriptBlocks.run(job, directory: fileDirectory) { return output }
15 case .emacs: 16 case .emacs:
16 break 17 break
17 } 18 }
Tests/OrgAppTests/JavaScriptBlocksTests.swift +42 −5
@@ -66,6 +66,12 @@ struct JavaScriptBlocksTests {
66 "setTimeout(() => { throw new TypeError('in timer'); }, 1); setTimeout(() => console.log('not reached'), 5)", 66 "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)", 67 "var x = 5; console.log(globalThis.x, this === globalThis, typeof module, __filename, global === globalThis)",
68 "console.log(JSON.stringify({a: 1, b: [1, 2]}, null, 2), [3, 1, 2].sort(), 0.1 + 0.2)", 68 "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(' '))",
71 "console.log(Object.prototype.toString.call(process), Object.prototype.toString.call(console), typeof require, require.name, require.length)",
72 "module.exports = 5; console.log(module.exports, exports, typeof module)",
73 "const e = new TypeError('x'); e.stack = 's'; console.log(e.stack, 'stack' in e, Object.keys(e), JSON.stringify(e), String(e))",
74 "class Stack { constructor() { this.stack = []; } }; const s = new Stack(); s.stack.push(1); console.log(s.stack, s)",
69 ] 75 ]
70 76
71 /// The values a block returns, printed by `util.inspect`, and what `console` and timers 77 /// The values a block returns, printed by `util.inspect`, and what `console` and timers
@@ -137,13 +143,33 @@ struct JavaScriptBlocksTests {
137 143
138 @Test func whatNodeAloneHasIsRefused() async throws { 144 @Test func whatNodeAloneHasIsRefused() async throws {
139 let folder = FileManager.default.temporaryDirectory 145 let folder = FileManager.default.temporaryDirectory
140 for (body, what) in [("return new Error('x')", "util.inspect of an Error"), ("return Promise.resolve(1)", "util.inspect of a Promise"), 146 let module = "top-level await, import or export", stack = "an error's own properties"
141 ("return Buffer.from('a')", "Buffer"), ("return process.env.HOME", "process.env"), 147 for (header, body, what) in [
142 ("console.table([1])", "console.table")] { 148 ("", "return new Error('x')", "util.inspect of an Error"), ("", "return Promise.resolve(1)", "util.inspect of a Promise"),
143 await #expect(throws: Babel.Failure.message("This block uses \(what), which runs only in node.")) { 149 ("", "return Buffer.from('a')", "Buffer"), ("", "return process.env.HOME", "process.env"), ("", "console.table([1])", "console.table"),
144 try await JavaScriptBlocks.run(Self.plan("#+begin_src js\n\(body)\n#+end_src\n"), directory: folder) 150 (" :results output", "console.log(await Promise.resolve(5))", module), (" :results output", "for await (const x of [1]) console.log(x)", module),
151 (" :results output", "import util from 'util'; console.log(util.format('%d', 3))", module),
152 (" :results output", "console.log(import.meta.url)", module), (" :results output", "export const x = 1", module),
153 ("", "return new Error('x').stack", "Error.stack"), (" :results output", "try { null.x } catch (e) { console.log(e.stack) }", "Error.stack"),
154 ("", "return Error.stackTraceLimit", "Error.stackTraceLimit"), ("", "const o = {}; Error.captureStackTrace(o); return o", "Error.captureStackTrace"),
155 ("", "return Object.getOwnPropertyNames(new Error('x'))", stack), ("", "return Reflect.ownKeys(new RangeError('x'))", stack),
156 ("", "return new Error('x').hasOwnProperty('stack')", stack), ("", "return Object.hasOwn(new Error('x'), 'stack')", stack),
157 ("", "return require('util').inspect(Error.prototype, {showHidden: true})", stack),
158 ("", "return typeof Temporal", "Temporal"), ("", "return new SharedArrayBuffer(2)", "SharedArrayBuffer"),
159 ("", "return typeof DOMException", "DOMException"), ("", "return typeof ReadableStream", "ReadableStream"),
160 ("", "return 'env' in process", "process.env"), ("", "return Object.keys(console).length", "the members of console"),
161 ("", "return Object.getPrototypeOf(process)", "the prototype of process"), ("", "process.exitCode = 1", "process.exitCode"),
162 ("", "return process.toString()", "process.toString"), ("", "return typeof require.resolve", "require.resolve"),
163 ("", "return require.cache", "require.cache"), ("", "return module.id", "module.id"), ("", "return typeof module.paths", "module.paths"),
164 (" :results output", "console.log(globalThis)", "util.inspect of the global object"), ("", "return this", "util.inspect of the global object"),
165 ("", "return require", "util.inspect of require"), ("", "return module", "util.inspect of module"),
166 ] {
167 await #expect(throws: Babel.Failure.message("This block uses \(what), which runs only in node."), "\(body)") {
168 try await JavaScriptBlocks.run(Self.plan("#+begin_src js\(header)\n\(body)\n#+end_src\n"), directory: folder)
145 } 169 }
146 } 170 }
171 // 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)
147 #expect(try await JavaScriptBlocks.run(Self.plan("#+begin_src python\n1\n#+end_src\n"), directory: folder) == nil) 173 #expect(try await JavaScriptBlocks.run(Self.plan("#+begin_src python\n1\n#+end_src\n"), directory: folder) == nil)
148 await #expect(throws: Babel.Failure.message("No folder \(folder.appendingPathComponent("nowhere").path) for :dir.")) { 174 await #expect(throws: Babel.Failure.message("No folder \(folder.appendingPathComponent("nowhere").path) for :dir.")) {
149 try await JavaScriptBlocks.run(Self.plan("#+begin_src js :dir nowhere\nreturn 1\n#+end_src\n"), directory: folder) 175 try await JavaScriptBlocks.run(Self.plan("#+begin_src js :dir nowhere\nreturn 1\n#+end_src\n"), directory: folder)
@@ -160,6 +186,17 @@ struct JavaScriptBlocksTests {
160 #expect(try await run("", "throw new Error('boom')") == BabelOutput(stdout: "", stderr: "Error: boom\n", status: 1)) 186 #expect(try await run("", "throw new Error('boom')") == BabelOutput(stdout: "", stderr: "Error: boom\n", status: 1))
161 #expect(try await run("", "[x, {y}]")?.resultFile == "[ 41, { y: 2 } ]") 187 #expect(try await run("", "[x, {y}]")?.resultFile == "[ 41, { y: 2 } ]")
162 #expect(try await run(" :results output", "console.log(x); x") == BabelOutput(stdout: "41\n")) 188 #expect(try await run(" :results output", "console.log(x); x") == BabelOutput(stdout: "41\n"))
189 // node's session returns before a timer runs, and it prints later; a block that leaves one is refused.
190 await #expect(throws: Babel.Failure.message("This block uses a timer in a session, which runs only in node.")) {
191 try await run(" :results output", "var z = 1; setInterval(() => console.log('tick'), 10)")
192 }
193 await #expect(throws: Babel.Failure.message("This block uses a timer in a session, which runs only in node.")) {
194 try await run("", "setTimeout(() => {}, 1).unref(); 2")
195 }
196 #expect(try await run("", "const t = setTimeout(() => {}, 1); clearTimeout(t); z")?.resultFile == "1")
197 // An error while printing the value is reported, and there is no result.
198 let thrown = try await run("", "({[Symbol.for('nodejs.util.inspect.custom')]() { throw new TypeError('boom') }})")
199 #expect(thrown == BabelOutput(stdout: "", stderr: "TypeError: boom\n", status: 1))
163 let other = try Folder() 200 let other = try Folder()
164 #expect(try await JavaScriptBlocks.run(Self.plan("#+begin_src js :session work\ntypeof x\n#+end_src\n"), directory: other.url)?.resultFile == "'undefined'") 201 #expect(try await JavaScriptBlocks.run(Self.plan("#+begin_src js :session work\ntypeof x\n#+end_src\n"), directory: other.url)?.resultFile == "'undefined'")
165 } 202 }
Tests/OrgProgramsTests/ProgramsTests.swift +8
@@ -187,6 +187,14 @@ struct JavaScriptFallbackTests {
187 #expect(try await run("#+begin_src js :cmd no-such-node :session s\n6 * 7\n#+end_src\n").resultFile == "42") 187 #expect(try await run("#+begin_src js :cmd no-such-node :session s\n6 * 7\n#+end_src\n").resultFile == "42")
188 } 188 }
189 189
190 /// A `:cmd` with arguments isn't run in JavaScriptCore, which can't take node's options.
191 @Test func leavesACommandWithArgumentsToTheRunner() async throws {
192 let error = await #expect(throws: BabelRunner.Failure.self) {
193 try await run("#+begin_src js :cmd \"no-such-node --no-warnings\" :results output\nconsole.log(1)\n#+end_src\n")
194 }
195 #expect(error?.description == "no-such-node --no-warnings isn't installed.")
196 }
197
190 @Test(.enabled(if: BabelRunner.installed("node"))) 198 @Test(.enabled(if: BabelRunner.installed("node")))
191 func usesNodeWhenInstalled() async throws { 199 func usesNodeWhenInstalled() async throws {
192 #expect(try await run("#+begin_src js :results output\nconsole.log(typeof require('fs').readFileSync)\n#+end_src\n").stdout == "function\n") 200 #expect(try await run("#+begin_src js :results output\nconsole.log(typeof require('fs').readFileSync)\n#+end_src\n").stdout == "function\n")
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
107 107
108** JavaScript in JavaScriptCore 108** JavaScript in JavaScriptCore
109 109
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 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 =node= runs a program on standard input, and its output and result are what node gives:
111 111
112- =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. 112- =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.
113- =require('util')= has =inspect=, =format= and =formatWithOptions=, which print values as Node 26 prints them. =require('process')= has =stdout= and =stderr=. 113- =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. 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.
115- 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". 115- 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".
116- =require= of any other module fails as it does for a module node can't find: "Error: Cannot find module 'fs'". 116- =require= of any other module fails as it does for a module node can't find: "Error: Cannot find module 'fs'".
117 117
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= and =console= (=process.env=, =console.table=), Node's other globals (=Buffer=, =fetch=, =URL=, =TextEncoder=, =setImmediate=, =structuredClone=), and printing an =Error=, a =Promise= or an iterator 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= 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.
119 119
120Some things still differ from node: 120Some things still differ from node:
121 121