JavaScriptWorker.swift 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. import Foundation
  2. import JavaScriptCore
  3. private let contextLock = NSRecursiveLock()
  4. extension String {
  5. var lowercasingFirst: String { prefix(1).lowercased() + dropFirst() }
  6. var uppercasingFirst: String { prefix(1).uppercased() + dropFirst() }
  7. var camelCased: String {
  8. guard !isEmpty else { return "" }
  9. let parts = components(separatedBy: .alphanumerics.inverted)
  10. let first = parts.first!.lowercasingFirst
  11. let rest = parts.dropFirst().map(\.uppercasingFirst)
  12. return ([first] + rest).joined()
  13. }
  14. var pascalCased: String {
  15. guard !isEmpty else { return "" }
  16. let parts = components(separatedBy: .alphanumerics.inverted)
  17. let first = parts.first!.uppercasingFirst
  18. let rest = parts.dropFirst().map(\.uppercasingFirst)
  19. return ([first] + rest).joined()
  20. }
  21. }
  22. final class JavaScriptWorker {
  23. private let processQueue = DispatchQueue(label: "DispatchQueue.JavaScriptWorker")
  24. private let virtualMachine: JSVirtualMachine
  25. @SyncAccess(lock: contextLock) private var commonContext: JSContext? = nil
  26. private var aggregatedLogs: [String] = []
  27. private var logFormatting: String = ""
  28. init() {
  29. virtualMachine = processQueue.sync { JSVirtualMachine()! }
  30. }
  31. private func createContext() -> JSContext {
  32. let context = JSContext(virtualMachine: virtualMachine)!
  33. context.exceptionHandler = { _, exception in
  34. if let error = exception?.toString() {
  35. warning(.openAPS, "JavaScript Error: \(error)")
  36. }
  37. }
  38. let consoleLog: @convention(block) (String) -> Void = { message in
  39. let trimmedMessage = message.trimmingCharacters(in: .whitespacesAndNewlines)
  40. if !trimmedMessage.isEmpty {
  41. // debug(.openAPS, "JavaScript log: \(trimmedMessage)")
  42. self.aggregatedLogs.append("\(trimmedMessage)")
  43. }
  44. }
  45. context.setObject(
  46. consoleLog,
  47. forKeyedSubscript: "_consoleLog" as NSString
  48. )
  49. return context
  50. }
  51. // New method to flush aggregated logs
  52. private func aggregateLogs() {
  53. let combinedLogs = aggregatedLogs.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines)
  54. aggregatedLogs.removeAll()
  55. if combinedLogs.isEmpty { return }
  56. var logOutput = ""
  57. var jsonOutput = ""
  58. switch logFormatting {
  59. case "Middleware":
  60. jsonOutput += "{\n"
  61. combinedLogs.replacingOccurrences(of: ";", with: ",")
  62. .replacingOccurrences(of: "\\s?:\\s?,?", with: ": ", options: .regularExpression)
  63. .replacingOccurrences(of: "(\\w+: \\d+(?= [^,:\\s]+:))", with: "$1,", options: .regularExpression)
  64. .replacingOccurrences(of: "^[^\\w]*", with: "", options: .regularExpression)
  65. .replacingOccurrences(of: "(\\sset)?\\sto:?\\s+", with: ": ", options: .regularExpression)
  66. .replacingOccurrences(of: "(\\w+) is (\\w+)\\!?", with: "$1: $2", options: .regularExpression)
  67. .replacingOccurrences(of: "NaN \\(\\. (.+)\\)", with: "$1, ", options: .regularExpression)
  68. .replacingOccurrences(of: "Setting (.+) of (.*)", with: "$1: $2 ", options: .regularExpression)
  69. .replacingOccurrences(of: "(Using\\s|\\sused)", with: "", options: .regularExpression)
  70. .replacingOccurrences(
  71. of: " instead of past 24 h \\((" + "(-?\\d+(\\.\\d+)?)" + " U)\\)",
  72. with: "weighted TDD average past 24h: $1",
  73. options: .regularExpression
  74. )
  75. .replacingOccurrences(of: "^(.+) \\((.+)\\)$", with: "$1: $2", options: .regularExpression)
  76. .replacingOccurrences(of: "\\s?,\\s?$", with: "", options: .regularExpression)
  77. .split(separator: "\n").forEach { logLine in
  78. jsonOutput += " "
  79. logLine.split(separator: ",").forEach { logItem in
  80. let keyPair = logItem.split(separator: ":")
  81. if keyPair.count == 2 {
  82. let key = keyPair[0].trimmingCharacters(in: .whitespacesAndNewlines).pascalCased
  83. let value = keyPair[1].trimmingCharacters(in: .whitespacesAndNewlines)
  84. jsonOutput += "\"\(key)\": \"\(value)\", "
  85. } else {
  86. logOutput += "\(logItem)\n"
  87. }
  88. }
  89. jsonOutput += "\n"
  90. }
  91. jsonOutput += "}"
  92. jsonOutput = jsonOutput.replacingOccurrences(of: "\\s+\\n+", with: "\n", options: .regularExpression)
  93. case "prepare/autosens.js":
  94. logOutput += combinedLogs.replacingOccurrences(
  95. of: "((?:[\\=\\+\\-]\\n)+)?\\d+h\\n((?:[\\=\\+\\-]\\n)+)?",
  96. with: "",
  97. options: .regularExpression
  98. )
  99. // case "prepare/autotune-prep.js"
  100. // case "prepare/autotune-core.js"
  101. default:
  102. debug(.openAPS, "JavaScript Format: \(logFormatting)")
  103. logOutput = combinedLogs
  104. }
  105. if !jsonOutput.isEmpty {
  106. if let jsonData = "\(jsonOutput)".data(using: .utf8) {
  107. do {
  108. let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options: [])
  109. _ = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
  110. debug(.openAPS, "JavaScript log: \(jsonOutput)")
  111. } catch {
  112. logOutput = combinedLogs
  113. }
  114. }
  115. }
  116. if !logOutput.isEmpty {
  117. logOutput.split(separator: "\n").forEach { logLine in
  118. if !"\(logLine)".trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
  119. debug(.openAPS, "JavaScript log: \(logLine)")
  120. }
  121. }
  122. }
  123. }
  124. @discardableResult func evaluate(script: Script) -> JSValue! {
  125. logFormatting = script.name
  126. let result = evaluate(string: script.body)
  127. aggregateLogs()
  128. return result
  129. }
  130. private func evaluate(string: String) -> JSValue! {
  131. let ctx = commonContext ?? createContext()
  132. return ctx.evaluateScript(string)
  133. }
  134. private func json(for string: String) -> RawJSON {
  135. evaluate(string: "JSON.stringify(\(string), null, 4);")!.toString()!
  136. }
  137. func call(function: String, with arguments: [JSON]) -> RawJSON {
  138. let joined = arguments.map(\.rawJSON).joined(separator: ",")
  139. return json(for: "\(function)(\(joined))")
  140. }
  141. func inCommonContext<Value>(execute: (JavaScriptWorker) -> Value) -> Value {
  142. commonContext = createContext()
  143. defer {
  144. commonContext = nil
  145. aggregateLogs()
  146. }
  147. return execute(self)
  148. }
  149. }