@camstack/addon-provider-reolink 1.1.14 → 1.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/addon.js +1301 -76
  2. package/dist/addon.mjs +1301 -76
  3. package/package.json +1 -1
package/dist/addon.mjs CHANGED
@@ -4650,7 +4650,7 @@ function _instanceof(cls, params = {}) {
4650
4650
  return inst;
4651
4651
  }
4652
4652
  //#endregion
4653
- //#region ../types/dist/sleep-MHm--th-.mjs
4653
+ //#region ../types/dist/sleep-BiDFW0E7.mjs
4654
4654
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
4655
4655
  EventCategory["SystemBoot"] = "system.boot";
4656
4656
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -5463,6 +5463,100 @@ function createDurableState(deps) {
5463
5463
  };
5464
5464
  }
5465
5465
  /**
5466
+ * Per-node scoping for the shared addon-settings blob.
5467
+ *
5468
+ * An addon's settings store is hub-central (the `addon-settings` cap is
5469
+ * hub-routed — the hub instance answers for every node), so fields whose
5470
+ * value is a NODE fact (decoder backend, engine pick, probed hardware
5471
+ * capabilities) persist under the node-scoped key `<key>@<nodeId>` inside
5472
+ * the single shared blob. The SCHEMA field key stays bare: the write path
5473
+ * ({@link scopePatch}) maps the bare field onto the target node's scoped
5474
+ * key; the read/hydrate path ({@link projectStore}) maps THIS node's value
5475
+ * back, so UI forms and `resolveConfig` only ever see the bare key.
5476
+ *
5477
+ * Fields opt in via the `perNode: true` schema marker on `ConfigFieldBase`
5478
+ * (`interfaces/config-ui.ts`); `BaseAddon` derives the key set from the
5479
+ * schema and routes reads/writes through these helpers.
5480
+ *
5481
+ * ## No bare-key fallback — deliberate
5482
+ *
5483
+ * {@link readNodeValue} reads the node-scoped key ONLY. A node with no
5484
+ * scoped key resolves to `undefined` so the field's schema `default` wins —
5485
+ * NEVER `store[base]` and never another node's value. A bare legacy key in
5486
+ * the store is invisible to every node, hub included, so one node's
5487
+ * selection can never leak onto another. (This generalizes the
5488
+ * `decoder-backend-keys.ts` semantics — the no-fallback variant — over an
5489
+ * arbitrary set of per-node field keys.)
5490
+ *
5491
+ * Pure functions only — no I/O, no imports beyond the language. This is a
5492
+ * LEAF module: import it via its deep path, never from the root barrel.
5493
+ */
5494
+ /**
5495
+ * Normalize a raw kernel node id to the bare node id used for scoping.
5496
+ * `localNodeId` can carry a `<node>/<addon>` suffix on forked child
5497
+ * processes; per-node settings are per-NODE, so strip the addon segment.
5498
+ * `undefined` / `null` / empty falls back to `'hub'`.
5499
+ */
5500
+ function normalizeNodeId(raw) {
5501
+ if (raw === void 0 || raw === null || raw === "") return "hub";
5502
+ const slashIdx = raw.indexOf("/");
5503
+ if (slashIdx < 0) return raw;
5504
+ const bare = raw.slice(0, slashIdx);
5505
+ return bare === "" ? "hub" : bare;
5506
+ }
5507
+ /** The node-scoped store key for a per-node field: `<base>@<nodeId>`. */
5508
+ function nodeScopedKey(base, nodeId) {
5509
+ return `${base}@${normalizeNodeId(nodeId)}`;
5510
+ }
5511
+ /**
5512
+ * Read a node's value for a per-node field from the raw shared store:
5513
+ * the node-scoped key when present, otherwise `undefined`.
5514
+ * Deliberately NO bare-key fallback (see module doc) — the caller lets the
5515
+ * schema `default` win on `undefined`.
5516
+ */
5517
+ function readNodeValue(store, base, nodeId) {
5518
+ return store[nodeScopedKey(base, nodeId)];
5519
+ }
5520
+ /**
5521
+ * Re-map a UI/settings patch so every bare perNode field persists under the
5522
+ * TARGET node's scoped key; all other keys pass through unchanged. Used on
5523
+ * the write path so a save for one node never clobbers another node's value
5524
+ * (and the bare key is never written). Returns a new object — the input
5525
+ * patch is not mutated.
5526
+ */
5527
+ function scopePatch(patch, perNodeKeys, nodeId) {
5528
+ const out = {};
5529
+ for (const [key, value] of Object.entries(patch)) out[perNodeKeys.has(key) ? nodeScopedKey(key, nodeId) : key] = value;
5530
+ return out;
5531
+ }
5532
+ /**
5533
+ * Project the raw shared store onto the bare schema keys for ONE node so a
5534
+ * UI schema (whose field keys are bare) hydrates from that node's own
5535
+ * values:
5536
+ *
5537
+ * - EVERY `@`-scoped key (any node's) is dropped from the pass-through.
5538
+ * - Every bare perNode key is dropped from the pass-through (a stray bare
5539
+ * legacy key must never hydrate any node — no bare fallback).
5540
+ * - THIS node's effective value ({@link readNodeValue}) is then laid onto
5541
+ * each bare perNode key; when the node has no scoped key the bare key is
5542
+ * left ABSENT so the field's schema `default` wins.
5543
+ *
5544
+ * Returns a new object — the input store is not mutated.
5545
+ */
5546
+ function projectStore(store, perNodeKeys, nodeId) {
5547
+ const out = {};
5548
+ for (const [key, value] of Object.entries(store)) {
5549
+ if (key.includes("@")) continue;
5550
+ if (perNodeKeys.has(key)) continue;
5551
+ out[key] = value;
5552
+ }
5553
+ for (const base of perNodeKeys) {
5554
+ const value = readNodeValue(store, base, nodeId);
5555
+ if (value !== void 0) out[base] = value;
5556
+ }
5557
+ return out;
5558
+ }
5559
+ /**
5466
5560
  * Base class for CamStack addons. Eliminates settings boilerplate:
5467
5561
  *
5468
5562
  * - Typed `config` property with automatic resolution from store + defaults
@@ -5630,23 +5724,63 @@ var BaseAddon = class {
5630
5724
  deviceSettingsSchema() {
5631
5725
  return null;
5632
5726
  }
5633
- async getGlobalSettings(overlay, cap, _nodeId) {
5727
+ async getGlobalSettings(overlay, cap, nodeId) {
5634
5728
  const schema = this.globalSettingsSchema(cap);
5635
5729
  if (!schema) return { sections: [] };
5636
- const raw = await this._ctx?.settings?.readAddonStore() ?? {};
5730
+ const projected = await this.resolveGlobalStore(nodeId, cap);
5637
5731
  return hydrateSchema(schema, overlay ? {
5638
- ...raw,
5732
+ ...projected,
5639
5733
  ...overlay
5640
- } : raw);
5734
+ } : projected);
5641
5735
  }
5642
- async updateGlobalSettings(patch, _nodeId) {
5643
- await this._ctx?.settings?.writeAddonStore(patch);
5736
+ /**
5737
+ * The raw addon store PROJECTED onto the target node's bare per-node keys:
5738
+ * every `perNode: true` field carries THAT node's scoped value on its bare
5739
+ * key (absent scoped key ⇒ key absent, so the schema `default` wins — no
5740
+ * bare fallback), all `@`-scoped and stray bare per-node keys are dropped.
5741
+ * A no-op passthrough when the schema declares no `perNode` field.
5742
+ *
5743
+ * This is the sanctioned way for a `getGlobalSettings` OVERRIDE that needs
5744
+ * the store for custom option logic (option narrowing, value snapping) to
5745
+ * read it per-node — never `ctx.settings.readAddonStore()` directly.
5746
+ * `nodeId` omitted ⇒ the local node (node-blind injection from ctx).
5747
+ */
5748
+ async resolveGlobalStore(nodeId, cap) {
5749
+ const raw = await this._ctx?.settings?.readAddonStore() ?? {};
5750
+ const keys = this.perNodeKeys(cap);
5751
+ const node = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
5752
+ return keys.size > 0 ? projectStore(raw, keys, node) : raw;
5753
+ }
5754
+ async updateGlobalSettings(patch, nodeId) {
5755
+ const keys = this.perNodeKeys();
5756
+ const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
5757
+ const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
5758
+ const barePatch = patch;
5759
+ const scoped = keys.size > 0 ? scopePatch(barePatch, keys, target) : barePatch;
5760
+ await this._ctx?.settings?.writeAddonStore(scoped);
5761
+ if (target !== localNode) return;
5644
5762
  await this.resolveConfig();
5645
5763
  await this.onConfigChanged();
5646
5764
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
5647
5765
  this.maybeAutoRestart(patch, this.globalSettingsSchema());
5648
5766
  }
5649
5767
  /**
5768
+ * The set of field keys the global settings schema declares `perNode: true`
5769
+ * — derived once per `cap` argument and memoized (schemas are static
5770
+ * declarations). Empty set ⇒ every per-node code path is bypassed and the
5771
+ * settings API behaves exactly like the legacy node-agnostic one.
5772
+ */
5773
+ _perNodeKeysCache = /* @__PURE__ */ new Map();
5774
+ perNodeKeys(cap) {
5775
+ const cacheKey = cap ?? "";
5776
+ const cached = this._perNodeKeysCache.get(cacheKey);
5777
+ if (cached) return cached;
5778
+ const schema = this.globalSettingsSchema(cap);
5779
+ const keys = new Set(schema ? schema.sections.flatMap((section) => collectPerNodeFieldKeys(section.fields)) : []);
5780
+ this._perNodeKeysCache.set(cacheKey, keys);
5781
+ return keys;
5782
+ }
5783
+ /**
5650
5784
  * If any field in `patch` is marked `requiresRestart` in `schema`,
5651
5785
  * schedule an addon restart for the next tick. Deferred via
5652
5786
  * `setImmediate` so the tRPC mutation that triggered the write has
@@ -5799,12 +5933,19 @@ var BaseAddon = class {
5799
5933
  * The merge is shallow: each key in `defaults` is checked against the store.
5800
5934
  * Only keys present in defaults are read — the store can contain extra keys
5801
5935
  * (e.g. from older versions) without polluting the typed config.
5936
+ *
5937
+ * Keys the global settings schema declares `perNode: true` resolve from
5938
+ * THIS node's scoped key (`<key>@<localNode>`) via `readNodeValue` — never
5939
+ * from the bare key — so a per-node field resolves to this node's own
5940
+ * selection at boot (absent scoped key ⇒ the constructor default wins).
5802
5941
  */
5803
5942
  async resolveConfig() {
5804
5943
  const stored = await this.readAddonStoreWithRetry();
5944
+ const perNode = this.perNodeKeys();
5945
+ const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
5805
5946
  const resolved = { ...this.defaults };
5806
5947
  for (const key of Object.keys(this.defaults)) {
5807
- const storedValue = stored[key];
5948
+ const storedValue = perNode.has(key) ? readNodeValue(stored, key, localNode) : stored[key];
5808
5949
  if (storedValue !== void 0 && storedValue !== null) {
5809
5950
  const defaultType = typeof this.defaults[key];
5810
5951
  if (typeof storedValue === defaultType) resolved[key] = storedValue;
@@ -5888,6 +6029,27 @@ var BaseAddon = class {
5888
6029
  }
5889
6030
  };
5890
6031
  /**
6032
+ * Collect the keys of every field marked `perNode: true`, recursing into
6033
+ * layout containers (`group` fields and `sub-tabs` tabs) the same way
6034
+ * `hydrateSchema` does. Valueless structural fields (separator/info/…)
6035
+ * don't declare `perNode` and are excluded by the `in` narrowing.
6036
+ */
6037
+ function collectPerNodeFieldKeys(fields) {
6038
+ const collected = [];
6039
+ for (const field of fields) {
6040
+ if (field.type === "group") {
6041
+ collected.push(...collectPerNodeFieldKeys(field.fields));
6042
+ continue;
6043
+ }
6044
+ if (field.type === "sub-tabs") {
6045
+ for (const tab of field.tabs) collected.push(...collectPerNodeFieldKeys(tab.fields));
6046
+ continue;
6047
+ }
6048
+ if ("perNode" in field && field.perNode === true) collected.push(field.key);
6049
+ }
6050
+ return collected;
6051
+ }
6052
+ /**
5891
6053
  * Normalize an `ICamstackAddon.initialize()` return value into the
5892
6054
  * `AddonInitResult` envelope. Arrays are wrapped into `{ providers }`;
5893
6055
  * envelopes pass through; void stays void.
@@ -6295,6 +6457,13 @@ var DeviceType = /* @__PURE__ */ function(DeviceType) {
6295
6457
  /** Single still-image entity (HA `image.*`). Read-only display of an
6296
6458
  * `entity_picture` signed URL the browser loads directly. `image` cap. */
6297
6459
  DeviceType["Image"] = "image";
6460
+ /** Smart pet feeder — cloud-connected food dispenser with a bowl food
6461
+ * level, battery, desiccant life, feeding state and manual-feed /
6462
+ * call-pet / maintenance actions. Installed with the `pet-feeder` cap;
6463
+ * dual-hopper models (D4S/D4SH) expose per-hopper portions. Sources:
6464
+ * native PetKit (`nodepetkit` `FeederDevice`), reusable by other feeder
6465
+ * integrations sharing the same food/desiccant/hopper surface. */
6466
+ DeviceType["PetFeeder"] = "pet-feeder";
6298
6467
  return DeviceType;
6299
6468
  }({});
6300
6469
  var DeviceFeature = /* @__PURE__ */ function(DeviceFeature) {
@@ -7646,6 +7815,601 @@ var _macroLookup = /* @__PURE__ */ new Map();
7646
7815
  for (const [k, v] of Object.entries(YAMNET_TO_MACRO.mapping)) _macroLookup.set(k.toLowerCase(), v);
7647
7816
  for (const [k, v] of Object.entries(APPLE_SA_TO_MACRO.mapping)) _macroLookup.set(k.toLowerCase(), v);
7648
7817
  /**
7818
+ * Error types for the safe expression engine. Two distinct classes so callers
7819
+ * can tell a compile-time (grammar) failure from a runtime (evaluation)
7820
+ * failure — both are non-fatal to the host: read paths degrade to "skip link".
7821
+ */
7822
+ /** Thrown by the tokenizer / parser. Carries a 0-based source `position` when
7823
+ * the failure is anchored to a character (author-facing inline feedback). */
7824
+ var ExpressionParseError = class extends Error {
7825
+ position;
7826
+ constructor(message, position) {
7827
+ super(message);
7828
+ this.name = "ExpressionParseError";
7829
+ this.position = position;
7830
+ }
7831
+ };
7832
+ /** Thrown by the evaluator (unknown identifier, type mismatch, non-finite
7833
+ * result, unknown builtin, step-budget exceeded). */
7834
+ var ExpressionEvalError = class extends Error {
7835
+ constructor(message) {
7836
+ super(message);
7837
+ this.name = "ExpressionEvalError";
7838
+ }
7839
+ };
7840
+ /**
7841
+ * Resource-bound constants for the safe expression engine.
7842
+ *
7843
+ * Every bound is defense-in-depth: the grammar is non-Turing-complete (no
7844
+ * loops, recursion, lambdas or member access — see `ast.ts`), so evaluation is
7845
+ * O(nodeCount) by construction. These caps merely put a hard ceiling on the
7846
+ * work a single author-supplied expression can request, so a hostile or
7847
+ * accidental pathological string can never spend unbounded CPU/memory.
7848
+ */
7849
+ /** Max source length (chars) — checked BEFORE tokenizing so a huge string is
7850
+ * rejected without allocation. */
7851
+ var MAX_EXPRESSION_SOURCE_LENGTH = 2048;
7852
+ /** A legal binding / identifier name. */
7853
+ var EXPRESSION_IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
7854
+ /** Binding names an author may NOT use: `now` is auto-injected; the literal
7855
+ * keywords lex as values, not identifiers, so binding to them is meaningless. */
7856
+ var RESERVED_BINDING_NAMES = new Set([
7857
+ "now",
7858
+ "true",
7859
+ "false",
7860
+ "null"
7861
+ ]);
7862
+ /**
7863
+ * Tokenizer for the safe expression mini-language. Hand-rolled, single-pass,
7864
+ * zero-dependency. The grammar is deliberately boring: decimal numbers,
7865
+ * single/double-quoted strings with a tiny escape set, identifiers, the three
7866
+ * value keywords (`true`/`false`/`null`) and a fixed punctuator set. Anything
7867
+ * outside that — a bare `.`, `=`, `[`, `]`, `{`, `}`, `;`, backtick, `&`, `|` —
7868
+ * is a parse error with a source position, so member access / assignment /
7869
+ * template literals are lexically impossible.
7870
+ */
7871
+ var KEYWORDS = new Set([
7872
+ "true",
7873
+ "false",
7874
+ "null"
7875
+ ]);
7876
+ function isDigit(ch) {
7877
+ return ch >= "0" && ch <= "9";
7878
+ }
7879
+ function isIdentStart(ch) {
7880
+ return ch >= "A" && ch <= "Z" || ch >= "a" && ch <= "z" || ch === "_";
7881
+ }
7882
+ function isIdentPart(ch) {
7883
+ return isIdentStart(ch) || isDigit(ch);
7884
+ }
7885
+ function isWhitespace(ch) {
7886
+ return ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === "\f" || ch === "\v";
7887
+ }
7888
+ /** Tokenize `source` into a flat token list ending with a single `eof` token.
7889
+ * Throws `ExpressionParseError` on any illegal character or unterminated
7890
+ * string. */
7891
+ function tokenize(source) {
7892
+ if (source.length > 2048) throw new ExpressionParseError(`expression too long (${source.length} > ${MAX_EXPRESSION_SOURCE_LENGTH} chars)`, 0);
7893
+ const tokens = [];
7894
+ let i = 0;
7895
+ const n = source.length;
7896
+ while (i < n) {
7897
+ const ch = source[i];
7898
+ if (isWhitespace(ch)) {
7899
+ i += 1;
7900
+ continue;
7901
+ }
7902
+ if (isDigit(ch)) {
7903
+ const start = i;
7904
+ while (i < n && isDigit(source[i])) i += 1;
7905
+ if (i < n && source[i] === ".") {
7906
+ if (i + 1 >= n || !isDigit(source[i + 1])) throw new ExpressionParseError("malformed number: decimal point needs a digit", i);
7907
+ i += 1;
7908
+ while (i < n && isDigit(source[i])) i += 1;
7909
+ }
7910
+ const text = source.slice(start, i);
7911
+ const value = Number(text);
7912
+ if (!Number.isFinite(value)) throw new ExpressionParseError(`malformed number: '${text}'`, start);
7913
+ tokens.push({
7914
+ type: "number",
7915
+ value,
7916
+ pos: start
7917
+ });
7918
+ continue;
7919
+ }
7920
+ if (ch === "'" || ch === "\"") {
7921
+ const quote = ch;
7922
+ const start = i;
7923
+ i += 1;
7924
+ let out = "";
7925
+ let closed = false;
7926
+ while (i < n) {
7927
+ const c = source[i];
7928
+ if (c === "\\") {
7929
+ const next = i + 1 < n ? source[i + 1] : "";
7930
+ if (next === "\\" || next === "'" || next === "\"") {
7931
+ out += next;
7932
+ i += 2;
7933
+ continue;
7934
+ }
7935
+ throw new ExpressionParseError(`invalid string escape: '\\${next}'`, i);
7936
+ }
7937
+ if (c === quote) {
7938
+ closed = true;
7939
+ i += 1;
7940
+ break;
7941
+ }
7942
+ out += c;
7943
+ i += 1;
7944
+ }
7945
+ if (!closed) throw new ExpressionParseError("unterminated string literal", start);
7946
+ tokens.push({
7947
+ type: "string",
7948
+ value: out,
7949
+ pos: start
7950
+ });
7951
+ continue;
7952
+ }
7953
+ if (isIdentStart(ch)) {
7954
+ const start = i;
7955
+ while (i < n && isIdentPart(source[i])) i += 1;
7956
+ const text = source.slice(start, i);
7957
+ if (KEYWORDS.has(text)) tokens.push({
7958
+ type: "keyword",
7959
+ keyword: keywordOf(text),
7960
+ pos: start
7961
+ });
7962
+ else tokens.push({
7963
+ type: "identifier",
7964
+ name: text,
7965
+ pos: start
7966
+ });
7967
+ continue;
7968
+ }
7969
+ const two = i + 1 < n ? source.slice(i, i + 2) : "";
7970
+ if (two === "<=" || two === ">=" || two === "==" || two === "!=" || two === "&&" || two === "||") {
7971
+ tokens.push({
7972
+ type: "punct",
7973
+ punct: two,
7974
+ pos: i
7975
+ });
7976
+ i += 2;
7977
+ continue;
7978
+ }
7979
+ if (isSinglePunct(ch)) {
7980
+ tokens.push({
7981
+ type: "punct",
7982
+ punct: ch,
7983
+ pos: i
7984
+ });
7985
+ i += 1;
7986
+ continue;
7987
+ }
7988
+ throw new ExpressionParseError(`unexpected character '${ch}'`, i);
7989
+ }
7990
+ tokens.push({
7991
+ type: "eof",
7992
+ pos: n
7993
+ });
7994
+ return tokens;
7995
+ }
7996
+ function keywordOf(text) {
7997
+ if (text === "true") return "true";
7998
+ if (text === "false") return "false";
7999
+ return "null";
8000
+ }
8001
+ function isSinglePunct(ch) {
8002
+ return ch === "(" || ch === ")" || ch === "," || ch === "?" || ch === ":" || ch === "+" || ch === "-" || ch === "*" || ch === "/" || ch === "%" || ch === "!" || ch === "<" || ch === ">";
8003
+ }
8004
+ /**
8005
+ * Frozen, null-prototype builtin function table for the expression engine
8006
+ * (spec §4 rule 4). The table is the SOLE surface of callable functions: the
8007
+ * parser rejects any callee not in it, and the evaluator gates each call on an
8008
+ * own-property check against it.
8009
+ *
8010
+ * Because the object has a NULL prototype AND is `Object.freeze`d:
8011
+ * - it cannot be polluted (no `__proto__` / `constructor` write reaches it);
8012
+ * - a lookup for `toString` / `hasOwnProperty` / `constructor` finds NOTHING
8013
+ * (there is no `Object.prototype` in the chain), so those names are not
8014
+ * callable — they are simply "unknown function" at parse time.
8015
+ *
8016
+ * Every numeric argument is validated as a finite number and every numeric
8017
+ * RESULT is re-checked finite, so `/0`, `sqrt(-1)` (→ NaN) and overflow
8018
+ * (`pow(10,400)` → Infinity) all raise `ExpressionEvalError` and fail the link
8019
+ * closed rather than emitting a garbage value.
8020
+ */
8021
+ function asFiniteNumber(value, name, index) {
8022
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new ExpressionEvalError(`${name}: argument ${index + 1} must be a finite number`);
8023
+ return value;
8024
+ }
8025
+ function asString$1(value, name, index) {
8026
+ if (typeof value !== "string") throw new ExpressionEvalError(`${name}: argument ${index + 1} must be a string`);
8027
+ return value;
8028
+ }
8029
+ function finiteResult(value, name) {
8030
+ if (!Number.isFinite(value)) throw new ExpressionEvalError(`${name}: produced a non-finite result`);
8031
+ return value;
8032
+ }
8033
+ function allFiniteNumbers(args, name) {
8034
+ return args.map((a, idx) => asFiniteNumber(a, name, idx));
8035
+ }
8036
+ var INF = Number.POSITIVE_INFINITY;
8037
+ var table$1 = {
8038
+ min: {
8039
+ minArgs: 1,
8040
+ maxArgs: INF,
8041
+ apply: (args) => finiteResult(Math.min(...allFiniteNumbers(args, "min")), "min")
8042
+ },
8043
+ max: {
8044
+ minArgs: 1,
8045
+ maxArgs: INF,
8046
+ apply: (args) => finiteResult(Math.max(...allFiniteNumbers(args, "max")), "max")
8047
+ },
8048
+ abs: {
8049
+ minArgs: 1,
8050
+ maxArgs: 1,
8051
+ apply: (args) => finiteResult(Math.abs(asFiniteNumber(args[0], "abs", 0)), "abs")
8052
+ },
8053
+ floor: {
8054
+ minArgs: 1,
8055
+ maxArgs: 1,
8056
+ apply: (args) => finiteResult(Math.floor(asFiniteNumber(args[0], "floor", 0)), "floor")
8057
+ },
8058
+ ceil: {
8059
+ minArgs: 1,
8060
+ maxArgs: 1,
8061
+ apply: (args) => finiteResult(Math.ceil(asFiniteNumber(args[0], "ceil", 0)), "ceil")
8062
+ },
8063
+ sqrt: {
8064
+ minArgs: 1,
8065
+ maxArgs: 1,
8066
+ apply: (args) => finiteResult(Math.sqrt(asFiniteNumber(args[0], "sqrt", 0)), "sqrt")
8067
+ },
8068
+ round: {
8069
+ minArgs: 1,
8070
+ maxArgs: 2,
8071
+ apply: (args) => {
8072
+ const x = asFiniteNumber(args[0], "round", 0);
8073
+ const digits = args.length > 1 ? Math.trunc(asFiniteNumber(args[1], "round", 1)) : 0;
8074
+ if (digits < 0 || digits > 100) throw new ExpressionEvalError("round: digits must be between 0 and 100");
8075
+ const factor = 10 ** digits;
8076
+ return finiteResult(Math.round(x * factor) / factor, "round");
8077
+ }
8078
+ },
8079
+ pow: {
8080
+ minArgs: 2,
8081
+ maxArgs: 2,
8082
+ apply: (args) => finiteResult(asFiniteNumber(args[0], "pow", 0) ** asFiniteNumber(args[1], "pow", 1), "pow")
8083
+ },
8084
+ clamp: {
8085
+ minArgs: 3,
8086
+ maxArgs: 3,
8087
+ apply: (args) => {
8088
+ const x = asFiniteNumber(args[0], "clamp", 0);
8089
+ const lo = asFiniteNumber(args[1], "clamp", 1);
8090
+ const hi = asFiniteNumber(args[2], "clamp", 2);
8091
+ if (lo > hi) throw new ExpressionEvalError("clamp: lower bound is greater than upper bound");
8092
+ return finiteResult(Math.min(hi, Math.max(lo, x)), "clamp");
8093
+ }
8094
+ },
8095
+ avg: {
8096
+ minArgs: 1,
8097
+ maxArgs: INF,
8098
+ apply: (args) => {
8099
+ const nums = allFiniteNumbers(args, "avg");
8100
+ return finiteResult(nums.reduce((acc, v) => acc + v, 0) / nums.length, "avg");
8101
+ }
8102
+ },
8103
+ sum: {
8104
+ minArgs: 1,
8105
+ maxArgs: INF,
8106
+ apply: (args) => finiteResult(allFiniteNumbers(args, "sum").reduce((acc, v) => acc + v, 0), "sum")
8107
+ },
8108
+ coalesce: {
8109
+ minArgs: 1,
8110
+ maxArgs: INF,
8111
+ apply: (args) => {
8112
+ for (const a of args) if (a !== null) return a;
8113
+ return null;
8114
+ }
8115
+ },
8116
+ age: {
8117
+ minArgs: 2,
8118
+ maxArgs: 2,
8119
+ apply: (args) => finiteResult(asFiniteNumber(args[0], "age", 0) - asFiniteNumber(args[1], "age", 1), "age")
8120
+ },
8121
+ convert: {
8122
+ minArgs: 3,
8123
+ maxArgs: 3,
8124
+ apply: (args, hooks) => {
8125
+ const x = asFiniteNumber(args[0], "convert", 0);
8126
+ const from = asString$1(args[1], "convert", 1).trim();
8127
+ const to = asString$1(args[2], "convert", 2).trim();
8128
+ if (hooks.convert) {
8129
+ const out = hooks.convert(x, from, to);
8130
+ if (out === null) throw new ExpressionEvalError(`convert: cannot convert '${from}' to '${to}'`);
8131
+ return finiteResult(out, "convert");
8132
+ }
8133
+ if (from === to) return x;
8134
+ throw new ExpressionEvalError("convert: unit conversion table not installed");
8135
+ }
8136
+ }
8137
+ };
8138
+ Object.freeze(Object.assign(Object.create(null), table$1));
8139
+ /** The set of valid builtin names — used by the parser to reject unknown
8140
+ * callees at parse time (immediate author feedback). */
8141
+ var EXPRESSION_BUILTIN_NAMES = new Set(Object.keys(table$1));
8142
+ /**
8143
+ * Pratt (precedence-climbing) parser for the safe expression mini-language.
8144
+ *
8145
+ * Precedence (low → high): ternary `?:` (right-assoc) → `||` → `&&` → equality
8146
+ * → relational → additive → multiplicative → unary `! -` → call / primary.
8147
+ * Calls are ONLY `IDENT '(' args? ')'` at primary position — the callee is a
8148
+ * string validated against the builtin table at parse time, so an unknown
8149
+ * function is rejected immediately (author feedback) and a persisted expression
8150
+ * that references a since-removed builtin degrades at read.
8151
+ *
8152
+ * A node counter caps total AST size (`MAX_EXPRESSION_AST_NODES`) and call
8153
+ * arity is capped (`MAX_EXPRESSION_CALL_ARGS`) — both raise `ExpressionParseError`.
8154
+ */
8155
+ /** Binary/logical operator precedence (higher binds tighter). */
8156
+ var BINARY_PRECEDENCE = {
8157
+ "||": 1,
8158
+ "&&": 2,
8159
+ "==": 3,
8160
+ "!=": 3,
8161
+ "<": 4,
8162
+ "<=": 4,
8163
+ ">": 4,
8164
+ ">=": 4,
8165
+ "+": 5,
8166
+ "-": 5,
8167
+ "*": 6,
8168
+ "/": 6,
8169
+ "%": 6
8170
+ };
8171
+ function isLogicalOp(op) {
8172
+ return op === "&&" || op === "||";
8173
+ }
8174
+ function isBinaryOp(op) {
8175
+ return op === "+" || op === "-" || op === "*" || op === "/" || op === "%" || op === "==" || op === "!=" || op === "<" || op === "<=" || op === ">" || op === ">=";
8176
+ }
8177
+ var Parser = class {
8178
+ tokens;
8179
+ pos = 0;
8180
+ nodeCount = 0;
8181
+ identifiers = /* @__PURE__ */ new Set();
8182
+ callees = /* @__PURE__ */ new Set();
8183
+ constructor(tokens) {
8184
+ this.tokens = tokens;
8185
+ }
8186
+ parse() {
8187
+ const ast = this.parseTernary();
8188
+ const tok = this.peek();
8189
+ if (tok.type !== "eof") throw new ExpressionParseError("unexpected trailing input", tok.pos);
8190
+ return {
8191
+ ast,
8192
+ identifiers: this.identifiers,
8193
+ callees: this.callees,
8194
+ nodeCount: this.nodeCount
8195
+ };
8196
+ }
8197
+ peek() {
8198
+ return this.tokens[this.pos];
8199
+ }
8200
+ next() {
8201
+ return this.tokens[this.pos++];
8202
+ }
8203
+ /** Consume a punctuator token, erroring if the next token isn't it. */
8204
+ expectPunct(punct) {
8205
+ const tok = this.peek();
8206
+ if (tok.type !== "punct" || tok.punct !== punct) throw new ExpressionParseError(`expected '${punct}'`, tok.pos);
8207
+ this.pos += 1;
8208
+ }
8209
+ matchPunct(punct) {
8210
+ const tok = this.peek();
8211
+ if (tok.type === "punct" && tok.punct === punct) {
8212
+ this.pos += 1;
8213
+ return true;
8214
+ }
8215
+ return false;
8216
+ }
8217
+ countNode() {
8218
+ this.nodeCount += 1;
8219
+ if (this.nodeCount > 256) throw new ExpressionParseError("expression too complex", this.peek().pos);
8220
+ }
8221
+ parseTernary() {
8222
+ const test = this.parseBinary(1);
8223
+ if (this.matchPunct("?")) {
8224
+ const consequent = this.parseTernary();
8225
+ this.expectPunct(":");
8226
+ const alternate = this.parseTernary();
8227
+ this.countNode();
8228
+ return {
8229
+ kind: "conditional",
8230
+ test,
8231
+ consequent,
8232
+ alternate
8233
+ };
8234
+ }
8235
+ return test;
8236
+ }
8237
+ parseBinary(minPrec) {
8238
+ let left = this.parseUnary();
8239
+ for (;;) {
8240
+ const tok = this.peek();
8241
+ if (tok.type !== "punct") break;
8242
+ const prec = BINARY_PRECEDENCE[tok.punct];
8243
+ if (prec === void 0 || prec < minPrec) break;
8244
+ const op = tok.punct;
8245
+ this.pos += 1;
8246
+ const right = this.parseBinary(prec + 1);
8247
+ this.countNode();
8248
+ if (isLogicalOp(op)) left = {
8249
+ kind: "logical",
8250
+ op,
8251
+ left,
8252
+ right
8253
+ };
8254
+ else if (isBinaryOp(op)) left = {
8255
+ kind: "binary",
8256
+ op,
8257
+ left,
8258
+ right
8259
+ };
8260
+ else throw new ExpressionParseError(`unexpected operator '${op}'`, tok.pos);
8261
+ }
8262
+ return left;
8263
+ }
8264
+ parseUnary() {
8265
+ const tok = this.peek();
8266
+ if (tok.type === "punct" && (tok.punct === "!" || tok.punct === "-")) {
8267
+ const op = tok.punct;
8268
+ this.pos += 1;
8269
+ const operand = this.parseUnary();
8270
+ this.countNode();
8271
+ return {
8272
+ kind: "unary",
8273
+ op,
8274
+ operand
8275
+ };
8276
+ }
8277
+ return this.parsePrimary();
8278
+ }
8279
+ parsePrimary() {
8280
+ const tok = this.next();
8281
+ switch (tok.type) {
8282
+ case "number":
8283
+ this.countNode();
8284
+ return {
8285
+ kind: "literal",
8286
+ value: tok.value
8287
+ };
8288
+ case "string":
8289
+ this.countNode();
8290
+ return {
8291
+ kind: "literal",
8292
+ value: tok.value
8293
+ };
8294
+ case "keyword":
8295
+ this.countNode();
8296
+ return {
8297
+ kind: "literal",
8298
+ value: tok.keyword === "null" ? null : tok.keyword === "true"
8299
+ };
8300
+ case "identifier": {
8301
+ const nextTok = this.peek();
8302
+ if (nextTok.type === "punct" && nextTok.punct === "(") return this.parseCall(tok.name, tok.pos);
8303
+ this.identifiers.add(tok.name);
8304
+ this.countNode();
8305
+ return {
8306
+ kind: "identifier",
8307
+ name: tok.name
8308
+ };
8309
+ }
8310
+ case "punct":
8311
+ if (tok.punct === "(") {
8312
+ const inner = this.parseTernary();
8313
+ this.expectPunct(")");
8314
+ return inner;
8315
+ }
8316
+ throw new ExpressionParseError(`unexpected token '${tok.punct}'`, tok.pos);
8317
+ case "eof": throw new ExpressionParseError("unexpected end of expression", tok.pos);
8318
+ }
8319
+ }
8320
+ parseCall(callee, pos) {
8321
+ if (!EXPRESSION_BUILTIN_NAMES.has(callee)) throw new ExpressionParseError(`unknown function '${callee}'`, pos);
8322
+ this.expectPunct("(");
8323
+ const args = [];
8324
+ if (!this.matchPunct(")")) for (;;) {
8325
+ args.push(this.parseTernary());
8326
+ if (args.length > 16) throw new ExpressionParseError(`too many arguments to '${callee}'`, pos);
8327
+ if (this.matchPunct(",")) continue;
8328
+ this.expectPunct(")");
8329
+ break;
8330
+ }
8331
+ this.callees.add(callee);
8332
+ this.countNode();
8333
+ return {
8334
+ kind: "call",
8335
+ callee,
8336
+ args
8337
+ };
8338
+ }
8339
+ };
8340
+ /** Tokenize + parse `source` into a validated `ParsedExpression`. Throws
8341
+ * `ExpressionParseError` on any lexical or grammatical failure. */
8342
+ function parseExpression(source) {
8343
+ return new Parser(tokenize(source)).parse();
8344
+ }
8345
+ Object.freeze({});
8346
+ /**
8347
+ * LRU compile cache for parsed expressions (spec §2.4 "parse once … LRU keyed
8348
+ * by expr"). The cache stores BOTH successes and failures (negative caching),
8349
+ * so a corrupt persisted string costs exactly one tokenize+parse total — not
8350
+ * one per read on a hot resolve path.
8351
+ *
8352
+ * The cache is a module-level singleton: entries are pure, content-addressed
8353
+ * ASTs keyed by the raw source string, so sharing one instance across all
8354
+ * callers is safe and maximises hit rate.
8355
+ */
8356
+ var cache$1 = /* @__PURE__ */ new Map();
8357
+ function getCached(source) {
8358
+ const hit = cache$1.get(source);
8359
+ if (hit !== void 0) {
8360
+ cache$1.delete(source);
8361
+ cache$1.set(source, hit);
8362
+ return hit;
8363
+ }
8364
+ let result;
8365
+ try {
8366
+ result = {
8367
+ ok: true,
8368
+ parsed: parseExpression(source)
8369
+ };
8370
+ } catch (err) {
8371
+ result = {
8372
+ ok: false,
8373
+ error: err instanceof ExpressionParseError ? err.message : String(err)
8374
+ };
8375
+ }
8376
+ cache$1.set(source, result);
8377
+ if (cache$1.size > 256) {
8378
+ const oldest = cache$1.keys().next().value;
8379
+ if (oldest !== void 0) cache$1.delete(oldest);
8380
+ }
8381
+ return result;
8382
+ }
8383
+ /** Compile `source`, returning a discriminated result instead of throwing.
8384
+ * Used by read paths that must degrade rather than raise. LRU/negative-cached. */
8385
+ function compileExpressionSafe(source) {
8386
+ return getCached(source);
8387
+ }
8388
+ /**
8389
+ * Author-time validation. Returns `null` when the source is valid, else a
8390
+ * human-readable error message. Checks: the expression compiles; binding count
8391
+ * is within `MAX_EXPRESSION_BINDINGS`; every binding name is a legal identifier,
8392
+ * is not reserved (`now`/keywords) and does not shadow a builtin; and every
8393
+ * FREE identifier of the AST is covered by a binding or the injected `now`.
8394
+ */
8395
+ function validateExpressionSource(src) {
8396
+ const names = Object.keys(src.bindings);
8397
+ if (names.length > 32) return `too many bindings (${names.length} > 32)`;
8398
+ for (const name of names) {
8399
+ if (!EXPRESSION_IDENTIFIER_RE.test(name)) return `invalid binding name '${name}'`;
8400
+ if (RESERVED_BINDING_NAMES.has(name)) return `binding name '${name}' is reserved`;
8401
+ if (EXPRESSION_BUILTIN_NAMES.has(name)) return `binding name '${name}' shadows a builtin function`;
8402
+ }
8403
+ const compiled = compileExpressionSafe(src.expr);
8404
+ if (!compiled.ok) return compiled.error;
8405
+ const bound = new Set(names);
8406
+ for (const id of compiled.parsed.identifiers) {
8407
+ if (id === "now") continue;
8408
+ if (!bound.has(id)) return `expression references unbound identifier '${id}'`;
8409
+ }
8410
+ return null;
8411
+ }
8412
+ /**
7649
8413
  * Accessory device helpers — shared across drivers.
7650
8414
  *
7651
8415
  * Many vendor-specific drivers register accessory child devices on
@@ -8529,7 +9293,13 @@ onStatusChanged: { data: object({
8529
9293
  }) } },
8530
9294
  status: {
8531
9295
  schema: BatteryStatusSchema,
8532
- kind: "push"
9296
+ kind: "push",
9297
+ empty: {
9298
+ percentage: 0,
9299
+ charging: "none",
9300
+ sleeping: false,
9301
+ lastUpdated: 0
9302
+ }
8533
9303
  },
8534
9304
  /**
8535
9305
  * Runtime-state slice — every provider that registers this cap
@@ -9472,21 +10242,38 @@ var connectivityCapability = {
9472
10242
  },
9473
10243
  runtimeState: ConnectivityStatusSchema
9474
10244
  };
10245
+ /**
10246
+ * Generic device-consumables capability — surfaces a device's
10247
+ * maintenance items (vacuum filters/brushes, replaceable cartridges,
10248
+ * descaling cycles, …) with their remaining life and an optional
10249
+ * "Replaced" reset action. Device-agnostic: any provider that knows its
10250
+ * device tracks consumables can register it; the cap declares no
10251
+ * vocabulary of its own — the provider names each item verbatim.
10252
+ *
10253
+ * Like `childLayout`, the cap is INERT until a provider sets items: no
10254
+ * provider populates it by guessing (no HA inference). The UI renders a
10255
+ * "No consumables reported" placeholder when `items` is empty.
10256
+ */
10257
+ /** A single consumable item. Either a continuous `level` (remaining
10258
+ * life %) or a discrete `status` may be known — both may be null when a
10259
+ * provider only knows the item exists. `level` and `status` are not
10260
+ * mutually exclusive; a provider may report both. */
10261
+ var ConsumableItemSchema = object({
10262
+ /** Stable id, e.g. 'main-brush'. */
10263
+ key: string().min(1),
10264
+ /** Display name. */
10265
+ label: string().min(1),
10266
+ /** Remaining life % when known (0..100). */
10267
+ level: number().min(0).max(100).nullable(),
10268
+ /** Discrete state when known (binary mode). */
10269
+ status: _enum(["ok", "replace"]).nullable(),
10270
+ /** Ms epoch of the last replace, when known. */
10271
+ lastResetAt: number().nullable(),
10272
+ /** Whether `reset()` is meaningful for this item. */
10273
+ resettable: boolean()
10274
+ });
9475
10275
  var ConsumablesStatusSchema = object({
9476
- items: array(object({
9477
- /** Stable id, e.g. 'main-brush'. */
9478
- key: string().min(1),
9479
- /** Display name. */
9480
- label: string().min(1),
9481
- /** Remaining life % when known (0..100). */
9482
- level: number().min(0).max(100).nullable(),
9483
- /** Discrete state when known (binary mode). */
9484
- status: _enum(["ok", "replace"]).nullable(),
9485
- /** Ms epoch of the last replace, when known. */
9486
- lastResetAt: number().nullable(),
9487
- /** Whether `reset()` is meaningful for this item. */
9488
- resettable: boolean()
9489
- })),
10276
+ items: array(ConsumableItemSchema),
9490
10277
  lastChangedAt: number()
9491
10278
  });
9492
10279
  var consumablesCapability = {
@@ -9545,7 +10332,25 @@ reset: method(object({
9545
10332
  }) },
9546
10333
  status: {
9547
10334
  schema: ConsumablesStatusSchema,
9548
- kind: "push"
10335
+ kind: "push",
10336
+ empty: {
10337
+ items: [],
10338
+ lastChangedAt: 0
10339
+ },
10340
+ itemArray: {
10341
+ path: "items",
10342
+ keyField: "key",
10343
+ labelField: "label",
10344
+ itemSchema: ConsumableItemSchema,
10345
+ emptyItem: {
10346
+ key: "",
10347
+ label: "",
10348
+ level: null,
10349
+ status: null,
10350
+ lastResetAt: null,
10351
+ resettable: false
10352
+ }
10353
+ }
9549
10354
  },
9550
10355
  runtimeState: ConsumablesStatusSchema.extend({ lastFetchedAt: number() })
9551
10356
  };
@@ -10787,7 +11592,8 @@ var MotionAnalysisResultSchema = object({
10787
11592
  });
10788
11593
  method(object({
10789
11594
  deviceId: number(),
10790
- frame: FrameInputSchema
11595
+ frame: FrameInputSchema.optional(),
11596
+ frameHandle: FrameHandleSchema.optional()
10791
11597
  }), MotionAnalysisResultSchema, { kind: "mutation" }), method(object({ deviceId: number() }), _void(), { kind: "mutation" }), method(_void(), _void(), { kind: "mutation" }), object({
10792
11598
  deviceId: number(),
10793
11599
  detected: boolean(),
@@ -11034,6 +11840,12 @@ method(_void(), array(PipelineEngineChoiceSchema)), method(_void(), PipelineEngi
11034
11840
  engine: PipelineEngineChoiceSchema.optional(),
11035
11841
  steps: array(PipelineStepInputSchema).min(1),
11036
11842
  frame: FrameInputSchema.optional(),
11843
+ /**
11844
+ * CB5 shm passthrough — a `FrameHandle` naming the same ring slot
11845
+ * the decoded pixels live in. One more member of the one-of
11846
+ * frame/frameHandle/image/imageBase64/referenceImage group.
11847
+ */
11848
+ frameHandle: FrameHandleSchema.optional(),
11037
11849
  imageBase64: string().optional(),
11038
11850
  /**
11039
11851
  * Binary JPEG bytes — preferred over `imageBase64` on internal
@@ -11276,6 +12088,31 @@ var ReportMotionInputSchema = object({
11276
12088
  regions: array(MotionRegionSchema).readonly().optional()
11277
12089
  });
11278
12090
  /**
12091
+ * Where a runner gets a camera's decoded frames (cross-node Phase 2,
12092
+ * restream-owner model — P2c).
12093
+ *
12094
+ * - `local-broker` (DEFAULT): today's path — subscribe to the co-located
12095
+ * stream-broker's shm frame plane. Every pre-P2c attach payload (no
12096
+ * `frameSource` key) parses to this, so the field is additive with zero
12097
+ * behavior change.
12098
+ * - `remote-restream`: the detect node is NOT the camera's source-owner.
12099
+ * The runner acquires the owner's COMPRESSED passthrough restream
12100
+ * (`streamBroker.getStreamWithCodec({video:'copy'})` — refcounted, the
12101
+ * double-pull guard) and decodes LOCALLY via a satellite frame plane +
12102
+ * pull-mode decoder session pinned to its own node. The shm ring stays
12103
+ * node-local; only H.264/H.265 packets cross the wire.
12104
+ * `hubHostnameOverride` mirrors the recorder's `recordingHubHostname`:
12105
+ * when set it overrides the `CAMSTACK_HUB_URL`-derived host the runner
12106
+ * dials for the owner's restream.
12107
+ */
12108
+ var RunnerFrameSourceSchema = discriminatedUnion("kind", [object({ kind: literal("local-broker") }), object({
12109
+ kind: literal("remote-restream"),
12110
+ /** The camera's source-owner node (slice 1: always the hub). */
12111
+ ownerNodeId: string(),
12112
+ /** Operator override for the owner host the runner dials. */
12113
+ hubHostnameOverride: string().optional()
12114
+ })]).describe("Per-camera frame-source mode for the runner (P2c)");
12115
+ /**
11279
12116
  * Camera assignment payload sent by `addon-pipeline-orchestrator` to a
11280
12117
  * specific runner instance via `attachCamera`. Carries everything the
11281
12118
  * runner needs to subscribe to the local broker and execute inference.
@@ -11373,7 +12210,15 @@ var RunnerCameraConfigSchema = object({
11373
12210
  */
11374
12211
  onboardMotionDrivesAnalyzer: boolean().default(true),
11375
12212
  occupancyRecheckSec: number().min(occupancyRecheckSecField.min).max(occupancyRecheckSecField.max).default(occupancyRecheckSecField.default),
11376
- occupancyRecheckFrames: number().min(occupancyRecheckFramesField.min).max(occupancyRecheckFramesField.max).default(occupancyRecheckFramesField.default)
12213
+ occupancyRecheckFrames: number().min(occupancyRecheckFramesField.min).max(occupancyRecheckFramesField.max).default(occupancyRecheckFramesField.default),
12214
+ /**
12215
+ * Where this runner gets the camera's decoded frames (P2c). Defaulted so
12216
+ * every existing payload behaves as `local-broker` — the pre-Phase-2 path.
12217
+ * Populated with `remote-restream` by the orchestrator ONLY when the
12218
+ * camera's detect node differs from its source-owner (P2d, gated by the
12219
+ * `remoteSourcingNodes` rollout setting).
12220
+ */
12221
+ frameSource: RunnerFrameSourceSchema.default({ kind: "local-broker" })
11377
12222
  });
11378
12223
  motionFpsField.min, motionFpsField.max, motionFpsField.step, motionFpsField.default, detectionFpsField.min, detectionFpsField.max, detectionFpsField.step, detectionFpsField.default, motionCooldownMsField.min, motionCooldownMsField.max, motionCooldownMsField.step, motionCooldownMsField.default, occupancyRecheckSecField.min, occupancyRecheckSecField.max, occupancyRecheckSecField.step, occupancyRecheckSecField.default, occupancyRecheckFramesField.min, occupancyRecheckFramesField.max, occupancyRecheckFramesField.step, occupancyRecheckFramesField.default;
11379
12224
  /**
@@ -11937,6 +12782,157 @@ var numericSensorCapability = {
11937
12782
  runtimeState: NumericSensorStatusSchema
11938
12783
  };
11939
12784
  /**
12785
+ * Feeder connectivity / power status — mirrors the HA petkit device-status
12786
+ * enum: `normal` (online, mains), `offline` (not reaching PetKit cloud),
12787
+ * `on_batteries` (running on battery backup). `null` until first reported.
12788
+ */
12789
+ var PetFeederDeviceStatusSchema = _enum([
12790
+ "normal",
12791
+ "offline",
12792
+ "on_batteries"
12793
+ ]);
12794
+ var gramsPortion = number().int().min(4).max(200);
12795
+ var PetFeederStatusSchema = object({
12796
+ /** Food currently in the bowl (grams). Null when the device has not
12797
+ * reported a reading yet. On dual-hopper models this is the combined
12798
+ * bowl reading; per-hopper levels live in `food1`/`food2`. */
12799
+ foodLevel: number().nullable(),
12800
+ /** Hopper-1 food level (grams) on dual-hopper feeders; null on
12801
+ * single-hopper models. */
12802
+ food1: number().nullable(),
12803
+ /** Hopper-2 food level (grams) on dual-hopper feeders; null on
12804
+ * single-hopper models. */
12805
+ food2: number().nullable(),
12806
+ /** Derived low-food flag — mirrors the HA `food_level` binary_sensor
12807
+ * (`device_class: problem`, on = low). True when the bowl is empty /
12808
+ * below the feeder's low threshold. */
12809
+ lowFood: boolean(),
12810
+ /** Battery charge 0..100 (%). Null on mains-powered models or when the
12811
+ * device has no battery reading. */
12812
+ batteryPower: number().min(0).max(100).nullable(),
12813
+ /** Days of desiccant life remaining. Null when the model has no
12814
+ * desiccant sensor. */
12815
+ desiccantLeftDays: number().nullable(),
12816
+ /** True while a feed is in progress. */
12817
+ feeding: boolean(),
12818
+ /** Decoded connectivity / power status (HA petkit device-status enum).
12819
+ * Null until the device has reported a status. */
12820
+ status: PetFeederDeviceStatusSchema.nullable(),
12821
+ /** Decoded human-readable fault message. Null (or the device's `no_error`
12822
+ * sentinel) means healthy; a non-null string is an active fault. Pairs
12823
+ * with `errorCode` for consumers that want the raw integer. */
12824
+ error: string().nullable(),
12825
+ /** Raw device error code (0 / null = no error). */
12826
+ errorCode: number().nullable(),
12827
+ /** True for D4S/D4SH dual-hopper hardware — gates the per-hopper UI. */
12828
+ isDualHopper: boolean(),
12829
+ /** Child-lock (manual-lock) setting — buttons on the unit are disabled. */
12830
+ childLock: boolean(),
12831
+ /** Front indicator-light setting. */
12832
+ indicatorLight: boolean(),
12833
+ /** Play a chime when dispensing. */
12834
+ feedSound: boolean(),
12835
+ /** Speaker / prompt volume level (device-scaled integer). */
12836
+ volume: number(),
12837
+ /** Ms epoch when the slice was last refreshed from the cloud. */
12838
+ lastFetchedAt: number()
12839
+ });
12840
+ var petFeederCapability = {
12841
+ name: "pet-feeder",
12842
+ scope: "device",
12843
+ deviceNative: true,
12844
+ mode: "singleton",
12845
+ deviceTypes: [DeviceType.PetFeeder],
12846
+ methods: {
12847
+ /**
12848
+ * Dispense food now. Single-hopper feeders take `grams`; dual-hopper
12849
+ * feeders (D4S/D4SH) accept `hopper1`/`hopper2` to target one or both
12850
+ * hoppers. All portions honour the 4–200 g hardware range. At least
12851
+ * one of the three must be present — the provider rejects an empty
12852
+ * request.
12853
+ */
12854
+ feed: method(object({
12855
+ deviceId: number().int().nonnegative(),
12856
+ grams: gramsPortion.optional(),
12857
+ hopper1: gramsPortion.optional(),
12858
+ hopper2: gramsPortion.optional()
12859
+ }), _void(), {
12860
+ kind: "mutation",
12861
+ auth: "admin"
12862
+ }),
12863
+ /** Cancel an in-progress manual feed. */
12864
+ cancelFeed: method(object({ deviceId: number().int().nonnegative() }), _void(), {
12865
+ kind: "mutation",
12866
+ auth: "admin"
12867
+ }),
12868
+ /** Reset the desiccant "days remaining" counter after replacing it. */
12869
+ resetDesiccant: method(object({ deviceId: number().int().nonnegative() }), _void(), {
12870
+ kind: "mutation",
12871
+ auth: "admin"
12872
+ }),
12873
+ /** Mark a hopper as refilled (D4H/D4S/D4SH). */
12874
+ markFoodReplenished: method(object({ deviceId: number().int().nonnegative() }), _void(), {
12875
+ kind: "mutation",
12876
+ auth: "admin"
12877
+ }),
12878
+ /** Call the pet with the recorded prompt (D3). */
12879
+ callPet: method(object({ deviceId: number().int().nonnegative() }), _void(), {
12880
+ kind: "mutation",
12881
+ auth: "admin"
12882
+ }),
12883
+ /** Play a stored sound by id (D3 / D4H / D4SH). */
12884
+ playSound: method(object({
12885
+ deviceId: number().int().nonnegative(),
12886
+ soundId: number().int().nonnegative()
12887
+ }), _void(), {
12888
+ kind: "mutation",
12889
+ auth: "admin"
12890
+ }),
12891
+ /** Toggle the child-lock (manual-lock) setting. */
12892
+ setChildLock: method(object({
12893
+ deviceId: number().int().nonnegative(),
12894
+ on: boolean()
12895
+ }), _void(), {
12896
+ kind: "mutation",
12897
+ auth: "admin"
12898
+ }),
12899
+ /** Toggle the front indicator light. */
12900
+ setIndicatorLight: method(object({
12901
+ deviceId: number().int().nonnegative(),
12902
+ on: boolean()
12903
+ }), _void(), {
12904
+ kind: "mutation",
12905
+ auth: "admin"
12906
+ }),
12907
+ /** Toggle the dispense chime. */
12908
+ setFeedSound: method(object({
12909
+ deviceId: number().int().nonnegative(),
12910
+ on: boolean()
12911
+ }), _void(), {
12912
+ kind: "mutation",
12913
+ auth: "admin"
12914
+ }),
12915
+ /** Set the speaker / prompt volume level. */
12916
+ setVolume: method(object({
12917
+ deviceId: number().int().nonnegative(),
12918
+ level: number().int().nonnegative()
12919
+ }), _void(), {
12920
+ kind: "mutation",
12921
+ auth: "admin"
12922
+ })
12923
+ },
12924
+ status: {
12925
+ schema: PetFeederStatusSchema,
12926
+ kind: "poll"
12927
+ },
12928
+ /**
12929
+ * Runtime-state slice — mirrored by the kernel. UI feeder cards read
12930
+ * the full slice via `device.state.petFeeder.value` and refresh on
12931
+ * every poll without re-querying the provider.
12932
+ */
12933
+ runtimeState: PetFeederStatusSchema
12934
+ };
12935
+ /**
11940
12936
  * Multi-metric electrical meter. One slice can carry any combination
11941
12937
  * of instantaneous power (W), cumulative energy (kWh), voltage (V),
11942
12938
  * and current (A) — all fields optional so a single-metric source
@@ -13239,6 +14235,7 @@ var DEVICE_LOCAL_STATE_CAPS = {
13239
14235
  nativeObjectDetection: nativeObjectDetectionCapability,
13240
14236
  notifier: notifierCapability,
13241
14237
  numericSensor: numericSensorCapability,
14238
+ petFeeder: petFeederCapability,
13242
14239
  powerMeter: powerMeterCapability,
13243
14240
  presence: presenceCapability,
13244
14241
  pressureSensor: pressureSensorCapability,
@@ -15167,10 +16164,12 @@ method(object({ codec: string() }), boolean()), method(_void(), object({
15167
16164
  url: string()
15168
16165
  }), _void()), method(object({
15169
16166
  sessionId: string(),
15170
- maxCount: number().default(1)
16167
+ maxCount: number().default(1),
16168
+ waitMs: number().optional()
15171
16169
  }), array(DecodedFrameSchema)), method(object({
15172
16170
  sessionId: string(),
15173
- maxCount: number().default(1)
16171
+ maxCount: number().default(1),
16172
+ waitMs: number().optional()
15174
16173
  }), array(FrameHandleSchema)), method(object({ handle: FrameHandleSchema }), DecodedFrameSchema.nullable()), method(object({ sessionId: string() }), ShmRingStatsSchema.nullable()), method(object({
15175
16174
  sessionId: string(),
15176
16175
  config: DecoderSessionConfigSchema.partial()
@@ -15457,14 +16456,63 @@ var ChildLayoutEntrySchema = object({
15457
16456
  collapsed: boolean().optional()
15458
16457
  });
15459
16458
  /** Cap-wire shape of a DeviceLink — structurally mirrors `DeviceLink` in
15460
- * `device-management.ts`. */
16459
+ * `device-management.ts`. Source is a union: a FIELD source copies a sibling
16460
+ * accessory's status field (`kind` optional/absent for wire compat); a
16461
+ * LITERAL source carries a per-device constant (no sibling is read); a
16462
+ * GLOBAL source (P2e) copies ANY device's status field, addressed by the
16463
+ * source device's full re-sync-stable `stableId`. */
16464
+ var DeviceLinkFieldSourceSchema = object({
16465
+ kind: literal("field").optional(),
16466
+ sourceKey: string(),
16467
+ cap: string(),
16468
+ fieldPath: string()
16469
+ });
16470
+ var DeviceLinkLiteralSourceSchema = object({
16471
+ kind: literal("literal"),
16472
+ value: union([
16473
+ string(),
16474
+ number(),
16475
+ boolean(),
16476
+ _null()
16477
+ ])
16478
+ });
16479
+ var DeviceLinkGlobalSourceSchema = object({
16480
+ kind: literal("global"),
16481
+ sourceStableId: string(),
16482
+ cap: string(),
16483
+ fieldPath: string()
16484
+ });
16485
+ /** Expression source (Stage X): compute the target field from N named bindings
16486
+ * via the safe expression engine. Bindings are field | literal | global — never
16487
+ * another expression (no nesting). The `superRefine` runs the SAME author-time
16488
+ * validation as `validateExpressionSource` (compiles the expr, checks binding
16489
+ * names + identifier coverage) so every wire boundary that parses a DeviceLink
16490
+ * (tRPC mount, kernel create pre-seed, projection output) validates-at-write.
16491
+ * Compiles are LRU-cached, so repeated validation of the same expr is a hit. */
16492
+ var DeviceLinkExpressionSourceSchema = object({
16493
+ kind: literal("expression"),
16494
+ expr: string().min(1).max(MAX_EXPRESSION_SOURCE_LENGTH),
16495
+ bindings: record(string().regex(EXPRESSION_IDENTIFIER_RE), union([
16496
+ DeviceLinkFieldSourceSchema,
16497
+ DeviceLinkLiteralSourceSchema,
16498
+ DeviceLinkGlobalSourceSchema
16499
+ ]))
16500
+ }).superRefine((src, ctx) => {
16501
+ const err = validateExpressionSource(src);
16502
+ if (err !== null) ctx.addIssue({
16503
+ code: "custom",
16504
+ message: err,
16505
+ path: ["expr"]
16506
+ });
16507
+ });
15461
16508
  var DeviceLinkSchema = object({
15462
16509
  id: string(),
15463
- source: object({
15464
- sourceKey: string(),
15465
- cap: string(),
15466
- fieldPath: string()
15467
- }),
16510
+ source: union([
16511
+ DeviceLinkFieldSourceSchema,
16512
+ DeviceLinkLiteralSourceSchema,
16513
+ DeviceLinkGlobalSourceSchema,
16514
+ DeviceLinkExpressionSourceSchema
16515
+ ]),
15468
16516
  target: object({
15469
16517
  cap: string(),
15470
16518
  fieldPath: string(),
@@ -15493,6 +16541,31 @@ var DeviceLinkSchema = object({
15493
16541
  })
15494
16542
  ]).optional()
15495
16543
  });
16544
+ /** Cap-wire shape of a per-cap display refinement — mirrors
16545
+ * `DeviceCapDisplayOverride` in `device-management.ts`. */
16546
+ var DeviceCapDisplayOverrideSchema = object({
16547
+ unit: string().min(1).optional(),
16548
+ precision: number().int().min(0).max(10).optional()
16549
+ });
16550
+ /** Cap-wire shape of an operator-authored per-device display override —
16551
+ * mirrors `DeviceDisplayOverride` in `device-management.ts`. `precision`
16552
+ * bounds mirror `numeric-sensor.cap.ts` (`int 0-10`). */
16553
+ var DeviceDisplayOverrideSchema = object({
16554
+ icon: string().min(1).optional(),
16555
+ label: string().min(1).optional(),
16556
+ unit: string().min(1).optional(),
16557
+ precision: number().int().min(0).max(10).optional(),
16558
+ hidden: boolean().optional(),
16559
+ perCap: record(string(), DeviceCapDisplayOverrideSchema).optional()
16560
+ });
16561
+ /** Cap-wire shape of a per-role display default — mirrors `RoleDisplayDefault`
16562
+ * in `device-management.ts`. Keyed by `DeviceRole` string (role strings cross
16563
+ * the wire as plain strings everywhere else — cf. `DeviceInfoSchema.role`). */
16564
+ var RoleDisplayDefaultSchema = object({
16565
+ unit: string().min(1).optional(),
16566
+ precision: number().int().min(0).max(10).optional(),
16567
+ icon: string().min(1).optional()
16568
+ });
15496
16569
  /**
15497
16570
  * Serializable projection of a live IDevice.
15498
16571
  * Returned by listAll, getDevice, getChildren.
@@ -15548,7 +16621,9 @@ var DeviceInfoSchema = object({
15548
16621
  * `DeviceMeta.childLayout`. Absent ⇒ no layout declared. */
15549
16622
  childLayout: array(ChildLayoutEntrySchema).readonly().optional(),
15550
16623
  /** Operator-authored cross-device field wirings. See `DeviceMeta.deviceLinks`. */
15551
- deviceLinks: array(DeviceLinkSchema).readonly().optional()
16624
+ deviceLinks: array(DeviceLinkSchema).readonly().optional(),
16625
+ /** Operator-authored per-device display override. See `DeviceMeta.display`. */
16626
+ display: DeviceDisplayOverrideSchema.optional()
15552
16627
  });
15553
16628
  var ConfigEntrySchema = object({
15554
16629
  key: string(),
@@ -15613,7 +16688,9 @@ var DeviceMetaSchema = object({
15613
16688
  deviceLinks: array(DeviceLinkSchema).readonly().optional(),
15614
16689
  /** Semantic role string (`DeviceRole`) — propagated from the spawn pre-seed.
15615
16690
  * Optional: only present for accessory children that carry a known role. */
15616
- role: string().nullable().optional()
16691
+ role: string().nullable().optional(),
16692
+ /** Operator-authored per-device display override. See `DeviceMeta.display`. */
16693
+ display: DeviceDisplayOverrideSchema.optional()
15617
16694
  });
15618
16695
  /** ConfigUISchema passed through as unknown — mirrors device-provider's CreationSchemaOutputSchema */
15619
16696
  var ConfigUISchemaOutput = unknown().nullable();
@@ -15707,7 +16784,19 @@ method(object({
15707
16784
  }), _void(), {
15708
16785
  kind: "mutation",
15709
16786
  auth: "admin"
15710
- }), method(object({ deviceId: number() }), object({ caps: array(object({
16787
+ }), method(object({
16788
+ deviceId: number(),
16789
+ display: DeviceDisplayOverrideSchema.nullable()
16790
+ }), _void(), {
16791
+ kind: "mutation",
16792
+ auth: "admin"
16793
+ }), method(object({}), object({ defaults: record(string(), RoleDisplayDefaultSchema) }), { kind: "query" }), method(object({ defaults: record(string(), RoleDisplayDefaultSchema) }), _void(), {
16794
+ kind: "mutation",
16795
+ auth: "admin"
16796
+ }), method(object({
16797
+ deviceId: number(),
16798
+ includeSynthesizable: boolean().optional()
16799
+ }), object({ caps: array(object({
15711
16800
  cap: string(),
15712
16801
  fields: array(object({
15713
16802
  path: string(),
@@ -15717,8 +16806,13 @@ method(object({
15717
16806
  "boolean",
15718
16807
  "enum"
15719
16808
  ]),
15720
- enumValues: array(string()).optional()
15721
- })).readonly()
16809
+ enumValues: array(string()).optional(),
16810
+ item: boolean().optional()
16811
+ })).readonly(),
16812
+ itemArray: object({
16813
+ path: string(),
16814
+ keyField: string()
16815
+ }).optional()
15722
16816
  })).readonly() }), { kind: "query" }), method(object({
15723
16817
  deviceId: number(),
15724
16818
  role: string().nullable()
@@ -15788,7 +16882,11 @@ method(object({
15788
16882
  deviceId: number(),
15789
16883
  entries: array(object({
15790
16884
  capName: string(),
15791
- kind: _enum(["native", "wrapped"]),
16885
+ kind: _enum([
16886
+ "native",
16887
+ "wrapped",
16888
+ "linked"
16889
+ ]),
15792
16890
  providerAddonId: string(),
15793
16891
  providerNodeId: string(),
15794
16892
  nativeAddonId: string()
@@ -15797,7 +16895,11 @@ method(object({
15797
16895
  deviceId: number(),
15798
16896
  entries: array(object({
15799
16897
  capName: string(),
15800
- kind: _enum(["native", "wrapped"]),
16898
+ kind: _enum([
16899
+ "native",
16900
+ "wrapped",
16901
+ "linked"
16902
+ ]),
15801
16903
  providerAddonId: string(),
15802
16904
  providerNodeId: string(),
15803
16905
  nativeAddonId: string()
@@ -19651,7 +20753,10 @@ var HwAccelBackendInputSchema = _enum([
19651
20753
  "webgpu",
19652
20754
  "none"
19653
20755
  ]).nullable().optional();
19654
- var HwAccelResolutionSchema = object({ preferred: array(string()).readonly() });
20756
+ var HwAccelResolutionSchema = object({
20757
+ preferred: array(string()).readonly(),
20758
+ rationale: string()
20759
+ });
19655
20760
  var HardwareEncoderIdSchema = _enum([
19656
20761
  "h264_videotoolbox",
19657
20762
  "hevc_videotoolbox",
@@ -19756,10 +20861,7 @@ var ResolvedInferenceConfigSchema = object({
19756
20861
  format: ModelFormatSchema,
19757
20862
  reason: string()
19758
20863
  });
19759
- method(_void(), PlatformCapabilitiesSchema), method(_void(), HardwareInfoSchema), method(object({ requirements: array(ModelRequirementSchema).readonly() }), ResolvedInferenceConfigSchema), method(object({
19760
- prefer: HwAccelBackendInputSchema,
19761
- nodeId: string().optional()
19762
- }), HwAccelResolutionSchema), method(_void(), HardwareEncodersSchema), method(_void(), HardwareEncodersSchema, {
20864
+ method(_void(), PlatformCapabilitiesSchema), method(_void(), HardwareInfoSchema), method(object({ requirements: array(ModelRequirementSchema).readonly() }), ResolvedInferenceConfigSchema), method(object({ prefer: HwAccelBackendInputSchema }), HwAccelResolutionSchema), method(_void(), HardwareEncodersSchema), method(_void(), HardwareEncodersSchema, {
19763
20865
  kind: "mutation",
19764
20866
  auth: "admin"
19765
20867
  }), method(_void(), HardwareDecodeAccelsSchema), method(_void(), HardwareDecodeAccelsSchema, {
@@ -19885,6 +20987,16 @@ var rebootCapability = {
19885
20987
  auth: "admin"
19886
20988
  }) }
19887
20989
  };
20990
+ /**
20991
+ * `recording` cap — footage availability + HLS playback manifests + per-device
20992
+ * recording config. NOTE on events (source of truth, R5/C3): this cap carries
20993
+ * NO event surface — `getPlaybackManifest` returns playlist URLs only. Timeline
20994
+ * events (motion/object/audio) come from `pipelineAnalytics` (durable SQLite
20995
+ * rows); the recorder's internal EventMap markers are ephemeral in-RAM
20996
+ * annotations that are not exposed here and must not be treated as an event
20997
+ * feed. Event<->footage joins are by time, padded with the shared `EVENT_PAD_MS`
20998
+ * (`interfaces/recording-config.ts`).
20999
+ */
19888
21000
  var RecordingStatusSchema = object({
19889
21001
  deviceId: number(),
19890
21002
  enabled: boolean(),
@@ -21732,6 +22844,12 @@ Object.freeze({
21732
22844
  addonId: null,
21733
22845
  access: "view"
21734
22846
  },
22847
+ "deviceManager.getRoleDisplayDefaults": {
22848
+ capName: "device-manager",
22849
+ capScope: "system",
22850
+ addonId: null,
22851
+ access: "view"
22852
+ },
21735
22853
  "deviceManager.getSettingsSchema": {
21736
22854
  capName: "device-manager",
21737
22855
  capScope: "system",
@@ -21882,6 +23000,12 @@ Object.freeze({
21882
23000
  addonId: null,
21883
23001
  access: "create"
21884
23002
  },
23003
+ "deviceManager.setDisplay": {
23004
+ capName: "device-manager",
23005
+ capScope: "system",
23006
+ addonId: null,
23007
+ access: "create"
23008
+ },
21885
23009
  "deviceManager.setIntegrationId": {
21886
23010
  capName: "device-manager",
21887
23011
  capScope: "system",
@@ -21924,6 +23048,12 @@ Object.freeze({
21924
23048
  addonId: null,
21925
23049
  access: "create"
21926
23050
  },
23051
+ "deviceManager.setRoleDisplayDefaults": {
23052
+ capName: "device-manager",
23053
+ capScope: "system",
23054
+ addonId: null,
23055
+ access: "create"
23056
+ },
21927
23057
  "deviceManager.setStreamProfileMap": {
21928
23058
  capName: "device-manager",
21929
23059
  capScope: "system",
@@ -22974,6 +24104,66 @@ Object.freeze({
22974
24104
  addonId: null,
22975
24105
  access: "create"
22976
24106
  },
24107
+ "petFeeder.callPet": {
24108
+ capName: "pet-feeder",
24109
+ capScope: "device",
24110
+ addonId: null,
24111
+ access: "create"
24112
+ },
24113
+ "petFeeder.cancelFeed": {
24114
+ capName: "pet-feeder",
24115
+ capScope: "device",
24116
+ addonId: null,
24117
+ access: "create"
24118
+ },
24119
+ "petFeeder.feed": {
24120
+ capName: "pet-feeder",
24121
+ capScope: "device",
24122
+ addonId: null,
24123
+ access: "create"
24124
+ },
24125
+ "petFeeder.markFoodReplenished": {
24126
+ capName: "pet-feeder",
24127
+ capScope: "device",
24128
+ addonId: null,
24129
+ access: "create"
24130
+ },
24131
+ "petFeeder.playSound": {
24132
+ capName: "pet-feeder",
24133
+ capScope: "device",
24134
+ addonId: null,
24135
+ access: "create"
24136
+ },
24137
+ "petFeeder.resetDesiccant": {
24138
+ capName: "pet-feeder",
24139
+ capScope: "device",
24140
+ addonId: null,
24141
+ access: "delete"
24142
+ },
24143
+ "petFeeder.setChildLock": {
24144
+ capName: "pet-feeder",
24145
+ capScope: "device",
24146
+ addonId: null,
24147
+ access: "create"
24148
+ },
24149
+ "petFeeder.setFeedSound": {
24150
+ capName: "pet-feeder",
24151
+ capScope: "device",
24152
+ addonId: null,
24153
+ access: "create"
24154
+ },
24155
+ "petFeeder.setIndicatorLight": {
24156
+ capName: "pet-feeder",
24157
+ capScope: "device",
24158
+ addonId: null,
24159
+ access: "create"
24160
+ },
24161
+ "petFeeder.setVolume": {
24162
+ capName: "pet-feeder",
24163
+ capScope: "device",
24164
+ addonId: null,
24165
+ access: "create"
24166
+ },
22977
24167
  "pipelineAnalytics.clearTracks": {
22978
24168
  capName: "pipeline-analytics",
22979
24169
  capScope: "device",
@@ -223208,6 +224398,47 @@ function buildCreationFormSchema() {
223208
224398
  ] };
223209
224399
  }
223210
224400
  //#endregion
224401
+ //#region src/reolink-discovery-map.ts
224402
+ /**
224403
+ * Flatten a host (IP / hostname) into a flat row-key slug — shared by `generateStableId` and the
224404
+ * discovery candidate mapping so a host-keyed camera is detected as already onboarded on re-scan.
224405
+ */
224406
+ function slugifyReolinkHost(host) {
224407
+ return host.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
224408
+ }
224409
+ /**
224410
+ * Map discovered Reolink hosts to adoption {@link DiscoveryCandidate}s, de-duplicated by host (the
224411
+ * same camera can answer on more than one discovery method — UDP broadcast, ONVIF, HTTP scan). The
224412
+ * first responder for a host wins. Pure: no I/O.
224413
+ *
224414
+ * The authoritative stableId is `mac-<mac>` (learned during autodetect at adopt time), which discovery
224415
+ * can't produce — so a re-scan of a MAC-keyed camera may still show as addable. The `host-` key still
224416
+ * lets host-added cameras be detected as onboarded on re-scan.
224417
+ */
224418
+ function mapReolinkDiscoveryToCandidates(devices, credentials) {
224419
+ const username = credentials.username?.trim() ?? "";
224420
+ const password = credentials.password ?? "";
224421
+ const byHost = /* @__PURE__ */ new Map();
224422
+ for (const d of devices) if (!byHost.has(d.host)) byHost.set(d.host, d);
224423
+ return [...byHost.values()].map((d) => {
224424
+ const displayName = d.name ?? d.model ?? d.host;
224425
+ return {
224426
+ stableId: `host-${slugifyReolinkHost(d.host)}`,
224427
+ type: DeviceType.Camera,
224428
+ suggestedName: displayName,
224429
+ prefilledConfig: {
224430
+ name: displayName,
224431
+ host: d.host,
224432
+ transport: "auto",
224433
+ ...d.httpPort !== void 0 ? { port: d.httpPort } : {},
224434
+ ...d.uid ? { uid: d.uid } : {},
224435
+ ...username ? { username } : {},
224436
+ ...password ? { password } : {}
224437
+ }
224438
+ };
224439
+ });
224440
+ }
224441
+ //#endregion
223211
224442
  //#region src/autodetect-cache.ts
223212
224443
  var DEFAULT_TTL_MS = 6e4;
223213
224444
  var AutodetectCache = class {
@@ -223720,11 +224951,6 @@ function isMeaningfulIdentifier(s) {
223720
224951
  if (!s || s.length < 6) return false;
223721
224952
  return new Set(s.toLowerCase().split("").filter((c) => c !== "0" && c !== "f")).size >= 1;
223722
224953
  }
223723
- /** Flatten a host (IP / hostname) into a flat row-key slug — shared by `generateStableId` and the
223724
- * discovery candidate mapping so a host-keyed camera is detected as already onboarded on re-scan. */
223725
- function slugifyReolinkHost(host) {
223726
- return host.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
223727
- }
223728
224954
  /**
223729
224955
  * Patch `detection.deviceInfo` + `hostNetworkInfo` in-place with the
223730
224956
  * post-login HOST identifiers. Two distinct gaps to fill:
@@ -223831,14 +225057,32 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
223831
225057
  }
223832
225058
  return cameras;
223833
225059
  }
225060
+ /**
225061
+ * Bootstrapped SMTP AUTH credentials — Zod-validated durable handles
225062
+ * over the SAME two store keys the raw writer used. Built lazily
225063
+ * (needs `this.ctx`) and memoised.
225064
+ */
225065
+ _emailPushAuthUsernameState = null;
225066
+ _emailPushAuthPasswordState = null;
225067
+ get emailPushAuthUsernameState() {
225068
+ if (!this._emailPushAuthUsernameState) this._emailPushAuthUsernameState = this.state("emailPushAuthUsername", string(), "");
225069
+ return this._emailPushAuthUsernameState;
225070
+ }
225071
+ get emailPushAuthPasswordState() {
225072
+ if (!this._emailPushAuthPasswordState) this._emailPushAuthPasswordState = this.state("emailPushAuthPassword", string(), "");
225073
+ return this._emailPushAuthPasswordState;
225074
+ }
223834
225075
  /** Lazily build the email-push server, wiring its provider deps. */
223835
225076
  ensureEmailPushServer() {
223836
225077
  if (!this.emailPushServer) this.emailPushServer = new ReolinkEmailPushServer({
223837
225078
  logger: this.ctx.logger.child("email-push"),
223838
225079
  listCameras: () => this.listReolinkCameras(),
223839
- readStore: async () => await this.ctx.settings?.readAddonStore() ?? {},
225080
+ readStore: async () => await this.resolveGlobalStore(),
223840
225081
  writeStore: async (patch) => {
223841
- await this.ctx.settings?.writeAddonStore(patch);
225082
+ const username = patch["emailPushAuthUsername"];
225083
+ if (typeof username === "string") await this.emailPushAuthUsernameState.set(username);
225084
+ const password = patch["emailPushAuthPassword"];
225085
+ if (typeof password === "string") await this.emailPushAuthPasswordState.set(password);
223842
225086
  }
223843
225087
  });
223844
225088
  return this.emailPushServer;
@@ -223917,13 +225161,9 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
223917
225161
  });
223918
225162
  }
223919
225163
  async getGlobalSettings() {
223920
- const raw = await this.ctx.settings?.readAddonStore() ?? {};
225164
+ const raw = await this.resolveGlobalStore();
223921
225165
  return hydrateSchema(buildEmailPushSettingsSchema(listLanHosts()[0] ?? "127.0.0.1"), raw);
223922
225166
  }
223923
- async updateGlobalSettings(patch) {
223924
- await this.ctx.settings?.writeAddonStore(patch);
223925
- await this.onConfigChanged();
223926
- }
223927
225167
  async onInitialize() {
223928
225168
  const regs = await super.onInitialize();
223929
225169
  this.subscribe({ category: EventCategory.StreamBrokerOnRequestStreamSourceRefresh }, (event) => {
@@ -224019,24 +225259,9 @@ var ReolinkProviderAddon = class extends BaseDeviceProvider {
224019
225259
  networkCidr: networkCidr || "local",
224020
225260
  enableOnvif
224021
225261
  } });
224022
- const byHost = /* @__PURE__ */ new Map();
224023
- for (const d of devices) if (!byHost.has(d.host)) byHost.set(d.host, d);
224024
- return [...byHost.values()].map((d) => {
224025
- const displayName = d.name ?? d.model ?? d.host;
224026
- return {
224027
- stableId: `host-${slugifyReolinkHost(d.host)}`,
224028
- type: DeviceType.Camera,
224029
- suggestedName: displayName,
224030
- prefilledConfig: {
224031
- name: displayName,
224032
- host: d.host,
224033
- transport: "auto",
224034
- ...d.httpPort !== void 0 ? { port: d.httpPort } : {},
224035
- ...d.uid ? { uid: d.uid } : {},
224036
- ...username ? { username } : {},
224037
- ...password ? { password } : {}
224038
- }
224039
- };
225262
+ return mapReolinkDiscoveryToCandidates(devices, {
225263
+ username,
225264
+ password
224040
225265
  });
224041
225266
  }
224042
225267
  async adoptDiscoveredDevice(input) {