Commit f5aa93a763
Verified · cmc
Layout: unified · split
Sources/OrgApp/JavaScriptBlocks.swift +144 −49
| @@ -102,7 +102,7 @@ public enum JavaScriptBlocks { | |||
| 102 | func engine(_ key: String) -> Engine { | 102 | func engine(_ key: String) -> Engine { |
| 103 | lock.withLock { | 103 | lock.withLock { |
| 104 | if let engine = engines[key] { return engine } | 104 | if let engine = engines[key] { return engine } |
| 105 | let engine = Engine() | 105 | let engine = Engine(session: true) |
| 106 | engines[key] = engine | 106 | engines[key] = engine |
| 107 | return engine | 107 | return engine |
| 108 | } | 108 | } |
| @@ -126,18 +126,32 @@ public enum JavaScriptBlocks { | |||
| 126 | private let output: Output | 126 | private let output: Output |
| 127 | private let lock = NSLock() | 127 | private let lock = NSLock() |
| 128 | 128 | ||
| 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) { | ||
| 130 | let output = Output() | 132 | let output = Output() |
| 131 | self.output = output | 133 | self.output = output |
| 132 | context = JSContext() | 134 | context = JSContext() |
| 133 | let write: @convention(block) (Int32, String) -> Void = { fd, text in | 135 | let write: @convention(block) (Int32, String) -> Void = { fd, text in |
| 134 | if fd == 1 { output.stdout += text } else { output.stderr += text } | 136 | if fd == 1 { output.stdout += text } else { output.stderr += text } |
| 135 | } | 137 | } |
| 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 | } | ||
| 136 | context.exceptionHandler = { _, exception in output.exception = exception } | 150 | 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]) |
| 138 | } | 152 | } |
| 139 | 153 | ||
| 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. |
| 141 | func main(_ source: String, run: Run) throws -> BabelOutput { | 155 | func main(_ source: String, run: Run) throws -> BabelOutput { |
| 142 | node.invokeMethod("main", withArguments: [source]) | 156 | node.invokeMethod("main", withArguments: [source]) |
| 143 | runTimers(run) | 157 | runTimers(run) |
| @@ -146,28 +160,17 @@ public enum JavaScriptBlocks { | |||
| 146 | 160 | ||
| 147 | /// Runs `source` where the session's earlier scripts ran, as `vm.runInThisContext` does; | 161 | /// 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. A block | 162 | /// 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. |
| 150 | func session(_ source: String, value: Bool, run: Run) throws -> BabelOutput { | 164 | func session(_ source: String, value: Bool, run: Run) throws -> BabelOutput { |
| 151 | try lock.withLock { | 165 | try lock.withLock { |
| 152 | output.stdout = "" | 166 | output.stdout = "" |
| 153 | output.stderr = "" | 167 | output.stderr = "" |
| 154 | output.exception = nil | 168 | output.exception = nil |
| 155 | node.invokeMethod("begin", withArguments: []) | 169 | node.invokeMethod("session", withArguments: [source, value]) |
| 156 | let completion = context.evaluateScript(source) | 170 | // node's session returns before its timers and promise callbacks run, and they print later. |
| 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("settle", withArguments: []) | 171 | 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) | ||
| 171 | } | 174 | } |
| 172 | } | 175 | } |
| 173 | 176 | ||
| @@ -191,16 +194,22 @@ public enum JavaScriptBlocks { | |||
| 191 | /// lib/internal/util/inspect.js (MIT License, Node.js contributors). It returns the | 194 | /// lib/internal/util/inspect.js (MIT License, Node.js contributors). It returns the |
| 192 | /// runner's controls. | 195 | /// runner's controls. |
| 193 | static let shim = #""" | 196 | static let shim = #""" |
| 194 | (function (write) { | 197 | (function shim(write, script, session) { |
| 195 | 'use strict'; | 198 | 'use strict'; |
| 196 | const evaluate = eval; | 199 | const functionToString = Function.prototype.toString; |
| 197 | const state = { dead: false, error: undefined, refused: '', timers: [], seq: 0, now: Date.now() }; | 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'; | ||
| 198 | 202 | ||
| 199 | function refuse(what) { | 203 | function refuse(what) { |
| 200 | if (!state.refused) state.refused = what; | 204 | if (!state.refused) state.refused = what; |
| 201 | throw new Error(`${what} isn't available`); | 205 | throw new Error(`${what} isn't available`); |
| 202 | } | 206 | } |
| 203 | function out(fd, text) { | 207 | 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 | } | ||
| 204 | if (!state.dead) write(fd, text.toWellFormed()); | 213 | if (!state.dead) write(fd, text.toWellFormed()); |
| 205 | } | 214 | } |
| 206 | // Members a script may use, its own and those in `extra`; any other, and listing them, is | 215 | // Members a script may use, its own and those in `extra`; any other, and listing them, is |
| @@ -695,7 +704,7 @@ public enum JavaScriptBlocks { | |||
| 695 | } | 704 | } |
| 696 | 705 | ||
| 697 | function getFunctionBase(ctx, value, constructor, tag) { | 706 | function getFunctionBase(ctx, value, constructor, tag) { |
| 698 | const stringified = Function.prototype.toString.call(value); | 707 | const stringified = functionToString.call(value); |
| 699 | if (stringified.startsWith('class') && stringified[stringified.length - 1] === '}') { | 708 | if (stringified.startsWith('class') && stringified[stringified.length - 1] === '}') { |
| 700 | const slice = stringified.slice(5, -1); | 709 | const slice = stringified.slice(5, -1); |
| 701 | const bracketIndex = slice.indexOf('{'); | 710 | const bracketIndex = slice.indexOf('{'); |
| @@ -1274,6 +1283,10 @@ public enum JavaScriptBlocks { | |||
| 1274 | state.timers = state.timers.filter((t) => t !== timer); | 1283 | state.timers = state.timers.filter((t) => t !== timer); |
| 1275 | } | 1284 | } |
| 1276 | function uncaught(error) { | 1285 | function uncaught(error) { |
| 1286 | if (state.draining) { | ||
| 1287 | if (!state.refused) state.refused = lateInSession; | ||
| 1288 | return; | ||
| 1289 | } | ||
| 1277 | if (state.error === undefined) state.error = describe(error); | 1290 | if (state.error === undefined) state.error = describe(error); |
| 1278 | state.dead = true; | 1291 | state.dead = true; |
| 1279 | } | 1292 | } |
| @@ -1288,14 +1301,19 @@ public enum JavaScriptBlocks { | |||
| 1288 | } | 1301 | } |
| 1289 | 1302 | ||
| 1290 | const AsyncFunction = (async function () {}).constructor; | 1303 | 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. | ||
| 1291 | function moduleOnly(source) { | 1306 | 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; |
| 1293 | try { new AsyncFunction(source); } catch { return false; } | 1308 | try { new AsyncFunction(source); } catch { return false; } |
| 1294 | try { new Function(source); return false; } catch { return true; } | 1309 | try { new Function(source); return false; } catch { return true; } |
| 1295 | } | 1310 | } |
| 1311 | // `import()`, which parses in a script and never settles here. | ||
| 1312 | const dynamicImport = /(?<![\w$.])import\s*(\(|\/[*\/])/; | ||
| 1296 | 1313 | ||
| 1314 | const module = guard({ exports: {} }, 'module'); | ||
| 1297 | const globals = { | 1315 | const globals = { |
| 1298 | require, console, process, global: globalThis, Proxy: ProxyConstructor, module: guard({ exports: {} }, 'module'), __filename: '[stdin]', __dirname: '.', | 1316 | console, process, global: globalThis, Proxy: ProxyConstructor, |
| 1299 | setTimeout: (callback, delay, ...args) => schedule(callback, delay, args, false), | 1317 | setTimeout: (callback, delay, ...args) => schedule(callback, delay, args, false), |
| 1300 | setInterval: (callback, delay, ...args) => schedule(callback, delay, args, true), | 1318 | setInterval: (callback, delay, ...args) => schedule(callback, delay, args, true), |
| 1301 | clearTimeout: clear, clearInterval: clear, | 1319 | clearTimeout: clear, clearInterval: clear, |
| @@ -1304,11 +1322,40 @@ public enum JavaScriptBlocks { | |||
| 1304 | Promise.resolve().then(() => { try { callback(); } catch (error) { uncaught(error); } }); | 1322 | Promise.resolve().then(() => { try { callback(); } catch (error) { uncaught(error); } }); |
| 1305 | }, | 1323 | }, |
| 1306 | }; | 1324 | }; |
| 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 | } | ||
| 1308 | for (const [name, value] of Object.entries(globals)) { | 1355 | 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 }); |
| 1310 | } | 1357 | } |
| 1311 | // Node 26's globals that JavaScriptCore lacks. | 1358 | // Node 26's other globals that JavaScriptCore lacks. |
| 1312 | for (const name of [ | 1359 | for (const name of [ |
| 1313 | 'AbortController', 'AbortSignal', 'AsyncDisposableStack', 'atob', 'Blob', 'BroadcastChannel', 'btoa', 'Buffer', | 1360 | 'AbortController', 'AbortSignal', 'AsyncDisposableStack', 'atob', 'Blob', 'BroadcastChannel', 'btoa', 'Buffer', |
| 1314 | 'ByteLengthQueuingStrategy', 'clearImmediate', 'CloseEvent', 'CompressionStream', 'CountQueuingStrategy', 'Crypto', | 1361 | 'ByteLengthQueuingStrategy', 'clearImmediate', 'CloseEvent', 'CompressionStream', 'CountQueuingStrategy', 'Crypto', |
| @@ -1340,53 +1387,101 @@ public enum JavaScriptBlocks { | |||
| 1340 | configurable: true, | 1387 | configurable: true, |
| 1341 | }); | 1388 | }); |
| 1342 | const errorLike = (v) => v === Error.prototype || isError(v); | 1389 | 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) { | ||
| 1344 | object[name] = new RealProxy(object[name], { | 1392 | object[name] = new RealProxy(object[name], { |
| 1345 | apply(target, self, args) { | 1393 | 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); | ||
| 1347 | return Reflect.apply(target, self, args); | 1396 | return Reflect.apply(target, self, args); |
| 1348 | }, | 1397 | }, |
| 1349 | }); | 1398 | }); |
| 1350 | } | 1399 | } |
| 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" : ''; | ||
| 1351 | for (const [object, name] of [[Object, 'getOwnPropertyNames'], [Object, 'getOwnPropertyDescriptors'], [Reflect, 'ownKeys']]) { | 1408 | 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 : '')); |
| 1353 | } | 1410 | } |
| 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*\)/; | ||
| 1354 | for (const [object, name] of [[Object, 'getOwnPropertyDescriptor'], [Object, 'hasOwn'], [Reflect, 'getOwnPropertyDescriptor']]) { | 1415 | 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 : ''); |
| 1356 | } | 1417 | } |
| 1357 | for (const name of ['hasOwnProperty', 'propertyIsEnumerable']) { | 1418 | 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 : ''); |
| 1359 | } | 1420 | } |
| 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 | }); | ||
| 1360 | 1429 | ||
| 1361 | return { | 1430 | 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. | ||
| 1363 | main(source) { | 1433 | 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; | ||
| 1364 | try { | 1443 | try { |
| 1365 | evaluate(source); | 1444 | body = new Function('exports', 'require', 'module', '__filename', '__dirname', source); |
| 1366 | } catch (error) { | 1445 | } catch (error) { |
| 1367 | // node runs a script that doesn't parse as one as an ES module, when that parses. | 1446 | // node runs a script that doesn't parse as one as an ES module, when that parses. |
| 1368 | if (error instanceof SyntaxError && moduleOnly(source)) { | 1447 | if (error instanceof SyntaxError && moduleOnly(source)) state.refused = 'top-level await, import or export'; |
| 1369 | if (!state.refused) state.refused = 'top-level await, import or export'; | 1448 | else uncaught(error); |
| 1370 | } else { | 1449 | return; |
| 1371 | uncaught(error); | 1450 | } |
| 1372 | } | 1451 | try { |
| 1452 | body.call(module.exports, module.exports, require, module, undefined, undefined); | ||
| 1453 | } catch (error) { | ||
| 1454 | uncaught(error); | ||
| 1373 | } | 1455 | } |
| 1374 | }, | 1456 | }, |
| 1375 | begin() { | 1457 | // A session's script, and its value as the session writes it. Promise callbacks run |
| 1376 | state.dead = false; | 1458 | // after this returns. |
| 1377 | state.error = undefined; | 1459 | session(source, value) { |
| 1378 | state.refused = ''; | 1460 | Object.assign(state, { dead: false, error: undefined, refused: '', now: Date.now(), draining: false, result: undefined }); |
| 1379 | state.now = Date.now(); | 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 | } | ||
| 1380 | }, | 1476 | }, |
| 1381 | // After a session's script: its error, or its value as the session writes it. | ||
| 1382 | failed(error) { uncaught(error); }, | ||
| 1383 | // Drops a session's timers, which would print after the block in node, and refuses the block. | 1477 | // Drops a session's timers, which would print after the block in node, and refuses the block. |
| 1384 | settle() { | 1478 | settle() { |
| 1479 | state.draining = false; | ||
| 1385 | if (state.timers.length === 0) return; | 1480 | if (state.timers.length === 0) return; |
| 1386 | state.timers = []; | 1481 | state.timers = []; |
| 1387 | if (!state.refused) state.refused = 'a timer in a session'; | 1482 | if (!state.refused) state.refused = 'a timer in a session'; |
| 1388 | }, | 1483 | }, |
| 1389 | inspect(value) { return inspect(value); }, | 1484 | get result() { return state.result; }, |
| 1390 | // Runs the next timer that is due: the milliseconds until one is, 0 after running one, | 1485 | // Runs the next timer that is due: the milliseconds until one is, 0 after running one, |
| 1391 | // or -1 when none is left to wait for. | 1486 | // or -1 when none is left to wait for. |
| 1392 | tick() { | 1487 | tick() { |
Tests/OrgAppTests/JavaScriptBlocksTests.swift +62 −11
| @@ -1,4 +1,5 @@ | |||
| 1 | import Foundation | 1 | import Foundation |
| 2 | import JavaScriptCore | ||
| 2 | import OrgCore | 3 | import OrgCore |
| 3 | import OrgDocument | 4 | import OrgDocument |
| 4 | import Testing | 5 | import Testing |
| @@ -16,19 +17,20 @@ struct JavaScriptBlocksTests { | |||
| 16 | return job | 17 | return job |
| 17 | } | 18 | } |
| 18 | 19 | ||
| 19 | /// `node` reading `input` on standard input, as BabelRunner starts it. | 20 | /// `node` running `input` from a file, as Emacs runs it. |
| 20 | static func node(_ input: String, in folder: URL) throws -> (stdout: String, status: Int32) { | 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) } | ||
| 21 | let process = Process() | 25 | let process = Process() |
| 22 | process.executableURL = URL(fileURLWithPath: "/usr/bin/env") | 26 | process.executableURL = URL(fileURLWithPath: "/usr/bin/env") |
| 23 | process.arguments = ["node"] | 27 | process.arguments = ["node"] + arguments + [file.path] |
| 24 | process.currentDirectoryURL = folder | 28 | process.currentDirectoryURL = folder |
| 25 | let stdin = Pipe(), stdout = Pipe() | 29 | let stdout = Pipe() |
| 26 | process.standardInput = stdin | 30 | process.standardInput = FileHandle.nullDevice |
| 27 | process.standardOutput = stdout | 31 | process.standardOutput = stdout |
| 28 | process.standardError = FileHandle.nullDevice | 32 | process.standardError = FileHandle.nullDevice |
| 29 | try process.run() | 33 | try process.run() |
| 30 | stdin.fileHandleForWriting.write(Data(input.utf8)) | ||
| 31 | try stdin.fileHandleForWriting.close() | ||
| 32 | let data = stdout.fileHandleForReading.readDataToEndOfFile() | 34 | let data = stdout.fileHandleForReading.readDataToEndOfFile() |
| 33 | process.waitUntilExit() | 35 | process.waitUntilExit() |
| 34 | return (String(decoding: data, as: UTF8.self), process.terminationStatus) | 36 | return (String(decoding: data, as: UTF8.self), process.terminationStatus) |
| @@ -64,10 +66,13 @@ struct JavaScriptBlocksTests { | |||
| 64 | "console.log('before'); undefinedThing.x; console.log('after')", | 66 | "console.log('before'); undefinedThing.x; console.log('after')", |
| 65 | "Promise.resolve().then(() => console.log('not printed')); throw new Error('sync')", | 67 | "Promise.resolve().then(() => console.log('not printed')); throw new Error('sync')", |
| 66 | "setTimeout(() => { throw new TypeError('in timer'); }, 1); setTimeout(() => console.log('not reached'), 5)", | 68 | "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')", | ||
| 68 | "console.log(JSON.stringify({a: 1, b: [1, 2]}, null, 2), [3, 1, 2].sort(), 0.1 + 0.2)", | 72 | "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. | 73 | "globalThis.y = 1; z = 2; console.log(Object.keys(globalThis).join(' ')); for (const k in global) console.log(k)", |
| 70 | "console.log(Object.getOwnPropertyNames(globalThis).sort().join(' '))", | 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 {}}`)", | ||
| 71 | "console.log(Object.prototype.toString.call(process), Object.prototype.toString.call(console), typeof require, require.name, require.length)", | 76 | "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)", | 77 | "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))", | 78 | "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 { | |||
| 100 | "#+begin_src js :results output :epilogue console.log('end')\nconsole.log('body')\n#+end_src\n", | 105 | "#+begin_src js :results output :epilogue console.log('end')\nconsole.log('body')\n#+end_src\n", |
| 101 | "#+begin_src js\nreturn {a: 1, b: [1, 2]}\n#+end_src\n", | 106 | "#+begin_src js\nreturn {a: 1, b: [1, 2]}\n#+end_src\n", |
| 102 | "#+begin_src js :results output\nsetTimeout(() => console.log('later'), 10); console.log('now')\n#+end_src\n", | 107 | "#+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", | ||
| 103 | ] | 109 | ] |
| 104 | 110 | ||
| 105 | /// The results the app inserts, as Emacs inserts them running the block with node. | 111 | /// The results the app inserts, as Emacs inserts them running the block with node. |
| @@ -144,6 +150,7 @@ struct JavaScriptBlocksTests { | |||
| 144 | @Test func whatNodeAloneHasIsRefused() async throws { | 150 | @Test func whatNodeAloneHasIsRefused() async throws { |
| 145 | let folder = FileManager.default.temporaryDirectory | 151 | let folder = FileManager.default.temporaryDirectory |
| 146 | let module = "top-level await, import or export", stack = "an error's own properties" | 152 | 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" | ||
| 147 | for (header, body, what) in [ | 154 | for (header, body, what) in [ |
| 148 | ("", "return new Error('x')", "util.inspect of an Error"), ("", "return Promise.resolve(1)", "util.inspect of a Promise"), | 155 | ("", "return new Error('x')", "util.inspect of an Error"), ("", "return Promise.resolve(1)", "util.inspect of a Promise"), |
| 149 | ("", "return Buffer.from('a')", "Buffer"), ("", "return process.env.HOME", "process.env"), ("", "console.table([1])", "console.table"), | 156 | ("", "return Buffer.from('a')", "Buffer"), ("", "return process.env.HOME", "process.env"), ("", "console.table([1])", "console.table"), |
| @@ -163,13 +170,22 @@ struct JavaScriptBlocksTests { | |||
| 163 | ("", "return require.cache", "require.cache"), ("", "return module.id", "module.id"), ("", "return typeof module.paths", "module.paths"), | 170 | ("", "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"), | 171 | (" :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"), | 172 | ("", "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), | ||
| 166 | ] { | 182 | ] { |
| 167 | await #expect(throws: Babel.Failure.message("This block uses \(what), which runs only in node."), "\(body)") { | 183 | 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) | 184 | try await JavaScriptBlocks.run(Self.plan("#+begin_src js\(header)\n\(body)\n#+end_src\n"), directory: folder) |
| 169 | } | 185 | } |
| 170 | } | 186 | } |
| 171 | // A syntax error that isn't a module's is reported, as node reports it. | 187 | // 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) |
| 173 | #expect(try await JavaScriptBlocks.run(Self.plan("#+begin_src python\n1\n#+end_src\n"), directory: folder) == nil) | 189 | #expect(try await JavaScriptBlocks.run(Self.plan("#+begin_src python\n1\n#+end_src\n"), directory: folder) == nil) |
| 174 | await #expect(throws: Babel.Failure.message("No folder \(folder.appendingPathComponent("nowhere").path) for :dir.")) { | 190 | await #expect(throws: Babel.Failure.message("No folder \(folder.appendingPathComponent("nowhere").path) for :dir.")) { |
| 175 | try await JavaScriptBlocks.run(Self.plan("#+begin_src js :dir nowhere\nreturn 1\n#+end_src\n"), directory: folder) | 191 | 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 { | |||
| 194 | try await run("", "setTimeout(() => {}, 1).unref(); 2") | 210 | try await run("", "setTimeout(() => {}, 1).unref(); 2") |
| 195 | } | 211 | } |
| 196 | #expect(try await run("", "const t = setTimeout(() => {}, 1); clearTimeout(t); z")?.resultFile == "1") | 212 | #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 | } | ||
| 197 | // An error while printing the value is reported, and there is no result. | 233 | // 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') }})") | 234 | 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)) | 235 | #expect(thrown == BabelOutput(stdout: "", stderr: "TypeError: boom\n", status: 1)) |
| @@ -201,6 +237,21 @@ struct JavaScriptBlocksTests { | |||
| 201 | #expect(try await JavaScriptBlocks.run(Self.plan("#+begin_src js :session work\ntypeof x\n#+end_src\n"), directory: other.url)?.resultFile == "'undefined'") | 237 | #expect(try await JavaScriptBlocks.run(Self.plan("#+begin_src js :session work\ntypeof x\n#+end_src\n"), directory: other.url)?.resultFile == "'undefined'") |
| 202 | } | 238 | } |
| 203 | 239 | ||
| 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 | |||
| 204 | @Test func cancelAndTimeoutEndTheRun() async throws { | 255 | @Test func cancelAndTimeoutEndTheRun() async throws { |
| 205 | let folder = FileManager.default.temporaryDirectory | 256 | let folder = FileManager.default.temporaryDirectory |
| 206 | // Spins for seconds, as an endless loop would, but ends so the test leaves no thread busy. | 257 | // 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 | |||
| 107 | 107 | ||
| 108 | ** JavaScript in JavaScriptCore | 108 | ** JavaScript in JavaScriptCore |
| 109 | 109 | ||
| 110 | In 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: | 110 | In 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: |
| 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. 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. |
| 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 | ||
| 118 | A 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. | 118 | A 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. |
| 119 | 119 | ||
| 120 | Some things still differ from node: | 120 | Some things still differ from node: |
| 121 | 121 | ||