@songloft/lynx-plugin-sdk 0.0.0-stage → 2.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,144 @@
1
- # Temporary Holding Version
1
+ # @songloft/lynx-plugin-sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Lynx 原生渲染插件的客户端 SDK。运行在子 `<frame>` bundle 内,通过 `NativeModules.SongloftPluginBridge` 与宿主通信。
4
+
5
+ ## 安装
6
+
7
+ ```bash
8
+ pnpm add @songloft/lynx-plugin-sdk
9
+ ```
10
+
11
+ ## 快速上手
12
+
13
+ ```tsx
14
+ import { invokeHost, onPlayerState, onThemeChange, getTheme, getFrameId } from '@songloft/lynx-plugin-sdk'
15
+
16
+ // 调用宿主方法(返回 Promise)
17
+ const info = await invokeHost('host', 'getInfo')
18
+ await invokeHost('player', 'play', { id: 123 })
19
+
20
+ // 监听播放器状态
21
+ const unsub = onPlayerState((state) => {
22
+ console.log(state.current_song, state.is_playing)
23
+ })
24
+
25
+ // 监听主题切换
26
+ onThemeChange((theme) => {
27
+ console.log('theme:', theme) // 'light' | 'dark'
28
+ })
29
+
30
+ // 读取宿主注入的全局属性
31
+ const frameId = getFrameId()
32
+ const theme = getTheme()
33
+ ```
34
+
35
+ ## API
36
+
37
+ ### `invokeHost(ns, method, params?): Promise<HostCallResult>`
38
+
39
+ 向宿主发送一次 RPC 调用。宿主收到后通过 `hostReply` 回传结果。
40
+
41
+ - `ns` — 命名空间(如 `'host'`、`'player'`)
42
+ - `method` — 方法名
43
+ - `params` — 可选参数对象
44
+ - 返回 `{ ok: boolean; data?: unknown; error?: string }`
45
+ - 超时 10 秒自动返回 `{ ok: false, error: 'timeout' }`
46
+
47
+ ### `onPlayerState(cb): () => void`
48
+
49
+ 监听宿主推送的播放器状态。返回取消订阅函数。
50
+
51
+ `PlayerState` 包含:`queue`、`current_index`、`current_song`、`is_playing`、`current_time`、`duration`、`volume`、`play_mode`、`source_playlist_id`。
52
+
53
+ ### `onThemeChange(cb): () => void`
54
+
55
+ 监听宿主推送的主题变更(`'light'` / `'dark'`)。返回取消订阅函数。
56
+
57
+ ### `onPush(cb): () => void`
58
+
59
+ 监听所有宿主推送事件。`cb(event, data)` 中 `event` 为事件名,`data` 为原始 JSON 字符串。
60
+
61
+ 事件订阅会注册子 frame,不要求先调用 RPC。原生宿主通过 `onPush` 推送 `event === 'lifecycle'`、`JSON.parse(data).state === 'resumed'`:首次订阅准备完成提供一次初始可见通知,此后每次恢复前台通知一次,插件自行重连/刷新快照。取消订阅后不再消费事件;宿主切换/关闭插件后停止推送。Web 使用浏览器可见性通知。已有插件需要用包含此注册逻辑的 SDK 重新构建,旧 bundle 不会自动获得这段 SDK 改动。
62
+
63
+ ### `getGlobalProps(): Partial<PluginGlobalProps>`
64
+
65
+ 读取宿主通过 `<frame>` 元素注入的全局属性。
66
+
67
+ ### `getFrameId(): string`
68
+
69
+ 返回当前 frame 的 ID(用于标识父子通信通道)。
70
+
71
+ ### `getTheme(): 'light' | 'dark'`
72
+
73
+ 返回当前主题,默认 `'light'`。
74
+
75
+ ## 通信架构
76
+
77
+ ```
78
+ ┌─────────────────────┐ ┌────────────────────────┐
79
+ │ 宿主 (Host App) │ │ 子 frame (Plugin) │
80
+ │ │ │ │
81
+ │ registerHost(fid) │◄────────│ registerChild(fid) │
82
+ │ │ │ │
83
+ │ hostCall handler │◄────────│ invokeHost(ns,method) │
84
+ │ ↓ process │ │ │
85
+ │ hostReply(callId) │────────►│ Promise resolves │
86
+ │ │ │ │
87
+ │ pushToChild(event) │────────►│ onPush / onPlayer... │
88
+ └─────────────────────┘ └────────────────────────┘
89
+ ```
90
+
91
+ 通信通过 `SongloftPluginBridge` Native Module 中转,按 `frameId` 路由。三端(Android/iOS/HarmonyOS)实现一致,由契约测试锁住。
92
+
93
+ ## 适用场景
94
+
95
+ 此 SDK 仅用于 `renderEngine: "lynx"` 的插件。WebView 插件使用 `@songloft/plugin-sdk`。
96
+
97
+ 创建 Lynx 插件:
98
+
99
+ ```bash
100
+ pnpm create @songloft/songloft-plugin
101
+ # 选择 "Lynx 原生渲染" 模板
102
+ ```
103
+
104
+ ## 插件业务请求 / Plugin API requests
105
+
106
+ ```ts
107
+ import { apiGet, apiPost, apiPut, apiDelete } from '@songloft/lynx-plugin-sdk'
108
+ const status = await apiGet<{ logged_in: boolean }>('/api/login/status')
109
+ await apiPost('/api/settings', { audio_quality: 'high' })
110
+ await apiPut('/api/settings', { audio_quality: 'lossless' })
111
+ await apiDelete('/api/groups?id=1')
112
+ ```
113
+
114
+ 请求通过 `plugin.apiRequest` 交给当前 frame 的宿主;宿主绑定插件身份,处理服务器子路径与认证。只接受 `/api` 下的 GET/POST/PUT/DELETE JSON 请求,禁止绝对地址、编码路径与路径穿越。成功返回业务数据,HTTP、桥接、超时或响应中的 `error` 会抛出异常。宿主请求上限 60 秒,SDK 等待回复上限 65 秒。旧宿主不支持时明确报错,需要更新 Lynx 客户端;Flutter/Web 回退需要更新服务端提供的 shim。插件不需要获取 Token。
115
+
116
+ Requests use `plugin.apiRequest`. The host binds the current frame's plugin identity and supplies the server base path and authentication. Only GET/POST/PUT/DELETE JSON requests under `/api` are accepted; absolute URLs, encoded route paths and traversal are rejected. Successful calls return business data. HTTP, bridge, timeout and response `error` failures throw. Host requests expire after 60 seconds; SDK replies expire after 65 seconds. Older hosts report an unsupported-call error: update the Lynx client, or the server-provided shim for Flutter/Web fallback. Plugins do not need access tokens.
117
+
118
+ ## 发布 / Publishing
119
+
120
+ 本包加入工具链统一发版(从 v2.20.0 起),`scripts/release.mjs` 同步版本和脚手架依赖,Release workflow 发布 npm 包。首次发布需先完成 npm 身份认证及后续 Trusted Publisher 配置,不能把仅推送 main 视为 npm 已发布。
121
+
122
+ This package participates in the unified toolchain release (starting with v2.20.0). The release script synchronizes package/template versions and the Release workflow publishes to npm. Initial publishing needs npm authentication and subsequent Trusted Publisher configuration; a main-branch push alone does not publish the package.
123
+
124
+
125
+ 发布中途失败后,可以从 main 执行 `gh workflow run release.yml -f tag=v2.20.0` 恢复同一个 tag。源码仍固定到该 tag,发布工具取自工作流提交;已存在版本跳过,仅明确的 npm E404 才尝试发布,认证和网络失败会中止。首次发布 Lynx SDK 需 npm 账号完成浏览器验证,随后可在 npm 包设置中配置此仓库 `release.yml` 的 Trusted Publisher。
126
+
127
+ After a partial failure, run `gh workflow run release.yml -f tag=v2.20.0` from main to resume the same tag. Package sources remain pinned to the tag; publishing tools come from the workflow revision. Existing versions are skipped; only explicit npm E404 results permit publishing, while authentication/network errors stop the run. Initial SDK publishing requires browser verification through an npm account; configure this repository's `release.yml` as a Trusted Publisher in the package settings afterward.
128
+
129
+ ## 文本连接 / Text sockets
130
+
131
+ ```ts
132
+ import { PluginSocket } from '@songloft/lynx-plugin-sdk'
133
+ const socket = new PluginSocket('/status/ws?device_id=example')
134
+ socket.onopen = () => socket.send('refresh')
135
+ socket.onmessage = ({ data }) => console.log(data)
136
+ socket.onerror = () => console.log('connection failed')
137
+ socket.onclose = () => console.log('closed')
138
+ // Dispose on hide/unmount; create a fresh connection when resumed.
139
+ socket.close()
140
+ ```
141
+
142
+ 路径仅限当前插件的相对路径;宿主提供服务器地址、子路径与认证,按 frame 限八条连接并在释放时关闭。`readyState` 为 0/1/2/3;文本上行最多 65536 字符。需要配套新版 Android/iOS/HarmonyOS/Web 宿主或服务端回退 shim;源码存在不代表 npm 已发布。
143
+
144
+ Only relative paths within the current plugin are accepted. The host supplies server/base path/authentication, caps each frame at eight sockets and closes them on release. `readyState` is 0/1/2/3; outgoing text is limited to 65536 characters. Matching updated native/Web hosts or the server fallback shim are required. Source changes do not imply an npm publication.
package/dist/api.d.ts ADDED
@@ -0,0 +1,6 @@
1
+ /** Only routes belonging to this plugin are accepted. Query values may be encoded. */
2
+ export declare function validateApiPath(path: string): void;
3
+ export declare const apiGet: <T = unknown>(path: string) => Promise<T>;
4
+ export declare const apiPost: <T = unknown>(path: string, body: unknown) => Promise<T>;
5
+ export declare const apiPut: <T = unknown>(path: string, body: unknown) => Promise<T>;
6
+ export declare const apiDelete: <T = unknown>(path: string) => Promise<T>;
package/dist/api.js ADDED
@@ -0,0 +1,25 @@
1
+ import { invokeHost } from './bridge.js';
2
+ /** Only routes belonging to this plugin are accepted. Query values may be encoded. */
3
+ export function validateApiPath(path) {
4
+ const route = path.split('?')[0];
5
+ if (!/^\/api(?:\/|$)/.test(route) ||
6
+ /[\\#\s]/.test(path) ||
7
+ /%/.test(route) ||
8
+ route.split('/').some((part) => part === '.' || part === '..')) {
9
+ throw new Error('invalid plugin API path');
10
+ }
11
+ }
12
+ async function request(method, path, body) {
13
+ validateApiPath(path);
14
+ const reply = await invokeHost('plugin', 'apiRequest', { method, path, body }, 65000);
15
+ if (!reply.ok)
16
+ throw new Error(reply.error || 'plugin API request failed');
17
+ const data = reply.data;
18
+ if (data && typeof data === 'object' && data.error)
19
+ throw new Error(String(data.error));
20
+ return data;
21
+ }
22
+ export const apiGet = (path) => request('GET', path);
23
+ export const apiPost = (path, body) => request('POST', path, body);
24
+ export const apiPut = (path, body) => request('PUT', path, body);
25
+ export const apiDelete = (path) => request('DELETE', path);
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Host call bridge — sends requests to the parent via NativeModules.SongloftPluginBridge
3
+ * and awaits replies via GlobalEventEmitter.
4
+ */
5
+ export interface HostCallResult {
6
+ ok: boolean;
7
+ data?: unknown;
8
+ error?: string;
9
+ }
10
+ /**
11
+ * Invoke a host method. Returns a promise that resolves when the host replies.
12
+ *
13
+ * @example
14
+ * const info = await invokeHost('host', 'getInfo')
15
+ * await invokeHost('player', 'play', { id: 123 })
16
+ */
17
+ export declare function invokeHost(ns: string, method: string, params?: Record<string, unknown>, timeoutMs?: number): Promise<HostCallResult>;
package/dist/bridge.js ADDED
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Host call bridge — sends requests to the parent via NativeModules.SongloftPluginBridge
3
+ * and awaits replies via GlobalEventEmitter.
4
+ */
5
+ import { getFrameId } from './globals.js';
6
+ import { registerChild } from './registration.js';
7
+ let callIdCounter = 0;
8
+ const pendingCalls = new Map();
9
+ let initialized = false;
10
+ function ensureInit() {
11
+ registerChild();
12
+ if (initialized)
13
+ return;
14
+ try {
15
+ if (typeof lynx === 'undefined')
16
+ return;
17
+ const emitter = lynx.getJSModule('GlobalEventEmitter');
18
+ if (!emitter)
19
+ return;
20
+ initialized = true;
21
+ emitter.addListener('SongloftPluginBridge.hostReply', (data) => {
22
+ const payload = data;
23
+ if (!payload?.callId)
24
+ return;
25
+ const pending = pendingCalls.get(payload.callId);
26
+ if (!pending)
27
+ return;
28
+ pendingCalls.delete(payload.callId);
29
+ if (pending.timer !== undefined)
30
+ clearTimeout(pending.timer);
31
+ try {
32
+ const result = JSON.parse(payload.result ?? '{"ok":false,"error":"empty reply"}');
33
+ pending.resolve(result);
34
+ }
35
+ catch {
36
+ pending.resolve({ ok: false, error: 'invalid reply JSON' });
37
+ }
38
+ });
39
+ }
40
+ catch {
41
+ /* no emitter */
42
+ }
43
+ }
44
+ /**
45
+ * Invoke a host method. Returns a promise that resolves when the host replies.
46
+ *
47
+ * @example
48
+ * const info = await invokeHost('host', 'getInfo')
49
+ * await invokeHost('player', 'play', { id: 123 })
50
+ */
51
+ export function invokeHost(ns, method, params, timeoutMs = 10000) {
52
+ ensureInit();
53
+ const frameId = getFrameId();
54
+ const callId = `c${++callIdCounter}`;
55
+ return new Promise((resolve) => {
56
+ const pending = {
57
+ resolve,
58
+ timer: undefined,
59
+ };
60
+ pendingCalls.set(callId, pending);
61
+ try {
62
+ if (typeof NativeModules !== 'undefined' &&
63
+ NativeModules.SongloftPluginBridge) {
64
+ NativeModules.SongloftPluginBridge.hostCall(frameId, callId, ns, method, JSON.stringify(params ?? {}));
65
+ }
66
+ else {
67
+ pendingCalls.delete(callId);
68
+ resolve({ ok: false, error: 'SongloftPluginBridge not available' });
69
+ }
70
+ }
71
+ catch (e) {
72
+ pendingCalls.delete(callId);
73
+ resolve({ ok: false, error: String(e) });
74
+ }
75
+ // Timeout: don't leave promises hanging forever
76
+ if (!pendingCalls.has(callId))
77
+ return;
78
+ pending.timer = setTimeout(() => {
79
+ if (pendingCalls.has(callId)) {
80
+ pendingCalls.delete(callId);
81
+ resolve({ ok: false, error: 'timeout' });
82
+ }
83
+ }, timeoutMs);
84
+ });
85
+ }
@@ -0,0 +1,29 @@
1
+ export interface PlayerState {
2
+ queue: Array<{
3
+ id: number;
4
+ title?: string;
5
+ artist?: string;
6
+ }>;
7
+ current_index: number;
8
+ current_song: {
9
+ id: number;
10
+ title?: string;
11
+ artist?: string;
12
+ } | null;
13
+ is_playing: boolean;
14
+ current_time: number;
15
+ duration: number;
16
+ volume: number;
17
+ play_mode: string;
18
+ source_playlist_id: number | null;
19
+ }
20
+ type PushCallback = (event: string, data: unknown) => void;
21
+ type PlayerStateCallback = (state: PlayerState) => void;
22
+ type ThemeCallback = (theme: 'light' | 'dark') => void;
23
+ /** Subscribe to all push events from the host. */
24
+ export declare function onPush(cb: PushCallback): () => void;
25
+ /** Subscribe to player state updates from the host. */
26
+ export declare function onPlayerState(cb: PlayerStateCallback): () => void;
27
+ /** Subscribe to theme changes from the host. */
28
+ export declare function onThemeChange(cb: ThemeCallback): () => void;
29
+ export {};
package/dist/events.js ADDED
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Event subscriptions — listen for state/theme pushes from the host.
3
+ */
4
+ import { registerChild, notifyPushReady } from './registration.js';
5
+ const pushListeners = [];
6
+ const playerStateListeners = [];
7
+ const themeListeners = [];
8
+ let eventsInitialized = false;
9
+ function ensureEvents() {
10
+ registerChild();
11
+ if (eventsInitialized)
12
+ return;
13
+ try {
14
+ if (typeof lynx === 'undefined')
15
+ return;
16
+ const emitter = lynx.getJSModule('GlobalEventEmitter');
17
+ if (!emitter)
18
+ return;
19
+ emitter.addListener('SongloftPluginBridge.push', (data) => {
20
+ const payload = data;
21
+ if (!payload?.event)
22
+ return;
23
+ for (const cb of pushListeners)
24
+ cb(payload.event, payload.data);
25
+ if (payload.event === 'playerState' && payload.data) {
26
+ try {
27
+ const state = JSON.parse(payload.data);
28
+ for (const cb of playerStateListeners)
29
+ cb(state);
30
+ }
31
+ catch { /* invalid JSON */ }
32
+ }
33
+ if (payload.event === 'theme' && payload.data) {
34
+ try {
35
+ const { theme } = JSON.parse(payload.data);
36
+ for (const cb of themeListeners)
37
+ cb(theme);
38
+ }
39
+ catch { /* invalid JSON */ }
40
+ }
41
+ });
42
+ eventsInitialized = true;
43
+ notifyPushReady();
44
+ }
45
+ catch { /* no emitter */ }
46
+ }
47
+ /** Subscribe to all push events from the host. */
48
+ export function onPush(cb) {
49
+ pushListeners.push(cb);
50
+ ensureEvents();
51
+ return () => {
52
+ const i = pushListeners.indexOf(cb);
53
+ if (i >= 0)
54
+ pushListeners.splice(i, 1);
55
+ };
56
+ }
57
+ /** Subscribe to player state updates from the host. */
58
+ export function onPlayerState(cb) {
59
+ playerStateListeners.push(cb);
60
+ ensureEvents();
61
+ return () => {
62
+ const i = playerStateListeners.indexOf(cb);
63
+ if (i >= 0)
64
+ playerStateListeners.splice(i, 1);
65
+ };
66
+ }
67
+ /** Subscribe to theme changes from the host. */
68
+ export function onThemeChange(cb) {
69
+ themeListeners.push(cb);
70
+ ensureEvents();
71
+ return () => {
72
+ const i = themeListeners.indexOf(cb);
73
+ if (i >= 0)
74
+ themeListeners.splice(i, 1);
75
+ };
76
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Read host-injected data from global-props (set by the parent <frame> element).
3
+ */
4
+ export interface PluginGlobalProps {
5
+ frameId: string;
6
+ theme: 'light' | 'dark';
7
+ hostVersion: string;
8
+ embed: boolean;
9
+ }
10
+ export declare function getGlobalProps(): Partial<PluginGlobalProps>;
11
+ export declare function getFrameId(): string;
12
+ export declare function getTheme(): 'light' | 'dark';
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Read host-injected data from global-props (set by the parent <frame> element).
3
+ */
4
+ export function getGlobalProps() {
5
+ try {
6
+ if (typeof lynx !== 'undefined' && lynx?.__globalProps) {
7
+ return lynx.__globalProps;
8
+ }
9
+ }
10
+ catch { /* bare global not available */ }
11
+ return {};
12
+ }
13
+ export function getFrameId() {
14
+ return getGlobalProps().frameId ?? '';
15
+ }
16
+ export function getTheme() {
17
+ return getGlobalProps().theme ?? 'light';
18
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * @songloft/lynx-plugin-sdk
3
+ *
4
+ * SDK for Lynx-native Songloft plugins (renderEngine: "lynx").
5
+ * Runs inside a child <frame> bundle, communicates with the host app
6
+ * through NativeModules.SongloftPluginBridge.
7
+ *
8
+ * Usage:
9
+ * import { invokeHost, onPlayerState, onThemeChange, getGlobalProps } from '@songloft/lynx-plugin-sdk'
10
+ *
11
+ * const info = await invokeHost('host', 'getInfo')
12
+ * onPlayerState((state) => { ... })
13
+ */
14
+ export { invokeHost, type HostCallResult } from './bridge.js';
15
+ export { apiGet, apiPost, apiPut, apiDelete } from './api.js';
16
+ export { onPlayerState, onThemeChange, onPush, type PlayerState, } from './events.js';
17
+ export { getGlobalProps, getFrameId, getTheme } from './globals.js';
18
+ export { PluginSocket } from './socket.js';
package/dist/index.js ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * @songloft/lynx-plugin-sdk
3
+ *
4
+ * SDK for Lynx-native Songloft plugins (renderEngine: "lynx").
5
+ * Runs inside a child <frame> bundle, communicates with the host app
6
+ * through NativeModules.SongloftPluginBridge.
7
+ *
8
+ * Usage:
9
+ * import { invokeHost, onPlayerState, onThemeChange, getGlobalProps } from '@songloft/lynx-plugin-sdk'
10
+ *
11
+ * const info = await invokeHost('host', 'getInfo')
12
+ * onPlayerState((state) => { ... })
13
+ */
14
+ export { invokeHost } from './bridge.js';
15
+ export { apiGet, apiPost, apiPut, apiDelete } from './api.js';
16
+ export { onPlayerState, onThemeChange, onPush, } from './events.js';
17
+ export { getGlobalProps, getFrameId, getTheme } from './globals.js';
18
+ export { PluginSocket } from './socket.js';
@@ -0,0 +1,4 @@
1
+ /** Event-only plugins must be reachable before their first RPC call. */
2
+ export declare function registerChild(): void;
3
+ /** Notify the parent only after its child's push listener is installed. */
4
+ export declare function notifyPushReady(): void;
@@ -0,0 +1,26 @@
1
+ import { getFrameId } from './globals.js';
2
+ let registered = '';
3
+ /** Event-only plugins must be reachable before their first RPC call. */
4
+ export function registerChild() {
5
+ try {
6
+ const frameId = getFrameId();
7
+ if (!frameId || registered === frameId || typeof NativeModules === 'undefined')
8
+ return;
9
+ const bridge = NativeModules.SongloftPluginBridge;
10
+ if (typeof bridge?.registerChild !== 'function')
11
+ return;
12
+ bridge.registerChild(frameId);
13
+ registered = frameId;
14
+ }
15
+ catch { /* A later subscription/RPC can retry an unavailable host. */ }
16
+ }
17
+ /** Notify the parent only after its child's push listener is installed. */
18
+ export function notifyPushReady() {
19
+ try {
20
+ const frameId = getFrameId();
21
+ if (frameId && typeof NativeModules !== 'undefined') {
22
+ NativeModules.SongloftPluginBridge?.hostCall(frameId, 'lifecycle-ready', 'lifecycle', 'ready', '{}');
23
+ }
24
+ }
25
+ catch { /* Older hosts still support their existing RPC/event methods. */ }
26
+ }
@@ -0,0 +1,22 @@
1
+ /** A text WebSocket scoped to the current plugin. Authentication stays in the host. */
2
+ export declare class PluginSocket {
3
+ readonly CONNECTING = 0;
4
+ readonly OPEN = 1;
5
+ readonly CLOSING = 2;
6
+ readonly CLOSED = 3;
7
+ readyState: number;
8
+ onopen: (() => void) | null;
9
+ onmessage: ((event: {
10
+ data: string;
11
+ }) => void) | null;
12
+ onerror: ((event?: unknown) => void) | null;
13
+ onclose: (() => void) | null;
14
+ private readonly id;
15
+ private unsubscribe;
16
+ constructor(path: string);
17
+ private call;
18
+ private fail;
19
+ private finish;
20
+ send(data: string): void;
21
+ close(code?: number, reason?: string): void;
22
+ }
package/dist/socket.js ADDED
@@ -0,0 +1,88 @@
1
+ import { invokeHost } from './bridge.js';
2
+ import { onPush } from './events.js';
3
+ let sequence = 0;
4
+ /** A text WebSocket scoped to the current plugin. Authentication stays in the host. */
5
+ export class PluginSocket {
6
+ constructor(path) {
7
+ this.CONNECTING = 0;
8
+ this.OPEN = 1;
9
+ this.CLOSING = 2;
10
+ this.CLOSED = 3;
11
+ this.readyState = 0;
12
+ this.onopen = null;
13
+ this.onmessage = null;
14
+ this.onerror = null;
15
+ this.onclose = null;
16
+ this.id = `socket-${++sequence}`;
17
+ if (!path.startsWith('/') ||
18
+ path.startsWith('//') ||
19
+ /[\\#\s]/.test(path) ||
20
+ /%/.test(path.split('?')[0]) ||
21
+ path
22
+ .split('?')[0]
23
+ .split('/')
24
+ .some((p) => p === '..' || p === '.'))
25
+ throw new Error('invalid plugin socket path');
26
+ this.unsubscribe = onPush((event, raw) => {
27
+ if (event !== 'pluginSocket')
28
+ return;
29
+ let frame;
30
+ try {
31
+ frame = JSON.parse(String(raw));
32
+ }
33
+ catch {
34
+ return;
35
+ }
36
+ if (!frame ||
37
+ typeof frame !== 'object' ||
38
+ frame.id !== this.id ||
39
+ this.readyState === this.CLOSED)
40
+ return;
41
+ if (frame.type === 'open' && this.readyState === this.CONNECTING) {
42
+ this.readyState = this.OPEN;
43
+ this.onopen?.();
44
+ }
45
+ else if (frame.type === 'message' && this.readyState === this.OPEN)
46
+ this.onmessage?.({ data: frame.data || '' });
47
+ else if (frame.type === 'error')
48
+ this.fail();
49
+ else if (frame.type === 'close')
50
+ this.finish();
51
+ });
52
+ void this.call('socketOpen', { path }).catch(() => this.fail());
53
+ }
54
+ async call(method, params = {}) {
55
+ const result = await invokeHost('plugin', method, {
56
+ ...params,
57
+ id: this.id,
58
+ });
59
+ if (!result.ok)
60
+ throw new Error(result.error || 'plugin socket failed');
61
+ }
62
+ fail() {
63
+ if (this.readyState >= this.CLOSING)
64
+ return;
65
+ this.onerror?.();
66
+ this.finish();
67
+ }
68
+ finish() {
69
+ if (this.readyState === this.CLOSED)
70
+ return;
71
+ this.readyState = this.CLOSED;
72
+ this.unsubscribe();
73
+ this.onclose?.();
74
+ }
75
+ send(data) {
76
+ if (this.readyState !== this.OPEN)
77
+ throw new Error('socket is not open');
78
+ void this.call('socketSend', { data }).catch(() => this.fail());
79
+ }
80
+ close(code = 1000, reason = 'client') {
81
+ if (this.readyState >= this.CLOSING)
82
+ return;
83
+ this.readyState = this.CLOSING;
84
+ void this.call('socketClose', { code, reason })
85
+ .finally(() => this.finish())
86
+ .catch(() => { });
87
+ }
88
+ }
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "@songloft/lynx-plugin-sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "2.21.0",
4
+ "description": "SDK for Songloft plugins rendered via Lynx native (renderEngine: lynx)",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.js"
12
+ }
13
+ },
14
+ "files": [
15
+ "dist",
16
+ "README.md"
17
+ ],
18
+ "license": "MIT",
19
+ "devDependencies": {
20
+ "typescript": "~5.8.0"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/songloft-org/plugin-toolchain.git",
28
+ "directory": "packages/lynx-plugin-sdk"
29
+ },
30
+ "scripts": {
31
+ "build": "tsc",
32
+ "dev": "tsc --watch",
33
+ "test": "node --test tests/*.test.mjs"
34
+ }
6
35
  }