kiosko 0.2.10 → 0.2.12

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/cli.js CHANGED
@@ -21,12 +21,12 @@ function dayKey(at) {
21
21
  }
22
22
  function scheduleOn(w, at) {
23
23
  const day = new Date(at).getDay();
24
- const own = w.byDay?.[String(day)] ?? {};
25
- const start = own.start || w.start;
26
- const end = own.end || w.end;
24
+ const own2 = w.byDay?.[String(day)] ?? {};
25
+ const start = own2.start || w.start;
26
+ const end = own2.end || w.end;
27
27
  const holiday = (w.holidays ?? []).includes(dayKey(at));
28
28
  const working = w.days.includes(day) && !holiday;
29
- return { working, holiday, start, end, startMin: minutesOf(start), endMin: minutesOf(end), hours: working ? own.hours ?? w.hours ?? 0 : 0 };
29
+ return { working, holiday, start, end, startMin: minutesOf(start), endMin: minutesOf(end), hours: working ? own2.hours ?? w.hours ?? 0 : 0 };
30
30
  }
31
31
  function isWorkingAt(w, at) {
32
32
  const s = scheduleOn(w, at);
@@ -197,7 +197,7 @@ function toJsonSchema(f) {
197
197
  const secret = f.kind === "string" && !!f.secret;
198
198
  const help = f.help === void 0 ? void 0 : localize(f.help, "en");
199
199
  const description = secret ? [help, SECRET_NOTE].filter(Boolean).join(" ") : help;
200
- const base3 = {
200
+ const base4 = {
201
201
  ...f.label === void 0 ? {} : { title: localize(f.label, "en") },
202
202
  ...description ? { description } : {},
203
203
  default: f.default,
@@ -207,21 +207,21 @@ function toJsonSchema(f) {
207
207
  };
208
208
  switch (f.kind) {
209
209
  case "string":
210
- return { ...base3, type: "string", ...f.format === "date" ? { format: "date" } : {}, ...f.maxLength ? { maxLength: f.maxLength } : {}, "x-ui": { ...ui, secret: f.secret, multiline: f.multiline, placeholder: f.placeholder, format: f.format, choices: f.choices } };
210
+ return { ...base4, type: "string", ...f.format === "date" ? { format: "date" } : {}, ...f.maxLength ? { maxLength: f.maxLength } : {}, "x-ui": { ...ui, secret: f.secret, multiline: f.multiline, placeholder: f.placeholder, format: f.format, choices: f.choices } };
211
211
  case "color":
212
- return { ...base3, type: "string", "x-ui": { ...ui, widget: "color" } };
212
+ return { ...base4, type: "string", "x-ui": { ...ui, widget: "color" } };
213
213
  case "number":
214
- return { ...base3, type: f.integer ? "integer" : "number", minimum: f.min, maximum: f.max, "x-ui": { ...ui, unit: f.unit, step: f.step, slider: f.slider } };
214
+ return { ...base4, type: f.integer ? "integer" : "number", minimum: f.min, maximum: f.max, "x-ui": { ...ui, unit: f.unit, step: f.step, slider: f.slider } };
215
215
  case "boolean":
216
- return { ...base3, type: "boolean" };
216
+ return { ...base4, type: "boolean" };
217
217
  case "enum":
218
- return { ...base3, type: "string", enum: [...f.values], "x-ui": { ...ui, labels: f.labels } };
218
+ return { ...base4, type: "string", enum: [...f.values], "x-ui": { ...ui, labels: f.labels } };
219
219
  case "list":
220
- return { ...base3, type: "array", items: toJsonSchema(f.item), maxItems: f.max, ...f.filter ? { "x-ui": { ...ui, widget: "filter", choices: f.item.kind === "string" ? f.item.choices : void 0 }, "x-filter": true } : {} };
220
+ return { ...base4, type: "array", items: toJsonSchema(f.item), maxItems: f.max, ...f.filter ? { "x-ui": { ...ui, widget: "filter", choices: f.item.kind === "string" ? f.item.choices : void 0 }, "x-filter": true } : {} };
221
221
  case "map":
222
- return { ...base3, type: "object", additionalProperties: { type: "string" } };
222
+ return { ...base4, type: "object", additionalProperties: { type: "string" }, ...f.keyChoices ? { "x-ui": { ...ui, keyChoices: f.keyChoices } } : {} };
223
223
  case "object":
224
- return { ...base3, type: "object", properties: Object.fromEntries(Object.entries(f.props).map(([k, sub]) => [k, toJsonSchema(sub)])) };
224
+ return { ...base4, type: "object", properties: Object.fromEntries(Object.entries(f.props).map(([k, sub]) => [k, toJsonSchema(sub)])) };
225
225
  }
226
226
  }
227
227
  function risksOf(f) {
@@ -358,10 +358,10 @@ function createFormatters(o) {
358
358
  const h = d.getHours();
359
359
  const rest = `:${pad2(d.getMinutes())}${opts.seconds ? `:${pad2(d.getSeconds())}` : ""}`;
360
360
  if (!hour12) return `${pad2(h)}${rest}`;
361
- const base3 = `${h % 12 || 12}${rest}`;
362
- if (opts.ampm === false) return base3;
361
+ const base4 = `${h % 12 || 12}${rest}`;
362
+ if (opts.ampm === false) return base4;
363
363
  const mark = h < 12 ? w.am : w.pm;
364
- return w.ampmFirst ? `${mark} ${base3}` : `${base3} ${mark}`;
364
+ return w.ampmFirst ? `${mark} ${base4}` : `${base4} ${mark}`;
365
365
  },
366
366
  range(from, to, opts = {}) {
367
367
  const a = new Date(toMs(from));
@@ -738,8 +738,8 @@ var init_sparkline = __esm({
738
738
  // packages/lcd-canvas-kit/src/pixelshift.ts
739
739
  function pixelShift(now, o) {
740
740
  if (!o.enabled) return { x: 0, y: 0 };
741
- const step = CYCLE[Math.floor(now / o.periodMs) % CYCLE.length];
742
- return { x: Math.round(step[0] * o.amplitude), y: Math.round(step[1] * o.amplitude) };
741
+ const step2 = CYCLE[Math.floor(now / o.periodMs) % CYCLE.length];
742
+ return { x: Math.round(step2[0] * o.amplitude), y: Math.round(step2[1] * o.amplitude) };
743
743
  }
744
744
  var CYCLE;
745
745
  var init_pixelshift = __esm({
@@ -1139,8 +1139,8 @@ var init_testing = __esm({
1139
1139
 
1140
1140
  // packages/server/src/cli.ts
1141
1141
  import { spawn as spawn3 } from "node:child_process";
1142
- import { existsSync as existsSync18, readFileSync as readFileSync13, writeFileSync as writeFileSync13 } from "node:fs";
1143
- import { dirname as dirname9, join as join20 } from "node:path";
1142
+ import { existsSync as existsSync19, readFileSync as readFileSync14, writeFileSync as writeFileSync14 } from "node:fs";
1143
+ import { dirname as dirname9, join as join22 } from "node:path";
1144
1144
 
1145
1145
  // packages/core/src/config/model.ts
1146
1146
  init_workday();
@@ -1199,6 +1199,50 @@ function rescale(items, from, to) {
1199
1199
  });
1200
1200
  }
1201
1201
 
1202
+ // packages/core/src/config/profiles.ts
1203
+ var PROFILE_SEP = "#";
1204
+ var PROFILE_ID_PATTERN = "^[a-z0-9][a-z0-9_-]{0,39}$";
1205
+ var PROFILE_ID_RE = new RegExp(PROFILE_ID_PATTERN);
1206
+ var isProfileId = (id) => typeof id === "string" && PROFILE_ID_RE.test(id);
1207
+ var acceptsProfiles = (def) => def?.profiles === true;
1208
+ function sourceKey(type, profile) {
1209
+ return profile ? `${type}${PROFILE_SEP}${profile}` : type;
1210
+ }
1211
+ function parseSourceKey(key) {
1212
+ const i = key.indexOf(PROFILE_SEP);
1213
+ return i < 0 ? { type: key, profile: null } : { type: key.slice(0, i), profile: key.slice(i + 1) || null };
1214
+ }
1215
+ function profilesOf(cfg, type) {
1216
+ return cfg.sourceProfiles?.[type] ?? {};
1217
+ }
1218
+ function resolveSourceKey(cfg, type, profile, def) {
1219
+ if (!profile || !acceptsProfiles(def) || !Object.hasOwn(profilesOf(cfg, type), profile)) return type;
1220
+ return sourceKey(type, profile);
1221
+ }
1222
+ function sourceKeysOf(cfg, types2, profile, source) {
1223
+ return (types2 ?? []).map((t2) => [t2, resolveSourceKey(cfg, t2, profile, source(t2))]);
1224
+ }
1225
+ function sourceOptionsOf(cfg, key) {
1226
+ const { type, profile } = parseSourceKey(key);
1227
+ if (!profile) return cfg.sources[type] ?? {};
1228
+ return profilesOf(cfg, type)[profile]?.options ?? {};
1229
+ }
1230
+ function normalizeProfiles(raw2) {
1231
+ if (!raw2 || typeof raw2 !== "object" || Array.isArray(raw2)) return void 0;
1232
+ const out = {};
1233
+ for (const [type, list2] of Object.entries(raw2)) {
1234
+ if (!list2 || typeof list2 !== "object" || Array.isArray(list2)) continue;
1235
+ const clean = {};
1236
+ for (const [id, p] of Object.entries(list2)) {
1237
+ if (!isProfileId(id) || !p || typeof p !== "object" || Array.isArray(p)) continue;
1238
+ const { name: name2, options: options2 } = p;
1239
+ clean[id] = { name: typeof name2 === "string" && name2.trim() ? name2 : id, options: options2 && typeof options2 === "object" && !Array.isArray(options2) ? options2 : {} };
1240
+ }
1241
+ if (Object.keys(clean).length) out[type] = clean;
1242
+ }
1243
+ return Object.keys(out).length ? out : void 0;
1244
+ }
1245
+
1202
1246
  // packages/core/src/config/model.ts
1203
1247
  var CONFIG_VERSION = 1;
1204
1248
  var CONFIG_SCHEMA_ID = "https://kioskolcd.dev/schema/v1/config.json";
@@ -1214,6 +1258,8 @@ function zoomOf(inst) {
1214
1258
  if (typeof z !== "number" || !Number.isFinite(z)) return 1;
1215
1259
  return Math.round(Math.min(ZOOM.max, Math.max(ZOOM.min, z)) * 100) / 100;
1216
1260
  }
1261
+ var COMPARE_OPS = ["truthy", "falsy", "eq", "ne", "gt", "gte", "lt", "lte", "contains"];
1262
+ var CONTEXT_TIMING = { minMs: 2e4, holdMs: 1e4 };
1217
1263
  var THREADS_MODES = ["auto", "always", "never"];
1218
1264
  var ALERT_THRESHOLDS = ["info", "warn", "critical", "off"];
1219
1265
  function screenAlerts(s) {
@@ -1235,6 +1281,7 @@ var READING_CM = { near: 40, normal: 60, far: 90 };
1235
1281
  var TEXT_SCALE = { min: 0.75, max: 2, step: 0.05 };
1236
1282
  var DEFAULT_MAX_BYTES = 48e4;
1237
1283
  var SETUP_STATES = ["pending", "done", "skipped"];
1284
+ var PUSH_NAME_PATTERN = "^[a-z0-9][a-z0-9_-]{0,39}$";
1238
1285
  var STARTER_NAMES = {
1239
1286
  screen: { en: "My panel", es: "Mi panel", de: "Mein Panel", "zh-Hant": "\u6211\u7684\u9762\u677F", "zh-Hans": "\u6211\u7684\u5C4F\u5E55" },
1240
1287
  page: { en: "Home", es: "Inicio", de: "Start", "zh-Hant": "\u9996\u9801", "zh-Hans": "\u9996\u9875" }
@@ -1385,10 +1432,13 @@ var CATEGORIES = [
1385
1432
  ];
1386
1433
  var ALERT_LEVELS = ["info", "warn", "critical"];
1387
1434
  var PAD_KEYS = ["up", "down", "left", "right", "a", "b", "x", "y", "l", "r", "start", "select"];
1388
- var SDK_VERSION = "0.2.10";
1435
+ var SDK_VERSION = "0.2.12";
1389
1436
  function defineWidget(w) {
1390
1437
  return w;
1391
1438
  }
1439
+ function defineSource(s) {
1440
+ return s;
1441
+ }
1392
1442
  function definePlugin(p) {
1393
1443
  return p;
1394
1444
  }
@@ -1479,21 +1529,21 @@ function listLayout(box, count, options2, spec) {
1479
1529
  const divisor = fixed > 0 ? fixed : Math.max(n, spec.minRows ?? 1, 1);
1480
1530
  const fits = (space, rowH2) => Math.floor(space / rowH2 + TOLERANCE);
1481
1531
  let rowH = clamp2(h / divisor, min, max);
1482
- let shown = Math.min(target, fits(h, rowH));
1532
+ let shown2 = Math.min(target, fits(h, rowH));
1483
1533
  let more = null;
1484
- if (shown < n) {
1534
+ if (shown2 < n) {
1485
1535
  let moreH = Math.min(spec.moreH ?? moreHeight(rowH), rowH);
1486
1536
  rowH = clamp2((h - moreH) / divisor, min, max);
1487
- shown = Math.min(target, fits(h - moreH, rowH));
1488
- if (shown < 1) {
1489
- shown = Math.min(1, n);
1537
+ shown2 = Math.min(target, fits(h - moreH, rowH));
1538
+ if (shown2 < 1) {
1539
+ shown2 = Math.min(1, n);
1490
1540
  rowH = Math.min(h, min);
1491
1541
  moreH = Math.min(moreH, h - rowH);
1492
1542
  }
1493
- if (moreH >= MIN_MORE_H) more = { x: box.x, y: box.y + shown * rowH, w: box.w, h: moreH };
1543
+ if (moreH >= MIN_MORE_H) more = { x: box.x, y: box.y + shown2 * rowH, w: box.w, h: moreH };
1494
1544
  }
1495
- const rows = Array.from({ length: shown }, (_, i) => ({ x: box.x, y: box.y + i * rowH, w: box.w, h: rowH }));
1496
- return { layout, rowH, rows, shown, hidden: n - shown, more, ...text3(rowH) };
1545
+ const rows = Array.from({ length: shown2 }, (_, i) => ({ x: box.x, y: box.y + i * rowH, w: box.w, h: rowH }));
1546
+ return { layout, rowH, rows, shown: shown2, hidden: n - shown2, more, ...text3(rowH) };
1497
1547
  }
1498
1548
  function moreLabel(n, tr) {
1499
1549
  return tr({ en: `+${n} more`, es: `+${n} m\xE1s`, de: `+${n} weitere`, "zh-Hant": `\u9084\u6709 ${n} \u500B`, "zh-Hans": `\u8FD8\u6709 ${n} \u4E2A` });
@@ -1641,6 +1691,35 @@ var hostOf = (url2) => {
1641
1691
  return url2;
1642
1692
  }
1643
1693
  };
1694
+ async function limitedText(res, max, url2) {
1695
+ const tooBig = () => new HttpError(`response larger than ${max} bytes from ${hostOf(url2)}`, { status: res.status, url: url2 });
1696
+ const declared = Number(res.headers.get("content-length"));
1697
+ if (Number.isFinite(declared) && declared > max) {
1698
+ await res.body?.cancel().catch(() => void 0);
1699
+ throw tooBig();
1700
+ }
1701
+ if (!res.body) return "";
1702
+ const reader = res.body.getReader();
1703
+ const chunks = [];
1704
+ let size = 0;
1705
+ for (; ; ) {
1706
+ const { done: done2, value } = await reader.read();
1707
+ if (done2) break;
1708
+ size += value.byteLength;
1709
+ if (size > max) {
1710
+ await reader.cancel().catch(() => void 0);
1711
+ throw tooBig();
1712
+ }
1713
+ chunks.push(value);
1714
+ }
1715
+ const all = new Uint8Array(size);
1716
+ let at = 0;
1717
+ for (const c of chunks) {
1718
+ all.set(c, at);
1719
+ at += c.byteLength;
1720
+ }
1721
+ return new TextDecoder().decode(all);
1722
+ }
1644
1723
  function createHttp(o = {}) {
1645
1724
  const doFetch = o.fetch ?? fetch;
1646
1725
  const now = o.now ?? Date.now;
@@ -1670,7 +1749,7 @@ function createHttp(o = {}) {
1670
1749
  throw new HttpError(`HTTP ${res.status} from ${host}: rate-limited until ${new Date(at).toISOString()}`, { status: res.status, url: url2, retryAt: at });
1671
1750
  }
1672
1751
  if (!res.ok) throw new HttpError(`HTTP ${res.status} from ${host}`, { status: res.status, url: url2 });
1673
- const body2 = await res.text();
1752
+ const body2 = req.maxBytes === void 0 ? await res.text() : await limitedText(res, req.maxBytes, url2);
1674
1753
  if (cacheable) {
1675
1754
  const etag = res.headers.get("etag") ?? void 0;
1676
1755
  const modified = res.headers.get("last-modified") ?? void 0;
@@ -1732,8 +1811,8 @@ var paths = {
1732
1811
  */
1733
1812
  cache(plugin) {
1734
1813
  if (platform() === "win32") return join2(process.env.LOCALAPPDATA ?? join2(homedir2(), "AppData", "Local"), "Kiosko", "cache", plugin.replace(/[^a-z0-9._-]/gi, "_"));
1735
- const base3 = process.env.XDG_RUNTIME_DIR && existsSync(process.env.XDG_RUNTIME_DIR) ? join2(process.env.XDG_RUNTIME_DIR, "kiosko-cache") : existsSync("/dev/shm") ? `/dev/shm/kiosko-cache-${process.getuid?.() ?? "u"}` : null;
1736
- return base3 && join2(base3, plugin.replace(/[^a-z0-9._-]/gi, "_"));
1814
+ const base4 = process.env.XDG_RUNTIME_DIR && existsSync(process.env.XDG_RUNTIME_DIR) ? join2(process.env.XDG_RUNTIME_DIR, "kiosko-cache") : existsSync("/dev/shm") ? `/dev/shm/kiosko-cache-${process.getuid?.() ?? "u"}` : null;
1815
+ return base4 && join2(base4, plugin.replace(/[^a-z0-9._-]/gi, "_"));
1737
1816
  },
1738
1817
  /** Per-plugin data that must persist: `data/<plugin>`. */
1739
1818
  data(plugin) {
@@ -1745,8 +1824,9 @@ var paths = {
1745
1824
  init_format();
1746
1825
  init_workday();
1747
1826
  function normalize(raw2) {
1748
- const { $schema, threads, setup, bootAnimation, ...c } = raw2 && typeof raw2 === "object" && !Array.isArray(raw2) ? raw2 : {};
1827
+ const { $schema, threads, setup, bootAnimation, sourceProfiles, ...c } = raw2 && typeof raw2 === "object" && !Array.isArray(raw2) ? raw2 : {};
1749
1828
  const screens = Array.isArray(c.screens) ? c.screens.map(normalizeScreen) : [];
1829
+ const profiles = normalizeProfiles(sourceProfiles);
1750
1830
  return {
1751
1831
  ...typeof $schema === "string" && $schema ? { $schema } : {},
1752
1832
  ...DEFAULT_CONFIG,
@@ -1756,9 +1836,12 @@ function normalize(raw2) {
1756
1836
  // A copy of the defaults: the editor edits the result in place.
1757
1837
  workday: { ...JSON.parse(JSON.stringify(DEFAULT_WORKDAY)), ...c.workday ?? {} },
1758
1838
  sources: c.sources ?? {},
1839
+ // Only when there are any: a config without profiles stays as it was.
1840
+ ...profiles ? { sourceProfiles: profiles } : {},
1759
1841
  plugins: { disabled: c.plugins?.disabled ?? [] },
1760
1842
  server: { ...DEFAULT_CONFIG.server, ...c.server ?? {} },
1761
1843
  ...c.homeassistant && typeof c.homeassistant === "object" ? { homeassistant: normalizeHa(c.homeassistant) } : {},
1844
+ ...c.push && typeof c.push === "object" ? { push: normalizePush(c.push) } : {},
1762
1845
  ...THREADS_MODES.includes(threads) ? { threads } : {},
1763
1846
  ...SETUP_STATES.includes(setup) ? { setup } : {},
1764
1847
  // On unless switched off: only `false` is written.
@@ -1777,6 +1860,18 @@ function normalizeHa(h) {
1777
1860
  nodeId: id || "kiosko"
1778
1861
  };
1779
1862
  }
1863
+ function normalizePush(p) {
1864
+ const seen = /* @__PURE__ */ new Set();
1865
+ const name2 = new RegExp(PUSH_NAME_PATTERN);
1866
+ const hooks = (Array.isArray(p.hooks) ? p.hooks : []).flatMap((h) => {
1867
+ if (!h || typeof h !== "object") return [];
1868
+ const n = String(h.name ?? "").trim().toLowerCase();
1869
+ if (!name2.test(n) || seen.has(n)) return [];
1870
+ seen.add(n);
1871
+ return [{ name: n, token: typeof h.token === "string" ? h.token.trim() : "" }];
1872
+ });
1873
+ return { hooks };
1874
+ }
1780
1875
  function normalizeScreen(s, i) {
1781
1876
  const width = s.width ?? 1920;
1782
1877
  const height = s.height ?? 462;
@@ -1794,12 +1889,14 @@ function normalizeScreen(s, i) {
1794
1889
  enabled: p.enabled ?? true,
1795
1890
  durationMs: p.durationMs ?? 10 * 6e4,
1796
1891
  when: p.when ?? "always",
1892
+ ...normalizeShowWhen(p.showWhen, p.inRotation),
1797
1893
  grid: p.grid ?? suggestGrid(width, height),
1798
1894
  gravity: p.gravity ?? "none",
1799
1895
  background: p.background ?? {},
1800
1896
  tiles: (p.tiles ?? []).map((t2, k) => ({ id: t2.id ?? `tile-${k + 1}`, x: t2.x ?? 0, y: t2.y ?? 0, w: t2.w ?? 1, h: t2.h ?? 1, ...t2.locked ? { locked: true } : {}, widgets: (t2.widgets ?? []).map((w, n) => ({ ...w, id: w.id ?? `w-${i + 1}-${j + 1}-${k + 1}-${n + 1}`, options: w.options ?? {} })), rotateMs: t2.rotateMs ?? 3e4, chrome: t2.chrome ?? "auto" }))
1801
1897
  })),
1802
1898
  ...s.pinnedPage ? { pinnedPage: s.pinnedPage } : {},
1899
+ ...normalizeContextTiming(s.context),
1803
1900
  interludes: (s.interludes ?? []).map((x, k) => ({ id: x.id ?? `interlude-${k + 1}`, type: x.type, enabled: x.enabled ?? true, everyMs: x.everyMs ?? 15 * 6e4, maxSeconds: x.maxSeconds ?? 30, options: x.options ?? {} })),
1804
1901
  pixelShift: { enabled: true, amplitude: 2, periodMs: 8 * 6e4, ...s.pixelShift ?? {} },
1805
1902
  sleepWhenIdle: s.sleepWhenIdle ?? false,
@@ -1815,6 +1912,40 @@ function normalizeScreen(s, i) {
1815
1912
  };
1816
1913
  }
1817
1914
  var HHMM = /^([01][0-9]|2[0-3]):[0-5][0-9]$/;
1915
+ function normalizeShowWhen(raw2, inRotation2) {
1916
+ if (!Array.isArray(raw2)) return {};
1917
+ const rules = [];
1918
+ for (const r of raw2) {
1919
+ if (!r || typeof r !== "object") continue;
1920
+ const out = {};
1921
+ if (typeof r.label === "string" && r.label.trim()) out.label = r.label.trim();
1922
+ if (typeof r.priority === "number" && Number.isFinite(r.priority) && r.priority !== 0) out.priority = Math.round(r.priority);
1923
+ if (typeof r.app === "string" && r.app.trim()) out.app = r.app.trim();
1924
+ if (typeof r.source === "string" && r.source.trim()) {
1925
+ out.source = r.source.trim();
1926
+ if (typeof r.path === "string" && r.path.trim()) out.path = r.path.trim();
1927
+ if (COMPARE_OPS.includes(r.op)) out.op = r.op;
1928
+ if (["string", "number", "boolean"].includes(typeof r.value)) out.value = r.value;
1929
+ }
1930
+ const t2 = r.time;
1931
+ if (t2 && typeof t2 === "object" && HHMM.test(String(t2.start)) && HHMM.test(String(t2.end)) && t2.start !== t2.end) {
1932
+ const days = Array.isArray(t2.days) ? [...new Set(t2.days.filter((d) => Number.isInteger(d) && d >= 0 && d <= 6))].sort() : [];
1933
+ out.time = { start: t2.start, end: t2.end, ...days.length && days.length < 7 ? { days } : {} };
1934
+ }
1935
+ if (r.urgent === true) out.urgent = true;
1936
+ if (out.app || out.source || out.time || out.urgent) rules.push(out);
1937
+ }
1938
+ if (!rules.length) return {};
1939
+ return { showWhen: rules, ...inRotation2 === true ? { inRotation: true } : {} };
1940
+ }
1941
+ function normalizeContextTiming(raw2) {
1942
+ if (!raw2 || typeof raw2 !== "object") return {};
1943
+ const c = raw2;
1944
+ const ms = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 ? Math.min(36e5, Math.round(v)) : void 0;
1945
+ const minMs = ms(c.minMs), holdMs = ms(c.holdMs);
1946
+ if (minMs === void 0 && holdMs === void 0) return {};
1947
+ return { context: { ...minMs !== void 0 ? { minMs } : {}, ...holdMs !== void 0 ? { holdMs } : {} } };
1948
+ }
1818
1949
  function normalizeAlerts(raw2) {
1819
1950
  if (!raw2 || typeof raw2 !== "object") return {};
1820
1951
  const a = raw2;
@@ -1861,11 +1992,17 @@ var MIN_TIMEOUT_MS = 1e3;
1861
1992
  var MAX_TIMEOUT_MS = 10 * 6e4;
1862
1993
  var canRunInBackground = (def) => def.background === true && typeof def.alerts === "function" && !("background" in (def.options?.props ?? {}));
1863
1994
  function backgroundSources(cfg, source) {
1864
- return Object.keys(cfg.sources).filter((type) => {
1995
+ const out = Object.keys(cfg.sources).filter((type) => {
1865
1996
  if (cfg.sources[type]?.background !== true) return false;
1866
1997
  const def = source(type);
1867
1998
  return !!def && canRunInBackground(def);
1868
1999
  });
2000
+ for (const [type, list2] of Object.entries(cfg.sourceProfiles ?? {})) {
2001
+ const def = source(type);
2002
+ if (!def || !canRunInBackground(def) || !acceptsProfiles(def)) continue;
2003
+ for (const [id, p] of Object.entries(list2)) if (p.options?.background === true) out.push(sourceKey(type, id));
2004
+ }
2005
+ return out;
1869
2006
  }
1870
2007
  function human(ms) {
1871
2008
  if (ms % 36e5 === 0) return `${ms / 36e5} h`;
@@ -1911,20 +2048,20 @@ function sourceCommonFields(def) {
1911
2048
  help: { en: "A reading that takes longer is cancelled and counts as failed; the next try comes sooner.", es: "Una lectura que tarde m\xE1s se cancela y cuenta como fallida; el siguiente intento llega antes.", de: "Ein Lesevorgang, der l\xE4nger dauert, wird abgebrochen und z\xE4hlt als fehlgeschlagen; der n\xE4chste Versuch kommt fr\xFCher.", "zh-Hant": "\u8D85\u904E\u6B64\u6642\u9593\u7684\u8B80\u53D6\u6703\u88AB\u53D6\u6D88\u4E26\u8996\u70BA\u5931\u6557\uFF1B\u4E0B\u6B21\u6703\u63D0\u65E9\u91CD\u8A66\u3002", "zh-Hans": "\u8D85\u8FC7\u6B64\u65F6\u95F4\u7684\u8BFB\u53D6\u4F1A\u88AB\u53D6\u6D88\u5E76\u89C6\u4E3A\u5931\u8D25\uFF1B\u4E0B\u6B21\u4F1A\u63D0\u524D\u91CD\u8BD5\u3002" }
1912
2049
  })
1913
2050
  });
1914
- const own = def.options?.props ?? {};
1915
- return Object.fromEntries(Object.entries(fields).filter(([k]) => !(k in own)));
2051
+ const own2 = def.options?.props ?? {};
2052
+ return Object.fromEntries(Object.entries(fields).filter(([k]) => !(k in own2)));
1916
2053
  }
1917
2054
  function sourceTimes(def, options2) {
1918
2055
  const timing = sourceTiming(def);
1919
2056
  const managed = sourceCommonFields(def);
1920
- const pick = (k) => k in managed && typeof options2[k] === "number" ? options2[k] : timing[k];
1921
- return { intervalMs: pick("intervalMs"), timeoutMs: pick("timeoutMs") };
2057
+ const pick2 = (k) => k in managed && typeof options2[k] === "number" ? options2[k] : timing[k];
2058
+ return { intervalMs: pick2("intervalMs"), timeoutMs: pick2("timeoutMs") };
1922
2059
  }
1923
2060
  var merged = /* @__PURE__ */ new WeakMap();
1924
2061
  function sourceOptionsField(def) {
1925
2062
  if (!merged.has(def)) {
1926
- const own = def.options?.props ?? {};
1927
- const props = { ...own, ...sourceCommonFields(def) };
2063
+ const own2 = def.options?.props ?? {};
2064
+ const props = { ...own2, ...sourceCommonFields(def) };
1928
2065
  const o = def.options;
1929
2066
  merged.set(def, Object.keys(props).length ? t.object(props, { ...o?.label ? { label: o.label } : {}, ...o?.help ? { help: o.help } : {} }) : null);
1930
2067
  }
@@ -1957,6 +2094,7 @@ function sizeHint(size) {
1957
2094
  return [size.min && `Needs a tile of at least ${px(size.min)}`, size.preferred && `looks best around ${px(size.preferred)}`, size.max && `at most ${px(size.max)}`].filter(Boolean).join(", ");
1958
2095
  }
1959
2096
  function configSchema(plugins) {
2097
+ const withProfiles = new Set(plugins.flatMap((p) => (p.sources ?? []).filter((s) => acceptsProfiles(s)).map((s) => `${p.id}/${s.id}`)));
1960
2098
  const sourceUsers = /* @__PURE__ */ new Map();
1961
2099
  for (const p of plugins) for (const w of p.widgets ?? []) for (const s of w.sources ?? []) sourceUsers.set(s, [...sourceUsers.get(s) ?? [], `${p.id}/${w.id}`]);
1962
2100
  for (const p of plugins) for (const i of p.interludes ?? []) for (const s of i.sources ?? []) sourceUsers.set(s, [...sourceUsers.get(s) ?? [], `${p.id}/${i.id}`]);
@@ -1979,7 +2117,8 @@ function configSchema(plugins) {
1979
2117
  disabled: { type: "boolean", default: false, description: "Kept in the tile but never shown." },
1980
2118
  zoom: { $ref: "#/$defs/zoom" },
1981
2119
  ...w.urgent ? { takeOver: { ...TAKE_OVER, default: w.takeOver ?? true } } : {},
1982
- ...w.empty ? { hideWhenEmpty: { ...HIDE_WHEN_EMPTY, default: w.hideWhenEmpty ?? false } } : {}
2120
+ ...w.empty ? { hideWhenEmpty: { ...HIDE_WHEN_EMPTY, default: w.hideWhenEmpty ?? false } } : {},
2121
+ ...w.sources?.some((x) => withProfiles.has(x)) ? { profile: { $ref: "#/$defs/profile", description: `The profile of ${w.sources.filter((x) => withProfiles.has(x)).join(", ")} it reads, by id (see "sourceProfiles"). Missing, or one that isn't there: the default one, "sources".` } } : {}
1983
2122
  },
1984
2123
  "x-plugin": p.id,
1985
2124
  "x-category": w.category ?? "info",
@@ -2029,6 +2168,30 @@ function configSchema(plugins) {
2029
2168
  })
2030
2169
  )
2031
2170
  );
2171
+ const profiles = Object.fromEntries(
2172
+ plugins.flatMap(
2173
+ (p) => (p.sources ?? []).filter((s) => acceptsProfiles(s)).map((s) => {
2174
+ const type = `${p.id}/${s.id}`;
2175
+ return [
2176
+ type,
2177
+ {
2178
+ type: "object",
2179
+ description: `Profiles of ${en(s.name)} (${type}) besides the default one, by id.`,
2180
+ propertyNames: { $ref: "#/$defs/profile" },
2181
+ additionalProperties: {
2182
+ type: "object",
2183
+ additionalProperties: false,
2184
+ required: ["name"],
2185
+ properties: {
2186
+ name: { type: "string", description: 'What it is called in the editor: "Technology", "Work account".' },
2187
+ options: { ...options(sourceOptionsField(s), "source"), description: `Its options, as "sources" has them for the default one.` }
2188
+ }
2189
+ }
2190
+ }
2191
+ ];
2192
+ })
2193
+ )
2194
+ );
2032
2195
  return {
2033
2196
  $schema: "https://json-schema.org/draft/2020-12/schema",
2034
2197
  $id: CONFIG_SCHEMA_ID,
@@ -2086,6 +2249,13 @@ function configSchema(plugins) {
2086
2249
  propertyNames: { pattern: TYPE_PATTERN, "x-pattern-hint": 'a source type such as "weather/current"' },
2087
2250
  additionalProperties: { type: "object" }
2088
2251
  },
2252
+ sourceProfiles: {
2253
+ type: "object",
2254
+ description: 'More named configurations ("profiles") of the sources that accept them, by "plugin/source" and then by profile id: { "news/deck": { "tech": { "name": "Technology", "options": { "feeds": [ \u2026 ] } } } }. Each is read on its own; a widget picks one with its "profile". The default profile is still "sources".',
2255
+ properties: profiles,
2256
+ propertyNames: { pattern: TYPE_PATTERN, "x-pattern-hint": 'a source type such as "news/deck"' },
2257
+ additionalProperties: { type: "object" }
2258
+ },
2089
2259
  plugins: {
2090
2260
  type: "object",
2091
2261
  additionalProperties: false,
@@ -2126,10 +2296,31 @@ function configSchema(plugins) {
2126
2296
  discoveryPrefix: { type: "string", default: "homeassistant", description: "Home Assistant's MQTT discovery prefix." },
2127
2297
  nodeId: { type: "string", pattern: "^[a-z0-9_-]+$", description: "This Kiosko's id in the topics, so several machines don't collide. Default: kiosko." }
2128
2298
  }
2299
+ },
2300
+ push: {
2301
+ type: "object",
2302
+ additionalProperties: false,
2303
+ description: "Names scripts may push to with POST /api/push/<name> (a value, a text, a level), for the Push and JSON widgets. Each has its own token. See docs/rest-webhook.md.",
2304
+ properties: {
2305
+ hooks: {
2306
+ type: "array",
2307
+ default: [],
2308
+ items: {
2309
+ type: "object",
2310
+ additionalProperties: false,
2311
+ required: ["name", "token"],
2312
+ properties: {
2313
+ name: { type: "string", pattern: PUSH_NAME_PATTERN, "x-pattern-hint": 'lowercase letters, digits, "-" and "_", up to 40', description: "Goes in the URL: /api/push/<name>." },
2314
+ token: { type: "string", "x-secret": true, description: 'Sent as "Authorization: Bearer <token>" (or ?token=). At least 16 characters; the editor makes a random one.' }
2315
+ }
2316
+ }
2317
+ }
2318
+ }
2129
2319
  }
2130
2320
  },
2131
2321
  $defs: {
2132
2322
  id: { type: "string", pattern: ID_PATTERN, "x-pattern-hint": 'an id of letters, digits, ".", "_" or "-" (no spaces, at most 80)', description: "Stable id, unique among its siblings (widget ids: unique in the whole config). Generated when missing." },
2323
+ profile: { type: "string", pattern: PROFILE_ID_PATTERN, "x-pattern-hint": 'a profile id: lowercase letters, digits, "-" or "_" (at most 40)' },
2133
2324
  time: { type: "string", pattern: TIME_PATTERN, "x-pattern-hint": "a time as HH:MM (24 h)" },
2134
2325
  when: { enum: ["always", "work", "off"], default: "always", description: 'When it shows: always, only in work hours, or only outside them (see "workday").' },
2135
2326
  zoom: {
@@ -2195,7 +2386,15 @@ function configSchema(plugins) {
2195
2386
  id: { type: "string", description: "The name the screen had when it was added (it may be renamed on the screen's setup page); shown until the screen says its own." },
2196
2387
  key: { type: "string", pattern: "^[0-9a-f]{64}$", description: "The pairing key (64 hex digits), set by pairing in the editor. Empty: not paired yet.", "x-secret": true },
2197
2388
  host: { type: "string", description: "Address to use instead of finding it by mDNS (another subnet, a network without multicast).", "x-risk": "network" },
2198
- port: { type: "integer", minimum: 1, maximum: 65535, default: 7428 }
2389
+ port: { type: "integer", minimum: 1, maximum: 65535, default: 7428 },
2390
+ brightness: { type: "integer", minimum: 0, maximum: 100, description: "Backlight brightness, 0-100 (perceived; 0 = off), pushed to the screen on every connection. Screen firmware 0.1.2 or later; older ones ignore it. Empty: the screen keeps its own (70 % unless set on its setup page)." },
2391
+ night: {
2392
+ type: "object",
2393
+ additionalProperties: false,
2394
+ required: ["start", "end", "brightness"],
2395
+ description: "Night mode: from start to end (local time; start after end goes across midnight) the backlight goes to this brightness (0 = off), and back at the end. Alerts that take the panel over still show at full brightness. Screen firmware 0.1.4 or later; older ones ignore it. Whatever this says, the backlight goes off while Kiosko shows the screen black (switched off, asleep).",
2396
+ properties: { start: { $ref: "#/$defs/time" }, end: { $ref: "#/$defs/time" }, brightness: { type: "integer", minimum: 0, maximum: 100 } }
2397
+ }
2199
2398
  }
2200
2399
  },
2201
2400
  {
@@ -2246,6 +2445,32 @@ function configSchema(plugins) {
2246
2445
  chrome: { enum: ["auto", "card", "bare"], default: "auto", description: "card: framed with an optional title; bare: edge to edge; auto: what the shown widget prefers." }
2247
2446
  }
2248
2447
  },
2448
+ showWhenRule: {
2449
+ type: "object",
2450
+ additionalProperties: false,
2451
+ description: "A context rule: every condition it has must hold (app, source, time, urgent); a page comes up when any of its rules holds.",
2452
+ properties: {
2453
+ label: { type: "string", description: 'What it means ("game open"), shown in the editor as the reason the page is on screen.' },
2454
+ priority: { type: "integer", default: 0, description: "Higher wins when several pages want the screen." },
2455
+ app: { type: "string", description: 'A program running: its process name as a glob, case-insensitive ("steam*", "obs*", "zoom*"); several separated by commas. Linux: the kernel name or argv[0]; macOS: the executable or its .app; Windows: the image name, with or without .exe.' },
2456
+ source: { type: "string", description: 'A source, "plugin/source" (e.g. "calls/active"): it runs even with no widget showing it.' },
2457
+ path: { type: "string", description: `Where in the source's data: dots and brackets ("active", "items[0].price"). Empty: the data itself.` },
2458
+ op: { enum: ["truthy", "falsy", "eq", "ne", "gt", "gte", "lt", "lte", "contains"], description: 'How the value compares: default eq with a "value", truthy without. No data yet (or no such path) never matches.' },
2459
+ value: { type: ["string", "number", "boolean"], description: "What the value is compared with." },
2460
+ time: {
2461
+ type: "object",
2462
+ additionalProperties: false,
2463
+ required: ["start", "end"],
2464
+ description: "A local time window; start after end goes across midnight.",
2465
+ properties: {
2466
+ start: { $ref: "#/$defs/time" },
2467
+ end: { $ref: "#/$defs/time" },
2468
+ days: { type: "array", items: { type: "integer", minimum: 0, maximum: 6 }, description: "The days it starts on, 0 = Sunday \u2026 6 = Saturday. Missing: every day." }
2469
+ }
2470
+ },
2471
+ urgent: { type: "boolean", description: "A widget on this page is urgent (a meeting about to start, a permission waiting)." }
2472
+ }
2473
+ },
2249
2474
  page: {
2250
2475
  type: "object",
2251
2476
  additionalProperties: false,
@@ -2256,6 +2481,12 @@ function configSchema(plugins) {
2256
2481
  enabled: { type: "boolean", default: true },
2257
2482
  durationMs: { type: "integer", minimum: 1e4, default: 10 * 6e4, description: "Time on screen when pages take turns, in ms." },
2258
2483
  when: { $ref: "#/$defs/when" },
2484
+ showWhen: {
2485
+ type: "array",
2486
+ items: { $ref: "#/$defs/showWhenRule" },
2487
+ description: "Context rules: while one holds (a program running, a source's value, a time window, an urgent widget on this page), this page takes the screen over from the rotation; when none holds any more, the rotation comes back. The highest priority wins; equals take turns. A pinned page and alerts still go first."
2488
+ },
2489
+ inRotation: { type: "boolean", default: false, description: 'With "showWhen": also take a turn in the normal rotation. Pages without rules always do.' },
2259
2490
  grid: { $ref: "#/$defs/grid", description: "Missing: a grid of square-ish cells of about 80 px for the screen size." },
2260
2491
  gravity: { enum: ["none", "up", "left"], default: "none", description: "How the editor closes gaps after a move: none (free placement), up (masonry), left (wide strips)." },
2261
2492
  background: {
@@ -2284,6 +2515,15 @@ function configSchema(plugins) {
2284
2515
  device: { $ref: "#/$defs/device" },
2285
2516
  pages: { type: "array", items: { $ref: "#/$defs/page" }, default: [] },
2286
2517
  pinnedPage: { type: "string", description: "Id of a page to show all the time (no turns)." },
2518
+ context: {
2519
+ type: "object",
2520
+ additionalProperties: false,
2521
+ description: 'Anti-flicker for context pages ("showWhen"), in ms. Missing: 20 s and 10 s.',
2522
+ properties: {
2523
+ minMs: { type: "integer", minimum: 0, maximum: 36e5, default: 2e4, description: "Least time a context page stays once it came up (a higher priority one doesn't wait)." },
2524
+ holdMs: { type: "integer", minimum: 0, maximum: 36e5, default: 1e4, description: "How long it stays after its rule stopped holding, in case it holds again." }
2525
+ }
2526
+ },
2287
2527
  interludes: { type: "array", items: { $ref: "#/$defs/interlude" }, default: [] },
2288
2528
  pixelShift: {
2289
2529
  type: "object",
@@ -2424,8 +2664,8 @@ function didYouMean(word, candidates) {
2424
2664
  return near2.length ? ` (did you mean ${near2.map(q).join(" or ")}?)` : "";
2425
2665
  }
2426
2666
  function listOf(values, max = 12) {
2427
- const shown = values.slice(0, max).map(q).join(", ");
2428
- return values.length > max ? `${shown}\u2026 (${values.length - max} more)` : shown;
2667
+ const shown2 = values.slice(0, max).map(q).join(", ");
2668
+ return values.length > max ? `${shown2}\u2026 (${values.length - max} more)` : shown2;
2429
2669
  }
2430
2670
  function unknownTag(tag, value, known) {
2431
2671
  const names = known.map(String);
@@ -2470,101 +2710,101 @@ function validDate(s) {
2470
2710
  const d = new Date(Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])));
2471
2711
  return d.getUTCMonth() === Number(m[2]) - 1 && d.getUTCDate() === Number(m[3]);
2472
2712
  }
2473
- function push(run, path, message, context) {
2474
- run.issues.push({ path: formatPath(path), pointer: toPointer(path), message, ...context ? { context } : {} });
2713
+ function push(run2, path, message, context) {
2714
+ run2.issues.push({ path: formatPath(path), pointer: toPointer(path), message, ...context ? { context } : {} });
2475
2715
  }
2476
- function trial(run, schema2, value, path, context) {
2477
- const sub = { root: run.root, issues: [] };
2716
+ function trial(run2, schema2, value, path, context) {
2717
+ const sub = { root: run2.root, issues: [] };
2478
2718
  check(sub, schema2, value, path, context);
2479
2719
  return sub.issues;
2480
2720
  }
2481
- function check(run, schema2, value, path, context) {
2721
+ function check(run2, schema2, value, path, context) {
2482
2722
  if (schema2 === true) return;
2483
- if (schema2 === false) return push(run, path, "is not allowed here", context);
2484
- const s = deref(run.root, schema2);
2723
+ if (schema2 === false) return push(run2, path, "is not allowed here", context);
2724
+ const s = deref(run2.root, schema2);
2485
2725
  if (s === void 0 || typeof s !== "object") return;
2486
- if (Array.isArray(s.allOf)) for (const sub of s.allOf) check(run, sub, value, path, context);
2726
+ if (Array.isArray(s.allOf)) for (const sub of s.allOf) check(run2, sub, value, path, context);
2487
2727
  for (const key of ["oneOf", "anyOf"]) {
2488
2728
  const branches = s[key];
2489
2729
  if (!Array.isArray(branches)) continue;
2490
- const tag = branches.length ? tagOf(run.root, branches) : null;
2730
+ const tag = branches.length ? tagOf(run2.root, branches) : null;
2491
2731
  if (tag) {
2492
- if (!isObj(value)) return push(run, path, `must be an object; got ${describe(value)}`, context);
2493
- const pick = pickBranch(run.root, branches, tag, value);
2494
- if ("missing" in pick) return push(run, [...path, tag], `is required: one of ${listOf(branches.map((b) => deref(run.root, b).properties[tag]).map((p) => p.const))}`, context);
2495
- if ("unknown" in pick) return push(run, [...path, tag], unknownTag(tag, pick.unknown, pick.known), context);
2496
- check(run, pick.branch, value, path, typeof value[tag] === "string" ? value[tag] : context);
2732
+ if (!isObj(value)) return push(run2, path, `must be an object; got ${describe(value)}`, context);
2733
+ const pick2 = pickBranch(run2.root, branches, tag, value);
2734
+ if ("missing" in pick2) return push(run2, [...path, tag], `is required: one of ${listOf(branches.map((b) => deref(run2.root, b).properties[tag]).map((p) => p.const))}`, context);
2735
+ if ("unknown" in pick2) return push(run2, [...path, tag], unknownTag(tag, pick2.unknown, pick2.known), context);
2736
+ check(run2, pick2.branch, value, path, typeof value[tag] === "string" ? value[tag] : context);
2497
2737
  continue;
2498
2738
  }
2499
- const results = branches.map((b) => trial(run, b, value, path, context));
2739
+ const results = branches.map((b) => trial(run2, b, value, path, context));
2500
2740
  const valid = results.filter((r) => !r.length).length;
2501
2741
  if (valid === 0) {
2502
2742
  const best = results.reduce((a, b) => b.length < a.length ? b : a, results[0] ?? []);
2503
- if (best.length) run.issues.push(...best);
2504
- else push(run, path, "matches none of the allowed forms", context);
2505
- } else if (key === "oneOf" && valid > 1) push(run, path, "matches more than one of the allowed forms", context);
2743
+ if (best.length) run2.issues.push(...best);
2744
+ else push(run2, path, "matches none of the allowed forms", context);
2745
+ } else if (key === "oneOf" && valid > 1) push(run2, path, "matches more than one of the allowed forms", context);
2506
2746
  }
2507
- if (s.not !== void 0 && !trial(run, s.not, value, path).length) push(run, path, typeof s.description === "string" ? `is not allowed here: ${s.description}` : "is not allowed here", context);
2508
- if (s.const !== void 0 && !equal(value, s.const)) return push(run, path, `must be ${q(s.const)}; got ${describe(value)}`, context);
2747
+ if (s.not !== void 0 && !trial(run2, s.not, value, path).length) push(run2, path, typeof s.description === "string" ? `is not allowed here: ${s.description}` : "is not allowed here", context);
2748
+ if (s.const !== void 0 && !equal(value, s.const)) return push(run2, path, `must be ${q(s.const)}; got ${describe(value)}`, context);
2509
2749
  if (Array.isArray(s.enum) && !s.enum.some((e) => equal(e, value))) {
2510
2750
  const hint = typeof value === "string" ? didYouMean(value, s.enum.filter((e) => typeof e === "string")) : "";
2511
- return push(run, path, `must be one of ${listOf(s.enum, 20)}; got ${describe(value)}${hint}`, context);
2751
+ return push(run2, path, `must be one of ${listOf(s.enum, 20)}; got ${describe(value)}${hint}`, context);
2512
2752
  }
2513
2753
  const types2 = typeof s.type === "string" ? [s.type] : Array.isArray(s.type) ? s.type : null;
2514
2754
  if (types2 && !types2.some((t2) => typeOk(t2, value))) {
2515
- return push(run, path, `must be ${types2.map((t2) => TYPE_NOUN[t2] ?? t2).join(" or ")}; got ${describe(value)}`, context);
2755
+ return push(run2, path, `must be ${types2.map((t2) => TYPE_NOUN[t2] ?? t2).join(" or ")}; got ${describe(value)}`, context);
2516
2756
  }
2517
2757
  if (typeof value === "number") {
2518
- if (typeof s.minimum === "number" && value < s.minimum) push(run, path, `must be at least ${s.minimum}; got ${value}`, context);
2519
- if (typeof s.maximum === "number" && value > s.maximum) push(run, path, `must be at most ${s.maximum}; got ${value}`, context);
2758
+ if (typeof s.minimum === "number" && value < s.minimum) push(run2, path, `must be at least ${s.minimum}; got ${value}`, context);
2759
+ if (typeof s.maximum === "number" && value > s.maximum) push(run2, path, `must be at most ${s.maximum}; got ${value}`, context);
2520
2760
  }
2521
2761
  if (typeof value === "string") {
2522
- if (typeof s.minLength === "number" && value.length < s.minLength) push(run, path, s.minLength === 1 ? "must not be empty" : `must be at least ${s.minLength} characters long`, context);
2523
- if (typeof s.maxLength === "number" && value.length > s.maxLength) push(run, path, `must be at most ${s.maxLength} characters long; got ${value.length}`, context);
2762
+ if (typeof s.minLength === "number" && value.length < s.minLength) push(run2, path, s.minLength === 1 ? "must not be empty" : `must be at least ${s.minLength} characters long`, context);
2763
+ if (typeof s.maxLength === "number" && value.length > s.maxLength) push(run2, path, `must be at most ${s.maxLength} characters long; got ${value.length}`, context);
2524
2764
  if (typeof s.pattern === "string" && !new RegExp(s.pattern, "u").test(value)) {
2525
2765
  const hint = typeof s["x-pattern-hint"] === "string" ? s["x-pattern-hint"] : `text matching /${s.pattern}/`;
2526
- push(run, path, `must be ${hint}; got ${describe(value)}`, context);
2766
+ push(run2, path, `must be ${hint}; got ${describe(value)}`, context);
2527
2767
  }
2528
- if (s.format === "date" && !validDate(value)) push(run, path, `must be a date as YYYY-MM-DD; got ${describe(value)}`, context);
2529
- if (s.format === "date-time" && !(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/.test(value) && validDate(value.slice(0, 10)))) push(run, path, `must be a date and time as YYYY-MM-DDTHH:MM:SSZ; got ${describe(value)}`, context);
2768
+ if (s.format === "date" && !validDate(value)) push(run2, path, `must be a date as YYYY-MM-DD; got ${describe(value)}`, context);
2769
+ if (s.format === "date-time" && !(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/.test(value) && validDate(value.slice(0, 10)))) push(run2, path, `must be a date and time as YYYY-MM-DDTHH:MM:SSZ; got ${describe(value)}`, context);
2530
2770
  }
2531
2771
  if (Array.isArray(value)) {
2532
- if (typeof s.minItems === "number" && value.length < s.minItems) push(run, path, `must have at least ${s.minItems} item${s.minItems === 1 ? "" : "s"}; has ${value.length}`, context);
2533
- if (typeof s.maxItems === "number" && value.length > s.maxItems) push(run, path, `must have at most ${s.maxItems} items; has ${value.length}`, context);
2772
+ if (typeof s.minItems === "number" && value.length < s.minItems) push(run2, path, `must have at least ${s.minItems} item${s.minItems === 1 ? "" : "s"}; has ${value.length}`, context);
2773
+ if (typeof s.maxItems === "number" && value.length > s.maxItems) push(run2, path, `must have at most ${s.maxItems} items; has ${value.length}`, context);
2534
2774
  if (s.uniqueItems === true) {
2535
2775
  const seen = /* @__PURE__ */ new Set();
2536
2776
  value.forEach((v, i) => {
2537
2777
  const k = JSON.stringify(v);
2538
- if (seen.has(k)) push(run, [...path, i], `repeats ${describe(v)}; items must be unique`, context);
2778
+ if (seen.has(k)) push(run2, [...path, i], `repeats ${describe(v)}; items must be unique`, context);
2539
2779
  seen.add(k);
2540
2780
  });
2541
2781
  }
2542
- if (s.items !== void 0) value.forEach((v, i) => check(run, s.items, v, [...path, i], context));
2782
+ if (s.items !== void 0) value.forEach((v, i) => check(run2, s.items, v, [...path, i], context));
2543
2783
  }
2544
2784
  if (isObj(value)) {
2545
2785
  const props = isObj(s.properties) ? s.properties : {};
2546
2786
  if (Array.isArray(s.required)) {
2547
- for (const k of s.required) if (value[k] === void 0) push(run, [...path, k], "is required but missing", context);
2787
+ for (const k of s.required) if (value[k] === void 0) push(run2, [...path, k], "is required but missing", context);
2548
2788
  }
2549
2789
  const names = isObj(s.propertyNames) ? s.propertyNames : null;
2550
2790
  for (const [k, v] of Object.entries(value)) {
2551
2791
  if (names && typeof names.pattern === "string" && !new RegExp(names.pattern, "u").test(k)) {
2552
- push(run, [...path, k], `is not a valid name here: must be ${typeof names["x-pattern-hint"] === "string" ? names["x-pattern-hint"] : `text matching /${names.pattern}/`}`, context);
2792
+ push(run2, [...path, k], `is not a valid name here: must be ${typeof names["x-pattern-hint"] === "string" ? names["x-pattern-hint"] : `text matching /${names.pattern}/`}`, context);
2553
2793
  continue;
2554
2794
  }
2555
- if (props[k] !== void 0) check(run, props[k], v, [...path, k], context);
2795
+ if (props[k] !== void 0) check(run2, props[k], v, [...path, k], context);
2556
2796
  else if (s.additionalProperties === false) {
2557
2797
  const known = Object.keys(props);
2558
- push(run, [...path, k], `is not a known property here${didYouMean(k, known)}. Allowed: ${known.join(", ") || "none"}`, context);
2559
- } else if (s.additionalProperties !== void 0 && s.additionalProperties !== true) check(run, s.additionalProperties, v, [...path, k], context);
2798
+ push(run2, [...path, k], `is not a known property here${didYouMean(k, known)}. Allowed: ${known.join(", ") || "none"}`, context);
2799
+ } else if (s.additionalProperties !== void 0 && s.additionalProperties !== true) check(run2, s.additionalProperties, v, [...path, k], context);
2560
2800
  }
2561
2801
  }
2562
2802
  }
2563
2803
  function validateJson(schema2, value) {
2564
- const run = { root: schema2, issues: [] };
2565
- check(run, schema2, value, []);
2804
+ const run2 = { root: schema2, issues: [] };
2805
+ check(run2, schema2, value, []);
2566
2806
  const seen = /* @__PURE__ */ new Set();
2567
- return run.issues.filter((i) => {
2807
+ return run2.issues.filter((i) => {
2568
2808
  const k = `${i.pointer}\0${i.message}`;
2569
2809
  if (seen.has(k)) return false;
2570
2810
  seen.add(k);
@@ -2583,8 +2823,8 @@ function walkWithSchema(root, value, visit) {
2583
2823
  if (!Array.isArray(branches) || !branches.length) continue;
2584
2824
  const tag = tagOf(root, branches);
2585
2825
  if (!tag) continue;
2586
- const pick = pickBranch(root, branches, tag, v);
2587
- if ("branch" in pick) go(pick.branch, v, path, parent, typeof v[tag] === "string" ? v[tag] : context);
2826
+ const pick2 = pickBranch(root, branches, tag, v);
2827
+ if ("branch" in pick2) go(pick2.branch, v, path, parent, typeof v[tag] === "string" ? v[tag] : context);
2588
2828
  }
2589
2829
  if (Array.isArray(v) && s.items !== void 0) v.forEach((x, i) => go(s.items, x, [...path, i], { value: v, schema: s, path }, context));
2590
2830
  if (isObj(v)) {
@@ -2654,6 +2894,9 @@ function checkConfig(raw2, plugins) {
2654
2894
  s.pages.forEach((p, pi) => {
2655
2895
  const pp = [...sp, "pages", pi];
2656
2896
  if (!isObj2(p) || !Array.isArray(p.tiles)) return;
2897
+ p.showWhen?.forEach((r, ri) => {
2898
+ if (r.source && !sources.has(r.source)) warnings.push(issue([...pp, "showWhen", ri, "source"], `no installed plugin provides the source ${JSON.stringify(r.source)}, so this rule never holds${near(r.source, [...sources.keys()])}`));
2899
+ });
2657
2900
  repeated(p.tiles, [...pp, "tiles"], "tile", errors);
2658
2901
  const grid = validGrid(p.grid) ? p.grid : null;
2659
2902
  p.tiles.forEach((t2, ti) => {
@@ -2693,6 +2936,11 @@ function checkConfig(raw2, plugins) {
2693
2936
  }
2694
2937
  }
2695
2938
  if (def.options) unknownOptions(def.options, w.options, [...wp, "options"], warnings, w.type);
2939
+ if (typeof w.profile === "string") {
2940
+ const own2 = (def.sources ?? []).filter((x) => acceptsProfiles(sources.get(x)));
2941
+ if (!own2.length) warnings.push(issue([...wp, "profile"], `${w.type} reads no source with profiles, so it is ignored`, w.type));
2942
+ else if (!own2.some((x) => Object.hasOwn(profilesOf(cfg, x), w.profile))) warnings.push(issue([...wp, "profile"], `no profile ${JSON.stringify(w.profile)} in sourceProfiles[${JSON.stringify(own2[0])}], so it reads the default one${near(w.profile, own2.flatMap((x) => Object.keys(profilesOf(cfg, x))))}`, w.type));
2943
+ }
2696
2944
  });
2697
2945
  });
2698
2946
  });
@@ -2711,6 +2959,19 @@ function checkConfig(raw2, plugins) {
2711
2959
  else if (!def && new RegExp(TYPE_PATTERN).test(type)) warnings.push(issue(["sources", type], `no installed plugin provides this source, so it is ignored${near(type, [...sources.keys()])}`));
2712
2960
  }
2713
2961
  }
2962
+ for (const [type, list2] of Object.entries(cfg.sourceProfiles ?? {})) {
2963
+ const def = sources.get(type);
2964
+ if (!def) {
2965
+ if (new RegExp(TYPE_PATTERN).test(type)) warnings.push(issue(["sourceProfiles", type], `no installed plugin provides this source, so its profiles are ignored${near(type, [...sources.keys()])}`));
2966
+ continue;
2967
+ }
2968
+ if (!acceptsProfiles(def)) {
2969
+ warnings.push(issue(["sourceProfiles", type], "this source has no profiles (one configuration only), so these are ignored"));
2970
+ continue;
2971
+ }
2972
+ const field = sourceOptionsField(def);
2973
+ for (const [id, p] of Object.entries(list2)) if (field) unknownOptions(field, p.options, ["sourceProfiles", type, id, "options"], warnings, type);
2974
+ }
2714
2975
  if (Array.isArray(cfg.plugins.disabled)) {
2715
2976
  cfg.plugins.disabled.forEach((id, i) => {
2716
2977
  if (typeof id === "string" && !pluginIds.includes(id)) warnings.push(issue(["plugins", "disabled", i], `no installed plugin is called ${JSON.stringify(id)}${near(id, pluginIds)}`));
@@ -2805,6 +3066,16 @@ function diffConfigs(before, after) {
2805
3066
  else if (b && !a) out.push({ depth: 0, op: "-", kind: "source", text: `source ${k}` });
2806
3067
  else if (a && b && !same(a, b)) out.push({ depth: 0, op: "~", kind: "source", text: `source ${k}: ${changedKeys(b, a).join(", ")} changed` });
2807
3068
  }
3069
+ const profiles = (c) => Object.entries(c.sourceProfiles ?? {}).flatMap(([type, list2]) => Object.entries(list2).map(([id, p]) => [`${type}#${id}`, p]));
3070
+ const pb = new Map(profiles(before));
3071
+ const pa = new Map(profiles(after));
3072
+ for (const k of [.../* @__PURE__ */ new Set([...pb.keys(), ...pa.keys()])].sort()) {
3073
+ const b = pb.get(k);
3074
+ const a = pa.get(k);
3075
+ if (!b && a) out.push({ depth: 0, op: "+", kind: "source", text: `source profile ${k} ${q2(a.name)}` });
3076
+ else if (b && !a) out.push({ depth: 0, op: "-", kind: "source", text: `source profile ${k} ${q2(b.name)}` });
3077
+ else if (a && b && !same(a, b)) out.push({ depth: 0, op: "~", kind: "source", text: `source profile ${k}: ${[...a.name !== b.name ? [`renamed from ${q2(b.name)} to ${q2(a.name)}`] : [], ...same(a.options, b.options) ? [] : [`${changedKeys(b.options, a.options).join(", ")} changed`]].join("; ")}` });
3078
+ }
2808
3079
  const m = match(before.screens, after.screens, (s) => s.name);
2809
3080
  for (const s of m.removed) out.push({ depth: 0, op: "-", kind: "screen", text: `screen ${q2(s.name)} ${s.width}\xD7${s.height} (${plural2(s.pages.length, "page")})` });
2810
3081
  for (const s of m.added) {
@@ -2947,9 +3218,9 @@ function hostMoved(schema2, merged2, mergedPath, current, currentPath, holder) {
2947
3218
  const a = getAt(merged2, mergedPath.slice(0, -1));
2948
3219
  const b = getAt(current, currentPath.slice(0, -1));
2949
3220
  if (!isObj3(a) || !isObj3(b)) return null;
2950
- const own = mergedPath[mergedPath.length - 1];
3221
+ const own2 = mergedPath[mergedPath.length - 1];
2951
3222
  for (const [k, sub] of Object.entries(holder.properties)) {
2952
- if (k === own) continue;
3223
+ if (k === own2) continue;
2953
3224
  const s = deref(schema2, sub);
2954
3225
  if (typeof s !== "object" || !(risksOf(s).includes("network") || HOSTISH.test(k) && s.type === "string")) continue;
2955
3226
  const was = String(b[k] ?? "").trim();
@@ -3067,6 +3338,19 @@ function planImport(incoming, current, plugins, schema2 = configSchema(plugins))
3067
3338
  }
3068
3339
  }
3069
3340
  raw2.sources = sources;
3341
+ if (current.sourceProfiles) {
3342
+ const profiles = isObj3(raw2.sourceProfiles) ? { ...raw2.sourceProfiles } : {};
3343
+ for (const [type, list2] of Object.entries(current.sourceProfiles)) {
3344
+ const into = isObj3(profiles[type]) ? { ...profiles[type] } : {};
3345
+ for (const [id, p] of Object.entries(list2)) {
3346
+ if (into[id] !== void 0) continue;
3347
+ into[id] = clone2(p);
3348
+ carried.push(`sourceProfiles[${JSON.stringify(type)}][${JSON.stringify(id)}]`);
3349
+ }
3350
+ profiles[type] = into;
3351
+ }
3352
+ raw2.sourceProfiles = profiles;
3353
+ }
3070
3354
  const config2 = normalize(raw2);
3071
3355
  return { report, config: config2, carried, diff: diffConfigs(current, config2), risks: listRisks(config2, schema2, current), secrets };
3072
3356
  }
@@ -3117,10 +3401,10 @@ function marketOf(locale) {
3117
3401
  }
3118
3402
  function starterPage(has, o) {
3119
3403
  const { width, height } = o;
3120
- const L = (t2) => localize(t2, o.locale ?? "en");
3404
+ const L3 = (t2) => localize(t2, o.locale ?? "en");
3121
3405
  const { offered } = marketOf(o.locale);
3122
3406
  const ok = (t2) => offered(t2) && has(t2) && (o.weather !== false || !t2.startsWith("weather/"));
3123
- const page = newPage(o.name ?? L(STARTER_NAMES.page), width, height);
3407
+ const page = newPage(o.name ?? L3(STARTER_NAMES.page), width, height);
3124
3408
  page.grid = { cols: 24, rows: 6, gap: 10, padding: 10 };
3125
3409
  page.gravity = "left";
3126
3410
  const tiles = [];
@@ -3140,9 +3424,9 @@ function starterPage(has, o) {
3140
3424
  add2({ x: 11, y: 4, w: 5, h: 2 }, ["weather/forecast", "mirror/compliments"]);
3141
3425
  add2({ x: 16, y: 0, w: 8, h: 6 }, ["vitals/vitals", "system/health", "usage/rail", "mirror/countdown"].filter(ok).slice(0, 3));
3142
3426
  if (!tiles.length) {
3143
- add2({ x: 0, y: 0, w: 24, h: 6 }, ["core/text"], L({ en: "Welcome", es: "Bienvenida", de: "Willkommen", "zh-Hant": "\u6B61\u8FCE", "zh-Hans": "\u6B22\u8FCE" }));
3427
+ add2({ x: 0, y: 0, w: 24, h: 6 }, ["core/text"], L3({ en: "Welcome", es: "Bienvenida", de: "Willkommen", "zh-Hant": "\u6B61\u8FCE", "zh-Hans": "\u6B22\u8FCE" }));
3144
3428
  const welcome = tiles[0]?.widgets[0];
3145
- if (welcome) welcome.options = { text: L({ en: "Hi there.\nDrag widgets from the library to build your panel.", es: "Hola.\nArrastra widgets desde la biblioteca para montar tu panel.", de: "Hallo!\nZieh Widgets aus der Bibliothek, um dein Panel zu gestalten.", "zh-Hant": "\u4F60\u597D\u3002\n\u5F9E\u5C0F\u5DE5\u5177\u5EAB\u62D6\u66F3\u5C0F\u5DE5\u5177\uFF0C\n\u6253\u9020\u4F60\u7684\u9762\u677F\u3002", "zh-Hans": "\u4F60\u597D\u3002\n\u4ECE\u7EC4\u4EF6\u5E93\u62D6\u52A8\u5C0F\u7EC4\u4EF6\uFF0C\n\u5E03\u7F6E\u4F60\u7684\u526F\u5C4F\u3002" }), maxSize: 54 };
3429
+ if (welcome) welcome.options = { text: L3({ en: "Hi there.\nDrag widgets from the library to build your panel.", es: "Hola.\nArrastra widgets desde la biblioteca para montar tu panel.", de: "Hallo!\nZieh Widgets aus der Bibliothek, um dein Panel zu gestalten.", "zh-Hant": "\u4F60\u597D\u3002\n\u5F9E\u5C0F\u5DE5\u5177\u5EAB\u62D6\u66F3\u5C0F\u5DE5\u5177\uFF0C\n\u6253\u9020\u4F60\u7684\u9762\u677F\u3002", "zh-Hans": "\u4F60\u597D\u3002\n\u4ECE\u7EC4\u4EF6\u5E93\u62D6\u52A8\u5C0F\u7EC4\u4EF6\uFF0C\n\u5E03\u7F6E\u4F60\u7684\u526F\u5C4F\u3002" }), maxSize: 54 };
3146
3430
  }
3147
3431
  page.tiles = tiles;
3148
3432
  if (height > width) transposePage(page, width, height);
@@ -3173,11 +3457,11 @@ function offersSetup(c) {
3173
3457
  function pickInStack(entries, now, rotateMs) {
3174
3458
  const urgent = entries.find((e) => e.visible && e.urgent);
3175
3459
  if (urgent) return urgent.id;
3176
- const shown = entries.filter((e) => e.visible);
3177
- if (!shown.length) return null;
3178
- if (shown.length === 1 || rotateMs <= 0) return shown[0].id;
3460
+ const shown2 = entries.filter((e) => e.visible);
3461
+ if (!shown2.length) return null;
3462
+ if (shown2.length === 1 || rotateMs <= 0) return shown2[0].id;
3179
3463
  const turn = Math.floor(now / Math.max(1e3, rotateMs));
3180
- return shown[turn % shown.length].id;
3464
+ return shown2[turn % shown2.length].id;
3181
3465
  }
3182
3466
  function nextTurnAt(now, rotateMs) {
3183
3467
  const p = Math.max(1e3, rotateMs);
@@ -3318,9 +3602,9 @@ function baseContext(cfg, plugin, log, now) {
3318
3602
  const dir = paths.data(plugin);
3319
3603
  const cache = paths.cache(plugin);
3320
3604
  let cacheMade = false;
3321
- const base3 = createBaseContext({ now, locale: resolveLocale(cfg), timeFormat: cfg.timeFormat, workday: cfg.workday, ...cfg.location ? { location: cfg.location } : {}, log: (msg2) => log(plugin, msg2) });
3605
+ const base4 = createBaseContext({ now, locale: resolveLocale(cfg), timeFormat: cfg.timeFormat, workday: cfg.workday, ...cfg.location ? { location: cfg.location } : {}, log: (msg2) => log(plugin, msg2) });
3322
3606
  return {
3323
- ...base3,
3607
+ ...base4,
3324
3608
  get cacheDir() {
3325
3609
  if (!cache) return this.dataDir;
3326
3610
  if (!cacheMade) {
@@ -3372,14 +3656,14 @@ var OTHER_SCRIPTS = [
3372
3656
  { script: "Armn", probe: "\u0531", families: ["Noto Sans Armenian", "Sylfaen", "DejaVu Sans"] },
3373
3657
  { script: "Ethi", probe: "\u12A0", families: ["Noto Sans Ethiopic", "Ebrima", "Kefa"] }
3374
3658
  ];
3375
- function scriptOrder(own) {
3659
+ function scriptOrder(own2) {
3376
3660
  const rest = ["Hans", "Hant", "Jpan", "Kore"];
3377
- if (!own) return rest;
3378
- const first = own === "Hant-HK" ? ["Hant-HK", "Hant"] : [own];
3661
+ if (!own2) return rest;
3662
+ const first = own2 === "Hant-HK" ? ["Hant-HK", "Hant"] : [own2];
3379
3663
  return [...first, ...rest.filter((s) => !first.includes(s))];
3380
3664
  }
3381
- function cjkFamiliesFor(locale, available2, own = []) {
3382
- const out = [...own];
3665
+ function cjkFamiliesFor(locale, available2, own2 = []) {
3666
+ const out = [...own2];
3383
3667
  for (const s of scriptOrder(hanScript(locale))) {
3384
3668
  const found = CJK_FAMILIES[s].find((f) => !out.includes(f) && available2(f));
3385
3669
  if (found) out.push(found);
@@ -3600,7 +3884,7 @@ function resolve(input, inst) {
3600
3884
  if (!def) return null;
3601
3885
  let options2 = def.options ? validate(def.options, inst.options).value : {};
3602
3886
  let data = input.dataOf(inst);
3603
- let sources = input.sourcesOf(def.sources);
3887
+ let sources = input.sourcesOf(def.sources, inst.profile);
3604
3888
  if (input.demo && def.demo) {
3605
3889
  const needData = data === void 0;
3606
3890
  const needSources = (def.sources ?? []).some((s) => sources[s] === void 0);
@@ -3693,8 +3977,8 @@ function paintTile(g, input, tile, rect2, out, nextAt, idles, animatable) {
3693
3977
  }
3694
3978
  const state = stateCtx(r, now, working, input.cfg);
3695
3979
  idles.push(safe(() => r.def.idle?.(state) ?? false, false));
3696
- const step = redrawStep(r.def, state);
3697
- if (step) nextAt.v = Math.min(nextAt.v, (Math.floor(now / step) + 1) * step);
3980
+ const step2 = redrawStep(r.def, state);
3981
+ if (step2) nextAt.v = Math.min(nextAt.v, (Math.floor(now / step2) + 1) * step2);
3698
3982
  const animation = r.def.animation;
3699
3983
  if (animation && !input.preview) {
3700
3984
  animatable.push({
@@ -3718,7 +4002,7 @@ function paintTile(g, input, tile, rect2, out, nextAt, idles, animatable) {
3718
4002
  return;
3719
4003
  }
3720
4004
  const cfg = input.cfg;
3721
- const key = JSON.stringify([r.inst.id, r.inst.type, r.inst.options, r.inst.title ?? "", zoomOf(r.inst), input.screen.textScale ?? 1, legibleCjkPx(input.screen), chrome, rect2, theme.id, step ? Math.floor(now / step) : 0, cfg.locale, cfg.timeFormat, cfg.workday, cfg.location ?? null, working]);
4005
+ const key = JSON.stringify([r.inst.id, r.inst.type, r.inst.options, r.inst.title ?? "", zoomOf(r.inst), input.screen.textScale ?? 1, legibleCjkPx(input.screen), chrome, rect2, theme.id, step2 ? Math.floor(now / step2) : 0, cfg.locale, cfg.timeFormat, cfg.workday, cfg.location ?? null, working]);
3722
4006
  const refs = [r.data, ...(r.def.sources ?? []).map((s) => r.sources[s])];
3723
4007
  const hit = input.cache.get(tile.id);
3724
4008
  if (hit && hit.key === key && hit.refs.length === refs.length && hit.refs.every((x, i) => x === refs[i])) {
@@ -4131,6 +4415,202 @@ var AlertBoard = class {
4131
4415
  }
4132
4416
  };
4133
4417
 
4418
+ // packages/core/src/context.ts
4419
+ init_workday();
4420
+ function valueAt(data, path) {
4421
+ const keys = (path ?? "").replace(/\[(\d+|"[^"]*"|'[^']*')\]/g, (_, k) => `.${k.replace(/^["']|["']$/g, "")}`).split(".").filter((k) => k !== "");
4422
+ let v = data;
4423
+ for (const k of keys) {
4424
+ if (v === null || v === void 0 || typeof v !== "object") return void 0;
4425
+ v = v[k];
4426
+ }
4427
+ return v;
4428
+ }
4429
+ var asNumber = (v) => typeof v === "number" ? v : typeof v === "string" && v.trim() !== "" ? Number(v) : typeof v === "boolean" ? Number(v) : NaN;
4430
+ function compareValue(v, op, value) {
4431
+ if (v === void 0) return false;
4432
+ const how = op ?? (value === void 0 ? "truthy" : "eq");
4433
+ const truthy = Array.isArray(v) ? v.length > 0 : !!v && v !== "false" && v !== "0";
4434
+ switch (how) {
4435
+ case "truthy":
4436
+ return truthy;
4437
+ case "falsy":
4438
+ return !truthy;
4439
+ case "eq":
4440
+ case "ne": {
4441
+ const a = asNumber(v), b = asNumber(value);
4442
+ const same3 = typeof value === "boolean" ? truthy === value : Number.isFinite(a) && Number.isFinite(b) ? a === b : String(v ?? "").toLowerCase() === String(value ?? "").toLowerCase();
4443
+ return how === "eq" ? same3 : !same3;
4444
+ }
4445
+ case "gt":
4446
+ case "gte":
4447
+ case "lt":
4448
+ case "lte": {
4449
+ const a = asNumber(v), b = asNumber(value);
4450
+ if (!Number.isFinite(a) || !Number.isFinite(b)) return false;
4451
+ return how === "gt" ? a > b : how === "gte" ? a >= b : how === "lt" ? a < b : a <= b;
4452
+ }
4453
+ case "contains": {
4454
+ const want = String(value ?? "").toLowerCase();
4455
+ if (Array.isArray(v)) return v.some((x) => String(x).toLowerCase() === want);
4456
+ return typeof v === "string" && v.toLowerCase().includes(want);
4457
+ }
4458
+ }
4459
+ return false;
4460
+ }
4461
+ function shown(v) {
4462
+ if (typeof v === "string") return v.length > 40 ? `${v.slice(0, 39)}\u2026` : v;
4463
+ if (typeof v === "number" || typeof v === "boolean" || v === null) return String(v);
4464
+ if (Array.isArray(v)) return `[${v.length}]`;
4465
+ return "{\u2026}";
4466
+ }
4467
+ var globCache = /* @__PURE__ */ new Map();
4468
+ function globs(pattern) {
4469
+ let out = globCache.get(pattern);
4470
+ if (!out) {
4471
+ out = pattern.split(",").map((p) => p.trim()).filter(Boolean).map((p) => new RegExp(`^${p.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".")}$`, "i"));
4472
+ if (globCache.size > 200) globCache.clear();
4473
+ globCache.set(pattern, out);
4474
+ }
4475
+ return out;
4476
+ }
4477
+ function matchApp(pattern, names) {
4478
+ const res = globs(pattern);
4479
+ if (!res.length) return null;
4480
+ for (const n of names) if (res.some((r) => r.test(n))) return n;
4481
+ return null;
4482
+ }
4483
+ function inTimeWindow(w, now) {
4484
+ const a = minutesOf(w.start), b = minutesOf(w.end);
4485
+ if (a === b) return false;
4486
+ const d = new Date(now);
4487
+ const t2 = d.getHours() * 60 + d.getMinutes();
4488
+ const today = d.getDay();
4489
+ const days = w.days?.length ? w.days : null;
4490
+ if (a < b) return t2 >= a && t2 < b && (!days || days.includes(today));
4491
+ if (t2 >= a) return !days || days.includes(today);
4492
+ if (t2 < b) return !days || days.includes((today + 6) % 7);
4493
+ return false;
4494
+ }
4495
+ function ruleHasConditions(r) {
4496
+ return !!(r.app?.trim() || r.source || r.time || r.urgent);
4497
+ }
4498
+ function evalRule(rule2, page, env) {
4499
+ if (!ruleHasConditions(rule2)) return null;
4500
+ const why2 = rule2.label ? { label: rule2.label } : {};
4501
+ if (rule2.app?.trim()) {
4502
+ const hit = env.apps ? matchApp(rule2.app, env.apps) : null;
4503
+ if (!hit) return null;
4504
+ why2.app = hit;
4505
+ }
4506
+ if (rule2.source) {
4507
+ const v = valueAt(env.source(rule2.source), rule2.path);
4508
+ if (!compareValue(v, rule2.op, rule2.value)) return null;
4509
+ why2.source = rule2.source;
4510
+ if (rule2.path) why2.path = rule2.path;
4511
+ why2.value = shown(v);
4512
+ }
4513
+ if (rule2.time) {
4514
+ if (!inTimeWindow(rule2.time, env.now)) return null;
4515
+ why2.time = `${rule2.time.start}\u2013${rule2.time.end}`;
4516
+ }
4517
+ if (rule2.urgent) {
4518
+ const u = env.urgent(page);
4519
+ if (!u) return null;
4520
+ why2.urgent = u;
4521
+ }
4522
+ return why2;
4523
+ }
4524
+ function matchingPages(screen, env, working) {
4525
+ const out = [];
4526
+ for (const page of screen.pages) {
4527
+ if (page.enabled === false || !page.showWhen?.length || !whenMatches(page.when, working)) continue;
4528
+ let best = null;
4529
+ for (const rule2 of page.showWhen) {
4530
+ const priority = rule2.priority ?? 0;
4531
+ if (best && priority <= best.priority) continue;
4532
+ const reason = evalRule(rule2, page, env);
4533
+ if (reason) best = { page, priority, reason };
4534
+ }
4535
+ if (best) out.push(best);
4536
+ }
4537
+ return out;
4538
+ }
4539
+ function inRotation(p) {
4540
+ return !p.showWhen?.length || p.inRotation === true;
4541
+ }
4542
+ function choosePage(screen, now, working, pinned, context) {
4543
+ const eligible = screen.pages.filter((p) => whenMatches(p.when, working));
4544
+ const on = (id) => id ? eligible.find((p) => p.id === id && p.enabled !== false) : void 0;
4545
+ const fixed = on(pinned) ?? on(context);
4546
+ if (fixed) return fixed;
4547
+ const rotation = eligible.filter(inRotation);
4548
+ return pickPage(rotation.some((p) => p.enabled !== false) ? rotation : eligible, now);
4549
+ }
4550
+ var ContextEngine = class {
4551
+ held = /* @__PURE__ */ new Map();
4552
+ step(screen, matches, now) {
4553
+ const minMs = Math.max(0, screen.context?.minMs ?? CONTEXT_TIMING.minMs);
4554
+ const holdMs = Math.max(0, screen.context?.holdMs ?? CONTEXT_TIMING.holdMs);
4555
+ let cur = this.held.get(screen.id) ?? null;
4556
+ if (cur) {
4557
+ const ids2 = new Set(screen.pages.filter((p) => p.enabled !== false).map((p) => p.id));
4558
+ cur.pages = cur.pages.filter((m) => ids2.has(m.page.id));
4559
+ if (!cur.pages.length) cur = null;
4560
+ }
4561
+ const top = matches.length ? Math.max(...matches.map((m) => m.priority)) : null;
4562
+ const best = top === null ? [] : matches.filter((m) => m.priority === top);
4563
+ const mayGo = (c) => now - c.heldAt >= holdMs && now - c.since >= minMs;
4564
+ if (top !== null && (!cur || top > cur.priority)) cur = { priority: top, pages: best, since: now, heldAt: now };
4565
+ else if (top !== null && cur && top === cur.priority) {
4566
+ cur.pages = best;
4567
+ cur.heldAt = now;
4568
+ } else if (cur && mayGo(cur)) cur = top === null ? null : { priority: top, pages: best, since: now, heldAt: now };
4569
+ if (!cur) {
4570
+ this.held.delete(screen.id);
4571
+ return null;
4572
+ }
4573
+ this.held.set(screen.id, cur);
4574
+ const page = cur.pages.length === 1 ? cur.pages[0] : cur.pages.find((m) => m.page.id === pickPage(cur.pages.map((x) => x.page), now)?.id) ?? cur.pages[0];
4575
+ return { page: page.page.id, reason: page.reason, priority: cur.priority, since: cur.since, leaving: cur.heldAt < now };
4576
+ }
4577
+ /** Forgets screens that are gone. */
4578
+ retain(ids2) {
4579
+ for (const id of this.held.keys()) if (!ids2.has(id)) this.held.delete(id);
4580
+ }
4581
+ };
4582
+ function dataPaths(data, max = 60) {
4583
+ const out = [];
4584
+ const walk = (v, path, depth) => {
4585
+ if (out.length >= max) return;
4586
+ if (Array.isArray(v)) {
4587
+ if (path) out.push({ path, value: shown(v) });
4588
+ if (v.length && depth < 6) walk(v[0], `${path}[0]`, depth + 1);
4589
+ return;
4590
+ }
4591
+ if (v && typeof v === "object") {
4592
+ if (depth >= 6) return;
4593
+ for (const [k, x] of Object.entries(v)) walk(x, /^[A-Za-z_$][\w$-]*$/.test(k) ? path ? `${path}.${k}` : k : `${path}["${k}"]`, depth + 1);
4594
+ return;
4595
+ }
4596
+ out.push({ path, value: shown(v) });
4597
+ };
4598
+ walk(data, "", 0);
4599
+ return out;
4600
+ }
4601
+ function needsApps(cfg) {
4602
+ return cfg.screens.some((s) => s.enabled && s.pages.some((p) => p.enabled !== false && p.showWhen?.some((r) => !!r.app?.trim())));
4603
+ }
4604
+ function ruleSources(cfg) {
4605
+ const out = /* @__PURE__ */ new Set();
4606
+ for (const s of cfg.screens) if (s.enabled) {
4607
+ for (const p of s.pages) if (p.enabled !== false) {
4608
+ for (const r of p.showWhen ?? []) if (r.source) out.add(r.source);
4609
+ }
4610
+ }
4611
+ return out;
4612
+ }
4613
+
4134
4614
  // packages/core/src/data.ts
4135
4615
  var DEFAULT_FETCH_MS = 10 * 6e4;
4136
4616
  var RETRY_MS = 6e4;
@@ -4183,47 +4663,48 @@ var SourceHub = class {
4183
4663
  this.log = log;
4184
4664
  this.onChange = onChange;
4185
4665
  }
4186
- /** Keeps exactly the sources in `wanted` running (with current options). */
4666
+ /** Keeps exactly the source keys in `wanted` running (with current options). */
4187
4667
  retain(wanted, cfg) {
4188
- for (const [type, st] of this.states) {
4189
- if (!wanted.has(type) || this.optionsKey(cfg, type) !== st.key) {
4668
+ for (const [key, st] of this.states) {
4669
+ if (!wanted.has(key) || this.optionsKey(cfg, key) !== st.optionsKey) {
4190
4670
  st.stop?.();
4191
4671
  st.abort.abort();
4192
- this.states.delete(type);
4672
+ this.states.delete(key);
4193
4673
  }
4194
4674
  }
4195
- for (const type of wanted) {
4196
- if (this.states.has(type)) continue;
4675
+ for (const key of wanted) {
4676
+ if (this.states.has(key)) continue;
4677
+ const { type, profile } = parseSourceKey(key);
4197
4678
  const def = this.registry.source(type);
4198
4679
  if (!def) continue;
4199
4680
  const field = sourceOptionsField(def);
4200
- const options2 = field ? validate(field, cfg.sources[type] ?? {}).value : {};
4681
+ const options2 = field ? validate(field, sourceOptionsOf(cfg, key)).value : {};
4201
4682
  const { intervalMs, timeoutMs } = sourceTimes(def, options2);
4202
- const st = { type, def, key: this.optionsKey(cfg, type), options: options2, intervalMs, timeoutMs, data: void 0, nextAt: 0, inflight: false, abort: new AbortController() };
4203
- this.states.set(type, st);
4683
+ const st = { key, type, profile, def, optionsKey: this.optionsKey(cfg, key), options: options2, intervalMs, timeoutMs, data: void 0, nextAt: 0, inflight: false, abort: new AbortController() };
4684
+ this.states.set(key, st);
4204
4685
  if (def.watch) {
4205
4686
  try {
4206
4687
  st.stop = def.watch(this.ctx(cfg, st), (data) => this.set(st, data));
4207
4688
  } catch (err) {
4208
4689
  st.error = msg(err, cfg);
4209
- this.log(type, `watch failed: ${st.error}`);
4690
+ this.log(key, `watch failed: ${st.error}`);
4210
4691
  }
4211
4692
  }
4212
4693
  }
4213
4694
  }
4214
- optionsKey(cfg, type) {
4215
- return JSON.stringify(cfg.sources[type] ?? {});
4695
+ optionsKey(cfg, key) {
4696
+ return JSON.stringify(sourceOptionsOf(cfg, key));
4216
4697
  }
4217
4698
  ctx(cfg, st, signal = st.abort.signal) {
4218
4699
  const [plugin] = st.type.split("/");
4219
- return { ...baseContext(cfg, plugin, this.log, Date.now()), options: st.options, signal, intervalMs: st.intervalMs, timeoutMs: st.timeoutMs };
4700
+ return { ...baseContext(cfg, plugin, st.profile ? (_scope, m) => this.log(st.key, m) : this.log, Date.now()), options: st.options, signal, intervalMs: st.intervalMs, timeoutMs: st.timeoutMs, ...st.profile ? { profile: st.profile } : {} };
4220
4701
  }
4221
4702
  set(st, data) {
4222
4703
  st.updatedAt = Date.now();
4223
4704
  st.error = void 0;
4224
4705
  if (same2(st.data, data)) return;
4225
4706
  st.data = data;
4226
- this.onChange(st.type);
4707
+ this.onChange(st.key);
4227
4708
  }
4228
4709
  /**
4229
4710
  * Starts the reads that are due. A read gets its own signal, aborted after
@@ -4238,7 +4719,7 @@ var SourceHub = class {
4238
4719
  const d = deadline(st.abort.signal, st.timeoutMs);
4239
4720
  const fail = (err) => {
4240
4721
  st.error = d.timedOut() ? timedOutMsg(st.timeoutMs) : msg(err, cfg);
4241
- this.log(st.type, `read failed: ${st.error}`);
4722
+ this.log(st.key, `read failed: ${st.error}`);
4242
4723
  st.nextAt = Date.now() + Math.min(RETRY_MS, st.intervalMs);
4243
4724
  };
4244
4725
  d.signal.addEventListener("abort", () => d.timedOut() && fail(null), { once: true });
@@ -4261,20 +4742,29 @@ var SourceHub = class {
4261
4742
  });
4262
4743
  }
4263
4744
  }
4264
- data(type) {
4265
- return this.states.get(type)?.data;
4745
+ /** The latest data of a source key (a bare type: its default profile). */
4746
+ data(key) {
4747
+ return this.states.get(key)?.data;
4266
4748
  }
4267
4749
  /** The sources running now, with their options. */
4268
4750
  running() {
4269
- return [...this.states.values()].map((s) => ({ type: s.type, options: s.options }));
4751
+ return [...this.states.values()].map((s) => ({ key: s.key, type: s.type, profile: s.profile, options: s.options }));
4270
4752
  }
4271
- pick(types2) {
4753
+ /**
4754
+ * The data a widget (or interlude) gets in `ctx.sources`, by type: of the
4755
+ * profile `profile` where the source has it, else of the default one.
4756
+ */
4757
+ pick(types2, cfg, profile) {
4272
4758
  const out = {};
4273
- for (const t2 of types2 ?? []) out[t2] = this.data(t2);
4759
+ if (!cfg || !profile) {
4760
+ for (const t2 of types2 ?? []) out[t2] = this.data(t2);
4761
+ return out;
4762
+ }
4763
+ for (const [t2, key] of sourceKeysOf(cfg, types2, profile, (x) => this.registry.source(x))) out[t2] = this.data(key);
4274
4764
  return out;
4275
4765
  }
4276
4766
  status() {
4277
- return [...this.states.values()].map((s) => ({ type: s.type, ok: !s.error, error: s.error ?? null, updatedAt: s.updatedAt ?? null, ...s.def.read ? { intervalMs: s.intervalMs } : {} }));
4767
+ return [...this.states.values()].map((s) => ({ type: s.type, key: s.key, profile: s.profile, ok: !s.error, error: s.error ?? null, updatedAt: s.updatedAt ?? null, ...s.def.read ? { intervalMs: s.intervalMs } : {} }));
4278
4768
  }
4279
4769
  stop() {
4280
4770
  for (const st of this.states.values()) {
@@ -4285,11 +4775,11 @@ var SourceHub = class {
4285
4775
  }
4286
4776
  /** Stops the sources of a plugin whose code changed (reloaded, removed); the next `retain` starts them again with the new code. */
4287
4777
  forget(pluginId) {
4288
- for (const [type, st] of this.states) {
4289
- if (type.split("/")[0] !== pluginId) continue;
4778
+ for (const [key, st] of this.states) {
4779
+ if (st.type.split("/")[0] !== pluginId) continue;
4290
4780
  st.stop?.();
4291
4781
  st.abort.abort();
4292
- this.states.delete(type);
4782
+ this.states.delete(key);
4293
4783
  }
4294
4784
  }
4295
4785
  };
@@ -4318,12 +4808,12 @@ var FetchHost = class {
4318
4808
  for (const { inst, def } of instances) {
4319
4809
  if (!def.fetch) continue;
4320
4810
  keep.add(inst.id);
4321
- const key = JSON.stringify([inst.type, inst.options, inst.intervalMs]);
4811
+ const key = JSON.stringify([inst.type, inst.options, inst.intervalMs, inst.profile ?? null]);
4322
4812
  const old = this.states.get(inst.id);
4323
4813
  if (old && old.key === key) continue;
4324
4814
  old?.abort.abort();
4325
4815
  const options2 = def.options ? validate(def.options, inst.options).value : {};
4326
- this.states.set(inst.id, { id: inst.id, type: inst.type, def, key, options: options2, data: old?.type === inst.type ? old.data : void 0, nextAt: 0, inflight: false, intervalMs: inst.intervalMs ?? def.intervalMs ?? DEFAULT_FETCH_MS, userIntervalMs: inst.intervalMs, timeoutMs: def.timeoutMs ?? DEFAULT_TIMEOUT_MS, abort: new AbortController() });
4816
+ this.states.set(inst.id, { id: inst.id, type: inst.type, def, key, profile: inst.profile, options: options2, data: old?.type === inst.type ? old.data : void 0, nextAt: 0, inflight: false, intervalMs: inst.intervalMs ?? def.intervalMs ?? DEFAULT_FETCH_MS, userIntervalMs: inst.intervalMs, timeoutMs: def.timeoutMs ?? DEFAULT_TIMEOUT_MS, abort: new AbortController() });
4327
4817
  }
4328
4818
  for (const [id, st] of this.states) {
4329
4819
  if (!keep.has(id)) {
@@ -4338,14 +4828,14 @@ var FetchHost = class {
4338
4828
  st.inflight = true;
4339
4829
  const [plugin] = st.type.split("/");
4340
4830
  const d = deadline(st.abort.signal, st.timeoutMs);
4341
- const ctx = { ...baseContext(cfg, plugin, (_s, m) => this.log(st.type, m), now), options: st.options, canvas: CANVAS, signal: d.signal, timeoutMs: st.timeoutMs, sources: this.hub.pick(st.def.sources) };
4342
- let run;
4831
+ const ctx = { ...baseContext(cfg, plugin, (_s, m) => this.log(st.type, m), now), options: st.options, canvas: CANVAS, signal: d.signal, timeoutMs: st.timeoutMs, sources: this.hub.pick(st.def.sources, cfg, st.profile) };
4832
+ let run2;
4343
4833
  try {
4344
- run = Promise.resolve(st.def.fetch(ctx));
4834
+ run2 = Promise.resolve(st.def.fetch(ctx));
4345
4835
  } catch (err) {
4346
- run = Promise.reject(err);
4836
+ run2 = Promise.reject(err);
4347
4837
  }
4348
- run.then((data) => {
4838
+ run2.then((data) => {
4349
4839
  st.updatedAt = Date.now();
4350
4840
  st.error = void 0;
4351
4841
  if (st.userIntervalMs === void 0 && st.def.intervalOf) st.intervalMs = ownInterval(st, data);
@@ -4642,11 +5132,11 @@ var LyPanel = class _LyPanel {
4642
5132
  * caller reconnects.
4643
5133
  */
4644
5134
  send(jpeg) {
4645
- const run = async () => {
5135
+ const run2 = async () => {
4646
5136
  for (const part of frameWrites(prepareFrame(jpeg, this.pid), this.pid)) await this.transport.write(part, WRITE_TIMEOUT_MS);
4647
5137
  return isAccepted(await this.transport.read(REPLY_SIZE, ACK_TIMEOUT_MS));
4648
5138
  };
4649
- const next = this.queue.then(run, run);
5139
+ const next = this.queue.then(run2, run2);
4650
5140
  this.queue = next.catch(() => void 0);
4651
5141
  return next;
4652
5142
  }
@@ -5532,8 +6022,124 @@ function browser() {
5532
6022
  return shared;
5533
6023
  }
5534
6024
 
6025
+ // packages/core/src/remote/firmware.ts
6026
+ import { createHash as createHash2 } from "node:crypto";
6027
+
6028
+ // packages/core/src/kiosko-release.ts
6029
+ var GITHUB_REPO = "kiosko-lcd/kiosko";
6030
+ var GITHUB_API = "https://api.github.com";
6031
+ var releasePage = (version) => `https://github.com/${GITHUB_REPO}/releases/tag/v${version}`;
6032
+ var windowsInstallerName = (version) => `Kiosko-Setup-${version}-x64.exe`;
6033
+ var releaseAsset = (version, name2) => `https://github.com/${GITHUB_REPO}/releases/download/v${version}/${name2}`;
6034
+ function parseSha256File(text3, name2) {
6035
+ for (const line of text3.split(/\r?\n/)) {
6036
+ const m = /^([a-f0-9]{64})(?:\s+\*?(.+?))?\s*$/i.exec(line.trim());
6037
+ if (m && (!m[2] || m[2] === name2)) return m[1].toLowerCase();
6038
+ }
6039
+ return null;
6040
+ }
6041
+ var NOTES_MAX_CHARS = 3e3;
6042
+ var NOTES_MAX_RELEASES = 10;
6043
+ var stable = (v) => {
6044
+ const x = parseVersion(v);
6045
+ return !!x && !x[3];
6046
+ };
6047
+ var tagVersion = (tag) => {
6048
+ const v = (tag ?? "").replace(/^v/, "");
6049
+ return parseVersion(v) ? v : null;
6050
+ };
6051
+ function trimNotes(body2, max = NOTES_MAX_CHARS) {
6052
+ const clean = body2.replace(/<!--[\s\S]*?-->/g, "").replace(/\r\n?/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
6053
+ if (clean.length <= max) return { body: clean, truncated: false };
6054
+ const cut = clean.lastIndexOf("\n", max);
6055
+ return { body: clean.slice(0, cut > max / 2 ? cut : max).trimEnd(), truncated: true };
6056
+ }
6057
+ function versionsBetween(all, current, latest) {
6058
+ return all.filter((v) => stable(v) && compareVersions(v, current) > 0 && compareVersions(v, latest) <= 0).sort((a, b) => compareVersions(b, a));
6059
+ }
6060
+ async function kioskoReleaseNotes(current, latest, o) {
6061
+ const fromNpm = versionsBetween(o.npmVersions ?? [latest], current, latest).slice(0, NOTES_MAX_RELEASES).map((version) => ({ version, url: releasePage(version) }));
6062
+ let list2;
6063
+ try {
6064
+ const r = await o.http.json(`${o.api ?? GITHUB_API}/repos/${GITHUB_REPO}/releases?per_page=30`, { headers: { Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28" }, ...o.signal ? { signal: o.signal } : {} });
6065
+ if (!Array.isArray(r.data)) throw new Error("GitHub did not answer with a list of releases");
6066
+ list2 = r.data;
6067
+ } catch (err) {
6068
+ return { from: "npm", releases: fromNpm, error: err instanceof Error ? err.message : String(err) };
6069
+ }
6070
+ const byVersion = /* @__PURE__ */ new Map();
6071
+ for (const g of list2) {
6072
+ const v = tagVersion(g.tag_name);
6073
+ if (v && !g.draft && !g.prerelease && stable(v)) byVersion.set(v, g);
6074
+ }
6075
+ const versions = [.../* @__PURE__ */ new Set([...fromNpm.map((r) => r.version), ...versionsBetween([...byVersion.keys()], current, latest)])].sort((a, b) => compareVersions(b, a)).slice(0, NOTES_MAX_RELEASES);
6076
+ const releases2 = versions.map((version) => {
6077
+ const g = byVersion.get(version);
6078
+ if (!g) return { version, url: releasePage(version) };
6079
+ const notes = g.body ? trimNotes(g.body) : null;
6080
+ const url2 = g.html_url?.startsWith(`https://github.com/${GITHUB_REPO}/`) ? g.html_url : releasePage(version);
6081
+ return { version, ...g.name ? { name: g.name } : {}, ...notes?.body ? { body: notes.body, ...notes.truncated ? { truncated: true } : {} } : {}, url: url2, ...g.published_at ? { date: g.published_at } : {} };
6082
+ });
6083
+ const newest = byVersion.get(latest);
6084
+ const name2 = windowsInstallerName(latest);
6085
+ const asset = (n) => newest?.assets?.find((a) => a.name === n)?.browser_download_url;
6086
+ const exe = asset(name2);
6087
+ const sha = asset(`${name2}.sha256`);
6088
+ const ours = (u) => !!u && u.startsWith(`https://github.com/${GITHUB_REPO}/releases/download/`);
6089
+ return { from: "github", releases: releases2, ...ours(exe) && ours(sha) ? { windows: { name: name2, exe, sha256: sha } } : {} };
6090
+ }
6091
+
6092
+ // packages/core/src/remote/firmware.ts
6093
+ var SCREEN_FIRMWARE = {
6094
+ /** firmware/esp32-screen/version.txt */
6095
+ version: "0.1.4",
6096
+ /** The boards the release has images for: each one's `model`, as the screen says it (BOARD_MODEL). */
6097
+ boards: ["waveshare-esp32c6-lcd-1.47"]
6098
+ };
6099
+ function firmwareFiles(version, board) {
6100
+ return { app: `kiosko-screen-${version}-${board}.bin`, full: `kiosko-screen-${version}-${board}-full.bin` };
6101
+ }
6102
+ function firmwareOffer(model, fw, shipped2 = SCREEN_FIRMWARE) {
6103
+ if (!model || !fw || !shipped2.boards.includes(model)) return null;
6104
+ if (!parseVersion(fw) || !parseVersion(shipped2.version)) return null;
6105
+ return compareVersions(shipped2.version, fw) > 0 ? shipped2.version : null;
6106
+ }
6107
+ var MAX_IMAGE = 4 * 1024 * 1024;
6108
+ async function downloadFirmware(o) {
6109
+ const shipped2 = o.shipped ?? SCREEN_FIRMWARE;
6110
+ if (!shipped2.boards.includes(o.model)) throw new ScreenError("noFirmware", `this Kiosko has no firmware for ${o.model}`);
6111
+ const get = o.fetch ?? ((u, i) => fetch(u, i));
6112
+ const name2 = firmwareFiles(shipped2.version, o.model).app;
6113
+ const url2 = releaseAsset(o.kioskoVersion, name2);
6114
+ const signal = () => AbortSignal.timeout(o.timeoutMs ?? 6e4);
6115
+ let expected;
6116
+ try {
6117
+ const r = await get(`${url2}.sha256`, { redirect: "follow", signal: signal() });
6118
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
6119
+ expected = parseSha256File((await r.text()).slice(0, 4096), name2);
6120
+ } catch (err) {
6121
+ throw new ScreenError("downloadFailed", `could not download ${name2}.sha256 from the Kiosko ${o.kioskoVersion} release on GitHub (${err instanceof Error ? err.message : String(err)})`);
6122
+ }
6123
+ if (!expected) throw new ScreenError("hashMissing", `the release has no usable checksum for ${name2}: not sending it`);
6124
+ let image2;
6125
+ try {
6126
+ const r = await get(url2, { redirect: "follow", signal: signal() });
6127
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
6128
+ image2 = Buffer.from(await r.arrayBuffer());
6129
+ } catch (err) {
6130
+ throw new ScreenError("downloadFailed", `could not download ${name2} from GitHub (${err instanceof Error ? err.message : String(err)})`);
6131
+ }
6132
+ const sha256 = createHash2("sha256").update(image2).digest("hex");
6133
+ if (sha256 !== expected) throw new ScreenError("hashMismatch", `${name2} is not the file the release publishes (sha256 ${sha256.slice(0, 12)}\u2026, expected ${expected.slice(0, 12)}\u2026): not sent`);
6134
+ if (image2.length > MAX_IMAGE || image2[0] !== 233) throw new ScreenError("notFirmware", `${name2} is not an app image`);
6135
+ return { version: shipped2.version, name: name2, image: image2, sha256, url: url2 };
6136
+ }
6137
+
5535
6138
  // packages/core/src/remote/device.ts
5536
6139
  var ROTATIONS = [0, 90, 180, 270];
6140
+ function brightnessOf(v) {
6141
+ return typeof v === "number" && Number.isFinite(v) ? Math.min(100, Math.max(0, Math.round(v))) : null;
6142
+ }
5537
6143
  var RemoteDevice = class {
5538
6144
  status;
5539
6145
  cfg;
@@ -5548,6 +6154,8 @@ var RemoteDevice = class {
5548
6154
  fresh = false;
5549
6155
  led = null;
5550
6156
  ledDirty = false;
6157
+ dim = null;
6158
+ dimDirty = false;
5551
6159
  closed = false;
5552
6160
  paused = 0;
5553
6161
  wire = null;
@@ -5575,7 +6183,7 @@ var RemoteDevice = class {
5575
6183
  code: "connecting",
5576
6184
  framesSent: 0,
5577
6185
  lastSentAt: null,
5578
- remote: { online: false, id: cfg.id ?? cfg.uid, host: cfg.host ?? null, fw: "", model: "", w: 0, h: 0, rot: this.rotate, fps: 0, rttMs: null, decodeMs: null, lastFrameAt: null, dropped: 0, since: null }
6186
+ remote: { online: false, id: cfg.id ?? cfg.uid, host: cfg.host ?? null, fw: "", model: "", w: 0, h: 0, rot: this.rotate, fps: 0, rttMs: null, decodeMs: null, lastFrameAt: null, dropped: 0, since: null, tempC: null, bright: null, dim: null, dimmable: null, firmwareOffer: null }
5579
6187
  };
5580
6188
  this.mdns.retain();
5581
6189
  this.mdns.on("found", this.onFound);
@@ -5635,6 +6243,20 @@ var RemoteDevice = class {
5635
6243
  this.ledDirty = true;
5636
6244
  this.notify("frame");
5637
6245
  }
6246
+ /**
6247
+ * Dims the backlight for now (0-100, 0 = off), or back to the screen's own
6248
+ * brightness (null): night mode and black screens (backlight.ts). Never
6249
+ * saved on the screen; it ends with the session, and is sent again on every
6250
+ * connection. Firmware older than 0.1.4 ignores it.
6251
+ */
6252
+ setDim(level) {
6253
+ const next = level === null ? null : brightnessOf(level);
6254
+ if (next === this.dim) return;
6255
+ this.dim = next;
6256
+ this.status.remote.dim = next;
6257
+ this.dimDirty = true;
6258
+ this.notify("frame");
6259
+ }
5638
6260
  close() {
5639
6261
  if (this.closed) return;
5640
6262
  this.closed = true;
@@ -5709,8 +6331,8 @@ var RemoteDevice = class {
5709
6331
  async backoff(err) {
5710
6332
  this.failures++;
5711
6333
  const hopeless = err instanceof ScreenError && ["badKey", "notPaired", "proto"].includes(err.code);
5712
- const base3 = hopeless ? 6e4 : Math.min(this.deps.maxRetryMs, this.deps.retryMs * 2 ** Math.min(this.failures - 1, 8));
5713
- await this.wait(Math.round(base3 * (0.85 + Math.random() * 0.3)), ["found", "resume", "pause"]);
6334
+ const base4 = hopeless ? 6e4 : Math.min(this.deps.maxRetryMs, this.deps.retryMs * 2 ** Math.min(this.failures - 1, 8));
6335
+ await this.wait(Math.round(base4 * (0.85 + Math.random() * 0.3)), ["found", "resume", "pause"]);
5714
6336
  }
5715
6337
  async serve(conn, host) {
5716
6338
  const { wire, info, session: session2 } = conn;
@@ -5721,8 +6343,10 @@ var RemoteDevice = class {
5721
6343
  if (st.type !== T.STATE) throw new Error("the screen did not say its state");
5722
6344
  this.applyState(st.json());
5723
6345
  const extra = this.deps.settings?.() ?? {};
5724
- sendSealed(wire, session2, T.SET, { rot: this.rotate, ...extra });
6346
+ const bright = brightnessOf(this.cfg.brightness);
6347
+ sendSealed(wire, session2, T.SET, { rot: this.rotate, ...extra, ...bright !== null ? { bright } : {}, ...this.dim !== null ? { dim: this.dim } : {} });
5725
6348
  this.rotDirty = false;
6349
+ this.dimDirty = false;
5726
6350
  this.ledDirty = !!this.led;
5727
6351
  this.fresh = !!this.latest;
5728
6352
  r.online = true;
@@ -5737,6 +6361,11 @@ var RemoteDevice = class {
5737
6361
  sendSealed(wire, session2, T.SET, { rot: this.rotate });
5738
6362
  lastTx = Date.now();
5739
6363
  }
6364
+ if (this.dimDirty) {
6365
+ this.dimDirty = false;
6366
+ sendSealed(wire, session2, T.SET, { dim: this.dim ?? -1 });
6367
+ lastTx = Date.now();
6368
+ }
5740
6369
  if (this.ledDirty && this.led) {
5741
6370
  this.ledDirty = false;
5742
6371
  sendSealed(wire, session2, T.LED, this.led);
@@ -5802,6 +6431,10 @@ var RemoteDevice = class {
5802
6431
  if (typeof j.fw === "string") r.fw = j.fw;
5803
6432
  if (typeof j.w === "number") r.w = j.w;
5804
6433
  if (typeof j.h === "number") r.h = j.h;
6434
+ if (typeof j.tempC === "number" && Number.isFinite(j.tempC)) r.tempC = j.tempC;
6435
+ if (typeof j.bright === "number" && Number.isFinite(j.bright)) r.bright = j.bright;
6436
+ r.dimmable = typeof j.dim === "number";
6437
+ r.firmwareOffer = firmwareOffer(r.model, r.fw);
5805
6438
  }
5806
6439
  /**
5807
6440
  * Runs `fn` while this driver stands aside: its session is closed and it
@@ -5982,7 +6615,7 @@ var UsbDevice = class {
5982
6615
  /** Writes what is pending; concurrent callers share one run. */
5983
6616
  pump() {
5984
6617
  if (this.pumping) return this.pumping;
5985
- const run = async () => {
6618
+ const run2 = async () => {
5986
6619
  while (!this.closed && this.latest && Date.now() >= this.retryAt && (this.fresh || this.due(Date.now()))) {
5987
6620
  try {
5988
6621
  const frame = this.latest;
@@ -6010,7 +6643,7 @@ var UsbDevice = class {
6010
6643
  }
6011
6644
  }
6012
6645
  };
6013
- this.pumping = run().finally(() => this.pumping = null);
6646
+ this.pumping = run2().finally(() => this.pumping = null);
6014
6647
  return this.pumping;
6015
6648
  }
6016
6649
  describe() {
@@ -6110,6 +6743,114 @@ function ledFor(level) {
6110
6743
  return ["000000", 0];
6111
6744
  }
6112
6745
 
6746
+ // packages/core/src/processes.ts
6747
+ import { execFile } from "node:child_process";
6748
+ import { readdir, readFile } from "node:fs/promises";
6749
+ var APPS_EVERY_MS = 3e3;
6750
+ var base3 = (p) => p.split(/[\\/]/).pop() ?? p;
6751
+ var uniq = (xs) => [...new Set(xs.map((x) => x.trim()).filter(Boolean))];
6752
+ function parseLinuxProc(procs) {
6753
+ const out = [];
6754
+ for (const p of procs) {
6755
+ if (p.comm) out.push(p.comm.trim());
6756
+ const argv2 = (p.cmdline ?? "").split("\0").filter(Boolean);
6757
+ const argv0 = argv2[0];
6758
+ if (!argv0) continue;
6759
+ if (argv2.length > 1 || !argv0.includes(" ")) {
6760
+ out.push(base3(argv0));
6761
+ continue;
6762
+ }
6763
+ out.push(base3(argv0.split(" -")[0].trim()));
6764
+ const first = argv0.split(" ")[0];
6765
+ if (!first.includes("/")) out.push(first);
6766
+ }
6767
+ return uniq(out);
6768
+ }
6769
+ function parsePs(stdout) {
6770
+ const out = [];
6771
+ for (const line of stdout.split("\n")) {
6772
+ const path = line.trim();
6773
+ if (!path) continue;
6774
+ out.push(base3(path));
6775
+ const bundle = /\/([^/]+)\.app\//.exec(path);
6776
+ if (bundle) out.push(bundle[1]);
6777
+ }
6778
+ return uniq(out);
6779
+ }
6780
+ function parseTasklist(stdout) {
6781
+ const out = [];
6782
+ for (const line of stdout.split(/\r?\n/)) {
6783
+ const m = /^"([^"]+)"/.exec(line.trim());
6784
+ if (!m) continue;
6785
+ out.push(m[1]);
6786
+ if (/\.exe$/i.test(m[1])) out.push(m[1].slice(0, -4));
6787
+ }
6788
+ return uniq(out);
6789
+ }
6790
+ function run(cmd2, args) {
6791
+ return new Promise((resolve8, reject) => {
6792
+ execFile(cmd2, args, { timeout: 5e3, maxBuffer: 8 * 1024 * 1024, windowsHide: true }, (err, stdout) => err ? reject(err) : resolve8(String(stdout)));
6793
+ });
6794
+ }
6795
+ async function linuxList(root = "/proc") {
6796
+ const pids = (await readdir(root)).filter((d) => /^\d+$/.test(d));
6797
+ const procs = await Promise.all(
6798
+ pids.map(async (pid) => {
6799
+ const [comm, cmdline] = await Promise.all([readFile(`${root}/${pid}/comm`, "utf8").catch(() => ""), readFile(`${root}/${pid}/cmdline`, "utf8").catch(() => "")]);
6800
+ return { comm, cmdline };
6801
+ })
6802
+ );
6803
+ return parseLinuxProc(procs);
6804
+ }
6805
+ function systemProcesses(platform3 = process.platform) {
6806
+ if (platform3 === "linux") return { list: () => linuxList() };
6807
+ if (platform3 === "win32") return { list: async () => parseTasklist(await run("tasklist", ["/fo", "csv", "/nh"])) };
6808
+ return { list: async () => parsePs(await run("ps", ["-axo", "comm="])) };
6809
+ }
6810
+ var ProcessWatch = class {
6811
+ names = null;
6812
+ askedAt = Number.NEGATIVE_INFINITY;
6813
+ busy = false;
6814
+ failed = null;
6815
+ lister;
6816
+ log;
6817
+ everyMs;
6818
+ constructor(lister, log = () => {
6819
+ }, everyMs = APPS_EVERY_MS) {
6820
+ this.lister = lister;
6821
+ this.log = log;
6822
+ this.everyMs = everyMs;
6823
+ }
6824
+ /** Asks again if due; `changed` is called when the names changed. */
6825
+ poll(now, changed = () => {
6826
+ }) {
6827
+ if (this.busy || now - this.askedAt < this.everyMs) return;
6828
+ this.busy = true;
6829
+ this.askedAt = now;
6830
+ this.lister.list().then(
6831
+ (names) => {
6832
+ this.busy = false;
6833
+ this.failed = null;
6834
+ const before = this.names?.join("\0");
6835
+ this.names = names;
6836
+ if (before !== names.join("\0")) changed();
6837
+ },
6838
+ (err) => {
6839
+ this.busy = false;
6840
+ const m = err instanceof Error ? err.message : String(err);
6841
+ if (this.failed !== m) this.log(`could not list the running programs: ${m}`);
6842
+ this.failed = m;
6843
+ this.names = null;
6844
+ }
6845
+ );
6846
+ }
6847
+ /** No rule needs it any more: forgets the list. */
6848
+ stop() {
6849
+ this.names = null;
6850
+ this.askedAt = Number.NEGATIVE_INFINITY;
6851
+ }
6852
+ };
6853
+
6113
6854
  // packages/core/src/remote/tz.ts
6114
6855
  var formats = /* @__PURE__ */ new Map();
6115
6856
  function offsetMinutes(tz, at) {
@@ -6163,6 +6904,23 @@ function posixTz(tz = Intl.DateTimeFormat().resolvedOptions().timeZone, year = (
6163
6904
  }
6164
6905
  }
6165
6906
 
6907
+ // packages/core/src/remote/backlight.ts
6908
+ var HHMM2 = /^([01][0-9]|2[0-3]):[0-5][0-9]$/;
6909
+ function nightOf(d) {
6910
+ if (d.driver !== "remote" || !d.night || typeof d.night !== "object") return null;
6911
+ const { start, end, brightness } = d.night;
6912
+ if (!HHMM2.test(String(start)) || !HHMM2.test(String(end)) || start === end) return null;
6913
+ if (typeof brightness !== "number" || !Number.isFinite(brightness)) return null;
6914
+ return { start, end, brightness: Math.min(100, Math.max(0, Math.round(brightness))) };
6915
+ }
6916
+ function dimFor(screen, state, now) {
6917
+ if (screen.device.driver !== "remote") return null;
6918
+ if (state.alert) return null;
6919
+ if (!screen.enabled || state.sleeping) return 0;
6920
+ const night = nightOf(screen.device);
6921
+ return night && inQuietHours(night, now) ? night.brightness : null;
6922
+ }
6923
+
6166
6924
  // packages/core/src/screen-runner.ts
6167
6925
  init_src();
6168
6926
 
@@ -6180,10 +6938,10 @@ var LEVEL_COLORS = {
6180
6938
  function alertStepMs(maxFps) {
6181
6939
  return Math.max(500, Math.ceil(1e3 / Math.max(1, maxFps || 1)));
6182
6940
  }
6183
- function alertIntensity(level, elapsed, step) {
6184
- const k = Math.floor(Math.max(0, elapsed) / step);
6941
+ function alertIntensity(level, elapsed, step2) {
6942
+ const k = Math.floor(Math.max(0, elapsed) / step2);
6185
6943
  if (level !== "info" && elapsed < FLASH_MS) return k % 2 === 0 ? 1 : 0.15;
6186
- const t2 = k * step % PULSE_MS / PULSE_MS;
6944
+ const t2 = k * step2 % PULSE_MS / PULSE_MS;
6187
6945
  const depth = level === "info" ? 0.3 : 0.45;
6188
6946
  return Math.round((1 - depth * (0.5 - 0.5 * Math.cos(2 * Math.PI * t2))) * 100) / 100;
6189
6947
  }
@@ -6248,8 +7006,8 @@ function drawIcon(g, a, x, y, size, color2, family) {
6248
7006
  g.restore();
6249
7007
  }
6250
7008
  var mixHex = (a, b, t2) => css(mix(hex(a), hex(b), clamp3(t2)));
6251
- function paintAlert(g, w, h, shown, o) {
6252
- const a = shown.top;
7009
+ function paintAlert(g, w, h, shown2, o) {
7010
+ const a = shown2.top;
6253
7011
  const { color: color2, bg } = LEVEL_COLORS[a.level];
6254
7012
  g.save();
6255
7013
  g.fillStyle = bg;
@@ -6268,8 +7026,8 @@ function paintAlert(g, w, h, shown, o) {
6268
7026
  const regular = o.fonts.sans;
6269
7027
  const small = Math.max(minPx, Math.round(Math.min(box.h, box.w) * 0.12));
6270
7028
  let counterW = 0;
6271
- if (shown.more > 0) {
6272
- const label = `+${shown.more}`;
7029
+ if (shown2.more > 0) {
7030
+ const label = `+${shown2.more}`;
6273
7031
  const tw = measureTracked(g, label, { size: small, family: bold2 });
6274
7032
  const ph = Math.round(small * 1.35);
6275
7033
  counterW = Math.round(tw + small);
@@ -6479,14 +7237,14 @@ function paintBoot(g, w, h, ms, look) {
6479
7237
  const p = easeOut((ms - 650) / 700);
6480
7238
  if (p > 0) {
6481
7239
  const wx = shape === "wide" ? gx + mark + gap : Math.round((w - wordW) / 2);
6482
- const base3 = shape === "wide" ? gy + mark / 2 + size * 0.36 : gy + mark + gap + size * 0.82;
7240
+ const base4 = shape === "wide" ? gy + mark / 2 + size * 0.36 : gy + mark + gap + size * 0.82;
6483
7241
  g.save();
6484
7242
  g.beginPath();
6485
7243
  if (shape === "wide") g.rect(wx - 2, 0, (wordW + 4) * p, h);
6486
7244
  else g.rect(0, 0, w, h);
6487
7245
  g.clip();
6488
7246
  g.globalAlpha = fade * (shape === "wide" ? 1 : p);
6489
- drawTracked(g, word, wx, base3 + (1 - p) * size * 0.25, { size, family: bold2, color: theme.colors.ink });
7247
+ drawTracked(g, word, wx, base4 + (1 - p) * size * 0.25, { size, family: bold2, color: theme.colors.ink });
6490
7248
  g.restore();
6491
7249
  const u = easeOut((ms - 1150) / 600);
6492
7250
  if (u > 0) {
@@ -6497,7 +7255,7 @@ function paintBoot(g, w, h, ms, look) {
6497
7255
  g.fillStyle = gr;
6498
7256
  const uh = Math.max(2, Math.round(size * 0.07));
6499
7257
  g.beginPath();
6500
- g.roundRect(wx, base3 + size * 0.16, wordW * u, uh, uh / 2);
7258
+ g.roundRect(wx, base4 + size * 0.16, wordW * u, uh, uh / 2);
6501
7259
  g.fill();
6502
7260
  }
6503
7261
  }
@@ -6536,25 +7294,25 @@ function paintCard(g, w, h, look) {
6536
7294
  return { k: k2, body: body2, chip, hint, title, open: open2, cmd: cmd2, cmdW, orW, urlW, oneLine: oneLine2, hints, height, fits, lineH };
6537
7295
  };
6538
7296
  let k = Math.round(shape === "wide" ? h * 0.17 : shape === "tall" ? w * 0.12 : Math.min(w * 0.085, h * 0.11));
6539
- let L = layout(k);
6540
- while (k > 12 && (L.height > bh || !L.fits)) L = layout(--k);
6541
- const my = shape === "wide" ? Math.round((h - mark) / 2) : Math.max(pad, Math.round((h - mark - gap - L.height) / 2));
7297
+ let L3 = layout(k);
7298
+ while (k > 12 && (L3.height > bh || !L3.fits)) L3 = layout(--k);
7299
+ const my = shape === "wide" ? Math.round((h - mark) / 2) : Math.max(pad, Math.round((h - mark - gap - L3.height) / 2));
6542
7300
  paintBackground(g, w, h, theme, mx + mark / 2, my + mark / 2, 1);
6543
7301
  paintMark(g, mx, my, mark, theme);
6544
- let y = shape === "wide" ? pad + Math.max(0, Math.round((bh - L.height) / 2)) : my + mark + gap;
7302
+ let y = shape === "wide" ? pad + Math.max(0, Math.round((bh - L3.height) / 2)) : my + mark + gap;
6545
7303
  const ax = center ? w / 2 : bx;
6546
7304
  const align = center ? "center" : "left";
6547
- for (const line of L.title) {
6548
- drawTracked(g, line, ax, y + L.k * 0.95, { size: L.k, family: bold2, color: theme.colors.ink, align });
6549
- y += L.lineH(L.k);
7305
+ for (const line of L3.title) {
7306
+ drawTracked(g, line, ax, y + L3.k * 0.95, { size: L3.k, family: bold2, color: theme.colors.ink, align });
7307
+ y += L3.lineH(L3.k);
6550
7308
  }
6551
- y += L.k * 0.25;
6552
- for (const line of L.open) {
6553
- drawTracked(g, line, ax, y + L.body * 0.95, { size: L.body, family: sans, color: theme.colors.inkDim, align });
6554
- y += L.lineH(L.body);
7309
+ y += L3.k * 0.25;
7310
+ for (const line of L3.open) {
7311
+ drawTracked(g, line, ax, y + L3.body * 0.95, { size: L3.body, family: sans, color: theme.colors.inkDim, align });
7312
+ y += L3.lineH(L3.body);
6555
7313
  }
6556
- y += L.body * 0.35;
6557
- const chipH = Math.round(L.chip * 1.6);
7314
+ y += L3.body * 0.35;
7315
+ const chipH = Math.round(L3.chip * 1.6);
6558
7316
  const drawChip = (x, text3, cw) => {
6559
7317
  g.fillStyle = theme.colors.surface;
6560
7318
  g.strokeStyle = theme.colors.surfaceEdge;
@@ -6563,30 +7321,30 @@ function paintCard(g, w, h, look) {
6563
7321
  g.roundRect(x, y, cw, chipH, chipH / 3);
6564
7322
  g.fill();
6565
7323
  g.stroke();
6566
- drawTracked(g, text3, x + cw / 2, y + chipH / 2 + L.chip * 0.36, { size: L.chip, family: mono, color: theme.colors.ink, align: "center" });
7324
+ drawTracked(g, text3, x + cw / 2, y + chipH / 2 + L3.chip * 0.36, { size: L3.chip, family: mono, color: theme.colors.ink, align: "center" });
6567
7325
  };
6568
- const drawUrl = (x) => drawTracked(g, look.url, x, y + chipH / 2 + L.chip * 0.36, { size: L.chip, family: mono, color: theme.colors.accent });
6569
- if (L.oneLine) {
6570
- const total = L.cmdW + L.body * 0.6 + L.orW + L.body * 0.6 + L.urlW;
7326
+ const drawUrl = (x) => drawTracked(g, look.url, x, y + chipH / 2 + L3.chip * 0.36, { size: L3.chip, family: mono, color: theme.colors.accent });
7327
+ if (L3.oneLine) {
7328
+ const total = L3.cmdW + L3.body * 0.6 + L3.orW + L3.body * 0.6 + L3.urlW;
6571
7329
  let x = center ? Math.round((w - total) / 2) : bx;
6572
- drawChip(x, L.cmd, L.cmdW);
6573
- x += L.cmdW + L.body * 0.6;
6574
- drawTracked(g, tx.or, x, y + chipH / 2 + L.body * 0.36, { size: L.body, family: sans, color: theme.colors.inkDim });
6575
- x += L.orW + L.body * 0.6;
7330
+ drawChip(x, L3.cmd, L3.cmdW);
7331
+ x += L3.cmdW + L3.body * 0.6;
7332
+ drawTracked(g, tx.or, x, y + chipH / 2 + L3.body * 0.36, { size: L3.body, family: sans, color: theme.colors.inkDim });
7333
+ x += L3.orW + L3.body * 0.6;
6576
7334
  drawUrl(x);
6577
- y += L.chip * 1.9;
7335
+ y += L3.chip * 1.9;
6578
7336
  } else {
6579
- drawChip(center ? Math.round((w - L.cmdW) / 2) : bx, L.cmd, L.cmdW);
6580
- y += L.chip * 1.9;
6581
- drawTracked(g, tx.or, ax, y + L.body * 0.95, { size: L.body, family: sans, color: theme.colors.inkDim, align });
6582
- y += L.lineH(L.body);
6583
- drawUrl(center ? Math.round((w - L.urlW) / 2) : bx);
6584
- y += L.chip * 1.9;
7337
+ drawChip(center ? Math.round((w - L3.cmdW) / 2) : bx, L3.cmd, L3.cmdW);
7338
+ y += L3.chip * 1.9;
7339
+ drawTracked(g, tx.or, ax, y + L3.body * 0.95, { size: L3.body, family: sans, color: theme.colors.inkDim, align });
7340
+ y += L3.lineH(L3.body);
7341
+ drawUrl(center ? Math.round((w - L3.urlW) / 2) : bx);
7342
+ y += L3.chip * 1.9;
6585
7343
  }
6586
- y += L.hint * 0.6;
6587
- for (const line of L.hints) {
6588
- drawTracked(g, line, ax, y + L.hint * 0.95, { size: L.hint, family: sans, color: theme.colors.inkFaint, align });
6589
- y += L.lineH(L.hint);
7344
+ y += L3.hint * 0.6;
7345
+ for (const line of L3.hints) {
7346
+ drawTracked(g, line, ax, y + L3.hint * 0.95, { size: L3.hint, family: sans, color: theme.colors.inkFaint, align });
7347
+ y += L3.lineH(L3.hint);
6590
7348
  }
6591
7349
  }
6592
7350
 
@@ -6652,6 +7410,7 @@ var ScreenRunner = class {
6652
7410
  nextAt = 0;
6653
7411
  busy = false;
6654
7412
  pinned = null;
7413
+ context = null;
6655
7414
  playedSlot = /* @__PURE__ */ new Map();
6656
7415
  interlude = null;
6657
7416
  /** The buttons of whoever plays the interlude now (Play page). */
@@ -6735,24 +7494,22 @@ var ScreenRunner = class {
6735
7494
  this.dirty = true;
6736
7495
  }
6737
7496
  currentPage(now) {
6738
- const working = this.rt.working(now);
6739
- const pages = this.screen.pages.filter((p) => whenMatches(p.when, working));
6740
- return pickPage(pages, now, this.pinned);
7497
+ return choosePage(this.screen, now, this.rt.working(now), this.pinned, this.context?.page ?? null);
6741
7498
  }
6742
7499
  /**
6743
7500
  * The alert for this screen now (or none). One coming up stops what plays
6744
7501
  * (an interlude, a game, an animation: they check `alert`) and the next
6745
7502
  * update paints it; one going away gives the pages back.
6746
7503
  */
6747
- setAlert(shown, now) {
7504
+ setAlert(shown2, now) {
6748
7505
  const was = this.alert;
6749
- this.alert = shown;
6750
- if (shown && shown.top.id !== was?.top.id) this.alertStart = now;
6751
- if (shown && !was && this.interlude) {
7506
+ this.alert = shown2;
7507
+ if (shown2 && shown2.top.id !== was?.top.id) this.alertStart = now;
7508
+ if (shown2 && !was && this.interlude) {
6752
7509
  this.rt.log(`screen:${this.screen.name}`, `${this.interlude.type} stopped: an alert`);
6753
7510
  this.stopInterlude();
6754
7511
  }
6755
- if (!shown && was) {
7512
+ if (!shown2 && was) {
6756
7513
  this.alertKey = null;
6757
7514
  this.last = null;
6758
7515
  this.dirty = true;
@@ -6813,7 +7570,7 @@ var ScreenRunner = class {
6813
7570
  now,
6814
7571
  working: this.rt.working(now),
6815
7572
  dataOf: (inst) => this.rt.dataOf(inst.id),
6816
- sourcesOf: (types2) => this.rt.sourcesOf(types2),
7573
+ sourcesOf: (types2, profile) => this.rt.sourcesOf(types2, profile),
6817
7574
  log: this.rt.log,
6818
7575
  demo: this.rt.demoMode,
6819
7576
  cache: this.tiles,
@@ -6856,15 +7613,15 @@ var ScreenRunner = class {
6856
7613
  * frame's brightness steps every half second at most, see alert-paint.ts),
6857
7614
  * so a flashing alert costs 2 frames a second and no more.
6858
7615
  */
6859
- async paintAlert(shown, now) {
7616
+ async paintAlert(shown2, now) {
6860
7617
  const { screen } = this;
6861
- const a = shown.top;
7618
+ const a = shown2.top;
6862
7619
  const intensity = alertIntensity(a.level, now - this.alertStart, alertStepMs(screen.maxFps));
6863
7620
  const shift = screen.pixelShift.enabled ? pixelShift(now, screen.pixelShift) : { x: 0, y: 0 };
6864
7621
  const cfg = this.rt.config;
6865
7622
  const sinceText = createFormatters({ locale: resolveLocale(cfg), timeFormat: cfg.timeFormat, now }).time(a.since);
6866
7623
  const minPx = legibleCjkPx(screen);
6867
- const key = JSON.stringify([a.id, a.level, a.title, a.text, a.source, a.detail, a.icon, shown.more, intensity, shift, sinceText, minPx, screen.width, screen.height, screen.rotate]);
7624
+ const key = JSON.stringify([a.id, a.level, a.title, a.text, a.source, a.detail, a.icon, shown2.more, intensity, shift, sinceText, minPx, screen.width, screen.height, screen.rotate]);
6868
7625
  if (key === this.alertKey) return;
6869
7626
  this.alertKey = key;
6870
7627
  const t0 = performance.now();
@@ -6872,7 +7629,7 @@ var ScreenRunner = class {
6872
7629
  setFontLocale(resolveLocale(cfg));
6873
7630
  src_exports.setMinCjkPx(minPx);
6874
7631
  const canvas = CANVAS.createCanvas(screen.width, screen.height);
6875
- paintAlert(canvas.getContext("2d"), screen.width, screen.height, shown, { intensity, fonts: this.rt.theme().fonts, minPx, sinceText, shift });
7632
+ paintAlert(canvas.getContext("2d"), screen.width, screen.height, shown2, { intensity, fonts: this.rt.theme().fonts, minPx, sinceText, shift });
6876
7633
  const kind = encodeFor(screen.device, screen.jpegQuality || 85);
6877
7634
  const turned = rotateCanvas(canvas, paintTurn(screen));
6878
7635
  const out = await this.fit(turned, kind, screen.jpegQuality || 85, screen, performance.now() - t0);
@@ -6979,7 +7736,7 @@ var ScreenRunner = class {
6979
7736
  async maybeInterlude(now, force, play = false) {
6980
7737
  const due = this.screen.interludes.find((s) => {
6981
7738
  if (force) return s.id === force;
6982
- if (!s.enabled || s.everyMs < 6e4) return false;
7739
+ if (!s.enabled || s.everyMs < 6e4 || this.context) return false;
6983
7740
  const slot = Math.floor(now / s.everyMs);
6984
7741
  return now - slot * s.everyMs < 6e4 && this.playedSlot.get(s.id) !== slot;
6985
7742
  });
@@ -7130,9 +7887,9 @@ var ScreenRunner = class {
7130
7887
  if (!memoData.has(inst.id)) memoData.set(inst.id, this.rt.dataOf(inst.id));
7131
7888
  return memoData.get(inst.id);
7132
7889
  },
7133
- sourcesOf: (types2) => {
7134
- const k = JSON.stringify(types2 ?? []);
7135
- if (!memoSources.has(k)) memoSources.set(k, this.rt.sourcesOf(types2));
7890
+ sourcesOf: (types2, profile) => {
7891
+ const k = JSON.stringify([types2 ?? [], profile ?? null]);
7892
+ if (!memoSources.has(k)) memoSources.set(k, this.rt.sourcesOf(types2, profile));
7136
7893
  return memoSources.get(k);
7137
7894
  },
7138
7895
  log: this.rt.log,
@@ -7200,6 +7957,10 @@ var ScreenRunner = class {
7200
7957
  this.pinned = pageId;
7201
7958
  this.dirty = true;
7202
7959
  }
7960
+ setContext(pick2) {
7961
+ if (pick2?.page !== this.context?.page) this.dirty = true;
7962
+ this.context = pick2;
7963
+ }
7203
7964
  setOff(off2) {
7204
7965
  this.off = off2;
7205
7966
  if (off2) this.stopInterlude();
@@ -7232,9 +7993,9 @@ function planThreads(cfg, cores = availableParallelism()) {
7232
7993
  const mode = threadsMode(cfg);
7233
7994
  const out = /* @__PURE__ */ new Map();
7234
7995
  const on = cfg.screens.filter((s) => s.enabled);
7235
- const own = (s) => s.thread ?? (mode === "auto" ? null : mode);
7236
- const sure = on.filter((s) => own(s) === "always").length;
7237
- const auto = on.filter((s) => own(s) === null);
7996
+ const own2 = (s) => s.thread ?? (mode === "auto" ? null : mode);
7997
+ const sure = on.filter((s) => own2(s) === "always").length;
7998
+ const auto = on.filter((s) => own2(s) === null);
7238
7999
  const autoWhy = on.length < 2 ? "fewScreens" : cores < sure + auto.length + 1 ? "fewCores" : "auto";
7239
8000
  for (const s of cfg.screens) {
7240
8001
  if (!s.enabled) out.set(s.id, { thread: false, why: "off" });
@@ -7336,6 +8097,7 @@ var ThreadRunner = class {
7336
8097
  device;
7337
8098
  deviceKey;
7338
8099
  pinned;
8100
+ context = null;
7339
8101
  off = false;
7340
8102
  alert = null;
7341
8103
  lastInfo = null;
@@ -7392,6 +8154,7 @@ var ThreadRunner = class {
7392
8154
  startedAt: this.owner.startedAt,
7393
8155
  ...this.owner.editorUrl ? { editorUrl: this.owner.editorUrl } : {},
7394
8156
  pinned: this.pinned,
8157
+ context: this.context,
7395
8158
  off: this.off
7396
8159
  };
7397
8160
  const w = new Worker2(this.entry, { workerData: init, name: `kiosko screen ${this.screen.id}` });
@@ -7415,7 +8178,7 @@ var ThreadRunner = class {
7415
8178
  const def = reg.widget(widget.type);
7416
8179
  if (!def || widget.disabled) continue;
7417
8180
  ids2.add(widget.id);
7418
- for (const s of def.sources ?? []) sources.add(s);
8181
+ for (const s of this.owner.sourceKeys(def.sources, widget.profile)) sources.add(s);
7419
8182
  }
7420
8183
  for (const slot of this.screen.interludes) for (const s of reg.interlude(slot.type)?.sources ?? []) sources.add(s);
7421
8184
  return { ids: ids2, sources };
@@ -7544,17 +8307,22 @@ var ThreadRunner = class {
7544
8307
  dataChanged(change) {
7545
8308
  if (change.instance && this.need.ids.has(change.instance) || change.source && this.need.sources.has(change.source)) this.sendData(change);
7546
8309
  }
7547
- setAlert(shown) {
7548
- const key = JSON.stringify(shown);
7549
- this.alert = shown;
8310
+ setAlert(shown2) {
8311
+ const key = JSON.stringify(shown2);
8312
+ this.alert = shown2;
7550
8313
  if (key === this.alertKey) return;
7551
8314
  this.alertKey = key;
7552
- this.post({ t: "alert", shown });
8315
+ this.post({ t: "alert", shown: shown2 });
7553
8316
  }
7554
8317
  setPinned(pageId) {
7555
8318
  this.pinned = pageId;
7556
8319
  this.post({ t: "pin", page: pageId });
7557
8320
  }
8321
+ setContext(pick2) {
8322
+ const same3 = JSON.stringify(pick2) === JSON.stringify(this.context);
8323
+ this.context = pick2;
8324
+ if (!same3) this.post({ t: "context", pick: pick2 });
8325
+ }
7558
8326
  setOff(off2) {
7559
8327
  this.off = off2;
7560
8328
  if (off2) this.state = { ...this.state, interlude: null };
@@ -7609,6 +8377,7 @@ var PaintTimes = class {
7609
8377
  }
7610
8378
  };
7611
8379
  var round2 = (ms) => Math.round(ms * 10) / 10;
8380
+ var CONTEXT_EVERY_MS = 1e3;
7612
8381
  var ALERTS_EVERY_MS = 5e3;
7613
8382
  var TEST_ALERT_TITLE = { en: "Test alert", es: "Alerta de prueba", de: "Testalarm", "zh-Hant": "\u6E2C\u8A66\u8B66\u5831", "zh-Hans": "\u6D4B\u8BD5\u8B66\u62A5" };
7614
8383
  var TEST_ALERT_TEXT = {
@@ -7642,6 +8411,12 @@ var Runtime = class extends EventEmitter2 {
7642
8411
  alertsSig = "";
7643
8412
  /** A plugin's `alerts` failing, said once per message. */
7644
8413
  alertErrors = /* @__PURE__ */ new Map();
8414
+ /** Context pages (context.ts): what holds, over time, per screen. */
8415
+ contextEngine = new ContextEngine();
8416
+ contextDirty = true;
8417
+ contextAt = Number.NEGATIVE_INFINITY;
8418
+ /** The running programs, listed only while an `app` rule needs them; null: none can be (the browser demo). */
8419
+ apps;
7645
8420
  /** The cores `threads: auto` counts on (see threads/plan.ts); tests set it. */
7646
8421
  cores = cpuCount();
7647
8422
  /** Where each screen is painted, and why (see threads/plan.ts). */
@@ -7662,6 +8437,7 @@ var Runtime = class extends EventEmitter2 {
7662
8437
  editorUrl;
7663
8438
  /** When this runtime was made: the boot animation plays only soon after. */
7664
8439
  startedAt = Date.now();
8440
+ /** `processes`: who lists the running programs for `app` rules (tests pass a fake); null: nobody. Default: this system's (none in demo mode). */
7665
8441
  constructor(registry2, config2, o = {}) {
7666
8442
  super();
7667
8443
  this.registry = registry2;
@@ -7673,6 +8449,8 @@ var Runtime = class extends EventEmitter2 {
7673
8449
  this.config = config2;
7674
8450
  this.hub = new SourceHub(registry2, this.log, (type) => this.onData({ source: type }));
7675
8451
  this.fetches = new FetchHost(this.hub, this.log, (id) => this.onData({ instance: id }));
8452
+ const lister = o.processes !== void 0 ? o.processes : o.demo ? null : systemProcesses();
8453
+ this.apps = lister ? new ProcessWatch(lister, (m) => this.log("context", m), o.appsEveryMs) : null;
7676
8454
  }
7677
8455
  log = (scope, message) => {
7678
8456
  const e = { at: Date.now(), scope, message };
@@ -7691,11 +8469,15 @@ var Runtime = class extends EventEmitter2 {
7691
8469
  dataOf(instanceId) {
7692
8470
  return this.fetches.data(instanceId);
7693
8471
  }
7694
- sourceData(type) {
7695
- return this.hub.data(type);
8472
+ sourceData(key) {
8473
+ return this.hub.data(key);
8474
+ }
8475
+ sourcesOf(types2, profile) {
8476
+ return this.hub.pick(types2, this.config, profile);
7696
8477
  }
7697
- sourcesOf(types2) {
7698
- return this.hub.pick(types2);
8478
+ /** The source keys a widget with `profile` reads (see config/profiles.ts). */
8479
+ sourceKeys(types2, profile) {
8480
+ return sourceKeysOf(this.config, types2, profile, (t2) => this.registry.source(t2)).map(([, key]) => key);
7699
8481
  }
7700
8482
  paintTime(instance, type, ms, now) {
7701
8483
  this.paintTimes.record(instance, type, ms, now, this.log);
@@ -7711,6 +8493,7 @@ var Runtime = class extends EventEmitter2 {
7711
8493
  }
7712
8494
  onData(change) {
7713
8495
  this.alertsDirty = true;
8496
+ this.contextDirty = true;
7714
8497
  for (const r of this.runners.values()) r.dataChanged(change);
7715
8498
  this.emit("data", change);
7716
8499
  }
@@ -7729,15 +8512,17 @@ var Runtime = class extends EventEmitter2 {
7729
8512
  const def = this.registry.widget(widget.type);
7730
8513
  if (!def || widget.disabled) continue;
7731
8514
  instances.push({ inst: widget, def });
7732
- for (const s of def.sources ?? []) sources.add(s);
8515
+ const keys = this.sourceKeys(def.sources, widget.profile);
8516
+ for (const s of keys) sources.add(s);
7733
8517
  if (!r.page || r.page.id === page.id) {
7734
8518
  r.visibleIds.add(widget.id);
7735
- for (const s of def.sources ?? []) r.sourceTypes.add(s);
8519
+ for (const s of keys) r.sourceTypes.add(s);
7736
8520
  }
7737
8521
  }
7738
8522
  for (const slot of r.screen.interludes) for (const s of this.registry.interlude(slot.type)?.sources ?? []) if (slot.enabled) sources.add(s);
7739
8523
  }
7740
8524
  for (const s of backgroundSources(this.config, (type) => this.registry.source(type))) sources.add(s);
8525
+ for (const s of ruleSources(this.config)) if (this.registry.source(s)) sources.add(s);
7741
8526
  this.paintTimes.retain(new Set(instances.map((i) => i.inst.id)));
7742
8527
  if (this.demoMode) {
7743
8528
  sources.clear();
@@ -7767,6 +8552,7 @@ var Runtime = class extends EventEmitter2 {
7767
8552
  apply(config2) {
7768
8553
  this.config = config2;
7769
8554
  this.alertsDirty = true;
8555
+ this.contextDirty = true;
7770
8556
  this.registry.setDisabled(config2.plugins.disabled);
7771
8557
  const ids2 = new Set(config2.screens.map((s) => s.id));
7772
8558
  for (const [id, r] of this.runners) {
@@ -7813,6 +8599,7 @@ var Runtime = class extends EventEmitter2 {
7813
8599
  const r = thread ? new ThreadRunner(s, this, this.threadEntry ?? defaultThreadEntry(), device) : new ScreenRunner(s, this, device);
7814
8600
  if (old) {
7815
8601
  if (old.pinned !== r.pinned) r.setPinned(old.pinned);
8602
+ if (old.context) r.setContext(old.context);
7816
8603
  if (old.off) r.setOff(true);
7817
8604
  if (old.alert) r.setAlert(old.alert, Date.now());
7818
8605
  }
@@ -7838,7 +8625,9 @@ var Runtime = class extends EventEmitter2 {
7838
8625
  this.fetches.tick(this.config, now);
7839
8626
  if (this.alertsDirty || now - this.alertsAskedAt >= ALERTS_EVERY_MS) this.askAlerts(now);
7840
8627
  this.refreshAlerts(now);
8628
+ this.refreshContext(now);
7841
8629
  await Promise.all([...this.runners.values()].map((r) => r.update(now)));
8630
+ this.refreshBacklights(now);
7842
8631
  };
7843
8632
  this.timer = setInterval(() => void loop(), TICK_MS);
7844
8633
  this.apply(this.config);
@@ -7854,6 +8643,10 @@ var Runtime = class extends EventEmitter2 {
7854
8643
  lastFrame(screenId) {
7855
8644
  return this.runners.get(screenId)?.lastInfo ?? null;
7856
8645
  }
8646
+ /** The context page that has a screen now, and why (see context.ts). */
8647
+ contextOf(screenId) {
8648
+ return this.runners.get(screenId)?.context ?? null;
8649
+ }
7857
8650
  pin(screenId, pageId) {
7858
8651
  const r = this.runners.get(screenId);
7859
8652
  r?.setPinned(pageId);
@@ -7909,31 +8702,84 @@ var Runtime = class extends EventEmitter2 {
7909
8702
  done2.add(widget.id);
7910
8703
  call2(widget.type, () => {
7911
8704
  const options2 = def.options ? validate(def.options, widget.options).value : {};
7912
- return def.alerts({ options: options2, data: this.fetches.data(widget.id), sources: this.hub.pick(def.sources), now, working, workday: cfg.workday, ...cfg.location ? { location: cfg.location } : {} });
8705
+ return def.alerts({ options: options2, data: this.fetches.data(widget.id), sources: this.hub.pick(def.sources, cfg, widget.profile), now, working, workday: cfg.workday, ...cfg.location ? { location: cfg.location } : {} });
7913
8706
  }, "widget");
7914
8707
  }
7915
8708
  }
7916
- for (const { type, options: options2 } of this.hub.running()) {
8709
+ for (const { key, type, options: options2 } of this.hub.running()) {
7917
8710
  const def = this.registry.source(type);
7918
- if (def?.alerts) call2(type, () => def.alerts({ data: this.hub.data(type), options: options2, now }), "source");
8711
+ if (def?.alerts) call2(type, () => def.alerts({ data: this.hub.data(key), options: options2, now }), "source");
7919
8712
  }
7920
8713
  }
7921
8714
  this.alerts.sync(out, now, resolveLocale(this.config));
7922
8715
  }
7923
- /** Every screen gets the alert it must show now, and the editor hears of any change. */
7924
- refreshAlerts(now = Date.now()) {
7925
- this.alerts.prune(now);
7926
- const list2 = this.alerts.list(now);
7927
- for (const r of this.runners.values()) {
7928
- const shown = r.screen.enabled ? this.alerts.forScreen(r.screen, now, r.off) : null;
7929
- r.setAlert(shown, now);
7930
- r.device.setLed?.(...ledFor(shown?.top.level ?? null));
8716
+ /**
8717
+ * Every screen gets the context page it must show now (context.ts), if
8718
+ * any: at most every `CONTEXT_EVERY_MS`, or sooner when data, the running
8719
+ * programs or the config changed.
8720
+ */
8721
+ refreshContext(now = Date.now()) {
8722
+ const wantApps = needsApps(this.config);
8723
+ if (wantApps) this.apps?.poll(now, () => this.contextDirty = true);
8724
+ else this.apps?.stop();
8725
+ if (!this.contextDirty && now - this.contextAt < CONTEXT_EVERY_MS) return;
8726
+ this.contextDirty = false;
8727
+ this.contextAt = now;
8728
+ const working = this.working(now);
8729
+ const env = {
8730
+ now,
8731
+ apps: wantApps ? this.apps?.names ?? null : null,
8732
+ source: (type) => this.hub.data(type),
8733
+ urgent: (page) => this.urgentOn(page, now, working)
8734
+ };
8735
+ this.contextEngine.retain(new Set(this.config.screens.map((s) => s.id)));
8736
+ for (const r of this.runners.values()) {
8737
+ const has = r.screen.enabled && r.screen.pages.some((p) => p.showWhen?.length);
8738
+ const pick2 = has ? this.contextEngine.step(r.screen, matchingPages(r.screen, env, working), now) : null;
8739
+ const was = r.context;
8740
+ r.setContext(pick2);
8741
+ if (pick2?.page !== was?.page || pick2?.leaving !== was?.leaving) {
8742
+ if (pick2?.page !== was?.page) this.log(`screen:${r.screen.name}`, pick2 ? `context page ${pick2.page}: ${describeReason(pick2.reason)}` : "context page gone: back to the rotation");
8743
+ this.emit("screen", { screenId: r.screen.id, context: pick2 });
8744
+ }
8745
+ }
8746
+ }
8747
+ /** The type of a widget on `page` that is urgent now (as its tile sees it), or null. */
8748
+ urgentOn(page, now, working) {
8749
+ if (this.demoMode) return null;
8750
+ const cfg = this.config;
8751
+ for (const tile of page.tiles) {
8752
+ for (const w of tile.widgets) {
8753
+ const def = this.registry.widget(w.type);
8754
+ if (!def?.urgent || w.disabled || !whenMatches(w.when, working)) continue;
8755
+ const options2 = def.options ? validate(def.options, w.options).value : {};
8756
+ const state = { options: options2, data: this.fetches.data(w.id), sources: this.hub.pick(def.sources), now, working, workday: cfg.workday, ...cfg.location ? { location: cfg.location } : {} };
8757
+ if (tileState(def, w, state).urgent) return w.type;
8758
+ }
8759
+ }
8760
+ return null;
8761
+ }
8762
+ /** Every screen gets the alert it must show now, and the editor hears of any change. */
8763
+ refreshAlerts(now = Date.now()) {
8764
+ this.alerts.prune(now);
8765
+ const list2 = this.alerts.list(now);
8766
+ for (const r of this.runners.values()) {
8767
+ const shown2 = r.screen.enabled ? this.alerts.forScreen(r.screen, now, r.off) : null;
8768
+ r.setAlert(shown2, now);
8769
+ r.device.setLed?.(...ledFor(shown2?.top.level ?? null));
7931
8770
  }
7932
8771
  const sig = JSON.stringify(list2);
7933
8772
  if (sig === this.alertsSig) return;
7934
8773
  this.alertsSig = sig;
7935
8774
  this.emit("alerts", list2);
7936
8775
  }
8776
+ /** Remote screens' backlights: off while Kiosko shows them black, the night's brightness in their night window (remote/backlight.ts). */
8777
+ refreshBacklights(now = Date.now()) {
8778
+ for (const r of this.runners.values()) {
8779
+ if (!r.device.setDim) continue;
8780
+ r.device.setDim(dimFor(r.screen, { sleeping: r.off || !!r.lastInfo?.sleeping, alert: !!r.alert }, now));
8781
+ }
8782
+ }
7937
8783
  /** Alerts not seen nor expired, highest first; the snoozed ones too. */
7938
8784
  listAlerts(now = Date.now()) {
7939
8785
  return this.alerts.list(now);
@@ -7992,6 +8838,8 @@ var Runtime = class extends EventEmitter2 {
7992
8838
  name: r.screen.name,
7993
8839
  page: r.page?.id ?? null,
7994
8840
  pinned: r.pinned,
8841
+ /** The context page that has the screen, and why (see context.ts); null: none. */
8842
+ context: r.context,
7995
8843
  interlude: r.interlude?.type ?? null,
7996
8844
  /** The interlude is being played from the Play page. */
7997
8845
  playing: r.interlude?.play ?? false,
@@ -8041,7 +8889,7 @@ var Runtime = class extends EventEmitter2 {
8041
8889
  now: o.now ?? Date.now(),
8042
8890
  working: this.working(o.now ?? Date.now()),
8043
8891
  dataOf: (inst) => this.fetches.data(inst.id),
8044
- sourcesOf: (types2) => this.hub.pick(types2),
8892
+ sourcesOf: (types2, profile) => this.hub.pick(types2, this.config, profile),
8045
8893
  preview: true,
8046
8894
  demo: o.demo ?? true,
8047
8895
  ...o.forceShown ? { forceShown: o.forceShown } : {},
@@ -8074,6 +8922,10 @@ function memory() {
8074
8922
  return { heapBytes: 0, rssBytes: 0 };
8075
8923
  }
8076
8924
  }
8925
+ function describeReason(r) {
8926
+ const parts = [r.app && `${r.app} running`, r.source && `${r.source}${r.path ? ` ${r.path}` : ""} = ${r.value}`, r.time && `time ${r.time}`, r.urgent && `${r.urgent} urgent`].filter(Boolean);
8927
+ return [r.label, parts.join(", ")].filter(Boolean).join(": ");
8928
+ }
8077
8929
  function withLook(cfg, look) {
8078
8930
  return { ...cfg, ...look.theme ? { theme: look.theme } : {}, ...look.locale ? { locale: look.locale } : {} };
8079
8931
  }
@@ -8226,6 +9078,7 @@ function pluginManifest(def, o = {}) {
8226
9078
  ...s.description ? { description: s.description } : {},
8227
9079
  polled: !!s.read,
8228
9080
  ...s.read && s.intervalMs ? { intervalMs: s.intervalMs } : {},
9081
+ ...s.profiles === true ? { profiles: true } : {},
8229
9082
  options: s.options ? toJsonSchema(s.options) : null
8230
9083
  })),
8231
9084
  interludes: (def.interludes ?? []).map((i) => ({ type: `${def.id}/${i.id}`, name: i.name, ...i.description ? { description: i.description } : {}, ...i.icon ? { icon: i.icon } : {}, fps: i.fps, ...i.input ? { input: true } : {}, ...i.preview ? { preview: i.preview } : {} })),
@@ -8502,13 +9355,13 @@ var Registry = class {
8502
9355
  }
8503
9356
  /** What the editor needs to know about every widget, source and interlude (JSON-safe). */
8504
9357
  catalog(locale) {
8505
- const L = (x) => localize(x, locale);
9358
+ const L3 = (x) => localize(x, locale);
8506
9359
  const has = (type) => !!(this.widget(type) ?? this.source(type) ?? this.interlude(type));
8507
9360
  return this.list().map(({ def, origin, enabled }) => ({
8508
9361
  id: def.id,
8509
- name: L(def.name),
9362
+ name: L3(def.name),
8510
9363
  version: def.version,
8511
- description: L(def.description),
9364
+ description: L3(def.description),
8512
9365
  author: def.author,
8513
9366
  homepage: def.homepage,
8514
9367
  repository: def.repository,
@@ -8525,15 +9378,15 @@ var Registry = class {
8525
9378
  optional: (def.optional ?? []).map((type) => ({ type, plugin: pluginOf(type), ok: has(type) })),
8526
9379
  templates: (def.templates ?? []).map((tp) => {
8527
9380
  const tiles = (list2) => list2?.map((tile) => ({ ...tile, widgets: tile.widgets.map((w) => typeof w === "string" ? fullType(def.id, w) : [fullType(def.id, w[0]), w[1]]) }));
8528
- return { id: `${def.id}/${tp.id}`, name: L(tp.name), icon: tp.icon ?? "layout-template", wide: tiles(tp.wide), square: tiles(tp.square), tall: tiles(tp.tall) };
9381
+ return { id: `${def.id}/${tp.id}`, name: L3(tp.name), icon: tp.icon ?? "layout-template", wide: tiles(tp.wide), square: tiles(tp.square), tall: tiles(tp.tall) };
8529
9382
  }),
8530
9383
  builtin: origin === "builtin",
8531
9384
  origin,
8532
9385
  enabled,
8533
9386
  widgets: (def.widgets ?? []).map((w) => ({
8534
9387
  type: `${def.id}/${w.id}`,
8535
- name: L(w.name),
8536
- description: L(w.description),
9388
+ name: L3(w.name),
9389
+ description: L3(w.description),
8537
9390
  icon: w.icon,
8538
9391
  category: w.category ?? "info",
8539
9392
  tags: w.tags ?? [],
@@ -8551,9 +9404,9 @@ var Registry = class {
8551
9404
  })),
8552
9405
  sources: (def.sources ?? []).map((s) => {
8553
9406
  const field = sourceOptionsField(s);
8554
- return { type: `${def.id}/${s.id}`, name: L(s.name), description: L(s.description), options: field ? toJsonSchema(field) : null, intervalMs: s.read ? sourceTiming(s).intervalMs : null, polled: !!s.read, background: canRunInBackground(s) };
9407
+ return { type: `${def.id}/${s.id}`, name: L3(s.name), description: L3(s.description), options: field ? toJsonSchema(field) : null, intervalMs: s.read ? sourceTiming(s).intervalMs : null, polled: !!s.read, background: canRunInBackground(s), profiles: acceptsProfiles(s) };
8555
9408
  }),
8556
- interludes: (def.interludes ?? []).map((i) => ({ type: `${def.id}/${i.id}`, name: L(i.name), description: L(i.description), icon: i.icon, fps: i.fps, input: !!i.input, options: i.options ? toJsonSchema(i.options) : null }))
9409
+ interludes: (def.interludes ?? []).map((i) => ({ type: `${def.id}/${i.id}`, name: L3(i.name), description: L3(i.description), icon: i.icon, fps: i.fps, input: !!i.input, options: i.options ? toJsonSchema(i.options) : null }))
8557
9410
  }));
8558
9411
  }
8559
9412
  };
@@ -8744,8 +9597,8 @@ function lintPlugin(def) {
8744
9597
  }
8745
9598
  if (!declared.includes("en")) add2("error", "plugin", "languages: English (`en`) is the one every text falls back to: list it, and write every text in it");
8746
9599
  if (new Set(declared).size !== declared.length) add2("warn", "plugin", "languages: a language is listed twice");
8747
- const own = languagesOf({ ...def, widgets: def.widgets?.map(bare), sources: def.sources?.map(bare), interludes: def.interludes?.map(bare) });
8748
- const unlisted = own.filter((l) => !declared.includes(l));
9600
+ const own2 = languagesOf({ ...def, widgets: def.widgets?.map(bare), sources: def.sources?.map(bare), interludes: def.interludes?.map(bare) });
9601
+ const unlisted = own2.filter((l) => !declared.includes(l));
8749
9602
  if (unlisted.length) add2("warn", "plugin", `its texts come in ${unlisted.join(", ")} too, which \`languages\` doesn't list`);
8750
9603
  }
8751
9604
  const langs = declared?.length ? declared : used;
@@ -8820,65 +9673,6 @@ function lintPlugin(def) {
8820
9673
  import { readFileSync as readFileSync4 } from "node:fs";
8821
9674
  import { homedir as homedir3 } from "node:os";
8822
9675
  import { join as join7 } from "node:path";
8823
-
8824
- // packages/core/src/kiosko-release.ts
8825
- var GITHUB_REPO = "kiosko-lcd/kiosko";
8826
- var GITHUB_API = "https://api.github.com";
8827
- var releasePage = (version) => `https://github.com/${GITHUB_REPO}/releases/tag/v${version}`;
8828
- var windowsInstallerName = (version) => `Kiosko-Setup-${version}-x64.exe`;
8829
- var releaseAsset = (version, name2) => `https://github.com/${GITHUB_REPO}/releases/download/v${version}/${name2}`;
8830
- var NOTES_MAX_CHARS = 3e3;
8831
- var NOTES_MAX_RELEASES = 10;
8832
- var stable = (v) => {
8833
- const x = parseVersion(v);
8834
- return !!x && !x[3];
8835
- };
8836
- var tagVersion = (tag) => {
8837
- const v = (tag ?? "").replace(/^v/, "");
8838
- return parseVersion(v) ? v : null;
8839
- };
8840
- function trimNotes(body2, max = NOTES_MAX_CHARS) {
8841
- const clean = body2.replace(/<!--[\s\S]*?-->/g, "").replace(/\r\n?/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
8842
- if (clean.length <= max) return { body: clean, truncated: false };
8843
- const cut = clean.lastIndexOf("\n", max);
8844
- return { body: clean.slice(0, cut > max / 2 ? cut : max).trimEnd(), truncated: true };
8845
- }
8846
- function versionsBetween(all, current, latest) {
8847
- return all.filter((v) => stable(v) && compareVersions(v, current) > 0 && compareVersions(v, latest) <= 0).sort((a, b) => compareVersions(b, a));
8848
- }
8849
- async function kioskoReleaseNotes(current, latest, o) {
8850
- const fromNpm = versionsBetween(o.npmVersions ?? [latest], current, latest).slice(0, NOTES_MAX_RELEASES).map((version) => ({ version, url: releasePage(version) }));
8851
- let list2;
8852
- try {
8853
- const r = await o.http.json(`${o.api ?? GITHUB_API}/repos/${GITHUB_REPO}/releases?per_page=30`, { headers: { Accept: "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28" }, ...o.signal ? { signal: o.signal } : {} });
8854
- if (!Array.isArray(r.data)) throw new Error("GitHub did not answer with a list of releases");
8855
- list2 = r.data;
8856
- } catch (err) {
8857
- return { from: "npm", releases: fromNpm, error: err instanceof Error ? err.message : String(err) };
8858
- }
8859
- const byVersion = /* @__PURE__ */ new Map();
8860
- for (const g of list2) {
8861
- const v = tagVersion(g.tag_name);
8862
- if (v && !g.draft && !g.prerelease && stable(v)) byVersion.set(v, g);
8863
- }
8864
- const versions = [.../* @__PURE__ */ new Set([...fromNpm.map((r) => r.version), ...versionsBetween([...byVersion.keys()], current, latest)])].sort((a, b) => compareVersions(b, a)).slice(0, NOTES_MAX_RELEASES);
8865
- const releases2 = versions.map((version) => {
8866
- const g = byVersion.get(version);
8867
- if (!g) return { version, url: releasePage(version) };
8868
- const notes = g.body ? trimNotes(g.body) : null;
8869
- const url2 = g.html_url?.startsWith(`https://github.com/${GITHUB_REPO}/`) ? g.html_url : releasePage(version);
8870
- return { version, ...g.name ? { name: g.name } : {}, ...notes?.body ? { body: notes.body, ...notes.truncated ? { truncated: true } : {} } : {}, url: url2, ...g.published_at ? { date: g.published_at } : {} };
8871
- });
8872
- const newest = byVersion.get(latest);
8873
- const name2 = windowsInstallerName(latest);
8874
- const asset = (n) => newest?.assets?.find((a) => a.name === n)?.browser_download_url;
8875
- const exe = asset(name2);
8876
- const sha = asset(`${name2}.sha256`);
8877
- const ours = (u) => !!u && u.startsWith(`https://github.com/${GITHUB_REPO}/releases/download/`);
8878
- return { from: "github", releases: releases2, ...ours(exe) && ours(sha) ? { windows: { name: name2, exe, sha256: sha } } : {} };
8879
- }
8880
-
8881
- // packages/core/src/plugin-updates.ts
8882
9676
  var REGISTRY = "https://registry.npmjs.org";
8883
9677
  function npmRegistry(env = process.env, home = homedir3()) {
8884
9678
  const fromEnv = env.npm_config_registry ?? env.NPM_CONFIG_REGISTRY;
@@ -8907,14 +9701,14 @@ function pickUpdate(installed2, p, env) {
8907
9701
  return { id: installed2.id, package: installed2.package, current: installed2.version, latest, ...version ? { version } : {}, ...blocked ? { blocked } : {}, ...unlocks ? { unlockedBy: env.kioskoLatest } : {} };
8908
9702
  }
8909
9703
  async function checkUpdates(plugins, o = {}) {
8910
- const http = o.http ?? createHttp({ agent: "kiosko-updates" });
9704
+ const http2 = o.http ?? createHttp({ agent: "kiosko-updates" });
8911
9705
  const env = { sdk: o.sdk ?? SDK_VERSION, platform: o.platform ?? process.platform };
8912
- const base3 = o.registry ?? npmRegistry();
9706
+ const base4 = o.registry ?? npmRegistry();
8913
9707
  const headers2 = { Accept: "application/vnd.npm.install-v1+json" };
8914
9708
  const errors = [];
8915
9709
  const read = async (pkg) => {
8916
9710
  try {
8917
- return (await http.json(`${base3}/${pkg.replace("/", "%2F")}`, { headers: headers2, ...o.signal ? { signal: o.signal } : {} })).data;
9711
+ return (await http2.json(`${base4}/${pkg.replace("/", "%2F")}`, { headers: headers2, ...o.signal ? { signal: o.signal } : {} })).data;
8918
9712
  } catch (err) {
8919
9713
  errors.push({ package: pkg, error: err instanceof Error ? err.message : String(err) });
8920
9714
  return null;
@@ -8926,7 +9720,7 @@ async function checkUpdates(plugins, o = {}) {
8926
9720
  if (o.kioskoVersion && latest && compareVersions(latest, o.kioskoVersion) > 0) {
8927
9721
  const all = Object.keys(k?.versions ?? {});
8928
9722
  const versions = versionsBetween(all.length ? all : [latest], o.kioskoVersion, latest);
8929
- const notes = o.github === false ? void 0 : await kioskoReleaseNotes(o.kioskoVersion, latest, { http, npmVersions: versions, ...o.github ? { api: o.github } : {}, ...o.signal ? { signal: o.signal } : {} });
9723
+ const notes = o.github === false ? void 0 : await kioskoReleaseNotes(o.kioskoVersion, latest, { http: http2, npmVersions: versions, ...o.github ? { api: o.github } : {}, ...o.signal ? { signal: o.signal } : {} });
8930
9724
  kiosko = { current: o.kioskoVersion, latest, versions, ...notes ? { notes } : {} };
8931
9725
  }
8932
9726
  const picked = plugins.map((pl, i) => found[i] ? pickUpdate(pl, found[i], { ...env, ...kiosko ? { kioskoLatest: kiosko.latest } : {} }) : null);
@@ -8958,7 +9752,7 @@ function addedPermissions(before, after) {
8958
9752
  var MAX_TARBALL_BYTES = 20 * 1024 * 1024;
8959
9753
 
8960
9754
  // packages/core/src/remote/ops.ts
8961
- import { createHash as createHash2 } from "node:crypto";
9755
+ import { createHash as createHash3 } from "node:crypto";
8962
9756
  var CHUNK = 16 * 1024;
8963
9757
  async function session(host, port, key, uid) {
8964
9758
  const s = await openSession(host, port, key, uid);
@@ -8970,7 +9764,7 @@ async function otaUpdate(host, port, key, uid, image2, progress) {
8970
9764
  if (image2[0] !== 233) throw new ScreenError("notFirmware", "not an ESP32 firmware image (.bin)");
8971
9765
  const { wire, session: s } = await session(host, port, key, uid);
8972
9766
  try {
8973
- sendSealed(wire, s, T.OTA_BEGIN, { size: image2.length, sha256: createHash2("sha256").update(image2).digest("hex") });
9767
+ sendSealed(wire, s, T.OTA_BEGIN, { size: image2.length, sha256: createHash3("sha256").update(image2).digest("hex") });
8974
9768
  const next = async () => {
8975
9769
  for (; ; ) {
8976
9770
  const m = await nextSealed(wire, s, 3e4);
@@ -9023,8 +9817,497 @@ async function unpairScreen(host, port, key, uid) {
9023
9817
  }
9024
9818
 
9025
9819
  // plugins/core/src/index.ts
9026
- import { readdir, readFile, stat } from "node:fs/promises";
9820
+ import { readdir as readdir2, readFile as readFile3, stat } from "node:fs/promises";
9821
+ import { join as join9 } from "node:path";
9822
+
9823
+ // plugins/core/src/json.ts
9824
+ import { mkdir, readFile as readFile2, writeFile } from "node:fs/promises";
9027
9825
  import { join as join8 } from "node:path";
9826
+
9827
+ // plugins/core/src/json-format.ts
9828
+ var TONES = ["ok", "info", "warn", "alert", "accent", "dim"];
9829
+ function toNumber(v) {
9830
+ if (typeof v === "number") return Number.isFinite(v) ? v : void 0;
9831
+ if (typeof v === "string" && /^\s*[-+]?(\d+\.?\d*|\.\d+)([eE][-+]?\d+)?\s*$/.test(v)) {
9832
+ const n = Number(v);
9833
+ return Number.isFinite(n) ? n : void 0;
9834
+ }
9835
+ return void 0;
9836
+ }
9837
+ var MAX_TEXT2 = 200;
9838
+ function formatNumber(n, decimals, locale) {
9839
+ const d = Math.max(-1, Math.min(6, Math.round(decimals)));
9840
+ try {
9841
+ return new Intl.NumberFormat(locale, d < 0 ? { maximumFractionDigits: 2 } : { minimumFractionDigits: d, maximumFractionDigits: d }).format(n);
9842
+ } catch {
9843
+ return d < 0 ? String(n) : n.toFixed(d);
9844
+ }
9845
+ }
9846
+ function valueText(v, o) {
9847
+ const n = typeof v === "number" || typeof v === "string" && o.decimals >= 0 ? toNumber(v) : void 0;
9848
+ if (n !== void 0) return formatNumber(n, o.decimals, o.locale);
9849
+ if (v === null || v === void 0 || v === "") return "\u2014";
9850
+ if (typeof v === "string") return v.length > MAX_TEXT2 ? `${v.slice(0, MAX_TEXT2 - 1)}\u2026` : v;
9851
+ if (typeof v === "boolean" || typeof v === "number") return String(v);
9852
+ let s;
9853
+ try {
9854
+ s = JSON.stringify(v);
9855
+ } catch {
9856
+ s = String(v);
9857
+ }
9858
+ return s.length > MAX_TEXT2 ? `${s.slice(0, MAX_TEXT2 - 1)}\u2026` : s;
9859
+ }
9860
+ var TIGHT_UNIT = /^(%|°|′|″|‰)/;
9861
+ function formatValue(v, o) {
9862
+ const text3 = valueText(v, o);
9863
+ if (text3 === "\u2014") return text3;
9864
+ const unit = o.unit.trim();
9865
+ return `${o.prefix}${text3}${unit ? TIGHT_UNIT.test(unit) ? unit : ` ${unit}` : ""}`;
9866
+ }
9867
+ var RULE = /^\s*(>=|<=|!=|==|=|>|<)?\s*(.*?)\s*$/s;
9868
+ function meets(v, when) {
9869
+ const m = RULE.exec(when);
9870
+ if (!m) return false;
9871
+ const op = m[1] ?? (toNumber(m[2]) !== void 0 ? ">=" : "=");
9872
+ const rhs = m[2];
9873
+ if (op === "=" || op === "==" || op === "!=") {
9874
+ const n2 = toNumber(v), r2 = toNumber(rhs);
9875
+ const equal3 = n2 !== void 0 && r2 !== void 0 ? n2 === r2 : String(v ?? "").trim().toLowerCase() === rhs.toLowerCase();
9876
+ return op === "!=" ? !equal3 : equal3;
9877
+ }
9878
+ const n = toNumber(v), r = toNumber(rhs);
9879
+ if (n === void 0 || r === void 0) return false;
9880
+ return op === ">=" ? n >= r : op === ">" ? n > r : op === "<" ? n < r : n <= r;
9881
+ }
9882
+ function toneFor(v, rules) {
9883
+ for (const r of rules) if (r.when.trim() && meets(v, r.when)) return r.tone;
9884
+ return void 0;
9885
+ }
9886
+
9887
+ // plugins/core/src/json-path.ts
9888
+ var MAX_PATH_LENGTH = 300;
9889
+ var MAX_PATH_STEPS = 32;
9890
+ var MAX_PATH_RESULTS = 500;
9891
+ var PathError = class extends Error {
9892
+ constructor(message) {
9893
+ super(message);
9894
+ this.name = "PathError";
9895
+ }
9896
+ };
9897
+ var NAME = /[\p{L}\p{N}_$@-]/u;
9898
+ function parsePath(path) {
9899
+ const p = path.trim();
9900
+ if (p.length > MAX_PATH_LENGTH) throw new PathError(`path longer than ${MAX_PATH_LENGTH} characters`);
9901
+ const steps = [];
9902
+ let i = 0;
9903
+ if (p[0] === "$") i = 1;
9904
+ const push3 = (s) => {
9905
+ if (steps.length >= MAX_PATH_STEPS) throw new PathError(`path with more than ${MAX_PATH_STEPS} steps`);
9906
+ steps.push(s);
9907
+ };
9908
+ let needDot = i === 1;
9909
+ while (i < p.length) {
9910
+ const c = p[i];
9911
+ if (c === ".") {
9912
+ i++;
9913
+ if (p[i] === "*") {
9914
+ push3({ all: true });
9915
+ i++;
9916
+ } else {
9917
+ const start = i;
9918
+ while (i < p.length && NAME.test(p[i])) i++;
9919
+ if (i === start) throw new PathError(`a name is missing after the dot at ${start}`);
9920
+ push3({ key: p.slice(start, i) });
9921
+ }
9922
+ needDot = true;
9923
+ continue;
9924
+ }
9925
+ if (c === "[") {
9926
+ i++;
9927
+ const q3 = p[i];
9928
+ if (q3 === "'" || q3 === '"') {
9929
+ let key = "";
9930
+ i++;
9931
+ for (; ; ) {
9932
+ if (i >= p.length) throw new PathError("a quoted key is not closed");
9933
+ const ch = p[i];
9934
+ if (ch === "\\" && i + 1 < p.length) {
9935
+ key += p[i + 1];
9936
+ i += 2;
9937
+ continue;
9938
+ }
9939
+ if (ch === q3) break;
9940
+ key += ch;
9941
+ i++;
9942
+ }
9943
+ i++;
9944
+ push3({ key });
9945
+ } else if (q3 === "*") {
9946
+ i++;
9947
+ push3({ all: true });
9948
+ } else {
9949
+ const m = /^-?\d{1,9}/.exec(p.slice(i));
9950
+ if (!m) throw new PathError(`expected a number, '*' or a quoted key at ${i}`);
9951
+ i += m[0].length;
9952
+ push3({ index: Number(m[0]) });
9953
+ }
9954
+ if (p[i] !== "]") throw new PathError(`expected ']' at ${i}`);
9955
+ i++;
9956
+ needDot = true;
9957
+ continue;
9958
+ }
9959
+ if (!needDot && NAME.test(c)) {
9960
+ const start = i;
9961
+ while (i < p.length && NAME.test(p[i])) i++;
9962
+ push3({ key: p.slice(start, i) });
9963
+ needDot = true;
9964
+ continue;
9965
+ }
9966
+ throw new PathError(`unexpected '${c}' at ${i}`);
9967
+ }
9968
+ return steps;
9969
+ }
9970
+ var own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
9971
+ function step(v, s, out) {
9972
+ if (v === null || typeof v !== "object") return;
9973
+ if ("all" in s) {
9974
+ for (const x of Array.isArray(v) ? v : Object.values(v)) {
9975
+ if (out.length >= MAX_PATH_RESULTS) return;
9976
+ out.push(x);
9977
+ }
9978
+ return;
9979
+ }
9980
+ if ("index" in s) {
9981
+ if (!Array.isArray(v)) return;
9982
+ const i = s.index < 0 ? v.length + s.index : s.index;
9983
+ if (i >= 0 && i < v.length) out.push(v[i]);
9984
+ return;
9985
+ }
9986
+ if (own(v, s.key)) out.push(v[s.key]);
9987
+ }
9988
+ function readPath(doc, path) {
9989
+ const steps = typeof path === "string" ? parsePath(path) : path;
9990
+ const many = steps.some((s) => "all" in s);
9991
+ let cur = [doc];
9992
+ for (const s of steps) {
9993
+ const next = [];
9994
+ for (const v of cur) {
9995
+ step(v, s, next);
9996
+ if (next.length >= MAX_PATH_RESULTS) break;
9997
+ }
9998
+ cur = next;
9999
+ if (!cur.length) break;
10000
+ }
10001
+ if (many) return { found: cur.length > 0, value: cur };
10002
+ return cur.length ? { found: true, value: cur[0] } : { found: false, value: void 0 };
10003
+ }
10004
+ var keyStep = (k) => /^[A-Za-z_$][\w$-]*$/.test(k) ? `.${k}` : `['${k.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}']`;
10005
+ function leafPaths(doc, max = 8) {
10006
+ const out = [];
10007
+ const walk = (v, at, depth) => {
10008
+ if (out.length >= max) return;
10009
+ if (v !== null && typeof v === "object" && depth < 8) {
10010
+ if (Array.isArray(v)) {
10011
+ if (v.length) walk(v[0], `${at}[0]`, depth + 1);
10012
+ else out.push({ path: at, value: v });
10013
+ return;
10014
+ }
10015
+ const keys = Object.keys(v);
10016
+ if (!keys.length) out.push({ path: at, value: v });
10017
+ for (const k of keys) walk(v[k], at + keyStep(k), depth + 1);
10018
+ return;
10019
+ }
10020
+ out.push({ path: at, value: v });
10021
+ };
10022
+ walk(doc, "$", 0);
10023
+ return out;
10024
+ }
10025
+
10026
+ // plugins/core/src/push-store.ts
10027
+ var PUSH_LIMITS = {
10028
+ /** Largest body a push may send. */
10029
+ maxBytes: 64 * 1024,
10030
+ /** Most payloads kept per name for the charts… */
10031
+ historyItems: 240,
10032
+ /** …and most bytes they may take together. */
10033
+ historyBytes: 64 * 1024,
10034
+ /** Longest `ttlMs` honoured: 30 days. */
10035
+ maxTtlMs: 30 * 24 * 36e5
10036
+ };
10037
+ var PUSH_NAME = /^[a-z0-9][a-z0-9_-]{0,39}$/;
10038
+ var sizeOf = (v) => {
10039
+ try {
10040
+ return JSON.stringify(v)?.length ?? 0;
10041
+ } catch {
10042
+ return Infinity;
10043
+ }
10044
+ };
10045
+ var PushStore = class {
10046
+ names = [];
10047
+ entries = /* @__PURE__ */ new Map();
10048
+ listeners = /* @__PURE__ */ new Set();
10049
+ /** The push names set up (from the config): payloads of names no longer there are dropped. */
10050
+ configure(names) {
10051
+ const next = [...new Set(names.filter((n) => PUSH_NAME.test(n)))].sort();
10052
+ if (next.join("\n") === this.names.join("\n")) return;
10053
+ this.names = next;
10054
+ for (const k of [...this.entries.keys()]) if (!next.includes(k)) this.entries.delete(k);
10055
+ this.changed();
10056
+ }
10057
+ has(name2) {
10058
+ return this.names.includes(name2);
10059
+ }
10060
+ /** Keeps `payload` as the latest of `name` (which must be set up), with its `ttlMs` if it says one. */
10061
+ set(name2, payload, now = Date.now()) {
10062
+ if (!this.has(name2)) throw new Error(`unknown push name: ${name2}`);
10063
+ const ttl = payload && typeof payload === "object" && !Array.isArray(payload) ? payload.ttlMs : void 0;
10064
+ const ttlMs = typeof ttl === "number" && Number.isFinite(ttl) && ttl > 0 ? Math.min(ttl, PUSH_LIMITS.maxTtlMs) : void 0;
10065
+ const old = this.entries.get(name2);
10066
+ const history = [...old?.history ?? [], { at: now, payload }];
10067
+ let bytes = history.reduce((s, r) => s + sizeOf(r.payload), 0);
10068
+ while (history.length > 1 && (history.length > PUSH_LIMITS.historyItems || bytes > PUSH_LIMITS.historyBytes)) bytes -= sizeOf(history.shift().payload);
10069
+ const entry = { at: now, payload, ...ttlMs ? { expiresAt: now + ttlMs } : {}, history };
10070
+ this.entries.set(name2, entry);
10071
+ this.changed();
10072
+ return entry;
10073
+ }
10074
+ /** Forgets the payloads of `name` (`DELETE /api/push/<name>`). */
10075
+ clear(name2) {
10076
+ const had = this.entries.delete(name2);
10077
+ if (had) this.changed();
10078
+ return had;
10079
+ }
10080
+ get(name2) {
10081
+ return this.entries.get(name2);
10082
+ }
10083
+ snapshot() {
10084
+ return { hooks: Object.fromEntries(this.names.map((n) => [n, this.entries.get(n) ?? null])) };
10085
+ }
10086
+ /** Calls `fn` with a new snapshot on every change; returns what stops it. */
10087
+ subscribe(fn) {
10088
+ this.listeners.add(fn);
10089
+ return () => this.listeners.delete(fn);
10090
+ }
10091
+ /** The entries, to keep on disk. */
10092
+ dump() {
10093
+ return Object.fromEntries(this.entries);
10094
+ }
10095
+ /** Entries kept on disk, back (those of names not set up are ignored, malformed ones too). */
10096
+ load(saved) {
10097
+ if (!saved || typeof saved !== "object") return;
10098
+ for (const [name2, e] of Object.entries(saved)) {
10099
+ if (!this.has(name2) || !e || typeof e !== "object") continue;
10100
+ const { at, payload, expiresAt, history } = e;
10101
+ if (typeof at !== "number") continue;
10102
+ const hist = Array.isArray(history) ? history.filter((r) => !!r && typeof r === "object" && typeof r.at === "number").slice(-PUSH_LIMITS.historyItems) : [];
10103
+ this.entries.set(name2, { at, payload, ...typeof expiresAt === "number" ? { expiresAt } : {}, history: hist.length ? hist : [{ at, payload }] });
10104
+ }
10105
+ this.changed();
10106
+ }
10107
+ changed() {
10108
+ if (!this.listeners.size) return;
10109
+ const snap = this.snapshot();
10110
+ for (const fn of this.listeners) fn(snap);
10111
+ }
10112
+ };
10113
+ var pushes = new PushStore();
10114
+ var live = (e, now) => !!e && (e.expiresAt === void 0 || e.expiresAt > now);
10115
+
10116
+ // plugins/core/src/json.ts
10117
+ var L = (en2, es, de, hant, hans) => ({ en: en2, es, de, "zh-Hant": hant, "zh-Hans": hans });
10118
+ var PUSH_SOURCE = "core/push";
10119
+ var TONE_LABELS = {
10120
+ ok: L("Green (fine)", "Verde (bien)", "Gr\xFCn (gut)", "\u7DA0\u8272\uFF08\u6B63\u5E38\uFF09", "\u7EFF\u8272\uFF08\u6B63\u5E38\uFF09"),
10121
+ info: L("Blue (note)", "Azul (aviso)", "Blau (Hinweis)", "\u85CD\u8272\uFF08\u63D0\u793A\uFF09", "\u84DD\u8272\uFF08\u63D0\u793A\uFF09"),
10122
+ warn: L("Amber (watch)", "\xC1mbar (ojo)", "Bernstein (aufpassen)", "\u7425\u73C0\u8272\uFF08\u6CE8\u610F\uFF09", "\u7425\u73C0\u8272\uFF08\u6CE8\u610F\uFF09"),
10123
+ alert: L("Red (needs you)", "Rojo (te necesita)", "Rot (braucht dich)", "\u7D05\u8272\uFF08\u9700\u8981\u8655\u7406\uFF09", "\u7EA2\u8272\uFF08\u9700\u8981\u5904\u7406\uFF09"),
10124
+ accent: L("Accent", "Acento", "Akzent", "\u5F37\u8ABF\u8272", "\u5F3A\u8C03\u8272"),
10125
+ dim: L("Dim", "Tenue", "Ged\xE4mpft", "\u6DE1\u8272", "\u6697\u6DE1")
10126
+ };
10127
+ var toneColor = (theme, tone) => tone === void 0 ? theme.colors.ink : tone === "dim" ? theme.colors.inkDim : theme.colors[tone];
10128
+ function sourceOptions() {
10129
+ return {
10130
+ url: t.string({
10131
+ format: "url",
10132
+ risk: "network",
10133
+ placeholder: "https://api.example.com/status.json",
10134
+ label: L("URL", "URL", "URL", "URL", "URL"),
10135
+ help: L(
10136
+ "Asked every refresh (the widget's interval). It should answer JSON; plain text is read as one value. {secret} in it becomes the secret below.",
10137
+ "Se consulta en cada refresco (el intervalo del widget). Deber\xEDa responder JSON; el texto plano se lee como un solo valor. {secret} se cambia por el secreto de abajo.",
10138
+ "Wird bei jeder Aktualisierung abgefragt (Intervall des Widgets). Sie sollte JSON liefern; reiner Text gilt als ein Wert. {secret} wird durch das Geheimnis unten ersetzt.",
10139
+ "\u6BCF\u6B21\u91CD\u65B0\u6574\u7406\u6642\u67E5\u8A62\uFF08\u5C0F\u5DE5\u5177\u7684\u9593\u9694\uFF09\u3002\u61C9\u56DE\u50B3 JSON\uFF1B\u7D14\u6587\u5B57\u6703\u7576\u6210\u55AE\u4E00\u6578\u503C\u3002\u5176\u4E2D\u7684 {secret} \u6703\u63DB\u6210\u4E0B\u65B9\u7684\u5BC6\u9470\u3002",
10140
+ "\u6BCF\u6B21\u5237\u65B0\u65F6\u8BF7\u6C42\uFF08\u5C0F\u7EC4\u4EF6\u7684\u95F4\u9694\uFF09\u3002\u5E94\u8FD4\u56DE JSON\uFF1B\u7EAF\u6587\u672C\u4F1A\u5F53\u4F5C\u5355\u4E2A\u503C\u3002\u5176\u4E2D\u7684 {secret} \u4F1A\u66FF\u6362\u4E3A\u4E0B\u65B9\u7684\u5BC6\u94A5\u3002"
10141
+ )
10142
+ }),
10143
+ push: t.string({
10144
+ choices: { source: PUSH_SOURCE, list: "names" },
10145
+ placeholder: "garage",
10146
+ label: L("Or a push name", "O un nombre de push", "Oder ein Push-Name", "\u6216\u63A8\u9001\u540D\u7A31", "\u6216\u63A8\u9001\u540D\u79F0"),
10147
+ help: L(
10148
+ "Instead of a URL: what a script sends to POST /api/push/<name>. Set up push names in Settings \u2192 Push.",
10149
+ "En vez de una URL: lo que un script env\xEDa a POST /api/push/<nombre>. Los nombres se crean en Ajustes \u2192 Push.",
10150
+ "Statt einer URL: was ein Skript an POST /api/push/<name> sendet. Push-Namen legst du unter Einstellungen \u2192 Push an.",
10151
+ "\u53D6\u4EE3 URL\uFF1A\u8173\u672C\u50B3\u9001\u5230 POST /api/push/<\u540D\u7A31> \u7684\u5167\u5BB9\u3002\u63A8\u9001\u540D\u7A31\u5728\u300C\u8A2D\u5B9A \u2192 \u63A8\u9001\u300D\u4E2D\u5EFA\u7ACB\u3002",
10152
+ "\u4EE3\u66FF URL\uFF1A\u811A\u672C\u53D1\u9001\u5230 POST /api/push/<\u540D\u79F0> \u7684\u5185\u5BB9\u3002\u63A8\u9001\u540D\u79F0\u5728\u201C\u8BBE\u7F6E \u2192 \u63A8\u9001\u201D\u4E2D\u521B\u5EFA\u3002"
10153
+ )
10154
+ }),
10155
+ secret: t.string({
10156
+ secret: true,
10157
+ label: L("Secret (token, API key)", "Secreto (token, clave de API)", "Geheimnis (Token, API-Schl\xFCssel)", "\u5BC6\u9470\uFF08\u6B0A\u6756\u3001API \u91D1\u9470\uFF09", "\u5BC6\u94A5\uFF08\u4EE4\u724C\u3001API \u5BC6\u94A5\uFF09"),
10158
+ help: L(
10159
+ 'Sent in the header below (e.g. "Bearer abc123"), or wherever {secret} appears in the URL, headers or body.',
10160
+ "Se env\xEDa en la cabecera de abajo (p. ej. \xABBearer abc123\xBB), o donde aparezca {secret} en la URL, las cabeceras o el cuerpo.",
10161
+ "Wird im Header unten gesendet (z. B. \u201EBearer abc123\u201C) oder dort, wo {secret} in URL, Headern oder Body steht.",
10162
+ "\u653E\u5728\u4E0B\u65B9\u7684\u6A19\u982D\u4E2D\u9001\u51FA\uFF08\u4F8B\u5982\u300CBearer abc123\u300D\uFF09\uFF0C\u6216\u653E\u5728 URL\u3001\u6A19\u982D\u3001\u5167\u6587\u4E2D {secret} \u51FA\u73FE\u7684\u4F4D\u7F6E\u3002",
10163
+ "\u653E\u5728\u4E0B\u65B9\u7684\u8BF7\u6C42\u5934\u4E2D\u53D1\u9001\uFF08\u4F8B\u5982\u201CBearer abc123\u201D\uFF09\uFF0C\u6216\u653E\u5728 URL\u3001\u8BF7\u6C42\u5934\u3001\u8BF7\u6C42\u4F53\u4E2D {secret} \u51FA\u73B0\u7684\u4F4D\u7F6E\u3002"
10164
+ )
10165
+ }),
10166
+ authHeader: t.string({
10167
+ default: "Authorization",
10168
+ advanced: true,
10169
+ label: L("Header for the secret", "Cabecera del secreto", "Header f\xFCr das Geheimnis", "\u5BC6\u9470\u4F7F\u7528\u7684\u6A19\u982D", "\u5BC6\u94A5\u4F7F\u7528\u7684\u8BF7\u6C42\u5934"),
10170
+ help: L("Authorization, X-Api-Key\u2026 Empty: only where {secret} is written.", "Authorization, X-Api-Key\u2026 Vac\xEDa: solo donde est\xE9 {secret}.", "Authorization, X-Api-Key\u2026 Leer: nur dort, wo {secret} steht.", "Authorization\u3001X-Api-Key\u2026 \u7559\u7A7A\uFF1A\u53EA\u653E\u5728 {secret} \u7684\u4F4D\u7F6E\u3002", "Authorization\u3001X-Api-Key\u2026 \u7559\u7A7A\uFF1A\u53EA\u653E\u5728 {secret} \u7684\u4F4D\u7F6E\u3002")
10171
+ }),
10172
+ headers: t.map({ advanced: true, label: L("Other headers", "Otras cabeceras", "Weitere Header", "\u5176\u4ED6\u6A19\u982D", "\u5176\u4ED6\u8BF7\u6C42\u5934"), keyLabel: L("Header", "Cabecera", "Header", "\u6A19\u982D", "\u8BF7\u6C42\u5934"), valueLabel: L("Value", "Valor", "Wert", "\u503C", "\u503C") }),
10173
+ method: t.enum(["GET", "POST"], { advanced: true, label: L("Method", "M\xE9todo", "Methode", "\u65B9\u6CD5", "\u65B9\u6CD5") }),
10174
+ body: t.string({ multiline: true, advanced: true, placeholder: '{"query": "\u2026"}', label: L("Body (POST)", "Cuerpo (POST)", "Body (POST)", "\u5167\u6587\uFF08POST\uFF09", "\u8BF7\u6C42\u4F53\uFF08POST\uFF09"), help: L("Sent as JSON when it looks like JSON, else as text.", "Se env\xEDa como JSON si lo parece; si no, como texto.", "Wird als JSON gesendet, wenn es danach aussieht, sonst als Text.", "\u770B\u8D77\u4F86\u50CF JSON \u6642\u4EE5 JSON \u9001\u51FA\uFF0C\u5426\u5247\u4EE5\u7D14\u6587\u5B57\u9001\u51FA\u3002", "\u770B\u8D77\u6765\u50CF JSON \u65F6\u6309 JSON \u53D1\u9001\uFF0C\u5426\u5219\u6309\u7EAF\u6587\u672C\u53D1\u9001\u3002") }),
10175
+ timeoutMs: t.duration({ default: 1e4, min: 1e3, max: 6e4, advanced: true, label: L("Give up after", "Abandonar tras", "Aufgeben nach", "\u903E\u6642\u6642\u9593", "\u8D85\u65F6\u65F6\u95F4") }),
10176
+ maxKb: t.integer({ default: 512, min: 1, max: 5120, unit: "KB", advanced: true, label: L("Largest answer", "Respuesta m\xE1s grande", "Gr\xF6\xDFte Antwort", "\u56DE\u61C9\u5927\u5C0F\u4E0A\u9650", "\u54CD\u5E94\u5927\u5C0F\u4E0A\u9650"), help: L("A longer answer is refused, so a wrong URL can't fill the memory.", "Una m\xE1s larga se rechaza, para que una URL equivocada no llene la memoria.", "Eine l\xE4ngere wird abgelehnt, damit eine falsche URL nicht den Speicher f\xFCllt.", "\u8D85\u904E\u7684\u56DE\u61C9\u6703\u88AB\u62D2\u7D55\uFF0C\u4EE5\u514D\u932F\u8AA4\u7684 URL \u585E\u6EFF\u8A18\u61B6\u9AD4\u3002", "\u8D85\u51FA\u7684\u54CD\u5E94\u4F1A\u88AB\u62D2\u7EDD\uFF0C\u4EE5\u514D\u9519\u8BEF\u7684 URL \u5360\u6EE1\u5185\u5B58\u3002") })
10177
+ };
10178
+ }
10179
+ var pathField = (o = {}) => t.string({
10180
+ placeholder: o.placeholder ?? "$.current.temperature_2m",
10181
+ label: o.label ?? L("Path to the value", "Ruta del valor", "Pfad zum Wert", "\u6578\u503C\u8DEF\u5F91", "\u6570\u503C\u8DEF\u5F84"),
10182
+ help: o.help ?? L(
10183
+ "$.a.b, items[0].price, items[-1], ['key with spaces']. Empty: the widget lists the paths it finds.",
10184
+ "$.a.b, items[0].price, items[-1], ['clave con espacios']. Vac\xEDa: el widget ense\xF1a las rutas que encuentra.",
10185
+ "$.a.b, items[0].price, items[-1], ['Schl\xFCssel mit Leerzeichen']. Leer: Das Widget zeigt die gefundenen Pfade.",
10186
+ "$.a.b\u3001items[0].price\u3001items[-1]\u3001['\u542B\u7A7A\u683C\u7684\u9375']\u3002\u7559\u7A7A\uFF1A\u5C0F\u5DE5\u5177\u6703\u5217\u51FA\u627E\u5230\u7684\u8DEF\u5F91\u3002",
10187
+ "$.a.b\u3001items[0].price\u3001items[-1]\u3001['\u542B\u7A7A\u683C\u7684\u952E']\u3002\u7559\u7A7A\uFF1A\u5C0F\u7EC4\u4EF6\u4F1A\u5217\u51FA\u627E\u5230\u7684\u8DEF\u5F84\u3002"
10188
+ )
10189
+ });
10190
+ var formatOptions = () => ({
10191
+ prefix: t.string({ placeholder: "$", label: L("Before the value", "Antes del valor", "Vor dem Wert", "\u6578\u503C\u524D\u7DB4", "\u6570\u503C\u524D\u7F00") }),
10192
+ unit: t.string({ placeholder: "\xB0C", label: L("Unit", "Unidad", "Einheit", "\u55AE\u4F4D", "\u5355\u4F4D") }),
10193
+ decimals: t.integer({ default: -1, min: -1, max: 6, label: L("Decimals", "Decimales", "Nachkommastellen", "\u5C0F\u6578\u4F4D\u6578", "\u5C0F\u6570\u4F4D\u6570"), help: L("-1: as it comes (up to 2).", "-1: tal como viene (hasta 2).", "-1: wie geliefert (bis zu 2).", "-1\uFF1A\u4F9D\u539F\u59CB\u503C\uFF08\u6700\u591A 2 \u4F4D\uFF09\u3002", "-1\uFF1A\u6309\u539F\u59CB\u503C\uFF08\u6700\u591A 2 \u4F4D\uFF09\u3002") }),
10194
+ thresholds: t.list(
10195
+ t.object({
10196
+ when: t.string({ placeholder: ">= 30", label: L("When", "Cuando", "Wenn", "\u689D\u4EF6", "\u6761\u4EF6") }),
10197
+ tone: t.enum(TONES, { default: "warn", label: L("Colour", "Color", "Farbe", "\u984F\u8272", "\u989C\u8272"), labels: TONE_LABELS })
10198
+ }),
10199
+ {
10200
+ max: 8,
10201
+ label: L("Colours by value", "Colores seg\xFAn el valor", "Farben nach Wert", "\u4F9D\u6578\u503C\u8B8A\u8272", "\u6309\u6570\u503C\u53D8\u8272"),
10202
+ help: L(
10203
+ "The first that holds wins: >= 30, > 30, < 0, <= 5, = failed, != ok, or a bare number (meaning >=).",
10204
+ "Gana la primera que se cumple: >= 30, > 30, < 0, <= 5, = failed, != ok, o un n\xFAmero solo (es >=).",
10205
+ "Die erste zutreffende gilt: >= 30, > 30, < 0, <= 5, = failed, != ok oder eine blo\xDFe Zahl (bedeutet >=).",
10206
+ "\u7B2C\u4E00\u500B\u6210\u7ACB\u7684\u689D\u4EF6\u751F\u6548\uFF1A>= 30\u3001> 30\u3001< 0\u3001<= 5\u3001= failed\u3001!= ok\uFF0C\u6216\u55AE\u7368\u4E00\u500B\u6578\u5B57\uFF08\u8868\u793A >=\uFF09\u3002",
10207
+ "\u7B2C\u4E00\u4E2A\u6210\u7ACB\u7684\u6761\u4EF6\u751F\u6548\uFF1A>= 30\u3001> 30\u3001< 0\u3001<= 5\u3001= failed\u3001!= ok\uFF0C\u6216\u5355\u72EC\u4E00\u4E2A\u6570\u5B57\uFF08\u8868\u793A >=\uFF09\u3002"
10208
+ )
10209
+ }
10210
+ )
10211
+ });
10212
+ var http = createHttp({ agent: "kiosko-core" });
10213
+ var recent = /* @__PURE__ */ new Map();
10214
+ var SHARE_MS = 2e3;
10215
+ var fill = (s, secret) => s.replace(/\{secret\}/g, secret);
10216
+ function requestOf(o) {
10217
+ const placed = [o.url, o.body, ...Object.keys(o.headers), ...Object.values(o.headers)].some((s) => s.includes("{secret}"));
10218
+ const url2 = o.url.includes("{secret}") ? o.url.replace(/\{secret\}/g, encodeURIComponent(o.secret)) : o.url.trim();
10219
+ const headers2 = {};
10220
+ for (const [k, v] of Object.entries(o.headers)) if (k.trim()) headers2[k.trim()] = fill(String(v), o.secret);
10221
+ if (o.secret && !placed && o.authHeader.trim()) headers2[o.authHeader.trim()] = o.secret;
10222
+ const body2 = o.method === "POST" && o.body.trim() ? fill(o.body, o.secret) : void 0;
10223
+ if (body2 !== void 0 && !Object.keys(headers2).some((k) => k.toLowerCase() === "content-type")) headers2["Content-Type"] = /^\s*[[{]/.test(body2) ? "application/json" : "text/plain; charset=utf-8";
10224
+ return { url: url2, method: o.method, headers: headers2, ...body2 !== void 0 ? { body: body2 } : {} };
10225
+ }
10226
+ function parseBody(text3) {
10227
+ try {
10228
+ return JSON.parse(text3);
10229
+ } catch {
10230
+ return text3.trim();
10231
+ }
10232
+ }
10233
+ async function requestJson(o, signal) {
10234
+ const req = requestOf(o);
10235
+ if (!/^https?:\/\//i.test(req.url)) throw new Error("the URL must start with http:// or https://");
10236
+ const key = JSON.stringify([req, o.maxKb]);
10237
+ const now = Date.now();
10238
+ for (const [k, r] of recent) if (now - r.at > SHARE_MS) recent.delete(k);
10239
+ const hit = recent.get(key);
10240
+ if (hit) return hit.doc;
10241
+ const timeout = AbortSignal.timeout(o.timeoutMs);
10242
+ const doc = http.text(req.url, { signal: AbortSignal.any([signal, timeout]), method: req.method, headers: { Accept: "application/json, text/plain;q=0.8, */*;q=0.5", ...req.headers }, ...req.body !== void 0 ? { body: req.body } : {}, maxBytes: o.maxKb * 1024 }).then((r) => parseBody(r.data));
10243
+ recent.set(key, { at: now, doc });
10244
+ doc.catch(() => recent.delete(key));
10245
+ return doc;
10246
+ }
10247
+ function pushedDoc(sources, name2, now) {
10248
+ const e = sources[PUSH_SOURCE]?.hooks?.[name2.trim()];
10249
+ return live(e, now) ? { found: true, doc: e.payload, at: e.at } : { found: false, doc: void 0 };
10250
+ }
10251
+ function hintsOf(doc, max = 6) {
10252
+ return leafPaths(doc, max).map((l) => `${l.path} = ${valueText(l.value, { decimals: -1, locale: "en" }).slice(0, 40)}`);
10253
+ }
10254
+ function pick(doc, path) {
10255
+ if (!path.trim()) return { found: false, hints: hintsOf(doc) };
10256
+ try {
10257
+ const r = readPath(doc, path);
10258
+ return r.found ? { found: true, value: r.value } : { found: false, hints: hintsOf(doc) };
10259
+ } catch (err) {
10260
+ return { found: false, error: err instanceof Error ? err.message : String(err) };
10261
+ }
10262
+ }
10263
+ var MAX_POINTS = 500;
10264
+ var SAME_POINT_MS = 2e3;
10265
+ var histories = /* @__PURE__ */ new Map();
10266
+ function hash(s) {
10267
+ let h = 2166136261;
10268
+ for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619) >>> 0;
10269
+ return h.toString(36);
10270
+ }
10271
+ function addPoint(series, at, v, max) {
10272
+ const last2 = series.at(-1);
10273
+ const out = last2 && Math.abs(at - last2[0]) < SAME_POINT_MS ? [...series.slice(0, -1), [at, v]] : [...series, [at, v]];
10274
+ return out.slice(-Math.max(2, Math.min(MAX_POINTS, max)));
10275
+ }
10276
+ async function remember(dir, key, at, v, max) {
10277
+ const file = join8(dir, "json-history", `${hash(key)}.json`);
10278
+ let series = histories.get(key);
10279
+ if (!series) {
10280
+ try {
10281
+ const saved = JSON.parse(await readFile2(file, "utf8"));
10282
+ series = Array.isArray(saved) ? saved.filter((p) => Array.isArray(p) && typeof p[0] === "number" && typeof p[1] === "number") : [];
10283
+ } catch {
10284
+ series = [];
10285
+ }
10286
+ }
10287
+ if (v !== void 0) {
10288
+ series = addPoint(series, at, v, max);
10289
+ await mkdir(join8(dir, "json-history"), { recursive: true });
10290
+ await writeFile(file, JSON.stringify(series));
10291
+ }
10292
+ histories.set(key, series);
10293
+ return series;
10294
+ }
10295
+ function pushedSeries(sources, name2, path, max) {
10296
+ const e = sources[PUSH_SOURCE]?.hooks?.[name2.trim()];
10297
+ if (!e || !path.trim()) return [];
10298
+ let steps;
10299
+ try {
10300
+ steps = parsePath(path);
10301
+ } catch {
10302
+ return [];
10303
+ }
10304
+ const out = [];
10305
+ for (const r of e.history) {
10306
+ const n = toNumber(readPath(r.payload, steps).value);
10307
+ if (n !== void 0) out.push([r.at, n]);
10308
+ }
10309
+ return out.slice(-max);
10310
+ }
9028
10311
  function fit2(g, text3, family, w, h, max = 400) {
9029
10312
  let size = Math.min(max, h);
9030
10313
  g.font = `${size}px "${family}"`;
@@ -9032,6 +10315,522 @@ function fit2(g, text3, family, w, h, max = 400) {
9032
10315
  if (width > w) size = Math.floor(size * w / width);
9033
10316
  return Math.max(8, size);
9034
10317
  }
10318
+ function drawNothing(g, ctx, p) {
10319
+ const { box, kit, theme } = ctx;
10320
+ const size = Math.max(10, Math.min(26, Math.round(box.h / 7)));
10321
+ const font = { size, family: theme.fonts.sans, color: theme.colors.inkDim };
10322
+ kit.drawTracked(g, kit.truncate(g, p.message, box.w, font), box.x, box.y + size * 1.1, font);
10323
+ const hs = Math.max(9, Math.round(size * 0.8));
10324
+ const mono = { size: hs, family: theme.fonts.mono, color: theme.colors.inkFaint };
10325
+ (p.hints ?? []).forEach((h, i) => {
10326
+ const y = box.y + size * 1.1 + (i + 1) * hs * 1.35;
10327
+ if (y < box.y + box.h) kit.drawTracked(g, kit.truncate(g, h, box.w, mono), box.x, y, mono);
10328
+ });
10329
+ }
10330
+ var WAITING = L("Waiting for data\u2026", "Esperando datos\u2026", "Warte auf Daten\u2026", "\u7B49\u5F85\u8CC7\u6599\u4E2D\u2026", "\u7B49\u5F85\u6570\u636E\u4E2D\u2026");
10331
+ var NO_SOURCE = L("Set a URL or a push name", "Pon una URL o un nombre de push", "URL oder Push-Namen angeben", "\u8ACB\u8A2D\u5B9A URL \u6216\u63A8\u9001\u540D\u7A31", "\u8BF7\u8BBE\u7F6E URL \u6216\u63A8\u9001\u540D\u79F0");
10332
+ var NOT_FOUND = L("Nothing at that path. It has:", "No hay nada en esa ruta. Tiene:", "Unter diesem Pfad ist nichts. Vorhanden:", "\u8A72\u8DEF\u5F91\u6C92\u6709\u8CC7\u6599\u3002\u53EF\u7528\u7684\u6709\uFF1A", "\u8BE5\u8DEF\u5F84\u6CA1\u6709\u6570\u636E\u3002\u53EF\u7528\u7684\u6709\uFF1A");
10333
+ var CHOOSE = L("Choose a path. It has:", "Elige una ruta. Tiene:", "W\xE4hle einen Pfad. Vorhanden:", "\u8ACB\u9078\u64C7\u8DEF\u5F91\u3002\u53EF\u7528\u7684\u6709\uFF1A", "\u8BF7\u9009\u62E9\u8DEF\u5F84\u3002\u53EF\u7528\u7684\u6709\uFF1A");
10334
+ var BAD_PATH = L("Wrong path: ", "Ruta incorrecta: ", "Falscher Pfad: ", "\u8DEF\u5F91\u932F\u8AA4\uFF1A", "\u8DEF\u5F84\u9519\u8BEF\uFF1A");
10335
+ var NO_PUSH = L('Nothing pushed to "{name}" yet', "A\xFAn no se ha enviado nada a \xAB{name}\xBB", "Noch nichts an \u201E{name}\u201C gesendet", "\u5C1A\u672A\u6709\u5167\u5BB9\u63A8\u9001\u5230\u300C{name}\u300D", "\u5C1A\u672A\u6709\u5185\u5BB9\u63A8\u9001\u5230\u201C{name}\u201D");
10336
+ function drawCurve(g, ctx, series, b, color2) {
10337
+ if (series.length < 2 || b.w < 4 || b.h < 4) return;
10338
+ const vs = series.map((p) => p[1]);
10339
+ let lo = Math.min(...vs), hi = Math.max(...vs);
10340
+ if (hi === lo) {
10341
+ lo -= 1;
10342
+ hi += 1;
10343
+ }
10344
+ const t0 = series[0][0], t1 = series.at(-1)[0];
10345
+ const span = t1 - t0 || 1;
10346
+ const lw = Math.max(2, Math.round(b.h / 24));
10347
+ const xy = (p) => [b.x + (p[0] - t0) / span * b.w, b.y + lw / 2 + (1 - (p[1] - lo) / (hi - lo)) * (b.h - lw)];
10348
+ const pts = series.map(xy);
10349
+ g.save();
10350
+ g.beginPath();
10351
+ g.moveTo(pts[0][0], b.y + b.h);
10352
+ for (const [x, y] of pts) g.lineTo(x, y);
10353
+ g.lineTo(pts.at(-1)[0], b.y + b.h);
10354
+ g.closePath();
10355
+ g.fillStyle = /^#[0-9a-f]{6}$/i.test(color2) ? ctx.kit.css(ctx.kit.hex(color2), 0.18) : color2;
10356
+ g.fill();
10357
+ g.beginPath();
10358
+ pts.forEach(([x, y], i) => i ? g.lineTo(x, y) : g.moveTo(x, y));
10359
+ g.strokeStyle = color2;
10360
+ g.lineWidth = lw;
10361
+ g.lineJoin = "round";
10362
+ g.lineCap = "round";
10363
+ g.stroke();
10364
+ const [lx, ly] = pts.at(-1);
10365
+ g.fillStyle = color2;
10366
+ g.beginPath();
10367
+ g.arc(lx, ly, lw * 1.4, 0, Math.PI * 2);
10368
+ g.fill();
10369
+ g.restore();
10370
+ }
10371
+ var jsonValue = defineWidget({
10372
+ id: "json",
10373
+ name: L("JSON value", "Valor JSON", "JSON-Wert", "JSON \u6578\u503C", "JSON \u6570\u503C"),
10374
+ description: L(
10375
+ "One number or word from any URL that answers JSON, or from a push: big, with its unit, colours by value and a curve of its history.",
10376
+ "Un n\xFAmero o una palabra de cualquier URL que responda JSON, o de un push: grande, con su unidad, colores seg\xFAn el valor y una curva con su hist\xF3rico.",
10377
+ "Eine Zahl oder ein Wort von einer beliebigen URL, die JSON liefert, oder aus einem Push: gro\xDF, mit Einheit, Farben nach Wert und einer Kurve des Verlaufs.",
10378
+ "\u4F86\u81EA\u4EFB\u4F55\u56DE\u50B3 JSON \u7684 URL \u6216\u63A8\u9001\u7684\u4E00\u500B\u6578\u5B57\u6216\u6587\u5B57\uFF1A\u5927\u5B57\u986F\u793A\uFF0C\u9644\u55AE\u4F4D\u3001\u4F9D\u6578\u503C\u8B8A\u8272\uFF0C\u4EE5\u53CA\u6B77\u53F2\u66F2\u7DDA\u3002",
10379
+ "\u6765\u81EA\u4EFB\u4F55\u8FD4\u56DE JSON \u7684 URL \u6216\u63A8\u9001\u7684\u4E00\u4E2A\u6570\u5B57\u6216\u6587\u5B57\uFF1A\u5927\u5B57\u663E\u793A\uFF0C\u9644\u5355\u4F4D\u3001\u6309\u6570\u503C\u53D8\u8272\uFF0C\u4EE5\u53CA\u5386\u53F2\u66F2\u7EBF\u3002"
10380
+ ),
10381
+ icon: "braces",
10382
+ category: "dev",
10383
+ tags: ["rest", "api", "json", "webhook", "push"],
10384
+ size: { min: { w: 120, h: 80 }, preferred: { w: 320, h: 220 } },
10385
+ sources: [PUSH_SOURCE],
10386
+ options: t.object({
10387
+ ...sourceOptions(),
10388
+ select: pathField(),
10389
+ label: t.string({ placeholder: "Temperature", label: L("Label", "Etiqueta", "Beschriftung", "\u6A19\u7C64", "\u6807\u7B7E"), help: L("A few words above the value. The tile's title works too.", "Unas palabras encima del valor. Tambi\xE9n vale el t\xEDtulo de la tesela.", "Ein paar Worte \xFCber dem Wert. Der Titel der Kachel geht auch.", "\u6578\u503C\u4E0A\u65B9\u7684\u5E7E\u500B\u5B57\u3002\u4E5F\u53EF\u4EE5\u7528\u65B9\u683C\u7684\u6A19\u984C\u3002", "\u6570\u503C\u4E0A\u65B9\u7684\u51E0\u4E2A\u5B57\u3002\u4E5F\u53EF\u4EE5\u7528\u683C\u5B50\u7684\u6807\u9898\u3002") }),
10390
+ ...formatOptions(),
10391
+ chart: t.enum(["below", "none"], { label: L("History curve", "Curva del hist\xF3rico", "Verlaufskurve", "\u6B77\u53F2\u66F2\u7DDA", "\u5386\u53F2\u66F2\u7EBF"), labels: { below: L("Under the value", "Debajo del valor", "Unter dem Wert", "\u5728\u6578\u503C\u4E0B\u65B9", "\u5728\u6570\u503C\u4E0B\u65B9"), none: L("None", "Ninguna", "Keine", "\u4E0D\u986F\u793A", "\u4E0D\u663E\u793A") } }),
10392
+ points: t.integer({ default: 60, min: 5, max: MAX_POINTS, advanced: true, label: L("Points in the curve", "Puntos de la curva", "Punkte der Kurve", "\u66F2\u7DDA\u9EDE\u6578", "\u66F2\u7EBF\u70B9\u6570"), help: L("One per refresh (or per push).", "Uno por refresco (o por push).", "Einer pro Aktualisierung (oder pro Push).", "\u6BCF\u6B21\u91CD\u65B0\u6574\u7406\uFF08\u6216\u6BCF\u6B21\u63A8\u9001\uFF09\u4E00\u9EDE\u3002", "\u6BCF\u6B21\u5237\u65B0\uFF08\u6216\u6BCF\u6B21\u63A8\u9001\uFF09\u4E00\u4E2A\u70B9\u3002") })
10393
+ }),
10394
+ intervalMs: 6e4,
10395
+ timeoutMs: 65e3,
10396
+ async fetch({ options: options2, signal, cacheDir }) {
10397
+ if (options2.push.trim() || !options2.url.trim()) return null;
10398
+ const doc = await requestJson(options2, signal);
10399
+ const picked = pick(doc, options2.select);
10400
+ const at = Date.now();
10401
+ const n = picked.found ? toNumber(picked.value) : void 0;
10402
+ const series = options2.chart === "none" ? [] : await remember(cacheDir, JSON.stringify([requestOf(options2).url, options2.method, options2.body, options2.select]), at, n, options2.points).catch(() => []);
10403
+ return { at, picked, series };
10404
+ },
10405
+ redraw: "minute",
10406
+ render(g, ctx) {
10407
+ const { box, options: options2, theme, kit, now, sources } = ctx;
10408
+ let picked;
10409
+ let series = [];
10410
+ if (options2.push.trim()) {
10411
+ const p = pushedDoc(sources, options2.push, now);
10412
+ if (!p.found) return drawNothing(g, ctx, { message: ctx.t(NO_PUSH).replace("{name}", options2.push.trim()) });
10413
+ picked = pick(p.doc, options2.select);
10414
+ if (options2.chart !== "none") series = pushedSeries(sources, options2.push, options2.select, options2.points);
10415
+ } else if (!options2.url.trim()) return drawNothing(g, ctx, { message: ctx.t(NO_SOURCE) });
10416
+ else if (ctx.data) {
10417
+ picked = ctx.data.picked;
10418
+ series = ctx.data.series ?? [];
10419
+ }
10420
+ if (!picked) return drawNothing(g, ctx, { message: ctx.t(WAITING) });
10421
+ if (picked.error) return drawNothing(g, ctx, { message: ctx.t(BAD_PATH) + picked.error });
10422
+ if (!picked.found) return drawNothing(g, ctx, { message: ctx.t(options2.select.trim() ? NOT_FOUND : CHOOSE), hints: picked.hints });
10423
+ const tone = toneFor(picked.value, options2.thresholds);
10424
+ const color2 = toneColor(theme, tone);
10425
+ const labelH = options2.label.trim() ? Math.max(10, Math.min(30, Math.round(box.h * 0.14))) : 0;
10426
+ const curve = options2.chart !== "none" && series.length >= 2;
10427
+ const curveH = curve ? Math.round(box.h * 0.32) : 0;
10428
+ if (labelH) kit.drawTracked(g, kit.truncate(g, options2.label.trim(), box.w, { size: labelH, family: theme.fonts.sansBold }), box.x, box.y + labelH * 0.9, { size: labelH, family: theme.fonts.sansBold, color: theme.colors.inkDim, smallCaps: true, tracking: 1 });
10429
+ const text3 = options2.prefix + valueText(picked.value, { decimals: options2.decimals, locale: ctx.locale });
10430
+ const unit = options2.unit.trim();
10431
+ const top = box.y + (labelH ? labelH * 1.4 : 0);
10432
+ const room = box.h - (top - box.y) - (curveH ? curveH + 6 : 0);
10433
+ const numeric = toNumber(picked.value) !== void 0;
10434
+ const family = numeric ? theme.fonts.monoBold : theme.fonts.sansBold;
10435
+ let size = fit2(g, text3, family, box.w * (unit ? 0.78 : 0.98), room * 0.92);
10436
+ let unitSize = Math.max(8, Math.round(size * 0.42));
10437
+ g.font = `${unitSize}px "${theme.fonts.sans}"`;
10438
+ const unitW = unit ? g.measureText(unit).width + size * 0.1 : 0;
10439
+ g.font = `${size}px "${family}"`;
10440
+ let textW = g.measureText(text3).width;
10441
+ if (textW + unitW > box.w) {
10442
+ const k = box.w / (textW + unitW);
10443
+ size = Math.max(8, Math.floor(size * k));
10444
+ unitSize = Math.max(8, Math.round(size * 0.42));
10445
+ g.font = `${size}px "${family}"`;
10446
+ textW = g.measureText(text3).width;
10447
+ }
10448
+ const base4 = top + (room + size * 0.72) / 2;
10449
+ g.fillStyle = color2;
10450
+ g.textAlign = "left";
10451
+ g.fillText(text3, box.x, base4);
10452
+ if (unit) {
10453
+ g.font = `${unitSize}px "${theme.fonts.sans}"`;
10454
+ g.fillStyle = theme.colors.inkDim;
10455
+ g.fillText(unit, box.x + textW + size * 0.1, base4);
10456
+ }
10457
+ if (curve) drawCurve(g, ctx, series, { x: box.x, y: box.y + box.h - curveH, w: box.w, h: curveH }, tone ? color2 : theme.colors.accent);
10458
+ },
10459
+ demo: ({ now }) => ({
10460
+ options: { url: "https://api.open-meteo.com/v1/forecast?latitude=40.4&longitude=-3.7&current=temperature_2m", select: "$.current.temperature_2m", label: "Madrid", unit: "\xB0C", decimals: 1, thresholds: [{ when: ">= 30", tone: "alert" }, { when: ">= 25", tone: "warn" }] },
10461
+ data: { at: now, picked: { found: true, value: 21.4 }, series: Array.from({ length: 24 }, (_, i) => [now - (23 - i) * 36e5, 14 + 7 * Math.sin((i - 6) / 4) + i % 3 * 0.3]) }
10462
+ })
10463
+ });
10464
+ function rowsOf(doc, o) {
10465
+ try {
10466
+ if (o.items.trim()) {
10467
+ const r = readPath(doc, o.items);
10468
+ const items = !r.found ? [] : Array.isArray(r.value) ? r.value : r.value && typeof r.value === "object" ? Object.entries(r.value).map(([k, v]) => ({ key: k, value: v })) : [];
10469
+ if (!r.found) return { rows: null, hints: hintsOf(doc) };
10470
+ const labelSteps = o.itemLabel.trim() ? parsePath(o.itemLabel) : null;
10471
+ const valueSteps = o.itemValue.trim() ? parsePath(o.itemValue) : null;
10472
+ return {
10473
+ rows: items.slice(0, 200).map((it) => ({
10474
+ label: labelSteps ? valueText(readPath(it, labelSteps).value, { decimals: -1, locale: "en" }) : valueText(it, { decimals: -1, locale: "en" }),
10475
+ value: valueSteps ? readPath(it, valueSteps).value : void 0
10476
+ }))
10477
+ };
10478
+ }
10479
+ const fields = o.fields.filter((f) => f.select.trim());
10480
+ if (!fields.length) return { rows: null, hints: hintsOf(doc, 8) };
10481
+ return { rows: fields.map((f) => ({ label: f.label || f.select, value: readPath(doc, f.select).value, ...f.unit ? { unit: f.unit } : {} })) };
10482
+ } catch (err) {
10483
+ return { rows: null, error: err instanceof Error ? err.message : String(err) };
10484
+ }
10485
+ }
10486
+ var jsonList = defineWidget({
10487
+ id: "json-list",
10488
+ name: L("JSON list", "Lista JSON", "JSON-Liste", "JSON \u6E05\u55AE", "JSON \u5217\u8868"),
10489
+ description: L(
10490
+ "Several values from a URL that answers JSON, or from a push: the fields you choose, or the items of a list, each with its value.",
10491
+ "Varios valores de una URL que responda JSON, o de un push: los campos que elijas, o los elementos de una lista, cada uno con su valor.",
10492
+ "Mehrere Werte von einer URL, die JSON liefert, oder aus einem Push: die Felder, die du w\xE4hlst, oder die Eintr\xE4ge einer Liste, jeder mit seinem Wert.",
10493
+ "\u4F86\u81EA\u56DE\u50B3 JSON \u7684 URL \u6216\u63A8\u9001\u7684\u591A\u500B\u6578\u503C\uFF1A\u4F60\u9078\u7684\u6B04\u4F4D\uFF0C\u6216\u6E05\u55AE\u4E2D\u7684\u6BCF\u500B\u9805\u76EE\u53CA\u5176\u6578\u503C\u3002",
10494
+ "\u6765\u81EA\u8FD4\u56DE JSON \u7684 URL \u6216\u63A8\u9001\u7684\u591A\u4E2A\u6570\u503C\uFF1A\u4F60\u9009\u7684\u5B57\u6BB5\uFF0C\u6216\u5217\u8868\u4E2D\u7684\u6BCF\u4E2A\u6761\u76EE\u53CA\u5176\u6570\u503C\u3002"
10495
+ ),
10496
+ icon: "list",
10497
+ category: "dev",
10498
+ tags: ["rest", "api", "json", "webhook", "push"],
10499
+ size: { min: { w: 160, h: 80 }, preferred: { w: 360, h: 240 } },
10500
+ sources: [PUSH_SOURCE],
10501
+ options: t.object({
10502
+ ...sourceOptions(),
10503
+ fields: t.list(
10504
+ t.object({
10505
+ label: t.string({ label: L("Label", "Etiqueta", "Beschriftung", "\u6A19\u7C64", "\u6807\u7B7E") }),
10506
+ select: pathField({ placeholder: "$.current.wind_speed_10m", help: L("$.a.b, items[0].price\u2026", "$.a.b, items[0].price\u2026", "$.a.b, items[0].price\u2026", "$.a.b\u3001items[0].price\u2026", "$.a.b\u3001items[0].price\u2026") }),
10507
+ unit: t.string({ placeholder: "km/h", label: L("Unit", "Unidad", "Einheit", "\u55AE\u4F4D", "\u5355\u4F4D") })
10508
+ }),
10509
+ { max: 30, label: L("Fields", "Campos", "Felder", "\u6B04\u4F4D", "\u5B57\u6BB5"), help: L("One row each. Or leave them empty and give a list below.", "Una fila cada uno. O d\xE9jalos vac\xEDos y da una lista abajo.", "Je eine Zeile. Oder leer lassen und unten eine Liste angeben.", "\u6BCF\u500B\u6B04\u4F4D\u4E00\u5217\u3002\u6216\u7559\u7A7A\uFF0C\u6539\u5728\u4E0B\u65B9\u6307\u5B9A\u6E05\u55AE\u3002", "\u6BCF\u4E2A\u5B57\u6BB5\u4E00\u884C\u3002\u6216\u7559\u7A7A\uFF0C\u6539\u5728\u4E0B\u65B9\u6307\u5B9A\u5217\u8868\u3002") }
10510
+ ),
10511
+ items: pathField({ placeholder: "$.items", label: L("Or a list in it", "O una lista suya", "Oder eine Liste darin", "\u6216\u5176\u4E2D\u7684\u6E05\u55AE", "\u6216\u5176\u4E2D\u7684\u5217\u8868"), help: L("A row per item of the list (or per key of an object) at this path.", "Una fila por elemento de la lista (o por clave de un objeto) en esta ruta.", "Eine Zeile pro Eintrag der Liste (oder pro Schl\xFCssel eines Objekts) unter diesem Pfad.", "\u6B64\u8DEF\u5F91\u4E0B\u6E05\u55AE\u7684\u6BCF\u500B\u9805\u76EE\uFF08\u6216\u7269\u4EF6\u7684\u6BCF\u500B\u9375\uFF09\u5404\u4E00\u5217\u3002", "\u6B64\u8DEF\u5F84\u4E0B\u5217\u8868\u7684\u6BCF\u4E2A\u6761\u76EE\uFF08\u6216\u5BF9\u8C61\u7684\u6BCF\u4E2A\u952E\uFF09\u5404\u4E00\u884C\u3002") }),
10512
+ itemLabel: t.string({ placeholder: "name", label: L("Label of each item", "Etiqueta de cada elemento", "Beschriftung jedes Eintrags", "\u6BCF\u500B\u9805\u76EE\u7684\u6A19\u7C64", "\u6BCF\u4E2A\u6761\u76EE\u7684\u6807\u7B7E"), help: L("A path inside the item (name, user.login; key for an object's keys).", "Una ruta dentro del elemento (name, user.login; key para las claves de un objeto).", "Ein Pfad im Eintrag (name, user.login; key f\xFCr die Schl\xFCssel eines Objekts).", "\u9805\u76EE\u5167\u7684\u8DEF\u5F91\uFF08name\u3001user.login\uFF1B\u7269\u4EF6\u7684\u9375\u7528 key\uFF09\u3002", "\u6761\u76EE\u5185\u7684\u8DEF\u5F84\uFF08name\u3001user.login\uFF1B\u5BF9\u8C61\u7684\u952E\u7528 key\uFF09\u3002") }),
10513
+ itemValue: t.string({ placeholder: "price", label: L("Value of each item", "Valor de cada elemento", "Wert jedes Eintrags", "\u6BCF\u500B\u9805\u76EE\u7684\u6578\u503C", "\u6BCF\u4E2A\u6761\u76EE\u7684\u6570\u503C"), help: L("A path inside the item; empty: only the label.", "Una ruta dentro del elemento; vac\xEDa: solo la etiqueta.", "Ein Pfad im Eintrag; leer: nur die Beschriftung.", "\u9805\u76EE\u5167\u7684\u8DEF\u5F91\uFF1B\u7559\u7A7A\uFF1A\u53EA\u986F\u793A\u6A19\u7C64\u3002", "\u6761\u76EE\u5185\u7684\u8DEF\u5F84\uFF1B\u7559\u7A7A\uFF1A\u53EA\u663E\u793A\u6807\u7B7E\u3002") }),
10514
+ ...formatOptions(),
10515
+ ...listOptions()
10516
+ }),
10517
+ intervalMs: 6e4,
10518
+ timeoutMs: 65e3,
10519
+ async fetch({ options: options2, signal }) {
10520
+ if (options2.push.trim() || !options2.url.trim()) return null;
10521
+ return { at: Date.now(), ...rowsOf(await requestJson(options2, signal), options2) };
10522
+ },
10523
+ render(g, ctx) {
10524
+ const { box, options: options2, theme, kit, now, sources } = ctx;
10525
+ let d = null;
10526
+ if (options2.push.trim()) {
10527
+ const p = pushedDoc(sources, options2.push, now);
10528
+ if (!p.found) return drawNothing(g, ctx, { message: ctx.t(NO_PUSH).replace("{name}", options2.push.trim()) });
10529
+ d = rowsOf(p.doc, options2);
10530
+ } else if (!options2.url.trim()) return drawNothing(g, ctx, { message: ctx.t(NO_SOURCE) });
10531
+ else d = ctx.data ?? null;
10532
+ if (!d) return drawNothing(g, ctx, { message: ctx.t(WAITING) });
10533
+ if (d.error) return drawNothing(g, ctx, { message: ctx.t(BAD_PATH) + d.error });
10534
+ if (!d.rows) return drawNothing(g, ctx, { message: ctx.t(options2.items.trim() ? NOT_FOUND : CHOOSE), hints: d.hints });
10535
+ const rows = d.rows;
10536
+ if (!rows.length) return drawEmpty(g, ctx, ctx.t(L("The list is empty", "La lista est\xE1 vac\xEDa", "Die Liste ist leer", "\u6E05\u55AE\u662F\u7A7A\u7684", "\u5217\u8868\u4E3A\u7A7A")));
10537
+ const plan = listLayout(box, rows.length, options2, { sizes: { "one-line": { min: 18, max: 44 } }, minRows: 2 });
10538
+ const ts = plan.textSize;
10539
+ plan.rows.forEach((row, i) => {
10540
+ const r = rows[i];
10541
+ const base4 = row.y + plan.rowH * 0.5 + ts * 0.36;
10542
+ const hasValue = r.value !== void 0;
10543
+ const value = hasValue ? formatValue(r.value, { decimals: options2.decimals, prefix: options2.prefix, unit: r.unit ?? options2.unit, locale: ctx.locale }) : "";
10544
+ const vfont = { size: ts, family: toNumber(r.value) !== void 0 ? theme.fonts.monoBold : theme.fonts.sansBold, color: toneColor(theme, toneFor(r.value, options2.thresholds)) };
10545
+ const vw = value ? Math.min(box.w * 0.6, kit.measureTracked(g, value, vfont)) : 0;
10546
+ const shown2 = value ? kit.truncate(g, value, vw, vfont) : "";
10547
+ if (shown2) kit.drawTracked(g, shown2, box.x + box.w, base4, { ...vfont, align: "right" });
10548
+ const lfont = { size: ts, family: theme.fonts.sans, color: hasValue ? theme.colors.inkDim : theme.colors.ink };
10549
+ kit.drawTracked(g, kit.truncate(g, r.label, Math.max(1, box.w - vw - ts * 0.6), lfont), box.x, base4, lfont);
10550
+ });
10551
+ drawMore(g, ctx, plan);
10552
+ },
10553
+ demo: () => ({
10554
+ options: { url: "https://api.open-meteo.com/v1/forecast?latitude=40.4&longitude=-3.7&current=temperature_2m,relative_humidity_2m,wind_speed_10m", fields: [{ label: "Temperature", select: "$.current.temperature_2m", unit: "\xB0C" }, { label: "Humidity", select: "$.current.relative_humidity_2m", unit: "%" }, { label: "Wind", select: "$.current.wind_speed_10m", unit: "km/h" }], thresholds: [{ when: ">= 80", tone: "info" }] },
10555
+ data: { at: 0, rows: [{ label: "Temperature", value: 21.4, unit: "\xB0C" }, { label: "Humidity", value: 83, unit: "%" }, { label: "Wind", value: 12.6, unit: "km/h" }] }
10556
+ })
10557
+ });
10558
+ var MAX_SLOTS = 40;
10559
+ function fillTemplate(template, doc, o) {
10560
+ let slots = 0;
10561
+ return template.replace(/\{\{|\}\}|\{([^{}\n]{1,300})\}/g, (m, path) => {
10562
+ if (m === "{{") return "{";
10563
+ if (m === "}}") return "}";
10564
+ if (++slots > MAX_SLOTS) return m;
10565
+ try {
10566
+ const r = readPath(doc, path);
10567
+ return r.found ? Array.isArray(r.value) && /\*/.test(path) ? r.value.map((v) => valueText(v, o)).join(", ") : valueText(r.value, o) : "\u2014";
10568
+ } catch {
10569
+ return m;
10570
+ }
10571
+ });
10572
+ }
10573
+ var jsonText = defineWidget({
10574
+ id: "json-text",
10575
+ name: L("JSON text", "Texto JSON", "JSON-Text", "JSON \u6587\u5B57", "JSON \u6587\u5B57"),
10576
+ description: L(
10577
+ 'A sentence with values from a URL that answers JSON, or from a push: "Backup OK at 03:12", "Deploy #812: passed".',
10578
+ "Una frase con valores de una URL que responda JSON, o de un push: \xABCopia OK a las 03:12\xBB, \xABDespliegue #812: correcto\xBB.",
10579
+ "Ein Satz mit Werten von einer URL, die JSON liefert, oder aus einem Push: \u201EBackup OK um 03:12\u201C, \u201EDeployment #812: bestanden\u201C.",
10580
+ "\u4E00\u53E5\u8A71\uFF0C\u5176\u4E2D\u7684\u6578\u503C\u4F86\u81EA\u56DE\u50B3 JSON \u7684 URL \u6216\u63A8\u9001\uFF1A\u300C\u5099\u4EFD\u5B8C\u6210 03:12\u300D\u3001\u300C\u90E8\u7F72 #812\uFF1A\u901A\u904E\u300D\u3002",
10581
+ "\u4E00\u53E5\u8BDD\uFF0C\u5176\u4E2D\u7684\u6570\u503C\u6765\u81EA\u8FD4\u56DE JSON \u7684 URL \u6216\u63A8\u9001\uFF1A\u201C\u5907\u4EFD\u5B8C\u6210 03:12\u201D\u3001\u201C\u90E8\u7F72 #812\uFF1A\u901A\u8FC7\u201D\u3002"
10582
+ ),
10583
+ icon: "text-quote",
10584
+ category: "dev",
10585
+ tags: ["rest", "api", "json", "webhook", "push"],
10586
+ size: { min: { w: 120, h: 60 }, preferred: { w: 400, h: 160 } },
10587
+ sources: [PUSH_SOURCE],
10588
+ options: t.object({
10589
+ ...sourceOptions(),
10590
+ template: t.string({
10591
+ default: "{$.text}",
10592
+ multiline: true,
10593
+ label: L("Text", "Texto", "Text", "\u6587\u5B57", "\u6587\u5B57"),
10594
+ help: L(
10595
+ "Paths in braces are filled in: Backup {$.status} at {$.time}. {$.items[*].name} lists them all. {{ and }} write braces.",
10596
+ "Las rutas entre llaves se rellenan: Copia {$.status} a las {$.time}. {$.items[*].name} las enumera todas. {{ y }} escriben llaves.",
10597
+ "Pfade in geschweiften Klammern werden ersetzt: Backup {$.status} um {$.time}. {$.items[*].name} z\xE4hlt alle auf. {{ und }} schreiben Klammern.",
10598
+ "\u5927\u62EC\u865F\u4E2D\u7684\u8DEF\u5F91\u6703\u88AB\u586B\u5165\uFF1A\u5099\u4EFD {$.status}\uFF0C\u6642\u9593 {$.time}\u3002{$.items[*].name} \u6703\u5168\u90E8\u5217\u51FA\u3002{{ \u548C }} \u8868\u793A\u5927\u62EC\u865F\u672C\u8EAB\u3002",
10599
+ "\u5927\u62EC\u53F7\u4E2D\u7684\u8DEF\u5F84\u4F1A\u88AB\u586B\u5165\uFF1A\u5907\u4EFD {$.status}\uFF0C\u65F6\u95F4 {$.time}\u3002{$.items[*].name} \u4F1A\u5168\u90E8\u5217\u51FA\u3002{{ \u548C }} \u8868\u793A\u5927\u62EC\u53F7\u672C\u8EAB\u3002"
10600
+ )
10601
+ }),
10602
+ colorFrom: t.string({ advanced: true, placeholder: "$.status", label: L("Colour from", "Color seg\xFAn", "Farbe nach", "\u984F\u8272\u4F9D\u64DA", "\u989C\u8272\u4F9D\u636E"), help: L("The path whose value the colours below look at.", "La ruta cuyo valor miran los colores de abajo.", "Der Pfad, dessen Wert die Farben unten pr\xFCfen.", "\u4E0B\u65B9\u984F\u8272\u898F\u5247\u6240\u53C3\u8003\u7684\u8DEF\u5F91\u3002", "\u4E0B\u65B9\u989C\u8272\u89C4\u5219\u6240\u53C2\u8003\u7684\u8DEF\u5F84\u3002") }),
10603
+ decimals: formatOptions().decimals,
10604
+ thresholds: formatOptions().thresholds,
10605
+ maxSize: t.integer({ default: 64, min: 10, max: 300, unit: "px", slider: true, label: L("Largest letter size", "Tama\xF1o m\xE1ximo de letra", "Gr\xF6\xDFte Schriftgr\xF6\xDFe", "\u6700\u5927\u5B57\u9AD4\u5927\u5C0F", "\u6700\u5927\u5B57\u53F7") }),
10606
+ align: t.enum(["left", "center", "right"], { label: L("Alignment", "Alineaci\xF3n", "Ausrichtung", "\u5C0D\u9F4A", "\u5BF9\u9F50"), labels: { left: L("Left", "Izquierda", "Links", "\u9760\u5DE6", "\u5DE6\u5BF9\u9F50"), center: L("Centre", "Centro", "Mitte", "\u7F6E\u4E2D", "\u5C45\u4E2D"), right: L("Right", "Derecha", "Rechts", "\u9760\u53F3", "\u53F3\u5BF9\u9F50") } })
10607
+ }),
10608
+ intervalMs: 6e4,
10609
+ timeoutMs: 65e3,
10610
+ async fetch({ options: options2, signal, locale }) {
10611
+ if (options2.push.trim() || !options2.url.trim()) return null;
10612
+ return textOf(await requestJson(options2, signal), options2, locale, Date.now());
10613
+ },
10614
+ render(g, ctx) {
10615
+ const { box, options: options2, theme, kit, now, sources } = ctx;
10616
+ let d;
10617
+ if (options2.push.trim()) {
10618
+ const p = pushedDoc(sources, options2.push, now);
10619
+ if (!p.found) return drawNothing(g, ctx, { message: ctx.t(NO_PUSH).replace("{name}", options2.push.trim()) });
10620
+ d = textOf(p.doc, options2, ctx.locale, p.at ?? now);
10621
+ } else if (!options2.url.trim()) return drawNothing(g, ctx, { message: ctx.t(NO_SOURCE) });
10622
+ else d = ctx.data ?? null;
10623
+ if (!d) return drawNothing(g, ctx, { message: ctx.t(WAITING) });
10624
+ const family = theme.fonts.sans;
10625
+ const paragraphs = d.text.split("\n");
10626
+ let size = options2.maxSize;
10627
+ let lines = [];
10628
+ for (; ; size -= 2) {
10629
+ lines = paragraphs.flatMap((p) => p.trim() ? kit.wrapLines(g, p, box.w, 50, { size, family }) : [""]);
10630
+ if (size - 2 < 10 || lines.length * size * 1.2 <= box.h && !lines.some((l) => l.endsWith("\u2026"))) break;
10631
+ }
10632
+ const lh = size * 1.2;
10633
+ const top = box.y + Math.max(0, box.h - lines.length * lh) / 2 + size * 0.85;
10634
+ const x = options2.align === "center" ? box.x + box.w / 2 : options2.align === "right" ? box.x + box.w : box.x;
10635
+ lines.forEach((l, i) => kit.drawTracked(g, l, x, top + i * lh, { size, family, color: toneColor(theme, d.tone), align: options2.align }));
10636
+ },
10637
+ demo: ({ now }) => ({
10638
+ options: { url: "https://nas.local/backup/status.json", template: "Backup {$.status} \xB7 {$.size}", thresholds: [{ when: "!= ok", tone: "alert" }], colorFrom: "$.status" },
10639
+ data: { at: now, text: "Backup ok \xB7 12.4 GB" }
10640
+ })
10641
+ });
10642
+ function textOf(doc, o, locale, at) {
10643
+ const text3 = fillTemplate(o.template, doc, { decimals: o.decimals, locale });
10644
+ let tone;
10645
+ if (o.thresholds.length) {
10646
+ let v = text3;
10647
+ try {
10648
+ if (o.colorFrom.trim()) v = readPath(doc, o.colorFrom).value;
10649
+ } catch {
10650
+ v = void 0;
10651
+ }
10652
+ tone = toneFor(v, o.thresholds);
10653
+ }
10654
+ return { at, text: text3, ...tone ? { tone } : {} };
10655
+ }
10656
+
10657
+ // plugins/core/src/push.ts
10658
+ var L2 = (en2, es, de, hant, hans) => ({ en: en2, es, de, "zh-Hant": hant, "zh-Hans": hans });
10659
+ var pushSource = defineSource({
10660
+ id: "push",
10661
+ name: L2("Pushes", "Pushes", "Pushes", "\u63A8\u9001", "\u63A8\u9001"),
10662
+ description: L2(
10663
+ "What scripts send to POST /api/push/<name>, for the Push widget and the JSON ones.",
10664
+ "Lo que los scripts env\xEDan a POST /api/push/<nombre>, para el widget Push y los JSON.",
10665
+ "Was Skripte an POST /api/push/<name> senden, f\xFCr das Push-Widget und die JSON-Widgets.",
10666
+ "\u8173\u672C\u50B3\u9001\u5230 POST /api/push/<\u540D\u7A31> \u7684\u5167\u5BB9\uFF0C\u4F9B\u63A8\u9001\u5C0F\u5DE5\u5177\u8207 JSON \u5C0F\u5DE5\u5177\u4F7F\u7528\u3002",
10667
+ "\u811A\u672C\u53D1\u9001\u5230 POST /api/push/<\u540D\u79F0> \u7684\u5185\u5BB9\uFF0C\u4F9B\u63A8\u9001\u5C0F\u7EC4\u4EF6\u548C JSON \u5C0F\u7EC4\u4EF6\u4F7F\u7528\u3002"
10668
+ ),
10669
+ watch(_ctx, emit) {
10670
+ emit(pushes.snapshot());
10671
+ return pushes.subscribe(emit);
10672
+ },
10673
+ choices: {
10674
+ names: (d) => Object.keys(d?.hooks ?? {}).map((value) => ({ value }))
10675
+ },
10676
+ demo: ({ now }) => demoPushes(now)
10677
+ });
10678
+ var LEVELS = ["ok", "info", "warn", "alert", "critical"];
10679
+ var str = (v) => typeof v === "string" ? v : typeof v === "number" || typeof v === "boolean" ? String(v) : void 0;
10680
+ function viewOf(payload) {
10681
+ if (typeof payload === "string") return { text: payload };
10682
+ if (typeof payload === "number" || typeof payload === "boolean") return { value: payload };
10683
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) return {};
10684
+ const p = payload;
10685
+ const level = typeof p.level === "string" ? p.level.toLowerCase() : void 0;
10686
+ const text3 = str(p.text) ?? str(p.message);
10687
+ const title = str(p.title);
10688
+ const unit = str(p.unit);
10689
+ return {
10690
+ ...title ? { title } : {},
10691
+ ...p.value !== void 0 ? { value: p.value } : {},
10692
+ ...text3 !== void 0 ? { text: text3 } : {},
10693
+ ...unit ? { unit } : {},
10694
+ ...LEVELS.includes(level) ? { level } : {}
10695
+ };
10696
+ }
10697
+ var entryOf = (sources, name2) => sources[PUSH_SOURCE]?.hooks?.[name2.trim()];
10698
+ var push2 = defineWidget({
10699
+ id: "push",
10700
+ name: L2("Push", "Push", "Push", "\u63A8\u9001", "\u63A8\u9001"),
10701
+ description: L2(
10702
+ "What a script, cron, CI or Home Assistant sends to POST /api/push/<name>: a value, a text and a level. An alert keeps the tile; it goes away when its time runs out.",
10703
+ "Lo que un script, cron, la CI o Home Assistant env\xEDa a POST /api/push/<nombre>: un valor, un texto y un nivel. Una alerta se queda la tesela; se quita sola cuando caduca.",
10704
+ "Was ein Skript, Cron, CI oder Home Assistant an POST /api/push/<name> sendet: ein Wert, ein Text und eine Stufe. Ein Alarm beh\xE4lt die Kachel; er verschwindet, wenn seine Zeit abl\xE4uft.",
10705
+ "\u8173\u672C\u3001cron\u3001CI \u6216 Home Assistant \u50B3\u9001\u5230 POST /api/push/<\u540D\u7A31> \u7684\u5167\u5BB9\uFF1A\u6578\u503C\u3001\u6587\u5B57\u8207\u7B49\u7D1A\u3002\u8B66\u5831\u6703\u4F54\u4F4F\u65B9\u683C\uFF0C\u5230\u671F\u5F8C\u81EA\u52D5\u6D88\u5931\u3002",
10706
+ "\u811A\u672C\u3001cron\u3001CI \u6216 Home Assistant \u53D1\u9001\u5230 POST /api/push/<\u540D\u79F0> \u7684\u5185\u5BB9\uFF1A\u6570\u503C\u3001\u6587\u5B57\u548C\u7EA7\u522B\u3002\u8B66\u62A5\u4F1A\u5360\u4F4F\u683C\u5B50\uFF0C\u5230\u671F\u540E\u81EA\u52A8\u6D88\u5931\u3002"
10707
+ ),
10708
+ icon: "webhook",
10709
+ category: "dev",
10710
+ tags: ["webhook", "push", "curl", "script", "cron", "ci"],
10711
+ size: { min: { w: 120, h: 60 }, preferred: { w: 360, h: 200 } },
10712
+ sources: [PUSH_SOURCE],
10713
+ options: t.object({
10714
+ name: t.string({ choices: { source: PUSH_SOURCE, list: "names" }, placeholder: "backup", label: L2("Push name", "Nombre del push", "Push-Name", "\u63A8\u9001\u540D\u7A31", "\u63A8\u9001\u540D\u79F0"), help: L2("Set up push names, with their URL and token, in Settings \u2192 Push.", "Los nombres, con su URL y su token, se crean en Ajustes \u2192 Push.", "Push-Namen mit URL und Token legst du unter Einstellungen \u2192 Push an.", "\u63A8\u9001\u540D\u7A31\u53CA\u5176 URL \u548C\u6B0A\u6756\u5728\u300C\u8A2D\u5B9A \u2192 \u63A8\u9001\u300D\u4E2D\u5EFA\u7ACB\u3002", "\u63A8\u9001\u540D\u79F0\u53CA\u5176 URL \u548C\u4EE4\u724C\u5728\u201C\u8BBE\u7F6E \u2192 \u63A8\u9001\u201D\u4E2D\u521B\u5EFA\u3002") }),
10715
+ unit: t.string({ placeholder: "\xB0C", label: L2("Unit", "Unidad", "Einheit", "\u55AE\u4F4D", "\u5355\u4F4D"), help: L2("When the push doesn't say one.", "Si el push no trae una.", "Wenn der Push keine mitbringt.", "\u63A8\u9001\u5167\u5BB9\u672A\u6307\u5B9A\u55AE\u4F4D\u6642\u4F7F\u7528\u3002", "\u63A8\u9001\u5185\u5BB9\u672A\u6307\u5B9A\u5355\u4F4D\u65F6\u4F7F\u7528\u3002") }),
10716
+ decimals: t.integer({ default: -1, min: -1, max: 6, label: L2("Decimals", "Decimales", "Nachkommastellen", "\u5C0F\u6578\u4F4D\u6578", "\u5C0F\u6570\u4F4D\u6570"), help: L2("-1: as it comes (up to 2).", "-1: tal como viene (hasta 2).", "-1: wie geliefert (bis zu 2).", "-1\uFF1A\u4F9D\u539F\u59CB\u503C\uFF08\u6700\u591A 2 \u4F4D\uFF09\u3002", "-1\uFF1A\u6309\u539F\u59CB\u503C\uFF08\u6700\u591A 2 \u4F4D\uFF09\u3002") }),
10717
+ showAge: t.boolean({ default: true, label: L2("Show how long ago", "Mostrar hace cu\xE1nto", "Anzeigen, wie lange her", "\u986F\u793A\u591A\u4E45\u4EE5\u524D", "\u663E\u793A\u591A\u4E45\u4EE5\u524D") })
10718
+ }),
10719
+ redraw: "minute",
10720
+ visible: ({ options: options2, sources, now }) => {
10721
+ const e = entryOf(sources, options2.name);
10722
+ return !e || live(e, now);
10723
+ },
10724
+ urgent: ({ options: options2, sources, now }) => {
10725
+ const e = entryOf(sources, options2.name);
10726
+ const level = live(e, now) ? viewOf(e.payload).level : void 0;
10727
+ return level === "alert" || level === "critical";
10728
+ },
10729
+ alerts: ({ options: options2, sources, now }) => {
10730
+ const e = entryOf(sources, options2.name);
10731
+ if (!live(e, now)) return [];
10732
+ const v = viewOf(e.payload);
10733
+ if (v.level !== "critical") return [];
10734
+ const title = v.title ?? v.text ?? options2.name;
10735
+ const alert = { id: `push-${options2.name.trim()}-${e.at}`, level: "critical", title, icon: "webhook", source: "Push", ...e.expiresAt ? { expiresAt: e.expiresAt } : {} };
10736
+ if (v.title && v.text) alert.text = v.text;
10737
+ return [alert];
10738
+ },
10739
+ render(g, ctx) {
10740
+ const { box, options: options2, theme, kit, now, sources, fmt } = ctx;
10741
+ const name2 = options2.name.trim();
10742
+ const small = Math.max(10, Math.min(24, Math.round(box.h / 7)));
10743
+ const dimFont = { size: small, family: theme.fonts.sans, color: theme.colors.inkDim };
10744
+ if (!name2) return void kit.drawTracked(g, kit.truncate(g, ctx.t(L2("Choose a push name", "Elige un nombre de push", "W\xE4hle einen Push-Namen", "\u8ACB\u9078\u64C7\u63A8\u9001\u540D\u7A31", "\u8BF7\u9009\u62E9\u63A8\u9001\u540D\u79F0")), box.w, dimFont), box.x, box.y + small * 1.1, dimFont);
10745
+ const e = entryOf(sources, name2);
10746
+ if (!e) {
10747
+ kit.drawTracked(g, kit.truncate(g, ctx.t(L2("Waiting for a push", "Esperando un push", "Warte auf einen Push", "\u7B49\u5F85\u63A8\u9001", "\u7B49\u5F85\u63A8\u9001")), box.w, dimFont), box.x, box.y + small * 1.1, dimFont);
10748
+ const mono = { size: Math.max(9, Math.round(small * 0.8)), family: theme.fonts.mono, color: theme.colors.inkFaint };
10749
+ kit.drawTracked(g, kit.truncate(g, `POST /api/push/${name2}`, box.w, mono), box.x, box.y + small * 2.5, mono);
10750
+ return;
10751
+ }
10752
+ const v = viewOf(e.payload);
10753
+ const tone = v.level === "critical" ? "alert" : v.level;
10754
+ const color2 = toneColor(theme, tone);
10755
+ let y = box.y;
10756
+ const footer = options2.showAge ? small * 1.3 : 0;
10757
+ if (v.title) {
10758
+ const tf = { size: small, family: theme.fonts.sansBold, color: theme.colors.inkDim, smallCaps: true, tracking: 1 };
10759
+ kit.drawTracked(g, kit.truncate(g, v.title, box.w, tf), box.x, y + small * 0.9, tf);
10760
+ y += small * 1.4;
10761
+ }
10762
+ const room = box.y + box.h - footer - y;
10763
+ const hasValue = v.value !== void 0;
10764
+ const hasText = !!v.text?.trim();
10765
+ if (hasValue) {
10766
+ const valueH = hasText ? room * 0.62 : room;
10767
+ const text3 = valueText(v.value, { decimals: options2.decimals, locale: ctx.locale });
10768
+ const unit = (v.unit ?? options2.unit).trim();
10769
+ const numeric = toNumber(v.value) !== void 0;
10770
+ const family = numeric ? theme.fonts.monoBold : theme.fonts.sansBold;
10771
+ let size = Math.min(valueH * 0.9, 400);
10772
+ g.font = `${size}px "${family}"`;
10773
+ const unitK = 0.42;
10774
+ const full = () => g.measureText(text3).width + (unit ? g.measureText(unit).width * unitK + size * 0.1 : 0);
10775
+ const w = full();
10776
+ if (w > box.w) size = Math.max(8, Math.floor(size * box.w / w));
10777
+ g.font = `${size}px "${family}"`;
10778
+ const tw = g.measureText(text3).width;
10779
+ const base4 = y + (valueH + size * 0.72) / 2;
10780
+ g.fillStyle = color2;
10781
+ g.textAlign = "left";
10782
+ g.fillText(text3, box.x, base4);
10783
+ if (unit) {
10784
+ g.font = `${Math.max(8, Math.round(size * unitK))}px "${theme.fonts.sans}"`;
10785
+ g.fillStyle = theme.colors.inkDim;
10786
+ g.fillText(unit, box.x + tw + size * 0.1, base4);
10787
+ }
10788
+ y += valueH;
10789
+ }
10790
+ if (hasText) {
10791
+ const h = hasValue ? room * 0.38 : room;
10792
+ let size = Math.min(hasValue ? h * 0.8 : 64, h);
10793
+ let lines = [];
10794
+ for (; ; size -= 2) {
10795
+ lines = kit.wrapLines(g, v.text, box.w, hasValue ? 2 : 6, { size, family: theme.fonts.sans });
10796
+ if (size - 2 < 10 || lines.length * size * 1.2 <= h) break;
10797
+ }
10798
+ const lh = size * 1.2;
10799
+ const top = y + Math.max(0, h - lines.length * lh) / 2 + size * 0.85;
10800
+ const tc = hasValue ? theme.colors.ink : color2;
10801
+ lines.forEach((l, i) => kit.drawTracked(g, l, box.x, top + i * lh, { size, family: theme.fonts.sans, color: tc }));
10802
+ }
10803
+ if (!hasValue && !hasText) {
10804
+ const raw2 = formatValue(e.payload, { decimals: options2.decimals, prefix: "", unit: "", locale: ctx.locale });
10805
+ kit.drawTracked(g, kit.truncate(g, raw2, box.w, { size: small, family: theme.fonts.mono }), box.x, y + small * 1.2, { size: small, family: theme.fonts.mono, color: theme.colors.ink });
10806
+ }
10807
+ if (footer) {
10808
+ const af = { size: Math.max(9, Math.round(small * 0.8)), family: theme.fonts.sans, color: theme.colors.inkFaint };
10809
+ kit.drawTracked(g, fmt.ago(e.at), box.x + box.w, box.y + box.h - af.size * 0.3, { ...af, align: "right" });
10810
+ }
10811
+ },
10812
+ demo: ({ now }) => ({ options: { name: "backup" }, sources: { [PUSH_SOURCE]: demoPushes(now) } })
10813
+ });
10814
+ function demoPushes(now) {
10815
+ const at = now - 25 * 6e4;
10816
+ const backup = { title: "Backup", value: "OK", text: "nas \u2192 b2 \xB7 12.4 GB", level: "ok" };
10817
+ const garage = { temp: 21.4, humidity: 48 };
10818
+ return {
10819
+ hooks: {
10820
+ backup: { at, payload: backup, history: [{ at, payload: backup }] },
10821
+ garage: { at: now - 6e4, payload: garage, history: Array.from({ length: 24 }, (_, i) => ({ at: now - (23 - i) * 36e5, payload: { temp: 18 + 4 * Math.sin(i / 4), humidity: 48 } })) }
10822
+ }
10823
+ };
10824
+ }
10825
+
10826
+ // plugins/core/src/index.ts
10827
+ function fit3(g, text3, family, w, h, max = 400) {
10828
+ let size = Math.min(max, h);
10829
+ g.font = `${size}px "${family}"`;
10830
+ const width = g.measureText(text3).width;
10831
+ if (width > w) size = Math.floor(size * w / width);
10832
+ return Math.max(8, size);
10833
+ }
9035
10834
  function isoWeek(d) {
9036
10835
  const t0 = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
9037
10836
  t0.setUTCDate(t0.getUTCDate() + 4 - (t0.getUTCDay() || 7));
@@ -9091,10 +10890,10 @@ var clock = defineWidget({
9091
10890
  const markFirst = !!mark && full.startsWith(mark);
9092
10891
  const dateText = options2.showDate ? new Date(at).toLocaleDateString(locale, DATE_FORMATS[options2.dateFormat]) : "";
9093
10892
  const dateH = options2.showDate ? Math.min(box.h * 0.2, 40) : 0;
9094
- const size = fit2(g, text3, theme.fonts.monoBold, box.w * (mark ? 0.76 : 0.96), (box.h - dateH * 1.3) * 0.95);
10893
+ const size = fit3(g, text3, theme.fonts.monoBold, box.w * (mark ? 0.76 : 0.96), (box.h - dateH * 1.3) * 0.95);
9095
10894
  const color2 = options2.color === "accent" ? theme.colors.accent : options2.color === "dim" ? theme.colors.inkDim : theme.colors.ink;
9096
10895
  const block = size * 0.78 + (dateH ? dateH * 1.4 : 0);
9097
- const base3 = box.y + (box.h - block) / 2 + size * 0.78;
10896
+ const base4 = box.y + (box.h - block) / 2 + size * 0.78;
9098
10897
  g.font = `${size}px "${theme.fonts.monoBold}"`;
9099
10898
  const digitsW = g.measureText(text3).width;
9100
10899
  const markSize = Math.max(8, Math.round(size * 0.26));
@@ -9106,19 +10905,19 @@ var clock = defineWidget({
9106
10905
  g.textAlign = "left";
9107
10906
  g.fillStyle = color2;
9108
10907
  g.font = `${size}px "${theme.fonts.monoBold}"`;
9109
- g.fillText(text3, digitsX, base3);
10908
+ g.fillText(text3, digitsX, base4);
9110
10909
  if (mark) {
9111
10910
  g.fillStyle = theme.colors.inkDim;
9112
10911
  g.font = `${markSize}px "${theme.fonts.sansBold}"`;
9113
- g.fillText(mark, markFirst ? left : left + digitsW + size * 0.08, base3 - size * 0.78 + markSize * 0.92);
10912
+ g.fillText(mark, markFirst ? left : left + digitsW + size * 0.08, base4 - size * 0.78 + markSize * 0.92);
9114
10913
  }
9115
10914
  const x = options2.align === "left" ? box.x : options2.align === "right" ? box.x + box.w : box.x + box.w / 2;
9116
10915
  g.textAlign = options2.align;
9117
10916
  if (dateH) {
9118
- const ds = Math.min(dateH, fit2(g, dateText, theme.fonts.sans, box.w * 0.96, dateH));
10917
+ const ds = Math.min(dateH, fit3(g, dateText, theme.fonts.sans, box.w * 0.96, dateH));
9119
10918
  g.font = `${ds}px "${theme.fonts.sans}"`;
9120
10919
  g.fillStyle = theme.colors.inkDim;
9121
- g.fillText(dateText, x, base3 + dateH * 1.35);
10920
+ g.fillText(dateText, x, base4 + dateH * 1.35);
9122
10921
  }
9123
10922
  g.textAlign = "left";
9124
10923
  }
@@ -9148,7 +10947,7 @@ var date = defineWidget({
9148
10947
  const weekdayColor = { accent: c.accent, ink: c.ink, dim: c.inkDim, alert: c.alert }[options2.weekdayColor];
9149
10948
  kit.drawTracked(g, weekday, box.x + box.w / 2, box.y + top, { size: top, family: theme.fonts.sansBold, color: weekdayColor, align: "center", smallCaps: true, tracking: 2 });
9150
10949
  const num = String(d.getDate());
9151
- const size = fit2(g, num, theme.fonts.sansBold, box.w * 0.9, box.h * 0.56);
10950
+ const size = fit3(g, num, theme.fonts.sansBold, box.w * 0.9, box.h * 0.56);
9152
10951
  g.font = `${size}px "${theme.fonts.sansBold}"`;
9153
10952
  g.fillStyle = theme.colors.ink;
9154
10953
  g.textAlign = "center";
@@ -9158,7 +10957,7 @@ var date = defineWidget({
9158
10957
  const ms = Math.min(top, box.h * 0.13);
9159
10958
  let line = month;
9160
10959
  if (options2.showWeekNumber) line += ` \xB7 ${tr({ en: "wk {n}", es: "sem {n}", de: "KW {n}", "zh-Hant": "\u7B2C {n} \u9031", "zh-Hans": "\u7B2C {n} \u5468" }).replace("{n}", String(isoWeek(d)))}`;
9161
- const ls = Math.min(ms, fit2(g, line, theme.fonts.sans, box.w * 0.96, ms));
10960
+ const ls = Math.min(ms, fit3(g, line, theme.fonts.sans, box.w * 0.96, ms));
9162
10961
  g.font = `${ls}px "${theme.fonts.sans}"`;
9163
10962
  g.fillStyle = theme.colors.inkDim;
9164
10963
  g.textAlign = "center";
@@ -9208,7 +11007,7 @@ var text2 = defineWidget({
9208
11007
  timeoutMs: 1e4,
9209
11008
  async fetch({ options: options2, signal }) {
9210
11009
  if (!options2.file.trim()) return { text: null };
9211
- const body2 = await readFile(expandHome(options2.file), { encoding: "utf8", signal });
11010
+ const body2 = await readFile3(expandHome(options2.file), { encoding: "utf8", signal });
9212
11011
  return { text: body2.slice(0, MAX_FILE_CHARS).replace(/\s+$/, "") };
9213
11012
  },
9214
11013
  empty: ({ options: options2, data }) => !noteOf(options2, data).trim(),
@@ -9270,16 +11069,16 @@ var list = defineWidget({
9270
11069
  const tx = box.x + dot * 4;
9271
11070
  plan.rows.forEach((row, i) => {
9272
11071
  const item2 = items[i];
9273
- const base3 = detailed ? row.y + ts * 1.05 : row.y + plan.rowH * 0.5 + ts * 0.36;
11072
+ const base4 = detailed ? row.y + ts * 1.05 : row.y + plan.rowH * 0.5 + ts * 0.36;
9274
11073
  g.fillStyle = theme.colors.accent;
9275
11074
  g.beginPath();
9276
- g.arc(box.x + dot * 1.5, base3 - ts * 0.34, dot, 0, Math.PI * 2);
11075
+ g.arc(box.x + dot * 1.5, base4 - ts * 0.34, dot, 0, Math.PI * 2);
9277
11076
  g.fill();
9278
11077
  const main2 = { size: ts, family: theme.fonts.sans, color: theme.colors.ink };
9279
- kit.drawTracked(g, kit.truncate(g, item2.text, box.x + box.w - tx, main2), tx, base3, main2);
11078
+ kit.drawTracked(g, kit.truncate(g, item2.text, box.x + box.w - tx, main2), tx, base4, main2);
9280
11079
  if (detailed && item2.detail) {
9281
11080
  const sub = { size: ds, family: theme.fonts.sans, color: theme.colors.inkDim };
9282
- kit.drawTracked(g, kit.truncate(g, item2.detail, box.x + box.w - tx, sub), tx, base3 + ds * 1.45, sub);
11081
+ kit.drawTracked(g, kit.truncate(g, item2.detail, box.x + box.w - tx, sub), tx, base4 + ds * 1.45, sub);
9283
11082
  }
9284
11083
  });
9285
11084
  drawMore(g, ctx, plan, { indent: tx - box.x });
@@ -9289,11 +11088,11 @@ var list = defineWidget({
9289
11088
  var IMAGE_FILE = /\.(png|jpe?g|webp|gif|avif|bmp|svg)$/i;
9290
11089
  var turns = /* @__PURE__ */ new Map();
9291
11090
  async function nextInFolder(dir) {
9292
- const files = (await readdir(dir, { withFileTypes: true })).filter((f) => f.isFile() && IMAGE_FILE.test(f.name)).map((f) => f.name).sort((a, b) => a.localeCompare(b));
11091
+ const files = (await readdir2(dir, { withFileTypes: true })).filter((f) => f.isFile() && IMAGE_FILE.test(f.name)).map((f) => f.name).sort((a, b) => a.localeCompare(b));
9293
11092
  if (!files.length) return null;
9294
11093
  const i = ((turns.get(dir) ?? -1) + 1) % files.length;
9295
11094
  turns.set(dir, i);
9296
- return join8(dir, files[i]);
11095
+ return join9(dir, files[i]);
9297
11096
  }
9298
11097
  function imageUrl(src, now, addTimestamp = false) {
9299
11098
  const filled = src.replace(/\{now\}/g, String(now)).replace(/\{unix\}/g, String(Math.floor(now / 1e3)));
@@ -9302,8 +11101,8 @@ function imageUrl(src, now, addTimestamp = false) {
9302
11101
  u.searchParams.set("t", String(now));
9303
11102
  return u.href;
9304
11103
  }
9305
- function placeImage(box, w, h, fit3, position) {
9306
- const s = fit3 === "cover" ? Math.max(box.w / w, box.h / h) : Math.min(box.w / w, box.h / h);
11104
+ function placeImage(box, w, h, fit4, position) {
11105
+ const s = fit4 === "cover" ? Math.max(box.w / w, box.h / h) : Math.min(box.w / w, box.h / h);
9307
11106
  const dw = w * s, dh = h * s;
9308
11107
  const fx = position === "left" ? 0 : position === "right" ? 1 : 0.5;
9309
11108
  const fy = position === "top" ? 0 : position === "bottom" ? 1 : 0.5;
@@ -9386,27 +11185,28 @@ var image = defineWidget({
9386
11185
  var src_default = definePlugin({
9387
11186
  id: "core",
9388
11187
  name: { en: "Essentials", es: "B\xE1sicos", de: "Grundlagen", "zh-Hant": "\u57FA\u672C\u5DE5\u5177", "zh-Hans": "\u57FA\u7840\u7EC4\u4EF6" },
9389
- version: "0.2.10",
11188
+ version: "0.2.12",
9390
11189
  languages: ["en", "es", "de", "zh-Hant", "zh-Hans"],
9391
11190
  sdk: "^0.2.0",
9392
- // The picture widget reads the image (or folder, or URL) you give it.
11191
+ // The picture widget reads the image (or folder, or URL) you give it; the JSON ones ask the URL you give them.
9393
11192
  permissions: { files: ["user"], network: ["user"] },
9394
- description: { en: "Clock, date, notes, lists and pictures.", es: "Reloj, fecha, notas, listas e im\xE1genes.", de: "Uhr, Datum, Notizen, Listen und Bilder.", "zh-Hant": "\u6642\u9418\u3001\u65E5\u671F\u3001\u4FBF\u689D\u3001\u6E05\u55AE\u548C\u5716\u7247\u3002", "zh-Hans": "\u65F6\u949F\u3001\u65E5\u671F\u3001\u4FBF\u7B7E\u3001\u5217\u8868\u548C\u56FE\u7247\u3002" },
11193
+ description: { en: "Clock, date, notes, lists, pictures, any JSON and pushes from your scripts.", es: "Reloj, fecha, notas, listas, im\xE1genes, cualquier JSON y los push de tus scripts.", de: "Uhr, Datum, Notizen, Listen, Bilder, beliebiges JSON und Pushes deiner Skripte.", "zh-Hant": "\u6642\u9418\u3001\u65E5\u671F\u3001\u4FBF\u689D\u3001\u6E05\u55AE\u3001\u5716\u7247\u3001\u4EFB\u4F55 JSON\uFF0C\u4EE5\u53CA\u8173\u672C\u50B3\u4F86\u7684\u63A8\u9001\u3002", "zh-Hans": "\u65F6\u949F\u3001\u65E5\u671F\u3001\u4FBF\u7B7E\u3001\u5217\u8868\u3001\u56FE\u7247\u3001\u4EFB\u4F55 JSON\uFF0C\u4EE5\u53CA\u811A\u672C\u53D1\u6765\u7684\u63A8\u9001\u3002" },
9395
11194
  author: "Kiosko",
9396
11195
  license: "MIT",
9397
11196
  icon: "box",
9398
- widgets: [clock, date, text2, list, image]
11197
+ widgets: [clock, date, text2, list, image, jsonValue, jsonList, jsonText, push2],
11198
+ sources: [pushSource]
9399
11199
  });
9400
11200
 
9401
11201
  // plugins/legacy/src/index.ts
9402
11202
  import { existsSync as existsSync7, statSync as statSync2 } from "node:fs";
9403
- import { isAbsolute, join as join9 } from "node:path";
11203
+ import { isAbsolute, join as join10 } from "node:path";
9404
11204
  import { pathToFileURL as pathToFileURL3 } from "node:url";
9405
11205
  var loaded = /* @__PURE__ */ new Map();
9406
11206
  function resolveModule(name2, dir) {
9407
11207
  const expanded = expandPath(name2);
9408
- const base3 = isAbsolute(expanded) ? expanded : join9(expandPath(dir), expanded);
9409
- for (const p of [base3, `${base3}.mjs`, `${base3}.js`, join9(base3, "index.mjs"), join9(base3, "index.js")]) {
11208
+ const base4 = isAbsolute(expanded) ? expanded : join10(expandPath(dir), expanded);
11209
+ for (const p of [base4, `${base4}.mjs`, `${base4}.js`, join10(base4, "index.mjs"), join10(base4, "index.js")]) {
9410
11210
  if (existsSync7(p) && statSync2(p).isFile()) return p;
9411
11211
  }
9412
11212
  return null;
@@ -9482,7 +11282,7 @@ var module2 = defineWidget({
9482
11282
  var src_default2 = definePlugin({
9483
11283
  id: "legacy",
9484
11284
  name: { en: "aimonitor compatibility", es: "Compatibilidad aimonitor", de: "aimonitor-Kompatibilit\xE4t", "zh-Hant": "aimonitor \u76F8\u5BB9\u6027", "zh-Hans": "aimonitor \u517C\u5BB9" },
9485
- version: "0.2.10",
11285
+ version: "0.2.12",
9486
11286
  languages: ["en", "es", "de", "zh-Hant", "zh-Hans"],
9487
11287
  sdk: "^0.2.0",
9488
11288
  // Runs the aimonitor modules you point it at, and reads their folder.
@@ -9496,7 +11296,7 @@ var src_default2 = definePlugin({
9496
11296
 
9497
11297
  // packages/server/src/official.ts
9498
11298
  var BUNDLED_PLUGIN_IDS = ["agents", "cats", "system", "vitals", "usage", "weather", "calendar", "news", "mirror", "gitlab", "github", "calls", "timesheet", "llm", "gpu", "homeassistant"];
9499
- var OPTIONAL_PLUGIN_IDS = ["doom", "video", "fractals", "gaming", "logs", "hazards", "batteries"];
11299
+ var OPTIONAL_PLUGIN_IDS = ["doom", "video", "fractals", "gaming", "logs", "hazards", "batteries", "switchbot"];
9500
11300
  var OFFICIAL_PLUGINS = [
9501
11301
  ...BUNDLED_PLUGIN_IDS.map((id) => ({ id, npm: `kiosko-plugin-${id}`, bundled: true })),
9502
11302
  ...OPTIONAL_PLUGIN_IDS.map((id) => ({ id, npm: `kiosko-plugin-${id}`, bundled: false }))
@@ -9509,11 +11309,11 @@ var BUILTIN_PLUGINS = [src_default, src_default2];
9509
11309
  // packages/server/src/config-cli.ts
9510
11310
  import { copyFileSync as copyFileSync2, existsSync as existsSync9, mkdirSync as mkdirSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync6 } from "node:fs";
9511
11311
  import { tmpdir } from "node:os";
9512
- import { dirname as dirname4, isAbsolute as isAbsolute2, join as join11, relative, resolve as resolve2 } from "node:path";
11312
+ import { dirname as dirname4, isAbsolute as isAbsolute2, join as join12, relative, resolve as resolve2 } from "node:path";
9513
11313
 
9514
11314
  // packages/server/src/preview.ts
9515
11315
  import { existsSync as existsSync8, mkdirSync as mkdirSync4, writeFileSync as writeFileSync5 } from "node:fs";
9516
- import { dirname as dirname3, join as join10 } from "node:path";
11316
+ import { dirname as dirname3, join as join11 } from "node:path";
9517
11317
  function writePreview(rt, screen, page, out, o = {}) {
9518
11318
  const r = rt.preview(screen, page, { demo: o.demo ?? true });
9519
11319
  if (!existsSync8(dirname3(out))) mkdirSync4(dirname3(out), { recursive: true });
@@ -9531,7 +11331,7 @@ function renderPreviews(registry2, cfg, dir) {
9531
11331
  try {
9532
11332
  safe2.screens.forEach(
9533
11333
  (s, si) => s.pages.forEach((p, pi) => {
9534
- const file = join10(dir, `${si + 1}-${slug(s.name || s.id)}--${pi + 1}-${slug(p.name || p.id)}.png`);
11334
+ const file = join11(dir, `${si + 1}-${slug(s.name || s.id)}--${pi + 1}-${slug(p.name || p.id)}.png`);
9535
11335
  const problems = writePreview(rt, s, p, file);
9536
11336
  out.push({ screen: s.name || s.id, page: p.name || p.id, file, size: `${s.width}\xD7${s.height}`, problems });
9537
11337
  })
@@ -9596,14 +11396,14 @@ async function findRunning(cfg, configPath, o) {
9596
11396
  const host0 = o.host || cfg.server.host || "127.0.0.1";
9597
11397
  const host = host0 === "0.0.0.0" || host0 === "::" ? "127.0.0.1" : host0;
9598
11398
  const port = Number(o.port || cfg.server.port);
9599
- const base3 = `http://${host.includes(":") ? `[${host}]` : host}:${port}`;
11399
+ const base4 = `http://${host.includes(":") ? `[${host}]` : host}:${port}`;
9600
11400
  try {
9601
- const r = await fetch(`${base3}/api/state`, { signal: AbortSignal.timeout(1500) });
11401
+ const r = await fetch(`${base4}/api/state`, { signal: AbortSignal.timeout(1500) });
9602
11402
  if (!r.ok) return null;
9603
11403
  const s = await r.json();
9604
11404
  if (typeof s.rev !== "number" || !s.config) return null;
9605
11405
  const servedPath = s.paths?.config ?? "";
9606
- return { base: base3, rev: s.rev, config: s.config, servedPath, same: !!servedPath && resolve2(servedPath) === resolve2(configPath) };
11406
+ return { base: base4, rev: s.rev, config: s.config, servedPath, same: !!servedPath && resolve2(servedPath) === resolve2(configPath) };
9607
11407
  } catch {
9608
11408
  return null;
9609
11409
  }
@@ -9746,7 +11546,7 @@ ${bold("Changes")}: ${summarizeDiff(plan.diff)}`);
9746
11546
  }
9747
11547
  if (plan.carried.length) console.log(dim(` kept from your current config (the file leaves them out): ${plan.carried.join(", ")}`));
9748
11548
  if (!flags.has("--no-preview")) {
9749
- const dir = opts.get("--preview") || join11(tmpdir(), `kiosko-import-${stamp()}`);
11549
+ const dir = opts.get("--preview") || join12(tmpdir(), `kiosko-import-${stamp()}`);
9750
11550
  try {
9751
11551
  const files = renderPreviews(reg, c, dir);
9752
11552
  console.log(`
@@ -9849,13 +11649,13 @@ async function editorCommand({ server, flags, open: open2, log }) {
9849
11649
  // packages/server/src/plugins-cli.ts
9850
11650
  import { execFileSync as execFileSync2 } from "node:child_process";
9851
11651
  import { existsSync as existsSync10, lstatSync, mkdirSync as mkdirSync6, readdirSync as readdirSync4, readFileSync as readFileSync6, rmSync, symlinkSync, watch, writeFileSync as writeFileSync7 } from "node:fs";
9852
- import { basename, join as join12, resolve as resolve4 } from "node:path";
11652
+ import { basename, join as join13, resolve as resolve4 } from "node:path";
9853
11653
  import { pathToFileURL as pathToFileURL4 } from "node:url";
9854
11654
  var npmName = (s) => /^[a-z0-9][\w.-]*$/.test(s) && !s.startsWith("kiosko-plugin-") && !s.includes("/") ? `kiosko-plugin-${s}` : s;
9855
11655
  function ensureFolder() {
9856
11656
  const dir = paths.plugins;
9857
11657
  mkdirSync6(dir, { recursive: true });
9858
- const pkg = join12(dir, "package.json");
11658
+ const pkg = join13(dir, "package.json");
9859
11659
  if (!existsSync10(pkg)) writeFileSync7(pkg, `${JSON.stringify({ name: "kiosko-user-plugins", private: true, type: "module" }, null, 2)}
9860
11660
  `);
9861
11661
  return dir;
@@ -9865,10 +11665,10 @@ function npm(args, cwd) {
9865
11665
  }
9866
11666
  async function loadPluginDir(dir, o = {}) {
9867
11667
  const root = resolve4(dir);
9868
- const pkgPath = join12(root, "package.json");
11668
+ const pkgPath = join13(root, "package.json");
9869
11669
  const pkg = existsSync10(pkgPath) ? JSON.parse(readFileSync6(pkgPath, "utf8")) : {};
9870
- const built = [pkg.kiosko?.plugin, pkg.main, "index.mjs", "index.js"].filter((x) => typeof x === "string").map((x) => join12(root, x)).find(existsSync10);
9871
- const src = join12(root, "src", "index.ts");
11670
+ const built = [pkg.kiosko?.plugin, pkg.main, "index.mjs", "index.js"].filter((x) => typeof x === "string").map((x) => join13(root, x)).find(existsSync10);
11671
+ const src = join13(root, "src", "index.ts");
9872
11672
  const entry = (o.src || !built) && existsSync10(src) ? src : built;
9873
11673
  if (!entry) throw new Error(`no plugin in ${root}: no package.json "kiosko.plugin", index.js or src/index.ts`);
9874
11674
  installSdkResolver();
@@ -9917,8 +11717,8 @@ ${errors.length} errors, ${issues.length - errors.length} warnings` : "\u2713 no
9917
11717
  async function manifest(dir, argv2) {
9918
11718
  const root = resolve4(dir);
9919
11719
  const { def, pkg } = await loadPluginDir(root, { src: flagOf(argv2, "--src") });
9920
- const screenshots = Object.fromEntries((def.widgets ?? []).map((w) => [w.id, `docs/${w.id}.png`]).filter(([, f]) => existsSync10(join12(root, f))));
9921
- const out = optOf(argv2, "--out") ?? join12(root, "kiosko-manifest.json");
11720
+ const screenshots = Object.fromEntries((def.widgets ?? []).map((w) => [w.id, `docs/${w.id}.png`]).filter(([, f]) => existsSync10(join13(root, f))));
11721
+ const out = optOf(argv2, "--out") ?? join13(root, "kiosko-manifest.json");
9922
11722
  writeFileSync7(out, `${JSON.stringify(pluginManifest(def, { pkg, screenshots }), null, 2)}
9923
11723
  `);
9924
11724
  console.log(out);
@@ -10157,8 +11957,8 @@ async function pluginsCommand(argv2, registry2) {
10157
11957
  const dir = resolve4(where2 ?? `kiosko-plugin-${id}`);
10158
11958
  if (existsSync10(dir) && readdirSync4(dir).length) throw new Error(`${dir} is not empty`);
10159
11959
  for (const [file, body2] of Object.entries(newPluginFiles(id))) {
10160
- mkdirSync6(join12(dir, file, ".."), { recursive: true });
10161
- writeFileSync7(join12(dir, file), body2);
11960
+ mkdirSync6(join13(dir, file, ".."), { recursive: true });
11961
+ writeFileSync7(join13(dir, file), body2);
10162
11962
  }
10163
11963
  console.log(`${dir}
10164
11964
 
@@ -10190,12 +11990,12 @@ plugins folder: ${paths.plugins}`);
10190
11990
  const dir = ensureFolder();
10191
11991
  for (const n of names) {
10192
11992
  const src = resolve4(n);
10193
- const pkgPath = join12(src, "package.json");
11993
+ const pkgPath = join13(src, "package.json");
10194
11994
  if (!existsSync10(pkgPath)) throw new Error(`${src} has no package.json`);
10195
11995
  const pkg = JSON.parse(readFileSync6(pkgPath, "utf8"));
10196
11996
  const entry = pkg.kiosko?.plugin;
10197
- if (entry && !existsSync10(join12(src, entry))) console.warn(`warning: ${entry} doesn't exist yet in ${src} (run its build)`);
10198
- const target = join12(dir, pkg.kiosko?.id ?? basename(src).replace(/^kiosko-plugin-/, ""));
11997
+ if (entry && !existsSync10(join13(src, entry))) console.warn(`warning: ${entry} doesn't exist yet in ${src} (run its build)`);
11998
+ const target = join13(dir, pkg.kiosko?.id ?? basename(src).replace(/^kiosko-plugin-/, ""));
10199
11999
  const existing = (() => {
10200
12000
  try {
10201
12001
  return lstatSync(target);
@@ -10216,7 +12016,7 @@ plugins folder: ${paths.plugins}`);
10216
12016
  const dir = ensureFolder();
10217
12017
  for (const n of names) {
10218
12018
  const id = n.replace(/^kiosko-plugin-/, "");
10219
- const link = join12(dir, id);
12019
+ const link = join13(dir, id);
10220
12020
  const st = (() => {
10221
12021
  try {
10222
12022
  return lstatSync(link);
@@ -10339,7 +12139,8 @@ function remoteApi(ctx) {
10339
12139
  if (s) {
10340
12140
  const keepHost = s.device.driver === "remote" ? s.device.host : void 0;
10341
12141
  const keepPort = s.device.driver === "remote" ? s.device.port : void 0;
10342
- s.device = { driver: "remote", uid: info.uid, id: info.id, key: hex2, ...keepHost ? { host: keepHost } : {}, ...keepPort ? { port: keepPort } : {} };
12142
+ const keepBright = s.device.driver === "remote" ? s.device.brightness : void 0;
12143
+ s.device = { driver: "remote", uid: info.uid, id: info.id, key: hex2, ...keepHost ? { host: keepHost } : {}, ...keepPort ? { port: keepPort } : {}, ...keepBright !== void 0 ? { brightness: keepBright } : {} };
10343
12144
  } else {
10344
12145
  s = remoteScreen(ctx.runtime.registry, info, hex2, ctx.runtime.config.locale === "auto" ? "en" : ctx.runtime.config.locale);
10345
12146
  cfg.screens.push(s);
@@ -10347,13 +12148,13 @@ function remoteApi(ctx) {
10347
12148
  ctx.commit(cfg);
10348
12149
  return ctx.json(res, 200, { ok: true, screenId: s.id }), true;
10349
12150
  }
10350
- mm = /^\/api\/screens\/([^/]+)\/remote\/(unpair|ota|logs)$/.exec(p);
12151
+ mm = /^\/api\/screens\/([^/]+)\/remote\/(unpair|ota|logs|firmware)$/.exec(p);
10351
12152
  if (mm) {
10352
12153
  const id = decodeURIComponent(mm[1]);
10353
12154
  const r = remoteOf(id);
10354
12155
  if (!r) return ctx.json(res, 404, { error: "not a remote screen", code: "unknownScreen" }), true;
10355
12156
  const key = /^[0-9a-f]{64}$/.test(r.device.key ?? "") ? Buffer.from(r.device.key, "hex") : null;
10356
- const run = async (fn) => {
12157
+ const run2 = async (fn) => {
10357
12158
  if (r.driver) return r.driver.exclusive(fn);
10358
12159
  const at = await locate(r.device.uid, r.device.host, r.device.port);
10359
12160
  if (!at) throw new ScreenError("offline", "that screen is not on the network");
@@ -10364,7 +12165,7 @@ function remoteApi(ctx) {
10364
12165
  let told = false;
10365
12166
  if (key) {
10366
12167
  try {
10367
- await run((h, port) => unpairScreen(h, port, key, r.device.uid));
12168
+ await run2((h, port) => unpairScreen(h, port, key, r.device.uid));
10368
12169
  told = true;
10369
12170
  } catch {
10370
12171
  }
@@ -10376,12 +12177,21 @@ function remoteApi(ctx) {
10376
12177
  return ctx.json(res, 200, { ok: true, told }), true;
10377
12178
  }
10378
12179
  if (!key) return ctx.json(res, 409, { error: "not paired", code: "remote.notPaired" }), true;
10379
- if (mm[2] === "logs" && m === "GET") return ctx.json(res, 200, { text: await run((h, port) => screenLogs(h, port, key, r.device.uid)) }), true;
12180
+ if (mm[2] === "logs" && m === "GET") return ctx.json(res, 200, { text: await run2((h, port) => screenLogs(h, port, key, r.device.uid)) }), true;
10380
12181
  if (mm[2] === "ota" && m === "POST") {
10381
12182
  const image2 = await raw(req, 4 * 1024 * 1024);
10382
- await run((h, port) => otaUpdate(h, port, key, r.device.uid, image2));
12183
+ await run2((h, port) => otaUpdate(h, port, key, r.device.uid, image2));
10383
12184
  return ctx.json(res, 200, { ok: true }), true;
10384
12185
  }
12186
+ if (mm[2] === "firmware" && m === "POST") {
12187
+ const st = r.driver?.status.remote;
12188
+ if (!st?.online) throw new ScreenError("offline", "that screen is not connected now");
12189
+ const version = firmwareOffer(st.model, st.fw);
12190
+ if (!version) return ctx.json(res, 409, { error: `no newer firmware for ${st.model} ${st.fw} in this Kiosko`, code: "remote.upToDate" }), true;
12191
+ const fw = await downloadFirmware({ kioskoVersion: ctx.version, model: st.model, ...ctx.fetch ? { fetch: ctx.fetch } : {} });
12192
+ await run2((h, port) => otaUpdate(h, port, key, r.device.uid, fw.image));
12193
+ return ctx.json(res, 200, { ok: true, version: fw.version, sha256: fw.sha256 }), true;
12194
+ }
10385
12195
  } catch (err) {
10386
12196
  return fail(res, err), true;
10387
12197
  }
@@ -10493,7 +12303,7 @@ async function remoteCommand(args, o) {
10493
12303
 
10494
12304
  // packages/server/src/gallery.ts
10495
12305
  import { mkdirSync as mkdirSync7, writeFileSync as writeFileSync8 } from "node:fs";
10496
- import { join as join13 } from "node:path";
12306
+ import { join as join14 } from "node:path";
10497
12307
  var HOME_URL = "https://kioskolcd.dev/";
10498
12308
  var RELEASES_URL = "https://github.com/kiosko-lcd/kiosko/releases/latest";
10499
12309
  var MADRID = { latitude: 40.4168, longitude: -3.7038, name: "Madrid" };
@@ -10524,9 +12334,9 @@ function buildGallery(registry2, o) {
10524
12334
  let count = 0;
10525
12335
  const pluginsOf = registry2.list().filter(({ def, enabled }) => enabled && def.widgets?.length);
10526
12336
  for (const lang of langs) {
10527
- mkdirSync7(join13(o.out, "img", folder(lang.id)), { recursive: true });
12337
+ mkdirSync7(join14(o.out, "img", folder(lang.id)), { recursive: true });
10528
12338
  const cfg = normalize({ locale: lang.locale, theme: theme.id, location: SAMPLE_PLACES[lang.id] ?? MADRID });
10529
- const L = (x) => localize(x, lang.locale);
12339
+ const L3 = (x) => localize(x, lang.locale);
10530
12340
  const up = folder(lang.id) ? "../" : "";
10531
12341
  const sections = [];
10532
12342
  const without = languageById(lang.id)?.plugins?.without ?? [];
@@ -10539,8 +12349,8 @@ function buildGallery(registry2, o) {
10539
12349
  const width = Math.min(1920, pref.w);
10540
12350
  const height = Math.min(720, pref.h);
10541
12351
  const file = `img/${folder(lang.id)}${def.id}-${w.id}.png`;
10542
- const r = composeWidget({ cfg, registry: registry2, theme, type: `${def.id}/${w.id}`, width, height, now, ...w.chrome === "bare" ? {} : { title: L(w.name) } });
10543
- writeFileSync8(join13(o.out, file), r.canvas.toBuffer("image/png"));
12352
+ const r = composeWidget({ cfg, registry: registry2, theme, type: `${def.id}/${w.id}`, width, height, now, ...w.chrome === "bare" ? {} : { title: L3(w.name) } });
12353
+ writeFileSync8(join14(o.out, file), r.canvas.toBuffer("image/png"));
10544
12354
  let shot = listed.widgets.find((x) => x.type === `${def.id}/${w.id}`);
10545
12355
  if (!shot) {
10546
12356
  count++;
@@ -10548,16 +12358,16 @@ function buildGallery(registry2, o) {
10548
12358
  }
10549
12359
  shot.file[lang.id] = file;
10550
12360
  const wide = width >= 900;
10551
- return `<figure class="${wide ? "wide" : ""}"><div class="shot"><img src="${up}${file}" width="${width}" height="${height}" loading="lazy" alt="${esc(L(w.name))}"></div><figcaption><b>${esc(L(w.name))}</b> <code>${def.id}/${w.id}</code><span>${esc(L(w.description))}</span></figcaption></figure>`;
12361
+ return `<figure class="${wide ? "wide" : ""}"><div class="shot"><img src="${up}${file}" width="${width}" height="${height}" loading="lazy" alt="${esc(L3(w.name))}"></div><figcaption><b>${esc(L3(w.name))}</b> <code>${def.id}/${w.id}</code><span>${esc(L3(w.description))}</span></figcaption></figure>`;
10552
12362
  });
10553
- if (!without.includes(def.id)) sections.push(`<section><h2>${esc(L(def.name))} <small>${esc(def.id)} \xB7 v${esc(def.version)}</small></h2><p>${esc(L(def.description))}</p><div class="grid">${cards.join("")}</div></section>`);
12363
+ if (!without.includes(def.id)) sections.push(`<section><h2>${esc(L3(def.name))} <small>${esc(def.id)} \xB7 v${esc(def.version)}</small></h2><p>${esc(L3(def.description))}</p><div class="grid">${cards.join("")}</div></section>`);
10554
12364
  }
10555
12365
  const home = `${HOME_URL}${folder(lang.id)}`;
10556
12366
  const usb = lang.id.startsWith("zh") ? `${HOME_URL}${lang.id}/docs/usb/` : "https://github.com/kiosko-lcd/kiosko/blob/main/docs/usb.md";
10557
- mkdirSync7(join13(o.out, folder(lang.id)), { recursive: true });
12367
+ mkdirSync7(join14(o.out, folder(lang.id)), { recursive: true });
10558
12368
  writeFileSync8(
10559
- join13(o.out, folder(lang.id), "index.html"),
10560
- `<!doctype html><html lang="${lang.id}" dir="${lang.dir}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(L(T2.title))}</title>
12369
+ join14(o.out, folder(lang.id), "index.html"),
12370
+ `<!doctype html><html lang="${lang.id}" dir="${lang.dir}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${esc(L3(T2.title))}</title>
10561
12371
  <style>
10562
12372
  :root{color-scheme:dark;--bg:#0a0d13;--panel:#121722;--line:rgba(255,255,255,.08);--text:#e7ecf4;--dim:#a3adbf}
10563
12373
  body{margin:0;background:var(--bg);color:var(--text);font:15px/1.5 ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
@@ -10574,7 +12384,7 @@ figcaption code{color:#22d3ee;font-size:12px}figcaption span{flex-basis:100%;col
10574
12384
  a{color:#22d3ee}
10575
12385
  p.os{margin-top:14px}p.os b{color:var(--text)}
10576
12386
  a.try{display:inline-block;margin-top:10px;padding:8px 14px;border-radius:10px;background:linear-gradient(135deg,#8b5cf6,#22d3ee);color:#fff;font-weight:600;text-decoration:none}
10577
- </style></head><body><header><p><a href="${home}">\u2190 Kiosko</a></p><h1>${esc(L(T2.title))}</h1><p>${esc(L(T2.lede).replace("{n}", String(listedHere.reduce((n, p) => n + p.def.widgets.length, 0))))} <a href="https://github.com/kiosko-lcd/kiosko">${esc(L(T2.github))}</a></p><p><a class="try" href="${HOME_URL}demo/?lang=${lang.locale}">${esc(L(T2.editor))}</a> &nbsp; <a class="try" href="${HOME_URL}demo/3d/?lang=${lang.locale}">${esc(L(T2.in3d))}</a></p><p class="os">${L(T2.os).replace("{releases}", RELEASES_URL).replace("{usb}", usb)}</p></header><main>${sections.join("")}</main></body></html>`
12387
+ </style></head><body><header><p><a href="${home}">\u2190 Kiosko</a></p><h1>${esc(L3(T2.title))}</h1><p>${esc(L3(T2.lede).replace("{n}", String(listedHere.reduce((n, p) => n + p.def.widgets.length, 0))))} <a href="https://github.com/kiosko-lcd/kiosko">${esc(L3(T2.github))}</a></p><p><a class="try" href="${HOME_URL}demo/?lang=${lang.locale}">${esc(L3(T2.editor))}</a> &nbsp; <a class="try" href="${HOME_URL}demo/3d/?lang=${lang.locale}">${esc(L3(T2.in3d))}</a></p><p class="os">${L3(T2.os).replace("{releases}", RELEASES_URL).replace("{usb}", usb)}</p></header><main>${sections.join("")}</main></body></html>`
10578
12388
  );
10579
12389
  }
10580
12390
  if (o.pages) {
@@ -10586,12 +12396,12 @@ a.try{display:inline-block;margin-top:10px;padding:8px 14px;border-radius:10px;b
10586
12396
  }
10587
12397
  for (const l of langs) {
10588
12398
  const local = normalize({ ...localizeSample(sample, l.locale), locale: l.locale });
10589
- const shown = local.screens.find((s) => s.id === screen.id);
12399
+ const shown2 = local.screens.find((s) => s.id === screen.id);
10590
12400
  const rt = new Runtime(registry2, local, { demo: true });
10591
12401
  try {
10592
12402
  for (const listed of data.pages) {
10593
- const page = shown.pages.find((p) => p.id === listed.id);
10594
- writeFileSync8(join13(o.out, listed.file[l.id]), rt.preview(shown, page, { now, demo: true }).canvas.toBuffer("image/jpeg", 88));
12403
+ const page = shown2.pages.find((p) => p.id === listed.id);
12404
+ writeFileSync8(join14(o.out, listed.file[l.id]), rt.preview(shown2, page, { now, demo: true }).canvas.toBuffer("image/jpeg", 88));
10595
12405
  }
10596
12406
  } finally {
10597
12407
  rt.stop();
@@ -10599,7 +12409,7 @@ a.try{display:inline-block;margin-top:10px;padding:8px 14px;border-radius:10px;b
10599
12409
  }
10600
12410
  }
10601
12411
  data.count = count;
10602
- writeFileSync8(join13(o.out, "gallery.json"), `${JSON.stringify(data)}
12412
+ writeFileSync8(join14(o.out, "gallery.json"), `${JSON.stringify(data)}
10603
12413
  `);
10604
12414
  return count;
10605
12415
  }
@@ -10641,16 +12451,16 @@ var WHEN = { jornada: "work", fuera: "off", siempre: "always" };
10641
12451
  function widgetFor(m, reg, notes, modulesDir) {
10642
12452
  if (m.disabled) return null;
10643
12453
  const mapped = MODULE_MAP[m.module];
10644
- const base3 = { id: newId("w"), ...m.header ? { title: m.header } : {}, ...m.updateMs ? { intervalMs: m.updateMs } : {}, ...m.when && m.when !== "siempre" ? { when: WHEN[m.when] } : {} };
12454
+ const base4 = { id: newId("w"), ...m.header ? { title: m.header } : {}, ...m.updateMs ? { intervalMs: m.updateMs } : {}, ...m.when && m.when !== "siempre" ? { when: WHEN[m.when] } : {} };
10645
12455
  if (mapped) {
10646
12456
  if (!reg.widget(mapped)) notes.push(`"${m.module}" maps to ${mapped}: install it with \`kiosko plugins add ${mapped.split("/")[0]}\``);
10647
- return { ...base3, type: mapped, options: optionsOf(m.module, m.config) };
12457
+ return { ...base4, type: mapped, options: optionsOf(m.module, m.config) };
10648
12458
  }
10649
12459
  if (NOT_PORTED.has(m.module)) {
10650
12460
  notes.push(`"${m.module}" depends on aimonitor-only services and has no Kiosko widget yet: skipped`);
10651
12461
  return null;
10652
12462
  }
10653
- return { ...base3, type: "legacy/module", options: { module: m.module, dir: modulesDir, json: m.config ? JSON.stringify(m.config, null, 2) : "" } };
12463
+ return { ...base4, type: "legacy/module", options: { module: m.module, dir: modulesDir, json: m.config ? JSON.stringify(m.config, null, 2) : "" } };
10654
12464
  }
10655
12465
  function columnsPage(name2, width, height, mods, rotateMs, reg, notes, modulesDir) {
10656
12466
  const groups = [];
@@ -10768,7 +12578,7 @@ function importAimonitor(old, reg, modeOverride, o = {}) {
10768
12578
  import { execFileSync as execFileSync3 } from "node:child_process";
10769
12579
  import { existsSync as existsSync11, mkdirSync as mkdirSync8, rmSync as rmSync2, writeFileSync as writeFileSync9 } from "node:fs";
10770
12580
  import { homedir as homedir4, platform as platform2 } from "node:os";
10771
- import { dirname as dirname5, join as join14, resolve as resolve5, win32 as win322 } from "node:path";
12581
+ import { dirname as dirname5, join as join15, resolve as resolve5, win32 as win322 } from "node:path";
10772
12582
  import { fileURLToPath } from "node:url";
10773
12583
  var xml = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
10774
12584
  function servicePlan(o = {}) {
@@ -10778,10 +12588,10 @@ function servicePlan(o = {}) {
10778
12588
  const args = [...nodeArgs, cli, "start", ...o.args ?? []];
10779
12589
  const os = o.os ?? platform2();
10780
12590
  const sep2 = os === "win32" ? ";" : ":";
10781
- const path = [dirname5(node), join14(homedir4(), ".local", "bin"), ...os === "darwin" ? ["/opt/homebrew/bin"] : [], "/usr/local/bin", "/usr/bin", "/bin"].join(sep2);
12591
+ const path = [dirname5(node), join15(homedir4(), ".local", "bin"), ...os === "darwin" ? ["/opt/homebrew/bin"] : [], "/usr/local/bin", "/usr/bin", "/bin"].join(sep2);
10782
12592
  const env = { ...os === "win32" ? {} : { PATH: path }, ...o.env ?? {} };
10783
12593
  if (os === "darwin") {
10784
- const file2 = join14(homedir4(), "Library", "LaunchAgents", "dev.kiosko.plist");
12594
+ const file2 = join15(homedir4(), "Library", "LaunchAgents", "dev.kiosko.plist");
10785
12595
  const content2 = `<?xml version="1.0" encoding="UTF-8"?>
10786
12596
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
10787
12597
  <plist version="1.0">
@@ -10798,8 +12608,8 @@ ${Object.entries(env).map(([k, v]) => ` <key>${xml(k)}</key><string>${xml(v)}
10798
12608
  <key>RunAtLoad</key><true/>
10799
12609
  <key>KeepAlive</key><true/>
10800
12610
  <key>ProcessType</key><string>Background</string>
10801
- <key>StandardOutPath</key><string>${xml(join14(homedir4(), "Library", "Logs", "kiosko.log"))}</string>
10802
- <key>StandardErrorPath</key><string>${xml(join14(homedir4(), "Library", "Logs", "kiosko.log"))}</string>
12611
+ <key>StandardOutPath</key><string>${xml(join15(homedir4(), "Library", "Logs", "kiosko.log"))}</string>
12612
+ <key>StandardErrorPath</key><string>${xml(join15(homedir4(), "Library", "Logs", "kiosko.log"))}</string>
10803
12613
  </dict>
10804
12614
  </plist>
10805
12615
  `;
@@ -10827,7 +12637,7 @@ CreateObject("WScript.Shell").Run ${vbs(`cmd.exe /d /s /c "${inner}"`)}, 0, Fals
10827
12637
  disable: [["schtasks", "/End", "/TN", "Kiosko"], stopProcesses(cli), ["schtasks", "/Delete", "/F", "/TN", "Kiosko"]]
10828
12638
  };
10829
12639
  }
10830
- const file = join14(process.env.XDG_CONFIG_HOME ?? join14(homedir4(), ".config"), "systemd", "user", "kiosko.service");
12640
+ const file = join15(process.env.XDG_CONFIG_HOME ?? join15(homedir4(), ".config"), "systemd", "user", "kiosko.service");
10831
12641
  const q3 = (a) => /[\s"\\]/.test(a) ? `"${a.replace(/(["\\])/g, "\\$1")}"` : a;
10832
12642
  const content = `[Unit]
10833
12643
  Description=Kiosko: widgets for USB LCD panels
@@ -10887,21 +12697,21 @@ function runService(action, plan) {
10887
12697
  // packages/server/src/server.ts
10888
12698
  import { spawn as spawn2 } from "node:child_process";
10889
12699
  import { randomBytes as randomBytes4 } from "node:crypto";
10890
- import { existsSync as existsSync16, openSync, readFileSync as readFileSync12, statSync as statSync3 } from "node:fs";
12700
+ import { existsSync as existsSync17, openSync, readFileSync as readFileSync13, statSync as statSync3 } from "node:fs";
10891
12701
  import { createServer } from "node:http";
10892
12702
  import { tmpdir as tmpdir2 } from "node:os";
10893
12703
  import { createRequire as createRequire3 } from "node:module";
10894
- import { dirname as dirname8, extname, join as join18, normalize as normPath, resolve as resolve7 } from "node:path";
12704
+ import { dirname as dirname8, extname, join as join20, normalize as normPath, resolve as resolve7 } from "node:path";
10895
12705
 
10896
12706
  // packages/server/src/plugins-manage.ts
10897
- import { execFile } from "node:child_process";
12707
+ import { execFile as execFile2 } from "node:child_process";
10898
12708
  import { existsSync as existsSync12, lstatSync as lstatSync2, mkdirSync as mkdirSync9, readFileSync as readFileSync8, rmSync as rmSync3, writeFileSync as writeFileSync10 } from "node:fs";
10899
- import { join as join15, relative as relative2, resolve as resolve6, sep } from "node:path";
12709
+ import { join as join16, relative as relative2, resolve as resolve6, sep } from "node:path";
10900
12710
  var NPM_NAME = /^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*(@[\w.^~<>=*-]+)?$/i;
10901
12711
  var packageName = (spec) => spec.startsWith("@") ? `@${spec.slice(1).split("@")[0]}` : spec.split("@")[0];
10902
12712
  function ensureFolder2(dir) {
10903
12713
  mkdirSync9(dir, { recursive: true });
10904
- const pkg = join15(dir, "package.json");
12714
+ const pkg = join16(dir, "package.json");
10905
12715
  if (!existsSync12(pkg)) writeFileSync10(pkg, `${JSON.stringify({ name: "kiosko-user-plugins", private: true, type: "module" }, null, 2)}
10906
12716
  `);
10907
12717
  }
@@ -10910,11 +12720,11 @@ var IntegrityError = class extends Error {
10910
12720
  };
10911
12721
  var realNpm = (args, cwd) => new Promise((ok, fail) => {
10912
12722
  const npm2 = process.platform === "win32" ? "npm.cmd" : "npm";
10913
- execFile(npm2, args, { cwd, timeout: 18e4, shell: process.platform === "win32" }, (err, stdout, stderr) => err ? fail(new Error((stderr || err.message).slice(-2e3))) : ok(stdout.slice(-2e3)));
12723
+ execFile2(npm2, args, { cwd, timeout: 18e4, shell: process.platform === "win32" }, (err, stdout, stderr) => err ? fail(new Error((stderr || err.message).slice(-2e3))) : ok(stdout.slice(-2e3)));
10914
12724
  });
10915
12725
  function installedIntegrity(dir, name2) {
10916
12726
  try {
10917
- const lock = JSON.parse(readFileSync8(join15(dir, "node_modules", ".package-lock.json"), "utf8"));
12727
+ const lock = JSON.parse(readFileSync8(join16(dir, "node_modules", ".package-lock.json"), "utf8"));
10918
12728
  return lock.packages?.[`node_modules/${name2}`]?.integrity;
10919
12729
  } catch {
10920
12730
  return void 0;
@@ -10926,8 +12736,8 @@ async function installPlugin(spec, o) {
10926
12736
  ensureFolder2(dir);
10927
12737
  const npm2 = o.npm ?? realNpm;
10928
12738
  const r = o.registry;
10929
- const folder = join15(dir, "node_modules", packageName(spec));
10930
- const readPkg = () => existsSync12(join15(folder, "package.json")) ? JSON.parse(readFileSync8(join15(folder, "package.json"), "utf8")) : null;
12739
+ const folder = join16(dir, "node_modules", packageName(spec));
12740
+ const readPkg = () => existsSync12(join16(folder, "package.json")) ? JSON.parse(readFileSync8(join16(folder, "package.json"), "utf8")) : null;
10931
12741
  const beforePkg = readPkg();
10932
12742
  const beforeId = beforePkg ? packageMeta(beforePkg).id : void 0;
10933
12743
  const output = await npm2(["install", "--no-audit", "--no-fund", "--ignore-scripts", "--save-exact", spec], dir);
@@ -10983,7 +12793,7 @@ async function removePlugin(id, o) {
10983
12793
  const name2 = parts[1].startsWith("@") ? `${parts[1]}/${parts[2]}` : parts[1];
10984
12794
  await (o.npm ?? realNpm)(["uninstall", "--no-audit", "--no-fund", name2], dir);
10985
12795
  } else {
10986
- const top = join15(dir, parts[0]);
12796
+ const top = join16(dir, parts[0]);
10987
12797
  if (!lstatSync2(top).isSymbolicLink()) return { removed: false, reason: `${top} is a folder you put there: delete it yourself if you mean it` };
10988
12798
  rmSync3(top);
10989
12799
  }
@@ -10999,14 +12809,14 @@ async function reloadPlugin(id, o) {
10999
12809
 
11000
12810
  // packages/server/src/store.ts
11001
12811
  import { existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync9, renameSync as renameSync4, writeFileSync as writeFileSync11 } from "node:fs";
11002
- import { dirname as dirname6, join as join16 } from "node:path";
12812
+ import { dirname as dirname6, join as join17 } from "node:path";
11003
12813
  var STORE_URL = "https://kioskolcd.dev/store/v1/";
11004
12814
  function shipped(...candidates) {
11005
12815
  for (const c of candidates) if (existsSync13(c)) return c;
11006
12816
  return null;
11007
12817
  }
11008
12818
  function snapshotIndex() {
11009
- const file = shipped(join16(import.meta.dirname, "../assets/store-index.json"), join16(import.meta.dirname, "assets/store-index.json"));
12819
+ const file = shipped(join17(import.meta.dirname, "../assets/store-index.json"), join17(import.meta.dirname, "assets/store-index.json"));
11010
12820
  try {
11011
12821
  return file ? JSON.parse(readFileSync9(file, "utf8")) : null;
11012
12822
  } catch {
@@ -11016,7 +12826,7 @@ function snapshotIndex() {
11016
12826
  var schema;
11017
12827
  function indexSchema() {
11018
12828
  if (schema !== void 0) return schema;
11019
- const file = shipped(join16(import.meta.dirname, "../../core/schema/store-index.json"), join16(import.meta.dirname, "assets/store-index.schema.json"));
12829
+ const file = shipped(join17(import.meta.dirname, "../../core/schema/store-index.json"), join17(import.meta.dirname, "assets/store-index.schema.json"));
11020
12830
  schema = file ? JSON.parse(readFileSync9(file, "utf8")) : null;
11021
12831
  return schema;
11022
12832
  }
@@ -11045,7 +12855,7 @@ var StoreCatalog = class {
11045
12855
  } else if (snap) this.state = { index: snap, from: "snapshot", fetchedAt: null, error: null };
11046
12856
  }
11047
12857
  get file() {
11048
- return join16(this.o.cacheDir, "index.json");
12858
+ return join17(this.o.cacheDir, "index.json");
11049
12859
  }
11050
12860
  readCache() {
11051
12861
  try {
@@ -11131,7 +12941,7 @@ function encodeLength(n) {
11131
12941
  } while (n > 0);
11132
12942
  return Buffer.from(out);
11133
12943
  }
11134
- var str = (s) => {
12944
+ var str2 = (s) => {
11135
12945
  const b = Buffer.from(s, "utf8");
11136
12946
  const len = Buffer.alloc(2);
11137
12947
  len.writeUInt16BE(b.length);
@@ -11140,28 +12950,28 @@ var str = (s) => {
11140
12950
  var packet = (type, flags, body2) => Buffer.concat([Buffer.from([type << 4 | flags]), encodeLength(body2.length), body2]);
11141
12951
  function connectPacket(o) {
11142
12952
  let flags = 2;
11143
- const payload = [str(o.clientId)];
12953
+ const payload = [str2(o.clientId)];
11144
12954
  if (o.will) {
11145
12955
  flags |= 4 | (o.will.retain ? 32 : 0);
11146
- payload.push(str(o.will.topic), str(o.will.payload));
12956
+ payload.push(str2(o.will.topic), str2(o.will.payload));
11147
12957
  }
11148
12958
  if (o.username) {
11149
12959
  flags |= 128;
11150
- payload.push(str(o.username));
12960
+ payload.push(str2(o.username));
11151
12961
  if (o.password) {
11152
12962
  flags |= 64;
11153
- payload.push(str(o.password));
12963
+ payload.push(str2(o.password));
11154
12964
  }
11155
12965
  }
11156
12966
  const keep = Buffer.alloc(2);
11157
12967
  keep.writeUInt16BE(o.keepalive ?? 30);
11158
- return packet(1, 0, Buffer.concat([str("MQTT"), Buffer.from([4, flags]), keep, ...payload]));
12968
+ return packet(1, 0, Buffer.concat([str2("MQTT"), Buffer.from([4, flags]), keep, ...payload]));
11159
12969
  }
11160
- var publishPacket = (topic, payload, retain = false) => packet(3, retain ? 1 : 0, Buffer.concat([str(topic), Buffer.from(payload, "utf8")]));
12970
+ var publishPacket = (topic, payload, retain = false) => packet(3, retain ? 1 : 0, Buffer.concat([str2(topic), Buffer.from(payload, "utf8")]));
11161
12971
  function subscribePacket(id, topics) {
11162
12972
  const pid = Buffer.alloc(2);
11163
12973
  pid.writeUInt16BE(id);
11164
- return packet(8, 2, Buffer.concat([pid, ...topics.map((t2) => Buffer.concat([str(t2), Buffer.from([0])]))]));
12974
+ return packet(8, 2, Buffer.concat([pid, ...topics.map((t2) => Buffer.concat([str2(t2), Buffer.from([0])]))]));
11165
12975
  }
11166
12976
  function readPackets(buf) {
11167
12977
  const packets = [];
@@ -11394,21 +13204,21 @@ var HomeAssistantBridge = class {
11394
13204
  }
11395
13205
  this.disconnect();
11396
13206
  this.link = want;
11397
- const base3 = `kiosko/${want.nodeId}`;
13207
+ const base4 = `kiosko/${want.nodeId}`;
11398
13208
  const c = this.makeClient({
11399
13209
  url: want.broker,
11400
13210
  clientId: `kiosko-${want.nodeId}-${hostname3().slice(0, 20)}`.slice(0, 23),
11401
13211
  ...want.username ? { username: want.username } : {},
11402
13212
  ...want.password ? { password: want.password } : {},
11403
13213
  keepalive: 30,
11404
- will: { topic: `${base3}/status`, payload: "offline", retain: true }
13214
+ will: { topic: `${base4}/status`, payload: "offline", retain: true }
11405
13215
  });
11406
13216
  this.client = c;
11407
13217
  c.on("connect", () => {
11408
13218
  if (this.client !== c) return;
11409
13219
  this.last.clear();
11410
- c.publish(`${base3}/status`, "online", true);
11411
- c.subscribe([`${base3}/+/page/set`, `${base3}/+/display/set`, `${base3}/+/interlude/+/press`, `${base3}/alerts/ack/press`, `${this.link.discoveryPrefix}/status`]);
13220
+ c.publish(`${base4}/status`, "online", true);
13221
+ c.subscribe([`${base4}/+/page/set`, `${base4}/+/display/set`, `${base4}/+/interlude/+/press`, `${base4}/alerts/ack/press`, `${this.link.discoveryPrefix}/status`]);
11412
13222
  this.announce();
11413
13223
  });
11414
13224
  c.on("message", (topic, payload) => this.client === c && this.onMessage(topic, payload));
@@ -11574,17 +13384,177 @@ var HomeAssistantBridge = class {
11574
13384
  }
11575
13385
  };
11576
13386
 
13387
+ // packages/server/src/push-api.ts
13388
+ import { createHash as createHash4, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
13389
+ import { chmodSync as chmodSync2, existsSync as existsSync14, readFileSync as readFileSync10, renameSync as renameSync5, writeFileSync as writeFileSync12 } from "node:fs";
13390
+ import { join as join18 } from "node:path";
13391
+ var MIN_TOKEN_LENGTH = 16;
13392
+ var PUSH_RATE = { burst: 20, perSecond: 5 };
13393
+ var TooLarge = class extends Error {
13394
+ };
13395
+ async function rawBody(req, limit) {
13396
+ const hardCap = limit * 16;
13397
+ const declared = Number(req.headers["content-length"]);
13398
+ if (Number.isFinite(declared) && declared > hardCap) throw new TooLarge();
13399
+ const chunks = [];
13400
+ let size = 0;
13401
+ for await (const c of req) {
13402
+ size += c.length;
13403
+ if (size > hardCap) break;
13404
+ if (size <= limit) chunks.push(c);
13405
+ }
13406
+ if (size > limit) throw new TooLarge();
13407
+ return Buffer.concat(chunks);
13408
+ }
13409
+ var formValue = (v) => /^\s*-?(\d+\.?\d*|\.\d+)\s*$/.test(v) ? Number(v) : v;
13410
+ function parsePushBody(buf, contentType) {
13411
+ const text3 = buf.toString("utf8").replace(/^/, "");
13412
+ if (!text3.trim()) return { ok: false, error: "empty body" };
13413
+ const type = (contentType ?? "").toLowerCase();
13414
+ try {
13415
+ return { ok: true, payload: JSON.parse(text3) };
13416
+ } catch {
13417
+ if (type.includes("json")) return { ok: false, error: "the body is not valid JSON" };
13418
+ }
13419
+ if (type.startsWith("application/x-www-form-urlencoded") && /^[^\s=&]+=/.test(text3)) {
13420
+ return { ok: true, payload: Object.fromEntries([...new URLSearchParams(text3)].map(([k, v]) => [k, formValue(v)])) };
13421
+ }
13422
+ return { ok: true, payload: { text: text3.trim() } };
13423
+ }
13424
+ var digest = (s) => createHash4("sha256").update(s).digest();
13425
+ function sameToken(given, expected) {
13426
+ if (expected.length < MIN_TOKEN_LENGTH || !given) return false;
13427
+ return timingSafeEqual2(digest(given), digest(expected));
13428
+ }
13429
+ function tokenOf(req, url2) {
13430
+ const auth = req.headers.authorization ?? "";
13431
+ const m = /^Bearer\s+(\S+)\s*$/i.exec(auth);
13432
+ return m ? m[1] : url2.searchParams.get("token") ?? "";
13433
+ }
13434
+ function pushApi(o) {
13435
+ const store = o.store ?? pushes;
13436
+ const now = o.now ?? Date.now;
13437
+ const buckets = /* @__PURE__ */ new Map();
13438
+ const hooks = (cfg) => cfg.push?.hooks ?? [];
13439
+ const sync = (cfg) => store.configure(hooks(cfg).map((h) => h.name));
13440
+ sync(o.runtime.config);
13441
+ if (o.file && existsSync14(o.file)) {
13442
+ try {
13443
+ store.load(JSON.parse(readFileSync10(o.file, "utf8")));
13444
+ } catch {
13445
+ }
13446
+ }
13447
+ const onConfig = (cfg) => sync(cfg);
13448
+ o.runtime.on("config", onConfig);
13449
+ let saveTimer = null;
13450
+ const save = () => {
13451
+ saveTimer = null;
13452
+ if (!o.file) return;
13453
+ try {
13454
+ const tmp = `${o.file}.tmp`;
13455
+ writeFileSync12(tmp, JSON.stringify(store.dump()), { mode: 384 });
13456
+ renameSync5(tmp, o.file);
13457
+ if (process.platform !== "win32") chmodSync2(o.file, 384);
13458
+ } catch {
13459
+ }
13460
+ };
13461
+ const unsubscribe = store.subscribe(() => {
13462
+ if (!o.file || saveTimer) return;
13463
+ saveTimer = setTimeout(save, 1e3);
13464
+ saveTimer.unref?.();
13465
+ });
13466
+ function allowed(name2) {
13467
+ const t2 = now();
13468
+ const b = buckets.get(name2) ?? { tokens: PUSH_RATE.burst, at: t2 };
13469
+ b.tokens = Math.min(PUSH_RATE.burst, b.tokens + (t2 - b.at) / 1e3 * PUSH_RATE.perSecond);
13470
+ b.at = t2;
13471
+ buckets.set(name2, b);
13472
+ if (b.tokens < 1) return false;
13473
+ b.tokens -= 1;
13474
+ return true;
13475
+ }
13476
+ async function handle(req, res, url2) {
13477
+ const m = /^\/api\/push\/([^/]+)\/?$/.exec(url2.pathname);
13478
+ if (!m) return false;
13479
+ const method = req.method ?? "GET";
13480
+ res.setHeader("cache-control", "no-store");
13481
+ let name2;
13482
+ try {
13483
+ name2 = decodeURIComponent(m[1]).toLowerCase();
13484
+ } catch {
13485
+ name2 = "";
13486
+ }
13487
+ const hook = hooks(o.runtime.config).find((h) => h.name === name2);
13488
+ if (!hook || !sameToken(tokenOf(req, url2), hook.token)) {
13489
+ req.resume();
13490
+ res.setHeader("www-authenticate", 'Bearer realm="kiosko-push"');
13491
+ o.json(res, 401, { error: "unknown push name or wrong token", code: "unauthorized" });
13492
+ return true;
13493
+ }
13494
+ if (!allowed(name2)) {
13495
+ req.resume();
13496
+ res.setHeader("retry-after", "1");
13497
+ o.json(res, 429, { error: `more than ${PUSH_RATE.perSecond} pushes a second`, code: "rateLimited" });
13498
+ return true;
13499
+ }
13500
+ if (method === "GET") {
13501
+ const e2 = store.get(name2);
13502
+ o.json(res, 200, e2 ? { name: name2, at: e2.at, payload: e2.payload, ...e2.expiresAt ? { expiresAt: e2.expiresAt } : {} } : { name: name2, at: null, payload: null });
13503
+ return true;
13504
+ }
13505
+ if (method === "DELETE") {
13506
+ store.clear(name2);
13507
+ o.json(res, 200, { ok: true });
13508
+ return true;
13509
+ }
13510
+ if (method !== "POST" && method !== "PUT") {
13511
+ req.resume();
13512
+ res.setHeader("allow", "GET, POST, PUT, DELETE");
13513
+ o.json(res, 405, { error: "use POST", code: "method" });
13514
+ return true;
13515
+ }
13516
+ let buf;
13517
+ try {
13518
+ buf = await rawBody(req, PUSH_LIMITS.maxBytes);
13519
+ } catch (err) {
13520
+ if (!(err instanceof TooLarge)) throw err;
13521
+ res.setHeader("connection", "close");
13522
+ o.json(res, 413, { error: `body larger than ${PUSH_LIMITS.maxBytes / 1024} KB`, code: "tooLarge" });
13523
+ return true;
13524
+ }
13525
+ const parsed = parsePushBody(buf, req.headers["content-type"]);
13526
+ if (!parsed.ok) {
13527
+ o.json(res, 400, { error: parsed.error, code: "badBody" });
13528
+ return true;
13529
+ }
13530
+ const e = store.set(name2, parsed.payload, now());
13531
+ o.json(res, 200, { ok: true, name: name2, at: e.at, ...e.expiresAt ? { expiresAt: e.expiresAt } : {} });
13532
+ return true;
13533
+ }
13534
+ const status = () => hooks(o.runtime.config).map((h) => ({ name: h.name, at: store.get(h.name)?.at ?? null }));
13535
+ function close() {
13536
+ o.runtime.off("config", onConfig);
13537
+ unsubscribe();
13538
+ if (saveTimer) {
13539
+ clearTimeout(saveTimer);
13540
+ save();
13541
+ }
13542
+ }
13543
+ return { handle, status, close };
13544
+ }
13545
+ var pushFile = (home) => join18(home, "push.json");
13546
+
11577
13547
  // packages/server/src/install-kind.ts
11578
- import { existsSync as existsSync14, readFileSync as readFileSync10, realpathSync } from "node:fs";
13548
+ import { existsSync as existsSync15, readFileSync as readFileSync11, realpathSync } from "node:fs";
11579
13549
  import { posix, win32 as win323 } from "node:path";
11580
13550
  function detectInstall(i) {
11581
- const exists = i.exists ?? existsSync14;
11582
- const read = i.readFile ?? ((p) => readFileSync10(p, "utf8"));
13551
+ const exists = i.exists ?? existsSync15;
13552
+ const read = i.readFile ?? ((p) => readFileSync11(p, "utf8"));
11583
13553
  const win = i.platform === "win32";
11584
13554
  const P2 = win ? win323 : posix;
11585
13555
  const cli = i.cli;
11586
13556
  const service2 = detectService(i.platform, i.env, read);
11587
- const base3 = { cli, service: service2, platform: i.platform };
13557
+ const base4 = { cli, service: service2, platform: i.platform };
11588
13558
  const norm = (p) => win ? p.toLowerCase() : p;
11589
13559
  const gitUp = (from) => {
11590
13560
  for (let d = from, n = 0; n < 8; n++) {
@@ -11595,25 +13565,25 @@ function detectInstall(i) {
11595
13565
  }
11596
13566
  return null;
11597
13567
  };
11598
- if (cli.endsWith(".ts")) return { ...base3, kind: "source", dir: gitUp(P2.dirname(cli)) ?? P2.resolve(P2.dirname(cli), "..", "..", "..") };
13568
+ if (cli.endsWith(".ts")) return { ...base4, kind: "source", dir: gitUp(P2.dirname(cli)) ?? P2.resolve(P2.dirname(cli), "..", "..", "..") };
11599
13569
  const dir = P2.dirname(cli);
11600
13570
  if (win && P2.basename(dir).toLowerCase() === "app") {
11601
13571
  const app = P2.dirname(dir);
11602
13572
  if (exists(P2.join(app, "kiosko.cmd")) && exists(P2.join(app, "unins000.exe")) && norm(i.execPath) === norm(P2.join(app, "node.exe"))) {
11603
13573
  const local = i.env.LOCALAPPDATA && norm(app).startsWith(norm(P2.join(i.env.LOCALAPPDATA, "Programs") + P2.sep));
11604
- return { ...base3, kind: "windows-installer", dir: app, perUser: !!local };
13574
+ return { ...base4, kind: "windows-installer", dir: app, perUser: !!local };
11605
13575
  }
11606
13576
  }
11607
13577
  const checkout = gitUp(dir);
11608
- if (checkout && !/[\\/]node_modules[\\/]/.test(dir)) return { ...base3, kind: "source", dir: checkout };
11609
- if (/[\\/]_npx[\\/]/.test(dir)) return { ...base3, kind: "npx", dir };
13578
+ if (checkout && !/[\\/]node_modules[\\/]/.test(dir)) return { ...base4, kind: "source", dir: checkout };
13579
+ if (/[\\/]_npx[\\/]/.test(dir)) return { ...base4, kind: "npx", dir };
11610
13580
  if (P2.basename(dir) === "kiosko" && P2.basename(P2.dirname(dir)) === "node_modules") {
11611
13581
  const nm = P2.dirname(dir);
11612
13582
  const prefix = win ? P2.dirname(nm) : P2.basename(P2.dirname(nm)) === "lib" ? P2.dirname(P2.dirname(nm)) : null;
11613
13583
  const shim = prefix && (win ? exists(P2.join(prefix, "kiosko.cmd")) : exists(P2.join(prefix, "bin", "kiosko")));
11614
- if (prefix && shim) return { ...base3, kind: "npm-global", dir, prefix };
13584
+ if (prefix && shim) return { ...base4, kind: "npm-global", dir, prefix };
11615
13585
  }
11616
- return { ...base3, kind: "other", dir };
13586
+ return { ...base4, kind: "other", dir };
11617
13587
  }
11618
13588
  function detectService(platform3, env, read) {
11619
13589
  if (platform3 === "linux") {
@@ -11658,9 +13628,9 @@ function updateBlocker(info, o = {}) {
11658
13628
 
11659
13629
  // packages/server/src/self-update.ts
11660
13630
  import { spawn } from "node:child_process";
11661
- import { createHash as createHash3 } from "node:crypto";
11662
- import { createReadStream, createWriteStream, existsSync as existsSync15, mkdirSync as mkdirSync11, readFileSync as readFileSync11, realpathSync as realpathSync2, rmSync as rmSync4, writeFileSync as writeFileSync12 } from "node:fs";
11663
- import { dirname as dirname7, join as join17, win32 as win324 } from "node:path";
13631
+ import { createHash as createHash5 } from "node:crypto";
13632
+ import { createReadStream, createWriteStream, existsSync as existsSync16, mkdirSync as mkdirSync11, readFileSync as readFileSync12, realpathSync as realpathSync2, rmSync as rmSync4, writeFileSync as writeFileSync13 } from "node:fs";
13633
+ import { dirname as dirname7, join as join19, win32 as win324 } from "node:path";
11664
13634
  import { Readable, Transform } from "node:stream";
11665
13635
  import { pipeline } from "node:stream/promises";
11666
13636
  var UpdateError = class extends Error {
@@ -11695,15 +13665,8 @@ function judgeSelfCheck(now, next, target) {
11695
13665
  if (missing.length || fresh.length) return { ok: false, why: [missing.length ? `plugins that would not load: ${missing.join(", ")}` : "", ...fresh.map((p) => `${p.origin}: ${p.message}`)].filter(Boolean).join("; "), warnings };
11696
13666
  return { ok: true, warnings };
11697
13667
  }
11698
- function parseSha256File(text3, name2) {
11699
- for (const line of text3.split(/\r?\n/)) {
11700
- const m = /^([a-f0-9]{64})(?:\s+\*?(.+?))?\s*$/i.exec(line.trim());
11701
- if (m && (!m[2] || m[2] === name2)) return m[1].toLowerCase();
11702
- }
11703
- return null;
11704
- }
11705
13668
  async function sha256File(file) {
11706
- const h = createHash3("sha256");
13669
+ const h = createHash5("sha256");
11707
13670
  await pipeline(createReadStream(file), h);
11708
13671
  return h.digest("hex");
11709
13672
  }
@@ -11773,8 +13736,8 @@ var KioskoUpdater = class {
11773
13736
  }
11774
13737
  /** npm next to this Node (nvm, Homebrew…), else the one on the PATH. */
11775
13738
  npm() {
11776
- const here = join17(dirname7(this.d.node), process.platform === "win32" ? "npm.cmd" : "npm");
11777
- return existsSync15(here) ? here : process.platform === "win32" ? "npm.cmd" : "npm";
13739
+ const here = join19(dirname7(this.d.node), process.platform === "win32" ? "npm.cmd" : "npm");
13740
+ return existsSync16(here) ? here : process.platform === "win32" ? "npm.cmd" : "npm";
11778
13741
  }
11779
13742
  registryArgs() {
11780
13743
  return this.d.registry && this.d.registry !== REGISTRY ? [`--registry=${this.d.registry}`] : [];
@@ -11936,10 +13899,10 @@ var KioskoUpdater = class {
11936
13899
  async downloadInstaller(version) {
11937
13900
  const name2 = windowsInstallerName(version);
11938
13901
  const exeUrl = releaseAsset(version, name2);
11939
- const dir = join17(this.d.tmpDir, `kiosko-update-${version}`);
13902
+ const dir = join19(this.d.tmpDir, `kiosko-update-${version}`);
11940
13903
  rmSync4(dir, { recursive: true, force: true });
11941
13904
  mkdirSync11(dir, { recursive: true });
11942
- const file = join17(dir, name2);
13905
+ const file = join19(dir, name2);
11943
13906
  this.step("download", null, exeUrl);
11944
13907
  let expected;
11945
13908
  try {
@@ -11954,7 +13917,7 @@ var KioskoUpdater = class {
11954
13917
  this.step("download", false, `${name2}.sha256 names no checksum for ${name2}`);
11955
13918
  throw new UpdateError("hashMissing", `the release has no usable checksum for ${name2}: not running it`);
11956
13919
  }
11957
- const hash = createHash3("sha256");
13920
+ const hash2 = createHash5("sha256");
11958
13921
  let size = 0;
11959
13922
  try {
11960
13923
  const r = await this.d.fetch(exeUrl, { redirect: "follow" });
@@ -11963,7 +13926,7 @@ var KioskoUpdater = class {
11963
13926
  transform(chunk, _e, cb) {
11964
13927
  size += chunk.length;
11965
13928
  if (size > 500 * 1024 * 1024) return cb(new Error("larger than 500 MB: not an installer of ours"));
11966
- hash.update(chunk);
13929
+ hash2.update(chunk);
11967
13930
  cb(null, chunk);
11968
13931
  }
11969
13932
  });
@@ -11974,7 +13937,7 @@ var KioskoUpdater = class {
11974
13937
  throw new UpdateError("downloadFailed", `could not download ${name2}: ${err instanceof Error ? err.message : String(err)}`);
11975
13938
  }
11976
13939
  this.step("download", true, `${(size / 1024 / 1024).toFixed(1)} MB`);
11977
- const got = hash.digest("hex");
13940
+ const got = hash2.digest("hex");
11978
13941
  if (got !== expected) {
11979
13942
  rmSync4(dir, { recursive: true, force: true });
11980
13943
  this.step("hash", false, `sha256 ${got}, the release says ${expected}`);
@@ -11996,11 +13959,11 @@ var KioskoUpdater = class {
11996
13959
  const info = this.d.install;
11997
13960
  const dir = dirname7(this.file);
11998
13961
  const service2 = await this.d.serviceTask?.().catch(() => false) ?? false;
11999
- const script = join17(dir, "kiosko-upgrade.cmd");
13962
+ const script = join19(dir, "kiosko-upgrade.cmd");
12000
13963
  const log = win324.join(this.d.home, "kiosko.log");
12001
- writeFileSync12(script, windowsUpgradeScript({ exe: this.file, args: installerArgs(!!info.perUser, join17(dir, "install.log")), dir: info.dir, service: service2, port: this.d.port, log }));
13964
+ writeFileSync13(script, windowsUpgradeScript({ exe: this.file, args: installerArgs(!!info.perUser, join19(dir, "install.log")), dir: info.dir, service: service2, port: this.d.port, log }));
12002
13965
  this.d.mark?.({ from: this.d.current, to: version, at: this.now, how: "installer", lines: this.lines.slice(-30) });
12003
- this.step("launch", true, `${this.file} ${installerArgs(!!info.perUser, join17(dir, "install.log")).join(" ")}${info.perUser ? "" : " (the wizard: this Kiosko is not installed per user)"}`);
13966
+ this.step("launch", true, `${this.file} ${installerArgs(!!info.perUser, join19(dir, "install.log")).join(" ")}${info.perUser ? "" : " (the wizard: this Kiosko is not installed per user)"}`);
12004
13967
  this.set({ state: "restarting", restart: "installer" });
12005
13968
  this.d.launch?.(script);
12006
13969
  return this.status;
@@ -12029,19 +13992,19 @@ var realRun = (cmd2, args, o = {}) => new Promise((ok) => {
12029
13992
  ok({ code: code ?? 1, stdout, stderr });
12030
13993
  });
12031
13994
  });
12032
- var markerFile = (home) => join17(home, "update.json");
13995
+ var markerFile = (home) => join19(home, "update.json");
12033
13996
  function writeMarker(home, m) {
12034
13997
  if (!m) return void rmSync4(markerFile(home), { force: true });
12035
13998
  mkdirSync11(home, { recursive: true });
12036
- writeFileSync12(markerFile(home), `${JSON.stringify(m)}
13999
+ writeFileSync13(markerFile(home), `${JSON.stringify(m)}
12037
14000
  `);
12038
14001
  }
12039
14002
  function readMarker(home, version, now = Date.now()) {
12040
14003
  const f = markerFile(home);
12041
- if (!existsSync15(f)) return null;
14004
+ if (!existsSync16(f)) return null;
12042
14005
  let m = {};
12043
14006
  try {
12044
- m = JSON.parse(readFileSync11(f, "utf8"));
14007
+ m = JSON.parse(readFileSync12(f, "utf8"));
12045
14008
  } catch {
12046
14009
  }
12047
14010
  rmSync4(f, { force: true });
@@ -12069,10 +14032,10 @@ var realDiscover = async (url2, tokenFile) => {
12069
14032
  return { trcc, usb, remote };
12070
14033
  };
12071
14034
  function webRoot() {
12072
- const bundled = join18(import.meta.dirname, "web");
12073
- if (existsSync16(join18(bundled, "index.html"))) return bundled;
14035
+ const bundled = join20(import.meta.dirname, "web");
14036
+ if (existsSync17(join20(bundled, "index.html"))) return bundled;
12074
14037
  try {
12075
- return join18(dirname8(require3.resolve("@kiosko/web/package.json")), "dist");
14038
+ return join20(dirname8(require3.resolve("@kiosko/web/package.json")), "dist");
12076
14039
  } catch {
12077
14040
  return resolve7(import.meta.dirname, "../../web/dist");
12078
14041
  }
@@ -12114,7 +14077,7 @@ function startServer(o) {
12114
14077
  const checking = o.checkUpdates ?? (!runtime.demoMode && process.env.KIOSKO_NO_UPDATE_CHECK !== "1");
12115
14078
  const updateTimers = checking ? [setTimeout(() => void refreshUpdates().catch(() => void 0), 2e4), setInterval(() => void refreshUpdates().catch(() => void 0), 24 * 36e5)] : [];
12116
14079
  for (const t2 of updateTimers) t2.unref?.();
12117
- const store = o.store ?? new StoreCatalog({ cacheDir: join18(paths.home, "store") });
14080
+ const store = o.store ?? new StoreCatalog({ cacheDir: join20(paths.home, "store") });
12118
14081
  const storeTimers = checking ? [setTimeout(() => void store.refresh(), 15e3), setInterval(() => void store.refresh(), 24 * 36e5)] : [];
12119
14082
  for (const t2 of storeTimers) t2.unref?.();
12120
14083
  const home = o.home ?? paths.home;
@@ -12126,7 +14089,7 @@ function startServer(o) {
12126
14089
  const probeHost = o.host === "0.0.0.0" || o.host === "::" ? "127.0.0.1" : o.host.includes(":") ? `[${o.host}]` : o.host;
12127
14090
  const handover = {
12128
14091
  instance,
12129
- logFile: join18(home, "kiosko.log"),
14092
+ logFile: join20(home, "kiosko.log"),
12130
14093
  release: async () => {
12131
14094
  runtime.stop();
12132
14095
  for (const c of clients) c.end();
@@ -12148,7 +14111,7 @@ function startServer(o) {
12148
14111
  runtime.start();
12149
14112
  },
12150
14113
  spawn: () => {
12151
- const out = openSync(join18(home, "kiosko.log"), "a");
14114
+ const out = openSync(join20(home, "kiosko.log"), "a");
12152
14115
  const args = process.argv.slice(2).filter((a) => a !== "--open");
12153
14116
  const child = spawn2(process.execPath, [...process.execArgv, install.cli, ...args], { detached: true, stdio: ["ignore", out, out], env: process.env, cwd: process.cwd(), windowsHide: true });
12154
14117
  const exited = new Promise((ok) => {
@@ -12232,7 +14195,8 @@ data: ${JSON.stringify(data)}
12232
14195
  runtime.on("log", onLog);
12233
14196
  runtime.on("config", () => thumbs.clear());
12234
14197
  const bridge = o.homeassistant ?? !runtime.demoMode ? new HomeAssistantBridge(runtime, o.version) : null;
12235
- const fullStatus = () => ({ ...runtime.status(), homeassistant: bridge?.status() ?? { enabled: false, state: "off", error: null } });
14198
+ const push3 = pushApi({ runtime, json, ...runtime.demoMode ? {} : { file: pushFile(home) } });
14199
+ const fullStatus = () => ({ ...runtime.status(), homeassistant: bridge?.status() ?? { enabled: false, state: "off", error: null }, push: push3.status() });
12236
14200
  const statusTimer = setInterval(() => send("status", fullStatus()), 3e3);
12237
14201
  const allowedHosts = /* @__PURE__ */ new Set([`127.0.0.1:${o.port}`, `localhost:${o.port}`, `[::1]:${o.port}`, `${o.host}:${o.port}`]);
12238
14202
  function uiLocale(req) {
@@ -12266,6 +14230,8 @@ data: ${JSON.stringify(data)}
12266
14230
  }
12267
14231
  const remote = remoteApi({
12268
14232
  runtime,
14233
+ version: o.version,
14234
+ ...o.firmwareFetch ? { fetch: o.firmwareFetch } : {},
12269
14235
  json,
12270
14236
  body,
12271
14237
  commit: (cfg) => {
@@ -12282,6 +14248,7 @@ data: ${JSON.stringify(data)}
12282
14248
  async function api(req, res, url2) {
12283
14249
  const p = url2.pathname;
12284
14250
  const m = req.method ?? "GET";
14251
+ if (p.startsWith("/api/push/") && await push3.handle(req, res, url2)) return;
12285
14252
  if (m !== "GET" && req.headers["x-kiosko"] !== "1") return json(res, 403, { error: "missing X-Kiosko header" });
12286
14253
  if (p === "/api/state" && m === "GET") return json(res, 200, state(req));
12287
14254
  if (p === "/api/config" && m === "PUT") {
@@ -12436,7 +14403,23 @@ data: ${JSON.stringify({ version: o.version })}
12436
14403
  if (p === "/api/choices" && m === "GET") {
12437
14404
  const source = url2.searchParams.get("source") ?? "";
12438
14405
  const list2 = url2.searchParams.get("list") ?? "";
12439
- return json(res, 200, runtime.registry.choices(source, list2, runtime.hub.data(source), uiLocale(req)));
14406
+ const key = resolveSourceKey(runtime.config, source, url2.searchParams.get("profile"), runtime.registry.source(source));
14407
+ return json(res, 200, runtime.registry.choices(source, list2, runtime.hub.data(key), uiLocale(req)));
14408
+ }
14409
+ if (p === "/api/source-paths" && m === "GET") {
14410
+ const source = url2.searchParams.get("source") ?? "";
14411
+ const def = runtime.registry.source(source);
14412
+ if (!def) return json(res, 404, { error: `no source ${source}`, code: "noSource" });
14413
+ const live2 = runtime.hub.data(source);
14414
+ let data = live2;
14415
+ if (data === void 0 && def.demo) {
14416
+ try {
14417
+ data = def.demo({ now: Date.now(), locale: uiLocale(req) });
14418
+ } catch {
14419
+ data = void 0;
14420
+ }
14421
+ }
14422
+ return json(res, 200, { paths: dataPaths(data), from: live2 !== void 0 ? "live" : data !== void 0 ? "demo" : "none" });
12440
14423
  }
12441
14424
  if (p === "/api/plugins/install" && m === "POST") {
12442
14425
  const b = await body(req);
@@ -12569,16 +14552,16 @@ data: ${JSON.stringify({ version: o.version })}
12569
14552
  }
12570
14553
  function serveStatic(res, pathname) {
12571
14554
  const rel = normPath(decodeURIComponent(pathname)).replace(/^([/\\])+/, "");
12572
- let file = join18(root, rel || "index.html");
14555
+ let file = join20(root, rel || "index.html");
12573
14556
  if (!file.startsWith(root)) return void json(res, 400, { error: "bad path" });
12574
- if (!existsSync16(file) || statSync3(file).isDirectory()) file = join18(root, "index.html");
12575
- if (!existsSync16(file)) {
14557
+ if (!existsSync17(file) || statSync3(file).isDirectory()) file = join20(root, "index.html");
14558
+ if (!existsSync17(file)) {
12576
14559
  res.writeHead(500, { "content-type": "text/plain" });
12577
14560
  return void res.end("The editor is not built. Run `npm run web:build`.");
12578
14561
  }
12579
14562
  const ext = extname(file);
12580
14563
  res.writeHead(200, { "content-type": MIME[ext] ?? "application/octet-stream", "cache-control": ext === ".html" ? "no-cache" : "max-age=300" });
12581
- res.end(readFileSync12(file));
14564
+ res.end(readFileSync13(file));
12582
14565
  }
12583
14566
  const server = createServer((req, res) => {
12584
14567
  const host = req.headers.host ?? "";
@@ -12603,6 +14586,7 @@ data: ${JSON.stringify({ version: o.version })}
12603
14586
  function close() {
12604
14587
  clearInterval(statusTimer);
12605
14588
  bridge?.stop();
14589
+ push3.close();
12606
14590
  for (const t2 of updateTimers) clearTimeout(t2);
12607
14591
  for (const t2 of storeTimers) clearTimeout(t2);
12608
14592
  runtime.off("frame", onFrame);
@@ -12616,17 +14600,17 @@ data: ${JSON.stringify({ version: o.version })}
12616
14600
  }
12617
14601
 
12618
14602
  // packages/server/src/starter.ts
12619
- import { existsSync as existsSync17, readdirSync as readdirSync5 } from "node:fs";
14603
+ import { existsSync as existsSync18, readdirSync as readdirSync5 } from "node:fs";
12620
14604
  import { homedir as homedir5 } from "node:os";
12621
- import { join as join19 } from "node:path";
14605
+ import { join as join21 } from "node:path";
12622
14606
  var ROTATIONS2 = [0, 90, 180, 270];
12623
14607
  function starterPanels(found, trccUrl = "http://127.0.0.1:8099") {
12624
14608
  const out = [];
12625
14609
  const named = (width, height) => {
12626
- const base3 = PANEL_PRESETS.find((p) => p.width === width && p.height === height || p.width === height && p.height === width)?.name ?? `${width}\xD7${height}`;
12627
- const same3 = out.filter((p) => p.name === base3 || p.name.startsWith(`${base3} `)).length;
12628
- if (same3 === 1) out.find((p) => p.name === base3).name = `${base3} 1`;
12629
- return same3 ? `${base3} ${same3 + 1}` : base3;
14610
+ const base4 = PANEL_PRESETS.find((p) => p.width === width && p.height === height || p.width === height && p.height === width)?.name ?? `${width}\xD7${height}`;
14611
+ const same3 = out.filter((p) => p.name === base4 || p.name.startsWith(`${base4} `)).length;
14612
+ if (same3 === 1) out.find((p) => p.name === base4).name = `${base4} 1`;
14613
+ return same3 ? `${base4} ${same3 + 1}` : base4;
12630
14614
  };
12631
14615
  for (const u of found.usb) {
12632
14616
  const width = u.width || 1920;
@@ -12637,10 +14621,10 @@ function starterPanels(found, trccUrl = "http://127.0.0.1:8099") {
12637
14621
  return out;
12638
14622
  }
12639
14623
  function agentTraces(env = process.env, home = homedir5()) {
12640
- const dirs = [env.AGENT_SESSIONS_DIR ?? join19(env.AIMONITOR_DIR ?? join19(home, ".aimonitor"), "sessions"), join19(home, ".codex", "sessions"), join19(home, ".qwen", "projects"), join19(home, ".kimi", "sessions")];
14624
+ const dirs = [env.AGENT_SESSIONS_DIR ?? join21(env.AIMONITOR_DIR ?? join21(home, ".aimonitor"), "sessions"), join21(home, ".codex", "sessions"), join21(home, ".qwen", "projects"), join21(home, ".kimi", "sessions")];
12641
14625
  return dirs.some((d) => {
12642
14626
  try {
12643
- return existsSync17(d) && readdirSync5(d).length > 0;
14627
+ return existsSync18(d) && readdirSync5(d).length > 0;
12644
14628
  } catch {
12645
14629
  return false;
12646
14630
  }
@@ -12668,7 +14652,7 @@ function starterConfig(registry2, o = {}) {
12668
14652
  }
12669
14653
 
12670
14654
  // packages/server/src/cli.ts
12671
- var VERSION = "0.2.10";
14655
+ var VERSION = "0.2.12";
12672
14656
  var USAGE2 = `Kiosko ${VERSION}: a widget mosaic for USB LCD panels
12673
14657
 
12674
14658
  kiosko start [--port 7420] [--host 127.0.0.1] [--config file] [--open] [--demo]
@@ -12698,7 +14682,7 @@ var opt = (name2) => {
12698
14682
  const i = argv.indexOf(name2);
12699
14683
  return i >= 0 ? argv[i + 1] : void 0;
12700
14684
  };
12701
- var SCREEN_THREAD = ["./screen-thread.js", "./screen-thread.ts"].map((f) => new URL(f, import.meta.url)).find((u) => existsSync18(u));
14685
+ var SCREEN_THREAD = ["./screen-thread.js", "./screen-thread.ts"].map((f) => new URL(f, import.meta.url)).find((u) => existsSync19(u));
12702
14686
  var THREADS = SCREEN_THREAD ? { threadEntry: SCREEN_THREAD } : {};
12703
14687
  async function registry() {
12704
14688
  installSdkResolver();
@@ -12746,8 +14730,8 @@ async function main() {
12746
14730
  const cfg = await config(reg, path);
12747
14731
  const host = opt("--host") ?? cfg.server.host;
12748
14732
  const port = Number(opt("--port") ?? cfg.server.port);
12749
- const shown = host === "0.0.0.0" || host === "::" || !host ? "127.0.0.1" : host;
12750
- const editorAt = `http://${shown.includes(":") ? `[${shown}]` : shown}:${port}`;
14733
+ const shown2 = host === "0.0.0.0" || host === "::" || !host ? "127.0.0.1" : host;
14734
+ const editorAt = `http://${shown2.includes(":") ? `[${shown2}]` : shown2}:${port}`;
12751
14735
  const rt = new Runtime(reg, cfg, { demo: flag("--demo"), welcome: true, editorUrl: editorAt, ...THREADS });
12752
14736
  if (flag("--demo")) console.log("demo mode: every widget shows sample data, nothing is read");
12753
14737
  rt.start();
@@ -12804,20 +14788,20 @@ async function main() {
12804
14788
  }
12805
14789
  case "import-aimonitor": {
12806
14790
  const from = opt("--from") ?? `${process.env.HOME ?? ""}/.aimonitor/config.json`;
12807
- if (!existsSync18(from)) {
14791
+ if (!existsSync19(from)) {
12808
14792
  console.error(`not found: ${from}`);
12809
14793
  process.exit(1);
12810
14794
  }
12811
14795
  const reg = await registry();
12812
- const modePath = join20(dirname9(from), "modo");
12813
- const modeOverride = existsSync18(modePath) ? readFileSync13(modePath, "utf8") : null;
12814
- const { config: imported, notes } = importAimonitor(JSON.parse(readFileSync13(from, "utf8")), reg, modeOverride, { withSecrets: flag("--with-secrets") });
14796
+ const modePath = join22(dirname9(from), "modo");
14797
+ const modeOverride = existsSync19(modePath) ? readFileSync14(modePath, "utf8") : null;
14798
+ const { config: imported, notes } = importAimonitor(JSON.parse(readFileSync14(from, "utf8")), reg, modeOverride, { withSecrets: flag("--with-secrets") });
12815
14799
  if (modeOverride) notes.push(`mode from ${modePath}: ${modeOverride.trim()}`);
12816
14800
  for (const n of notes) console.log(`- ${n}`);
12817
14801
  if (flag("--write")) {
12818
- if (existsSync18(path)) writeFileSync13(`${path}.bak`, readFileSync13(path));
14802
+ if (existsSync19(path)) writeFileSync14(`${path}.bak`, readFileSync14(path));
12819
14803
  saveConfig(imported, path);
12820
- console.log(`written ${path}${existsSync18(`${path}.bak`) ? ` (previous one in ${path}.bak)` : ""}`);
14804
+ console.log(`written ${path}${existsSync19(`${path}.bak`) ? ` (previous one in ${path}.bak)` : ""}`);
12821
14805
  } else {
12822
14806
  console.log(JSON.stringify(imported, null, 2));
12823
14807
  console.log("\n(dry run: add --write to save it)");
@@ -12899,7 +14883,7 @@ async function main() {
12899
14883
  const reg = await registry();
12900
14884
  const out = opt("--out") ?? "gallery";
12901
14885
  const sample = opt("--pages");
12902
- const n = buildGallery(reg, { out, locale: opt("--locale") ?? "en", languages: flag("--all-languages"), theme: opt("--theme") ?? "midnight", ...sample ? { pages: JSON.parse(readFileSync13(sample, "utf8")) } : {} });
14886
+ const n = buildGallery(reg, { out, locale: opt("--locale") ?? "en", languages: flag("--all-languages"), theme: opt("--theme") ?? "midnight", ...sample ? { pages: JSON.parse(readFileSync14(sample, "utf8")) } : {} });
12903
14887
  console.log(`${n} widgets \u2192 ${out}/index.html`);
12904
14888
  return;
12905
14889
  }