@ayira/plugin-sdk
v0.0.43
Published
Client SDK for building platform plugins without manual postMessage wiring.
Readme
Ayira Plugin SDK
Client-side helper for building Ayira platform plugins. The SDK wraps the host RPC peer, exposes typed helpers for collections and services, and provides a small event system for host notifications.
Scope: This package is intended for use inside plugin iframes or sandboxed contexts that communicate with the Ayira host shell.
Installation
Add the SDK as a dependency of your plugin workspace:
pnpm add @ayira/plugin-sdkQuick Start
import { createHostClient } from "@ayira/plugin-sdk";
const client = createHostClient();
async function bootstrap() {
const { peerId, caps } = await client.ready();
console.log("Connected to host", peerId, "with capabilities", caps);
const notes = await client.collections.query("workspace_notes", {
filter: { workspaceId: "ws_123" },
options: { limit: 50 },
});
console.table(notes.items);
client.on("preferences.updated", (payload) => {
console.log("Host preferences changed", payload);
});
}
bootstrap().catch((err) => {
console.error("Failed to initialise plugin host client", err);
});API Reference
createHostClient(options?: HostClientOptions): HostClient
Creates a connected client that communicates with the Ayira host application.
HostClient
| Member | Description |
| --- | --- |
| ready(): Promise<{ peerId: string; caps: string[] }> | Performs the initial handshake. Resolves once the plugin is fully registered with the host. Subsequent calls reuse the cached result. |
| getCapabilities(): Promise<string[]> | Returns the host capability list. Short-circuits to the cached value from ready() when available. |
| collections.listCollections(): Promise<CollectionMetadata[]> | Lists all collections the plugin has access to, including their schemas and record counts. |
| collections.createCollection(input: CollectionDefinitionInput): Promise<CollectionMetadata> | Registers a new collection with the provided schema. |
| collections.getCollection(collection: string): Promise<CollectionMetadata> | Returns metadata for the named collection. |
| collections.updateCollection(collection: string, patch: CollectionUpdateInput): Promise<CollectionMetadata> | Updates a collection's metadata or schema. |
| collections.deleteCollection(collection: string): Promise<void> | Removes a collection and all associated records. |
| collections.create(collection: string, record: unknown): Promise<{ id: string }> | Inserts a record into the named collection and returns the new identifier. |
| collections.read(collection: string, id: string): Promise<unknown> | Reads a single record by identifier. |
| collections.update(collection: string, id: string, patch: unknown): Promise<void> | Applies a partial update to the specified record. |
| collections.delete(collection: string, id: string): Promise<void> | Removes a record from the collection. |
| collections.query<T>(collection: string, query: Query): Promise<Page<T>> | Executes a collection query and returns a paginated result. |
| bindService<T>(serviceId: string): Promise<T> | Binds to a host-exposed service (e.g., preferences, notifications) and returns the typed proxy. |
| on(event: string, handler: (...args: unknown[]) => void): () => void | Subscribes to host-emitted events. Returns an unsubscribe function. |
| close(): void | Closes the underlying RPC peer and transport, removing all event handlers. |
HostClientOptions
| Option | Type | Default | Description |
| --- | --- | --- | --- |
| timeoutMs | number | 15000 | RPC call timeout applied to all host method invocations. |
| window | Window | globalThis.window | Explicit window reference (useful when the global window is unavailable). |
| transport | HostTransport | PostMessageTransport | Provide a pre-configured transport (e.g., during testing). |
| createTransport | (parent: Window, self: Window) => HostTransport | new PostMessageTransport(parent, "*", self) | Factory for creating the transport. Ignored if transport is supplied. |
| createPeer | (transport: HostTransport, timeoutMs: number) => RpcPeerAdapter | new RpcPeer(...) | Factory for constructing the RPC peer. Useful for dependency injection in tests. |
Types
| Type | Description |
| --- | --- |
| Query | { filter?: Record<string, unknown>; options?: { limit?: number; cursor?: string } } |
| Page<T> | { items: T[]; total: number; nextCursor?: string } (defined in @platform/core-types) |
| CollectionDefinitionInput | { slug: string; name: string; description?: string; schema: CollectionSchema; temporary?: boolean } |
| CollectionMetadata | CollectionDefinitionInput & { createdAt: string; updatedAt: string; recordCount: number; isTemporary: boolean } |
| CollectionUpdateInput | { name?: string; description?: string; schema?: CollectionSchema } |
| HostTransport | { send(message: unknown, meta?: { target?: Window; origin?: string }): void; onMessage(callback): () => void; close?(): void; } |
| RpcPeerAdapter | Minimal interface used by the SDK (call, close). |
Host RPC Methods
The SDK wraps the following host RPC methods. Understanding them is useful when implementing custom transports or debugging:
| Method | Description |
| --- | --- |
| plugin.ready | Sent during ready() to register the plugin and receive peerId & capabilities. |
| host.getCapabilities | Requests the current capability list (used by getCapabilities()). |
| collections.listCollections | List collections and their schemas. |
| collections.createCollection | Create a new collection definition. |
| collections.getCollection | Fetch collection metadata and schema. |
| collections.updateCollection | Patch an existing collection definition. |
| collections.deleteCollection | Remove a collection definition and its records. |
| collections.create | Insert a record into a named collection. |
| collections.read | Retrieve a record by ID. |
| collections.update | Apply a patch to an existing record. |
| collections.delete | Delete a record from a collection. |
| collections.query | Execute a query with filters, pagination, and sorting. |
| services.bind | Bind to a service exposed by the host (returns service-specific RPC proxy). |
Events emitted by the host are forwarded through the on(event, handler) listener API. Typical event names include:
preferences.updatedcollections.updatedservices.shutdown
The exact event catalog depends on host capabilities returned by getCapabilities().
Advanced Usage
Custom Transport
To run the SDK in a non-browser environment (e.g., integration testing), supply a custom transport that conforms to HostTransport:
const client = createHostClient({
createTransport: () => mockTransport,
createPeer: (transport, timeoutMs) => mockPeer(transport, timeoutMs),
});Graceful Shutdown
Always call client.close() when your plugin is torn down to release listeners and terminate the RPC peer:
window.addEventListener("beforeunload", () => client.close());Testing Tips
- Inject fake transports and peer adapters via
createTransport/createPeerto avoid real postMessage traffic. - Mock host responses by stubbing the injected peer's
callmethod. - Use the exported types (
Query,Page,HostTransport) to maintain type safety in tests.
