expo-modules-core 58.0.24 → 58.0.27

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.
Files changed (34) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/android/build.gradle +3 -3
  3. package/android/prebuilt/metadata.json +2 -2
  4. package/android/prebuilt/native-libs.tar.xz +0 -0
  5. package/android/src/main/cpp/ArrayBuffer.cpp +7 -1
  6. package/android/src/main/cpp/ArrayBuffer.h +2 -0
  7. package/android/src/main/java/expo/modules/interfaces/taskManager/TaskServiceProviderHelper.kt +1 -1
  8. package/android/src/main/java/expo/modules/kotlin/sharedobjects/SharedObject.kt +5 -0
  9. package/android/src/main/java/expo/modules/kotlin/sharedobjects/SharedObjectRegistry.kt +14 -0
  10. package/common/cpp/fabric/ExpoViewShadowNode.h +34 -5
  11. package/expo-module-gradle-plugin/build.gradle.kts +1 -1
  12. package/ios/Benchmarks/EventEmitterBenchmarks.swift +73 -0
  13. package/ios/Benchmarks/FunctionBenchmarks.swift +28 -0
  14. package/ios/Benchmarks/SharedObjectBenchmarks.swift +97 -3
  15. package/ios/Core/AppContext.swift +32 -5
  16. package/ios/Core/ArrayBuffers/ArrayBuffer.swift +44 -6
  17. package/ios/Core/Classes/ClassDefinition.swift +4 -3
  18. package/ios/Core/DynamicTypes/DynamicSharedObjectType.swift +1 -1
  19. package/ios/Core/Events/EventEmitter.swift +68 -26
  20. package/ios/Core/ExpoModulesMacros.swift +13 -14
  21. package/ios/Core/ModuleHolder.swift +7 -9
  22. package/ios/Core/Modules/ModuleDefinition.swift +2 -3
  23. package/ios/Core/Protocols/AnyModule.swift +12 -4
  24. package/ios/Core/SharedObjects/SharedObject.swift +30 -0
  25. package/ios/Core/SharedObjects/SharedObjectNativeState.swift +51 -9
  26. package/ios/Core/SharedObjects/SharedObjectRegistry.swift +19 -8
  27. package/ios/JS/JavaScriptBindings.swift +53 -0
  28. package/ios/Utilities/Mutex.swift +15 -3
  29. package/package.json +3 -3
  30. package/prebuilds/output/debug/xcframeworks/ExpoModulesCore.tar.gz +0 -0
  31. package/prebuilds/output/debug/xcframeworks/ExpoModulesWorklets.tar.gz +0 -0
  32. package/prebuilds/output/headers/xcframeworks/ExpoModulesCoreHeaders.tar.gz +0 -0
  33. package/prebuilds/output/release/xcframeworks/ExpoModulesCore.tar.gz +0 -0
  34. package/prebuilds/output/release/xcframeworks/ExpoModulesWorklets.tar.gz +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,39 @@
1
1
  # Changelog
2
2
 
3
+ ## 58.0.27
4
+
5
+ ### Patch Changes
6
+
7
+ - [Android] Fix a crash when a function returns the same `ArrayBuffer` to JavaScript many times. Each return held a new JNI global reference until garbage collection, which overflowed the global reference table. ([#52278](https://github.com/expo/expo/pull/52278) by [@github-actions](https://github.com/apps/github-actions))
8
+ - [Android] Avoid Kotlin reflection when sorting task service providers. ([`571588f`](https://github.com/expo/expo/commit/571588f363d0598e9196bb9560635bc1cf8fe817) by [@matthew-gizmo](https://github.com/matthew-gizmo))
9
+ - [iOS] Reduce the overhead of emitting events by reaching the JSI runtime, the emitter object and the payload in one call. ([#52178](https://github.com/expo/expo/pull/52178) by [@tsapeta](https://github.com/tsapeta))
10
+ - [iOS] Reduce the overhead of emitting events with a `JavaScriptEncodable` payload, including from `@Event` properties, by specializing `emit(event:payload:)` for the payload type in the caller's module. ([#52179](https://github.com/expo/expo/pull/52179) by [@tsapeta](https://github.com/tsapeta))
11
+ - [iOS] Build the JavaScript classes of `@SharedObject` classes registered with `@ExpoModule(classes:)` from their type, without a `ClassDefinition`. ([#52137](https://github.com/expo/expo/pull/52137) by [@tsapeta](https://github.com/tsapeta))
12
+ - [iOS] Update `expo-modules-macros` to 0.24.0. A sync closure argument of a `@JS` function now encodes its arguments with code specialized for their types. ([#52232](https://github.com/expo/expo/pull/52232) by [@tsapeta](https://github.com/tsapeta))
13
+ - [iOS] Update `expo-modules-macros` to 0.23.1. `@JS` now supports a `lazy var`, which is read-only from JavaScript and stores its value on the JavaScript object at the first read. `@SharedObject` now supports subclasses of `SharedRef<T>`. Macros in a generic type no longer fail to build when a generic parameter of the type has the same name as one in the generated code. ([#52200](https://github.com/expo/expo/pull/52200) by [@tsapeta](https://github.com/tsapeta))
14
+ - [iOS] Fix `MenuView` triggers that fill their parent, so text in them wraps and they resize on rotation. ([#52278](https://github.com/expo/expo/pull/52278) by [@github-actions](https://github.com/apps/github-actions))
15
+ - Updated dependencies. ([#52232](https://github.com/expo/expo/pull/52232), [#52164](https://github.com/expo/expo/pull/52164), [#52178](https://github.com/expo/expo/pull/52178))
16
+ - expo-modules-jsi@58.0.20
17
+
18
+ ## 58.0.26
19
+
20
+ ### Patch Changes
21
+
22
+ - [iOS] Reduce the overhead of creating shared objects in JavaScript and of returning them from native functions. ([#52096](https://github.com/expo/expo/pull/52096) by [@tsapeta](https://github.com/tsapeta))
23
+ - Updated dependencies. ([#52095](https://github.com/expo/expo/pull/52095))
24
+ - expo-modules-jsi@58.0.19
25
+
26
+ ## 58.0.25
27
+
28
+ ### Patch Changes
29
+
30
+ - [iOS] Support `static` and `class` `@JS` members on `@SharedObject` classes. They are bound onto the JavaScript class itself, for example `Cache.open(name)`. ([#51966](https://github.com/expo/expo/pull/51966) by [@tsapeta](https://github.com/tsapeta))
31
+ - [Android] Fix "Cannot use shared object that was already released" errors when a view with a shared object prop, such as the `@expo/ui` `TextInput`, is remounted right after its first render. ([#51934](https://github.com/expo/expo/pull/51934) by [@expo-tuft](https://github.com/apps/expo-tuft))
32
+ - [iOS] Fix apps running out of memory when native functions return many new `ArrayBuffer` values to JavaScript, because the garbage collector did not count their memory. ([#52124](https://github.com/expo/expo/pull/52124) by [@tsapeta](https://github.com/tsapeta))
33
+ - [iOS] Fix `ArrayBuffer.wrap(dataWithoutCopy:)` keeping the bytes of released buffers alive until the current autorelease pool drains, which could make apps run out of memory when JavaScript calls a native function in a loop. ([#52123](https://github.com/expo/expo/pull/52123) by [@tsapeta](https://github.com/tsapeta))
34
+ - Updated dependencies. ([#52125](https://github.com/expo/expo/pull/52125), [#52031](https://github.com/expo/expo/pull/52031), [#52133](https://github.com/expo/expo/pull/52133), [#52122](https://github.com/expo/expo/pull/52122), [#52055](https://github.com/expo/expo/pull/52055))
35
+ - expo-modules-jsi@58.0.18
36
+
3
37
  ## 58.0.24
4
38
 
5
39
  ### Patch Changes
@@ -46,7 +46,7 @@ if (shouldIncludeCompose) {
46
46
  }
47
47
 
48
48
  group = 'host.exp.exponent'
49
- version = '58.0.24'
49
+ version = '58.0.27'
50
50
 
51
51
  def isExpoModulesCoreTests = {
52
52
  Gradle gradle = getGradle()
@@ -97,7 +97,7 @@ if (workletsProject != null) {
97
97
 
98
98
  def reactNativeWorkletsRootDir = workletsProject?.projectDir?.parentFile
99
99
 
100
- def expoModulesV2Version = "0.2.5"
100
+ def expoModulesV2Version = "0.2.6"
101
101
 
102
102
  configurations {
103
103
  // Artifact-only: the C++ sources, not something to put on any classpath.
@@ -175,7 +175,7 @@ android {
175
175
  defaultConfig {
176
176
  consumerProguardFiles 'proguard-rules.pro'
177
177
  versionCode 1
178
- versionName "58.0.24"
178
+ versionName "58.0.27"
179
179
  buildConfigField "String", "EXPO_MODULES_CORE_VERSION", "\"${versionName}\""
180
180
  buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", "true"
181
181
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "reactNativeVersion": "0.88.0",
3
- "sourceHash": "d5785b6fa4de4ea64f18bdac451d0308",
3
+ "sourceHash": "e93890c6e60394cdef56149d38614433",
4
4
  "variants": [
5
5
  "debug",
6
6
  "release"
@@ -16,5 +16,5 @@
16
16
  "libexpo-modules-jsi.so"
17
17
  ],
18
18
  "stripped": true,
19
- "createdAt": "2026-10-21T17:10:44.785915196Z"
19
+ "createdAt": "2026-10-27T11:46:34.803657897Z"
20
20
  }
Binary file
@@ -282,7 +282,13 @@ jni::local_ref<jni::JByteBuffer> ByteBufferArrayBufferStorage::toDirectBuffer()
282
282
  }
283
283
 
284
284
  std::shared_ptr<jsi::MutableBuffer> ByteBufferArrayBufferStorage::jsiMutableBuffer() {
285
- return std::make_shared<ByteBufferJSIMutableBuffer>(jni::make_local(_byteBuffer));
285
+ // All JS array buffers of this storage share one mutable buffer. Each mutable buffer holds a
286
+ // JNI global reference, and Android aborts the app when the global reference table overflows.
287
+ std::lock_guard<std::mutex> lock(_jsiMutableBufferMutex);
288
+ if (_jsiMutableBuffer == nullptr) {
289
+ _jsiMutableBuffer = std::make_shared<ByteBufferJSIMutableBuffer>(jni::make_local(_byteBuffer));
290
+ }
291
+ return _jsiMutableBuffer;
286
292
  }
287
293
 
288
294
  jsi::Value ByteBufferArrayBufferStorage::toJSIValue(jsi::Runtime &runtime) {
@@ -87,6 +87,8 @@ public:
87
87
 
88
88
  private:
89
89
  jni::global_ref<jni::JByteBuffer> _byteBuffer;
90
+ std::mutex _jsiMutableBufferMutex;
91
+ std::shared_ptr<jsi::MutableBuffer> _jsiMutableBuffer;
90
92
  };
91
93
 
92
94
  class MutableBufferViewArrayBufferStorage : public ArrayBufferStorage {
@@ -30,7 +30,7 @@ object TaskServiceProviderHelper {
30
30
  // Invoke and get the list of packages
31
31
  val result = getPackageList.invoke(null) as? List<*> ?: return null
32
32
  val packages = result.filterIsInstance<Package>()
33
- .sortedByDescending { ModulePriorities.get(it::class.qualifiedName) }
33
+ .sortedByDescending { ModulePriorities.get(it.javaClass.canonicalName) }
34
34
 
35
35
  // Check if any of the packages are providing a task manager implementation
36
36
  return packages
@@ -80,6 +80,11 @@ open class SharedObject(runtime: Runtime? = null) {
80
80
  }
81
81
  }
82
82
 
83
+ /**
84
+ * Delays the release until the queued view updates are applied. Use it for objects passed as view props.
85
+ */
86
+ open val releasesAfterPendingViewUpdates: Boolean = false
87
+
83
88
  open fun onStartListeningToEvent(eventName: String) = Unit
84
89
 
85
90
  open fun onStopListeningToEvent(eventName: String) = Unit
@@ -1,5 +1,6 @@
1
1
  package expo.modules.kotlin.sharedobjects
2
2
 
3
+ import com.facebook.react.modules.core.ReactChoreographer
3
4
  import expo.modules.kotlin.runtime.Runtime
4
5
  import expo.modules.kotlin.exception.Exceptions
5
6
  import expo.modules.kotlin.exception.InvalidSharedObjectIdException
@@ -85,6 +86,19 @@ class SharedObjectRegistry(runtime: Runtime) {
85
86
  }
86
87
 
87
88
  internal fun delete(id: SharedObjectId) {
89
+ val native = synchronized(this) { pairs[id]?.first } ?: return
90
+ if (native.releasesAfterPendingViewUpdates) {
91
+ val choreographer = runCatching { ReactChoreographer.getInstance() }.getOrNull()
92
+ if (choreographer != null) {
93
+ // Runs after Fabric's `DISPATCH_UI` callback, which applies the queued view updates.
94
+ choreographer.postFrameCallback(ReactChoreographer.CallbackType.IDLE_EVENT) { remove(id) }
95
+ return
96
+ }
97
+ }
98
+ remove(id)
99
+ }
100
+
101
+ private fun remove(id: SharedObjectId) {
88
102
  synchronized(this) {
89
103
  pairs.remove(id)
90
104
  }?.let { (native, _) ->
@@ -95,6 +95,18 @@ public:
95
95
  return it != viewProps->propsMap.end() && it->second.isBool() && it->second.getBool();
96
96
  }
97
97
 
98
+ // Set by `MenuView`'s `RNHostView`, whose `Host` is sized by Yoga instead of its content.
99
+ static bool boundedByHost(const react::Props::Shared &props) {
100
+ auto const *viewProps = dynamic_cast<const ExpoViewProps *>(props.get());
101
+
102
+ if (viewProps == nullptr) {
103
+ return false;
104
+ }
105
+
106
+ auto const it = viewProps->propsMap.find("expoInternalBoundedByHost");
107
+ return it != viewProps->propsMap.end() && it->second.isBool() && it->second.getBool();
108
+ }
109
+
98
110
  // Yoga calls this method for RNHostView when it has matchContents set
99
111
  react::Size measureContent(
100
112
  const react::LayoutContext &layoutContext,
@@ -111,7 +123,14 @@ public:
111
123
  return {};
112
124
  }
113
125
 
114
- return content->measure(layoutContext, hostedContentConstraints(*content));
126
+ auto constraints = hostedContentConstraints(*content);
127
+
128
+ if (boundedByHost(this->getProps())) {
129
+ // Like any Yoga child, the content can't be bigger than the space the `Host` offers.
130
+ constrainToMaximumSize(constraints, layoutConstraints.maximumSize);
131
+ }
132
+
133
+ return content->measure(layoutContext, constraints);
115
134
  }
116
135
 
117
136
  // We override this so RNHostView can lay out it's children
@@ -130,11 +149,14 @@ public:
130
149
  }
131
150
 
132
151
  // Use the same constraint that was used to measure the content, so that the layout is consistent with the measurement
152
+ auto constraints = hostedContentConstraints(*content);
153
+
154
+ if (boundedByHost(this->getProps())) {
155
+ constrainToMaximumSize(constraints, this->getLayoutMetrics().frame.size);
156
+ }
157
+
133
158
  auto const clonedContent = content->clone({});
134
- static_cast<react::LayoutableShadowNode &>(*clonedContent).layoutTree(
135
- layoutContext,
136
- hostedContentConstraints(*content)
137
- );
159
+ static_cast<react::LayoutableShadowNode &>(*clonedContent).layoutTree(layoutContext, constraints);
138
160
 
139
161
  this->replaceChild(*content, clonedContent, 0);
140
162
 
@@ -145,6 +167,13 @@ public:
145
167
  }
146
168
 
147
169
  private:
170
+ static void constrainToMaximumSize(react::LayoutConstraints &constraints, react::Size maximumSize) {
171
+ constraints.maximumSize.width = std::min(constraints.maximumSize.width, maximumSize.width);
172
+ constraints.maximumSize.height = std::min(constraints.maximumSize.height, maximumSize.height);
173
+ constraints.minimumSize.width = std::min(constraints.minimumSize.width, constraints.maximumSize.width);
174
+ constraints.minimumSize.height = std::min(constraints.minimumSize.height, constraints.maximumSize.height);
175
+ }
176
+
148
177
  // Owning on purpose: `layout()` calls `replaceChild()`, which overwrites this node's only strong
149
178
  // reference to the content — `RNHostView` is a leaf Yoga node, so Yoga keeps no second one, and
150
179
  // `YogaLayoutableShadowNode::replaceChild()` reads `oldChild` right after.
@@ -33,7 +33,7 @@ dependencies {
33
33
  implementation("com.facebook.react:react-native-gradle-plugin")
34
34
  implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.3")
35
35
  implementation("io.github.expo.pika:pika-gradle:1.1.0")
36
- implementation("io.github.expo:expo-modules-v2-gradle-plugin:0.2.5")
36
+ implementation("io.github.expo:expo-modules-v2-gradle-plugin:0.2.6")
37
37
 
38
38
  if (isExpoAutolinkingSettingsPluginAvailable) {
39
39
  implementation("expo.modules:expo-autolinking-plugin-shared")
@@ -21,6 +21,17 @@ extension Benchmarks {
21
21
  }
22
22
  }
23
23
 
24
+ @Test
25
+ func `emit: no payload through @Event`() async throws {
26
+ try await eventBenchmarkCase { module, runtime in
27
+ try benchmark("emit: no payload through @Event", runtime: runtime) { iterations in
28
+ for _ in 0..<iterations {
29
+ module.onPing()
30
+ }
31
+ }
32
+ }
33
+ }
34
+
24
35
  @Test
25
36
  func `emit: no payload, 100 other modules registered`() async throws {
26
37
  try await eventBenchmarkCase(otherModuleCount: 100) { module, runtime in
@@ -76,6 +87,17 @@ extension Benchmarks {
76
87
  }
77
88
  }
78
89
 
90
+ @Test
91
+ func `emit: record payload through @Event`() async throws {
92
+ try await eventBenchmarkCase { module, runtime in
93
+ try benchmark("emit: record payload through @Event", runtime: runtime) { iterations in
94
+ for index in 0..<iterations {
95
+ module.onProgress(ProgressPayload(percent: index, label: "loading"))
96
+ }
97
+ }
98
+ }
99
+ }
100
+
79
101
  @Test
80
102
  func `emit: record payload as AnyArgument`() async throws {
81
103
  try await eventBenchmarkCase { module, runtime in
@@ -86,6 +108,49 @@ extension Benchmarks {
86
108
  }
87
109
  }
88
110
  }
111
+
112
+ @Test
113
+ func `emit: shared object payload`() async throws {
114
+ try await eventBenchmarkCase { module, runtime in
115
+ // Encoding the object once pairs it with a JavaScript object, as an object already used from
116
+ // JavaScript would be. Holding that object keeps the pair alive across garbage collections.
117
+ // A shared object isn't `Sendable`, so it can't be sent to `emit` more than once without
118
+ // opting out of the check, and an `@Event` with this payload type doesn't compile.
119
+ nonisolated(unsafe) let payload = EventPayloadObject()
120
+ let payloadObject = try EventPayloadObject.encode(payload, in: runtime)
121
+
122
+ try withExtendedLifetime(payloadObject) {
123
+ try benchmark("emit: shared object payload", runtime: runtime) { iterations in
124
+ for _ in 0..<iterations {
125
+ module.emit(event: "object", payload: payload)
126
+ }
127
+ }
128
+ }
129
+ }
130
+ }
131
+
132
+ @Test
133
+ func `emit: [String: Any] payload`() async throws {
134
+ try await eventBenchmarkCase { module, runtime in
135
+ // `[String: Any]` isn't `Sendable`, so an `@Event` with this payload type doesn't compile.
136
+ try benchmark("emit: [String: Any] payload", runtime: runtime) { iterations in
137
+ for index in 0..<iterations {
138
+ module.emit(event: "dictionary", payload: ["percent": index, "label": "loading"] as [String: Any])
139
+ }
140
+ }
141
+ }
142
+ }
143
+
144
+ @Test
145
+ func `emit: [String: String] payload through @Event`() async throws {
146
+ try await eventBenchmarkCase { module, runtime in
147
+ try benchmark("emit: [String: String] payload through @Event", runtime: runtime) { iterations in
148
+ for _ in 0..<iterations {
149
+ module.onStrings(["state": "loading", "label": "file"])
150
+ }
151
+ }
152
+ }
153
+ }
89
154
  }
90
155
 
91
156
  @Record
@@ -94,6 +159,8 @@ private struct ProgressPayload {
94
159
  var label: String = ""
95
160
  }
96
161
 
162
+ private final class EventPayloadObject: SharedObject {}
163
+
97
164
  @ExpoModule
98
165
  private final class EventBenchmarkModule: Module {
99
166
  @Event
@@ -104,6 +171,9 @@ private final class EventBenchmarkModule: Module {
104
171
 
105
172
  @Event
106
173
  var onProgress: (ProgressPayload) -> Void
174
+
175
+ @Event
176
+ var onStrings: ([String: String]) -> Void
107
177
  }
108
178
 
109
179
  @ExpoModule
@@ -127,6 +197,9 @@ private func eventBenchmarkCase(
127
197
  expo.modules.EventBenchmarkModule.addListener('ping', listener);
128
198
  expo.modules.EventBenchmarkModule.addListener('count', listener);
129
199
  expo.modules.EventBenchmarkModule.addListener('progress', listener);
200
+ expo.modules.EventBenchmarkModule.addListener('object', listener);
201
+ expo.modules.EventBenchmarkModule.addListener('dictionary', listener);
202
+ expo.modules.EventBenchmarkModule.addListener('strings', listener);
130
203
  """
131
204
  )
132
205
  try body(module, runtime)
@@ -93,6 +93,34 @@ extension Benchmarks {
93
93
  }
94
94
  }
95
95
 
96
+ /// Benchmarks for encoding an array of records in Swift, with no JavaScript call around it.
97
+ extension Benchmarks {
98
+ @Test(arguments: [10, 1000])
99
+ func `encode an array of records`(count: Int) async throws {
100
+ try await recordBenchmarkCase { runtime in
101
+ let points = (0..<count).map { BenchmarkPoint(x: Double($0), y: Double($0)) }
102
+ try benchmark("[Record].encode: \(count) records", runtime: runtime) { iterations in
103
+ for _ in 0..<iterations {
104
+ _ = try [BenchmarkPoint].encode(points, in: runtime)
105
+ }
106
+ }
107
+ }
108
+ }
109
+ }
110
+
111
+ /// Runs one case with the runtime of a new app context.
112
+ private func recordBenchmarkCase(
113
+ _ measure: @escaping @JavaScriptActor (JavaScriptRuntime) throws -> Void
114
+ ) async throws {
115
+ try await benchmarkCase {
116
+ let appContext = AppContext.create()
117
+ let runtime = try appContext.runtime
118
+ try withExtendedLifetime(appContext) {
119
+ try measure(runtime)
120
+ }
121
+ }
122
+ }
123
+
96
124
  @Record
97
125
  private struct BenchmarkPoint {
98
126
  var x: Double = 0
@@ -5,9 +5,18 @@ import Testing
5
5
 
6
6
  @testable import ExpoModulesCore
7
7
 
8
- /// Benchmarks for JavaScript using a `@SharedObject` class: creating instances, getting them from a `@JS`
9
- /// function and calling their `@JS` members. A JavaScript driver runs the measured loop. Read every result
10
- /// against `JS: empty driver loop`.
8
+ /// Benchmarks for JavaScript using a `@SharedObject` class: creating, releasing and collecting instances,
9
+ /// reading their IDs, passing them to and getting them from `@JS` functions, and calling their `@JS` members.
10
+ /// A JavaScript driver runs the measured loop, so read these results against `JS: empty driver loop`.
11
+ ///
12
+ /// Notes on reading the results:
13
+ /// - `new instance and garbage collection` adds one full collection to each sample and spreads its cost over
14
+ /// the instances created in the sample. It shows whether collecting shared objects got cheaper, not the
15
+ /// exact cost of finalizing one instance.
16
+ /// - `existing instance returned from a function` includes decoding the argument, which
17
+ /// `instance passed as an argument` measures alone.
18
+ /// - `emit: Int payload from a @SharedObject` emits from Swift in a loop, without the JavaScript driver.
19
+ /// Read it against `emit: Int payload`, which emits the same payload from a module.
11
20
  extension Benchmarks {
12
21
  @Test
13
22
  func `@SharedObject: new instance`() async throws {
@@ -18,6 +27,25 @@ extension Benchmarks {
18
27
  }
19
28
  }
20
29
 
30
+ @Test
31
+ func `@SharedObject: new instance and release`() async throws {
32
+ try await sharedObjectBenchmarkCase(body: "new Counter(i).release();") { run, runtime in
33
+ try benchmark("@SharedObject: new instance and release", runtime: runtime) { iterations in
34
+ _ = try run.call(arguments: iterations)
35
+ }
36
+ }
37
+ }
38
+
39
+ @Test
40
+ func `@SharedObject: new instance and garbage collection`() async throws {
41
+ try await sharedObjectBenchmarkCase(body: "new Counter(i);") { run, runtime in
42
+ try benchmark("@SharedObject: new instance and garbage collection", runtime: runtime) { iterations in
43
+ _ = try run.call(arguments: iterations)
44
+ runtime.collectGarbage()
45
+ }
46
+ }
47
+ }
48
+
21
49
  @Test
22
50
  func `@SharedObject: instance returned from a function`() async throws {
23
51
  try await sharedObjectBenchmarkCase(body: "m.makeCounter(i);") { run, runtime in
@@ -36,6 +64,62 @@ extension Benchmarks {
36
64
  }
37
65
  }
38
66
 
67
+ @Test
68
+ func `@SharedObject: new instance and ID read`() async throws {
69
+ try await sharedObjectBenchmarkCase(body: "new Counter(i).__expo_shared_object_id__;") { run, runtime in
70
+ try benchmark("@SharedObject: new instance and ID read", runtime: runtime) { iterations in
71
+ _ = try run.call(arguments: iterations)
72
+ }
73
+ }
74
+ }
75
+
76
+ @Test
77
+ func `@SharedObject: ID read`() async throws {
78
+ try await sharedObjectBenchmarkCase(body: "counter.__expo_shared_object_id__;") { run, runtime in
79
+ try benchmark("@SharedObject: ID read", runtime: runtime) { iterations in
80
+ _ = try run.call(arguments: iterations)
81
+ }
82
+ }
83
+ }
84
+
85
+ @Test
86
+ func `@SharedObject: instance passed as an argument`() async throws {
87
+ try await sharedObjectBenchmarkCase(body: "m.readCounter(counter);") { run, runtime in
88
+ try benchmark("@SharedObject: instance passed as an argument", runtime: runtime) { iterations in
89
+ _ = try run.call(arguments: iterations)
90
+ }
91
+ }
92
+ }
93
+
94
+ @Test
95
+ func `@SharedObject: existing instance returned from a function`() async throws {
96
+ try await sharedObjectBenchmarkCase(body: "m.echoCounter(counter);") { run, runtime in
97
+ try benchmark("@SharedObject: existing instance returned from a function", runtime: runtime) { iterations in
98
+ _ = try run.call(arguments: iterations)
99
+ }
100
+ }
101
+ }
102
+
103
+ @Test
104
+ func `emit: Int payload from a @SharedObject`() async throws {
105
+ try await moduleBenchmarkCase { appContext in
106
+ return SharedObjectBenchmarkModule(appContext: appContext)
107
+ } _: { _, runtime in
108
+ let counterObject = try runtime.eval([
109
+ "var counter = new expo.modules.SharedObjectBenchmarkModule.BenchmarkCounter(0)",
110
+ "counter.addListener('count', () => {})",
111
+ "counter"
112
+ ]).asObject()
113
+ let counter = try SharedObject.native(from: counterObject)
114
+
115
+ try benchmark("emit: Int payload from a @SharedObject", runtime: runtime) { iterations in
116
+ for index in 0..<iterations {
117
+ counter.emit(event: "count", payload: index)
118
+ }
119
+ }
120
+ }
121
+ }
122
+
39
123
  @Test
40
124
  func `@SharedObject: method call`() async throws {
41
125
  try await sharedObjectBenchmarkCase(body: "counter.increment(1);") { run, runtime in
@@ -87,6 +171,16 @@ private final class SharedObjectBenchmarkModule: Module {
87
171
  func makeRef(value: Int) -> SharedRef<Int> {
88
172
  return SharedRef(value)
89
173
  }
174
+
175
+ @JS
176
+ func readCounter(counter: BenchmarkCounter) -> Int {
177
+ return counter.current
178
+ }
179
+
180
+ @JS
181
+ func echoCounter(counter: BenchmarkCounter) -> BenchmarkCounter {
182
+ return counter
183
+ }
90
184
  }
91
185
 
92
186
  /// Runs one case with `SharedObjectBenchmarkModule` registered and a JavaScript driver that runs `body`
@@ -582,12 +582,9 @@ public class AppContext: NSObject, EXAppContextProtocol, @unchecked Sendable {
582
582
  }) {
583
583
  instance = cachedInstance
584
584
  } else {
585
- guard let classDefinition = self.findClassDefinition(for: typeId) else {
586
- throw SharedObjectClassNotRegisteredException(String(describing: type(of: nativeObject)))
587
- }
588
- let built = try classDefinition.buildPrototype(
585
+ let built = try self.buildWorkletPrototype(
586
+ for: type(of: nativeObject),
589
587
  in: runtime,
590
- appContext: self,
591
588
  basePrototype: sharedObjectBaseProto.getObject()
592
589
  )
593
590
  instance = runtime.createObject(prototype: built)
@@ -601,6 +598,25 @@ public class AppContext: NSObject, EXAppContextProtocol, @unchecked Sendable {
601
598
  sharedObjectClass.setProperty("__resolveInWorklet", value: resolveInWorklet.asObject())
602
599
  }
603
600
 
601
+ /// Builds the worklet prototype for a native shared object class, from the `ClassDefinition` of a module
602
+ /// that defines it or from a module that registers it in `_classTypes`.
603
+ @JavaScriptActor
604
+ private func buildWorkletPrototype(
605
+ for nativeType: SharedObject.Type,
606
+ in runtime: JavaScriptRuntime,
607
+ basePrototype: consuming JavaScriptObject
608
+ ) throws -> JavaScriptObject {
609
+ let typeId = ObjectIdentifier(nativeType)
610
+
611
+ if let classDefinition = findClassDefinition(for: typeId) {
612
+ return try classDefinition.buildPrototype(in: runtime, appContext: self, basePrototype: basePrototype)
613
+ }
614
+ if let classType = findClassType(for: typeId) {
615
+ return try JavaScriptBindings.buildSharedObjectPrototype(classType, in: runtime, basePrototype: basePrototype)
616
+ }
617
+ throw SharedObjectClassNotRegisteredException(String(describing: nativeType))
618
+ }
619
+
604
620
  /**
605
621
  Finds the ClassDefinition for a given native type identifier by searching all modules.
606
622
  */
@@ -616,6 +632,17 @@ public class AppContext: NSObject, EXAppContextProtocol, @unchecked Sendable {
616
632
  return nil
617
633
  }
618
634
 
635
+ /// Finds the `@SharedObject` class for a given native type identifier among the classes that modules
636
+ /// register in `_classTypes`.
637
+ private func findClassType(for typeId: ObjectIdentifier) -> SharedObject.Type? {
638
+ for module in moduleRegistry {
639
+ if let classType = type(of: module.module)._classTypes.first(where: { ObjectIdentifier($0) == typeId }) {
640
+ return classType
641
+ }
642
+ }
643
+ return nil
644
+ }
645
+
619
646
  /**
620
647
  Unsets runtime objects that we hold for each module.
621
648
  */
@@ -9,6 +9,9 @@ import ExpoModulesJSI
9
9
  public final class ArrayBuffer: AnyArrayBuffer, Sendable {
10
10
  private let storage: ArrayBufferStorage
11
11
 
12
+ /// Whether a live JavaScript array buffer reports this buffer's memory to the garbage collector.
13
+ private let isMemoryReported = Mutex(false)
14
+
12
15
  private var rawPointer: UnsafeMutableRawPointer {
13
16
  return storage.rawPointer
14
17
  }
@@ -86,14 +89,34 @@ public final class ArrayBuffer: AnyArrayBuffer, Sendable {
86
89
  /// The native buffer is retained for the lifetime of the `JavaScriptArrayBuffer`.
87
90
  @usableFromInline
88
91
  func asJavaScriptArrayBuffer(runtime: JavaScriptRuntime) -> JavaScriptArrayBuffer {
89
- return runtime.createArrayBuffer(
92
+ // The garbage collector does not see native memory, so one live JavaScript array buffer reports it.
93
+ // Reporting it for every wrapper would add the full size each time the same buffer is returned.
94
+ // Borrowed memory belongs to another JavaScript array buffer, which accounts for it.
95
+ let reportsMemory =
96
+ storage.ownsMemory && byteLength > 0
97
+ && isMemoryReported.withLock { isReported in
98
+ if isReported {
99
+ return false
100
+ }
101
+ isReported = true
102
+ return true
103
+ }
104
+ let jsArrayBuffer = runtime.createArrayBuffer(
90
105
  data: rawPointer.assumingMemoryBound(to: UInt8.self),
91
106
  size: byteLength
92
107
  ) { [self] in
93
108
  // Retain `self` until the JS engine releases the ArrayBuffer. When this
94
109
  // closure is dropped, the buffer deinits and deallocates its memory.
95
- _ = self
110
+ if reportsMemory {
111
+ isMemoryReported.withLock { isReported in
112
+ isReported = false
113
+ }
114
+ }
96
115
  }
116
+ if reportsMemory {
117
+ jsArrayBuffer.asValue().getObject().setExternalMemoryPressure(byteLength)
118
+ }
119
+ return jsArrayBuffer
97
120
  }
98
121
 
99
122
  // MARK: - Copy
@@ -147,10 +170,16 @@ public final class ArrayBuffer: AnyArrayBuffer, Sendable {
147
170
  /// - Warning: This bypasses Data's copy-on-write capabilities, effectively allowing
148
171
  /// mutation of the Data from JavaScript code.
149
172
  public static func wrap(dataWithoutCopy data: Data) -> ArrayBuffer {
150
- let retained = Unmanaged.passRetained(data as NSData)
151
- let pointer = UnsafeMutableRawPointer(mutating: retained.takeUnretainedValue().bytes)
152
- return ArrayBuffer(owning: pointer, count: data.count) {
153
- retained.release()
173
+ // `NSData.bytes` returns an inner pointer, so the call retains and autoreleases the `NSData`, which
174
+ // owns the bytes. Without this pool, the bytes stay alive until the caller's pool drains, which never
175
+ // happens while a caller such as a JavaScript loop does not return to its run loop. `retained` keeps
176
+ // the `NSData` alive after this pool drains.
177
+ return autoreleasepool {
178
+ let retained = Unmanaged.passRetained(data as NSData)
179
+ let pointer = UnsafeMutableRawPointer(mutating: retained.takeUnretainedValue().bytes)
180
+ return ArrayBuffer(owning: pointer, count: data.count) {
181
+ retained.release()
182
+ }
154
183
  }
155
184
  }
156
185
 
@@ -305,6 +334,15 @@ private enum ArrayBufferStorage: Sendable {
305
334
  }
306
335
  }
307
336
 
337
+ var ownsMemory: Bool {
338
+ switch self {
339
+ case .ownedNative:
340
+ return true
341
+ case .nativeBacked:
342
+ return false
343
+ }
344
+ }
345
+
308
346
  func cleanup() {
309
347
  switch self {
310
348
  case .ownedNative(let storage), .nativeBacked(let storage):