@vestra-player/sdk 1.7.8 → 1.7.10

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.
Files changed (43) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/api-requests.js +3 -0
  3. package/dist/capabilities.d.ts +9 -0
  4. package/dist/capabilities.js +1 -0
  5. package/dist/capability-rules.d.ts +3 -0
  6. package/dist/capability-rules.js +6 -1
  7. package/dist/commands.d.ts +15 -2
  8. package/dist/commands.js +7 -1
  9. package/dist/docs-tree.json.gz +0 -0
  10. package/dist/host-capabilities.js +53 -0
  11. package/dist/manifest.js +12 -1
  12. package/dist/player-runtime.d.ts +1 -0
  13. package/dist/player-runtime.js +1 -0
  14. package/dist/plugin/commands.d.ts +2 -1
  15. package/dist/plugin/commands.js +131 -4
  16. package/dist/plugin/connection.d.ts +7 -1
  17. package/dist/plugin/connection.js +16 -3
  18. package/dist/plugin/errors.d.ts +5 -1
  19. package/dist/plugin/errors.js +8 -2
  20. package/dist/plugin/index.js +4 -0
  21. package/dist/plugin/player.js +1 -1
  22. package/dist/plugin/scope.d.ts +1 -0
  23. package/dist/plugin/scope.js +2 -1
  24. package/dist/plugin/subtitles.js +2 -2
  25. package/dist/plugin/testing/commands.d.ts +7 -0
  26. package/dist/plugin/testing/commands.js +211 -0
  27. package/dist/plugin/testing/index.d.ts +70 -0
  28. package/dist/plugin/testing/index.js +66 -1
  29. package/dist/plugin/testing/internals.d.ts +14 -0
  30. package/dist/plugin/testing/internals.js +14 -1
  31. package/dist/plugin/types/base.d.ts +8 -5
  32. package/dist/plugin/types/commands.d.ts +412 -1
  33. package/dist/request-queue.d.ts +66 -0
  34. package/dist/request-queue.js +209 -0
  35. package/dist/source.d.ts +2 -1
  36. package/dist/source.js +3 -5
  37. package/dist/subtitles.d.ts +4 -2
  38. package/dist/subtitles.js +4 -10
  39. package/dist/wire.d.ts +25 -4
  40. package/dist/wire.js +6 -0
  41. package/llms.txt +2 -2
  42. package/package.json +1 -1
  43. package/slint/vestra/icons.slint +4 -0
@@ -6,6 +6,7 @@ import { BAR_BUTTON_ICONS, BAR_BUTTON_LIMITS, MENU_IDS } from "../commands.js";
6
6
  import { ImageHandle } from "./view/image.js";
7
7
  import { isTextValue, textProblem } from "../i18n.js";
8
8
  import { conditionJson, isCondition } from "./when.js";
9
+ import { shownText } from "./osd.js";
9
10
  const value = (item) => typeof item === "function" ? item() : item;
10
11
  /**
11
12
  * A state field given as a function: the command is evaluated in the update
@@ -73,6 +74,10 @@ function declare(options) {
73
74
  // Only when set: players before 0.7.6 refuse the fields.
74
75
  if (category !== undefined)
75
76
  declaration.category = category;
77
+ if (options.destructive === true)
78
+ declaration.destructive = true;
79
+ else if (options.destructive !== undefined && options.destructive !== false)
80
+ throw failure("invalid", `command ${options.id}: destructive is a boolean`);
76
81
  if (options.home !== undefined) {
77
82
  if (typeof options.home !== "string")
78
83
  throw failure("invalid", `command ${options.id}: home is a command id`);
@@ -92,15 +97,19 @@ function button(id, value, inMenu) {
92
97
  order < 0 ||
93
98
  order > BAR_BUTTON_LIMITS.maxOrder)
94
99
  throw fail(`button order must be an integer 0–${BAR_BUTTON_LIMITS.maxOrder}`);
100
+ return { icon: iconJson(icon, fail, "button"), order };
101
+ }
102
+ /** An icon name of the player's set or an image, checked, in wire form. */
103
+ function iconJson(icon, fail, what) {
95
104
  if (icon instanceof ImageHandle) {
96
105
  if (icon.released)
97
- throw fail(`button image ${icon.path} was released with the scope that created it`);
98
- return { icon: icon.toJSON(), order };
106
+ throw fail(`${what} image ${icon.path} was released with the scope that created it`);
107
+ return icon.toJSON();
99
108
  }
100
109
  if (typeof icon !== "string" ||
101
110
  !BAR_BUTTON_ICONS.includes(icon))
102
- throw fail(`unknown button icon ${JSON.stringify(icon)}: a name of @vestra/icons.slint (BAR_BUTTON_ICONS) or an image from plugin.ui.image`);
103
- return { icon, order };
111
+ throw fail(`unknown ${what} icon ${JSON.stringify(icon)}: a name of @vestra/icons.slint (BAR_BUTTON_ICONS) or an image from plugin.ui.image`);
112
+ return icon;
104
113
  }
105
114
  class CommandHandle {
106
115
  id;
@@ -349,4 +358,122 @@ export const commands = (scope) => ({
349
358
  scope.runtime.depends(KEYS, id);
350
359
  return service.get(id);
351
360
  },
361
+ list: async () => {
362
+ needs(scope, "commands.run");
363
+ return scope.runtime.host.commands.list();
364
+ },
365
+ async run(id, options) {
366
+ needs(scope, "commands.run");
367
+ if (typeof id !== "string" || id === "")
368
+ throw failure("invalid", "run takes a command id: <plugin>/<id>");
369
+ const { ticket, step, of } = (options ?? {});
370
+ if (typeof ticket !== "string" || ticket === "")
371
+ throw failure("ticket", "run needs the ticket of a user action");
372
+ // As the player: both or neither, 1 <= step <= of <= 99.
373
+ const whole = (value) => Number.isInteger(value) &&
374
+ value >= 1 &&
375
+ value <= 99;
376
+ if ((step === undefined) !== (of === undefined) ||
377
+ (step !== undefined && (!whole(step) || !whole(of) || step > of)))
378
+ throw failure("invalid", "step and of go together, 1 <= step <= of <= 99");
379
+ return scope.runtime.host.commands.run({
380
+ id,
381
+ ticket,
382
+ ...(step === undefined ? {} : { step }),
383
+ ...(of === undefined ? {} : { of }),
384
+ });
385
+ },
386
+ });
387
+ /** Refuse at once without `capability`, as the player does. */
388
+ function needs(scope, capability) {
389
+ if (!scope.runtime.can(capability))
390
+ throw failure("capability", `${capability} must be declared in manifest`);
391
+ }
392
+ // ---------------------------------------------------------------- palette lead
393
+ /** `PaletteLeadOptions` checked and in wire form; the player checks lengths. */
394
+ function leadJson(options) {
395
+ if (options === null || typeof options !== "object")
396
+ throw failure("invalid", "lead takes { title, icon, ... }");
397
+ const text = (value, what) => shownText(value, undefined, what);
398
+ const out = {
399
+ title: text(options.title, "title"),
400
+ icon: iconJson(options.icon, (problem) => failure("invalid", problem), "lead"),
401
+ };
402
+ for (const key of ["placeholder", "empty", "note"])
403
+ if (options[key] !== undefined)
404
+ out[key] = text(options[key], key);
405
+ const status = options.status;
406
+ if (status === null)
407
+ out.status = null;
408
+ else if (status !== undefined) {
409
+ if (typeof status !== "object")
410
+ throw failure("invalid", "status is { text, note? } or null");
411
+ out.status = {
412
+ text: text(status.text, "status.text"),
413
+ ...(status.note === undefined
414
+ ? {}
415
+ : { note: text(status.note, "status.note") }),
416
+ };
417
+ }
418
+ return out;
419
+ }
420
+ class LeadHandle {
421
+ ready;
422
+ #scope;
423
+ #pump;
424
+ #listeners = new Set();
425
+ #event;
426
+ #disposed = false;
427
+ constructor(scope, options) {
428
+ needs(scope, "palette.lead");
429
+ const first = leadJson(options);
430
+ this.#scope = scope;
431
+ const host = scope.runtime.host.palette;
432
+ this.#pump = new Latest((value) => host.set(value));
433
+ // Not an activation step: a refusal (a development load is not built
434
+ // in) reaches `ready` and onError, and the rest of the plugin runs.
435
+ this.ready = quiet(this.#pump.push(first).then(() => { }));
436
+ this.ready.catch((error) => scope.report(error));
437
+ // Sent to the lead's owner unasked, like `commands.execute`.
438
+ this.#event = scope.runtime.raw("palette.lead", (data) => {
439
+ const raw = (data ?? {});
440
+ const run = {
441
+ query: String(raw.query ?? ""),
442
+ keep: raw.keep === true,
443
+ ticket: String(raw.ticket ?? ""),
444
+ status: raw.status === true,
445
+ };
446
+ for (const listener of [...this.#listeners])
447
+ scope.run(listener, run);
448
+ });
449
+ scope.add(this);
450
+ }
451
+ async update(options) {
452
+ if (this.#disposed)
453
+ return;
454
+ await this.#pump.push(leadJson(options));
455
+ }
456
+ onRun(listener) {
457
+ this.#listeners.add(listener);
458
+ return { dispose: async () => void this.#listeners.delete(listener) };
459
+ }
460
+ async done(ticket) {
461
+ if (typeof ticket !== "string" || ticket === "")
462
+ throw failure("invalid", "done takes a ticket");
463
+ await this.#scope.runtime.host.palette.done(ticket);
464
+ }
465
+ async dispose() {
466
+ if (this.#disposed)
467
+ return;
468
+ this.#disposed = true;
469
+ this.#scope.forget(this);
470
+ this.#listeners.clear();
471
+ await this.#event.dispose();
472
+ this.#pump.stop();
473
+ if (await this.ready.then(() => true, () => false))
474
+ await this.#scope.runtime.host.palette.clear().catch(() => { });
475
+ }
476
+ }
477
+ export const palette = (scope) => ({
478
+ lead: (options) => new LeadHandle(scope, options),
352
479
  });
@@ -1,3 +1,4 @@
1
+ import { RequestQueue } from "../request-queue.ts";
1
2
  import type { Json, LocalServices, Transport, Wire } from "../wire.ts";
2
3
  import type { App, Disposable, Locale, StopReason, SystemInfo } from "./types.ts";
3
4
  /**
@@ -57,6 +58,11 @@ export declare class Connection {
57
58
  readonly local: LocalServices | undefined;
58
59
  /** Registrations that activation must wait for before reporting ready. */
59
60
  readonly startup: Set<Promise<unknown>>;
61
+ /**
62
+ * Every request of this plugin goes through it: at most
63
+ * `REQUEST_LIMITS` in flight, the rest wait in order (`request-queue.ts`).
64
+ */
65
+ readonly requests: RequestQueue;
60
66
  readonly views: Map<string, (callback: string, args: Json[]) => void>;
61
67
  readonly commands: Map<string, () => void>;
62
68
  /**
@@ -150,7 +156,7 @@ export declare class Connection {
150
156
  * One request by its method name, as given (`plugin.wire.request`): nothing
151
157
  * added, nothing checked here, the player checks the capability. Every other
152
158
  * part of the SDK uses the typed clients (`host`); `scripts/check-layers.mjs`
153
- * keeps it so.
159
+ * keeps it so. It waits in the request queue like every other.
154
160
  */
155
161
  request<T>(method: string, params?: Json): Promise<T>;
156
162
  /** Raw transport events the host pushes without a subscription. */
@@ -7,6 +7,7 @@
7
7
  * nothing of update passes (`passes.ts`); `Runtime` (`runtime.ts`) adds them.
8
8
  */
9
9
  import { createWire, HostError } from "../wire.js";
10
+ import { RequestQueue } from "../request-queue.js";
10
11
  import { LOCALES } from "../i18n.js";
11
12
  import { failure } from "./errors.js";
12
13
  import { basename, isAbsolute, relative } from "node:path";
@@ -81,6 +82,11 @@ export class Connection {
81
82
  /** Declarations skipped during activation: reported once it completes. */
82
83
  #refusals = [];
83
84
  #transport;
85
+ /**
86
+ * Every request of this plugin goes through it: at most
87
+ * `REQUEST_LIMITS` in flight, the rest wait in order (`request-queue.ts`).
88
+ */
89
+ requests;
84
90
  #events = new Map();
85
91
  /** The missing `events` warning was given (once per plugin). */
86
92
  #warnedEvents = false;
@@ -127,7 +133,14 @@ export class Connection {
127
133
  this.#strict = options.strictDeclarations ?? false;
128
134
  this.dataDirectory = dataDirectory;
129
135
  this.local = transport.local;
130
- this.host = createWire(transport);
136
+ const requests = new RequestQueue(transport);
137
+ this.requests = requests;
138
+ this.host = createWire({
139
+ request: (method, params, options) => requests.request(method, params, options),
140
+ on: (event, listener) => transport.on(event, listener),
141
+ local: transport.local,
142
+ locale: transport.locale,
143
+ });
131
144
  const host = this.host;
132
145
  this.app = appInfo(app, () => host.app.system());
133
146
  const features = app
@@ -419,10 +432,10 @@ export class Connection {
419
432
  * One request by its method name, as given (`plugin.wire.request`): nothing
420
433
  * added, nothing checked here, the player checks the capability. Every other
421
434
  * part of the SDK uses the typed clients (`host`); `scripts/check-layers.mjs`
422
- * keeps it so.
435
+ * keeps it so. It waits in the request queue like every other.
423
436
  */
424
437
  request(method, params) {
425
- return this.#transport.request(method, params);
438
+ return this.requests.request(method, params);
426
439
  }
427
440
  /** Raw transport events the host pushes without a subscription. */
428
441
  raw(event, listener) {
@@ -2,7 +2,11 @@ import type { PluginError } from "./types.ts";
2
2
  export declare const sleep: (ms: number) => Promise<void>;
3
3
  export declare function toError(error: unknown): PluginError;
4
4
  export declare const failure: (code: string, message?: string) => PluginError;
5
- /** Host replies are definite; anything else (lost reply, client timeout) is not. */
5
+ /**
6
+ * Host replies are definite; anything else (lost reply, client timeout) is
7
+ * not. An abort is definite too: the SDK's request queue rejects a waiting
8
+ * request with it, unsent (`request-queue.ts`).
9
+ */
6
10
  export declare const uncertain: (error: unknown) => boolean;
7
11
  /** Mark a promise as observed so an unused `ready` never crashes the runner. */
8
12
  export declare function quiet<T>(promise: Promise<T>): Promise<T>;
@@ -20,8 +20,14 @@ export function toError(error) {
20
20
  return new HostError("error", String(error));
21
21
  }
22
22
  export const failure = (code, message = code) => new HostError(code, message);
23
- /** Host replies are definite; anything else (lost reply, client timeout) is not. */
24
- export const uncertain = (error) => !(error instanceof HostError) || error.code === "timeout";
23
+ /**
24
+ * Host replies are definite; anything else (lost reply, client timeout) is
25
+ * not. An abort is definite too: the SDK's request queue rejects a waiting
26
+ * request with it, unsent (`request-queue.ts`).
27
+ */
28
+ export const uncertain = (error) => error instanceof HostError
29
+ ? error.code === "timeout"
30
+ : !(error instanceof Error && error.name === "AbortError");
25
31
  /** Mark a promise as observed so an unused `ready` never crashes the runner. */
26
32
  export function quiet(promise) {
27
33
  promise.catch(() => { });
@@ -43,6 +43,10 @@ options) {
43
43
  activated: () => runtime.activated(),
44
44
  dispose: async (info) => {
45
45
  runtime.stopping ??= { reason: stopReason(info?.reason) };
46
+ // Before the cleanup runs: what still waits to be sent rejects as the
47
+ // requests in flight do when the runner stops (`disabled`); the
48
+ // cleanup's own requests go to the transport as before.
49
+ runtime.requests.close();
46
50
  await root.dispose();
47
51
  runtime.stop();
48
52
  },
@@ -272,7 +272,7 @@ export class PlayerService {
272
272
  try {
273
273
  result = await (options.send
274
274
  ? options.send(id)
275
- : this.runtime.host.source.submit(intent, id));
275
+ : this.runtime.host.source.submit(intent, id, options.signal));
276
276
  }
277
277
  catch (error) {
278
278
  if (!uncertain(error))
@@ -36,6 +36,7 @@ export declare class ScopeImpl implements Plugin {
36
36
  readonly resolvers: import("./types.ts").Resolvers;
37
37
  readonly packages: import("./types.ts").Packages;
38
38
  readonly osd: import("./types.ts").Osd;
39
+ readonly palette: import("./types.ts").Palette;
39
40
  readonly host: import("./types.ts").Host;
40
41
  readonly clipboard: import("./types.ts").Clipboard;
41
42
  readonly power: import("./types.ts").Power;
@@ -1,6 +1,6 @@
1
1
  /** Scopes own handles. Disposal runs newest first and never throws. */
2
2
  import { failure, toError } from "./errors.js";
3
- import { commands, keysOf } from "./commands.js";
3
+ import { commands, keysOf, palette } from "./commands.js";
4
4
  import { WHEN } from "./when.js";
5
5
  import { dialogs } from "./services/dialogs.js";
6
6
  import { ui } from "./view/image.js";
@@ -88,6 +88,7 @@ export class ScopeImpl {
88
88
  resolvers = resolvers(this);
89
89
  packages = packages(this);
90
90
  osd = osd(this);
91
+ palette = palette(this);
91
92
  host = host(this);
92
93
  clipboard = clipboard(this);
93
94
  power = power(this);
@@ -324,11 +324,11 @@ export function subtitles(scope) {
324
324
  throw abortError();
325
325
  };
326
326
  check();
327
- await host().begin(uploadId, current.sourceId, srt.length);
327
+ await host().begin(uploadId, current.sourceId, srt.length, options?.signal);
328
328
  for (let offset = 0; offset < srt.length; offset += CHUNK) {
329
329
  check();
330
330
  const chunk = Buffer.from(srt.subarray(offset, offset + CHUNK));
331
- await host().append(uploadId, offset, chunk.toString("base64"));
331
+ await host().append(uploadId, offset, chunk.toString("base64"), options?.signal);
332
332
  }
333
333
  const sha256 = createHash("sha256").update(srt).digest("hex");
334
334
  check();
@@ -62,3 +62,10 @@ export declare function press(host: TestHost, inner: Internals, binding: string,
62
62
  export declare function barButtons(host: TestHost, _inner: Internals): readonly FakeBarButton[];
63
63
  /** The default handlers of this area's wire methods, by method name. */
64
64
  export declare function commandsHandlers(host: TestHost, inner: Internals): Record<string, Handler>;
65
+ /** The default handlers of `commands.run` and `palette.lead`. */
66
+ export declare function builtinHandlers(host: TestHost, inner: Internals): Record<string, Handler>;
67
+ /** Implements `TestHost.runPaletteLead`. */
68
+ export declare function runPaletteLead(host: TestHost, inner: Internals, query: string, options: {
69
+ keep?: boolean;
70
+ status?: boolean;
71
+ }): Promise<string>;
@@ -409,3 +409,214 @@ export function commandsHandlers(host, inner) {
409
409
  },
410
410
  };
411
411
  }
412
+ /// ---------------------------------------------------------------- built-in only: commands.run, palette.lead
413
+ /** The player's refusal of a built-in-only capability to any other plugin. */
414
+ function builtinOnly(host) {
415
+ if (!host.builtin)
416
+ throw new HostError("capability", "this capability is for built-in plugins only");
417
+ }
418
+ /** The palette's rows: the player's core commands and the plugin's own. */
419
+ function rows(host) {
420
+ return [
421
+ ...[...host.coreCommands].map(([id, command]) => ({
422
+ global: id,
423
+ local: id,
424
+ owner: "host",
425
+ command,
426
+ })),
427
+ ...[...host.commands].map(([id, command]) => ({
428
+ global: `${host.manifestId}/${id}`,
429
+ local: id,
430
+ owner: "plugin",
431
+ command,
432
+ })),
433
+ ].filter(({ command }) =>
434
+ // As the palette: no panel-only command, no disabled one without a reason.
435
+ command.declaration.focus !== "panel" &&
436
+ (command.state.enabled || !!command.display.reason));
437
+ }
438
+ /** A row as `commands.list` writes it (capabilities/commands_run.rs `listed`). */
439
+ function listed(host, inner, row) {
440
+ const { declaration, display, state } = row.command;
441
+ const builtin = row.owner === "host" || host.builtin;
442
+ const plugin = row.owner === "host" ? "Vestra Player" : host.manifestId;
443
+ const keys = declaration.path ?? [];
444
+ const parent = display.path.slice(0, -1);
445
+ const declared = declaration.category ?? null;
446
+ const category = declared !== null
447
+ ? (display.category ?? menuTextKey(declared))
448
+ : parent.length
449
+ ? parent.join(" ▸ ")
450
+ : plugin;
451
+ const categoryKey = declared !== null
452
+ ? menuTextKey(declared)
453
+ : parent.length
454
+ ? keys.slice(0, -1).map(menuTextKey).join(" ▸ ")
455
+ : row.owner === "host"
456
+ ? plugin
457
+ : host.manifestId;
458
+ const home = declaration.home ? host.commands.get(declaration.home) : null;
459
+ const place = home
460
+ ? home.display.title.replace(/…$/, "")
461
+ : !display.path.length
462
+ ? ""
463
+ : declared === null || !parent.length
464
+ ? "Menu"
465
+ : `${parent.join(" ▸ ")} ▸`;
466
+ const root = keys[0] === undefined ? undefined : menuTextKey(keys[0]);
467
+ return {
468
+ id: row.global,
469
+ label: `${category}: ${display.title}`,
470
+ labelSource: `${categoryKey}: ${menuTextKey(declaration.title)}`,
471
+ title: display.title,
472
+ category,
473
+ path: display.path,
474
+ place,
475
+ keys: commandKeys(host, inner).keys[row.local] ?? [],
476
+ plugin,
477
+ builtin,
478
+ enabled: state.enabled,
479
+ checkable: state.checked !== null,
480
+ radio: declaration.radio,
481
+ group: declaration.group,
482
+ busy: state.busy,
483
+ // Asks first: not built in, destructive, the player's Close and Quit,
484
+ // the Settings and Plugins menus.
485
+ dangerous: !builtin ||
486
+ declaration.destructive === true ||
487
+ row.global === "host/stop" ||
488
+ row.global === "host/quit" ||
489
+ root === "Settings" ||
490
+ root === "Plugins",
491
+ ...(state.checked === null ? {} : { checked: state.checked }),
492
+ ...(!state.enabled && display.reason ? { reason: display.reason } : {}),
493
+ };
494
+ }
495
+ /** `palette.lead.set` texts: at most this many characters each. */
496
+ const LEAD_TEXTS = {
497
+ title: 40,
498
+ placeholder: 60,
499
+ empty: 80,
500
+ note: 40,
501
+ "status.text": 80,
502
+ "status.note": 40,
503
+ };
504
+ /** The default handlers of `commands.run` and `palette.lead`. */
505
+ export function builtinHandlers(host, inner) {
506
+ return {
507
+ "commands.list": () => {
508
+ builtinOnly(host);
509
+ const commands = rows(host).map((row) => listed(host, inner, row));
510
+ // The revision changes with the table.
511
+ const text = JSON.stringify(commands);
512
+ if (text !== inner.listed.text)
513
+ inner.listed = { text, revision: inner.listed.revision + 1 };
514
+ return { revision: inner.listed.revision, commands };
515
+ },
516
+ "commands.run": async (p) => {
517
+ builtinOnly(host);
518
+ // The player's order: the ticket given, step and of, the command,
519
+ // then the ticket's count and rates, then the alert.
520
+ if (p.ticket === undefined || p.ticket === null)
521
+ throw new HostError("ticket", "commands.run needs the ticket of a palette.lead event");
522
+ const whole = (value) => Number.isInteger(value) && Number(value) >= 1 && Number(value) <= 99;
523
+ if ((p.step === undefined) !== (p.of === undefined) ||
524
+ (p.step !== undefined &&
525
+ (!whole(p.step) || !whole(p.of) || Number(p.step) > Number(p.of))))
526
+ throw new HostError("invalid", "step and of go together, step ≤ of");
527
+ const id = String(p.id);
528
+ const row = rows(host).find((each) => each.global === id);
529
+ if (!row)
530
+ throw new HostError("missing", `no command ${id}`);
531
+ if (id === "host/palette")
532
+ throw new HostError("invalid", "the command palette is not run this way");
533
+ const item = listed(host, inner, row);
534
+ if (!item.enabled)
535
+ throw new HostError("disabled", item.reason ?? `${item.label} is disabled`);
536
+ if (item.busy)
537
+ throw new HostError("busy", `${item.label} is busy`);
538
+ const now = Date.now();
539
+ const ticket = inner.tickets.get(String(p.ticket));
540
+ if (!ticket || now - ticket.last > 120_000) {
541
+ inner.tickets.delete(String(p.ticket));
542
+ throw new HostError("ticket", "no live ticket");
543
+ }
544
+ inner.runs = inner.runs.filter((at) => now - at < 60_000);
545
+ ticket.runs = ticket.runs.filter((at) => now - at < 1000);
546
+ if (ticket.count >= 30)
547
+ throw new HostError("limit", "a ticket runs at most 30 commands");
548
+ if (ticket.runs.length >= 4)
549
+ throw new HostError("limit", "at most 4 commands a second");
550
+ if (inner.runs.length >= 120)
551
+ throw new HostError("limit", "at most 120 commands a minute");
552
+ ticket.count++;
553
+ ticket.runs.push(now);
554
+ ticket.last = now;
555
+ inner.runs.push(now);
556
+ // The player's own alert, answered like the plugin's alerts.
557
+ if (item.dangerous) {
558
+ const answer = host.dialogAnswers.shift();
559
+ if (answer === undefined || answer === null || Array.isArray(answer))
560
+ throw new Error("test host: no confirm answer queued for commands.run");
561
+ if (!answer.confirmed)
562
+ return { ran: false, declined: true };
563
+ }
564
+ // The OSD line naming the caller and the command.
565
+ const step = p.step === undefined ? "" : ` · ${p.step}/${p.of}`;
566
+ host.osd.push(`${host.manifestId}${step} · ${item.label}`);
567
+ if (row.owner === "host")
568
+ await host.request("host.run", { action: id.slice("host/".length) });
569
+ else
570
+ host.emit("commands.execute", {
571
+ id: row.local,
572
+ revision: row.command.revision,
573
+ });
574
+ return { ran: true };
575
+ },
576
+ "palette.lead.set": (p) => {
577
+ builtinOnly(host);
578
+ for (const [name, max] of Object.entries(LEAD_TEXTS)) {
579
+ const [first, second] = name.split(".");
580
+ const value = second
581
+ ? p[first]?.[second]
582
+ : p[first];
583
+ if (value === undefined || value === null) {
584
+ if (name === "title")
585
+ throw new HostError("invalid", "title is required");
586
+ continue;
587
+ }
588
+ const length = [...menuTextKey(value)].length;
589
+ if (length < 1 || length > max)
590
+ throw new HostError("invalid", `${name} has 1–${max} characters`);
591
+ }
592
+ if (typeof p.icon !== "string" && host.imagePath(p.icon) === null)
593
+ throw new HostError("invalid", "icon is an icon name or an image");
594
+ host.paletteLead = { ...p };
595
+ },
596
+ "palette.lead.clear": () => {
597
+ builtinOnly(host);
598
+ host.paletteLead = null;
599
+ },
600
+ "palette.lead.done": (p) => {
601
+ builtinOnly(host);
602
+ inner.tickets.delete(String(p.ticket));
603
+ },
604
+ };
605
+ }
606
+ /** Implements `TestHost.runPaletteLead`. */
607
+ export async function runPaletteLead(host, inner, query, options) {
608
+ if (!host.paletteLead)
609
+ throw new Error("test host: no palette lead is set");
610
+ // One request at a time: the plugin's earlier tickets end.
611
+ inner.tickets.clear();
612
+ const ticket = `ticket-${++inner.next.ticket}`;
613
+ inner.tickets.set(ticket, { count: 0, runs: [], last: Date.now() });
614
+ host.emit("palette.lead", {
615
+ query,
616
+ keep: options.keep ?? false,
617
+ ticket,
618
+ status: options.status ?? false,
619
+ });
620
+ await host.settle();
621
+ return ticket;
622
+ }
@@ -2325,6 +2325,68 @@ export declare class TestHost implements Transport {
2325
2325
  }[];
2326
2326
  /** Every core action run (`host.run`, a core command, a pressed core binding), newest last. */
2327
2327
  readonly coreRuns: string[];
2328
+ /**
2329
+ * The plugin is built into the player (`startPlugin`'s `builtin`). Only
2330
+ * then does the host take the built-in-only capabilities
2331
+ * (`commands.run`, `palette.lead`); otherwise their calls fail with
2332
+ * `capability`, as in the player.
2333
+ *
2334
+ * @since 1.7.9
2335
+ */
2336
+ builtin: boolean;
2337
+ /**
2338
+ * The palette's lead row as the plugin last set it (`palette.lead.set`,
2339
+ * wire form), `null` without one. Wire-level.
2340
+ *
2341
+ * @since 1.7.9
2342
+ */
2343
+ paletteLead: Record<string, Json> | null;
2344
+ /**
2345
+ * Simulate the user activating the palette's lead row: Enter (`keep`:
2346
+ * Shift+Enter) with `query` typed, or Enter on the status row
2347
+ * (`status`). Mints a ticket, sends the `palette.lead` event, waits until
2348
+ * the host is idle and returns the ticket.
2349
+ *
2350
+ * Like the player, `commands.run` takes the ticket until
2351
+ * `PaletteLead.done` or 120 s after its last run, at most 30 runs, 4 a
2352
+ * second, and 120 runs a minute per plugin (`limit`). A command declared
2353
+ * `destructive` (and the player's `host/stop`) is confirmed first: the
2354
+ * answer comes from {@link TestHost.dialogAnswers}
2355
+ * (`{ confirmed: false, checked: false }` is Don't Run); each run adds
2356
+ * the command's title (and ` · step/of`) to {@link TestHost.osd}.
2357
+ *
2358
+ * @param query - What the user typed.
2359
+ * @param options - `keep`: Shift+Enter; `status`: the status row.
2360
+ * @returns The ticket of this user action.
2361
+ *
2362
+ * @example Test a request that runs a destructive command
2363
+ * The user asks the plugin to stop playback and declines the
2364
+ * confirmation. `builtin` lets the plugin hold the lead; the ticket
2365
+ * minted here is what its listener passes to `commands.run`, and the
2366
+ * queued answer declines the player's alert for `host/stop`.
2367
+ * ```ts
2368
+ * import assert from "node:assert/strict";
2369
+ * import { startPlugin } from "@vestra-player/sdk/testing";
2370
+ * import activate from "../main.ts";
2371
+ *
2372
+ * const { host, stop } = await startPlugin(activate, {
2373
+ * directory: new URL("..", import.meta.url),
2374
+ * builtin: true, // as a plugin built into the player
2375
+ * });
2376
+ * host.dialogAnswers.push({ confirmed: false, checked: false }); // Don't Run
2377
+ * await host.runPaletteLead("stop playback");
2378
+ * assert.deepEqual(host.coreRuns, []); // declined: nothing ran
2379
+ * await stop();
2380
+ * ```
2381
+ *
2382
+ * @capability None.
2383
+ * @throws `Error` without a code (rejects) The plugin has no lead row.
2384
+ * @since 1.7.9
2385
+ */
2386
+ runPaletteLead(query: string, options?: {
2387
+ keep?: boolean;
2388
+ status?: boolean;
2389
+ }): Promise<string>;
2328
2390
  /**
2329
2391
  * One of the 14 core actions (`play-pause`, `stop`, `seek-forward`, ...)
2330
2392
  * that the test host registers like the player, as `host/<id>`. Throws for
@@ -3189,6 +3251,14 @@ export declare function startPlugin(activate: (plugin: Plugin) => unknown, optio
3189
3251
  id?: string;
3190
3252
  /** Use these capabilities instead of reading `manifest.json`. */
3191
3253
  capabilities?: string[];
3254
+ /**
3255
+ * Run the plugin as one built into the player
3256
+ * ({@link TestHost.builtin}): only then do `commands.run` and
3257
+ * `palette.lead` work. Default `false`.
3258
+ *
3259
+ * @since 1.7.9
3260
+ */
3261
+ builtin?: boolean;
3192
3262
  /** A host to use (to preset data before activation). Default: a new one. */
3193
3263
  host?: TestHost;
3194
3264
  /** Use an existing directory as `plugin.dataDirectory` (to test a restart). */