@camstack/addon-provider-homematic 1.2.10 → 1.2.11

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 +1252 -948
  2. package/dist/addon.mjs +1252 -948
  3. package/package.json +1 -1
package/dist/addon.js CHANGED
@@ -7942,6 +7942,780 @@ var ConvertResultSchema = object({
7942
7942
  })).readonly()
7943
7943
  });
7944
7944
  /**
7945
+ * Error types for the safe expression engine. Two distinct classes so callers
7946
+ * can tell a compile-time (grammar) failure from a runtime (evaluation)
7947
+ * failure — both are non-fatal to the host: read paths degrade to "skip link".
7948
+ */
7949
+ /** Thrown by the tokenizer / parser. Carries a 0-based source `position` when
7950
+ * the failure is anchored to a character (author-facing inline feedback). */
7951
+ var ExpressionParseError = class extends Error {
7952
+ position;
7953
+ constructor(message, position) {
7954
+ super(message);
7955
+ this.name = "ExpressionParseError";
7956
+ this.position = position;
7957
+ }
7958
+ };
7959
+ /** Thrown by the evaluator (unknown identifier, type mismatch, non-finite
7960
+ * result, unknown builtin, step-budget exceeded). */
7961
+ var ExpressionEvalError = class extends Error {
7962
+ constructor(message) {
7963
+ super(message);
7964
+ this.name = "ExpressionEvalError";
7965
+ }
7966
+ };
7967
+ /**
7968
+ * Frozen, null-prototype builtin function table for the expression engine
7969
+ * (spec §4 rule 4). The table is the SOLE surface of callable functions: the
7970
+ * parser rejects any callee not in it, and the evaluator gates each call on an
7971
+ * own-property check against it.
7972
+ *
7973
+ * Because the object has a NULL prototype AND is `Object.freeze`d:
7974
+ * - it cannot be polluted (no `__proto__` / `constructor` write reaches it);
7975
+ * - a lookup for `toString` / `hasOwnProperty` / `constructor` finds NOTHING
7976
+ * (there is no `Object.prototype` in the chain), so those names are not
7977
+ * callable — they are simply "unknown function" at parse time.
7978
+ *
7979
+ * Every numeric argument is validated as a finite number and every numeric
7980
+ * RESULT is re-checked finite, so `/0`, `sqrt(-1)` (→ NaN) and overflow
7981
+ * (`pow(10,400)` → Infinity) all raise `ExpressionEvalError` and fail the link
7982
+ * closed rather than emitting a garbage value.
7983
+ */
7984
+ function asFiniteNumber(value, name, index) {
7985
+ if (typeof value !== "number" || !Number.isFinite(value)) throw new ExpressionEvalError(`${name}: argument ${index + 1} must be a finite number`);
7986
+ return value;
7987
+ }
7988
+ function asString$1(value, name, index) {
7989
+ if (typeof value !== "string") throw new ExpressionEvalError(`${name}: argument ${index + 1} must be a string`);
7990
+ return value;
7991
+ }
7992
+ function finiteResult(value, name) {
7993
+ if (!Number.isFinite(value)) throw new ExpressionEvalError(`${name}: produced a non-finite result`);
7994
+ return value;
7995
+ }
7996
+ function allFiniteNumbers(args, name) {
7997
+ return args.map((a, idx) => asFiniteNumber(a, name, idx));
7998
+ }
7999
+ var INF = Number.POSITIVE_INFINITY;
8000
+ var table = {
8001
+ min: {
8002
+ minArgs: 1,
8003
+ maxArgs: INF,
8004
+ apply: (args) => finiteResult(Math.min(...allFiniteNumbers(args, "min")), "min")
8005
+ },
8006
+ max: {
8007
+ minArgs: 1,
8008
+ maxArgs: INF,
8009
+ apply: (args) => finiteResult(Math.max(...allFiniteNumbers(args, "max")), "max")
8010
+ },
8011
+ abs: {
8012
+ minArgs: 1,
8013
+ maxArgs: 1,
8014
+ apply: (args) => finiteResult(Math.abs(asFiniteNumber(args[0], "abs", 0)), "abs")
8015
+ },
8016
+ floor: {
8017
+ minArgs: 1,
8018
+ maxArgs: 1,
8019
+ apply: (args) => finiteResult(Math.floor(asFiniteNumber(args[0], "floor", 0)), "floor")
8020
+ },
8021
+ ceil: {
8022
+ minArgs: 1,
8023
+ maxArgs: 1,
8024
+ apply: (args) => finiteResult(Math.ceil(asFiniteNumber(args[0], "ceil", 0)), "ceil")
8025
+ },
8026
+ sqrt: {
8027
+ minArgs: 1,
8028
+ maxArgs: 1,
8029
+ apply: (args) => finiteResult(Math.sqrt(asFiniteNumber(args[0], "sqrt", 0)), "sqrt")
8030
+ },
8031
+ round: {
8032
+ minArgs: 1,
8033
+ maxArgs: 2,
8034
+ apply: (args) => {
8035
+ const x = asFiniteNumber(args[0], "round", 0);
8036
+ const digits = args.length > 1 ? Math.trunc(asFiniteNumber(args[1], "round", 1)) : 0;
8037
+ if (digits < 0 || digits > 100) throw new ExpressionEvalError("round: digits must be between 0 and 100");
8038
+ const factor = 10 ** digits;
8039
+ return finiteResult(Math.round(x * factor) / factor, "round");
8040
+ }
8041
+ },
8042
+ pow: {
8043
+ minArgs: 2,
8044
+ maxArgs: 2,
8045
+ apply: (args) => finiteResult(asFiniteNumber(args[0], "pow", 0) ** asFiniteNumber(args[1], "pow", 1), "pow")
8046
+ },
8047
+ clamp: {
8048
+ minArgs: 3,
8049
+ maxArgs: 3,
8050
+ apply: (args) => {
8051
+ const x = asFiniteNumber(args[0], "clamp", 0);
8052
+ const lo = asFiniteNumber(args[1], "clamp", 1);
8053
+ const hi = asFiniteNumber(args[2], "clamp", 2);
8054
+ if (lo > hi) throw new ExpressionEvalError("clamp: lower bound is greater than upper bound");
8055
+ return finiteResult(Math.min(hi, Math.max(lo, x)), "clamp");
8056
+ }
8057
+ },
8058
+ avg: {
8059
+ minArgs: 1,
8060
+ maxArgs: INF,
8061
+ apply: (args) => {
8062
+ const nums = allFiniteNumbers(args, "avg");
8063
+ return finiteResult(nums.reduce((acc, v) => acc + v, 0) / nums.length, "avg");
8064
+ }
8065
+ },
8066
+ sum: {
8067
+ minArgs: 1,
8068
+ maxArgs: INF,
8069
+ apply: (args) => finiteResult(allFiniteNumbers(args, "sum").reduce((acc, v) => acc + v, 0), "sum")
8070
+ },
8071
+ coalesce: {
8072
+ minArgs: 1,
8073
+ maxArgs: INF,
8074
+ apply: (args) => {
8075
+ for (const a of args) if (a !== null) return a;
8076
+ return null;
8077
+ }
8078
+ },
8079
+ age: {
8080
+ minArgs: 2,
8081
+ maxArgs: 2,
8082
+ apply: (args) => finiteResult(asFiniteNumber(args[0], "age", 0) - asFiniteNumber(args[1], "age", 1), "age")
8083
+ },
8084
+ convert: {
8085
+ minArgs: 3,
8086
+ maxArgs: 3,
8087
+ apply: (args, hooks) => {
8088
+ const x = asFiniteNumber(args[0], "convert", 0);
8089
+ const from = asString$1(args[1], "convert", 1).trim();
8090
+ const to = asString$1(args[2], "convert", 2).trim();
8091
+ if (hooks.convert) {
8092
+ const out = hooks.convert(x, from, to);
8093
+ if (out === null) throw new ExpressionEvalError(`convert: cannot convert '${from}' to '${to}'`);
8094
+ return finiteResult(out, "convert");
8095
+ }
8096
+ if (from === to) return x;
8097
+ throw new ExpressionEvalError("convert: unit conversion table not installed");
8098
+ }
8099
+ }
8100
+ };
8101
+ Object.freeze(Object.assign(Object.create(null), table));
8102
+ /** The set of valid builtin names — used by the parser to reject unknown
8103
+ * callees at parse time (immediate author feedback). */
8104
+ var EXPRESSION_BUILTIN_NAMES = new Set(Object.keys(table));
8105
+ /**
8106
+ * Resource-bound constants for the safe expression engine.
8107
+ *
8108
+ * Every bound is defense-in-depth: the grammar is non-Turing-complete (no
8109
+ * loops, recursion, lambdas or member access — see `ast.ts`), so evaluation is
8110
+ * O(nodeCount) by construction. These caps merely put a hard ceiling on the
8111
+ * work a single author-supplied expression can request, so a hostile or
8112
+ * accidental pathological string can never spend unbounded CPU/memory.
8113
+ */
8114
+ /** Max source length (chars) — checked BEFORE tokenizing so a huge string is
8115
+ * rejected without allocation. */
8116
+ var MAX_EXPRESSION_SOURCE_LENGTH = 2048;
8117
+ /** A legal binding / identifier name. */
8118
+ var EXPRESSION_IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
8119
+ /** Binding names an author may NOT use: `now` is auto-injected; the literal
8120
+ * keywords lex as values, not identifiers, so binding to them is meaningless. */
8121
+ var RESERVED_BINDING_NAMES = new Set([
8122
+ "now",
8123
+ "true",
8124
+ "false",
8125
+ "null"
8126
+ ]);
8127
+ /**
8128
+ * Tokenizer for the safe expression mini-language. Hand-rolled, single-pass,
8129
+ * zero-dependency. The grammar is deliberately boring: decimal numbers,
8130
+ * single/double-quoted strings with a tiny escape set, identifiers, the three
8131
+ * value keywords (`true`/`false`/`null`) and a fixed punctuator set. Anything
8132
+ * outside that — a bare `.`, `=`, `[`, `]`, `{`, `}`, `;`, backtick, `&`, `|` —
8133
+ * is a parse error with a source position, so member access / assignment /
8134
+ * template literals are lexically impossible.
8135
+ */
8136
+ var KEYWORDS = new Set([
8137
+ "true",
8138
+ "false",
8139
+ "null"
8140
+ ]);
8141
+ function isDigit(ch) {
8142
+ return ch >= "0" && ch <= "9";
8143
+ }
8144
+ function isIdentStart(ch) {
8145
+ return ch >= "A" && ch <= "Z" || ch >= "a" && ch <= "z" || ch === "_";
8146
+ }
8147
+ function isIdentPart(ch) {
8148
+ return isIdentStart(ch) || isDigit(ch);
8149
+ }
8150
+ function isWhitespace(ch) {
8151
+ return ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === "\f" || ch === "\v";
8152
+ }
8153
+ /** Tokenize `source` into a flat token list ending with a single `eof` token.
8154
+ * Throws `ExpressionParseError` on any illegal character or unterminated
8155
+ * string. */
8156
+ function tokenize(source) {
8157
+ if (source.length > 2048) throw new ExpressionParseError(`expression too long (${source.length} > ${MAX_EXPRESSION_SOURCE_LENGTH} chars)`, 0);
8158
+ const tokens = [];
8159
+ let i = 0;
8160
+ const n = source.length;
8161
+ while (i < n) {
8162
+ const ch = source[i];
8163
+ if (isWhitespace(ch)) {
8164
+ i += 1;
8165
+ continue;
8166
+ }
8167
+ if (isDigit(ch)) {
8168
+ const start = i;
8169
+ while (i < n && isDigit(source[i])) i += 1;
8170
+ if (i < n && source[i] === ".") {
8171
+ if (i + 1 >= n || !isDigit(source[i + 1])) throw new ExpressionParseError("malformed number: decimal point needs a digit", i);
8172
+ i += 1;
8173
+ while (i < n && isDigit(source[i])) i += 1;
8174
+ }
8175
+ const text = source.slice(start, i);
8176
+ const value = Number(text);
8177
+ if (!Number.isFinite(value)) throw new ExpressionParseError(`malformed number: '${text}'`, start);
8178
+ tokens.push({
8179
+ type: "number",
8180
+ value,
8181
+ pos: start
8182
+ });
8183
+ continue;
8184
+ }
8185
+ if (ch === "'" || ch === "\"") {
8186
+ const quote = ch;
8187
+ const start = i;
8188
+ i += 1;
8189
+ let out = "";
8190
+ let closed = false;
8191
+ while (i < n) {
8192
+ const c = source[i];
8193
+ if (c === "\\") {
8194
+ const next = i + 1 < n ? source[i + 1] : "";
8195
+ if (next === "\\" || next === "'" || next === "\"") {
8196
+ out += next;
8197
+ i += 2;
8198
+ continue;
8199
+ }
8200
+ throw new ExpressionParseError(`invalid string escape: '\\${next}'`, i);
8201
+ }
8202
+ if (c === quote) {
8203
+ closed = true;
8204
+ i += 1;
8205
+ break;
8206
+ }
8207
+ out += c;
8208
+ i += 1;
8209
+ }
8210
+ if (!closed) throw new ExpressionParseError("unterminated string literal", start);
8211
+ tokens.push({
8212
+ type: "string",
8213
+ value: out,
8214
+ pos: start
8215
+ });
8216
+ continue;
8217
+ }
8218
+ if (isIdentStart(ch)) {
8219
+ const start = i;
8220
+ while (i < n && isIdentPart(source[i])) i += 1;
8221
+ const text = source.slice(start, i);
8222
+ if (KEYWORDS.has(text)) tokens.push({
8223
+ type: "keyword",
8224
+ keyword: keywordOf(text),
8225
+ pos: start
8226
+ });
8227
+ else tokens.push({
8228
+ type: "identifier",
8229
+ name: text,
8230
+ pos: start
8231
+ });
8232
+ continue;
8233
+ }
8234
+ const two = i + 1 < n ? source.slice(i, i + 2) : "";
8235
+ if (two === "<=" || two === ">=" || two === "==" || two === "!=" || two === "&&" || two === "||") {
8236
+ tokens.push({
8237
+ type: "punct",
8238
+ punct: two,
8239
+ pos: i
8240
+ });
8241
+ i += 2;
8242
+ continue;
8243
+ }
8244
+ if (isSinglePunct(ch)) {
8245
+ tokens.push({
8246
+ type: "punct",
8247
+ punct: ch,
8248
+ pos: i
8249
+ });
8250
+ i += 1;
8251
+ continue;
8252
+ }
8253
+ throw new ExpressionParseError(`unexpected character '${ch}'`, i);
8254
+ }
8255
+ tokens.push({
8256
+ type: "eof",
8257
+ pos: n
8258
+ });
8259
+ return tokens;
8260
+ }
8261
+ function keywordOf(text) {
8262
+ if (text === "true") return "true";
8263
+ if (text === "false") return "false";
8264
+ return "null";
8265
+ }
8266
+ function isSinglePunct(ch) {
8267
+ return ch === "(" || ch === ")" || ch === "," || ch === "?" || ch === ":" || ch === "+" || ch === "-" || ch === "*" || ch === "/" || ch === "%" || ch === "!" || ch === "<" || ch === ">";
8268
+ }
8269
+ /**
8270
+ * Pratt (precedence-climbing) parser for the safe expression mini-language.
8271
+ *
8272
+ * Precedence (low → high): ternary `?:` (right-assoc) → `||` → `&&` → equality
8273
+ * → relational → additive → multiplicative → unary `! -` → call / primary.
8274
+ * Calls are ONLY `IDENT '(' args? ')'` at primary position — the callee is a
8275
+ * string validated against the builtin table at parse time, so an unknown
8276
+ * function is rejected immediately (author feedback) and a persisted expression
8277
+ * that references a since-removed builtin degrades at read.
8278
+ *
8279
+ * A node counter caps total AST size (`MAX_EXPRESSION_AST_NODES`) and call
8280
+ * arity is capped (`MAX_EXPRESSION_CALL_ARGS`) — both raise `ExpressionParseError`.
8281
+ */
8282
+ /** Binary/logical operator precedence (higher binds tighter). */
8283
+ var BINARY_PRECEDENCE = {
8284
+ "||": 1,
8285
+ "&&": 2,
8286
+ "==": 3,
8287
+ "!=": 3,
8288
+ "<": 4,
8289
+ "<=": 4,
8290
+ ">": 4,
8291
+ ">=": 4,
8292
+ "+": 5,
8293
+ "-": 5,
8294
+ "*": 6,
8295
+ "/": 6,
8296
+ "%": 6
8297
+ };
8298
+ function isLogicalOp(op) {
8299
+ return op === "&&" || op === "||";
8300
+ }
8301
+ function isBinaryOp(op) {
8302
+ return op === "+" || op === "-" || op === "*" || op === "/" || op === "%" || op === "==" || op === "!=" || op === "<" || op === "<=" || op === ">" || op === ">=";
8303
+ }
8304
+ var Parser = class {
8305
+ tokens;
8306
+ pos = 0;
8307
+ nodeCount = 0;
8308
+ identifiers = /* @__PURE__ */ new Set();
8309
+ callees = /* @__PURE__ */ new Set();
8310
+ constructor(tokens) {
8311
+ this.tokens = tokens;
8312
+ }
8313
+ parse() {
8314
+ const ast = this.parseTernary();
8315
+ const tok = this.peek();
8316
+ if (tok.type !== "eof") throw new ExpressionParseError("unexpected trailing input", tok.pos);
8317
+ return {
8318
+ ast,
8319
+ identifiers: this.identifiers,
8320
+ callees: this.callees,
8321
+ nodeCount: this.nodeCount
8322
+ };
8323
+ }
8324
+ peek() {
8325
+ return this.tokens[this.pos];
8326
+ }
8327
+ next() {
8328
+ return this.tokens[this.pos++];
8329
+ }
8330
+ /** Consume a punctuator token, erroring if the next token isn't it. */
8331
+ expectPunct(punct) {
8332
+ const tok = this.peek();
8333
+ if (tok.type !== "punct" || tok.punct !== punct) throw new ExpressionParseError(`expected '${punct}'`, tok.pos);
8334
+ this.pos += 1;
8335
+ }
8336
+ matchPunct(punct) {
8337
+ const tok = this.peek();
8338
+ if (tok.type === "punct" && tok.punct === punct) {
8339
+ this.pos += 1;
8340
+ return true;
8341
+ }
8342
+ return false;
8343
+ }
8344
+ countNode() {
8345
+ this.nodeCount += 1;
8346
+ if (this.nodeCount > 256) throw new ExpressionParseError("expression too complex", this.peek().pos);
8347
+ }
8348
+ parseTernary() {
8349
+ const test = this.parseBinary(1);
8350
+ if (this.matchPunct("?")) {
8351
+ const consequent = this.parseTernary();
8352
+ this.expectPunct(":");
8353
+ const alternate = this.parseTernary();
8354
+ this.countNode();
8355
+ return {
8356
+ kind: "conditional",
8357
+ test,
8358
+ consequent,
8359
+ alternate
8360
+ };
8361
+ }
8362
+ return test;
8363
+ }
8364
+ parseBinary(minPrec) {
8365
+ let left = this.parseUnary();
8366
+ for (;;) {
8367
+ const tok = this.peek();
8368
+ if (tok.type !== "punct") break;
8369
+ const prec = BINARY_PRECEDENCE[tok.punct];
8370
+ if (prec === void 0 || prec < minPrec) break;
8371
+ const op = tok.punct;
8372
+ this.pos += 1;
8373
+ const right = this.parseBinary(prec + 1);
8374
+ this.countNode();
8375
+ if (isLogicalOp(op)) left = {
8376
+ kind: "logical",
8377
+ op,
8378
+ left,
8379
+ right
8380
+ };
8381
+ else if (isBinaryOp(op)) left = {
8382
+ kind: "binary",
8383
+ op,
8384
+ left,
8385
+ right
8386
+ };
8387
+ else throw new ExpressionParseError(`unexpected operator '${op}'`, tok.pos);
8388
+ }
8389
+ return left;
8390
+ }
8391
+ parseUnary() {
8392
+ const tok = this.peek();
8393
+ if (tok.type === "punct" && (tok.punct === "!" || tok.punct === "-")) {
8394
+ const op = tok.punct;
8395
+ this.pos += 1;
8396
+ const operand = this.parseUnary();
8397
+ this.countNode();
8398
+ return {
8399
+ kind: "unary",
8400
+ op,
8401
+ operand
8402
+ };
8403
+ }
8404
+ return this.parsePrimary();
8405
+ }
8406
+ parsePrimary() {
8407
+ const tok = this.next();
8408
+ switch (tok.type) {
8409
+ case "number":
8410
+ this.countNode();
8411
+ return {
8412
+ kind: "literal",
8413
+ value: tok.value
8414
+ };
8415
+ case "string":
8416
+ this.countNode();
8417
+ return {
8418
+ kind: "literal",
8419
+ value: tok.value
8420
+ };
8421
+ case "keyword":
8422
+ this.countNode();
8423
+ return {
8424
+ kind: "literal",
8425
+ value: tok.keyword === "null" ? null : tok.keyword === "true"
8426
+ };
8427
+ case "identifier": {
8428
+ const nextTok = this.peek();
8429
+ if (nextTok.type === "punct" && nextTok.punct === "(") return this.parseCall(tok.name, tok.pos);
8430
+ this.identifiers.add(tok.name);
8431
+ this.countNode();
8432
+ return {
8433
+ kind: "identifier",
8434
+ name: tok.name
8435
+ };
8436
+ }
8437
+ case "punct":
8438
+ if (tok.punct === "(") {
8439
+ const inner = this.parseTernary();
8440
+ this.expectPunct(")");
8441
+ return inner;
8442
+ }
8443
+ throw new ExpressionParseError(`unexpected token '${tok.punct}'`, tok.pos);
8444
+ case "eof": throw new ExpressionParseError("unexpected end of expression", tok.pos);
8445
+ }
8446
+ }
8447
+ parseCall(callee, pos) {
8448
+ if (!EXPRESSION_BUILTIN_NAMES.has(callee)) throw new ExpressionParseError(`unknown function '${callee}'`, pos);
8449
+ this.expectPunct("(");
8450
+ const args = [];
8451
+ if (!this.matchPunct(")")) for (;;) {
8452
+ args.push(this.parseTernary());
8453
+ if (args.length > 16) throw new ExpressionParseError(`too many arguments to '${callee}'`, pos);
8454
+ if (this.matchPunct(",")) continue;
8455
+ this.expectPunct(")");
8456
+ break;
8457
+ }
8458
+ this.callees.add(callee);
8459
+ this.countNode();
8460
+ return {
8461
+ kind: "call",
8462
+ callee,
8463
+ args
8464
+ };
8465
+ }
8466
+ };
8467
+ /** Tokenize + parse `source` into a validated `ParsedExpression`. Throws
8468
+ * `ExpressionParseError` on any lexical or grammatical failure. */
8469
+ function parseExpression(source) {
8470
+ return new Parser(tokenize(source)).parse();
8471
+ }
8472
+ /**
8473
+ * LRU compile cache for parsed expressions (spec §2.4 "parse once … LRU keyed
8474
+ * by expr"). The cache stores BOTH successes and failures (negative caching),
8475
+ * so a corrupt persisted string costs exactly one tokenize+parse total — not
8476
+ * one per read on a hot resolve path.
8477
+ *
8478
+ * The cache is a module-level singleton: entries are pure, content-addressed
8479
+ * ASTs keyed by the raw source string, so sharing one instance across all
8480
+ * callers is safe and maximises hit rate.
8481
+ */
8482
+ var cache = /* @__PURE__ */ new Map();
8483
+ function getCached(source) {
8484
+ const hit = cache.get(source);
8485
+ if (hit !== void 0) {
8486
+ cache.delete(source);
8487
+ cache.set(source, hit);
8488
+ return hit;
8489
+ }
8490
+ let result;
8491
+ try {
8492
+ result = {
8493
+ ok: true,
8494
+ parsed: parseExpression(source)
8495
+ };
8496
+ } catch (err) {
8497
+ result = {
8498
+ ok: false,
8499
+ error: err instanceof ExpressionParseError ? err.message : String(err)
8500
+ };
8501
+ }
8502
+ cache.set(source, result);
8503
+ if (cache.size > 256) {
8504
+ const oldest = cache.keys().next().value;
8505
+ if (oldest !== void 0) cache.delete(oldest);
8506
+ }
8507
+ return result;
8508
+ }
8509
+ /** Compile `source`, returning a discriminated result instead of throwing.
8510
+ * Used by read paths that must degrade rather than raise. LRU/negative-cached. */
8511
+ function compileExpressionSafe(source) {
8512
+ return getCached(source);
8513
+ }
8514
+ Object.freeze({});
8515
+ /**
8516
+ * Author-time validation. Returns `null` when the source is valid, else a
8517
+ * human-readable error message. Checks: the expression compiles; binding count
8518
+ * is within `MAX_EXPRESSION_BINDINGS`; every binding name is a legal identifier,
8519
+ * is not reserved (`now`/keywords) and does not shadow a builtin; and every
8520
+ * FREE identifier of the AST is covered by a binding or the injected `now`.
8521
+ */
8522
+ function validateExpressionSource(src) {
8523
+ const names = Object.keys(src.bindings);
8524
+ if (names.length > 32) return `too many bindings (${names.length} > 32)`;
8525
+ for (const name of names) {
8526
+ if (!EXPRESSION_IDENTIFIER_RE.test(name)) return `invalid binding name '${name}'`;
8527
+ if (RESERVED_BINDING_NAMES.has(name)) return `binding name '${name}' is reserved`;
8528
+ if (EXPRESSION_BUILTIN_NAMES.has(name)) return `binding name '${name}' shadows a builtin function`;
8529
+ }
8530
+ const compiled = compileExpressionSafe(src.expr);
8531
+ if (!compiled.ok) return compiled.error;
8532
+ const bound = new Set(names);
8533
+ for (const id of compiled.parsed.identifiers) {
8534
+ if (id === "now") continue;
8535
+ if (!bound.has(id)) return `expression references unbound identifier '${id}'`;
8536
+ }
8537
+ return null;
8538
+ }
8539
+ var ExpressionBindingSourceSchema = union([
8540
+ object({
8541
+ kind: literal("field").optional(),
8542
+ sourceKey: string(),
8543
+ cap: string(),
8544
+ fieldPath: string()
8545
+ }),
8546
+ object({
8547
+ kind: literal("literal"),
8548
+ value: union([
8549
+ string(),
8550
+ number(),
8551
+ boolean(),
8552
+ _null()
8553
+ ])
8554
+ }),
8555
+ object({
8556
+ kind: literal("global"),
8557
+ sourceStableId: string(),
8558
+ cap: string(),
8559
+ fieldPath: string()
8560
+ })
8561
+ ]);
8562
+ object({
8563
+ expr: string().min(1).max(MAX_EXPRESSION_SOURCE_LENGTH),
8564
+ bindings: record(string().regex(EXPRESSION_IDENTIFIER_RE), ExpressionBindingSourceSchema)
8565
+ }).superRefine((src, ctx) => {
8566
+ const err = validateExpressionSource(src);
8567
+ if (err !== null) ctx.addIssue({
8568
+ code: "custom",
8569
+ message: err,
8570
+ path: ["expr"]
8571
+ });
8572
+ });
8573
+ /** How a leaf compares a device field to a value. Derived from the field's
8574
+ * `kind` in `deviceManager.getWireableFields`, never hand-maintained. */
8575
+ var AutomationConditionOperatorSchema = _enum([
8576
+ "eq",
8577
+ "ne",
8578
+ "gt",
8579
+ "gte",
8580
+ "lt",
8581
+ "lte",
8582
+ "contains",
8583
+ "in"
8584
+ ]);
8585
+ var AutomationConditionLeafSchema = object({
8586
+ kind: literal("condition"),
8587
+ deviceId: number().int().nonnegative(),
8588
+ cap: string().min(1),
8589
+ fieldPath: string().min(1),
8590
+ operator: AutomationConditionOperatorSchema,
8591
+ value: union([
8592
+ string(),
8593
+ number(),
8594
+ boolean(),
8595
+ array(union([string(), number()]))
8596
+ ])
8597
+ });
8598
+ /**
8599
+ * The expression leaf, declared as a plain object rather than an intersection
8600
+ * with {@link ExpressionSourceSchema}: a discriminated union has to be able to
8601
+ * read `kind` off each option, and an intersection hides it. The author-time
8602
+ * validation is the SAME function `ExpressionSourceSchema` runs, so the two
8603
+ * cannot drift — an expression that one accepts, the other accepts.
8604
+ */
8605
+ var AutomationConditionExpressionSchema = object({
8606
+ kind: literal("expression"),
8607
+ expr: string().min(1).max(MAX_EXPRESSION_SOURCE_LENGTH),
8608
+ bindings: record(string().regex(EXPRESSION_IDENTIFIER_RE), ExpressionBindingSourceSchema)
8609
+ }).superRefine((src, ctx) => {
8610
+ const err = validateExpressionSource(src);
8611
+ if (err !== null) ctx.addIssue({
8612
+ code: "custom",
8613
+ message: err,
8614
+ path: ["expr"]
8615
+ });
8616
+ });
8617
+ var AutomationConditionSchema = lazy(() => discriminatedUnion("kind", [
8618
+ object({
8619
+ kind: literal("all"),
8620
+ children: array(AutomationConditionSchema)
8621
+ }),
8622
+ object({
8623
+ kind: literal("any"),
8624
+ children: array(AutomationConditionSchema)
8625
+ }),
8626
+ object({
8627
+ kind: literal("not"),
8628
+ child: AutomationConditionSchema
8629
+ }),
8630
+ AutomationConditionLeafSchema,
8631
+ AutomationConditionExpressionSchema
8632
+ ]));
8633
+ /**
8634
+ * What starts a run.
8635
+ *
8636
+ * D8 compliance, and it is the reason `device-state` is not merely an event
8637
+ * subscription: the trigger evaluates against the **state mirror**, which is
8638
+ * reconciled, and an event only WAKES the evaluation. A dropped event therefore
8639
+ * DELAYS a trigger; it does not lose it. `schedule` uses `croner` — the one
8640
+ * already in the repo — because `setInterval(24h)` drifts and "at 23:30" does
8641
+ * not.
8642
+ */
8643
+ var AutomationTriggerSchema = discriminatedUnion("kind", [
8644
+ object({
8645
+ kind: literal("device-state"),
8646
+ deviceId: number().int().nonnegative(),
8647
+ cap: string().min(1),
8648
+ fieldPath: string().min(1),
8649
+ /** Fire when the field takes this value. Omit to fire on any change. */
8650
+ becomes: union([
8651
+ string(),
8652
+ number(),
8653
+ boolean()
8654
+ ]).optional(),
8655
+ /** Only on a CHANGE of value, not on every re-report. */
8656
+ edge: boolean().optional(),
8657
+ /** The condition must hold this long before the run starts. */
8658
+ forMs: number().int().min(0).max(864e5).optional(),
8659
+ /** Collapse a burst into one run. */
8660
+ debounceMs: number().int().min(0).max(6e5).optional()
8661
+ }),
8662
+ object({
8663
+ kind: literal("device-event"),
8664
+ /** An `EventCategory` value. */
8665
+ category: string().min(1),
8666
+ deviceId: number().int().nonnegative().optional()
8667
+ }),
8668
+ object({
8669
+ kind: literal("schedule"),
8670
+ cron: string().min(1).max(120)
8671
+ }),
8672
+ object({ kind: literal("manual") })
8673
+ ]);
8674
+ /**
8675
+ * One action step.
8676
+ *
8677
+ * `wait` and `cap` are `NcRuleActionSchema`'s two members, kept structurally
8678
+ * identical so `NcRuleActionRunner` runs them unchanged — its device-scope
8679
+ * check, stop-at-first-failure and per-sequence throttle are the whole reason
8680
+ * to reuse it, and none of them are re-implemented here.
8681
+ *
8682
+ * **The one divergence, and it is forced.** `NcRuleActionSchema.cap.deviceId` is
8683
+ * a literal `z.number().int()`, and the NC runner's own `RunSequencesInput`
8684
+ * documents its subject device as *"for the log tag, never for routing"*. So an
8685
+ * NC action can never target the device that triggered it — which is fine for
8686
+ * the NC (its rules already scope to a device) and fatal for an automation
8687
+ * ("sound the siren of the camera that saw the person"). `deviceId` therefore
8688
+ * also accepts `{ $var }`, resolved from the run's `vars` bag BEFORE the runner
8689
+ * is called. The runner still receives a number and is untouched; the
8690
+ * resolution is the recipe's job, not the runner's.
8691
+ */
8692
+ var AutomationActionSchema = discriminatedUnion("kind", [
8693
+ object({
8694
+ kind: literal("wait"),
8695
+ seconds: number().min(0).max(300)
8696
+ }),
8697
+ object({
8698
+ kind: literal("cap"),
8699
+ deviceId: union([number().int(), object({ $var: string().min(1) })]),
8700
+ cap: string().min(1),
8701
+ method: string().min(1),
8702
+ /** Values may carry `{{vars.x}}` slots, which SUBSTITUTE and do not
8703
+ * evaluate (§3.2.3). Anything beyond substitution is the expression leaf. */
8704
+ args: record(string(), unknown()).optional()
8705
+ }),
8706
+ object({
8707
+ kind: literal("code"),
8708
+ /** Compiled into the automation's OWN block by esbuild — not a third
8709
+ * runtime, not a `vm`, and not dynamically evaluated. */
8710
+ code: string().min(1).max(2e4)
8711
+ })
8712
+ ]);
8713
+ object({
8714
+ triggers: array(AutomationTriggerSchema),
8715
+ conditions: AutomationConditionSchema.optional(),
8716
+ actions: array(AutomationActionSchema)
8717
+ });
8718
+ /**
7945
8719
  * `addon-pages` — system-scoped singleton aggregator cap. Public-facing
7946
8720
  * surface that admin-ui consumes through `useAddonPagesListPages()`.
7947
8721
  *
@@ -12053,7 +12827,7 @@ DeviceType.Camera, method(object({
12053
12827
  * Why: pub/sub routing over the system event-bus loses fidelity
12054
12828
  * (callback shape, QoS guarantees, will/retain semantics) and adds
12055
12829
  * refcount bookkeeping that addons would rather own themselves. The
12056
- * canonical consumer (`addon-export-ha-mqtt`) needs raw `mqtt.js`
12830
+ * canonical consumer needs raw `mqtt.js`
12057
12831
  * features anyway — give it the connection config, get out of the way.
12058
12832
  *
12059
12833
  * Consumer flow:
@@ -14621,8 +15395,26 @@ var TrackSchema = object({
14621
15395
  /** Periodic snapshots at snapshotIntervalMs cadence (subject to
14622
15396
  * saveThumbnails policy). */
14623
15397
  snapshots: array(TrackSnapshotSchema).readonly(),
14624
- /** Deduplicated zones the track has entered at least once. */
15398
+ /** Deduplicated zones the track has entered at least once. Zone IDS. */
14625
15399
  zonesVisited: array(string()).readonly(),
15400
+ /**
15401
+ * Human NAMES for {@link zonesVisited}, resolved at READ time against the
15402
+ * `zones` capability.
15403
+ *
15404
+ * `zonesVisited` persists ids (`cfeec78c-8d69-…`), which no operator can type
15405
+ * and no card can render — so every free-text search surface was structurally
15406
+ * unable to answer "show me the tracks in Uscio", and did not fail loudly, it
15407
+ * just returned nothing. Resolving here rather than in each client keeps ONE
15408
+ * derivation and costs the clients no extra call (the `zones` cap is
15409
+ * per-device, so a client-side resolve would be a per-camera fan-out on a
15410
+ * surface built to avoid exactly that).
15411
+ *
15412
+ * Resolved, never invented: a zone deleted since the track was written has no
15413
+ * name and is DROPPED, so this array can be shorter than `zonesVisited` — the
15414
+ * two are not positionally aligned. Absent when the track visited no zone, or
15415
+ * when the zone catalogue could not be read.
15416
+ */
15417
+ zoneNames: array(string()).readonly().optional(),
14626
15418
  /** Deduplicated set of detector classes observed for this track over its
14627
15419
  * life (a track may be reclassified, e.g. person→vehicle). Absent on
14628
15420
  * legacy rows written before class accumulation shipped. */
@@ -16725,6 +17517,23 @@ var CameraRecordingStatusSchema = object({
16725
17517
  active: boolean(),
16726
17518
  storageBytes: number()
16727
17519
  });
17520
+ /** One stage of the fan-out that could NOT be read, and how long it cost. */
17521
+ var CameraStatusDegradationSchema = object({
17522
+ stage: _enum([
17523
+ "source",
17524
+ "broker",
17525
+ "detection",
17526
+ "recording",
17527
+ "switches"
17528
+ ]),
17529
+ reason: _enum([
17530
+ "timeout",
17531
+ "error",
17532
+ "partial"
17533
+ ]),
17534
+ /** Wall-clock ms spent on the stage before it was abandoned. */
17535
+ elapsedMs: number()
17536
+ });
16728
17537
  /**
16729
17538
  * Aggregated per-camera pipeline status — server-composed, single call.
16730
17539
  *
@@ -16755,9 +17564,28 @@ var CameraStatusSchema = object({
16755
17564
  * differently — a quiet camera that looks identical to a dead one is the
16756
17565
  * silence-reads-as-never-happened trap this repo keeps paying for.
16757
17566
  *
16758
- * Empty when nothing is off. Never contains a switch no provider offers.
17567
+ * Empty when nothing is off, and never contains a switch no provider offers
17568
+ * — but an empty list is only a POSITIVE claim when `degraded` does not name
17569
+ * `'switches'`. When it does, the switch set could not be read and nothing
17570
+ * here may be rendered as "the operator turned nothing off": that is the
17571
+ * D62 failure (a camera we could not read painted as broken) in the very
17572
+ * field that exists to prevent it.
16759
17573
  */
16760
17574
  switchedOff: array(CameraSwitchIdSchema).readonly(),
17575
+ /**
17576
+ * Stages of the bounded fan-out that were CUT SHORT — a timeout or a
17577
+ * rejection — and whose block is therefore `null` because we could not
17578
+ * READ it, not because there is nothing there.
17579
+ *
17580
+ * Without this, three different facts arrive as the same `null`: "the stage
17581
+ * timed out", "the stage failed", and "this camera legitimately has no
17582
+ * decoder / no recording". Every surface that draws a conclusion from a null
17583
+ * block (or from an empty `switchedOff`) must consult this first; a stage
17584
+ * named here supports no conclusion at all, only "unknown".
17585
+ *
17586
+ * Empty on a clean read — the overwhelmingly common case.
17587
+ */
17588
+ degraded: array(CameraStatusDegradationSchema).readonly(),
16761
17589
  /** Unix timestamp (ms) when this snapshot was composed server-side. */
16762
17590
  fetchedAt: number()
16763
17591
  });
@@ -17275,6 +18103,37 @@ DeviceType.Camera, method(object({
17275
18103
  lastCapturedAt: number().nullable(),
17276
18104
  cacheAgeMs: number().nullable(),
17277
18105
  etag: string().nullable()
18106
+ }))), systemMethod(object({
18107
+ /** The tiles a surface is actually rendering. One entry per (device,
18108
+ * width) the caller will paint — the width is snapped to the server's
18109
+ * ladder and becomes part of the link's SIGNED identity. */
18110
+ targets: array(object({
18111
+ deviceId: number(),
18112
+ /** Target width in px. Omit for the frame as captured — correct
18113
+ * for a full-bleed surface, wrong (and expensive) for a grid. */
18114
+ width: number().int().positive().optional()
18115
+ })).min(1).max(200) }), array(object({
18116
+ deviceId: number(),
18117
+ /** Root-relative signed path, or null when the link plane is not
18118
+ * served (no data-plane facility). Present even for a device that has
18119
+ * never captured — the request is what triggers the first one (D94). */
18120
+ url: string().nullable(),
18121
+ /** Epoch ms of the frame this link serves. Null = never captured.
18122
+ * THE honest age: the tRPC path carried none before this. */
18123
+ capturedAt: number().nullable(),
18124
+ /** Age of that frame at the moment the answer was built. */
18125
+ ageMs: number().nullable(),
18126
+ /** Epoch ms after which `url` stops verifying. */
18127
+ expiresAt: number().nullable(),
18128
+ /** Ladder rung the bytes are at; null = the frame as captured. */
18129
+ width: number().nullable(),
18130
+ /** The device has never produced a frame. An empty state, not a
18131
+ * failure — and never a reason to withhold the link (D94). */
18132
+ neverCaptured: boolean(),
18133
+ /** A sleeping battery camera: the frame is deliberately stale and will
18134
+ * NOT refresh in the background. A surface should say so rather than
18135
+ * present it as current. */
18136
+ sleeping: boolean()
17278
18137
  })));
17279
18138
  /**
17280
18139
  * `sso-bridge` — internal hub-only cap that lets SSO-style auth
@@ -19939,7 +20798,29 @@ var FaceInfoSchema = object({
19939
20798
  recognizedIdentityId: string().optional(),
19940
20799
  identityName: string().optional(),
19941
20800
  assigned: boolean(),
20801
+ /**
20802
+ * The crop, inline, base64.
20803
+ *
20804
+ * **Prefer {@link cropUrl}.** At the 500 rows the Faces view asks for this
20805
+ * field alone is ~2.87 MiB, re-sent in full on every operator assign and
20806
+ * every 30 s poll, base64-inflated over the msgpack socket and held in the
20807
+ * query heap. It stays for callers that have not migrated; `includeCrops:
20808
+ * false` turns it off once they have.
20809
+ */
19942
20810
  base64: string().optional(),
20811
+ /**
20812
+ * Same crop, as a data-plane URL for `<img src>` — the move the admin
20813
+ * snapshot surfaces made on 2026-08-08.
20814
+ *
20815
+ * Served by the `event-media` plane, which resolves a raw MediaStore key and
20816
+ * is `access: 'authenticated'`: a bare `<img>` carries the `camstack_session`
20817
+ * cookie, so no header plumbing is needed. The bytes then ride the browser's
20818
+ * HTTP cache with an ETag and `immutable`, instead of the WebSocket.
20819
+ *
20820
+ * Absent when the face has no stored crop, or when the addon has no data
20821
+ * plane — callers fall back to {@link base64}.
20822
+ */
20823
+ cropUrl: string().optional(),
19943
20824
  /** Design B: the face bbox (pixel space) on the key frame — lets a detail
19944
20825
  * view draw the box over the native `keyFrameMediaKey` frame. Absent on
19945
20826
  * legacy rows written before design B. */
@@ -20004,7 +20885,23 @@ method(_void(), array(IdentitySchema).readonly()), method(object({ name: string(
20004
20885
  auth: "admin"
20005
20886
  }), method(object({
20006
20887
  limit: number().int().positive().optional(),
20007
- filter: FaceFilterEnum.optional()
20888
+ filter: FaceFilterEnum.optional(),
20889
+ /**
20890
+ * Inline the base64 crop on every row. Default `true` — the existing
20891
+ * behaviour, kept so no caller breaks.
20892
+ *
20893
+ * Set `false` once the caller renders {@link FaceInfo.cropUrl}: that
20894
+ * drops ~2.87 MiB per 500-row page to a few KiB of metadata and lets
20895
+ * the browser cache the images.
20896
+ *
20897
+ * **This is an INPUT field, so it does not reach the addon until the
20898
+ * next train.** The hub router validates cap inputs against its own
20899
+ * compiled Zod, which strips a key it does not know — verified today
20900
+ * on the OUTPUT side, where an additive field DOES arrive immediately
20901
+ * (`Track.hasFace`). Until the train ships, sending `false` is
20902
+ * harmless and simply keeps the crops inline.
20903
+ */
20904
+ includeCrops: boolean().optional()
20008
20905
  }).optional(), array(FaceInfoSchema).readonly()), method(object({
20009
20906
  deviceId: number().int(),
20010
20907
  trackId: string()
@@ -25732,987 +26629,358 @@ var BaseDevice = class {
25732
26629
  * to reshape before `config.setAll`.
25733
26630
  */
25734
26631
  async applySettingsPatch(patch) {
25735
- await this.config.setAll(patch);
25736
- }
25737
- /**
25738
- * Phase 3 — populate device-scoped state needed by downstream phases
25739
- * (accessory reconciliation, public `features` array, optional cap
25740
- * registration). Called ONCE per construction, after register but
25741
- * before `getAccessoryChildren()`.
25742
- *
25743
- * Drivers write the `feature-probe` runtime-state slice via
25744
- * `this.runtimeState.setCapState('feature-probe', {...})` — flag bag
25745
- * is open (Reolink writes `hasPtz/hasIntercom`, Hikvision writes
25746
- * `hasSupplementalLight/hasAlarmIo`, etc).
25747
- *
25748
- * Default: nothing to probe → mark the device PROBED (set `lastProbedAt`) so
25749
- * the kernel treats it as ready immediately. A device that derives its shape
25750
- * from a spec (a container, or an accessory sensor) rather than from a
25751
- * hardware probe has no probe to "complete"; without stamping `lastProbedAt`
25752
- * it would look perpetually un-probed — logging "Initial probe did not
25753
- * complete" on every boot and spinning a pointless retry chain. Drivers that
25754
- * DO probe override this and write their own `feature-probe` slice (including
25755
- * `lastProbedAt`) once their probe actually succeeds.
25756
- */
25757
- async onProbe() {
25758
- const base = this.runtimeState.getCapState("feature-probe") ?? {
25759
- flags: {},
25760
- deviceType: null,
25761
- model: null,
25762
- channelCount: null,
25763
- lastProbedAt: 0,
25764
- lastFetchedAt: 0
25765
- };
25766
- this.runtimeState.setCapState("feature-probe", {
25767
- ...base,
25768
- lastProbedAt: Date.now()
25769
- });
25770
- }
25771
- /**
25772
- * Phase 5 — fired after the device + its accessories are registered.
25773
- * Drivers publish streams to the broker, kick off background tasks,
25774
- * or subscribe to lib events that need a fully-registered device id.
25775
- *
25776
- * Default: no-op.
25777
- *
25778
- * RENAMED FROM `onCreated` (which still exists for back-compat in this
25779
- * pass). The new name reflects the post-probe, post-accessory contract.
25780
- */
25781
- async onActivate() {}
25782
- /**
25783
- * Re-run the probe + reconcile accessories + refresh features meta.
25784
- * Drivers call this when device-side state changes (battery cam wakes,
25785
- * firmware update, manual operator trigger).
25786
- *
25787
- * The kernel injects `_kernelReprobe` on registration so this method
25788
- * delegates to the same orchestrator that runs the boot-time phase
25789
- * 3 + 4 sequence. Drivers should NOT override this — they override
25790
- * `onProbe()` instead.
25791
- */
25792
- async reprobe() {
25793
- if (this._kernelReprobe) await this._kernelReprobe();
25794
- else await this.onProbe();
25795
- }
25796
- /**
25797
- * Kernel-injected callback that runs the full post-probe orchestration
25798
- * (onProbe → registerDevice meta refresh → accessory reconciliation).
25799
- * Set by `device-cap-proxy.register()`. Drivers should not touch this
25800
- * directly — call `reprobe()` instead.
25801
- */
25802
- _kernelReprobe;
25803
- /**
25804
- * Declare accessory child devices the kernel should auto-spawn
25805
- * after `onProbe()` resolves. Each spec fully describes one child
25806
- * — stableId suffix (deterministic per kind for restore-safety),
25807
- * meta (type / name / location), config (initial blob the child
25808
- * self-hydrates), and a factory that constructs the concrete
25809
- * class with whatever closure-captured refs it needs (typically
25810
- * `this` for the parent reference).
25811
- *
25812
- * The kernel handles the rest: allocateDeviceId, persistInitialConfig
25813
- * (skipped on restore when the row already exists),
25814
- * persistInitialMeta, createContext, factory invocation, register,
25815
- * and recursive lifecycle (probe + accessories + activate).
25816
- *
25817
- * Implementations should derive children from
25818
- * `this.runtimeState.getCapState('feature-probe')` (post-probe truth).
25819
- * Drivers can use the `getProbeFlags()` helper to read the flag bag
25820
- * with a typed cast.
25821
- *
25822
- * Default: no children.
25823
- */
25824
- getAccessoryChildren() {
25825
- return [];
25826
- }
25827
- /**
25828
- * Read the current feature-probe flag bag with a typed cast. Helper
25829
- * for `getAccessoryChildren()` and `features` getters that derive
25830
- * outputs from the probe results.
25831
- */
25832
- getProbeFlags() {
25833
- return this.runtimeState.getCapState("feature-probe")?.flags ?? {};
25834
- }
25835
- /**
25836
- * Returns true once `onProbe` has completed at least once
25837
- * (`lastProbedAt > 0`). Drivers gate `getAccessoryChildren()` on this
25838
- * to avoid spawning stale accessories on a fresh device whose probe
25839
- * hasn't landed yet.
25840
- */
25841
- hasProbed() {
25842
- return (this.runtimeState.getCapState("feature-probe")?.lastProbedAt ?? 0) > 0;
25843
- }
25844
- };
25845
- /**
25846
- * Convert an IDevice to the flat DeviceSummary shape expected by the
25847
- * device-provider cap router. Shared across all providers.
25848
- */
25849
- function toDeviceSummary(device, addonId) {
25850
- const config = {};
25851
- for (const entry of device.config.entries()) config[entry.key] = entry.value;
25852
- return {
25853
- id: device.id,
25854
- stableId: device.stableId,
25855
- addonId,
25856
- type: String(device.type),
25857
- name: device.name,
25858
- parentDeviceId: device.parentDeviceId,
25859
- online: device.online,
25860
- features: [...device.features],
25861
- config,
25862
- sourceInfo: device.sourceInfo
25863
- };
25864
- }
25865
- /**
25866
- * Base class for device-provider addons (rtsp, onvif, frigate).
25867
- *
25868
- * Provides default implementations for the common device-provider cap
25869
- * methods (`start`, `stop`, `getStatus`, `getDevices`, `supportsDiscovery`,
25870
- * `supportsManualCreation`, `toDeviceSummary`). Subclasses override the
25871
- * methods that differ per provider.
25872
- *
25873
- * @example
25874
- * ```ts
25875
- * class RtspProvider extends BaseDeviceProvider {
25876
- * protected readonly addonId = 'provider-rtsp'
25877
- * protected readonly providerName = 'RTSP'
25878
- *
25879
- * protected async onCreateDevice(input) { ... }
25880
- * protected async onGetCreationSchema(type) { ... }
25881
- * protected async onRestoreDevices(saved) { ... }
25882
- * }
25883
- * ```
25884
- */
25885
- var BaseDeviceProvider = class extends BaseAddon {
25886
- async onInitialize() {
25887
- this.ctx.logger.info(`${this.providerName} Provider initialized`);
25888
- return [{
25889
- capability: deviceProviderCapability,
25890
- provider: this
25891
- }];
25892
- }
25893
- async onShutdown() {
25894
- const devices = await this.ctx.kernel.devices?.getAll() ?? [];
25895
- for (const device of devices) try {
25896
- await this.ctx.kernel.devices?.decommission(device.id);
25897
- } catch (err) {
25898
- this.ctx.logger.warn(`${this.providerName}: decommission failed`, {
25899
- tags: {
25900
- deviceId: device.id,
25901
- stableId: device.stableId
25902
- },
25903
- meta: { error: err instanceof Error ? err.message : String(err) }
25904
- });
25905
- }
25906
- this.ctx.logger.info(`${this.providerName} Provider shut down`, { meta: { decommissionedCount: devices.length } });
25907
- }
25908
- async start() {}
25909
- async stop() {}
25910
- async getStatus() {
25911
- return {
25912
- connected: true,
25913
- deviceCount: (await this.ctx.kernel.devices?.getAll() ?? []).length
25914
- };
25915
- }
25916
- async getDevices() {
25917
- return (await this.ctx.kernel.devices?.getAll() ?? []).map((d) => ({
25918
- id: d.stableId,
25919
- name: d.name,
25920
- type: String(d.type)
25921
- }));
25922
- }
25923
- async supportsDiscovery() {
25924
- return false;
25925
- }
25926
- async discoverDevices(_input) {
25927
- return [];
25928
- }
25929
- /** Extra per-scan input form (e.g. a broadcast address for another subnet).
25930
- * Null = no extra params. Override in providers that support scoped scans. */
25931
- async getDiscoveryParamsSchema() {
25932
- return null;
25933
- }
25934
- /**
25935
- * The DeviceType this provider creates via manual add — derived from the
25936
- * `deviceClasses` map (first registered type). `null` when manual creation is
25937
- * unsupported. Lets the Add-Device dialog pick the right type per provider.
25938
- */
25939
- async getManualCreationType() {
25940
- if (!await this.supportsManualCreation()) return { deviceType: null };
25941
- return { deviceType: Object.values(DeviceType).find((t) => this.deviceClasses[t] !== void 0) ?? null };
25942
- }
25943
- async adoptDiscoveredDevice(_input) {
25944
- throw new Error(`${this.providerName} provider does not support discovery-based adoption`);
25945
- }
25946
- async supportsManualCreation() {
25947
- return true;
25948
- }
25949
- async getChildCreationSchema(input) {
25950
- return this.onGetCreationSchema(input.type);
25951
- }
25952
- /**
25953
- * Default kernel-orchestrated `createDevice` implementation. The
25954
- * subclass's `onCreateDevice` returns a declarative
25955
- * `CreateDeviceSpec` (`{meta, config}`) — this method handles
25956
- * stableId generation, class lookup, kernel.devices.create
25957
- * dispatch, and DeviceSummary mapping. Subclasses should NOT
25958
- * override this method; override `onCreateDevice` and
25959
- * `deviceClasses` instead.
25960
- */
25961
- async createDevice(input) {
25962
- const spec = await this.onCreateDevice(input.type, input.config);
25963
- const Class = this.deviceClasses[spec.meta.type];
25964
- if (!Class) throw new Error(`${this.providerName} provider: no device class registered for type "${spec.meta.type}" — add it to the deviceClasses map`);
25965
- const stableId = this.generateStableId(spec.meta.type, spec.config);
25966
- const device = await this.ctx.kernel.devices.create(stableId, Class, spec.config, null, spec.meta);
25967
- if (spec.onAfterCreate) try {
25968
- await spec.onAfterCreate(device);
25969
- } catch (err) {
25970
- this.ctx.logger.warn("createDevice: onAfterCreate hook threw — device is already registered", {
25971
- tags: {
25972
- deviceId: device.id,
25973
- stableId
25974
- },
25975
- meta: { error: err instanceof Error ? err.message : String(err) }
25976
- });
25977
- }
25978
- return this.toSummary(device);
26632
+ await this.config.setAll(patch);
25979
26633
  }
25980
26634
  /**
25981
- * Generate a stableId for a newly-created device. Default uses the
25982
- * `${addonId}-${Date.now()}` pattern as a unique-but-opaque
25983
- * fallback; any provider that has access to durable hardware
25984
- * identity (UID, MAC, serial) should override and derive from it
25985
- * so re-adding the same physical device reuses its persisted row.
26635
+ * Phase 3 — populate device-scoped state needed by downstream phases
26636
+ * (accessory reconciliation, public `features` array, optional cap
26637
+ * registration). Called ONCE per construction, after register but
26638
+ * before `getAccessoryChildren()`.
25986
26639
  *
25987
- * `config` is the parsed CreateDeviceSpec.config the subclass
25988
- * returned from `onCreateDevice` — the override has access to
25989
- * every operator-supplied + autodetect-resolved field. Optional
25990
- * for back-compat: existing overrides that take only `type`
25991
- * keep working unchanged.
26640
+ * Drivers write the `feature-probe` runtime-state slice via
26641
+ * `this.runtimeState.setCapState('feature-probe', {...})` — flag bag
26642
+ * is open (Reolink writes `hasPtz/hasIntercom`, Hikvision writes
26643
+ * `hasSupplementalLight/hasAlarmIo`, etc).
26644
+ *
26645
+ * Default: nothing to probe → mark the device PROBED (set `lastProbedAt`) so
26646
+ * the kernel treats it as ready immediately. A device that derives its shape
26647
+ * from a spec (a container, or an accessory sensor) rather than from a
26648
+ * hardware probe has no probe to "complete"; without stamping `lastProbedAt`
26649
+ * it would look perpetually un-probed — logging "Initial probe did not
26650
+ * complete" on every boot and spinning a pointless retry chain. Drivers that
26651
+ * DO probe override this and write their own `feature-probe` slice (including
26652
+ * `lastProbedAt`) once their probe actually succeeds.
25992
26653
  */
25993
- generateStableId(_type, _config) {
25994
- return `${this.addonId}-${Date.now()}`;
25995
- }
25996
- async testCreationField(_input) {
25997
- return {
25998
- status: "ok",
25999
- labels: ["probe not implemented"]
26654
+ async onProbe() {
26655
+ const base = this.runtimeState.getCapState("feature-probe") ?? {
26656
+ flags: {},
26657
+ deviceType: null,
26658
+ model: null,
26659
+ channelCount: null,
26660
+ lastProbedAt: 0,
26661
+ lastFetchedAt: 0
26000
26662
  };
26001
- }
26002
- async restoreDevices(savedDevices) {
26003
- await this.onRestoreDevices(savedDevices);
26004
- if (savedDevices.length > 0) this.ctx.logger.info(`Restored ${savedDevices.length} ${this.providerName} device(s)`);
26663
+ this.runtimeState.setCapState("feature-probe", {
26664
+ ...base,
26665
+ lastProbedAt: Date.now()
26666
+ });
26005
26667
  }
26006
26668
  /**
26007
- * Restore devices from persisted state. Two-pass:
26669
+ * Phase 5 — fired after the device + its accessories are registered.
26670
+ * Drivers publish streams to the broker, kick off background tasks,
26671
+ * or subscribe to lib events that need a fully-registered device id.
26008
26672
  *
26009
- * 1. **Top-level pass** — invokes `kernel.devices.create()` for every
26010
- * `parentDeviceId === null` row using the `deviceClasses` map.
26011
- * The kernel's register flow handles `getAccessoryChildren()` for
26012
- * each parent (siren / floodlight / PIR / etc).
26673
+ * Default: no-op.
26013
26674
  *
26014
- * 2. **Hub-adopted children pass** — for rows with
26015
- * `parentDeviceId !== null` whose `type` IS in `deviceClasses`
26016
- * (e.g. Reolink hub-adopted cameras under an NVR), spawn them
26017
- * explicitly with the persisted `parentDeviceId`. These are
26018
- * NOT accessory children — they're first-class adopted devices
26019
- * that just happen to have a parent. Without this pass, every
26020
- * server restart would lose hub-adopted cameras (their type is
26021
- * in `deviceClasses` but parent's `getAccessoryChildren` doesn't
26022
- * spawn them — that callback is only for purpose-built
26023
- * accessory roles).
26675
+ * RENAMED FROM `onCreated` (which still exists for back-compat in this
26676
+ * pass). The new name reflects the post-probe, post-accessory contract.
26677
+ */
26678
+ async onActivate() {}
26679
+ /**
26680
+ * Re-run the probe + reconcile accessories + refresh features meta.
26681
+ * Drivers call this when device-side state changes (battery cam wakes,
26682
+ * firmware update, manual operator trigger).
26024
26683
  *
26025
- * Rows whose `type` is NOT in `deviceClasses` are skipped — those
26026
- * are accessory children (siren/light/sensor) that the kernel's
26027
- * accessory-spawn flow handles via the parent's
26028
- * `getAccessoryChildren()`. Override only when the default doesn't
26029
- * fit.
26684
+ * The kernel injects `_kernelReprobe` on registration so this method
26685
+ * delegates to the same orchestrator that runs the boot-time phase
26686
+ * 3 + 4 sequence. Drivers should NOT override this — they override
26687
+ * `onProbe()` instead.
26030
26688
  */
26031
- async onRestoreDevices(savedDevices) {
26032
- const restored = /* @__PURE__ */ new Set();
26033
- for (const saved of savedDevices) {
26034
- if (saved.parentDeviceId !== null) continue;
26035
- const Class = this.deviceClasses[saved.type];
26036
- if (!Class) {
26037
- this.ctx.logger.warn("No device class registered for restored type — skipping", {
26038
- tags: { stableId: saved.stableId },
26039
- meta: { type: saved.type }
26040
- });
26041
- continue;
26042
- }
26043
- try {
26044
- await this.ctx.kernel.devices.create(saved.stableId, Class, {});
26045
- restored.add(saved.id);
26046
- } catch (err) {
26047
- this.ctx.logger.warn("Failed to restore device", {
26048
- tags: { stableId: saved.stableId },
26049
- meta: {
26050
- type: saved.type,
26051
- error: err instanceof Error ? err.message : String(err)
26052
- }
26053
- });
26054
- }
26055
- }
26056
- const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
26057
- for (const saved of childRows) {
26058
- const Class = this.deviceClasses[saved.type];
26059
- if (!Class) continue;
26060
- if (saved.parentDeviceId === null) continue;
26061
- if (!restored.has(saved.parentDeviceId)) continue;
26062
- try {
26063
- await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
26064
- restored.add(saved.id);
26065
- } catch (err) {
26066
- this.ctx.logger.warn("Failed to restore hub-adopted child", {
26067
- tags: {
26068
- stableId: saved.stableId,
26069
- parentDeviceId: saved.parentDeviceId
26070
- },
26071
- meta: {
26072
- type: saved.type,
26073
- error: err instanceof Error ? err.message : String(err)
26074
- }
26075
- });
26076
- }
26077
- }
26078
- }
26079
- /** Convert an IDevice to the flat DeviceSummary for the cap router. */
26080
- toSummary(device) {
26081
- return toDeviceSummary(device, this.addonId);
26082
- }
26083
- };
26084
- DeviceType.Cover, DeviceType.Valve, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.Camera, DeviceType.Hub, DeviceType.Switch, DeviceType.Siren, DeviceType.Light, DeviceType.Fan, DeviceType.Sensor, DeviceType.Thermostat, DeviceType.Climate, DeviceType.Button, DeviceType.EventEmitter, DeviceType.Update, DeviceType.Generic, DeviceType.Notifier, DeviceType.Script, DeviceType.Automation, DeviceType.Lock, DeviceType.MediaPlayer, DeviceType.AlarmPanel, DeviceType.Control, DeviceType.Presence, DeviceType.Weather, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.Container, DeviceType.Image, DeviceType.PetFeeder;
26085
- new Set(Object.values(DeviceType));
26086
- DeviceFeature.BatteryOperated;
26087
- /**
26088
- * Error types for the safe expression engine. Two distinct classes so callers
26089
- * can tell a compile-time (grammar) failure from a runtime (evaluation)
26090
- * failure — both are non-fatal to the host: read paths degrade to "skip link".
26091
- */
26092
- /** Thrown by the tokenizer / parser. Carries a 0-based source `position` when
26093
- * the failure is anchored to a character (author-facing inline feedback). */
26094
- var ExpressionParseError = class extends Error {
26095
- position;
26096
- constructor(message, position) {
26097
- super(message);
26098
- this.name = "ExpressionParseError";
26099
- this.position = position;
26100
- }
26101
- };
26102
- /** Thrown by the evaluator (unknown identifier, type mismatch, non-finite
26103
- * result, unknown builtin, step-budget exceeded). */
26104
- var ExpressionEvalError = class extends Error {
26105
- constructor(message) {
26106
- super(message);
26107
- this.name = "ExpressionEvalError";
26689
+ async reprobe() {
26690
+ if (this._kernelReprobe) await this._kernelReprobe();
26691
+ else await this.onProbe();
26108
26692
  }
26109
- };
26110
- /**
26111
- * Frozen, null-prototype builtin function table for the expression engine
26112
- * (spec §4 rule 4). The table is the SOLE surface of callable functions: the
26113
- * parser rejects any callee not in it, and the evaluator gates each call on an
26114
- * own-property check against it.
26115
- *
26116
- * Because the object has a NULL prototype AND is `Object.freeze`d:
26117
- * - it cannot be polluted (no `__proto__` / `constructor` write reaches it);
26118
- * - a lookup for `toString` / `hasOwnProperty` / `constructor` finds NOTHING
26119
- * (there is no `Object.prototype` in the chain), so those names are not
26120
- * callable — they are simply "unknown function" at parse time.
26121
- *
26122
- * Every numeric argument is validated as a finite number and every numeric
26123
- * RESULT is re-checked finite, so `/0`, `sqrt(-1)` (→ NaN) and overflow
26124
- * (`pow(10,400)` → Infinity) all raise `ExpressionEvalError` and fail the link
26125
- * closed rather than emitting a garbage value.
26126
- */
26127
- function asFiniteNumber(value, name, index) {
26128
- if (typeof value !== "number" || !Number.isFinite(value)) throw new ExpressionEvalError(`${name}: argument ${index + 1} must be a finite number`);
26129
- return value;
26130
- }
26131
- function asString$1(value, name, index) {
26132
- if (typeof value !== "string") throw new ExpressionEvalError(`${name}: argument ${index + 1} must be a string`);
26133
- return value;
26134
- }
26135
- function finiteResult(value, name) {
26136
- if (!Number.isFinite(value)) throw new ExpressionEvalError(`${name}: produced a non-finite result`);
26137
- return value;
26138
- }
26139
- function allFiniteNumbers(args, name) {
26140
- return args.map((a, idx) => asFiniteNumber(a, name, idx));
26141
- }
26142
- var INF = Number.POSITIVE_INFINITY;
26143
- var table = {
26144
- min: {
26145
- minArgs: 1,
26146
- maxArgs: INF,
26147
- apply: (args) => finiteResult(Math.min(...allFiniteNumbers(args, "min")), "min")
26148
- },
26149
- max: {
26150
- minArgs: 1,
26151
- maxArgs: INF,
26152
- apply: (args) => finiteResult(Math.max(...allFiniteNumbers(args, "max")), "max")
26153
- },
26154
- abs: {
26155
- minArgs: 1,
26156
- maxArgs: 1,
26157
- apply: (args) => finiteResult(Math.abs(asFiniteNumber(args[0], "abs", 0)), "abs")
26158
- },
26159
- floor: {
26160
- minArgs: 1,
26161
- maxArgs: 1,
26162
- apply: (args) => finiteResult(Math.floor(asFiniteNumber(args[0], "floor", 0)), "floor")
26163
- },
26164
- ceil: {
26165
- minArgs: 1,
26166
- maxArgs: 1,
26167
- apply: (args) => finiteResult(Math.ceil(asFiniteNumber(args[0], "ceil", 0)), "ceil")
26168
- },
26169
- sqrt: {
26170
- minArgs: 1,
26171
- maxArgs: 1,
26172
- apply: (args) => finiteResult(Math.sqrt(asFiniteNumber(args[0], "sqrt", 0)), "sqrt")
26173
- },
26174
- round: {
26175
- minArgs: 1,
26176
- maxArgs: 2,
26177
- apply: (args) => {
26178
- const x = asFiniteNumber(args[0], "round", 0);
26179
- const digits = args.length > 1 ? Math.trunc(asFiniteNumber(args[1], "round", 1)) : 0;
26180
- if (digits < 0 || digits > 100) throw new ExpressionEvalError("round: digits must be between 0 and 100");
26181
- const factor = 10 ** digits;
26182
- return finiteResult(Math.round(x * factor) / factor, "round");
26183
- }
26184
- },
26185
- pow: {
26186
- minArgs: 2,
26187
- maxArgs: 2,
26188
- apply: (args) => finiteResult(asFiniteNumber(args[0], "pow", 0) ** asFiniteNumber(args[1], "pow", 1), "pow")
26189
- },
26190
- clamp: {
26191
- minArgs: 3,
26192
- maxArgs: 3,
26193
- apply: (args) => {
26194
- const x = asFiniteNumber(args[0], "clamp", 0);
26195
- const lo = asFiniteNumber(args[1], "clamp", 1);
26196
- const hi = asFiniteNumber(args[2], "clamp", 2);
26197
- if (lo > hi) throw new ExpressionEvalError("clamp: lower bound is greater than upper bound");
26198
- return finiteResult(Math.min(hi, Math.max(lo, x)), "clamp");
26199
- }
26200
- },
26201
- avg: {
26202
- minArgs: 1,
26203
- maxArgs: INF,
26204
- apply: (args) => {
26205
- const nums = allFiniteNumbers(args, "avg");
26206
- return finiteResult(nums.reduce((acc, v) => acc + v, 0) / nums.length, "avg");
26207
- }
26208
- },
26209
- sum: {
26210
- minArgs: 1,
26211
- maxArgs: INF,
26212
- apply: (args) => finiteResult(allFiniteNumbers(args, "sum").reduce((acc, v) => acc + v, 0), "sum")
26213
- },
26214
- coalesce: {
26215
- minArgs: 1,
26216
- maxArgs: INF,
26217
- apply: (args) => {
26218
- for (const a of args) if (a !== null) return a;
26219
- return null;
26220
- }
26221
- },
26222
- age: {
26223
- minArgs: 2,
26224
- maxArgs: 2,
26225
- apply: (args) => finiteResult(asFiniteNumber(args[0], "age", 0) - asFiniteNumber(args[1], "age", 1), "age")
26226
- },
26227
- convert: {
26228
- minArgs: 3,
26229
- maxArgs: 3,
26230
- apply: (args, hooks) => {
26231
- const x = asFiniteNumber(args[0], "convert", 0);
26232
- const from = asString$1(args[1], "convert", 1).trim();
26233
- const to = asString$1(args[2], "convert", 2).trim();
26234
- if (hooks.convert) {
26235
- const out = hooks.convert(x, from, to);
26236
- if (out === null) throw new ExpressionEvalError(`convert: cannot convert '${from}' to '${to}'`);
26237
- return finiteResult(out, "convert");
26238
- }
26239
- if (from === to) return x;
26240
- throw new ExpressionEvalError("convert: unit conversion table not installed");
26241
- }
26693
+ /**
26694
+ * Kernel-injected callback that runs the full post-probe orchestration
26695
+ * (onProbe → registerDevice meta refresh → accessory reconciliation).
26696
+ * Set by `device-cap-proxy.register()`. Drivers should not touch this
26697
+ * directly — call `reprobe()` instead.
26698
+ */
26699
+ _kernelReprobe;
26700
+ /**
26701
+ * Declare accessory child devices the kernel should auto-spawn
26702
+ * after `onProbe()` resolves. Each spec fully describes one child
26703
+ * — stableId suffix (deterministic per kind for restore-safety),
26704
+ * meta (type / name / location), config (initial blob the child
26705
+ * self-hydrates), and a factory that constructs the concrete
26706
+ * class with whatever closure-captured refs it needs (typically
26707
+ * `this` for the parent reference).
26708
+ *
26709
+ * The kernel handles the rest: allocateDeviceId, persistInitialConfig
26710
+ * (skipped on restore when the row already exists),
26711
+ * persistInitialMeta, createContext, factory invocation, register,
26712
+ * and recursive lifecycle (probe + accessories + activate).
26713
+ *
26714
+ * Implementations should derive children from
26715
+ * `this.runtimeState.getCapState('feature-probe')` (post-probe truth).
26716
+ * Drivers can use the `getProbeFlags()` helper to read the flag bag
26717
+ * with a typed cast.
26718
+ *
26719
+ * Default: no children.
26720
+ */
26721
+ getAccessoryChildren() {
26722
+ return [];
26242
26723
  }
26243
- };
26244
- Object.freeze(Object.assign(Object.create(null), table));
26245
- /** The set of valid builtin names — used by the parser to reject unknown
26246
- * callees at parse time (immediate author feedback). */
26247
- var EXPRESSION_BUILTIN_NAMES = new Set(Object.keys(table));
26248
- /**
26249
- * Resource-bound constants for the safe expression engine.
26250
- *
26251
- * Every bound is defense-in-depth: the grammar is non-Turing-complete (no
26252
- * loops, recursion, lambdas or member access — see `ast.ts`), so evaluation is
26253
- * O(nodeCount) by construction. These caps merely put a hard ceiling on the
26254
- * work a single author-supplied expression can request, so a hostile or
26255
- * accidental pathological string can never spend unbounded CPU/memory.
26256
- */
26257
- /** Max source length (chars) — checked BEFORE tokenizing so a huge string is
26258
- * rejected without allocation. */
26259
- var MAX_EXPRESSION_SOURCE_LENGTH = 2048;
26260
- /** A legal binding / identifier name. */
26261
- var EXPRESSION_IDENTIFIER_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
26262
- /** Binding names an author may NOT use: `now` is auto-injected; the literal
26263
- * keywords lex as values, not identifiers, so binding to them is meaningless. */
26264
- var RESERVED_BINDING_NAMES = new Set([
26265
- "now",
26266
- "true",
26267
- "false",
26268
- "null"
26269
- ]);
26270
- /**
26271
- * Tokenizer for the safe expression mini-language. Hand-rolled, single-pass,
26272
- * zero-dependency. The grammar is deliberately boring: decimal numbers,
26273
- * single/double-quoted strings with a tiny escape set, identifiers, the three
26274
- * value keywords (`true`/`false`/`null`) and a fixed punctuator set. Anything
26275
- * outside that — a bare `.`, `=`, `[`, `]`, `{`, `}`, `;`, backtick, `&`, `|` —
26276
- * is a parse error with a source position, so member access / assignment /
26277
- * template literals are lexically impossible.
26278
- */
26279
- var KEYWORDS = new Set([
26280
- "true",
26281
- "false",
26282
- "null"
26283
- ]);
26284
- function isDigit(ch) {
26285
- return ch >= "0" && ch <= "9";
26286
- }
26287
- function isIdentStart(ch) {
26288
- return ch >= "A" && ch <= "Z" || ch >= "a" && ch <= "z" || ch === "_";
26289
- }
26290
- function isIdentPart(ch) {
26291
- return isIdentStart(ch) || isDigit(ch);
26292
- }
26293
- function isWhitespace(ch) {
26294
- return ch === " " || ch === " " || ch === "\n" || ch === "\r" || ch === "\f" || ch === "\v";
26295
- }
26296
- /** Tokenize `source` into a flat token list ending with a single `eof` token.
26297
- * Throws `ExpressionParseError` on any illegal character or unterminated
26298
- * string. */
26299
- function tokenize(source) {
26300
- if (source.length > 2048) throw new ExpressionParseError(`expression too long (${source.length} > ${MAX_EXPRESSION_SOURCE_LENGTH} chars)`, 0);
26301
- const tokens = [];
26302
- let i = 0;
26303
- const n = source.length;
26304
- while (i < n) {
26305
- const ch = source[i];
26306
- if (isWhitespace(ch)) {
26307
- i += 1;
26308
- continue;
26309
- }
26310
- if (isDigit(ch)) {
26311
- const start = i;
26312
- while (i < n && isDigit(source[i])) i += 1;
26313
- if (i < n && source[i] === ".") {
26314
- if (i + 1 >= n || !isDigit(source[i + 1])) throw new ExpressionParseError("malformed number: decimal point needs a digit", i);
26315
- i += 1;
26316
- while (i < n && isDigit(source[i])) i += 1;
26317
- }
26318
- const text = source.slice(start, i);
26319
- const value = Number(text);
26320
- if (!Number.isFinite(value)) throw new ExpressionParseError(`malformed number: '${text}'`, start);
26321
- tokens.push({
26322
- type: "number",
26323
- value,
26324
- pos: start
26325
- });
26326
- continue;
26327
- }
26328
- if (ch === "'" || ch === "\"") {
26329
- const quote = ch;
26330
- const start = i;
26331
- i += 1;
26332
- let out = "";
26333
- let closed = false;
26334
- while (i < n) {
26335
- const c = source[i];
26336
- if (c === "\\") {
26337
- const next = i + 1 < n ? source[i + 1] : "";
26338
- if (next === "\\" || next === "'" || next === "\"") {
26339
- out += next;
26340
- i += 2;
26341
- continue;
26342
- }
26343
- throw new ExpressionParseError(`invalid string escape: '\\${next}'`, i);
26344
- }
26345
- if (c === quote) {
26346
- closed = true;
26347
- i += 1;
26348
- break;
26349
- }
26350
- out += c;
26351
- i += 1;
26352
- }
26353
- if (!closed) throw new ExpressionParseError("unterminated string literal", start);
26354
- tokens.push({
26355
- type: "string",
26356
- value: out,
26357
- pos: start
26358
- });
26359
- continue;
26360
- }
26361
- if (isIdentStart(ch)) {
26362
- const start = i;
26363
- while (i < n && isIdentPart(source[i])) i += 1;
26364
- const text = source.slice(start, i);
26365
- if (KEYWORDS.has(text)) tokens.push({
26366
- type: "keyword",
26367
- keyword: keywordOf(text),
26368
- pos: start
26369
- });
26370
- else tokens.push({
26371
- type: "identifier",
26372
- name: text,
26373
- pos: start
26374
- });
26375
- continue;
26376
- }
26377
- const two = i + 1 < n ? source.slice(i, i + 2) : "";
26378
- if (two === "<=" || two === ">=" || two === "==" || two === "!=" || two === "&&" || two === "||") {
26379
- tokens.push({
26380
- type: "punct",
26381
- punct: two,
26382
- pos: i
26383
- });
26384
- i += 2;
26385
- continue;
26386
- }
26387
- if (isSinglePunct(ch)) {
26388
- tokens.push({
26389
- type: "punct",
26390
- punct: ch,
26391
- pos: i
26392
- });
26393
- i += 1;
26394
- continue;
26395
- }
26396
- throw new ExpressionParseError(`unexpected character '${ch}'`, i);
26724
+ /**
26725
+ * Read the current feature-probe flag bag with a typed cast. Helper
26726
+ * for `getAccessoryChildren()` and `features` getters that derive
26727
+ * outputs from the probe results.
26728
+ */
26729
+ getProbeFlags() {
26730
+ return this.runtimeState.getCapState("feature-probe")?.flags ?? {};
26397
26731
  }
26398
- tokens.push({
26399
- type: "eof",
26400
- pos: n
26401
- });
26402
- return tokens;
26403
- }
26404
- function keywordOf(text) {
26405
- if (text === "true") return "true";
26406
- if (text === "false") return "false";
26407
- return "null";
26408
- }
26409
- function isSinglePunct(ch) {
26410
- return ch === "(" || ch === ")" || ch === "," || ch === "?" || ch === ":" || ch === "+" || ch === "-" || ch === "*" || ch === "/" || ch === "%" || ch === "!" || ch === "<" || ch === ">";
26732
+ /**
26733
+ * Returns true once `onProbe` has completed at least once
26734
+ * (`lastProbedAt > 0`). Drivers gate `getAccessoryChildren()` on this
26735
+ * to avoid spawning stale accessories on a fresh device whose probe
26736
+ * hasn't landed yet.
26737
+ */
26738
+ hasProbed() {
26739
+ return (this.runtimeState.getCapState("feature-probe")?.lastProbedAt ?? 0) > 0;
26740
+ }
26741
+ };
26742
+ /**
26743
+ * Convert an IDevice to the flat DeviceSummary shape expected by the
26744
+ * device-provider cap router. Shared across all providers.
26745
+ */
26746
+ function toDeviceSummary(device, addonId) {
26747
+ const config = {};
26748
+ for (const entry of device.config.entries()) config[entry.key] = entry.value;
26749
+ return {
26750
+ id: device.id,
26751
+ stableId: device.stableId,
26752
+ addonId,
26753
+ type: String(device.type),
26754
+ name: device.name,
26755
+ parentDeviceId: device.parentDeviceId,
26756
+ online: device.online,
26757
+ features: [...device.features],
26758
+ config,
26759
+ sourceInfo: device.sourceInfo
26760
+ };
26411
26761
  }
26412
26762
  /**
26413
- * Pratt (precedence-climbing) parser for the safe expression mini-language.
26763
+ * Base class for device-provider addons (rtsp, onvif, frigate).
26414
26764
  *
26415
- * Precedence (low → high): ternary `?:` (right-assoc) → `||` → `&&` → equality
26416
- * → relational → additive → multiplicative → unary `! -` → call / primary.
26417
- * Calls are ONLY `IDENT '(' args? ')'` at primary position — the callee is a
26418
- * string validated against the builtin table at parse time, so an unknown
26419
- * function is rejected immediately (author feedback) and a persisted expression
26420
- * that references a since-removed builtin degrades at read.
26765
+ * Provides default implementations for the common device-provider cap
26766
+ * methods (`start`, `stop`, `getStatus`, `getDevices`, `supportsDiscovery`,
26767
+ * `supportsManualCreation`, `toDeviceSummary`). Subclasses override the
26768
+ * methods that differ per provider.
26421
26769
  *
26422
- * A node counter caps total AST size (`MAX_EXPRESSION_AST_NODES`) and call
26423
- * arity is capped (`MAX_EXPRESSION_CALL_ARGS`) — both raise `ExpressionParseError`.
26770
+ * @example
26771
+ * ```ts
26772
+ * class RtspProvider extends BaseDeviceProvider {
26773
+ * protected readonly addonId = 'provider-rtsp'
26774
+ * protected readonly providerName = 'RTSP'
26775
+ *
26776
+ * protected async onCreateDevice(input) { ... }
26777
+ * protected async onGetCreationSchema(type) { ... }
26778
+ * protected async onRestoreDevices(saved) { ... }
26779
+ * }
26780
+ * ```
26424
26781
  */
26425
- /** Binary/logical operator precedence (higher binds tighter). */
26426
- var BINARY_PRECEDENCE = {
26427
- "||": 1,
26428
- "&&": 2,
26429
- "==": 3,
26430
- "!=": 3,
26431
- "<": 4,
26432
- "<=": 4,
26433
- ">": 4,
26434
- ">=": 4,
26435
- "+": 5,
26436
- "-": 5,
26437
- "*": 6,
26438
- "/": 6,
26439
- "%": 6
26440
- };
26441
- function isLogicalOp(op) {
26442
- return op === "&&" || op === "||";
26443
- }
26444
- function isBinaryOp(op) {
26445
- return op === "+" || op === "-" || op === "*" || op === "/" || op === "%" || op === "==" || op === "!=" || op === "<" || op === "<=" || op === ">" || op === ">=";
26446
- }
26447
- var Parser = class {
26448
- tokens;
26449
- pos = 0;
26450
- nodeCount = 0;
26451
- identifiers = /* @__PURE__ */ new Set();
26452
- callees = /* @__PURE__ */ new Set();
26453
- constructor(tokens) {
26454
- this.tokens = tokens;
26782
+ var BaseDeviceProvider = class extends BaseAddon {
26783
+ async onInitialize() {
26784
+ this.ctx.logger.info(`${this.providerName} Provider initialized`);
26785
+ return [{
26786
+ capability: deviceProviderCapability,
26787
+ provider: this
26788
+ }];
26455
26789
  }
26456
- parse() {
26457
- const ast = this.parseTernary();
26458
- const tok = this.peek();
26459
- if (tok.type !== "eof") throw new ExpressionParseError("unexpected trailing input", tok.pos);
26790
+ async onShutdown() {
26791
+ const devices = await this.ctx.kernel.devices?.getAll() ?? [];
26792
+ for (const device of devices) try {
26793
+ await this.ctx.kernel.devices?.decommission(device.id);
26794
+ } catch (err) {
26795
+ this.ctx.logger.warn(`${this.providerName}: decommission failed`, {
26796
+ tags: {
26797
+ deviceId: device.id,
26798
+ stableId: device.stableId
26799
+ },
26800
+ meta: { error: err instanceof Error ? err.message : String(err) }
26801
+ });
26802
+ }
26803
+ this.ctx.logger.info(`${this.providerName} Provider shut down`, { meta: { decommissionedCount: devices.length } });
26804
+ }
26805
+ async start() {}
26806
+ async stop() {}
26807
+ async getStatus() {
26460
26808
  return {
26461
- ast,
26462
- identifiers: this.identifiers,
26463
- callees: this.callees,
26464
- nodeCount: this.nodeCount
26809
+ connected: true,
26810
+ deviceCount: (await this.ctx.kernel.devices?.getAll() ?? []).length
26465
26811
  };
26466
26812
  }
26467
- peek() {
26468
- return this.tokens[this.pos];
26469
- }
26470
- next() {
26471
- return this.tokens[this.pos++];
26472
- }
26473
- /** Consume a punctuator token, erroring if the next token isn't it. */
26474
- expectPunct(punct) {
26475
- const tok = this.peek();
26476
- if (tok.type !== "punct" || tok.punct !== punct) throw new ExpressionParseError(`expected '${punct}'`, tok.pos);
26477
- this.pos += 1;
26813
+ async getDevices() {
26814
+ return (await this.ctx.kernel.devices?.getAll() ?? []).map((d) => ({
26815
+ id: d.stableId,
26816
+ name: d.name,
26817
+ type: String(d.type)
26818
+ }));
26478
26819
  }
26479
- matchPunct(punct) {
26480
- const tok = this.peek();
26481
- if (tok.type === "punct" && tok.punct === punct) {
26482
- this.pos += 1;
26483
- return true;
26484
- }
26820
+ async supportsDiscovery() {
26485
26821
  return false;
26486
26822
  }
26487
- countNode() {
26488
- this.nodeCount += 1;
26489
- if (this.nodeCount > 256) throw new ExpressionParseError("expression too complex", this.peek().pos);
26823
+ async discoverDevices(_input) {
26824
+ return [];
26490
26825
  }
26491
- parseTernary() {
26492
- const test = this.parseBinary(1);
26493
- if (this.matchPunct("?")) {
26494
- const consequent = this.parseTernary();
26495
- this.expectPunct(":");
26496
- const alternate = this.parseTernary();
26497
- this.countNode();
26498
- return {
26499
- kind: "conditional",
26500
- test,
26501
- consequent,
26502
- alternate
26503
- };
26504
- }
26505
- return test;
26826
+ /** Extra per-scan input form (e.g. a broadcast address for another subnet).
26827
+ * Null = no extra params. Override in providers that support scoped scans. */
26828
+ async getDiscoveryParamsSchema() {
26829
+ return null;
26506
26830
  }
26507
- parseBinary(minPrec) {
26508
- let left = this.parseUnary();
26509
- for (;;) {
26510
- const tok = this.peek();
26511
- if (tok.type !== "punct") break;
26512
- const prec = BINARY_PRECEDENCE[tok.punct];
26513
- if (prec === void 0 || prec < minPrec) break;
26514
- const op = tok.punct;
26515
- this.pos += 1;
26516
- const right = this.parseBinary(prec + 1);
26517
- this.countNode();
26518
- if (isLogicalOp(op)) left = {
26519
- kind: "logical",
26520
- op,
26521
- left,
26522
- right
26523
- };
26524
- else if (isBinaryOp(op)) left = {
26525
- kind: "binary",
26526
- op,
26527
- left,
26528
- right
26529
- };
26530
- else throw new ExpressionParseError(`unexpected operator '${op}'`, tok.pos);
26531
- }
26532
- return left;
26831
+ /**
26832
+ * The DeviceType this provider creates via manual add — derived from the
26833
+ * `deviceClasses` map (first registered type). `null` when manual creation is
26834
+ * unsupported. Lets the Add-Device dialog pick the right type per provider.
26835
+ */
26836
+ async getManualCreationType() {
26837
+ if (!await this.supportsManualCreation()) return { deviceType: null };
26838
+ return { deviceType: Object.values(DeviceType).find((t) => this.deviceClasses[t] !== void 0) ?? null };
26533
26839
  }
26534
- parseUnary() {
26535
- const tok = this.peek();
26536
- if (tok.type === "punct" && (tok.punct === "!" || tok.punct === "-")) {
26537
- const op = tok.punct;
26538
- this.pos += 1;
26539
- const operand = this.parseUnary();
26540
- this.countNode();
26541
- return {
26542
- kind: "unary",
26543
- op,
26544
- operand
26545
- };
26546
- }
26547
- return this.parsePrimary();
26840
+ async adoptDiscoveredDevice(_input) {
26841
+ throw new Error(`${this.providerName} provider does not support discovery-based adoption`);
26548
26842
  }
26549
- parsePrimary() {
26550
- const tok = this.next();
26551
- switch (tok.type) {
26552
- case "number":
26553
- this.countNode();
26554
- return {
26555
- kind: "literal",
26556
- value: tok.value
26557
- };
26558
- case "string":
26559
- this.countNode();
26560
- return {
26561
- kind: "literal",
26562
- value: tok.value
26563
- };
26564
- case "keyword":
26565
- this.countNode();
26566
- return {
26567
- kind: "literal",
26568
- value: tok.keyword === "null" ? null : tok.keyword === "true"
26569
- };
26570
- case "identifier": {
26571
- const nextTok = this.peek();
26572
- if (nextTok.type === "punct" && nextTok.punct === "(") return this.parseCall(tok.name, tok.pos);
26573
- this.identifiers.add(tok.name);
26574
- this.countNode();
26575
- return {
26576
- kind: "identifier",
26577
- name: tok.name
26578
- };
26579
- }
26580
- case "punct":
26581
- if (tok.punct === "(") {
26582
- const inner = this.parseTernary();
26583
- this.expectPunct(")");
26584
- return inner;
26585
- }
26586
- throw new ExpressionParseError(`unexpected token '${tok.punct}'`, tok.pos);
26587
- case "eof": throw new ExpressionParseError("unexpected end of expression", tok.pos);
26588
- }
26843
+ async supportsManualCreation() {
26844
+ return true;
26589
26845
  }
26590
- parseCall(callee, pos) {
26591
- if (!EXPRESSION_BUILTIN_NAMES.has(callee)) throw new ExpressionParseError(`unknown function '${callee}'`, pos);
26592
- this.expectPunct("(");
26593
- const args = [];
26594
- if (!this.matchPunct(")")) for (;;) {
26595
- args.push(this.parseTernary());
26596
- if (args.length > 16) throw new ExpressionParseError(`too many arguments to '${callee}'`, pos);
26597
- if (this.matchPunct(",")) continue;
26598
- this.expectPunct(")");
26599
- break;
26846
+ async getChildCreationSchema(input) {
26847
+ return this.onGetCreationSchema(input.type);
26848
+ }
26849
+ /**
26850
+ * Default kernel-orchestrated `createDevice` implementation. The
26851
+ * subclass's `onCreateDevice` returns a declarative
26852
+ * `CreateDeviceSpec` (`{meta, config}`) — this method handles
26853
+ * stableId generation, class lookup, kernel.devices.create
26854
+ * dispatch, and DeviceSummary mapping. Subclasses should NOT
26855
+ * override this method; override `onCreateDevice` and
26856
+ * `deviceClasses` instead.
26857
+ */
26858
+ async createDevice(input) {
26859
+ const spec = await this.onCreateDevice(input.type, input.config);
26860
+ const Class = this.deviceClasses[spec.meta.type];
26861
+ if (!Class) throw new Error(`${this.providerName} provider: no device class registered for type "${spec.meta.type}" — add it to the deviceClasses map`);
26862
+ const stableId = this.generateStableId(spec.meta.type, spec.config);
26863
+ const device = await this.ctx.kernel.devices.create(stableId, Class, spec.config, null, spec.meta);
26864
+ if (spec.onAfterCreate) try {
26865
+ await spec.onAfterCreate(device);
26866
+ } catch (err) {
26867
+ this.ctx.logger.warn("createDevice: onAfterCreate hook threw — device is already registered", {
26868
+ tags: {
26869
+ deviceId: device.id,
26870
+ stableId
26871
+ },
26872
+ meta: { error: err instanceof Error ? err.message : String(err) }
26873
+ });
26600
26874
  }
26601
- this.callees.add(callee);
26602
- this.countNode();
26603
- return {
26604
- kind: "call",
26605
- callee,
26606
- args
26607
- };
26875
+ return this.toSummary(device);
26608
26876
  }
26609
- };
26610
- /** Tokenize + parse `source` into a validated `ParsedExpression`. Throws
26611
- * `ExpressionParseError` on any lexical or grammatical failure. */
26612
- function parseExpression(source) {
26613
- return new Parser(tokenize(source)).parse();
26614
- }
26615
- /**
26616
- * LRU compile cache for parsed expressions (spec §2.4 "parse once … LRU keyed
26617
- * by expr"). The cache stores BOTH successes and failures (negative caching),
26618
- * so a corrupt persisted string costs exactly one tokenize+parse total — not
26619
- * one per read on a hot resolve path.
26620
- *
26621
- * The cache is a module-level singleton: entries are pure, content-addressed
26622
- * ASTs keyed by the raw source string, so sharing one instance across all
26623
- * callers is safe and maximises hit rate.
26624
- */
26625
- var cache = /* @__PURE__ */ new Map();
26626
- function getCached(source) {
26627
- const hit = cache.get(source);
26628
- if (hit !== void 0) {
26629
- cache.delete(source);
26630
- cache.set(source, hit);
26631
- return hit;
26877
+ /**
26878
+ * Generate a stableId for a newly-created device. Default uses the
26879
+ * `${addonId}-${Date.now()}` pattern as a unique-but-opaque
26880
+ * fallback; any provider that has access to durable hardware
26881
+ * identity (UID, MAC, serial) should override and derive from it
26882
+ * so re-adding the same physical device reuses its persisted row.
26883
+ *
26884
+ * `config` is the parsed CreateDeviceSpec.config the subclass
26885
+ * returned from `onCreateDevice` — the override has access to
26886
+ * every operator-supplied + autodetect-resolved field. Optional
26887
+ * for back-compat: existing overrides that take only `type`
26888
+ * keep working unchanged.
26889
+ */
26890
+ generateStableId(_type, _config) {
26891
+ return `${this.addonId}-${Date.now()}`;
26632
26892
  }
26633
- let result;
26634
- try {
26635
- result = {
26636
- ok: true,
26637
- parsed: parseExpression(source)
26638
- };
26639
- } catch (err) {
26640
- result = {
26641
- ok: false,
26642
- error: err instanceof ExpressionParseError ? err.message : String(err)
26893
+ async testCreationField(_input) {
26894
+ return {
26895
+ status: "ok",
26896
+ labels: ["probe not implemented"]
26643
26897
  };
26644
26898
  }
26645
- cache.set(source, result);
26646
- if (cache.size > 256) {
26647
- const oldest = cache.keys().next().value;
26648
- if (oldest !== void 0) cache.delete(oldest);
26899
+ async restoreDevices(savedDevices) {
26900
+ await this.onRestoreDevices(savedDevices);
26901
+ if (savedDevices.length > 0) this.ctx.logger.info(`Restored ${savedDevices.length} ${this.providerName} device(s)`);
26649
26902
  }
26650
- return result;
26651
- }
26652
- /** Compile `source`, returning a discriminated result instead of throwing.
26653
- * Used by read paths that must degrade rather than raise. LRU/negative-cached. */
26654
- function compileExpressionSafe(source) {
26655
- return getCached(source);
26656
- }
26657
- Object.freeze({});
26658
- /**
26659
- * Author-time validation. Returns `null` when the source is valid, else a
26660
- * human-readable error message. Checks: the expression compiles; binding count
26661
- * is within `MAX_EXPRESSION_BINDINGS`; every binding name is a legal identifier,
26662
- * is not reserved (`now`/keywords) and does not shadow a builtin; and every
26663
- * FREE identifier of the AST is covered by a binding or the injected `now`.
26664
- */
26665
- function validateExpressionSource(src) {
26666
- const names = Object.keys(src.bindings);
26667
- if (names.length > 32) return `too many bindings (${names.length} > 32)`;
26668
- for (const name of names) {
26669
- if (!EXPRESSION_IDENTIFIER_RE.test(name)) return `invalid binding name '${name}'`;
26670
- if (RESERVED_BINDING_NAMES.has(name)) return `binding name '${name}' is reserved`;
26671
- if (EXPRESSION_BUILTIN_NAMES.has(name)) return `binding name '${name}' shadows a builtin function`;
26903
+ /**
26904
+ * Restore devices from persisted state. Two-pass:
26905
+ *
26906
+ * 1. **Top-level pass** — invokes `kernel.devices.create()` for every
26907
+ * `parentDeviceId === null` row using the `deviceClasses` map.
26908
+ * The kernel's register flow handles `getAccessoryChildren()` for
26909
+ * each parent (siren / floodlight / PIR / etc).
26910
+ *
26911
+ * 2. **Hub-adopted children pass** — for rows with
26912
+ * `parentDeviceId !== null` whose `type` IS in `deviceClasses`
26913
+ * (e.g. Reolink hub-adopted cameras under an NVR), spawn them
26914
+ * explicitly with the persisted `parentDeviceId`. These are
26915
+ * NOT accessory children — they're first-class adopted devices
26916
+ * that just happen to have a parent. Without this pass, every
26917
+ * server restart would lose hub-adopted cameras (their type is
26918
+ * in `deviceClasses` but parent's `getAccessoryChildren` doesn't
26919
+ * spawn them — that callback is only for purpose-built
26920
+ * accessory roles).
26921
+ *
26922
+ * Rows whose `type` is NOT in `deviceClasses` are skipped — those
26923
+ * are accessory children (siren/light/sensor) that the kernel's
26924
+ * accessory-spawn flow handles via the parent's
26925
+ * `getAccessoryChildren()`. Override only when the default doesn't
26926
+ * fit.
26927
+ */
26928
+ async onRestoreDevices(savedDevices) {
26929
+ const restored = /* @__PURE__ */ new Set();
26930
+ for (const saved of savedDevices) {
26931
+ if (saved.parentDeviceId !== null) continue;
26932
+ const Class = this.deviceClasses[saved.type];
26933
+ if (!Class) {
26934
+ this.ctx.logger.warn("No device class registered for restored type — skipping", {
26935
+ tags: { stableId: saved.stableId },
26936
+ meta: { type: saved.type }
26937
+ });
26938
+ continue;
26939
+ }
26940
+ try {
26941
+ await this.ctx.kernel.devices.create(saved.stableId, Class, {});
26942
+ restored.add(saved.id);
26943
+ } catch (err) {
26944
+ this.ctx.logger.warn("Failed to restore device", {
26945
+ tags: { stableId: saved.stableId },
26946
+ meta: {
26947
+ type: saved.type,
26948
+ error: err instanceof Error ? err.message : String(err)
26949
+ }
26950
+ });
26951
+ }
26952
+ }
26953
+ const childRows = savedDevices.filter((s) => s.parentDeviceId !== null);
26954
+ for (const saved of childRows) {
26955
+ const Class = this.deviceClasses[saved.type];
26956
+ if (!Class) continue;
26957
+ if (saved.parentDeviceId === null) continue;
26958
+ if (!restored.has(saved.parentDeviceId)) continue;
26959
+ try {
26960
+ await this.ctx.kernel.devices.create(saved.stableId, Class, {}, saved.parentDeviceId);
26961
+ restored.add(saved.id);
26962
+ } catch (err) {
26963
+ this.ctx.logger.warn("Failed to restore hub-adopted child", {
26964
+ tags: {
26965
+ stableId: saved.stableId,
26966
+ parentDeviceId: saved.parentDeviceId
26967
+ },
26968
+ meta: {
26969
+ type: saved.type,
26970
+ error: err instanceof Error ? err.message : String(err)
26971
+ }
26972
+ });
26973
+ }
26974
+ }
26672
26975
  }
26673
- const compiled = compileExpressionSafe(src.expr);
26674
- if (!compiled.ok) return compiled.error;
26675
- const bound = new Set(names);
26676
- for (const id of compiled.parsed.identifiers) {
26677
- if (id === "now") continue;
26678
- if (!bound.has(id)) return `expression references unbound identifier '${id}'`;
26976
+ /** Convert an IDevice to the flat DeviceSummary for the cap router. */
26977
+ toSummary(device) {
26978
+ return toDeviceSummary(device, this.addonId);
26679
26979
  }
26680
- return null;
26681
- }
26682
- var ExpressionBindingSourceSchema = union([
26683
- object({
26684
- kind: literal("field").optional(),
26685
- sourceKey: string(),
26686
- cap: string(),
26687
- fieldPath: string()
26688
- }),
26689
- object({
26690
- kind: literal("literal"),
26691
- value: union([
26692
- string(),
26693
- number(),
26694
- boolean(),
26695
- _null()
26696
- ])
26697
- }),
26698
- object({
26699
- kind: literal("global"),
26700
- sourceStableId: string(),
26701
- cap: string(),
26702
- fieldPath: string()
26703
- })
26704
- ]);
26705
- object({
26706
- expr: string().min(1).max(MAX_EXPRESSION_SOURCE_LENGTH),
26707
- bindings: record(string().regex(EXPRESSION_IDENTIFIER_RE), ExpressionBindingSourceSchema)
26708
- }).superRefine((src, ctx) => {
26709
- const err = validateExpressionSource(src);
26710
- if (err !== null) ctx.addIssue({
26711
- code: "custom",
26712
- message: err,
26713
- path: ["expr"]
26714
- });
26715
- });
26980
+ };
26981
+ DeviceType.Cover, DeviceType.Valve, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.Camera, DeviceType.Hub, DeviceType.Switch, DeviceType.Siren, DeviceType.Light, DeviceType.Fan, DeviceType.Sensor, DeviceType.Thermostat, DeviceType.Climate, DeviceType.Button, DeviceType.EventEmitter, DeviceType.Update, DeviceType.Generic, DeviceType.Notifier, DeviceType.Script, DeviceType.Automation, DeviceType.Lock, DeviceType.MediaPlayer, DeviceType.AlarmPanel, DeviceType.Control, DeviceType.Presence, DeviceType.Weather, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.Container, DeviceType.Image, DeviceType.PetFeeder;
26982
+ new Set(Object.values(DeviceType));
26983
+ DeviceFeature.BatteryOperated;
26716
26984
  Object.freeze({
26717
26985
  "accessories.setChildHidden": {
26718
26986
  capName: "accessories",
@@ -31046,6 +31314,12 @@ Object.freeze({
31046
31314
  addonId: null,
31047
31315
  access: "view"
31048
31316
  },
31317
+ "snapshot.getSnapshotLinks": {
31318
+ capName: "snapshot",
31319
+ capScope: "device",
31320
+ addonId: null,
31321
+ access: "view"
31322
+ },
31049
31323
  "snapshot.getSnapshotOverview": {
31050
31324
  capName: "snapshot",
31051
31325
  capScope: "device",
@@ -56796,8 +57070,9 @@ var HmChildDevice = class extends BaseDevice {
56796
57070
  }
56797
57071
  /**
56798
57072
  * Attach a facade `valueChanged` listener filtered to this child's device
56799
- * address. The subclass-supplied `handle` runs only for matching events.
56800
- * No-ops when no facade is present (the child reconnects on next reconcile).
57073
+ * address AND — when the child owns one — to its channel. The
57074
+ * subclass-supplied `handle` runs only for matching events. No-ops when no
57075
+ * facade is present (the child reconnects on next reconcile).
56801
57076
  */
56802
57077
  attachValueChangedListener(handle) {
56803
57078
  this.valueHandler = handle;
@@ -56805,12 +57080,41 @@ var HmChildDevice = class extends BaseDevice {
56805
57080
  if (!facade) return;
56806
57081
  this.valueChangedUnsub = facade.on("valueChanged", (event) => {
56807
57082
  if (event.device !== this.address) return;
57083
+ if (!this.ownsEventChannel(event)) return;
56808
57084
  handle(event);
56809
57085
  });
56810
57086
  this.seedTriggerUnsubs = [facade.on("ready", () => this.seedCurrentValues()), facade.on("connection", () => this.seedCurrentValues())];
56811
57087
  this.seedCurrentValues();
56812
57088
  }
56813
57089
  /**
57090
+ * Whether an inbound value event belongs to THIS child's channel.
57091
+ *
57092
+ * One CCU device address can host SEVERAL independent functional entities —
57093
+ * an HmIP-BS2 carries two unrelated relays, on `<addr>:4` and `<addr>:8`, and
57094
+ * BOTH emit `STATE`. Filtering on the device address alone let either relay's
57095
+ * event write the other's slice: actuating one made both report ON while only
57096
+ * one was physically on. The seed path (`seedCurrentValues`) has always been
57097
+ * channel-scoped; this makes the live path agree with it.
57098
+ *
57099
+ * Channel-less children (event-emitter, firmware update) span the whole
57100
+ * device by design and accept every channel.
57101
+ */
57102
+ ownsEventChannel(event) {
57103
+ const owned = this.channel;
57104
+ if (owned === void 0) return true;
57105
+ const channel = event.channel;
57106
+ if (typeof channel === "string" && channel.length > 0) return channel === owned;
57107
+ this.ctx.logger.warn("Homematic value event without a channel — dropped", {
57108
+ tags: { deviceId: this.ctx.id },
57109
+ meta: {
57110
+ address: this.address,
57111
+ ownedChannel: owned,
57112
+ parameter: event.parameter
57113
+ }
57114
+ });
57115
+ return false;
57116
+ }
57117
+ /**
56814
57118
  * Replay this child's CURRENT cached datapoint values through the registered
56815
57119
  * value handler. Reads the live `HmDevice` snapshot (the library backfills the
56816
57120
  * seeded values onto its datapoints) and feeds each non-null value on THIS