or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

app-component-creation.mdautomation.mdbuild-configuration.mdindex.mdnavigation-apis.mdnetwork-apis.mdruntime-api.mdsystem-apis.mdvue-integration.md
tile.json

runtime-api.mddocs/

Runtime API

The Runtime API provides the core uni-app interface for Baidu Mini Program applications. The main uni object serves as a proxy to over 200 native Baidu APIs while providing uni-app's unified interface and automatic promisification.

Capabilities

Core API Object

The main uni API object that provides access to all platform capabilities.

/**
 * Main uni-app API object providing unified access to Baidu Mini Program capabilities
 * All native Baidu swan APIs are proxied through this object with automatic promisification
 */
const uni: UniAPI;

interface UniAPI {
  // Base utility functions
  upx2px(number: number, newDeviceWidth?: number): number;
  addInterceptor(method: string, interceptor: Interceptor): void;
  removeInterceptor(method: string, interceptor?: Interceptor): void;
  interceptors: InterceptorMap;
  
  // Event system
  $on(event: string, handler: Function): void;
  $off(event: string, handler?: Function): void;
  $once(event: string, handler: Function): void;
  $emit(event: string, ...args: any[]): void;
  
  // Custom Baidu-specific APIs
  requestPayment(params: PaymentParams): Promise<PaymentResult>;
  createMediaQueryObserver(): MediaQueryObserver;
  getProvider(options: ProviderOptions): Promise<ProviderResult>;
  
  // All native Baidu swan APIs (proxied with promisification)
  [key: string]: any;
}

Unit Conversion

Converts upx (universal pixel) units to actual pixel values based on device characteristics.

/**
 * Convert upx units to px based on device screen width
 * @param number - Value in upx units
 * @param newDeviceWidth - Optional custom device width, defaults to current device width
 * @returns Converted value in px
 */
function upx2px(number: number, newDeviceWidth?: number): number;

Usage Example:

import uni from "@dcloudio/uni-mp-baidu";

// Convert 750upx to px (typically 375px on most devices)
const pixels = uni.upx2px(750);
console.log(pixels); // 375 (on a 750px wide device)

// Convert with custom device width
const customPixels = uni.upx2px(750, 1125);
console.log(customPixels); // 562.5

API Interceptors

System for intercepting and modifying API calls globally or per-method.

/**
 * Add an interceptor for a specific API method
 * @param method - API method name to intercept
 * @param interceptor - Interceptor configuration object
 */
function addInterceptor(method: string, interceptor: Interceptor): void;

/**
 * Remove an interceptor for a specific API method
 * @param method - API method name
 * @param interceptor - Optional specific interceptor to remove, removes all if not provided
 */
function removeInterceptor(method: string, interceptor?: Interceptor): void;

interface Interceptor {
  /** Called before the API method is invoked */
  invoke?(options: any): any;
  /** Called when the API method succeeds */
  success?(result: any): any;
  /** Called when the API method fails */
  fail?(error: any): any;
  /** Called after success or fail */
  complete?(): void;
  /** Called to modify the return value */
  returnValue?(result: any): any;
}

/** Predefined interceptors for common APIs */
interface InterceptorMap {
  [method: string]: Interceptor;
}

Usage Example:

import uni from "@dcloudio/uni-mp-baidu";

// Add global request interceptor
uni.addInterceptor('request', {
  invoke(options) {
    // Add authorization header
    options.header = options.header || {};
    options.header['Authorization'] = 'Bearer ' + getToken();
    return options;
  },
  success(result) {
    console.log('Request succeeded:', result);
  },
  fail(error) {
    console.log('Request failed:', error);
    if (error.statusCode === 401) {
      // Handle unauthorized
      redirectToLogin();
    }
  }
});

Event System

Global event bus for cross-component communication.

/**
 * Register an event listener
 * @param event - Event name
 * @param handler - Event handler function
 */
function $on(event: string, handler: Function): void;

/**
 * Remove an event listener
 * @param event - Event name
 * @param handler - Optional specific handler to remove
 */
function $off(event: string, handler?: Function): void;

/**
 * Register a one-time event listener
 * @param event - Event name
 * @param handler - Event handler function
 */
function $once(event: string, handler: Function): void;

/**
 * Emit an event
 * @param event - Event name
 * @param args - Arguments to pass to handlers
 */
function $emit(event: string, ...args: any[]): void;

Usage Example:

import uni from "@dcloudio/uni-mp-baidu";

// Register event listener
uni.$on('user-login', (user) => {
  console.log('User logged in:', user);
});

// Emit event
uni.$emit('user-login', { id: 123, name: 'Alice' });

// One-time listener
uni.$once('app-ready', () => {
  console.log('App is ready');
});

// Remove specific listener
const handler = (data) => console.log(data);
uni.$on('data-update', handler);
uni.$off('data-update', handler);

Payment API

Baidu Mini Program specific payment functionality.

/**
 * Initiate a payment request specific to Baidu Mini Program
 * @param params - Payment parameters
 * @returns Promise resolving to payment result
 */
function requestPayment(params: PaymentParams): Promise<PaymentResult>;

interface PaymentParams {
  /** Payment order information from server */
  orderInfo: string;
  /** Success callback */
  success?(result: PaymentResult): void;
  /** Failure callback */
  fail?(error: PaymentError): void;
  /** Completion callback */
  complete?(): void;
}

interface PaymentResult {
  /** Payment result status */
  result: 'success' | 'fail' | 'cancel';
  /** Additional payment data */
  [key: string]: any;
}

interface PaymentError {
  /** Error code */
  errCode: number;
  /** Error message */
  errMsg: string;
}

Usage Example:

import uni from "@dcloudio/uni-mp-baidu";

// Initiate payment
try {
  const result = await uni.requestPayment({
    orderInfo: 'payment_order_info_from_server'
  });
  
  if (result.result === 'success') {
    console.log('Payment successful');
    // Handle successful payment
  }
} catch (error) {
  console.log('Payment failed:', error.errMsg);
  // Handle payment failure
}

Media Query Observer

Creates observers for responsive design based on media queries.

/**
 * Create a media query observer for responsive design
 * @returns MediaQueryObserver instance
 */
function createMediaQueryObserver(): MediaQueryObserver;

interface MediaQueryObserver {
  /** Observe changes to media query conditions */
  observe(descriptor: MediaQueryDescriptor, callback: MediaQueryCallback): void;
  /** Stop observing media query changes */
  disconnect(): void;
}

interface MediaQueryDescriptor {
  /** Minimum width in px */
  minWidth?: number;
  /** Maximum width in px */
  maxWidth?: number;
  /** Width in px */
  width?: number;
  /** Height in px */
  height?: number;
  /** Device orientation */
  orientation?: 'portrait' | 'landscape';
}

interface MediaQueryCallback {
  (result: MediaQueryResult): void;
}

interface MediaQueryResult {
  /** Whether the media query matches */
  matches: boolean;
}

Usage Example:

import uni from "@dcloudio/uni-mp-baidu";

// Create media query observer
const observer = uni.createMediaQueryObserver();

// Observe viewport changes
observer.observe({
  minWidth: 768
}, (result) => {
  if (result.matches) {
    console.log('Tablet or desktop view');
  } else {
    console.log('Mobile view');
  }
});

// Stop observing
observer.disconnect();

Service Provider API

Gets information about available service providers on the platform.

/**
 * Get available service providers for different capabilities
 * @param options - Provider query options
 * @returns Promise resolving to provider information
 */
function getProvider(options: ProviderOptions): Promise<ProviderResult>;

interface ProviderOptions {
  /** Service type to query */
  service: 'oauth' | 'share' | 'payment' | 'push';
  /** Success callback */
  success?(result: ProviderResult): void;
  /** Failure callback */
  fail?(error: any): void;
}

interface ProviderResult {
  /** Service type */
  service: string;
  /** Array of available providers */
  provider: string[];
}

Usage Example:

import uni from "@dcloudio/uni-mp-baidu";

// Get available OAuth providers
const oauthProviders = await uni.getProvider({
  service: 'oauth'
});
console.log('OAuth providers:', oauthProviders.provider);
// Might return: ['baidu']

// Get available payment providers
const paymentProviders = await uni.getProvider({
  service: 'payment'
});
console.log('Payment providers:', paymentProviders.provider);
// Might return: ['baidupay']

Native Swan API Proxy

All native Baidu swan APIs are automatically wrapped and exposed through the uni object with promisification and protocol adaptation. This includes over 200 methods covering:

  • UI APIs: showToast, showModal, showActionSheet, etc.
  • Navigation: navigateTo, redirectTo, switchTab, etc.
  • Network: request, uploadFile, downloadFile, etc.
  • Storage: setStorage, getStorage, removeStorage, etc.
  • Location: getLocation, chooseLocation, openLocation, etc.
  • Device: getSystemInfo, getNetworkType, getBatteryInfo, etc.
  • Media: chooseImage, previewImage, chooseVideo, etc.
  • File System: getFileSystemManager APIs
  • Canvas: createCanvasContext, canvasToTempFilePath, etc.
  • Animation: createAnimation APIs

Example of proxied APIs:

// All these native swan APIs are available through uni
await uni.showToast({ title: 'Hello' });
await uni.navigateTo({ url: '/pages/detail/detail' });
const systemInfo = await uni.getSystemInfo();
const location = await uni.getLocation({ type: 'gcj02' });