@sdeck/plugin-audio 0.1.0 → 0.3.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/dist/index.js CHANGED
@@ -1,802 +1,17 @@
1
1
  // @bun
2
2
  // src/index.tsx
3
3
  import { existsSync as existsSync2 } from "fs";
4
-
5
- // ../core/src/element.ts
6
- var runtime;
7
- function registerElementRuntime(next) {
8
- runtime = next;
9
- }
10
- // ../react/src/render.ts
11
- function isReactElement(value) {
12
- return typeof value === "object" && value !== null && "$$typeof" in value;
13
- }
14
- var defaultRenderer = {};
15
- var fontRenderers = new WeakMap;
16
- async function createRenderer(fonts) {
17
- const { Renderer } = await import("@takumi-rs/core");
18
- const renderer = new Renderer;
19
- for (const font of fonts) {
20
- await renderer.registerFont({
21
- name: font.name,
22
- data: font.data,
23
- ...font.weight !== undefined && { weight: font.weight },
24
- ...font.style !== undefined && { style: font.style }
25
- });
26
- }
27
- return renderer;
28
- }
29
- function getRenderer(fonts) {
30
- if (!fonts?.length) {
31
- defaultRenderer.current ??= createRenderer([]);
32
- defaultRenderer.current.catch(() => {
33
- defaultRenderer.current = undefined;
34
- });
35
- return defaultRenderer.current;
36
- }
37
- let renderer = fontRenderers.get(fonts);
38
- if (!renderer) {
39
- renderer = createRenderer(fonts);
40
- renderer.catch(() => fontRenderers.delete(fonts));
41
- fontRenderers.set(fonts, renderer);
42
- }
43
- return renderer;
44
- }
45
- var number = (value) => typeof value === "number" && Number.isFinite(value) ? value : undefined;
46
- function toNode(node, text = true) {
47
- if ("text" in node) {
48
- return text ? { type: "text", text: node.text } : { type: "container", children: [] };
49
- }
50
- const { style, tw, src, width, height } = node.props;
51
- const common = {
52
- ...typeof tw === "string" && { tw }
53
- };
54
- if (node.type === "img") {
55
- if (typeof src !== "string")
56
- throw new Error("<img> needs a string `src` (URL or data: URI)");
57
- return {
58
- type: "image",
59
- src,
60
- ...number(width) !== undefined && { width: number(width) },
61
- ...number(height) !== undefined && { height: number(height) },
62
- ...typeof style === "object" && style !== null && { style },
63
- ...common
64
- };
65
- }
66
- return {
67
- type: "container",
68
- style: { display: "flex", ...typeof style === "object" ? style : {} },
69
- children: node.children.filter((child) => text || !("text" in child)).map((child) => toNode(child, text)),
70
- ...common
71
- };
72
- }
73
- var reconciler;
74
- var flushing = 0;
75
- function flushAll(renderer) {
76
- flushing++;
77
- try {
78
- renderer.flushSyncWork();
79
- for (let i = 0;i < 20 && renderer.flushPassiveEffects(); i++)
80
- renderer.flushSyncWork();
81
- } finally {
82
- flushing--;
83
- }
84
- }
85
- function loadReconciler() {
86
- reconciler ??= (async () => {
87
- let factoryModule;
88
- let constants;
89
- let React;
90
- try {
91
- [factoryModule, constants, React] = await Promise.all([
92
- import("react-reconciler"),
93
- import("react-reconciler/constants.js"),
94
- import("react")
95
- ]);
96
- } catch (cause) {
97
- throw new Error("Rendering React elements requires `react` (>=19.3) to be installed", {
98
- cause
99
- });
100
- }
101
- let priority = constants.NoEventPriority;
102
- const noop = () => {};
103
- const hostConfig = {
104
- supportsMutation: true,
105
- supportsPersistence: false,
106
- supportsHydration: false,
107
- isPrimaryRenderer: true,
108
- warnsIfNotActing: false,
109
- noTimeout: -1,
110
- scheduleTimeout: setTimeout,
111
- cancelTimeout: clearTimeout,
112
- supportsMicrotasks: true,
113
- scheduleMicrotask: queueMicrotask,
114
- createInstance: (type, props) => {
115
- const { children: _children, ...rest } = props;
116
- return { type, props: rest, children: [] };
117
- },
118
- createTextInstance: (text) => ({ text }),
119
- shouldSetTextContent: () => false,
120
- appendInitialChild: (parent, child) => parent.children.push(child),
121
- appendChild: (parent, child) => parent.children.push(child),
122
- appendChildToContainer: (container, child) => container.children.push(child),
123
- insertBefore: (parent, child, before) => {
124
- const children = parent.children;
125
- const existing = children.indexOf(child);
126
- if (existing !== -1)
127
- children.splice(existing, 1);
128
- children.splice(children.indexOf(before), 0, child);
129
- },
130
- insertInContainerBefore: (container, child, before) => {
131
- const children = container.children;
132
- const existing = children.indexOf(child);
133
- if (existing !== -1)
134
- children.splice(existing, 1);
135
- children.splice(children.indexOf(before), 0, child);
136
- },
137
- removeChild: (parent, child) => {
138
- parent.children.splice(parent.children.indexOf(child), 1);
139
- },
140
- removeChildFromContainer: (container, child) => {
141
- container.children.splice(container.children.indexOf(child), 1);
142
- },
143
- clearContainer: (container) => {
144
- container.children = [];
145
- },
146
- commitUpdate: (instance, _type, _prev, next) => {
147
- const { children: _children, ...rest } = next;
148
- instance.props = rest;
149
- },
150
- commitTextUpdate: (text, _old, next) => {
151
- text.text = next;
152
- },
153
- finalizeInitialChildren: () => false,
154
- getPublicInstance: (instance) => instance,
155
- getRootHostContext: () => ({}),
156
- getChildHostContext: (parent) => parent,
157
- prepareForCommit: () => null,
158
- resetAfterCommit: (container) => container.onCommit(),
159
- preparePortalMount: noop,
160
- detachDeletedInstance: noop,
161
- hideInstance: noop,
162
- unhideInstance: noop,
163
- hideTextInstance: noop,
164
- unhideTextInstance: noop,
165
- getInstanceFromNode: () => null,
166
- beforeActiveInstanceBlur: noop,
167
- afterActiveInstanceBlur: noop,
168
- prepareScopeUpdate: noop,
169
- getInstanceFromScope: () => null,
170
- bindToConsole: (method, args) => console[method]?.bind(console, ...args) ?? noop,
171
- extraDevToolsConfig: null,
172
- rendererVersion: "0.0.0",
173
- rendererPackageName: "sdeck",
174
- getCurrentUpdatePriority: () => priority,
175
- setCurrentUpdatePriority: (next) => {
176
- priority = next;
177
- },
178
- resolveUpdatePriority: () => priority !== constants.NoEventPriority ? priority : flushing > 0 ? constants.DiscreteEventPriority : constants.DefaultEventPriority,
179
- resolveEventType: () => null,
180
- resolveEventTimeStamp: () => -1.1,
181
- shouldAttemptEagerTransition: () => false,
182
- trackSchedulerEvent: noop,
183
- requestPostPaintCallback: noop,
184
- maySuspendCommit: () => false,
185
- preloadInstance: () => true,
186
- startSuspendingCommit: noop,
187
- suspendInstance: noop,
188
- waitForCommitToBeReady: () => null,
189
- getSuspendedCommitReason: () => null,
190
- NotPendingTransition: null,
191
- HostTransitionContext: React.createContext(null),
192
- resetFormInstance: noop
193
- };
194
- const factory = factoryModule.default ?? factoryModule;
195
- return factory(hostConfig);
196
- })();
197
- reconciler.catch(() => {
198
- reconciler = undefined;
199
- });
200
- return reconciler;
201
- }
202
- function noopIndicator() {}
203
- async function createReactRoot(size, onFrame, options = {}) {
204
- const [takumi, renderer] = await Promise.all([getRenderer(options.fonts), loadReconciler()]);
205
- let dirty = false;
206
- let drawing;
207
- let lastTree;
208
- let unmounted = false;
209
- let renderError;
210
- let initial = true;
211
- const fail = (error) => {
212
- if (initial)
213
- renderError ??= { error };
214
- else
215
- (options.onError ?? ((e) => console.error("sdeck: React render failed:", e)))(error);
216
- };
217
- async function draw() {
218
- await Promise.resolve();
219
- while (dirty && !unmounted) {
220
- dirty = false;
221
- try {
222
- const [root] = container.children;
223
- if (!root)
224
- continue;
225
- const tree = toNode(root, options.text !== false);
226
- const key = JSON.stringify(tree);
227
- if (key === lastTree)
228
- continue;
229
- lastTree = key;
230
- const pixels = await takumi.render(tree, {
231
- width: size.width,
232
- height: size.height,
233
- format: "raw",
234
- ...options.scale !== undefined && { devicePixelRatio: options.scale }
235
- });
236
- await onFrame({
237
- data: new Uint8Array(pixels.buffer, pixels.byteOffset, pixels.byteLength),
238
- width: size.width,
239
- height: size.height,
240
- channels: 4
241
- });
242
- } catch (error) {
243
- lastTree = undefined;
244
- fail(error);
245
- }
246
- }
247
- drawing = undefined;
248
- }
249
- const container = {
250
- children: [],
251
- onCommit() {
252
- dirty = true;
253
- drawing ??= draw();
254
- }
255
- };
256
- const onError = (error) => fail(error);
257
- const onCaughtError = () => {};
258
- const root = renderer.createContainer(container, 1, null, false, null, "", onError, onCaughtError, onError, noopIndicator, null);
259
- const flush = () => flushAll(renderer);
260
- const handle = {
261
- render(element) {
262
- if (unmounted)
263
- throw new Error("This React root was unmounted");
264
- renderer.updateContainerSync(element, root, null, null);
265
- flush();
266
- },
267
- async idle() {
268
- while (drawing)
269
- await drawing;
270
- if (initial && renderError) {
271
- const { error } = renderError;
272
- renderError = undefined;
273
- throw error;
274
- }
275
- initial = false;
276
- },
277
- async unmount() {
278
- if (unmounted)
279
- return;
280
- renderer.updateContainerSync(null, root, null, null);
281
- flush();
282
- unmounted = true;
283
- await drawing;
284
- }
285
- };
286
- return handle;
287
- }
288
- async function renderReact(element, size, fonts, scale) {
289
- let frame;
290
- const root = await createReactRoot(size, (next) => {
291
- frame = next;
292
- }, { ...fonts && { fonts }, ...scale !== undefined && { scale } });
293
- try {
294
- root.render(element);
295
- await root.idle();
296
- } finally {
297
- await root.unmount();
298
- }
299
- if (!frame)
300
- throw new Error("React element rendered nothing");
301
- return frame;
302
- }
303
- registerElementRuntime({
304
- matches: isReactElement,
305
- render: (element, size, options) => renderReact(element, size, options?.fonts),
306
- createRoot: (size, onFrame, options) => createReactRoot(size, onFrame, options)
307
- });
308
- // ../app/src/app.tsx
309
- import { Fragment, useSyncExternalStore } from "react";
310
-
311
- // ../app/src/context.ts
312
- import { createContext, useContext } from "react";
313
- var DeckContext = createContext(undefined);
314
- var SlotContext = createContext(undefined);
315
- var NavigatorContext = createContext(undefined);
316
- function useDeck() {
317
- const deck = useContext(DeckContext);
318
- if (!deck)
319
- throw new Error("useDeck() must be used inside a component mounted by @sdeck/app");
320
- return deck;
321
- }
322
- function useSlot() {
323
- return useContext(SlotContext);
324
- }
325
- // ../app/src/hooks.ts
326
- import { useContext as useContext2, useEffect, useRef, useState, useSyncExternalStore as useSyncExternalStore2 } from "react";
327
-
328
- // ../app/src/swipe.ts
329
- var SWIPE_WINDOW_MS = 400;
330
-
331
- class SwipeTracker {
332
- #handlers = new Set;
333
- #stamps = new Map;
334
- #completing = new Set;
335
- #first;
336
- constructor(deck) {
337
- deck.on("sensorDown", (index) => this.#down(index));
338
- }
339
- get active() {
340
- return this.#handlers.size > 0;
341
- }
342
- stamp(index) {
343
- return this.#stamps.get(index) ?? 0;
344
- }
345
- completes(index) {
346
- return this.#completing.has(index);
347
- }
348
- listen(handler) {
349
- this.#handlers.add(handler);
350
- return () => void this.#handlers.delete(handler);
351
- }
352
- #down(index) {
353
- this.#completing.delete(index);
354
- const now = performance.now();
355
- const first = this.#first;
356
- if (!this.active || !first || first.index === index || now - first.at > SWIPE_WINDOW_MS) {
357
- this.#first = { index, at: now };
358
- return;
359
- }
360
- this.#first = undefined;
361
- this.#completing.add(index);
362
- for (const sensor of [first.index, index])
363
- this.#stamps.set(sensor, this.stamp(sensor) + 1);
364
- const direction = index > first.index ? "right" : "left";
365
- for (const handler of [...this.#handlers])
366
- handler(direction);
367
- }
368
- }
369
- var trackers = new WeakMap;
370
- function swipeTracker(deck) {
371
- let tracker = trackers.get(deck);
372
- if (!tracker) {
373
- tracker = new SwipeTracker(deck);
374
- trackers.set(deck, tracker);
375
- }
376
- return tracker;
377
- }
378
-
379
- // ../app/src/hooks.ts
380
- function useLatest(value) {
381
- const ref = useRef(value);
382
- useEffect(() => {
383
- ref.current = value;
384
- });
385
- return ref;
386
- }
387
- function useTarget(kind, explicit) {
388
- const slot = useSlot();
389
- if (explicit !== undefined)
390
- return explicit;
391
- return slot?.kind === kind ? slot.index : undefined;
392
- }
393
- function usePressed(kind, explicit) {
394
- const deck = useDeck();
395
- const target = useTarget(kind, explicit);
396
- const [pressed, setPressed] = useState(false);
397
- if (target === undefined) {
398
- throw new Error(`use${kind === "key" ? "Key" : "Sensor"}Pressed() needs an index outside a ${kind} slot`);
399
- }
400
- useEffect(() => {
401
- setPressed(false);
402
- const offDown = deck.on(`${kind}Down`, (i) => i === target && setPressed(true));
403
- const offUp = deck.on(`${kind}Up`, (i) => i === target && setPressed(false));
404
- return () => {
405
- offDown();
406
- offUp();
407
- };
408
- }, [deck, kind, target]);
409
- return pressed;
410
- }
411
- function useRepeat(kind, handler, explicit, options) {
412
- const deck = useDeck();
413
- const target = useTarget(kind, explicit);
414
- const latest = useLatest({ handler, ...options });
415
- useEffect(() => {
416
- const swipes = kind === "sensor" ? swipeTracker(deck) : undefined;
417
- let first;
418
- let delay;
419
- let repeat;
420
- const stop = () => {
421
- clearTimeout(delay);
422
- clearInterval(repeat);
423
- };
424
- const offDown = deck.on(`${kind}Down`, (index) => {
425
- if (target !== undefined && index !== target)
426
- return;
427
- if (swipes?.completes(index))
428
- return;
429
- stop();
430
- clearTimeout(first);
431
- const stamp = swipes?.stamp(index);
432
- const swiped = () => swipes !== undefined && swipes.stamp(index) !== stamp;
433
- const run = () => {
434
- if (!swiped())
435
- latest.current.handler(index);
436
- };
437
- if (swipes?.active)
438
- first = setTimeout(run, SWIPE_WINDOW_MS);
439
- else
440
- run();
441
- const wait = latest.current.delayMs ?? 400;
442
- delay = setTimeout(() => {
443
- repeat = setInterval(run, latest.current.intervalMs ?? 100);
444
- }, swipes?.active ? Math.max(wait, SWIPE_WINDOW_MS) : wait);
445
- });
446
- const offUp = deck.on(`${kind}Up`, (index) => {
447
- if (target === undefined || index === target)
448
- stop();
449
- });
450
- return () => {
451
- offDown();
452
- offUp();
453
- stop();
454
- clearTimeout(first);
455
- };
456
- }, [deck, kind, target, latest]);
457
- }
458
- function useKeyRepeat(handler, options = {}) {
459
- useRepeat("key", handler, options.key, options);
460
- }
461
- function useSensorRepeat(handler, options = {}) {
462
- useRepeat("sensor", handler, options.sensor, options);
463
- }
464
- function useSensorPressed(sensor) {
465
- return usePressed("sensor", sensor);
466
- }
467
- // ../engine/src/state.ts
468
- function sameValue(a, b) {
469
- if (Object.is(a, b))
470
- return true;
471
- if (typeof a !== "object" || typeof b !== "object" || a === null || b === null)
472
- return false;
473
- if (Array.isArray(a) !== Array.isArray(b))
474
- return false;
475
- const ka = Object.keys(a);
476
- const kb = Object.keys(b);
477
- if (ka.length !== kb.length)
478
- return false;
479
- return ka.every((k) => Object.hasOwn(b, k) && sameValue(a[k], b[k]));
480
- }
481
- // ../schema/src/layers.ts
482
- function iconLayer(id, icon, options = {}) {
483
- const { color, size = 52, position = "middle", visible, row, frame } = options;
484
- const src = /^[a-z0-9]+\/[A-Za-z0-9-]+$/.test(icon) ? `icon:${icon}` : icon;
485
- return {
486
- id,
487
- type: "image",
488
- src,
489
- size,
490
- position,
491
- ...color && { color },
492
- ...visible && { visible },
493
- ...row && { row },
494
- ...frame && { frame }
495
- };
496
- }
497
- function textLayer(id, text, options = {}) {
498
- const { color = "#ffffff", size = 14, weight = 700, position = "middle" } = options;
499
- const { visible, row, frame } = options;
500
- return {
501
- id,
502
- type: "text",
503
- text,
504
- color,
505
- size,
506
- weight,
507
- position,
508
- ...visible && { visible },
509
- ...row && { row },
510
- ...frame && { frame }
511
- };
512
- }
513
- // ../plugin/src/bridge.ts
514
4
  import {
515
- createContext as createContext2,
516
- useCallback,
517
- useContext as useContext3,
518
- useEffect as useEffect2,
519
- useMemo,
520
- useRef as useRef2,
521
- useState as useState2,
522
- useSyncExternalStore as useSyncExternalStore3
523
- } from "react";
524
- var HostBridgeContext = createContext2(undefined);
525
- function useBridge() {
526
- const bridge = useContext3(HostBridgeContext);
527
- if (!bridge)
528
- throw new Error("sdeck live-state hooks must be used inside an action drawn by the host");
529
- return bridge;
530
- }
531
- function useWatched(paths, read) {
532
- const bridge = useBridge();
533
- const key = paths.join(`
534
- `);
535
- const subscribe = useCallback((listener) => bridge.watch(paths, listener), [bridge, key]);
536
- const last = useRef2(undefined);
537
- const snapshot = () => {
538
- const value = read();
539
- if (last.current && sameValue(last.current.value, value))
540
- return last.current.value;
541
- last.current = { value };
542
- return value;
543
- };
544
- return useSyncExternalStore3(subscribe, snapshot);
545
- }
546
- function useHostState(key) {
547
- const bridge = useBridge();
548
- const paths = useMemo(() => [key], [key]);
549
- return useWatched(paths, () => {
550
- const dot = key.indexOf(".");
551
- const ns = bridge.scope()[key.slice(0, dot)];
552
- return dot > 0 ? ns?.[key.slice(dot + 1)] : undefined;
553
- });
554
- }
555
- function useImage(src, color) {
556
- const bridge = useBridge();
557
- return useSyncExternalStore3(bridge.watchImages, () => src ? bridge.image(src, color) : undefined);
558
- }
559
- // ../plugin/src/settings.ts
560
- function checkSchema(schema, sources = {}) {
561
- const problems = [];
562
- const types = new Set([
563
- "text",
564
- "number",
565
- "boolean",
566
- "color",
567
- "select",
568
- "page",
569
- "image",
570
- "secret"
571
- ]);
572
- for (const [key, field] of Object.entries(schema)) {
573
- if (!field || typeof field !== "object" || !types.has(field.type)) {
574
- problems.push(`setting "${key}" has an unknown type`);
575
- continue;
576
- }
577
- if (typeof field.label !== "string")
578
- problems.push(`setting "${key}" needs a label`);
579
- const source = "source" in field ? field.source : undefined;
580
- if (source !== undefined && !(source in sources)) {
581
- problems.push(`setting "${key}" uses unknown option source "${source}"`);
582
- }
583
- if (field.type === "select" && (!Array.isArray(field.options) || field.options.length === 0 && source === undefined)) {
584
- problems.push(`setting "${key}" needs at least one option or a source`);
585
- }
586
- for (const other of "dependsOn" in field && field.dependsOn || []) {
587
- if (!(other in schema))
588
- problems.push(`setting "${key}" depends on unknown "${other}"`);
589
- }
590
- if (field.visibleIf !== undefined) {
591
- for (const other of Object.keys(field.visibleIf)) {
592
- if (!(other in schema))
593
- problems.push(`setting "${key}" depends on unknown "${other}"`);
594
- }
595
- }
596
- }
597
- return problems;
598
- }
5
+ defineAction,
6
+ definePlugin,
7
+ useHostState,
8
+ useImage,
9
+ useKeyRepeat,
10
+ useSensorPressed,
11
+ useSensorRepeat
12
+ } from "@sdeck/plugin";
13
+ import { iconLayer, textLayer } from "@sdeck/schema";
599
14
 
600
- // ../plugin/src/plugin.ts
601
- var PERMISSIONS = [
602
- "shell",
603
- "process",
604
- "filesystem",
605
- "network",
606
- "input",
607
- "audio",
608
- "clipboard"
609
- ];
610
- var ID = /^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*$/;
611
- var NAMESPACE = /^[a-z][\w-]{0,31}$/;
612
- var LOCAL_ID = /^[\w.-]+$/;
613
- function defineAction(def) {
614
- return {
615
- ...def,
616
- slots: def.slots ?? ["key"],
617
- settings: def.settings ?? {}
618
- };
619
- }
620
- function definePlugin(def) {
621
- const problems = checkPlugin(def);
622
- if (problems.length > 0) {
623
- throw new TypeError(`invalid plugin "${def?.id}": ${problems.join("; ")}`);
624
- }
625
- return def;
626
- }
627
- function checkLocalIds(kind, items, problems) {
628
- const seen = new Set;
629
- for (const item of items) {
630
- const name = typeof item?.id === "string" ? item.id : "?";
631
- if (typeof item?.id !== "string" || !LOCAL_ID.test(item.id)) {
632
- problems.push(`${kind} "${name}": id must be letters, digits, ".", "-" or "_"`);
633
- } else if (seen.has(item.id)) {
634
- problems.push(`${kind} "${name}" is defined twice`);
635
- }
636
- seen.add(name);
637
- }
638
- return seen;
639
- }
640
- function checkPlugin(value) {
641
- if (!value || typeof value !== "object")
642
- return ["not an object"];
643
- const def = value;
644
- const problems = [];
645
- if (typeof def.id !== "string" || !ID.test(def.id)) {
646
- problems.push("id must be a package-style name (lowercase, e.g. `my-plugin` or `@me/plugin`)");
647
- }
648
- if (typeof def.name !== "string" || def.name === "")
649
- problems.push("name is required");
650
- if (typeof def.version !== "string" || def.version === "")
651
- problems.push("version is required");
652
- if (def.namespace !== undefined && !NAMESPACE.test(def.namespace)) {
653
- problems.push("namespace must be lowercase letters, digits, - or _ (starting with a letter)");
654
- }
655
- if (def.activate !== undefined && typeof def.activate !== "function") {
656
- problems.push("activate must be a function");
657
- }
658
- if (def.permissions !== undefined) {
659
- if (!Array.isArray(def.permissions))
660
- problems.push("permissions must be an array");
661
- else
662
- for (const p of def.permissions)
663
- if (!PERMISSIONS.includes(p))
664
- problems.push(`unknown permission "${String(p)}"`);
665
- }
666
- if (def.settings !== undefined) {
667
- for (const p of checkSchema(def.settings, def.optionSources ?? {})) {
668
- problems.push(`plugin ${p}`);
669
- }
670
- }
671
- if (def.commands !== undefined) {
672
- if (!Array.isArray(def.commands))
673
- problems.push("commands must be an array");
674
- else {
675
- checkLocalIds("command", def.commands, problems);
676
- for (const c of def.commands) {
677
- const name = typeof c?.id === "string" ? c.id : "?";
678
- if (typeof c?.name !== "string")
679
- problems.push(`command "${name}": name is required`);
680
- if (typeof c?.run !== "function")
681
- problems.push(`command "${name}": run is required`);
682
- }
683
- }
684
- }
685
- if (def.onboarding !== undefined)
686
- problems.push(...checkOnboarding(def));
687
- const sources = def.optionSources ?? {};
688
- if (typeof sources !== "object")
689
- problems.push("optionSources must be an object");
690
- else
691
- for (const [name, fn] of Object.entries(sources))
692
- if (typeof fn !== "function")
693
- problems.push(`option source "${name}" must be a function`);
694
- if (!Array.isArray(def.actions))
695
- return [...problems, "actions must be an array"];
696
- checkLocalIds("action", def.actions, problems);
697
- for (const action of def.actions) {
698
- const name = typeof action?.id === "string" ? action.id : "?";
699
- if (typeof action?.name !== "string")
700
- problems.push(`action "${name}": name is required`);
701
- const hasComponent = typeof action?.component === "function" || typeof action?.component === "object";
702
- const hasRun = typeof action?.run === "function";
703
- if (!hasComponent && !hasRun)
704
- problems.push(`action "${name}": needs run or component`);
705
- if (action?.look !== undefined && typeof action.look !== "function") {
706
- problems.push(`action "${name}": look must be a function`);
707
- }
708
- const slots = action?.slots ?? ["key"];
709
- if (!Array.isArray(slots) || slots.length === 0 || slots.some((s) => !["key", "sensor", "window"].includes(s))) {
710
- problems.push(`action "${name}": slots must list "key", "sensor" and/or "window"`);
711
- }
712
- for (const p of checkSchema(action?.settings ?? {}, sources)) {
713
- problems.push(`action "${name}": ${p}`);
714
- }
715
- for (const [key, field] of Object.entries(action?.settings ?? {})) {
716
- if (field?.type === "secret") {
717
- problems.push(`action "${name}": setting "${key}": secrets belong in the plugin settings`);
718
- }
719
- }
720
- }
721
- if (def.state !== undefined) {
722
- if (!Array.isArray(def.state))
723
- problems.push("state must be an array");
724
- else {
725
- checkLocalIds("state", def.state, problems);
726
- for (const s of def.state) {
727
- const name = typeof s?.id === "string" ? s.id : "?";
728
- if (typeof s?.name !== "string")
729
- problems.push(`state "${name}": name is required`);
730
- if (!["number", "string", "boolean", "json"].includes(s?.type)) {
731
- problems.push(`state "${name}": type must be number, string, boolean or json`);
732
- }
733
- if (s?.poll && (typeof s.poll.read !== "function" || !(s.poll.everyMs > 0))) {
734
- problems.push(`state "${name}": poll needs read() and everyMs > 0`);
735
- }
736
- if (s?.start !== undefined && typeof s.start !== "function") {
737
- problems.push(`state "${name}": start must be a function`);
738
- }
739
- }
740
- }
741
- }
742
- if (def.triggers !== undefined) {
743
- if (!Array.isArray(def.triggers))
744
- problems.push("triggers must be an array");
745
- else {
746
- checkLocalIds("trigger", def.triggers, problems);
747
- for (const t of def.triggers) {
748
- const name = typeof t?.id === "string" ? t.id : "?";
749
- if (typeof t?.name !== "string")
750
- problems.push(`trigger "${name}": name is required`);
751
- if (typeof t?.subscribe !== "function") {
752
- problems.push(`trigger "${name}": subscribe is required`);
753
- }
754
- for (const p of checkSchema(t?.settings ?? {}, sources)) {
755
- problems.push(`trigger "${name}": ${p}`);
756
- }
757
- }
758
- }
759
- }
760
- return problems;
761
- }
762
- function checkOnboarding(def) {
763
- const onboarding = def.onboarding;
764
- if (!Array.isArray(onboarding?.steps))
765
- return ["onboarding: steps must be an array"];
766
- const problems = [];
767
- checkLocalIds("onboarding step", onboarding.steps, problems);
768
- const settings = def.settings ?? {};
769
- const commands = new Set((def.commands ?? []).map((c) => c.id));
770
- for (const step of onboarding.steps) {
771
- const name = typeof step?.id === "string" ? step.id : "?";
772
- if (typeof step?.title !== "string")
773
- problems.push(`onboarding step "${name}": title is required`);
774
- for (const key of step?.settings ?? []) {
775
- if (!(key in settings))
776
- problems.push(`onboarding step "${name}": no setting "${key}"`);
777
- }
778
- if (step?.command !== undefined && !commands.has(step.command)) {
779
- problems.push(`onboarding step "${name}": no command "${step.command}"`);
780
- }
781
- if (step?.done !== undefined && typeof step.done !== "function") {
782
- problems.push(`onboarding step "${name}": done must be a function`);
783
- }
784
- }
785
- const page = onboarding.starterPage;
786
- if (page) {
787
- const actions = new Set((def.actions ?? []).map((a) => a.id));
788
- const used = [
789
- ...Object.values(page.keys ?? {}),
790
- ...Object.values(page.sensors ?? {}),
791
- ...page.window ? [page.window] : []
792
- ];
793
- for (const { action } of used) {
794
- if (!actions.has(action))
795
- problems.push(`onboarding starter page: no action "${action}"`);
796
- }
797
- }
798
- return problems;
799
- }
800
15
  // src/helper.ts
801
16
  import { spawn } from "child_process";
802
17
  import { existsSync } from "fs";
@@ -1149,7 +364,7 @@ var volume = defineAction({
1149
364
  max: 100,
1150
365
  visibleIf: { operation: "set" }
1151
366
  },
1152
- background: { type: "color", label: "Background", default: "#172554" }
367
+ background: { type: "color", label: "Background", default: "#172554", appearance: true }
1153
368
  },
1154
369
  run: async ({ settings }) => {
1155
370
  const target = targetOf(settings);
@@ -1222,7 +437,7 @@ var slider = defineAction({
1222
437
  ]
1223
438
  },
1224
439
  step: { type: "number", label: "Step (%)", default: 4, min: 1, max: 50 },
1225
- color: { type: "color", label: "Bar colour", default: "#60a5fa" }
440
+ color: { type: "color", label: "Bar colour", default: "#60a5fa", appearance: true }
1226
441
  },
1227
442
  run: async ({ settings }) => {
1228
443
  const target = targetOf(settings);
@@ -1355,7 +570,7 @@ var defaultDevice = defineAction({
1355
570
  options: [{ value: NEXT, label: "The next device" }],
1356
571
  visibleIf: { flow: "input" }
1357
572
  },
1358
- background: { type: "color", label: "Background", default: "#3b0764" }
573
+ background: { type: "color", label: "Background", default: "#3b0764", appearance: true }
1359
574
  },
1360
575
  run: async ({ settings }) => {
1361
576
  const wanted = settings.flow === "output" ? settings.output : settings.input;
@@ -1395,7 +610,7 @@ var deviceOptions = async (flow) => (await helper2.request("snapshot"))[flow].ma
1395
610
  var src_default = definePlugin({
1396
611
  id: "@sdeck/plugin-audio",
1397
612
  name: "Audio",
1398
- version: "0.1.0",
613
+ version: "0.3.0",
1399
614
  namespace: "audio",
1400
615
  description: "Volume and mute for speakers, microphone and each app, and device switching.",
1401
616
  author: "sdeck",
@@ -1463,4 +678,4 @@ export {
1463
678
  targetPath
1464
679
  };
1465
680
 
1466
- //# debugId=234E92790EEA874864756E2164756E21
681
+ //# debugId=C19813BE49E56B2064756E2164756E21