NebulaNebula
Reference

@nebula-rn/client

Nebula miniapp client API reference, providing detailed interface documentation for device, media, storage, network, sensor, and other capabilities.

@nebula-rn/client is the main API package for miniapp developers, providing a stable interface for calling host capabilities. All APIs communicate with the host through the Nebula protocol layer.


QR Code / Barcode Scanning

scanCode(options?)

Opens the host-managed scanning UI and returns the scan result. The interface automatically closes and returns data upon successful scan; throws an exception on failure.

PlatformSupport
iOS✅
Android✅
function scanCode(options?: ScanCodeOptions): Promise<ScanCodeData>;

Parameters ScanCodeOptions:

ParameterTypeRequiredDefaultDescription
scanTypestring[]No['qr', 'ean-13', 'code-128']List of barcode types to recognize.
onlyFromCamerabooleanNofalseWhen true, only uses the camera; disables selection from album.

Return value ScanCodeData:

FieldTypeDescription
resultstring | undefinedThe scanned content string.
scanTypestringRecognized barcode type, e.g., 'QR_CODE'. 'unknown' if not recognized.
rawDataunknownRaw scan data.

Timeout: 120000ms

Error codes:

Error codeDescription
PERMISSION_DENIEDCamera permission not granted.
USER_CANCELLEDUser closed the scan interface.
UNSUPPORTED_SOURCERequested scan source is unavailable.
SCAN_FAILEDAn error occurred during scanning.

scanCodeSafe(options?)

Same functionality as scanCode, but does not throw exceptions. Returns a Result type instead, suitable for scenarios where you want to handle both success and failure uniformly at the call site.

function scanCodeSafe(options?: ScanCodeOptions): Promise<ScanCodeResult>;

Return value ScanCodeResult:

// Success
{ ok: true, data: ScanCodeData }

// Failure
{ ok: false, error: { code: ScanCodeErrorCode, message: string } }

Media

chooseMedia(options?)

Selects images/videos from the album or camera.

PlatformSupport
iOS✅
Android✅
function chooseMedia(options?: ChooseMediaOption): Promise<ChooseMediaResult>;

Parameters ChooseMediaOption:

ParameterTypeRequiredDefaultDescription
countnumberNo9Maximum number of files to select.
mediaType('image' | 'video' | 'mix')[]No['image', 'video']Allowed media types.
sourceType('album' | 'camera')[]No['album', 'camera']File source. If only 'camera' is included, opens the camera directly.
maxDurationnumberNo10Maximum recording duration for video (seconds).
sizeType('original' | 'compressed')[]No['original', 'compressed']Image size types. When 'compressed' is included, quality is compressed to 0.8.
camera'back' | 'front'No'back'Default camera direction.

Return value ChooseMediaResult:

FieldTypeDescription
tempFilesChooseMediaFile[]List of selected files.
type'image' | 'video' | 'mix'The actual selected media type.

ChooseMediaFile structure:

FieldTypeDescription
tempFilePathstringTemporary local path of the file.
sizenumberFile size in bytes.
fileType'image' | 'video'File type.
durationnumber(Optional) Video duration in seconds.
widthnumber(Optional) Width in pixels.
heightnumber(Optional) Height in pixels.
thumbTempFilePathstring(Optional) Video thumbnail path.

Timeout: 120000ms

previewImages(options)

Opens a full-screen image preview interface, supporting browsing multiple images and saving.

PlatformSupport
iOS✅
Android✅
function previewImages(options: PreviewImageOptions): Promise<void>;

Parameters PreviewImageOptions:

ParameterTypeRequiredDefaultDescription
urlsstring[]Yes-List of image URLs to preview.
currentstringNourls[0]The currently displayed image URL.
showMenubooleanNofalseWhether to show save/share menu.
saveMediaTextstringNo-Custom text for the save button.
cancelTextstringNo-Custom text for the cancel button.

Timeout: 120000ms

getImageInfo(option)

Gets image dimensions, type, and other information.

PlatformSupport
iOS✅
Android✅
function getImageInfo(
  option: GetImageInfoOption,
): Promise<GetImageInfoSuccessResult>;

Parameters GetImageInfoOption:

ParameterTypeRequiredDescription
srcstringYesImage path or URL.

Return value GetImageInfoSuccessResult:

FieldTypeDescription
widthnumberImage width in pixels.
heightnumberImage height in pixels.
pathstringLocal path of the image.
orientationstringImage orientation.
typestringImage format.

compressImage(options)

Compresses and scales an image, outputting in JPEG format.

PlatformSupport
iOS✅
Android✅
function compressImage(options: CompressImageOption): Promise<string>;

Parameters CompressImageOption:

ParameterTypeRequiredDefaultDescription
srcstringYes-Source image path.
qualitynumberNo80Compression quality (0-100).
compressedWidthnumberNo0Target width. 0 means scale proportionally.
compressedHeightnumberNo0Target height. 0 means scale proportionally.

Return value: Promise<string> — Path to the compressed image.

saveMedia(url, type, options?)

Saves an image or video to the system photo album.

PlatformSupport
iOS✅
Android✅
function saveMedia(
  url: string,
  type: MediaType,
  options?: SaveMediaOptions,
): Promise<string>;

Parameters:

ParameterTypeRequiredDescription
urlstringYesPath to the media file to save.
type'photo' | 'video'YesMedia type.
options.albumstringNoTarget album name.

Return value: Promise<string> — System resource URI after saving.


Location

getLocation(options?)

Gets the current device geographic location.

PlatformSupportNotes
iOS✅Requires location permission configuration in Info.plist.
Android✅Automatically requests ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION permission on first call.
function getLocation(options?: GetLocationOption): Promise<GetLocationResult>;

Parameters GetLocationOption:

ParameterTypeRequiredDefaultDescription
altitudebooleanNofalseWhether to request altitude data.
isHighAccuracybooleanNofalseWhether to use high-accuracy positioning.
highAccuracyExpireTimenumberNo10000High-accuracy positioning timeout (milliseconds).

Return value GetLocationResult:

FieldTypeDescription
latitudenumberLatitude (-90 to 90).
longitudenumberLongitude (-180 to 180).
speednumberSpeed in meters per second.
accuracynumberAccuracy in meters.
altitudenumberAltitude in meters.
verticalAccuracynumberVertical accuracy in meters.
horizontalAccuracynumberHorizontal accuracy in meters.

onLocationChange(enableHighAccuracy, onSuccess, onError?)

Subscribes to location change events, continuously receiving location updates.

PlatformSupport
iOS✅
Android✅
function onLocationChange(
  enableHighAccuracy: boolean,
  onSuccess: (data: LocationData) => void,
  onError?: (error: unknown) => void,
): () => void;

Parameters:

ParameterTypeRequiredDefaultDescription
enableHighAccuracybooleanNotrueWhether to enable high accuracy.
onSuccess(data: LocationData) => voidYes-Callback invoked on each location update. Receives a LocationData object.
onError(error: unknown) => voidNo-Callback invoked when location acquisition fails.

Callback parameter LocationData:

FieldTypeDescription
latitudenumberLatitude.
longitudenumberLongitude.
accuracynumberAccuracy in meters.
altitudenumber | nullAltitude in meters, null if unavailable.
speednumber | nullSpeed in meters per second, null if unavailable.
timestampnumberTimestamp.

Return value: () => void — Call this function to unsubscribe.


Storage

setStorage(options)

Writes data to local key-value storage. Values are serialized to JSON strings. Uses the MMKV storage engine under the hood.

PlatformSupport
iOS✅
Android✅
function setStorage(options: SetStorageOption): Promise<void>;

Parameters SetStorageOption:

ParameterTypeRequiredDescription
keystringYesStorage key.
dataunknownYesData to store; any JSON-serializable value.

getStorage<T>(key)

Reads data from local storage. Values are deserialized from JSON strings to their original types.

PlatformSupport
iOS✅
Android✅
function getStorage<T>(key: string): Promise<T>;

Parameters:

ParameterTypeRequiredDescription
keystringYesStorage key.

Return value: Promise<T> — Deserialized data.

Exception: Throws an Error if the key does not exist, with message 'getStorage:fail data not found'.

getStorageInfo()

Gets storage usage information.

PlatformSupport
iOS✅
Android✅
function getStorageInfo(): Promise<GetStorageInfoResult>;

Return value GetStorageInfoResult:

FieldTypeDescription
keysstring[]All keys in the current storage.
currentSizenumberCurrent used storage size in KB.
limitSizenumberStorage limit, fixed at 10240 (10 MB).

Device

getSystemInfo()

Gets system information including device hardware, screen dimensions, and safe areas.

PlatformSupportNotes
iOS✅Status bar height calculated via safe-area insets.
Android✅Status bar height obtained via StatusBar.currentHeight.
function getSystemInfo(): Promise<SystemInfo>;

Return value SystemInfo:

FieldTypeDescription
brandstringDevice brand.
modelstringDevice model.
pixelRationumberScreen pixel density.
screenWidthnumberScreen width in pixels.
screenHeightnumberScreen height in pixels.
windowWidthnumberAvailable window width.
windowHeightnumberAvailable window height.
statusBarHeightnumberStatus bar height.
safeAreaSafeAreaSafe area information.
systemstringOperating system and version, e.g., 'ios 17.0', 'android 14'.
platformstringPlatform identifier: 'ios' or 'android'.
fontSizeSettingnumberSystem font scale factor.
deviceOrientation'portrait' | 'landscape'Current device orientation.

SafeArea structure:

FieldTypeDescription
leftnumberSafe area left inset.
rightnumberSafe area right inset.
topnumberSafe area top inset.
bottomnumberSafe area bottom inset.
widthnumberSafe area width.
heightnumberSafe area height.

getAppBaseInfo()

Gets basic information about the host application.

PlatformSupport
iOS✅
Android✅
function getAppBaseInfo(): Promise<AppBaseInfo>;

Return value AppBaseInfo:

FieldTypeDescription
versionstringDevice operating system version.
languagestringLanguage setting.
enableDebugbooleanWhether in debug mode (corresponds to __DEV__).
themestringCurrent theme, currently fixed to 'light'.

getScreenBrightness()

Gets the current screen brightness.

PlatformSupport
iOS✅
Android✅
function getScreenBrightness(): Promise<number>;

Return value: Promise<number> — Brightness value ranging from 0 (darkest) to 1 (brightest).

makePhoneCall(phoneNumber)

Brings up the system dialer interface.

PlatformSupport
iOS✅
Android✅
function makePhoneCall(phoneNumber: string): Promise<boolean>;

Parameters:

ParameterTypeRequiredDescription
phoneNumberstringYesPhone number to call.

Return value: Promise<boolean> — Whether the dialer was successfully invoked.


Clipboard

getClipboardData()

Reads text content from the system clipboard.

PlatformSupport
iOS✅
Android✅
function getClipboardData(): Promise<string>;

Return value: Promise<string> — Text content from the clipboard.

setClipboardData(data)

Writes text to the system clipboard.

PlatformSupport
iOS✅
Android✅
function setClipboardData(data: string): Promise<void>;

Parameters:

ParameterTypeRequiredDescription
datastringYesText to write to the clipboard.

File Transfer

downloadFile(options)

Downloads a file to a local temporary path. Returns a Task object that supports aborting the download and listening for progress.

PlatformSupport
iOS✅
Android✅
function downloadFile(options: DownloadFileOption): DownloadTask;

Parameters DownloadFileOption:

ParameterTypeRequiredDefaultDescription
urlstringYes-Download URL.
headerRecord<string, string>No-Custom HTTP request headers.
timeoutnumberNo60000Timeout in milliseconds.
filePathstringNo-Destination save path. If not specified, saves to a temporary directory.

Return value DownloadTask:

DownloadTask is both a Promise and a Task object. You can await it for the result, or call methods to control the download.

MethodDescription
abort()Aborts the download. Returns Promise<void>.
onProgressUpdate(callback)Registers a download progress callback. See table below for callback parameters.
offProgressUpdate(callback)Unregisters a previously registered progress callback.
onHeadersReceived(callback)Registers a response headers received callback.
offHeadersReceived(callback)Unregisters a previously registered headers callback.

Progress callback parameters DownloadProgressRes:

FieldTypeDescription
progressnumberDownload progress (0-100).
totalBytesWrittennumberNumber of bytes downloaded.
totalBytesExpectedToWritenumberTotal expected bytes.

Final return value DownloadFileResult:

FieldTypeDescription
tempFilePathstringLocal path of the downloaded file.
statusCodenumberHTTP status code.

uploadFile(options)

Uploads a local file to a server. Returns a Task object that supports aborting the upload and listening for progress.

PlatformSupport
iOS✅
Android✅
function uploadFile(options: UploadFileOption): UploadTask;

Parameters UploadFileOption:

ParameterTypeRequiredDescription
urlstringYesUpload target URL.
filePathstringYesLocal path of the file to upload.
namestringYesForm field name for the file.
headerRecord<string, string>NoCustom HTTP request headers.
formDataRecord<string, string>NoAdditional form data to submit with the file.

Return value UploadTask:

Same structure as DownloadTask, supporting abort(), onProgressUpdate(), onHeadersReceived(), etc.

Progress callback parameters UploadProgressRes:

FieldTypeDescription
progressnumberUpload progress (0-100).
totalBytesSentnumberNumber of bytes uploaded.
totalBytesExpectedToSendnumberTotal expected bytes.

Final return value UploadFileResult:

FieldTypeDescription
datastringServer response body.
statusCodenumberHTTP status code.

removeFile(options)

Deletes a file from the sandbox.

PlatformSupport
iOS✅
Android✅
function removeFile(options: { filePath: string }): Promise<void>;

Parameters:

ParameterTypeRequiredDescription
filePathstringYesPath of the file to delete.

Exception: Throws a FILE_NOT_FOUND error if the file does not exist.


File System

getFileSystemManager()

Gets the file system manager singleton, providing complete sandbox file operations. All file paths are automatically resolved relative to the miniapp sandbox directory.

PlatformSupport
iOS✅
Android✅
function getFileSystemManager(): FileSystemManager;

FileSystemManager.access(options)

Checks whether a file or directory exists. Resolves if it exists, rejects with a FILE_NOT_FOUND error if it does not.

access(options: { path: string }): Promise<void>
ParameterTypeRequiredDescription
pathstringYesPath of the file or directory to check.

FileSystemManager.readFile(options)

Reads file content.

readFile(options: FileReadOption): Promise<{ data: string }>
ParameterTypeRequiredDefaultDescription
filePathstringYes-File path.
encoding'ascii' | 'base64' | 'utf8'No'utf8'File encoding.
positionnumberNo-Starting position for reading (bytes).
lengthnumberNo-Length to read (bytes).

FileSystemManager.writeFile(options)

Writes to a file. If the file already exists, it will be overwritten.

writeFile(options: FileWriteOption): Promise<void>
ParameterTypeRequiredDefaultDescription
filePathstringYes-File path.
datastringYes-Content to write.
encoding'ascii' | 'base64' | 'utf8'No'utf8'File encoding.

FileSystemManager.appendFile(options)

Appends content to the end of a file.

appendFile(options: { filePath: string; data: string; encoding?: string }): Promise<void>
ParameterTypeRequiredDefaultDescription
filePathstringYes-File path.
datastringYes-Content to append.
encoding'ascii' | 'base64' | 'utf8'No'utf8'File encoding.

FileSystemManager.copyFile(options)

Copies a file.

copyFile(options: { srcPath: string; destPath: string }): Promise<void>
ParameterTypeRequiredDescription
srcPathstringYesSource file path.
destPathstringYesDestination file path.

FileSystemManager.rename(options)

Renames or moves a file/directory.

rename(options: { oldPath: string; newPath: string }): Promise<void>
ParameterTypeRequiredDescription
oldPathstringYesOriginal path.
newPathstringYesNew path.

FileSystemManager.unlink(options)

Deletes a file.

unlink(options: { filePath: string }): Promise<void>
ParameterTypeRequiredDescription
filePathstringYesPath of the file to delete.

FileSystemManager.mkdir(options)

Creates a directory.

mkdir(options: { dirPath: string; recursive?: boolean }): Promise<void>
ParameterTypeRequiredDefaultDescription
dirPathstringYes-Directory path.
recursivebooleanNofalseWhether to create parent directories recursively.

FileSystemManager.rmdir(options)

Deletes a directory.

rmdir(options: { dirPath: string; recursive?: boolean }): Promise<void>
ParameterTypeRequiredDefaultDescription
dirPathstringYes-Directory path.
recursivebooleanNofalseWhether to delete contents recursively.

FileSystemManager.readdir(options)

Lists files and subdirectories in a directory.

readdir(options: { dirPath: string }): Promise<{ files: string[] }>
ParameterTypeRequiredDescription
dirPathstringYesDirectory path.

FileSystemManager.saveFile(options)

Saves a temporary file to the sandbox. If filePath is not specified, automatically generates a name using a timestamp.

saveFile(options: { tempFilePath: string; filePath?: string }): Promise<{ savedFilePath: string }>
ParameterTypeRequiredDescription
tempFilePathstringYesTemporary file path.
filePathstringNoDestination save path. If not specified, auto-generates.

FileSystemManager.getFileInfo(options)

Gets file size and hash digest.

getFileInfo(options: GetFileInfoOption): Promise<GetFileInfoResult>
ParameterTypeRequiredDefaultDescription
filePathstringYes-File path.
digestAlgorithm'md5' | 'sha1' | 'sha256'No'md5'Digest algorithm.

Return value GetFileInfoResult:

FieldTypeDescription
sizenumberFile size in bytes.
digeststringFile hash digest.

Network

getNetworkType()

Gets the current network connection type.

PlatformSupport
iOS✅
Android✅
function getNetworkType(): Promise<string>;

Return value: Promise<string> — Network type, such as 'wifi', 'cellular', 'none', or 'unknown'.

onNetworkStatusChange(callback)

Subscribes to network status change events.

PlatformSupport
iOS✅
Android✅
function onNetworkStatusChange(
  callback: (res: NetworkStatusChangeResult) => void,
): () => void;

Parameters:

ParameterTypeRequiredDescription
callback(res: NetworkStatusChangeResult) => voidYesCallback invoked when network status changes. Receives an object with isConnected and networkType fields.

Callback parameter NetworkStatusChangeResult:

FieldTypeDescription
isConnectedbooleanWhether there is currently a network connection.
networkTypestringNetwork type ('wifi', 'cellular', 'none', etc.).

Return value: () => void — Call this function to unsubscribe.


Sensors

All sensor APIs return an unsubscribe function. After subscription, they continuously receive data updates until the unsubscribe function is called.

onAccelerometerChange(callback, interval?)

Subscribes to accelerometer data changes.

PlatformSupport
iOS✅
Android✅
function onAccelerometerChange(
  callback: (data: SensorData) => void,
  interval?: number,
): () => void;

Parameters:

ParameterTypeRequiredDefaultDescription
callback(data: SensorData) => voidYes-Callback invoked on each data update. Receives an object with x, y, z acceleration values.
intervalnumberNo100Data sampling interval in milliseconds.

Callback parameter SensorData:

FieldTypeDescription
xnumberX-axis value.
ynumberY-axis value.
znumberZ-axis value.
timestampnumber(Optional) Timestamp.

Return value: () => void — Call this function to unsubscribe.

onGyroscopeChange(callback, interval?)

Subscribes to gyroscope data changes. Parameter and return value structure is the same as onAccelerometerChange.

PlatformSupport
iOS✅
Android✅
function onGyroscopeChange(
  callback: (data: SensorData) => void,
  interval?: number,
): () => void;

onMagnetometerChange(callback, interval?)

Subscribes to magnetometer data changes. Parameter and return value structure is the same as onAccelerometerChange.

PlatformSupport
iOS✅
Android✅
function onMagnetometerChange(
  callback: (data: SensorData) => void,
  interval?: number,
): () => void;

onBarometerChange(callback)

Subscribes to barometer data changes.

PlatformSupport
iOS✅
Android✅
function onBarometerChange(callback: (data: BarometerData) => void): () => void;

Parameters:

ParameterTypeRequiredDescription
callback(data: BarometerData) => voidYesCallback invoked on each data update. Receives an object with a pressure field.

Callback parameter BarometerData:

FieldTypeDescription
pressurenumberAtmospheric pressure.

Return value: () => void — Call this function to unsubscribe.


Screenshot Listener

onUserCaptureScreen(callback)

Listens for user screenshot events.

PlatformSupport
iOS✅
Android✅
function onUserCaptureScreen(callback: () => void): () => void;

Parameters:

ParameterTypeRequiredDescription
callback() => voidYesCallback invoked when the user takes a screenshot.

Return value: () => void — Call this function to stop listening.


Miniapp Update

getMiniAppUpdateInfo()

Checks whether an update is available for the current miniapp. Does not require any parameters; automatically uses the appId of the currently running miniapp.

PlatformSupport
iOS✅
Android✅
function getMiniAppUpdateInfo(): Promise<MiniAppUpdateInfo>;

Return value MiniAppUpdateInfo:

FieldTypeDescription
hasUpdatebooleanWhether an update is available.
latestVersionstring | undefinedLatest version number.
sourceUrlstring | undefinedDownload URL for the new bundle.
mode'development' | 'production' | undefinedCurrent installation mode.

Timeout: 15000ms

applyMiniAppUpdate()

Downloads and installs the latest version of the bundle. Typically called after confirming an update via getMiniAppUpdateInfo().

PlatformSupport
iOS✅
Android✅
function applyMiniAppUpdate(): Promise<MiniAppUpdateInfo>;

Return value: Same MiniAppUpdateInfo object as getMiniAppUpdateInfo, reflecting the state after the update.

Timeout: 120000ms


Common Conventions

Timeouts

CategoryDefault Timeout
General APIs15000ms
Media/Scanning related120000ms
File transfer60000ms

File Paths

  • All file paths are automatically resolved relative to the miniapp sandbox directory
  • /Documents/ paths are mapped to DocumentDirectoryPath
  • The file:// protocol prefix is automatically stripped
  • Miniapp path prefix is /Documents/MiniApps/{appId}

Subscription Pattern

All subscription APIs (sensors, network, location, screenshot) follow a unified pattern:

// Subscribe
const unsubscribe = onXxxChange(callback);

// Unsubscribe
unsubscribe();