Commit ea71ae826c

ea71ae826c3d74a17b301811f18cc4fe05aa0bd3

parent: 537216e8fd

Verified · cmc

cmc <hello@cleberg.net> · 2026-11-21 18:52 UTC

Run js blocks as node FILE, as ob-js does

Layout: unified · split

Sources/OrgApp/JavaScriptBlocks.swift +6 −5
@@ -19,7 +19,7 @@ public enum JavaScriptBlocks {
1919 switch job.runner {
2020 case .process:
2121 guard FileManager.default.fileExists(atPath: folder.path) else { throw Babel.Failure.message("No folder \(folder.path) for :dir.") }
22 return try await evaluate(timeout: timeout) { run in try Engine().main(job.input, run: run) }
22 return try await evaluate(timeout: timeout) { run in try Engine().main(job.script ?? job.input, run: run) }
2323 case .session(let name, _, .node):
2424 guard FileManager.default.fileExists(atPath: folder.path) else { throw Babel.Failure.message("No folder \(folder.path) for :dir.") }
2525 // One context per file folder and session name; a stopped run's context is dropped.
@@ -41,19 +41,20 @@ public enum JavaScriptBlocks {
4141 /// and is still running is refused without starting another.
4242 public static func runHere(_ job: BabelJob, timeout: Duration = .seconds(5)) throws -> BabelOutput? {
4343 guard job.language == "js" || job.language == "javascript", case .process = job.runner else { return nil }
44 if abandoned.contains(job.input) { throw Stopped(description: "The block took too long before and is still running.") }
44 let source = job.script ?? job.input
45 if abandoned.contains(source) { throw Stopped(description: "The block took too long before and is still running.") }
4546 let run = Run()
4647 let flag = Abandoned.Flag()
4748 let thread = Thread {
48 run.end(Result { try Engine().main(job.input, run: run) })
49 abandoned.ended(job.input, flag)
49 run.end(Result { try Engine().main(source, run: run) })
50 abandoned.ended(source, flag)
5051 }
5152 thread.stackSize = 8 << 20
5253 thread.start()
5354 do {
5455 return try run.result(within: timeout)
5556 } catch let error as Stopped {
56 abandoned.add(job.input, flag)
57 abandoned.add(source, flag)
5758 throw error
5859 }
5960 }
Sources/OrgCore/Compute/Babel.swift +8 −5
@@ -585,11 +585,14 @@ public enum Babel {
585585 input: full, directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.script(js: true, session: true))
586586 ))
587587 }
588 return .success(BabelJob(
589 language: language, runner: .process(executable: params.single[":cmd"] ?? executable, arguments: arguments),
590 input: output ? full : jsWrapper(full), directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk,
591 finish: finishBase(.script(js: true))
592 ))
588 // `org-babel-execute:js`: the program in a file, run as `:cmd FILE`, with the
589 // newline `org-babel-eval` sends as its input.
590 var job = BabelJob(
591 language: language, runner: .process(executable: params.single[":cmd"] ?? executable, arguments: [scriptFileToken]),
592 input: "\n", directory: dir, block: location, blockText: blockText, alwaysAsk: alwaysAsk, finish: finishBase(.script(js: true))
593 )
594 job.script = output ? full : jsWrapper(full)
595 return .success(job)
593596 case "awk":
594597 // `org-babel-expand-body:awk`; the variables go on the command line.
595598 let full = (params.single[":prologue"].map { $0 + "\n" } ?? "") + body + (params.single[":epilogue"].map { "\n" + $0 + "\n" } ?? "")
Sources/OrgPrograms/BabelRunner.swift +6 −3
@@ -2,8 +2,8 @@
22import Foundation
33import OrgCore
44
5/// Runs Babel jobs as processes: the interpreter reads the program on standard input, in the
6/// file's folder or `:dir`.
5/// Runs Babel jobs as processes, in the file's folder or `:dir`: the interpreter reads the
6/// program on standard input, or from the file `job.script` is written to.
77public enum BabelRunner {
88 public struct Failure: Error, CustomStringConvertible {
99 public let description: String
@@ -51,7 +51,10 @@ public enum BabelRunner {
5151 try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: file.path)
5252 arguments = arguments.map { $0.replacingOccurrences(of: Babel.scriptFileToken, with: file.path) }
5353 }
54 process.arguments = [executable] + arguments
54 // A command with arguments, such as `:cmd "node --no-warnings"`, runs in the shell as
55 // Org runs it.
56 process.arguments = executable.contains(where: \.isWhitespace)
57 ? ["/bin/sh", "-c", executable + " \"$@\"", "sh"] + arguments : [executable] + arguments
5558 case .emacs:
5659 guard let emacs = EmacsRunner.executable() else { throw Failure(description: "Emacs isn't installed, so Emacs Lisp blocks can't run.") }
5760 let script = folder.appendingPathComponent("babel.el")
Tests/OrgAppTests/JavaScriptBlocksTests.swift +1 −1
@@ -88,7 +88,7 @@ struct JavaScriptBlocksTests {
8888 + Self.programs.map { "#+begin_src js :results output\n\($0)\n#+end_src\n" }
8989 for block in blocks {
9090 let job = try Self.plan(block)
91 let theirs = try Self.node(job.input, in: folder)
91 let theirs = try Self.node(try #require(job.script), in: folder)
9292 let ours = try await JavaScriptBlocks.run(job, directory: folder)
9393 #expect(ours?.stdout == theirs.stdout && ours?.status == theirs.status, "\(block)\nours: \(ours?.stdout ?? "nil") \(ours?.stderr ?? "")\nnode: \(theirs.stdout)")
9494 }
Tests/OrgProgramsTests/ProgramsTests.swift +70
@@ -256,6 +256,76 @@ struct JavaScriptFallbackTests {
256256 }
257257}
258258
259/// js blocks without a session run as `node FILE`, as `org-babel-execute:js` runs them.
260@MainActor
261@Suite(.programs)
262struct NodeFileTests {
263 static let cases = [
264 "#+begin_src js :results output\nconsole.log(typeof require, typeof module, typeof exports, process.argv.length, require.main === module)\n#+end_src\n",
265 "#+begin_src js :results output\nconst path = require('path'), fs = require('fs')\nconsole.log(path.dirname(__filename) === __dirname, __dirname === process.cwd(), "
266 + "path.dirname(__dirname) === fs.realpathSync(require('os').tmpdir()), path.basename(process.argv[1]) === path.basename(__filename))\n#+end_src\n",
267 "#+begin_src js\nreturn [typeof require, typeof module, process.argv.length, this === module.exports]\n#+end_src\n",
268 "#+begin_src js :results output\ntry { require('./helper'); console.log('found') } catch (e) { console.log(e.code) }\nconsole.log(require(process.cwd() + '/helper'))\n#+end_src\n",
269 "#+begin_src js :results output\nimport os from 'os'\nconsole.log(typeof require, typeof os.tmpdir)\n#+end_src\n",
270 "#+begin_src js :cmd \"node --no-warnings\" :results output\nconsole.log(process.argv.length, process.execArgv.join(' '))\n#+end_src\n",
271 "#+begin_src js :results output\nconsole.log(JSON.stringify(require('fs').readFileSync(0, 'utf8')))\n#+end_src\n",
272 "#+begin_src js :results output\nconsole.log('top'); return; console.log('not reached')\n#+end_src\n",
273 ]
274
275 /// The results Emacs inserts. `org-babel-temporary-directory` is set as interactive Emacs
276 /// sets it; `--batch` leaves it nil and writes the file straight into the temporary folder.
277 @Test(.enabled(if: EmacsRunner.executable() != nil && BabelRunner.installed("node") && ProcessInfo.processInfo.environment["ORGSTAR_SKIP_ORACLE"] == nil))
278 func resultsMatchEmacs() async throws {
279 let folder = try Folder()
280 try folder.write("helper.js", "module.exports = 1\n")
281 var forms: [String] = []
282 var ours: [String] = []
283 for text in Self.cases {
284 let file = try folder.write("b.org", text)
285 let session = DocumentSession(recovery: FileRecoveryStore(directory: folder.url.appendingPathComponent(".r")))
286 session.open(file.path)
287 guard case .external(.babel(let job)) = session.perform(ExecuteSrcBlock(), path: file.path, at: 2, expect: nil) else {
288 Issue.record("not planned: \(text)")
289 return
290 }
291 _ = await session.runBabel(job)
292 ours.append(session.document?.text ?? "")
293 let quoted = "\"" + text.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\""
294 forms.append("(with-temp-buffer (insert \(quoted)) (org-mode) (goto-char 3) (org-babel-execute-src-block) (princ (concat (buffer-string) \"\\f\")))")
295 }
296 let process = Process()
297 process.executableURL = EmacsRunner.executable()
298 process.currentDirectoryURL = folder.url
299 process.arguments = ["-Q", "--batch", "--eval", """
300 (progn (require 'org) (require 'ob-js)
301 (setq org-confirm-babel-evaluate nil org-babel-js-cmd "node" org-babel-temporary-directory (make-temp-file "babel-" t))
302 \(forms.joined(separator: "\n"))
303 (delete-directory org-babel-temporary-directory t))
304 """]
305 let out = Pipe()
306 process.standardOutput = out
307 process.standardError = FileHandle.nullDevice
308 try process.run()
309 let emacs = String(decoding: out.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
310 .split(separator: "\u{0C}", omittingEmptySubsequences: false).map(String.init)
311 process.waitUntilExit()
312 for (i, text) in Self.cases.enumerated() {
313 #expect(ours[i] == emacs[i], "\(text)\nours:\n\(ours[i])\nemacs:\n\(emacs[i])")
314 }
315 }
316
317 /// The file is gone once the block has run.
318 @Test(.enabled(if: BabelRunner.installed("node")))
319 func removesTheFile() async throws {
320 let text = "#+begin_src js :results output\nconsole.log(__filename)\n#+end_src\n"
321 let context = EditContext(revision: 0, text: text, tree: OrgParser.parse(text), selection: [2..<2])
322 guard case .success(let job) = Babel.plan(context) else { throw Babel.Failure.message("not planned") }
323 let output = try await BabelRunner.run(job, fileDirectory: FileManager.default.temporaryDirectory)
324 let file = output.stdout.trimmingCharacters(in: .newlines)
325 #expect(file.hasPrefix("/") && !FileManager.default.fileExists(atPath: file))
326 }
327}
328
259329/// Emacs Lisp runs in `Elisp` when Emacs isn't installed.
260330struct EmacsLispFallbackTests {
261331 func run(_ text: String) async throws -> BabelOutput {
docs/manual/guide/11-code-blocks.org +2 −2
@@ -91,13 +91,13 @@ On the Mac, orgstar starts each interpreter through =/usr/bin/env=. Because an a
9191| =python= | =python3=, or the program in =:python= |
9292| =emacs-lisp=, =elisp= | =emacs -Q --batch=, or the interpreter; see below |
9393| =ruby= | =ruby=, or the program in =:ruby= |
94| =js=, =javascript= | =node=, or JavaScriptCore without it; see below |
94| =js=, =javascript= | =node FILE=, the program written to a file, or JavaScriptCore without node; see below |
9595| =R= | =Rscript -= |
9696| =awk= | =awk -f=, the program written to a file |
9797| =dot=, =plantuml=, =mermaid= | =dot=, =plantuml=, =mmdc=; see Graphics below |
9898| =C=, =C++=, =cpp=, =D=, =java=, =fortran=, =clojure= | A compiler, or =bb= or =clojure=; see Compiled languages below |
9999
100For =js=, =javascript= and =R=, =:cmd= names a different program. =awk= takes =:cmd-line= arguments after its program, and =:in-file= as the file it reads.
100For =js=, =javascript= and =R=, =:cmd= names a different program. A program given with options, such as =:cmd "node --no-warnings"=, runs through =/bin/sh=, as Org runs it. =awk= takes =:cmd-line= arguments after its program, and =:in-file= as the file it reads.
101101
102102Any other language is refused with "No way to run /language/ blocks yet."
103103