Install#
npm install https://apps.salopha.com/sdk/v1/salopha-mini-app-sdk-1.6.0.tgz
import { SalophaMiniApp, SalophaBridgeError, MiniAppScopes } from "@salopha/mini-app-sdk";
<script src="https://apps.salopha.com/sdk/v1/salopha-sdk.umd.min.js"></script>
<script>const app = new Salopha.SalophaMiniApp();</script>
Browsers: iOS 14+ and Android WebView 80+ (the UMD bundle is ES2017, ESM and CJS are ES2019).
Constructor#
const app = new SalophaMiniApp(options?: SalophaMiniAppOptions);
| Option | Default | Notes |
|---|---|---|
devSimulator | false | true, simulator options or a DevHostSimulator. Used only when no host is present. Never ship it enabled. |
autoReady | true | Calls ready() after initialize() and the window load event. Set false to remove the splash yourself. |
timeoutMs | 10000 | Per-request timeout, then SalophaBridgeError("timeout"). |
interactiveTimeoutMs | 120000 | Timeout for requests the user must answer (consent, pickers, sharing, payment, sendToChat). |
transport, launch, global | automatic | Advanced: a custom transport, explicit launch info or global object (tests). |
Properties: isInHost, isSimulated, simulator, context (the last known AppContext), sessionId, protocolVersion, launchNonce, storage.
The SDK picks its transport by itself: the native channel in the phone and desktop apps, a postMessage bridge when SALOPHA Web frames your page, and a limited standalone mode when Linux opens your app in the system browser. See Web and desktop.
Lifecycle#
| Method | Result | Notes |
|---|---|---|
initialize({ sdkVersion? }) | AppContext | Call first. Safe to call twice while in flight. |
getContext() | AppContext | Refreshed context |
ready() | void | Removes the splash (automatic unless autoReady: false) |
getAppInfo() | AppInfo | Your app's id, name, version, ownership, cache mode, display, favourite state, hostName, hostVersion, platform, topInset? |
setTitle(title) | void | At most 40 characters |
back() / close() | void | Go back in the host, or close your app |
showToast(message) | void | At most 120 characters |
hapticFeedback(kind = "light") | void | light, medium, heavy, selection, success, warning, error |
interface AppContext {
sessionId: string;
locale: string; // the user's language in SALOPHA, e.g. "ar"
theme: "light" | "dark"; // the user's theme in SALOPHA
platform: "ios" | "android" | "web" | "desktop";
hostVersion: string;
grantedScopes: string[];
entryDeepLink?: string; // path to open (notification, shortcut, shared link)
appId?: string; appVersion?: string; cacheMode?: "online" | "networkFirst" | "local"; display?: "standard" | "immersive";
launch?: LaunchContext; // where the app was opened from (protocol 1.2)
}
Sign-in#
| Method | Result | Notes |
|---|---|---|
requestAuthCode() | { code, expiresAt, launchSessionId } | First call: the launch code. Later calls: fresh one-time codes with no UI (silent re-login). |
launchNonce (property) | string | null | Send it with the code; your server passes it to exchangeCode. |
The SDK has no API for tokens on purpose. See Sign-in and identity.
Identity and consent#
| Method | Scope | Result |
|---|---|---|
requestScope(scope) | any client scope | { scope, granted, oneTime?, alreadyGranted? } |
requestPermission({ name }) | — | { name, granted, blocked? } for location, location.precise, camera, media, file, contacts, notifications |
getIdentity() | profile.basic | { userId, displayName, avatarUrl?, locale?, countryCode?, phone?, grantedScopes? }: only approved fields |
getPhoneNumber() | profile.phone or profile.phone.request | string | null |
userId in getIdentity() is your app's pairwise id, the same as sub on your server.
Places#
| Method | Scope | Result |
|---|---|---|
getLocation({ precise?, maxAgeMs? }) | location.current / location.precise | { latitude, longitude, accuracy, timestamp } |
pickAddress({ purpose?, title? }) | none (the choice is the consent) | Address | null |
getAddresses() | addresses.read | Address[] |
interface Address {
id: string; label: string; kind: "home" | "work" | "other";
recipientName?: string; phone?: string;
countryCode: string; city: string; area: string; street: string; building: string; floor: string; apartment: string;
landmark: string; // the nearest landmark, which couriers rely on
notes: string; latitude?: number; longitude?: number; isDefault: boolean;
}
History#
| Method | Scope | Result |
|---|---|---|
getTransactions({ limit?, activeOnly? }) | transactions.read | The user's transactions with your app: { id, appId, externalReference, type, status, title?, amountMinor?, currency?, createdAt, updatedAt, … }[] |
Device#
| Method | Scope | Result |
|---|---|---|
scanQr({ title? }) | qr.scan | { value, format } | null |
pickImage({ source: "camera" | "gallery", maxWidth?, quality? }) | camera.pick / media.pick | PickedFile | null |
pickFile({ accept?, maxBytes? }) | file.pick | PickedFile | null |
pickContact() | contacts.pick | { name, phones } | null |
authenticateBiometric(reason) | biometric.auth | boolean |
getNetworkStatus() | — | { online, type: "wifi" | "cellular" | "ethernet" | "none" | "other" } |
PickedFile is { name, mimeType, size, dataBase64 }. The exported toBlob(file) helper turns it into a Blob for upload. Pickers return null when the user cancels.
Out of your app#
| Method | Scope | Notes |
|---|---|---|
openUrl({ url, external? }) | url.open | In the host's browser, or the system browser with external: true |
openMaps({ latitude, longitude, label } | { query }) | maps.open | |
callPhone(number) | phone.call | |
shareText({ text?, url?, title? }) | share.system | { shared } |
copyText(text) | clipboard.write |
SALOPHA features#
| Method | Scope | Result |
|---|---|---|
shareObject({ appId, objectType, objectId, visibility?, title?, subtitle?, imageUrl? }) | share.object | { shared, targets?, cancelled? }: the user picks chats |
sendToChat({ objectType, objectId, text?, title?, subtitle?, imageUrl? }) | share.object | { sent, cancelled?, closing? }. See Chat actions. |
getLaunchContext() | — | { source, actionId?, chat?: { kind, title }, canSendToChat, actor } (actor since 1.5) |
requestBusinessJoin({ businessId? }) | — | 1.5: { status: "active" | "pendingReview" | "cancelled", businessId? }. See Business audience. |
switchActor({ kind: "user" } | { kind: "business", businessId }) | — | 1.5: { switched }; the host relaunches the app as that actor |
openChat({ providerExternalId? | businessId? | userId?, draftText? }) | chat.open | Opens a chat. With providerExternalId, your merchant's business chat; rejects unavailable when not connected. |
openObject({ appId, type, objectId }) | — | Opens a shared object |
openBusiness({ businessId }) | business.profile.read | Opens a business profile |
openPayment({ paymentIntentId, … }) | — | Not live yet: answers unsupported |
setFavorite(favorite) | — | boolean |
canCreateShortcut() | — | { supported, reason? }; iOS answers ios_not_permitted |
createShortcut({ path?, label? }) | shortcut.create | boolean; Android home-screen icon |
getNotificationStatus() | — | { enabled, systemEnabled } |
requestNotifications() | notifications.service | { enabled, systemEnabled } after asking |
Storage#
app.storage is a small key-value store on the device, per user and per app (scope storage.local). Values are strings of at most 64 KB; at most 200 keys.
await app.storage.set("cart", JSON.stringify(cart));
const cart = JSON.parse((await app.storage.get("cart")) ?? "[]");
await app.storage.remove("cart");
await app.storage.clear();
Events#
const off = app.on("backPressed", () => closeSheetIfOpen()); // return true to consume the back press
off(); // or app.off("backPressed", handler)
| Event | Payload | Notes |
|---|---|---|
themeChanged | { theme } | app.context.theme is updated |
localeChanged | { locale } | app.context.locale is updated |
backPressed | {} | Return true to keep your app open |
visibilityChanged | { visible } | |
networkChanged | { online } | |
notificationReceived | { title, body, path? } | Your app's notification arrived while it is open |
sessionExpired | { reason? } | Pending requests fail with session_invalid; show a relaunch screen |
entitlementsChanged | { appId? } | 1.4: the user's plan changed. See Plans. |
actorChanged | Actor | 1.5: the app now runs as another actor; app.context.actor is updated |
Language and theme#
Inside SALOPHA the user's choice in the app wins, not the device's: the web view's prefers-color-scheme and Accept-Language follow the phone, so don't rely on them. SALOPHA puts salopha_locale and salopha_theme on your launch URL for the first paint, returns them from initialize() and sends localeChanged and themeChanged while your app is open. Set lang, dir and your theme from them before the first paint, and hide your own language and theme switches inside the host.
Errors#
Every method rejects with SalophaBridgeError { code, message, hostCode?, method?, isRetryable }.
| Code | Meaning |
|---|---|
not_in_host | No SALOPHA host (plain browser without the simulator, or a feature the system browser can't offer) |
session_invalid | The launch session ended or the request was replayed |
scope_denied | The user said no, or the scope isn't declared and approved |
method_not_allowed | Unknown method, or a server-only capability |
timeout | No answer in time |
cancelled | The user closed the sheet or picker |
unavailable | The host can't do it right now, or an older host doesn't know the method |
Host codes outside this list are normalised (permission_denied to scope_denied, session_expired to session_invalid, user_cancelled to cancelled, anything else to unavailable) and kept in hostCode. isSalophaBridgeError(x) works across bundle copies.
try {
await app.scanQr();
} catch (e) {
if (e instanceof SalophaBridgeError && e.code === "not_in_host") hideScanButton();
}
The simulator#
DevHostSimulator answers every method with mock data when your page runs in a plain browser. It enforces the host's rules: unknown sessions and replays fail, scopes outside the manifest are denied, and profile.phone.request is one-time.
const app = new SalophaMiniApp({
devSimulator: {
consent: "prompt", // "grant" | "deny" | "prompt" (window.confirm)
grantedScopes: ["chat.open"],
identity: { displayName: "Demo" },
locale: "ar", theme: "light", platform: "web", latencyMs: 120, log: true,
launch: { source: "chat", actionId: "find_food", chat: { kind: "direct", title: "Ali" } }, // a chat launch
// 1.5: businesses: [{ businessId: "biz_1", name: { ar: "…", en: "…" } }], joinApproval: "developer", actor: { kind: "user" },
},
});
app.simulator?.emit("themeChanged", { theme: "dark" });
app.simulator?.setConsentMode("deny");
Security rules#
| Rule | How |
|---|---|
| Origin allow-list | The bridge answers only pages served from your manifest's allowedOrigins (HTTPS; http://localhost in development). |
| Session binding | Every request carries the launch session and a nonce derived from the launch nonce, with a strictly increasing counter. Replays fail. |
| No secrets in JavaScript | There is no token API. Parameters whose names look like credentials (token, secret, bearer, apiKey, cookie…) are refused before sending, and such keys in answers are stripped. |
| Method allow-list | Only the 52 bridge methods can be sent. Server-only scopes can't be requested. |
| Server-side transactions | Transactions and their events are published only from your server, signed. |
| Input hygiene | Titles and toasts are length-capped; share previews are plain text. |
Wire format#
For host implementers and debugging. Requests go to the host channel, answers and events come back through window.__salophaReceive.
{ "id": "rab12cd-3", "method": "requestScope", "launchSessionId": "ls_…", "nonce": "3.9f1c…", "params": { "scope": "profile.basic" }, "version": "1.0" }
{ "id": "rab12cd-3", "ok": true, "result": { "scope": "profile.basic", "granted": true } }
{ "id": "rab12cd-3", "ok": false, "error": { "code": "scope_denied", "message": "…" } }
{ "event": "backPressed", "payload": {} }
Low-level exports: BridgeClient, createWebViewTransport, createFramedTransport, createStandaloneTransport, installReceiver, isInHost, readLaunchInfo, deriveRequestNonce, BRIDGE_METHODS, BRIDGE_PROTOCOL_VERSION, MiniAppScopes, SERVER_ONLY_SCOPES, WEB_HOST_ORIGINS.
Compatibility#
| SDK | Bridge protocol | SALOPHA app | Adds |
|---|---|---|---|
| 1.0 | 1.0 | 0.1.0 | 15 methods, 5 events |
| 1.1 | 1.1 | 0.1.5 | 43 methods: device, addresses, transactions, storage, shortcuts, notifications, ready, requestAuthCode; 7 events |
| 1.2 | 1.2 | 0.1.6 | 45 methods: getLaunchContext, sendToChat (chat actions) |
| 1.3 | 1.2 | web and desktop clients | Framed (postMessage) and standalone transports; platform desktop. No new methods. |
| 1.4 | 1.2 | commerce-capable app | 50 methods: commerce (getEntitlements, purchase, manageSubscription, openExternalPayment, requestAddressGrant); event entitlementsChanged |
| 1.5 | 1.2 | acting-identity app | 52 methods: requestBusinessJoin, switchActor; actor in the context; event actorChanged |
Older hosts answer newer methods with method_not_allowed or unavailable; everything else keeps working.