expo-modules-core 58.0.29 → 58.1.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.
Files changed (32) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/ExpoModulesCore.podspec +6 -8
  3. package/android/build.gradle +2 -2
  4. package/android/prebuilt/metadata.json +1 -1
  5. package/android/prebuilt/native-libs.tar.xz +0 -0
  6. package/android/src/main/java/expo/modules/adapters/react/apploader/RNHeadlessAppLoader.kt +2 -3
  7. package/ios/Benchmarks/FunctionBenchmarks.swift +2 -14
  8. package/ios/Core/AppContext.swift +29 -2
  9. package/ios/Core/Arguments/Convertibles.swift +1 -24
  10. package/ios/Core/Coding/JavaScriptCodable+Color.swift +887 -0
  11. package/ios/Core/Coding/JavaScriptCodable+URL.swift +55 -0
  12. package/ios/Core/Convertibles/Convertibles+Color.swift +10 -686
  13. package/ios/Core/Events/EventEmitter.swift +194 -1
  14. package/ios/Core/ExpoModulesMacros.swift +50 -8
  15. package/ios/Core/ExpoPackage.swift +29 -0
  16. package/ios/Core/Logging/Logger.swift +8 -2
  17. package/ios/Core/ModulesProvider.swift +19 -0
  18. package/ios/Core/Records/Record.swift +18 -6
  19. package/ios/Core/SharedObjects/SharedObjectRegistry.swift +28 -16
  20. package/ios/Core/Views/SwiftUI/Convertibles+SwiftUI.swift +2 -67
  21. package/ios/Core/Views/SwiftUI/SwiftUIHostingView.swift +1 -0
  22. package/ios/Core/Views/SwiftUI/SwiftUIViewHost.swift +100 -39
  23. package/ios/Core/Views/SwiftUI/SwiftUIVirtualView.swift +1 -0
  24. package/ios/ReactDelegates/ExpoReactDelegate.swift +1 -1
  25. package/ios/ReactDelegates/ExpoRootViewController.swift +22 -0
  26. package/package.json +4 -4
  27. package/prebuilds/output/debug/xcframeworks/ExpoModulesCore.tar.gz +0 -0
  28. package/prebuilds/output/debug/xcframeworks/ExpoModulesWorklets.tar.gz +0 -0
  29. package/prebuilds/output/headers/xcframeworks/ExpoModulesCoreHeaders.tar.gz +0 -0
  30. package/prebuilds/output/release/xcframeworks/ExpoModulesCore.tar.gz +0 -0
  31. package/prebuilds/output/release/xcframeworks/ExpoModulesWorklets.tar.gz +0 -0
  32. package/spm.config.json +4 -1
@@ -172,6 +172,184 @@ public extension EventEmitter {
172
172
  }
173
173
  }
174
174
 
175
+ public extension EventEmitter {
176
+ /// Emits an event with the given name to the associated JavaScript object. On the JavaScript thread,
177
+ /// the listeners run before this function returns; on any other thread, the event is scheduled, the
178
+ /// same as with `emit`. It never blocks. The `@Event(.inline)` macro calls it.
179
+ @inlinable
180
+ func emitInline(event: String) {
181
+ emitInline(event: event, payload: JavaScriptUndefined())
182
+ }
183
+
184
+ /// Emits an event with the given name and payload to the associated JavaScript object. On the
185
+ /// JavaScript thread, the payload is converted and the listeners run before this function returns; on
186
+ /// any other thread, the event is scheduled, the same as with `emit`. It never blocks.
187
+ ///
188
+ /// Listeners that run inline can call back into the emitter before this function returns, so emit
189
+ /// after the emitter's state is up to date. On the JavaScript thread, the event can reach the
190
+ /// listeners before events that `emit` scheduled earlier. An event emitted before the emitter is paired
191
+ /// with its JavaScript object, for example from a shared object's initializer, is dropped.
192
+ @inlinable
193
+ func emitInline<P: JavaScriptEncodable & ~Copyable>(event: String, payload: consuming sending P) {
194
+ emitInline(event: event, payload: payload) { payload, slot, runtime in
195
+ try P.encode(payload, into: slot, in: runtime)
196
+ }
197
+ }
198
+
199
+ /// Emits an event like `emitInline(event:payload:)`, converting the payload with `encode`. The
200
+ /// `@Event(.inline)` macro uses it for payload types that can't conform to `JavaScriptEncodable`, such
201
+ /// as tuples.
202
+ @inlinable
203
+ func emitInline<P: ~Copyable>(
204
+ event: String,
205
+ payload: consuming sending P,
206
+ encode: @escaping @JavaScriptActor @Sendable (consuming P, borrowing JavaScriptValue.Slot, borrowing JavaScriptRuntime)
207
+ throws -> Void
208
+ ) {
209
+ guard let runtime = eventRuntime(forEvent: event) else {
210
+ return
211
+ }
212
+ // See the note in `emit(event:payload:)` above.
213
+ let emitter = WeakEventEmitterReference(value: self)
214
+ var payload: P? = payload
215
+ if runtime.isOnJavaScriptThread() {
216
+ // Emits right away, without the closure and the box that scheduling needs.
217
+ JavaScriptActor.assumeIsolated {
218
+ guard let emitter = emitter.value else {
219
+ return
220
+ }
221
+ emitEventNow(event: event, payload: &payload, encode: encode, from: emitter, in: runtime)
222
+ }
223
+ return
224
+ }
225
+ // An escaping closure can't consume a captured non-copyable value, so the payload moves into a box.
226
+ let box = EventPayloadBox(payload)
227
+
228
+ runtime.schedule {
229
+ guard let emitter = emitter.value else {
230
+ return
231
+ }
232
+ emitEventNow(event: event, payload: &box.value, encode: encode, from: emitter, in: runtime)
233
+ }
234
+ }
235
+
236
+ /// Emits an event with the given name to the associated JavaScript object. The listeners run before
237
+ /// this function returns, on any thread: a call from another thread blocks until the JavaScript thread
238
+ /// runs them. The `@Event(.blocking)` macro calls it.
239
+ @available(*, noasync)
240
+ @inlinable
241
+ func emitBlocking(event: String) {
242
+ emitBlocking(event: event, payload: JavaScriptUndefined())
243
+ }
244
+
245
+ /// Emits an event with the given name and payload to the associated JavaScript object. The payload is
246
+ /// converted and the listeners run before this function returns, on any thread: on the JavaScript
247
+ /// thread they run inline, and a call from another thread blocks until the JavaScript thread runs them.
248
+ ///
249
+ /// A call from another thread waits for the task that the JavaScript thread is running, so a call from
250
+ /// the main thread freezes the UI while the JavaScript thread is busy, for example while it loads the
251
+ /// bundle. It deadlocks when the JavaScript thread is waiting for the calling thread, for example when
252
+ /// a synchronous function waits for the main thread with `DispatchQueue.main.sync` while the main
253
+ /// thread emits. The event is scheduled with immediate priority, so it can reach the listeners before
254
+ /// events that `emit` scheduled earlier. Use `emitInline(event:payload:)` when the caller doesn't need
255
+ /// to wait.
256
+ ///
257
+ /// `noasync` covers direct calls only. An `@Event(.blocking)` property calls this method from the
258
+ /// closure it returns, so calling the property from an `async` function compiles and blocks a thread
259
+ /// of the cooperative pool.
260
+ @available(*, noasync)
261
+ @inlinable
262
+ func emitBlocking<P: JavaScriptEncodable & ~Copyable>(event: String, payload: consuming sending P) {
263
+ emitBlocking(event: event, payload: payload) { payload, slot, runtime in
264
+ try P.encode(payload, into: slot, in: runtime)
265
+ }
266
+ }
267
+
268
+ /// Emits an event like `emitBlocking(event:payload:)`, converting the payload with `encode`. The
269
+ /// `@Event(.blocking)` macro uses it for payload types that can't conform to `JavaScriptEncodable`,
270
+ /// such as tuples.
271
+ @available(*, noasync)
272
+ @inlinable
273
+ func emitBlocking<P: ~Copyable>(
274
+ event: String,
275
+ payload: consuming sending P,
276
+ encode: @escaping @JavaScriptActor @Sendable (consuming P, borrowing JavaScriptValue.Slot, borrowing JavaScriptRuntime)
277
+ throws -> Void
278
+ ) {
279
+ guard let runtime = eventRuntime(forEvent: event) else {
280
+ return
281
+ }
282
+ // See the note in `emit(event:payload:)` above.
283
+ let emitter = WeakEventEmitterReference(value: self)
284
+ var payload: P? = payload
285
+ if runtime.isOnJavaScriptThread() {
286
+ // See the note in `emitInline(event:payload:encode:)` above.
287
+ JavaScriptActor.assumeIsolated {
288
+ guard let emitter = emitter.value else {
289
+ return
290
+ }
291
+ emitEventNow(event: event, payload: &payload, encode: encode, from: emitter, in: runtime)
292
+ }
293
+ return
294
+ }
295
+ // See the note in `emitInline(event:payload:encode:)` above.
296
+ let box = EventPayloadBox(payload)
297
+
298
+ do {
299
+ try runtime.execute {
300
+ guard let emitter = emitter.value else {
301
+ return
302
+ }
303
+ emitEventNow(event: event, payload: &box.value, encode: encode, from: emitter, in: runtime)
304
+ }
305
+ } catch {
306
+ warnRuntimeLost(event: event, emitterType: type(of: self))
307
+ }
308
+ }
309
+ }
310
+
311
+ /// Holds an event payload until the JavaScript thread takes it, so a closure that escapes can carry a
312
+ /// non-copyable payload. The payload is taken once, on the JavaScript thread.
313
+ @usableFromInline
314
+ internal final class EventPayloadBox<P: ~Copyable>: @unchecked Sendable {
315
+ @usableFromInline
316
+ var value: P?
317
+
318
+ // Not `@inlinable`: with library evolution, an inlinable initializer of a class must delegate to
319
+ // another initializer.
320
+ @usableFromInline
321
+ init(_ value: consuming P?) {
322
+ self.value = consume value
323
+ }
324
+ }
325
+
326
+ /// Takes the payload out of `payload`, converts it with `encode` and sends it to the JavaScript object of
327
+ /// the emitter. Logs a warning when the conversion fails.
328
+ @JavaScriptActor
329
+ @inlinable
330
+ internal func emitEventNow<P: ~Copyable>(
331
+ event: String,
332
+ payload: inout P?,
333
+ encode: (consuming P, borrowing JavaScriptValue.Slot, borrowing JavaScriptRuntime) throws -> Void,
334
+ from emitter: any EventEmitter,
335
+ in runtime: JavaScriptRuntime
336
+ ) {
337
+ guard payload != nil else {
338
+ return
339
+ }
340
+ let jsPayload: JavaScriptValue
341
+ do {
342
+ // A closure can't consume a captured non-copyable value, but it can take it out of an optional.
343
+ jsPayload = try JavaScriptValue.encoding(in: runtime) { slot in
344
+ try encode(payload.take()!, slot, runtime)
345
+ }
346
+ } catch {
347
+ warnNonCopyablePayloadNotEncoded(event: event, payloadType: P.self, error: error)
348
+ return
349
+ }
350
+ dispatchEvent(event: event, payload: jsPayload, from: emitter, in: runtime)
351
+ }
352
+
175
353
  /// A weak reference to an event emitter that the scheduled `emit` closures capture by value, so it is stored
176
354
  /// in the closure context without an allocation of its own. Frozen, because with library evolution the
177
355
  /// inlinable initializer can't assign the stored property of a struct whose layout isn't fixed.
@@ -192,13 +370,19 @@ extension EventEmitter {
192
370
  @usableFromInline
193
371
  internal func eventRuntime(forEvent event: String) -> JavaScriptRuntime? {
194
372
  guard let appContext, let runtime = try? appContext.runtime else {
195
- log.warn("Trying to send event '\(event)' to \(type(of: self)), but the JS runtime has been lost")
373
+ warnRuntimeLost(event: event, emitterType: type(of: self))
196
374
  return nil
197
375
  }
198
376
  return runtime
199
377
  }
200
378
  }
201
379
 
380
+ /// Logs that the runtime was lost before an event could be emitted.
381
+ @usableFromInline
382
+ internal func warnRuntimeLost(event: String, emitterType: Any.Type) {
383
+ log.warn("Trying to send event '\(event)' to \(emitterType), but the JS runtime has been lost")
384
+ }
385
+
202
386
  /// Logs that the payload of an event couldn't be converted, so the event is not emitted.
203
387
  @usableFromInline
204
388
  internal func warnPayloadNotEncoded(event: String, payloadType: Any.Type, error: any Error) {
@@ -207,6 +391,15 @@ internal func warnPayloadNotEncoded(event: String, payloadType: Any.Type, error:
207
391
  )
208
392
  }
209
393
 
394
+ /// Logs that the payload of an event couldn't be converted, like `warnPayloadNotEncoded`, for a payload
395
+ /// type that may be non-copyable: such a metatype doesn't convert to `Any.Type`.
396
+ @usableFromInline
397
+ internal func warnNonCopyablePayloadNotEncoded(event: String, payloadType: any (~Copyable).Type, error: any Error) {
398
+ log.warn(
399
+ "Failed to convert payload for event '\(event)' on \(payloadType); the event will not be emitted: \(error)"
400
+ )
401
+ }
402
+
210
403
  /// Sends a pre-converted event payload to the JavaScript object of the given emitter. Logs a warning
211
404
  /// when the emitter is no longer associated with a JavaScript object.
212
405
  @JavaScriptActor
@@ -87,6 +87,29 @@ public macro JS(_ jsName: String? = nil, _ options: JSOptions...) =
87
87
  public macro JS(_ options: JSOptions...) =
88
88
  #externalMacro(module: "ExpoModulesMacros", type: "JSMacro")
89
89
 
90
+ /// Options passed to `@Event` after the optional JS name, e.g. `@Event(.inline)` or
91
+ /// `@Event("tick", .blocking)`. The macro reads them from the source, so spell them as `.option`
92
+ /// literals rather than constants. Without an option, the event is scheduled on the JavaScript thread
93
+ /// and the listeners run later. An event property is callable from any thread with each option.
94
+ public enum EventOptions {
95
+ /// Runs the listeners before the call returns when it is made on the JavaScript thread, for example
96
+ /// from a synchronous function. On any other thread, the event is scheduled, the same as without an
97
+ /// option. It never blocks. The listeners can call back into the module or shared object before the
98
+ /// call returns, so emit after its state is up to date. On the JavaScript thread, the event can reach
99
+ /// the listeners before events emitted earlier without an option. An event emitted before the shared
100
+ /// object is paired with its JavaScript object, for example from its initializer, is dropped.
101
+ case inline
102
+
103
+ /// Runs the listeners before the call returns, on any thread. A call from another thread blocks until
104
+ /// the JavaScript thread runs them: from the main thread it freezes the UI while the JavaScript thread
105
+ /// is busy, and it deadlocks when the JavaScript thread is waiting for the calling thread, for example
106
+ /// in `DispatchQueue.main.sync` while the main thread emits. The event can reach the listeners before
107
+ /// events emitted earlier without an option. Don't call the property from an `async` function: it
108
+ /// would block a thread of the cooperative pool, and the compiler doesn't report it. Prefer `.inline`
109
+ /// unless the caller must wait for the listeners.
110
+ case blocking
111
+ }
112
+
90
113
  /// Turns a function-typed `var` on a module or shared object into a typed JavaScript event.
91
114
  /// Calling the property emits the event to JavaScript, with the closure's parameter as the payload.
92
115
  ///
@@ -101,9 +124,17 @@ public macro JS(_ options: JSOptions...) =
101
124
  ///
102
125
  /// // Emit it from anywhere:
103
126
  /// onProgress(ProgressEvent(percent: 50))
127
+ ///
128
+ /// Trailing `EventOptions` tune the event. The options-only overload exists because an option can't
129
+ /// fill the unlabeled `name` slot.
130
+ @attached(accessor)
131
+ @attached(peer, names: arbitrary)
132
+ public macro Event(_ name: String? = nil, _ options: EventOptions...) =
133
+ #externalMacro(module: "ExpoModulesMacros", type: "EventMacro")
134
+
104
135
  @attached(accessor)
105
136
  @attached(peer, names: arbitrary)
106
- public macro Event(_ name: String? = nil, sync: Bool = false) =
137
+ public macro Event(_ options: EventOptions...) =
107
138
  #externalMacro(module: "ExpoModulesMacros", type: "EventMacro")
108
139
 
109
140
  /// Member macro applied to a `Module` subclass. Scans the class body for declarations
@@ -115,6 +146,11 @@ public macro Event(_ name: String? = nil, sync: Bool = false) =
115
146
  /// is no `Name(…)` DSL entry. It defaults to the class name; pass `@ExpoModule("CustomName")` to
116
147
  /// override it.
117
148
  ///
149
+ /// The class gets an `@unchecked Sendable` conformance when it isn't `Sendable` yet, because native
150
+ /// code calls the module from more than one thread (for example a `.withAsync` variant runs on the
151
+ /// concurrent thread pool). Keep mutable state that more than one thread uses behind a lock or an
152
+ /// actor.
153
+ ///
118
154
  /// Usage:
119
155
  ///
120
156
  /// @ExpoModule
@@ -128,7 +164,7 @@ public macro Event(_ name: String? = nil, sync: Bool = false) =
128
164
  named(_jsName), named(_classTypes), named(appContext), named(init),
129
165
  named(_decorateModule), named(_assertTypesConformance))
130
166
  @attached(memberAttribute)
131
- @attached(extension, conformances: AnyModule)
167
+ @attached(extension, conformances: AnyModule, Sendable)
132
168
  public macro ExpoModule(_ name: String? = nil, classes: [Any.Type] = []) =
133
169
  #externalMacro(module: "ExpoModulesMacros", type: "ExpoModuleMacro")
134
170
 
@@ -145,6 +181,9 @@ public macro ExpoModule(_ name: String? = nil, classes: [Any.Type] = []) =
145
181
  /// JS arguments. Core calls them when building the class. The class must be a `SharedObject`
146
182
  /// subclass, direct or not, or the `_jsName` override doesn't compile.
147
183
  ///
184
+ /// Like `@ExpoModule`, the macro adds an `@unchecked Sendable` conformance when the class isn't
185
+ /// `Sendable` yet.
186
+ ///
148
187
  /// Usage:
149
188
  ///
150
189
  /// @SharedObject
@@ -164,18 +203,21 @@ public macro ExpoModule(_ name: String? = nil, classes: [Any.Type] = []) =
164
203
  named(_jsName), named(_decorateSharedObject), named(_constructSharedObject),
165
204
  named(_assertTypesConformance))
166
205
  @attached(memberAttribute)
206
+ @attached(extension, conformances: Sendable)
167
207
  public macro SharedObject(_ name: String? = nil) =
168
208
  #externalMacro(module: "ExpoModulesMacros", type: "SharedObjectMacro")
169
209
 
170
210
  /// Member + extension macro applied to a record `struct` or `class`. Every non-`static`,
171
211
  /// non-`private`/`fileprivate`, non-`lazy`, non-computed stored property is part of the record — no
172
212
  /// `@Field` wrapper needed — and the macro synthesizes the whole conversion surface from each
173
- /// property's static type: a memberwise `init`, the `from(object:appContext:)` /
174
- /// `from(dictionary:appContext:)` factories, the `toDictionary(appContext:)` /
175
- /// `toObject(appContext:)` write side, and the `JavaScriptDecodable` / `JavaScriptEncodable`
176
- /// conversions `decode(_:in:)` and `encode(_:in:)`. The type is auto-conformed to `Record`; the
177
- /// synthesized methods override `Record`'s reflection-based defaults, so it stays usable anywhere a
178
- /// `Record` argument is expected.
213
+ /// property's static type: a memberwise `init`, `from(object:appContext:)`,
214
+ /// `toDictionary(appContext:)` / `toObject(appContext:)`, and the `JavaScriptDecodable` /
215
+ /// `JavaScriptEncodable` conversions `decode(_:in:)` and `encode(_:in:)`. The type is auto-conformed to
216
+ /// `Record`; the synthesized methods override `Record`'s reflection-based defaults, so it stays usable
217
+ /// anywhere a `Record` argument is expected.
218
+ ///
219
+ /// A record converts only from and to JavaScript values. The synthesized `from(dictionary:appContext:)`
220
+ /// throws `RecordDictionaryConversionException`, so a record can't be created from a native dictionary.
179
221
  ///
180
222
  /// `decode(_:in:)` and `encode(_:in:)` use the runtime they receive and don't need an app context, so
181
223
  /// the record converts on any runtime. A class with an inheritance clause doesn't get them, so it
@@ -0,0 +1,29 @@
1
+ // Copyright 2026-present 650 Industries. All rights reserved.
2
+
3
+ /**
4
+ The native exports of one npm package that are declared with the Expo Modules API 2.0 macros: its modules
5
+ and shared object classes. A modules provider returns the packages keyed by the npm package name, and that name
6
+ is the JS name of the package.
7
+ Local and inline modules are in the `$local` package.
8
+ */
9
+ public struct ExpoPackage {
10
+ /**
11
+ Name of the package of local and inline modules. It can't be the name of an npm package.
12
+ */
13
+ public static let localPackageName = "$local"
14
+
15
+ /**
16
+ Module classes of the package.
17
+ */
18
+ public let modules: [AnyModule.Type]
19
+
20
+ /**
21
+ Shared object classes of the package. They are exported next to the modules, not as members of a module.
22
+ */
23
+ public let sharedObjects: [SharedObject.Type]
24
+
25
+ public init(modules: [AnyModule.Type] = [], sharedObjects: [SharedObject.Type] = []) {
26
+ self.modules = modules
27
+ self.sharedObjects = sharedObjects
28
+ }
29
+ }
@@ -14,10 +14,16 @@ public class Logger: @unchecked Sendable {
14
14
  public static let EXPO_MODULES_LOG_SUBSYSTEM = "dev.expo.modules"
15
15
  public static let EXPO_LOG_CATEGORY = "expo"
16
16
 
17
+ /**
18
+ The least severe log type this logger passes to its handlers. Defaults to `.trace` in debug builds
19
+ and `.info` in release builds. Apps can raise it, for example with `log.minLevel = .error` before
20
+ the React Native host starts, to keep less severe logs of the shared `log` instance out of the
21
+ device log. Set it once at launch: changes are not synchronized with logging on other threads.
22
+ */
17
23
  #if DEBUG || EXPO_CONFIGURATION_DEBUG
18
- private var minLevel: LogType = .trace
24
+ public var minLevel: LogType = .trace
19
25
  #else
20
- private var minLevel: LogType = .info
26
+ public var minLevel: LogType = .info
21
27
  #endif
22
28
 
23
29
  private let logHandlers: [LogHandler]
@@ -6,6 +6,12 @@ import Foundation
6
6
  public protocol ModulesProviderProtocol {
7
7
  typealias ExpoModuleTupleType = (module: AnyModule.Type, name: String?)
8
8
 
9
+ /**
10
+ The packages that provide modules declared with the Expo Modules API 2.0 macros, keyed by the npm package name.
11
+ Their modules are also in `getModuleClasses()`, which is the list that the module registry registers.
12
+ */
13
+ var packages: [String: ExpoPackage] { get }
14
+
9
15
  func getModuleClasses() -> [ExpoModuleTupleType]
10
16
 
11
17
  /**
@@ -22,6 +28,15 @@ public protocol ModulesProviderProtocol {
22
28
  func getAppCodeSignEntitlements() -> AppCodeSignEntitlements
23
29
  }
24
30
 
31
+ public extension ModulesProviderProtocol {
32
+ /**
33
+ Providers that conform to the protocol directly, without inheriting from `ModulesProvider`, have no packages by default.
34
+ */
35
+ var packages: [String: ExpoPackage] {
36
+ return [:]
37
+ }
38
+ }
39
+
25
40
  /**
26
41
  The default implementation for modules provider.
27
42
  The proper implementation is generated by autolinking as part of `pod install` command.
@@ -30,6 +45,10 @@ public protocol ModulesProviderProtocol {
30
45
  open class ModulesProvider: NSObject, ModulesProviderProtocol {
31
46
  public override required init() {}
32
47
 
48
+ open var packages: [String: ExpoPackage] {
49
+ return [:]
50
+ }
51
+
33
52
  open func getModuleClasses() -> [ExpoModuleTupleType] {
34
53
  return []
35
54
  }
@@ -30,8 +30,9 @@ public protocol Record: Convertible, JavaScriptDecodable, JavaScriptEncodable {
30
30
 
31
31
  /**
32
32
  Reads the record's members from a `[String: Any]` dictionary. The `@Field`-based default goes
33
- through reflection (`init()` + `update(withDict:)`); the `@Record` macro overrides it with a
34
- direct, statically-typed factory.
33
+ through reflection (`init()` + `update(withDict:)`). The `@Record` macro overrides it with a
34
+ factory that throws `RecordDictionaryConversionException`, since a macro record converts only from
35
+ JavaScript values.
35
36
  */
36
37
  static func from(dictionary: Dict, appContext: AppContext) throws -> Self
37
38
 
@@ -69,14 +70,25 @@ public final class RecordPropertyRequiredException: GenericException<String>, @u
69
70
  }
70
71
  }
71
72
 
73
+ /**
74
+ Thrown by a synthesized record's `from(dictionary:appContext:)`. A `@Record` type converts only from
75
+ and to JavaScript values, through its `decode` and `encode`, so it can't be created from a native
76
+ dictionary. The parameter is the name of the record type.
77
+ */
78
+ public final class RecordDictionaryConversionException: GenericException<String>, @unchecked Sendable {
79
+ override public var reason: String {
80
+ return "Cannot create '\(param)' from a native dictionary, because a @Record type converts only from JavaScript values. Receive the value as a JavaScript argument, or create it with its memberwise initializer"
81
+ }
82
+ }
83
+
72
84
  /**
73
85
  Provides the default implementation of `Record` protocol.
74
86
  */
75
87
  public extension Record {
76
88
  static func convert(from value: Any?, appContext: AppContext) throws -> Self {
77
89
  if let value = value as? Dict {
78
- // `from(dictionary:)` dispatches dynamically — reflection for `@Field` records, the
79
- // synthesized factory for `@Record` ones — so both read correctly off a dictionary.
90
+ // `from(dictionary:)` dispatches dynamically: reflection for `@Field` records, and for `@Record`
91
+ // ones the synthesized factory, which throws `RecordDictionaryConversionException`.
80
92
  return try Self.from(dictionary: value, appContext: appContext)
81
93
  }
82
94
  // It's possible that the current implementation tries to convert a value that is already of the desired type.
@@ -102,8 +114,8 @@ public extension Record {
102
114
  }
103
115
 
104
116
  static func from(dictionary: Dict, appContext: AppContext) throws -> Self {
105
- // Reflection-based default for `@Field` records. The `@Record` macro synthesizes a direct,
106
- // statically-typed override that takes precedence over this. Delegates to `init(from:appContext:)`
117
+ // Reflection-based default for `@Field` records. The `@Record` macro synthesizes an override that
118
+ // throws, which takes precedence over this. Delegates to `init(from:appContext:)`
107
119
  // so any custom dictionary initializer a record provides still runs.
108
120
  return try Self(from: dictionary, appContext: appContext)
109
121
  }
@@ -180,25 +180,37 @@ public final class SharedObjectRegistry: Sendable {
180
180
  Deletes the shared objects pair with a given ID.
181
181
  */
182
182
  internal func delete(_ id: SharedObjectId) {
183
- state.withLock { state in
184
- if let nativeState = state.pairs[id] {
185
- let native = nativeState.native
186
- nativeState.markReleased()
187
-
188
- // Delete the entry from the dictionary.
189
- state.pairs[id] = nil
190
-
191
- // A native object that was paired again after its JS object died has a new native state and ID,
192
- // and stays paired.
193
- guard native.nativeState === nativeState else {
194
- return
195
- }
196
- native.sharedObjectWillRelease()
197
- // Reset an ID on the object.
183
+ let released: (native: SharedObject, nativeState: SharedObjectNativeState)? = state.withLock { state in
184
+ guard let nativeState = state.pairs[id] else {
185
+ return nil
186
+ }
187
+ let native = nativeState.native
188
+ nativeState.markReleased()
189
+
190
+ // Delete the entry from the dictionary.
191
+ state.pairs[id] = nil
192
+
193
+ // A native object that was paired again after its JS object died has a new native state and ID,
194
+ // and stays paired.
195
+ guard native.nativeState === nativeState else {
196
+ return nil
197
+ }
198
+ return (native, nativeState)
199
+ }
200
+ guard let released else {
201
+ return
202
+ }
203
+ let native = released.native
204
+ // The hooks run without the lock: they can emit events whose listeners run inline on the JavaScript
205
+ // thread and use the registry again, and the lock isn't reentrant.
206
+ native.sharedObjectWillRelease()
207
+ // Reset an ID on the object, unless the hook paired it again.
208
+ state.withLock { _ in
209
+ if native.nativeState === released.nativeState {
198
210
  native.sharedObjectId = 0
199
- native.sharedObjectDidRelease()
200
211
  }
201
212
  }
213
+ native.sharedObjectDidRelease()
202
214
  }
203
215
 
204
216
  /**
@@ -4,77 +4,12 @@ import SwiftUI
4
4
 
5
5
  extension Color: Convertible {
6
6
  public static func convert(from value: Any?) throws -> Color {
7
- // Simply reuse the logic from UIColor
8
- if let uiColor = try? UIColor.convert(from: value) {
9
- return Color(uiColor)
10
- }
11
- // Context-dependent colors
12
- if let stringValue = value as? String, let color = colorFromName(stringValue) {
13
- return color
14
- }
15
- throw Conversions.ConvertingException<Color>(value)
7
+ return try swiftUIColorFromAny(value)
16
8
  }
9
+
17
10
  public static func convert(from value: Any?, appContext: AppContext) throws -> Color {
18
11
  return try convert(from: value)
19
12
  }
20
-
21
- private static func colorFromName(_ name: String) -> Color? {
22
- switch name {
23
- case "primary":
24
- return .primary
25
- case "secondary":
26
- return .secondary
27
- case "red":
28
- return .red
29
- case "orange":
30
- return .orange
31
- case "yellow":
32
- return .yellow
33
- case "green":
34
- return .green
35
- case "blue":
36
- return .blue
37
- case "purple":
38
- return .purple
39
- case "pink":
40
- return .pink
41
- case "white":
42
- return .white
43
- case "gray":
44
- return .gray
45
- case "black":
46
- return .black
47
- case "clear":
48
- return .clear
49
- case "mint":
50
- if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
51
- return .mint
52
- }
53
- return nil
54
- case "teal":
55
- if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
56
- return .teal
57
- }
58
- return nil
59
- case "cyan":
60
- if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
61
- return .cyan
62
- }
63
- return nil
64
- case "indigo":
65
- if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
66
- return .indigo
67
- }
68
- return nil
69
- case "brown":
70
- if #available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *) {
71
- return .brown
72
- }
73
- return nil
74
- default:
75
- return nil
76
- }
77
- }
78
13
  }
79
14
 
80
15
  extension UnitPoint: Convertible {
@@ -189,6 +189,7 @@ extension ExpoSwiftUI {
189
189
  }
190
190
 
191
191
  if let children = props.children {
192
+ (children.first(where: { $0.id == childViewId }) as? UIViewHost)?.didUnmount()
192
193
  props.children = children.filter({ $0.id != childViewId })
193
194
  #if DEBUG
194
195
  assert(props.children?.count == children.count - 1, "Failed to remove child view")