@shiqianjiang/ceru-plugin-sdk 0.1.0 → 0.2.1

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/dist/index.d.ts CHANGED
@@ -1,7 +1,22 @@
1
+ /// <reference path="./host-modules.d.ts" />
1
2
  /** This package defines the v2 wire/authoring contract. It does not grant Host permissions. */
2
3
  import type { LoDashStatic } from 'lodash';
3
4
  import type { HostIconName, HostAssetName, LODASH_METHODS } from './catalog.js';
4
5
  export * from './catalog.js';
6
+ export * from './http.js';
7
+ export * from './library.js';
8
+ export * from './sockets.js';
9
+ import type { SocketAPI } from './sockets.js';
10
+ import type { createHttpClient, HttpClientOptions } from './http.js';
11
+ export * from './music.js';
12
+ export * from './permissions.js';
13
+ export * from './services.js';
14
+ export * from './modules.js';
15
+ import type { PluginModules } from './modules.js';
16
+ import type { HostServices, HostUI } from './services.js';
17
+ import type { PermissionGrant, PermissionGroupRequest, PermissionGroupResult } from './permissions.js';
18
+ import type { ChartMetadata, LyricsDocument, PlaylistMetadata, TrackMetadata } from './music.js';
19
+ import type { LibraryAPI, PlaylistImporterImplementation } from './library.js';
5
20
  /** 宿主在插件自己的隔离环境提供这些 Lodash 方法;不会打入插件发行文件。 */
6
21
  export type HostLodash = Pick<LoDashStatic, (typeof LODASH_METHODS)[number]>;
7
22
  export * from './manifest.js';
@@ -12,12 +27,15 @@ export interface ResourceRef {
12
27
  connectionId?: string;
13
28
  kind: string;
14
29
  id: string;
30
+ /** Opaque plugin-owned JSON persisted by the Host and returned only to this plugin. */
31
+ data?: JsonObject;
15
32
  }
16
33
  export interface AssetHandle {
17
34
  readonly kind: 'asset';
18
35
  readonly id: string;
19
36
  }
20
37
  export interface MediaLease {
38
+ /** @deprecated v0.2 providers return direct playback URLs. */
21
39
  readonly kind: 'media';
22
40
  readonly id: string;
23
41
  }
@@ -45,6 +63,10 @@ export interface ContentEntity {
45
63
  durationMs?: number;
46
64
  capabilities: string[];
47
65
  extensions?: JsonObject;
66
+ /** Standard metadata consumed directly by the Host; never raw platform response objects. */
67
+ metadata?: TrackMetadata;
68
+ playlist?: PlaylistMetadata;
69
+ chart?: ChartMetadata;
48
70
  }
49
71
  export interface Page<T> {
50
72
  items: T[];
@@ -79,19 +101,50 @@ export interface MusicFault {
79
101
  }
80
102
  export type ResolveResult = {
81
103
  ok: true;
82
- media: MediaLease;
104
+ url: string;
105
+ expiresAt?: number;
83
106
  } | {
84
107
  ok: false;
85
108
  error: MusicFault;
86
109
  };
110
+ export interface TrackProvider {
111
+ search?(request: SearchRequest, operation: OperationContext): Promise<Page<ContentEntity>>;
112
+ resolve?(resource: ResourceRef, quality: string | undefined, operation: OperationContext): Promise<ResolveResult>;
113
+ lyrics?(resource: ResourceRef, operation: OperationContext): Promise<LyricsDocument>;
114
+ }
115
+ export interface PlaylistProvider {
116
+ search?(request: SearchRequest, operation: OperationContext): Promise<Page<ContentEntity>>;
117
+ categories?(operation: OperationContext): Promise<Page<ContentEntity>>;
118
+ list?(resource: ResourceRef, cursor: string | undefined, operation: OperationContext): Promise<Page<ContentEntity>>;
119
+ get?(resource: ResourceRef, cursor: string | undefined, operation: OperationContext): Promise<Page<ContentEntity>>;
120
+ }
121
+ export interface ChartProvider {
122
+ list?(operation: OperationContext): Promise<Page<ContentEntity>>;
123
+ getTracks?(resource: ResourceRef, cursor: string | undefined, operation: OperationContext): Promise<Page<ContentEntity>>;
124
+ }
125
+ export interface SharingProvider {
126
+ describe?(resource: ResourceRef, policy: JsonObject, operation: OperationContext): Promise<JsonObject>;
127
+ }
87
128
  export interface ProviderImplementation {
129
+ tracks?: TrackProvider;
130
+ playlists?: PlaylistProvider;
131
+ charts?: ChartProvider;
132
+ sharing?: SharingProvider;
133
+ /** @deprecated Use tracks.lyrics. Kept for v2 preview compatibility. */
134
+ lyrics?(resource: ResourceRef, operation: OperationContext): Promise<LyricsDocument>;
135
+ /** @deprecated Use tracks.search. */
88
136
  search?(request: SearchRequest, operation: OperationContext): Promise<Page<ContentEntity>>;
137
+ /** @deprecated Use tracks.resolve. */
89
138
  resolve?(resource: ResourceRef, quality: string | undefined, operation: OperationContext): Promise<ResolveResult>;
139
+ /** @deprecated Use playlists.categories. */
90
140
  categories?(operation: OperationContext): Promise<Page<ContentEntity>>;
141
+ /** @deprecated Use playlists.list/get or charts.getTracks. */
91
142
  list?(resource: ResourceRef, cursor: string | undefined, operation: OperationContext): Promise<Page<ContentEntity>>;
143
+ /** @deprecated Use sharing.describe. */
92
144
  share?(resource: ResourceRef, policy: JsonObject, operation: OperationContext): Promise<JsonObject>;
93
145
  }
94
- export interface PluginContext {
146
+ export interface PluginContext extends HostServices {
147
+ modules: PluginModules;
95
148
  readonly plugin: {
96
149
  id: string;
97
150
  version: string;
@@ -127,6 +180,13 @@ export interface PluginContext {
127
180
  config: {
128
181
  get<T extends JsonObject = JsonObject>(): Promise<T>;
129
182
  };
183
+ /** Uses the application's own local/cloud playlists after Host permission checks. */
184
+ library: LibraryAPI;
185
+ /** Host-provided Socket.IO / WebSocket; no socket library is bundled into the plugin. */
186
+ sockets: SocketAPI;
187
+ playlistImporters: {
188
+ register(id: string, implementation: PlaylistImporterImplementation): Disposable;
189
+ };
130
190
  providers: {
131
191
  register(id: string, implementation: ProviderImplementation): Disposable;
132
192
  };
@@ -134,6 +194,8 @@ export interface PluginContext {
134
194
  register<TInput extends JsonValue = JsonValue, TResult extends JsonValue | void = JsonValue | void>(id: string, handler: (input: TInput, operation: OperationContext) => MaybePromise<TResult>): Disposable;
135
195
  };
136
196
  permissions: {
197
+ getGranted(): Promise<PermissionGrant[]>;
198
+ requestGroup(request: PermissionGroupRequest): Promise<PermissionGroupResult>;
137
199
  query(request: {
138
200
  key: string;
139
201
  scope?: JsonObject;
@@ -149,12 +211,15 @@ export interface PluginContext {
149
211
  }>;
150
212
  };
151
213
  http: {
214
+ /** Axios-backed Host client with JSON/form helpers and typed results. */
215
+ create(options: HttpClientOptions): ReturnType<typeof createHttpClient>;
152
216
  request(request: {
153
217
  permissionKey: string;
154
218
  url: string;
155
219
  method?: string;
156
220
  headers?: Record<string, string>;
157
221
  body?: string;
222
+ timeoutMs?: number;
158
223
  credential?: CredentialRef;
159
224
  operation: OperationContext;
160
225
  }): Promise<{
@@ -166,19 +231,21 @@ export interface PluginContext {
166
231
  credentials: {
167
232
  get(connectionId: string): Promise<CredentialRef | null>;
168
233
  };
169
- media: {
170
- createLease(request: {
171
- permissionKey: string;
172
- url: string;
173
- credential?: CredentialRef;
174
- operation: OperationContext;
175
- expiresAt?: number;
176
- }): Promise<MediaLease>;
177
- };
178
234
  playback: {
179
235
  failure(error: MusicFault): ResolveResult;
180
236
  };
181
- ui: {
237
+ ui: HostUI & {
238
+ toast(message: {
239
+ message: string;
240
+ level?: 'info' | 'success' | 'warning' | 'error';
241
+ }): Promise<void>;
242
+ /** Opens the application's existing import dialog. This does not create a plugin Surface. */
243
+ playlistImport: {
244
+ open(request: {
245
+ importerId: string;
246
+ initialValue?: string;
247
+ }): Promise<void>;
248
+ };
182
249
  setState(surfaceId: string, state: JsonObject): Promise<void>;
183
250
  notify(message: {
184
251
  key: string;
@@ -223,6 +290,11 @@ export interface PluginContext {
223
290
  export type PermissionStatus = 'undeclared' | 'prompt' | 'granted' | 'denied' | 'expired' | 'restricted' | 'unavailable';
224
291
  export interface SurfaceContext extends Pick<PluginContext, 'host' | 'utils' | 'icons' | 'assets'> {
225
292
  readonly root: HTMLElement;
293
+ readonly mount: {
294
+ kind: 'page' | 'slot';
295
+ slot?: import('./manifest.js').UISlotName;
296
+ mode?: 'append' | 'prepend' | 'wrap' | 'replace';
297
+ };
226
298
  invoke(action: string, input: JsonValue): Promise<JsonValue>;
227
299
  subscribe(handler: (state: JsonObject) => void): Disposable;
228
300
  }
@@ -254,6 +326,8 @@ export type UINode = {
254
326
  type: 'button';
255
327
  label: string;
256
328
  action: string;
329
+ } | {
330
+ type: 'host-content';
257
331
  } | {
258
332
  type: 'text-input' | 'input' | 'number' | 'toggle';
259
333
  label: string;
package/dist/index.js CHANGED
@@ -1,4 +1,11 @@
1
1
  export * from './catalog.js';
2
+ export * from './http.js';
3
+ export * from './library.js';
4
+ export * from './sockets.js';
5
+ export * from './music.js';
6
+ export * from './permissions.js';
7
+ export * from './services.js';
8
+ export * from './modules.js';
2
9
  export * from './manifest.js';
3
10
  export function definePlugin(entry) {
4
11
  return entry;
@@ -0,0 +1,25 @@
1
+ import type { OperationContext, PluginContext } from './index.js';
2
+ export interface LegacyOptions {
3
+ method?: string;
4
+ headers?: Record<string, unknown>;
5
+ form?: Record<string, unknown>;
6
+ body?: unknown;
7
+ [key: string]: unknown;
8
+ }
9
+ export declare function createLegacyHttpBridge(host: PluginContext): {
10
+ httpFetch: (address: string, options?: LegacyOptions) => {
11
+ promise: Promise<{
12
+ body: any;
13
+ statusCode: number;
14
+ headers: {
15
+ location?: string | undefined;
16
+ };
17
+ raw: import("./manifest.js").JsonValue;
18
+ url: string;
19
+ }>;
20
+ cancelHttp(): void;
21
+ };
22
+ withOperation: <T>(operation: OperationContext, work: () => Promise<T>) => Promise<T>;
23
+ ensurePermission: (key: string, _origin: string, operation: OperationContext) => Promise<void>;
24
+ permissionKey: () => string;
25
+ };
@@ -0,0 +1,118 @@
1
+ import JSON5 from 'json5';
2
+ import { createHttpClient } from './http.js';
3
+ export function createLegacyHttpBridge(host) {
4
+ const client = createHttpClient(host, {
5
+ permissionKey: 'network',
6
+ requestPermission: true,
7
+ });
8
+ let current;
9
+ let queue = Promise.resolve();
10
+ // Legacy adapters carry mutable paging/cache state. Serialize top-level operations;
11
+ // the adapter's own independent HTTP requests can still run concurrently.
12
+ function withOperation(operation, work) {
13
+ const result = queue.then(async () => {
14
+ operation.signal.throwIfAborted();
15
+ current = operation;
16
+ try {
17
+ return await work();
18
+ }
19
+ finally {
20
+ current = undefined;
21
+ }
22
+ });
23
+ queue = result.catch(() => undefined);
24
+ return result;
25
+ }
26
+ function permissionKey() {
27
+ return 'network';
28
+ }
29
+ const ensurePermission = client.authorize;
30
+ function httpFetch(address, options = {}) {
31
+ const operation = current;
32
+ let cancelled = false;
33
+ const promise = (async () => {
34
+ if (!operation)
35
+ throw new Error('请求缺少操作上下文');
36
+ operation.signal.throwIfAborted();
37
+ const url = new URL(address);
38
+ const key = permissionKey();
39
+ await ensurePermission(key, url.origin, operation);
40
+ if (cancelled)
41
+ throw new Error('请求已取消');
42
+ const headers = { 'User-Agent': 'Mozilla/5.0' };
43
+ for (const [name, value] of Object.entries(options.headers ?? {})) {
44
+ if (value != null &&
45
+ !/^(host|connection|content-length|transfer-encoding|accept-encoding|proxy-.*|upgrade)$/i.test(name))
46
+ headers[name] = String(value);
47
+ }
48
+ let body;
49
+ if (options.form) {
50
+ headers['Content-Type'] = 'application/x-www-form-urlencoded';
51
+ body = new URLSearchParams(Object.entries(options.form).map(([k, v]) => [k, String(v)])).toString();
52
+ }
53
+ else if (options.body != null) {
54
+ if (typeof options.body === 'string')
55
+ body = options.body;
56
+ else {
57
+ body = JSON.stringify(options.body);
58
+ headers['Content-Type'] = 'application/json';
59
+ }
60
+ }
61
+ let response = await host.http.request({
62
+ permissionKey: key,
63
+ url: url.href,
64
+ method: (options.method ?? 'GET').toUpperCase(),
65
+ headers,
66
+ body,
67
+ timeoutMs: Number(options.timeout) || undefined,
68
+ operation,
69
+ });
70
+ const firstLocation = response.headers.location;
71
+ // Follow public redirects through Host permissions; never forward credentials across origins.
72
+ for (let count = 0; response.status >= 300 && response.status < 400 && response.headers.location; count++) {
73
+ if (count >= 4)
74
+ throw new Error('平台重定向次数过多');
75
+ const next = new URL(response.headers.location, url);
76
+ if (!['http:', 'https:'].includes(next.protocol))
77
+ throw new Error('平台重定向协议不受支持');
78
+ await ensurePermission(permissionKey(), next.origin, operation);
79
+ response = await host.http.request({
80
+ permissionKey: permissionKey(),
81
+ url: next.href,
82
+ method: 'GET',
83
+ operation,
84
+ });
85
+ url.href = next.href;
86
+ }
87
+ operation.signal.throwIfAborted();
88
+ if (cancelled)
89
+ throw new Error('请求已取消');
90
+ if (response.status >= 400)
91
+ throw new Error(url.hostname + ' 返回 HTTP ' + response.status);
92
+ let parsed = response.body;
93
+ if (typeof parsed === 'string') {
94
+ const content = parsed.trim().replace(/^[\w.$]+\s*\((\{[\s\S]*\})\)\s*;?$/, '$1');
95
+ try {
96
+ parsed = JSON5.parse(content);
97
+ }
98
+ catch {
99
+ /* Lyrics / HTML responses stay text. */
100
+ }
101
+ }
102
+ return {
103
+ body: parsed,
104
+ statusCode: response.status,
105
+ headers: { ...response.headers, ...(firstLocation ? { location: url.href } : {}) },
106
+ raw: response.body,
107
+ url: url.href,
108
+ };
109
+ })();
110
+ return {
111
+ promise,
112
+ cancelHttp() {
113
+ cancelled = true;
114
+ },
115
+ };
116
+ }
117
+ return { httpFetch, withOperation, ensurePermission, permissionKey };
118
+ }
@@ -0,0 +1,59 @@
1
+ import type { ContentEntity, OperationContext, Page } from './index.js';
2
+ export type PlaylistLocation = 'local' | 'cloud';
3
+ export interface PlaylistReference {
4
+ /** Host ID; never a path or backend database credential. */
5
+ id: string;
6
+ location: PlaylistLocation;
7
+ }
8
+ export interface LibraryPlaylist {
9
+ ref: PlaylistReference;
10
+ name: string;
11
+ description?: string;
12
+ trackCount?: number;
13
+ writable: boolean;
14
+ }
15
+ export interface PlaylistImportRequest {
16
+ /** Omit to let the Host show its existing playlist picker/create dialog. */
17
+ target?: PlaylistReference;
18
+ suggestedName?: string;
19
+ items: ContentEntity[];
20
+ /** Reuse this key when retrying the same batch, so the Host can avoid duplicates. */
21
+ requestId: string;
22
+ permissionKey: string;
23
+ operation: OperationContext;
24
+ }
25
+ export interface PlaylistImportResult {
26
+ cancelled: boolean;
27
+ target?: PlaylistReference;
28
+ added: number;
29
+ skipped: number;
30
+ }
31
+ export interface PlaylistImporterImplementation {
32
+ /** Resolve a pasted link/ID and return one page. Host owns paging and the import UI. */
33
+ getTracks(request: {
34
+ value: string;
35
+ cursor?: string;
36
+ limit: number;
37
+ }, operation: OperationContext): Promise<Page<ContentEntity> & {
38
+ name?: string;
39
+ }>;
40
+ }
41
+ /** Existing application library services. No plugin-owned playlist database. */
42
+ export interface LibraryAPI {
43
+ playlists: {
44
+ list(request: {
45
+ location?: PlaylistLocation;
46
+ cursor?: string;
47
+ permissionKey: string;
48
+ operation: OperationContext;
49
+ }): Promise<Page<LibraryPlaylist>>;
50
+ getTracks(request: {
51
+ target: PlaylistReference;
52
+ cursor?: string;
53
+ permissionKey: string;
54
+ operation: OperationContext;
55
+ }): Promise<Page<ContentEntity>>;
56
+ /** Host handles destination selection, auth, deduplication, persistence and cloud sync. */
57
+ import(request: PlaylistImportRequest): Promise<PlaylistImportResult>;
58
+ };
59
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -1,4 +1,5 @@
1
1
  import type { HostIconName, PermissionName } from './catalog.js';
2
+ import type { MenuContribution } from './services.js';
2
3
  export type JsonValue = null | boolean | number | string | JsonValue[] | {
3
4
  [key: string]: JsonValue;
4
5
  };
@@ -34,6 +35,37 @@ export interface SurfaceDeclaration {
34
35
  kind: 'schema' | 'web';
35
36
  entry: string;
36
37
  }
38
+ export type HomeSectionKind = 'playlists' | 'charts' | 'custom';
39
+ 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';
40
+ export interface HomeSectionContribution {
41
+ id: string;
42
+ title: string;
43
+ kind: HomeSectionKind;
44
+ icon?: IconRef;
45
+ /** Required for custom sections; built-in playlist/chart sections keep the existing Host UI. */
46
+ view?: string;
47
+ providerIds?: string[];
48
+ order?: number;
49
+ }
50
+ export interface UIExtensionContribution {
51
+ id: string;
52
+ slot: UISlotName;
53
+ mode: 'append' | 'prepend' | 'wrap' | 'replace';
54
+ /** Sandboxed visible Surface. Plugin JavaScript never runs in the application renderer. */
55
+ view: string;
56
+ order?: number;
57
+ when?: {
58
+ loggedIn?: boolean;
59
+ route?: string;
60
+ };
61
+ }
62
+ export interface StyleContribution {
63
+ id: string;
64
+ resource: string;
65
+ scope: 'surface' | 'slot' | 'application';
66
+ slots?: UISlotName[];
67
+ order?: number;
68
+ }
37
69
  export interface PluginManifest {
38
70
  manifestVersion: 2;
39
71
  id: string;
@@ -58,6 +90,20 @@ export interface PluginManifest {
58
90
  };
59
91
  contributes?: {
60
92
  providers?: ProviderDeclaration[];
93
+ /** Home tabs exist only while at least one enabled plugin contributes them. */
94
+ homeSections?: HomeSectionContribution[];
95
+ /** Controlled UI composition. The Host owns the target DOM and lifecycle. */
96
+ uiExtensions?: UIExtensionContribution[];
97
+ /** Surface/slot styles are scoped. Application styles require ui.styles.global. */
98
+ styles?: StyleContribution[];
99
+ menus?: MenuContribution[];
100
+ /** Entries for the application's existing playlist import menu/dialog. */
101
+ playlistImporters?: {
102
+ id: string;
103
+ title: string;
104
+ description?: string;
105
+ placeholder?: string;
106
+ }[];
61
107
  commands?: {
62
108
  id: string;
63
109
  title: string;
@@ -0,0 +1,19 @@
1
+ import type { PluginContext, HostLodash } from './index.js';
2
+ export interface BuiltinModules {
3
+ ceru: PluginContext;
4
+ '@ceru/http': PluginContext['http'];
5
+ '@ceru/ui': PluginContext['ui'];
6
+ '@ceru/socket': PluginContext['sockets'];
7
+ '@ceru/library': PluginContext['library'];
8
+ '@ceru/account': PluginContext['account'];
9
+ '@ceru/player': PluginContext['player'];
10
+ '@ceru/tools': PluginContext['utils'];
11
+ lodash: HostLodash;
12
+ '@ceru/crypto': typeof import('./compat/crypto.js');
13
+ '@ceru/compression': typeof import('./compat/zlib.js');
14
+ '@ceru/encoding': typeof import('./compat/encoding.js');
15
+ '@ceru/legacy-http': typeof import('./legacy-http.js');
16
+ }
17
+ export interface PluginModules {
18
+ require<K extends keyof BuiltinModules>(name: K): BuiltinModules[K];
19
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,65 @@
1
+ import type { ContentEntity, ResourceRef, ResolveResult } from './index.js';
2
+ /** Milliseconds throughout. Platform-specific formats/decryption stay inside the plugin. */
3
+ export interface LyricWord {
4
+ startTimeMs: number;
5
+ endTimeMs: number;
6
+ text: string;
7
+ }
8
+ export interface LyricLine {
9
+ startTimeMs: number;
10
+ endTimeMs?: number;
11
+ text: string;
12
+ translation?: string;
13
+ romanization?: string;
14
+ words?: LyricWord[];
15
+ }
16
+ export interface LyricsDocument {
17
+ version: 1;
18
+ track: ResourceRef;
19
+ offsetMs: number;
20
+ lines: LyricLine[];
21
+ /** Untimed lyrics only. Empty lines + no plainText means no available lyrics. */
22
+ plainText?: string;
23
+ }
24
+ export interface TrackMetadata {
25
+ artists: string[];
26
+ album?: {
27
+ id?: string;
28
+ title: string;
29
+ };
30
+ qualities?: string[];
31
+ artworkUrl?: string;
32
+ durationMs?: number;
33
+ }
34
+ export interface MusicTrack extends ContentEntity {
35
+ ref: ResourceRef & {
36
+ kind: 'track';
37
+ };
38
+ metadata: TrackMetadata;
39
+ }
40
+ export interface PlaylistMetadata {
41
+ trackCount?: number;
42
+ description?: string;
43
+ author?: string;
44
+ artworkUrl?: string;
45
+ }
46
+ export interface ChartMetadata {
47
+ updateFrequency?: string;
48
+ artworkUrl?: string;
49
+ }
50
+ export interface MusicPlaylist extends ContentEntity {
51
+ ref: ResourceRef & {
52
+ kind: 'playlist';
53
+ };
54
+ playlist?: PlaylistMetadata;
55
+ }
56
+ export interface MusicChart extends ContentEntity {
57
+ ref: ResourceRef & {
58
+ kind: 'chart';
59
+ };
60
+ chart?: ChartMetadata;
61
+ }
62
+ export declare function assertResourceRef(value: unknown): asserts value is ResourceRef;
63
+ export declare function assertContentPage(value: unknown): void;
64
+ export declare function assertResolveResult(value: unknown): asserts value is ResolveResult;
65
+ export declare function assertLyricsDocument(value: unknown): asserts value is LyricsDocument;
package/dist/music.js ADDED
@@ -0,0 +1,109 @@
1
+ const record = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
2
+ const text = (value, max = 4096) => typeof value === 'string' && value.length <= max;
3
+ const milliseconds = (value) => Number.isFinite(value) && Number(value) >= 0;
4
+ export function assertResourceRef(value) {
5
+ if (!record(value) ||
6
+ !['pluginId', 'providerId', 'kind', 'id'].every((key) => text(value[key], 2048) && value[key].length > 0))
7
+ throw new Error('Invalid resource reference');
8
+ if (value.data !== undefined) {
9
+ if (!record(value.data))
10
+ throw new Error('Invalid resource private data');
11
+ let encoded;
12
+ try {
13
+ encoded = JSON.stringify(value.data);
14
+ }
15
+ catch {
16
+ throw new Error('Resource private data must be JSON');
17
+ }
18
+ if (new TextEncoder().encode(encoded).byteLength > 64 * 1024)
19
+ throw new Error('Resource private data exceeds 64 KiB');
20
+ }
21
+ }
22
+ export function assertContentPage(value) {
23
+ if (!record(value) || !Array.isArray(value.items) || value.items.length > 10000)
24
+ throw new Error('Invalid content page');
25
+ if (value.nextCursor != null && (!text(value.nextCursor, 2048) || !value.nextCursor.length))
26
+ throw new Error('Invalid pagination cursor');
27
+ for (const item of value.items) {
28
+ if (!record(item) ||
29
+ !text(item.title) ||
30
+ !Array.isArray(item.capabilities) ||
31
+ !item.capabilities.every((entry) => text(entry, 128)))
32
+ throw new Error('Invalid content item');
33
+ assertResourceRef(item.ref);
34
+ if (item.ref.kind === 'track') {
35
+ if (!record(item.metadata) ||
36
+ !Array.isArray(item.metadata.artists) ||
37
+ !item.metadata.artists.every((artist) => text(artist)))
38
+ throw new Error('Track metadata must contain artists');
39
+ if (item.metadata.durationMs !== undefined && !milliseconds(item.metadata.durationMs))
40
+ throw new Error('Invalid track duration');
41
+ }
42
+ if (item.ref.kind === 'playlist' && item.playlist !== undefined) {
43
+ if (!record(item.playlist))
44
+ throw new Error('Invalid playlist metadata');
45
+ if (item.playlist.trackCount !== undefined &&
46
+ (!Number.isInteger(item.playlist.trackCount) || item.playlist.trackCount < 0))
47
+ throw new Error('Invalid playlist track count');
48
+ }
49
+ if (item.ref.kind === 'chart' && item.chart !== undefined && !record(item.chart))
50
+ throw new Error('Invalid chart metadata');
51
+ }
52
+ }
53
+ export function assertResolveResult(value) {
54
+ if (!record(value) || typeof value.ok !== 'boolean')
55
+ throw new Error('Invalid resolve result');
56
+ if (value.ok) {
57
+ if (!text(value.url, 8192))
58
+ throw new Error('Invalid playback URL');
59
+ const url = new URL(value.url);
60
+ if (!['http:', 'https:'].includes(url.protocol))
61
+ throw new Error('Invalid playback protocol');
62
+ if (value.expiresAt !== undefined && !milliseconds(value.expiresAt))
63
+ throw new Error('Invalid playback expiry');
64
+ return;
65
+ }
66
+ if (!record(value.error) || !text(value.error.code, 128) || !text(value.error.message, 65536))
67
+ throw new Error('Invalid music fault');
68
+ }
69
+ export function assertLyricsDocument(value) {
70
+ if (!record(value) ||
71
+ value.version !== 1 ||
72
+ !Number.isFinite(value.offsetMs) ||
73
+ !Array.isArray(value.lines) ||
74
+ value.lines.length > 20000)
75
+ throw new Error('Invalid lyrics document');
76
+ assertResourceRef(value.track);
77
+ let previous = -1;
78
+ for (const line of value.lines) {
79
+ if (!record(line) ||
80
+ !milliseconds(line.startTimeMs) ||
81
+ line.startTimeMs < previous ||
82
+ !text(line.text, 65536))
83
+ throw new Error('Invalid lyric line');
84
+ previous = line.startTimeMs;
85
+ if (line.endTimeMs !== undefined &&
86
+ (!milliseconds(line.endTimeMs) || line.endTimeMs < line.startTimeMs))
87
+ throw new Error('Invalid lyric line end');
88
+ for (const field of ['translation', 'romanization'])
89
+ if (line[field] !== undefined && !text(line[field], 65536))
90
+ throw new Error('Invalid lyric translation');
91
+ if (line.words !== undefined) {
92
+ if (!Array.isArray(line.words) || line.words.length > 10000)
93
+ throw new Error('Invalid lyric words');
94
+ let lastWord = line.startTimeMs;
95
+ for (const word of line.words) {
96
+ if (!record(word) ||
97
+ !milliseconds(word.startTimeMs) ||
98
+ !milliseconds(word.endTimeMs) ||
99
+ word.endTimeMs < word.startTimeMs ||
100
+ word.startTimeMs < lastWord ||
101
+ !text(word.text, 65536))
102
+ throw new Error('Invalid lyric word');
103
+ lastWord = word.startTimeMs;
104
+ }
105
+ }
106
+ }
107
+ if (value.plainText !== undefined && !text(value.plainText, 1048576))
108
+ throw new Error('Invalid plain lyrics');
109
+ }