@camstack/addon-export-alexa 1.2.179 → 1.2.180

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.
@@ -820,7 +820,7 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
820
820
  return EventCategory;
821
821
  }({});
822
822
  //#endregion
823
- //#region ../types/dist/device-type-CfHw_quR.mjs
823
+ //#region ../types/dist/device-type-D1fH5kaC.mjs
824
824
  /**
825
825
  import { errMsg } from '@camstack/types'
826
826
  * Extract a human-readable message from an unknown error value.
@@ -1051,6 +1051,12 @@ var DeviceFeature = /* @__PURE__ */ function(DeviceFeature) {
1051
1051
  DeviceFeature["MediaPlayerPrevious"] = "media-player-previous";
1052
1052
  /** Media player exposes stop distinct from pause. */
1053
1053
  DeviceFeature["MediaPlayerStop"] = "media-player-stop";
1054
+ /** Media player exposes volume up / down in steps (an infrared TV has no level). */
1055
+ DeviceFeature["MediaPlayerVolumeStep"] = "media-player-volume-step";
1056
+ /** Media player exposes channel up / down in steps. */
1057
+ DeviceFeature["MediaPlayerChannelStep"] = "media-player-channel-step";
1058
+ /** Media player exposes power on / off. */
1059
+ DeviceFeature["MediaPlayerPower"] = "media-player-power";
1054
1060
  /** Alarm panel requires a PIN code on arm/disarm. */
1055
1061
  DeviceFeature["AlarmPinRequired"] = "alarm-pin-required";
1056
1062
  /** Presence device carries GPS coordinates (lat/lng/accuracy) in
@@ -4587,6 +4593,12 @@ var numberProcessor = (schema, ctx, _json, _params) => {
4587
4593
  var booleanProcessor = (_schema, _ctx, json, _params) => {
4588
4594
  json.type = "boolean";
4589
4595
  };
4596
+ var bigintProcessor = (_schema, ctx, _json, _params) => {
4597
+ if (ctx.unrepresentable === "throw") throw new Error("BigInt cannot be represented in JSON Schema");
4598
+ };
4599
+ var symbolProcessor = (_schema, ctx, _json, _params) => {
4600
+ if (ctx.unrepresentable === "throw") throw new Error("Symbols cannot be represented in JSON Schema");
4601
+ };
4590
4602
  var nullProcessor = (_schema, ctx, json, _params) => {
4591
4603
  if (ctx.target === "openapi-3.0") {
4592
4604
  json.type = "string";
@@ -4594,12 +4606,17 @@ var nullProcessor = (_schema, ctx, json, _params) => {
4594
4606
  json.enum = [null];
4595
4607
  } else json.type = "null";
4596
4608
  };
4609
+ var undefinedProcessor = (_schema, ctx, _json, _params) => {
4610
+ if (ctx.unrepresentable === "throw") throw new Error("Undefined cannot be represented in JSON Schema");
4611
+ };
4597
4612
  var voidProcessor = (_schema, ctx, _json, _params) => {
4598
4613
  if (ctx.unrepresentable === "throw") throw new Error("Void cannot be represented in JSON Schema");
4599
4614
  };
4600
4615
  var neverProcessor = (_schema, _ctx, json, _params) => {
4601
4616
  json.not = {};
4602
4617
  };
4618
+ var anyProcessor = (_schema, _ctx, _json, _params) => {};
4619
+ var unknownProcessor = (_schema, _ctx, _json, _params) => {};
4603
4620
  var dateProcessor = (_schema, ctx, _json, _params) => {
4604
4621
  if (ctx.unrepresentable === "throw") throw new Error("Date cannot be represented in JSON Schema");
4605
4622
  };
@@ -4631,12 +4648,53 @@ var literalProcessor = (schema, ctx, json, _params) => {
4631
4648
  json.enum = vals;
4632
4649
  }
4633
4650
  };
4651
+ var nanProcessor = (_schema, ctx, _json, _params) => {
4652
+ if (ctx.unrepresentable === "throw") throw new Error("NaN cannot be represented in JSON Schema");
4653
+ };
4654
+ var templateLiteralProcessor = (schema, _ctx, json, _params) => {
4655
+ const _json = json;
4656
+ const pattern = schema._zod.pattern;
4657
+ if (!pattern) throw new Error("Pattern not found in template literal");
4658
+ _json.type = "string";
4659
+ _json.pattern = pattern.source;
4660
+ };
4661
+ var fileProcessor = (schema, _ctx, json, _params) => {
4662
+ const _json = json;
4663
+ const file = {
4664
+ type: "string",
4665
+ format: "binary",
4666
+ contentEncoding: "binary"
4667
+ };
4668
+ const { minimum, maximum, mime } = schema._zod.bag;
4669
+ if (minimum !== void 0) file.minLength = minimum;
4670
+ if (maximum !== void 0) file.maxLength = maximum;
4671
+ if (mime) if (mime.length === 1) {
4672
+ file.contentMediaType = mime[0];
4673
+ Object.assign(_json, file);
4674
+ } else {
4675
+ Object.assign(_json, file);
4676
+ _json.anyOf = mime.map((m) => ({ contentMediaType: m }));
4677
+ }
4678
+ else Object.assign(_json, file);
4679
+ };
4680
+ var successProcessor = (_schema, _ctx, json, _params) => {
4681
+ json.type = "boolean";
4682
+ };
4634
4683
  var customProcessor = (_schema, ctx, _json, _params) => {
4635
4684
  if (ctx.unrepresentable === "throw") throw new Error("Custom types cannot be represented in JSON Schema");
4636
4685
  };
4686
+ var functionProcessor = (_schema, ctx, _json, _params) => {
4687
+ if (ctx.unrepresentable === "throw") throw new Error("Function types cannot be represented in JSON Schema");
4688
+ };
4637
4689
  var transformProcessor = (_schema, ctx, _json, _params) => {
4638
4690
  if (ctx.unrepresentable === "throw") throw new Error("Transforms cannot be represented in JSON Schema");
4639
4691
  };
4692
+ var mapProcessor = (_schema, ctx, _json, _params) => {
4693
+ if (ctx.unrepresentable === "throw") throw new Error("Map cannot be represented in JSON Schema");
4694
+ };
4695
+ var setProcessor = (_schema, ctx, _json, _params) => {
4696
+ if (ctx.unrepresentable === "throw") throw new Error("Set cannot be represented in JSON Schema");
4697
+ };
4640
4698
  var arrayProcessor = (schema, ctx, _json, params) => {
4641
4699
  const json = _json;
4642
4700
  const def = schema._zod.def;
@@ -4841,6 +4899,12 @@ var readonlyProcessor = (schema, ctx, json, params) => {
4841
4899
  seen.ref = def.innerType;
4842
4900
  json.readOnly = true;
4843
4901
  };
4902
+ var promiseProcessor = (schema, ctx, _json, params) => {
4903
+ const def = schema._zod.def;
4904
+ process$1(def.innerType, ctx, params);
4905
+ const seen = ctx.seen.get(schema);
4906
+ seen.ref = def.innerType;
4907
+ };
4844
4908
  var optionalProcessor = (schema, ctx, _json, params) => {
4845
4909
  const def = schema._zod.def;
4846
4910
  process$1(def.innerType, ctx, params);
@@ -4853,6 +4917,81 @@ var lazyProcessor = (schema, ctx, _json, params) => {
4853
4917
  const seen = ctx.seen.get(schema);
4854
4918
  seen.ref = innerType;
4855
4919
  };
4920
+ var allProcessors = {
4921
+ string: stringProcessor,
4922
+ number: numberProcessor,
4923
+ boolean: booleanProcessor,
4924
+ bigint: bigintProcessor,
4925
+ symbol: symbolProcessor,
4926
+ null: nullProcessor,
4927
+ undefined: undefinedProcessor,
4928
+ void: voidProcessor,
4929
+ never: neverProcessor,
4930
+ any: anyProcessor,
4931
+ unknown: unknownProcessor,
4932
+ date: dateProcessor,
4933
+ enum: enumProcessor,
4934
+ literal: literalProcessor,
4935
+ nan: nanProcessor,
4936
+ template_literal: templateLiteralProcessor,
4937
+ file: fileProcessor,
4938
+ success: successProcessor,
4939
+ custom: customProcessor,
4940
+ function: functionProcessor,
4941
+ transform: transformProcessor,
4942
+ map: mapProcessor,
4943
+ set: setProcessor,
4944
+ array: arrayProcessor,
4945
+ object: objectProcessor,
4946
+ union: unionProcessor,
4947
+ intersection: intersectionProcessor,
4948
+ tuple: tupleProcessor,
4949
+ record: recordProcessor,
4950
+ nullable: nullableProcessor,
4951
+ nonoptional: nonoptionalProcessor,
4952
+ default: defaultProcessor,
4953
+ prefault: prefaultProcessor,
4954
+ catch: catchProcessor,
4955
+ pipe: pipeProcessor,
4956
+ readonly: readonlyProcessor,
4957
+ promise: promiseProcessor,
4958
+ optional: optionalProcessor,
4959
+ lazy: lazyProcessor
4960
+ };
4961
+ function toJSONSchema(input, params) {
4962
+ if ("_idmap" in input) {
4963
+ const registry = input;
4964
+ const ctx = initializeContext({
4965
+ ...params,
4966
+ processors: allProcessors
4967
+ });
4968
+ const defs = {};
4969
+ for (const entry of registry._idmap.entries()) {
4970
+ const [_, schema] = entry;
4971
+ process$1(schema, ctx);
4972
+ }
4973
+ const schemas = {};
4974
+ ctx.external = {
4975
+ registry,
4976
+ uri: params?.uri,
4977
+ defs
4978
+ };
4979
+ for (const entry of registry._idmap.entries()) {
4980
+ const [key, schema] = entry;
4981
+ extractDefs(ctx, schema);
4982
+ schemas[key] = finalize(ctx, schema);
4983
+ }
4984
+ if (Object.keys(defs).length > 0) schemas.__shared = { [ctx.target === "draft-2020-12" ? "$defs" : "definitions"]: defs };
4985
+ return { schemas };
4986
+ }
4987
+ const ctx = initializeContext({
4988
+ ...params,
4989
+ processors: allProcessors
4990
+ });
4991
+ process$1(input, ctx);
4992
+ extractDefs(ctx, input);
4993
+ return finalize(ctx, input);
4994
+ }
4856
4995
  //#endregion
4857
4996
  //#region ../../node_modules/zod/v4/classic/iso.js
4858
4997
  var ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => {
@@ -5877,7 +6016,7 @@ var ZodIssueCode = {
5877
6016
  var ZodFirstPartyTypeKind;
5878
6017
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5879
6018
  //#endregion
5880
- //#region ../types/dist/sleep-hmSP-eJt.mjs
6019
+ //#region ../types/dist/sleep-BKClVk0K.mjs
5881
6020
  /**
5882
6021
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5883
6022
  * window to float samples (D455).
@@ -5956,6 +6095,22 @@ function buildAlawTable() {
5956
6095
  }
5957
6096
  buildUlawTable();
5958
6097
  buildAlawTable();
6098
+ /**
6099
+ * An addon whose own migrations did not apply refuses to initialise (D987). The error is typed
6100
+ * so a runner hosting several addons can tell "this addon is blocked" from a crash and keep its
6101
+ * co-located siblings running. Recognised by NAME and shape, never `instanceof`: a forked addon
6102
+ * bundles its own copy of this module, so the class the runner sees is not the one that threw.
6103
+ */
6104
+ var MIGRATIONS_BLOCKED_ERROR_NAME = "AddonMigrationsBlockedError";
6105
+ var AddonMigrationsBlockedError = class extends Error {
6106
+ /** The ledger ids that did not apply and block the owner. */
6107
+ migrationIds;
6108
+ constructor(migrationIds) {
6109
+ super(`migration(s) ${migrationIds.join(", ")} did not apply and block this addon — fix or retry them (migrations.retry), then restart it`);
6110
+ this.name = MIGRATIONS_BLOCKED_ERROR_NAME;
6111
+ this.migrationIds = migrationIds;
6112
+ }
6113
+ };
5959
6114
  /** Is this field's stored value a credential? */
5960
6115
  function isSecretConfigField(field) {
5961
6116
  if (field.type === "password") return true;
@@ -6009,9 +6164,16 @@ function isSecretMarker(value) {
6009
6164
  const ref = value["$secret"];
6010
6165
  return typeof ref === "string" && ref.length > 0;
6011
6166
  }
6167
+ /** Anything carrying a `$secret` key — a stored marker or a UI view of one. */
6168
+ function isSecretMarkerLike(value) {
6169
+ return isRecord$7(value) && Object.prototype.hasOwnProperty.call(value, "$secret");
6170
+ }
6012
6171
  function isSecretClear(value) {
6013
6172
  return isRecord$7(value) && value["$secretClear"] === true;
6014
6173
  }
6174
+ function isSecretFieldView(value) {
6175
+ return isRecord$7(value) && value["set"] === true && isSecretMarkerLike(value);
6176
+ }
6015
6177
  /**
6016
6178
  * The UI view of a stored secret field value: a marker becomes "set", inline
6017
6179
  * plaintext becomes "set (inline)", nothing becomes `null`. A value never
@@ -6661,11 +6823,36 @@ function projectStore(store, perNodeKeys, nodeId) {
6661
6823
  }
6662
6824
  return out;
6663
6825
  }
6826
+ /**
6827
+ * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6828
+ *
6829
+ * A ref is DETERMINISTIC from where the value lives — the owner addon, the
6830
+ * scope (global, one node, one device, one integration, one row of a business
6831
+ * collection) and the field path inside that scope — so saving the same field
6832
+ * twice updates the same ref, and the ref itself says which settings blob
6833
+ * points at it. It is also the AAD of the value's ciphertext: a ciphertext
6834
+ * copied onto another ref does not decrypt.
6835
+ *
6836
+ * Array items are addressed by ITEM ID, never by index
6837
+ * (`providers[authentik].clientSecret`), so reordering a list keeps every ref.
6838
+ *
6839
+ * Pure and browser-safe: no node builtins, no I/O.
6840
+ */
6841
+ /** The URI scheme of every keychain ref. */
6842
+ var SECRET_REF_SCHEME = "secret://";
6664
6843
  var GLOBAL_SCOPE = { kind: "global" };
6665
6844
  /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6666
6845
  function globalSecretScope() {
6667
6846
  return GLOBAL_SCOPE;
6668
6847
  }
6848
+ /**
6849
+ * An addon id as a ref owner. A hub in-process builtin's context id is
6850
+ * `addon:<id>`; the owner of its secrets is `<id>`, exactly as for the same
6851
+ * addon running forked.
6852
+ */
6853
+ function normalizeSecretOwner(addonId) {
6854
+ return addonId.startsWith("addon:") ? addonId.slice(6) : addonId;
6855
+ }
6669
6856
  function encodeSegment(value) {
6670
6857
  return encodeURIComponent(value);
6671
6858
  }
@@ -6676,6 +6863,16 @@ function decodeSegment(value) {
6676
6863
  return null;
6677
6864
  }
6678
6865
  }
6866
+ /** The scope as it appears inside a ref (`global`, `node/<id>`, …). */
6867
+ function formatSecretScope(scope) {
6868
+ switch (scope.kind) {
6869
+ case "global": return "global";
6870
+ case "node": return `node/${encodeSegment(scope.nodeId)}`;
6871
+ case "device": return `device/${scope.deviceId}`;
6872
+ case "integration": return `integration/${encodeSegment(scope.integrationId)}`;
6873
+ case "row": return `row/${encodeSegment(scope.collection)}/${encodeSegment(scope.rowId)}`;
6874
+ }
6875
+ }
6679
6876
  /**
6680
6877
  * The field path of a value inside an array item, addressed by the item's id:
6681
6878
  * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
@@ -6684,6 +6881,13 @@ function decodeSegment(value) {
6684
6881
  function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6685
6882
  return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6686
6883
  }
6884
+ /** Build a ref. Throws on an empty owner or field path — both are bugs. */
6885
+ function buildSecretRef(parts) {
6886
+ const owner = normalizeSecretOwner(parts.owner);
6887
+ if (owner.length === 0) throw new Error("buildSecretRef: owner is empty");
6888
+ if (parts.fieldPath.length === 0) throw new Error("buildSecretRef: fieldPath is empty");
6889
+ return `${SECRET_REF_SCHEME}${encodeSegment(owner)}/${formatSecretScope(parts.scope)}/${parts.fieldPath}`;
6890
+ }
6687
6891
  function parseScope(segments) {
6688
6892
  switch (segments[0]) {
6689
6893
  case "global": return {
@@ -6824,7 +7028,7 @@ async function writeMembers(ctx, children, incoming, stored, pathOf) {
6824
7028
  for (const [member, node] of children) applyMember(out, member, await writeNode(ctx, node, incoming[member], stored[member], pathOf(member)), stored);
6825
7029
  return out;
6826
7030
  }
6827
- function rowId(row, idKey) {
7031
+ function rowId$1(row, idKey) {
6828
7032
  const raw = row[idKey];
6829
7033
  if (typeof raw === "string" && raw.length > 0) return raw;
6830
7034
  if (typeof raw === "number" && Number.isFinite(raw)) return String(raw);
@@ -6841,7 +7045,7 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6841
7045
  }
6842
7046
  const storedById = /* @__PURE__ */ new Map();
6843
7047
  for (const row of storedRows) {
6844
- const id = rowId(row, node.idKey);
7048
+ const id = rowId$1(row, node.idKey);
6845
7049
  if (id !== null) storedById.set(id, row);
6846
7050
  }
6847
7051
  const kept = /* @__PURE__ */ new Set();
@@ -6851,13 +7055,13 @@ async function writeArray(ctx, node, incoming, stored, fieldPath) {
6851
7055
  rows.push(row);
6852
7056
  continue;
6853
7057
  }
6854
- const id = rowId(row, node.idKey) ?? ctx.mintId();
7058
+ const id = rowId$1(row, node.idKey) ?? ctx.mintId();
6855
7059
  kept.add(id);
6856
7060
  const withId = {
6857
7061
  ...row,
6858
7062
  [node.idKey]: row[node.idKey] ?? id
6859
7063
  };
6860
- if (rowId(withId, node.idKey) === null) withId[node.idKey] = id;
7064
+ if (rowId$1(withId, node.idKey) === null) withId[node.idKey] = id;
6861
7065
  const storedRow = storedById.get(id) ?? {};
6862
7066
  rows.push(await writeMembers(ctx, node.item, withId, storedRow, (member) => arrayItemFieldPath(fieldPath, id, member)));
6863
7067
  }
@@ -7609,7 +7813,7 @@ var BaseAddon = class {
7609
7813
  startMigration: (input) => api.startMigration.mutate(input),
7610
7814
  finishMigration: (input) => api.finishMigration.mutate(input)
7611
7815
  }, migrations, this.ctx.logger);
7612
- if (report.blockOwner.length > 0) throw new Error(`migration(s) ${report.blockOwner.join(", ")} did not apply and block this addon — fix or retry them (migrations.retry), then restart it`);
7816
+ if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7613
7817
  return report;
7614
7818
  }
7615
7819
  /**
@@ -8588,6 +8792,45 @@ function normalizeAddonInitResult(result) {
8588
8792
  if (Array.isArray(result)) return { providers: result };
8589
8793
  return result;
8590
8794
  }
8795
+ var PREFIX$1 = "records/";
8796
+ /** The base of every records failure. `detail` is the human part of the message. */
8797
+ var RecordsError = class extends Error {
8798
+ code;
8799
+ detail;
8800
+ constructor(code, detail) {
8801
+ super(`${PREFIX$1}${code}: ${detail}`);
8802
+ this.name = "RecordsError";
8803
+ this.code = code;
8804
+ this.detail = detail;
8805
+ }
8806
+ };
8807
+ /** A write guarded by `ifRev` found another revision (or an existing row for `ifRev: 0`). */
8808
+ var RevConflictError = class extends RecordsError {
8809
+ constructor(detail) {
8810
+ super("rev-conflict", detail);
8811
+ this.name = "RevConflictError";
8812
+ }
8813
+ };
8814
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
8815
+ var RecordSecretUnavailableError = class extends RecordsError {
8816
+ constructor(detail) {
8817
+ super("secret-unavailable", detail);
8818
+ this.name = "RecordSecretUnavailableError";
8819
+ }
8820
+ };
8821
+ var InvalidRecordError = class extends RecordsError {
8822
+ constructor(detail) {
8823
+ super("invalid-record", detail);
8824
+ this.name = "InvalidRecordError";
8825
+ }
8826
+ };
8827
+ /** A kind declaration the engine refuses (non-additive change, bad shape, wrong file). */
8828
+ var DeclarationRefusedError = class extends RecordsError {
8829
+ constructor(detail) {
8830
+ super("declaration-refused", detail);
8831
+ this.name = "DeclarationRefusedError";
8832
+ }
8833
+ };
8591
8834
  /** Limits and names of `ctx.records` (D881). One authority; the engine and the facade read it. */
8592
8835
  /** The files a kind may live in. `history` is device-history's (D850), never records. */
8593
8836
  var RECORD_DATABASES = ["settings", "events"];
@@ -8603,6 +8846,152 @@ var RECORD_DEFAULT_MAX_DATA_BYTES = 64 * 1024;
8603
8846
  var RECORD_MAX_DATA_BYTES = 1024 * 1024;
8604
8847
  var RECORD_BATCH_MAX = 1e3;
8605
8848
  var RECORD_QUERY_MAX = 1e3;
8849
+ /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8850
+ var RECORD_SETTINGS_MAX_ROWS = 5e4;
8851
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8852
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
8853
+ /**
8854
+ * Secret fields of a record, addressed the way a Zod schema declares them
8855
+ * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
8856
+ * (`auth.accessToken`, `headers[].value`).
8857
+ *
8858
+ * Array elements are matched by a DECLARED id key (`secretArrayKeys`:
8859
+ * `{ headers: 'name' }`), never by index, so reordering a list keeps every
8860
+ * keychain ref (the same rule as `arrayItemFieldPath`). The concrete path of a
8861
+ * leaf names its element: `headers[X-Api].value`.
8862
+ *
8863
+ * Pure and browser-safe. Nothing here mutates: every transform returns a new value.
8864
+ */
8865
+ /** The array prefixes (declared form, e.g. `headers` or `a.headers`) of a path. */
8866
+ function parseSecretPath(path) {
8867
+ if (path.length === 0) throw new InvalidRecordError("an empty secret path");
8868
+ return path.split(".").map((raw) => {
8869
+ const each = raw.endsWith("[]");
8870
+ const key = each ? raw.slice(0, -2) : raw;
8871
+ if (key.length === 0) throw new InvalidRecordError(`secret path "${path}" has an empty segment`);
8872
+ return {
8873
+ key,
8874
+ each
8875
+ };
8876
+ });
8877
+ }
8878
+ /** The declared array prefixes of `path` that need an id key (`headers`, `a.rows`). */
8879
+ function secretArrayPrefixes(path) {
8880
+ const segments = parseSecretPath(path);
8881
+ const prefixes = [];
8882
+ const walked = [];
8883
+ for (const segment of segments) {
8884
+ walked.push(segment.key);
8885
+ if (segment.each) prefixes.push(walked.join("."));
8886
+ }
8887
+ return prefixes;
8888
+ }
8889
+ function isRecord$4(value) {
8890
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8891
+ }
8892
+ function elementId(element, idKey, declared, prefix) {
8893
+ const id = isRecord$4(element) ? element[idKey] : void 0;
8894
+ if (typeof id !== "string" || id.length === 0) throw new InvalidRecordError(`"${declared}": every element of "${prefix}" needs a non-empty string "${idKey}" to carry a secret`);
8895
+ return id;
8896
+ }
8897
+ /**
8898
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
8899
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
8900
+ * result is a new body, `data` is untouched.
8901
+ */
8902
+ var REMOVE_LEAF = Symbol("remove-leaf");
8903
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
8904
+ if (!isRecord$4(node)) return node;
8905
+ const segment = segments[index];
8906
+ if (segment === void 0) return node;
8907
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
8908
+ const child = node[segment.key];
8909
+ const keys = [...walkedKeys, segment.key];
8910
+ const last = index === segments.length - 1;
8911
+ if (segment.each) {
8912
+ if (!Array.isArray(child)) return node;
8913
+ const prefix = keys.join(".");
8914
+ const idKey = arrayKeys[prefix];
8915
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
8916
+ const mapped = child.map((element) => {
8917
+ const id = elementId(element, idKey, declared, prefix);
8918
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
8919
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
8920
+ });
8921
+ return {
8922
+ ...node,
8923
+ [segment.key]: mapped
8924
+ };
8925
+ }
8926
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
8927
+ if (last) {
8928
+ const replacement = visit({
8929
+ declared,
8930
+ concrete,
8931
+ value: child
8932
+ });
8933
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
8934
+ return {
8935
+ ...node,
8936
+ [segment.key]: replacement
8937
+ };
8938
+ }
8939
+ return {
8940
+ ...node,
8941
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
8942
+ };
8943
+ }
8944
+ /** Replace/remove every present secret leaf; returns a NEW body. */
8945
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
8946
+ let current = data;
8947
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
8948
+ return current;
8949
+ }
8950
+ /**
8951
+ * The keychain collection name a kind's secrets live under. Prefixed so a
8952
+ * record's refs never collide with the refs a legacy collection of the same name
8953
+ * already holds during an adoption.
8954
+ */
8955
+ function recordSecretCollection(kind) {
8956
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
8957
+ }
8958
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
8959
+ function recordSecretRef(owner, kind, rowId, concretePath) {
8960
+ return buildSecretRef({
8961
+ owner,
8962
+ scope: {
8963
+ kind: "row",
8964
+ collection: recordSecretCollection(kind),
8965
+ rowId
8966
+ },
8967
+ fieldPath: concretePath
8968
+ });
8969
+ }
8970
+ /**
8971
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
8972
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
8973
+ * token. The form hands it to the secret field, which reveals the value by ref
8974
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
8975
+ * stored secret (the records door reads a view as KEEP).
8976
+ *
8977
+ * ONE implementation for the entries service and for every addon that serves
8978
+ * its own instances (`RecordIntegrationInstances`).
8979
+ */
8980
+ function isRecord$3(value) {
8981
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8982
+ }
8983
+ function secretViewsOf(owner, kind, id, decl, data) {
8984
+ if (decl.secretPaths.length === 0) return data;
8985
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
8986
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
8987
+ return {
8988
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
8989
+ v: 1,
8990
+ set: true
8991
+ };
8992
+ });
8993
+ return isRecord$3(shown) ? shown : data;
8994
+ }
8606
8995
  /**
8607
8996
  * The share-view scope kinds a share-link token can carry. The hub mints
8608
8997
  * and validates them (`ShareViewGrantSchema` builds its
@@ -8627,6 +9016,73 @@ var PeerBytesTicketSchema = object({
8627
9016
  */
8628
9017
  declaredBytes: number().int().nonnegative().nullable()
8629
9018
  });
9019
+ function defOf(schema) {
9020
+ const zodBag = Reflect.get(schema, "_zod");
9021
+ if (typeof zodBag !== "object" || zodBag === null) return {};
9022
+ const def = Reflect.get(zodBag, "def");
9023
+ if (typeof def !== "object" || def === null) return {};
9024
+ return def;
9025
+ }
9026
+ function declaredHere(schema) {
9027
+ return globalRegistry.get(schema)?.secret === true;
9028
+ }
9029
+ /** Wrapper kinds whose `innerType` is the field itself. */
9030
+ var WRAPPERS = new Set([
9031
+ "optional",
9032
+ "nullable",
9033
+ "default",
9034
+ "prefault",
9035
+ "catch",
9036
+ "readonly",
9037
+ "nonoptional"
9038
+ ]);
9039
+ /**
9040
+ * The schema layers that make up ONE field: the schema itself and every
9041
+ * wrapper below it (optional / default / nullable / readonly / catch), plus
9042
+ * both sides of a pipe (`z.preprocess` puts the real schema on `out`,
9043
+ * `.transform` on `in`).
9044
+ */
9045
+ function layersOf(schema) {
9046
+ const out = [];
9047
+ const queue = [schema];
9048
+ while (queue.length > 0) {
9049
+ const s = queue.shift();
9050
+ if (!s || out.includes(s)) continue;
9051
+ out.push(s);
9052
+ const def = defOf(s);
9053
+ if (def.type !== void 0 && WRAPPERS.has(def.type) && def.innerType) queue.push(def.innerType);
9054
+ if (def.type === "pipe") {
9055
+ if (def.in) queue.push(def.in);
9056
+ if (def.out) queue.push(def.out);
9057
+ }
9058
+ }
9059
+ return out;
9060
+ }
9061
+ /** True when any layer of this field declares `.meta({ secret: true })`. */
9062
+ function isZodSecret(schema) {
9063
+ return layersOf(schema).some(declaredHere);
9064
+ }
9065
+ /**
9066
+ * Every declared secret path in a config schema: dotted keys, `[]` for "each
9067
+ * element of this array" (`connection.password`, `rows[].token`). A declared
9068
+ * object or array is reported as one path and not descended into — everything
9069
+ * under it is secret.
9070
+ */
9071
+ function collectZodSecretPaths(schema, prefix = "") {
9072
+ if (isZodSecret(schema)) return prefix.length > 0 ? [prefix] : [];
9073
+ const paths = [];
9074
+ for (const layer of layersOf(schema)) {
9075
+ const def = defOf(layer);
9076
+ if (def.type === "object" && def.shape) for (const [key, child] of Object.entries(def.shape)) paths.push(...collectZodSecretPaths(child, prefix ? `${prefix}.${key}` : key));
9077
+ else if (def.type === "array" && def.element) paths.push(...collectZodSecretPaths(def.element, `${prefix}[]`));
9078
+ else if (def.type === "union" && def.options) for (const option of def.options) paths.push(...collectZodSecretPaths(option, prefix));
9079
+ else if (def.type === "intersection") {
9080
+ if (def.left) paths.push(...collectZodSecretPaths(def.left, prefix));
9081
+ if (def.right) paths.push(...collectZodSecretPaths(def.right, prefix));
9082
+ }
9083
+ }
9084
+ return [...new Set(paths)];
9085
+ }
8630
9086
  /**
8631
9087
  * Record kinds (D881): the declaration an addon makes of one kind of fact, the
8632
9088
  * Zod row schema that describes it, and the helper that turns the two into the
@@ -8693,6 +9149,110 @@ var RecordKindDeclarationSchema = object({
8693
9149
  }).strict();
8694
9150
  /** The kind names: lower-case, dash separated, short enough for an index name. */
8695
9151
  var RecordKindNameSchema = string().regex(/^[a-z][a-z0-9-]{0,47}$/);
9152
+ /** Cross-field rules a declaration must satisfy. Throws {@link DeclarationRefusedError}. */
9153
+ function assertValidDeclaration(name, decl) {
9154
+ const refuse = (why) => {
9155
+ throw new DeclarationRefusedError(`kind "${name}": ${why}`);
9156
+ };
9157
+ if (!RecordKindNameSchema.safeParse(name).success) refuse("the name must be lower-case-dashed");
9158
+ const seen = /* @__PURE__ */ new Set();
9159
+ for (const index of decl.indexes) {
9160
+ if (seen.has(index.name)) refuse(`index name "${index.name}" is declared twice`);
9161
+ seen.add(index.name);
9162
+ }
9163
+ const { retention } = decl;
9164
+ const hasSecrets = decl.secretPaths.length > 0;
9165
+ if ("ttlMs" in retention) {
9166
+ if (retention.from === "at" && decl.at !== "required") refuse("a ttl from \"at\" needs at: \"required\"");
9167
+ if (hasSecrets) refuse("a kind with secret fields cannot use engine TTL (its keychain values would be orphaned)");
9168
+ }
9169
+ if ("maxRows" in retention || "maxRowsPerDevice" in retention) {
9170
+ if (retention.maxRowsPerDevice !== void 0 && decl.device !== "required") refuse("maxRowsPerDevice needs device: \"required\"");
9171
+ if (decl.at !== "required") refuse("a row bound trims the oldest \"at\": it needs at: \"required\"");
9172
+ if (hasSecrets) refuse("a kind with secret fields cannot use an engine row bound");
9173
+ const bound = Math.max(retention.maxRows ?? 0, retention.maxRowsPerDevice ?? 0);
9174
+ if (decl.database === "settings" && bound > 5e4) refuse(`a row bound above ${RECORD_SETTINGS_MAX_ROWS} belongs in database: "events" (a big delete on the settings thread stalls every configuration read)`);
9175
+ }
9176
+ if (decl.deviceRemoval === "delete" && decl.device === "none") refuse("deviceRemoval: \"delete\" needs a device: \"required\" or \"optional\"");
9177
+ for (const path of decl.secretPaths) for (const prefix of secretArrayPrefixes(path)) if (decl.secretArrayKeys[prefix] === void 0) refuse(`secret path "${path}" crosses the array "${prefix}": declare its id key in secretArrayKeys`);
9178
+ }
9179
+ function bodyFieldsOf(schema) {
9180
+ return { ...toJSONSchema(schema, {
9181
+ unrepresentable: "any",
9182
+ io: "input"
9183
+ }) };
9184
+ }
9185
+ function isRecordLike(value) {
9186
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9187
+ }
9188
+ /** Does every branch of the body schema carry `field`? (A discriminated union has several.) */
9189
+ function hasNameField(json, field) {
9190
+ const branches = json["oneOf"] ?? json["anyOf"];
9191
+ if (Array.isArray(branches)) return branches.length > 0 && branches.every((b) => isRecordLike(b) && hasNameField(b, field));
9192
+ const properties = json["properties"];
9193
+ return isRecordLike(properties) && Object.prototype.hasOwnProperty.call(properties, field);
9194
+ }
9195
+ /**
9196
+ * Declare the kinds of a package. The keys are the kind names. The result is
9197
+ * what `ctx.records.declare` sends to the engine and what `ctx.records.kind`
9198
+ * types its handle from.
9199
+ */
9200
+ function defineRecordKinds(specs) {
9201
+ const out = {};
9202
+ for (const [name, spec] of Object.entries(specs)) {
9203
+ const secretPaths = collectZodSecretPaths(spec.schema);
9204
+ const nameField = spec.entry?.nameField ?? "name";
9205
+ const fields = bodyFieldsOf(spec.schema);
9206
+ if (spec.entry !== void 0 && !hasNameField(fields, nameField)) throw new DeclarationRefusedError(`kind "${name}": an entry kind's schema needs a "${nameField}" field`);
9207
+ const parsed = RecordKindDeclarationSchema.parse({
9208
+ database: spec.database,
9209
+ class: spec.class,
9210
+ writeTrigger: spec.writeTrigger,
9211
+ device: spec.device,
9212
+ at: spec.at,
9213
+ indexes: spec.indexes === void 0 ? void 0 : [...spec.indexes],
9214
+ retention: spec.retention,
9215
+ deviceRemoval: spec.deviceRemoval,
9216
+ maxDataBytes: spec.maxDataBytes,
9217
+ secretPaths: [...secretPaths],
9218
+ secretArrayKeys: spec.secretArrayKeys === void 0 ? void 0 : { ...spec.secretArrayKeys },
9219
+ transactFamily: spec.transactFamily,
9220
+ entry: spec.entry === void 0 ? void 0 : {
9221
+ title: spec.entry.title,
9222
+ nameField,
9223
+ fields
9224
+ }
9225
+ });
9226
+ assertValidDeclaration(name, parsed);
9227
+ out[name] = {
9228
+ name,
9229
+ schema: spec.schema,
9230
+ declaration: parsed
9231
+ };
9232
+ }
9233
+ return out;
9234
+ }
9235
+ /**
9236
+ * Declare one entry kind. An entry is configuration: never trimmed by the
9237
+ * engine, never aged, belonging to no device.
9238
+ */
9239
+ function defineEntryKind(name, spec) {
9240
+ const defined = defineRecordKinds({ [name]: {
9241
+ schema: spec.schema,
9242
+ class: "config",
9243
+ writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
9244
+ retention: { none: "an entry goes only when the operator deletes it" },
9245
+ ...spec.database === void 0 ? {} : { database: spec.database },
9246
+ ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
9247
+ ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
9248
+ entry: {
9249
+ title: spec.title,
9250
+ ...spec.nameField === void 0 ? {} : { nameField: spec.nameField }
9251
+ }
9252
+ } })[name];
9253
+ if (defined === void 0) throw new DeclarationRefusedError(`entry kind "${name}" was not built`);
9254
+ return defined;
9255
+ }
8696
9256
  object({
8697
9257
  field: string().min(1),
8698
9258
  on: literal("advance")
@@ -11368,7 +11928,7 @@ object({
11368
11928
  params: record(string(), union([string(), number()])).optional()
11369
11929
  });
11370
11930
  //#endregion
11371
- //#region ../types/dist/composition-Dh3RfMx5.mjs
11931
+ //#region ../types/dist/composition-BodkvOV0.mjs
11372
11932
  /**
11373
11933
  * The ffmpeg build every CamStack node downloads, per platform and arch.
11374
11934
  *
@@ -12505,7 +13065,14 @@ var CompositionForwardCommandSchema = object({
12505
13065
  method: string().min(1),
12506
13066
  args: record(string().min(1), CompositionForwardArgSchema).optional()
12507
13067
  });
12508
- var CompositionCommandTargetSchema = discriminatedUnion("kind", [CompositionForwardCommandSchema, CompositionCodeSourceSchema]);
13068
+ var CompositionCommandTargetSchema = discriminatedUnion("kind", [
13069
+ CompositionForwardCommandSchema,
13070
+ CompositionCodeSourceSchema,
13071
+ object({
13072
+ kind: literal("extension"),
13073
+ target: literal("remote")
13074
+ })
13075
+ ]);
12509
13076
  /** An item key inside an item-array cap (`consumables.items[<key>]`). */
12510
13077
  var COMPOSITION_ITEM_KEY_RE = /^[a-z0-9][a-z0-9-]{0,47}$/;
12511
13078
  /**
@@ -12885,6 +13452,144 @@ function buildCapturingReply(envelope) {
12885
13452
  };
12886
13453
  return wrapper;
12887
13454
  }
13455
+ /** The most instances one addon lists (an integrations page, not a table). */
13456
+ var INSTANCES_LIST_MAX = 1e3;
13457
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
13458
+ function topLevelSecretKeys(paths) {
13459
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[")));
13460
+ }
13461
+ var RecordIntegrationInstances = class {
13462
+ records;
13463
+ kind;
13464
+ hooks;
13465
+ handle;
13466
+ secretKeys;
13467
+ nameField;
13468
+ constructor(records, kind, hooks) {
13469
+ this.records = records;
13470
+ this.kind = kind;
13471
+ this.hooks = hooks;
13472
+ this.handle = records.kind(kind);
13473
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
13474
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
13475
+ }
13476
+ /**
13477
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
13478
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
13479
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
13480
+ */
13481
+ async readResolved(id) {
13482
+ try {
13483
+ const record = await this.handle.getResolved(id);
13484
+ return record === null ? null : {
13485
+ id,
13486
+ body: record.data,
13487
+ enabled: record.data.enabled !== false,
13488
+ secrets: "resolved"
13489
+ };
13490
+ } catch (err) {
13491
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
13492
+ const stored = await this.handle.get(id);
13493
+ if (stored === null) return null;
13494
+ return {
13495
+ id,
13496
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
13497
+ enabled: stored.data.enabled !== false,
13498
+ secrets: "unavailable"
13499
+ };
13500
+ }
13501
+ }
13502
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
13503
+ async getResolved(id) {
13504
+ return (await this.readResolved(id))?.body ?? null;
13505
+ }
13506
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
13507
+ async listResolved() {
13508
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
13509
+ const out = [];
13510
+ for (const record of page.records) {
13511
+ const read = await this.readResolved(record.id);
13512
+ if (read !== null) out.push(read);
13513
+ }
13514
+ return out;
13515
+ }
13516
+ viewOf(record) {
13517
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
13518
+ const rawName = record.data[this.nameField];
13519
+ return {
13520
+ id: record.id,
13521
+ name: typeof rawName === "string" ? rawName : record.id,
13522
+ configured: this.hooks.configured(record.data),
13523
+ enabled: record.data.enabled !== false,
13524
+ formValues: shown
13525
+ };
13526
+ }
13527
+ describe = async () => this.hooks.description;
13528
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
13529
+ listInstances = async () => {
13530
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
13531
+ };
13532
+ getInstance = async ({ id }) => {
13533
+ const record = await this.handle.get(id);
13534
+ return record === null ? null : this.viewOf(record);
13535
+ };
13536
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
13537
+ createInstance = async ({ id, name }) => {
13538
+ await this.handle.put({
13539
+ id,
13540
+ data: this.hooks.initialBody(name)
13541
+ }, { ifRev: 0 });
13542
+ await this.hooks.onChanged?.(id);
13543
+ return { id };
13544
+ };
13545
+ updateInstance = async ({ id, name, values }) => {
13546
+ const patch = {};
13547
+ for (const [key, value] of Object.entries(values)) {
13548
+ if (value === void 0) continue;
13549
+ if (!this.secretKeys.has(key)) patch[key] = value;
13550
+ else if (isSecretClear(value)) patch[key] = null;
13551
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
13552
+ }
13553
+ if (name !== void 0) patch[this.nameField] = name;
13554
+ await this.handle.patch(id, patch);
13555
+ await this.hooks.onChanged?.(id);
13556
+ return { ok: true };
13557
+ };
13558
+ /** The switch lives in the record body; the addon is told so it applies it (D996). */
13559
+ setInstanceEnabled = async ({ id, enabled }) => {
13560
+ await this.handle.patch(id, { enabled });
13561
+ await this.hooks.onChanged?.(id);
13562
+ return { ok: true };
13563
+ };
13564
+ /** The row and its keychain refs go together (the records door). */
13565
+ deleteInstance = async ({ id }) => {
13566
+ await this.handle.delete(id);
13567
+ await this.hooks.onChanged?.(id);
13568
+ return { ok: true };
13569
+ };
13570
+ testInstance = async (input) => {
13571
+ if (this.hooks.test === void 0) return {
13572
+ success: false,
13573
+ status: "unsupported",
13574
+ error: "This integration declares no connection test"
13575
+ };
13576
+ return this.hooks.test(input);
13577
+ };
13578
+ /** The flat provider object to hand to `registerProvider`. */
13579
+ toProvider() {
13580
+ return {
13581
+ describe: this.describe,
13582
+ instanceFormSchema: this.instanceFormSchema,
13583
+ listInstances: this.listInstances,
13584
+ getInstance: this.getInstance,
13585
+ createInstance: this.createInstance,
13586
+ updateInstance: this.updateInstance,
13587
+ setInstanceEnabled: this.setInstanceEnabled,
13588
+ deleteInstance: this.deleteInstance,
13589
+ testInstance: this.testInstance
13590
+ };
13591
+ }
13592
+ };
12888
13593
  var EncodeProfileSchema = object({
12889
13594
  video: object({
12890
13595
  codec: _enum([
@@ -19309,6 +20014,48 @@ var APPLIANCE_CAP_VOCABULARY = {
19309
20014
  scope: "device",
19310
20015
  noun: t("Media player", "Lettore multimediale"),
19311
20016
  actions: [
20017
+ {
20018
+ id: "media.turnOn",
20019
+ method: "turnOn",
20020
+ label: t("Turn on", "Accendi"),
20021
+ phrase: t("Turn on {device}", "Accendi {device}"),
20022
+ icon: "power"
20023
+ },
20024
+ {
20025
+ id: "media.turnOff",
20026
+ method: "turnOff",
20027
+ label: t("Turn off", "Spegni"),
20028
+ phrase: t("Turn off {device}", "Spegni {device}"),
20029
+ icon: "power"
20030
+ },
20031
+ {
20032
+ id: "media.volumeUp",
20033
+ method: "volumeUp",
20034
+ label: t("Volume up", "Alza il volume"),
20035
+ phrase: t("Raise the volume of {device}", "Alza il volume di {device}"),
20036
+ icon: "volume-2"
20037
+ },
20038
+ {
20039
+ id: "media.volumeDown",
20040
+ method: "volumeDown",
20041
+ label: t("Volume down", "Abbassa il volume"),
20042
+ phrase: t("Lower the volume of {device}", "Abbassa il volume di {device}"),
20043
+ icon: "volume-2"
20044
+ },
20045
+ {
20046
+ id: "media.channelUp",
20047
+ method: "channelUp",
20048
+ label: t("Channel up", "Canale successivo"),
20049
+ phrase: t("Go to the next channel on {device}", "Passa al canale successivo su {device}"),
20050
+ icon: "skip-forward"
20051
+ },
20052
+ {
20053
+ id: "media.channelDown",
20054
+ method: "channelDown",
20055
+ label: t("Channel down", "Canale precedente"),
20056
+ phrase: t("Go to the previous channel on {device}", "Torna al canale precedente su {device}"),
20057
+ icon: "skip-back"
20058
+ },
19312
20059
  {
19313
20060
  id: "media.play",
19314
20061
  method: "play",
@@ -47885,6 +48632,188 @@ DeviceType.Control, method(object({
47885
48632
  kind: "mutation",
47886
48633
  auth: "protected"
47887
48634
  });
48635
+ /**
48636
+ * Media-player cap. Models HA `media_player.*` (Sonos, Chromecast,
48637
+ * Apple TV, Spotify, Roku, generic OTT receivers, …) on
48638
+ * `DeviceType.MediaPlayer`. Disjoint from the camera streaming
48639
+ * surface — those use `DeviceType.Camera` + the broker pipeline.
48640
+ *
48641
+ * The cap declares a wide method surface; not every backend supports
48642
+ * every method. Drivers signal sub-capability via the
48643
+ * `DeviceFeature.MediaPlayerXxx` flags (paired one-to-one with the
48644
+ * corresponding method) so the UI gates buttons without a slice
48645
+ * fetch — same pattern as `PanTiltZoom` for cameras.
48646
+ */
48647
+ var MediaPlayerStateSchema = _enum([
48648
+ "off",
48649
+ "on",
48650
+ "idle",
48651
+ "playing",
48652
+ "paused",
48653
+ "buffering",
48654
+ "standby"
48655
+ ]);
48656
+ var MediaPlayerRepeatSchema = _enum([
48657
+ "off",
48658
+ "all",
48659
+ "one"
48660
+ ]);
48661
+ var MediaInfoSchema = object({
48662
+ /** Free-form media kind (`music`, `tvshow`, `movie`, `app`, `channel`,
48663
+ * `podcast`, …). */
48664
+ type: string(),
48665
+ /** Human-readable title. */
48666
+ title: string(),
48667
+ /** Optional artist / channel / station label. */
48668
+ artist: string().optional(),
48669
+ /** Optional album / season / show name. */
48670
+ album: string().optional(),
48671
+ /** Optional cover-art / thumbnail URL. */
48672
+ imageUrl: string().optional()
48673
+ });
48674
+ /**
48675
+ * Where `state`, `volumeLevel`, `isMuted` and `source` come from. `reported`:
48676
+ * the device said so. `assumed`: the driver has no feedback (infrared) and
48677
+ * tracks what it last SENT; it moves only after a send was accepted, and a
48678
+ * human at the real remote makes it wrong. A UI shows an assumed value as a
48679
+ * guess, never as a reading.
48680
+ */
48681
+ var MediaPlayerStateSourceSchema = _enum(["reported", "assumed"]);
48682
+ /** The fields of a media-player status a driver can only guess. */
48683
+ var MediaPlayerAssumedFieldSchema = _enum([
48684
+ "state",
48685
+ "volumeLevel",
48686
+ "isMuted",
48687
+ "source"
48688
+ ]);
48689
+ var MediaPlayerStatusSchema = object({
48690
+ /** Playback lifecycle state. */
48691
+ state: MediaPlayerStateSchema,
48692
+ /**
48693
+ * Whether the state fields are readings or the driver's own bookkeeping.
48694
+ * A slice written before this field existed parses as `reported`.
48695
+ */
48696
+ stateSource: MediaPlayerStateSourceSchema.default("reported"),
48697
+ /**
48698
+ * Which fields are the driver's own guess. `stateSource` is `assumed` when
48699
+ * this is not empty; a field not listed here is a reading even then (power
48700
+ * from a running-state source, mute guessed from the last send).
48701
+ */
48702
+ assumedFields: array(MediaPlayerAssumedFieldSchema).default([]),
48703
+ /** Volume as 0..100 inclusive. Null when the device has no volume
48704
+ * surface. Pair with `DeviceFeature.MediaPlayerVolume`. */
48705
+ volumeLevel: number().min(0).max(100).nullable().meta(readingMeta("percentage")),
48706
+ /** Mute toggle distinct from volume=0. Null when no mute surface.
48707
+ * Pair with `DeviceFeature.MediaPlayerMute`. */
48708
+ isMuted: boolean().nullable(),
48709
+ /** Active source / input. Empty when no source surface. */
48710
+ source: string(),
48711
+ /** Selectable sources. Empty when no source surface.
48712
+ * Pair with `DeviceFeature.MediaPlayerSelectSource`. */
48713
+ availableSources: array(string()),
48714
+ /** Currently-playing media info. Null when nothing is playing. */
48715
+ currentMedia: MediaInfoSchema.nullable(),
48716
+ /** Current playback position in ms. Null when not seekable or
48717
+ * nothing is playing. Pair with `DeviceFeature.MediaPlayerSeek`. */
48718
+ position: number().int().nonnegative().nullable().meta(readingMeta("duration-ms")),
48719
+ /** Total duration of the current media in ms. Null when unknown
48720
+ * (live stream) or nothing is playing. */
48721
+ duration: number().int().nonnegative().nullable().meta(readingMeta("duration-ms")),
48722
+ /** Shuffle toggle. Null when no shuffle surface.
48723
+ * Pair with `DeviceFeature.MediaPlayerShuffle`. */
48724
+ shuffle: boolean().nullable(),
48725
+ /** Repeat mode. Null when no repeat surface.
48726
+ * Pair with `DeviceFeature.MediaPlayerRepeat`. */
48727
+ repeat: MediaPlayerRepeatSchema.nullable(),
48728
+ /** Ms epoch when the slice was last updated. */
48729
+ lastChangedAt: number()
48730
+ });
48731
+ var stepInput = object({
48732
+ deviceId: number().int().nonnegative(),
48733
+ /** How many presses: the caller's count (Alexa `volumeSteps`, `channelCount`). */
48734
+ steps: number().int().min(1).max(50).default(1)
48735
+ });
48736
+ var deviceOnly = object({ deviceId: number().int().nonnegative() });
48737
+ DeviceType.MediaPlayer, method(deviceOnly, _void(), {
48738
+ kind: "mutation",
48739
+ auth: "protected"
48740
+ }), method(deviceOnly, _void(), {
48741
+ kind: "mutation",
48742
+ auth: "protected"
48743
+ }), method(stepInput, _void(), {
48744
+ kind: "mutation",
48745
+ auth: "protected"
48746
+ }), method(stepInput, _void(), {
48747
+ kind: "mutation",
48748
+ auth: "protected"
48749
+ }), method(stepInput, _void(), {
48750
+ kind: "mutation",
48751
+ auth: "protected"
48752
+ }), method(stepInput, _void(), {
48753
+ kind: "mutation",
48754
+ auth: "protected"
48755
+ }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
48756
+ kind: "mutation",
48757
+ auth: "protected"
48758
+ }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
48759
+ kind: "mutation",
48760
+ auth: "protected"
48761
+ }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
48762
+ kind: "mutation",
48763
+ auth: "protected"
48764
+ }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
48765
+ kind: "mutation",
48766
+ auth: "protected"
48767
+ }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
48768
+ kind: "mutation",
48769
+ auth: "protected"
48770
+ }), method(object({
48771
+ deviceId: number().int().nonnegative(),
48772
+ position: number().int().nonnegative()
48773
+ }), _void(), {
48774
+ kind: "mutation",
48775
+ auth: "protected"
48776
+ }), method(object({
48777
+ deviceId: number().int().nonnegative(),
48778
+ volumeLevel: number().min(0).max(100)
48779
+ }), _void(), {
48780
+ kind: "mutation",
48781
+ auth: "protected"
48782
+ }), method(object({
48783
+ deviceId: number().int().nonnegative(),
48784
+ muted: boolean()
48785
+ }), _void(), {
48786
+ kind: "mutation",
48787
+ auth: "protected"
48788
+ }), method(object({
48789
+ deviceId: number().int().nonnegative(),
48790
+ shuffle: boolean()
48791
+ }), _void(), {
48792
+ kind: "mutation",
48793
+ auth: "protected"
48794
+ }), method(object({
48795
+ deviceId: number().int().nonnegative(),
48796
+ repeat: MediaPlayerRepeatSchema
48797
+ }), _void(), {
48798
+ kind: "mutation",
48799
+ auth: "protected"
48800
+ }), method(object({
48801
+ deviceId: number().int().nonnegative(),
48802
+ source: string().min(1)
48803
+ }), _void(), {
48804
+ kind: "mutation",
48805
+ auth: "protected"
48806
+ }), method(object({
48807
+ deviceId: number().int().nonnegative(),
48808
+ /** Media identifier / URL. */
48809
+ mediaId: string().min(1),
48810
+ /** Media kind (`music`, `tvshow`, `movie`, `app`, …) — provider
48811
+ * passes it through to the upstream service. */
48812
+ mediaType: string().min(1)
48813
+ }), _void(), {
48814
+ kind: "mutation",
48815
+ auth: "protected"
48816
+ });
47888
48817
  DeviceType.Camera, DeviceType.Sensor, DeviceType.Button, DeviceType.Switch, DeviceType.PetFeeder, DeviceType.Container, DeviceType.Thermostat, DeviceType.EventEmitter, DeviceType.Camera, DeviceType.Hub, DeviceType.Light, DeviceType.Siren, DeviceType.Switch, DeviceType.Sensor, DeviceType.Thermostat, DeviceType.Climate, DeviceType.Button, DeviceType.EventEmitter, DeviceType.Update, DeviceType.Generic, DeviceType.Notifier, DeviceType.Script, DeviceType.Automation, DeviceType.Lock, DeviceType.Cover, DeviceType.Valve, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.Fan, DeviceType.MediaPlayer, DeviceType.AlarmPanel, DeviceType.Control, DeviceType.Presence, DeviceType.Weather, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.Container, DeviceType.Image, DeviceType.PetFeeder, DeviceType.PetFountain, DeviceType.Dishwasher, DeviceType.Washer, DeviceType.Heater, DeviceType.Dryer, DeviceType.Gateway, DeviceType.Camera, DeviceType.Fan, DeviceType.Lock, DeviceType.Camera, DeviceType.Switch, DeviceType.Light, DeviceType.Fan, DeviceType.Climate, DeviceType.Thermostat, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.PetFeeder, DeviceType.Heater, DeviceType.Switch, DeviceType.Light, DeviceType.Fan, DeviceType.Climate, DeviceType.Thermostat, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.PetFeeder, DeviceType.Heater, DeviceType.Switch, DeviceType.Light, DeviceType.Fan, DeviceType.Climate, DeviceType.Thermostat, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.PetFeeder, DeviceType.Heater, DeviceType.Switch, DeviceType.Light, DeviceType.Fan, DeviceType.Climate, DeviceType.Thermostat, DeviceType.Humidifier, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.PetFeeder, DeviceType.Heater, DeviceType.Gateway, DeviceType.Hub, DeviceType.Camera, DeviceType.Sensor, DeviceType.MediaPlayer, DeviceType.Vacuum, DeviceType.Generic, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.PetFountain, DeviceType.Fan, DeviceType.Humidifier, DeviceType.Climate, DeviceType.WaterHeater, DeviceType.MediaPlayer, DeviceType.Washer, DeviceType.Dryer, DeviceType.Dishwasher, DeviceType.Vacuum, DeviceType.LawnMower, DeviceType.MediaPlayer, DeviceType.WaterHeater, DeviceType.Humidifier, DeviceType.Fan, DeviceType.Climate, DeviceType.Thermostat, DeviceType.PetFeeder, DeviceType.Heater;
47889
48818
  var NUMBER = {
47890
48819
  kind: "fixed",
@@ -53397,31 +54326,53 @@ var IntegrationInstancePatchSchema = object({
53397
54326
  /** Omitted / '' / redaction token keeps a secret; `{ $secretClear: true }` clears it. */
53398
54327
  values: record(string(), unknown())
53399
54328
  });
53400
- method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }), method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }), method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }), method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }), method(object({
53401
- id: IntegrationInstanceIdSchema,
53402
- name: string().min(1)
53403
- }), object({ id: string() }), {
53404
- kind: "mutation",
53405
- auth: "admin"
53406
- }), method(IntegrationInstancePatchSchema, object({ ok: literal(true) }), {
53407
- kind: "mutation",
53408
- auth: "admin"
53409
- }), method(object({
53410
- id: IntegrationInstanceIdSchema,
53411
- enabled: boolean()
53412
- }), object({ ok: literal(true) }), {
53413
- kind: "mutation",
53414
- auth: "admin"
53415
- }), method(object({ id: IntegrationInstanceIdSchema }), object({ ok: literal(true) }), {
53416
- kind: "mutation",
53417
- auth: "admin"
53418
- }), optionalMethod(object({
53419
- id: IntegrationInstanceIdSchema.nullable(),
53420
- values: record(string(), unknown())
53421
- }), TestConnectionResultSchema$1, {
53422
- kind: "mutation",
53423
- auth: "admin"
53424
- });
54329
+ var integrationInstancesCapability = {
54330
+ name: "integration-instances",
54331
+ scope: "system",
54332
+ mode: "collection",
54333
+ methods: {
54334
+ describe: method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }),
54335
+ /** The form; `id: null` is the create form. */
54336
+ instanceFormSchema: method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }),
54337
+ listInstances: method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }),
54338
+ getInstance: method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }),
54339
+ /** Insert the typed record under the given id (a duplicate id is refused). */
54340
+ createInstance: method(object({
54341
+ id: IntegrationInstanceIdSchema,
54342
+ name: string().min(1)
54343
+ }), object({ id: string() }), {
54344
+ kind: "mutation",
54345
+ auth: "admin"
54346
+ }),
54347
+ updateInstance: method(IntegrationInstancePatchSchema, object({ ok: literal(true) }), {
54348
+ kind: "mutation",
54349
+ auth: "admin"
54350
+ }),
54351
+ /**
54352
+ * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
54353
+ * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
54354
+ */
54355
+ setInstanceEnabled: method(object({
54356
+ id: IntegrationInstanceIdSchema,
54357
+ enabled: boolean()
54358
+ }), object({ ok: literal(true) }), {
54359
+ kind: "mutation",
54360
+ auth: "admin"
54361
+ }),
54362
+ /** Delete the record and its keychain refs together. */
54363
+ deleteInstance: method(object({ id: IntegrationInstanceIdSchema }), object({ ok: literal(true) }), {
54364
+ kind: "mutation",
54365
+ auth: "admin"
54366
+ }),
54367
+ testInstance: optionalMethod(object({
54368
+ id: IntegrationInstanceIdSchema.nullable(),
54369
+ values: record(string(), unknown())
54370
+ }), TestConnectionResultSchema$1, {
54371
+ kind: "mutation",
54372
+ auth: "admin"
54373
+ })
54374
+ }
54375
+ };
53425
54376
  /**
53426
54377
  * Two-way audio / talk-back cap. Clients open a WebRTC audio-only
53427
54378
  * session (server-initiated offer pattern, identical to the main
@@ -55404,164 +56355,6 @@ var LoginMethodContributionSchema = discriminatedUnion("kind", [
55404
56355
  ]);
55405
56356
  method(_void(), array(LoginMethodContributionSchema).readonly());
55406
56357
  /**
55407
- * Media-player cap. Models HA `media_player.*` (Sonos, Chromecast,
55408
- * Apple TV, Spotify, Roku, generic OTT receivers, …) on
55409
- * `DeviceType.MediaPlayer`. Disjoint from the camera streaming
55410
- * surface — those use `DeviceType.Camera` + the broker pipeline.
55411
- *
55412
- * The cap declares a wide method surface; not every backend supports
55413
- * every method. Drivers signal sub-capability via the
55414
- * `DeviceFeature.MediaPlayerXxx` flags (paired one-to-one with the
55415
- * corresponding method) so the UI gates buttons without a slice
55416
- * fetch — same pattern as `PanTiltZoom` for cameras.
55417
- */
55418
- var MediaPlayerStateSchema = _enum([
55419
- "off",
55420
- "on",
55421
- "idle",
55422
- "playing",
55423
- "paused",
55424
- "buffering",
55425
- "standby"
55426
- ]);
55427
- var MediaPlayerRepeatSchema = _enum([
55428
- "off",
55429
- "all",
55430
- "one"
55431
- ]);
55432
- var MediaInfoSchema = object({
55433
- /** Free-form media kind (`music`, `tvshow`, `movie`, `app`, `channel`,
55434
- * `podcast`, …). */
55435
- type: string(),
55436
- /** Human-readable title. */
55437
- title: string(),
55438
- /** Optional artist / channel / station label. */
55439
- artist: string().optional(),
55440
- /** Optional album / season / show name. */
55441
- album: string().optional(),
55442
- /** Optional cover-art / thumbnail URL. */
55443
- imageUrl: string().optional()
55444
- });
55445
- /**
55446
- * Where `state`, `volumeLevel`, `isMuted` and `source` come from. `reported`:
55447
- * the device said so. `assumed`: the driver has no feedback (infrared) and
55448
- * tracks what it last SENT; it moves only after a send was accepted, and a
55449
- * human at the real remote makes it wrong. A UI shows an assumed value as a
55450
- * guess, never as a reading.
55451
- */
55452
- var MediaPlayerStateSourceSchema = _enum(["reported", "assumed"]);
55453
- /** The fields of a media-player status a driver can only guess. */
55454
- var MediaPlayerAssumedFieldSchema = _enum([
55455
- "state",
55456
- "volumeLevel",
55457
- "isMuted",
55458
- "source"
55459
- ]);
55460
- object({
55461
- /** Playback lifecycle state. */
55462
- state: MediaPlayerStateSchema,
55463
- /**
55464
- * Whether the state fields are readings or the driver's own bookkeeping.
55465
- * A slice written before this field existed parses as `reported`.
55466
- */
55467
- stateSource: MediaPlayerStateSourceSchema.default("reported"),
55468
- /**
55469
- * Which fields are the driver's own guess. `stateSource` is `assumed` when
55470
- * this is not empty; a field not listed here is a reading even then (power
55471
- * from a running-state source, mute guessed from the last send).
55472
- */
55473
- assumedFields: array(MediaPlayerAssumedFieldSchema).default([]),
55474
- /** Volume as 0..100 inclusive. Null when the device has no volume
55475
- * surface. Pair with `DeviceFeature.MediaPlayerVolume`. */
55476
- volumeLevel: number().min(0).max(100).nullable().meta(readingMeta("percentage")),
55477
- /** Mute toggle distinct from volume=0. Null when no mute surface.
55478
- * Pair with `DeviceFeature.MediaPlayerMute`. */
55479
- isMuted: boolean().nullable(),
55480
- /** Active source / input. Empty when no source surface. */
55481
- source: string(),
55482
- /** Selectable sources. Empty when no source surface.
55483
- * Pair with `DeviceFeature.MediaPlayerSelectSource`. */
55484
- availableSources: array(string()),
55485
- /** Currently-playing media info. Null when nothing is playing. */
55486
- currentMedia: MediaInfoSchema.nullable(),
55487
- /** Current playback position in ms. Null when not seekable or
55488
- * nothing is playing. Pair with `DeviceFeature.MediaPlayerSeek`. */
55489
- position: number().int().nonnegative().nullable().meta(readingMeta("duration-ms")),
55490
- /** Total duration of the current media in ms. Null when unknown
55491
- * (live stream) or nothing is playing. */
55492
- duration: number().int().nonnegative().nullable().meta(readingMeta("duration-ms")),
55493
- /** Shuffle toggle. Null when no shuffle surface.
55494
- * Pair with `DeviceFeature.MediaPlayerShuffle`. */
55495
- shuffle: boolean().nullable(),
55496
- /** Repeat mode. Null when no repeat surface.
55497
- * Pair with `DeviceFeature.MediaPlayerRepeat`. */
55498
- repeat: MediaPlayerRepeatSchema.nullable(),
55499
- /** Ms epoch when the slice was last updated. */
55500
- lastChangedAt: number()
55501
- });
55502
- DeviceType.MediaPlayer, method(object({ deviceId: number().int().nonnegative() }), _void(), {
55503
- kind: "mutation",
55504
- auth: "protected"
55505
- }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
55506
- kind: "mutation",
55507
- auth: "protected"
55508
- }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
55509
- kind: "mutation",
55510
- auth: "protected"
55511
- }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
55512
- kind: "mutation",
55513
- auth: "protected"
55514
- }), method(object({ deviceId: number().int().nonnegative() }), _void(), {
55515
- kind: "mutation",
55516
- auth: "protected"
55517
- }), method(object({
55518
- deviceId: number().int().nonnegative(),
55519
- position: number().int().nonnegative()
55520
- }), _void(), {
55521
- kind: "mutation",
55522
- auth: "protected"
55523
- }), method(object({
55524
- deviceId: number().int().nonnegative(),
55525
- volumeLevel: number().min(0).max(100)
55526
- }), _void(), {
55527
- kind: "mutation",
55528
- auth: "protected"
55529
- }), method(object({
55530
- deviceId: number().int().nonnegative(),
55531
- muted: boolean()
55532
- }), _void(), {
55533
- kind: "mutation",
55534
- auth: "protected"
55535
- }), method(object({
55536
- deviceId: number().int().nonnegative(),
55537
- shuffle: boolean()
55538
- }), _void(), {
55539
- kind: "mutation",
55540
- auth: "protected"
55541
- }), method(object({
55542
- deviceId: number().int().nonnegative(),
55543
- repeat: MediaPlayerRepeatSchema
55544
- }), _void(), {
55545
- kind: "mutation",
55546
- auth: "protected"
55547
- }), method(object({
55548
- deviceId: number().int().nonnegative(),
55549
- source: string().min(1)
55550
- }), _void(), {
55551
- kind: "mutation",
55552
- auth: "protected"
55553
- }), method(object({
55554
- deviceId: number().int().nonnegative(),
55555
- /** Media identifier / URL. */
55556
- mediaId: string().min(1),
55557
- /** Media kind (`music`, `tvshow`, `movie`, `app`, …) — provider
55558
- * passes it through to the upstream service. */
55559
- mediaType: string().min(1)
55560
- }), _void(), {
55561
- kind: "mutation",
55562
- auth: "protected"
55563
- });
55564
- /**
55565
56358
  * mesh-network — collection cap for mesh-VPN providers.
55566
56359
  *
55567
56360
  * Different shape from `network-access` (public tunnels):
@@ -63854,6 +64647,21 @@ var NcTemplateVarKindSchema = _enum([
63854
64647
  "sound",
63855
64648
  "system"
63856
64649
  ]);
64650
+ /**
64651
+ * The default title/body a rule of one SITUATION is delivered with when the
64652
+ * operator wrote no template — served so an editor can pre-fill it (and the
64653
+ * operator can rebuild it from placeholders) instead of starting from a blank
64654
+ * box that, once saved, silently replaces it. `id` names the situation inside
64655
+ * a rule `kind`: `appliance-cycle` is a `sensor` rule whose device is an
64656
+ * appliance finishing a cycle. Texts are raw templates (`{{var}}` intact), in
64657
+ * the hub's current language and with its overrides applied.
64658
+ */
64659
+ var NcTemplateDefaultSchema = object({
64660
+ id: _enum(["appliance-cycle"]),
64661
+ kind: NcRuleKindSchema,
64662
+ title: string(),
64663
+ body: string()
64664
+ });
63857
64665
  /** Which producer renders a template: an ordinary rule, a timelapse, a digest. */
63858
64666
  var NcTemplateFamilySchema = _enum([
63859
64667
  "rule",
@@ -64709,7 +65517,11 @@ method(object({}), object({ rules: array(NcRuleSchema) }), { auth: "admin" }), m
64709
65517
  }), method(object({}), object({
64710
65518
  catalog: array(NcConditionDescriptorSchema),
64711
65519
  taxonomy: NcTaxonomySchema.optional()
64712
- })), method(object({}), object({ vars: array(NcTemplateVarDescriptorSchema) })), method(NcTemplatePreviewInputSchema, NcTemplatePreviewSchema, {
65520
+ })), method(object({}), object({
65521
+ vars: array(NcTemplateVarDescriptorSchema),
65522
+ /** Per-situation default texts; absent on a hub that predates them. */
65523
+ defaults: array(NcTemplateDefaultSchema)
65524
+ })), method(NcTemplatePreviewInputSchema, NcTemplatePreviewSchema, {
64713
65525
  kind: "mutation",
64714
65526
  access: "view"
64715
65527
  }), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" }), method(object({}), NcRuleLastRunsSchema, { auth: "admin" }), method(object({ artifactId: string().min(1) }), object({ url: string().nullable() }), { auth: "admin" }), method(object({}), object({ snoozes: array(NcSnoozeSchema) }), { caller: "required" }), method(object({ snooze: NcSnoozeInputSchema }), object({ snooze: NcSnoozeSchema }), {
@@ -70197,7 +71009,13 @@ var RemoteMediaCommandSchema = _enum([
70197
71009
  "next",
70198
71010
  "previous",
70199
71011
  "setMute",
70200
- "selectSource"
71012
+ "selectSource",
71013
+ "turnOn",
71014
+ "turnOff",
71015
+ "volumeUp",
71016
+ "volumeDown",
71017
+ "channelUp",
71018
+ "channelDown"
70201
71019
  ]);
70202
71020
  /** A send result, or `not-routed`: the role is not bound, so the native cap answers. */
70203
71021
  var RemoteMediaCommandResultSchema = discriminatedUnion("status", [...RemoteSendResultSchema.options, object({ status: literal("not-routed") })]);
@@ -70218,7 +71036,7 @@ method(deviceInput, RemoteConfigSchema, { auth: "admin" }), method(deviceInput.e
70218
71036
  }), RemoteSendResultSchema, {
70219
71037
  kind: "mutation",
70220
71038
  auth: "protected"
70221
- }), method(deviceInput.extend({
71039
+ }), method(deviceInput, MediaPlayerStatusSchema.nullable(), { auth: "protected" }), method(deviceInput.extend({
70222
71040
  command: RemoteMediaCommandSchema,
70223
71041
  muted: boolean().optional(),
70224
71042
  source: string().optional(),
@@ -72053,7 +72871,11 @@ Object.values(DeviceType), method(_void(), array(StreamSignalSchema).readonly())
72053
72871
  * `getSettingsUISchema()` surface.
72054
72872
  */
72055
72873
  var SwitchStatusSchema = object({
72056
- on: boolean().meta({ label: "On" }),
72874
+ /**
72875
+ * `null` = the device has never reported its state (a measurement that
72876
+ * has not happened is unknown, never `false`).
72877
+ */
72878
+ on: boolean().nullable().meta({ label: "On" }),
72057
72879
  /** Ms epoch of the last state change. Useful for UI "X minutes ago". */
72058
72880
  lastChangedAt: number()
72059
72881
  });
@@ -72065,7 +72887,7 @@ DeviceType.Switch, DeviceType.Siren, DeviceType.Light, DeviceType.Fan, DeviceTyp
72065
72887
  auth: "protected"
72066
72888
  }), object({
72067
72889
  deviceId: number(),
72068
- on: boolean(),
72890
+ on: boolean().nullable(),
72069
72891
  lastChangedAt: number()
72070
72892
  });
72071
72893
  /** C0 controls, DEL and the C1 range: none of them belongs in a name. */
@@ -75089,6 +75911,7 @@ function buildDescriptor(capName, kind) {
75089
75911
  * contributes one entry per bound cap present in this map.
75090
75912
  */
75091
75913
  var EVENT_KIND_BY_CAP = Object.freeze(Object.fromEntries(Object.entries(CAP_TO_KIND).map(([capName, kind]) => [capName, buildDescriptor(capName, kind)])));
75914
+ DeviceFeature.MediaPlayerPower, DeviceFeature.MediaPlayerVolumeStep, DeviceFeature.MediaPlayerChannelStep, DeviceFeature.MediaPlayerMute, DeviceFeature.MediaPlayerStop, DeviceFeature.MediaPlayerNext, DeviceFeature.MediaPlayerPrevious;
75092
75915
  var btn = (idSuffix, row, col, init) => ({
75093
75916
  idSuffix,
75094
75917
  row,
@@ -79703,6 +80526,20 @@ Object.freeze({
79703
80526
  access: "view",
79704
80527
  role: "admin"
79705
80528
  },
80529
+ "mediaPlayer.channelDown": {
80530
+ capName: "media-player",
80531
+ capScope: "device",
80532
+ addonId: null,
80533
+ access: "create",
80534
+ role: "viewer"
80535
+ },
80536
+ "mediaPlayer.channelUp": {
80537
+ capName: "media-player",
80538
+ capScope: "device",
80539
+ addonId: null,
80540
+ access: "create",
80541
+ role: "viewer"
80542
+ },
79706
80543
  "mediaPlayer.getStatus": {
79707
80544
  capName: "media-player",
79708
80545
  capScope: "device",
@@ -79794,6 +80631,34 @@ Object.freeze({
79794
80631
  access: "create",
79795
80632
  role: "viewer"
79796
80633
  },
80634
+ "mediaPlayer.turnOff": {
80635
+ capName: "media-player",
80636
+ capScope: "device",
80637
+ addonId: null,
80638
+ access: "create",
80639
+ role: "viewer"
80640
+ },
80641
+ "mediaPlayer.turnOn": {
80642
+ capName: "media-player",
80643
+ capScope: "device",
80644
+ addonId: null,
80645
+ access: "create",
80646
+ role: "viewer"
80647
+ },
80648
+ "mediaPlayer.volumeDown": {
80649
+ capName: "media-player",
80650
+ capScope: "device",
80651
+ addonId: null,
80652
+ access: "create",
80653
+ role: "viewer"
80654
+ },
80655
+ "mediaPlayer.volumeUp": {
80656
+ capName: "media-player",
80657
+ capScope: "device",
80658
+ addonId: null,
80659
+ access: "create",
80660
+ role: "viewer"
80661
+ },
79797
80662
  "meshNetwork.getStatus": {
79798
80663
  capName: "mesh-network",
79799
80664
  capScope: "system",
@@ -83350,6 +84215,13 @@ Object.freeze({
83350
84215
  access: "create",
83351
84216
  role: "admin"
83352
84217
  },
84218
+ "remote.getAssumedStatus": {
84219
+ capName: "remote",
84220
+ capScope: "system",
84221
+ addonId: null,
84222
+ access: "view",
84223
+ role: "admin"
84224
+ },
83353
84225
  "remote.getConfig": {
83354
84226
  capName: "remote",
83355
84227
  capScope: "system",
@@ -87041,6 +87913,16 @@ Object.freeze({
87041
87913
  form: "single",
87042
87914
  optional: true
87043
87915
  }],
87916
+ "mediaPlayer.channelDown": [{
87917
+ name: "deviceId",
87918
+ form: "single",
87919
+ optional: false
87920
+ }],
87921
+ "mediaPlayer.channelUp": [{
87922
+ name: "deviceId",
87923
+ form: "single",
87924
+ optional: false
87925
+ }],
87044
87926
  "mediaPlayer.getStatus": [{
87045
87927
  name: "deviceId",
87046
87928
  form: "single",
@@ -87106,6 +87988,26 @@ Object.freeze({
87106
87988
  form: "single",
87107
87989
  optional: false
87108
87990
  }],
87991
+ "mediaPlayer.turnOff": [{
87992
+ name: "deviceId",
87993
+ form: "single",
87994
+ optional: false
87995
+ }],
87996
+ "mediaPlayer.turnOn": [{
87997
+ name: "deviceId",
87998
+ form: "single",
87999
+ optional: false
88000
+ }],
88001
+ "mediaPlayer.volumeDown": [{
88002
+ name: "deviceId",
88003
+ form: "single",
88004
+ optional: false
88005
+ }],
88006
+ "mediaPlayer.volumeUp": [{
88007
+ name: "deviceId",
88008
+ form: "single",
88009
+ optional: false
88010
+ }],
87109
88011
  "meter.getStatus": [{
87110
88012
  name: "deviceId",
87111
88013
  form: "single",
@@ -88271,6 +89173,11 @@ Object.freeze({
88271
89173
  form: "single",
88272
89174
  optional: true
88273
89175
  }],
89176
+ "remote.getAssumedStatus": [{
89177
+ name: "deviceId",
89178
+ form: "single",
89179
+ optional: false
89180
+ }],
88274
89181
  "remote.getConfig": [{
88275
89182
  name: "deviceId",
88276
89183
  form: "single",
@@ -89526,6 +90433,7 @@ var STATE_SUMMARY_VARS = [
89526
90433
  [...RULE_TEXT],
89527
90434
  ([...RULE_TEXT], [...DEVICE_EVENTS]),
89528
90435
  ([...RULE_TEXT], [...COMBINED_ALARM]),
90436
+ ([...RULE_TEXT], [...COMBINED_ALARM]),
89529
90437
  ([...RULE_TEXT], [...DEVICE_EVENTS]),
89530
90438
  ([...RULE_TEXT], [...BATTERY, ...CONSUMABLE]),
89531
90439
  ([...RULE_TEXT], [...CONSUMABLE]),
@@ -91735,8 +92643,8 @@ function climateProperties(slice) {
91735
92643
  //#endregion
91736
92644
  //#region src/handlers/climate-controller.ts
91737
92645
  var CAP_CLIMATE = "climate-control";
91738
- var CAP_SWITCH$1 = "switch";
91739
- var UNCERTAINTY_MS$1 = 500;
92646
+ var CAP_SWITCH$2 = "switch";
92647
+ var UNCERTAINTY_MS$2 = 500;
91740
92648
  var PRESET_NONE = "none";
91741
92649
  var ScaleSchema = _enum([
91742
92650
  "CELSIUS",
@@ -92033,7 +92941,7 @@ function successResponse$2(c, properties) {
92033
92941
  context: { properties: properties.map((p) => ({
92034
92942
  ...p,
92035
92943
  timeOfSample: now,
92036
- uncertaintyInMilliseconds: UNCERTAINTY_MS$1
92944
+ uncertaintyInMilliseconds: UNCERTAINTY_MS$2
92037
92945
  })) }
92038
92946
  };
92039
92947
  }
@@ -92075,7 +92983,7 @@ async function handlesPower(c) {
92075
92983
  lastPowerClaim.set(deps, known);
92076
92984
  try {
92077
92985
  const caps = (await deps.ctx.api.deviceManager.getBindings.query({ deviceId: c.deviceId })).entries.map((e) => e.capName);
92078
- const claim = caps.includes(CAP_CLIMATE) && !caps.includes(CAP_SWITCH$1);
92986
+ const claim = caps.includes(CAP_CLIMATE) && !caps.includes(CAP_SWITCH$2);
92079
92987
  known.set(c.deviceId, claim);
92080
92988
  return claim;
92081
92989
  } catch (err) {
@@ -93135,7 +94043,7 @@ function fanProperties(slice) {
93135
94043
  //#endregion
93136
94044
  //#region src/handlers/fan-controller.ts
93137
94045
  var CAP_FAN = "fan-control";
93138
- var UNCERTAINTY_MS = 500;
94046
+ var UNCERTAINTY_MS$1 = 500;
93139
94047
  /** What AdjustRangeValue moves by when the device states no step of its own. */
93140
94048
  var DEFAULT_ADJUST = 10;
93141
94049
  var SetRangePayload = object({ rangeValue: number() });
@@ -93147,7 +94055,7 @@ var SetModePayload = object({ mode: string() });
93147
94055
  function clamp(value) {
93148
94056
  return Math.max(0, Math.min(100, Math.round(value)));
93149
94057
  }
93150
- function message(err) {
94058
+ function message$1(err) {
93151
94059
  return err instanceof Error ? err.message : String(err);
93152
94060
  }
93153
94061
  async function readSlice(c, deps) {
@@ -93159,7 +94067,7 @@ async function readSlice(c, deps) {
93159
94067
  } catch (err) {
93160
94068
  deps.logger.warn("alexa fan-controller: the fan state could not be read", {
93161
94069
  tags: { deviceId: c.deviceId },
93162
- meta: { error: message(err) }
94070
+ meta: { error: message$1(err) }
93163
94071
  });
93164
94072
  return null;
93165
94073
  }
@@ -93181,7 +94089,7 @@ function successResponse$1(c, properties) {
93181
94089
  context: { properties: properties.map((p) => ({
93182
94090
  ...p,
93183
94091
  timeOfSample: now,
93184
- uncertaintyInMilliseconds: UNCERTAINTY_MS
94092
+ uncertaintyInMilliseconds: UNCERTAINTY_MS$1
93185
94093
  })) }
93186
94094
  };
93187
94095
  }
@@ -93199,7 +94107,7 @@ async function setSpeed(c, deps, slice, speed) {
93199
94107
  tags: { deviceId: c.deviceId },
93200
94108
  meta: {
93201
94109
  speed,
93202
- error: message(err)
94110
+ error: message$1(err)
93203
94111
  }
93204
94112
  });
93205
94113
  return unreachable(c, "the fan did not accept the speed");
@@ -93242,7 +94150,7 @@ async function handleToggle(c, deps) {
93242
94150
  tags: { deviceId: c.deviceId },
93243
94151
  meta: {
93244
94152
  oscillating,
93245
- error: message(err)
94153
+ error: message$1(err)
93246
94154
  }
93247
94155
  });
93248
94156
  return unreachable(c, "the fan did not accept the command");
@@ -93262,7 +94170,7 @@ async function customNames(c, deps) {
93262
94170
  } catch (err) {
93263
94171
  deps.logger.warn("alexa fan-controller: the custom presets could not be read", {
93264
94172
  tags: { deviceId: c.deviceId },
93265
- meta: { error: message(err) }
94173
+ meta: { error: message$1(err) }
93266
94174
  });
93267
94175
  return [];
93268
94176
  }
@@ -93285,7 +94193,7 @@ async function handleMode(c, deps) {
93285
94193
  tags: { deviceId: c.deviceId },
93286
94194
  meta: {
93287
94195
  preset: mode.name,
93288
- error: message(err)
94196
+ error: message$1(err)
93289
94197
  }
93290
94198
  });
93291
94199
  return unreachable(c, "the fan did not accept the preset");
@@ -93337,7 +94245,7 @@ async function applyCustom(c, deps, name) {
93337
94245
  tags: { deviceId: c.deviceId },
93338
94246
  meta: {
93339
94247
  preset: name,
93340
- error: message(err)
94248
+ error: message$1(err)
93341
94249
  }
93342
94250
  });
93343
94251
  return unreachable(c, "the preset could not be applied");
@@ -93533,6 +94441,397 @@ var lockAdapter = {
93533
94441
  shaping: unshaped
93534
94442
  };
93535
94443
  //#endregion
94444
+ //#region src/endpoints/adapters/media-player-model.ts
94445
+ /**
94446
+ * A media player exported as a TV (planning#398). What Alexa is told depends on
94447
+ * what the player can DO (its features) and what it REPORTS (its slice):
94448
+ *
94449
+ * power → `Alexa.PowerController` (feature `media-player-power`)
94450
+ * volume ±N → `Alexa.StepSpeaker` (feature `media-player-volume-step`)
94451
+ * mute → `Alexa.Speaker` (`muted` only) (feature `media-player-mute`)
94452
+ * channel ±N → `Alexa.ChannelController` (feature `media-player-channel-step`)
94453
+ * transport → `Alexa.PlaybackController` (stop / next / previous by feature; play and
94454
+ * pause only when the player REPORTS its state,
94455
+ * since an assumed one cannot tell)
94456
+ * inputs → `Alexa.InputController` (the reported sources Amazon names)
94457
+ *
94458
+ * A property is reported only for a known value: an assumed `standby`, a null
94459
+ * mute and an unlisted volume or input produce no property at all (D393).
94460
+ */
94461
+ var CAP_MEDIA_PLAYER = "media-player";
94462
+ /** The input names Amazon accepts for `Alexa.InputController` (alexa-inputcontroller). */
94463
+ var AMAZON_INPUTS = [
94464
+ ...Array.from({ length: 7 }, (_, i) => `AUX ${i + 1}`),
94465
+ "BLURAY",
94466
+ "CABLE",
94467
+ "CD",
94468
+ "COAX 1",
94469
+ "COAX 2",
94470
+ "COMPOSITE 1",
94471
+ "DVD",
94472
+ "GAME",
94473
+ "HD RADIO",
94474
+ ...Array.from({ length: 10 }, (_, i) => `HDMI ${i + 1}`),
94475
+ "HDMI ARC",
94476
+ ...Array.from({ length: 10 }, (_, i) => `INPUT ${i + 1}`),
94477
+ "IPOD",
94478
+ ...Array.from({ length: 7 }, (_, i) => `LINE ${i + 1}`),
94479
+ "MEDIA PLAYER",
94480
+ "OPTICAL 1",
94481
+ "OPTICAL 2",
94482
+ "PHONO",
94483
+ "PLAYSTATION",
94484
+ "PLAYSTATION 3",
94485
+ "PLAYSTATION 4",
94486
+ "SATELLITE",
94487
+ "SMARTCAST",
94488
+ "TUNER",
94489
+ "TV",
94490
+ "USB",
94491
+ "USB DAC",
94492
+ "VIDEO 1",
94493
+ "VIDEO 2",
94494
+ "VIDEO 3",
94495
+ "XBOX"
94496
+ ];
94497
+ function squash(name) {
94498
+ return name.toUpperCase().replace(/[^A-Z0-9]/g, "");
94499
+ }
94500
+ /** The Amazon input a source name stands for ("hdmi1" → "HDMI 1"), or null. */
94501
+ function amazonInputOf(source) {
94502
+ const wanted = squash(source);
94503
+ return AMAZON_INPUTS.find((name) => squash(name) === wanted) ?? null;
94504
+ }
94505
+ /** The sources of a slice that Amazon has a name for, paired with the player's own name. */
94506
+ function inputPairs(status) {
94507
+ const seen = /* @__PURE__ */ new Set();
94508
+ const pairs = [];
94509
+ for (const source of status.availableSources) {
94510
+ const amazon = amazonInputOf(source);
94511
+ if (amazon === null || seen.has(amazon)) continue;
94512
+ seen.add(amazon);
94513
+ pairs.push({
94514
+ amazon,
94515
+ source
94516
+ });
94517
+ }
94518
+ return pairs;
94519
+ }
94520
+ function readMediaPlayerSlice(slice) {
94521
+ const parsed = MediaPlayerStatusSchema.safeParse(slice);
94522
+ return parsed.success ? parsed.data : null;
94523
+ }
94524
+ var PLAYBACK_BY_FEATURE = [
94525
+ [DeviceFeature.MediaPlayerStop, "Stop"],
94526
+ [DeviceFeature.MediaPlayerNext, "Next"],
94527
+ [DeviceFeature.MediaPlayerPrevious, "Previous"]
94528
+ ];
94529
+ function playbackOperations(device, status) {
94530
+ return [...status !== null && status.stateSource === "reported" ? ["Play", "Pause"] : [], ...PLAYBACK_BY_FEATURE.filter(([feature]) => device.features.includes(feature)).map(([, operation]) => operation)];
94531
+ }
94532
+ function describeMediaPlayerCapabilities(device) {
94533
+ const has = (feature) => device.features.includes(feature);
94534
+ const status = readMediaPlayerSlice(device.slices[CAP_MEDIA_PLAYER]);
94535
+ const capabilities = [];
94536
+ if (has(DeviceFeature.MediaPlayerPower)) capabilities.push(iface("Alexa.PowerController", "powerState"));
94537
+ if (has(DeviceFeature.MediaPlayerVolumeStep)) capabilities.push({
94538
+ type: "AlexaInterface",
94539
+ interface: "Alexa.StepSpeaker",
94540
+ version: "3"
94541
+ });
94542
+ if (has(DeviceFeature.MediaPlayerMute)) capabilities.push(iface("Alexa.Speaker", "muted"));
94543
+ if (has(DeviceFeature.MediaPlayerChannelStep)) capabilities.push({
94544
+ type: "AlexaInterface",
94545
+ interface: "Alexa.ChannelController",
94546
+ version: "3"
94547
+ });
94548
+ const operations = playbackOperations(device, status);
94549
+ if (operations.length > 0) capabilities.push({
94550
+ type: "AlexaInterface",
94551
+ interface: "Alexa.PlaybackController",
94552
+ version: "3",
94553
+ supportedOperations: operations
94554
+ });
94555
+ const inputs = status === null ? [] : inputPairs(status);
94556
+ if (has(DeviceFeature.MediaPlayerSelectSource) && inputs.length > 0) capabilities.push({
94557
+ ...iface("Alexa.InputController", "input"),
94558
+ inputs: inputs.map((i) => ({ name: i.amazon }))
94559
+ });
94560
+ return capabilities;
94561
+ }
94562
+ /** The Alexa properties of a slice: only what is known. */
94563
+ function mediaPlayerProperties(slice) {
94564
+ const status = readMediaPlayerSlice(slice);
94565
+ if (status === null) return [];
94566
+ const out = [];
94567
+ if (status.state === "off") out.push({
94568
+ namespace: "Alexa.PowerController",
94569
+ name: "powerState",
94570
+ value: "OFF"
94571
+ });
94572
+ else if (status.state !== "standby") out.push({
94573
+ namespace: "Alexa.PowerController",
94574
+ name: "powerState",
94575
+ value: "ON"
94576
+ });
94577
+ if (status.isMuted !== null) out.push({
94578
+ namespace: "Alexa.Speaker",
94579
+ name: "muted",
94580
+ value: status.isMuted
94581
+ });
94582
+ const input = inputPairs(status).find((i) => i.source === status.source);
94583
+ if (input !== void 0) out.push({
94584
+ namespace: "Alexa.InputController",
94585
+ name: "input",
94586
+ value: input.amazon
94587
+ });
94588
+ return out;
94589
+ }
94590
+ //#endregion
94591
+ //#region src/handlers/media-player-controller.ts
94592
+ var UNCERTAINTY_MS = 1e3;
94593
+ var CAP_SWITCH$1 = "switch";
94594
+ var StepsPayload = object({ volumeSteps: number().int() });
94595
+ var ChannelPayload = object({ channelCount: number().int() });
94596
+ var MutePayload = object({ mute: boolean() });
94597
+ var InputPayload = object({ input: string() });
94598
+ function message(err) {
94599
+ return err instanceof Error ? err.message : String(err);
94600
+ }
94601
+ function success(c, properties) {
94602
+ const now = (/* @__PURE__ */ new Date()).toISOString();
94603
+ return {
94604
+ event: {
94605
+ header: {
94606
+ namespace: "Alexa",
94607
+ name: "Response",
94608
+ messageId: c.header.messageId,
94609
+ ...c.header.correlationToken !== void 0 ? { correlationToken: c.header.correlationToken } : {},
94610
+ payloadVersion: "3"
94611
+ },
94612
+ endpoint: { endpointId: c.endpoint.endpointId },
94613
+ payload: {}
94614
+ },
94615
+ context: { properties: properties.map((p) => ({
94616
+ ...p,
94617
+ timeOfSample: now,
94618
+ uncertaintyInMilliseconds: UNCERTAINTY_MS
94619
+ })) }
94620
+ };
94621
+ }
94622
+ /** PowerController on a media player, not on a switch: decided by the bound caps. */
94623
+ async function claimsMediaPlayerPower(c) {
94624
+ const deps = c.deps.mediaPlayerController;
94625
+ try {
94626
+ const caps = (await deps.ctx.api.deviceManager.getBindings.query({ deviceId: c.deviceId })).entries.map((e) => e.capName);
94627
+ return caps.includes("media-player") && !caps.includes(CAP_SWITCH$1);
94628
+ } catch (err) {
94629
+ deps.logger.warn("alexa media-player-controller: the bound caps could not be read", {
94630
+ tags: { deviceId: c.deviceId },
94631
+ meta: {
94632
+ error: message(err),
94633
+ decidedFrom: "no previous answer: not claimed"
94634
+ }
94635
+ });
94636
+ return false;
94637
+ }
94638
+ }
94639
+ /** How long a step command may run before Alexa is answered anyway (its own budget is ~8 s). */
94640
+ var STEP_ANSWER_BUDGET_MS = 3e3;
94641
+ /** The properties a command may assert: only those the player READS back, never an assumption (D393). */
94642
+ async function reportedProperties(c, namespace) {
94643
+ const deps = c.deps.mediaPlayerController;
94644
+ try {
94645
+ const slice = await deps.ctx.api.deviceState.getCapSlice.query({
94646
+ deviceId: c.deviceId,
94647
+ capName: CAP_MEDIA_PLAYER
94648
+ });
94649
+ const status = readMediaPlayerSlice(slice);
94650
+ if (status === null || status.stateSource !== "reported") return [];
94651
+ return mediaPlayerProperties(slice).filter((p) => p.namespace === namespace);
94652
+ } catch (err) {
94653
+ deps.logger.warn("alexa media-player-controller: the state could not be re-read", {
94654
+ tags: { deviceId: c.deviceId },
94655
+ meta: { error: message(err) }
94656
+ });
94657
+ return [];
94658
+ }
94659
+ }
94660
+ async function attempt(c, what, run, options = {}) {
94661
+ const deps = c.deps.mediaPlayerController;
94662
+ const settled = run().then(() => ({ ok: true }), (error) => ({
94663
+ ok: false,
94664
+ error
94665
+ }));
94666
+ let timer;
94667
+ const outcome = options.slow === true ? await Promise.race([settled, new Promise((resolve) => {
94668
+ timer = setTimeout(() => resolve(null), STEP_ANSWER_BUDGET_MS);
94669
+ })]) : await settled;
94670
+ if (timer !== void 0) clearTimeout(timer);
94671
+ if (outcome === null) {
94672
+ deps.logger.info(`alexa media-player-controller: ${what} still sending, answered`, { tags: { deviceId: c.deviceId } });
94673
+ settled.then((late) => {
94674
+ if (!late.ok) deps.logger.warn(`alexa media-player-controller: ${what} failed after the answer`, {
94675
+ tags: { deviceId: c.deviceId },
94676
+ meta: { error: message(late.error) }
94677
+ });
94678
+ });
94679
+ return success(c, []);
94680
+ }
94681
+ if (!outcome.ok) {
94682
+ deps.logger.warn(`alexa media-player-controller: ${what} failed`, {
94683
+ tags: { deviceId: c.deviceId },
94684
+ meta: { error: message(outcome.error) }
94685
+ });
94686
+ return errorEnvelope(c.header, "ENDPOINT_UNREACHABLE", `the player did not accept ${what}`);
94687
+ }
94688
+ deps.logger.info(`alexa media-player-controller: ${what}`, { tags: { deviceId: c.deviceId } });
94689
+ return success(c, options.namespace === void 0 ? [] : await reportedProperties(c, options.namespace));
94690
+ }
94691
+ async function volume(c) {
94692
+ const payload = StepsPayload.safeParse(c.payload);
94693
+ if (!payload.success || payload.data.volumeSteps === 0) return errorEnvelope(c.header, "INVALID_DIRECTIVE", "volumeSteps is required");
94694
+ const steps = Math.min(Math.abs(payload.data.volumeSteps), 50);
94695
+ const api = c.deps.mediaPlayerController.ctx.api.mediaPlayer;
94696
+ const up = payload.data.volumeSteps > 0;
94697
+ return attempt(c, `volume ${up ? "up" : "down"} ${steps}`, () => up ? api.volumeUp.mutate({
94698
+ deviceId: c.deviceId,
94699
+ steps
94700
+ }) : api.volumeDown.mutate({
94701
+ deviceId: c.deviceId,
94702
+ steps
94703
+ }), { slow: true });
94704
+ }
94705
+ async function channel(c) {
94706
+ const payload = ChannelPayload.safeParse(c.payload);
94707
+ if (!payload.success || payload.data.channelCount === 0) return errorEnvelope(c.header, "INVALID_DIRECTIVE", "channelCount is required");
94708
+ const steps = Math.min(Math.abs(payload.data.channelCount), 50);
94709
+ const api = c.deps.mediaPlayerController.ctx.api.mediaPlayer;
94710
+ const up = payload.data.channelCount > 0;
94711
+ return attempt(c, `channel ${up ? "up" : "down"} ${steps}`, () => up ? api.channelUp.mutate({
94712
+ deviceId: c.deviceId,
94713
+ steps
94714
+ }) : api.channelDown.mutate({
94715
+ deviceId: c.deviceId,
94716
+ steps
94717
+ }), { slow: true });
94718
+ }
94719
+ async function mute(c) {
94720
+ const payload = MutePayload.safeParse(c.payload);
94721
+ if (!payload.success) return errorEnvelope(c.header, "INVALID_DIRECTIVE", "mute is required");
94722
+ const muted = payload.data.mute;
94723
+ const api = c.deps.mediaPlayerController.ctx.api.mediaPlayer;
94724
+ return attempt(c, `mute ${String(muted)}`, () => api.setMute.mutate({
94725
+ deviceId: c.deviceId,
94726
+ muted
94727
+ }), { namespace: "Alexa.Speaker" });
94728
+ }
94729
+ async function power$1(c) {
94730
+ const on = c.header.name === "TurnOn";
94731
+ const api = c.deps.mediaPlayerController.ctx.api.mediaPlayer;
94732
+ return attempt(c, on ? "turn on" : "turn off", () => on ? api.turnOn.mutate({ deviceId: c.deviceId }) : api.turnOff.mutate({ deviceId: c.deviceId }), { namespace: "Alexa.PowerController" });
94733
+ }
94734
+ async function playback(c) {
94735
+ const api = c.deps.mediaPlayerController.ctx.api.mediaPlayer;
94736
+ const input = { deviceId: c.deviceId };
94737
+ switch (c.header.name) {
94738
+ case "Play": return attempt(c, "play", () => api.play.mutate(input));
94739
+ case "Pause": return attempt(c, "pause", () => api.pause.mutate(input));
94740
+ case "Stop": return attempt(c, "stop", () => api.stop.mutate(input));
94741
+ case "Next": return attempt(c, "next", () => api.next.mutate(input));
94742
+ case "Previous": return attempt(c, "previous", () => api.previous.mutate(input));
94743
+ default: return errorEnvelope(c.header, "INVALID_DIRECTIVE", `unsupported ${c.header.name}`);
94744
+ }
94745
+ }
94746
+ async function selectInput(c) {
94747
+ const payload = InputPayload.safeParse(c.payload);
94748
+ if (!payload.success) return errorEnvelope(c.header, "INVALID_DIRECTIVE", "input is required");
94749
+ const deps = c.deps.mediaPlayerController;
94750
+ let source;
94751
+ try {
94752
+ const status = readMediaPlayerSlice(await deps.ctx.api.deviceState.getCapSlice.query({
94753
+ deviceId: c.deviceId,
94754
+ capName: CAP_MEDIA_PLAYER
94755
+ }));
94756
+ source = status === null ? void 0 : inputPairs(status).find((i) => i.amazon === payload.data.input)?.source;
94757
+ } catch (err) {
94758
+ deps.logger.warn("alexa media-player-controller: the sources could not be read", {
94759
+ tags: { deviceId: c.deviceId },
94760
+ meta: { error: message(err) }
94761
+ });
94762
+ return errorEnvelope(c.header, "ENDPOINT_UNREACHABLE", "the player sources could not be read");
94763
+ }
94764
+ if (source === void 0) return errorEnvelope(c.header, "INVALID_VALUE", `the player has no input ${payload.data.input}`);
94765
+ const chosen = source;
94766
+ return attempt(c, `select input ${chosen}`, () => deps.ctx.api.mediaPlayer.selectSource.mutate({
94767
+ deviceId: c.deviceId,
94768
+ source: chosen
94769
+ }), { namespace: "Alexa.InputController" });
94770
+ }
94771
+ /** The one handler behind every media-player directive. */
94772
+ async function handleMediaPlayerDirective(c) {
94773
+ switch (`${c.header.namespace}/${c.header.name}`) {
94774
+ case "Alexa.PowerController/TurnOn":
94775
+ case "Alexa.PowerController/TurnOff": return power$1(c);
94776
+ case "Alexa.StepSpeaker/AdjustVolume": return volume(c);
94777
+ case "Alexa.StepSpeaker/SetMute":
94778
+ case "Alexa.Speaker/SetMute": return mute(c);
94779
+ case "Alexa.ChannelController/SkipChannels": return channel(c);
94780
+ case "Alexa.InputController/SelectInput": return selectInput(c);
94781
+ default: return c.header.namespace === "Alexa.PlaybackController" ? playback(c) : errorEnvelope(c.header, "INVALID_DIRECTIVE", `unsupported ${c.header.name}`);
94782
+ }
94783
+ }
94784
+ //#endregion
94785
+ //#region src/endpoints/adapters/media-player.ts
94786
+ function directive(key, claims) {
94787
+ return {
94788
+ key,
94789
+ needsReachableDevice: true,
94790
+ handle: handleMediaPlayerDirective,
94791
+ ...claims === void 0 ? {} : { claims }
94792
+ };
94793
+ }
94794
+ var DIRECTIVES = [
94795
+ directive("Alexa.PowerController/TurnOn", claimsMediaPlayerPower),
94796
+ directive("Alexa.PowerController/TurnOff", claimsMediaPlayerPower),
94797
+ directive("Alexa.StepSpeaker/AdjustVolume"),
94798
+ directive("Alexa.StepSpeaker/SetMute"),
94799
+ directive("Alexa.Speaker/SetMute"),
94800
+ directive("Alexa.ChannelController/SkipChannels"),
94801
+ directive("Alexa.PlaybackController/Play"),
94802
+ directive("Alexa.PlaybackController/Pause"),
94803
+ directive("Alexa.PlaybackController/Stop"),
94804
+ directive("Alexa.PlaybackController/Next"),
94805
+ directive("Alexa.PlaybackController/Previous"),
94806
+ directive("Alexa.InputController/SelectInput")
94807
+ ];
94808
+ /**
94809
+ * `media-player` → a TV: power, step volume, mute, channel steps, transport and
94810
+ * inputs, each only when the player says it can (features) and, for the ones
94811
+ * that need a reading, only when it reports one. Registered before `switch`: a
94812
+ * TV is a TV, not a SWITCH.
94813
+ */
94814
+ var mediaPlayerAdapter = {
94815
+ cap: CAP_MEDIA_PLAYER,
94816
+ stateCaps: [CAP_MEDIA_PLAYER],
94817
+ discoveryReads: [CAP_MEDIA_PLAYER],
94818
+ describe: (device) => {
94819
+ const capabilities = describeMediaPlayerCapabilities(device);
94820
+ if (capabilities.length === 0) return {
94821
+ kind: "skip",
94822
+ reason: "the media player offers nothing Alexa can drive"
94823
+ };
94824
+ return {
94825
+ kind: "publish",
94826
+ capabilities,
94827
+ category: "TV"
94828
+ };
94829
+ },
94830
+ properties: (_cap, slice) => mediaPlayerProperties(slice),
94831
+ directives: DIRECTIVES,
94832
+ shaping: () => null
94833
+ };
94834
+ //#endregion
93536
94835
  //#region src/endpoints/adapters/motion.ts
93537
94836
  /** `motion` → `Alexa.MotionSensor` (MOTION_SENSOR). */
93538
94837
  var motionAdapter = {
@@ -93740,6 +95039,7 @@ var GENERIC_ADAPTERS = [
93740
95039
  temperatureAdapter,
93741
95040
  humidityAdapter,
93742
95041
  fanAdapter,
95042
+ mediaPlayerAdapter,
93743
95043
  {
93744
95044
  cap: "switch",
93745
95045
  stateCaps: ["switch", "brightness"],
@@ -93875,6 +95175,7 @@ var GENERIC_DEVICE_TYPES = [
93875
95175
  "climate",
93876
95176
  "cover",
93877
95177
  "fan",
95178
+ "media-player",
93878
95179
  "generic"
93879
95180
  ];
93880
95181
  function toEndpoint(input, plan) {
@@ -95476,7 +96777,12 @@ var ALLOWED_INTERFACE_VERSIONS = {
95476
96777
  "Alexa.SmartVision.SnapshotProvider": "1.1",
95477
96778
  "Alexa.SmartVision.ObjectDetectionSensor": "1.0",
95478
96779
  "Alexa.DataController": "1.0",
95479
- "Alexa.SceneController": "3"
96780
+ "Alexa.SceneController": "3",
96781
+ "Alexa.StepSpeaker": "3",
96782
+ "Alexa.Speaker": "3",
96783
+ "Alexa.ChannelController": "3",
96784
+ "Alexa.PlaybackController": "3",
96785
+ "Alexa.InputController": "3"
95480
96786
  };
95481
96787
  /** `imageNetClass` values Amazon accepts (alexa-smartvision-objectdetectionsensor). */
95482
96788
  var SMART_VISION_CLASSES = new Set(["person", "package"]);
@@ -95516,6 +96822,7 @@ var DISPLAY_CATEGORIES = new Set([
95516
96822
  "THERMOSTAT",
95517
96823
  "AIR_CONDITIONER",
95518
96824
  "FAN",
96825
+ "TV",
95519
96826
  "DOOR",
95520
96827
  "GATE",
95521
96828
  "GARAGE_DOOR",
@@ -99666,12 +100973,30 @@ function troubleshootingSection() {
99666
100973
  ]
99667
100974
  };
99668
100975
  }
99669
- /** Custom skill only: the public skill's shared Lambda sends one ingress token
99670
- * for every hub (`HUB_INGRESS_TOKEN`), so a per-hub token cannot apply to it. */
99671
- function customSkillSecuritySection(input) {
100976
+ /** The enforcement switch of the custom skill's ingress token: part of the skill instance. */
100977
+ function instanceSecuritySection(input) {
99672
100978
  return {
99673
100979
  id: "export-alexa-custom-security",
99674
100980
  title: "Custom-skill security",
100981
+ columns: 1,
100982
+ fields: [{
100983
+ type: "boolean",
100984
+ key: "enforceIngressToken",
100985
+ label: "Require ingress token",
100986
+ description: "When on, this hub refuses skill calls without the matching token. Turn it on only after HUB_INGRESS_TOKEN is set in your Lambda. The token itself is shown on the addon page.",
100987
+ default: input.defaults.enforceIngressToken,
100988
+ showWhen: CUSTOM_SKILL_ONLY
100989
+ }]
100990
+ };
100991
+ }
100992
+ /** Custom skill only: the public skill's shared Lambda sends one ingress token
100993
+ * for every hub (`HUB_INGRESS_TOKEN`), so a per-hub token cannot apply to it. The rows are
100994
+ * built only for a custom skill: the mode is not a field of this page. */
100995
+ function customSkillSecuritySection(input) {
100996
+ if (input.skillMode !== "custom") return null;
100997
+ return {
100998
+ id: "export-alexa-custom-security-token",
100999
+ title: "Custom-skill ingress token",
99675
101000
  style: "accordion",
99676
101001
  defaultCollapsed: true,
99677
101002
  columns: 1,
@@ -99681,8 +101006,7 @@ function customSkillSecuritySection(input) {
99681
101006
  key: "__ingress-token-info",
99682
101007
  label: "Ingress token",
99683
101008
  variant: "info",
99684
- showWhen: CUSTOM_SKILL_ONLY,
99685
- content: "An optional shared secret your skill Lambda sends on every call to this hub. Show it, put it in the Lambda's HUB_INGRESS_TOKEN environment variable, then turn on \"Require ingress token\". After a rotation, update the Lambda."
101009
+ content: "An optional shared secret your skill Lambda sends on every call to this hub. Show it, put it in the Lambda's HUB_INGRESS_TOKEN environment variable, then turn on \"Require ingress token\" on the skill. After a rotation, update the Lambda."
99686
101010
  },
99687
101011
  {
99688
101012
  type: "addon-action-button",
@@ -99693,8 +101017,7 @@ function customSkillSecuritySection(input) {
99693
101017
  buttonLabel: "Show ingress token",
99694
101018
  action: "revealIngressToken",
99695
101019
  variant: "default",
99696
- successMessage: "Ingress token: {ingressToken}",
99697
- showWhen: CUSTOM_SKILL_ONLY
101020
+ successMessage: "Ingress token: {ingressToken}"
99698
101021
  },
99699
101022
  {
99700
101023
  type: "addon-action-button",
@@ -99706,27 +101029,25 @@ function customSkillSecuritySection(input) {
99706
101029
  action: "regenerateIngressToken",
99707
101030
  variant: "default",
99708
101031
  successMessage: "New ingress token: {ingressToken} — put it in HUB_INGRESS_TOKEN now.",
99709
- confirmMessage: "Rotate the ingress token? With \"Require ingress token\" on, the Lambda is refused until you update HUB_INGRESS_TOKEN.",
99710
- showWhen: CUSTOM_SKILL_ONLY
99711
- },
99712
- {
99713
- type: "boolean",
99714
- key: "enforceIngressToken",
99715
- label: "Require ingress token",
99716
- description: "When on, this hub refuses skill calls without the matching token. Turn it on only after HUB_INGRESS_TOKEN is set in your Lambda.",
99717
- default: input.defaults.enforceIngressToken,
99718
- showWhen: CUSTOM_SKILL_ONLY
101032
+ confirmMessage: "Rotate the ingress token? With \"Require ingress token\" on, the Lambda is refused until you update HUB_INGRESS_TOKEN."
99719
101033
  }
99720
101034
  ]
99721
101035
  };
99722
101036
  }
99723
- function buildAlexaSettingsSections(input) {
101037
+ /** The skill instance's form (`skills` record). */
101038
+ function buildAlexaInstanceSections(input) {
99724
101039
  return [
99725
101040
  connectionSection(input),
99726
101041
  featuresSection(input),
101042
+ instanceSecuritySection(input)
101043
+ ];
101044
+ }
101045
+ function buildAlexaSettingsSections(input) {
101046
+ const security = customSkillSecuritySection(input);
101047
+ return [
99727
101048
  accountLinkSection(input),
99728
101049
  troubleshootingSection(),
99729
- customSkillSecuritySection(input)
101050
+ ...security === null ? [] : [security]
99730
101051
  ];
99731
101052
  }
99732
101053
  //#endregion
@@ -100461,7 +101782,7 @@ var ALEXA_ADDON_ID = "export-alexa";
100461
101782
  * key, id `<addonId>.<key>`, data `{ addonId, key, value }` (never a per-addon scoped table,
100462
101783
  * which exists only when something lazily declared it).
100463
101784
  */
100464
- var ADDON_SETTINGS_TABLE = "addon-settings";
101785
+ var ADDON_SETTINGS_TABLE$1 = "addon-settings";
100465
101786
  var RETIRED_PUBLIC_URL_KEYS = ["publicHubUrl"];
100466
101787
  async function planDropPublicHubUrl(ports) {
100467
101788
  const stored = await ports.readStored();
@@ -100470,7 +101791,7 @@ async function planDropPublicHubUrl(ports) {
100470
101791
  const rowId = (key) => `${ALEXA_ADDON_ID}.${key}`;
100471
101792
  return { edits: [{
100472
101793
  op: "deleteKeys",
100473
- scope: ADDON_SETTINGS_TABLE,
101794
+ scope: ADDON_SETTINGS_TABLE$1,
100474
101795
  keys: present.map(rowId),
100475
101796
  precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
100476
101797
  addonId: ALEXA_ADDON_ID,
@@ -100480,24 +101801,314 @@ async function planDropPublicHubUrl(ports) {
100480
101801
  }] };
100481
101802
  }
100482
101803
  //#endregion
101804
+ //#region src/skill-records.ts
101805
+ /**
101806
+ * The Alexa export as an integration instance (D985, D996): ONE `skills` record, owned by
101807
+ * `export-alexa` and named after it, holds how the skill reaches this hub and what each exposed
101808
+ * camera carries. The two ledgers of the link (`linkedAccounts`, `tokens`) are a second record,
101809
+ * `skill-links`, under the SAME id: the instance they belong to. The tokens' credentials are
101810
+ * keychain markers bound to that row, matched by user id so a reorder keeps every ref.
101811
+ */
101812
+ /** A single-instance addon keeps its records under its own addon id. */
101813
+ var ALEXA_INSTANCE_ID = "export-alexa";
101814
+ var alexaSkillsKind = defineEntryKind("skills", {
101815
+ title: "Alexa skill",
101816
+ nameField: "name",
101817
+ schema: object({
101818
+ name: string().min(1),
101819
+ skillMode: _enum(["public", "custom"]),
101820
+ region: _enum([
101821
+ "NA",
101822
+ "EU",
101823
+ "FE"
101824
+ ]),
101825
+ expectedAudience: string(),
101826
+ detectionSensors: boolean(),
101827
+ objectDetection: boolean(),
101828
+ snapshots: boolean(),
101829
+ enforceIngressToken: boolean(),
101830
+ enabled: boolean().optional()
101831
+ })
101832
+ });
101833
+ /** What a skill starts as: the defaults the addon's constructor used to carry. */
101834
+ var ALEXA_SKILL_DEFAULT_BODY = {
101835
+ skillMode: "public",
101836
+ region: "NA",
101837
+ expectedAudience: "",
101838
+ detectionSensors: true,
101839
+ objectDetection: true,
101840
+ snapshots: true,
101841
+ enforceIngressToken: false
101842
+ };
101843
+ /** The settings keys that moved into the `skills` record; the migrations name them. */
101844
+ var MOVED_SKILL_KEYS = [
101845
+ "skillMode",
101846
+ "region",
101847
+ "expectedAudience",
101848
+ "detectionSensors",
101849
+ "objectDetection",
101850
+ "snapshots",
101851
+ "enforceIngressToken"
101852
+ ];
101853
+ /** The ledger keys that moved into the `skill-links` record. */
101854
+ var MOVED_LEDGER_KEYS = ["linkedAccounts", "tokens"];
101855
+ var LinkedAccountSchema = object({
101856
+ userId: string(),
101857
+ username: string(),
101858
+ linkedAt: number()
101859
+ });
101860
+ var LwaTokenEntrySchema = object({
101861
+ userId: string(),
101862
+ accessToken: string().meta({ secret: true }),
101863
+ expiresAt: number(),
101864
+ receivedAt: number(),
101865
+ refreshToken: string().optional().meta({ secret: true }),
101866
+ brokerUrl: string().optional(),
101867
+ brokerCredential: string().optional().meta({ secret: true })
101868
+ });
101869
+ var alexaSkillLinksKind = defineEntryKind("skill-links", {
101870
+ title: "Alexa account links",
101871
+ nameField: "name",
101872
+ schema: object({
101873
+ name: string().min(1),
101874
+ linkedAccounts: array(LinkedAccountSchema),
101875
+ tokens: array(LwaTokenEntrySchema)
101876
+ }),
101877
+ secretArrayKeys: { tokens: "userId" }
101878
+ });
101879
+ //#endregion
101880
+ //#region src/migrations/settings-to-records.ts
101881
+ /**
101882
+ * The Alexa export's settings move into records (D985, D996). Three migrations of the catalogue
101883
+ * after the retired-URL one, each idempotent, in this order:
101884
+ *
101885
+ * 2. `moveSettingsToSkill` (procedure): the seven skill settings become the `skills` record.
101886
+ * An existing record is never overwritten.
101887
+ * 3. `moveLedgersToLinks` (procedure): `linkedAccounts` and `tokens` become the `skill-links`
101888
+ * record. The record is read BACK (credentials resolved) and must equal what the old
101889
+ * settings carried, byte for byte, BEFORE the old token credentials are cleared; any
101890
+ * difference throws and clears nothing. An existing record is never overwritten.
101891
+ * 4. `planDropMovedSettings` (plan): the moved keys are deleted from the canonical
101892
+ * `addon-settings` rows, and only while the records are confirmed to hold what they carried.
101893
+ *
101894
+ * All three are `tolerate`: the addon keeps reading the legacy keys until a record exists.
101895
+ */
101896
+ /** The canonical `addon-settings` table: one row per key, id `<addonId>.<key>`. */
101897
+ var ADDON_SETTINGS_TABLE = "addon-settings";
101898
+ var SKILL_NAME = "Alexa skill";
101899
+ var LINKS_NAME = "Alexa account links";
101900
+ function text(stored, key) {
101901
+ const value = stored[key];
101902
+ return typeof value === "string" ? value.trim() : "";
101903
+ }
101904
+ function flag(stored, key, fallback) {
101905
+ const value = stored[key];
101906
+ return typeof value === "boolean" ? value : fallback;
101907
+ }
101908
+ /** The record body the legacy settings describe; a missing or mistyped key takes the default. */
101909
+ function skillBodyFrom(stored) {
101910
+ const d = ALEXA_SKILL_DEFAULT_BODY;
101911
+ const region = stored["region"];
101912
+ return {
101913
+ name: SKILL_NAME,
101914
+ skillMode: stored["skillMode"] === "custom" ? "custom" : "public",
101915
+ region: region === "EU" || region === "FE" ? region : "NA",
101916
+ expectedAudience: text(stored, "expectedAudience"),
101917
+ detectionSensors: flag(stored, "detectionSensors", d.detectionSensors),
101918
+ objectDetection: flag(stored, "objectDetection", d.objectDetection),
101919
+ snapshots: flag(stored, "snapshots", d.snapshots),
101920
+ enforceIngressToken: flag(stored, "enforceIngressToken", d.enforceIngressToken)
101921
+ };
101922
+ }
101923
+ async function moveSettingsToSkill(ports) {
101924
+ const stored = await ports.readStored();
101925
+ if (!MOVED_SKILL_KEYS.some((key) => key in stored)) return {
101926
+ outcome: "already-done",
101927
+ summary: { moved: false }
101928
+ };
101929
+ return await ports.putSkill(skillBodyFrom(stored)) === "created" ? {
101930
+ outcome: "done",
101931
+ summary: { moved: true }
101932
+ } : {
101933
+ outcome: "already-done",
101934
+ summary: { moved: false }
101935
+ };
101936
+ }
101937
+ function accountsOf(value) {
101938
+ return Array.isArray(value) ? value.filter(isLinkedAccount) : [];
101939
+ }
101940
+ function tokensOf(value) {
101941
+ return Array.isArray(value) ? value.filter(isTokenEntry) : [];
101942
+ }
101943
+ function isLinkedAccount(value) {
101944
+ return typeof value === "object" && value !== null && "userId" in value && typeof value.userId === "string" && "username" in value && typeof value.username === "string" && "linkedAt" in value && typeof value.linkedAt === "number";
101945
+ }
101946
+ function isTokenEntry(value) {
101947
+ return typeof value === "object" && value !== null && "userId" in value && typeof value.userId === "string" && "accessToken" in value && typeof value.accessToken === "string" && "expiresAt" in value && typeof value.expiresAt === "number" && "receivedAt" in value && typeof value.receivedAt === "number";
101948
+ }
101949
+ /** Key-order-independent JSON, so "byte-identical" does not depend on how a store orders keys. */
101950
+ function canonical(value) {
101951
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
101952
+ if (typeof value === "object" && value !== null) return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
101953
+ return JSON.stringify(value) ?? "null";
101954
+ }
101955
+ async function moveLedgersToLinks(ports) {
101956
+ const stored = await ports.readStored();
101957
+ if (!MOVED_LEDGER_KEYS.some((key) => key in stored)) return {
101958
+ outcome: "already-done",
101959
+ summary: { moved: false }
101960
+ };
101961
+ const linkedAccounts = accountsOf(stored["linkedAccounts"]);
101962
+ const tokens = tokensOf(stored["tokens"]);
101963
+ const put = await ports.putLinks({
101964
+ name: LINKS_NAME,
101965
+ linkedAccounts,
101966
+ tokens
101967
+ });
101968
+ const held = await ports.readLinks();
101969
+ if (!(held !== null && canonical(held.linkedAccounts) === canonical(linkedAccounts) && canonical(held.tokens) === canonical(tokens))) {
101970
+ ports.warn("Alexa migration: the skill-links record does not hold what the settings carried; the legacy ledgers are kept");
101971
+ if (put === "created") throw new Error("the Alexa link record does not match the legacy settings; nothing was cleared");
101972
+ return {
101973
+ outcome: "already-done",
101974
+ summary: { moved: false }
101975
+ };
101976
+ }
101977
+ if (tokens.length > 0) await ports.clearOldTokenSecrets();
101978
+ return put === "created" ? {
101979
+ outcome: "done",
101980
+ summary: {
101981
+ moved: true,
101982
+ accounts: linkedAccounts.length
101983
+ }
101984
+ } : {
101985
+ outcome: "already-done",
101986
+ summary: { moved: false }
101987
+ };
101988
+ }
101989
+ /** Whether a stored token entry still carries a credential: text, or a keychain marker. */
101990
+ function carriesCredential(entry) {
101991
+ if (typeof entry !== "object" || entry === null) return false;
101992
+ return [
101993
+ "accessToken",
101994
+ "refreshToken",
101995
+ "brokerCredential"
101996
+ ].some((key) => {
101997
+ const value = Reflect.get(entry, key);
101998
+ if (typeof value === "string") return value.length > 0;
101999
+ return typeof value === "object" && value !== null;
102000
+ });
102001
+ }
102002
+ var rowId = (key) => `${ALEXA_INSTANCE_ID}.${key}`;
102003
+ async function planDropMovedSettings(ports) {
102004
+ const stored = await ports.readRawStored();
102005
+ const skillKeys = MOVED_SKILL_KEYS.filter((key) => key in stored);
102006
+ const ledgerKeys = MOVED_LEDGER_KEYS.filter((key) => key in stored);
102007
+ if (skillKeys.length === 0 && ledgerKeys.length === 0) return { edits: [] };
102008
+ const refuse = (reason) => {
102009
+ ports.warn(`Alexa migration: the legacy keys are kept: ${reason}`);
102010
+ throw new Error(`the legacy Alexa keys are not deleted: ${reason}`);
102011
+ };
102012
+ if (skillKeys.length > 0 && !await ports.hasSkill()) return refuse("no Alexa skill record exists");
102013
+ if (ledgerKeys.length > 0) {
102014
+ const links = await ports.readLinks();
102015
+ if (links === null) return refuse("no Alexa link record exists");
102016
+ const held = new Set(links.linkedAccounts.map((a) => a.userId));
102017
+ const heldTokens = new Set(links.tokens.map((t) => t.userId));
102018
+ const legacyTokens = stored["tokens"];
102019
+ if (Array.isArray(legacyTokens) && legacyTokens.some(carriesCredential)) return refuse("the old settings still carry Amazon push credentials");
102020
+ for (const account of accountsOf(stored["linkedAccounts"])) if (!held.has(account.userId)) return refuse(`the record lacks the account ${account.userId}`);
102021
+ for (const token of tokensOf(stored["tokens"])) if (!heldTokens.has(token.userId)) return refuse(`the record lacks the grant ${token.userId}`);
102022
+ }
102023
+ const present = [...skillKeys, ...ledgerKeys];
102024
+ return { edits: [{
102025
+ op: "deleteKeys",
102026
+ scope: ADDON_SETTINGS_TABLE,
102027
+ keys: present.map(rowId),
102028
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [rowId(key), {
102029
+ addonId: ALEXA_INSTANCE_ID,
102030
+ key,
102031
+ value: stored[key]
102032
+ }])))
102033
+ }] };
102034
+ }
102035
+ //#endregion
100483
102036
  //#region src/migrations/index.ts
100484
- /** The `export-alexa` catalogue (D987): offered to the engine when the addon initialises. */
100485
- var ADDON_MIGRATIONS = [{
100486
- meta: {
100487
- id: "export-alexa/2026-11-02-drop-public-hub-url",
100488
- owner: "export-alexa",
100489
- level: "addon-state",
100490
- seq: 1,
100491
- dependsOn: [],
100492
- store: "settings",
100493
- scope: "cluster",
100494
- onFailure: "tolerate",
100495
- bodyKind: "plan",
100496
- description: "Delete the retired publicHubUrl setting; the public URL is the publicEndpoint role",
100497
- fixtureMark: "the exposed device list the migration does not know"
100498
- },
100499
- plan: planDropPublicHubUrl
100500
- }];
102037
+ var DROP_PUBLIC_HUB_URL_ID = "export-alexa/2026-11-02-drop-public-hub-url";
102038
+ var SETTINGS_TO_INTEGRATION_ID = "export-alexa/2026-11-03-settings-to-integration";
102039
+ var LEDGERS_TO_INTEGRATION_ID = "export-alexa/2026-11-03-ledgers-to-integration";
102040
+ var DROP_MOVED_SETTINGS_ID = "export-alexa/2026-11-03-drop-moved-settings";
102041
+ var FIXTURE_MARK = "the exposed device list the migration does not know";
102042
+ /**
102043
+ * The `export-alexa` catalogue (D987): offered to the engine when the addon initialises. Every
102044
+ * entry is `tolerate`; until a record exists the addon keeps reading the legacy keys.
102045
+ */
102046
+ var ADDON_MIGRATIONS = [
102047
+ {
102048
+ meta: {
102049
+ id: DROP_PUBLIC_HUB_URL_ID,
102050
+ owner: "export-alexa",
102051
+ level: "addon-state",
102052
+ seq: 1,
102053
+ dependsOn: [],
102054
+ store: "settings",
102055
+ scope: "cluster",
102056
+ onFailure: "tolerate",
102057
+ bodyKind: "plan",
102058
+ description: "Delete the retired publicHubUrl setting; the public URL is the publicEndpoint role",
102059
+ fixtureMark: FIXTURE_MARK
102060
+ },
102061
+ plan: planDropPublicHubUrl
102062
+ },
102063
+ {
102064
+ meta: {
102065
+ id: SETTINGS_TO_INTEGRATION_ID,
102066
+ owner: "export-alexa",
102067
+ level: "addon-state",
102068
+ seq: 2,
102069
+ dependsOn: [],
102070
+ store: "settings",
102071
+ scope: "cluster",
102072
+ onFailure: "tolerate",
102073
+ bodyKind: "procedure",
102074
+ description: "Move the Alexa skill settings (mode, region, audience, feature switches) into the skills record",
102075
+ fixtureMark: FIXTURE_MARK
102076
+ },
102077
+ procedure: moveSettingsToSkill
102078
+ },
102079
+ {
102080
+ meta: {
102081
+ id: LEDGERS_TO_INTEGRATION_ID,
102082
+ owner: "export-alexa",
102083
+ level: "addon-state",
102084
+ seq: 3,
102085
+ dependsOn: [SETTINGS_TO_INTEGRATION_ID],
102086
+ store: "settings",
102087
+ scope: "cluster",
102088
+ onFailure: "tolerate",
102089
+ bodyKind: "procedure",
102090
+ description: "Move the linked accounts and Amazon push grants into the skill-links record; the old credentials are cleared only after the record reads back identical",
102091
+ fixtureMark: FIXTURE_MARK
102092
+ },
102093
+ procedure: moveLedgersToLinks
102094
+ },
102095
+ {
102096
+ meta: {
102097
+ id: DROP_MOVED_SETTINGS_ID,
102098
+ owner: "export-alexa",
102099
+ level: "addon-state",
102100
+ seq: 4,
102101
+ dependsOn: [SETTINGS_TO_INTEGRATION_ID, LEDGERS_TO_INTEGRATION_ID],
102102
+ store: "settings",
102103
+ scope: "cluster",
102104
+ onFailure: "tolerate",
102105
+ bodyKind: "plan",
102106
+ description: "Delete the Alexa settings and ledger keys that moved into the records",
102107
+ fixtureMark: FIXTURE_MARK
102108
+ },
102109
+ plan: planDropMovedSettings
102110
+ }
102111
+ ];
100501
102112
  //#endregion
100502
102113
  //#region src/oauth-integration.ts
100503
102114
  /**
@@ -101840,6 +103451,11 @@ var SUPPORTED_KINDS = [
101840
103451
  DeviceType.Cover,
101841
103452
  DeviceType.Generic
101842
103453
  ];
103454
+ /** Whether a stored token entry still carries a keychain marker instead of a resolved credential. */
103455
+ function hasUnresolvedCredential(entry) {
103456
+ if (typeof entry !== "object" || entry === null) return false;
103457
+ return "accessToken" in entry && isSecretMarker(entry.accessToken) || "refreshToken" in entry && isSecretMarker(entry.refreshToken) || "brokerCredential" in entry && isSecretMarker(entry.brokerCredential);
103458
+ }
101843
103459
  var ExportAlexaAddon = class extends BaseAddon {
101844
103460
  /** Hidden state that is a credential — kept in the keychain, never the blob (D787). */
101845
103461
  secretStatePaths = [
@@ -101875,13 +103491,69 @@ var ExportAlexaAddon = class extends BaseAddon {
101875
103491
  constructor() {
101876
103492
  super({ ...DEFAULT_CONFIG });
101877
103493
  }
103494
+ instances = null;
103495
+ /** The `skills` record, once it exists; until then the legacy settings keys answer. */
103496
+ skillRow = null;
103497
+ /** The `skill-links` record, once it exists; until then the legacy ledger keys answer. */
103498
+ linksRow = null;
103499
+ /** The keychain refused the link credentials: the ledger is read-only until it answers (D49). */
103500
+ linksLocked = false;
103501
+ /**
103502
+ * The settings as the addon reads them: the records where they exist, the legacy keys until
103503
+ * the migrations have moved them.
103504
+ */
103505
+ get view() {
103506
+ const skill = this.skillRow;
103507
+ const links = this.linksRow;
103508
+ if (skill === null && links === null) return this.config;
103509
+ return {
103510
+ ...this.config,
103511
+ ...skill === null ? {} : {
103512
+ skillMode: skill.skillMode,
103513
+ region: skill.region,
103514
+ expectedAudience: skill.expectedAudience,
103515
+ detectionSensors: skill.detectionSensors,
103516
+ objectDetection: skill.objectDetection,
103517
+ snapshots: skill.snapshots,
103518
+ enforceIngressToken: skill.enforceIngressToken
103519
+ },
103520
+ ...links === null ? {} : {
103521
+ linkedAccounts: links.linkedAccounts,
103522
+ tokens: links.tokens
103523
+ }
103524
+ };
103525
+ }
101878
103526
  /**
101879
103527
  * The hub's public origin: the `publicEndpoint` role of `local-network`, read on every use
101880
103528
  * through `ctx.api` (planning#378). No setting holds it and nothing ranks the palette here.
101881
103529
  */
101882
103530
  publicEndpoint = createPublicEndpointReader(() => this.ctx.api.localNetwork.getAddresses.query());
101883
103531
  async onInitialize() {
101884
- await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, { readStored: async () => this.resolveGlobalStore() }));
103532
+ const records = this.ctx.records;
103533
+ if (records === void 0) throw new Error("export-alexa needs ctx.records — check execution.placement (hub-only)");
103534
+ await records.declare({
103535
+ skills: alexaSkillsKind,
103536
+ "skill-links": alexaSkillLinksKind
103537
+ });
103538
+ this.instances = new RecordIntegrationInstances(records, alexaSkillsKind, {
103539
+ description: {
103540
+ instanceMode: "single",
103541
+ kind: "skills",
103542
+ canTest: false
103543
+ },
103544
+ formSchema: () => this.skillForm(),
103545
+ initialBody: (name) => ({
103546
+ ...ALEXA_SKILL_DEFAULT_BODY,
103547
+ name
103548
+ }),
103549
+ configured: () => true,
103550
+ onChanged: async () => {
103551
+ await this.refreshRecords();
103552
+ await this.onConfigChanged();
103553
+ }
103554
+ });
103555
+ await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, this.migrationPorts()));
103556
+ await this.refreshRecords();
101885
103557
  if (!this.config.ingressToken) await this.updateGlobalSettings({ ingressToken: generateIngressToken() });
101886
103558
  if (!this.config.snapshotSigningKey) await this.updateGlobalSettings({ snapshotSigningKey: generateIngressToken() });
101887
103559
  if (!this.config.visionNamespace) await this.updateGlobalSettings({ visionNamespace: (0, node_crypto.randomUUID)() });
@@ -101899,7 +103571,7 @@ var ExportAlexaAddon = class extends BaseAddon {
101899
103571
  });
101900
103572
  this.visibilityRef = new AccountVisibilityMirror({
101901
103573
  gate: this.accessGateRef,
101902
- listLinkedUserIds: () => this.config.linkedAccounts.map((a) => a.userId),
103574
+ listLinkedUserIds: () => this.view.linkedAccounts.map((a) => a.userId),
101903
103575
  listExposedDeviceIds: () => this.config.exposed.map((e) => e.deviceId),
101904
103576
  getStored: () => this.config.accountVisibility,
101905
103577
  setStored: (next) => this.updateGlobalSettings({ accountVisibility: next }),
@@ -101908,8 +103580,8 @@ var ExportAlexaAddon = class extends BaseAddon {
101908
103580
  this.visionRef = new AlexaVisionRuntime({
101909
103581
  ctx: this.ctx,
101910
103582
  logger: this.ctx.logger,
101911
- integrationOn: () => this.config.objectDetection,
101912
- snapshotsOn: () => this.config.snapshots,
103583
+ integrationOn: () => this.view.objectDetection,
103584
+ snapshotsOn: () => this.view.snapshots,
101913
103585
  isExposed: (deviceId) => this.config.exposed.some((e) => e.deviceId === deviceId),
101914
103586
  knownClasses: (deviceId) => this.config.detectionClasses[deviceId]?.classes ?? [],
101915
103587
  namespace: () => this.config.visionNamespace,
@@ -101920,12 +103592,12 @@ var ExportAlexaAddon = class extends BaseAddon {
101920
103592
  this.actionScenes = new ActionSceneExports({
101921
103593
  api: this.ctx.api,
101922
103594
  logger: this.ctx.logger,
101923
- linkedUserIds: () => this.config.linkedAccounts.map((a) => a.userId),
103595
+ linkedUserIds: () => this.view.linkedAccounts.map((a) => a.userId),
101924
103596
  isAdminUser: async (userId) => {
101925
103597
  const lookup = await this.accessGate.principal(userId);
101926
103598
  return lookup.kind === "found" && lookup.principal.kind === "admin";
101927
103599
  },
101928
- canPush: () => this.config.tokens.length > 0,
103600
+ canPush: () => this.view.tokens.length > 0,
101929
103601
  postAddOrUpdate: (userId, endpoints) => this.requireGateway().postReport(userId, (accessToken) => buildAddOrUpdateReportPayload(userId, endpoints, accessToken), `action scenes add/update (${endpoints.length})`),
101930
103602
  postDelete: (userId, ids) => this.requireGateway().postReport(userId, (accessToken) => buildDeleteReportPayload(userId, ids, accessToken), `action scenes delete (${ids.length})`),
101931
103603
  persist: (entries) => this.updateGlobalSettings({ exposedActions: [...entries] })
@@ -101936,7 +103608,7 @@ var ExportAlexaAddon = class extends BaseAddon {
101936
103608
  });
101937
103609
  const deviceExportProvider = {
101938
103610
  getStatus: async () => ({
101939
- linkState: this.config.linkedAccounts.length > 0 ? "linked" : "unlinked",
103611
+ linkState: this.view.linkedAccounts.length > 0 ? "linked" : "unlinked",
101940
103612
  exposedDeviceCount: this.config.exposed.length,
101941
103613
  setup: await this.buildSetupBlock()
101942
103614
  }),
@@ -102024,6 +103696,10 @@ var ExportAlexaAddon = class extends BaseAddon {
102024
103696
  ctx: this.ctx,
102025
103697
  logger: this.ctx.logger
102026
103698
  },
103699
+ mediaPlayerController: {
103700
+ ctx: this.ctx,
103701
+ logger: this.ctx.logger
103702
+ },
102027
103703
  coverController: {
102028
103704
  ctx: this.ctx,
102029
103705
  logger: this.ctx.logger,
@@ -102033,7 +103709,7 @@ var ExportAlexaAddon = class extends BaseAddon {
102033
103709
  ctx: this.ctx,
102034
103710
  logger: this.ctx.logger,
102035
103711
  store: this.snapshotStore,
102036
- enabled: () => this.config.snapshots,
103712
+ enabled: () => this.view.snapshots,
102037
103713
  publicEndpoint: this.publicEndpoint
102038
103714
  },
102039
103715
  vision: this.vision.context(),
@@ -102055,7 +103731,7 @@ var ExportAlexaAddon = class extends BaseAddon {
102055
103731
  onBrokerAdvertised: (raw) => this.rememberAdvertisedBroker(raw),
102056
103732
  snapshotRoute: {
102057
103733
  store: this.snapshotStore,
102058
- enabled: () => this.config.snapshots,
103734
+ enabled: () => this.view.snapshots,
102059
103735
  verifyToken: (token) => this.verifyAccountLinkToken(token),
102060
103736
  mayView: async (userId, deviceId) => {
102061
103737
  const lookup = await this.accessGate.principal(userId);
@@ -102083,13 +103759,13 @@ var ExportAlexaAddon = class extends BaseAddon {
102083
103759
  onExposedDoorbellPress: (deviceId) => {
102084
103760
  this.egressPrewarm?.onPress(deviceId);
102085
103761
  },
102086
- listLinkedAccounts: () => this.config.linkedAccounts,
102087
- listTokens: () => this.config.tokens,
103762
+ listLinkedAccounts: () => this.view.linkedAccounts,
103763
+ listTokens: () => this.view.tokens,
102088
103764
  upsertToken: (input) => this.upsertToken(input),
102089
103765
  removeLinkedAccount: (userId) => this.removeLinkedAccount(userId),
102090
103766
  getAdvertisedBrokerUrl: () => this.config.advertisedBrokerUrl || null,
102091
103767
  getPublicEndpoint: this.publicEndpoint,
102092
- getRegion: () => this.config.region,
103768
+ getRegion: () => this.view.region,
102093
103769
  getExportedSignature: (deviceId) => this.config.exportedSignatures[deviceId] ?? null,
102094
103770
  accountMaySee: (userId, deviceId) => this.visibility.allows(userId, deviceId)
102095
103771
  });
@@ -102097,7 +103773,7 @@ var ExportAlexaAddon = class extends BaseAddon {
102097
103773
  const gatewayForFeed = this.lwaGateway;
102098
103774
  this.detectionFeed = new DetectionSensorFeed({
102099
103775
  eventBus: this.ctx.eventBus,
102100
- enabled: () => this.config.detectionSensors,
103776
+ enabled: () => this.view.detectionSensors,
102101
103777
  isExposed: (deviceId) => this.config.exposed.some((e) => e.deviceId === deviceId),
102102
103778
  readActiveTracks: async (deviceId) => {
102103
103779
  return (await this.ctx.api.pipelineAnalytics.getActiveTracks.query({ deviceId })).map((t) => ({
@@ -102143,8 +103819,8 @@ var ExportAlexaAddon = class extends BaseAddon {
102143
103819
  this.syncEngine = new SyncEngine({
102144
103820
  logger: this.ctx.logger,
102145
103821
  listExposed: () => this.config.exposed,
102146
- listLinkedAccounts: () => this.config.linkedAccounts,
102147
- hasProactiveCredentials: () => this.config.tokens.length > 0,
103822
+ listLinkedAccounts: () => this.view.linkedAccounts,
103823
+ hasProactiveCredentials: () => this.view.tokens.length > 0,
102148
103824
  buildEndpoints: (deviceId) => this.buildEndpointsForOneDevice(deviceId),
102149
103825
  filterForAccount: (userId, endpoints) => this.filterForAccount(userId, endpoints),
102150
103826
  afterPush: (userId, endpoints) => this.requireGateway().scheduleInitialConnectivity(userId, endpoints),
@@ -102174,10 +103850,10 @@ var ExportAlexaAddon = class extends BaseAddon {
102174
103850
  this.ctx.addDisposer(async () => clearInterval(reaper));
102175
103851
  this.ctx.logger.info("export-alexa: initialized", { meta: {
102176
103852
  exposedCount: this.config.exposed.length,
102177
- skillMode: this.config.skillMode,
103853
+ skillMode: this.view.skillMode,
102178
103854
  skillIdSet: this.effectiveSettings().expectedAudience.length > 0,
102179
- pushGrants: this.config.tokens.length,
102180
- brokerGrants: this.config.tokens.filter(isBrokerGrant).length
103855
+ pushGrants: this.view.tokens.length,
103856
+ brokerGrants: this.view.tokens.filter(isBrokerGrant).length
102181
103857
  } });
102182
103858
  return {
102183
103859
  providers: [
@@ -102185,6 +103861,10 @@ var ExportAlexaAddon = class extends BaseAddon {
102185
103861
  capability: deviceExportCapability,
102186
103862
  provider: deviceExportProvider
102187
103863
  },
103864
+ {
103865
+ capability: integrationInstancesCapability,
103866
+ provider: this.requireInstances().toProvider()
103867
+ },
102188
103868
  {
102189
103869
  capability: addonRoutesCapability,
102190
103870
  provider: routeProvider
@@ -102292,18 +103972,18 @@ var ExportAlexaAddon = class extends BaseAddon {
102292
103972
  return buildEndpointsForExposedDevice(deviceId, {
102293
103973
  ctx: this.ctx,
102294
103974
  logger: this.ctx.logger,
102295
- snapshots: this.config.snapshots,
102296
- ...this.config.detectionSensors ? { detectionClasses: async (id) => effectiveSensorClasses(await classesOf(id), parseSensorSelection(await vision.readPrefs(id))) } : {},
103975
+ snapshots: this.view.snapshots,
103976
+ ...this.view.detectionSensors ? { detectionClasses: async (id) => effectiveSensorClasses(await classesOf(id), parseSensorSelection(await vision.readPrefs(id))) } : {},
102297
103977
  alexaName: async (id) => readAlexaName(await vision.readPrefs(id)),
102298
- ...this.config.objectDetection ? { objectDetection: async (id) => vision.buildClasses(id, await classesOf(id)) } : {}
103978
+ ...this.view.objectDetection ? { objectDetection: async (id) => vision.buildClasses(id, await classesOf(id)) } : {}
102299
103979
  });
102300
103980
  }
102301
103981
  /** The settings that change every exposed endpoint's shape, as one key. */
102302
103982
  shapeSwitches() {
102303
103983
  return JSON.stringify({
102304
- detectionSensors: this.config.detectionSensors,
102305
- snapshots: this.config.snapshots,
102306
- objectDetection: this.config.objectDetection
103984
+ detectionSensors: this.view.detectionSensors,
103985
+ snapshots: this.view.snapshots,
103986
+ objectDetection: this.view.objectDetection
102307
103987
  });
102308
103988
  }
102309
103989
  /**
@@ -102315,7 +103995,7 @@ var ExportAlexaAddon = class extends BaseAddon {
102315
103995
  const now = this.shapeSwitches();
102316
103996
  if (this.appliedShapeSwitches === null || now === this.appliedShapeSwitches) return;
102317
103997
  this.appliedShapeSwitches = now;
102318
- if (!this.config.snapshots) this.snapshotStore.clear();
103998
+ if (!this.view.snapshots) this.snapshotStore.clear();
102319
103999
  this.ctx.logger.info("export-alexa: an endpoint-shape switch changed — re-syncing every device", { meta: { switches: now } });
102320
104000
  const engine = this.syncEngine;
102321
104001
  if (engine === null) return;
@@ -102325,7 +104005,7 @@ var ExportAlexaAddon = class extends BaseAddon {
102325
104005
  }
102326
104006
  scheduleDetectionClassRefresh() {
102327
104007
  const timer = setInterval(() => {
102328
- if (!this.config.detectionSensors && !this.config.objectDetection) return;
104008
+ if (!this.view.detectionSensors && !this.view.objectDetection) return;
102329
104009
  this.requireSyncEngine().reconcileAllExposed().catch((err) => {
102330
104010
  this.ctx.logger.warn("export-alexa: detection-class refresh failed", { meta: { error: errMsg$1(err) } });
102331
104011
  });
@@ -102467,8 +104147,8 @@ var ExportAlexaAddon = class extends BaseAddon {
102467
104147
  * Throws when nothing can be sent, so the button says why.
102468
104148
  */
102469
104149
  async resyncDiscovery() {
102470
- if (this.config.linkedAccounts.length === 0) throw new Error("No linked Amazon account. Link the skill from the Alexa app first.");
102471
- if (this.config.tokens.length === 0) throw new Error("No Amazon push grant is stored for the linked account, so nothing can be sent. Re-link the skill from the Alexa app.");
104150
+ if (this.view.linkedAccounts.length === 0) throw new Error("No linked Amazon account. Link the skill from the Alexa app first.");
104151
+ if (this.view.tokens.length === 0) throw new Error("No Amazon push grant is stored for the linked account, so nothing can be sent. Re-link the skill from the Alexa app.");
102472
104152
  const r = await this.requireSyncEngine().resync();
102473
104153
  this.ctx.logger.info("export-alexa: manual discovery re-sync", { meta: { ...r } });
102474
104154
  return r;
@@ -102517,11 +104197,13 @@ var ExportAlexaAddon = class extends BaseAddon {
102517
104197
  }
102518
104198
  this.ctx.logger.warn("export-alexa: revokeOauthSession reported failure — the session may already be gone", { meta: { sessionId: id } });
102519
104199
  }
102520
- await this.revokeAtBroker(this.config.tokens);
102521
- const removedAccounts = this.config.linkedAccounts.length;
102522
- await this.updateGlobalSettings({
104200
+ await this.revokeAtBroker(this.view.tokens);
104201
+ const removedAccounts = this.view.linkedAccounts.length;
104202
+ await this.writeLedger({
102523
104203
  linkedAccounts: [],
102524
- tokens: [],
104204
+ tokens: []
104205
+ });
104206
+ await this.updateGlobalSettings({
102525
104207
  exportedEndpoints: {},
102526
104208
  exportedSignatures: {},
102527
104209
  accountVisibility: {}
@@ -102546,25 +104228,25 @@ var ExportAlexaAddon = class extends BaseAddon {
102546
104228
  ...input.brokerUrl ? { brokerUrl: input.brokerUrl } : {},
102547
104229
  ...input.brokerCredential ? { brokerCredential: input.brokerCredential } : {}
102548
104230
  };
102549
- const next = this.config.tokens.filter((t) => t.userId !== input.userId);
104231
+ const next = this.view.tokens.filter((t) => t.userId !== input.userId);
102550
104232
  next.push(entry);
102551
- await this.updateGlobalSettings({ tokens: next });
104233
+ await this.writeLedger({ tokens: next });
102552
104234
  }
102553
104235
  async removeLinkedAccount(userId) {
102554
- await this.updateGlobalSettings({
102555
- tokens: this.config.tokens.filter((t) => t.userId !== userId),
102556
- linkedAccounts: this.config.linkedAccounts.filter((a) => a.userId !== userId)
104236
+ await this.writeLedger({
104237
+ tokens: this.view.tokens.filter((t) => t.userId !== userId),
104238
+ linkedAccounts: this.view.linkedAccounts.filter((a) => a.userId !== userId)
102557
104239
  });
102558
104240
  this.ctx.logger.warn("export-alexa: unlinked revoked account", { meta: { userId } });
102559
104241
  }
102560
104242
  async recordLinkedAccount(input) {
102561
- if (this.config.linkedAccounts.some((a) => a.userId === input.userId)) return;
102562
- const next = [...this.config.linkedAccounts, {
104243
+ if (this.view.linkedAccounts.some((a) => a.userId === input.userId)) return;
104244
+ const next = [...this.view.linkedAccounts, {
102563
104245
  userId: input.userId,
102564
104246
  username: input.username,
102565
104247
  linkedAt: Date.now()
102566
104248
  }];
102567
- await this.updateGlobalSettings({ linkedAccounts: next });
104249
+ await this.writeLedger({ linkedAccounts: next });
102568
104250
  const engine = this.syncEngine;
102569
104251
  if (!engine) return;
102570
104252
  engine.pushAllToAccount(input.userId).then((r) => {
@@ -102583,8 +104265,8 @@ var ExportAlexaAddon = class extends BaseAddon {
102583
104265
  * token carries none). Idempotent via recordLinkedAccount.
102584
104266
  */
102585
104267
  async backfillLinkedAccounts() {
102586
- const linked = new Set(this.config.linkedAccounts.map((a) => a.userId));
102587
- const missing = this.config.tokens.filter((t) => !linked.has(t.userId));
104268
+ const linked = new Set(this.view.linkedAccounts.map((a) => a.userId));
104269
+ const missing = this.view.tokens.filter((t) => !linked.has(t.userId));
102588
104270
  for (const t of missing) await this.recordLinkedAccount({
102589
104271
  userId: t.userId,
102590
104272
  username: t.userId
@@ -102626,10 +104308,10 @@ var ExportAlexaAddon = class extends BaseAddon {
102626
104308
  * broker no longer recognises is reported, not retried — re-link instead.
102627
104309
  */
102628
104310
  async rotateBrokerCredentials() {
102629
- if (!this.config.tokens.some(isBrokerGrant)) throw new Error("No link is held at the skill's token broker, so there is no credential to rotate. Link the skill from the Alexa app first.");
104311
+ if (!this.view.tokens.some(isBrokerGrant)) throw new Error("No link is held at the skill's token broker, so there is no credential to rotate. Link the skill from the Alexa app first.");
102630
104312
  let rotated = 0;
102631
104313
  let failed = 0;
102632
- for (const t of this.config.tokens) {
104314
+ for (const t of this.view.tokens) {
102633
104315
  if (!isBrokerGrant(t)) continue;
102634
104316
  try {
102635
104317
  const next = await rotateBrokerCredential(fetch, t.brokerUrl, t.brokerCredential);
@@ -102681,17 +104363,133 @@ var ExportAlexaAddon = class extends BaseAddon {
102681
104363
  return buildAlexaSetupBlock({
102682
104364
  publicEndpoint: await this.publicEndpoint(),
102683
104365
  ingressToken: this.config.ingressToken,
102684
- skillMode: this.config.skillMode
104366
+ skillMode: this.view.skillMode
104367
+ });
104368
+ }
104369
+ requireInstances() {
104370
+ if (this.instances === null) throw new Error("export-alexa: the instances are not open");
104371
+ return this.instances;
104372
+ }
104373
+ skillHandle() {
104374
+ const records = this.ctx.records;
104375
+ if (records === void 0) throw new Error("records are not available");
104376
+ return records.kind(alexaSkillsKind);
104377
+ }
104378
+ linksHandle() {
104379
+ const records = this.ctx.records;
104380
+ if (records === void 0) throw new Error("records are not available");
104381
+ return records.kind(alexaSkillLinksKind);
104382
+ }
104383
+ /** Re-read both records. A failed read changes nothing: the addon keeps what it has. */
104384
+ async refreshRecords() {
104385
+ try {
104386
+ this.skillRow = (await this.skillHandle().getResolved("export-alexa"))?.data ?? null;
104387
+ } catch (err) {
104388
+ this.ctx.logger.warn("export-alexa: the skill record could not be read", {
104389
+ meta: { error: errMsg$1(err) },
104390
+ tags: {
104391
+ topic: "export-alexa",
104392
+ phase: "records-read-failed"
104393
+ }
104394
+ });
104395
+ }
104396
+ try {
104397
+ this.linksRow = (await this.linksHandle().getResolved("export-alexa"))?.data ?? null;
104398
+ this.linksLocked = false;
104399
+ } catch (err) {
104400
+ if (!(err instanceof RecordSecretUnavailableError)) {
104401
+ this.ctx.logger.warn("export-alexa: the link record could not be read", {
104402
+ meta: { error: errMsg$1(err) },
104403
+ tags: {
104404
+ topic: "export-alexa",
104405
+ phase: "records-read-failed"
104406
+ }
104407
+ });
104408
+ return;
104409
+ }
104410
+ this.linksLocked = true;
104411
+ this.ctx.logger.warn("export-alexa: the keychain is locked; the link ledger is read-only", { tags: {
104412
+ topic: "export-alexa",
104413
+ phase: "keychain-locked"
104414
+ } });
104415
+ }
104416
+ }
104417
+ /**
104418
+ * Write the account-link ledgers: to the `skill-links` record once it exists, to the legacy
104419
+ * settings keys until then (the migration moves them).
104420
+ */
104421
+ async writeLedger(patch) {
104422
+ if (this.linksRow === null) {
104423
+ await this.updateGlobalSettings({
104424
+ ...patch.linkedAccounts === void 0 ? {} : { linkedAccounts: patch.linkedAccounts },
104425
+ ...patch.tokens === void 0 ? {} : { tokens: patch.tokens }
104426
+ });
104427
+ return;
104428
+ }
104429
+ if (this.linksLocked) throw new Error("the keychain is locked: the Amazon link ledger cannot be changed right now");
104430
+ const next = {
104431
+ name: this.linksRow.name,
104432
+ linkedAccounts: patch.linkedAccounts ?? this.linksRow.linkedAccounts,
104433
+ tokens: patch.tokens ?? this.linksRow.tokens
104434
+ };
104435
+ await this.linksHandle().put({
104436
+ id: ALEXA_INSTANCE_ID,
104437
+ data: next
102685
104438
  });
104439
+ this.linksRow = next;
104440
+ }
104441
+ /** The ports of the settings migrations: the old settings in, the records out. */
104442
+ migrationPorts() {
104443
+ const skills = this.skillHandle();
104444
+ const links = this.linksHandle();
104445
+ const putOnce = async (handle, body) => {
104446
+ if (await handle.get("export-alexa") !== null) return "exists";
104447
+ try {
104448
+ await handle.put({
104449
+ id: ALEXA_INSTANCE_ID,
104450
+ data: body
104451
+ }, { ifRev: 0 });
104452
+ } catch (err) {
104453
+ if (err instanceof RevConflictError) return "exists";
104454
+ throw err;
104455
+ }
104456
+ return "created";
104457
+ };
104458
+ return {
104459
+ readStored: async () => {
104460
+ const stored = await this.resolveGlobalStore();
104461
+ const tokens = stored["tokens"];
104462
+ if (Array.isArray(tokens) && tokens.some(hasUnresolvedCredential)) throw new Error("the old Amazon push grants could not be resolved");
104463
+ return stored;
104464
+ },
104465
+ readRawStored: async () => await this.ctx.settings?.readAddonStore() ?? {},
104466
+ warn: (message) => {
104467
+ this.ctx.logger.warn(message, { tags: {
104468
+ topic: "export-alexa",
104469
+ phase: "migration"
104470
+ } });
104471
+ },
104472
+ putSkill: (body) => putOnce(skills, body),
104473
+ putLinks: (body) => putOnce(links, body),
104474
+ readLinks: async () => (await links.getResolved("export-alexa"))?.data ?? null,
104475
+ hasSkill: async () => await skills.get(ALEXA_INSTANCE_ID) !== null,
104476
+ clearOldTokenSecrets: async () => {
104477
+ await this.clearSecrets(["tokens"]);
104478
+ }
104479
+ };
104480
+ }
104481
+ /** The instance form: how the skill reaches this hub and what each camera carries. */
104482
+ skillForm() {
104483
+ return { sections: buildAlexaInstanceSections({ defaults: ALEXA_SKILL_DEFAULT_BODY }) };
102686
104484
  }
102687
104485
  /** The settings page: see `settings-schema.ts` for its layout. The account-
102688
104486
  * linking rows live in the `device-export` setup block instead. */
102689
104487
  globalSettingsSchema() {
102690
104488
  return { sections: buildAlexaSettingsSections({
102691
- linkedAccounts: this.config.linkedAccounts,
102692
- tokens: this.config.tokens,
104489
+ linkedAccounts: this.view.linkedAccounts,
104490
+ tokens: this.view.tokens,
102693
104491
  now: Date.now(),
102694
- defaults: DEFAULT_CONFIG
104492
+ skillMode: this.view.skillMode
102695
104493
  }) };
102696
104494
  }
102697
104495
  /**
@@ -102732,7 +104530,7 @@ var ExportAlexaAddon = class extends BaseAddon {
102732
104530
  const settings = entry?.settings ?? DEFAULT_DEVICE_SETTINGS;
102733
104531
  const enabled = entry !== null;
102734
104532
  const enabledKey = `alexa:${deviceId}:enabled`;
102735
- const linkedCount = this.config.linkedAccounts.length;
104533
+ const linkedCount = this.view.linkedAccounts.length;
102736
104534
  const statusLabel = enabled ? `Exposed${linkedCount > 0 ? `, ${linkedCount} linked Alexa account(s)` : " (no linked Alexa account yet)"}` : linkedCount > 0 ? `${linkedCount} linked Alexa account(s) — device not exposed` : "Not exposed";
102737
104535
  return {
102738
104536
  tabs: [{
@@ -102799,12 +104597,12 @@ var ExportAlexaAddon = class extends BaseAddon {
102799
104597
  available: this.detectionClassSource === null ? [] : await this.detectionClassSource.classesFor(deviceId).catch(() => []),
102800
104598
  saved: parseSensorSelection(store),
102801
104599
  enabledKey,
102802
- masterOn: this.config.detectionSensors
104600
+ masterOn: this.view.detectionSensors
102803
104601
  }), objectDetectionField({
102804
104602
  deviceId,
102805
104603
  store,
102806
104604
  enabledKey,
102807
- integrationOn: this.config.objectDetection
104605
+ integrationOn: this.view.objectDetection
102808
104606
  })];
102809
104607
  }
102810
104608
  /**