agents/openai.yaml
interface:
display_name: "Migrate Expo Module"
short_description: "Migrate Swift Expo modules from 1.0 DSL to 2.0"
default_prompt: "Use $expo-migrate-module to migrate this Expo module's Swift implementation from the 1.0 definition DSL to the 2.0 macro API without changing its JavaScript contract."
references/compatibility.md
# Expo Modules API 2.0 Compatibility Checks
The Expo Modules API 2.0 design and implementation evolve across three packages: the `expo-modules-macros` compiler plugin, `expo-modules-core`, and `expo-modules-jsi`. Verify the installed dependencies instead of relying on an SDK-number claim.
A fourth package, `expo-modules-cli`, provides the `expo-modules` command for module authors. `expo` depends on it and exposes the command as its own bin, so every project that depends on `expo` has it. Its `swift:check` and `swift:expand` commands run the macros of the installed `expo-modules-macros` version on Swift sources, without a build. See "Inspect the generated code".
## Find the actual declarations
Locate `ExpoModulesMacros.swift` in the target repository or installed dependencies (use your search tool, or portable shell commands - do not assume `rg` is installed):
```bash
find . -name 'ExpoModulesMacros.swift' -not -path '*/node_modules/.cache/*'
```
Inspect the macros that the user's source can import, and the options that `@JS` accepts:
```bash
grep -nE 'public macro (ExpoModule|JS|Event|SharedObject|Record|Union|ViewProps|ExpoView)' <path-to-ExpoModulesMacros.swift>
grep -nE '^ case ' <path-to-ExpoModulesMacros.swift>
```
In SDK 58, core declares `@ExpoModule`, `@JS`, `@Event`, `@SharedObject`, `@Record`, and `@Union`, and the `@JS` options `.concurrent` and `.withAsync`. It does not declare `@ViewProps` or `@ExpoView`. The plugin implements both, but source cannot use them until core declares them.
A declaration proves only that Swift recognizes the attribute, not that the code the macro generates will compile and run against the installed core.
## Check paired core support
The three packages can drift independently, so a successful macro expansion does not prove the generated code links or is called at runtime. The binding hooks live in `expo-modules-core`. The value conversions, including free-form `Any`, `Task`, and closure callbacks, live in `expo-modules-jsi`. Search both.
> The symbol names in this section are macro internals, for your own verification only. Never print them in the conversation, name them in your report, or write them into the migrated module's source. Report a capability by its macro (`@JS static`, `@Event(sync:)`) and by observable JS behavior. See the reporting rule in `SKILL.md`.
**Fast pre-check.** Search core and JSI for the hooks the generated code calls, to rule out an unsupported capability before you write any Swift:
```bash
grep -rnE '_decorateModule|_decorateSharedObject|_constructSharedObject|_jsName|EventEmitter|emitSync|didCreate|decodeAnyDictionary|encodeAny|extension Task: JavaScriptEncodable|JavaScriptCallback|JSOptions|withAsync|UnionCaseMismatch' <expo-modules-core> <expo-modules-jsi>
```
An absent hook is strong evidence the capability is unavailable. A present one is weaker: it proves the symbol exists, not that its signature matches what the plugin generates or that core ever calls it.
**Confirm by compiling.** Write the smallest `@JS` member that uses the capability. Run `swift:check` (see "Inspect the generated code") to see the macro's own errors without a build. Then build the module target against the installed core and read the diagnostics:
- The build succeeds: the capability is supported end to end.
- The macro reports an error or warning: the plugin itself rejects the construct. The diagnostic names the supported alternative.
- Expansion succeeds but the build fails on a missing symbol or an override with nothing to override: the plugin is ahead of core. Keep the member in the 1.0 DSL.
Then exercise the member from the example app or a test, because a binding can link and still never be invoked.
## Capability gates
Treat these as independent capabilities. Confirm each by compiling a minimal member that uses it, then calling it from JS. The SDK 58 column records what SDK 58 provides at the floor in `SKILL.md`. Use it to decide where to look first, not in place of the checks.
| Capability | Macro surface | Hook to grep (internal) | SDK 58 | Confirm by |
| --- | --- | --- | --- | --- |
| Module functions/properties | `@ExpoModule`, `@JS` | `_decorateModule` and its call site | yes | calling the function and reading the property from JS |
| Module name | `@ExpoModule("Name")` | `_jsName` and the name lookup that reads it | yes, but a `Name(...)` entry wins over it | resolving the module under its expected JS name |
| Records | `@Record` | coding conformances and field decode/encode | yes, on a struct or a `final class` with no inheritance clause | round-tripping a record argument and a record return value |
| Async events | `@Event` | `EventEmitter` on modules and shared objects | yes | receiving an emitted event through the module's JS listener |
| Shared-object instances | `@SharedObject`, `@JS` | `_decorateSharedObject(prototype:)`, construction hook | yes | constructing one from JS and calling an instance member |
| Shared-object static members | `@JS static` | `_decorateSharedObject(constructor:)`, distinct from the `prototype:` overload | yes | calling the member on the JS class itself, not an instance |
| Shared-object subclasses | `@SharedObject` on a `SharedRef<T>` subclass or another indirect subclass | none, the compiler checks the superclass | yes | constructing one from JS and calling a member |
| Lazy properties | `@JS lazy var` | none, the macro binds a getter that stores the value | yes | reading the property twice from JS and seeing one native evaluation |
| Tuples | tuples in `@JS`, `@Record`, `@Union`, `@Event`, and closure arguments | `decodeTuple` and `encodeTuple` in JSI | yes | round-tripping an unlabeled tuple as an array and a labeled one as an object |
| Synchronous events | `@Event(sync:)` | `emitSync` overloads | **no**, core and JSI have no `emitSync` | observing the listener run before the emit call returns |
| Task-returning functions | `@JS` returning `Task` | `JavaScriptEncodable` for `Task` in JSI (encode-only) | yes | awaiting the returned promise in JS |
| Views | `@ViewProps`, `@ExpoView` | the macro declarations in `ExpoModulesMacros.swift` | **no**, core does not declare them | rendering the view and updating every prop from JS |
| Module lifecycle methods | lifecycle members on the module class | `AnyModule` requirements and holder call sites | yes | observing each hook fire |
| Free-form `Any` | `@JS` and `@Record` with `Any`, `[Any]`, `[String: Any]` | `decodeAny…` and `encodeAny…` in JSI | yes | passing a JS object through and back |
| Closure arguments | `@JS` with a function-typed parameter | `JavaScriptCallback` in JSI | yes | calling the closure from native code and reading the JS result |
| Off-JS-thread async start | `@JS(.concurrent)` | `JSOptions` and the options-taking `@JS` overload | yes | the `@JS` declaration accepting the option |
| Promise variant of a sync function | `@JS("nameSync", .withAsync("name"))` | `withAsync` in `JSOptions` | yes | calling both JS names |
| Typed N-case unions | `@Union` | `Union` macro declaration and `UnionCaseMismatch` | yes | round-tripping each case through the JS boundary |
| Autolinked `@ExpoModule` discovery | none, it is a build-time step | `scanModules` in `expo-modules-autolinking` | yes | the module loading without an `apple.modules` list |
If a capability cannot be confirmed, keep that item in the 1.0 DSL.
## Known migration hazards
Use this only as a warning list; installed source wins.
- Async threading changed architecturally, not just syntactically: a 2.0 `async` member starts on the JS thread and leaves it at the first suspension point, where a 1.0 `AsyncFunction` never ran there. A verbatim migration can move blocking work onto the JS thread with no signature change. `@JS(.concurrent)` restores the 1.0 behavior. In Swift 6 language mode, `.concurrent`, `.withAsync`, and a detached `Task` need the module or shared object to be `@unchecked Sendable`, which newer macros add themselves. See the threading section in `references/migration-map.md`.
- Same-JS-name `@JS` overload grouping and dispatch were designed but never built. The plugin reports two `@JS` members with one JS name on one object as a build error. A shared object's static and instance members bind onto different JS objects, so they can share a name.
- `@Union` decoding is first-match in case-declaration order, so preserving a 1.0 `Either`'s type order is part of the contract. See the unions section in `references/migration-map.md`.
- Decode errors lacked the 1.0 argument-index wrapper. This affects diagnostics rather than call semantics, but tests asserting exact messages may fail.
- The plugin in SDK 58 implements `@ViewProps` and `@ExpoView`, but core does not declare either macro and has no typed view-props runtime. Views stay on the 1.0 DSL.
- `@Event(sync: true)` macro generation exists, but SDK 58 core and JSI have no `emitSync`.
- Shared-object `@JS static`/`class` members bind onto the JS class object through a `constructor:`-labeled decoration hook, separate from the `prototype:` one used for instance members. Instance support does not imply static support, so confirm a static member by calling it on the JS class.
- Async `@JS` bindings are two-phase: arguments decode synchronously before the asynchronous boundary, and return values encode on the JS thread. A 1.0 async function whose argument decoding had side effects ordered after the hop can therefore observe a different order.
- On SDK 58, `JavaScriptValue` is a non-copyable struct, and DSL `Function`, `AsyncFunction`, `Property`, and `Field` no longer accept it in their signatures. A DSL member that takes or returns a `JavaScriptValue` no longer compiles. Migrate it to `@JS` and take the value as `borrowing JavaScriptValue`. To keep the value after the call returns, store `value.ref()` and read it back with `take()` or `withUnwrappedValue(_:)`. Write `.undefined()` and `.null()`, which are functions now.
- Core reads the `@ExpoModule` name only when the module has no `Name(...)` entry. In mixed mode a leftover `Name(...)` wins, so a mismatch between the two names is silent.
- A no-payload `@Event` (`() -> Void`) sends `undefined`. A 1.0 `sendEvent("name")` without a body sent `{}`.
- `OnAppContextDestroys`, `OnAppEntersForeground`, `OnAppEntersBackground`, and `OnAppBecomesActive` have no 2.0 hook. They stay in `definition()`.
## Macro changes in SDK 58 that affect a migration
All of them are present under the `expo` `58.0.21` floor in `SKILL.md`.
### Free-form `Any`
`Any`, `[Any]`, and `[String: Any]` are accepted as `@JS` arguments, return values, and properties, and as `@Record` fields. One optional layer (`[String: Any]?`) also works, and so do nested types built from `Any`, arrays, `String`-keyed dictionaries, and optionals (`[String: [Any]]`). They convert through dedicated free-form methods in JSI, not through `JavaScriptDecodable`/`JavaScriptEncodable`.
A 1.0 DSL member with a loosely typed dictionary can therefore keep its Swift signature. Prefer a typed `@Record` only when the user asks for an API-shape change.
### Closure arguments
A `@JS` function or initializer can take a closure parameter, such as `(Point) throws -> Size` or `(String) async throws -> Data`. JS passes a function for it. Native code can store the closure and call it from any thread.
- A closure that returns a value must be `throws`, so that an error from JS can reach the caller.
- A throwing or value-returning closure blocks the caller until JS returns. An `async` closure suspends instead and awaits the promise that the JS function returns.
- A non-throwing `Void` closure returns before JS reads its arguments, so do not change a class instance after passing it to one.
- An optional closure (`((Int) -> Void)?`) turns JS `null` and `undefined` into `nil`.
- A closure nested in another type, such as an array, is not a closure parameter.
- The closure type accepts only the `@escaping` and `@Sendable` attributes. Its parameters cannot be variadic, `inout`, closures, or free-form `Any`, and it cannot use typed throws.
- A `@JS` function cannot return a closure, and a `@JS` property cannot have a closure type.
### Parameters and names
- `inout` and `isolated` parameters are build errors, because a `@JS` argument is a fresh value decoded from JS. `borrowing`, `consuming`, and `sending` parameters are accepted.
- A backticked Swift name binds under its bare name: ``@JS func `default`()`` is `default` in JS.
### `.withAsync`
`@JS("readSync", .withAsync("read"))` binds a synchronous function under its own JS name, and binds it again under the given name as a function that returns a promise and runs the body on the concurrent thread pool. See the threading section in `references/migration-map.md`. The macro rejects it on an `async` function, a property, or an initializer, and on a function isolated to a global actor.
### Records
`@Record` types convert without an app context. A `@Record` class must be `final` and have no inheritance clause, or the build fails; declare its protocol conformances in an extension. A 1.0 `class Options: Record` therefore becomes `@Record final class Options`, or a struct.
### Static members on shared objects
`static` and `class` `@JS` members of a `@SharedObject` class bind onto the JS class itself, so JS calls them as `Cache.open(name)`. A 1.0 `StaticFunction` or `StaticAsyncFunction` migrates to one. See the static members section in `references/migration-map.md`.
### `lazy` properties and shared-object subclasses
- A `@JS lazy var` is read-only from JS. Its first read stores the value as a data property on the JS object, so later reads do not call native code. On a frozen JS object the value is not stored, and each read calls the getter. This is the closest mapping for a 1.0 `Constant`.
- `@SharedObject` accepts a `SharedRef<T>` subclass and any other indirect `SharedObject` subclass. The compiler, not the macro, reports a class that is not a `SharedObject` subclass. Each `@SharedObject` class exposes only the `@JS` members that it declares. That matches 1.0, where a `Class(...)` block could not inherit from another.
### Tuples
A tuple can cross the boundary as a `@JS` argument, result, or property, a `@Record` property, a `@Union` or `@Event` payload, or a parameter or result of a closure argument that is not `async`.
- An unlabeled tuple such as `(Int, String)` converts to an array with one value per element. A labeled tuple such as `(x: Double, y: Double)` converts to an object with one property per label.
- A tuple must have two or more elements, all labeled or none, and each element must be convertible. Tuples nest in other tuples, optionals, arrays, and `String`-keyed dictionaries.
- A type alias of a tuple, such as `typealias Span = (start: Int, end: Int)`, resolves only when the `@ExpoModule` or `@SharedObject` class body declares it.
### Package and binary names
The package is `expo-modules-macros`, formerly `@expo/expo-modules-macros-plugin`, and the executable is `ExpoModulesMacros`, formerly `ExpoModulesMacros-tool`. `pod install` adds `-load-plugin-executable <plugin>/apple/ExpoModulesMacros#ExpoModulesMacros` to `OTHER_SWIFT_FLAGS`. Look for that flag when the compiler cannot find the macro implementation.
## Autolinked module discovery
On SDK 58, autolinking scans the package sources for `@ExpoModule` classes when it generates the modules provider. The rules that matter for a migration:
- When `expo-module.config.json` has an `apple.modules` list, even an empty one, autolinking uses only that list and ignores the scan.
- Without the list, it links every scanned class that is `public` or `open` and compiles for the target platform. An `internal` class gets a warning, and a lower access level opts the class out silently.
- A class inside an `#if` condition that the scanner cannot evaluate statically, such as `#if DEBUG` or `canImport(...)`, is skipped with a warning. List such a class in `apple.modules`.
- The scan skips `Tests`, `UITests`, `__tests__`, `__mocks__`, `example`, `examples`, `e2e`, `Pods`, `node_modules`, `.build`, and `.git` directories. A module class kept under one of those names needs the list.
- The scan finds only classes with the `@ExpoModule` attribute. A package that still has a module on the 1.0 DSL alone needs the list.
Run the scanners yourself as migration checks. Run this from the module package root, and pass the scanner's name, `scanModules` or `scanExports`, as the argument:
```bash
node -e "
const path = require('path');
let dir = process.cwd();
for (const name of ['expo', 'expo-modules-core', 'expo-modules-macros']) {
dir = path.dirname(require.resolve(name + '/package.json', { paths: [dir] }));
}
require(dir)[process.argv[1]](['ios']).then((r) => console.log(JSON.stringify(r, null, 2)));
" scanModules
```
The script resolves `expo`, then `expo-modules-core` from it, then `expo-modules-macros` from that, which is how `expo-modules-cli` finds the macros. Only `expo` has to be a dependency of the module, so the script also works with pnpm and bun isolated installs, where `expo-modules-core` cannot be resolved from the module root.
`scanModules` reports each detected class with its Swift `name`, `jsName`, `accessLevel`, and `platforms`, plus `warnings`. It catches an `@ExpoModule` that landed in a conditional block or on a non-public class.
`scanExports` reports the macro-declared surface: `modules`, `sharedObjects`, `records`, `unions`, and `enums`. Each module lists its `functions` (with `jsName`, `parameters`, `async`, `throws`, and `static`), `properties` (with `readonly`), `events` (with `jsName`, `payload`, and `sync`), and `classes`. Compare it against the inventory from step 1. It does not report members that stay in the DSL.
## Inspect the generated code
`expo-modules-cli` has two commands that run the macros on Swift sources without a build. Both find the `expo-modules-macros` version through the package's `expo` and `expo-modules-core`, which is the version the iOS build compiles with. Run them from the module package root:
```bash
# Only the macro errors and warnings, and a summary. The exit code is 1 when there is an error.
npx --no-install expo-modules swift:check ios
# The code that the macros generate, for a file or for one type or member.
npx --no-install expo-modules swift:expand ios/MyModule.swift
npx --no-install expo-modules swift:expand --symbol MyModule.load ios/MyModule.swift
```
`expo` declares the `expo-modules` bin itself and forwards it to `expo-modules-cli`, so every package manager links it into `node_modules/.bin`, also with pnpm and bun isolated installs. `pnpm exec expo-modules` and `bunx expo-modules` run the same command. It needs `expo` installed in the module package; when the command is missing, install the module's dependencies. `--no-install` keeps `npx` from downloading a package from npm in that case. A path is a `.swift` file or a directory. In a directory, only the files that use a macro are expanded, and test and example directories are skipped. The diagnostics use the compiler's `<file>:<line>:<column>: error: <message>` format. `--json` prints a report instead of text, and then the exit code is 0 even when there is an error.
Use `swift:check` to find a macro error fast, and `swift:expand` to see why a binding does not behave as expected. Do not copy the expansion into the module source, and do not quote it to the user: it consists of the internal symbols that the handoff rule in `SKILL.md` keeps out of reports. The macros see only syntax, so code with no diagnostics can still fail to type-check, build, or link against the installed core.
## Integration verification
Use the target project's own commands. A robust sequence is:
1. Run macro/unit tests if working inside the macros package.
2. Run `npx --no-install expo-modules swift:check ios` on the module's iOS sources.
3. Compile the migrated native module against the installed core.
4. Re-run CocoaPods installation when plugin dependencies or injection changed.
5. Restart Xcode after swapping a macro plugin binary; cleaning DerivedData alone may not reload it.
6. Build the example app and execute existing JS/TS behavior tests.
Do not report a migration complete based only on `swift:check`, `swift:expand`, or textual expansion tests.
references/example.md
# Worked Example: Full Module Migration
This walks a single small module from the 1.0 DSL through mixed mode to a fully migrated 2.0 form. Every per-member rule lives in `migration-map.md`; this shows how they compose and how mixed mode is an intermediate state, not a failure.
The module below is representative: a name, a sync function, two async functions (one that suspends, one that blocks), a settable property, a constant, an event with observing hooks, and a record.
## Starting point: 1.0 DSL
```swift
import ExpoModulesCore
@Record
struct DownloadOptions {
var url: URL // required
var retries: Int = 3 // omittable, default 3
var label: String? // omittable and nullable
}
public final class DownloaderModule: Module {
private var volume: Double = 1
public func definition() -> ModuleDefinition {
Name("Downloader")
Events("onProgress")
OnStartObserving {
self.beginProgressUpdates()
}
OnStopObserving {
self.stopProgressUpdates()
}
Constant("buildInfo") { computeBuildInfo() }
Function("clamp") { (value: Double) -> Double in
return min(max(value, 0), 1)
}
Property("volume") { self.volume }
.set { self.volume = $0 }
AsyncFunction("download") { (options: DownloadOptions) -> String in
return try await self.performDownload(options)
}
AsyncFunction("clearCache") {
try FileManager.default.removeItem(at: self.cacheDirectory)
}
}
private func report(percent: Double) {
sendEvent("onProgress", ["percent": percent])
}
}
```
The observable contract to preserve:
| Member | JS name | Contract |
| --- | --- | --- |
| Module | `Downloader` | `requireNativeModule("Downloader")` |
| `clamp` | `clamp` | sync, 1 arg, returns number |
| `volume` | `volume` | read/write number |
| `buildInfo` | `buildInfo` | read-only constant |
| `download` | `download` | async, 1 record arg, returns string |
| `clearCache` | `clearCache` | async, no args, blocking work runs off the JS thread |
| `onProgress` | `onProgress` | event, payload `{ percent }` |
| observing hooks | n/a | progress updates start/stop with the listener count |
| `DownloadOptions` | n/a | `url` required; `retries` default 3; `label` nullable |
## Intermediate: mixed mode
SDK 58 core supports everything used above: `@ExpoModule`, `@JS` functions/properties/constants, async `@JavaScriptActor`, `@JS(.concurrent)`, `@Record`, default async `@Event`, and the module lifecycle hooks. One member still needs a decision, by semantics rather than support: `clearCache` has a body that blocks and never suspends, and a 1.0 `AsyncFunction` runs it on a background queue automatically, while a 2.0 async member starts on the JS actor. Migrating it as-is would move blocking I/O onto the JS thread, so it stays in the DSL until its group is migrated deliberately.
The record migrates first because it is a pure data type and the function that consumes it depends on it. Its shape is already correct, so migration is just verifying each field decodes: `url`, `retries`, `label` all map cleanly, so `@Record` stays as-is (it was already using the macro here).
```swift
import ExpoModulesCore
@Record
struct DownloadOptions {
var url: URL
var retries: Int = 3
var label: String?
}
@ExpoModule("Downloader")
public final class DownloaderModule: Module {
// Explicit wire name: default @Event would strip "on" and emit "progress".
@Event("onProgress")
var onProgress: (ProgressEvent) -> Void
@JS("clamp")
func clamp(value: Double) -> Double {
return min(max(value, 0), 1)
}
// Stored var -> JS getter + setter, matching the 1.0 get/set pair.
@JS
var volume: Double = 1
// Read-only from JS, evaluated at the first read and cached, like the 1.0 Constant.
@JS
lazy var buildInfo = computeBuildInfo()
@JS
func download(options: DownloadOptions) async throws -> String {
return try await performDownload(options)
}
// override: the hooks are inherited from the Module base class.
public override func didStartListening(event: String) {
beginProgressUpdates()
}
public override func didStopListening(event: String) {
stopProgressUpdates()
}
// Kept on the DSL: the body blocks without suspending, and a 2.0 async
// member would start it on the JS actor instead of a background queue.
public func definition() -> ModuleDefinition {
AsyncFunction("clearCache") {
try FileManager.default.removeItem(at: self.cacheDirectory)
}
}
private func report(percent: Double) {
onProgress(ProgressEvent(percent: percent))
}
}
@Record
struct ProgressEvent {
var percent: Double
}
```
Notes on the choices, each traceable to `migration-map.md`:
- `Name("Downloader")` moved into `@ExpoModule("Downloader")`; the custom name is carried explicitly, never dropped.
- `@Event("onProgress")` uses the explicit wire name to avoid the `on`-stripping default; the untyped dictionary became a typed `ProgressEvent`.
- The duplicate `private var volume` field was removed once `@JS var volume` became the single source of truth. Watch for this: a 1.0 backing field plus a migrated `@JS var` of the same name is a double-declaration.
- `Constant("buildInfo")` became `@JS lazy var buildInfo`. Both evaluate at the first read from JS and cache the value, so the evaluation time does not change. A `@JS let` would evaluate when the module is created.
- `OnStartObserving`/`OnStopObserving` became the `didStartListening(event:)`/`didStopListening(event:)` hooks, with `public override` because the class inherits `Module` and is `public`. The 1.0 hooks were module-wide, so the event argument is ignored.
- `definition()` remains but now holds only the queue-sensitive `clearCache`. It is not deleted because it is non-empty.
- The class name did not change, so the package's `expo-module.config.json` entry (`"apple": { "modules": ["DownloaderModule"] }`) stays valid and is left as it is.
## Fully migrated (after explicitly moving the blocking work off the JS actor)
The DSL entry for `clearCache` was the semantics-preserving default. To finish the migration, migrate it with `@JS(.concurrent)`, so the blocking body still never runs on the JS thread, then delete the empty `definition()`.
```swift
import ExpoModulesCore
@Record
struct DownloadOptions {
var url: URL
var retries: Int = 3
var label: String?
}
@Record
struct ProgressEvent {
var percent: Double
}
@ExpoModule("Downloader")
public final class DownloaderModule: Module {
@Event("onProgress")
var onProgress: (ProgressEvent) -> Void
@JS("clamp")
func clamp(value: Double) -> Double {
return min(max(value, 0), 1)
}
@JS
var volume: Double = 1
@JS
lazy var buildInfo = computeBuildInfo()
@JS
func download(options: DownloadOptions) async throws -> String {
return try await performDownload(options)
}
// The body blocks without suspending, so it runs off the JS thread.
@JS(.concurrent)
func clearCache() async throws {
try FileManager.default.removeItem(at: cacheDirectory)
}
public override func didStartListening(event: String) {
beginProgressUpdates()
}
public override func didStopListening(event: String) {
stopProgressUpdates()
}
private func report(percent: Double) {
onProgress(ProgressEvent(percent: percent))
}
}
```
`definition()` is gone only because it was empty and `@ExpoModule("Downloader")` preserves the resolved name. If any member had stayed blocked or unverified, the mixed-mode form above is the correct place to stop, not a broken end state.
`.concurrent` sends the module off the JS thread, so in Swift 6 language mode the class needs `@unchecked Sendable`, as the `.concurrent` constraints in `migration-map.md` describe. The off-thread body reads only `cacheDirectory`, so the conformance is safe as long as `cacheDirectory` does not change. `volume` stays on the JS thread.
references/migration-map.md
# 1.0 to 2.0 Migration Map
Use this reference while editing. Preserve behavior first; macro adoption is secondary.
## Module and naming
Convert the module class, carry the name into `@ExpoModule("...")`, and remove `Name(...)`:
```swift
// 1.0
public final class CameraModule: Module {
public func definition() -> ModuleDefinition {
Name("Camera")
}
}
// 2.0
@ExpoModule("Camera")
public final class CameraModule: Module {}
```
Always carry a custom 1.0 name into `@ExpoModule("...")`. Without an argument, the name defaults to the Swift class name. Core reads the `@ExpoModule` name only when `definition()` has no `Name(...)` entry, so a stale `Name(...)` silently wins in mixed mode. Remove it, then verify that the module still resolves under its expected JS name.
Keep the `Module` superclass. `@ExpoModule` also works on a class without one, but removing it is not part of a migration: `sendEvent` and the overridable lifecycle hooks come from it.
## Functions
Move a DSL closure into a real method and use `@JS("wireName")` when the Swift method name is different:
```swift
// 1.0
Function("sum") { (a: Double, b: Double) -> Double in
return a + b
}
// 2.0
@JS("sum")
func add(a: Double, b: Double) -> Double {
return a + b
}
```
Preserve:
- the JS name
- positional arity
- optional arguments and Swift defaults
- thrown errors and return type
- whether the result is synchronous or a Promise
Keep functions that resolve to the same JS name on the DSL. The plugin has no overload grouping. It reports two `@JS` members with one JS name on one object as a build error, so leave the overloads in `definition()` as they are.
Keep in DSL any unsupported signature such as variadics or unresolved generics. `inout` and `isolated` parameters are build errors. A `Promise` parameter is also unsupported; refactor it as described under Async functions.
These argument types work in a `@JS` signature on SDK 58:
- **Free-form values.** `Any`, `[Any]`, and `[String: Any]`, optional or nested, are accepted as arguments, return values, and properties. A 1.0 `[String: Any]` argument keeps its Swift type.
- **Closures.** A function-typed parameter receives the JS function. A closure that returns a value must be `throws`, and it blocks the caller until JS returns. A `@JS` function cannot return a closure. See `references/compatibility.md` for the rules.
- **Tuples.** An unlabeled tuple such as `(Int, String)` converts to a JS array, and a labeled tuple such as `(x: Double, y: Double)` to a JS object. Replacing a 1.0 array or dictionary type with a tuple changes the Swift API, so do it only when the user asks.
- **`JavaScriptValue`.** Take it as `borrowing JavaScriptValue`. On SDK 58 the DSL no longer accepts `JavaScriptValue` arguments or results, so such a member must migrate.
```swift
// 1.0, no longer compiles on SDK 58
Function("isFunction") { (value: JavaScriptValue) -> Bool in
return value.isFunction()
}
// 2.0
@JS
func isFunction(_ value: borrowing JavaScriptValue) -> Bool {
return value.isFunction()
}
```
### Async functions
A `Promise` parameter is not supported in a `@JS` signature; 2.0 drops the trailing-`Promise` argument entirely. A Promise-returning function has three shapes in 2.0. Pick by how the underlying work produces its result.
**1. Standard `async` method.** The common case. Swift `async` maps to a JS Promise:
```swift
// 1.0
AsyncFunction("load") { (url: URL) -> String in
return try loadSynchronously(url)
}
// 2.0
@JS
func load(url: URL) async throws -> String {
return try await loadResource(url)
}
```
**2. Checked continuation.** When the result arrives through a delegate or completion handler that fires once, wrap it with `withCheckedThrowingContinuation` (or `withCheckedContinuation` for non-throwing callbacks, or an `AsyncStream` for repeated values). This is the usual refactor for a 1.0 `AsyncFunction` that took a trailing `Promise` instance:
```swift
// 1.0
AsyncFunction("start") { (promise: Promise) in
scanner.start(
onSuccess: { result in promise.resolve(result) },
onFailure: { error in promise.reject(error) }
)
}
// 2.0
@JS
func start() async throws -> ScanResult {
return try await withCheckedThrowingContinuation { continuation in
scanner.start(
onSuccess: { result in continuation.resume(returning: result) },
onFailure: { error in continuation.resume(throwing: error) }
)
}
}
```
Resume the continuation exactly once on every path. If the callback API cannot guarantee that, or the refactor is otherwise unsafe, keep the function on the DSL instead of forcing it.
**3. Synchronous method returning a `Task`.** The `Task` encodes to a promise that settles with its result. Use it when the work is naturally a `Task`, or when a promise is needed as a value nested inside another encoded result rather than as the function's own return:
```swift
// 2.0
@JS
func download(url: URL) -> Task<DownloadResult, any Error> {
return Task {
try await self.downloader.download(url)
}
}
```
This shape requires the `JavaScriptEncodable` conformance for `Task`, which `expo-modules-jsi` provides on SDK 58 (encode-only; a JS promise does not decode back into a `Task`). A `Task { }` created here starts on the JS thread. To run the work off it, see "Returning a `Task`" under Threading.
#### Threading: the architectural difference
This is the highest-risk part of an async migration, because the code compiles and the JS signature is unchanged while the work moves onto a different thread.
The two versions schedule async work from opposite starting points:
| | 1.0 `AsyncFunction` | 2.0 `async` `@JS` |
| --- | --- | --- |
| Where the body starts | off the JS thread, from the first statement | on the JS thread |
| When it leaves the JS thread | never runs there | at the first real suspension point |
| A body with no `await` | still runs off the JS thread | runs entirely on the JS thread |
A 2.0 async member is `@JavaScriptActor`-isolated and stays on the JS thread until it actually suspends. So the dangerous case is a function marked `async` whose body never awaits anything, or awaits only after doing substantial work. In 1.0 that body was off the JS thread from the start; migrated verbatim to 2.0, it now blocks the JS thread for its full duration. Nothing in the JS contract reveals this: the function still returns a promise.
Audit every `AsyncFunction` you migrate for what the body does before its first `await`:
- No `await` at all, or synchronous work ahead of the first `await`: the work is on the JS thread. Treat it as a regression unless the body is trivial.
- Blocking I/O, file or database access, image or crypto work, or an unbounded loop: never leave this on the JS actor.
- `.runOnQueue(...)` in 1.0: the queue was the contract. See the continuation pattern below.
To restore the 1.0 behavior, use the `@JS` macro's `.concurrent` option:
```swift
// Body runs off the JS thread, like a 1.0 AsyncFunction.
@JS(.concurrent)
func process(input: String) async throws -> String {
return try self.processor.process(input)
}
// The option is variadic, so it combines with an explicit JS name.
@JS("doWork", .concurrent)
func performWork() async throws {}
```
Only the body moves. Arguments are still decoded on the JS thread and the result is still encoded back on it, so `.concurrent` changes execution, not the JS contract. This makes it the preferred fix for a migrated function that relied on 1.0 background execution: the intent is explicit and the body stays as written.
Three constraints:
- `.concurrent` is valid only on an `async` function. On anything else it is diagnosed on the `@JS` attribute.
- You must still write `async` yourself. The macro cannot add it, but the diagnostic for a synchronous function carries a fix-it that inserts it.
- The call sends the module or shared object off the JS thread, so in Swift 6 language mode the class must be `Sendable`. `Module` and `SharedObject` are not `Sendable`, so `@unchecked Sendable` is the only conformance a subclass can have. Newer `expo-modules-macros` versions add it themselves. Run `npx --no-install expo-modules swift:expand --symbol MyModule ios/MyModule.swift`: when the output has an `extension MyModule: @unchecked Sendable` block, do not declare it. Otherwise declare `@unchecked Sendable` on the class, as `expo-sqlite` does. Either way the compiler no longer checks this state, so check that the off-thread code touches only state that is safe to share, and say in a comment what guards it.
#### Returning a `Task`
A synchronous `@JS` function that returns a `Task` also gives JS a promise (shape 3), and the task can run the work off the JS thread. That happens only when the task does not inherit `@JavaScriptActor`:
```swift
// The detached task runs on the concurrent thread pool. The function returns right away.
@JS
func clearCache() -> Task<Void, any Error> {
return Task.detached {
try FileManager.default.removeItem(at: self.cacheDirectory)
}
}
```
- The macro isolates a synchronous `@JS` function to `@JavaScriptActor`, and `Task { }` inherits that isolation. The executor of that actor runs each job immediately on the current thread, so the body of a `Task { }` runs on the JS thread before the function even returns. Use `Task.detached { }`, or mark the function `nonisolated` so that its `Task { }` runs on the concurrent thread pool.
- In Swift 6 language mode the closure sends `self` off the JS thread, so the class needs the `@unchecked Sendable` conformance described under `.concurrent`.
- Throw inside the task, not from the function. An error that the function throws before it returns the task reaches JS as a synchronous exception, where a 1.0 `AsyncFunction` rejected its promise.
For a plain migration, prefer `@JS(.concurrent)`: it keeps the `async` signature and the body as written. Return a `Task` when the work already is one.
#### Sync and async pairs
1.0 modules often register one body twice: a `Function` for synchronous calls and an `AsyncFunction` that runs the same work off the JS thread. Merge the pair with `.withAsync`, which binds the function under its own JS name and again under the given name as a promise-returning variant that runs on the concurrent thread pool:
```swift
// 1.0
Function("readSync") { (path: String) throws -> String in
return try self.readFile(path)
}
AsyncFunction("read") { (path: String) throws -> String in
return try self.readFile(path)
}
// 2.0
@JS("readSync", .withAsync("read"))
func readSync(path: String) throws -> String {
return try readFile(path)
}
```
Constraints:
- The function must be synchronous. On an `async` function the macro rejects the option and points to `.concurrent`.
- The name must be a string literal, and the option can appear only once.
- The variant is not isolated to the JS thread, so the body must be safe on any thread. A function isolated to a global actor such as `@MainActor` is rejected; mark it `nonisolated` when its isolation comes from elsewhere.
- In Swift 6 language mode the class needs the `@unchecked Sendable` conformance described under `.concurrent`.
#### Queue-pinned functions
For `.runOnQueue(.main)`, mark the `async` function `@MainActor`. The macro then does not isolate it to the JS thread, and the body runs on the main actor. `expo-haptics` migrated this way in SDK 58:
```swift
// 1.0
AsyncFunction("selectionAsync") {
UISelectionFeedbackGenerator().selectionChanged()
}
.runOnQueue(.main)
// 2.0
@JS
@MainActor
func selectionAsync() async {
UISelectionFeedbackGenerator().selectionChanged()
}
```
For a function pinned to any other queue, prefer restructuring the work onto the Swift Concurrency model (structured concurrency, an actor, or a detached task for blocking work). When that is not feasible because the queue itself is the contract, for example a library that must be called from one serial queue, convert to an `async` method that dispatches to that queue inside a checked continuation:
```swift
// 1.0
AsyncFunction("process") { (input: String) -> String in
return try self.processor.process(input)
}
.runOnQueue(processingQueue)
// 2.0
@JS
func process(input: String) async throws -> String {
return try await withCheckedThrowingContinuation { continuation in
processingQueue.async {
do {
continuation.resume(returning: try self.processor.process(input))
} catch {
continuation.resume(throwing: error)
}
}
}
}
```
## Properties and constants
Map a getter to a getter-only `@JS var`; map a getter/setter pair to a settable stored or computed `@JS var`:
```swift
// 1.0
Property("volume") { self.volume }
.set { self.volume = $0 }
// 2.0
@JS
var volume: Double = 1
```
Access control does not define JS mutability. Verify whether the declaration is syntactically settable; a stored `var` normally produces a JS setter.
Map a 1.0 `Constant` to a `@JS lazy var`. A 1.0 `Constant` runs its closure at the first read and caches the result. A `lazy` `@JS` property does the same: it is read-only from JS, and its first read stores the value as a data property on the JS object, so later reads do not call native code.
```swift
// 1.0
Constant("buildInfo") { computeBuildInfo() }
// 2.0
@JS
lazy var buildInfo = computeBuildInfo()
```
A `@JS let` also produces a read-only JS property, but it initializes with the module instance. Use it only for a cheap value whose evaluation time does not matter, such as a literal:
```swift
@JS
let apiVersion = 3
```
Do not map a 1.0 `Property` getter to a `lazy var`. A `Property` getter runs on every read, so a `lazy var` would freeze its first value.
## Events
Replace `Events(...)` plus `sendEvent(...)` with a typed function property:
```swift
@Record
struct ProgressEvent {
var percent: Double
}
// Explicit string preserves the old wire name.
@Event("onProgress")
var onProgress: (ProgressEvent) -> Void
func report(percent: Double) {
onProgress(ProgressEvent(percent: percent))
}
```
The default `@Event` wire name strips a leading `on` and decapitalizes the remainder: Swift `onProgress` emits `progress`. 1.0 modules commonly expose `onProgress`. During migration, pass the original wire name explicitly unless an intentional JS breaking change was approved.
For payloads, create or reuse a `JavaScriptEncodable` type instead of preserving an untyped dictionary. Migrate `OnStartObserving` and `OnStopObserving` to the `didStartListening(event:)`/`didStopListening(event:)` lifecycle hooks (see Views and lifecycle).
A `() -> Void` event sends `undefined` to the listener. A 1.0 `sendEvent("name")` without a body sent `{}`, so a listener that reads a field of its argument throws after a verbatim migration. Check the JS listeners. When any of them reads the argument, keep an object payload with an empty record:
```swift
@Record
struct ReadyEvent {}
@Event("onReady")
var onReady: (ReadyEvent) -> Void
// Sends {} as before.
onReady(ReadyEvent())
```
Use `() -> Void` only when no listener reads the argument, or when the user approves the change.
Default `@Event` dispatch schedules onto the JS thread and is callable from other isolation contexts. Do not use `sync: true`: SDK 58 core has no `emitSync`, so a synchronous event does not build.
## Shared objects
Move instance behavior from a `Class(...)` block onto the `SharedObject` subclass:
```swift
// 2.0
@SharedObject
final class Download: SharedObject {
@JS
init(url: URL) {
self.url = url
}
@JS
func pause() {}
@JS
var progress: Double { currentProgress }
}
@ExpoModule(classes: [Download.self])
final class DownloadModule: Module {}
```
Drop the leading owner argument used by instance DSL closures; use `self` in the real instance method. Preserve constructor arity and JS member names.
`@SharedObject` accepts any direct or indirect `SharedObject` subclass. That includes a `SharedRef<T>` subclass, such as `final class AudioPlayer: SharedRef<AVPlayer>`. Keep the superclass as it is.
The 1.0 DSL has no inheritance between JS classes: each `Class(...)` block exposes only its own entries. A `@SharedObject` class likewise exposes only the `@JS` members that it declares, so put the members of each JS class on that class.
SDK 58 core supplies the decoration and construction hooks for instance members, static members, and the `@JS init`. Never create both a 1.0 `Class(...)` entry and a 2.0 registration for the same class without confirming that core intentionally merges them.
Static members belong to shared objects, not modules: a module is exported to JS as an instance, so Swift `static` members on a `Module` class are not useful there. Keep module-level values as instance `@JS` members.
#### Static members
A static member installs on the JS class object itself, so JS reaches it as `Download.supportedSchemes()`, not through an instance. The 1.0 DSL has dedicated components for this: `StaticFunction` and `StaticAsyncFunction`. Unlike `Function`, they do not receive the instance as their first argument. There is no static *property* component in 1.0, so a static value was exposed as a `StaticFunction` returning it.
```swift
// 1.0
Class(Download.self) {
Constructor { (url: URL) in Download(url: url) }
// Instance function: receives the owner as its first argument.
Function("pause") { (download: Download) in
download.pause()
}
// Static: no owner argument, callable as Download.supportedSchemes()
StaticFunction("supportedSchemes") { () -> [String] in
Download.supportedSchemes
}
}
```
```swift
// 2.0
@SharedObject
final class Download: SharedObject {
@JS
init(url: URL) { self.url = url }
@JS
func pause() {}
@JS
static func supportedSchemes() -> [String] {
return Self.schemes
}
}
```
`StaticFunction` and `StaticAsyncFunction` both collapse into a `static` (or `class`) Swift declaration, with `async` carrying the distinction, exactly as `Function`/`AsyncFunction` do for instance members. Because 1.0 had no static property component, a `StaticFunction` that only returns a stored value can become a `@JS static var` in 2.0. That changes the JS contract from a call to a property access, so do it only when the user asks; a syntax migration keeps it a function.
Instance members bind onto the class prototype, while `static`/`class` members bind onto the JS class object through a separate hook. Confirm a migrated static member by calling it on the JS class, not on an instance: an instance-side test passes whether or not static binding works.
## Records
Attach `@Record`, remove field wrappers, and encode requiredness in the declaration:
```swift
@Record
struct Options {
var source: URL // required
var retries: Int = 3 // omittable; default applies
var label: String? // omittable and nullable
}
```
Rules:
- non-optional with no default: required
- any property with a default: omittable
- optional type: omittable and nullable
Preserve the 1.0 contract exactly. For example, migrate `@Field var source: URL? = nil` to `var source: URL?`, not to `var source: URL`, unless the user approved a breaking change.
Every non-`static`, non-`private`/`fileprivate`, non-`lazy` stored property is part of the 2.0 record surface. If the old type contains stored bookkeeping that was not a 1.0 field, make it `private` with a default value, move it out of the record, or leave the type on 1.0. Verify that each field supports the required `JavaScriptDecodable`/`JavaScriptEncodable` direction. Free-form fields such as `[String: Any]?` are accepted.
`@Record` applies to a struct, or to a `final class` with no inheritance clause. A 1.0 record class (`class Options: Record`) must become `final` and drop `: Record`. The macro adds the conformance, and other protocol conformances go in an extension. When the class has a superclass or subclasses, convert it to a struct only if no Swift caller relies on reference semantics; otherwise keep it on 1.0.
## Unions
`@Union` is the typed, N-case alternative to 1.0's `Either` types. It applies to a non-generic `enum` whose every case carries exactly one associated value:
```swift
// 1.0: JS `string | SourceOptions`, unwrapped by probing each side.
@JS
func load(_ source: Either<String, SourceOptions>) throws {
if let text: String = source.get() {
load(url: URL(string: text))
} else if let options: SourceOptions = source.get() {
load(url: options.url, headers: options.headers)
}
}
```
```swift
// 2.0: the same JS type, as a named enum.
@Union
enum Source {
case text(String)
case options(SourceOptions) // a @Record
}
@JS
func load(_ source: Source) throws {
switch source { // exhaustive; each payload keeps its static type
case .text(let text):
load(url: URL(string: text))
case .options(let options):
load(url: options.url, headers: options.headers)
}
}
```
The JS-visible type is unchanged: case order defines the accepted alternatives, so `Either<String, SourceOptions>` maps to cases in that same order. Decoding tries each case's payload in declaration order and the first match wins, which matters for overlapping types (`Int`/`Double`, `URL`/`String`): keep the 1.0 `Either` order, since reordering silently changes which case a given JS value lands in.
Besides `switch`, a value unwraps by payload type without naming the case, which is the closest analogue to 1.0's `get()`:
```swift
let text = try source.as(String.self) // throws on a mismatch
let options = try? source.as(SourceOptions.self) // SourceOptions?
```
A type the union does not carry is a compile error, not a runtime `nil`. A mismatch on a held value throws, where 1.0's `get()` returned `nil`, so a migrated probe chain must become a `switch` or a `try?`.
Constraints, each a compile error: a generic enum, no cases, a case with no payload or more than one, a default value on the payload, and two cases with the identical payload spelling.
Treat adopting `@Union` as an API-shape change to raise with the user rather than a mechanical step: it renames nothing in JS, but it does restructure Swift call sites.
## Views and lifecycle
Views are not covered by 2.0 yet. Keep UIKit `View`, `Prop`, view `Events`, and `OnViewDidUpdateProps` DSL entries on 1.0. Expansion tests alone do not prove the runtime update path exists.
The planned shape is a class marked `@ExpoView` whose props and event callbacks are declared once in a typed `@ViewProps` struct, instead of split between the native view and a hand-written JS prop type. The plugin implements both macros, but SDK 58 core does not declare them, so module source cannot use them. A module with views migrates its non-view members and keeps the view on the DSL. That is a normal mixed-mode result, not a failed migration.
Module lifecycle is core-owned rather than macro-generated. The DSL components map to hook methods with no-op defaults:
| 1.0 | 2.0 |
| --- | --- |
| `OnCreate` | `didCreate()` |
| `OnDestroy` | `willDestroy()` |
| `OnStartObserving` | `didStartListening(event:)` |
| `OnStopObserving` | `didStopListening(event:)` |
Rules:
- Use the `override` keyword when the class inherits `Module`/`BaseModule`; define the hooks directly (no `override`) when the conformance comes only from `@ExpoModule`. Hooks added only in a subclass of a macro module are not called; keep them on the class that declares the conformance.
- The listening hooks receive the event name. A module-wide 1.0 `OnStartObserving` ignores the argument; a per-event `OnStartObserving("name")` becomes a comparison on it.
- `didCreate()` runs after the module is registered, slightly later than 1.0 `OnCreate`, which fires before registration; `willDestroy()` runs at holder teardown. Verify nothing depends on the earlier timing before migrating `OnCreate`.
- DSL lifecycle components can remain during an incremental migration and each fires exactly once, but do not implement a DSL component and its hook for the same behavior, or the work runs twice.
`OnAppContextDestroys`, `OnAppEntersForeground`, `OnAppEntersBackground`, and `OnAppBecomesActive` have no 2.0 hook. Keep them in `definition()`.
## Mixed mode
`@ExpoModule` may coexist with a non-empty `definition()`; core merges the two surfaces. Keep only unsupported entries in the DSL and avoid duplicate names across macro and DSL registrations. `expo-sqlite` in SDK 58 is a shipped example: its module functions, properties, event, and lifecycle hooks use the 2.0 forms, while its shared-object classes stay in `definition()`.
Before deleting `definition()`, verify that it contains no:
- `Name(...)` entry whose name differs from the `@ExpoModule` name
- views or view events
- lifecycle or app-context listeners
- queue-pinned functions
## Contract checklist
For every migrated member compare before and after:
| Concern | Must remain stable |
| --- | --- |
| Module | registration name and `requireNativeModule` key |
| Function | JS name, accepted arity, omitted/default behavior, sync/Promise result |
| Property | JS name, read/write behavior, evaluation/caching |
| Event | listener string, payload shape, timing |
| Record | field names, requiredness, nullability, defaults |
| Shared object | constructor shape, prototype vs constructor placement, identity |
| Execution | JS actor, main actor, background queue, ordering |
SKILL.md
---
name: expo-migrate-module
description: Migrate an existing Apple/Swift Expo native module from the Expo Modules API 1.0 definition DSL to the 2.0 macro API (sometimes called v2) while preserving its JavaScript and TypeScript contract. Use when converting or incrementally adopting @ExpoModule, @JS, @Event, @SharedObject, or @Record in an existing module. Do not use for creating a new module, general Expo SDK upgrades, or Android/Kotlin migrations.
license: MIT
---
# Migrate an Expo Module
Migrate the Swift side of an existing Expo module without changing its observable JS API. Treat the current JS/TypeScript surface and tests as the compatibility contract. Leave Kotlin on the 1.0 DSL unless the user explicitly expands the task.
## Prerequisite
Use `expo` `58.0.21` or newer. Earlier `58.0.x` releases lack tuple conversion and the `swift:check` and `swift:expand` commands of `expo-modules-cli`. Older ones also lack `lazy` `@JS` properties, `SharedRef<T>` subclasses in `@SharedObject`, static shared-object members, and `.withAsync`, and the oldest lack closure arguments and free-form `Any` return values. SDK 57 also lacks `.concurrent`, `@Union`, and module auto-discovery. Do not target either. Before editing, check the installed version (`npm ls expo`, or the lockfile). If it is older, stop and tell the user to upgrade first.
Check the example app's own dependencies too, not only the module root. The example app is the integration surface you build and launch in step 4, so it needs the same floor.
This is a floor, not a guarantee: the macro and core surface changed in almost every `58.0.x` patch release, so step 2 must still verify the installed source.
The macros are still **experimental and undocumented**: SDK 58 has no page about them in the Expo docs, and the API can still change under you. Say this to the user before a large migration, and prefer incremental mixed mode over converting a module wholesale.
## References
- Read `references/migration-map.md` before changing source. It contains the 1.0-to-2.0 mappings, semantic traps, and mixed-mode rules.
- Read `references/example.md` for a full before/after walkthrough of one module through mixed mode to a complete migration. Consult it when you need to see how the per-member rules compose.
- Read `references/compatibility.md` when the checked-out `expo-modules-core` version or branch is not known to support every requested macro. It explains how to verify the actual compile-time and runtime surface instead of guessing from a version number, gives the SDK 58 status of each capability, and shows how to run the module scanners and the `expo-modules-cli` checks.
## Workflow
### 1. Establish the contract
Inspect repository instructions and the worktree before editing. Locate the Swift module classes, records, shared objects, native views, JS/TS bindings, tests, example app, podspec, `expo-module.config.json`, and installed or checked-out `expo-modules-core`.
Inventory every exported item before rewriting it:
- module and shared-object JS names
- function names, arity, labels, defaults, nullability, sync/async behavior, errors, and queue/thread semantics (note which `AsyncFunction` bodies do blocking or long-running work, any `.runOnQueue(...)`, and sync/async pairs that share a body, such as `readSync` and `read`)
- property names, mutability, and constant caching behavior
- event wire names and payload shapes, including events sent with no body (1.0 `sendEvent("name")` sends `{}`)
- record field names, defaults, requiredness, and nullability
- shared-object constructors and instance/static placement (`Function` vs `StaticFunction`/`StaticAsyncFunction`)
- lifecycle hooks and views
Use the TypeScript declarations and JS call sites to resolve ambiguity. Do not silently "improve" requiredness, rename an event, or change sync behavior during a syntax migration.
### 2. Verify the available 2.0 surface
Inspect the macro declarations and matching core hooks in the dependency actually used by the target. Do not assume that all items in the 2.0 design are present because one macro compiles.
Classify each 1.0 item as:
- **Migrate:** both its macro and required core runtime support exist.
- **Keep in DSL:** mixed mode preserves it safely, or 2.0 lacks an equivalent.
- **Blocked:** migration would alter the JS contract or requires unavailable runtime support.
A DSL member that takes or returns `JavaScriptValue` does not compile on SDK 58, so it cannot stay in the DSL. Migrate it to `@JS` with a `borrowing JavaScriptValue` parameter, as described in `references/migration-map.md`.
Prefer an incremental mixed-mode result over speculative generated code. Keep `definition()` for any remaining DSL elements; delete it only when it is empty and the resolved module name is preserved by `@ExpoModule`.
### 3. Apply the migration
Migrate one semantic group at a time: module naming, functions, properties/constants, events, shared objects, then records. Keep the diff narrow.
Follow these invariants:
- Preserve every existing JS-visible name explicitly when Swift naming rules or macro defaults differ.
- Keep original optional/default behavior. An optional 1.0 record field must not become required merely because 2.0 can express required fields.
- Keep same-JS-name overloads on the DSL. The plugin does not dispatch overloads, and it reports two `@JS` members with one JS name on one object as a build error.
- Preserve async threading behavior. A 1.0 `AsyncFunction` body ran off the JS thread; a 2.0 `async` `@JS` member starts on it and leaves only at the first `await`. A body that never awaits therefore blocks the JS thread, with no change to the JS signature. Audit what runs before the first `await`, and never leave blocking I/O on the JS actor. Fix with `@JS(.concurrent)`, return a `Task.detached` from a synchronous function, or restructure onto Swift Concurrency or a continuation. A plain `Task { }` in a `@JS` function that is not `nonisolated` starts on the JS thread, so it does not help. Queue-pinned functions get the same treatment; `.runOnQueue(.main)` becomes a `@MainActor` `async` function. Merge a sync/async pair that shares a body into one function with `.withAsync("name")`. See the threading section in `references/migration-map.md`.
- Do not use `@ViewProps`, `@ExpoView`, or `@Event(sync: true)`. The plugin implements them, but SDK 58 core does not declare the two view macros and has no runtime support for synchronous events, so none of them builds. Keep 1.0 views on the DSL. Check the installed core for each of these instead of trusting a plugin version. `references/compatibility.md` has the per-capability checks.
- Keep the `OnAppContextDestroys`, `OnAppEntersForeground`, `OnAppEntersBackground`, and `OnAppBecomesActive` components in `definition()`. 2.0 has no hook for them.
- Keep the JS payload of every event. A `() -> Void` `@Event` sends `undefined`, but a 1.0 `sendEvent("name")` without a body sent `{}`. When JS code reads that payload, give the event an empty `@Record` payload type, which encodes to `{}`, or ask the user before you change it.
- Keep `expo-module.config.json` as it is. When it has an `apple.modules` list (even an empty one), autolinking links only those classes. The entries are bare Swift class names, so renaming a class during migration detaches the module silently: it builds, then is absent at runtime. Without the list, autolinking links the `public` or `open` `@ExpoModule` classes that it finds in the package sources. It does not find a class that is still on the 1.0 DSL alone. A migrated class must stay `public` or `open` in both cases. Remove the list only when the user asks and every module class qualifies.
- Do not change Kotlin, JS wrappers, or public `.d.ts` files unless the user requested an API change.
- Never write macro-generated symbols into the module's source. The macro emits them; hand-writing or overriding them is not part of a migration.
After each group, search for old DSL entries and call sites that should have moved. Avoid broad formatting or unrelated cleanup.
### When a 2.0 equivalent is missing or a group fails
When step 2 classified an item as **Blocked**, or a migrated group fails to build or breaks the contract, do not force it. Stop on that group and:
1. **Ask the user how to proceed** for that item, with two options:
- **Co-exist:** keep the item in the 1.0 `definition()` DSL alongside the migrated `@ExpoModule` (mixed mode) and continue with the other groups.
- **Revert:** back out the group's edits, leaving it untouched on 1.0, and move on.
Default to co-existence when mixed mode is verified safe, since it preserves the most progress. Revert when the half-applied change left the module in a non-building state and cannot be salvaged incrementally.
2. **Open a tracking issue on `expo/expo`** noting the functionality that 2.0 does not yet cover, so the gap is recorded rather than silently worked around. Use `gh issue create --repo expo/expo` and confirm with the user before posting (per repo conventions, do not post outward-facing comments without approval). Include:
- the 1.0 member and its JS contract
- the specific macro or core hook that is missing (cite the evidence gap from `references/compatibility.md`)
- the installed `expo` version, or the `expo-modules-core` branch when the module builds against a checkout
Reference the issue in the handoff so the remaining DSL entry is traceable to a known limitation.
Keep going with the groups that do migrate cleanly; one blocked member does not block the rest.
### 4. Verify behavior
Run the narrowest available checks first, then the real integration surface:
1. Run `npx --no-install expo-modules swift:check ios` from the module package root. It reports macro errors and warnings in seconds, without a build. `references/compatibility.md` describes it.
2. Build or type-check the Apple module against the target `expo-modules-core`.
3. Run native unit tests and JS/TS tests.
4. Build and launch the example app when the repository provides one.
5. Confirm that autolinking still links every module class. With an `apple.modules` list, each entry must match a Swift class name as it now stands. Without the list, run the `scanModules` check in `references/compatibility.md` and confirm that it reports every class as `public` or `open`. A stale entry or a missed class builds clean and fails only at runtime, so the example app must actually resolve the module, not merely compile.
6. Compare the final exported surface with the inventory from step 1. The `scanExports` check in `references/compatibility.md` lists the JS names, parameters, and sync/async shape of every migrated member. Members that stay in the DSL are not in its output.
7. Search for stale `Name`, migrated `Function`/`AsyncFunction`/`StaticFunction`/`StaticAsyncFunction`/`Property`/`Constant`/`Events` entries, old `sendEvent` calls, `@Field`, and duplicate registrations. Search the source you wrote, not macro expansion output.
Expansion alone is insufficient: `swift:check` runs only the macros, so generated code with no diagnostics can still fail to link or run against a mismatched core. If dependencies changed or macro plugin flags are missing, reinstall JS dependencies as appropriate, run the repository's CocoaPods installation workflow, and restart Xcode before diagnosing plugin communication failures.
## Handoff
Never print macro-generated or core-internal symbol names to the user. `references/compatibility.md` cites them so you can grep for them, and the `swift:expand` output is full of them, but they are implementation details that change between plugin revisions, and they are noise in a report. Name a capability by its macro (`@JS static`, `@Event(sync:)`) and by observable JS behavior. Say "the installed core does not support synchronous events yet", not the name of the missing method. The exception is a tracking issue on `expo/expo`, where the specific missing hook is the point.
Report:
- which members moved to 2.0
- which members intentionally remain in the 1.0 DSL and why
- any compatibility-sensitive choices, especially event names, record requiredness, constants, and queues
- the commands run and any verification not completed
## Submitting Feedback
If you encounter errors, misleading or outdated information in this skill, report it so Expo can improve:
```bash
npx --yes @expo/agent-cli@latest feedback --category skills --subject "expo-migrate-module" "<actionable feedback>"
```
Only submit when you have something specific and actionable to report. Include as much relevant context as possible.
If an agent repeatedly fails at an Expo task or the user has to step in, submit a brief report of the task, expected result, and what went wrong using `--category evals` and the relevant Expo package or command as `--subject`.