BakeNative is under active development. APIs may change.
Skip to Content
BakeNative

System modules

Clipboard, Linking, Share and Haptics — registry modules an app adds with bake add, one API on every target.

Clipboard, Linking, Share and Haptics are registry modules: bake add clipboard copies the module's spec and its implementation for each target into native/clipboard/, and the app calls it as native.Clipboard (Adding modules). bake create adds all four. The app owns the files; the glue is generated on every build (Native modules). Names and behavior follow the web standards (navigator.clipboard, window.open / location, navigator.share).

ModuleWebiOSmacOSWindowsAndroid
clipboardyesyesyesyesyes
linkingyesyesyesyesyes
shareyesyesyesyesyes
hapticsyesyesyesno (build error, on purpose)yes

Native targets fail closed

A module supports the targets it has an implementation file for (.swift / .ios.swift / .mac.swift, .kt, .rs, .web.ts). A bundle that calls a module on a target without one is a build error (module-<name>), reported at the module's spec. A call inside a branch on import.meta.env.BAKE_TARGET is removed from other targets' bundles and builds clean.

import { native } from '@bake-native/octane';

const WEB = import.meta.env.BAKE_TARGET === 'web';

async function copyLink(url: string) {
  if (WEB) await native.Clipboard.writeText(url);
}

Clipboard

import { native } from '@bake-native/octane';

await native.Clipboard.writeText('hello');
const text = await native.Clipboard.readText();   // null when the clipboard holds no text
MemberReturnsWeb
writeText(text: string)Promise<void>navigator.clipboard.writeText. Where that API is missing or refuses, it falls back to document.execCommand('copy') on a hidden <textarea>.
readText()Promise<string | null>navigator.clipboard.readText. There is no fallback. The browser may ask for permission.

The async clipboard API needs a secure context (https, or localhost). Call writeText from a click or key handler, because browsers can refuse it without a user gesture.

Linking

import { host, native } from '@bake-native/octane';

await native.Linking.openURL('https://bake-native.com');       // web: a new tab
await native.Linking.openURL('mailto:hi@example.com');       // web: the mail app
const first = await native.Linking.getInitialURL();          // web: the page URL
const off = host.on('url', (url) => route(url));             // native: URLs received while running
MemberReturnsWeb
openURL(url: string)Promise<void>Opens http: and https: with window.open(url, '_blank'), with the new tab's opener cleared. Other schemes (mailto:, tel:, sms:, custom) are assigned to location.href, so the browser hands them to their app and the page stays. A blocked popup rejects with E_PERMISSION.
canOpenURL(url: string)Promise<boolean>true for any absolute URL that openURL accepts. false for an invalid URL.
getInitialURL()Promise<string | null>location.href when the module loaded.
getInitialURLSync()string | nullThe same, synchronously. Native: the host's launch URL (iOS, macOS, Android, Windows), else null. A router reads it before its first commit.

URLs the app receives while it runs are not a module member: every host sends them as the host event url (BakeNativeLinking.open on Apple, the running-instance hand-over on Windows), and the router subscribes to it when given linking: () => native.Linking. openURL and canOpenURL refuse javascript:, data:, blob: and about: URLs (E_ARGUMENT).

Share

import { native } from '@bake-native/octane';

const { action } = await native.Share.share({ title: 'BakeNative', text: 'Have a look', url: 'https://bake-native.com' });
// 'shared' | 'dismissed' | 'copied'
MemberReturnsWeb
share({ title?, text?, url? })Promise<{ action }>Uses navigator.share when the browser has it and navigator.canShare(data) allows the data. Closing the sheet resolves with dismissed, not an error. Without a share sheet (for example, desktop Firefox), it copies text and url joined by a line break to the clipboard and resolves with copied.

The data needs text or url. A title alone is not enough, and url must be an absolute URL (E_ARGUMENT). Browsers allow navigator.share only during a user gesture.

Only the modules an app uses

An app links only the modules its bundles call. A module that is never called, or called only inside a branch for another target, is neither in the bundle nor in the binary.

  1. bake build finds the modules in native/<name>/ the bundle still calls after tree-shaking (native.Clipboard or 'Clipboard' in native) and records first-party names in manifest.json requires.modules.

  2. The registration. It copies their implementations for the target into <app>/.bake/native/<target>/ with their generated contracts, and registers them: the Swift package BakeNativeAppModules (iOS, macOS), the Gradle module :bakenative-app-modules (Android), the crate bakenative-app-modules (Windows), and on the web the build loads their .web.ts. Unchanged files are not rewritten. bake native link writes it somewhere else, or for the union of several bundles (a host that shows more than one app):

    bake native link --target ios --root . --out ios/AppModules
    bake native link --target ios --bundle app-a/dist/ios --bundle app-b/dist/ios --out ios/AppModules

On iOS and macOS a screen passes the generated registry: BakeNativeViewController(bundle:, modules: BakeNativeBundleModules.root()), BakeNativeSurface(bundle:, modules: BakeNativeBundleModules.root()) or BakeNativeView(modules: BakeNativeBundleModules.root()) (AppKit). A registry module (from bake add, listed in bake-modules.json) is an entry; the generated code creates it. An app made by bake create is already wired up: calling a module from src/ needs no host change, only another build.

In this repository the framework still has build units for Clipboard, Linking and Share (the SwiftPM products BakeNativeModule*, the Gradle project :modules-share, the cargo feature module-linking): a bundle that calls one of those names without its own native/<name> links the framework's. An app's own copy always wins.

bake build --xcframework and bake package compile the used modules into the app's framework. The package lists first-party names as provides.modules in BakeNativePackage.json; an OTA update whose requires.modules names one the package does not contain is refused, and the package keeps running its embedded bundle (App packages).

iOS and macOS

BakeNativeView (iOS and macOS) registers the modules the app links (above), next to Platform, Storage and Haptics.

FunctioniOSmacOS
Clipboard.writeTextUIPasteboard.general.stringNSPasteboard.general, as .string
Clipboard.readTextUIPasteboard.general.string. Reading another app's text shows the system paste prompt. If the user denies it, the call rejects with E_PERMISSION.NSPasteboard.general .string
Linking.openURLUIApplication.open. Rejects with E_UNAVAILABLE when no app opened it.NSWorkspace.open. Rejects with E_UNAVAILABLE when no app handles the URL.
Linking.canOpenURLUIApplication.canOpenURL. http(s) always works. Another app's scheme answers true only when it is listed in the app's LSApplicationQueriesSchemes (Info.plist).NSWorkspace.urlForApplication(toOpen:)
Share.shareUIActivityViewController, presented over the view's window (a popover on iPad). shared when the user completed an activity, dismissed when they closed the sheet. The title is the subject (Mail).NSSharingServicePicker under the view. shared when the user picked a service, dismissed when the menu closed without one.
<!-- Info.plist: let canOpenURL answer for other apps' schemes -->
<key>LSApplicationQueriesSchemes</key>
<array>
  <string>maps</string>
  <string>whatsapp</string>
</array>

Incoming URLs

The app forwards the URLs it is opened with to BakeNativeLinking. The URL that launched the app is what Linking.getInitialURL() returns. A URL that arrives while the app runs is a url event on every running view.

// iOS: the scene delegate
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options: UIScene.ConnectionOptions) {
  BakeNativeLinking.launch(with: options)          // a custom scheme or universal link at launch
  …
}
func scene(_ scene: UIScene, openURLContexts contexts: Set<UIOpenURLContext>) {
  BakeNativeLinking.open(contexts)                 // while running
}
func scene(_ scene: UIScene, continue activity: NSUserActivity) {
  BakeNativeLinking.open(activity)                 // a universal link while running
}

// macOS: the app delegate
func application(_ application: NSApplication, open urls: [URL]) {
  urls.forEach(BakeNativeLinking.open)
}

// SwiftUI (either platform)
BakeNativeView(…).onOpenURL { BakeNativeLinking.open($0) }

An app delegate without scenes calls BakeNativeLinking.launch(with: launchOptions) in application(_:didFinishLaunchingWithOptions:) and BakeNativeLinking.open(url) in application(_:open:options:). UIKit hands the launch URL to both, and the second one is not sent again. A URL given to open before any view has started becomes the initial URL, because no view could receive it as an event (on macOS, a cold launch delivers its URL through application(_:open:)). When a view has already started, the URL is a url event instead, so listen with host.on('url', ...) as well as calling getInitialURL. Register the app's URL schemes (CFBundleURLTypes) or associated domains as for any iOS or macOS app.

Errors

Every function rejects with an Error whose code is one of the following (NativeError in the types, @bake-native/octane):

CodeWhen
E_ARGUMENTAn invalid argument: not a string, not an absolute URL, a refused scheme, or nothing to share.
E_UNAVAILABLEThe platform cannot do it, for example no clipboard API outside a secure context, or no app for the URL.
E_PERMISSIONThe platform refused, for example without a user gesture, after a denied permission prompt, or because of a popup blocker.
E_FAILEDAny other failure the platform reported.

Host contract (native implementations)

Each module's spec (registry/modules/<name>/<Name>.native.ts) is the contract; each platform's file implements the contract generated from it (Native modules). Adding a platform is adding its file next to the spec (and a new version of the module): that lifts the build error for that target. The generated glue checks argument types before the implementation runs; an implementation throws BakeNativeModuleError(code:_:) with the codes below for platform failures. The tables give each member's behavior on the native hosts.

Clipboard

MemberKindSignatureNotes
writeTextasync(text: String) -> VoidReplaces the general pasteboard with plain text (UIPasteboard.general.string, NSPasteboard.general .string, ClipboardManager.setPrimaryClip, Win32 CF_UNICODETEXT).
readTextasync() -> String?The pasteboard's text, or nil / null when it holds none. If the user denies the iOS paste prompt, throw E_PERMISSION.

Linking

MemberKindSignatureNotes
openURLasync(url: String) -> VoidOpens the URL with the system (UIApplication.open, NSWorkspace.open, an ACTION_VIEW intent, ShellExecuteW/Launcher). Throw E_UNAVAILABLE when no app handles it.
canOpenURLasync(url: String) -> BoolWhether an app handles the URL. On iOS, other apps' schemes must be listed in LSApplicationQueriesSchemes.
getInitialURLasync() -> String?The URL that launched the app (a universal link, custom scheme or file), or nil.
getInitialURLSyncsync() -> String?The same, synchronously on the JS thread, for hosts that know the launch URL before the bundle runs. The router then starts on that screen, so the first commit is already the deep link's screen. A host that implements it must also skip its first-screen snapshot when launched with a URL (the snapshot is baked with the initial tab).
host event urlroot.send("url", url)payload: StringOne event per URL received while the app runs (application(_:open:), onOpenURL, onNewIntent, protocol activation). host.on('url', (url) => …) receives it.

Windows implements Linking in registry/modules/linking/linking.rs on the host's link plumbing (bake-host-windows links): ShellExecuteW, the registered protocol handlers, the launch URL from the command line, and WM_COPYDATA from later launches to the running instance.

Android implements Linking in registry/modules/linking/Linking.kt with ACTION_VIEW intents. openURL starts one from the view's Activity (E_UNAVAILABLE when no app takes it). canOpenURL asks the package manager, which on Android 11 and later sees only the schemes the app lists in <queries> in its manifest: bake create's template lists http, https, mailto, tel, sms and geo. The launch URL is the data of the ACTION_VIEW intent that started the Activity, read when the module is created. A deep link while the app runs arrives in the Activity's onNewIntent (the template's Activity is singleTask), which sends it as the host event url with bakeNativeView.send("url", JSONObject.quote(url)). The template also registers the app's own scheme, its name (my-app://…).

Share

MemberKindSignatureNotes
shareasync(data: { title: String?, text: String?, url: String? }) -> { action: "shared" | "dismissed" } (copied is the web's)Presents the system share sheet (UIActivityViewController, NSSharingServicePicker, Intent.createChooser, DataTransferManager) and settles when it closes. At least one of text and url is set. url is already normalized.

A host that cannot tell whether the user completed sharing resolves shared once the sheet was shown. Android's chooser is an example: Share.kt sends the text and the URL, one per line, as an ACTION_SEND of text/plain, with the title as the subject and the chooser title. Settle each promise exactly once (see the rules in Native modules).

Windows implements Share in registry/modules/share/share.rs on the host's share plumbing (bake-host-windows share): DataTransferManager through IDataTransferManagerInterop::ShowShareUIForWindow, with the title, the text (and the URL on its own line) and the URL as a web link. It resolves shared when the user picks a target (DataPackage.ShareCompleted) and dismissed when the sheet closes without one (ShareCanceled, Windows 11 22H2 and later; before that, shared once the sheet is shown). Windows shows the sheet only for the window in front, so share rejects with E_UNAVAILABLE when the app's window is not the foreground window: call it from a click or key handler.

Haptics on Windows

There is no Windows implementation, on purpose. PCs have no haptic hardware an app can drive (Windows' pen and touchpad haptics belong to the input devices), and an implementation that does nothing and reports success would hide that from the app. A Windows build that calls native.Haptics fails (module-haptics): keep the call behind import.meta.env.BAKE_TARGET !== 'windows'.

On this page