SDK 类型与方法签名
适用读者 按接口名查类型的作者。前置条件 使用 SDK 3.0.0。学习目标 定位声明及其关联的可运行教程。预计 5 分钟。
在编辑器里按接口名跳转,或在下面展开声明。内容由本站构建时读取的官方 SDK 3.0.0 类型文件生成。声明中的相对导入属于 SDK 内部;插件源码从包名或文档示例指定的公开子入口导入。
第一次写插件,请先做计数器练习。查到 permissionKey 后看权限申请,查到 OperationContext 后看操作钩子。展开的代码可以搜索、选择和复制。
按方法名找参数、返回值和对应教程可用方法索引。以下类型文件保留 SDK 原始声明及废弃标记。
入口、清单与数据
PluginContext、ResourceRef、OperationContext 和注册入口
ts
/// <reference path="./host-modules.d.cts" />
/** This package defines the v3 wire/authoring contract. It does not grant Host permissions. */
import type { LoDashStatic } from 'lodash';
import type { HostIconName, HostAssetName, LODASH_METHODS } from './catalog.js';
export * from './catalog.js';
export * from './plugins-api.js';
export * from './http.js';
export * from './library.js';
export * from './validate.js';
export * from './sockets.js';
import type { SocketAPI } from './sockets.js';
import type { GuestAPI, GuestBootstrapAPI } from './guests.js';
import type { PluginStorageAPI } from './storage.js';
import type { createHttpClient, HttpClientOptions } from './http.js';
export * from './music.js';
export * from './streams.js';
export * from './server.js';
export type * from './wasm.js';
export type * from './crypto-streams.js';
export * from './music-api.js';
export * from './lyrics.js';
export * from './regions.js';
export * from './quality.js';
export * from './guests.js';
export * from './share.js';
export * from './storage.js';
export * from './accounts.js';
export * from './navigation.js';
export * from './permissions.js';
export * from './services.js';
export * from './modules.js';
import type { PluginModules } from './modules.js';
import type { HostServices, HostUI } from './services.js';
import type { PermissionGrant, PermissionGroupRequest, PermissionGroupResult } from './permissions.js';
import type { ChartMetadata, LyricsDocument, PlaylistMetadata, TrackMetadata } from './music.js';
import type { LibraryAPI, PlaylistImporterImplementation } from './library.js';
/** 宿主在插件自己的隔离环境提供这些 Lodash 方法;不会打入插件发行文件。 */
export type HostLodash = Pick<LoDashStatic, (typeof LODASH_METHODS)[number]>;
export * from './manifest.js';
import type { JsonValue, JsonObject, MaybePromise, Disposable, PluginManifest } from './manifest.js';
export interface ResourceRef {
/**
* Owning plugin for private resources. Public provider-scoped tracks may omit
* this field so a playlist/search result does not pin playback to its source
* plugin; the Host fills it in only when invoking a selected implementation.
*/
pluginId?: string;
providerId: string;
connectionId?: string;
kind: string;
id: string;
/** Public canonical track ID within providerId. Allows the Host's selected resolver.
* Omit for plugin/account-private IDs. Cannot be combined with connectionId.
* Cross-plugin calls receive only this public identity, never data.
*/
scope?: 'provider';
/** Opaque plugin-owned JSON persisted by the Host and returned only to this plugin. */
data?: JsonObject;
}
export interface AssetHandle {
readonly kind: 'asset';
readonly id: string;
}
export interface CredentialRef {
readonly kind: 'credential';
readonly id: string;
}
export interface UserIntentHandle {
readonly kind: 'user-intent';
readonly id: string;
}
export interface OperationContext {
id: string;
deadlineAt: number;
signal: AbortSignal;
connectionId?: string;
userIntent?: UserIntentHandle;
}
export interface ContentEntity {
ref: ResourceRef;
title: string;
subtitle?: string;
artwork?: AssetHandle;
playable?: boolean;
durationMs?: number;
capabilities: string[];
extensions?: JsonObject;
/** Standard metadata consumed directly by the Host; never raw platform response objects. */
metadata?: TrackMetadata;
playlist?: PlaylistMetadata;
chart?: ChartMetadata;
}
export interface Page<T> {
items: T[];
nextCursor?: string;
snapshotId?: string;
totalEstimate?: number;
}
export interface SearchRequest {
query: string;
kinds: string[];
filters: JsonObject;
cursor?: string;
/** Requested size; providers may clamp to their upstream API's supported range. */
limit: number;
}
export interface MusicFault {
code: 'RATE_LIMITED' | 'AUTH_REQUIRED' | 'ENTITLEMENT_EXPIRED' | 'NOT_FOUND' | 'REGION_UNAVAILABLE' | 'NETWORK_ERROR' | 'PERMISSION_DENIED' | 'UNSUPPORTED' | 'CANCELLED' | 'INTERNAL';
message: string;
retryAfterMs?: number;
retryable?: boolean;
recovery?: {
mode: 'default' | 'retry-later' | 'await-user' | 'stop-current';
maxWaitMs?: number;
actions?: ({
kind: 'retry' | 'choose-source' | 'cancel';
label?: string;
} | {
kind: 'plugin-command';
commandId: string;
label: string;
})[];
};
}
export type ResolveResult = {
ok: true;
url: string;
expiresAt?: number;
/** Headers the Host must attach while fetching this exact media URL. */
requestHeaders?: Record<string, string>;
/** Optional processing performed by the Host before playback or download. */
stream?: import('./streams.js').StreamSpec;
} | {
ok: false;
error: MusicFault;
};
/**
* 高清封面协议(可选)。
*
* 存在的意义:系统媒体控件(Windows SMTC / Linux MPRIS / macOS NowPlaying)
* 按整卡尺寸(约 1000px)显示封面,而平台音源在搜索/歌单阶段给出的
* `artworkUrl` 往往是缩略图(如 QQ 500、酷狗 240、酷我 500、网易云默认)。
* 把这层「按歌曲拿到尽可能高清封面」的能力开放给插件——插件最清楚自家
* CDN 的尺寸参数规则,可据此直接改写 URL 或另行请求,而宿主无需了解各平台差异。
*
* 可选性:插件**不实现**本方法即为不支持,宿主必须静默回落到原有 `artwork`
* 封面。实现时若无法给出更清晰的图,返回 `undefined` 或原样返回入参即可,
* 宿主会自行判定是否采纳(不会因为返回低清/相同地址而报错)。
*/
export interface ArtworkHiresRequest {
/**
* 完整歌曲信息(宿主透传,字段随平台而异,常见 `img`/`albumId`/`songmid`/
* `hash` 等)。插件可直接用它已有的 `img` 做尺寸转换,也可据此发起新请求。
*/
song: JsonObject;
/**
* 宿主当前已持有的封面地址(多为平台缩略图,也可能是 blob:/data: URL)。
* 插件可据此改写尺寸参数;若它不可用则由 `song` 重新生成更合适的地址。
*/
artworkUrl?: string;
/**
* 期望的长边像素提示。**不限定画质**——插件可按平台能力自由上调/下调或忽略,
* 最终以插件返回的地址为准。
*/
targetSize?: number;
}
export interface TrackProvider {
suggest?(query: string, operation: OperationContext): Promise<string[]>;
hotSearch?(operation: OperationContext): Promise<string[]>;
artwork?(resource: ResourceRef, operation: OperationContext): Promise<string | undefined>;
search?(request: SearchRequest, operation: OperationContext): Promise<Page<ContentEntity>>;
resolve?(resource: ResourceRef, quality: string | undefined, operation: OperationContext): Promise<ResolveResult>;
lyrics?(resource: ResourceRef, operation: OperationContext): Promise<LyricsDocument>;
/**
* 高清封面协议(可选)。返回一张尽可能高清的封面 URL;
* 无法提供时返回 `undefined`(宿主回落原封面)。
*/
artworkHires?(resource: ResourceRef, request: ArtworkHiresRequest, operation: OperationContext): Promise<string | undefined>;
}
export interface PlaylistProvider {
search?(request: SearchRequest, operation: OperationContext): Promise<Page<ContentEntity>>;
categories?(operation: OperationContext): Promise<Page<ContentEntity>>;
list?(resource: ResourceRef, cursor: string | undefined, operation: OperationContext): Promise<Page<ContentEntity>>;
get?(resource: ResourceRef, cursor: string | undefined, operation: OperationContext): Promise<import('./library.js').PlaylistTrackPage>;
}
export interface ChartProvider {
list?(operation: OperationContext): Promise<Page<ContentEntity>>;
getTracks?(resource: ResourceRef, cursor: string | undefined, operation: OperationContext): Promise<Page<ContentEntity>>;
}
export interface SharingProvider {
describe?(resource: ResourceRef, policy: JsonObject, operation: OperationContext): Promise<JsonObject>;
}
export interface ProviderImplementation {
tracks?: TrackProvider;
playlists?: PlaylistProvider;
charts?: ChartProvider;
sharing?: SharingProvider;
}
export type * from './hooks.js';
export { publicLink } from './links.js';
export type * from './lifecycle.js';
import { type PluginOptions } from './lifecycle.js';
export interface PluginContext extends HostServices {
server: import('./server.js').ServerAPI;
streams: import('./streams.js').StreamsAPI;
wasm: import('./wasm.js').WasmAPI;
crypto: import('./crypto-streams.js').CryptoStreamsAPI;
entries: {
invalidate(): Promise<void>;
selection(): Promise<import('./manifest.js').SourceSelection>;
};
accounts: {
current(accountId: string): Promise<{
connectionId: string;
expired: boolean;
} | null>;
reportExpired(accountId: string, connectionId: string, credential: CredentialRef): Promise<boolean>;
register(id: string, implementation: import('./accounts.js').AccountImplementation): () => void;
};
router: import('./navigation.js').PluginRouter;
lifecycle: import('./lifecycle.js').LifecycleAPI;
hooks: import('./hooks.js').HooksAPI;
music: import('./music-api.js').MusicAPI;
plugins: import('./plugins-api.js').PluginsAPI;
services: {
register(id: string, handlers: Record<string, import('./plugins-api.js').ServiceHandler>): () => void;
};
modules: PluginModules;
readonly plugin: {
id: string;
version: string;
/** The validated installed manifest. Runtime configuration is manifest.config. */
manifest: Readonly<PluginManifest>;
};
/** 当前 Host 的协议版本与共享资源版本。 */
readonly host: {
apiVersion: string;
libraries: {
lodash: string;
icons: string;
assets: string;
vue?: string;
react?: string;
'react-dom'?: string;
};
mode: 'development' | 'production';
};
/** 本地纯计算工具,不通过 RPC 逐项执行。没有模板执行、mixin 或任意上下文构造能力。 */
readonly utils: {
readonly lodash: HostLodash;
};
/** 使用宿主已经拥有的图标,无需将 SVG/PNG 打入插件。 */
readonly icons: {
list(): readonly HostIconName[];
url(name: HostIconName): Promise<string>;
};
/** Host 静态资源与本插件资源句柄;不是任意文件路径访问接口。 */
readonly assets: {
list(): readonly HostAssetName[];
url(name: HostAssetName | AssetHandle): Promise<string>;
};
/** 已验证的配置。凭据字段由 Host 替换为引用,不返回主密钥。 */
config: {
get<T = JsonObject>(): Promise<Readonly<T>>;
};
/** Uses the application's own local/cloud playlists after Host permission checks. */
library: LibraryAPI;
/** Host-provided Socket.IO / WebSocket; no socket library is bundled into the plugin. */
sockets: SocketAPI;
playlistImporters: {
register(id: string, implementation: PlaylistImporterImplementation): Disposable;
};
lyricConverters: {
register(id: string, implementation: import('./lyrics.js').LyricConverter): Disposable;
};
providers: {
register(id: string, implementation: ProviderImplementation): Disposable;
};
actions: {
register<TInput extends JsonValue = JsonValue, TResult extends JsonValue | void = JsonValue | void>(id: string, handler: (input: TInput, operation: OperationContext) => MaybePromise<TResult>): Disposable;
};
permissions: {
getGranted(): Promise<PermissionGrant[]>;
requestGroup(request: PermissionGroupRequest): Promise<PermissionGroupResult>;
query(request: {
key: string;
scope?: JsonObject;
}): Promise<{
status: PermissionStatus;
}>;
request(request: {
key: string;
scope?: JsonObject;
intent?: UserIntentHandle;
}): Promise<{
status: PermissionStatus;
}>;
};
http: {
/** Axios-backed Host client with JSON/form helpers and typed results. */
create(options: HttpClientOptions): ReturnType<typeof createHttpClient>;
request<Mode extends 'arraybuffer' | undefined = undefined>(request: {
responseType?: Mode;
permissionKey: string;
url: string;
method?: string;
headers?: Record<string, string>;
body?: string;
timeoutMs?: number;
credential?: CredentialRef;
operation: OperationContext;
}): Promise<{
status: number;
headers: Record<string, string>;
body: Mode extends 'arraybuffer' ? ArrayBuffer : JsonValue;
}>;
};
credentials: {
get(connectionId: string): Promise<CredentialRef | null>;
};
playback: {
failure(error: MusicFault): ResolveResult;
};
ui: HostUI & {
toast(message: {
message: string;
level?: 'info' | 'success' | 'warning' | 'error';
}): Promise<void>;
/** Opens the application's existing import dialog. This does not create a plugin Surface. */
playlistImport: {
/** Only this plugin's importers are offered. Omit importerId to let the user choose. */
open(request: {
importerId?: string;
initialValue?: string;
title?: string;
}): Promise<void>;
};
/** Requests an update through the Host UI. A queued result does not mean it was installed. */
pluginUpdate: {
request(request: {
version: string;
url: string;
notes?: string;
}): Promise<{
accepted: boolean;
updated: boolean;
version?: string;
queued?: boolean;
}>;
};
pages: {
open(pageId: string, props?: JsonObject): Promise<void>;
close(pageId: string): Promise<void>;
};
views: {
setState(viewId: string, state: JsonObject): Promise<void>;
on(event: 'mounted' | 'unmounted', handler: (info: {
viewId: string;
instanceId: string;
props: JsonObject;
}) => void): Disposable;
};
setState(surfaceId: string, state: JsonObject): Promise<void>;
notify(message: {
key: string;
level: 'info' | 'success' | 'warning' | 'error';
message: string;
}): Promise<void>;
openView(surfaceId: string): Promise<void>;
closeView(surfaceId: string): Promise<void>;
};
storage: PluginStorageAPI;
guests: GuestAPI & {
/** Legacy install-draft contract; availability depends on the Host. Prefer import on desktop. */
prepareInstall(request: {
adapterId: string;
artifactHandle: string;
operation: OperationContext;
}): Promise<{
draftId: string;
}>;
requestInstall(draftId: string, operation: OperationContext): Promise<{
guestId: string;
} | null>;
};
log: {
debug(message: string, data?: JsonValue): void;
info(message: string, data?: JsonValue): void;
warn(message: string, data?: JsonValue): void;
error(message: string, data?: JsonValue): void;
};
effects: {
add(dispose: Disposable): void;
};
}
export type PermissionStatus = 'undeclared' | 'prompt' | 'granted' | 'denied' | 'expired' | 'restricted' | 'unavailable';
export interface SurfaceContext extends Pick<PluginContext, 'host' | 'utils' | 'icons' | 'assets'> {
readonly root: HTMLElement;
readonly mount: {
kind: 'page' | 'slot';
slot?: import('./manifest.js').UISlotName;
mode?: 'append' | 'prepend' | 'wrap' | 'replace';
};
invoke(action: string, input: JsonValue): Promise<JsonValue>;
/** Close this mounted Surface after its current action has returned. */
close(): Promise<void>;
subscribe(handler: (state: JsonObject) => void): Disposable;
}
export interface GuestContext extends Pick<PluginContext, 'host' | 'utils'>, GuestBootstrapAPI {
readonly guestId: string;
expose(name: string, value: unknown): void;
invokeHost(method: string, input: JsonValue): Promise<JsonValue>;
}
export type LogicEntry = (ctx: PluginContext) => MaybePromise<void | Disposable>;
export type SurfaceEntry = (ctx: SurfaceContext) => MaybePromise<void | Disposable>;
export type GuestEntry = (ctx: GuestContext) => MaybePromise<void | Disposable>;
export declare function definePlugin(entry: LogicEntry | PluginOptions): LogicEntry;
export declare function defineSurface(entry: SurfaceEntry): SurfaceEntry;
export { defineNativeView, assertNativeView } from './native-view.js';
export type { NativeView, NativeViewSection, NativeViewAction } from './native-view.js';
export declare function defineGuestAdapter(entry: GuestEntry): GuestEntry;
export declare function defineManifest(manifest: PluginManifest): PluginManifest;
export declare function definePluginConfig<const T extends JsonObject>(config: T): T;
export declare function failure(error: MusicFault): ResolveResult;
/** 基础声明式界面;由 Host 渲染,不会把插件函数放进主界面组件树。 */
export type UINode = {
type: 'section' | 'stack' | 'grid' | 'form';
title?: string;
submitAction?: string;
children: UINode[];
} | {
type: 'text';
text?: string;
label?: string;
bind?: string;
} | {
type: 'button';
label: string;
action: string;
} | {
type: 'host-content';
} | {
type: 'text-input' | 'input' | 'number' | 'toggle';
label: string;
bind: string;
placeholder?: string;
} | {
type: 'host-credential';
label: string;
bind: string;
permissionKey: string;
};
export interface UISchema {
schemaVersion: '1.0';
id?: string;
root: UINode;
}
export * from './events.js';
export declare function defineUISchema(schema: UISchema): UISchema;清单、入口和 JSON 类型
ts
import type { HostIconName, PermissionName } from './catalog.js';
import type { LyricInputFormat } from './lyrics.js';
import type { MenuContribution } from './services.js';
export type JsonValue = null | boolean | number | string | JsonValue[] | {
[key: string]: JsonValue;
};
export type JsonObject = {
[key: string]: JsonValue;
};
export type MaybePromise<T> = T | Promise<T>;
export type Disposable = () => MaybePromise<void>;
export type IconRef = {
kind: 'host';
name: HostIconName;
} | {
kind: 'asset';
resource: string;
};
export interface PermissionDeclaration {
key: string;
name: PermissionName;
scope?: JsonObject;
reason: string;
optional?: boolean;
requiredFor?: string[];
}
export interface ProviderDeclaration {
when?: EntryVisibilityRule;
beforeSelect?: string;
id: string;
name: string;
protocols: string[];
/** Ordered from lowest to highest; names have no intrinsic rank. */
qualities?: string[];
icon?: IconRef;
connectionMode?: 'none' | 'single' | 'multiple';
}
export type UISlotName = 'home.header' | 'home.content.before' | 'home.content.after' | 'search.source-selector.after' | 'playlist.header.actions' | 'playlist.item.actions' | 'player.actions' | 'settings.sections';
export interface StyleContribution {
id: string;
resource: string;
scope: 'surface' | 'slot' | 'application';
slots?: UISlotName[];
order?: number;
}
export interface GuestPolicy {
maxDepth: 1;
allowedCapabilities: string[];
networkScopeMode: 'per-guest-user-approved';
allowNativeCode: false;
allowRemoteCodeExecution: false;
}
export interface PluginManifestV3 {
manifestVersion: 3;
id: string;
name: string;
version: string;
description?: string;
author?: string;
publisher?: string;
license?: string;
homepage?: string;
config?: JsonObject;
engines: {
hostApi: string;
logicRuntime: string;
libraries?: Partial<Record<'vue' | 'react' | 'react-dom', string>>;
};
entry: {
logic?: {
module: string;
activation?: string[];
};
share?: {
module: string;
configKeys?: string[];
guestAdapterId?: string;
guestGlobals?: string[];
};
views?: ViewDeclaration[];
server?: {
module: string;
runtime: 'sandbox' | 'node';
port?: number;
lan?: boolean;
};
native?: {
name: string;
platforms: Record<string, string>;
}[];
};
provides?: {
providers?: ProviderDeclaration[];
importers?: ImporterDeclaration[];
lyricConverters?: LyricConverterDeclaration[];
accounts?: AccountDeclaration[];
guestAdapters?: GuestAdapterDeclaration[];
services?: ServiceDeclaration[];
actions?: ActionDeclaration[];
};
uses?: {
permissions?: PermissionDeclaration[];
plugins?: PluginDependency[];
};
ui?: {
pages?: PageDeclaration[];
homeSections?: HomeSectionDeclaration[];
slots?: SlotDeclaration[];
menus?: MenuContribution[];
styles?: StyleContribution[];
regions?: RegionDeclaration[];
skins?: SkinDeclaration[];
};
guestPolicy?: GuestPolicy;
dataSchemas?: {
config: number;
state: number;
};
}
export interface ViewDeclaration {
id: string;
kind: 'component' | 'web' | 'native';
module: string;
title?: string;
presentation?: {
kind: 'drawer' | 'modal';
placement?: 'left' | 'right' | 'top' | 'bottom';
size?: number;
};
lifecycle?: {
openAction?: string;
closeAction?: string;
};
}
export interface ActionDeclaration {
id: string;
title: string;
description?: string;
view?: string;
}
export interface ImporterDeclaration {
id: string;
title: string;
providerId?: string;
examples?: {
label: string;
value: string;
}[];
instructions?: string[];
description?: string;
placeholder?: string;
}
export interface LyricConverterDeclaration {
id: string;
title: string;
formats: LyricInputFormat[];
}
export interface AccountDeclaration {
id: string;
title: string;
icon?: IconRef;
multiple?: boolean;
loginMethods: ('qrcode' | 'browser' | 'form' | 'oauth')[];
capabilities?: ('profile' | 'likes' | 'playlists' | 'history' | 'recommend')[];
providers?: string[];
view?: string;
}
export interface GuestAdapterDeclaration {
id: string;
title?: string;
extensions?: string[];
format: string;
badge?: {
label: string;
backgroundColor: string;
textColor: string;
};
compatibilityProfile: string;
bootstrap: string;
runtime: string;
projectableProtocols: string[];
}
export interface ServiceDeclaration {
id: string;
version: string;
methods: string[];
description?: string;
}
export interface PluginDependency {
pluginId: string;
service: string;
version: string;
optional?: boolean;
}
export interface EntryVisibilityRule {
loggedIn?: boolean;
selectedSource?: string;
predicate?: string;
combine?: 'all' | 'any';
}
export type EntryVisibilityDecision = boolean | 'force-show' | 'force-hide';
export type ProviderEntryDecision = EntryVisibilityDecision | {
state: 'disabled';
reason?: string;
};
export interface ProviderEntryContext extends SourceSelection {
providerId: string;
}
export type ProviderSelectionDecision = boolean | {
login: {
accountId: string;
method?: AccountDeclaration['loginMethods'][number];
connectionId?: string;
};
};
export interface SourceSelection {
selectedSource: string | null;
selectedProvider: string | null;
}
export interface EntryVisibilityContext extends SourceSelection {
pageId: string;
}
export interface PageDeclaration {
id: string;
title: string;
mount: 'sidebar' | 'settings' | 'home-tab' | 'playlist-section';
view: string;
icon?: IconRef;
group?: 'discover' | 'library' | 'tools';
order?: number;
when?: EntryVisibilityRule;
}
export interface HomeSectionDeclaration {
id: string;
title: string;
kind: 'playlists' | 'charts';
providerIds?: string[];
icon?: IconRef;
order?: number;
}
export interface SlotDeclaration {
id: string;
slot: UISlotName;
mode: 'append' | 'prepend' | 'wrap' | 'replace';
view: string;
order?: number;
when?: {
loggedIn?: boolean;
route?: string;
};
}
export interface RegionDeclaration {
region: string;
view: string;
}
export interface SkinDeclaration {
id: string;
title: string;
preview?: IconRef;
regions: string[];
settings?: JsonObject;
}
export type PluginManifest = PluginManifestV3;存储键和读取范围
ts
import type { JsonValue } from './manifest.js';
export type PluginStorageReadKey = string | {
key: string;
pluginId?: string;
};
export type PluginStorageWriteKey = string | {
key: string;
pluginId?: string;
/** Omitted preserves the existing policy; new keys are private. Empty array revokes sharing. */
readableBy?: '*' | string[];
};
/** JSON storage. Structured keys and shared reads require a supporting desktop Host. */
export interface PluginStorageAPI {
/** Missing local keys return null. Unauthorized shared reads reject. */
get<T extends JsonValue = JsonValue>(key: PluginStorageReadKey): Promise<T | null>;
set(key: PluginStorageWriteKey, value: JsonValue): Promise<void>;
delete(key: PluginStorageReadKey): Promise<void>;
}权限与权限组
ts
import type { JsonObject } from './manifest.js';
import type { PermissionName } from './catalog.js';
import type { PermissionStatus, UserIntentHandle } from './index.js';
/** Permission groups are user-facing decisions, not one prompt per method. */
export declare const PERMISSION_GROUPS: {
readonly musicRead: {
readonly title: "搜索与读取所有已安装音源";
readonly permissions: readonly ["music.read"];
};
readonly musicControl: {
readonly title: "播放任意音源的歌曲";
readonly permissions: readonly ["music.control"];
};
readonly network: {
readonly title: "访问公网服务";
readonly permissions: readonly ["network.request", "network.socket"];
};
readonly localServer: {
readonly title: "在本机运行网络服务";
readonly permissions: readonly ["network.serve"];
};
readonly lanServer: {
readonly title: "允许局域网设备访问插件服务";
readonly permissions: readonly ["network.serve.lan"];
};
readonly audioTransform: {
readonly title: "处理播放器的音频数据流";
readonly permissions: readonly ["streams.transform"];
};
readonly trustedRuntime: {
readonly title: "在独立进程中运行完全信任的代码";
readonly permissions: readonly ["runtime.trusted"];
};
readonly localNetwork: {
readonly title: "访问局域网与本机服务";
readonly permissions: readonly ["network.private", "network.discovery"];
};
readonly account: {
readonly title: "读取登录状态与基本账号资料";
readonly permissions: readonly ["account.profile"];
};
readonly accountIntercept: {
readonly title: "可以拦截子账号切换";
readonly permissions: readonly ["account.intercept"];
};
readonly libraryIntercept: {
readonly title: "可以拦截和改变收藏与歌单操作";
readonly permissions: readonly ["library.intercept"];
};
readonly searchIntercept: {
readonly title: "可以拦截搜索并改写搜索词";
readonly permissions: readonly ["search.intercept"];
};
readonly searchRead: {
readonly title: "观察搜索操作";
readonly permissions: readonly ["search.read"];
};
readonly linksRead: {
readonly title: "观察主动打开的公开链接";
readonly permissions: readonly ["links.read"];
};
readonly notificationsRead: {
readonly title: "观察软件内文字提示";
readonly permissions: readonly ["notifications.read"];
};
readonly windowRead: {
readonly title: "观察窗口关闭请求";
readonly permissions: readonly ["window.read"];
};
readonly libraryRead: {
readonly title: "读取歌单与收藏";
readonly permissions: readonly ["library.read"];
};
readonly libraryManage: {
readonly title: "创建和修改歌单与收藏";
readonly permissions: readonly ["library.write"];
};
readonly libraryDelete: {
readonly title: "删除歌单与歌曲记录";
readonly permissions: readonly ["library.delete"];
};
readonly playbackRead: {
readonly title: "读取播放状态和队列";
readonly permissions: readonly ["player.read"];
};
readonly navigationRead: {
readonly title: "读取当前页面名称";
readonly permissions: readonly ["route.read"];
};
readonly navigationIntercept: {
readonly title: "拦截页面跳转";
readonly permissions: readonly ["navigation.intercept"];
};
readonly playbackIntercept: {
readonly title: "可以拦截和改变你的播放操作,例如切歌、换歌";
readonly permissions: readonly ["player.intercept"];
};
readonly playbackControl: {
readonly title: "控制播放和播放队列";
readonly permissions: readonly ["player.control", "playback.fallback.hold"];
};
readonly downloads: {
readonly title: "管理下载任务";
readonly permissions: readonly ["downloads.create", "downloads.manage"];
};
readonly files: {
readonly title: "使用用户选定的文件";
readonly permissions: readonly ["files.read", "files.write"];
};
readonly localMusic: {
readonly title: "索引本地音乐和编辑标签";
readonly permissions: readonly ["localMusic.read", "localMusic.write"];
};
readonly clipboardRead: {
readonly title: "读取剪贴板";
readonly permissions: readonly ["clipboard.read"];
};
readonly clipboardWrite: {
readonly title: "写入剪贴板";
readonly permissions: readonly ["clipboard.write"];
};
readonly notifications: {
readonly title: "发送系统通知";
readonly permissions: readonly ["notifications.system"];
};
readonly external: {
readonly title: "在系统浏览器打开链接";
readonly permissions: readonly ["external.open"];
};
readonly settingsRead: {
readonly title: "读取软件偏好";
readonly permissions: readonly ["settings.read"];
};
readonly settingsWrite: {
readonly title: "修改软件偏好";
readonly permissions: readonly ["settings.write"];
};
readonly window: {
readonly title: "控制软件窗口";
readonly permissions: readonly ["window.control"];
};
readonly windowIntercept: {
readonly title: "可以拦截窗口关闭请求";
readonly permissions: readonly ["window.intercept"];
};
readonly lyricsIntercept: {
readonly title: "读取和处理当前歌曲的歌词";
readonly permissions: readonly ["lyrics.intercept"];
};
readonly downloadsIntercept: {
readonly title: "处理下载请求与下载文件名";
readonly permissions: readonly ["downloads.intercept"];
};
readonly sharingIntercept: {
readonly title: "处理歌曲分享请求与分享链接";
readonly permissions: readonly ["sharing.intercept"];
};
readonly linksIntercept: {
readonly title: "处理主动粘贴、拖入与打开的公开链接";
readonly permissions: readonly ["links.intercept"];
};
readonly notificationsIntercept: {
readonly title: "改写或隐藏软件内提示";
readonly permissions: readonly ["notifications.intercept"];
};
readonly hotkeys: {
readonly title: "注册全局快捷键";
readonly permissions: readonly ["hotkeys.register"];
};
readonly sharing: {
readonly title: "发布和撤销分享";
readonly permissions: readonly ["sharing.publish", "sharing.revoke"];
};
readonly roomsRead: {
readonly title: "读取一起听房间状态";
readonly permissions: readonly ["rooms.read"];
};
readonly roomsControl: {
readonly title: "加入房间和控制一起听";
readonly permissions: readonly ["rooms.control"];
};
readonly ai: {
readonly title: "使用软件 AI 服务";
readonly permissions: readonly ["ai.use"];
};
readonly devices: {
readonly title: "控制音频设备与投放";
readonly permissions: readonly ["devices.control"];
};
readonly uiAppearance: {
readonly title: "修改软件全局外观";
readonly permissions: readonly ["ui.styles.global"];
};
readonly background: {
readonly title: "后台任务";
readonly permissions: readonly ["background.run"];
};
readonly credentials: {
readonly title: "使用本插件已保存的连接凭据";
readonly permissions: readonly ["credentials.use"];
};
readonly credentialCapture: {
readonly title: "从独立登录窗口保存指定网站的登录凭据";
readonly permissions: readonly ["credentials.capture"];
};
readonly credentialExport: {
readonly title: "读取本插件连接凭据明文";
readonly permissions: readonly ["credentials.read"];
};
readonly guestPlugins: {
readonly title: "安装和运行兼容子插件";
readonly permissions: readonly ["guests.manage", "guests.run"];
};
readonly services: {
readonly title: "调用其他插件提供的服务";
readonly permissions: readonly ["services.consume"];
};
};
export type PermissionGroup = keyof typeof PERMISSION_GROUPS;
export declare function permissionGroup(name: PermissionName): PermissionGroup | undefined;
export interface PermissionGrant {
key: string;
name: PermissionName;
group?: PermissionGroup;
scope: JsonObject;
status: PermissionStatus;
expiresAt?: number;
}
export interface PermissionGroupRequest {
group: PermissionGroup;
/** Omit to request all statically scoped declarations in this group. */
keys?: string[];
/** Dynamic scopes keyed by declared permission key. */
scopes?: Record<string, JsonObject>;
intent?: UserIntentHandle;
}
export interface PermissionGroupResult {
group: PermissionGroup;
status: PermissionStatus;
grants: PermissionGrant[];
}生命周期和清理
ts
import type { PluginContext, LogicEntry } from './index.js';
export declare const LIFECYCLE_NAMES: readonly ["onAppReady", "onInstall", "onUninstall", "onEnable", "onDisable", "onUpdate", "onOnline", "onOffline", "onLocaleChange", "onBeforeQuit", "onWindowShow", "onWindowHide", "onWindowFocus", "onWindowBlur", "onSuspend", "onResume", "onLock", "onUnlock", "onThemeChange", "onConfigChange", "onPermissionChange"];
export type LifecycleName = (typeof LIFECYCLE_NAMES)[number];
export type LifecycleArgs<Name extends LifecycleName> = Name extends 'onUpdate' ? [update: {
from: string;
}] : Name extends 'onLocaleChange' ? [locale: string] : Name extends 'onThemeChange' ? [theme: 'light' | 'dark'] : Name extends 'onConfigChange' | 'onPermissionChange' ? [keys: string[]] : [];
export type LifecycleAPI = {
[Name in LifecycleName]: (handler: (...args: LifecycleArgs<Name>) => void | Promise<void>) => () => void;
} & {
onIdle(milliseconds: number, handler: () => void | Promise<void>): () => void;
};
export type PluginOptions = {
setup: LogicEntry;
} & {
[Name in LifecycleName]?: (ctx: PluginContext, ...args: LifecycleArgs<Name>) => void | Promise<void>;
} & {
onIdle?: {
milliseconds: number;
handler(ctx: PluginContext): void | Promise<void>;
};
};路由和守卫
ts
import type { ResourceRef } from './index.js';
import type { PluginManifest } from './manifest.js';
export declare const PLUGIN_ROUTE_NAMES: readonly ["welcome", "home", "find", "songlist", "local", "recent", "search", "recognize", "list", "download", "local-tag-editor", "profile", "community", "settings", "plugin-page"];
export type PluginRouteName = typeof PLUGIN_ROUTE_NAMES[number];
export interface PluginRoute {
name: PluginRouteName;
params: Record<string, string>;
query: Record<string, string>;
}
export type PluginRouteTarget = Pick<PluginRoute, 'name'> & Partial<Omit<PluginRoute, 'name'>>;
export type RouteGuard = (to: PluginRoute, from: PluginRoute | null) => void | false | PluginRouteTarget | Promise<void | false | PluginRouteTarget>;
export interface PluginRouter {
beforeEach(handler: RouteGuard): () => void;
afterEach(handler: (to: PluginRoute, from: PluginRoute | null) => void | Promise<void>): () => void;
current(): Promise<PluginRoute | null>;
push(to: PluginRouteTarget): Promise<boolean>;
}
export declare function projectPluginRoute(name: unknown, params: unknown, query: unknown, owner?: string): PluginRoute | null;
export declare function validatePluginRouteTarget(value: unknown, manifest: PluginManifest): PluginRoute;
export type HostNavigationRequest = {
query?: string;
ref?: ResourceRef;
} & ({
page: 'playlist';
sectionId?: string;
} | {
page: 'search' | 'charts' | 'downloads' | 'account' | 'settings';
sectionId?: never;
});
/** Validate using the calling plugin's manifest, never a caller-supplied owner ID. */
export declare function assertNavigationRequest(value: unknown, manifest?: PluginManifest): asserts value is HostNavigationRequest;音乐、歌词与账号
聚合音源与播放调用
ts
import type { SearchRequest, ContentEntity, Page, ResourceRef, ResolveResult, Disposable, ServiceCall, CrLyric, PlaylistTrackPage } from './index.js';
export interface MusicSource {
id: string;
pluginId: string;
runtime: 2 | 3 | 'host';
name: string;
protocols: string[];
qualities: string[];
icon?: string;
available: boolean;
}
export interface MusicAPI {
sources(): Promise<MusicSource[]>;
search(sourceId: string, request: SearchRequest, call: ServiceCall): Promise<Page<ContentEntity>>;
suggest(sourceId: string, query: string, call: ServiceCall): Promise<string[]>;
hotSearch(sourceId: string, call: ServiceCall): Promise<string[]>;
tracks: {
resolve(ref: ResourceRef, quality: string | undefined, call: ServiceCall): Promise<ResolveResult>;
lyrics(ref: ResourceRef, call: ServiceCall): Promise<CrLyric>;
artwork(ref: ResourceRef, call: ServiceCall): Promise<string | undefined>;
};
playlists: {
search(sourceId: string, request: SearchRequest, call: ServiceCall): Promise<Page<ContentEntity>>;
categories(sourceId: string, call: ServiceCall): Promise<Page<ContentEntity>>;
list(ref: ResourceRef, cursor: string | undefined, call: ServiceCall): Promise<Page<ContentEntity>>;
get(ref: ResourceRef, cursor: string | undefined, call: ServiceCall): Promise<PlaylistTrackPage>;
};
charts: {
list(sourceId: string, call: ServiceCall): Promise<Page<ContentEntity>>;
getTracks(ref: ResourceRef, cursor: string | undefined, call: ServiceCall): Promise<Page<ContentEntity>>;
};
importers: {
list(): Promise<{
id: string;
pluginId: string;
title: string;
description?: string;
}[]>;
parse(importerId: string, value: string, cursor: string | undefined, call: ServiceCall): Promise<Page<ContentEntity>>;
};
play(ref: ResourceRef, call: ServiceCall): Promise<void>;
enqueue(refs: ResourceRef[], position: 'next' | 'end', call: ServiceCall): Promise<void>;
on(event: 'sources.changed', handler: (sources: MusicSource[]) => void): Disposable;
}歌曲、歌单与 CrLyric
ts
import type { ContentEntity, ResourceRef, ResolveResult } from './index.js';
/** Milliseconds throughout. Platform-specific formats/decryption stay inside the plugin. */
export interface LyricWord {
/** Optional translation aligned with this timed source word. */
translation?: string;
romanization?: string;
startTimeMs: number;
endTimeMs: number;
text: string;
}
/** A translation or romanization, optionally preserving its own timed words. */
export interface LyricSubLine {
language?: string;
text: string;
words?: LyricWord[];
}
export interface LyricLine {
isBackground?: boolean;
isDuet?: boolean;
startTimeMs: number;
endTimeMs?: number;
text: string;
translation?: string;
romanization?: string;
/** Structured TTML-style alternatives. Singular fields remain backward compatible. */
translations?: LyricSubLine[];
romanizations?: LyricSubLine[];
words?: LyricWord[];
}
export interface CrLyric {
format: 'crlyric';
version: 1;
track: ResourceRef;
offsetMs: number;
lines: LyricLine[];
/** Untimed lyrics only. Empty lines + no plainText means no available lyrics. */
plainText?: string;
}
/** @deprecated Use CrLyric. */
export type LyricsDocument = CrLyric;
export interface TrackMetadata {
/** Optional platform hash; not a plugin owner or routing key. */
hash?: string;
/** Original display sizes when exact bytes are unavailable. Never infer bytes from these labels. */
qualitySizeLabels?: Record<string, string>;
artists: string[];
album?: {
id?: string;
title: string;
};
qualities?: string[];
/** Actual file sizes in bytes, keyed by the same IDs as qualities. Omit unknown sizes. */
qualitySizes?: Record<string, number>;
artworkUrl?: string;
durationMs?: number;
}
export interface MusicTrack extends ContentEntity {
ref: ResourceRef & {
kind: 'track';
};
metadata: TrackMetadata;
}
export interface PlaylistMetadata {
trackCount?: number;
description?: string;
author?: string;
artworkUrl?: string;
}
export interface ChartMetadata {
updateFrequency?: string;
artworkUrl?: string;
}
export interface MusicPlaylist extends ContentEntity {
ref: ResourceRef & {
kind: 'playlist';
};
playlist?: PlaylistMetadata;
}
export interface MusicChart extends ContentEntity {
ref: ResourceRef & {
kind: 'chart';
};
chart?: ChartMetadata;
}
export declare function assertResourceRef(value: unknown): asserts value is ResourceRef;
/** Retarget a public track without disclosing the original plugin's private data. */
export declare function retargetTrackRef(ref: ResourceRef, pluginId: string): ResourceRef;
export declare function assertContentPage(value: unknown): void;
export declare function assertResolveResult(value: unknown): asserts value is ResolveResult;
export declare function assertLyricsDocument(value: unknown): asserts value is LyricsDocument;比较和选择音质
ts
/** Manifest order is authoritative: first is lowest, last is highest. */
export declare function compareQualities(order: readonly string[], a: string, b: string): -1 | 0 | 1 | undefined;
export declare function selectQuality(order: readonly string[], available?: readonly string[], requested?: string): string | undefined;歌词格式、解析与导出
ts
import type { CrLyric } from './music.js';
import type { ResourceRef, OperationContext } from './index.js';
export type LyricInputFormat = 'auto' | 'lrc' | 'enhanced-lrc' | 'yrc' | 'qrc' | 'krc' | 'ttml' | 'plain';
export type LyricExportFormat = 'lrc' | 'enhanced-lrc' | 'yrc' | 'ttml';
export interface LyricParseRequest {
track: ResourceRef;
format: LyricInputFormat;
text: string;
translation?: string;
romanization?: string;
}
export interface LyricExportRequest {
document: CrLyric;
format: LyricExportFormat;
}
export interface LyricExportResult {
format: LyricExportFormat;
text: string;
mime: 'text/plain';
extension: 'lrc' | 'yrc' | 'ttml';
}
/** Parsing/decryption/serialization belongs to plugins, not the player or download manager. */
export interface LyricConverter {
parse(request: LyricParseRequest, operation: OperationContext): Promise<CrLyric>;
export(request: LyricExportRequest, operation: OperationContext): Promise<LyricExportResult>;
}曲库与歌单导入器
ts
import type { ContentEntity, OperationContext, Page } from './index.js';
export type PlaylistLocation = 'local' | 'cloud';
export interface PlaylistReference {
/** Host ID; never a path or backend database credential. */
id: string;
location: PlaylistLocation;
}
export interface LibraryPlaylist {
ref: PlaylistReference;
name: string;
description?: string;
trackCount?: number;
writable: boolean;
}
export interface PlaylistImportRequest {
/** Omit to let the Host show its existing playlist picker/create dialog. */
target?: PlaylistReference;
suggestedName?: string;
items: ContentEntity[];
/** Reuse this key when retrying the same batch, so the Host can avoid duplicates. */
requestId: string;
permissionKey: string;
operation: OperationContext;
}
export interface PlaylistImportResult {
cancelled: boolean;
target?: PlaylistReference;
added: number;
skipped: number;
}
export interface PlaylistRemoveRequest {
target: PlaylistReference;
/** Only `kind: 'track'` entities are accepted. */
items: ContentEntity[];
permissionKey: string;
operation: OperationContext;
}
export interface PlaylistRemoveResult {
/** Tracks that were actually in the playlist and are now gone. */
removed: number;
/** Tracks that matched nothing, so the caller can tell a no-op from a failure. */
notFound: number;
}
export interface PlaylistImporterImplementation {
/** Resolve a pasted link/ID and return one page. Host owns paging and the import UI. */
getTracks(request: {
value: string;
cursor?: string;
limit: number;
}, operation: OperationContext): Promise<PlaylistTrackPage>;
}
export interface PlaylistTrackPage extends Page<ContentEntity> {
name?: string;
playlist?: import('./music.js').PlaylistMetadata;
}
/** Existing application library services. No plugin-owned playlist database. */
export interface LibraryAPI {
playlists: {
list(request: {
location?: PlaylistLocation;
cursor?: string;
permissionKey: string;
operation: OperationContext;
}): Promise<Page<LibraryPlaylist>>;
getTracks(request: {
target: PlaylistReference;
cursor?: string;
permissionKey: string;
operation: OperationContext;
}): Promise<Page<ContentEntity>>;
/** Host handles destination selection, auth, deduplication, persistence and cloud sync. */
import(request: PlaylistImportRequest): Promise<PlaylistImportResult>;
/**
* Delete tracks from an existing playlist. Requires `library.delete`; never
* creates or relocates a playlist. `removed + notFound` equals `items.length`.
*/
removeTracks(request: PlaylistRemoveRequest): Promise<PlaylistRemoveResult>;
/** Empty a playlist while keeping the playlist itself. Requires `library.delete`. */
clearPlaylist(request: {
target: PlaylistReference;
permissionKey: string;
operation: OperationContext;
}): Promise<void>;
};
}账号、登录与凭据
ts
import type { CredentialRef, OperationContext, Page, ResourceRef } from './index.js';
import type { MusicTrack, MusicPlaylist } from './music.js';
export interface AccountConnection {
id: string;
credential: CredentialRef;
}
export interface PluginAccountProfile {
id: string;
displayName: string;
avatar?: string;
vip?: boolean;
}
export interface AccountFormField {
key: string;
label: string;
type: 'text' | 'password' | 'code';
optional?: boolean;
}
export interface AccountForm {
fields: AccountFormField[];
}
export interface AccountLoginResult {
credential: string;
binding?: {
origin: string;
sendAs: 'bearer' | 'cookie';
};
}
/** Public state supplied only to the custom QR view. No credential or login ticket. */
export type AccountQrViewState = {
kind: 'qrcode';
accountId: string;
status: 'waiting' | 'scanned';
expiresAt: number;
image?: string;
url?: string;
origin?: string;
};
export type AccountQrCode = ({
image: string;
url?: never;
} | {
url: string;
image?: never;
}) & {
/** Optional component/web view declared by this plugin. Omit for the Host template. */
view?: string;
expiresInMs: number;
poll(operation: OperationContext): Promise<{
status: 'waiting' | 'scanned' | 'expired';
} | ({
status: 'done';
} & AccountLoginResult)>;
};
export interface AccountOAuthOptions {
authorizationUrl: string;
tokenUrl: string;
clientId: string;
scopes?: string[];
resourceOrigin?: string;
}
export interface AccountLoginReceipt {
readonly completionId: string;
}
export type AccountListCapability = 'likes' | 'playlists' | 'history' | 'recommend';
export interface AccountPageRequest {
cursor?: string;
limit: number;
}
export interface AccountCollection<T> {
list(account: AccountConnection, request: AccountPageRequest, operation: OperationContext): Promise<Page<T>>;
}
export interface AccountBrowserOptions {
url: string;
until: {
cookie: string;
};
}
export interface AccountLoginRequest {
method: 'form' | 'qrcode' | 'oauth' | 'browser';
auth: {
form(form: AccountForm): Promise<Record<string, string> | null>;
qrcode(options: AccountQrCode): Promise<AccountLoginResult | null>;
oauth(options: AccountOAuthOptions): Promise<AccountLoginReceipt | null>;
browser(options: AccountBrowserOptions): Promise<AccountLoginReceipt | null>;
};
}
export interface AccountImplementation {
likes?: AccountCollection<MusicTrack> & {
set?(account: AccountConnection, change: {
ref: ResourceRef;
liked: boolean;
}, operation: OperationContext): Promise<void>;
};
playlists?: AccountCollection<MusicPlaylist>;
history?: AccountCollection<MusicTrack>;
recommend?: AccountCollection<MusicTrack>;
login(request: AccountLoginRequest, operation: OperationContext): Promise<AccountLoginResult | AccountLoginReceipt | null>;
profile(account: AccountConnection, operation: OperationContext): PluginAccountProfile | Promise<PluginAccountProfile>;
validate?(account: AccountConnection, operation: OperationContext): {
valid: boolean;
} | Promise<{
valid: boolean;
}>;
logout?(account: AccountConnection, operation: OperationContext): void | Promise<void>;
}
export declare function assertAccountForm(value: unknown): asserts value is AccountForm;
export type AccountSummary = {
signedIn: boolean;
displayName: string;
avatarUrl?: string;
badge?: string;
};
export declare function assertAccountSummary(value: unknown): asserts value is AccountSummary;界面与播放区域
Vue hooks 和组件挂载
ts
import { type Component, type Ref } from 'vue';
import type { JsonObject, JsonValue } from '../manifest.js';
import type { ViewBridge, ViewEntry } from '../view-bridge.js';
import type { PlayerRegion, RegionContext } from '../regions.js';
export type { ViewBridge, ViewEntry, ViewDeps, RegionTransitionHook, HostComponents, HostMediaItem, HostSongAction, HostSongActions } from '../view-bridge.js';
export declare const defineView: (setup: ViewEntry) => ViewEntry;
export declare const ViewDialog: import("vue").DefineComponent<{}, () => import("vue").VNode<import("vue").RendererNode, import("vue").RendererElement, {
[key: string]: any;
}>, {}, {}, {}, import("vue").ComponentOptionsMixin, import("vue").ComponentOptionsMixin, {}, string, import("vue").PublicProps, Readonly<{}> & Readonly<{}>, {}, {}, {}, {}, string, import("vue").ComponentProvideOptions, true, {}, any>;
export declare function mountComponent(component: Component, bridge: ViewBridge): () => void;
export declare function useView(): ViewBridge;
export declare function useAction<Input extends JsonValue = JsonValue, Output extends JsonValue = JsonValue>(action: string): (input?: Input) => Promise<Output>;
export declare function useViewState<State extends JsonObject = JsonObject>(): Readonly<Ref<State>>;
export declare function useHostComponents(): import("../view-contracts.js").HostComponents;
export declare function useRegion<Name extends PlayerRegion>(name: Name): RegionContext<Name>;
export declare function useFrame(callback: (timestamp: number) => void): () => void;
export declare function useSpectrum(): Readonly<Float32Array>;宿主组件、界面桥接与弹窗
ts
import type { AllowedComponentProps, Ref, VNodeProps } from 'vue';
import type { JsonObject, JsonValue, HostIconName } from './index.js';
export interface HostMediaItem {
title: string;
key?: string;
ref?: {
id: string;
providerId: string;
kind?: string;
pluginId?: string;
connectionId?: string;
scope?: 'provider';
};
source?: string;
subtitle?: string;
playable?: boolean;
durationMs?: number;
metadata?: {
artists?: string[];
qualities?: string[];
durationMs?: number;
};
playlist?: {
author?: string;
trackCount?: number;
};
}
export type HostSongAction = 'play' | 'enqueue' | 'favorite' | 'download';
export type HostSongActions = Partial<Record<HostSongAction, string>>;
export interface HostTextProps {
title?: string;
text?: string;
name?: string;
}
export interface HostPalette {
readonly accent: string;
readonly foreground: string;
readonly background: string;
}
export interface HostVisualProps {
artwork?: string | null;
track?: {
title?: string;
artists?: readonly string[];
album?: string;
} | null;
palette?: HostPalette;
playing?: boolean;
alt?: string;
}
export interface HostVisualizerProps extends HostVisualProps {
spectrum?: Readonly<Float32Array> | readonly number[];
color?: string;
barCount?: number;
height?: number;
}
type ViewComponent<Props> = new () => {
$props: Props & VNodeProps & AllowedComponentProps;
};
export interface HostComponents {
LyricAdapter: ViewComponent<{
alignPosition?: number;
enableBlur?: boolean;
enableSpring?: boolean;
enableScale?: boolean;
textAlign?: 'left' | 'center' | 'right';
onLineClick?: (milliseconds: number) => void;
}>;
AmlLyricPlayer: ViewComponent<{
alignPosition?: number;
enableBlur?: boolean;
enableSpring?: boolean;
enableScale?: boolean;
onLineClick?: (milliseconds: number) => void;
}>;
SquareCover: ViewComponent<HostVisualProps>;
VinylRecord: ViewComponent<HostVisualProps>;
ShaderBackground: ViewComponent<HostVisualProps>;
AudioVisualizer: ViewComponent<HostVisualizerProps>;
SongList: ViewComponent<{
items?: readonly HostMediaItem[];
actions?: HostSongActions;
label?: string;
onPlay?: {
listener(item: HostMediaItem): void;
}['listener'];
}>;
PlaylistCard: ViewComponent<HostTextProps & {
item?: HostMediaItem;
onOpen?: (item: HostMediaItem) => void;
}>;
PlaylistGrid: ViewComponent<HostTextProps & {
items?: readonly HostMediaItem[];
onOpen?: (item: HostMediaItem) => void;
}>;
QualityBadge: ViewComponent<HostTextProps & {
quality?: string;
}>;
SourceIcon: ViewComponent<HostTextProps & {
source?: string;
}>;
PageHeader: ViewComponent<HostTextProps & {
description?: string;
}>;
EmptyState: ViewComponent<HostTextProps & {
description?: string;
}>;
LoadingState: ViewComponent<HostTextProps>;
}
export interface ViewBridge {
readonly region?: import('./regions.js').MountedRegion;
readonly root: ShadowRoot;
readonly instanceId: string;
readonly viewId: string;
readonly props: Readonly<JsonObject>;
readonly state: Readonly<Ref<JsonObject>>;
readonly theme: Readonly<Ref<'light' | 'dark'>>;
readonly overlay: HTMLElement;
readonly components: HostComponents;
readonly icons: {
url(name: HostIconName): string;
};
invoke<Input extends JsonValue = JsonValue, Output extends JsonValue = JsonValue>(action: string, input?: Input): Promise<Output>;
close(): Promise<void>;
onDispose(cleanup: () => void): void;
}
export type RegionTransitionHook = (context: {
readonly root: ShadowRoot;
readonly signal: AbortSignal;
readonly reason: 'skin' | 'track';
}) => void | Promise<void>;
export type ViewEntry = ((bridge: ViewBridge) => void | (() => void)) & {
onEnter?: RegionTransitionHook;
onLeave?: RegionTransitionHook;
};
export {};原生视图与动作
ts
import type { ContentEntity, JsonValue, MaybePromise, OperationContext } from './index.js';
export interface NativeViewAction {
label: string;
action: string;
input?: JsonValue;
primary?: boolean;
}
export interface NativeViewSection {
id: string;
title?: string;
layout: 'grid' | 'list';
items: ContentEntity[];
/** Receives { ref }; typically opens a native playlist page. */
onOpen?: string;
/** Receives { ref, refs }; typically replaces the native playback queue. */
onPlay?: string;
/** Receives the action input merged with { ref }; the Host supplies the item's ref. */
itemActions?: NativeViewAction[];
}
/** Rendered using Host components. No plugin DOM, iframe, or framework runs in this surface. */
export interface NativeView {
type: 'page';
title?: string;
description?: string;
actions?: NativeViewAction[];
sections: NativeViewSection[];
}
/** A typed render callback that can be passed directly to ctx.actions.register. */
export declare function defineNativeView<TInput extends JsonValue = JsonValue>(render: (input: TInput, operation: OperationContext) => MaybePromise<NativeView>): (input: TInput, operation: OperationContext) => Promise<NativeView & JsonValue>;
export declare function assertNativeView(value: unknown, actions?: ReadonlySet<string>): asserts value is NativeView;播放器区域与上下文
ts
import type { LyricLine } from './music.js';
export declare const PLAYER_REGIONS: readonly ["player.lyrics", "player.artwork", "player.background", "player.visualizer", "player.songInfo", "player.stage", "desktopLyric"];
export type PlayerRegion = typeof PLAYER_REGIONS[number];
export declare function parsePlayerRegion(value: string): {
name: PlayerRegion;
version: number;
} | null;
type Live<Value> = {
readonly value: Value;
};
type DeepReadonly<Value> = Value extends object ? {
readonly [Key in keyof Value]: DeepReadonly<Value[Key]>;
} : Value;
export type RegionJsonValue = null | string | number | boolean | RegionJsonObject | readonly RegionJsonValue[];
export interface RegionJsonObject {
readonly [key: string]: RegionJsonValue;
}
export interface RegionTrack {
readonly title: string;
readonly artists: readonly string[];
readonly album?: string;
readonly durationMs?: number;
}
interface PlayerProps {
readonly track: RegionTrack | null;
readonly currentTime: Live<number>;
readonly playing: Live<boolean>;
readonly palette: Readonly<{
accent: string;
foreground: string;
background: string;
}>;
readonly layout: 'cd' | 'cover';
readonly forward: RegionJsonObject;
}
interface LyricsProps {
readonly lines: DeepReadonly<LyricLine[]>;
}
interface ArtworkProps {
readonly artwork: string | null;
}
interface SpectrumProps {
readonly spectrum: Readonly<Float32Array>;
}
interface DesktopProps {
readonly current: DeepReadonly<LyricLine> | null;
readonly next: DeepReadonly<LyricLine> | null;
readonly locked: Live<boolean>;
}
export interface RegionProps {
'player.lyrics': PlayerProps & LyricsProps;
'player.artwork': PlayerProps & ArtworkProps;
'player.background': PlayerProps & ArtworkProps & SpectrumProps;
'player.visualizer': PlayerProps & SpectrumProps;
'player.songInfo': PlayerProps;
'player.stage': PlayerProps & LyricsProps & ArtworkProps & SpectrumProps;
desktopLyric: PlayerProps & DesktopProps;
}
export interface RegionContext<Name extends PlayerRegion> {
readonly size: Live<Readonly<{
width: number;
height: number;
}>>;
readonly name: Name;
readonly version: 1;
readonly props: RegionProps[Name];
readonly settings: RegionJsonObject;
readonly actions: Name extends 'player.lyrics' | 'player.stage' ? {
seek(milliseconds: number): Promise<void>;
} : Readonly<Record<string, never>>;
onFrame(callback: (timestamp: number) => void): () => void;
}
export type MountedRegion = {
[Name in PlayerRegion]: RegionContext<Name>;
}[PlayerRegion];
export {};区域组件快捷入口
ts
import type { PlayerRegion, RegionContext } from '../regions.js';
import type { HostComponents } from '../view-contracts.js';
export type { HostComponents, RegionTransitionHook } from '../view-contracts.js';
export declare const useRegion: <Name extends PlayerRegion>(name: Name) => RegionContext<Name>;
export declare const useHostComponents: () => HostComponents;
export declare const useFrame: (callback: (timestamp: number) => void) => void;
export declare const useSpectrum: () => Readonly<Float32Array>;操作、事件与服务
可拦截操作、输入与结果
ts
import type { OperationContext } from './index.js';
import type { CrLyric } from './music.js';
export declare const PLAYBACK_OPERATION_NAMES: readonly ["player.play", "queue.add", "player.pause", "player.resume", "player.previous", "player.next", "player.error", "player.queueEnded", "player.seek", "player.setVolume", "player.setMode", "queue.remove", "queue.clear", "queue.shuffle"];
export type PlaybackOperationName = (typeof PLAYBACK_OPERATION_NAMES)[number];
export type SearchOperationName = 'search.query' | 'search.suggest' | 'search.results';
declare const LIBRARY_OPERATION_NAMES: readonly ["track.like", "playlist.create", "playlist.delete", "playlist.addTracks", "playlist.removeTracks", "playlist.export", "playlist.import"];
export type LibraryOperationName = (typeof LIBRARY_OPERATION_NAMES)[number];
export declare function isLibraryOperation(name: unknown): name is LibraryOperationName;
export type LyricOperationName = 'lyrics.load' | 'lyrics.transform';
export type DownloadOperationName = 'download.create' | 'download.filename';
export declare function isDownloadOperation(name: unknown): name is DownloadOperationName;
export declare function isLyricOperation(name: unknown): name is LyricOperationName;
export type OperationLyric = Omit<CrLyric, 'track'> & {
track: OperationTrack['ref'];
};
export type SystemOperationName = 'link.open' | 'notification.show';
export type HookOperationName = PlaybackOperationName | 'player.resolve' | 'account.switch' | 'window.close' | 'share.create' | SystemOperationName | SearchOperationName | LibraryOperationName | LyricOperationName | DownloadOperationName;
export interface ShareOperationResult {
id: string;
url: string;
template?: string;
}
export interface ResolveStatus {
readonly ok: boolean;
}
export type HookResult<Name extends HookOperationName> = Name extends 'share.create' ? ShareOperationResult | null : Name extends LyricOperationName ? OperationLyric | null : Name extends 'player.resolve' ? ResolveStatus : null;
export declare function isSearchOperation(name: unknown): name is SearchOperationName;
export type OperationSource = {
kind: 'ui' | 'system';
location?: string;
} | {
kind: 'plugin';
pluginId: string;
runtime: 2 | 3;
};
export interface OperationTrack {
ref: {
kind: 'track';
id: string;
providerId: string;
};
title: string;
metadata: {
artists: string[];
};
}
export interface OperationInputs {
'link.open': {
url: string;
readonly from: 'paste' | 'drop' | 'deeplink';
};
'notification.show': {
title: string;
body: string;
level: 'info' | 'success' | 'warning' | 'error';
};
'share.create': {
track: OperationTrack;
};
'download.create': {
tracks: OperationTrack[];
quality: string;
readonly directory?: string;
};
'download.filename': {
readonly track: OperationTrack;
name: string;
};
'lyrics.load': {
readonly track: OperationTrack;
};
'lyrics.transform': {
readonly track: OperationTrack;
lyric: OperationLyric | null;
};
'window.close': Record<string, never>;
'player.resolve': {
track: OperationTrack;
quality: string;
};
'track.like': {
track: OperationTrack;
liked: boolean;
};
'playlist.create': {
name: string;
readonly location: 'local' | 'cloud';
};
'playlist.delete': {
readonly playlist: {
readonly id: string;
readonly name: string;
readonly location: 'local' | 'cloud' | 'both';
};
};
'playlist.addTracks': OperationInputs['playlist.delete'] & {
tracks: OperationTrack[];
};
'playlist.removeTracks': OperationInputs['playlist.addTracks'];
'playlist.export': OperationInputs['playlist.delete'] & {
format: 'cmpl' | 'cpl';
};
'playlist.import': {
value: string;
importerId?: string;
};
'search.results': {
readonly query: string;
readonly sourceId: string;
page: {
readonly kind: 'track' | 'playlist';
items: SearchResultItem[];
};
};
'search.query': {
query: string;
readonly sourceId: string;
readonly kinds: readonly string[];
};
'search.suggest': {
readonly query: string;
items: string[];
};
'account.switch': {
readonly pluginId: string;
readonly accountId: string;
readonly fromConnectionId: string | null;
readonly connectionId: string;
};
'player.pause': Record<string, never>;
'player.resume': Record<string, never>;
'player.previous': Record<string, never>;
'player.seek': {
positionMs: number;
};
'player.setMode': {
mode: 'sequence' | 'random' | 'single';
};
'player.setVolume': {
volume: number;
};
'player.next': {
reason: 'user' | 'ended' | 'error';
track?: OperationTrack;
};
'player.error': {
readonly track: OperationTrack;
readonly error: 'resolve' | 'start' | 'media' | 'playback';
};
'player.queueEnded': {
tracks?: OperationTrack[];
};
'player.play': {
track: OperationTrack;
queueIndex?: number;
};
'queue.add': {
tracks: OperationTrack[];
position: 'next' | 'end';
};
'queue.remove': {
tracks: OperationTrack[];
};
'queue.clear': {
tracks?: OperationTrack[];
};
'queue.shuffle': {
items: OperationTrack[];
};
}
export interface SearchResultItem {
ref: {
kind: 'track' | 'playlist';
providerId: string;
id: string;
};
title: string;
subtitle?: string;
metadata?: {
artists: string[];
};
}
export type HookInput<Name extends HookOperationName> = OperationInputs[Name] | (Name extends 'player.next' ? {
track: OperationTrack;
} : never);
export type HookPriority = 'early' | 'normal' | 'late';
type ReadonlyTree<T> = T extends object ? {
readonly [Key in keyof T]: ReadonlyTree<T[Key]>;
} : T;
export type OperationState = ReadonlyTree<{
player: (Omit<import('./services.js').PlayerState, 'track'> & {
track: OperationTrack | null;
}) | null;
route: import('./navigation.js').PluginRoute | null;
account: import('./services.js').AccountSession | null;
}>;
export interface HookContext<Name extends HookOperationName> {
input: OperationInputs[Name];
readonly source: OperationSource;
readonly operation: OperationContext;
/** Missing read permission is represented by null; the snapshot cannot be mutated. */
readonly state: OperationState;
preventDefault(): void;
respondWith(result: HookResult<Name>): void;
}
export interface HooksAPI {
on<Name extends HookOperationName>(name: Name, handler: (op: HookContext<Name>, next: (input?: HookInput<Name>) => Promise<HookResult<Name>>) => void | HookResult<Name> | HookInput<Name> | Promise<void | HookResult<Name> | HookInput<Name>>, options?: {
priority?: HookPriority;
}): () => void;
}
export {};可订阅事件
ts
import type { HookOperationName, HookResult, OperationInputs, OperationSource } from './hooks.js';
import type { PermissionName } from './catalog.js';
export type OperationEventName = HookOperationName | `${HookOperationName}:done`;
type ReadonlyTree<T> = T extends object ? {
readonly [K in keyof T]: ReadonlyTree<T[K]>;
} : T;
export type OperationEvent<Name extends OperationEventName> = Name extends `${infer Op extends HookOperationName}:done` ? ReadonlyTree<{
input: OperationInputs[Op];
source: OperationSource;
result: HookResult<Op>;
prevented: boolean;
handledBy: string[];
failed: boolean;
}> : Name extends HookOperationName ? ReadonlyTree<{
input: OperationInputs[Name];
source: OperationSource;
}> & {
preventDefault(): void;
} : never;
export declare function operationEventPermission(name: string): PermissionName | undefined;
export {};HostServices 宿主接口
ts
import type { Disposable, JsonObject, JsonValue, IconRef } from './manifest.js';
import type { ContentEntity, MusicFault, OperationContext, Page, ResourceRef, AssetHandle } from './index.js';
import type { LibraryPlaylist, PlaylistReference } from './library.js';
import type { LyricsDocument } from './music.js';
import type { PermissionGroup } from './permissions.js';
import type { HostNavigationRequest } from './navigation.js';
import type { OperationInputs, ShareOperationResult } from './hooks.js';
import type { PermissionName } from './catalog.js';
export type CallableOperation = 'track.like' | 'player.play' | 'player.next' | 'player.pause' | 'player.resume' | 'player.previous' | 'player.seek' | 'player.setVolume' | 'player.setMode' | 'queue.add' | 'queue.remove' | 'queue.clear' | 'download.create' | 'share.create' | 'notification.show' | 'link.open' | 'window.close' | 'playlist.create' | 'playlist.delete' | 'playlist.addTracks' | 'playlist.removeTracks' | 'playlist.import' | 'playlist.export';
export type OperationToolResult<Name extends CallableOperation> = Name extends 'share.create' ? ShareOperationResult | null : null;
export interface OperationTool {
name: CallableOperation;
description: string;
inputSchema: JsonObject;
outputSchema: JsonObject;
/** null means the operation needs no additional grant (for example an in-app toast). */
permission: PermissionName | null;
}
/** Supplied by Host actions/events. Never construct trusted intents from plugin JSON. */
export interface ServiceCall {
operation: OperationContext;
permissionKey: string;
}
export interface ServiceAvailability {
service: string;
version: string;
available: boolean;
/** When present, only these methods are connected by the Host. */
methods?: string[];
reason?: 'host-not-connected' | 'unsupported' | 'not-logged-in' | 'disabled';
permissionGroups: PermissionGroup[];
}
export interface AccountProfile {
id: string;
displayName: string;
avatar?: AssetHandle;
/** Stable plugin-scoped identity; no email, phone, tokens or auth provider subject by default. */
identityScope: 'plugin';
}
export interface AccountSession {
loggedIn: boolean;
profile: AccountProfile | null;
}
export interface PlayerState {
status: 'idle' | 'loading' | 'playing' | 'paused' | 'ended' | 'error';
track: ContentEntity | null;
positionMs: number;
durationMs: number;
volume: number;
muted: boolean;
repeat: 'off' | 'one' | 'all';
shuffle: boolean;
}
export interface QueueState {
items: ContentEntity[];
currentIndex: number;
revision: string;
}
export interface DownloadTask {
id: string;
track: ContentEntity;
status: 'queued' | 'running' | 'paused' | 'completed' | 'failed' | 'cancelled';
receivedBytes: number;
totalBytes?: number;
error?: MusicFault;
}
export interface FileHandle {
kind: 'file';
id: string;
name: string;
size?: number;
mime?: string;
}
export interface DirectoryHandle {
kind: 'directory';
id: string;
name: string;
}
export interface AudioDevice {
id: string;
name: string;
kind: 'local' | 'dlna';
available: boolean;
}
export interface ShareDescriptor {
version: 1;
track: ResourceRef;
title: string;
artists: string[];
canonicalUrl?: string;
/** Public resolver identity; never executable plugin code, master keys or auth tokens. */
resolver?: {
id: string;
resourceId: string;
};
}
export interface RoomState {
joined: boolean;
id?: string;
title?: string;
role?: 'owner' | 'member';
members?: number;
}
export interface AppInfo {
name: string;
version: string;
platform: 'win32' | 'darwin' | 'linux';
locale: string;
theme: 'light' | 'dark';
hostApi: string;
}
export interface ListeningTrack {
title: string;
artist: string;
source: string;
}
export interface HostServiceEvents {
'entries.selectionChanged': import('./manifest.js').SourceSelection;
'player.progress': {
positionMs: number;
durationMs: number;
};
'track.started': {
track: ListeningTrack;
};
'track.finished': {
track: ListeningTrack;
playedMs: number;
completed: boolean;
};
'route.changed': {
from: string | null;
to: string | null;
};
'account.changed': AccountSession & {
accountId?: string;
connectionId?: string | null;
};
'account.expired': {
accountId: string;
connectionId: string;
};
'library.changed': {
target: PlaylistReference;
reason: 'created' | 'updated' | 'deleted' | 'synced';
};
'player.changed': PlayerState;
'queue.changed': QueueState;
'lyrics.changed': LyricsDocument | null;
'downloads.changed': DownloadTask;
'settings.changed': {
keys: string[];
};
'theme.changed': {
theme: 'light' | 'dark';
};
'rooms.changed': RoomState;
'devices.changed': AudioDevice[];
'permissions.changed': {
keys: string[];
};
}
export declare const HOST_SERVICE_EVENT_NAMES: readonly ["entries.selectionChanged", "player.progress", "track.started", "track.finished", "route.changed", "account.changed", "account.expired", "library.changed", "player.changed", "queue.changed", "lyrics.changed", "downloads.changed", "settings.changed", "theme.changed", "rooms.changed", "devices.changed", "permissions.changed"];
/** Contract first: availability must be checked before using services not connected by this Host. */
export interface HostServices {
capabilities: {
list(): Promise<ServiceAvailability[]>;
get(service: string): Promise<ServiceAvailability>;
};
account: {
getSession(call: ServiceCall): Promise<AccountSession>;
getProfile(call: ServiceCall): Promise<AccountProfile | null>;
/** Opens the application's own account page. Plugins do not implement login or receive its token. */
openLogin(operation: OperationContext): Promise<void>;
};
app: {
operations: {
list(): Promise<OperationTool[]>;
};
call<Name extends CallableOperation>(name: Name, input: OperationInputs[Name], call: ServiceCall): Promise<OperationToolResult<Name>>;
getInfo(): Promise<AppInfo>;
openSettings(section?: string): Promise<void>;
openExternal(url: string, call: ServiceCall): Promise<void>;
};
player: {
getState(call: ServiceCall): Promise<PlayerState>;
play(track: ResourceRef | undefined, call: ServiceCall): Promise<void>;
pause(call: ServiceCall): Promise<void>;
next(call: ServiceCall): Promise<void>;
previous(call: ServiceCall): Promise<void>;
seek(positionMs: number, call: ServiceCall): Promise<void>;
setVolume(volume: number, call: ServiceCall): Promise<void>;
setMode(mode: {
repeat?: PlayerState['repeat'];
shuffle?: boolean;
muted?: boolean;
}, call: ServiceCall): Promise<void>;
};
queue: {
get(call: ServiceCall): Promise<QueueState>;
append(items: ContentEntity[], call: ServiceCall): Promise<QueueState>;
replace(items: ContentEntity[], call: ServiceCall): Promise<QueueState>;
remove(refs: ResourceRef[], call: ServiceCall): Promise<QueueState>;
reorder(refs: ResourceRef[], revision: string, call: ServiceCall): Promise<QueueState>;
};
favorites: {
contains(refs: ResourceRef[], call: ServiceCall): Promise<boolean[]>;
add(refs: ResourceRef[], call: ServiceCall): Promise<void>;
remove(refs: ResourceRef[], call: ServiceCall): Promise<void>;
};
history: {
list(cursor: string | undefined, call: ServiceCall): Promise<Page<ContentEntity>>;
};
downloads: {
list(call: ServiceCall): Promise<DownloadTask[]>;
create(request: {
tracks: ResourceRef[];
quality?: string;
directory?: DirectoryHandle;
}, call: ServiceCall): Promise<DownloadTask[]>;
pause(ids: string[], call: ServiceCall): Promise<void>;
resume(ids: string[], call: ServiceCall): Promise<void>;
cancel(ids: string[], call: ServiceCall): Promise<void>;
retry(ids: string[], call: ServiceCall): Promise<void>;
reveal(id: string, call: ServiceCall): Promise<void>;
};
files: {
pick(request: {
title?: string;
extensions?: string[];
multiple?: boolean;
}, operation: OperationContext): Promise<FileHandle[]>;
pickDirectory(operation: OperationContext): Promise<DirectoryHandle | null>;
readText(file: FileHandle, call: ServiceCall): Promise<string>;
readBase64(file: FileHandle, call: ServiceCall): Promise<string>;
saveText(request: {
suggestedName: string;
text: string;
}, operation: OperationContext): Promise<FileHandle | null>;
writeText(file: FileHandle, text: string, call: ServiceCall): Promise<void>;
};
clipboard: {
readText(call: ServiceCall): Promise<string>;
writeText(text: string, call: ServiceCall): Promise<void>;
};
localMusic: {
list(cursor: string | undefined, call: ServiceCall): Promise<Page<ContentEntity>>;
scan(directories: DirectoryHandle[], call: ServiceCall): Promise<{
taskId: string;
}>;
getTags(track: ResourceRef, call: ServiceCall): Promise<JsonObject>;
writeTags(track: ResourceRef, tags: {
title?: string;
artists?: string[];
album?: string;
lyrics?: LyricsDocument;
}, call: ServiceCall): Promise<void>;
};
settings: {
/** Only explicit public setting names. Secret/unsafe settings are not part of this API. */
get(keys: string[], call: ServiceCall): Promise<JsonObject>;
update(values: JsonObject, call: ServiceCall): Promise<void>;
};
window: {
control(action: 'show' | 'minimize' | 'maximize' | 'restore' | 'mini-player', call: ServiceCall): Promise<void>;
};
hotkeys: {
register(request: {
id: string;
accelerator: string;
commandId: string;
}, call: ServiceCall): Promise<Disposable>;
};
sharing: {
create(request: ShareDescriptor, call: ServiceCall): Promise<{
id: string;
url: string;
expiresAt?: number;
}>;
revoke(id: string, call: ServiceCall): Promise<void>;
resolve(url: string, operation: OperationContext): Promise<ShareDescriptor>;
};
rooms: {
getState(call: ServiceCall): Promise<RoomState>;
join(inviteCode: string, call: ServiceCall): Promise<RoomState>;
leave(call: ServiceCall): Promise<void>;
requestTrack(track: ResourceRef, call: ServiceCall): Promise<void>;
};
devices: {
list(call: ServiceCall): Promise<AudioDevice[]>;
select(id: string, call: ServiceCall): Promise<void>;
};
ai: {
generate(request: {
prompt: string;
maxOutputChars?: number;
}, call: ServiceCall): Promise<{
text: string;
}>;
};
tasks: {
schedule(request: {
id: string;
commandId: string;
intervalMs: number;
}, call: ServiceCall): Promise<{
id: string;
}>;
cancel(id: string, call: ServiceCall): Promise<void>;
};
events: {
on<K extends import('./events.js').OperationEventName>(event: K, listener: (value: import('./events.js').OperationEvent<K>) => void | Promise<void>): Disposable;
on<K extends keyof HostServiceEvents>(event: K, listener: (value: HostServiceEvents[K]) => void, call?: ServiceCall): Disposable;
};
}
export interface HostUI {
dialogs: {
confirm(request: {
title: string;
message: string;
confirmText?: string;
}): Promise<boolean>;
prompt(request: {
title: string;
label: string;
value?: string;
secret?: boolean;
}): Promise<string | null>;
pickPlaylist(request?: {
location?: 'local' | 'cloud';
writable?: boolean;
}): Promise<LibraryPlaylist | null>;
};
navigation: {
open(request: HostNavigationRequest): Promise<void>;
};
notifications: {
show(request: {
title: string;
body: string;
}, call: ServiceCall): Promise<void>;
};
progress: {
create(request: {
title: string;
cancellable?: boolean;
}): Promise<{
id: string;
}>;
update(id: string, request: {
value?: number;
message?: string;
}): Promise<void>;
close(id: string): Promise<void>;
};
}
export interface MenuContribution {
id: string;
slot: 'playlist.import' | 'playlist.actions' | 'track.actions' | 'player.actions' | 'search.tools';
title: string;
description?: string;
commandId: string;
icon?: IconRef;
when?: {
kinds?: ('track' | 'playlist')[];
loggedIn?: boolean;
};
}
export type SerializedHostValue = JsonValue | AssetHandle;跨插件服务调用
ts
import type { JsonValue, OperationContext, ServiceDeclaration } from './index.js';
export type ServiceHandler = (input: JsonValue, call: {
callerPluginId: string;
operation: OperationContext;
}) => JsonValue | void | Promise<JsonValue | void>;
export interface PluginsAPI {
use<T = Record<string, (input: JsonValue) => Promise<JsonValue>>>(pluginId: string, service: string): Promise<T | null>;
list(): Promise<{
pluginId: string;
services: ServiceDeclaration[];
}[]>;
on(event: 'available' | 'unavailable', handler: (info: {
pluginId: string;
service: string;
}) => void): () => void;
}Guest 管理、协议与启动
ts
import type { Disposable, JsonValue } from './manifest.js';
import type { OperationContext } from './index.js';
export interface GuestProvider {
id: string;
name: string;
/** Lowest to highest, as declared by the imported script. */
qualities: string[];
protocols: string[];
}
export interface GuestInfo {
id: string;
adapterId: string;
name: string;
version: string;
author?: string;
state: 'ready' | 'stopped' | 'error';
selected: boolean;
providers: GuestProvider[];
error?: string;
}
/** Requires a Host with Guest management support; the SDK does not install Guest runtimes. */
export interface GuestAPI {
list(): Promise<GuestInfo[]>;
/** The Host owns file selection and approval. Cancellation returns null. */
import(adapterId: string): Promise<GuestInfo | null>;
select(guestId: string | null): Promise<void>;
remove(guestId: string): Promise<void>;
invoke(guestId: string, method: string, input: JsonValue, operation: OperationContext): Promise<JsonValue>;
}
export interface GuestBootstrapAPI {
readonly scriptInfo: Readonly<{
name: string;
version: string;
author?: string;
description?: string;
homepage?: string;
rawScript: string;
}>;
ready(metadata: {
providers: GuestProvider[];
}): void;
handle(handler: (method: string, input: JsonValue, operation: OperationContext) => Promise<JsonValue>): Disposable;
invokeHost(method: string, input: JsonValue): Promise<JsonValue>;
}分享与导入
ts
import type { JsonObject, MaybePromise } from './manifest.js';
export interface ShareMusicInfo {
songmid?: string | number;
hash?: string;
id?: string | number;
[key: string]: unknown;
}
/** Context supplied by the separate share-resolver Host, not the desktop PluginContext. */
export interface ShareResolverContext<Config = JsonObject> {
config: Readonly<Config>;
plugin: {
name: string;
version: string;
author?: string;
};
sources: Record<string, {
name: string;
qualitys: string[];
}>;
request<T = unknown>(url: string, options?: {
method?: string;
headers?: Record<string, string>;
body?: string;
timeout?: number;
}): Promise<{
body: T;
statusCode: number;
headers: Record<string, string>;
}>;
/** Only available when the manifest declares a selected Guest adapter. */
guest?: {
name: string;
version: string;
author?: string;
rawScript: string;
};
runGuest?(bindings: Record<string, unknown>): void;
utils: {
buffer: {
from(data: unknown, encoding?: 'base64' | 'hex' | 'utf8'): Uint8Array;
bufToString(data: Uint8Array, encoding?: 'base64' | 'hex' | 'utf8'): string;
};
crypto: {
md5(value: string): string;
randomBytes(size: number): Uint8Array;
aesEncrypt(data: unknown, mode: string, key: unknown, iv?: unknown): Uint8Array;
rsaEncrypt(data: string, key: string): string;
};
};
}
export interface ShareResolver {
musicUrl(source: string, musicInfo: ShareMusicInfo, quality: string): Promise<string>;
}
export type ShareResolverEntry<Config = JsonObject> = (context: ShareResolverContext<Config>) => MaybePromise<ShareResolver>;网络、资源与媒体流
HTTP 客户端、查询和响应
ts
import type { CredentialRef, OperationContext, PluginContext } from './index.js';
export type QueryValue = string | number | boolean | null | undefined;
export interface HttpResponse<T> {
status: number;
headers: Record<string, string>;
data: T;
}
export interface HttpRequestOptions {
responseType?: 'arraybuffer';
operation: OperationContext;
permissionKey?: string;
query?: Record<string, QueryValue | QueryValue[]>;
headers?: Record<string, string>;
method?: string;
json?: unknown;
form?: Record<string, QueryValue>;
body?: string;
credential?: CredentialRef;
timeoutMs?: number;
/** Default: true. Set false to inspect non-2xx platform responses yourself. */
throwHttpErrors?: boolean;
}
export interface HttpClientOptions {
baseURL?: string;
headers?: Record<string, string>;
permissionKey?: string | ((url: URL) => string);
/** Prompt only when a permission is in the prompt state. Never bypass a denial. */
requestPermission?: boolean;
}
export declare class HttpError<T = unknown> extends Error {
readonly response: HttpResponse<T>;
readonly origin: string;
readonly name = "HttpError";
constructor(response: HttpResponse<T>, origin: string);
get status(): number;
}
export declare function networkPermissionKey(origin: string): string;
/** Typed convenience layer over the Host broker. Does not use fetch or grant permissions. */
export declare function createHttpClient(ctx: {
http: Pick<PluginContext['http'], 'request'>;
permissions: Pick<PluginContext['permissions'], 'query' | 'request'>;
}, options: HttpClientOptions): {
request: <T = unknown>(address: string, input: HttpRequestOptions) => Promise<HttpResponse<T>>;
authorize: (key: string, _origin: string, operation: OperationContext) => Promise<void>;
get<T = unknown>(address: string, input: Omit<HttpRequestOptions, "method">): Promise<T>;
post<T = unknown>(address: string, input: Omit<HttpRequestOptions, "method">): Promise<T>;
};WebSocket 与 Socket.IO
ts
import type { Disposable, JsonValue } from './manifest.js';
import type { OperationContext } from './index.js';
export interface SocketConnectOptions {
/** Defaults to network.socket. */
permissionKey?: string;
operation: OperationContext;
/** wss:// for native WebSocket; https:// for Socket.IO. */
url: string;
kind: 'websocket' | 'socket.io';
path?: string;
auth?: Record<string, JsonValue>;
/** Socket.IO reconnects at most five times. Native WebSocket does not auto-reconnect. */
reconnection?: boolean;
}
export interface HostSocket {
readonly id: string;
/** Incoming Socket.IO payloads are arrays of event arguments. WebSocket messages are text. */
on<T extends JsonValue = JsonValue>(event: string, handler: (data: T) => void): Disposable;
emit(event: string, data: JsonValue): Promise<void>;
send(data: JsonValue): Promise<void>;
disconnect(): Promise<void>;
}
export interface SocketAPI {
connect(options: SocketConnectOptions): Promise<HostSocket>;
}服务入口与监听句柄
ts
import type { MaybePromise } from './manifest.js';
import type { Disposable } from './manifest.js';
import type { PluginContext } from './index.js';
/** Use an explicit context type for trusted Node entries supplied by the Host. */
export type ServerEntry<Context = PluginContext> = (ctx: Context) => MaybePromise<void | Disposable>;
/** Identity helper shared by sandbox and explicitly typed trusted server entries. */
export declare function defineServer<Context = PluginContext>(entry: ServerEntry<Context>): ServerEntry<Context>;
/** The handler and its Web streams stay inside the plugin's sandbox. */
export type ServerHandler = (request: Request) => MaybePromise<Response>;
export interface ServerOptions {
port?: number;
lan?: boolean;
permissionKey?: string;
lanPermissionKey?: string;
}
export interface ServerHandle {
readonly url: string;
readonly port: number;
/** Stops the listener and cancels its outstanding requests. Idempotent. */
close(): Promise<void>;
}
export interface ServerAPI {
/** Current sandbox or trusted server address; undefined while stopped. */
readonly url: string | undefined;
readonly port: number | undefined;
/**
* Starts one HTTP listener per plugin. The Host checks network.serve and any
* additional LAN permission. Bodies stream in chunks of at most 1 MiB;
* no more than eight requests may be active in a sandbox at once.
*/
serve(handler: ServerHandler, options?: ServerOptions): Promise<ServerHandle>;
}媒体流与变换
ts
import type { JsonObject, MaybePromise } from './manifest.js';
export type StreamAlgorithm = 'aes-128-ctr' | 'aes-256-ctr' | 'aes-128-cbc' | 'aes-256-cbc' | 'chacha20';
export interface StreamMetadata {
contentType?: string;
/** Plaintext byte length, including any audio headers. */
contentLength?: number;
}
export type StreamSpec = StreamMetadata & ({
decrypt: {
algorithm: StreamAlgorithm;
key: string;
iv: string;
encoding?: 'hex' | 'base64';
};
} | {
transform: string;
info?: JsonObject;
});
export interface StreamTransform {
transform(chunk: Uint8Array): MaybePromise<Uint8Array>;
flush?(): MaybePromise<Uint8Array | void>;
dispose?(): MaybePromise<void>;
}
export interface StreamTransformFactory {
seekable: boolean;
create(input: {
offset: number;
info?: JsonObject;
signal?: AbortSignal;
}): MaybePromise<StreamTransform>;
}
export interface StreamsAPI {
registerTransform(id: string, factory: StreamTransformFactory): () => void;
}
export declare function assertStreamSpec(value: unknown): asserts value is StreamSpec;WebAssembly 资源
ts
import type { AssetHandle } from './index.js';
export interface WasmAPI {
/** Instantiate a WebAssembly resource embedded in this plugin's artifact. */
instantiate(resource: AssetHandle | string, imports?: WebAssembly.Imports): Promise<WebAssembly.WebAssemblyInstantiatedSource>;
}加解密流
ts
import type { StreamAlgorithm } from './streams.js';
export interface CryptoStreamOptions {
/** String keys and IVs are hexadecimal unless base64 is specified. */
encoding?: 'hex' | 'base64';
signal?: AbortSignal;
}
export interface CryptoStreamsAPI {
createCipher(algorithm: StreamAlgorithm, key: string | Uint8Array, iv: string | Uint8Array, options?: CryptoStreamOptions): TransformStream<Uint8Array, Uint8Array>;
createDecipher(algorithm: StreamAlgorithm, key: string | Uint8Array, iv: string | Uint8Array, options?: CryptoStreamOptions): TransformStream<Uint8Array, Uint8Array>;
}图标与资源目录
ts
/** Stable names for Host-provided resources. Platform names identify icons, not mandatory providers. */
export declare const HOST_ICON_NAMES: readonly ["platform.tx", "platform.kg", "platform.kw", "platform.wy", "platform.mg", "platform.local", "platform.all", "search", "music-note", "library", "cloud", "server", "import", "chart", "settings", "play", "pause", "download", "share", "account", "heart", "refresh", "close", "add", "info"];
export type HostIconName = (typeof HOST_ICON_NAMES)[number];
export declare const HOST_ASSET_NAMES: readonly ["app.logo", "placeholder.cover", "placeholder.avatar"];
export type HostAssetName = (typeof HOST_ASSET_NAMES)[number];
export declare const PERMISSION_NAMES: readonly ["account.profile", "downloads.manage", "localMusic.read", "localMusic.write", "settings.read", "settings.write", "window.control", "hotkeys.register", "rooms.read", "rooms.control", "ai.use", "devices.control", "ui.styles.global", "network.request", "network.socket", "network.private", "network.discovery", "network.serve", "network.serve.lan", "streams.transform", "runtime.trusted", "credentials.use", "credentials.read", "credentials.capture", "library.read", "library.write", "library.delete", "player.read", "route.read", "navigation.intercept", "music.read", "music.control", "player.control", "player.intercept", "account.intercept", "library.intercept", "search.intercept", "search.read", "links.read", "notifications.read", "window.read", "window.intercept", "lyrics.intercept", "downloads.intercept", "sharing.intercept", "links.intercept", "notifications.intercept", "playback.fallback.hold", "files.read", "files.write", "downloads.create", "clipboard.read", "clipboard.write", "notifications.system", "external.open", "background.run", "services.consume", "sharing.publish", "sharing.revoke", "guests.manage", "guests.run"];
export type PermissionName = (typeof PERMISSION_NAMES)[number];
/** Runtime modules available to hand-written plugins without bundling. */
export declare const HOST_MODULE_NAMES: readonly ["ceru", "@ceru/http", "@ceru/ui", "@ceru/socket", "@ceru/library", "@ceru/account", "@ceru/player", "@ceru/tools", "@ceru/crypto", "@ceru/compression", "@ceru/encoding", "@ceru/legacy-http", "lodash"];
export type HostModuleName = (typeof HOST_MODULE_NAMES)[number];
export declare const LODASH_METHODS: readonly ["chunk", "compact", "concat", "difference", "drop", "dropRight", "flatten", "flattenDeep", "head", "last", "intersection", "uniq", "uniqBy", "union", "zip", "take", "takeRight", "groupBy", "keyBy", "countBy", "orderBy", "sortBy", "partition", "shuffle", "sample", "map", "filter", "find", "some", "every", "reduce", "includes", "get", "has", "pick", "omit", "mapKeys", "mapValues", "cloneDeep", "isEqual", "isEmpty", "isNil", "isString", "isNumber", "isArray", "isPlainObject", "camelCase", "kebabCase", "snakeCase", "startCase", "capitalize", "escape", "unescape", "trim", "truncate", "debounce", "throttle", "once", "memoize", "clamp", "range", "sum", "sumBy", "round"];
/** 引用宿主图标;例如 hostIcon('platform.tx'),不内嵌图片。 */
export declare function hostIcon(name: HostIconName): {
kind: 'host';
name: HostIconName;
};模块映射
ts
import type { PluginContext, HostLodash } from './index.js';
export interface BuiltinModules {
ceru: PluginContext;
'@ceru/http': PluginContext['http'];
'@ceru/ui': PluginContext['ui'];
'@ceru/socket': PluginContext['sockets'];
'@ceru/library': PluginContext['library'];
'@ceru/account': PluginContext['account'];
'@ceru/player': PluginContext['player'];
'@ceru/tools': PluginContext['utils'];
lodash: HostLodash;
'@ceru/crypto': typeof import('./compat/crypto.js');
'@ceru/compression': typeof import('./compat/zlib.js');
'@ceru/encoding': typeof import('./compat/encoding.js');
'@ceru/legacy-http': typeof import('./legacy-http.js');
}
export interface PluginModules {
require<K extends keyof BuiltinModules>(name: K): BuiltinModules[K];
}兼容工具与校验方法
旧 HTTP 帮助函数
ts
import type { OperationContext, PluginContext } from './index.js';
export interface LegacyOptions {
method?: string;
headers?: Record<string, unknown>;
form?: Record<string, unknown>;
body?: unknown;
[key: string]: unknown;
}
export declare function createLegacyHttpBridge(host: PluginContext): {
httpFetch: (address: string, options?: LegacyOptions) => {
promise: Promise<{
body: any;
statusCode: number;
headers: {
location?: string | undefined;
};
raw: import("./manifest.js").JsonValue;
url: string;
finalUrl: any;
}>;
cancelHttp(): void;
};
withOperation: <T>(operation: OperationContext, work: () => Promise<T>) => Promise<T>;
ensurePermission: (key: string, _origin: string, operation: OperationContext) => Promise<void>;
permissionKey: () => string;
};公开链接
ts
/** Only explicit, single, credential-free URLs may enter the plugin hook pipeline. */
export declare function publicLink(value: unknown): string | null;校验资源与查询参数
ts
import type { ContentEntity, SearchRequest } from './index.js';
export declare function assertSearchRequest(value: unknown): asserts value is SearchRequest;
/**
* Reject anything that is not a plain track list before a destructive call.
* Hosts pass untrusted renderer input here, so this must not depend on the
* caller having already validated shapes.
*/
export declare function assertRemovableTracks(value: unknown): asserts value is ContentEntity[];视图桥接导出
ts
export type * from './view-contracts.js';
export interface ViewDeps {
vue: typeof import('vue');
tdesign: typeof import('tdesign-vue-next');
sdk: typeof import('./vue/index.js');
}兼容加密工具
ts
export function createHash(name: any): {
update(value: any): /*elided*/ any;
/** @returns {string | Buffer} */
digest(encoding: any): string | Buffer;
};
/** @returns {Buffer} */
export function publicEncrypt(options: any, value: any): Buffer;
export function createCipheriv(mode: any, key: any, iv: any): {
/** @returns {Buffer} */
update(value: any): Buffer;
/** @returns {Buffer} */
final(): Buffer;
};
export function createDecipheriv(mode: any, key: any, iv: any): {
/** @returns {Buffer} */
update(value: any): Buffer;
/** @returns {Buffer} */
final(): Buffer;
};
export function randomBytes(size: any): Buffer;
export function randomUUID(): `${string}-${string}-${string}-${string}-${string}`;
export namespace constants {
let RSA_NO_PADDING: number;
}
declare namespace _default {
export { createHash };
export { createCipheriv };
export { createDecipheriv };
export { publicEncrypt };
export { randomBytes };
export { randomUUID };
export { constants };
}
export default _default;
import { Buffer } from 'buffer';编码工具
ts
declare namespace _default {
function decode(bytes: any, encoding: any): string;
}
export default _default;格式化工具
ts
export function decodeName(value: any): string;
export function formatPlayTime(seconds: any): string;
export function sizeFormate(size: any): string;
export function formatPlayCount(value: any): string;
export function dateFormat(value: any): string;
export function dateFormat2(value: any): string;
export function formatNumberToChineseSimple(value: any): string;
export function formatMinutesFlexible(seconds: any): string;压缩工具
ts
export function inflate(input: any, callback: any): void;
export function unzipSync(input: any): Buffer;
declare namespace _default {
export { unzipSync };
export { inflate };
}
export default _default;
import { Buffer } from 'buffer';Logic 的宿主模块别名(ceru、@ceru/http 等)
ts
declare module 'ceru' {
const core: import('./index.js').PluginContext
export = core
}
declare module '@ceru/http' {
const http: import('./index.js').PluginContext['http']
export = http
}
declare module '@ceru/ui' {
const ui: import('./index.js').PluginContext['ui']
export = ui
}
declare module '@ceru/socket' {
const sockets: import('./index.js').PluginContext['sockets']
export = sockets
}
declare module '@ceru/library' {
const library: import('./index.js').PluginContext['library']
export = library
}
declare module '@ceru/account' {
const account: import('./index.js').PluginContext['account']
export = account
}
declare module '@ceru/player' {
const player: import('./index.js').PluginContext['player']
export = player
}
declare module '@ceru/tools' {
const tools: import('./index.js').PluginContext['utils']
export = tools
}
declare module '@ceru/crypto' {
const crypto: typeof import('./compat/crypto.js')
export = crypto
}
declare module '@ceru/compression' {
const compression: typeof import('./compat/zlib.js')
export = compression
}
declare module '@ceru/encoding' {
const encoding: typeof import('./compat/encoding.js')
export = encoding
}
declare module '@ceru/legacy-http' {
export const createLegacyHttpBridge: typeof import('./legacy-http.js').createLegacyHttpBridge
}SDK 许可证
text
MIT License
Copyright (c) 2026 Ceru Music contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.从一个返回值读到下一步
例如歌单列表的返回类型含有分页对象,先查 library 或 music 方法的返回类型,再展开 Page<T> 和 MusicPlaylist。只把标题等展示字段送给 View,保留原始 ref 作为打开歌单的依据。遇到 @deprecated 应回到对应新类型,例如写新歌词接口时使用 CrLyric。v2 清单与运行时的实际可用方法请按v2 文档和迁移对照核对。