@labring/sealos-desktop-sdk
v0.1.25
Published
sealos desktop sdk
Keywords
Readme
Sealos Desktop SDK
🚀 Secure and efficient communication solution designed for iframe micro-frontend architecture
🌟 Features
- ✅ Type Safe: Complete TypeScript support, reducing runtime errors
- 🔒 Secure & Reliable: Multi-layer security validation with domain whitelist support
- 🚀 Promise-based: Asynchronous operations made synchronous for better DX
- 🎯 Bidirectional Communication: Built-in event system supporting complex interaction scenarios
- ⚡ Lightweight & Efficient: < 10KB gzipped, asynchronous non-blocking design
- 🔧 Extensible: Plugin architecture with custom API support
📦 Installation
# Using npm
npm install @labring/sealos-desktop-sdk
# Using pnpm
pnpm add @labring/sealos-desktop-sdk
# Using yarn
yarn add @labring/sealos-desktop-sdk🚀 Quick Start
Desktop Side (Main Application)
import { createMasterAPP } from '@labring/sealos-desktop-sdk/master';
useEffect(() => {
// Configure allowed domains (recommend using specific domains in production)
const cleanup = createMasterAPP(['https://app.example.com']);
return cleanup; // Cleanup on component unmount
}, []);App Side (Sub Application)
import { createSealosApp, sealosApp } from '@labring/sealos-desktop-sdk';
useEffect(() => {
// Initialize SDK
const cleanup = createSealosApp();
return cleanup;
}, []);
// Get user information
const getUserInfo = async () => {
try {
const session = await sealosApp.getSession();
console.log('User info:', session.user);
} catch (error) {
console.error('Failed to get user info:', error);
}
};
// Get language settings
const getLanguage = async () => {
const { lng } = await sealosApp.getLanguage();
console.log('Current language:', lng);
};📚 Core APIs
User Information
// Get user session information
const session = await sealosApp.getSession();
console.log(session.user.name); // Username
console.log(session.user.id); // User IDLanguage Settings
// Get current language settings
const { lng } = await sealosApp.getLanguage();
// lng: 'zh' | 'en' | other language codesOpen Desktop App
// Open an app in a small desktop window
await sealosApp.openApp({
appKey: 'system-costcenter',
appSize: 'windowed'
});
// Open an app with route, query, and message data
await sealosApp.openApp({
appKey: 'system-template',
pathname: '/instance',
query: { instanceName: 'demo' },
messageData: { source: 'my-app' },
appSize: 'maximized'
});Event Communication
// Sub-app listens to main app events
const unsubscribe = sealosApp.addAppEventListen('user-update', (userData) => {
console.log('User info updated:', userData);
});
// Sub-app sends events to main app
await sealosApp.runEvents('app-ready', { appId: 'my-app' });
// Cleanup event listeners
unsubscribe();🏗️ Communication Architecture
graph LR
A[Sub App] -->|postMessage| B[Main Desktop App]
B -->|postMessage| A
A -->|uuid identifier| B
B -->|same uuid response| A- Initialization: Main app and sub-app initialize their respective SDKs
- Request: Sub-app generates unique ID and sends request via postMessage
- Processing: Main app validates origin and processes business logic
- Response: Main app replies with the same ID
- Callback: Sub-app matches callback by ID to complete async call
🔧 Development Guide
Local Development
# 1. Install development tools
npm i -g yalc nodemon
# 2. Start development mode
npm run dev
# 3. Link to local project
npm run link-sdk
# 4. Unlink
npm run unlink-sdkExtending APIs
- Add new API names in
constants/api.ts - Implement corresponding handler methods in
src/master.ts - Add client-side call methods in
src/app.ts
Security Configuration
// Recommended production configuration
const allowedOrigins = ['https://your-app-domain.com', 'https://another-app.com'];
createMasterAPP(allowedOrigins);📖 API Reference
| API | Parameters | Return Value | Description |
| ----------------------------- | ------------------ | ------------------------ | ---------------------------- |
| getSession() | - | Promise<SessionV1> | Get user session information |
| getLanguage() | - | Promise<{lng: string}> | Get language settings |
| openApp(options) | OpenAppOptions | Promise<any> | Open a desktop app |
| runEvents(name, data) | string, any | Promise<any> | Trigger main app events |
| addAppEventListen(name, fn) | string, function | function | Listen to main app events |
🤝 Contributing
Issues and Pull Requests are welcome!
📄 License
Sealos Sustainable Use License 1.0
Host configuration
sealosApp.getHostConfig() returns the shared HostConfig type (exported from
sealos-desktop-sdk):
interface HostConfig {
cloud: { domain: string; port: string; regionUid: string };
features: { subscription: boolean; analytics?: boolean };
currencySymbol?: 'shellCoin' | 'cny' | 'usd';
}Starting with SDK 0.1.24, the currency field is typed. Updated Desktop hosts read
desktop.layout.currencySymbol and always return a symbol, defaulting to
shellCoin only after configuration has loaded. Requests made during loading wait
for initialization; if configuration is still unavailable after 8 seconds, the
request rejects. Consumers should retry failed requests instead of caching a
fallback for a loading error. The SDK does not cache host configuration.
Older Desktop hosts may omit currencySymbol; consumers can use
config.currencySymbol ?? 'shellCoin'. This is a display choice, not currency
conversion. The message API remains getHostConfig.
See RELEASING.md for release preparation and package naming.
Server-side kubeconfig handling
The /service entry accepts only inline tokens or inline client certificates. Executable authentication plugins, local file paths, proxies and impersonation are rejected before client creation. The API endpoint and CA come from the server's kubeconfig or in-cluster configuration; caller-provided server, CA and TLS bypass settings are ignored. initK8s parses credentials but does not establish the identity of user.name: any handler using an administrator client must first authenticate the caller and bind the requested resource to that verified identity.
