@swiftbrowser/cli#
Run an iOS SwiftUI app in the browser, from its Xcode project, without a Mac.
npx @swiftbrowser/cli doctor --install # Swift 6.4, the wasm SDK, wasm-opt
npx @swiftbrowser/cli init MyApp # a new SwiftUI app, as an Xcode project
npx @swiftbrowser/cli dev ~/Projects/MyApp # http://localhost:5173, rebuilds on save
npx @swiftbrowser/cli test ~/Projects/MyApp # the app's unit tests, in WebAssembly
npx @swiftbrowser/cli build ~/Projects/MyApp # ./dist: a static site to deploy anywhere
npx @swiftbrowser/cli native init MyApp # the other way round: a native iOS app whose logic is JavaScript
The app's sources compile unchanged against SwiftBrowser's SwiftUI shim and run as WebAssembly inside an iPhone frame (or full screen on a phone: open the dev server's QR code, then Share → Add to Home Screen). What the shim does not provide is a compile error, never a wrong rendering.
Commands#
| Command | What it does |
|---|---|
init [<dir>] |
Writes a new SwiftUI app into <dir> (default ., created if missing): an Xcode 16 project (<Name>.xcodeproj, an app target for iOS 18 and a unit-test target hosted by it, with a shared scheme) whose sources live in synchronized folders: <Name>/ (<Name>App.swift, ContentView.swift, an asset catalog) and <Name>Tests/ (a Swift Testing test of ContentView), plus a .gitignore and a README. It opens in Xcode as is (⌘U runs the test), runs with dev and tests with test; any Swift file added under <Name>/ or <Name>Tests/ belongs to both. --name <Name> sets the app name (default: from the directory, my-app → MyApp), --bundle-id the bundle identifier (default com.example.<Name>). An existing directory is fine as long as <Name>.xcodeproj, <Name>/ and <Name>Tests/ are free; its .gitignore gets the missing lines and its README is kept. |
doctor [--install] |
Checks Node ≥ 22, Swift 6.4, the Swift SDK for WebAssembly and wasm-opt; --install fetches the SDK (swift sdk install) and Binaryen into ~/.cache/swiftbrowser. Swift itself comes from swiftly (swiftly install 6.4.0), or point SWIFT_TOOLCHAIN_BIN at a toolchain's usr/bin. |
check <path> |
Lists what the app imports (supported / rewritten / unsupported, with the usual way around each), then compiles the app natively against the shim. Seconds, no wasm; every error names your file and line. |
dev <path> |
Builds the app for WebAssembly and serves it with the SwiftBrowser dev server at /, in an iPhone frame with dark mode and text size controls on a desktop, full screen on a phone; saving a Swift file rebuilds and reloads with the app's state carried over. --port, --host (expose on the LAN for phones; the command prints a QR code of the network address), --open. |
build <path> [-o dist] |
A release build, optimized and stripped with wasm-opt (17.4 MB for a small app, 4.5 MB with brotli), and a complete static site around it: the app at /, filling the window on every screen (a desktop browser gets the regular-width layout; ?mode=frame shows the iPhone frame), its manifest and catalogs. --no-optimize skips wasm-opt. |
test <path> |
Builds the app's unit tests for WebAssembly against the kit and runs them under Node's WASI, the runtime the browser runs the app in: XCTest and Swift Testing, each when some test imports it. The tests are the Xcode project's unit-test targets that depend on the app or load into it (TEST_HOST), each a module that can @testable import the app, or for a folder of sources the Swift files under its Tests and *Tests folders. A failing test, or a trap, fails the command (exit 1); errors name your files. The module runs with V8's optimizing tier off (--no-wasm-tier-up): with it on, a run could stop after every test had started and before any reported, and a test run is too short for optimized code to pay off. 11 s for a new app's test after the kit is built. UI test targets are not run, and Bundle.main holds none of the app's resources yet. |
kit |
Compiles SwiftBrowser for WebAssembly ahead of a build (the first dev or build does it otherwise) and prints where the kit is. |
native init [<dir>] |
Writes a SwiftBrowser Native app: an iOS and macOS app whose views are real SwiftUI and whose logic is a @swiftbrowser/react app running in JavaScriptCore. <Name>.xcodeproj holds one app target, built for iOS and for macOS, over apple/ (<Name>App.swift, three lines around NativeApp and NativeRootView; the asset catalog; the app.js bundle; the Mac build's entitlements) and depends on the Swift package @swiftbrowser/native ships, at node_modules/@swiftbrowser/native/swift; the project's root is the JavaScript project (npm install, then npm run build writes the bundle and npm run dev serves it with rebuild and Fast Refresh on save, with SB_DEV_SERVER enabled in the scheme). --name, --bundle-id as for init; --package <dir> depends on another SwiftBrowserNative package (a checkout's Native/); --icloud gives the app an iCloud Drive container (apple/<Name>.entitlements naming iCloud.<bundleId> for documents, and an apple/Info.plist that shows its Documents in the Files app), which fileManager.iCloudDirectory() answers once the App ID has the iCloud capability; --sign-in-with-apple adds the Sign in with Apple entitlement for signInWithApple and SignInWithAppleButton; --launch-background <#rrggbb> colors the launch screen (a LaunchBackground color set the generated launch screen names through an apple/Info.plist), which NativeRootView(app:background:) can continue behind the first frame while the bundle loads. --import-type <identifier>=<.ext>[,<.ext>…][:<description>] (repeatable) declares a file type the app opens that the system does not know (com.steinberg.vst.fxp=.fxp:VST 2 preset) in the apple/Info.plist's UTImportedTypeDeclarations, so a fileImporter naming its extension offers those files on iOS and macOS rather than any file. --with <name> (repeatable or comma-separated) links an optional Swift package and installs it in the App: local-model (SwiftBrowserLocalModel, an open language model on the device for LanguageModelSession where Apple Intelligence can't answer) or dsp (SwiftBrowserDSP, for @swiftbrowser/dsp's DSPNode). --github writes GitHub Actions workflows that call SwiftBrowser's reusable ones at this release: web.yml deploys the web page to Cloudflare Pages (pull requests to a commented preview), ios.yml makes an ad hoc iOS build installed over the air from the same project's ios alias, macos.yml a notarized Mac app downloaded from its mac alias; they go in the repository's .github/workflows (the nearest folder up with a .git), named for the app and limited to its folder when it is inside a larger repository. |
native add <name> [<dir>] |
Links an optional Swift package into an existing native app's Xcode project: the package from beside the SwiftBrowserNative one the project references (node_modules/@swiftbrowser/native/swift/Packages/<Package>) and its product in every target that links SwiftBrowserNative. Prints the line to add to the App's init; running it again changes nothing. |
native build <entry> --out <file> |
Bundles the app's entry module (src/index.tsx) into the app.js the Xcode target ships (--minify, --sourcemap), as the project's npm run build does through swiftbrowser-native. --worker <name>=<entry> (repeatable) bundles a worker beside it as <name>.worker.js, for createWorker(name): a second JavaScriptCore context on a thread of its own, as a page has a Web Worker. |
native dev <entry> --out <file> |
Serves the bundle with rebuild on save for NativeApp.watch(url:) (--port, default 5173). |
native site <entry> --out <dir> |
The native app as a static site the web renderer runs: the SwiftBrowser Native views compiled for WebAssembly against the shim (the module @swiftbrowser/native ships; --module <file> for another), the bundle and the page, in the layout build writes. --base /path/ for a site served under a path of another site, --catalog <dir.xcassets> (repeatable) for the app's named images, --worker <name>=<entry> (repeatable) for the app's workers, published beside the bundle for the page's Worker, --name <App> for the site's app name, --minify. |
<path> is an .xcodeproj, a folder holding one (directly or one level
down), or a plain folder of Swift sources. Options for all of them:
--target <name> when the project has several app targets, --platform ios|macos
(the platform the app is built for: which os() condition holds in its sources
and the window the page shows it in; iOS by default, see docs/notes/macos.md),
--config <file>, --verbose.
dev and build build apps against SwiftBrowser compiled ahead of time
(with Swift 6.4 and its Swift SDK for WebAssembly): every module of the shim,
and an archive of each module's objects, in a kit under
~/.cache/swiftbrowser/kits/ (SWIFTBROWSER_CACHE moves the cache). A
released CLI comes with its kit, @swiftbrowser/kit (36 MB to download): the
first build copies it into the cache and checks that your toolchain reads its
modules. Its macros (@Model, #Predicate, @Entry) come built as
WebAssembly, the same files on every host: the toolchain runs them through a
small launcher in @swiftbrowser/wasm-compiler, under the Node that runs the
CLI. Where the kit cannot serve (Windows, where the compiler runs no
launcher script; a toolchain whose compiler reads only modules it wrote), or
in a checkout of this repository, the first build compiles the kit itself, in
a minute or two. A kit takes 83 MB: 50 MB of archives, 15 MB of
modules and the 18 MB macro executable; SwiftPM's scratch path for building
kits takes 325 MB more.
Every app built after that, in any project, compiles its own code and
packages only: Counter's Swift build takes 6 s where it took 100 s. The app's
staged package depends on a package in the kit that stands in for
SwiftBrowser's, with the same products, whose targets link the archives of
the modules the app's imports need, and the compiler finds the modules
themselves in the kit (src/kit.ts). The kit is named by the shim's sources,
the toolchain and the SDK, so a change to any of them (a newer
@swiftbrowser/cli, an edit to the shim in this repository) builds another;
SwiftPM's scratch path for kits stays in the cache, so that rebuild compiles
only the modules the change touched, and the three most recent kits are kept.
SWIFTBROWSER_KIT=0 builds the shim from its sources in the app's own build
instead, as before kits. A native check compiles for the host against the
shim's sources and does not use the kit.
The WebAssembly compiler#
--compiler (or SWIFTBROWSER_COMPILER, which the flag overrides) picks
what compiles the app in check, dev, build and test (src/compiler.ts):
| Value | Builds with |
|---|---|
auto (the default) |
the Swift toolchain when it is installed (it builds faster), else the WebAssembly compiler, saying why |
native |
the Swift toolchain and SwiftPM |
wasm |
the Swift compiler and linker built as WebAssembly (@swiftbrowser/wasm-compiler, the tools from @swiftbrowser/wasm-tools or SWIFTBROWSER_WASM_TOOLS): no Swift install |
So with Swift installed nothing changes, and without it npx @swiftbrowser/cli dev builds with the npm packages alone, once
swiftbrowser doctor --install has downloaded the Swift SDK for
WebAssembly's files.
The WebAssembly compiler builds against the kit and needs only the Swift
SDK for WebAssembly's files: the toolchain's install, or, without a
toolchain, the CLI's own copy (swiftbrowser doctor --install; src/wasmSdk.ts).
That copy comes from npm: the SDK's files the compiler reads, split into
packages by who needs them (@swiftbrowser/wasm-sdk, -foundation, -icu,
-icu-data, -testing and -cxx, at the CLI's version; src/sdkPackages.ts),
51 MB to download and laid out in the cache as one SDK. A CLI whose version
has no such packages downloads swift.org's pinned bundle instead (93 MB).
Without a toolchain it uses the released
kit (@swiftbrowser/kit, checked by type-checking an import of every module)
and cannot build one. It runs the kit's macros
built as WebAssembly: @swiftbrowser/kit has them, and a kit made here gets
them from swiftbrowser kit --wasm-macros or the first WebAssembly build
(with a toolchain; minutes the first time, swift-syntax compiling for
WebAssembly). check type-checks against the kit with it. Package
dependencies build with it too: without SwiftPM in charge (no toolchain, or
--compiler wasm), the CLI resolves them with git, honouring
Package.resolved (src/resolve.ts; registry packages from their
registry, src/registry.ts), and runs their manifests with the
WebAssembly tools (src/manifest.ts; @swiftbrowser/wasm-tools ships SwiftPM's
PackageDescription for this), caching both. C targets in packages compile
with clang built as WebAssembly, and package traits are followed; Ice Cubes
builds this way. A package's macro targets (TCA's) build as WebAssembly
plugins, swift-syntax compiled for them alone (minutes the first time, then
cached). The packages' compiled modules are cached too, keyed by their
inputs (src/moduleCache.ts): a rebuild compiles only what an edit reaches,
and apps share the modules of the packages they have in common. test
builds with it too: the app as a testable module, each test target against
it, and a runner like SwiftPM's (XCTest's tests listed from the test
module's symbol graph, Swift Testing's found as it runs; src/testDiscovery.ts),
with swift-testing's macros built as WebAssembly. In
dev it compiles unoptimized (-Onone, without a DEBUG define, so the app
behaves as it will in build) and keeps the compiled tools between
rebuilds: a save rebuilds Counter in about 5 s, as SwiftPM does.
Building several apps in a row (a CI job, a script) can compile the
SwiftBrowser package once for all of them: set SWIFTBROWSER_BUILD_ROOT to a
directory, and every app is staged at <root>/<Name>/ and built with one
SwiftPM scratch path, <root>/.build. After the first app, a check takes a
few seconds instead of compiling the shim natively again. SwiftPM recompiles a
dependency when the staging package's parent directory changes, which is why
apps staged in their own projects cannot share it. One build at a time per
root (SwiftPM locks the scratch path), and two apps with the same name take
turns in the same staging directory.
What happens to your project#
Nothing, outside <project>/.swiftbrowser/ (add it to .gitignore), or
outside $SWIFTBROWSER_BUILD_ROOT when that is set. The CLI
reads the Xcode project (project.pbxproj, including Xcode 16 synchronized
folders) for the app target's Swift sources, asset catalogs, display name and
app icon, then writes a SwiftPM package under .swiftbrowser/<Name>/ whose one
executable target is a copy of those sources, adjusted for the shim:
import SwiftUIalso imports Foundation and the shim'sFoundationBridge(Apple's SwiftUI re-exports Foundation and Combine, soUUID,JSONEncoder,UserDefaults,Timer.publishare in scope without an import). Both it andimport Foundationalso import Observation, so@Observableworks in a file that imports only Foundation, as it does under Xcode;import FoundationbringsFoundationBridgetoo, so a default argument such assession: URLSession = .sharedfinds the bridge'sshared.x as? AnyObjectbecomesx as? _AnyObjectValuein a file that reads a number off it (.doubleValue,.intValue…), which Objective-C looks up on any object at run time.- A generated
_SwiftBrowserFoundation.swiftsettles the names both the shim and Foundation declare (CGFloat,CGPoint,CGSize,CGRect,Timer,RunLoop,UserDefaults,Bundle,DispatchQueue) with typealiases, in the shim's favor, and brings what Darwin's Foundation has and Linux's lacks (OperationQueue,CFAbsoluteTimeGetCurrent,os_unfair_lock, associated objects). - The target's Copy Bundle Resources (or
resourcesinswiftbrowser.json) are served next to the module and mounted at/bundlebefore the app starts, soBundle.main.url(forResource:withExtension:)andData(contentsOf:)read them. Asset catalogs are handled separately (Image("name"),Color("name")): the app's and its packages' make one catalog on the page; PNG, JPEG and SVG images are served as they are and PDF images (vector artwork) as the PNGs pdf.js renders them to at 3×. Swift reads the catalog too: the page mounts, in the bundle'sAssets.carfolder, the file of each image set iOS loads on a 3x iPhone (and the dark one, when the set has it) and each data set's file, soUIImage(named:)has the image's bytes, size and scale (pngData(),jpegData(compressionQuality:),cgImage, drawing into a renderer) andNSDataAsset(name:)its data, with no resource folder of copies. - Each module gets the asset symbols Xcode generates from its catalogs: a
static member of
ImageResourceorColorResourceper image, symbol and color set (Image(.floor1),ImageResource.Fountain.terracottain a namespace folder), and theColor/ShapeStylemembers (.foregroundStyle(.accent)) when the target setsASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS, as Xcode's templates do. - Each Core ML model becomes
<Class>.mlmodel.swift, the class Xcode would generate for it with the model embedded (see "Core ML" below). #Preview { … }blocks andPreviewProviderstructs are blanked (the shim has no previews).- Submodule imports of the shim's frameworks (
import UIKit.UIImage,import os.log) import the module;delegate?.urlSession?(…)(an Objective-C optional call) becomesdelegate?.urlSession(…); andProcessInfo.processInfo.physicalMemory, which reads 0 on WASI, becomes 4 GiB there. - What Swift allows only with the Objective-C runtime is rewritten
(
packages/cli/src/objc.ts): an@objcprotocol becomes class-bound and itsoptionalrequirements plain ones with default implementations (nothing forVoid, nil for an optional, the zero ofBool, numbers, strings and collections; a requirement obsoleted in Swift is removed); calls written for an optional requirement (delegate?.method?(…), in any file of the module) call it plainly; anoverridein an extension (description,isEqual(_:)on anNSObjectsubclass) is removed, so the superclass's stays;#keyPath(Type.property)becomes"property"; andProcessInfo()becomesProcessInfo.processInfo. What remains of the runtime (calling a method on a class found withNSClassFromString, anIMPfrommethod(for:)) does not compile and has to go behind#if !SWIFTBROWSER. SWIFTBROWSERis defined, so platform-specific code can go behind#if SWIFTBROWSER/#if !SWIFTBROWSER, like#if os(iOS).
Every change keeps line numbers, so compiler diagnostics point at your files.
The package depends on @swiftbrowser/swift (the shim at the version this CLI
was released with).
test stages the app the same way in a package of its own,
.swiftbrowser/<Name>.tests/, so that switching between test and dev
rebuilds neither from scratch. Each unit-test target is a test target in it
that depends on the app's. Its files get the same adjustments, along with
the generated alias file, because a test module imports both Foundation and
the app. It links the SDK's whole ICU data rather than a trimmed copy. The
WebAssembly compiler builds the same staging without SwiftPM.
Foundation#
Apps link the real Foundation (swift-corelibs-foundation, as the wasm SDK
ships it): DateFormatter, NumberFormatter, NSString, Locale-aware
formatted(), Measurement, NSRegularExpression, JSONEncoder, and the
rest compile as on iOS. Measured through the pipeline (release, wasm-opt -Oz, stripped) on the Counter example:
| ICU data | Module | gzipped | brotli |
|---|---|---|---|
| trimmed to English (default), 3.9 MB of it | 17.4 MB | 6.5 MB | 4.5 MB |
"locales": ["*"], the whole 34 MB package |
47 MB | 19 MB | 12 MB |
The SDK's Foundation carries ICU's complete 34 MB locale data package; the CLI
pulls that package out of the SDK's archive, keeps the locale-independent
tables plus the bundles of the languages in "locales" (default ["en"];
the region part of a tag is ignored, every regional variant of a language
stays), and links the trimmed package in the original's place. Formatting for
a language that was dropped falls back to ICU's root locale (11/14/2023, 22:13 and € 0.00 for French instead of 14/11/2023 22:13 and 0,00 €); it
never fails. Each language adds 100 to 300 kB, Chinese 1.7 MB (its collation
table); ["*"] keeps everything. Dropped for good: the legacy character-set
converters (String(data:encoding:) with Shift JIS, Windows-1252 and the like
returns nil; UTF-8/16/32, ASCII and Latin-1 need none), the StringPrep
profiles and the spoof-checker data. "collation": false also drops the
collation tables (0.9 MB) when the app never compares strings in a locale:
localizedCompare, localizedStandardCompare and .localizedStandard
sorting then order by Unicode scalar. locales also chooses the languages
of the app's string tables: its string catalogs (.xcstrings) and
<language>.lproj .strings / .stringsdict files are compiled for those
languages and the catalog's source language, as Xcode compiles them (Text,
String(localized:) and Bundle.localizedString look keys up in them). The
trimmed package is cached per SDK,
language set and collation choice under ~/.cache/swiftbrowser/icu/; the SDK
itself is not modified.
What Foundation lacks on WASI, the shim's FoundationBridge supplies: Timer
(corelibs' needs a run loop WASI does not have) with Timer.publish +
onReceive, and RunLoop.main for its signature; UserDefaults, which
Foundation's cannot persist on WASI, saved by the browser per app
(localStorage) and restored at the next launch; Bundle, whose Foundation
counterpart traps, reading the app's resources; and URLSession, URLRequest,
HTTPURLResponse, URLError and AsyncImage over the browser's fetch
(corelibs moved networking to FoundationNetworking, which the SDK does not
ship); and UndoManager, which corelibs does not have at all, as the
shim's (one per app, in @Environment(\.undoManager), with the page's ⌘Z
and ⇧⌘Z bound to it). Known gaps of corelibs Foundation on WASI:
NotificationCenter's closure observers and OperationQueue are missing.
Earlier releases had a lean mode (FoundationEssentials plus a small
formatting layer, about a quarter of the size). It is gone: --foundation
and "foundation" in swiftbrowser.json are accepted and ignored with a
warning, and an import FoundationLite becomes import FoundationBridge.
Locale and time zone#
The app runs in the viewer's time zone and, within the languages it ships, the
viewer's language, as an iOS app follows the device: Locale.current,
TimeZone.current, formatted(), DateFormatter and Text(_:format:) all
follow. The browser's first preferred language whose data the module carries
("locales") is used with its region, so a British visitor to an app shipping
["en"] gets 14/11/2023; a visitor whose language is not shipped gets the
first shipped language rather than a half-formatted root locale. Add
?locale=fr-FR to the app URL to try a locale without changing the browser
(an Xcode scheme's "App Language"). The headless harness pins en_001 and
GMT unless SB_LOCALE / TZ are set, so snapshots stay stable. Lean mode
formats in US English regardless.
The hook behind this: swift-foundation hard-codes en_001 on WASI, so the
CLI redirects that one function to FoundationBridge at link time
(--wrap); it depends on the SDK's swift-foundation, which the CLI pins and
CI checks.
swiftbrowser.json (optional)#
{
"name": "MyApp",
"displayName": "My App",
"target": "MyApp",
"sources": ["MyApp"],
"exclude": ["MyApp/Watch"],
"catalogs": ["MyApp/Assets.xcassets"],
"resources": ["MyApp/missions.json", "MyApp/Data"],
"icon": "MyApp/Assets.xcassets/AppIcon.appiconset/icon-1024.png",
"swiftLanguageMode": "5",
"locales": ["en"],
"collation": true,
"defines": ["DEMO"],
"corsProxy": "https://swiftbrowser-cors-proxy.you.workers.dev/",
"packages": [
{ "url": "https://github.com/twostraws/CodeScanner", "from": "2.5.2", "products": ["CodeScanner"] },
{ "id": "mona.LinkedList", "from": "1.2.0", "products": ["LinkedList"] },
{ "path": "../Shared", "products": ["SharedKit"] }
]
}
Everything is optional; sources, catalogs and resources replace what the
Xcode project says when set (a plain folder has resources only through the
config); locales and collation pick the ICU data that ships (see above).
A file in resources lands at the bundle's top level under its own name; a
folder keeps its name and structure, like a folder reference in Xcode:
"MyApp/Audio" puts morning.wav at /bundle/Audio/morning.wav, found with
Bundle.main.url(forResource: "morning", withExtension: "wav", subdirectory: "Audio"). To have the files at the top level, list them (or the folder's
files) one by one.
packages adds Swift packages to the ones the Xcode target links: the only
way a plain folder of sources depends on one. Each has a url with one rule
(from: up to the next major version, exact, branch or revision), a
package registry's id (scope.name) with from or exact, or a local
path (relative to the project), and the products the app imports. They
are built as described in "Swift packages". Registries are configured as
SwiftPM configures them (swift package-registry set):
.swiftpm/configuration/registries.json in the app's folder, then in your
home folder, with credentials in ~/.netrc; packages that depend on
registry packages (.package(id:)) find them the same way.
corsProxy (or --cors-proxy <url> on dev and build) names a CORS proxy:
the page retries a cross-origin GET or HEAD the browser refused (the server
does not allow the page's origin, as image servers often don't) through
<corsProxy>?url=<target>. The proxy is a small Cloudflare Worker you deploy
yourself (packages/cors-proxy);
it is meant for screenshots and demos.
blockHosts (or --block-host <host>, repeatable) makes the app's requests
to those hosts and their subdomains fail as if offline, without leaving the
page. It is for a public deploy of an app whose analytics or other services
belong to someone else, such as Ice Cubes' TelemetryDeck signals.
A module larger than 24 MiB (Cloudflare Pages takes files up to 25 MiB) is
published as <App>.wasm.0, .1… with a <App>.wasm.parts.json manifest,
and the page joins the parts before compiling (so does scripts/run-wasi.mjs,
given <App>.wasm). Unoptimized builds (--no-optimize) are often this
large.
On Linux, Binaryen's release wasm-opt is linked against musl, whose threads
get 128 KiB stacks; a large module overflows them. The CLI runs a copy (made
once, in its cache) whose program header asks musl for 8 MiB thread stacks,
so wasm-opt uses every core: 106 s for Ice Cubes on four, where one thread
took 300 s, for the same module byte for byte (src/threadStacks.ts). If it
still crashes, the CLI runs it again on one thread with a large stack.
The app target's language mode (SWIFT_VERSION) and concurrency settings come
from the Xcode project as well: SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor
becomes .defaultIsolation(MainActor.self) in the staged package, and
SWIFT_APPROACHABLE_CONCURRENCY and each SWIFT_UPCOMING_FEATURE_… its
upcoming features (those the language mode does not have already), so an app
written against Xcode 26's main-actor default compiles as it does in Xcode.
Frameworks#
Supported: SwiftUI (see the shim's
compatibility matrix), Observation, Swift Charts, Foundation, networking (URLSession,
URLRequest, HTTPURLResponse, URLError and AsyncImage run over the
browser's fetch, so the servers an app talks to must allow its origin, CORS),
and SwiftData: @Model, ModelContainer, ModelContext, @Query,
#Predicate, relationships with their delete rules, autosave. The models live
in memory while the app runs and the page keeps them in IndexedDB, one database
per app (sb-swiftdata:<App>); ?swiftdata=reset on the app's URL starts it
with no data. An app that imports SwiftData also builds SwiftData's macros,
which need swift-syntax: SwiftPM fetches it on the first build and uses its
prebuilt release where swift.org publishes one (Swift 6.4 on Linux and macOS),
else compiles it once (several minutes).
Files an app writes in its home (URL.documentsDirectory and the other
iOS directories, through Data, String or FileManager) are kept the same
way, in sb-files:<App>; ?files=reset starts with none.
check names the frameworks it knows have no browser counterpart yet (Core
Data, WidgetKit, Metal, …) with the usual way out: keep that code
behind #if !SWIFTBROWSER and give the browser a stand-in behind
#if SWIFTBROWSER.
The frameworks under SwiftUI that libraries build on are there, as far as
image and utility code uses them: UIKit's UIImage, UIColor and
UIScreen (its view classes exist so that code declaring UIKit views
compiles; none can be shown), Core Graphics contexts that draw, scale and
clip images, Image I/O sources, Combine (OpenCombine), CryptoKit's hashes and
os's locks and logs. AVKit and AVFoundation are empty: an unused import
compiles, and check warns about it. With them, real packages such as
Nuke build from their own sources.
StoreKit, Core Location and LocalAuthentication import fine, as far as apps
usually use them: requestReview does nothing, CLLocationCoordinate2D is a
plain struct (CLLocation measures distances), and an LAContext evaluation
always succeeds. MapKit's SwiftUI
Map draws its region without map data: a plain surface with latitude and
longitude lines, with its annotations, markers and overlays where they are on
it; MapReader converts a tap's location to a coordinate. It does not pan or
zoom. UIKit's MKMapView draws the same map at its camera. RealityKit's
RealityView, entities, components and systems run in Swift and draw with
three.js, models from USDZ files included (docs/realitykit.md;
experimental). The page's half, @swiftbrowser/reality
and the three.js it pins, is downloaded into the cache the first time the CLI
builds an app that imports RealityKit; other apps never fetch it. WeatherKit's
requests throw WeatherError.permissionDenied (Apple's service answers only
apps signed with the capability), and passkey and password requests
(ASAuthorizationController, SwiftUI's AuthorizationController) end in
ASAuthorizationError.notHandled, so an app takes its own fallback. PhotosUI's
PhotosPicker opens the browser's file chooser, and the picked files' bytes
load with loadTransferable(type: Data.self). Core Image
(import CoreImage, or import CoreImage.CIFilterBuiltins, which the staging
turns into import CoreImage) has its common built-in filters and the QR code
generator, drawn by the page; UIImage and CGImage come with SwiftUI, as on
iOS. UserNotifications runs over the browser's Notification API: the app asks
for permission with the browser's prompt, schedules its requests with timers of
its own and the page shows each one as it comes due. Notifications are
delivered only while the page is open (a closed tab delivers nothing), and
Safari on iPhone shows them only for an app added to the Home Screen.
Core ML#
The target's Core ML models (.mlmodel files and .mlpackage bundles in its
Sources phase or synchronized folders; in a plain folder, every one found, or
those "sources" names) compile into the classes Xcode generates for them:
SleepCalculator.mlmodel becomes SleepCalculator, SleepCalculatorInput
and SleepCalculatorOutput, with init(configuration:),
prediction(wake:estimatedSleep:coffee:) (each input typed as Xcode types
it), prediction(input:), predictions(inputs:), the load functions,
model and urlOfModelInThisBundle. The CLI reads the model's protobuf and
embeds its specification in the class; the shim's CoreML module evaluates
it (MLModel, MLFeatureValue, MLMultiArray, MLDictionaryFeatureProvider
and friends). That covers what Create ML makes from tables: linear and
logistic regression, boosted trees, random forests and decision trees, and
the one-hot encoders, imputers, normalizers, scalers and vectorizers around
them. Any other model (a neural network, an ML program, an image, sound or
text model) stops the build with its type named, for example
Classifier.mlmodel: the model is a neural network (neuralNetwork), which the browser cannot run. dev rebuilds when a Swift file changes; a retrained model
is picked up by the next rebuild.
Swift packages#
The Xcode target's package dependencies (File › Add Package Dependencies) are added to the staging package: each remote package with the version rule Xcode records (up to next major or minor, exact, a range, a branch or a revision), each local package by path. SwiftPM fetches and builds them for the browser with the app, so a pure-Swift package works if it builds for WASI.
A package that imports SwiftUI (or Charts, SwiftData, or another framework
SwiftBrowser stands in for) is built against the shim, from a copy under
.swiftbrowser/<Name>/Packages/: its sources get the same adjustments as
the app's, and lines appended to its manifest link the shim's modules to the
targets that import them and define SWIFTBROWSER. A package that depends
on such a package, directly or not, is copied too and pointed at the copy.
Your package folders and SwiftPM's checkouts are never written to.
A package that cannot work in the browser and that SwiftBrowser knows is
replaced by a module of the same name instead, and never fetched (when one of
your packages depends on it, that package gets the stand-in too). Today
there are none.
WrappingHStack builds from its own
sources: it measures its items with UIHostingController, whose
sizeThatFits(in:) answers from the page's measurements a render later.
CodeScanner builds from its own
sources over AVFoundation's capture sessions: it scans with the camera where
the browser has BarcodeDetector (Chrome on Android and macOS) and asks
for the code's text elsewhere. check lists each package and which way it
went:
✓ package CodeScanner (github.com/twostraws/CodeScanner, exactly 2.5.2): built against the shim (CodeScanner imports AVFoundation, SwiftUI, UIKit) (CodeScanner)
✓ package Nuke (github.com/kean/Nuke, exactly 13.2.0): built against the shim (Nuke imports AVKit, Combine, CoreGraphics, CoreImage, CryptoKit, ImageIO, UIKit, UniformTypeIdentifiers, os; NukeUI imports Combine, SwiftUI, UIKit; …) (Nuke, NukeUI)
✓ package swift-algorithms (github.com/apple/swift-algorithms, up to next major from 1.2.0): a SwiftPM dependency of the build (Algorithms)
✓ package Tags (/work/Tags): built against the shim (Tags imports SwiftUI) (Tags)
✓ package SwiftUI-Shimmer 1.5.1, a dependency of a dependency: built against the shim (Shimmer imports SwiftUI)
A package's type: .dynamic libraries are built as automatic ones (the
browser build is one module), so Apple's Backyard Birds sample builds with
its three local packages as they are:
git clone --depth 1 https://github.com/apple/sample-backyard-birds
npx @swiftbrowser/cli dev sample-backyard-birds --target "Backyard Birds"
Apple's Food Truck sample builds as it is too:
git clone --depth 1 https://github.com/apple/sample-food-truck
npx @swiftbrowser/cli dev sample-food-truck --target "Food Truck"
The Composable Architecture
builds as it is, with the packages it brings (swift-dependencies,
swift-navigation, swift-sharing, combine-schedulers and the rest): its
macros (@Reducer, @ObservableState, @DependencyClient) build as
plugins, and its packages are copied and built against the shim like any
other. swift-navigation's UIKit layer builds over the shim's UIKit, whose
views and view controllers are NSObjects with iOS 17's traits; the
Objective-C target it swizzles view controllers with is the shim's own
lifecycle hooks here. Code a package keeps for older systems
(#if canImport(ObjectiveC), CoreFoundation imports, -ObjC link flags,
KVO overrides) is adjusted in its copy (src/appSources.ts, vendor.ts). The
TCACounter fixture (packages/cli/test/fixtures/apps) is a counter, with
the versions it was made with pinned in its Package.resolved.
A package SwiftBrowser has a patch for is built from its own sources with a few passages replaced first: code that only works with the Objective-C runtime and no general adjustment can take. Today that is RevenueCat, patched for 5.102.3 (packages/cli/src/packagePatches.ts). The patch names each passage exactly; when the version SwiftPM resolves no longer has one, the build stops and says which, and the package has to be pinned to the release the patch was written for (or the patch updated).
A package that needs a framework the browser has no counterpart for (Core
Data, Metal, a UIKit view on screen…) fails to compile with an error naming
it; keep its uses behind #if !SWIFTBROWSER in your own packages. Images a
package downloads itself (Nuke does, with URLSession) go through the
browser's fetch, so their host must allow CORS. The SwiftUI it uses is held
to the same compatibility as an app's.
Example#
All twenty "Hacking with SwiftUI" projects run from their Xcode projects without a change (WeSplit, Guess the Flag, Views and Modifiers, BetterRest, WordScramble, Animations, iExpense, Moonshot, Navigation, Cupcake Corner, Bookworm, SwiftDataProject, Instafilter, Bucket List, Accessibility, Hot Prospects, Flashzilla, Layout and Geometry, SnowSeeker, Drawing):
git clone --depth 1 https://github.com/twostraws/HackingWithSwift
npx @swiftbrowser/cli dev HackingWithSwift/SwiftUI/project4 # BetterRest: Core ML
npx @swiftbrowser/cli dev HackingWithSwift/SwiftUI/project13 # Instafilter: PhotosPicker, Core Image
npx @swiftbrowser/cli dev HackingWithSwift/SwiftUI/project14 # Bucket List: MapKit, Face ID
npx @swiftbrowser/cli dev HackingWithSwift/SwiftUI/project16 # Hot Prospects: CodeScanner (the real package), notifications
npx @swiftbrowser/cli dev HackingWithSwift/SwiftUI/project17 # Flashzilla
npx @swiftbrowser/cli dev HackingWithSwift/SwiftUI/project11 # Bookworm: SwiftData