@sdeck/plugin-system 0.0.0-stage → 0.2.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,2417 @@
1
+ // @bun
2
+ // src/index.tsx
3
+ import { execFile as execFile3, spawn as spawn3 } from "child_process";
4
+ import { cpus as cpus2, freemem, homedir as homedir3, totalmem } from "os";
5
+ import { basename, join as join3 } from "path";
6
+
7
+ // ../core/src/element.ts
8
+ var runtime;
9
+ function registerElementRuntime(next) {
10
+ runtime = next;
11
+ }
12
+ // ../react/src/render.ts
13
+ function isReactElement(value) {
14
+ return typeof value === "object" && value !== null && "$$typeof" in value;
15
+ }
16
+ var defaultRenderer = {};
17
+ var fontRenderers = new WeakMap;
18
+ async function createRenderer(fonts) {
19
+ const { Renderer } = await import("@takumi-rs/core");
20
+ const renderer = new Renderer;
21
+ for (const font of fonts) {
22
+ await renderer.registerFont({
23
+ name: font.name,
24
+ data: font.data,
25
+ ...font.weight !== undefined && { weight: font.weight },
26
+ ...font.style !== undefined && { style: font.style }
27
+ });
28
+ }
29
+ return renderer;
30
+ }
31
+ function getRenderer(fonts) {
32
+ if (!fonts?.length) {
33
+ defaultRenderer.current ??= createRenderer([]);
34
+ defaultRenderer.current.catch(() => {
35
+ defaultRenderer.current = undefined;
36
+ });
37
+ return defaultRenderer.current;
38
+ }
39
+ let renderer = fontRenderers.get(fonts);
40
+ if (!renderer) {
41
+ renderer = createRenderer(fonts);
42
+ renderer.catch(() => fontRenderers.delete(fonts));
43
+ fontRenderers.set(fonts, renderer);
44
+ }
45
+ return renderer;
46
+ }
47
+ var number = (value) => typeof value === "number" && Number.isFinite(value) ? value : undefined;
48
+ function toNode(node, text = true) {
49
+ if ("text" in node) {
50
+ return text ? { type: "text", text: node.text } : { type: "container", children: [] };
51
+ }
52
+ const { style, tw, src, width, height } = node.props;
53
+ const common = {
54
+ ...typeof tw === "string" && { tw }
55
+ };
56
+ if (node.type === "img") {
57
+ if (typeof src !== "string")
58
+ throw new Error("<img> needs a string `src` (URL or data: URI)");
59
+ return {
60
+ type: "image",
61
+ src,
62
+ ...number(width) !== undefined && { width: number(width) },
63
+ ...number(height) !== undefined && { height: number(height) },
64
+ ...typeof style === "object" && style !== null && { style },
65
+ ...common
66
+ };
67
+ }
68
+ return {
69
+ type: "container",
70
+ style: { display: "flex", ...typeof style === "object" ? style : {} },
71
+ children: node.children.filter((child) => text || !("text" in child)).map((child) => toNode(child, text)),
72
+ ...common
73
+ };
74
+ }
75
+ var reconciler;
76
+ var flushing = 0;
77
+ function flushAll(renderer) {
78
+ flushing++;
79
+ try {
80
+ renderer.flushSyncWork();
81
+ for (let i = 0;i < 20 && renderer.flushPassiveEffects(); i++)
82
+ renderer.flushSyncWork();
83
+ } finally {
84
+ flushing--;
85
+ }
86
+ }
87
+ function loadReconciler() {
88
+ reconciler ??= (async () => {
89
+ let factoryModule;
90
+ let constants;
91
+ let React;
92
+ try {
93
+ [factoryModule, constants, React] = await Promise.all([
94
+ import("react-reconciler"),
95
+ import("react-reconciler/constants.js"),
96
+ import("react")
97
+ ]);
98
+ } catch (cause) {
99
+ throw new Error("Rendering React elements requires `react` (>=19.3) to be installed", {
100
+ cause
101
+ });
102
+ }
103
+ let priority = constants.NoEventPriority;
104
+ const noop = () => {};
105
+ const hostConfig = {
106
+ supportsMutation: true,
107
+ supportsPersistence: false,
108
+ supportsHydration: false,
109
+ isPrimaryRenderer: true,
110
+ warnsIfNotActing: false,
111
+ noTimeout: -1,
112
+ scheduleTimeout: setTimeout,
113
+ cancelTimeout: clearTimeout,
114
+ supportsMicrotasks: true,
115
+ scheduleMicrotask: queueMicrotask,
116
+ createInstance: (type, props) => {
117
+ const { children: _children, ...rest } = props;
118
+ return { type, props: rest, children: [] };
119
+ },
120
+ createTextInstance: (text) => ({ text }),
121
+ shouldSetTextContent: () => false,
122
+ appendInitialChild: (parent, child) => parent.children.push(child),
123
+ appendChild: (parent, child) => parent.children.push(child),
124
+ appendChildToContainer: (container, child) => container.children.push(child),
125
+ insertBefore: (parent, child, before) => {
126
+ const children = parent.children;
127
+ const existing = children.indexOf(child);
128
+ if (existing !== -1)
129
+ children.splice(existing, 1);
130
+ children.splice(children.indexOf(before), 0, child);
131
+ },
132
+ insertInContainerBefore: (container, child, before) => {
133
+ const children = container.children;
134
+ const existing = children.indexOf(child);
135
+ if (existing !== -1)
136
+ children.splice(existing, 1);
137
+ children.splice(children.indexOf(before), 0, child);
138
+ },
139
+ removeChild: (parent, child) => {
140
+ parent.children.splice(parent.children.indexOf(child), 1);
141
+ },
142
+ removeChildFromContainer: (container, child) => {
143
+ container.children.splice(container.children.indexOf(child), 1);
144
+ },
145
+ clearContainer: (container) => {
146
+ container.children = [];
147
+ },
148
+ commitUpdate: (instance, _type, _prev, next) => {
149
+ const { children: _children, ...rest } = next;
150
+ instance.props = rest;
151
+ },
152
+ commitTextUpdate: (text, _old, next) => {
153
+ text.text = next;
154
+ },
155
+ finalizeInitialChildren: () => false,
156
+ getPublicInstance: (instance) => instance,
157
+ getRootHostContext: () => ({}),
158
+ getChildHostContext: (parent) => parent,
159
+ prepareForCommit: () => null,
160
+ resetAfterCommit: (container) => container.onCommit(),
161
+ preparePortalMount: noop,
162
+ detachDeletedInstance: noop,
163
+ hideInstance: noop,
164
+ unhideInstance: noop,
165
+ hideTextInstance: noop,
166
+ unhideTextInstance: noop,
167
+ getInstanceFromNode: () => null,
168
+ beforeActiveInstanceBlur: noop,
169
+ afterActiveInstanceBlur: noop,
170
+ prepareScopeUpdate: noop,
171
+ getInstanceFromScope: () => null,
172
+ bindToConsole: (method, args) => console[method]?.bind(console, ...args) ?? noop,
173
+ extraDevToolsConfig: null,
174
+ rendererVersion: "0.0.0",
175
+ rendererPackageName: "sdeck",
176
+ getCurrentUpdatePriority: () => priority,
177
+ setCurrentUpdatePriority: (next) => {
178
+ priority = next;
179
+ },
180
+ resolveUpdatePriority: () => priority !== constants.NoEventPriority ? priority : flushing > 0 ? constants.DiscreteEventPriority : constants.DefaultEventPriority,
181
+ resolveEventType: () => null,
182
+ resolveEventTimeStamp: () => -1.1,
183
+ shouldAttemptEagerTransition: () => false,
184
+ trackSchedulerEvent: noop,
185
+ requestPostPaintCallback: noop,
186
+ maySuspendCommit: () => false,
187
+ preloadInstance: () => true,
188
+ startSuspendingCommit: noop,
189
+ suspendInstance: noop,
190
+ waitForCommitToBeReady: () => null,
191
+ getSuspendedCommitReason: () => null,
192
+ NotPendingTransition: null,
193
+ HostTransitionContext: React.createContext(null),
194
+ resetFormInstance: noop
195
+ };
196
+ const factory = factoryModule.default ?? factoryModule;
197
+ return factory(hostConfig);
198
+ })();
199
+ reconciler.catch(() => {
200
+ reconciler = undefined;
201
+ });
202
+ return reconciler;
203
+ }
204
+ function noopIndicator() {}
205
+ async function createReactRoot(size, onFrame, options = {}) {
206
+ const [takumi, renderer] = await Promise.all([getRenderer(options.fonts), loadReconciler()]);
207
+ let dirty = false;
208
+ let drawing;
209
+ let lastTree;
210
+ let unmounted = false;
211
+ let renderError;
212
+ let initial = true;
213
+ const fail = (error) => {
214
+ if (initial)
215
+ renderError ??= { error };
216
+ else
217
+ (options.onError ?? ((e) => console.error("sdeck: React render failed:", e)))(error);
218
+ };
219
+ async function draw() {
220
+ await Promise.resolve();
221
+ while (dirty && !unmounted) {
222
+ dirty = false;
223
+ try {
224
+ const [root] = container.children;
225
+ if (!root)
226
+ continue;
227
+ const tree = toNode(root, options.text !== false);
228
+ const key = JSON.stringify(tree);
229
+ if (key === lastTree)
230
+ continue;
231
+ lastTree = key;
232
+ const pixels = await takumi.render(tree, {
233
+ width: size.width,
234
+ height: size.height,
235
+ format: "raw",
236
+ ...options.scale !== undefined && { devicePixelRatio: options.scale }
237
+ });
238
+ await onFrame({
239
+ data: new Uint8Array(pixels.buffer, pixels.byteOffset, pixels.byteLength),
240
+ width: size.width,
241
+ height: size.height,
242
+ channels: 4
243
+ });
244
+ } catch (error) {
245
+ lastTree = undefined;
246
+ fail(error);
247
+ }
248
+ }
249
+ drawing = undefined;
250
+ }
251
+ const container = {
252
+ children: [],
253
+ onCommit() {
254
+ dirty = true;
255
+ drawing ??= draw();
256
+ }
257
+ };
258
+ const onError = (error) => fail(error);
259
+ const onCaughtError = () => {};
260
+ const root = renderer.createContainer(container, 1, null, false, null, "", onError, onCaughtError, onError, noopIndicator, null);
261
+ const flush = () => flushAll(renderer);
262
+ const handle = {
263
+ render(element) {
264
+ if (unmounted)
265
+ throw new Error("This React root was unmounted");
266
+ renderer.updateContainerSync(element, root, null, null);
267
+ flush();
268
+ },
269
+ async idle() {
270
+ while (drawing)
271
+ await drawing;
272
+ if (initial && renderError) {
273
+ const { error } = renderError;
274
+ renderError = undefined;
275
+ throw error;
276
+ }
277
+ initial = false;
278
+ },
279
+ async unmount() {
280
+ if (unmounted)
281
+ return;
282
+ renderer.updateContainerSync(null, root, null, null);
283
+ flush();
284
+ unmounted = true;
285
+ await drawing;
286
+ }
287
+ };
288
+ return handle;
289
+ }
290
+ async function renderReact(element, size, fonts, scale) {
291
+ let frame;
292
+ const root = await createReactRoot(size, (next) => {
293
+ frame = next;
294
+ }, { ...fonts && { fonts }, ...scale !== undefined && { scale } });
295
+ try {
296
+ root.render(element);
297
+ await root.idle();
298
+ } finally {
299
+ await root.unmount();
300
+ }
301
+ if (!frame)
302
+ throw new Error("React element rendered nothing");
303
+ return frame;
304
+ }
305
+ registerElementRuntime({
306
+ matches: isReactElement,
307
+ render: (element, size, options) => renderReact(element, size, options?.fonts),
308
+ createRoot: (size, onFrame, options) => createReactRoot(size, onFrame, options)
309
+ });
310
+ // ../app/src/app.tsx
311
+ import { Fragment, useSyncExternalStore } from "react";
312
+
313
+ // ../app/src/context.ts
314
+ import { createContext, useContext } from "react";
315
+ var DeckContext = createContext(undefined);
316
+ var SlotContext = createContext(undefined);
317
+ var NavigatorContext = createContext(undefined);
318
+ // ../app/src/hooks.ts
319
+ import { useContext as useContext2, useEffect, useRef, useState, useSyncExternalStore as useSyncExternalStore2 } from "react";
320
+
321
+ // ../app/src/swipe.ts
322
+ var trackers = new WeakMap;
323
+ // ../schema/src/keys.ts
324
+ var MODIFIER_NAMES = {
325
+ ctrl: "ctrl",
326
+ control: "ctrl",
327
+ alt: "alt",
328
+ option: "alt",
329
+ shift: "shift",
330
+ win: "win",
331
+ meta: "win",
332
+ super: "win",
333
+ cmd: "win",
334
+ command: "win"
335
+ };
336
+ var MODIFIER_ORDER = ["ctrl", "alt", "shift", "win"];
337
+ var MODIFIER_CODES = {
338
+ ctrl: 17,
339
+ alt: 18,
340
+ shift: 16,
341
+ win: 91
342
+ };
343
+ function range(prefix, first, last, code) {
344
+ const out = {};
345
+ for (let n = first;n <= last; n++)
346
+ out[`${prefix}${n}`] = code + n - first;
347
+ return out;
348
+ }
349
+ var KEY_CODES = {
350
+ ...Object.fromEntries(Array.from({ length: 26 }, (_, i) => [String.fromCharCode(97 + i), 65 + i])),
351
+ ...range("", 0, 9, 48),
352
+ ...range("f", 1, 24, 112),
353
+ ...range("num", 0, 9, 96),
354
+ backspace: 8,
355
+ tab: 9,
356
+ enter: 13,
357
+ pause: 19,
358
+ capslock: 20,
359
+ escape: 27,
360
+ space: 32,
361
+ pageup: 33,
362
+ pagedown: 34,
363
+ end: 35,
364
+ home: 36,
365
+ left: 37,
366
+ up: 38,
367
+ right: 39,
368
+ down: 40,
369
+ printscreen: 44,
370
+ insert: 45,
371
+ delete: 46,
372
+ menu: 93,
373
+ multiply: 106,
374
+ add: 107,
375
+ subtract: 109,
376
+ decimal: 110,
377
+ divide: 111,
378
+ numlock: 144,
379
+ scrolllock: 145,
380
+ volumemute: 173,
381
+ volumedown: 174,
382
+ volumeup: 175,
383
+ medianext: 176,
384
+ mediaprevious: 177,
385
+ mediastop: 178,
386
+ playpause: 179,
387
+ ";": 186,
388
+ "=": 187,
389
+ ",": 188,
390
+ "-": 189,
391
+ ".": 190,
392
+ "/": 191,
393
+ "`": 192,
394
+ "[": 219,
395
+ "\\": 220,
396
+ "]": 221,
397
+ "'": 222
398
+ };
399
+ var ALIASES = {
400
+ return: "enter",
401
+ esc: "escape",
402
+ del: "delete",
403
+ ins: "insert",
404
+ pgup: "pageup",
405
+ pgdn: "pagedown",
406
+ plus: "=",
407
+ minus: "-",
408
+ comma: ",",
409
+ period: ".",
410
+ prtsc: "printscreen",
411
+ spacebar: "space",
412
+ arrowleft: "left",
413
+ arrowup: "up",
414
+ arrowright: "right",
415
+ arrowdown: "down"
416
+ };
417
+ function parseAccelerator(text) {
418
+ const parts = text.split("+").map((p) => p.trim().toLowerCase()).filter(Boolean);
419
+ if (parts.length === 0)
420
+ throw new Error("no keys given");
421
+ const modifiers = new Set;
422
+ let key;
423
+ for (const part of parts) {
424
+ const modifier = MODIFIER_NAMES[part];
425
+ if (modifier) {
426
+ modifiers.add(modifier);
427
+ continue;
428
+ }
429
+ const name = ALIASES[part] ?? part;
430
+ if (!Object.hasOwn(KEY_CODES, name))
431
+ throw new Error(`unknown key "${part}"`);
432
+ if (key !== undefined)
433
+ throw new Error(`"${text}" has more than one key besides modifiers`);
434
+ key = name;
435
+ }
436
+ if (key === undefined) {
437
+ const only = modifiers.size === 1 ? [...modifiers][0] : undefined;
438
+ if (!only)
439
+ throw new Error(`"${text}" needs a key besides the modifiers`);
440
+ return { modifiers: [], key: only, code: MODIFIER_CODES[only] };
441
+ }
442
+ return {
443
+ modifiers: MODIFIER_ORDER.filter((m) => modifiers.has(m)),
444
+ key,
445
+ code: KEY_CODES[key]
446
+ };
447
+ }
448
+ function formatAccelerator(accelerator) {
449
+ return [...accelerator.modifiers, accelerator.key].join("+");
450
+ }
451
+ // ../schema/src/layers.ts
452
+ function iconLayer(id, icon, options = {}) {
453
+ const { color, size = 52, position = "middle", visible, row, frame } = options;
454
+ const src = /^[a-z0-9]+\/[A-Za-z0-9-]+$/.test(icon) ? `icon:${icon}` : icon;
455
+ return {
456
+ id,
457
+ type: "image",
458
+ src,
459
+ size,
460
+ position,
461
+ ...color && { color },
462
+ ...visible && { visible },
463
+ ...row && { row },
464
+ ...frame && { frame }
465
+ };
466
+ }
467
+ function iconLook(options) {
468
+ const { icon, background, caption = "", color = "#ffffff" } = options;
469
+ return {
470
+ background,
471
+ layers: [
472
+ iconLayer("icon", icon, {
473
+ color,
474
+ size: caption ? 46 : 58,
475
+ position: caption ? "top" : "middle"
476
+ }),
477
+ ...caption ? [textLayer("label", caption, { color, size: 13, position: "bottom" })] : []
478
+ ]
479
+ };
480
+ }
481
+ function textLayer(id, text, options = {}) {
482
+ const { color = "#ffffff", size = 14, weight = 700, position = "middle" } = options;
483
+ const { visible, row, frame } = options;
484
+ return {
485
+ id,
486
+ type: "text",
487
+ text,
488
+ color,
489
+ size,
490
+ weight,
491
+ position,
492
+ ...visible && { visible },
493
+ ...row && { row },
494
+ ...frame && { frame }
495
+ };
496
+ }
497
+ // ../plugin/src/settings.ts
498
+ function checkSchema(schema, sources = {}) {
499
+ const problems = [];
500
+ const types = new Set([
501
+ "text",
502
+ "number",
503
+ "boolean",
504
+ "color",
505
+ "select",
506
+ "page",
507
+ "image",
508
+ "secret"
509
+ ]);
510
+ for (const [key, field] of Object.entries(schema)) {
511
+ if (!field || typeof field !== "object" || !types.has(field.type)) {
512
+ problems.push(`setting "${key}" has an unknown type`);
513
+ continue;
514
+ }
515
+ if (typeof field.label !== "string")
516
+ problems.push(`setting "${key}" needs a label`);
517
+ const source = "source" in field ? field.source : undefined;
518
+ if (source !== undefined && !(source in sources)) {
519
+ problems.push(`setting "${key}" uses unknown option source "${source}"`);
520
+ }
521
+ if (field.type === "select" && (!Array.isArray(field.options) || field.options.length === 0 && source === undefined)) {
522
+ problems.push(`setting "${key}" needs at least one option or a source`);
523
+ }
524
+ for (const other of "dependsOn" in field && field.dependsOn || []) {
525
+ if (!(other in schema))
526
+ problems.push(`setting "${key}" depends on unknown "${other}"`);
527
+ }
528
+ if (field.visibleIf !== undefined) {
529
+ for (const other of Object.keys(field.visibleIf)) {
530
+ if (!(other in schema))
531
+ problems.push(`setting "${key}" depends on unknown "${other}"`);
532
+ }
533
+ }
534
+ }
535
+ return problems;
536
+ }
537
+
538
+ // ../plugin/src/plugin.ts
539
+ var PERMISSIONS = [
540
+ "shell",
541
+ "process",
542
+ "filesystem",
543
+ "network",
544
+ "input",
545
+ "audio",
546
+ "clipboard"
547
+ ];
548
+ var ID = /^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*$/;
549
+ var NAMESPACE = /^[a-z][\w-]{0,31}$/;
550
+ var LOCAL_ID = /^[\w.-]+$/;
551
+ function defineAction(def) {
552
+ return {
553
+ ...def,
554
+ slots: def.slots ?? ["key"],
555
+ settings: def.settings ?? {}
556
+ };
557
+ }
558
+ function defineTrigger(def) {
559
+ return { ...def, settings: def.settings ?? {} };
560
+ }
561
+ function definePlugin(def) {
562
+ const problems = checkPlugin(def);
563
+ if (problems.length > 0) {
564
+ throw new TypeError(`invalid plugin "${def?.id}": ${problems.join("; ")}`);
565
+ }
566
+ return def;
567
+ }
568
+ function checkLocalIds(kind, items, problems) {
569
+ const seen = new Set;
570
+ for (const item of items) {
571
+ const name = typeof item?.id === "string" ? item.id : "?";
572
+ if (typeof item?.id !== "string" || !LOCAL_ID.test(item.id)) {
573
+ problems.push(`${kind} "${name}": id must be letters, digits, ".", "-" or "_"`);
574
+ } else if (seen.has(item.id)) {
575
+ problems.push(`${kind} "${name}" is defined twice`);
576
+ }
577
+ seen.add(name);
578
+ }
579
+ return seen;
580
+ }
581
+ function checkPlugin(value) {
582
+ if (!value || typeof value !== "object")
583
+ return ["not an object"];
584
+ const def = value;
585
+ const problems = [];
586
+ if (typeof def.id !== "string" || !ID.test(def.id)) {
587
+ problems.push("id must be a package-style name (lowercase, e.g. `my-plugin` or `@me/plugin`)");
588
+ }
589
+ if (typeof def.name !== "string" || def.name === "")
590
+ problems.push("name is required");
591
+ if (typeof def.version !== "string" || def.version === "")
592
+ problems.push("version is required");
593
+ if (def.namespace !== undefined && !NAMESPACE.test(def.namespace)) {
594
+ problems.push("namespace must be lowercase letters, digits, - or _ (starting with a letter)");
595
+ }
596
+ if (def.activate !== undefined && typeof def.activate !== "function") {
597
+ problems.push("activate must be a function");
598
+ }
599
+ if (def.permissions !== undefined) {
600
+ if (!Array.isArray(def.permissions))
601
+ problems.push("permissions must be an array");
602
+ else
603
+ for (const p of def.permissions)
604
+ if (!PERMISSIONS.includes(p))
605
+ problems.push(`unknown permission "${String(p)}"`);
606
+ }
607
+ if (def.settings !== undefined) {
608
+ for (const p of checkSchema(def.settings, def.optionSources ?? {})) {
609
+ problems.push(`plugin ${p}`);
610
+ }
611
+ }
612
+ if (def.commands !== undefined) {
613
+ if (!Array.isArray(def.commands))
614
+ problems.push("commands must be an array");
615
+ else {
616
+ checkLocalIds("command", def.commands, problems);
617
+ for (const c of def.commands) {
618
+ const name = typeof c?.id === "string" ? c.id : "?";
619
+ if (typeof c?.name !== "string")
620
+ problems.push(`command "${name}": name is required`);
621
+ if (typeof c?.run !== "function")
622
+ problems.push(`command "${name}": run is required`);
623
+ }
624
+ }
625
+ }
626
+ if (def.onboarding !== undefined)
627
+ problems.push(...checkOnboarding(def));
628
+ const sources = def.optionSources ?? {};
629
+ if (typeof sources !== "object")
630
+ problems.push("optionSources must be an object");
631
+ else
632
+ for (const [name, fn] of Object.entries(sources))
633
+ if (typeof fn !== "function")
634
+ problems.push(`option source "${name}" must be a function`);
635
+ if (!Array.isArray(def.actions))
636
+ return [...problems, "actions must be an array"];
637
+ checkLocalIds("action", def.actions, problems);
638
+ for (const action of def.actions) {
639
+ const name = typeof action?.id === "string" ? action.id : "?";
640
+ if (typeof action?.name !== "string")
641
+ problems.push(`action "${name}": name is required`);
642
+ const hasComponent = typeof action?.component === "function" || typeof action?.component === "object";
643
+ const hasRun = typeof action?.run === "function";
644
+ if (!hasComponent && !hasRun)
645
+ problems.push(`action "${name}": needs run or component`);
646
+ if (action?.look !== undefined && typeof action.look !== "function") {
647
+ problems.push(`action "${name}": look must be a function`);
648
+ }
649
+ const slots = action?.slots ?? ["key"];
650
+ if (!Array.isArray(slots) || slots.length === 0 || slots.some((s) => !["key", "sensor", "window"].includes(s))) {
651
+ problems.push(`action "${name}": slots must list "key", "sensor" and/or "window"`);
652
+ }
653
+ for (const p of checkSchema(action?.settings ?? {}, sources)) {
654
+ problems.push(`action "${name}": ${p}`);
655
+ }
656
+ for (const [key, field] of Object.entries(action?.settings ?? {})) {
657
+ if (field?.type === "secret") {
658
+ problems.push(`action "${name}": setting "${key}": secrets belong in the plugin settings`);
659
+ }
660
+ }
661
+ }
662
+ if (def.state !== undefined) {
663
+ if (!Array.isArray(def.state))
664
+ problems.push("state must be an array");
665
+ else {
666
+ checkLocalIds("state", def.state, problems);
667
+ for (const s of def.state) {
668
+ const name = typeof s?.id === "string" ? s.id : "?";
669
+ if (typeof s?.name !== "string")
670
+ problems.push(`state "${name}": name is required`);
671
+ if (!["number", "string", "boolean", "json"].includes(s?.type)) {
672
+ problems.push(`state "${name}": type must be number, string, boolean or json`);
673
+ }
674
+ if (s?.poll && (typeof s.poll.read !== "function" || !(s.poll.everyMs > 0))) {
675
+ problems.push(`state "${name}": poll needs read() and everyMs > 0`);
676
+ }
677
+ if (s?.start !== undefined && typeof s.start !== "function") {
678
+ problems.push(`state "${name}": start must be a function`);
679
+ }
680
+ }
681
+ }
682
+ }
683
+ if (def.triggers !== undefined) {
684
+ if (!Array.isArray(def.triggers))
685
+ problems.push("triggers must be an array");
686
+ else {
687
+ checkLocalIds("trigger", def.triggers, problems);
688
+ for (const t of def.triggers) {
689
+ const name = typeof t?.id === "string" ? t.id : "?";
690
+ if (typeof t?.name !== "string")
691
+ problems.push(`trigger "${name}": name is required`);
692
+ if (typeof t?.subscribe !== "function") {
693
+ problems.push(`trigger "${name}": subscribe is required`);
694
+ }
695
+ for (const p of checkSchema(t?.settings ?? {}, sources)) {
696
+ problems.push(`trigger "${name}": ${p}`);
697
+ }
698
+ }
699
+ }
700
+ }
701
+ return problems;
702
+ }
703
+ function checkOnboarding(def) {
704
+ const onboarding = def.onboarding;
705
+ if (!Array.isArray(onboarding?.steps))
706
+ return ["onboarding: steps must be an array"];
707
+ const problems = [];
708
+ checkLocalIds("onboarding step", onboarding.steps, problems);
709
+ const settings = def.settings ?? {};
710
+ const commands = new Set((def.commands ?? []).map((c) => c.id));
711
+ for (const step of onboarding.steps) {
712
+ const name = typeof step?.id === "string" ? step.id : "?";
713
+ if (typeof step?.title !== "string")
714
+ problems.push(`onboarding step "${name}": title is required`);
715
+ for (const key of step?.settings ?? []) {
716
+ if (!(key in settings))
717
+ problems.push(`onboarding step "${name}": no setting "${key}"`);
718
+ }
719
+ if (step?.command !== undefined && !commands.has(step.command)) {
720
+ problems.push(`onboarding step "${name}": no command "${step.command}"`);
721
+ }
722
+ if (step?.done !== undefined && typeof step.done !== "function") {
723
+ problems.push(`onboarding step "${name}": done must be a function`);
724
+ }
725
+ }
726
+ const page = onboarding.starterPage;
727
+ if (page) {
728
+ const actions = new Set((def.actions ?? []).map((a) => a.id));
729
+ const used = [
730
+ ...Object.values(page.keys ?? {}),
731
+ ...Object.values(page.sensors ?? {}),
732
+ ...page.window ? [page.window] : []
733
+ ];
734
+ for (const { action } of used) {
735
+ if (!actions.has(action))
736
+ problems.push(`onboarding starter page: no action "${action}"`);
737
+ }
738
+ }
739
+ return problems;
740
+ }
741
+ // ../plugin/src/shared.ts
742
+ class Shared {
743
+ #listeners = new Set;
744
+ #start;
745
+ #stop;
746
+ #last;
747
+ constructor(start) {
748
+ this.#start = start;
749
+ }
750
+ get last() {
751
+ return this.#last?.value;
752
+ }
753
+ listen(listener) {
754
+ this.#listeners.add(listener);
755
+ if (!this.#stop) {
756
+ this.#stop = this.#start((value) => {
757
+ this.#last = { value };
758
+ for (const l of [...this.#listeners])
759
+ l(value);
760
+ });
761
+ }
762
+ return () => {
763
+ this.#listeners.delete(listener);
764
+ if (this.#listeners.size === 0) {
765
+ this.#stop?.();
766
+ this.#stop = undefined;
767
+ this.#last = undefined;
768
+ }
769
+ };
770
+ }
771
+ }
772
+ // src/controls.ts
773
+ import { execFile } from "child_process";
774
+ import { mkdir } from "fs/promises";
775
+ import { dirname } from "path";
776
+ var MEDIA_KEYS = {
777
+ "play-pause": "playpause",
778
+ next: "medianext",
779
+ previous: "mediaprevious",
780
+ stop: "mediastop",
781
+ mute: "volumemute",
782
+ "volume-up": "volumeup",
783
+ "volume-down": "volumedown"
784
+ };
785
+ var EXTENDED = 1;
786
+ var KEY_UP = 2;
787
+ var UNICODE = 4;
788
+ var EXTENDED_KEYS = new Set([
789
+ 33,
790
+ 34,
791
+ 35,
792
+ 36,
793
+ 37,
794
+ 38,
795
+ 39,
796
+ 40,
797
+ 44,
798
+ 45,
799
+ 46,
800
+ 91,
801
+ 93,
802
+ 111,
803
+ 144,
804
+ 173,
805
+ 174,
806
+ 175,
807
+ 176,
808
+ 177,
809
+ 178,
810
+ 179
811
+ ]);
812
+ function hotkeyEvents(accelerator) {
813
+ const codes = [...accelerator.modifiers.map((m) => MODIFIER_CODES[m]), accelerator.code];
814
+ const event = (vk, up) => ({
815
+ vk,
816
+ scan: 0,
817
+ flags: (EXTENDED_KEYS.has(vk) ? EXTENDED : 0) | (up ? KEY_UP : 0)
818
+ });
819
+ return [...codes.map((c) => event(c, false)), ...codes.reverse().map((c) => event(c, true))];
820
+ }
821
+ function textEvents(text) {
822
+ const events = [];
823
+ const normalized = text.replace(/\r\n?/g, `
824
+ `);
825
+ for (let i = 0;i < normalized.length; i++) {
826
+ const unit = normalized.charCodeAt(i);
827
+ if (unit === 10 || unit === 9) {
828
+ const vk = unit === 10 ? 13 : 9;
829
+ events.push({ vk, scan: 0, flags: 0 }, { vk, scan: 0, flags: KEY_UP });
830
+ } else {
831
+ events.push({ vk: 0, scan: unit, flags: UNICODE }, { vk: 0, scan: unit, flags: UNICODE | KEY_UP });
832
+ }
833
+ }
834
+ return events;
835
+ }
836
+ var INPUT_SIZE = 40;
837
+ function encodeInputs(events) {
838
+ const buffer = new Uint8Array(events.length * INPUT_SIZE);
839
+ const view = new DataView(buffer.buffer);
840
+ events.forEach((event, i) => {
841
+ const at = i * INPUT_SIZE;
842
+ view.setUint32(at, 1, true);
843
+ view.setUint16(at + 8, event.vk, true);
844
+ view.setUint16(at + 10, event.scan, true);
845
+ view.setUint32(at + 12, event.flags, true);
846
+ });
847
+ return buffer;
848
+ }
849
+ function run(file, args, env) {
850
+ return new Promise((resolve, reject) => {
851
+ execFile(file, args, { windowsHide: true, timeout: 30000, ...env && { env: { ...process.env, ...env } } }, (error, _stdout, stderr) => {
852
+ if (!error)
853
+ return resolve();
854
+ if (error.code === "ENOENT") {
855
+ return reject(new Error(`this needs "${file}", which is not installed`));
856
+ }
857
+ reject(new Error(stderr.trim() || error.message));
858
+ });
859
+ });
860
+ }
861
+ var WINDOWS_SCREENSHOT = `
862
+ $ErrorActionPreference = "Stop"
863
+ Add-Type -AssemblyName System.Windows.Forms, System.Drawing
864
+ Add-Type -Name Dpi -Namespace Sdeck -MemberDefinition '[System.Runtime.InteropServices.DllImport("user32.dll")] public static extern bool SetProcessDPIAware();'
865
+ [void][Sdeck.Dpi]::SetProcessDPIAware()
866
+ $area = [System.Windows.Forms.SystemInformation]::VirtualScreen
867
+ $image = New-Object System.Drawing.Bitmap $area.Width, $area.Height
868
+ $graphics = [System.Drawing.Graphics]::FromImage($image)
869
+ $graphics.CopyFromScreen($area.Location, [System.Drawing.Point]::Empty, $area.Size)
870
+ $image.Save($env:SDECK_SCREENSHOT, [System.Drawing.Imaging.ImageFormat]::Png)
871
+ $graphics.Dispose(); $image.Dispose()
872
+ `;
873
+ async function windowsControls() {
874
+ const { dlopen, FFIType, ptr } = await import("bun:ffi");
875
+ const user32 = dlopen("user32.dll", {
876
+ SendInput: { args: [FFIType.u32, FFIType.ptr, FFIType.i32], returns: FFIType.u32 },
877
+ LockWorkStation: { args: [], returns: FFIType.i32 }
878
+ });
879
+ const power = dlopen("powrprof.dll", {
880
+ SetSuspendState: { args: [FFIType.u8, FFIType.u8, FFIType.u8], returns: FFIType.u8 }
881
+ });
882
+ const send = (events) => {
883
+ for (let i = 0;i < events.length; i += 200) {
884
+ const batch = events.slice(i, i + 200);
885
+ const sent = user32.symbols.SendInput(batch.length, ptr(encodeInputs(batch)), INPUT_SIZE);
886
+ if (sent !== batch.length) {
887
+ throw new Error("Windows blocked the input (is the focused app running as administrator?)");
888
+ }
889
+ }
890
+ };
891
+ return {
892
+ media: async (key) => send(hotkeyEvents(parseAccelerator(MEDIA_KEYS[key]))),
893
+ hotkey: async (accelerator) => send(hotkeyEvents(accelerator)),
894
+ type: async (text) => send(textEvents(text)),
895
+ lock: async () => {
896
+ if (!user32.symbols.LockWorkStation())
897
+ throw new Error("Windows refused to lock");
898
+ },
899
+ sleep: async () => {
900
+ if (!power.symbols.SetSuspendState(0, 0, 0))
901
+ throw new Error("Windows refused to sleep");
902
+ },
903
+ screenshot: async (file) => {
904
+ await mkdir(dirname(file), { recursive: true });
905
+ const encoded = Buffer.from(WINDOWS_SCREENSHOT, "utf16le").toString("base64");
906
+ await run("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], {
907
+ SDECK_SCREENSHOT: file
908
+ });
909
+ },
910
+ snip: async () => send(hotkeyEvents(parseAccelerator("win+shift+s")))
911
+ };
912
+ }
913
+ var appleString = (text) => `"${text.replace(/[\\"]/g, "\\$&")}"`;
914
+ var MAC_KEY_CODES = {
915
+ enter: 36,
916
+ tab: 48,
917
+ space: 49,
918
+ backspace: 51,
919
+ escape: 53,
920
+ left: 123,
921
+ right: 124,
922
+ down: 125,
923
+ up: 126
924
+ };
925
+ var MAC_MODIFIERS = {
926
+ ctrl: "control down",
927
+ alt: "option down",
928
+ shift: "shift down",
929
+ win: "command down"
930
+ };
931
+ function macHotkey(accelerator) {
932
+ const { key, modifiers } = accelerator;
933
+ const code = MAC_KEY_CODES[key];
934
+ if (code === undefined && key.length !== 1) {
935
+ throw new Error(`"${key}" cannot be sent on macOS`);
936
+ }
937
+ const press = code === undefined ? `keystroke ${appleString(key)}` : `key code ${code}`;
938
+ const using = modifiers.length > 0 ? ` using {${modifiers.map((m) => MAC_MODIFIERS[m]).join(", ")}}` : "";
939
+ return `tell application "System Events" to ${press}${using}`;
940
+ }
941
+ function macControls() {
942
+ const script = (source) => run("osascript", ["-e", source]);
943
+ const volume = (change) => script(`set volume output volume ((output volume of (get volume settings)) ${change})`);
944
+ return {
945
+ media: async (key) => {
946
+ if (key === "volume-up")
947
+ return volume("+ 6");
948
+ if (key === "volume-down")
949
+ return volume("- 6");
950
+ if (key === "mute") {
951
+ return script("set volume output muted not (output muted of (get volume settings))");
952
+ }
953
+ throw new Error("playback keys are not available on macOS");
954
+ },
955
+ hotkey: async (accelerator) => script(macHotkey(accelerator)),
956
+ type: (text) => script(`tell application "System Events" to keystroke ${appleString(text)}`),
957
+ lock: () => run("pmset", ["displaysleepnow"]),
958
+ sleep: () => run("pmset", ["sleepnow"]),
959
+ screenshot: async (file) => {
960
+ await mkdir(dirname(file), { recursive: true });
961
+ await run("screencapture", ["-x", file]);
962
+ },
963
+ snip: () => run("screencapture", ["-i", "-c"])
964
+ };
965
+ }
966
+ var X_KEYS = {
967
+ enter: "Return",
968
+ escape: "Escape",
969
+ backspace: "BackSpace",
970
+ tab: "Tab",
971
+ space: "space",
972
+ delete: "Delete",
973
+ insert: "Insert",
974
+ home: "Home",
975
+ end: "End",
976
+ pageup: "Prior",
977
+ pagedown: "Next",
978
+ left: "Left",
979
+ right: "Right",
980
+ up: "Up",
981
+ down: "Down",
982
+ printscreen: "Print",
983
+ playpause: "XF86AudioPlay",
984
+ medianext: "XF86AudioNext",
985
+ mediaprevious: "XF86AudioPrev",
986
+ mediastop: "XF86AudioStop",
987
+ volumemute: "XF86AudioMute",
988
+ volumeup: "XF86AudioRaiseVolume",
989
+ volumedown: "XF86AudioLowerVolume"
990
+ };
991
+ var X_MODIFIERS = { ctrl: "ctrl", alt: "alt", shift: "shift", win: "super" };
992
+ function xHotkey(accelerator) {
993
+ const { key, modifiers } = accelerator;
994
+ const name = X_KEYS[key] ?? (/^f\d+$/.test(key) ? key.toUpperCase() : key);
995
+ return [...modifiers.map((m) => X_MODIFIERS[m]), name].join("+");
996
+ }
997
+ function linuxControls() {
998
+ const hotkey = (accelerator) => run("xdotool", ["key", xHotkey(accelerator)]);
999
+ return {
1000
+ media: (key) => hotkey(parseAccelerator(MEDIA_KEYS[key])),
1001
+ hotkey,
1002
+ type: (text) => run("xdotool", ["type", "--clearmodifiers", "--", text]),
1003
+ lock: () => run("loginctl", ["lock-session"]),
1004
+ sleep: () => run("systemctl", ["suspend"]),
1005
+ screenshot: async (file) => {
1006
+ await mkdir(dirname(file), { recursive: true });
1007
+ await run("gnome-screenshot", ["-f", file]);
1008
+ },
1009
+ snip: () => run("gnome-screenshot", ["-a", "-c"])
1010
+ };
1011
+ }
1012
+ var controls;
1013
+ function systemControls() {
1014
+ controls ??= process.platform === "win32" ? windowsControls() : Promise.resolve(process.platform === "darwin" ? macControls() : linuxControls());
1015
+ return controls;
1016
+ }
1017
+
1018
+ // src/monitor.ts
1019
+ import { execFile as execFile2, spawn } from "child_process";
1020
+ import { readdir, readFile, statfs } from "fs/promises";
1021
+ import { cpus, homedir } from "os";
1022
+ import { join } from "path";
1023
+
1024
+ class Unavailable extends Error {
1025
+ }
1026
+ function capture(file, args, options = {}) {
1027
+ return new Promise((resolve, reject) => {
1028
+ execFile2(file, args, {
1029
+ windowsHide: true,
1030
+ timeout: options.timeoutMs ?? 1e4,
1031
+ maxBuffer: 4 * 1024 * 1024,
1032
+ ...options.signal && { signal: options.signal }
1033
+ }, (error, stdout, stderr) => {
1034
+ const code = error ? error.code : 0;
1035
+ if (code === "ENOENT")
1036
+ return reject(new Unavailable(`"${file}" is not installed`));
1037
+ resolve({ code: typeof code === "number" ? code : -1, stdout, stderr });
1038
+ });
1039
+ });
1040
+ }
1041
+ var coreTimes = () => cpus().map(({ times: t }) => ({
1042
+ idle: t.idle,
1043
+ total: t.user + t.nice + t.sys + t.irq + t.idle
1044
+ }));
1045
+ function coreSampler(read = coreTimes) {
1046
+ let last = read();
1047
+ return () => {
1048
+ const now = read();
1049
+ const out = now.map((core, i) => {
1050
+ const total = core.total - (last[i]?.total ?? 0);
1051
+ const idle = core.idle - (last[i]?.idle ?? 0);
1052
+ return total > 0 ? Math.round(100 * (1 - idle / total)) : 0;
1053
+ });
1054
+ last = now;
1055
+ return out;
1056
+ };
1057
+ }
1058
+ async function diskUsage(path) {
1059
+ const s = await statfs(path);
1060
+ const total = s.blocks * s.bsize;
1061
+ const free = s.bavail * s.bsize;
1062
+ if (total <= 0)
1063
+ throw new Unavailable(`no size for ${path}`);
1064
+ return { percent: Math.round(100 * (1 - free / total)), free, total };
1065
+ }
1066
+ var VIRTUAL = /^(lo|docker|veth|br-|virbr|vmnet|utun|awdl|llw|bridge)/;
1067
+ function parseProcNetDev(text) {
1068
+ const total = { received: 0, sent: 0 };
1069
+ for (const line of text.split(`
1070
+ `)) {
1071
+ const match = /^\s*([^:]+):\s*(.*)$/.exec(line);
1072
+ if (!match?.[1] || VIRTUAL.test(match[1].trim()))
1073
+ continue;
1074
+ const fields = (match[2] ?? "").trim().split(/\s+/).map(Number);
1075
+ total.received += fields[0] || 0;
1076
+ total.sent += fields[8] || 0;
1077
+ }
1078
+ return total;
1079
+ }
1080
+ function parseNetstat(text) {
1081
+ const total = { received: 0, sent: 0 };
1082
+ const lines = text.split(`
1083
+ `);
1084
+ const header = (lines[0] ?? "").trim().split(/\s+/);
1085
+ const fromEnd = (name) => header.length - header.indexOf(name);
1086
+ for (const line of lines.slice(1)) {
1087
+ const fields = line.trim().split(/\s+/);
1088
+ if (!fields[0] || VIRTUAL.test(fields[0]) || !fields[2]?.startsWith("<Link"))
1089
+ continue;
1090
+ total.received += Number(fields[fields.length - fromEnd("Ibytes")]) || 0;
1091
+ total.sent += Number(fields[fields.length - fromEnd("Obytes")]) || 0;
1092
+ }
1093
+ return total;
1094
+ }
1095
+ function throughput(before, after, seconds) {
1096
+ const rate = (a, b) => seconds > 0 ? Math.max(0, Math.round((b - a) / seconds)) : 0;
1097
+ return {
1098
+ received: rate(before.received, after.received),
1099
+ sent: rate(before.sent, after.sent)
1100
+ };
1101
+ }
1102
+ var WINDOWS_NETWORK = `
1103
+ while ($true) {
1104
+ $rx = 0; $tx = 0
1105
+ foreach ($n in [System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces()) {
1106
+ if ($n.OperationalStatus -ne 'Up' -or $n.NetworkInterfaceType -eq 'Loopback' -or $n.NetworkInterfaceType -eq 'Tunnel') { continue }
1107
+ if ($n.Description -match 'Virtual|Hyper-V|vEthernet|Filter|VirtualBox|VMware') { continue }
1108
+ $s = $n.GetIPStatistics(); $rx += $s.BytesReceived; $tx += $s.BytesSent
1109
+ }
1110
+ [Console]::Out.WriteLine("$rx $tx"); [Console]::Out.Flush()
1111
+ Start-Sleep -Seconds 1
1112
+ }
1113
+ `;
1114
+ function lines(child, read, onError) {
1115
+ let buffer = "";
1116
+ let stopped = false;
1117
+ child.stdout?.setEncoding("utf8");
1118
+ child.stdout?.on("data", (chunk) => {
1119
+ buffer += chunk;
1120
+ const parts = buffer.split(/\r?\n/);
1121
+ buffer = parts.pop() ?? "";
1122
+ for (const line of parts)
1123
+ read(line);
1124
+ });
1125
+ child.once("error", (error) => {
1126
+ stopped = true;
1127
+ const missing = error.code === "ENOENT";
1128
+ onError(missing ? new Unavailable(`"${child.spawnfile}" is not installed`) : error);
1129
+ });
1130
+ child.once("close", (code) => {
1131
+ if (!stopped && code !== 0)
1132
+ onError(new Unavailable(`"${child.spawnfile}" exited (${code})`));
1133
+ });
1134
+ return () => {
1135
+ stopped = true;
1136
+ child.kill();
1137
+ };
1138
+ }
1139
+ function watchNetwork(emit, onError) {
1140
+ let last;
1141
+ const sample = (counters) => {
1142
+ const at = performance.now();
1143
+ if (last)
1144
+ emit(throughput(last.counters, counters, (at - last.at) / 1000));
1145
+ last = { counters, at };
1146
+ };
1147
+ if (process.platform === "win32") {
1148
+ const encoded = Buffer.from(WINDOWS_NETWORK, "utf16le").toString("base64");
1149
+ const child = spawn("powershell.exe", ["-NoProfile", "-NonInteractive", "-EncodedCommand", encoded], { cwd: homedir(), stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
1150
+ return lines(child, (line) => {
1151
+ const [received, sent] = line.trim().split(" ").map(Number);
1152
+ if (Number.isFinite(received) && Number.isFinite(sent)) {
1153
+ sample({ received, sent });
1154
+ }
1155
+ }, onError);
1156
+ }
1157
+ const read = async () => {
1158
+ try {
1159
+ sample(process.platform === "darwin" ? parseNetstat((await capture("netstat", ["-ibn"])).stdout) : parseProcNetDev(await readFile("/proc/net/dev", "utf8")));
1160
+ } catch (error) {
1161
+ onError(error);
1162
+ }
1163
+ };
1164
+ read();
1165
+ const timer = setInterval(read, 1000);
1166
+ return () => clearInterval(timer);
1167
+ }
1168
+ function isHost(host) {
1169
+ return /^[A-Za-z0-9_[][A-Za-z0-9_.:%[\]-]{0,252}$/.test(host);
1170
+ }
1171
+ function parsePing(output) {
1172
+ for (const line of output.split(/\r?\n/)) {
1173
+ if (!/ttl/i.test(line) && !/time[=<]/i.test(line))
1174
+ continue;
1175
+ const match = /[=<]\s*([\d.,]+)\s*ms/i.exec(line);
1176
+ if (match?.[1])
1177
+ return Number(match[1].replace(",", "."));
1178
+ }
1179
+ return;
1180
+ }
1181
+ async function ping(host, signal) {
1182
+ const target = host.trim();
1183
+ if (!isHost(target))
1184
+ throw new Error(`"${host}" is not a host name or address`);
1185
+ const args = process.platform === "win32" ? ["-n", "1", "-w", "2000", target] : ["-c", "1", "-W", process.platform === "darwin" ? "2000" : "2", target];
1186
+ const { stdout } = await capture("ping", args, { timeoutMs: 5000, ...signal && { signal } });
1187
+ const ms = parsePing(stdout);
1188
+ if (ms === undefined)
1189
+ throw new Error(`${target} did not answer`);
1190
+ return ms;
1191
+ }
1192
+ var NVIDIA_QUERY = [
1193
+ "--query-gpu=name,utilization.gpu,temperature.gpu,memory.used,memory.total",
1194
+ "--format=csv,noheader,nounits"
1195
+ ];
1196
+ function parseNvidia(csv) {
1197
+ const fields = csv.split(/\r?\n/)[0]?.split(",").map((f) => f.trim());
1198
+ if (!fields || fields.length < 5 || !fields[0])
1199
+ return;
1200
+ const number = (text) => {
1201
+ const n = Number(text);
1202
+ return text && Number.isFinite(n) ? n : undefined;
1203
+ };
1204
+ const used = number(fields[3]);
1205
+ const total = number(fields[4]);
1206
+ return {
1207
+ name: fields[0],
1208
+ load: number(fields[1]),
1209
+ temperature: number(fields[2]),
1210
+ memory: used !== undefined && total ? Math.round(100 * used / total) : undefined
1211
+ };
1212
+ }
1213
+ async function readGpu() {
1214
+ const { code, stdout, stderr } = await capture("nvidia-smi", NVIDIA_QUERY);
1215
+ const gpu = code === 0 ? parseNvidia(stdout) : undefined;
1216
+ if (!gpu)
1217
+ throw new Unavailable(stderr.trim() || "nvidia-smi reported no GPU");
1218
+ return gpu;
1219
+ }
1220
+ var WINDOWS_TEMPERATURE = "(Get-CimInstance -Namespace root/wmi -ClassName MSAcpi_ThermalZoneTemperature -ErrorAction Stop | Measure-Object -Property CurrentTemperature -Maximum).Maximum";
1221
+ function parseThermalZone(output) {
1222
+ const raw = Number(output.trim());
1223
+ return output.trim() && Number.isFinite(raw) && raw > 0 ? Math.round(raw / 10 - 273.15) : undefined;
1224
+ }
1225
+ async function cpuTemperature(thermal = "/sys/class/thermal") {
1226
+ if (process.platform === "win32") {
1227
+ const { code, stdout } = await capture("powershell.exe", [
1228
+ "-NoProfile",
1229
+ "-NonInteractive",
1230
+ "-Command",
1231
+ WINDOWS_TEMPERATURE
1232
+ ]);
1233
+ const value = code === 0 ? parseThermalZone(stdout) : undefined;
1234
+ if (value === undefined) {
1235
+ throw new Unavailable("Windows exposes no thermal zone (common on desktops; it may need administrator rights)");
1236
+ }
1237
+ return value;
1238
+ }
1239
+ const readings = [];
1240
+ for (const zone of await readdir(thermal).catch(() => [])) {
1241
+ if (!zone.startsWith("thermal_zone"))
1242
+ continue;
1243
+ try {
1244
+ const type = (await readFile(join(thermal, zone, "type"), "utf8")).trim();
1245
+ const value = Number(await readFile(join(thermal, zone, "temp"), "utf8")) / 1000;
1246
+ if (Number.isFinite(value))
1247
+ readings.push({ type, value });
1248
+ } catch {}
1249
+ }
1250
+ const cpu = readings.filter((r) => /pkg|cpu|k10|core/i.test(r.type));
1251
+ const pool = cpu.length > 0 ? cpu : readings;
1252
+ if (pool.length === 0)
1253
+ throw new Unavailable("no temperature sensor is exposed");
1254
+ return Math.round(Math.max(...pool.map((r) => r.value)));
1255
+ }
1256
+ function presentMonParser() {
1257
+ let app = -1;
1258
+ let time = -1;
1259
+ return (line) => {
1260
+ const fields = line.split(",");
1261
+ if (time < 0) {
1262
+ const names = fields.map((f) => f.trim().toLowerCase());
1263
+ app = names.indexOf("application");
1264
+ time = ["msbetweenpresents", "frametime"].map((n) => names.indexOf(n)).find((i) => i >= 0) ?? -1;
1265
+ return;
1266
+ }
1267
+ const ms = Number(fields[time]);
1268
+ const name = fields[app]?.trim().toLowerCase();
1269
+ return name && Number.isFinite(ms) && ms > 0 ? { app: name, ms } : undefined;
1270
+ };
1271
+ }
1272
+ var COMPOSITORS = new Set(["dwm.exe"]);
1273
+ function frameRate(frames, foreground) {
1274
+ const byApp = new Map;
1275
+ for (const frame of frames) {
1276
+ if (COMPOSITORS.has(frame.app))
1277
+ continue;
1278
+ const list = byApp.get(frame.app);
1279
+ if (list)
1280
+ list.push(frame);
1281
+ else
1282
+ byApp.set(frame.app, [frame]);
1283
+ }
1284
+ const chosen = (foreground ? byApp.get(foreground.toLowerCase()) : undefined) ?? [...byApp.values()].sort((a, b) => b.length - a.length)[0];
1285
+ if (!chosen)
1286
+ return;
1287
+ const total = chosen.reduce((sum, f) => sum + f.ms, 0);
1288
+ return Math.round(1000 * chosen.length / total);
1289
+ }
1290
+ function watchFrameRate(command, foreground, emit, onError) {
1291
+ if (process.platform !== "win32") {
1292
+ onError(new Unavailable("frame rates need PresentMon, which is Windows only"));
1293
+ return () => {};
1294
+ }
1295
+ const parse = presentMonParser();
1296
+ let frames = [];
1297
+ const child = spawn(command, ["--output_stdout", "--stop_existing_session"], {
1298
+ cwd: homedir(),
1299
+ stdio: ["ignore", "pipe", "ignore"],
1300
+ windowsHide: true
1301
+ });
1302
+ const stop = lines(child, (line) => {
1303
+ const frame = parse(line);
1304
+ if (frame)
1305
+ frames.push(frame);
1306
+ }, (error) => {
1307
+ clearInterval(timer);
1308
+ emit(undefined);
1309
+ onError(new Unavailable(`${error.message}. Install PresentMon and run sdeck as administrator (or add your user to "Performance Log Users")`));
1310
+ });
1311
+ const timer = setInterval(() => {
1312
+ emit(frameRate(frames, foreground()));
1313
+ frames = [];
1314
+ }, 1000);
1315
+ return () => {
1316
+ clearInterval(timer);
1317
+ stop();
1318
+ };
1319
+ }
1320
+
1321
+ // src/watchers.ts
1322
+ import { spawn as spawn2 } from "child_process";
1323
+ import { existsSync, readdirSync, watch } from "fs";
1324
+ import { homedir as homedir2, networkInterfaces } from "os";
1325
+ import { join as join2 } from "path";
1326
+ function processChanges(before, after) {
1327
+ return {
1328
+ started: [...after].filter((p) => !before.has(p)),
1329
+ stopped: [...before].filter((p) => !after.has(p))
1330
+ };
1331
+ }
1332
+ function namePattern(glob) {
1333
+ const trimmed = glob.trim();
1334
+ if (!trimmed)
1335
+ return /^/;
1336
+ const escaped = trimmed.replace(/[.+^${}()|[\]\\]/g, "\\$&");
1337
+ return new RegExp(`^${escaped.replace(/\*/g, ".*").replace(/\?/g, ".")}$`, "i");
1338
+ }
1339
+ function watchFolder(folder, onCreated) {
1340
+ if (!existsSync(folder))
1341
+ throw new Error(`folder "${folder}" does not exist`);
1342
+ const known = new Set(readdirSync(folder));
1343
+ let watcher = watch(folder, (_event, name) => {
1344
+ if (!name)
1345
+ return;
1346
+ const file = String(name);
1347
+ const exists = existsSync(join2(folder, file));
1348
+ if (exists && !known.has(file)) {
1349
+ known.add(file);
1350
+ onCreated(file);
1351
+ } else if (!exists)
1352
+ known.delete(file);
1353
+ });
1354
+ watcher.on("error", () => {
1355
+ watcher?.close();
1356
+ watcher = undefined;
1357
+ });
1358
+ return () => watcher?.close();
1359
+ }
1360
+ function networkAddresses() {
1361
+ const out = [];
1362
+ for (const [name, addresses] of Object.entries(networkInterfaces())) {
1363
+ for (const a of addresses ?? [])
1364
+ if (!a.internal)
1365
+ out.push(`${name} ${a.address}`);
1366
+ }
1367
+ return out.sort();
1368
+ }
1369
+ var WINDOWS_IDLE = `
1370
+ Add-Type @'
1371
+ using System;
1372
+ using System.Runtime.InteropServices;
1373
+ public static class SdeckIdle {
1374
+ [StructLayout(LayoutKind.Sequential)] struct Info { public uint Size; public uint Time; }
1375
+ [DllImport("user32.dll")] static extern bool GetLastInputInfo(ref Info info);
1376
+ public static long Ms() {
1377
+ var info = new Info(); info.Size = (uint)Marshal.SizeOf(info);
1378
+ if (!GetLastInputInfo(ref info)) return -1;
1379
+ return (long)(uint)((uint)Environment.TickCount - info.Time);
1380
+ }
1381
+ }
1382
+ '@
1383
+ while ($true) { [Console]::Out.WriteLine([SdeckIdle]::Ms()); [Console]::Out.Flush(); Start-Sleep -Seconds 2 }
1384
+ `;
1385
+ function idleSeconds(line, unit = "ms") {
1386
+ const n = Number(line.trim());
1387
+ if (!Number.isFinite(n) || n < 0)
1388
+ return;
1389
+ return Math.floor(unit === "ns" ? n / 1e9 : n / 1000);
1390
+ }
1391
+ function watchIdle(emit, onError) {
1392
+ if (process.platform === "win32") {
1393
+ const encoded = Buffer.from(WINDOWS_IDLE, "utf16le").toString("base64");
1394
+ const child = spawn2("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded], { cwd: homedir2(), stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
1395
+ let buffer = "";
1396
+ child.stdout?.setEncoding("utf8");
1397
+ child.stdout?.on("data", (chunk) => {
1398
+ buffer += chunk;
1399
+ const lines = buffer.split(/\r?\n/);
1400
+ buffer = lines.pop() ?? "";
1401
+ for (const line of lines) {
1402
+ const s = idleSeconds(line);
1403
+ if (s !== undefined)
1404
+ emit(s);
1405
+ }
1406
+ });
1407
+ child.once("error", (error) => onError(error));
1408
+ return () => child.kill();
1409
+ }
1410
+ const [file, args, parse] = process.platform === "darwin" ? [
1411
+ "ioreg",
1412
+ ["-c", "IOHIDSystem", "-d", "4"],
1413
+ (out) => idleSeconds(/"HIDIdleTime" = (\d+)/.exec(out)?.[1] ?? "", "ns")
1414
+ ] : ["xprintidle", [], (out) => idleSeconds(out)];
1415
+ let stopped = false;
1416
+ let timer;
1417
+ const tick = () => {
1418
+ const child = spawn2(file, [...args], { stdio: ["ignore", "pipe", "ignore"] });
1419
+ let out = "";
1420
+ child.stdout?.setEncoding("utf8");
1421
+ child.stdout?.on("data", (c) => {
1422
+ out += c;
1423
+ });
1424
+ child.once("error", () => {
1425
+ stopped = true;
1426
+ onError(new Error(`idle time is unavailable: "${file}" could not run`));
1427
+ });
1428
+ child.once("close", () => {
1429
+ const s = parse(out);
1430
+ if (s !== undefined)
1431
+ emit(s);
1432
+ if (!stopped)
1433
+ timer = setTimeout(tick, 2000);
1434
+ });
1435
+ };
1436
+ tick();
1437
+ return () => {
1438
+ stopped = true;
1439
+ clearTimeout(timer);
1440
+ };
1441
+ }
1442
+ var WINDOWS_FOREGROUND = `
1443
+ Add-Type @'
1444
+ using System;
1445
+ using System.Runtime.InteropServices;
1446
+ public static class SdeckFg {
1447
+ [DllImport("user32.dll")] public static extern IntPtr GetForegroundWindow();
1448
+ [DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr h, out uint pid);
1449
+ public static uint Pid() { uint pid; GetWindowThreadProcessId(GetForegroundWindow(), out pid); return pid; }
1450
+ }
1451
+ '@
1452
+ $last = $null
1453
+ while ($true) {
1454
+ $name = ""
1455
+ $id = [SdeckFg]::Pid()
1456
+ if ($id -ne 0) { $p = Get-Process -Id $id -ErrorAction SilentlyContinue; if ($p) { $name = $p.ProcessName + ".exe" } }
1457
+ if ($name -ne $last) { [Console]::Out.WriteLine($name); [Console]::Out.Flush(); $last = $name }
1458
+ Start-Sleep -Milliseconds 700
1459
+ }
1460
+ `;
1461
+ function foregroundName(line) {
1462
+ const trimmed = line.trim();
1463
+ return (trimmed.split(/[\\/]/).pop() ?? "").toLowerCase();
1464
+ }
1465
+ function watchForeground(emit, onError) {
1466
+ if (process.platform === "win32") {
1467
+ const encoded = Buffer.from(WINDOWS_FOREGROUND, "utf16le").toString("base64");
1468
+ const child = spawn2("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-EncodedCommand", encoded], { cwd: homedir2(), stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
1469
+ let buffer = "";
1470
+ child.stdout?.setEncoding("utf8");
1471
+ child.stdout?.on("data", (chunk) => {
1472
+ buffer += chunk;
1473
+ const lines = buffer.split(/\r?\n/);
1474
+ buffer = lines.pop() ?? "";
1475
+ for (const line of lines)
1476
+ emit(foregroundName(line));
1477
+ });
1478
+ child.once("error", (error) => onError(error));
1479
+ return () => child.kill();
1480
+ }
1481
+ const script = process.platform === "darwin" ? `ps -p "$(osascript -e 'tell application "System Events" to get unix id of first application process whose frontmost is true')" -o comm=` : `cat "/proc/$(xdotool getactivewindow getwindowpid)/comm"`;
1482
+ const tool = process.platform === "darwin" ? "osascript" : "xdotool";
1483
+ let stopped = false;
1484
+ let last;
1485
+ let failures = 0;
1486
+ let timer;
1487
+ const tick = () => {
1488
+ const child = spawn2("sh", ["-c", script], { stdio: ["ignore", "pipe", "ignore"] });
1489
+ let out = "";
1490
+ child.stdout?.setEncoding("utf8");
1491
+ child.stdout?.on("data", (c) => {
1492
+ out += c;
1493
+ });
1494
+ child.once("error", (error) => {
1495
+ stopped = true;
1496
+ onError(error);
1497
+ });
1498
+ child.once("close", (code) => {
1499
+ if (stopped)
1500
+ return;
1501
+ if (code === 0) {
1502
+ failures = 0;
1503
+ const app = foregroundName(out);
1504
+ if (app !== last) {
1505
+ last = app;
1506
+ emit(app);
1507
+ }
1508
+ } else if (++failures === 3) {
1509
+ onError(new Error(`the foreground app is unavailable: "${tool}" did not answer`));
1510
+ }
1511
+ timer = setTimeout(tick, 1000);
1512
+ });
1513
+ };
1514
+ tick();
1515
+ return () => {
1516
+ stopped = true;
1517
+ clearTimeout(timer);
1518
+ };
1519
+ }
1520
+
1521
+ // src/index.tsx
1522
+ function openWithSystem(target) {
1523
+ const [command, args] = process.platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", target]] : process.platform === "darwin" ? ["open", [target]] : ["xdg-open", [target]];
1524
+ spawn3(command, args, {
1525
+ cwd: homedir3(),
1526
+ detached: true,
1527
+ stdio: "ignore",
1528
+ windowsHide: true
1529
+ }).unref();
1530
+ }
1531
+ var OUTPUT_LIMIT = 64 * 1024;
1532
+ function runShell(command, cwd, signal) {
1533
+ return new Promise((resolve) => {
1534
+ let output = "";
1535
+ const child = spawn3(command, {
1536
+ shell: true,
1537
+ stdio: ["ignore", "pipe", "ignore"],
1538
+ windowsHide: true,
1539
+ ...cwd && { cwd },
1540
+ ...signal && { signal }
1541
+ });
1542
+ child.stdout?.setEncoding("utf8");
1543
+ child.stdout?.on("data", (chunk) => {
1544
+ if (output.length < OUTPUT_LIMIT)
1545
+ output += chunk;
1546
+ });
1547
+ const done = (code) => resolve({ code, output: output.slice(0, OUTPUT_LIMIT).trim() });
1548
+ child.once("error", () => done(-1));
1549
+ child.once("close", (code) => done(code ?? -1));
1550
+ });
1551
+ }
1552
+ var buttonLook = (icon, caption, image, background) => iconLook({ icon: image || icon, caption, background });
1553
+ var open = defineAction({
1554
+ id: "open",
1555
+ name: "Open",
1556
+ description: "Opens a website, file, folder or app.",
1557
+ category: "System",
1558
+ icon: "external-link",
1559
+ settings: {
1560
+ target: {
1561
+ type: "text",
1562
+ label: "URL or path",
1563
+ placeholder: "https://example.com or C:\\Tools\\app.exe"
1564
+ },
1565
+ text: { type: "text", label: "Text", placeholder: "Optional, under the icon" },
1566
+ image: { type: "image", label: "Image" },
1567
+ background: { type: "color", label: "Background", default: "#0969da" }
1568
+ },
1569
+ run: ({ settings, plugin }) => {
1570
+ if (!settings.target)
1571
+ throw new Error("nothing to open");
1572
+ plugin.log("open", settings.target);
1573
+ openWithSystem(settings.target);
1574
+ return { label: `Open ${settings.target}` };
1575
+ },
1576
+ look: (s) => buttonLook("lucide/external-link", s.text, s.image, s.background)
1577
+ });
1578
+ var command = defineAction({
1579
+ id: "command",
1580
+ name: "Run command",
1581
+ description: "Runs a shell command. Fails when it exits with an error; its output is the result.",
1582
+ category: "System",
1583
+ icon: "terminal",
1584
+ settings: {
1585
+ command: { type: "text", label: "Command", placeholder: "echo hello", multiline: true },
1586
+ cwd: { type: "text", label: "Working directory", placeholder: "Defaults to your home folder" },
1587
+ undo: {
1588
+ type: "text",
1589
+ label: "Undo command",
1590
+ description: "Run to revert it (from the history, or a toggle's second press).",
1591
+ multiline: true
1592
+ },
1593
+ text: { type: "text", label: "Text", placeholder: "Optional, under the icon" },
1594
+ image: { type: "image", label: "Image" },
1595
+ background: { type: "color", label: "Background", default: "#24292f" }
1596
+ },
1597
+ run: async ({ settings, plugin, signal }) => {
1598
+ if (!settings.command)
1599
+ throw new Error("no command");
1600
+ const cwd = settings.cwd || homedir3();
1601
+ plugin.log("run", settings.command);
1602
+ const { code, output } = await runShell(settings.command, cwd, signal);
1603
+ if (code !== 0)
1604
+ throw new Error(`"${settings.command}" exited with ${code}`);
1605
+ const undo = settings.undo;
1606
+ return {
1607
+ result: output,
1608
+ label: settings.command,
1609
+ ...undo && {
1610
+ undo: async () => {
1611
+ const r = await runShell(undo, cwd);
1612
+ if (r.code !== 0)
1613
+ throw new Error(`"${undo}" exited with ${r.code}`);
1614
+ }
1615
+ }
1616
+ };
1617
+ },
1618
+ look: (s) => buttonLook("lucide/terminal", s.text, s.image, s.background)
1619
+ });
1620
+ function cpuSampler() {
1621
+ const read = () => cpus2().reduce((acc, cpu) => {
1622
+ const t = cpu.times;
1623
+ acc.idle += t.idle;
1624
+ acc.total += t.user + t.nice + t.sys + t.irq + t.idle;
1625
+ return acc;
1626
+ }, { idle: 0, total: 0 });
1627
+ let last = read();
1628
+ return () => {
1629
+ const now = read();
1630
+ const total = now.total - last.total;
1631
+ const idle = now.idle - last.idle;
1632
+ last = now;
1633
+ return total > 0 ? Math.round(100 * (1 - idle / total)) : 0;
1634
+ };
1635
+ }
1636
+ function listProcesses() {
1637
+ const [file, args] = process.platform === "win32" ? ["tasklist", ["/fo", "csv", "/nh"]] : ["ps", ["-A", "-o", "comm="]];
1638
+ return new Promise((resolve, reject) => {
1639
+ execFile3(file, args, { windowsHide: true, maxBuffer: 8 * 1024 * 1024 }, (error, stdout) => {
1640
+ if (error)
1641
+ return reject(error);
1642
+ const names = new Set;
1643
+ for (const line of stdout.split(/\r?\n/)) {
1644
+ const name = process.platform === "win32" ? /^"([^"]+)"/.exec(line)?.[1] : basename(line.trim());
1645
+ if (name)
1646
+ names.add(name.toLowerCase());
1647
+ }
1648
+ resolve([...names].sort());
1649
+ });
1650
+ });
1651
+ }
1652
+ var reading = (key, unit) => `{{system.${key} == null ? "N/A" : round(system.${key}) + "${unit}"}}`;
1653
+ var METRICS = {
1654
+ cpu: { icon: "lucide/cpu", text: reading("cpu", "%"), bar: "system.cpu" },
1655
+ memory: { icon: "lucide/memory-stick", text: reading("memory", "%"), bar: "system.memory" },
1656
+ disk: { icon: "lucide/hard-drive", text: reading("disk", "%"), bar: "system.disk" },
1657
+ gpu: { icon: "lucide/gpu", text: reading("gpu", "%"), bar: "system.gpu" },
1658
+ "gpu-temp": { icon: "lucide/thermometer", text: reading("gpuTemp", "\xB0C"), bar: "system.gpuTemp" },
1659
+ "cpu-temp": { icon: "lucide/thermometer", text: reading("cpuTemp", "\xB0C"), bar: "system.cpuTemp" },
1660
+ core: {
1661
+ icon: "lucide/zap",
1662
+ text: "{{max(system.cpuCores ?? 0)}}%",
1663
+ bar: "max(system.cpuCores ?? 0)"
1664
+ },
1665
+ ping: { icon: "lucide/activity", text: reading("ping", " ms"), bar: undefined },
1666
+ fps: { icon: "lucide/gauge", text: reading("fps", ""), bar: undefined }
1667
+ };
1668
+ var stats = defineAction({
1669
+ id: "stats",
1670
+ name: "System stats",
1671
+ description: "Live CPU, memory, disk, network, GPU, ping and FPS (also usable anywhere as {{system.cpu}}).",
1672
+ category: "Monitoring",
1673
+ icon: "activity",
1674
+ slots: ["key", "sensor", "window"],
1675
+ settings: {
1676
+ show: {
1677
+ type: "select",
1678
+ label: "Show",
1679
+ default: "both",
1680
+ options: [
1681
+ { value: "both", label: "CPU and memory" },
1682
+ { value: "cpu", label: "CPU" },
1683
+ { value: "core", label: "Busiest CPU core" },
1684
+ { value: "memory", label: "Memory" },
1685
+ { value: "disk", label: "Disk space used" },
1686
+ { value: "network", label: "Network speed" },
1687
+ { value: "ping", label: "Ping" },
1688
+ { value: "gpu", label: "GPU load (NVIDIA)" },
1689
+ { value: "gpu-temp", label: "GPU temperature (NVIDIA)" },
1690
+ { value: "cpu-temp", label: "CPU temperature" },
1691
+ { value: "fps", label: "Frame rate (PresentMon)" }
1692
+ ]
1693
+ },
1694
+ color: { type: "color", label: "Colour", default: "#58a6ff" },
1695
+ background: { type: "color", label: "Background", default: "#0d1117" }
1696
+ },
1697
+ run: () => {
1698
+ return;
1699
+ },
1700
+ look: (s) => {
1701
+ const bar = (id, value) => ({
1702
+ id,
1703
+ type: "bar",
1704
+ value,
1705
+ color: s.color,
1706
+ track: "#30363d",
1707
+ position: "bottom",
1708
+ thickness: 6
1709
+ });
1710
+ const row = (id, icon, value, size) => [
1711
+ iconLayer(`${id}-icon`, icon, { color: s.color, size: 22, row: id }),
1712
+ textLayer(id, value, { color: s.color, size, row: id })
1713
+ ];
1714
+ if (s.show === "both") {
1715
+ return {
1716
+ background: s.background,
1717
+ layers: [
1718
+ ...row("cpu", "lucide/cpu", "{{system.cpu}}%", 18),
1719
+ ...row("memory", "lucide/memory-stick", "{{system.memory}}%", 18)
1720
+ ]
1721
+ };
1722
+ }
1723
+ if (s.show === "network") {
1724
+ return {
1725
+ background: s.background,
1726
+ layers: [
1727
+ ...row("down", "lucide/arrow-down", "{{bytes(system.netDown ?? 0)}}", 13),
1728
+ ...row("up", "lucide/arrow-up", "{{bytes(system.netUp ?? 0)}}", 13)
1729
+ ]
1730
+ };
1731
+ }
1732
+ const metric = METRICS[s.show];
1733
+ const id = s.show;
1734
+ return {
1735
+ background: s.background,
1736
+ layers: [
1737
+ iconLayer(`${id}-icon`, metric.icon, { color: s.color, size: 40, position: "top" }),
1738
+ textLayer(id, metric.text, { color: s.color, size: 20, position: "bottom" }),
1739
+ ...metric.bar ? [bar(`${id}-bar`, metric.bar)] : []
1740
+ ]
1741
+ };
1742
+ }
1743
+ });
1744
+ var MEDIA = {
1745
+ "play-pause": { label: "Play / Pause", icons: ["play", "pause"], undo: "play-pause" },
1746
+ next: { label: "Next track", icons: ["skip-forward"], undo: "previous" },
1747
+ previous: { label: "Previous track", icons: ["skip-back"], undo: "next" },
1748
+ stop: { label: "Stop playback", icons: ["square"], undo: undefined },
1749
+ "volume-up": { label: "Volume up", icons: ["volume-2", "plus"], undo: "volume-down" },
1750
+ "volume-down": { label: "Volume down", icons: ["volume-1", "minus"], undo: "volume-up" },
1751
+ mute: { label: "Mute", icons: ["volume-x"], undo: "mute" }
1752
+ };
1753
+ var media = defineAction({
1754
+ id: "media",
1755
+ name: "Media and volume",
1756
+ description: "Presses a media or volume key, as a keyboard would.",
1757
+ category: "Controls",
1758
+ icon: "play",
1759
+ slots: ["key", "sensor"],
1760
+ settings: {
1761
+ key: {
1762
+ type: "select",
1763
+ label: "Key",
1764
+ default: "play-pause",
1765
+ options: Object.entries(MEDIA).map(([value, m]) => ({ value, label: m.label }))
1766
+ },
1767
+ steps: {
1768
+ type: "number",
1769
+ label: "Presses",
1770
+ description: "Each volume press is about 2%.",
1771
+ default: 1,
1772
+ min: 1,
1773
+ max: 50,
1774
+ visibleIf: { key: ["volume-up", "volume-down"] }
1775
+ },
1776
+ background: { type: "color", label: "Background", default: "#1f2937" }
1777
+ },
1778
+ run: async ({ settings }) => {
1779
+ const controls = await systemControls();
1780
+ const { key } = settings;
1781
+ const times = key === "volume-up" || key === "volume-down" ? settings.steps : 1;
1782
+ const press = async (which) => {
1783
+ for (let i = 0;i < times; i++)
1784
+ await controls.media(which);
1785
+ };
1786
+ await press(key);
1787
+ const undo = MEDIA[key].undo;
1788
+ return { label: MEDIA[key].label, ...undo && { undo: () => press(undo) } };
1789
+ },
1790
+ look: (s) => {
1791
+ const { icons } = MEDIA[s.key];
1792
+ return {
1793
+ background: s.background,
1794
+ layers: icons.map((name, i) => iconLayer(i === 0 ? "icon" : `icon-${i + 1}`, `lucide/${name}`, {
1795
+ size: icons.length === 1 ? 58 : s.key === "play-pause" ? 36 : i === 0 ? 46 : 26,
1796
+ row: "icons"
1797
+ }))
1798
+ };
1799
+ }
1800
+ });
1801
+ var hotkey = defineAction({
1802
+ id: "hotkey",
1803
+ name: "Press a shortcut",
1804
+ description: "Sends a keyboard shortcut to the focused app.",
1805
+ category: "Controls",
1806
+ icon: "keyboard",
1807
+ slots: ["key", "sensor"],
1808
+ settings: {
1809
+ keys: { type: "text", label: "Shortcut", placeholder: "ctrl+shift+m" },
1810
+ text: { type: "text", label: "Text", placeholder: "Defaults to the shortcut" },
1811
+ background: { type: "color", label: "Background", default: "#374151" }
1812
+ },
1813
+ run: async ({ settings }) => {
1814
+ const accelerator = parseAccelerator(settings.keys);
1815
+ await (await systemControls()).hotkey(accelerator);
1816
+ return { label: `Press ${formatAccelerator(accelerator)}` };
1817
+ },
1818
+ look: (s) => iconLook({ icon: "lucide/keyboard", caption: s.text || s.keys, background: s.background })
1819
+ });
1820
+ var type = defineAction({
1821
+ id: "type",
1822
+ name: "Type text",
1823
+ description: "Types text into the focused app. The text can use {{templates}}.",
1824
+ category: "Controls",
1825
+ icon: "text-cursor-input",
1826
+ slots: ["key", "sensor"],
1827
+ settings: {
1828
+ content: { type: "text", label: "Text to type", multiline: true },
1829
+ text: { type: "text", label: "Key text", placeholder: "Optional, under the icon" },
1830
+ background: { type: "color", label: "Background", default: "#374151" }
1831
+ },
1832
+ run: async ({ settings }) => {
1833
+ if (!settings.content)
1834
+ throw new Error("nothing to type");
1835
+ await (await systemControls()).type(settings.content);
1836
+ return { label: `Type ${settings.content.length} character(s)` };
1837
+ },
1838
+ look: (s) => iconLook({ icon: "lucide/text-cursor-input", caption: s.text, background: s.background })
1839
+ });
1840
+ var lock = defineAction({
1841
+ id: "lock",
1842
+ name: "Lock the screen",
1843
+ category: "Controls",
1844
+ icon: "lock",
1845
+ slots: ["key", "sensor"],
1846
+ settings: {
1847
+ text: { type: "text", label: "Text", placeholder: "Optional, under the icon" },
1848
+ background: { type: "color", label: "Background", default: "#7c2d12" }
1849
+ },
1850
+ run: async () => {
1851
+ await (await systemControls()).lock();
1852
+ return { label: "Lock the screen" };
1853
+ },
1854
+ look: (s) => iconLook({ icon: "lucide/lock", caption: s.text, background: s.background })
1855
+ });
1856
+ var sleep = defineAction({
1857
+ id: "sleep",
1858
+ name: "Sleep",
1859
+ description: "Puts the computer to sleep.",
1860
+ category: "Controls",
1861
+ icon: "moon",
1862
+ slots: ["key", "sensor"],
1863
+ settings: {
1864
+ text: { type: "text", label: "Text", placeholder: "Optional, under the icon" },
1865
+ background: { type: "color", label: "Background", default: "#1e1b4b" }
1866
+ },
1867
+ run: async () => {
1868
+ await (await systemControls()).sleep();
1869
+ return { label: "Sleep" };
1870
+ },
1871
+ look: (s) => iconLook({ icon: "lucide/moon", caption: s.text, background: s.background })
1872
+ });
1873
+ function screenshotName(at) {
1874
+ const two = (n) => String(n).padStart(2, "0");
1875
+ const day = `${at.getFullYear()}${two(at.getMonth() + 1)}${two(at.getDate())}`;
1876
+ const time = `${two(at.getHours())}${two(at.getMinutes())}${two(at.getSeconds())}`;
1877
+ return `screenshot-${day}-${time}.png`;
1878
+ }
1879
+ var screenshot = defineAction({
1880
+ id: "screenshot",
1881
+ name: "Screenshot",
1882
+ description: "Saves the screen to a file (the result), or opens the region picker.",
1883
+ category: "Controls",
1884
+ icon: "camera",
1885
+ slots: ["key", "sensor"],
1886
+ settings: {
1887
+ mode: {
1888
+ type: "select",
1889
+ label: "Capture",
1890
+ default: "file",
1891
+ options: [
1892
+ { value: "file", label: "Whole screen, to a file" },
1893
+ { value: "snip", label: "A region I choose" }
1894
+ ]
1895
+ },
1896
+ folder: {
1897
+ type: "text",
1898
+ label: "Folder",
1899
+ placeholder: "Pictures/sdeck",
1900
+ visibleIf: { mode: "file" }
1901
+ },
1902
+ text: { type: "text", label: "Text", placeholder: "Optional, under the icon" },
1903
+ background: { type: "color", label: "Background", default: "#065f46" }
1904
+ },
1905
+ run: async ({ settings }) => {
1906
+ const controls = await systemControls();
1907
+ if (settings.mode === "snip") {
1908
+ await controls.snip();
1909
+ return { label: "Screenshot a region" };
1910
+ }
1911
+ const folder = settings.folder || join3(homedir3(), "Pictures", "sdeck");
1912
+ const file = join3(folder, screenshotName(new Date));
1913
+ await controls.screenshot(file);
1914
+ return { result: file, label: `Screenshot ${file}` };
1915
+ },
1916
+ look: (s) => iconLook({
1917
+ icon: s.mode === "snip" ? "lucide/scissors" : "lucide/camera",
1918
+ caption: s.text,
1919
+ background: s.background
1920
+ })
1921
+ });
1922
+ var pingAction = defineAction({
1923
+ id: "ping",
1924
+ name: "Ping",
1925
+ description: "Pings a host; the result is the round trip in ms. Fails when it does not answer.",
1926
+ category: "Monitoring",
1927
+ icon: "radio",
1928
+ settings: {
1929
+ host: { type: "text", label: "Host", default: "1.1.1.1" },
1930
+ background: { type: "color", label: "Background", default: "#0d1117" }
1931
+ },
1932
+ run: async ({ settings, signal }) => {
1933
+ const ms = await ping(settings.host, signal);
1934
+ return { result: ms, label: `Ping ${settings.host}: ${ms} ms` };
1935
+ },
1936
+ look: (s) => iconLook({ icon: "lucide/activity", caption: s.host, background: s.background })
1937
+ });
1938
+ var processes = new Shared((emit) => {
1939
+ let stopped = false;
1940
+ let timer;
1941
+ const tick = async () => {
1942
+ try {
1943
+ emit(new Set(await listProcesses()));
1944
+ } catch {}
1945
+ if (!stopped)
1946
+ timer = setTimeout(tick, 3000);
1947
+ };
1948
+ tick();
1949
+ return () => {
1950
+ stopped = true;
1951
+ clearTimeout(timer);
1952
+ };
1953
+ });
1954
+ var network = new Shared((emit) => {
1955
+ emit(networkAddresses());
1956
+ const timer = setInterval(() => emit(networkAddresses()), 5000);
1957
+ return () => clearInterval(timer);
1958
+ });
1959
+ var idleError;
1960
+ var idle = new Shared((emit) => {
1961
+ idleError = undefined;
1962
+ return watchIdle(emit, (error) => {
1963
+ idleError = error;
1964
+ });
1965
+ });
1966
+ var foregroundError;
1967
+ var foreground = new Shared((emit) => {
1968
+ foregroundError = undefined;
1969
+ return watchForeground(emit, (error) => {
1970
+ foregroundError = error;
1971
+ });
1972
+ });
1973
+ var RETRY_MS = 60000;
1974
+ var unavailable = new Map;
1975
+ function report(context) {
1976
+ const reasons = [...unavailable].map(([what, u]) => `${what}: ${u.reason}`);
1977
+ context.status(reasons.length > 0 ? `Unavailable here. ${reasons.join(". ")}` : undefined, "info");
1978
+ }
1979
+ function markUnavailable(context, what, error) {
1980
+ const reason = error instanceof Error ? error.message : String(error);
1981
+ if (unavailable.get(what)?.reason !== reason)
1982
+ context.log(`${what} is unavailable:`, reason);
1983
+ unavailable.set(what, { reason, retryAt: Date.now() + RETRY_MS });
1984
+ report(context);
1985
+ }
1986
+ async function measured(context, what, read) {
1987
+ const failed = unavailable.get(what);
1988
+ if (failed && Date.now() < failed.retryAt)
1989
+ return;
1990
+ try {
1991
+ const value = await read();
1992
+ if (unavailable.delete(what))
1993
+ report(context);
1994
+ return value;
1995
+ } catch (error) {
1996
+ markUnavailable(context, what, error);
1997
+ return;
1998
+ }
1999
+ }
2000
+ var gpuReading;
2001
+ function gpu(context) {
2002
+ if (!gpuReading || Date.now() - gpuReading.at > 1500) {
2003
+ gpuReading = { at: Date.now(), value: measured(context, "GPU", readGpu) };
2004
+ }
2005
+ return gpuReading.value;
2006
+ }
2007
+ var defaultDisk = () => process.platform === "win32" ? `${process.env.SystemDrive ?? "C:"}\\` : "/";
2008
+ async function disks(context) {
2009
+ const list = String(context.settings().disks || defaultDisk()).split(",").map((d) => d.trim()).filter(Boolean);
2010
+ const out = {};
2011
+ for (const path of list) {
2012
+ const name = /^[a-z]:/i.test(path) ? path[0].toLowerCase() : path;
2013
+ const full = /^[a-z]:$/i.test(path) ? `${path}\\` : path;
2014
+ const usage = await measured(context, `disk ${path}`, () => diskUsage(full));
2015
+ if (usage)
2016
+ out[name] = usage;
2017
+ }
2018
+ return out;
2019
+ }
2020
+ var throughputSource = new Shared((emit) => watchNetwork(emit, (error) => networkError?.(error)));
2021
+ var networkError;
2022
+ var netState = (id, name, pick) => ({
2023
+ id,
2024
+ name,
2025
+ type: "number",
2026
+ unit: "B/s",
2027
+ start: (set, context) => {
2028
+ networkError = (error) => markUnavailable(context, "network speed", error);
2029
+ return throughputSource.listen((rate) => set(pick(rate)));
2030
+ }
2031
+ });
2032
+ var gpuState = (id, name, type, pick, unit) => ({
2033
+ id,
2034
+ name,
2035
+ type,
2036
+ ...unit && { unit },
2037
+ poll: {
2038
+ everyMs: 2000,
2039
+ read: async (context) => {
2040
+ const g = await gpu(context);
2041
+ return g && pick(g);
2042
+ }
2043
+ }
2044
+ });
2045
+ var monitoring = [
2046
+ (() => {
2047
+ let sample;
2048
+ return {
2049
+ id: "cpuCores",
2050
+ name: "CPU use per core",
2051
+ type: "json",
2052
+ description: "system.cpuCores[0] is the first core.",
2053
+ poll: {
2054
+ everyMs: 2000,
2055
+ read: () => {
2056
+ sample ??= coreSampler();
2057
+ return sample();
2058
+ }
2059
+ }
2060
+ };
2061
+ })(),
2062
+ {
2063
+ id: "disks",
2064
+ name: "Disks",
2065
+ type: "json",
2066
+ description: "system.disks.c.percent, .free, .total (choose them in the plugin's settings).",
2067
+ poll: { everyMs: 15000, read: disks }
2068
+ },
2069
+ {
2070
+ id: "disk",
2071
+ name: "Disk space used",
2072
+ type: "number",
2073
+ unit: "%",
2074
+ description: "The first disk in the plugin's settings.",
2075
+ poll: {
2076
+ everyMs: 15000,
2077
+ read: async (context) => Object.values(await disks(context))[0]?.percent
2078
+ }
2079
+ },
2080
+ netState("netDown", "Download speed", (c) => c.received),
2081
+ netState("netUp", "Upload speed", (c) => c.sent),
2082
+ {
2083
+ id: "ping",
2084
+ name: "Ping",
2085
+ type: "number",
2086
+ unit: "ms",
2087
+ description: "To the host in the plugin's settings.",
2088
+ poll: {
2089
+ everyMs: 5000,
2090
+ read: (context) => measured(context, "ping", () => ping(String(context.settings().pingHost)))
2091
+ }
2092
+ },
2093
+ gpuState("gpu", "GPU load", "number", (g) => g.load, "%"),
2094
+ gpuState("gpuTemp", "GPU temperature", "number", (g) => g.temperature, "\xB0C"),
2095
+ gpuState("gpuMemory", "GPU memory used", "number", (g) => g.memory, "%"),
2096
+ gpuState("gpuName", "GPU name", "string", (g) => g.name),
2097
+ {
2098
+ id: "cpuTemp",
2099
+ name: "CPU temperature",
2100
+ type: "number",
2101
+ unit: "\xB0C",
2102
+ poll: {
2103
+ everyMs: 5000,
2104
+ read: (context) => measured(context, "CPU temperature", () => cpuTemperature())
2105
+ }
2106
+ },
2107
+ {
2108
+ id: "fps",
2109
+ name: "Frame rate",
2110
+ type: "number",
2111
+ description: "Of the app in front, measured by PresentMon.",
2112
+ start: (set, context) => {
2113
+ let front;
2114
+ const stopFront = foreground.listen((app) => {
2115
+ front = app;
2116
+ });
2117
+ let stop = () => {};
2118
+ const begin = () => {
2119
+ stop();
2120
+ stop = watchFrameRate(String(context.settings().presentMon), () => front, set, (error) => markUnavailable(context, "frame rate", error));
2121
+ };
2122
+ begin();
2123
+ let command = context.settings().presentMon;
2124
+ const off = context.onSettings(() => {
2125
+ if (context.settings().presentMon === command)
2126
+ return;
2127
+ command = context.settings().presentMon;
2128
+ unavailable.delete("frame rate");
2129
+ begin();
2130
+ });
2131
+ return () => {
2132
+ off();
2133
+ stop();
2134
+ stopFront();
2135
+ };
2136
+ }
2137
+ }
2138
+ ];
2139
+ var processSetting = {
2140
+ process: {
2141
+ type: "text",
2142
+ label: "Process",
2143
+ placeholder: "javaw.exe",
2144
+ description: "The executable name, as in the task manager (case does not matter)."
2145
+ }
2146
+ };
2147
+ function onProcess(name, want, fire) {
2148
+ const target = name.trim().toLowerCase();
2149
+ if (!target)
2150
+ throw new Error("no process name");
2151
+ let before;
2152
+ return processes.listen((now) => {
2153
+ if (before) {
2154
+ const changes = processChanges(before, now);
2155
+ if (changes[want].includes(target))
2156
+ fire({ process: target });
2157
+ }
2158
+ before = now;
2159
+ });
2160
+ }
2161
+ var appOpen = defineTrigger({
2162
+ id: "app-open",
2163
+ name: "When an app opens",
2164
+ description: "Runs when a process starts (checked every 3 s).",
2165
+ settings: processSetting,
2166
+ subscribe: ({ settings, fire }) => onProcess(settings.process, "started", fire)
2167
+ });
2168
+ var appClose = defineTrigger({
2169
+ id: "app-close",
2170
+ name: "When an app closes",
2171
+ description: "Runs when a process exits (checked every 3 s).",
2172
+ settings: processSetting,
2173
+ subscribe: ({ settings, fire }) => onProcess(settings.process, "stopped", fire)
2174
+ });
2175
+ var fileCreated = defineTrigger({
2176
+ id: "file-created",
2177
+ name: "When a file appears",
2178
+ description: "Runs when a new file shows up in a folder (event.name, event.path).",
2179
+ settings: {
2180
+ folder: { type: "text", label: "Folder", placeholder: "C:\\Users\\me\\Downloads" },
2181
+ pattern: {
2182
+ type: "text",
2183
+ label: "Name pattern",
2184
+ placeholder: "*.png",
2185
+ description: "Empty means any file."
2186
+ }
2187
+ },
2188
+ subscribe: ({ settings, fire }) => {
2189
+ if (!settings.folder)
2190
+ throw new Error("no folder");
2191
+ const pattern = namePattern(settings.pattern);
2192
+ return watchFolder(settings.folder, (name) => {
2193
+ if (pattern.test(name))
2194
+ fire({ name, path: join3(settings.folder, name) });
2195
+ });
2196
+ }
2197
+ });
2198
+ var networkChange = defineTrigger({
2199
+ id: "network-change",
2200
+ name: "When the network changes",
2201
+ description: "Runs when network addresses change (event.online, event.addresses).",
2202
+ settings: {},
2203
+ subscribe: ({ fire }) => {
2204
+ let before;
2205
+ return network.listen((addresses) => {
2206
+ const key = addresses.join(`
2207
+ `);
2208
+ if (before !== undefined && key !== before) {
2209
+ fire({ online: addresses.length > 0, addresses });
2210
+ }
2211
+ before = key;
2212
+ });
2213
+ }
2214
+ });
2215
+ var idleTrigger = defineTrigger({
2216
+ id: "idle",
2217
+ name: "When the computer is idle",
2218
+ description: "Runs after no keyboard or mouse input for a while, or when input comes back.",
2219
+ settings: {
2220
+ minutes: { type: "number", label: "Idle for (minutes)", default: 5, min: 1, max: 600 },
2221
+ when: {
2222
+ type: "select",
2223
+ label: "Run",
2224
+ default: "idle",
2225
+ options: [
2226
+ { value: "idle", label: "When it becomes idle" },
2227
+ { value: "back", label: "When input comes back" }
2228
+ ]
2229
+ }
2230
+ },
2231
+ subscribe: ({ settings, fire, plugin }) => {
2232
+ const limit = settings.minutes * 60;
2233
+ let isIdle = false;
2234
+ const stop = idle.listen((seconds) => {
2235
+ if (!isIdle && seconds >= limit) {
2236
+ isIdle = true;
2237
+ if (settings.when === "idle")
2238
+ fire({ seconds });
2239
+ } else if (isIdle && seconds < limit) {
2240
+ isIdle = false;
2241
+ if (settings.when === "back")
2242
+ fire({ seconds });
2243
+ }
2244
+ });
2245
+ const check = setTimeout(() => {
2246
+ if (idleError)
2247
+ plugin.log("idle trigger:", idleError.message);
2248
+ }, 5000);
2249
+ return () => {
2250
+ clearTimeout(check);
2251
+ stop();
2252
+ };
2253
+ }
2254
+ });
2255
+ var appFocus = defineTrigger({
2256
+ id: "app-focus",
2257
+ name: "When an app comes to the front",
2258
+ description: "Runs when a window of this app gets focus (event.app), or of any app if empty.",
2259
+ settings: {
2260
+ process: {
2261
+ ...processSetting.process,
2262
+ description: "The executable name; empty means any app."
2263
+ }
2264
+ },
2265
+ subscribe: ({ settings, fire, plugin }) => {
2266
+ const target = settings.process.trim().toLowerCase();
2267
+ let first = true;
2268
+ const stop = foreground.listen((app) => {
2269
+ if (!first && app && (!target || app === target))
2270
+ fire({ app });
2271
+ first = false;
2272
+ });
2273
+ const check = setTimeout(() => {
2274
+ if (foregroundError)
2275
+ plugin.log("app focus trigger:", foregroundError.message);
2276
+ }, 5000);
2277
+ return () => {
2278
+ clearTimeout(check);
2279
+ stop();
2280
+ };
2281
+ }
2282
+ });
2283
+ var src_default = definePlugin({
2284
+ id: "@sdeck/plugin-system",
2285
+ name: "System",
2286
+ version: "0.2.0",
2287
+ description: "Open apps and run commands, press media keys and shortcuts, lock and sleep, take screenshots, and monitor the computer.",
2288
+ author: "sdeck",
2289
+ permissions: ["shell", "process", "input", "network", "filesystem"],
2290
+ settings: {
2291
+ pingHost: { type: "text", label: "Ping host", default: "1.1.1.1" },
2292
+ disks: {
2293
+ type: "text",
2294
+ label: "Disks",
2295
+ placeholder: process.platform === "win32" ? "C:, D:" : "/, /home",
2296
+ description: "Comma separated. Empty means the system disk."
2297
+ },
2298
+ presentMon: {
2299
+ type: "text",
2300
+ label: "PresentMon",
2301
+ default: "PresentMon",
2302
+ description: "Command or full path, for the frame rate (Windows)."
2303
+ }
2304
+ },
2305
+ actions: [open, command, media, hotkey, type, screenshot, lock, sleep, stats, pingAction],
2306
+ triggers: [appOpen, appClose, appFocus, fileCreated, networkChange, idleTrigger],
2307
+ state: [
2308
+ ...monitoring,
2309
+ (() => {
2310
+ let sample;
2311
+ return {
2312
+ id: "cpu",
2313
+ name: "CPU use",
2314
+ type: "number",
2315
+ unit: "%",
2316
+ poll: {
2317
+ everyMs: 2000,
2318
+ read: () => {
2319
+ sample ??= cpuSampler();
2320
+ return sample();
2321
+ }
2322
+ }
2323
+ };
2324
+ })(),
2325
+ {
2326
+ id: "memory",
2327
+ name: "Memory use",
2328
+ type: "number",
2329
+ unit: "%",
2330
+ poll: { everyMs: 2000, read: () => Math.round(100 * (1 - freemem() / totalmem())) }
2331
+ },
2332
+ {
2333
+ id: "memoryFree",
2334
+ name: "Free memory",
2335
+ type: "number",
2336
+ unit: "bytes",
2337
+ poll: { everyMs: 2000, read: () => freemem() }
2338
+ },
2339
+ {
2340
+ id: "processes",
2341
+ name: "Running processes",
2342
+ type: "json",
2343
+ description: 'Lowercased names; e.g. contains(system.processes, "javaw.exe").',
2344
+ start: (set) => processes.listen((names) => set([...names]))
2345
+ },
2346
+ {
2347
+ id: "idle",
2348
+ name: "Idle time",
2349
+ type: "number",
2350
+ unit: "s",
2351
+ description: "Seconds since the last keyboard or mouse input.",
2352
+ start: (set) => idle.listen(set)
2353
+ },
2354
+ {
2355
+ id: "foreground",
2356
+ name: "App in front",
2357
+ type: "string",
2358
+ description: `The focused window's executable, lowercased ("javaw.exe"); empty when none. Profiles switch on it.`,
2359
+ start: (set) => foreground.listen(set)
2360
+ },
2361
+ {
2362
+ id: "online",
2363
+ name: "Online",
2364
+ type: "boolean",
2365
+ description: "Whether any network interface has an address.",
2366
+ start: (set) => network.listen((addresses) => set(addresses.length > 0))
2367
+ }
2368
+ ],
2369
+ activate(context) {
2370
+ context.log("ready on", process.platform);
2371
+ }
2372
+ });
2373
+ export {
2374
+ INPUT_SIZE,
2375
+ NVIDIA_QUERY,
2376
+ Shared,
2377
+ Unavailable,
2378
+ capture,
2379
+ coreSampler,
2380
+ cpuSampler,
2381
+ cpuTemperature,
2382
+ src_default as default,
2383
+ diskUsage,
2384
+ encodeInputs,
2385
+ foregroundName,
2386
+ frameRate,
2387
+ hotkeyEvents,
2388
+ idleSeconds,
2389
+ isHost,
2390
+ listProcesses,
2391
+ macHotkey,
2392
+ namePattern,
2393
+ networkAddresses,
2394
+ openWithSystem,
2395
+ parseNetstat,
2396
+ parseNvidia,
2397
+ parsePing,
2398
+ parseProcNetDev,
2399
+ parseThermalZone,
2400
+ ping,
2401
+ presentMonParser,
2402
+ processChanges,
2403
+ readGpu,
2404
+ runShell,
2405
+ screenshotName,
2406
+ systemControls,
2407
+ textEvents,
2408
+ throughput,
2409
+ watchFolder,
2410
+ watchForeground,
2411
+ watchFrameRate,
2412
+ watchIdle,
2413
+ watchNetwork,
2414
+ xHotkey
2415
+ };
2416
+
2417
+ //# debugId=FB0D3C42A9AF9F4864756E2164756E21