@nativue/core 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Package.swift CHANGED
@@ -8,6 +8,30 @@ let package = Package(
8
8
  products: [.library(name: "Nativue", targets: ["Nativue"])],
9
9
  dependencies: [.package(url: "https://github.com/facebook/yoga.git", .upToNextMinor(from: "3.2.2"))],
10
10
  targets: [
11
- .target(name: "Nativue", dependencies: [.product(name: "yoga", package: "yoga")], path: "ios"),
12
- ]
11
+ .target(
12
+ name: "Nativue",
13
+ dependencies: ["JavaScriptRuntime", .product(name: "yoga", package: "yoga")],
14
+ path: "ios",
15
+ exclude: ["JavaScriptRuntime"]
16
+ ),
17
+ .target(
18
+ name: "JavaScriptRuntime",
19
+ dependencies: ["hermesvm"],
20
+ path: "ios/JavaScriptRuntime",
21
+ exclude: ["vendor/hermes/LICENSE"],
22
+ cxxSettings: [
23
+ .headerSearchPath("vendor"),
24
+ .headerSearchPath("../../android/src/main/cpp/jsi"),
25
+ ]
26
+ ),
27
+ // The iOS slices of hermes-ios (Maven Central), the same Hermes version as hermes-android in
28
+ // android/build.gradle.kts and hermes-compiler in package.json: bytecode only runs on the Hermes
29
+ // that compiled it.
30
+ .binaryTarget(
31
+ name: "hermesvm",
32
+ url: "https://github.com/nativue/nativue/releases/download/hermes-260318099.0.8/hermesvm.xcframework.zip",
33
+ checksum: "9147f0187b5790e6c478cfd3de4de585666fa2af34a67dc8a0e8243ff0ff580d"
34
+ ),
35
+ ],
36
+ cxxLanguageStandard: .cxx20
13
37
  )
@@ -66,8 +66,8 @@ android {
66
66
  }
67
67
 
68
68
  dependencies {
69
- // Same version as the vendored JSI headers in src/main/cpp/jsi, and as hermes-compiler in
70
- // package.json: bytecode only runs on the Hermes that compiled it.
69
+ // Same version as the vendored JSI headers in src/main/cpp/jsi, hermes-compiler in package.json
70
+ // and hermesvm in Package.swift: bytecode only runs on the Hermes that compiled it.
71
71
  implementation("com.facebook.hermes:hermes-android:260318099.0.8")
72
72
  implementation("com.facebook.yoga:yoga:3.2.1")
73
73
  implementation("com.facebook.soloader:soloader:0.10.5")
package/cli/nativue.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  // The nativue CLI, run from the app's folder:
3
3
  // nativue build bundles src/app/ into ios/App/main.bundle.js (and, with an android/
4
- // folder, android/app/src/main/assets/main.bundle.js; Hermes bytecode
5
- // with --production)
4
+ // folder, android/app/src/main/assets/main.bundle.js); Hermes bytecode
5
+ // with --production
6
6
  // nativue dev rebuilds on save and tells the app (via SSE) to reload the bundle
7
7
  // nativue run <ios | android> builds, installs and opens the app on a simulator or emulator, then
8
8
  // keeps going as `nativue dev` (unless one is already running)
@@ -11,7 +11,7 @@ import vue from '@vitejs/plugin-vue'
11
11
  import http from 'node:http'
12
12
  import net from 'node:net'
13
13
  import { execFileSync } from 'node:child_process'
14
- import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'
14
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync } from 'node:fs'
15
15
  import { createRequire } from 'node:module'
16
16
  import { dirname } from 'node:path'
17
17
  import { fileURLToPath } from 'node:url'
@@ -59,27 +59,27 @@ function hermescPath() {
59
59
  return `${packageDirectory}/hermesc/${HERMESC_BY_PLATFORM[process.platform]}`
60
60
  }
61
61
 
62
- // The Android app packages its assets folder, so it gets the bundle. A production one is compiled
63
- // to Hermes bytecode, which starts faster: no parsing when the app opens. The runtime tells
64
- // bytecode from source on its own, so the file keeps its name.
65
- function bundleForAndroid(mode) {
62
+ // Hermes bytecode starts faster: no parsing when the app opens. The runtime tells bytecode from
63
+ // source on its own, so the file keeps its name.
64
+ function compileToBytecode(bundlePath) {
65
+ const bytecodePath = `${bundlePath}.hbc`
66
+
67
+ execFileSync(hermescPath(), ['-emit-binary', '-O', '-w', '-out', bytecodePath, bundlePath], {
68
+ stdio: 'inherit',
69
+ })
70
+ renameSync(bytecodePath, bundlePath)
71
+ }
72
+
73
+ // A production bundle becomes bytecode; the Android app packages its assets folder, so it gets a copy.
74
+ function finishBundle(mode) {
66
75
  return {
67
- name: 'nativue-android-bundle',
76
+ name: 'nativue-finish-bundle',
68
77
  writeBundle() {
78
+ if (mode === 'production') compileToBytecode(BUNDLE_PATH)
69
79
  if (!existsSync('android')) return
70
80
 
71
- const androidBundlePath = `${ANDROID_ASSETS_DIRECTORY}/main.bundle.js`
72
81
  mkdirSync(ANDROID_ASSETS_DIRECTORY, { recursive: true })
73
-
74
- if (mode !== 'production') return copyFileSync(BUNDLE_PATH, androidBundlePath)
75
-
76
- execFileSync(
77
- hermescPath(),
78
- ['-emit-binary', '-O', '-w', '-out', androidBundlePath, BUNDLE_PATH],
79
- {
80
- stdio: 'inherit',
81
- },
82
- )
82
+ copyFileSync(BUNDLE_PATH, `${ANDROID_ASSETS_DIRECTORY}/main.bundle.js`)
83
83
  },
84
84
  }
85
85
  }
@@ -98,7 +98,7 @@ function viteConfig({ mode, plugins = [], watch = null, sourcemap = false }) {
98
98
  compilerOptions: { isCustomElement: (tag) => NATIVE_COMPONENT_TAGS.includes(tag) },
99
99
  },
100
100
  }),
101
- bundleForAndroid(mode),
101
+ finishBundle(mode),
102
102
  ...plugins,
103
103
  ],
104
104
  // Compiled templates and app code import from 'vue': point them to the native renderer.
@@ -1,13 +1,11 @@
1
- // Maps stack frames of the bundle back to the app's files with the bundle's source map, in the
2
- // engine's format: JavaScriptCore's `name@main.bundle.js:8161:20` becomes `name@src/app/index.vue:22:9`,
3
- // Hermes' `at name (main.bundle.js:8161:20)` becomes `at name (src/app/index.vue:22:9)`. Consecutive
1
+ // Maps stack frames of the bundle back to the app's files with the bundle's source map: Hermes'
2
+ // `at name (main.bundle.js:8161:20)` becomes `at name (src/app/index.vue:22:9)`. Consecutive
4
3
  // frames from outside src/ (Vue, nativue, Hermes' native ones) collapse into one line, so the app's
5
4
  // own frames stand out. Other lines are kept.
6
5
  import { SourceMap } from 'node:module'
7
6
  import { relative, resolve } from 'node:path'
8
7
 
9
8
  // Groups: before the location, the location's line and column, after it.
10
- const JAVASCRIPTCORE_FRAME = /^(.*@)(?:.*main\.bundle\.js):(\d+):(\d+)()$/
11
9
  const HERMES_FRAME = /^(\s*at .* \()(?:.*main\.bundle\.js):(\d+):(\d+)(\))$/
12
10
  const HERMES_NATIVE_FRAME = /^\s*at .* \(native\)$/
13
11
 
@@ -28,7 +26,7 @@ export function createSymbolicator(sourceMapPayload, bundleDirectory) {
28
26
  function symbolicateLine(line) {
29
27
  if (HERMES_NATIVE_FRAME.test(line)) return { text: line, isInternal: true }
30
28
 
31
- const frame = JAVASCRIPTCORE_FRAME.exec(line) ?? HERMES_FRAME.exec(line)
29
+ const frame = HERMES_FRAME.exec(line)
32
30
  if (!frame) return { text: line, isInternal: false }
33
31
 
34
32
  const [, before, lineNumber, columnNumber, after] = frame
package/ios/Bridge.swift CHANGED
@@ -1,5 +1,5 @@
1
1
  import UIKit
2
- import JavaScriptCore
2
+ import JavaScriptRuntime
3
3
  import yoga
4
4
 
5
5
  /// Runs the JS bundle off the main thread and applies the operations sent by the Vue renderer
@@ -27,7 +27,7 @@ final class Bridge {
27
27
  private let javaScriptQueue = DispatchQueue(label: "dev.nativue.javascript", qos: .userInteractive)
28
28
 
29
29
  // Only touched on javaScriptQueue.
30
- private(set) var context: JSContext!
30
+ private var runtime: JavaScriptRuntime?
31
31
  private var pendingOperations: [() -> Void] = []
32
32
  private var gestureReportersByNodeId: [Int: GestureReporter] = [:]
33
33
  private let animatedGraph = AnimatedGraph()
@@ -45,7 +45,7 @@ final class Bridge {
45
45
  /// Read on the main thread at start, for Dimensions.get('window').
46
46
  private var windowSize: CGSize = .zero
47
47
  /// The bundle running now, for the error overlay's Reload.
48
- private var source = ""
48
+ private var bundle = Data()
49
49
  private let errorOverlay = ErrorOverlay()
50
50
 
51
51
  func start(rootView: RootView) {
@@ -63,29 +63,28 @@ final class Bridge {
63
63
  guard let bundleURL = Bundle.main.url(forResource: "main.bundle", withExtension: "js") else {
64
64
  fatalError("ios/App/main.bundle.js is missing: run `npm run dev` (or `npm run build`), then build again")
65
65
  }
66
- let source = try! String(contentsOf: bundleURL, encoding: .utf8)
67
-
68
- run(source)
66
+ run(try! Data(contentsOf: bundleURL))
69
67
  #if DEBUG
70
68
  Task { await listenForReload() }
71
69
  #endif
72
70
  }
73
71
 
74
- /// Discards the current node tree and JSContext, then runs the bundle from scratch.
75
- func run(_ source: String) {
76
- self.source = source
72
+ /// Discards the current node tree and runtime, then runs the bundle from scratch: JavaScript, or
73
+ /// Hermes bytecode (production builds).
74
+ func run(_ bundle: Data) {
75
+ self.bundle = bundle
77
76
  errorOverlay.hide()
78
77
 
79
78
  evaluate { [unowned self] in
80
79
  enqueue { [unowned self] in resetNodeTree() }
81
80
 
82
- context = makeContext()
83
- context.evaluateScript(source, withSourceURL: URL(string: "main.bundle.js"))
81
+ runtime = makeRuntime()
82
+ runtime?.evaluate(bundle, sourceURL: "main.bundle.js")
84
83
  }
85
84
  }
86
85
 
87
86
  /// Runs `work` on the JS queue, then applies every native operation it produced, in one batch, on the
88
- /// main thread. JavaScriptCore drains microtasks when `work` returns, so Vue's updates are included.
87
+ /// main thread. The runtime drains promise jobs after each call, so Vue's updates are included.
89
88
  func evaluate(_ work: @escaping () -> Void) {
90
89
  javaScriptQueue.async { [unowned self] in
91
90
  work()
@@ -124,9 +123,7 @@ final class Bridge {
124
123
  /// Queued on the JS queue, so a URL that opens the app arrives after the bundle has run.
125
124
  private func openURL(_ url: URL) {
126
125
  evaluate { [unowned self] in
127
- guard let openURL = context.objectForKeyedSubscript("__openURL"), openURL.isObject else { return }
128
-
129
- openURL.call(withArguments: [url.absoluteString])
126
+ runtime?.call("__openURL", arguments: [url.absoluteString])
130
127
  }
131
128
  }
132
129
 
@@ -147,7 +144,7 @@ final class Bridge {
147
144
  for try await line in events.lines where line == "data: reload" {
148
145
  let (data, _) = try await URLSession.shared.data(from: bundleURL)
149
146
  print("[Nativue] reload")
150
- run(String(decoding: data, as: UTF8.self))
147
+ run(data)
151
148
  }
152
149
  } catch {}
153
150
 
@@ -162,78 +159,91 @@ final class Bridge {
162
159
  pendingOperations.append(operation)
163
160
  }
164
161
 
165
- private func makeContext() -> JSContext {
166
- let context = JSContext()!
167
- // Errors outside Vue: timers, native callbacks, the bundle itself. Vue's go through reportError.
168
- context.exceptionHandler = { [unowned self] _, exception in
169
- reportError(
170
- message: exception?.toString() ?? "",
171
- details: exception?.objectForKeyedSubscript("stack")?.toString() ?? ""
172
- )
173
- }
162
+ private typealias NativeFunction = (_ arguments: [Any]) -> Any?
163
+ private typealias Define = (_ name: String, _ function: @escaping (_ arguments: [Any]) -> Void) -> Void
164
+ private typealias DefineGetter = (_ name: String, _ function: @escaping NativeFunction) -> Void
174
165
 
175
- let nativeModule = JSValue(newObjectIn: context)!
176
- func define(_ name: String, _ block: Any) {
177
- nativeModule.setObject(block, forKeyedSubscript: name as NSString)
166
+ /// Errors outside Vue (timers, native callbacks, the bundle itself) come from the runtime; Vue's
167
+ /// through `__native.reportError`.
168
+ private func makeRuntime() -> JavaScriptRuntime {
169
+ var functions: [String: Any] = [:]
170
+ func defineGetter(_ name: String, _ function: @escaping NativeFunction) {
171
+ functions[name] = function as @convention(block) ([Any]) -> Any?
172
+ }
173
+ func define(_ name: String, _ function: @escaping (_ arguments: [Any]) -> Void) {
174
+ defineGetter(name) { arguments in
175
+ function(arguments)
176
+ return nil
177
+ }
178
178
  }
179
179
 
180
- define("log", { message in print("[JS]", message) } as @convention(block) (String) -> Void)
180
+ define("log") { arguments in print("[JS]", arguments[0]) }
181
181
 
182
- define("reportError", { [unowned self] message, details in
183
- reportError(message: message, details: details)
184
- } as @convention(block) (String, String) -> Void)
182
+ define("reportError") { [unowned self] arguments in
183
+ reportError(message: string(arguments[0]), details: string(arguments[1]))
184
+ }
185
185
 
186
186
  // ponytail: the size at launch; report rotation and split view changes if the app supports them.
187
- define("windowSize", { [unowned self] in
187
+ defineGetter("windowSize") { [unowned self] _ in
188
188
  ["width": windowSize.width, "height": windowSize.height]
189
- } as @convention(block) () -> [String: Double])
189
+ }
190
190
 
191
- define("create", { [unowned self] id, type in
191
+ define("create") { [unowned self] arguments in
192
+ let (id, type) = (int(arguments[0]), string(arguments[1]))
192
193
  enqueue { [unowned self] in nodesById[id] = makeNode(type: type, id: id) }
193
- } as @convention(block) (Int, String) -> Void)
194
+ }
194
195
 
195
- define("insert", { [unowned self] parentId, childId, index in
196
+ define("insert") { [unowned self] arguments in
197
+ let (parentId, childId, index) = (int(arguments[0]), int(arguments[1]), int(arguments[2]))
196
198
  enqueue { [unowned self] in insertNode(childId: childId, parentId: parentId, at: index) }
197
- } as @convention(block) (Int, Int, Int) -> Void)
199
+ }
198
200
 
199
- define("remove", { [unowned self] id in
201
+ define("remove") { [unowned self] arguments in
202
+ let id = int(arguments[0])
200
203
  enqueue { [unowned self] in removeNode(id: id) }
201
- } as @convention(block) (Int) -> Void)
204
+ }
202
205
 
203
- define("setText", { [unowned self] id, text in
206
+ define("setText") { [unowned self] arguments in
207
+ let (id, text) = (int(arguments[0]), string(arguments[1]))
204
208
  enqueue { [unowned self] in setText(text, onNodeId: id) }
205
- } as @convention(block) (Int, String) -> Void)
209
+ }
206
210
 
207
- define("setProp", { [unowned self] id, key, value in
208
- let convertedValue = value.toObject() // JSValue must not leave the JS queue
209
- enqueue { [unowned self] in setProp(key, value: convertedValue, onNodeId: id) }
210
- } as @convention(block) (Int, String, JSValue) -> Void)
211
+ define("setProp") { [unowned self] arguments in
212
+ let (id, key, value) = (int(arguments[0]), string(arguments[1]), arguments[2])
213
+ enqueue { [unowned self] in setProp(key, value: value, onNodeId: id) }
214
+ }
211
215
 
212
216
  defineAnimatedFunctions(define)
213
- defineStorageFunctions(define)
217
+ defineStorageFunctions(define, defineGetter)
214
218
  defineFetch(define)
215
219
 
216
- define("setTimer", { [unowned self, weak context] timerId, delayInMilliseconds in
217
- // Weak: after a hot reload, the old context's timers die with it instead of firing in the new
218
- // context, where timer ids start over.
219
- DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(delayInMilliseconds)) { [unowned self, weak context] in
220
- evaluate {
221
- _ = context?.objectForKeyedSubscript("__fireTimer").call(withArguments: [timerId])
222
- }
223
- }
224
- } as @convention(block) (Int, Int) -> Void)
220
+ define("setTimer") { [unowned self] arguments in
221
+ let (timerId, delayInMilliseconds) = (int(arguments[0]), int(arguments[1]))
222
+ setTimer(timerId, delayInMilliseconds: delayInMilliseconds)
223
+ }
225
224
 
226
- define("configureNextLayoutAnimation", { [unowned self] config in
227
- nextLayoutAnimation = LayoutAnimation(config: config)
228
- } as @convention(block) ([String: Any]) -> Void)
225
+ define("configureNextLayoutAnimation") { [unowned self] arguments in
226
+ nextLayoutAnimation = LayoutAnimation(config: arguments[0] as? [String: Any] ?? [:])
227
+ }
229
228
 
230
- define("dismissKeyboard", { [unowned self] in
229
+ define("dismissKeyboard") { [unowned self] _ in
231
230
  enqueue { [unowned self] in rootView.window?.endEditing(true) }
232
- } as @convention(block) () -> Void)
231
+ }
232
+
233
+ return JavaScriptRuntime(functions: functions) { [unowned self] message, stack in
234
+ reportError(message: message, details: stack)
235
+ }
236
+ }
233
237
 
234
- context.setObject(nativeModule, forKeyedSubscript: "__native" as NSString)
238
+ /// A timer of a runtime that has since been reloaded doesn't fire: timer ids start over in the new one.
239
+ private func setTimer(_ timerId: Int, delayInMilliseconds: Int) {
240
+ let owner = runtime
235
241
 
236
- return context
242
+ javaScriptQueue.asyncAfter(deadline: .now() + .milliseconds(delayInMilliseconds)) { [unowned self] in
243
+ guard runtime === owner else { return }
244
+
245
+ evaluate { [unowned self] in runtime?.call("__fireTimer", arguments: [timerId]) }
246
+ }
237
247
  }
238
248
 
239
249
  /// Logged always; shown over the app in development builds.
@@ -243,7 +253,7 @@ final class Bridge {
243
253
  #if DEBUG
244
254
  Task { @MainActor [unowned self] in
245
255
  let details = await symbolicated(details)
246
- errorOverlay.show(message: message, details: details) { [unowned self] in run(source) }
256
+ errorOverlay.show(message: message, details: details) { [unowned self] in run(bundle) }
247
257
  }
248
258
  #endif
249
259
  }
@@ -275,7 +285,7 @@ final class Bridge {
275
285
  animatedGraph.reset()
276
286
  animatedGraph.onAnimationEnd = { [unowned self] animationId, finished in
277
287
  evaluate { [unowned self] in
278
- context.objectForKeyedSubscript("__animationFinished")?.call(withArguments: [animationId, finished])
288
+ runtime?.call("__animationFinished", arguments: [animationId, finished])
279
289
  }
280
290
  }
281
291
  nodesById = [0: NativeNode(view: rootView, measuresContent: false)]
@@ -436,33 +446,35 @@ final class Bridge {
436
446
  }
437
447
 
438
448
  /// AsyncStorage: synchronous on the JS queue (values are in memory); JS wraps them in promises.
439
- private func defineStorageFunctions(_ define: (String, Any) -> Void) {
440
- define("storageGet", { [unowned self] key in
441
- storage.value(forKey: key)
442
- } as @convention(block) (String) -> String?)
449
+ private func defineStorageFunctions(_ define: Define, _ defineGetter: DefineGetter) {
450
+ defineGetter("storageGet") { [unowned self] arguments in
451
+ storage.value(forKey: string(arguments[0]))
452
+ }
443
453
 
444
- define("storageSet", { [unowned self] key, value in
445
- storage.setValue(value, forKey: key)
446
- } as @convention(block) (String, String) -> Void)
454
+ define("storageSet") { [unowned self] arguments in
455
+ storage.setValue(string(arguments[1]), forKey: string(arguments[0]))
456
+ }
447
457
 
448
- define("storageRemove", { [unowned self] key in
449
- storage.removeValue(forKey: key)
450
- } as @convention(block) (String) -> Void)
458
+ define("storageRemove") { [unowned self] arguments in
459
+ storage.removeValue(forKey: string(arguments[0]))
460
+ }
451
461
 
452
- define("storageKeys", { [unowned self] in
462
+ defineGetter("storageKeys") { [unowned self] _ in
453
463
  storage.keys
454
- } as @convention(block) () -> [String])
464
+ }
455
465
 
456
- define("storageClear", { [unowned self] in
466
+ define("storageClear") { [unowned self] _ in
457
467
  storage.removeAll()
458
- } as @convention(block) () -> Void)
468
+ }
459
469
  }
460
470
 
461
471
  /// fetch: URLSession runs the request; JS hears back through __fetchFinished(requestId, response, error).
462
472
  /// ponytail: text bodies only (no binary, FormData or streaming) and no abort.
463
- private func defineFetch(_ define: (String, Any) -> Void) {
464
- define("fetch", { [unowned self] requestId, url, method, headers, body in
465
- let bodyText = body.isNull || body.isUndefined ? nil : body.toString()
473
+ private func defineFetch(_ define: Define) {
474
+ define("fetch") { [unowned self] arguments in
475
+ let (requestId, url, method) = (int(arguments[0]), string(arguments[1]), string(arguments[2]))
476
+ let headers = arguments[3] as? [String: String] ?? [:]
477
+ let bodyText = arguments[4] as? String
466
478
 
467
479
  guard let url = URL(string: url) else {
468
480
  return finishFetch(requestId, response: nil, error: "invalid URL \(url)")
@@ -484,48 +496,54 @@ final class Bridge {
484
496
  "body": String(decoding: data ?? Data(), as: UTF8.self),
485
497
  ], error: nil)
486
498
  }.resume()
487
- } as @convention(block) (Int, String, String, [String: String], JSValue) -> Void)
499
+ }
488
500
  }
489
501
 
490
502
  private func finishFetch(_ requestId: Int, response: [String: Any]?, error: String?) {
491
503
  evaluate { [unowned self] in
492
504
  let arguments: [Any] = [requestId, response ?? NSNull(), error ?? NSNull()]
493
- context.objectForKeyedSubscript("__fetchFinished")?.call(withArguments: arguments)
505
+ runtime?.call("__fetchFinished", arguments: arguments)
494
506
  }
495
507
  }
496
508
 
497
509
  /// Animated's native driver (see AnimatedGraph); queued like the view operations, so a value bound in
498
510
  /// a batch exists when that batch is applied.
499
- private func defineAnimatedFunctions(_ define: (String, Any) -> Void) {
500
- define("createAnimatedNode", { [unowned self] id, config in
511
+ private func defineAnimatedFunctions(_ define: Define) {
512
+ define("createAnimatedNode") { [unowned self] arguments in
513
+ let (id, config) = (int(arguments[0]), arguments[1] as? [String: Any] ?? [:])
501
514
  enqueue { [unowned self] in animatedGraph.createNode(id: id, config: config) }
502
- } as @convention(block) (Int, [String: Any]) -> Void)
515
+ }
503
516
 
504
- define("setAnimatedValue", { [unowned self] id, value in
517
+ define("setAnimatedValue") { [unowned self] arguments in
518
+ let (id, value) = (int(arguments[0]), double(arguments[1]))
505
519
  enqueue { [unowned self] in animatedGraph.setValue(value, ofNode: id) }
506
- } as @convention(block) (Int, Double) -> Void)
520
+ }
507
521
 
508
- define("startAnimation", { [unowned self] animationId, nodeId, config in
522
+ define("startAnimation") { [unowned self] arguments in
523
+ let (animationId, nodeId) = (int(arguments[0]), int(arguments[1]))
524
+ let config = arguments[2] as? [String: Any] ?? [:]
509
525
  enqueue { [unowned self] in animatedGraph.startAnimation(id: animationId, nodeId: nodeId, config: config) }
510
- } as @convention(block) (Int, Int, [String: Any]) -> Void)
526
+ }
511
527
 
512
- define("stopAnimation", { [unowned self] nodeId in
528
+ define("stopAnimation") { [unowned self] arguments in
529
+ let nodeId = int(arguments[0])
513
530
  enqueue { [unowned self] in animatedGraph.stopAnimation(ofNode: nodeId) }
514
- } as @convention(block) (Int) -> Void)
531
+ }
515
532
 
516
- define("setAnimatedStyle", { [unowned self] viewId, binding in
517
- let binding = binding.toObject() as? [String: Any] // JSValue must not leave the JS queue
533
+ define("setAnimatedStyle") { [unowned self] arguments in
534
+ let (viewId, binding) = (int(arguments[0]), arguments[1] as? [String: Any])
518
535
  enqueue { [unowned self] in
519
536
  guard let view = nodesById[viewId]?.view else { return }
520
537
 
521
538
  animatedGraph.bind(view: view, viewId: viewId, binding: binding)
522
539
  }
523
- } as @convention(block) (Int, JSValue) -> Void)
540
+ }
524
541
 
525
- define("setAnimatedEvent", { [unowned self] viewId, event, mapping in
526
- let mapping = mapping.toObject() as? [String: Int]
542
+ define("setAnimatedEvent") { [unowned self] arguments in
543
+ let (viewId, event) = (int(arguments[0]), string(arguments[1]))
544
+ let mapping = (arguments[2] as? [String: Any])?.compactMapValues { ($0 as? NSNumber)?.intValue }
527
545
  enqueue { [unowned self] in setAnimatedEvent(event, mapping: mapping, onNodeId: viewId) }
528
- } as @convention(block) (Int, String, JSValue) -> Void)
546
+ }
529
547
  }
530
548
 
531
549
  private func setAnimatedEvent(_ event: String, mapping: [String: Int]?, onNodeId id: Int) {
@@ -558,7 +576,7 @@ final class Bridge {
558
576
  private func dispatchEvent(_ eventName: String, toNodeId id: Int, payload: Any? = nil) {
559
577
  evaluate { [unowned self] in
560
578
  let arguments: [Any] = [id, eventName, payload ?? NSNull()]
561
- context.objectForKeyedSubscript("__dispatch").call(withArguments: arguments)
579
+ runtime?.call("__dispatch", arguments: arguments)
562
580
  }
563
581
  }
564
582
 
@@ -745,3 +763,17 @@ final class Bridge {
745
763
  return false
746
764
  }
747
765
  }
766
+
767
+ // JS numbers arrive as NSNumber doubles; a missing or mistyped argument reads as 0 or "".
768
+
769
+ private func int(_ argument: Any) -> Int {
770
+ (argument as? NSNumber)?.intValue ?? 0
771
+ }
772
+
773
+ private func double(_ argument: Any) -> Double {
774
+ (argument as? NSNumber)?.doubleValue ?? 0
775
+ }
776
+
777
+ private func string(_ argument: Any) -> String {
778
+ argument as? String ?? ""
779
+ }