@sdeck/plugin 0.0.0-stage → 0.1.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 ADDED
@@ -0,0 +1,3352 @@
1
+ // ../core/src/deck.ts
2
+ import sharp3 from "sharp";
3
+
4
+ // ../core/src/element.ts
5
+ var isRawImage = (value) => typeof value === "object" && value !== null && !ArrayBuffer.isView(value) && ("data" in value) && ("width" in value) && ("height" in value) && ("channels" in value);
6
+ var runtime;
7
+ function registerElementRuntime(next) {
8
+ runtime = next;
9
+ }
10
+ function getElementRuntime() {
11
+ if (!runtime) {
12
+ throw new Error("Drawing elements needs a renderer: install and import `@sdeck/react` (once, anywhere)");
13
+ }
14
+ return runtime;
15
+ }
16
+ var isRenderable = (value) => runtime !== undefined && typeof value === "object" && value !== null && runtime.matches(value);
17
+
18
+ // ../core/src/framebuffer.ts
19
+ var view = (data, offset, length) => Buffer.from(data.buffer, data.byteOffset + offset, length);
20
+
21
+ class Framebuffer {
22
+ width;
23
+ height;
24
+ data;
25
+ constructor(size) {
26
+ this.width = size.width;
27
+ this.height = size.height;
28
+ this.data = new Uint8Array(size.width * size.height * 3);
29
+ }
30
+ #check(rect, rgb) {
31
+ if (rect.x < 0 || rect.y < 0 || rect.x + rect.width > this.width || rect.y + rect.height > this.height) {
32
+ throw new RangeError(`region ${rect.width}×${rect.height} at (${rect.x}, ${rect.y}) is outside the ${this.width}×${this.height} screen`);
33
+ }
34
+ if (rgb && rgb.length !== rect.width * rect.height * 3) {
35
+ throw new RangeError(`expected ${rect.width}×${rect.height} RGB pixels, got ${rgb.length} bytes`);
36
+ }
37
+ }
38
+ equals(rect, rgb) {
39
+ this.#check(rect, rgb);
40
+ const row = rect.width * 3;
41
+ for (let y = 0;y < rect.height; y++) {
42
+ const at = ((rect.y + y) * this.width + rect.x) * 3;
43
+ if (!view(this.data, at, row).equals(view(rgb, y * row, row)))
44
+ return false;
45
+ }
46
+ return true;
47
+ }
48
+ blit(rect, rgb) {
49
+ this.#check(rect, rgb);
50
+ const row = rect.width * 3;
51
+ if (rect.x === 0 && rect.width === this.width) {
52
+ this.data.set(rgb, rect.y * row);
53
+ return;
54
+ }
55
+ for (let y = 0;y < rect.height; y++) {
56
+ this.data.set(rgb.subarray(y * row, (y + 1) * row), ((rect.y + y) * this.width + rect.x) * 3);
57
+ }
58
+ }
59
+ fill(color, rect = { x: 0, y: 0, width: this.width, height: this.height }) {
60
+ this.blit(rect, solidRgb(rect, color));
61
+ }
62
+ read(rect = { x: 0, y: 0, width: this.width, height: this.height }) {
63
+ this.#check(rect);
64
+ if (rect.x === 0 && rect.y === 0 && rect.width === this.width && rect.height === this.height) {
65
+ return { data: this.data.slice(), width: this.width, height: this.height, channels: 3 };
66
+ }
67
+ const row = rect.width * 3;
68
+ const out = new Uint8Array(row * rect.height);
69
+ for (let y = 0;y < rect.height; y++) {
70
+ const at = ((rect.y + y) * this.width + rect.x) * 3;
71
+ out.set(this.data.subarray(at, at + row), y * row);
72
+ }
73
+ return { data: out, width: rect.width, height: rect.height, channels: 3 };
74
+ }
75
+ }
76
+ function solidRgb(size, [r, g, b]) {
77
+ const out = new Uint8Array(size.width * size.height * 3);
78
+ for (let i = 0;i < out.length; i += 3) {
79
+ out[i] = r;
80
+ out[i + 1] = g;
81
+ out[i + 2] = b;
82
+ }
83
+ return out;
84
+ }
85
+ function parseHexColor(color) {
86
+ const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(color.trim())?.[1];
87
+ if (!hex)
88
+ return;
89
+ const full = hex.length === 3 ? [...hex].map((c) => c + c).join("") : hex;
90
+ const n = Number.parseInt(full, 16);
91
+ return [n >> 16 & 255, n >> 8 & 255, n & 255];
92
+ }
93
+ function flattenRgba(rgba, [br, bg, bb]) {
94
+ const out = new Uint8Array(rgba.length / 4 * 3);
95
+ for (let i = 0, j = 0;i < rgba.length; i += 4, j += 3) {
96
+ const a = rgba[i + 3];
97
+ if (a === 255) {
98
+ out[j] = rgba[i];
99
+ out[j + 1] = rgba[i + 1];
100
+ out[j + 2] = rgba[i + 2];
101
+ } else {
102
+ const inv = 255 - a;
103
+ out[j] = (rgba[i] * a + br * inv + 127) / 255;
104
+ out[j + 1] = (rgba[i + 1] * a + bg * inv + 127) / 255;
105
+ out[j + 2] = (rgba[i + 2] * a + bb * inv + 127) / 255;
106
+ }
107
+ }
108
+ return out;
109
+ }
110
+
111
+ // ../core/src/image.ts
112
+ import sharp from "sharp";
113
+ var SUPPORTED_FORMATS = new Set(["png", "jpeg", "webp"]);
114
+ async function prepareImage(source, size, options = {}) {
115
+ const { fit = "cover", background = "#000000", fonts } = options;
116
+ const input = isRenderable(source) ? await getElementRuntime().render(source, size, fonts ? { fonts } : {}) : source;
117
+ let pipeline;
118
+ if (isRawImage(input)) {
119
+ const { data, width, height, channels } = input;
120
+ pipeline = sharp(data, { raw: { width, height, channels } });
121
+ } else {
122
+ const encoded = input;
123
+ const { format } = await sharp(encoded).metadata();
124
+ if (!format || !SUPPORTED_FORMATS.has(format)) {
125
+ throw new Error(`Unsupported image format "${format ?? "unknown"}"; use PNG, JPEG or WebP`);
126
+ }
127
+ pipeline = sharp(encoded);
128
+ }
129
+ return pipeline.autoOrient().resize(size.width, size.height, { fit, background }).flatten({ background });
130
+ }
131
+ async function toRgb(source, size, options = {}) {
132
+ const { background = "#000000", fonts } = options;
133
+ const input = isRenderable(source) ? await getElementRuntime().render(source, size, fonts ? { fonts } : {}) : source;
134
+ if (isRawImage(input) && input.width === size.width && input.height === size.height) {
135
+ if (input.channels === 3)
136
+ return input.data;
137
+ const bg = parseHexColor(background);
138
+ if (bg)
139
+ return flattenRgba(input.data, bg);
140
+ }
141
+ const { data, info } = await (await prepareImage(input, size, options)).toColourspace("srgb").raw().toBuffer({ resolveWithObject: true });
142
+ if (info.channels !== 3) {
143
+ throw new Error(`expected RGB pixels, got ${info.channels} channels`);
144
+ }
145
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
146
+ }
147
+ async function encodeJpeg(rgb, size, options = {}) {
148
+ const { quality = 90, rotation = 0 } = options;
149
+ let pipeline = sharp(rgb, { raw: { width: size.width, height: size.height, channels: 3 } });
150
+ if (rotation === 180)
151
+ pipeline = pipeline.rotate(180);
152
+ const jpeg = await pipeline.jpeg({ quality, progressive: false, chromaSubsampling: "4:4:4" }).toBuffer();
153
+ return new Uint8Array(jpeg.buffer, jpeg.byteOffset, jpeg.byteLength);
154
+ }
155
+
156
+ // ../core/src/layout.ts
157
+ import sharp2 from "sharp";
158
+ function placements(layout, geometry) {
159
+ if ((layout.keys?.length ?? 0) > geometry.keys.length) {
160
+ throw new RangeError(`at most ${geometry.keys.length} key images, got ${layout.keys?.length}`);
161
+ }
162
+ if ((layout.sensors?.length ?? 0) > geometry.sensors.length) {
163
+ throw new RangeError(`at most ${geometry.sensors.length} sensor images, got ${layout.sensors?.length}`);
164
+ }
165
+ if (layout.window !== undefined && !geometry.window) {
166
+ throw new RangeError("this deck has no window");
167
+ }
168
+ const out = [
169
+ ...geometry.keys.map((rect, i) => [layout.keys?.[i], rect]),
170
+ ...geometry.sensors.map((rect, i) => [
171
+ layout.sensors?.[i],
172
+ rect
173
+ ])
174
+ ];
175
+ if (geometry.window)
176
+ out.push([layout.window, geometry.window]);
177
+ return out;
178
+ }
179
+ async function background(size, color) {
180
+ const { data } = await sharp2({ create: { ...size, channels: 3, background: color } }).raw().toBuffer({ resolveWithObject: true });
181
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
182
+ }
183
+ async function compose(layout, geometry, options) {
184
+ const { background: color = "#000000" } = options;
185
+ const slots = placements(layout, geometry);
186
+ const screen = new Framebuffer(geometry.screen);
187
+ const hex = parseHexColor(color);
188
+ const [base, ...pixels] = await Promise.all([
189
+ hex ? undefined : background(geometry.screen, color),
190
+ ...slots.map(([source, rect]) => source === undefined ? undefined : toRgb(source, rect, options))
191
+ ]);
192
+ if (hex)
193
+ screen.fill(hex);
194
+ else if (base)
195
+ screen.blit({ x: 0, y: 0, ...geometry.screen }, base);
196
+ slots.forEach(([, rect], i) => {
197
+ const rgb = pixels[i];
198
+ if (rgb)
199
+ screen.blit(rect, rgb);
200
+ });
201
+ return screen;
202
+ }
203
+ async function composeScreenRaw(layout, geometry, options = {}) {
204
+ const screen = await compose(layout, geometry, options);
205
+ return { data: screen.data, width: screen.width, height: screen.height, channels: 3 };
206
+ }
207
+
208
+ // ../core/src/deck.ts
209
+ var toError = (error) => error instanceof Error ? error : new Error(String(error));
210
+ var nextTick = () => new Promise((resolve) => setImmediate(resolve));
211
+
212
+ class StreamDeck {
213
+ model;
214
+ transport;
215
+ #listeners = {
216
+ keyDown: new Set,
217
+ keyUp: new Set,
218
+ sensorDown: new Set,
219
+ sensorUp: new Set,
220
+ draw: new Set,
221
+ error: new Set
222
+ };
223
+ #unsubscribe;
224
+ #pressed = [];
225
+ #closed = false;
226
+ #roots = new Set;
227
+ #queue = Promise.resolve();
228
+ #screen;
229
+ #allSlots;
230
+ #known = new Set;
231
+ #gen = new Map;
232
+ #seq = new Map;
233
+ #frame;
234
+ #pumping = false;
235
+ constructor(transport, model) {
236
+ this.transport = transport;
237
+ this.model = model;
238
+ this.#screen = new Framebuffer(model.layout.screen);
239
+ this.#allSlots = [
240
+ ...model.layout.keys.map((_, i) => `key:${i}`),
241
+ ...model.layout.sensors.map((_, i) => `sensor:${i}`),
242
+ ...model.layout.window ? ["window"] : [],
243
+ "rest"
244
+ ];
245
+ this.#unsubscribe = [
246
+ transport.onData((data) => this.#handleInput(data)),
247
+ transport.onError((error) => this.emit("error", toError(error)))
248
+ ];
249
+ }
250
+ get keyCount() {
251
+ return this.model.layout.keys.length;
252
+ }
253
+ get sensorCount() {
254
+ return this.model.layout.sensors.length;
255
+ }
256
+ get keySize() {
257
+ return this.#size(this.model.layout.keys[0], "keys");
258
+ }
259
+ get sensorSize() {
260
+ return this.#size(this.model.layout.sensors[0], "sensor strips");
261
+ }
262
+ get windowSize() {
263
+ return this.#size(this.model.layout.window, "a window");
264
+ }
265
+ get screenSize() {
266
+ return this.model.layout.screen;
267
+ }
268
+ get closed() {
269
+ return this.#closed;
270
+ }
271
+ slotDrawing(kind, index = 0) {
272
+ const { layout, design } = this.model;
273
+ const rect = kind === "window" ? layout.window : (kind === "key" ? layout.keys : layout.sensors)[index];
274
+ const size = this.#size(rect, kind === "window" ? "a window" : `${kind} ${index}`);
275
+ const base = design?.[kind];
276
+ if (!base)
277
+ return { size, scale: 1 };
278
+ const scale = Math.min(size.width / base.width, size.height / base.height);
279
+ return {
280
+ size: { width: Math.round(size.width / scale), height: Math.round(size.height / scale) },
281
+ scale
282
+ };
283
+ }
284
+ #size(rect, what) {
285
+ if (!rect)
286
+ throw new Error(`${this.model.name} has no ${what}`);
287
+ return { width: rect.width, height: rect.height };
288
+ }
289
+ #windowRect() {
290
+ const rect = this.model.layout.window;
291
+ if (!rect)
292
+ throw new Error(`${this.model.name} has no window`);
293
+ return rect;
294
+ }
295
+ get #screenRect() {
296
+ return { x: 0, y: 0, ...this.screenSize };
297
+ }
298
+ on(event, listener) {
299
+ this.#listeners[event].add(listener);
300
+ return () => this.off(event, listener);
301
+ }
302
+ off(event, listener) {
303
+ this.#listeners[event].delete(listener);
304
+ }
305
+ emit(event, ...args) {
306
+ for (const listener of [...this.#listeners[event]]) {
307
+ try {
308
+ listener(...args);
309
+ } catch (error) {
310
+ if (event !== "error")
311
+ this.emit("error", toError(error));
312
+ }
313
+ }
314
+ }
315
+ sendWindowJpeg(_jpeg) {
316
+ return Promise.reject(new Error(`${this.model.name} has no window`));
317
+ }
318
+ sendWindowRegionJpeg(_region, _jpeg) {
319
+ return Promise.reject(new Error(`${this.model.name} cannot update part of the window`));
320
+ }
321
+ async sendFillKey(index, color) {
322
+ const size = this.#size(this.model.layout.keys[index], "keys");
323
+ await this.sendKeyJpeg(index, await this.#encode(solidRgb(size, color), size));
324
+ }
325
+ async sendFillScreen(color) {
326
+ const size = this.screenSize;
327
+ await this.sendScreenJpeg(await this.#encode(solidRgb(size, color), size));
328
+ }
329
+ async onClosing() {}
330
+ async ping() {
331
+ await this.getSerialNumber();
332
+ }
333
+ async setKeyImage(index, image, options) {
334
+ this.assertKey(index);
335
+ const slot = `key:${index}`;
336
+ const rect = this.model.layout.keys[index];
337
+ const current = this.#claim([slot]);
338
+ const rgb = await toRgb(image, rect, options);
339
+ if (!current())
340
+ return;
341
+ await this.#commit([slot], rect, rgb, () => {
342
+ const jpeg = this.#encode(rgb, rect, options?.quality);
343
+ return async () => this.sendKeyJpeg(index, await jpeg);
344
+ });
345
+ }
346
+ async setWindowImage(image, options) {
347
+ const rect = this.#windowRect();
348
+ const current = this.#claim(["window"]);
349
+ const rgb = await toRgb(image, rect, options);
350
+ if (!current())
351
+ return;
352
+ await this.#commit(["window"], rect, rgb, () => {
353
+ const jpeg = this.#encode(rgb, rect, options?.quality);
354
+ return async () => this.sendWindowJpeg(await jpeg);
355
+ });
356
+ }
357
+ async setWindowRegionImage(region, image, options) {
358
+ const rect = this.#windowRegion(region);
359
+ const rgb = await toRgb(image, rect, options);
360
+ await this.#commit(["window"], rect, rgb, () => {
361
+ const jpeg = this.#encode(rgb, rect, options?.quality);
362
+ return async () => this.sendWindowRegionJpeg(region, await jpeg);
363
+ });
364
+ }
365
+ async setSensorImage(index, image, options) {
366
+ this.assertSensor(index);
367
+ const slot = `sensor:${index}`;
368
+ const rect = this.model.layout.sensors[index];
369
+ const current = this.#claim([slot]);
370
+ const rgb = await toRgb(image, rect, options);
371
+ if (!current() || this.#unchanged([slot], rect, rgb))
372
+ return;
373
+ this.#screen.blit(rect, rgb);
374
+ this.#touch([slot]);
375
+ await this.#requestFrame(options?.quality);
376
+ }
377
+ async setScreenImage(image, options) {
378
+ const current = this.#claim(this.#allSlots);
379
+ const rgb = await toRgb(image, this.screenSize, options);
380
+ if (current())
381
+ await this.#drawScreen(rgb, options?.quality);
382
+ }
383
+ async setScreenLayout(layout, options) {
384
+ const current = this.#claim(this.#allSlots);
385
+ const { data } = await composeScreenRaw(layout, this.model.layout, options);
386
+ if (current())
387
+ await this.#drawScreen(data, options?.quality);
388
+ }
389
+ fillKey(index, color) {
390
+ this.assertKey(index);
391
+ const slot = `key:${index}`;
392
+ const rect = this.model.layout.keys[index];
393
+ this.#claim([slot]);
394
+ return this.#commit([slot], rect, solidRgb(rect, color), () => () => this.sendFillKey(index, color));
395
+ }
396
+ fillScreen(color) {
397
+ this.#claim(this.#allSlots);
398
+ const rect = this.#screenRect;
399
+ return this.#commit(this.#allSlots, rect, solidRgb(rect, color), () => () => this.sendFillScreen(color));
400
+ }
401
+ setKeyJpeg(index, jpeg) {
402
+ this.assertKey(index);
403
+ return this.#raw([`key:${index}`], () => this.sendKeyJpeg(index, jpeg));
404
+ }
405
+ setScreenJpeg(jpeg) {
406
+ return this.#raw(this.#allSlots, () => this.sendScreenJpeg(jpeg));
407
+ }
408
+ setWindowJpeg(jpeg) {
409
+ return this.#raw(["window"], () => this.sendWindowJpeg(jpeg));
410
+ }
411
+ setWindowRegionJpeg(region, jpeg) {
412
+ this.#windowRegion(region);
413
+ return this.#raw(["window"], () => this.sendWindowRegionJpeg(region, jpeg));
414
+ }
415
+ readScreen(region) {
416
+ return this.#screen.read(region);
417
+ }
418
+ async snapshot(region) {
419
+ const { data, width, height } = this.#screen.read(region);
420
+ const png = await sharp3(data, { raw: { width, height, channels: 3 } }).png().toBuffer();
421
+ return new Uint8Array(png.buffer, png.byteOffset, png.byteLength);
422
+ }
423
+ #encode(rgb, size, quality) {
424
+ const jpeg = encodeJpeg(rgb, size, { quality, rotation: this.model.rotation });
425
+ jpeg.catch(() => {});
426
+ return jpeg;
427
+ }
428
+ #windowRegion(region) {
429
+ const win = this.#windowRect();
430
+ if (region.x < 0 || region.y < 0 || region.width <= 0 || region.height <= 0 || region.x + region.width > win.width || region.y + region.height > win.height) {
431
+ throw new RangeError(`region ${region.width}×${region.height} at (${region.x}, ${region.y}) is outside the ${win.width}×${win.height} window`);
432
+ }
433
+ return { ...region, x: win.x + region.x, y: win.y + region.y };
434
+ }
435
+ #claim(slots) {
436
+ const seqs = slots.map((slot) => {
437
+ const seq = (this.#seq.get(slot) ?? 0) + 1;
438
+ this.#seq.set(slot, seq);
439
+ return seq;
440
+ });
441
+ return () => slots.every((slot, i) => this.#seq.get(slot) === seqs[i]);
442
+ }
443
+ #touch(slots) {
444
+ const gens = new Map;
445
+ for (const slot of slots) {
446
+ const gen = (this.#gen.get(slot) ?? 0) + 1;
447
+ this.#gen.set(slot, gen);
448
+ this.#known.delete(slot);
449
+ gens.set(slot, gen);
450
+ }
451
+ return gens;
452
+ }
453
+ #gens(slots) {
454
+ return new Map(slots.map((slot) => [slot, this.#gen.get(slot) ?? 0]));
455
+ }
456
+ #unchanged(slots, rect, rgb) {
457
+ return slots.every((slot) => this.#known.has(slot)) && this.#screen.equals(rect, rgb);
458
+ }
459
+ async#settle(write, gens, region) {
460
+ try {
461
+ await write;
462
+ } catch (error) {
463
+ for (const slot of gens.keys())
464
+ this.#known.delete(slot);
465
+ throw error;
466
+ }
467
+ for (const [slot, gen] of gens)
468
+ if (this.#gen.get(slot) === gen)
469
+ this.#known.add(slot);
470
+ this.emit("draw", region);
471
+ }
472
+ #commit(slots, rect, rgb, prepare) {
473
+ if (this.#unchanged(slots, rect, rgb))
474
+ return Promise.resolve();
475
+ this.#screen.blit(rect, rgb);
476
+ const gens = this.#touch(slots);
477
+ return this.#settle(this.enqueue(prepare()), gens, rect);
478
+ }
479
+ async#raw(slots, write) {
480
+ this.#claim(slots);
481
+ this.#touch(slots);
482
+ await this.enqueue(write);
483
+ }
484
+ async#drawScreen(rgb, quality) {
485
+ const rect = this.#screenRect;
486
+ if (this.#unchanged(this.#allSlots, rect, rgb))
487
+ return;
488
+ this.#screen.blit(rect, rgb);
489
+ this.#touch(this.#allSlots);
490
+ await this.#requestFrame(quality);
491
+ }
492
+ #requestFrame(quality) {
493
+ this.#frame ??= { waiters: [] };
494
+ const frame = this.#frame;
495
+ if (quality !== undefined)
496
+ frame.quality = quality;
497
+ const done = new Promise((resolve, reject) => frame.waiters.push({ resolve, reject }));
498
+ if (!this.#pumping)
499
+ this.#pump();
500
+ return done;
501
+ }
502
+ async#pump() {
503
+ this.#pumping = true;
504
+ try {
505
+ while (this.#frame) {
506
+ await nextTick();
507
+ const frame = this.#frame;
508
+ this.#frame = undefined;
509
+ const gens = this.#gens(this.#allSlots);
510
+ const jpeg = this.#encode(this.#screen.data.slice(), this.screenSize, frame.quality);
511
+ const write = this.enqueue(async () => this.sendScreenJpeg(await jpeg));
512
+ try {
513
+ await this.#settle(write, gens, this.#screenRect);
514
+ for (const waiter of frame.waiters)
515
+ waiter.resolve();
516
+ } catch (error) {
517
+ for (const waiter of frame.waiters)
518
+ waiter.reject(error);
519
+ }
520
+ }
521
+ } finally {
522
+ this.#pumping = false;
523
+ }
524
+ }
525
+ mountKey(index, element, options) {
526
+ this.assertKey(index);
527
+ return this.#mount("key", index, (frame) => this.setKeyImage(index, frame, { ...options, fit: "fill" }), element, options);
528
+ }
529
+ mountSensor(index, element, options) {
530
+ this.assertSensor(index);
531
+ return this.#mount("sensor", index, (frame) => this.setSensorImage(index, frame, { ...options, fit: "fill" }), element, options);
532
+ }
533
+ mountWindow(element, options) {
534
+ return this.#mount("window", 0, (frame) => this.setWindowImage(frame, { ...options, fit: "fill" }), element, options);
535
+ }
536
+ mountScreen(element, options) {
537
+ return this.#mount("screen", 0, (frame) => this.setScreenImage(frame, { ...options, fit: "fill" }), element, options);
538
+ }
539
+ async#mount(kind, index, send, element, options = {}) {
540
+ if (this.#closed)
541
+ throw new Error(`${this.model.name} is closed`);
542
+ const drawing = kind === "screen" ? { size: this.screenSize, scale: 1 } : this.slotDrawing(kind, index);
543
+ const pixels = drawing.scale === 1 ? drawing.size : {
544
+ width: Math.round(drawing.size.width * drawing.scale),
545
+ height: Math.round(drawing.size.height * drawing.scale)
546
+ };
547
+ const inner = await getElementRuntime().createRoot(pixels, send, {
548
+ ...drawing.scale !== 1 && { scale: drawing.scale },
549
+ ...options,
550
+ onError: options.onError ?? ((error) => this.emit("error", toError(error)))
551
+ });
552
+ const roots = this.#roots;
553
+ const root = {
554
+ render: (next) => inner.render(next),
555
+ idle: () => inner.idle(),
556
+ async unmount() {
557
+ roots.delete(root);
558
+ await inner.unmount();
559
+ }
560
+ };
561
+ roots.add(root);
562
+ try {
563
+ root.render(element);
564
+ await root.idle();
565
+ } catch (error) {
566
+ await root.unmount();
567
+ throw error;
568
+ }
569
+ return root;
570
+ }
571
+ async close() {
572
+ if (this.#closed)
573
+ return;
574
+ await Promise.all([...this.#roots].map((root) => root.unmount()));
575
+ this.#closed = true;
576
+ for (const stop of this.#unsubscribe)
577
+ stop();
578
+ try {
579
+ await this.enqueueUnchecked(() => this.onClosing());
580
+ } finally {
581
+ await this.transport.close();
582
+ }
583
+ }
584
+ assertKey(index) {
585
+ if (!Number.isInteger(index) || index < 0 || index >= this.keyCount) {
586
+ throw new RangeError(`key index must be 0–${this.keyCount - 1}, got ${index}`);
587
+ }
588
+ }
589
+ assertSensor(index) {
590
+ if (!Number.isInteger(index) || index < 0 || index >= this.sensorCount) {
591
+ throw new RangeError(`sensor index must be 0–${Math.max(0, this.sensorCount - 1)}, got ${index}`);
592
+ }
593
+ }
594
+ enqueue(task) {
595
+ if (this.#closed)
596
+ return Promise.reject(new Error(`${this.model.name} is closed`));
597
+ return this.enqueueUnchecked(task);
598
+ }
599
+ enqueueUnchecked(task) {
600
+ const run = this.#queue.then(task, task);
601
+ this.#queue = run.catch(() => {
602
+ return;
603
+ });
604
+ return run;
605
+ }
606
+ #handleInput(data) {
607
+ const states = this.parseInput(data);
608
+ if (!states)
609
+ return;
610
+ const keys = this.keyCount;
611
+ for (let i = 0;i < states.length; i++) {
612
+ const pressed = states[i] === true;
613
+ if (pressed === (this.#pressed[i] === true))
614
+ continue;
615
+ if (i < keys) {
616
+ this.emit(pressed ? "keyDown" : "keyUp", i);
617
+ } else {
618
+ this.emit(pressed ? "sensorDown" : "sensorUp", i - keys);
619
+ }
620
+ }
621
+ this.#pressed = states;
622
+ }
623
+ }
624
+ // ../core/src/detect.ts
625
+ import { devices, devicesAsync, HID } from "node-hid";
626
+
627
+ // ../core/src/transport.ts
628
+ function view2(data) {
629
+ return Buffer.from(data.buffer, data.byteOffset, data.byteLength);
630
+ }
631
+ function fromNodeHid(device) {
632
+ return {
633
+ async write(data) {
634
+ device.write(view2(data));
635
+ },
636
+ async sendFeatureReport(data) {
637
+ device.sendFeatureReport(view2(data));
638
+ },
639
+ async getFeatureReport(reportId, length) {
640
+ return Uint8Array.from(device.getFeatureReport(reportId, length));
641
+ },
642
+ onData(listener) {
643
+ device.on("data", listener);
644
+ return () => device.removeListener("data", listener);
645
+ },
646
+ onError(listener) {
647
+ device.on("error", listener);
648
+ return () => device.removeListener("error", listener);
649
+ },
650
+ async close() {
651
+ device.close();
652
+ }
653
+ };
654
+ }
655
+
656
+ // ../core/src/detect.ts
657
+ var nodeHid = {
658
+ devices: () => devices(),
659
+ devicesAsync: () => devicesAsync(),
660
+ HID
661
+ };
662
+ var asArray = (value) => Array.isArray(value) ? value : [value];
663
+ function findDecks(devices, drivers) {
664
+ const list = asArray(drivers);
665
+ const found = new Map;
666
+ for (const device of devices) {
667
+ const driver = list.find(({ model }) => model.vendorId === device.vendorId && model.productId === device.productId);
668
+ if (!driver || !device.path || found.has(device.path))
669
+ continue;
670
+ found.set(device.path, {
671
+ path: device.path,
672
+ serialNumber: device.serialNumber || undefined,
673
+ driver
674
+ });
675
+ }
676
+ return [...found.values()];
677
+ }
678
+ async function listDecks(drivers, options = {}) {
679
+ const hid = options.hid ?? nodeHid;
680
+ return findDecks(hid.devicesAsync ? await hid.devicesAsync() : hid.devices(), drivers);
681
+ }
682
+ function sleep(ms, signal) {
683
+ return new Promise((resolve, reject) => {
684
+ if (signal?.aborted)
685
+ return reject(signal.reason);
686
+ const onAbort = () => {
687
+ clearTimeout(timer);
688
+ reject(signal?.reason);
689
+ };
690
+ const timer = setTimeout(() => {
691
+ signal?.removeEventListener("abort", onAbort);
692
+ resolve();
693
+ }, ms);
694
+ signal?.addEventListener("abort", onAbort, { once: true });
695
+ });
696
+ }
697
+ async function tryOpen(hid, drivers, options) {
698
+ const match = (await listDecks(drivers, { hid })).find((deck) => (options.path === undefined || deck.path === options.path) && (options.serialNumber === undefined || deck.serialNumber === options.serialNumber));
699
+ return match?.driver.create(fromNodeHid(new hid.HID(match.path)));
700
+ }
701
+ async function openDeck(drivers, options = {}) {
702
+ const hid = options.hid ?? nodeHid;
703
+ const { wait = true, pollIntervalMs = 1000, timeoutMs = Number.POSITIVE_INFINITY } = options;
704
+ const { signal } = options;
705
+ const deadline = Date.now() + timeoutMs;
706
+ let lastError;
707
+ for (;; ) {
708
+ signal?.throwIfAborted();
709
+ try {
710
+ const deck = await tryOpen(hid, drivers, options);
711
+ if (deck)
712
+ return deck;
713
+ lastError = undefined;
714
+ } catch (error) {
715
+ lastError = error;
716
+ }
717
+ const remaining = deadline - Date.now();
718
+ if (!wait || remaining <= 0)
719
+ break;
720
+ await sleep(Math.min(pollIntervalMs, remaining), signal);
721
+ }
722
+ const names = asArray(drivers).map(({ model }) => model.name).join(" or ");
723
+ const filtered = options.path !== undefined || options.serialNumber !== undefined;
724
+ throw new Error(`No ${names} found${filtered ? " matching the given path/serialNumber" : ""}`, {
725
+ cause: lastError
726
+ });
727
+ }
728
+ // ../core/src/manager.ts
729
+ var withTimeout = (promise, ms) => new Promise((resolve, reject) => {
730
+ const timer = setTimeout(() => reject(new Error(`no answer from the deck in ${ms} ms`)), ms);
731
+ promise.then((value) => {
732
+ clearTimeout(timer);
733
+ resolve(value);
734
+ }, (error) => {
735
+ clearTimeout(timer);
736
+ reject(error);
737
+ });
738
+ });
739
+ var pause = (ms, signal) => new Promise((resolve) => {
740
+ const done = () => {
741
+ clearTimeout(timer);
742
+ signal.removeEventListener("abort", done);
743
+ resolve();
744
+ };
745
+ const timer = setTimeout(done, ms);
746
+ signal.addEventListener("abort", done, { once: true });
747
+ });
748
+ function watchDeck(deck, options = {}) {
749
+ const { heartbeatMs = 3000, timeoutMs = 2000 } = options;
750
+ let markLost = () => {};
751
+ const lost = new Promise((resolve) => {
752
+ markLost = resolve;
753
+ });
754
+ let running = false;
755
+ const probe = async () => {
756
+ if (running)
757
+ return;
758
+ running = true;
759
+ try {
760
+ await withTimeout(deck.ping(), timeoutMs);
761
+ } catch (error) {
762
+ markLost(toError(error));
763
+ } finally {
764
+ running = false;
765
+ }
766
+ };
767
+ const stops = [
768
+ deck.on("error", (error) => {
769
+ options.onError?.(error);
770
+ probe();
771
+ })
772
+ ];
773
+ if (heartbeatMs > 0) {
774
+ const timer = setInterval(() => void probe(), heartbeatMs);
775
+ stops.push(() => clearInterval(timer));
776
+ }
777
+ return {
778
+ lost,
779
+ stop() {
780
+ for (const stop of stops.splice(0))
781
+ stop();
782
+ }
783
+ };
784
+ }
785
+ function manageDeck(options) {
786
+ const { reconnect = true, retryMs = 1000 } = options;
787
+ const controller = new AbortController;
788
+ const { signal } = controller;
789
+ if (options.signal?.aborted)
790
+ controller.abort();
791
+ else
792
+ options.signal?.addEventListener("abort", () => controller.abort(), { once: true });
793
+ let status = "waiting";
794
+ let current;
795
+ const setStatus = (next, deck) => {
796
+ status = next;
797
+ current = deck;
798
+ options.onStatus?.(next, deck);
799
+ };
800
+ const report = (error) => options.onError?.(toError(error));
801
+ const release = (deck) => withTimeout(deck.close(), 2000).catch(() => {});
802
+ const finished = (async () => {
803
+ while (!signal.aborted) {
804
+ setStatus("waiting");
805
+ let deck;
806
+ let cleanup;
807
+ try {
808
+ deck = await options.open(signal);
809
+ cleanup = await options.setup?.(deck, signal);
810
+ } catch (error) {
811
+ if (deck)
812
+ await release(deck);
813
+ if (signal.aborted)
814
+ break;
815
+ report(error);
816
+ await pause(retryMs, signal);
817
+ continue;
818
+ }
819
+ const watch = watchDeck(deck, {
820
+ ...options.heartbeatMs !== undefined && { heartbeatMs: options.heartbeatMs },
821
+ ...options.timeoutMs !== undefined && { timeoutMs: options.timeoutMs },
822
+ onError: report
823
+ });
824
+ setStatus("connected", deck);
825
+ const aborted = new Promise((resolve) => {
826
+ if (signal.aborted)
827
+ resolve(undefined);
828
+ else
829
+ signal.addEventListener("abort", () => resolve(undefined), { once: true });
830
+ });
831
+ const cause = await Promise.race([watch.lost, aborted]);
832
+ watch.stop();
833
+ try {
834
+ await cleanup?.();
835
+ } catch (error) {
836
+ report(error);
837
+ }
838
+ await release(deck);
839
+ if (cause)
840
+ report(cause);
841
+ if (!reconnect)
842
+ break;
843
+ }
844
+ setStatus("stopped");
845
+ })();
846
+ return {
847
+ get status() {
848
+ return status;
849
+ },
850
+ get deck() {
851
+ return current;
852
+ },
853
+ stop: async () => {
854
+ controller.abort();
855
+ await finished;
856
+ },
857
+ finished
858
+ };
859
+ }
860
+ // ../neo/src/protocol.ts
861
+ var ELGATO_VENDOR_ID = 4057;
862
+ var STREAM_DECK_NEO_PRODUCT_ID = 154;
863
+ var OUTPUT_REPORT_SIZE = 1024;
864
+ var FEATURE_REPORT_SIZE = 32;
865
+ var INPUT_REPORT_ID = 1;
866
+ var OUTPUT_REPORT_ID = 2;
867
+ var SETTER_REPORT_ID = 3;
868
+ var GetterReportId = {
869
+ FirmwareLd: 4,
870
+ FirmwareAp2: 5,
871
+ SerialNumber: 6,
872
+ FirmwareAp1: 7,
873
+ UnitInformation: 8,
874
+ SleepDuration: 10
875
+ };
876
+ var SetterCommand = {
877
+ ShowLogo: 2,
878
+ FillLcd: 5,
879
+ FillKey: 6,
880
+ Brightness: 8,
881
+ SleepDuration: 13
882
+ };
883
+ var OutputCommand = {
884
+ ButtonImage: 7,
885
+ FullScreenImage: 8,
886
+ WindowImage: 11,
887
+ PartialWindowImage: 12
888
+ };
889
+ function assertUint(name, value, max) {
890
+ if (!Number.isInteger(value) || value < 0 || value > max) {
891
+ throw new RangeError(`${name} must be an integer between 0 and ${max}, got ${value}`);
892
+ }
893
+ }
894
+ function assertRgb([r, g, b]) {
895
+ assertUint("red", r, 255);
896
+ assertUint("green", g, 255);
897
+ assertUint("blue", b, 255);
898
+ }
899
+ function byteAt(data, offset) {
900
+ return data[offset] ?? 0;
901
+ }
902
+ function u16At(data, offset) {
903
+ return byteAt(data, offset) | byteAt(data, offset + 1) << 8;
904
+ }
905
+ function u32At(data, offset) {
906
+ return (u16At(data, offset) | u16At(data, offset + 2) << 16) >>> 0;
907
+ }
908
+ function i32At(data, offset) {
909
+ return u32At(data, offset) | 0;
910
+ }
911
+ function asciiString(data) {
912
+ let end = data.length;
913
+ const nul = data.indexOf(0);
914
+ if (nul !== -1)
915
+ end = nul;
916
+ let out = "";
917
+ for (let i = 0;i < end; i++)
918
+ out += String.fromCharCode(byteAt(data, i));
919
+ return out;
920
+ }
921
+ function featureReport(command, ...payload) {
922
+ const report = new Uint8Array(FEATURE_REPORT_SIZE);
923
+ report[0] = SETTER_REPORT_ID;
924
+ report[1] = command;
925
+ report.set(payload, 2);
926
+ return report;
927
+ }
928
+ function showLogoReport() {
929
+ return featureReport(SetterCommand.ShowLogo);
930
+ }
931
+ function fillLcdReport(color) {
932
+ assertRgb(color);
933
+ return featureReport(SetterCommand.FillLcd, ...color);
934
+ }
935
+ function fillKeyReport(index, color) {
936
+ assertUint("key index", index, 255);
937
+ assertRgb(color);
938
+ return featureReport(SetterCommand.FillKey, index, ...color);
939
+ }
940
+ function brightnessReport(percent) {
941
+ assertUint("brightness", percent, 100);
942
+ return featureReport(SetterCommand.Brightness, percent);
943
+ }
944
+ function sleepDurationReport(seconds) {
945
+ assertUint("sleep duration", seconds, 2147483647);
946
+ return featureReport(SetterCommand.SleepDuration, seconds & 255, seconds >>> 8 & 255, seconds >>> 16 & 255, seconds >>> 24 & 255);
947
+ }
948
+ function parseFirmwareVersion(report) {
949
+ return {
950
+ checksum: u32At(report, 2),
951
+ version: asciiString(report.subarray(6, 14))
952
+ };
953
+ }
954
+ function parseSerialNumber(report) {
955
+ const length = byteAt(report, 1);
956
+ return asciiString(report.subarray(2, 2 + length));
957
+ }
958
+ function parseSleepDuration(report) {
959
+ return i32At(report, 2);
960
+ }
961
+ function parseUnitInformation(report) {
962
+ if (report.length < 15) {
963
+ throw new RangeError(`unit information report too short: ${report.length} bytes`);
964
+ }
965
+ return {
966
+ keyRows: byteAt(report, 1),
967
+ keyColumns: byteAt(report, 2),
968
+ keyWidth: u16At(report, 3),
969
+ keyHeight: u16At(report, 5),
970
+ lcdWidth: u16At(report, 7),
971
+ lcdHeight: u16At(report, 9),
972
+ imageBitsPerPixel: byteAt(report, 11),
973
+ imageColorScheme: byteAt(report, 12),
974
+ galleryKeyImages: byteAt(report, 13),
975
+ galleryLcdImages: byteAt(report, 14),
976
+ demoFrames: byteAt(report, 15)
977
+ };
978
+ }
979
+ function chunkedImagePackets(image, headerSize, writeHeader) {
980
+ if (image.length === 0)
981
+ throw new RangeError("image data is empty");
982
+ const maxChunk = OUTPUT_REPORT_SIZE - headerSize;
983
+ const packets = [];
984
+ for (let offset = 0, index = 0;offset < image.length; offset += maxChunk, index++) {
985
+ const chunk = image.subarray(offset, offset + maxChunk);
986
+ const isLast = offset + maxChunk >= image.length;
987
+ if (index > 65535)
988
+ throw new RangeError("image is too large");
989
+ const packet = new Uint8Array(OUTPUT_REPORT_SIZE);
990
+ packet[0] = OUTPUT_REPORT_ID;
991
+ writeHeader(packet, index, chunk.length, isLast);
992
+ packet.set(chunk, headerSize);
993
+ packets.push(packet);
994
+ }
995
+ return packets;
996
+ }
997
+ function standardImagePackets(command, byte2, image) {
998
+ return chunkedImagePackets(image, 8, (packet, index, size, isLast) => {
999
+ packet[1] = command;
1000
+ packet[2] = byte2;
1001
+ packet[3] = isLast ? 1 : 0;
1002
+ packet[4] = size & 255;
1003
+ packet[5] = size >>> 8;
1004
+ packet[6] = index & 255;
1005
+ packet[7] = index >>> 8;
1006
+ });
1007
+ }
1008
+ function buttonImagePackets(index, jpeg) {
1009
+ assertUint("key index", index, 255);
1010
+ return standardImagePackets(OutputCommand.ButtonImage, index, jpeg);
1011
+ }
1012
+ function fullScreenImagePackets(jpeg) {
1013
+ return standardImagePackets(OutputCommand.FullScreenImage, 0, jpeg);
1014
+ }
1015
+ function windowImagePackets(jpeg) {
1016
+ return standardImagePackets(OutputCommand.WindowImage, 0, jpeg);
1017
+ }
1018
+ function partialWindowImagePackets(region, jpeg) {
1019
+ assertUint("x", region.x, 65535);
1020
+ assertUint("y", region.y, 65535);
1021
+ assertUint("width", region.width, 65535);
1022
+ assertUint("height", region.height, 65535);
1023
+ return chunkedImagePackets(jpeg, 16, (packet, index, size, isLast) => {
1024
+ packet[1] = OutputCommand.PartialWindowImage;
1025
+ packet[2] = region.x & 255;
1026
+ packet[3] = region.x >>> 8;
1027
+ packet[4] = region.y & 255;
1028
+ packet[5] = region.y >>> 8;
1029
+ packet[6] = region.width & 255;
1030
+ packet[7] = region.width >>> 8;
1031
+ packet[8] = region.height & 255;
1032
+ packet[9] = region.height >>> 8;
1033
+ packet[10] = isLast ? 1 : 0;
1034
+ packet[11] = index & 255;
1035
+ packet[12] = index >>> 8;
1036
+ packet[13] = size & 255;
1037
+ packet[14] = size >>> 8;
1038
+ packet[15] = 0;
1039
+ });
1040
+ }
1041
+ function parseInputReport(data) {
1042
+ if (data.length < 4 || data[0] !== INPUT_REPORT_ID || data[1] !== 0)
1043
+ return null;
1044
+ const count = Math.min(u16At(data, 2), data.length - 4);
1045
+ const states = [];
1046
+ for (let i = 0;i < count; i++)
1047
+ states.push(byteAt(data, 4 + i) === 1);
1048
+ return states;
1049
+ }
1050
+
1051
+ // ../neo/src/model.ts
1052
+ var NEO_LAYOUT = {
1053
+ screen: { width: 480, height: 320 },
1054
+ keys: Array.from({ length: 8 }, (_, i) => ({
1055
+ x: 3 + i % 4 * 126,
1056
+ y: 9 + Math.floor(i / 4) * 126,
1057
+ width: 96,
1058
+ height: 96
1059
+ })),
1060
+ sensors: [
1061
+ { x: 3, y: 283, width: 96, height: 16 },
1062
+ { x: 381, y: 283, width: 96, height: 16 }
1063
+ ],
1064
+ window: { x: 116, y: 262, width: 248, height: 58 }
1065
+ };
1066
+ var NEO_MODEL = {
1067
+ id: "neo",
1068
+ name: "Stream Deck Neo",
1069
+ vendorId: ELGATO_VENDOR_ID,
1070
+ productId: STREAM_DECK_NEO_PRODUCT_ID,
1071
+ layout: NEO_LAYOUT,
1072
+ rotation: 180
1073
+ };
1074
+
1075
+ // ../neo/src/neo.ts
1076
+ var FIRMWARE_REPORT_IDS = {
1077
+ ld: GetterReportId.FirmwareLd,
1078
+ ap1: GetterReportId.FirmwareAp1,
1079
+ ap2: GetterReportId.FirmwareAp2
1080
+ };
1081
+
1082
+ class StreamDeckNeo extends StreamDeck {
1083
+ static KEY_COUNT = 8;
1084
+ static SENSOR_COUNT = 2;
1085
+ static KEY_SIZE = { width: 96, height: 96 };
1086
+ static SCREEN_SIZE = { width: 480, height: 320 };
1087
+ static WINDOW_SIZE = { width: 248, height: 58 };
1088
+ static SENSOR_SIZE = { width: 96, height: 16 };
1089
+ constructor(transport) {
1090
+ super(transport, NEO_MODEL);
1091
+ }
1092
+ parseInput(data) {
1093
+ return parseInputReport(data) ?? undefined;
1094
+ }
1095
+ sendKeyJpeg(index, jpeg) {
1096
+ return this.#write(buttonImagePackets(index, jpeg));
1097
+ }
1098
+ sendScreenJpeg(jpeg) {
1099
+ return this.#write(fullScreenImagePackets(jpeg));
1100
+ }
1101
+ sendWindowJpeg(jpeg) {
1102
+ return this.#write(windowImagePackets(jpeg));
1103
+ }
1104
+ sendWindowRegionJpeg(region, jpeg) {
1105
+ return this.#write(partialWindowImagePackets(region, jpeg));
1106
+ }
1107
+ sendFillKey(index, color) {
1108
+ return this.transport.sendFeatureReport(fillKeyReport(index, color));
1109
+ }
1110
+ sendFillScreen(color) {
1111
+ return this.transport.sendFeatureReport(fillLcdReport(color));
1112
+ }
1113
+ async onClosing() {
1114
+ await this.transport.sendFeatureReport(showLogoReport());
1115
+ }
1116
+ setBrightness(percent) {
1117
+ return this.#feature(brightnessReport(percent));
1118
+ }
1119
+ showLogo() {
1120
+ return this.#feature(showLogoReport());
1121
+ }
1122
+ setSleepDuration(seconds) {
1123
+ return this.#feature(sleepDurationReport(seconds));
1124
+ }
1125
+ async getSleepDuration() {
1126
+ return parseSleepDuration(await this.#getFeature(GetterReportId.SleepDuration));
1127
+ }
1128
+ async getFirmwareVersion(kind = "ap2") {
1129
+ return parseFirmwareVersion(await this.#getFeature(FIRMWARE_REPORT_IDS[kind]));
1130
+ }
1131
+ async getSerialNumber() {
1132
+ return parseSerialNumber(await this.#getFeature(GetterReportId.SerialNumber));
1133
+ }
1134
+ async getUnitInformation() {
1135
+ return parseUnitInformation(await this.#getFeature(GetterReportId.UnitInformation));
1136
+ }
1137
+ #feature(report) {
1138
+ return this.enqueue(() => this.transport.sendFeatureReport(report));
1139
+ }
1140
+ #getFeature(reportId) {
1141
+ return this.enqueue(() => this.transport.getFeatureReport(reportId, FEATURE_REPORT_SIZE));
1142
+ }
1143
+ async#write(packets) {
1144
+ for (const packet of packets)
1145
+ await this.transport.write(packet);
1146
+ }
1147
+ }
1148
+ var neoDriver = {
1149
+ model: NEO_MODEL,
1150
+ create: (transport) => new StreamDeckNeo(transport)
1151
+ };
1152
+
1153
+ // ../neo/src/detect.ts
1154
+ function openStreamDeckNeo(options = {}) {
1155
+ return openDeck(neoDriver, options);
1156
+ }
1157
+ // ../react/src/render.ts
1158
+ function isReactElement(value) {
1159
+ return typeof value === "object" && value !== null && "$$typeof" in value;
1160
+ }
1161
+ var defaultRenderer = {};
1162
+ var fontRenderers = new WeakMap;
1163
+ async function createRenderer(fonts) {
1164
+ const { Renderer } = await import("@takumi-rs/core");
1165
+ const renderer = new Renderer;
1166
+ for (const font of fonts) {
1167
+ await renderer.registerFont({
1168
+ name: font.name,
1169
+ data: font.data,
1170
+ ...font.weight !== undefined && { weight: font.weight },
1171
+ ...font.style !== undefined && { style: font.style }
1172
+ });
1173
+ }
1174
+ return renderer;
1175
+ }
1176
+ function getRenderer(fonts) {
1177
+ if (!fonts?.length) {
1178
+ defaultRenderer.current ??= createRenderer([]);
1179
+ defaultRenderer.current.catch(() => {
1180
+ defaultRenderer.current = undefined;
1181
+ });
1182
+ return defaultRenderer.current;
1183
+ }
1184
+ let renderer = fontRenderers.get(fonts);
1185
+ if (!renderer) {
1186
+ renderer = createRenderer(fonts);
1187
+ renderer.catch(() => fontRenderers.delete(fonts));
1188
+ fontRenderers.set(fonts, renderer);
1189
+ }
1190
+ return renderer;
1191
+ }
1192
+ var number = (value) => typeof value === "number" && Number.isFinite(value) ? value : undefined;
1193
+ function toNode(node, text = true) {
1194
+ if ("text" in node) {
1195
+ return text ? { type: "text", text: node.text } : { type: "container", children: [] };
1196
+ }
1197
+ const { style, tw, src, width, height } = node.props;
1198
+ const common = {
1199
+ ...typeof tw === "string" && { tw }
1200
+ };
1201
+ if (node.type === "img") {
1202
+ if (typeof src !== "string")
1203
+ throw new Error("<img> needs a string `src` (URL or data: URI)");
1204
+ return {
1205
+ type: "image",
1206
+ src,
1207
+ ...number(width) !== undefined && { width: number(width) },
1208
+ ...number(height) !== undefined && { height: number(height) },
1209
+ ...typeof style === "object" && style !== null && { style },
1210
+ ...common
1211
+ };
1212
+ }
1213
+ return {
1214
+ type: "container",
1215
+ style: { display: "flex", ...typeof style === "object" ? style : {} },
1216
+ children: node.children.filter((child) => text || !("text" in child)).map((child) => toNode(child, text)),
1217
+ ...common
1218
+ };
1219
+ }
1220
+ var reconciler;
1221
+ var flushing = 0;
1222
+ function flushAll(renderer) {
1223
+ flushing++;
1224
+ try {
1225
+ renderer.flushSyncWork();
1226
+ for (let i = 0;i < 20 && renderer.flushPassiveEffects(); i++)
1227
+ renderer.flushSyncWork();
1228
+ } finally {
1229
+ flushing--;
1230
+ }
1231
+ }
1232
+ function loadReconciler() {
1233
+ reconciler ??= (async () => {
1234
+ let factoryModule;
1235
+ let constants;
1236
+ let React;
1237
+ try {
1238
+ [factoryModule, constants, React] = await Promise.all([
1239
+ import("react-reconciler"),
1240
+ import("react-reconciler/constants.js"),
1241
+ import("react")
1242
+ ]);
1243
+ } catch (cause) {
1244
+ throw new Error("Rendering React elements requires `react` (>=19.3) to be installed", {
1245
+ cause
1246
+ });
1247
+ }
1248
+ let priority = constants.NoEventPriority;
1249
+ const noop = () => {};
1250
+ const hostConfig = {
1251
+ supportsMutation: true,
1252
+ supportsPersistence: false,
1253
+ supportsHydration: false,
1254
+ isPrimaryRenderer: true,
1255
+ warnsIfNotActing: false,
1256
+ noTimeout: -1,
1257
+ scheduleTimeout: setTimeout,
1258
+ cancelTimeout: clearTimeout,
1259
+ supportsMicrotasks: true,
1260
+ scheduleMicrotask: queueMicrotask,
1261
+ createInstance: (type, props) => {
1262
+ const { children: _children, ...rest } = props;
1263
+ return { type, props: rest, children: [] };
1264
+ },
1265
+ createTextInstance: (text) => ({ text }),
1266
+ shouldSetTextContent: () => false,
1267
+ appendInitialChild: (parent, child) => parent.children.push(child),
1268
+ appendChild: (parent, child) => parent.children.push(child),
1269
+ appendChildToContainer: (container, child) => container.children.push(child),
1270
+ insertBefore: (parent, child, before) => {
1271
+ const children = parent.children;
1272
+ const existing = children.indexOf(child);
1273
+ if (existing !== -1)
1274
+ children.splice(existing, 1);
1275
+ children.splice(children.indexOf(before), 0, child);
1276
+ },
1277
+ insertInContainerBefore: (container, child, before) => {
1278
+ const children = container.children;
1279
+ const existing = children.indexOf(child);
1280
+ if (existing !== -1)
1281
+ children.splice(existing, 1);
1282
+ children.splice(children.indexOf(before), 0, child);
1283
+ },
1284
+ removeChild: (parent, child) => {
1285
+ parent.children.splice(parent.children.indexOf(child), 1);
1286
+ },
1287
+ removeChildFromContainer: (container, child) => {
1288
+ container.children.splice(container.children.indexOf(child), 1);
1289
+ },
1290
+ clearContainer: (container) => {
1291
+ container.children = [];
1292
+ },
1293
+ commitUpdate: (instance, _type, _prev, next) => {
1294
+ const { children: _children, ...rest } = next;
1295
+ instance.props = rest;
1296
+ },
1297
+ commitTextUpdate: (text, _old, next) => {
1298
+ text.text = next;
1299
+ },
1300
+ finalizeInitialChildren: () => false,
1301
+ getPublicInstance: (instance) => instance,
1302
+ getRootHostContext: () => ({}),
1303
+ getChildHostContext: (parent) => parent,
1304
+ prepareForCommit: () => null,
1305
+ resetAfterCommit: (container) => container.onCommit(),
1306
+ preparePortalMount: noop,
1307
+ detachDeletedInstance: noop,
1308
+ hideInstance: noop,
1309
+ unhideInstance: noop,
1310
+ hideTextInstance: noop,
1311
+ unhideTextInstance: noop,
1312
+ getInstanceFromNode: () => null,
1313
+ beforeActiveInstanceBlur: noop,
1314
+ afterActiveInstanceBlur: noop,
1315
+ prepareScopeUpdate: noop,
1316
+ getInstanceFromScope: () => null,
1317
+ bindToConsole: (method, args) => console[method]?.bind(console, ...args) ?? noop,
1318
+ extraDevToolsConfig: null,
1319
+ rendererVersion: "0.0.0",
1320
+ rendererPackageName: "sdeck",
1321
+ getCurrentUpdatePriority: () => priority,
1322
+ setCurrentUpdatePriority: (next) => {
1323
+ priority = next;
1324
+ },
1325
+ resolveUpdatePriority: () => priority !== constants.NoEventPriority ? priority : flushing > 0 ? constants.DiscreteEventPriority : constants.DefaultEventPriority,
1326
+ resolveEventType: () => null,
1327
+ resolveEventTimeStamp: () => -1.1,
1328
+ shouldAttemptEagerTransition: () => false,
1329
+ trackSchedulerEvent: noop,
1330
+ requestPostPaintCallback: noop,
1331
+ maySuspendCommit: () => false,
1332
+ preloadInstance: () => true,
1333
+ startSuspendingCommit: noop,
1334
+ suspendInstance: noop,
1335
+ waitForCommitToBeReady: () => null,
1336
+ getSuspendedCommitReason: () => null,
1337
+ NotPendingTransition: null,
1338
+ HostTransitionContext: React.createContext(null),
1339
+ resetFormInstance: noop
1340
+ };
1341
+ const factory = factoryModule.default ?? factoryModule;
1342
+ return factory(hostConfig);
1343
+ })();
1344
+ reconciler.catch(() => {
1345
+ reconciler = undefined;
1346
+ });
1347
+ return reconciler;
1348
+ }
1349
+ function noopIndicator() {}
1350
+ async function createReactRoot(size, onFrame, options = {}) {
1351
+ const [takumi, renderer] = await Promise.all([getRenderer(options.fonts), loadReconciler()]);
1352
+ let dirty = false;
1353
+ let drawing;
1354
+ let lastTree;
1355
+ let unmounted = false;
1356
+ let renderError;
1357
+ let initial = true;
1358
+ const fail = (error) => {
1359
+ if (initial)
1360
+ renderError ??= { error };
1361
+ else
1362
+ (options.onError ?? ((e) => console.error("sdeck: React render failed:", e)))(error);
1363
+ };
1364
+ async function draw() {
1365
+ await Promise.resolve();
1366
+ while (dirty && !unmounted) {
1367
+ dirty = false;
1368
+ try {
1369
+ const [root] = container.children;
1370
+ if (!root)
1371
+ continue;
1372
+ const tree = toNode(root, options.text !== false);
1373
+ const key = JSON.stringify(tree);
1374
+ if (key === lastTree)
1375
+ continue;
1376
+ lastTree = key;
1377
+ const pixels = await takumi.render(tree, {
1378
+ width: size.width,
1379
+ height: size.height,
1380
+ format: "raw",
1381
+ ...options.scale !== undefined && { devicePixelRatio: options.scale }
1382
+ });
1383
+ await onFrame({
1384
+ data: new Uint8Array(pixels.buffer, pixels.byteOffset, pixels.byteLength),
1385
+ width: size.width,
1386
+ height: size.height,
1387
+ channels: 4
1388
+ });
1389
+ } catch (error) {
1390
+ lastTree = undefined;
1391
+ fail(error);
1392
+ }
1393
+ }
1394
+ drawing = undefined;
1395
+ }
1396
+ const container = {
1397
+ children: [],
1398
+ onCommit() {
1399
+ dirty = true;
1400
+ drawing ??= draw();
1401
+ }
1402
+ };
1403
+ const onError = (error) => fail(error);
1404
+ const onCaughtError = () => {};
1405
+ const root = renderer.createContainer(container, 1, null, false, null, "", onError, onCaughtError, onError, noopIndicator, null);
1406
+ const flush = () => flushAll(renderer);
1407
+ const handle = {
1408
+ render(element) {
1409
+ if (unmounted)
1410
+ throw new Error("This React root was unmounted");
1411
+ renderer.updateContainerSync(element, root, null, null);
1412
+ flush();
1413
+ },
1414
+ async idle() {
1415
+ while (drawing)
1416
+ await drawing;
1417
+ if (initial && renderError) {
1418
+ const { error } = renderError;
1419
+ renderError = undefined;
1420
+ throw error;
1421
+ }
1422
+ initial = false;
1423
+ },
1424
+ async unmount() {
1425
+ if (unmounted)
1426
+ return;
1427
+ renderer.updateContainerSync(null, root, null, null);
1428
+ flush();
1429
+ unmounted = true;
1430
+ await drawing;
1431
+ }
1432
+ };
1433
+ return handle;
1434
+ }
1435
+ async function renderReact(element, size, fonts, scale) {
1436
+ let frame;
1437
+ const root = await createReactRoot(size, (next) => {
1438
+ frame = next;
1439
+ }, { ...fonts && { fonts }, ...scale !== undefined && { scale } });
1440
+ try {
1441
+ root.render(element);
1442
+ await root.idle();
1443
+ } finally {
1444
+ await root.unmount();
1445
+ }
1446
+ if (!frame)
1447
+ throw new Error("React element rendered nothing");
1448
+ return frame;
1449
+ }
1450
+ registerElementRuntime({
1451
+ matches: isReactElement,
1452
+ render: (element, size, options) => renderReact(element, size, options?.fonts),
1453
+ createRoot: (size, onFrame, options) => createReactRoot(size, onFrame, options)
1454
+ });
1455
+ // ../app/src/app.tsx
1456
+ import { Fragment, useSyncExternalStore } from "react";
1457
+
1458
+ // ../app/src/context.ts
1459
+ import { createContext, useContext } from "react";
1460
+ var DeckContext = createContext(undefined);
1461
+ var SlotContext = createContext(undefined);
1462
+ var NavigatorContext = createContext(undefined);
1463
+ function useDeck() {
1464
+ const deck = useContext(DeckContext);
1465
+ if (!deck)
1466
+ throw new Error("useDeck() must be used inside a component mounted by @sdeck/app");
1467
+ return deck;
1468
+ }
1469
+ function useSlot() {
1470
+ return useContext(SlotContext);
1471
+ }
1472
+
1473
+ // ../app/src/navigator.ts
1474
+ class Navigator {
1475
+ #initial;
1476
+ #has;
1477
+ #listeners = new Set;
1478
+ #state;
1479
+ pages;
1480
+ sequence;
1481
+ constructor(initial, has, pages = [], sequence = pages) {
1482
+ this.#initial = initial;
1483
+ this.#has = has;
1484
+ this.pages = pages;
1485
+ this.sequence = sequence;
1486
+ this.#state = { page: initial, stack: [initial], forwardStack: [] };
1487
+ }
1488
+ getSnapshot = () => this.#state;
1489
+ subscribe = (listener) => {
1490
+ this.#listeners.add(listener);
1491
+ return () => void this.#listeners.delete(listener);
1492
+ };
1493
+ get page() {
1494
+ return this.#state.page;
1495
+ }
1496
+ push = (page) => {
1497
+ this.#assert(page);
1498
+ if (page === this.#state.page)
1499
+ return;
1500
+ this.#set([...this.#state.stack, page], []);
1501
+ };
1502
+ replace = (page) => {
1503
+ this.#assert(page);
1504
+ if (page === this.#state.page)
1505
+ return;
1506
+ this.#set([...this.#state.stack.slice(0, -1), page], []);
1507
+ };
1508
+ back = () => {
1509
+ const { stack, page, forwardStack } = this.#state;
1510
+ if (stack.length < 2)
1511
+ return false;
1512
+ this.#set(stack.slice(0, -1), [page, ...forwardStack]);
1513
+ return true;
1514
+ };
1515
+ forward = () => {
1516
+ const [next, ...rest] = this.#state.forwardStack;
1517
+ if (next === undefined)
1518
+ return false;
1519
+ this.#set([...this.#state.stack, next], rest);
1520
+ return true;
1521
+ };
1522
+ next = (wrap = false) => this.#step(1, wrap);
1523
+ previous = (wrap = false) => this.#step(-1, wrap);
1524
+ #step(by, wrap) {
1525
+ const order = this.sequence;
1526
+ const n = order.length;
1527
+ const i = order.indexOf(this.#state.page);
1528
+ if (i === -1 || n < 2)
1529
+ return false;
1530
+ let j = i + by;
1531
+ if (j < 0 || j >= n) {
1532
+ if (!wrap)
1533
+ return false;
1534
+ j = (j + n) % n;
1535
+ }
1536
+ this.push(order[j]);
1537
+ return true;
1538
+ }
1539
+ home = () => {
1540
+ const { stack, page, forwardStack } = this.#state;
1541
+ if (stack.length === 1 && page === this.#initial && forwardStack.length === 0)
1542
+ return;
1543
+ this.#set([this.#initial], []);
1544
+ };
1545
+ #assert(page) {
1546
+ if (!this.#has(page))
1547
+ throw new RangeError(`unknown page "${page}"`);
1548
+ }
1549
+ #set(stack, forwardStack) {
1550
+ this.#state = { page: stack.at(-1), stack, forwardStack };
1551
+ for (const listener of [...this.#listeners])
1552
+ listener();
1553
+ }
1554
+ }
1555
+
1556
+ // ../app/src/app.tsx
1557
+ import { jsx } from "react/jsx-runtime";
1558
+ function defineApp(app) {
1559
+ const names = Object.keys(app.pages);
1560
+ if (names.length === 0)
1561
+ throw new RangeError("an app needs at least one page");
1562
+ if (app.initial !== undefined && !(app.initial in app.pages)) {
1563
+ throw new RangeError(`initial page "${app.initial}" is not defined`);
1564
+ }
1565
+ for (const [name, page] of Object.entries(app.pages)) {
1566
+ const indices = Array.isArray(page.keys) ? page.keys.length > 0 ? [page.keys.length - 1] : [] : Object.keys(page.keys ?? {}).map(Number);
1567
+ for (const index of indices) {
1568
+ if (!Number.isInteger(index) || index < 0) {
1569
+ throw new RangeError(`page "${name}": key index must be a non-negative integer, got ${index}`);
1570
+ }
1571
+ }
1572
+ }
1573
+ return app;
1574
+ }
1575
+ function createNavigator(app) {
1576
+ const initial = app.initial ?? Object.keys(app.pages)[0];
1577
+ const pages = Object.keys(app.pages);
1578
+ const sequence = app.sequence?.filter((page) => Object.hasOwn(app.pages, page)) ?? pages;
1579
+ return new Navigator(initial, (page) => Object.hasOwn(app.pages, page), pages, sequence);
1580
+ }
1581
+ function Blank({ background }) {
1582
+ return /* @__PURE__ */ jsx("div", {
1583
+ style: { display: "flex", width: "100%", height: "100%", background }
1584
+ });
1585
+ }
1586
+ function PageSlot({
1587
+ app,
1588
+ nav,
1589
+ pick
1590
+ }) {
1591
+ const { page } = useSyncExternalStore(nav.subscribe, nav.getSnapshot);
1592
+ const content = pick(app.pages[page] ?? {});
1593
+ return /* @__PURE__ */ jsx(Fragment, {
1594
+ children: content ?? /* @__PURE__ */ jsx(Blank, {
1595
+ background: app.background ?? "#000000"
1596
+ })
1597
+ }, page);
1598
+ }
1599
+ function Providers({
1600
+ deck,
1601
+ nav,
1602
+ slot,
1603
+ children
1604
+ }) {
1605
+ return /* @__PURE__ */ jsx(DeckContext.Provider, {
1606
+ value: deck,
1607
+ children: /* @__PURE__ */ jsx(NavigatorContext.Provider, {
1608
+ value: nav,
1609
+ children: /* @__PURE__ */ jsx(SlotContext.Provider, {
1610
+ value: slot,
1611
+ children
1612
+ })
1613
+ })
1614
+ });
1615
+ }
1616
+ async function mountApp(deck, app, options = {}) {
1617
+ const nav = options.navigation ?? createNavigator(app);
1618
+ const { heartbeatMs = 3000 } = options;
1619
+ const cleanups = [];
1620
+ const roots = [];
1621
+ const report = (error) => options.onError?.(toError(error));
1622
+ const watch = watchDeck(deck, { heartbeatMs, onError: report });
1623
+ const lost = watch.lost;
1624
+ cleanups.push(() => watch.stop());
1625
+ const dispose = async () => {
1626
+ for (const cleanup of cleanups.splice(0))
1627
+ cleanup();
1628
+ await deck.close().catch(() => {});
1629
+ };
1630
+ try {
1631
+ if (app.brightness !== undefined)
1632
+ await deck.setBrightness(app.brightness);
1633
+ if (app.sleepSeconds !== undefined) {
1634
+ const sleepable = deck;
1635
+ await sleepable.setSleepDuration?.(app.sleepSeconds);
1636
+ }
1637
+ await app.onConnect?.(deck);
1638
+ if (app.idle) {
1639
+ const { afterMs, brightness: dimmed = 5 } = app.idle;
1640
+ const awake = app.brightness ?? 100;
1641
+ let dim;
1642
+ let isDim = false;
1643
+ const arm = () => {
1644
+ clearTimeout(dim);
1645
+ dim = setTimeout(() => {
1646
+ isDim = true;
1647
+ deck.setBrightness(dimmed).catch(report);
1648
+ }, afterMs);
1649
+ };
1650
+ const wake = () => {
1651
+ if (isDim) {
1652
+ isDim = false;
1653
+ deck.setBrightness(awake).catch(report);
1654
+ }
1655
+ arm();
1656
+ };
1657
+ for (const event of ["keyDown", "keyUp", "sensorDown", "sensorUp"]) {
1658
+ cleanups.push(deck.on(event, wake));
1659
+ }
1660
+ cleanups.push(() => clearTimeout(dim));
1661
+ arm();
1662
+ }
1663
+ const mountOptions = {
1664
+ background: app.background,
1665
+ ...app.mount,
1666
+ onError: app.mount?.onError ?? report
1667
+ };
1668
+ const pages = Object.values(app.pages);
1669
+ const slot = (info, pick) => /* @__PURE__ */ jsx(Providers, {
1670
+ deck,
1671
+ nav,
1672
+ slot: info,
1673
+ children: /* @__PURE__ */ jsx(PageSlot, {
1674
+ app,
1675
+ nav,
1676
+ pick
1677
+ })
1678
+ });
1679
+ roots.push(...await Promise.all(Array.from({ length: deck.keyCount }, (_, index) => deck.mountKey(index, slot({ kind: "key", index }, (page) => page.keys?.[index]), mountOptions))));
1680
+ if (deck.model.layout.window) {
1681
+ roots.push(await deck.mountWindow(slot({ kind: "window" }, (page) => page.window), mountOptions));
1682
+ }
1683
+ for (let index = 0;index < deck.sensorCount; index++) {
1684
+ if (!pages.some((page) => page.sensors?.[index] !== undefined))
1685
+ continue;
1686
+ roots.push(await deck.mountSensor(index, slot({ kind: "sensor", index }, (page) => page.sensors?.[index]), app.sensorText === false ? { ...mountOptions, text: false } : mountOptions));
1687
+ }
1688
+ } catch (error) {
1689
+ await dispose();
1690
+ throw error;
1691
+ }
1692
+ return { navigation: nav, lost, dispose };
1693
+ }
1694
+ function runApp(app, options = {}) {
1695
+ const navigation = createNavigator(app);
1696
+ const handle = manageDeck({
1697
+ open: options.openDeck ?? ((signal) => openStreamDeckNeo({ ...options.open, signal })),
1698
+ async setup(deck) {
1699
+ const session = await mountApp(deck, app, {
1700
+ navigation,
1701
+ heartbeatMs: 0,
1702
+ ...options.onError && { onError: options.onError }
1703
+ });
1704
+ return () => session.dispose();
1705
+ },
1706
+ ...options.reconnect !== undefined && { reconnect: options.reconnect },
1707
+ ...options.signal && { signal: options.signal },
1708
+ ...options.heartbeatMs !== undefined && { heartbeatMs: options.heartbeatMs },
1709
+ ...options.onStatus && { onStatus: options.onStatus },
1710
+ ...options.onError && { onError: options.onError }
1711
+ });
1712
+ return {
1713
+ get status() {
1714
+ return handle.status;
1715
+ },
1716
+ get deck() {
1717
+ return handle.deck;
1718
+ },
1719
+ navigation,
1720
+ stop: handle.stop,
1721
+ finished: handle.finished
1722
+ };
1723
+ }
1724
+ // ../app/src/hooks.ts
1725
+ import { useContext as useContext2, useEffect, useRef, useState, useSyncExternalStore as useSyncExternalStore2 } from "react";
1726
+
1727
+ // ../app/src/swipe.ts
1728
+ var SWIPE_WINDOW_MS = 400;
1729
+
1730
+ class SwipeTracker {
1731
+ #handlers = new Set;
1732
+ #stamps = new Map;
1733
+ #completing = new Set;
1734
+ #first;
1735
+ constructor(deck) {
1736
+ deck.on("sensorDown", (index) => this.#down(index));
1737
+ }
1738
+ get active() {
1739
+ return this.#handlers.size > 0;
1740
+ }
1741
+ stamp(index) {
1742
+ return this.#stamps.get(index) ?? 0;
1743
+ }
1744
+ completes(index) {
1745
+ return this.#completing.has(index);
1746
+ }
1747
+ listen(handler) {
1748
+ this.#handlers.add(handler);
1749
+ return () => void this.#handlers.delete(handler);
1750
+ }
1751
+ #down(index) {
1752
+ this.#completing.delete(index);
1753
+ const now = performance.now();
1754
+ const first = this.#first;
1755
+ if (!this.active || !first || first.index === index || now - first.at > SWIPE_WINDOW_MS) {
1756
+ this.#first = { index, at: now };
1757
+ return;
1758
+ }
1759
+ this.#first = undefined;
1760
+ this.#completing.add(index);
1761
+ for (const sensor of [first.index, index])
1762
+ this.#stamps.set(sensor, this.stamp(sensor) + 1);
1763
+ const direction = index > first.index ? "right" : "left";
1764
+ for (const handler of [...this.#handlers])
1765
+ handler(direction);
1766
+ }
1767
+ }
1768
+ var trackers = new WeakMap;
1769
+ function swipeTracker(deck) {
1770
+ let tracker = trackers.get(deck);
1771
+ if (!tracker) {
1772
+ tracker = new SwipeTracker(deck);
1773
+ trackers.set(deck, tracker);
1774
+ }
1775
+ return tracker;
1776
+ }
1777
+
1778
+ // ../app/src/hooks.ts
1779
+ function useLatest(value) {
1780
+ const ref = useRef(value);
1781
+ useEffect(() => {
1782
+ ref.current = value;
1783
+ });
1784
+ return ref;
1785
+ }
1786
+ function useTarget(kind, explicit) {
1787
+ const slot = useSlot();
1788
+ if (explicit !== undefined)
1789
+ return explicit;
1790
+ return slot?.kind === kind ? slot.index : undefined;
1791
+ }
1792
+ function useInput(kind, phase, handler, explicit) {
1793
+ const deck = useDeck();
1794
+ const target = useTarget(kind, explicit);
1795
+ const latest = useLatest(handler);
1796
+ useEffect(() => {
1797
+ const matches = (index) => target === undefined || index === target;
1798
+ if (phase === "Down") {
1799
+ return deck.on(`${kind}Down`, (index) => matches(index) && latest.current(index));
1800
+ }
1801
+ const held = new Set;
1802
+ const offDown = deck.on(`${kind}Down`, (index) => matches(index) && held.add(index));
1803
+ const offUp = deck.on(`${kind}Up`, (index) => {
1804
+ if (held.delete(index))
1805
+ latest.current(index);
1806
+ });
1807
+ return () => {
1808
+ offDown();
1809
+ offUp();
1810
+ };
1811
+ }, [deck, kind, phase, target, latest]);
1812
+ }
1813
+ function usePressed(kind, explicit) {
1814
+ const deck = useDeck();
1815
+ const target = useTarget(kind, explicit);
1816
+ const [pressed, setPressed] = useState(false);
1817
+ if (target === undefined) {
1818
+ throw new Error(`use${kind === "key" ? "Key" : "Sensor"}Pressed() needs an index outside a ${kind} slot`);
1819
+ }
1820
+ useEffect(() => {
1821
+ setPressed(false);
1822
+ const offDown = deck.on(`${kind}Down`, (i) => i === target && setPressed(true));
1823
+ const offUp = deck.on(`${kind}Up`, (i) => i === target && setPressed(false));
1824
+ return () => {
1825
+ offDown();
1826
+ offUp();
1827
+ };
1828
+ }, [deck, kind, target]);
1829
+ return pressed;
1830
+ }
1831
+ function useKeyDown(handler, key) {
1832
+ useInput("key", "Down", handler, key);
1833
+ }
1834
+ function useKeyUp(handler, key) {
1835
+ useInput("key", "Up", handler, key);
1836
+ }
1837
+ function useKeyPressed(key) {
1838
+ return usePressed("key", key);
1839
+ }
1840
+ function usePress(kind, onPress, gestures, explicit) {
1841
+ const deck = useDeck();
1842
+ const target = useTarget(kind, explicit);
1843
+ const latest = useLatest({
1844
+ onPress,
1845
+ onLongPress: gestures.onLongPress,
1846
+ longPressMs: gestures.longPressMs ?? 500,
1847
+ onDoublePress: gestures.onDoublePress ?? gestures.onDoubleTap,
1848
+ doublePressMs: gestures.doublePressMs ?? gestures.doubleTapMs ?? 300,
1849
+ onRelease: gestures.onRelease ?? false
1850
+ });
1851
+ useEffect(() => {
1852
+ const swipes = kind === "sensor" ? swipeTracker(deck) : undefined;
1853
+ const state = new Map;
1854
+ const held = new Set;
1855
+ const get = (index) => {
1856
+ let s = state.get(index);
1857
+ if (!s) {
1858
+ s = { longFired: false, immediate: false, downAt: 0, stamp: 0 };
1859
+ state.set(index, s);
1860
+ }
1861
+ return s;
1862
+ };
1863
+ const offDown = deck.on(`${kind}Down`, (index) => {
1864
+ if (target !== undefined && index !== target)
1865
+ return;
1866
+ if (swipes?.completes(index))
1867
+ return;
1868
+ held.add(index);
1869
+ const o = latest.current;
1870
+ const s = get(index);
1871
+ s.longFired = false;
1872
+ s.downAt = performance.now();
1873
+ s.stamp = swipes?.stamp(index) ?? 0;
1874
+ s.immediate = !o.onLongPress && !o.onDoublePress && !o.onRelease && !swipes?.active;
1875
+ if (s.immediate) {
1876
+ o.onPress?.(index);
1877
+ return;
1878
+ }
1879
+ if (o.onLongPress) {
1880
+ s.long = setTimeout(() => {
1881
+ if (swipes && swipes.stamp(index) !== s.stamp)
1882
+ return;
1883
+ s.longFired = true;
1884
+ clearTimeout(s.double);
1885
+ s.double = undefined;
1886
+ latest.current.onLongPress?.(index);
1887
+ }, o.longPressMs);
1888
+ }
1889
+ });
1890
+ const offUp = deck.on(`${kind}Up`, (index) => {
1891
+ if (!held.delete(index))
1892
+ return;
1893
+ const s = get(index);
1894
+ clearTimeout(s.long);
1895
+ if (s.immediate || s.longFired)
1896
+ return;
1897
+ if (!swipes?.active)
1898
+ return released(index, s);
1899
+ const wait = Math.max(0, SWIPE_WINDOW_MS - (performance.now() - s.downAt));
1900
+ s.deferred = setTimeout(() => {
1901
+ if (swipes.stamp(index) === s.stamp)
1902
+ released(index, s);
1903
+ }, wait);
1904
+ });
1905
+ function released(index, s) {
1906
+ const o = latest.current;
1907
+ if (!o.onDoublePress) {
1908
+ o.onPress?.(index);
1909
+ } else if (s.double !== undefined) {
1910
+ clearTimeout(s.double);
1911
+ s.double = undefined;
1912
+ o.onDoublePress(index);
1913
+ } else {
1914
+ s.double = setTimeout(() => {
1915
+ s.double = undefined;
1916
+ latest.current.onPress?.(index);
1917
+ }, o.doublePressMs);
1918
+ }
1919
+ }
1920
+ return () => {
1921
+ offDown();
1922
+ offUp();
1923
+ for (const s of state.values()) {
1924
+ clearTimeout(s.long);
1925
+ clearTimeout(s.double);
1926
+ clearTimeout(s.deferred);
1927
+ }
1928
+ };
1929
+ }, [deck, kind, target, latest]);
1930
+ }
1931
+ function useKeyPress(onPress, options = {}) {
1932
+ usePress("key", onPress, options, options.key);
1933
+ }
1934
+ function useSensorPress(onPress, options = {}) {
1935
+ usePress("sensor", onPress, options, options.sensor);
1936
+ }
1937
+ function useRepeat(kind, handler, explicit, options) {
1938
+ const deck = useDeck();
1939
+ const target = useTarget(kind, explicit);
1940
+ const latest = useLatest({ handler, ...options });
1941
+ useEffect(() => {
1942
+ const swipes = kind === "sensor" ? swipeTracker(deck) : undefined;
1943
+ let first;
1944
+ let delay;
1945
+ let repeat;
1946
+ const stop = () => {
1947
+ clearTimeout(delay);
1948
+ clearInterval(repeat);
1949
+ };
1950
+ const offDown = deck.on(`${kind}Down`, (index) => {
1951
+ if (target !== undefined && index !== target)
1952
+ return;
1953
+ if (swipes?.completes(index))
1954
+ return;
1955
+ stop();
1956
+ clearTimeout(first);
1957
+ const stamp = swipes?.stamp(index);
1958
+ const swiped = () => swipes !== undefined && swipes.stamp(index) !== stamp;
1959
+ const run = () => {
1960
+ if (!swiped())
1961
+ latest.current.handler(index);
1962
+ };
1963
+ if (swipes?.active)
1964
+ first = setTimeout(run, SWIPE_WINDOW_MS);
1965
+ else
1966
+ run();
1967
+ const wait = latest.current.delayMs ?? 400;
1968
+ delay = setTimeout(() => {
1969
+ repeat = setInterval(run, latest.current.intervalMs ?? 100);
1970
+ }, swipes?.active ? Math.max(wait, SWIPE_WINDOW_MS) : wait);
1971
+ });
1972
+ const offUp = deck.on(`${kind}Up`, (index) => {
1973
+ if (target === undefined || index === target)
1974
+ stop();
1975
+ });
1976
+ return () => {
1977
+ offDown();
1978
+ offUp();
1979
+ stop();
1980
+ clearTimeout(first);
1981
+ };
1982
+ }, [deck, kind, target, latest]);
1983
+ }
1984
+ function useKeyRepeat(handler, options = {}) {
1985
+ useRepeat("key", handler, options.key, options);
1986
+ }
1987
+ function useSensorRepeat(handler, options = {}) {
1988
+ useRepeat("sensor", handler, options.sensor, options);
1989
+ }
1990
+ function useSwipe(handler) {
1991
+ const deck = useDeck();
1992
+ const latest = useLatest(handler);
1993
+ const on = handler !== undefined;
1994
+ useEffect(() => {
1995
+ if (!on)
1996
+ return;
1997
+ return swipeTracker(deck).listen((direction) => latest.current?.(direction));
1998
+ }, [deck, on, latest]);
1999
+ }
2000
+ function useSensorDown(handler, sensor) {
2001
+ useInput("sensor", "Down", handler, sensor);
2002
+ }
2003
+ function useSensorUp(handler, sensor) {
2004
+ useInput("sensor", "Up", handler, sensor);
2005
+ }
2006
+ function useSensorPressed(sensor) {
2007
+ return usePressed("sensor", sensor);
2008
+ }
2009
+ function useInterval(callback, ms) {
2010
+ const latest = useLatest(callback);
2011
+ useEffect(() => {
2012
+ if (ms === null)
2013
+ return;
2014
+ const id = setInterval(() => latest.current(), ms);
2015
+ return () => clearInterval(id);
2016
+ }, [ms, latest]);
2017
+ }
2018
+ function useNow(ms = 1000) {
2019
+ const [now, setNow] = useState(() => new Date);
2020
+ useInterval(() => setNow(new Date), ms);
2021
+ return now;
2022
+ }
2023
+ function useNavigation() {
2024
+ const nav = useContext2(NavigatorContext);
2025
+ if (!nav)
2026
+ throw new Error("useNavigation() must be used inside a component mounted by sdeck/app");
2027
+ const state = useSyncExternalStore2(nav.subscribe, nav.getSnapshot);
2028
+ return {
2029
+ ...state,
2030
+ canGoBack: state.stack.length > 1,
2031
+ canGoForward: state.forwardStack.length > 0,
2032
+ push: nav.push,
2033
+ replace: nav.replace,
2034
+ back: nav.back,
2035
+ forward: nav.forward,
2036
+ next: nav.next,
2037
+ previous: nav.previous,
2038
+ pages: nav.pages,
2039
+ sequence: nav.sequence,
2040
+ home: nav.home
2041
+ };
2042
+ }
2043
+ function usePage() {
2044
+ return useNavigation().page;
2045
+ }
2046
+
2047
+ // ../app/src/components.tsx
2048
+ import { jsx as jsx2, jsxs } from "react/jsx-runtime";
2049
+ var fill = {
2050
+ display: "flex",
2051
+ width: "100%",
2052
+ height: "100%",
2053
+ alignItems: "center",
2054
+ justifyContent: "center"
2055
+ };
2056
+ function KeyButton({
2057
+ label,
2058
+ icon,
2059
+ iconSize,
2060
+ color = "#2b2b2b",
2061
+ textColor = "#ffffff",
2062
+ pressedColor = "#5a5a5a",
2063
+ fontSize = 18,
2064
+ onPress,
2065
+ ...gestures
2066
+ }) {
2067
+ const pressed = useKeyPressed();
2068
+ useKeyPress(onPress, gestures);
2069
+ const size = iconSize ?? (label ? 48 : 64);
2070
+ return /* @__PURE__ */ jsxs("div", {
2071
+ style: {
2072
+ ...fill,
2073
+ flexDirection: "column",
2074
+ gap: 4,
2075
+ background: pressed ? pressedColor : color,
2076
+ color: textColor,
2077
+ fontSize,
2078
+ fontWeight: 700
2079
+ },
2080
+ children: [
2081
+ icon ? /* @__PURE__ */ jsx2("img", {
2082
+ src: icon,
2083
+ width: size,
2084
+ height: size,
2085
+ alt: ""
2086
+ }) : null,
2087
+ label ? /* @__PURE__ */ jsx2("div", {
2088
+ style: { display: "flex" },
2089
+ children: label
2090
+ }) : null
2091
+ ]
2092
+ });
2093
+ }
2094
+ function SensorButton({
2095
+ label,
2096
+ color = "#2b2b2b",
2097
+ textColor = "#ffffff",
2098
+ pressedColor = "#5a5a5a",
2099
+ fontSize = 11,
2100
+ onPress,
2101
+ ...gestures
2102
+ }) {
2103
+ const pressed = useSensorPressed();
2104
+ useSensorPress(onPress, gestures);
2105
+ return /* @__PURE__ */ jsx2("div", {
2106
+ style: {
2107
+ ...fill,
2108
+ background: pressed ? pressedColor : color,
2109
+ color: textColor,
2110
+ fontSize,
2111
+ fontWeight: 700
2112
+ },
2113
+ children: label ?? null
2114
+ });
2115
+ }
2116
+ function BackButton(props) {
2117
+ const { back } = useNavigation();
2118
+ return /* @__PURE__ */ jsx2(KeyButton, {
2119
+ label: "Back",
2120
+ ...props,
2121
+ onPress: () => back()
2122
+ });
2123
+ }
2124
+ function Clock({
2125
+ format = { hour: "2-digit", minute: "2-digit", second: "2-digit" },
2126
+ locale = "en-GB",
2127
+ color = "#7CFC00",
2128
+ background = "#202020",
2129
+ fontSize = 34
2130
+ }) {
2131
+ const now = useNow(1000);
2132
+ return /* @__PURE__ */ jsx2("div", {
2133
+ style: { ...fill, background, color, fontSize },
2134
+ children: now.toLocaleTimeString(locale, format)
2135
+ });
2136
+ }
2137
+ // ../engine/src/expr.ts
2138
+ class ExpressionError extends Error {
2139
+ position;
2140
+ constructor(message, position) {
2141
+ super(message);
2142
+ this.name = "ExpressionError";
2143
+ this.position = position;
2144
+ }
2145
+ }
2146
+ var OPS = ["===", "!==", "==", "!=", "<=", ">=", "&&", "||", "??", ..."+-*/%<>!?:.,()[]"];
2147
+ function tokenize(src) {
2148
+ const out = [];
2149
+ let i = 0;
2150
+ while (i < src.length) {
2151
+ const c = src[i];
2152
+ if (/\s/.test(c)) {
2153
+ i++;
2154
+ continue;
2155
+ }
2156
+ if (/[0-9]/.test(c) || c === "." && /[0-9]/.test(src[i + 1] ?? "")) {
2157
+ const m = /^(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?/i.exec(src.slice(i));
2158
+ const text = m?.[0] ?? c;
2159
+ out.push({ t: "num", v: Number(text), at: i });
2160
+ i += text.length;
2161
+ continue;
2162
+ }
2163
+ if (c === '"' || c === "'") {
2164
+ let v = "";
2165
+ let j = i + 1;
2166
+ for (;j < src.length && src[j] !== c; j++) {
2167
+ if (src[j] === "\\" && j + 1 < src.length) {
2168
+ const e = src[++j];
2169
+ v += e === "n" ? `
2170
+ ` : e === "t" ? "\t" : e;
2171
+ } else
2172
+ v += src[j];
2173
+ }
2174
+ if (j >= src.length)
2175
+ throw new ExpressionError("unterminated string", i);
2176
+ out.push({ t: "str", v, at: i });
2177
+ i = j + 1;
2178
+ continue;
2179
+ }
2180
+ if (/[A-Za-z_$]/.test(c)) {
2181
+ const m = /^[A-Za-z_$][\w$]*/.exec(src.slice(i));
2182
+ const v = m?.[0] ?? c;
2183
+ out.push({ t: "id", v, at: i });
2184
+ i += v.length;
2185
+ continue;
2186
+ }
2187
+ const op = OPS.find((o) => src.startsWith(o, i));
2188
+ if (!op)
2189
+ throw new ExpressionError(`unexpected "${c}"`, i);
2190
+ out.push({ t: "op", v: op.length === 3 ? op.slice(0, 2) : op, at: i });
2191
+ i += op.length;
2192
+ }
2193
+ out.push({ t: "end", at: src.length });
2194
+ return out;
2195
+ }
2196
+ var BINARY = [
2197
+ ["??"],
2198
+ ["||"],
2199
+ ["&&"],
2200
+ ["==", "!="],
2201
+ ["<", "<=", ">", ">="],
2202
+ ["+", "-"],
2203
+ ["*", "/", "%"]
2204
+ ];
2205
+ var KEYWORDS = {
2206
+ true: true,
2207
+ false: false,
2208
+ null: null,
2209
+ undefined: undefined
2210
+ };
2211
+
2212
+ class Parser {
2213
+ #i = 0;
2214
+ #tokens;
2215
+ constructor(tokens) {
2216
+ this.#tokens = tokens;
2217
+ }
2218
+ get #peek() {
2219
+ return this.#tokens[this.#i];
2220
+ }
2221
+ #isOp(v) {
2222
+ const t = this.#peek;
2223
+ return t.t === "op" && t.v === v;
2224
+ }
2225
+ #expect(v) {
2226
+ if (!this.#isOp(v))
2227
+ throw new ExpressionError(`expected "${v}"`, this.#peek.at);
2228
+ this.#i++;
2229
+ }
2230
+ parse() {
2231
+ const node = this.#ternary();
2232
+ if (this.#peek.t !== "end")
2233
+ throw new ExpressionError("unexpected input", this.#peek.at);
2234
+ return node;
2235
+ }
2236
+ #ternary() {
2237
+ const test = this.#binary(0);
2238
+ if (!this.#isOp("?"))
2239
+ return test;
2240
+ this.#i++;
2241
+ const then = this.#ternary();
2242
+ this.#expect(":");
2243
+ return { kind: "ternary", test, then, else: this.#ternary() };
2244
+ }
2245
+ #binary(level) {
2246
+ if (level >= BINARY.length)
2247
+ return this.#unary();
2248
+ let left = this.#binary(level + 1);
2249
+ const ops = BINARY[level];
2250
+ for (;; ) {
2251
+ const t = this.#peek;
2252
+ if (t.t !== "op" || !ops.includes(t.v))
2253
+ return left;
2254
+ this.#i++;
2255
+ left = { kind: "binary", op: t.v, left, right: this.#binary(level + 1) };
2256
+ }
2257
+ }
2258
+ #unary() {
2259
+ const t = this.#peek;
2260
+ if (t.t === "op" && (t.v === "!" || t.v === "-" || t.v === "+")) {
2261
+ this.#i++;
2262
+ return { kind: "unary", op: t.v, arg: this.#unary() };
2263
+ }
2264
+ return this.#postfix();
2265
+ }
2266
+ #postfix() {
2267
+ let node = this.#primary();
2268
+ for (;; ) {
2269
+ if (this.#isOp(".")) {
2270
+ this.#i++;
2271
+ const t = this.#peek;
2272
+ if (t.t !== "id")
2273
+ throw new ExpressionError("expected a property name", t.at);
2274
+ this.#i++;
2275
+ node = {
2276
+ kind: "member",
2277
+ object: node,
2278
+ property: { kind: "literal", value: t.v },
2279
+ computed: false
2280
+ };
2281
+ } else if (this.#isOp("[")) {
2282
+ this.#i++;
2283
+ const property = this.#ternary();
2284
+ this.#expect("]");
2285
+ node = { kind: "member", object: node, property, computed: true };
2286
+ } else if (this.#isOp("(")) {
2287
+ if (node.kind !== "ident")
2288
+ throw new ExpressionError("only functions can be called", this.#peek.at);
2289
+ const at = this.#peek.at;
2290
+ this.#i++;
2291
+ if (!Object.hasOwn(FUNCTIONS, node.name)) {
2292
+ throw new ExpressionError(`unknown function "${node.name}"`, at);
2293
+ }
2294
+ node = { kind: "call", name: node.name, args: this.#list(")") };
2295
+ } else
2296
+ return node;
2297
+ }
2298
+ }
2299
+ #list(close) {
2300
+ const items = [];
2301
+ if (this.#isOp(close)) {
2302
+ this.#i++;
2303
+ return items;
2304
+ }
2305
+ for (;; ) {
2306
+ items.push(this.#ternary());
2307
+ if (this.#isOp(",")) {
2308
+ this.#i++;
2309
+ continue;
2310
+ }
2311
+ this.#expect(close);
2312
+ return items;
2313
+ }
2314
+ }
2315
+ #primary() {
2316
+ const t = this.#peek;
2317
+ this.#i++;
2318
+ switch (t.t) {
2319
+ case "num":
2320
+ case "str":
2321
+ return { kind: "literal", value: t.v };
2322
+ case "id":
2323
+ return Object.hasOwn(KEYWORDS, t.v) ? { kind: "literal", value: KEYWORDS[t.v] } : { kind: "ident", name: t.v };
2324
+ case "op":
2325
+ if (t.v === "(") {
2326
+ const inner = this.#ternary();
2327
+ this.#expect(")");
2328
+ return inner;
2329
+ }
2330
+ if (t.v === "[")
2331
+ return { kind: "array", items: this.#list("]") };
2332
+ throw new ExpressionError(`unexpected "${t.v}"`, t.at);
2333
+ case "end":
2334
+ throw new ExpressionError("unexpected end", t.at);
2335
+ }
2336
+ }
2337
+ }
2338
+ var BLOCKED = new Set(["__proto__", "prototype", "constructor"]);
2339
+ function member(object, key) {
2340
+ if (object === null || object === undefined)
2341
+ return;
2342
+ if (typeof object === "string") {
2343
+ if (key === "length")
2344
+ return object.length;
2345
+ return typeof key === "number" ? object[key] : undefined;
2346
+ }
2347
+ if (Array.isArray(object)) {
2348
+ if (key === "length")
2349
+ return object.length;
2350
+ return typeof key === "number" ? object[key] : undefined;
2351
+ }
2352
+ if (typeof object !== "object")
2353
+ return;
2354
+ const k = String(key);
2355
+ if (BLOCKED.has(k) || !Object.hasOwn(object, k))
2356
+ return;
2357
+ return object[k];
2358
+ }
2359
+ function looseEqual(a, b) {
2360
+ if (typeof a === "number" && typeof b === "string" && b.trim() !== "")
2361
+ return a === Number(b);
2362
+ if (typeof b === "number" && typeof a === "string" && a.trim() !== "")
2363
+ return b === Number(a);
2364
+ if (a === undefined)
2365
+ return b === undefined || b === null;
2366
+ if (a === null)
2367
+ return b === undefined || b === null;
2368
+ return Object.is(a, b) || a === b;
2369
+ }
2370
+ var toNum = (v) => typeof v === "number" ? v : Number(v ?? Number.NaN);
2371
+ function compare(op, a, b) {
2372
+ const both = typeof a === "string" && typeof b === "string";
2373
+ const x = both ? a : toNum(a);
2374
+ const y = both ? b : toNum(b);
2375
+ switch (op) {
2376
+ case "<":
2377
+ return x < y;
2378
+ case "<=":
2379
+ return x <= y;
2380
+ case ">":
2381
+ return x > y;
2382
+ case ">=":
2383
+ return x >= y;
2384
+ }
2385
+ }
2386
+ function evaluate(node, scope) {
2387
+ switch (node.kind) {
2388
+ case "literal":
2389
+ return node.value;
2390
+ case "ident":
2391
+ return Object.hasOwn(scope, node.name) ? scope[node.name] : undefined;
2392
+ case "member":
2393
+ return member(evaluate(node.object, scope), evaluate(node.property, scope));
2394
+ case "array":
2395
+ return node.items.map((n) => evaluate(n, scope));
2396
+ case "call": {
2397
+ const fn = FUNCTIONS[node.name];
2398
+ return fn(...node.args.map((n) => evaluate(n, scope)));
2399
+ }
2400
+ case "unary": {
2401
+ const v = evaluate(node.arg, scope);
2402
+ return node.op === "!" ? !v : node.op === "-" ? -toNum(v) : toNum(v);
2403
+ }
2404
+ case "ternary":
2405
+ return evaluate(node.test, scope) ? evaluate(node.then, scope) : evaluate(node.else, scope);
2406
+ case "binary": {
2407
+ const { op } = node;
2408
+ if (op === "&&")
2409
+ return evaluate(node.left, scope) && evaluate(node.right, scope);
2410
+ if (op === "||")
2411
+ return evaluate(node.left, scope) || evaluate(node.right, scope);
2412
+ if (op === "??")
2413
+ return evaluate(node.left, scope) ?? evaluate(node.right, scope);
2414
+ const a = evaluate(node.left, scope);
2415
+ const b = evaluate(node.right, scope);
2416
+ switch (op) {
2417
+ case "+":
2418
+ return typeof a === "string" || typeof b === "string" ? display(a) + display(b) : toNum(a) + toNum(b);
2419
+ case "-":
2420
+ return toNum(a) - toNum(b);
2421
+ case "*":
2422
+ return toNum(a) * toNum(b);
2423
+ case "/":
2424
+ return toNum(a) / toNum(b);
2425
+ case "%":
2426
+ return toNum(a) % toNum(b);
2427
+ case "==":
2428
+ return looseEqual(a, b);
2429
+ case "!=":
2430
+ return !looseEqual(a, b);
2431
+ default:
2432
+ return compare(op, a, b);
2433
+ }
2434
+ }
2435
+ }
2436
+ }
2437
+ var pad2 = (n) => String(n).padStart(2, "0");
2438
+ function display(value) {
2439
+ if (value === undefined || value === null)
2440
+ return "";
2441
+ if (typeof value === "number") {
2442
+ if (!Number.isFinite(value))
2443
+ return Number.isNaN(value) ? "" : value > 0 ? "∞" : "-∞";
2444
+ return String(Math.round(value * 100) / 100);
2445
+ }
2446
+ if (typeof value === "string")
2447
+ return value;
2448
+ if (typeof value === "boolean")
2449
+ return value ? "true" : "false";
2450
+ try {
2451
+ return JSON.stringify(value) ?? "";
2452
+ } catch {
2453
+ return "";
2454
+ }
2455
+ }
2456
+ var UNITS = ["B", "KB", "MB", "GB", "TB", "PB"];
2457
+ function currentTurn(first, second, at) {
2458
+ const lengths = (Array.isArray(first) ? first.map(toNum) : Array.from({ length: Math.min(100, Math.max(0, Math.trunc(toNum(first)))) }, () => toNum(second ?? 5))).map((s) => Number.isFinite(s) && s > 0 ? s : 0);
2459
+ const total = lengths.reduce((a, b) => a + b, 0);
2460
+ if (total <= 0)
2461
+ return 0;
2462
+ let into = at / 1000 % total;
2463
+ for (const [i, length] of lengths.entries()) {
2464
+ if (into < length)
2465
+ return i;
2466
+ into -= length;
2467
+ }
2468
+ return lengths.length - 1;
2469
+ }
2470
+ var FUNCTIONS = {
2471
+ round: (x, digits) => {
2472
+ const d = Math.max(0, Math.min(10, Math.trunc(toNum(digits ?? 0)) || 0));
2473
+ const f = 10 ** d;
2474
+ return Math.round(toNum(x) * f) / f;
2475
+ },
2476
+ floor: (x) => Math.floor(toNum(x)),
2477
+ ceil: (x) => Math.ceil(toNum(x)),
2478
+ abs: (x) => Math.abs(toNum(x)),
2479
+ min: (...xs) => Math.min(...xs.flat().map(toNum)),
2480
+ max: (...xs) => Math.max(...xs.flat().map(toNum)),
2481
+ clamp: (x, lo, hi) => Math.min(toNum(hi), Math.max(toNum(lo), toNum(x))),
2482
+ fmt: (x, digits) => {
2483
+ const n = toNum(x);
2484
+ if (!Number.isFinite(n))
2485
+ return "";
2486
+ return n.toFixed(Math.max(0, Math.min(10, Math.trunc(toNum(digits ?? 0)) || 0)));
2487
+ },
2488
+ bytes: (x) => {
2489
+ let n = toNum(x);
2490
+ if (!Number.isFinite(n))
2491
+ return "";
2492
+ let u = 0;
2493
+ while (Math.abs(n) >= 1024 && u < UNITS.length - 1) {
2494
+ n /= 1024;
2495
+ u++;
2496
+ }
2497
+ return `${u === 0 ? n : n.toFixed(n < 10 ? 1 : 0)} ${UNITS[u]}`;
2498
+ },
2499
+ pad: (x, width, fill) => display(x).padStart(Math.min(64, toNum(width) || 0), display(fill ?? "0") || "0"),
2500
+ str: (x) => display(x),
2501
+ num: (x) => {
2502
+ const n = toNum(x);
2503
+ return Number.isFinite(n) ? n : 0;
2504
+ },
2505
+ upper: (s) => display(s).toUpperCase(),
2506
+ lower: (s) => display(s).toLowerCase(),
2507
+ trim: (s) => display(s).trim(),
2508
+ len: (x) => typeof x === "string" || Array.isArray(x) ? x.length : 0,
2509
+ contains: (haystack, needle) => Array.isArray(haystack) ? haystack.some((v) => looseEqual(v, needle)) : display(haystack).includes(display(needle)),
2510
+ startsWith: (s, p) => display(s).startsWith(display(p)),
2511
+ endsWith: (s, p) => display(s).endsWith(display(p)),
2512
+ replace: (s, a, b) => display(s).split(display(a)).join(display(b)),
2513
+ join: (xs, sep) => Array.isArray(xs) ? xs.map(display).join(sep === undefined ? ", " : display(sep)) : "",
2514
+ if: (c, a, b) => c ? a : b,
2515
+ now: () => Date.now(),
2516
+ time: (seconds) => {
2517
+ const d = new Date;
2518
+ const hm = `${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
2519
+ return seconds ? `${hm}:${pad2(d.getSeconds())}` : hm;
2520
+ },
2521
+ turn: (first, second) => currentTurn(first, second, Date.now()),
2522
+ date: () => {
2523
+ const d = new Date;
2524
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
2525
+ }
2526
+ };
2527
+ function pathOf(node) {
2528
+ if (node.kind === "ident")
2529
+ return node.name;
2530
+ if (node.kind === "member") {
2531
+ const base = pathOf(node.object);
2532
+ if (base === undefined)
2533
+ return;
2534
+ if (!node.computed && node.property.kind === "literal")
2535
+ return `${base}.${String(node.property.value)}`;
2536
+ return base;
2537
+ }
2538
+ return;
2539
+ }
2540
+ var TIME_FUNCTIONS = new Set(["now", "time", "date", "turn"]);
2541
+ function collect(node, paths, flags) {
2542
+ switch (node.kind) {
2543
+ case "ident":
2544
+ paths.add(node.name);
2545
+ return;
2546
+ case "member": {
2547
+ const path = pathOf(node);
2548
+ if (path !== undefined)
2549
+ paths.add(path);
2550
+ else
2551
+ collect(node.object, paths, flags);
2552
+ if (node.computed)
2553
+ collect(node.property, paths, flags);
2554
+ return;
2555
+ }
2556
+ case "call":
2557
+ if (TIME_FUNCTIONS.has(node.name))
2558
+ flags.time = true;
2559
+ for (const a of node.args)
2560
+ collect(a, paths, flags);
2561
+ return;
2562
+ case "array":
2563
+ for (const a of node.items)
2564
+ collect(a, paths, flags);
2565
+ return;
2566
+ case "unary":
2567
+ collect(node.arg, paths, flags);
2568
+ return;
2569
+ case "binary":
2570
+ collect(node.left, paths, flags);
2571
+ collect(node.right, paths, flags);
2572
+ return;
2573
+ case "ternary":
2574
+ collect(node.test, paths, flags);
2575
+ collect(node.then, paths, flags);
2576
+ collect(node.else, paths, flags);
2577
+ return;
2578
+ case "literal":
2579
+ return;
2580
+ }
2581
+ }
2582
+ function minimal(paths) {
2583
+ const sorted = [...paths].sort((a, b) => a.length - b.length);
2584
+ const out = [];
2585
+ for (const p of sorted)
2586
+ if (!out.some((q) => p === q || p.startsWith(`${q}.`)))
2587
+ out.push(p);
2588
+ return out;
2589
+ }
2590
+ var cache = new Map;
2591
+ function compile(source) {
2592
+ const hit = cache.get(source);
2593
+ if (hit)
2594
+ return hit;
2595
+ const trimmed = source.trim();
2596
+ const ast = trimmed === "" ? { kind: "literal", value: undefined } : new Parser(tokenize(trimmed)).parse();
2597
+ const paths = new Set;
2598
+ const flags = { time: false };
2599
+ collect(ast, paths, flags);
2600
+ const expression = {
2601
+ source,
2602
+ paths: minimal(paths),
2603
+ timeDependent: flags.time,
2604
+ evaluate(scope) {
2605
+ try {
2606
+ return evaluate(ast, scope);
2607
+ } catch {
2608
+ return;
2609
+ }
2610
+ }
2611
+ };
2612
+ if (cache.size > 2000)
2613
+ cache.clear();
2614
+ cache.set(source, expression);
2615
+ return expression;
2616
+ }
2617
+
2618
+ // ../engine/src/state.ts
2619
+ function sameValue(a, b) {
2620
+ if (Object.is(a, b))
2621
+ return true;
2622
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null)
2623
+ return false;
2624
+ if (Array.isArray(a) !== Array.isArray(b))
2625
+ return false;
2626
+ const ka = Object.keys(a);
2627
+ const kb = Object.keys(b);
2628
+ if (ka.length !== kb.length)
2629
+ return false;
2630
+ return ka.every((k) => Object.hasOwn(b, k) && sameValue(a[k], b[k]));
2631
+ }
2632
+
2633
+ // ../engine/src/template.ts
2634
+ var HOLE = /\{\{([\s\S]*?)\}\}/g;
2635
+ function parts(source) {
2636
+ const out = [];
2637
+ let last = 0;
2638
+ for (const m of source.matchAll(HOLE)) {
2639
+ if (m.index > last)
2640
+ out.push(source.slice(last, m.index));
2641
+ try {
2642
+ out.push(compile(m[1] ?? ""));
2643
+ } catch (error) {
2644
+ out.push(error instanceof ExpressionError ? new ExpressionError(error.message, m.index + 2 + error.position) : new ExpressionError(String(error), m.index));
2645
+ }
2646
+ last = m.index + m[0].length;
2647
+ }
2648
+ if (last < source.length)
2649
+ out.push(source.slice(last));
2650
+ return out;
2651
+ }
2652
+ var cache2 = new Map;
2653
+ function template(source) {
2654
+ const hit = cache2.get(source);
2655
+ if (hit)
2656
+ return hit;
2657
+ const list = parts(source);
2658
+ const expressions = list.filter((p) => typeof p === "object" && !(p instanceof ExpressionError));
2659
+ const errors = list.filter((p) => p instanceof ExpressionError);
2660
+ const paths = [...new Set(expressions.flatMap((e) => e.paths))];
2661
+ const render = (scope) => list.map((p) => typeof p === "string" ? p : p instanceof ExpressionError ? "⚠" : display(p.evaluate(scope))).join("");
2662
+ const single = list.length === 1 && expressions.length === 1 ? expressions[0] : undefined;
2663
+ const t = {
2664
+ source,
2665
+ render,
2666
+ value: (scope) => single ? single.evaluate(scope) : render(scope),
2667
+ paths,
2668
+ timeDependent: expressions.some((e) => e.timeDependent),
2669
+ errors,
2670
+ dynamic: expressions.length + errors.length > 0
2671
+ };
2672
+ if (cache2.size > 2000)
2673
+ cache2.clear();
2674
+ cache2.set(source, t);
2675
+ return t;
2676
+ }
2677
+ // src/bridge.ts
2678
+ import {
2679
+ createContext as createContext2,
2680
+ useCallback,
2681
+ useContext as useContext3,
2682
+ useEffect as useEffect2,
2683
+ useMemo,
2684
+ useRef as useRef2,
2685
+ useState as useState2,
2686
+ useSyncExternalStore as useSyncExternalStore3
2687
+ } from "react";
2688
+ var HostBridgeContext = createContext2(undefined);
2689
+ function useBridge() {
2690
+ const bridge = useContext3(HostBridgeContext);
2691
+ if (!bridge)
2692
+ throw new Error("sdeck live-state hooks must be used inside an action drawn by the host");
2693
+ return bridge;
2694
+ }
2695
+ function useClock(on) {
2696
+ const [tick, setTick] = useState2(0);
2697
+ useEffect2(() => {
2698
+ if (!on)
2699
+ return;
2700
+ const timer = setInterval(() => setTick((t) => t + 1), 1000);
2701
+ return () => clearInterval(timer);
2702
+ }, [on]);
2703
+ return tick;
2704
+ }
2705
+ function useWatched(paths, read) {
2706
+ const bridge = useBridge();
2707
+ const key = paths.join(`
2708
+ `);
2709
+ const subscribe = useCallback((listener) => bridge.watch(paths, listener), [bridge, key]);
2710
+ const last = useRef2(undefined);
2711
+ const snapshot = () => {
2712
+ const value = read();
2713
+ if (last.current && sameValue(last.current.value, value))
2714
+ return last.current.value;
2715
+ last.current = { value };
2716
+ return value;
2717
+ };
2718
+ return useSyncExternalStore3(subscribe, snapshot);
2719
+ }
2720
+ function useExpression(source) {
2721
+ const bridge = useBridge();
2722
+ const expression = useMemo(() => compile(source), [source]);
2723
+ useClock(expression.timeDependent);
2724
+ return useWatched(expression.paths, () => expression.evaluate(bridge.scope()));
2725
+ }
2726
+ function useTemplate(source) {
2727
+ const bridge = useBridge();
2728
+ const compiled = useMemo(() => template(source), [source]);
2729
+ useClock(compiled.timeDependent);
2730
+ return useWatched(compiled.paths, () => compiled.render(bridge.scope()));
2731
+ }
2732
+ function useHostState(key) {
2733
+ const bridge = useBridge();
2734
+ const paths = useMemo(() => [key], [key]);
2735
+ return useWatched(paths, () => {
2736
+ const dot = key.indexOf(".");
2737
+ const ns = bridge.scope()[key.slice(0, dot)];
2738
+ return dot > 0 ? ns?.[key.slice(dot + 1)] : undefined;
2739
+ });
2740
+ }
2741
+ function useVariable(name) {
2742
+ const bridge = useBridge();
2743
+ const paths = useMemo(() => [`vars.${name}`], [name]);
2744
+ const value = useWatched(paths, () => bridge.scope().vars[name]);
2745
+ const set = useCallback((v) => bridge.setVariable(name, v), [bridge, name]);
2746
+ return [value, set];
2747
+ }
2748
+ function useRunAction() {
2749
+ return useBridge().run;
2750
+ }
2751
+ function useImage(src, color) {
2752
+ const bridge = useBridge();
2753
+ return useSyncExternalStore3(bridge.watchImages, () => src ? bridge.image(src, color) : undefined);
2754
+ }
2755
+ // src/connection.ts
2756
+ class PermanentError extends Error {
2757
+ }
2758
+
2759
+ class ManagedConnection {
2760
+ #options;
2761
+ #waiters = new Set;
2762
+ #holders = 0;
2763
+ #link;
2764
+ #attempt;
2765
+ #retry;
2766
+ #linger;
2767
+ #delay;
2768
+ #failed;
2769
+ constructor(options) {
2770
+ this.#options = options;
2771
+ this.#delay = options.retry?.minMs ?? 1000;
2772
+ }
2773
+ get current() {
2774
+ return this.#link?.value;
2775
+ }
2776
+ hold() {
2777
+ this.#holders++;
2778
+ clearTimeout(this.#linger);
2779
+ this.#connect();
2780
+ let released = false;
2781
+ return () => {
2782
+ if (released)
2783
+ return;
2784
+ released = true;
2785
+ this.#holders--;
2786
+ if (this.#holders > 0)
2787
+ return;
2788
+ this.#linger = setTimeout(() => this.#drop(), this.#options.lingerMs ?? 3000);
2789
+ };
2790
+ }
2791
+ async with(use, timeoutMs = 5000) {
2792
+ const release = this.hold();
2793
+ try {
2794
+ return await use(await this.#ready(timeoutMs));
2795
+ } finally {
2796
+ release();
2797
+ }
2798
+ }
2799
+ restart() {
2800
+ this.#failed = undefined;
2801
+ this.#delay = this.#options.retry?.minMs ?? 1000;
2802
+ this.#drop();
2803
+ if (this.#holders > 0)
2804
+ this.#connect();
2805
+ }
2806
+ close() {
2807
+ this.#holders = 0;
2808
+ clearTimeout(this.#linger);
2809
+ this.#drop();
2810
+ this.#reject(new Error("the connection was closed"));
2811
+ }
2812
+ #ready(timeoutMs) {
2813
+ if (this.#link)
2814
+ return Promise.resolve(this.#link.value);
2815
+ if (this.#failed)
2816
+ return Promise.reject(this.#failed);
2817
+ if (this.#retry) {
2818
+ clearTimeout(this.#retry);
2819
+ this.#retry = undefined;
2820
+ this.#connect();
2821
+ }
2822
+ return new Promise((resolve, reject) => {
2823
+ let last;
2824
+ const waiter = {
2825
+ resolve: (value) => {
2826
+ clearTimeout(timer);
2827
+ resolve(value);
2828
+ },
2829
+ reject: (error) => {
2830
+ last = error;
2831
+ clearTimeout(timer);
2832
+ this.#waiters.delete(waiter);
2833
+ reject(last);
2834
+ }
2835
+ };
2836
+ const timer = setTimeout(() => waiter.reject(new Error("could not connect in time")), timeoutMs);
2837
+ this.#waiters.add(waiter);
2838
+ });
2839
+ }
2840
+ #connect() {
2841
+ if (this.#link || this.#attempt || this.#retry || this.#failed)
2842
+ return;
2843
+ const attempt = new AbortController;
2844
+ this.#attempt = attempt;
2845
+ this.#options.onStatus?.("connecting");
2846
+ let lostEarly;
2847
+ let link;
2848
+ const lost = (error) => {
2849
+ if (!link) {
2850
+ lostEarly = error;
2851
+ return;
2852
+ }
2853
+ if (this.#link !== link)
2854
+ return;
2855
+ this.#link = undefined;
2856
+ link.close();
2857
+ this.#options.onStatus?.("disconnected", error);
2858
+ this.#schedule(error);
2859
+ };
2860
+ const open = async () => {
2861
+ const opened = await this.#options.open(lost, attempt.signal);
2862
+ if (attempt.signal.aborted) {
2863
+ opened.close();
2864
+ return;
2865
+ }
2866
+ if (lostEarly) {
2867
+ opened.close();
2868
+ throw lostEarly;
2869
+ }
2870
+ link = opened;
2871
+ this.#attempt = undefined;
2872
+ this.#link = opened;
2873
+ this.#delay = this.#options.retry?.minMs ?? 1000;
2874
+ this.#options.onStatus?.("connected");
2875
+ for (const waiter of this.#waiters)
2876
+ waiter.resolve(opened.value);
2877
+ this.#waiters.clear();
2878
+ };
2879
+ open().catch((error) => {
2880
+ if (attempt.signal.aborted || this.#attempt !== attempt)
2881
+ return;
2882
+ this.#attempt = undefined;
2883
+ this.#options.onStatus?.("disconnected", error);
2884
+ this.#reject(error);
2885
+ this.#schedule(error);
2886
+ });
2887
+ }
2888
+ #schedule(error) {
2889
+ if (error instanceof PermanentError) {
2890
+ this.#failed = error;
2891
+ this.#reject(error);
2892
+ return;
2893
+ }
2894
+ if (this.#holders <= 0)
2895
+ return;
2896
+ clearTimeout(this.#retry);
2897
+ this.#retry = setTimeout(() => {
2898
+ this.#retry = undefined;
2899
+ if (this.#holders > 0)
2900
+ this.#connect();
2901
+ }, this.#delay);
2902
+ this.#delay = Math.min(this.#delay * 2, this.#options.retry?.maxMs ?? 30000);
2903
+ }
2904
+ #reject(error) {
2905
+ for (const waiter of [...this.#waiters])
2906
+ waiter.reject(error);
2907
+ this.#waiters.clear();
2908
+ }
2909
+ #drop() {
2910
+ clearTimeout(this.#retry);
2911
+ this.#retry = undefined;
2912
+ this.#attempt?.abort();
2913
+ this.#attempt = undefined;
2914
+ const link = this.#link;
2915
+ this.#link = undefined;
2916
+ if (!link)
2917
+ return;
2918
+ link.close();
2919
+ this.#options.onStatus?.("disconnected");
2920
+ }
2921
+ }
2922
+ // src/settings.ts
2923
+ var HEX = /^#[0-9a-f]{6}$/i;
2924
+ function defaultValue(field) {
2925
+ switch (field.type) {
2926
+ case "number":
2927
+ return field.default ?? field.min ?? 0;
2928
+ case "boolean":
2929
+ return field.default ?? false;
2930
+ case "color":
2931
+ return field.default ?? "#000000";
2932
+ case "select":
2933
+ return field.default ?? field.options[0]?.value ?? "";
2934
+ default:
2935
+ return field.default ?? "";
2936
+ }
2937
+ }
2938
+ function coerce(field, value) {
2939
+ switch (field.type) {
2940
+ case "number": {
2941
+ const n = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
2942
+ if (typeof n !== "number" || !Number.isFinite(n))
2943
+ return defaultValue(field);
2944
+ return Math.min(field.max ?? Infinity, Math.max(field.min ?? -Infinity, n));
2945
+ }
2946
+ case "boolean":
2947
+ return typeof value === "boolean" ? value : defaultValue(field);
2948
+ case "color":
2949
+ return typeof value === "string" && HEX.test(value) ? value.toLowerCase() : defaultValue(field);
2950
+ case "select":
2951
+ if (typeof value !== "string")
2952
+ return defaultValue(field);
2953
+ if (field.source !== undefined)
2954
+ return value;
2955
+ return field.options.some((o) => o.value === value) ? value : defaultValue(field);
2956
+ default:
2957
+ return typeof value === "string" ? value : defaultValue(field);
2958
+ }
2959
+ }
2960
+ function resolveSettings(schema, stored) {
2961
+ const out = {};
2962
+ for (const [key, field] of Object.entries(schema))
2963
+ out[key] = coerce(field, stored?.[key]);
2964
+ return out;
2965
+ }
2966
+ function isFieldVisible(field, settings) {
2967
+ if (!field.visibleIf)
2968
+ return true;
2969
+ return Object.entries(field.visibleIf).every(([key, want]) => {
2970
+ const value = settings[key];
2971
+ return Array.isArray(want) ? want.includes(value) : value === want;
2972
+ });
2973
+ }
2974
+ function checkSchema(schema, sources = {}) {
2975
+ const problems = [];
2976
+ const types = new Set([
2977
+ "text",
2978
+ "number",
2979
+ "boolean",
2980
+ "color",
2981
+ "select",
2982
+ "page",
2983
+ "image",
2984
+ "secret"
2985
+ ]);
2986
+ for (const [key, field] of Object.entries(schema)) {
2987
+ if (!field || typeof field !== "object" || !types.has(field.type)) {
2988
+ problems.push(`setting "${key}" has an unknown type`);
2989
+ continue;
2990
+ }
2991
+ if (typeof field.label !== "string")
2992
+ problems.push(`setting "${key}" needs a label`);
2993
+ const source = "source" in field ? field.source : undefined;
2994
+ if (source !== undefined && !(source in sources)) {
2995
+ problems.push(`setting "${key}" uses unknown option source "${source}"`);
2996
+ }
2997
+ if (field.type === "select" && (!Array.isArray(field.options) || field.options.length === 0 && source === undefined)) {
2998
+ problems.push(`setting "${key}" needs at least one option or a source`);
2999
+ }
3000
+ for (const other of "dependsOn" in field && field.dependsOn || []) {
3001
+ if (!(other in schema))
3002
+ problems.push(`setting "${key}" depends on unknown "${other}"`);
3003
+ }
3004
+ if (field.visibleIf !== undefined) {
3005
+ for (const other of Object.keys(field.visibleIf)) {
3006
+ if (!(other in schema))
3007
+ problems.push(`setting "${key}" depends on unknown "${other}"`);
3008
+ }
3009
+ }
3010
+ }
3011
+ return problems;
3012
+ }
3013
+
3014
+ // src/plugin.ts
3015
+ var PLUGIN_API_VERSION = 2;
3016
+ var PERMISSIONS = [
3017
+ "shell",
3018
+ "process",
3019
+ "filesystem",
3020
+ "network",
3021
+ "input",
3022
+ "audio",
3023
+ "clipboard"
3024
+ ];
3025
+ var ID = /^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*$/;
3026
+ var NAMESPACE = /^[a-z][\w-]{0,31}$/;
3027
+ var LOCAL_ID = /^[\w.-]+$/;
3028
+ function pluginNamespace(def) {
3029
+ if (def.namespace)
3030
+ return def.namespace;
3031
+ const base = def.id.replace(/^@[^/]+\//, "").replace(/^sdeck-plugin-/, "").replace(/^plugin-/, "").toLowerCase().replace(/[^\w-]/g, "-");
3032
+ return /^[a-z]/.test(base) ? base.slice(0, 32) : `p-${base}`.slice(0, 32);
3033
+ }
3034
+ function defineAction(def) {
3035
+ return {
3036
+ ...def,
3037
+ slots: def.slots ?? ["key"],
3038
+ settings: def.settings ?? {}
3039
+ };
3040
+ }
3041
+ function defineTrigger(def) {
3042
+ return { ...def, settings: def.settings ?? {} };
3043
+ }
3044
+ function definePlugin(def) {
3045
+ const problems = checkPlugin(def);
3046
+ if (problems.length > 0) {
3047
+ throw new TypeError(`invalid plugin "${def?.id}": ${problems.join("; ")}`);
3048
+ }
3049
+ return def;
3050
+ }
3051
+ function checkLocalIds(kind, items, problems) {
3052
+ const seen = new Set;
3053
+ for (const item of items) {
3054
+ const name = typeof item?.id === "string" ? item.id : "?";
3055
+ if (typeof item?.id !== "string" || !LOCAL_ID.test(item.id)) {
3056
+ problems.push(`${kind} "${name}": id must be letters, digits, ".", "-" or "_"`);
3057
+ } else if (seen.has(item.id)) {
3058
+ problems.push(`${kind} "${name}" is defined twice`);
3059
+ }
3060
+ seen.add(name);
3061
+ }
3062
+ return seen;
3063
+ }
3064
+ function checkPlugin(value) {
3065
+ if (!value || typeof value !== "object")
3066
+ return ["not an object"];
3067
+ const def = value;
3068
+ const problems = [];
3069
+ if (typeof def.id !== "string" || !ID.test(def.id)) {
3070
+ problems.push("id must be a package-style name (lowercase, e.g. `my-plugin` or `@me/plugin`)");
3071
+ }
3072
+ if (typeof def.name !== "string" || def.name === "")
3073
+ problems.push("name is required");
3074
+ if (typeof def.version !== "string" || def.version === "")
3075
+ problems.push("version is required");
3076
+ if (def.namespace !== undefined && !NAMESPACE.test(def.namespace)) {
3077
+ problems.push("namespace must be lowercase letters, digits, - or _ (starting with a letter)");
3078
+ }
3079
+ if (def.activate !== undefined && typeof def.activate !== "function") {
3080
+ problems.push("activate must be a function");
3081
+ }
3082
+ if (def.permissions !== undefined) {
3083
+ if (!Array.isArray(def.permissions))
3084
+ problems.push("permissions must be an array");
3085
+ else
3086
+ for (const p of def.permissions)
3087
+ if (!PERMISSIONS.includes(p))
3088
+ problems.push(`unknown permission "${String(p)}"`);
3089
+ }
3090
+ if (def.settings !== undefined) {
3091
+ for (const p of checkSchema(def.settings, def.optionSources ?? {})) {
3092
+ problems.push(`plugin ${p}`);
3093
+ }
3094
+ }
3095
+ if (def.commands !== undefined) {
3096
+ if (!Array.isArray(def.commands))
3097
+ problems.push("commands must be an array");
3098
+ else {
3099
+ checkLocalIds("command", def.commands, problems);
3100
+ for (const c of def.commands) {
3101
+ const name = typeof c?.id === "string" ? c.id : "?";
3102
+ if (typeof c?.name !== "string")
3103
+ problems.push(`command "${name}": name is required`);
3104
+ if (typeof c?.run !== "function")
3105
+ problems.push(`command "${name}": run is required`);
3106
+ }
3107
+ }
3108
+ }
3109
+ if (def.onboarding !== undefined)
3110
+ problems.push(...checkOnboarding(def));
3111
+ const sources = def.optionSources ?? {};
3112
+ if (typeof sources !== "object")
3113
+ problems.push("optionSources must be an object");
3114
+ else
3115
+ for (const [name, fn] of Object.entries(sources))
3116
+ if (typeof fn !== "function")
3117
+ problems.push(`option source "${name}" must be a function`);
3118
+ if (!Array.isArray(def.actions))
3119
+ return [...problems, "actions must be an array"];
3120
+ checkLocalIds("action", def.actions, problems);
3121
+ for (const action of def.actions) {
3122
+ const name = typeof action?.id === "string" ? action.id : "?";
3123
+ if (typeof action?.name !== "string")
3124
+ problems.push(`action "${name}": name is required`);
3125
+ const hasComponent = typeof action?.component === "function" || typeof action?.component === "object";
3126
+ const hasRun = typeof action?.run === "function";
3127
+ if (!hasComponent && !hasRun)
3128
+ problems.push(`action "${name}": needs run or component`);
3129
+ if (action?.look !== undefined && typeof action.look !== "function") {
3130
+ problems.push(`action "${name}": look must be a function`);
3131
+ }
3132
+ const slots = action?.slots ?? ["key"];
3133
+ if (!Array.isArray(slots) || slots.length === 0 || slots.some((s) => !["key", "sensor", "window"].includes(s))) {
3134
+ problems.push(`action "${name}": slots must list "key", "sensor" and/or "window"`);
3135
+ }
3136
+ for (const p of checkSchema(action?.settings ?? {}, sources)) {
3137
+ problems.push(`action "${name}": ${p}`);
3138
+ }
3139
+ for (const [key, field] of Object.entries(action?.settings ?? {})) {
3140
+ if (field?.type === "secret") {
3141
+ problems.push(`action "${name}": setting "${key}": secrets belong in the plugin settings`);
3142
+ }
3143
+ }
3144
+ }
3145
+ if (def.state !== undefined) {
3146
+ if (!Array.isArray(def.state))
3147
+ problems.push("state must be an array");
3148
+ else {
3149
+ checkLocalIds("state", def.state, problems);
3150
+ for (const s of def.state) {
3151
+ const name = typeof s?.id === "string" ? s.id : "?";
3152
+ if (typeof s?.name !== "string")
3153
+ problems.push(`state "${name}": name is required`);
3154
+ if (!["number", "string", "boolean", "json"].includes(s?.type)) {
3155
+ problems.push(`state "${name}": type must be number, string, boolean or json`);
3156
+ }
3157
+ if (s?.poll && (typeof s.poll.read !== "function" || !(s.poll.everyMs > 0))) {
3158
+ problems.push(`state "${name}": poll needs read() and everyMs > 0`);
3159
+ }
3160
+ if (s?.start !== undefined && typeof s.start !== "function") {
3161
+ problems.push(`state "${name}": start must be a function`);
3162
+ }
3163
+ }
3164
+ }
3165
+ }
3166
+ if (def.triggers !== undefined) {
3167
+ if (!Array.isArray(def.triggers))
3168
+ problems.push("triggers must be an array");
3169
+ else {
3170
+ checkLocalIds("trigger", def.triggers, problems);
3171
+ for (const t of def.triggers) {
3172
+ const name = typeof t?.id === "string" ? t.id : "?";
3173
+ if (typeof t?.name !== "string")
3174
+ problems.push(`trigger "${name}": name is required`);
3175
+ if (typeof t?.subscribe !== "function") {
3176
+ problems.push(`trigger "${name}": subscribe is required`);
3177
+ }
3178
+ for (const p of checkSchema(t?.settings ?? {}, sources)) {
3179
+ problems.push(`trigger "${name}": ${p}`);
3180
+ }
3181
+ }
3182
+ }
3183
+ }
3184
+ return problems;
3185
+ }
3186
+ function checkOnboarding(def) {
3187
+ const onboarding = def.onboarding;
3188
+ if (!Array.isArray(onboarding?.steps))
3189
+ return ["onboarding: steps must be an array"];
3190
+ const problems = [];
3191
+ checkLocalIds("onboarding step", onboarding.steps, problems);
3192
+ const settings = def.settings ?? {};
3193
+ const commands = new Set((def.commands ?? []).map((c) => c.id));
3194
+ for (const step of onboarding.steps) {
3195
+ const name = typeof step?.id === "string" ? step.id : "?";
3196
+ if (typeof step?.title !== "string")
3197
+ problems.push(`onboarding step "${name}": title is required`);
3198
+ for (const key of step?.settings ?? []) {
3199
+ if (!(key in settings))
3200
+ problems.push(`onboarding step "${name}": no setting "${key}"`);
3201
+ }
3202
+ if (step?.command !== undefined && !commands.has(step.command)) {
3203
+ problems.push(`onboarding step "${name}": no command "${step.command}"`);
3204
+ }
3205
+ if (step?.done !== undefined && typeof step.done !== "function") {
3206
+ problems.push(`onboarding step "${name}": done must be a function`);
3207
+ }
3208
+ }
3209
+ const page = onboarding.starterPage;
3210
+ if (page) {
3211
+ const actions = new Set((def.actions ?? []).map((a) => a.id));
3212
+ const used = [
3213
+ ...Object.values(page.keys ?? {}),
3214
+ ...Object.values(page.sensors ?? {}),
3215
+ ...page.window ? [page.window] : []
3216
+ ];
3217
+ for (const { action } of used) {
3218
+ if (!actions.has(action))
3219
+ problems.push(`onboarding starter page: no action "${action}"`);
3220
+ }
3221
+ }
3222
+ return problems;
3223
+ }
3224
+
3225
+ // src/manifest.ts
3226
+ var PLUGIN_KEYWORD = "sdeck-plugin";
3227
+ var HOST_MODULES = [
3228
+ "react",
3229
+ "react/jsx-runtime",
3230
+ "react/jsx-dev-runtime",
3231
+ "@sdeck/plugin",
3232
+ "@sdeck/app",
3233
+ "@sdeck/core",
3234
+ "@sdeck/engine",
3235
+ "@sdeck/schema"
3236
+ ];
3237
+ var SUPPORTED_API_VERSIONS = [1, PLUGIN_API_VERSION];
3238
+ function parseManifest(pkg) {
3239
+ if (!pkg || typeof pkg !== "object")
3240
+ return { ok: false, error: "package.json is not an object" };
3241
+ const p = pkg;
3242
+ const sdeck = p.sdeck;
3243
+ if (typeof p.name !== "string")
3244
+ return { ok: false, error: "package.json has no name" };
3245
+ if (!sdeck || typeof sdeck !== "object") {
3246
+ return { ok: false, error: `${p.name} is not an sdeck plugin (no "sdeck" field)` };
3247
+ }
3248
+ const apiVersion = sdeck.apiVersion;
3249
+ if (typeof apiVersion !== "number" || !SUPPORTED_API_VERSIONS.includes(apiVersion)) {
3250
+ return {
3251
+ ok: false,
3252
+ error: `${p.name} targets plugin API ${String(apiVersion)}, this host supports ${SUPPORTED_API_VERSIONS.join(" and ")}`
3253
+ };
3254
+ }
3255
+ const entry = typeof sdeck.entry === "string" ? sdeck.entry : typeof p.main === "string" ? p.main : "index.js";
3256
+ return {
3257
+ ok: true,
3258
+ manifest: {
3259
+ name: p.name,
3260
+ version: typeof p.version === "string" ? p.version : "0.0.0",
3261
+ ...typeof p.description === "string" && { description: p.description },
3262
+ entry,
3263
+ apiVersion
3264
+ }
3265
+ };
3266
+ }
3267
+ // src/shared.ts
3268
+ class Shared {
3269
+ #listeners = new Set;
3270
+ #start;
3271
+ #stop;
3272
+ #last;
3273
+ constructor(start) {
3274
+ this.#start = start;
3275
+ }
3276
+ get last() {
3277
+ return this.#last?.value;
3278
+ }
3279
+ listen(listener) {
3280
+ this.#listeners.add(listener);
3281
+ if (!this.#stop) {
3282
+ this.#stop = this.#start((value) => {
3283
+ this.#last = { value };
3284
+ for (const l of [...this.#listeners])
3285
+ l(value);
3286
+ });
3287
+ }
3288
+ return () => {
3289
+ this.#listeners.delete(listener);
3290
+ if (this.#listeners.size === 0) {
3291
+ this.#stop?.();
3292
+ this.#stop = undefined;
3293
+ this.#last = undefined;
3294
+ }
3295
+ };
3296
+ }
3297
+ }
3298
+ export {
3299
+ BackButton,
3300
+ Clock,
3301
+ HOST_MODULES,
3302
+ HostBridgeContext,
3303
+ KeyButton,
3304
+ ManagedConnection,
3305
+ Navigator,
3306
+ PERMISSIONS,
3307
+ PLUGIN_API_VERSION,
3308
+ PLUGIN_KEYWORD,
3309
+ PermanentError,
3310
+ SUPPORTED_API_VERSIONS,
3311
+ SWIPE_WINDOW_MS,
3312
+ SensorButton,
3313
+ Shared,
3314
+ checkPlugin,
3315
+ checkSchema,
3316
+ defaultValue,
3317
+ defineAction,
3318
+ defineApp,
3319
+ definePlugin,
3320
+ defineTrigger,
3321
+ isFieldVisible,
3322
+ mountApp,
3323
+ parseManifest,
3324
+ pluginNamespace,
3325
+ resolveSettings,
3326
+ runApp,
3327
+ useDeck,
3328
+ useExpression,
3329
+ useHostState,
3330
+ useImage,
3331
+ useInterval,
3332
+ useKeyDown,
3333
+ useKeyPress,
3334
+ useKeyPressed,
3335
+ useKeyRepeat,
3336
+ useKeyUp,
3337
+ useNavigation,
3338
+ useNow,
3339
+ usePage,
3340
+ useRunAction,
3341
+ useSensorDown,
3342
+ useSensorPress,
3343
+ useSensorPressed,
3344
+ useSensorRepeat,
3345
+ useSensorUp,
3346
+ useSlot,
3347
+ useSwipe,
3348
+ useTemplate,
3349
+ useVariable
3350
+ };
3351
+
3352
+ //# debugId=317791B36DA824C564756E2164756E21