@camstack/addon-export-google 0.1.125 → 0.1.127

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.
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  //#region src/google-home/cap-dispatch.ts
2
3
  async function dispatchCapCall(api, call) {
3
4
  switch (call.kind) {
@@ -6055,7 +6056,7 @@ var ZodIssueCode = {
6055
6056
  var ZodFirstPartyTypeKind;
6056
6057
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
6057
6058
  //#endregion
6058
- //#region ../types/dist/sleep-BaWhXZFm.mjs
6059
+ //#region ../types/dist/sleep-9TIHFj1w.mjs
6059
6060
  /**
6060
6061
  * The audio chunk plane's byte format, and the ONE expansion from a coded
6061
6062
  * window to float samples (D455).
@@ -6203,9 +6204,16 @@ function isSecretMarker(value) {
6203
6204
  const ref = value["$secret"];
6204
6205
  return typeof ref === "string" && ref.length > 0;
6205
6206
  }
6207
+ /** Anything carrying a `$secret` key — a stored marker or a UI view of one. */
6208
+ function isSecretMarkerLike(value) {
6209
+ return isRecord$7(value) && Object.prototype.hasOwnProperty.call(value, "$secret");
6210
+ }
6206
6211
  function isSecretClear(value) {
6207
6212
  return isRecord$7(value) && value["$secretClear"] === true;
6208
6213
  }
6214
+ function isSecretFieldView(value) {
6215
+ return isRecord$7(value) && value["set"] === true && isSecretMarkerLike(value);
6216
+ }
6209
6217
  /**
6210
6218
  * The UI view of a stored secret field value: a marker becomes "set", inline
6211
6219
  * plaintext becomes "set (inline)", nothing becomes `null`. A value never
@@ -6648,7 +6656,7 @@ var NOT_RUN = {
6648
6656
  * throws: an unreachable or refusing engine is logged and reported `declared: false`,
6649
6657
  * because the hub (and this addon's boot) must not hang on a migration.
6650
6658
  */
6651
- async function runAddonMigrations(host, migrations, logger) {
6659
+ async function runAddonMigrations(host, migrations, logger, options = {}) {
6652
6660
  const first = migrations[0];
6653
6661
  if (first === void 0) return NOT_RUN;
6654
6662
  const owner = first.meta.owner;
@@ -6677,7 +6685,9 @@ async function runAddonMigrations(host, migrations, logger) {
6677
6685
  else if (status === "blocked") blocked.push(id);
6678
6686
  else skipped.push(id);
6679
6687
  };
6688
+ const selected = options.only === void 0 ? null : new Set(options.only);
6680
6689
  for (const step of declaration.steps) {
6690
+ if (selected !== null && !selected.has(step.id)) continue;
6681
6691
  const bound = byId.get(step.id);
6682
6692
  if (bound === void 0 || step.action === "skip") {
6683
6693
  skipped.push(step.id);
@@ -6855,11 +6865,36 @@ function projectStore(store, perNodeKeys, nodeId) {
6855
6865
  }
6856
6866
  return out;
6857
6867
  }
6868
+ /**
6869
+ * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6870
+ *
6871
+ * A ref is DETERMINISTIC from where the value lives — the owner addon, the
6872
+ * scope (global, one node, one device, one integration, one row of a business
6873
+ * collection) and the field path inside that scope — so saving the same field
6874
+ * twice updates the same ref, and the ref itself says which settings blob
6875
+ * points at it. It is also the AAD of the value's ciphertext: a ciphertext
6876
+ * copied onto another ref does not decrypt.
6877
+ *
6878
+ * Array items are addressed by ITEM ID, never by index
6879
+ * (`providers[authentik].clientSecret`), so reordering a list keeps every ref.
6880
+ *
6881
+ * Pure and browser-safe: no node builtins, no I/O.
6882
+ */
6883
+ /** The URI scheme of every keychain ref. */
6884
+ var SECRET_REF_SCHEME = "secret://";
6858
6885
  var GLOBAL_SCOPE = { kind: "global" };
6859
6886
  /** The scope every addon-wide (not per-node, not per-device) setting lives in. */
6860
6887
  function globalSecretScope() {
6861
6888
  return GLOBAL_SCOPE;
6862
6889
  }
6890
+ /**
6891
+ * An addon id as a ref owner. A hub in-process builtin's context id is
6892
+ * `addon:<id>`; the owner of its secrets is `<id>`, exactly as for the same
6893
+ * addon running forked.
6894
+ */
6895
+ function normalizeSecretOwner(addonId) {
6896
+ return addonId.startsWith("addon:") ? addonId.slice(6) : addonId;
6897
+ }
6863
6898
  function encodeSegment(value) {
6864
6899
  return encodeURIComponent(value);
6865
6900
  }
@@ -6870,6 +6905,16 @@ function decodeSegment(value) {
6870
6905
  return null;
6871
6906
  }
6872
6907
  }
6908
+ /** The scope as it appears inside a ref (`global`, `node/<id>`, …). */
6909
+ function formatSecretScope(scope) {
6910
+ switch (scope.kind) {
6911
+ case "global": return "global";
6912
+ case "node": return `node/${encodeSegment(scope.nodeId)}`;
6913
+ case "device": return `device/${scope.deviceId}`;
6914
+ case "integration": return `integration/${encodeSegment(scope.integrationId)}`;
6915
+ case "row": return `row/${encodeSegment(scope.collection)}/${encodeSegment(scope.rowId)}`;
6916
+ }
6917
+ }
6873
6918
  /**
6874
6919
  * The field path of a value inside an array item, addressed by the item's id:
6875
6920
  * `arrayItemFieldPath('providers', 'authentik', 'clientSecret')` →
@@ -6878,6 +6923,13 @@ function decodeSegment(value) {
6878
6923
  function arrayItemFieldPath(arrayKey, itemId, fieldKey) {
6879
6924
  return `${arrayKey}[${encodeSegment(itemId)}].${fieldKey}`;
6880
6925
  }
6926
+ /** Build a ref. Throws on an empty owner or field path — both are bugs. */
6927
+ function buildSecretRef(parts) {
6928
+ const owner = normalizeSecretOwner(parts.owner);
6929
+ if (owner.length === 0) throw new Error("buildSecretRef: owner is empty");
6930
+ if (parts.fieldPath.length === 0) throw new Error("buildSecretRef: fieldPath is empty");
6931
+ return `${SECRET_REF_SCHEME}${encodeSegment(owner)}/${formatSecretScope(parts.scope)}/${parts.fieldPath}`;
6932
+ }
6881
6933
  function parseScope(segments) {
6882
6934
  switch (segments[0]) {
6883
6935
  case "global": return {
@@ -7795,14 +7847,18 @@ var BaseAddon = class {
7795
7847
  * nothing; the boot continues. A migration that FAILED (or was blocked by one)
7796
7848
  * and declares `onFailure: 'block-owner'` makes this throw, so the addon does not
7797
7849
  * serve data whose shape it cannot trust; `tolerate` migrations never do.
7850
+ *
7851
+ * ALWAYS pass the whole catalogue; a phase that must run only some of it passes
7852
+ * `{ only: [ids] }` — never a filtered catalogue (the engine would judge the
7853
+ * omitted applied ids "newer").
7798
7854
  */
7799
- async runMigrations(migrations) {
7855
+ async runMigrations(migrations, options) {
7800
7856
  const api = this.ctx.api.migrations;
7801
7857
  const report = await runAddonMigrations({
7802
7858
  declareOwner: (input) => api.declareOwner.mutate(input),
7803
7859
  startMigration: (input) => api.startMigration.mutate(input),
7804
7860
  finishMigration: (input) => api.finishMigration.mutate(input)
7805
- }, migrations, this.ctx.logger);
7861
+ }, migrations, this.ctx.logger, options);
7806
7862
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7807
7863
  return report;
7808
7864
  }
@@ -7944,10 +8000,9 @@ var BaseAddon = class {
7944
8000
  *
7945
8001
  * Override it only when an `instanceMode: multiple` addon's instances differ: an NVR integration
7946
8002
  * needs its connection fields, the default integration the addon's own sections. It is the
7947
- * SHAPE of the form only — the values live in `integrations.getSettings`, and the write path is
7948
- * unchanged (`integrations.setSettings` for an account integration).
8003
+ * SHAPE of the form only — the values live on the instance record.
7949
8004
  */
7950
- async integrationSettingsSchema(_instance) {
8005
+ async integrationFormSchema(_instance) {
7951
8006
  return null;
7952
8007
  }
7953
8008
  /**
@@ -7993,7 +8048,7 @@ var BaseAddon = class {
7993
8048
  * per-instance schema when it declares one, else its global schema (what they always showed).
7994
8049
  */
7995
8050
  async getIntegrationFormSchema(instance, nodeId) {
7996
- const scoped = await this.integrationSettingsSchema(instance);
8051
+ const scoped = await this.integrationFormSchema(instance);
7997
8052
  if (scoped === null) return this.getGlobalSettings(void 0, void 0, nodeId);
7998
8053
  return hydrateSchema(scoped, {}, { inlineSecretsAsViews: true });
7999
8054
  }
@@ -8805,6 +8860,13 @@ var RevConflictError = class extends RecordsError {
8805
8860
  this.name = "RevConflictError";
8806
8861
  }
8807
8862
  };
8863
+ /** The keychain could not store or serve a value: explicit, never an empty string. */
8864
+ var RecordSecretUnavailableError = class extends RecordsError {
8865
+ constructor(detail) {
8866
+ super("secret-unavailable", detail);
8867
+ this.name = "RecordSecretUnavailableError";
8868
+ }
8869
+ };
8808
8870
  var InvalidRecordError = class extends RecordsError {
8809
8871
  constructor(detail) {
8810
8872
  super("invalid-record", detail);
@@ -8835,6 +8897,8 @@ var RECORD_BATCH_MAX = 1e3;
8835
8897
  var RECORD_QUERY_MAX = 1e3;
8836
8898
  /** A kind in the `settings` file may not bound itself above this (D447: high volume is `events`). */
8837
8899
  var RECORD_SETTINGS_MAX_ROWS = 5e4;
8900
+ /** The `Column`-free proof prefix: a ref collection for a kind's secret fields. */
8901
+ var RECORD_SECRET_COLLECTION_PREFIX = "records:";
8838
8902
  /**
8839
8903
  * Secret fields of a record, addressed the way a Zod schema declares them
8840
8904
  * (`collectZodSecretPaths`): dotted keys, `[]` for "each element of this array"
@@ -8877,6 +8941,128 @@ function secretArrayPrefixes(path) {
8877
8941
  }
8878
8942
  return prefixes;
8879
8943
  }
8944
+ function isRecord$4(value) {
8945
+ return typeof value === "object" && value !== null && !Array.isArray(value);
8946
+ }
8947
+ function elementId(element, idKey, declared, prefix) {
8948
+ const id = isRecord$4(element) ? element[idKey] : void 0;
8949
+ 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`);
8950
+ return id;
8951
+ }
8952
+ /**
8953
+ * Visit every secret leaf PRESENT in `data` (an absent branch has nothing to
8954
+ * visit). `replace` returns the new leaf value, or {@link REMOVE_LEAF}; the
8955
+ * result is a new body, `data` is untouched.
8956
+ */
8957
+ var REMOVE_LEAF = Symbol("remove-leaf");
8958
+ function mapAt(node, segments, index, walkedKeys, concretePrefix, declared, arrayKeys, visit) {
8959
+ if (!isRecord$4(node)) return node;
8960
+ const segment = segments[index];
8961
+ if (segment === void 0) return node;
8962
+ if (!Object.prototype.hasOwnProperty.call(node, segment.key)) return node;
8963
+ const child = node[segment.key];
8964
+ const keys = [...walkedKeys, segment.key];
8965
+ const last = index === segments.length - 1;
8966
+ if (segment.each) {
8967
+ if (!Array.isArray(child)) return node;
8968
+ const prefix = keys.join(".");
8969
+ const idKey = arrayKeys[prefix];
8970
+ if (idKey === void 0) throw new InvalidRecordError(`"${declared}": no id key declared for the array "${prefix}"`);
8971
+ const mapped = child.map((element) => {
8972
+ const id = elementId(element, idKey, declared, prefix);
8973
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}[${encodeURIComponent(id)}]`;
8974
+ return last ? element : mapAt(element, segments, index + 1, keys, concrete, declared, arrayKeys, visit);
8975
+ });
8976
+ return {
8977
+ ...node,
8978
+ [segment.key]: mapped
8979
+ };
8980
+ }
8981
+ if (segment.map) {
8982
+ if (!isRecord$4(child)) return node;
8983
+ const kept = Object.entries(child).map(([mapKey, value]) => {
8984
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}{${encodeURIComponent(mapKey)}}`;
8985
+ if (!last) return [mapKey, mapAt(value, segments, index + 1, keys, concrete, declared, arrayKeys, visit)];
8986
+ return [mapKey, visit({
8987
+ declared,
8988
+ concrete,
8989
+ value
8990
+ })];
8991
+ }).filter(([, value]) => value !== REMOVE_LEAF);
8992
+ return {
8993
+ ...node,
8994
+ [segment.key]: Object.fromEntries(kept)
8995
+ };
8996
+ }
8997
+ const concrete = `${concretePrefix}${concretePrefix.length > 0 ? "." : ""}${segment.key}`;
8998
+ if (last) {
8999
+ const replacement = visit({
9000
+ declared,
9001
+ concrete,
9002
+ value: child
9003
+ });
9004
+ if (replacement === REMOVE_LEAF) return Object.fromEntries(Object.entries(node).filter(([key]) => key !== segment.key));
9005
+ return {
9006
+ ...node,
9007
+ [segment.key]: replacement
9008
+ };
9009
+ }
9010
+ return {
9011
+ ...node,
9012
+ [segment.key]: mapAt(child, segments, index + 1, keys, concrete, declared, arrayKeys, visit)
9013
+ };
9014
+ }
9015
+ /** Replace/remove every present secret leaf; returns a NEW body. */
9016
+ function mapSecretLeaves(data, paths, arrayKeys, visit) {
9017
+ let current = data;
9018
+ for (const declared of paths) current = mapAt(current, parseSecretPath(declared), 0, [], "", declared, arrayKeys, visit);
9019
+ return current;
9020
+ }
9021
+ /**
9022
+ * The keychain collection name a kind's secrets live under. Prefixed so a
9023
+ * record's refs never collide with the refs a legacy collection of the same name
9024
+ * already holds during an adoption.
9025
+ */
9026
+ function recordSecretCollection(kind) {
9027
+ return `${RECORD_SECRET_COLLECTION_PREFIX}${kind}`;
9028
+ }
9029
+ /** The ONE ref a row's secret field may carry: the engine and the facade both build it here. */
9030
+ function recordSecretRef(owner, kind, rowId, concretePath) {
9031
+ return buildSecretRef({
9032
+ owner,
9033
+ scope: {
9034
+ kind: "row",
9035
+ collection: recordSecretCollection(kind),
9036
+ rowId
9037
+ },
9038
+ fieldPath: concretePath
9039
+ });
9040
+ }
9041
+ /**
9042
+ * A stored secret, as an admin read shows it: a VIEW naming the row's own
9043
+ * keychain ref (`set: true`), never the value and no longer the bare redaction
9044
+ * token. The form hands it to the secret field, which reveals the value by ref
9045
+ * through the audited `keychain-admin.reveal`; sent back untouched it keeps the
9046
+ * stored secret (the records door reads a view as KEEP).
9047
+ *
9048
+ * ONE implementation for the entries service and for every addon that serves
9049
+ * its own instances (`RecordIntegrationInstances`).
9050
+ */
9051
+ function isRecord$3(value) {
9052
+ return typeof value === "object" && value !== null && !Array.isArray(value);
9053
+ }
9054
+ function secretViewsOf(owner, kind, id, decl, data) {
9055
+ if (decl.secretPaths.length === 0) return data;
9056
+ const shown = mapSecretLeaves(data, decl.secretPaths, decl.secretArrayKeys, (leaf) => {
9057
+ if (leaf.value !== "__camstack_redacted__") return leaf.value;
9058
+ return {
9059
+ $secret: recordSecretRef(owner, kind, id, leaf.concrete),
9060
+ v: 1,
9061
+ set: true
9062
+ };
9063
+ });
9064
+ return isRecord$3(shown) ? shown : data;
9065
+ }
8880
9066
  /**
8881
9067
  * The share-view scope kinds a share-link token can carry. The hub mints
8882
9068
  * and validates them (`ShareViewGrantSchema` builds its
@@ -9129,6 +9315,7 @@ function defineEntryKind(name, spec) {
9129
9315
  class: "config",
9130
9316
  writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
9131
9317
  retention: { none: "an entry goes only when the operator deletes it" },
9318
+ ...spec.maxDataBytes === void 0 ? {} : { maxDataBytes: spec.maxDataBytes },
9132
9319
  ...spec.database === void 0 ? {} : { database: spec.database },
9133
9320
  ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
9134
9321
  ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
@@ -11794,7 +11981,7 @@ object({
11794
11981
  params: record(string(), union([string(), number()])).optional()
11795
11982
  });
11796
11983
  //#endregion
11797
- //#region ../types/dist/composition-CRNwcFYY.mjs
11984
+ //#region ../types/dist/composition-pOHbTzRB.mjs
11798
11985
  /**
11799
11986
  * The ffmpeg build every CamStack node downloads, per platform and arch.
11800
11987
  *
@@ -13258,6 +13445,205 @@ function buildCapturingReply(envelope) {
13258
13445
  };
13259
13446
  return wrapper;
13260
13447
  }
13448
+ /**
13449
+ * `RecordIntegrationInstances` - the `integration-instances` provider over ONE
13450
+ * entry kind, so an addon that holds a connection serves it in ~30 lines.
13451
+ *
13452
+ * Every instance is one record of the addon's own kind, keyed by the
13453
+ * `integrations` registry id. The records door does the secret work: a field the
13454
+ * kind marks `.meta({ secret: true })` is a keychain marker bound to the row, so
13455
+ * deleting the row deletes the secret, and one row's value is never another's.
13456
+ *
13457
+ * Patch rules for a secret (`updateInstance`): omitted, `''`, the redaction
13458
+ * token or the view the form was given KEEP the stored secret;
13459
+ * `{ $secretClear: true }` clears it; any other string replaces it.
13460
+ */
13461
+ /** The most instances one addon lists (an integrations page, not a table). */
13462
+ var INSTANCES_LIST_MAX = 1e3;
13463
+ /** The keys of the kind's secret fields that sit at the top level of the body. */
13464
+ function topLevelSecretKeys(paths) {
13465
+ return new Set(paths.filter((p) => !p.includes(".") && !p.includes("[") && !p.includes("{")));
13466
+ }
13467
+ /** The keys of the kind's top-level MAPS whose values are secrets (`applianceSecrets{}`). */
13468
+ function secretMapKeys(paths) {
13469
+ return new Set(paths.filter((p) => p.endsWith("{}") && !p.slice(0, -2).match(/[.[{]/)).map((p) => p.slice(0, -2)));
13470
+ }
13471
+ /**
13472
+ * A patch value for a map of secrets: an entry that is omitted, `''`, the redaction token or the
13473
+ * view the form was given KEEPS its stored secret (it is left out of the merge); `{ $secretClear }`
13474
+ * or `null` removes the entry; any other string replaces it. Null when nothing is left to merge.
13475
+ */
13476
+ function secretMapPatch(value) {
13477
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
13478
+ const out = {};
13479
+ for (const [key, entry] of Object.entries(value)) if (entry === null || isSecretClear(entry)) out[key] = null;
13480
+ else if (typeof entry === "string" && entry !== "" && entry !== "__camstack_redacted__" && !isSecretFieldView(entry)) out[key] = entry;
13481
+ return Object.keys(out).length > 0 ? out : null;
13482
+ }
13483
+ /** Does the kind's body schema carry an `enabled` field? */
13484
+ function declaresEnabled(kind) {
13485
+ const json = toJSONSchema(kind.schema, {
13486
+ unrepresentable: "any",
13487
+ io: "input"
13488
+ });
13489
+ const properties = Reflect.get(json, "properties");
13490
+ return typeof properties === "object" && properties !== null && "enabled" in properties;
13491
+ }
13492
+ var RecordIntegrationInstances = class {
13493
+ records;
13494
+ kind;
13495
+ hooks;
13496
+ handle;
13497
+ secretKeys;
13498
+ secretMaps;
13499
+ nameField;
13500
+ /** The `integrations` registry owns the on/off switch (`role: devices`); the body has none. */
13501
+ registryOwnsEnabled;
13502
+ constructor(records, kind, hooks) {
13503
+ this.records = records;
13504
+ this.kind = kind;
13505
+ this.hooks = hooks;
13506
+ this.handle = records.kind(kind);
13507
+ this.secretKeys = topLevelSecretKeys(kind.declaration.secretPaths);
13508
+ this.secretMaps = secretMapKeys(kind.declaration.secretPaths);
13509
+ this.nameField = kind.declaration.entry?.nameField ?? "name";
13510
+ this.registryOwnsEnabled = hooks.description.role === "devices";
13511
+ if (this.registryOwnsEnabled && declaresEnabled(kind)) throw new Error(`kind "${kind.name}": the integrations registry owns the on/off switch of a role "devices" addon, so the body must not declare "enabled"`);
13512
+ }
13513
+ /**
13514
+ * One instance read for the addon's own runtime; null when absent. When the keychain is
13515
+ * locked the row is served WITHOUT its secrets and says so (`secrets: 'unavailable'`), so the
13516
+ * caller can keep what it had instead of reconfiguring with an empty secret (D49).
13517
+ */
13518
+ async readResolved(id) {
13519
+ try {
13520
+ const record = await this.handle.getResolved(id);
13521
+ return record === null ? null : {
13522
+ id,
13523
+ body: record.data,
13524
+ enabled: record.data.enabled !== false,
13525
+ secrets: "resolved"
13526
+ };
13527
+ } catch (err) {
13528
+ if (!(err instanceof RecordSecretUnavailableError)) throw err;
13529
+ const stored = await this.handle.get(id);
13530
+ if (stored === null) return null;
13531
+ return {
13532
+ id,
13533
+ body: Object.fromEntries(Object.entries(stored.data).filter(([key]) => !this.secretKeys.has(key))),
13534
+ enabled: stored.data.enabled !== false,
13535
+ secrets: "unavailable"
13536
+ };
13537
+ }
13538
+ }
13539
+ /** The body of {@link readResolved} alone; a locked keychain yields the row without secrets. */
13540
+ async getResolved(id) {
13541
+ return (await this.readResolved(id))?.body ?? null;
13542
+ }
13543
+ /** Every instance, secrets resolved where the keychain allows; an absent one is skipped. */
13544
+ async listResolved() {
13545
+ const page = await this.handle.query({ limit: INSTANCES_LIST_MAX });
13546
+ const out = [];
13547
+ for (const record of page.records) {
13548
+ const read = await this.readResolved(record.id);
13549
+ if (read !== null) out.push(read);
13550
+ }
13551
+ return out;
13552
+ }
13553
+ viewOf(record) {
13554
+ const shown = secretViewsOf(this.records.owner, this.kind.name, record.id, this.kind.declaration, record.data);
13555
+ const rawName = record.data[this.nameField];
13556
+ const kind = this.hooks.kindOf?.(record.data);
13557
+ const health = this.hooks.health?.(record.data, record.id);
13558
+ return {
13559
+ id: record.id,
13560
+ name: typeof rawName === "string" ? rawName : record.id,
13561
+ configured: this.hooks.configured(record.data),
13562
+ ...this.registryOwnsEnabled ? {} : { enabled: record.data.enabled !== false },
13563
+ formValues: shown,
13564
+ ...kind !== void 0 ? { kind } : {},
13565
+ ...health?.status !== void 0 ? { status: health.status } : {},
13566
+ ...health?.lastCheckedAt !== void 0 ? { lastCheckedAt: health.lastCheckedAt } : {}
13567
+ };
13568
+ }
13569
+ describe = async () => this.hooks.mintId === void 0 ? this.hooks.description : {
13570
+ ...this.hooks.description,
13571
+ mintsId: true
13572
+ };
13573
+ instanceFormSchema = async ({ id }) => this.hooks.formSchema(id);
13574
+ listInstances = async () => {
13575
+ return (await this.handle.query({ limit: INSTANCES_LIST_MAX })).records.map((record) => this.viewOf(record));
13576
+ };
13577
+ getInstance = async ({ id }) => {
13578
+ const record = await this.handle.get(id);
13579
+ return record === null ? null : this.viewOf(record);
13580
+ };
13581
+ /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
13582
+ createInstance = async ({ id, name, kind }) => {
13583
+ const minted = id ?? this.hooks.mintId?.({
13584
+ name,
13585
+ ...kind !== void 0 ? { kind } : {}
13586
+ });
13587
+ if (minted === void 0) throw new Error("createInstance needs an id: this provider does not mint one");
13588
+ await this.handle.put({
13589
+ id: minted,
13590
+ data: this.hooks.initialBody(name, kind)
13591
+ }, { ifRev: 0 });
13592
+ await this.hooks.onChanged?.(minted, "created");
13593
+ return { id: minted };
13594
+ };
13595
+ updateInstance = async ({ id, name, values }) => {
13596
+ const patch = {};
13597
+ for (const [key, value] of Object.entries(values)) {
13598
+ if (value === void 0) continue;
13599
+ if (this.secretMaps.has(key)) {
13600
+ const entries = secretMapPatch(value);
13601
+ if (entries !== null) patch[key] = entries;
13602
+ } else if (!this.secretKeys.has(key)) patch[key] = value;
13603
+ else if (isSecretClear(value)) patch[key] = null;
13604
+ else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
13605
+ }
13606
+ if (name !== void 0) patch[this.nameField] = name;
13607
+ await this.handle.patch(id, patch);
13608
+ await this.hooks.onChanged?.(id, "updated");
13609
+ return { ok: true };
13610
+ };
13611
+ /** The switch lives in the record body; the addon is told so it applies it (D996). */
13612
+ setInstanceEnabled = async ({ id, enabled }) => {
13613
+ if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
13614
+ await this.handle.patch(id, { enabled });
13615
+ await this.hooks.onChanged?.(id, "enabled");
13616
+ return { ok: true };
13617
+ };
13618
+ /** The row and its keychain refs go together (the records door). */
13619
+ deleteInstance = async ({ id }) => {
13620
+ await this.handle.delete(id);
13621
+ await this.hooks.onChanged?.(id, "deleted");
13622
+ return { ok: true };
13623
+ };
13624
+ testInstance = async (input) => {
13625
+ if (this.hooks.test === void 0) return {
13626
+ success: false,
13627
+ status: "unsupported",
13628
+ error: "This integration declares no connection test"
13629
+ };
13630
+ return this.hooks.test(input);
13631
+ };
13632
+ /** The flat provider object to hand to `registerProvider`. */
13633
+ toProvider() {
13634
+ return {
13635
+ describe: this.describe,
13636
+ instanceFormSchema: this.instanceFormSchema,
13637
+ listInstances: this.listInstances,
13638
+ getInstance: this.getInstance,
13639
+ createInstance: this.createInstance,
13640
+ updateInstance: this.updateInstance,
13641
+ setInstanceEnabled: this.setInstanceEnabled,
13642
+ deleteInstance: this.deleteInstance,
13643
+ testInstance: this.testInstance
13644
+ };
13645
+ }
13646
+ };
13261
13647
  var EncodeProfileSchema = object({
13262
13648
  video: object({
13263
13649
  codec: _enum([
@@ -14303,7 +14689,13 @@ var MigrationLedgerEntrySchema = object({
14303
14689
  * joined by the engine from the catalogues it knows this boot. Absent when no
14304
14690
  * catalogue lists the id (a newer database).
14305
14691
  */
14306
- meta: MigrationMetaSchema.optional()
14692
+ meta: MigrationMetaSchema.optional(),
14693
+ /**
14694
+ * Set when this is an applied row of an addon owner whose catalogue the answering
14695
+ * process has not loaded (the owner has not declared yet): the row is applied, the
14696
+ * process just cannot judge it. Never `skipped-newer` — that needs the owner loaded.
14697
+ */
14698
+ ownerNotLoaded: boolean().optional()
14307
14699
  });
14308
14700
  /** A catalogued migration that is not applied, with where it stands. */
14309
14701
  var MigrationPendingEntrySchema = object({
@@ -48915,6 +49307,9 @@ var RunningProposalEvidenceSchema = object({
48915
49307
  runsFound: number().int().nonnegative(),
48916
49308
  pausesFound: number().int().nonnegative(),
48917
49309
  longestPauseMs: number().nonnegative(),
49310
+ /** Episodes shorter than ~90 s (an anti-crease pulse, a display waking): never a run, never a pause. */
49311
+ pulsesFound: number().int().nonnegative(),
49312
+ longestPulseMs: number().nonnegative(),
48918
49313
  idleFloorW: number(),
48919
49314
  noiseCeilingW: number(),
48920
49315
  plateauW: number(),
@@ -50085,13 +50480,6 @@ var ExportInstanceUnknownError = class extends Error {
50085
50480
  function statusInstanceOf(input) {
50086
50481
  return "instanceId" in input ? input.instanceId : void 0;
50087
50482
  }
50088
- /**
50089
- * A single-instance provider's check: an absent id or its own passes, any other throws
50090
- * `ExportInstanceUnknownError`.
50091
- */
50092
- function assertOwnExportInstance(addon, own, instanceId) {
50093
- if (instanceId !== void 0 && instanceId !== own) throw new ExportInstanceUnknownError(addon, instanceId);
50094
- }
50095
50483
  var LinkStateSchema = _enum([
50096
50484
  "unlinked",
50097
50485
  "linked",
@@ -50196,12 +50584,12 @@ var deviceExportCapability = {
50196
50584
  kind: "poll"
50197
50585
  },
50198
50586
  /**
50199
- * Each export provider contributes its own per-device "Export" panel
50200
- * (enabled toggle, preferred stream, addon-specific knobs like the
50201
- * HA-MQTT discovery prefix). The three framework methods
50202
- * `getDeviceSettingsContribution` / `getDeviceLiveContribution` /
50203
- * `applyDeviceSettingsPatch` are auto-injected on the provider
50204
- * interface and routed to the device-details aggregator.
50587
+ * Each export provider MAY contribute its own per-device "Export" panel
50588
+ * (enabled toggle, preferred stream, addon-specific knobs). The three
50589
+ * framework methods are mounted on the cap router when present.
50590
+ * `IDeviceExportProvider` leaves them optional: an exporter with no
50591
+ * per-device panel omits them (a `deviceConfig` cap's UI is derived and
50592
+ * never hand-written — D14 — and an exporter is not one of those).
50205
50593
  */
50206
50594
  exposesDeviceSettings: true,
50207
50595
  methods: {
@@ -53892,11 +54280,7 @@ var CreateIntegrationInputSchema = object({
53892
54280
  info: record(string(), unknown()).optional(),
53893
54281
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
53894
54282
  originStableId: string().optional(),
53895
- settings: record(string(), unknown()).optional(),
53896
- /** Keys of `settings` the form's schema declares secret (by type) — kept in
53897
- * the keychain, not the table (D787). */
53898
- secretKeys: array(string()).optional(),
53899
- skipRestart: boolean().optional()
54283
+ settings: record(string(), unknown()).optional()
53900
54284
  });
53901
54285
  var UpdateIntegrationInputSchema = object({
53902
54286
  id: string(),
@@ -53917,16 +54301,6 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
53917
54301
  }), method(object({ id: string() }), DeleteIntegrationResultSchema, {
53918
54302
  kind: "mutation",
53919
54303
  auth: "admin"
53920
- }), method(object({ id: string() }), record(string(), unknown()), { auth: "admin" }), method(object({
53921
- id: string(),
53922
- settings: record(string(), unknown()),
53923
- /** Keys the form's schema declares secret (by type) — keychain-stored (D787). */
53924
- secretKeys: array(string()).optional(),
53925
- /** The integration's own addon applies the change in-process and asks the hub not to respawn it. */
53926
- skipRestart: boolean().optional()
53927
- }), object({ success: boolean() }), {
53928
- kind: "mutation",
53929
- auth: "admin"
53930
54304
  }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
53931
54305
  addonId: string(),
53932
54306
  settings: record(string(), unknown())
@@ -54051,32 +54425,57 @@ var IntegrationInstancePatchSchema = object({
54051
54425
  /** Omitted / '' / redaction token keeps a secret; `{ $secretClear: true }` clears it. */
54052
54426
  values: record(string(), unknown())
54053
54427
  });
54054
- 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({
54055
- id: IntegrationInstanceIdSchema.optional(),
54056
- name: string().min(1),
54057
- kind: string().min(1).optional()
54058
- }), object({ id: string() }), {
54059
- kind: "mutation",
54060
- auth: "admin"
54061
- }), method(IntegrationInstancePatchSchema, object({ ok: literal(true) }), {
54062
- kind: "mutation",
54063
- auth: "admin"
54064
- }), method(object({
54065
- id: IntegrationInstanceIdSchema,
54066
- enabled: boolean()
54067
- }), object({ ok: literal(true) }), {
54068
- kind: "mutation",
54069
- auth: "admin"
54070
- }), method(object({ id: IntegrationInstanceIdSchema }), object({ ok: literal(true) }), {
54071
- kind: "mutation",
54072
- auth: "admin"
54073
- }), optionalMethod(object({
54074
- id: IntegrationInstanceIdSchema.nullable(),
54075
- values: record(string(), unknown())
54076
- }), TestConnectionResultSchema$1, {
54077
- kind: "mutation",
54078
- auth: "admin"
54079
- });
54428
+ var integrationInstancesCapability = {
54429
+ name: "integration-instances",
54430
+ scope: "system",
54431
+ mode: "collection",
54432
+ methods: {
54433
+ describe: method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }),
54434
+ /** The form; `id: null` is the create form. */
54435
+ instanceFormSchema: method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }),
54436
+ listInstances: method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }),
54437
+ getInstance: method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }),
54438
+ /**
54439
+ * Insert the typed record. With `id` it is stored under that id (a duplicate id is refused);
54440
+ * without one the PROVIDER mints it and answers it. `kind` picks one of `describe().kinds`.
54441
+ */
54442
+ createInstance: method(object({
54443
+ id: IntegrationInstanceIdSchema.optional(),
54444
+ name: string().min(1),
54445
+ kind: string().min(1).optional()
54446
+ }), object({ id: string() }), {
54447
+ kind: "mutation",
54448
+ auth: "admin"
54449
+ }),
54450
+ updateInstance: method(IntegrationInstancePatchSchema, object({ ok: literal(true) }), {
54451
+ kind: "mutation",
54452
+ auth: "admin"
54453
+ }),
54454
+ /**
54455
+ * Switch ONE instance on or off. A row control, not a form field: `updateInstance.values` is the
54456
+ * form patch (D62, D996). An off instance keeps its record and secrets and does no work.
54457
+ */
54458
+ setInstanceEnabled: method(object({
54459
+ id: IntegrationInstanceIdSchema,
54460
+ enabled: boolean()
54461
+ }), object({ ok: literal(true) }), {
54462
+ kind: "mutation",
54463
+ auth: "admin"
54464
+ }),
54465
+ /** Delete the record and its keychain refs together. */
54466
+ deleteInstance: method(object({ id: IntegrationInstanceIdSchema }), object({ ok: literal(true) }), {
54467
+ kind: "mutation",
54468
+ auth: "admin"
54469
+ }),
54470
+ testInstance: optionalMethod(object({
54471
+ id: IntegrationInstanceIdSchema.nullable(),
54472
+ values: record(string(), unknown())
54473
+ }), TestConnectionResultSchema$1, {
54474
+ kind: "mutation",
54475
+ auth: "admin"
54476
+ })
54477
+ }
54478
+ };
54080
54479
  /**
54081
54480
  * Two-way audio / talk-back cap. Clients open a WebRTC audio-only
54082
54481
  * session (server-initiated offer pattern, identical to the main
@@ -56626,6 +57025,27 @@ method(object({}), object({ entries: array(MigrationLedgerEntrySchema) }), { aut
56626
57025
  }), {
56627
57026
  kind: "mutation",
56628
57027
  auth: "admin"
57028
+ }), method(object({ integrationId: string().min(1) }), record(string(), unknown()), { auth: "admin" }), method(object({ integrationId: string().min(1) }), object({
57029
+ rows: number().int().nonnegative(),
57030
+ secrets: number().int().nonnegative()
57031
+ }), {
57032
+ kind: "mutation",
57033
+ auth: "admin"
57034
+ }), method(object({
57035
+ integrationId: string().min(1),
57036
+ patch: record(string(), unknown())
57037
+ }), object({ written: boolean() }), {
57038
+ kind: "mutation",
57039
+ auth: "admin"
57040
+ }), method(object({
57041
+ integrationId: string().min(1),
57042
+ keys: array(string().min(1))
57043
+ }), object({
57044
+ present: boolean(),
57045
+ removed: record(string(), unknown())
57046
+ }), {
57047
+ kind: "mutation",
57048
+ auth: "admin"
56629
57049
  });
56630
57050
  method(object({
56631
57051
  sourceUrl: string(),
@@ -75810,11 +76230,15 @@ discriminatedUnion("kind", [object({
75810
76230
  * 1. idle floor F = time-weighted median; noise ceiling N = highest value seen
75811
76231
  * near F. A device that is not near one level most of the time has no floor.
75812
76232
  * 2. coarse activity = above max(2N, N + 5 W); consecutive stretches are episodes.
75813
- * 3. gaps between episodes split in two by the largest log-scale jump (>= 3x):
75814
- * the short ones are pauses INSIDE a run (a soak), the long ones separate runs.
76233
+ * 3. an episode shorter than `PULSE_MAX_MS` is a PULSE (an anti-crease tumble, a
76234
+ * display waking): it is neither a run nor a pause. Among the remaining
76235
+ * episodes, gaps over `PAUSE_MAX_MS` always separate runs; the rest split in
76236
+ * two by the largest log-scale jump (>= 3x): the short ones are pauses INSIDE
76237
+ * a run (a soak), the long ones separate runs. A stretch under `MIN_RUN_MS`
76238
+ * is no run.
75815
76239
  * 4. T = geometric mean of N and the plateau's 10th percentile, snapped to a
75816
- * grid a person would type; stop dwell covers the longest pause; start dwell
75817
- * covers the longest standby blip above T.
76240
+ * grid a person would type; stop dwell covers the longest pause and the
76241
+ * kind's floor; start dwell covers the longest pulse and standby blip above T.
75818
76242
  * 5. the numbers are proved by REPLAY through the real `dwell` evaluation: each
75819
76243
  * run must hold exactly one true interval and nothing may flap outside.
75820
76244
  */
@@ -75825,6 +76249,10 @@ var MINUTE_MS$1 = 60 * SECOND_MS;
75825
76249
  30 * SECOND_MS;
75826
76250
  60 * SECOND_MS;
75827
76251
  20 * MINUTE_MS$1;
76252
+ 90 * SECOND_MS;
76253
+ 30 * MINUTE_MS$1;
76254
+ 10 * MINUTE_MS$1;
76255
+ DeviceType.Dryer, 3 * MINUTE_MS$1, DeviceType.Dishwasher, 3 * MINUTE_MS$1, DeviceType.Washer, 10 * MINUTE_MS$1;
75828
76256
  10 * SECOND_MS;
75829
76257
  10 * SECOND_MS;
75830
76258
  DeviceFeature.FanSpeed, DeviceFeature.FanPreset, DeviceFeature.FanDirection, DeviceFeature.FanOscillating, DeviceFeature.CoverStoppable, DeviceFeature.CoverPositionable, DeviceFeature.CoverTilt, DeviceFeature.ValvePositionable, DeviceFeature.MediaPlayerVolume, DeviceFeature.ClimateFanMode;
@@ -79580,13 +80008,6 @@ Object.freeze({
79580
80008
  access: "view",
79581
80009
  role: "admin"
79582
80010
  },
79583
- "integrations.getSettings": {
79584
- capName: "integrations",
79585
- capScope: "system",
79586
- addonId: null,
79587
- access: "view",
79588
- role: "admin"
79589
- },
79590
80011
  "integrations.list": {
79591
80012
  capName: "integrations",
79592
80013
  capScope: "system",
@@ -79594,13 +80015,6 @@ Object.freeze({
79594
80015
  access: "view",
79595
80016
  role: "admin"
79596
80017
  },
79597
- "integrations.setSettings": {
79598
- capName: "integrations",
79599
- capScope: "system",
79600
- addonId: null,
79601
- access: "create",
79602
- role: "admin"
79603
- },
79604
80018
  "integrations.testConnection": {
79605
80019
  capName: "integrations",
79606
80020
  capScope: "system",
@@ -80595,6 +81009,13 @@ Object.freeze({
80595
81009
  access: "view",
80596
81010
  role: "admin"
80597
81011
  },
81012
+ "migrations.clearLegacyIntegrationRows": {
81013
+ capName: "migrations",
81014
+ capScope: "system",
81015
+ addonId: null,
81016
+ access: "delete",
81017
+ role: "admin"
81018
+ },
80598
81019
  "migrations.declareOwner": {
80599
81020
  capName: "migrations",
80600
81021
  capScope: "system",
@@ -80602,6 +81023,13 @@ Object.freeze({
80602
81023
  access: "create",
80603
81024
  role: "admin"
80604
81025
  },
81026
+ "migrations.deleteLegacyIntegrationRowKeys": {
81027
+ capName: "migrations",
81028
+ capScope: "system",
81029
+ addonId: null,
81030
+ access: "delete",
81031
+ role: "admin"
81032
+ },
80605
81033
  "migrations.dryRun": {
80606
81034
  capName: "migrations",
80607
81035
  capScope: "system",
@@ -80637,6 +81065,20 @@ Object.freeze({
80637
81065
  access: "create",
80638
81066
  role: "admin"
80639
81067
  },
81068
+ "migrations.patchLegacyIntegrationRows": {
81069
+ capName: "migrations",
81070
+ capScope: "system",
81071
+ addonId: null,
81072
+ access: "create",
81073
+ role: "admin"
81074
+ },
81075
+ "migrations.readLegacyIntegrationRows": {
81076
+ capName: "migrations",
81077
+ capScope: "system",
81078
+ addonId: null,
81079
+ access: "view",
81080
+ role: "admin"
81081
+ },
80640
81082
  "migrations.restorePreMigration": {
80641
81083
  capName: "migrations",
80642
81084
  capScope: "system",
@@ -91064,7 +91506,11 @@ var ActionSceneExports = class {
91064
91506
  * scenes. The addon is its only writer; the in-memory copy it loads at boot is what every
91065
91507
  * fulfillment intent reads.
91066
91508
  */
91067
- /** A single-instance addon keeps its records under its own addon id. */
91509
+ /**
91510
+ * The id the first Google Home instance keeps: the one every record and every pasted fulfillment
91511
+ * URL was created under. New instances get minted ids; the legacy `/fulfillment` route answers
91512
+ * for this one.
91513
+ */
91068
91514
  var GOOGLE_INSTANCE_ID = "export-google";
91069
91515
  var ExposedDeviceEntrySchema = object({
91070
91516
  deviceId: number(),
@@ -91094,6 +91540,204 @@ var EMPTY_GOOGLE_EXPORTS = {
91094
91540
  };
91095
91541
  /** The settings keys that moved into the record; the migrations name them. */
91096
91542
  var MOVED_EXPOSURE_KEYS = ["exposed", "exposedActions"];
91543
+ var GoogleHomeBodySchema = object({
91544
+ name: string().min(1),
91545
+ enabled: boolean().optional()
91546
+ });
91547
+ var GOOGLE_HOMES_KIND_NAME = "google-homes";
91548
+ var GOOGLE_HOME_NAME = "Google Home";
91549
+ var googleHomesKind = defineEntryKind(GOOGLE_HOMES_KIND_NAME, {
91550
+ title: "Google Home instances",
91551
+ nameField: "name",
91552
+ schema: GoogleHomeBodySchema
91553
+ });
91554
+ var LinkedAccountSchema = object({
91555
+ userId: string(),
91556
+ username: string(),
91557
+ linkedAt: number()
91558
+ });
91559
+ var GoogleLinksBodySchema = object({
91560
+ name: string().min(1),
91561
+ linkedAccounts: array(LinkedAccountSchema)
91562
+ });
91563
+ var GOOGLE_LINKS_KIND_NAME = "google-links";
91564
+ var GOOGLE_LINKS_NAME = "Google links";
91565
+ var googleLinksKind = defineEntryKind(GOOGLE_LINKS_KIND_NAME, {
91566
+ title: "Google linked accounts",
91567
+ nameField: "name",
91568
+ schema: GoogleLinksBodySchema
91569
+ });
91570
+ var EMPTY_GOOGLE_LINKS = {
91571
+ name: GOOGLE_LINKS_NAME,
91572
+ linkedAccounts: []
91573
+ };
91574
+ /** The settings key that moved into the `google-links` record; the migrations name it. */
91575
+ var MOVED_LINKS_KEY = "linkedAccounts";
91576
+ //#endregion
91577
+ //#region src/google-instance.ts
91578
+ /** The most instances one hub lists. */
91579
+ var INSTANCES_MAX = 1e3;
91580
+ var GoogleInstance = class {
91581
+ id;
91582
+ home;
91583
+ exportsRow;
91584
+ linksRow;
91585
+ stores;
91586
+ logger;
91587
+ scenes;
91588
+ tail = Promise.resolve();
91589
+ constructor(id, home, exportsRow, linksRow, stores, logger, makeScenes) {
91590
+ this.id = id;
91591
+ this.home = home;
91592
+ this.exportsRow = exportsRow;
91593
+ this.linksRow = linksRow;
91594
+ this.stores = stores;
91595
+ this.logger = logger;
91596
+ this.scenes = makeScenes((entries) => this.writeExports({ actions: [...entries] }), exportsRow.actions);
91597
+ }
91598
+ get name() {
91599
+ return this.home.name;
91600
+ }
91601
+ get enabled() {
91602
+ return this.home.enabled !== false;
91603
+ }
91604
+ get devices() {
91605
+ return this.exportsRow.devices;
91606
+ }
91607
+ get linkedAccounts() {
91608
+ return this.linksRow.linkedAccounts;
91609
+ }
91610
+ applyHome(home) {
91611
+ this.home = home;
91612
+ }
91613
+ isExposed(deviceId) {
91614
+ return this.exportsRow.devices.some((entry) => entry.deviceId === deviceId);
91615
+ }
91616
+ /** One write at a time per instance: two concurrent changes must not lose each other. */
91617
+ serial(work) {
91618
+ const run = this.tail.then(work, work);
91619
+ this.tail = run.catch(() => void 0);
91620
+ return run;
91621
+ }
91622
+ /** Persist a change of the exposure: the record first, the in-memory copy after it landed. */
91623
+ writeExports(patch) {
91624
+ return this.serial(async () => {
91625
+ const next = {
91626
+ name: this.exportsRow.name,
91627
+ devices: patch.devices ?? this.exportsRow.devices,
91628
+ actions: patch.actions ?? this.exportsRow.actions
91629
+ };
91630
+ await this.stores.exports.put({
91631
+ id: this.id,
91632
+ data: next
91633
+ });
91634
+ this.exportsRow = next;
91635
+ });
91636
+ }
91637
+ /** Google's SYNC is the first thing a completed link does: the only "linked" signal there is. */
91638
+ recordLink(caller) {
91639
+ return this.serial(async () => {
91640
+ if (this.linksRow.linkedAccounts.some((a) => a.userId === caller.userId)) return;
91641
+ const next = {
91642
+ name: this.linksRow.name,
91643
+ linkedAccounts: [...this.linksRow.linkedAccounts, {
91644
+ userId: caller.userId,
91645
+ username: caller.username,
91646
+ linkedAt: Date.now()
91647
+ }]
91648
+ };
91649
+ await this.stores.links.put({
91650
+ id: this.id,
91651
+ data: next
91652
+ });
91653
+ this.linksRow = next;
91654
+ this.logger.info("export-google: recorded linked account", { meta: {
91655
+ instanceId: this.id,
91656
+ userId: caller.userId
91657
+ } });
91658
+ });
91659
+ }
91660
+ removeLink(userId) {
91661
+ return this.serial(async () => {
91662
+ const kept = this.linksRow.linkedAccounts.filter((a) => a.userId !== userId);
91663
+ if (kept.length === this.linksRow.linkedAccounts.length) return;
91664
+ const next = {
91665
+ name: this.linksRow.name,
91666
+ linkedAccounts: kept
91667
+ };
91668
+ await this.stores.links.put({
91669
+ id: this.id,
91670
+ data: next
91671
+ });
91672
+ this.linksRow = next;
91673
+ });
91674
+ }
91675
+ };
91676
+ var GoogleInstanceRegistry = class {
91677
+ stores;
91678
+ logger;
91679
+ makeScenes;
91680
+ loaded = /* @__PURE__ */ new Map();
91681
+ loading = /* @__PURE__ */ new Map();
91682
+ constructor(stores, logger, makeScenes) {
91683
+ this.stores = stores;
91684
+ this.logger = logger;
91685
+ this.makeScenes = makeScenes;
91686
+ }
91687
+ /** The instance, loaded (home, exposure AND links) on first use; null when no such instance. */
91688
+ get(id) {
91689
+ const ready = this.loaded.get(id);
91690
+ if (ready !== void 0) return Promise.resolve(ready);
91691
+ const inFlight = this.loading.get(id);
91692
+ if (inFlight !== void 0) return inFlight;
91693
+ const started = this.load(id).finally(() => {
91694
+ this.loading.delete(id);
91695
+ });
91696
+ this.loading.set(id, started);
91697
+ return started;
91698
+ }
91699
+ /** An instance already loaded; never reads. */
91700
+ peek(id) {
91701
+ return this.loaded.get(id);
91702
+ }
91703
+ async load(id) {
91704
+ const home = await this.stores.homes.get(id);
91705
+ if (home === null) return null;
91706
+ const [exported, links] = await Promise.all([this.stores.exports.get(id), this.stores.links.get(id)]);
91707
+ const instance = new GoogleInstance(id, home.data, exported?.data ?? EMPTY_GOOGLE_EXPORTS, links?.data ?? EMPTY_GOOGLE_LINKS, this.stores, this.logger, this.makeScenes);
91708
+ this.loaded.set(id, instance);
91709
+ return instance;
91710
+ }
91711
+ /** Every instance row, as stored. */
91712
+ async list() {
91713
+ return (await this.stores.homes.query({ limit: INSTANCES_MAX })).records.map((record) => ({
91714
+ id: record.id,
91715
+ body: record.data
91716
+ }));
91717
+ }
91718
+ /** The instance row changed (name, switch): a loaded instance takes it. */
91719
+ async refreshHome(id) {
91720
+ const home = await this.stores.homes.get(id);
91721
+ const instance = this.loaded.get(id);
91722
+ if (home === null) {
91723
+ this.loaded.delete(id);
91724
+ return;
91725
+ }
91726
+ if (instance === void 0) {
91727
+ await this.get(id);
91728
+ return;
91729
+ }
91730
+ instance.applyHome(home.data);
91731
+ }
91732
+ /** The instance is gone: its exposure and links rows go with it, and nothing serves it. */
91733
+ async remove(id) {
91734
+ this.loaded.delete(id);
91735
+ this.loading.delete(id);
91736
+ await this.stores.exports.delete(id);
91737
+ await this.stores.links.delete(id);
91738
+ this.logger.info("export-google: instance deleted with its exposure and links", { meta: { instanceId: id } });
91739
+ }
91740
+ };
91097
91741
  //#endregion
91098
91742
  //#region src/google-home/trait-catalog.ts
91099
91743
  /**
@@ -91778,11 +92422,17 @@ var OauthVerifiedResultSchema = object({
91778
92422
  }).nullable();
91779
92423
  function buildRoutes(deps) {
91780
92424
  return [{
92425
+ method: "POST",
92426
+ path: "/fulfillment/:instanceId",
92427
+ access: "public",
92428
+ description: "Google Home smart-home fulfillment of one instance (SYNC / QUERY / EXECUTE / DISCONNECT)",
92429
+ handler: (req, reply) => handleFulfillmentRequest(req, reply, deps, req.params["instanceId"] ?? "")
92430
+ }, {
91781
92431
  method: "POST",
91782
92432
  path: "/fulfillment",
91783
92433
  access: "public",
91784
- description: "Google Home smart-home fulfillment (SYNC / QUERY / EXECUTE / DISCONNECT)",
91785
- handler: (req, reply) => handleFulfillmentRequest(req, reply, deps)
92434
+ description: `Legacy fulfillment URL: answers for the first instance (${GOOGLE_INSTANCE_ID})`,
92435
+ handler: (req, reply) => handleFulfillmentRequest(req, reply, deps, GOOGLE_INSTANCE_ID)
91786
92436
  }];
91787
92437
  }
91788
92438
  /** Read `Authorization: Bearer <token>` case-insensitively. Node lower-cases
@@ -91794,7 +92444,7 @@ function readBearer(headers) {
91794
92444
  }
91795
92445
  return null;
91796
92446
  }
91797
- async function handleFulfillmentRequest(request, reply, deps) {
92447
+ async function handleFulfillmentRequest(request, reply, deps, instanceId) {
91798
92448
  const bearer = readBearer(request.headers);
91799
92449
  if (bearer === null) {
91800
92450
  deps.logger.warn("google fulfillment: rejected — no bearer token");
@@ -91813,84 +92463,19 @@ async function handleFulfillmentRequest(request, reply, deps) {
91813
92463
  username: verified.data.username,
91814
92464
  scopes: verified.data.scopes
91815
92465
  };
91816
- const result = await handleFulfillment(request.body, deps.fulfillment, caller);
92466
+ const lookup = await deps.resolveFulfillment(instanceId);
92467
+ if (!lookup.ok) {
92468
+ deps.logger.warn("google fulfillment: rejected — instance not served", { meta: {
92469
+ instanceId,
92470
+ reason: lookup.code
92471
+ } });
92472
+ reply.code(404).send({ error: lookup.code });
92473
+ return;
92474
+ }
92475
+ const result = await handleFulfillment(request.body, lookup.deps, caller);
91817
92476
  reply.code(result.status).send(result.body);
91818
92477
  }
91819
92478
  //#endregion
91820
- //#region src/oauth-integration.ts
91821
- /**
91822
- * The `export-google` OAuth client — the descriptor behind
91823
- * `/api/oauth2/authorize?integration=export-google`.
91824
- *
91825
- * Shaped exactly like `packages/addon-export-alexa/src/oauth-integration.ts`
91826
- * and `packages/addon-provider-homeassistant/src/ha-export/oauth-integration.ts`,
91827
- * which is the claim that file already makes and this one tests: a third
91828
- * integration is CONFIGURATION, not framework work
91829
- * ([D101](../../../docs/decisions/adr-0101.md)). Nothing in the kernel learned
91830
- * the word "Google".
91831
- */
91832
- /**
91833
- * Where Google lands after consent. Both origins are fixed and public and both
91834
- * are needed: `oauth-redirect` is production, `oauth-redirect-sandbox` is what
91835
- * the Actions console uses while the Action is in test mode — which is the ONLY
91836
- * mode a self-hosted hub will ever be in, since publishing an Action requires
91837
- * Google certification the operator cannot obtain for a private integration.
91838
- *
91839
- * Google appends the project id (`.../r/<project-id>`), so these stay prefixes.
91840
- */
91841
- var GOOGLE_REDIRECT_PREFIXES = ["https://oauth-redirect.googleusercontent.com/r/", "https://oauth-redirect-sandbox.googleusercontent.com/r/"];
91842
- /**
91843
- * What a linked Google Home NEEDS — the single meaning `requestedScopes`
91844
- * carries everywhere (see `oauth-integration.cap.ts`).
91845
- *
91846
- * `category:device [view, create]`, and each half is consumed by a named check
91847
- * in `fulfillment-router.ts`: `view` gates SYNC and QUERY, `create` gates
91848
- * EXECUTE. It is a category rather than a `capability:` list because the trait
91849
- * catalog is meant to grow, and a new trait row must not force every operator
91850
- * to re-link.
91851
- *
91852
- * **No `addon:` grant, and that is measured rather than assumed.** The single
91853
- * hub-side entry point, `POST /addon/export-google/fulfillment`, is
91854
- * `access: 'public'` and authenticates the token itself via
91855
- * `oauthVerifyAccessToken`, so it never passes through the
91856
- * `access: 'authenticated'` gate that [D103](../../../docs/decisions/adr-0103.md)
91857
- * checks an `addon:` grant on. Same field, same meaning, different routes.
91858
- *
91859
- * Google's smart-home account linking is a CONFIDENTIAL client — the client id
91860
- * and secret live in the Actions console, which is why there is no
91861
- * `requiresPkce` here. Note that the hub does not verify that secret either
91862
- * ([D92](../../../docs/decisions/adr-0092.md)); the security of the link rests
91863
- * on the authorization code and the redirect-prefix allow-list above.
91864
- */
91865
- function buildGoogleOauthIntegration() {
91866
- return {
91867
- integrationId: "export-google",
91868
- displayName: "Google Home",
91869
- requestedScopes: [{
91870
- type: "category",
91871
- target: "device",
91872
- access: ["view", "create"]
91873
- }],
91874
- allowedRedirectPrefixes: [...GOOGLE_REDIRECT_PREFIXES],
91875
- /**
91876
- * No expiry, for the reason Alexa's descriptor spells out at length: a
91877
- * smart-home link is meant to last until the user unlinks it, there is no
91878
- * unattended re-link, and a 30-day refresh silently kills the integration a
91879
- * month after setup.
91880
- *
91881
- * What bounds a leaked refresh token is revocation, not time — and for THIS
91882
- * integration revocation bites on the very next call, because the one entry
91883
- * point (`/fulfillment`) calls `oauthVerifyAccessToken` before doing any
91884
- * work, and that refuses once the session carries `revokedAt`.
91885
- *
91886
- * Google also has its own severing path: `action.devices.DISCONNECT`, which
91887
- * `fulfillment-router.ts` handles by dropping the linked-account record so
91888
- * `getStatus` stops claiming the export is live.
91889
- */
91890
- refreshTokenTtlSec: "never"
91891
- };
91892
- }
91893
- //#endregion
91894
92479
  //#region src/migrations/drop-public-hub-url.ts
91895
92480
  /**
91896
92481
  * The hub's public URL is no longer a setting of this addon (D986 §5): Google reads the
@@ -92014,10 +92599,84 @@ async function planDropMovedExposure(ports) {
92014
92599
  }] };
92015
92600
  }
92016
92601
  //#endregion
92602
+ //#region src/migrations/instance-and-links.ts
92603
+ /**
92604
+ * Google becomes a multi-instance exporter (planning#422 P2). Two migrations, both `block-owner`:
92605
+ * the addon must not serve a link ledger it cannot trust, and after them nothing reads the old key.
92606
+ *
92607
+ * 1. `moveInstanceAndLinks` (procedure): the first instance is the `google-homes` row under the
92608
+ * id `export-google`, and the `linkedAccounts` setting becomes the `google-links` row under
92609
+ * the same id. An existing row is never overwritten; a row this pass just wrote is read BACK
92610
+ * and must equal what the settings carried, or the pass throws.
92611
+ * 2. `planDropMovedLinks` (plan): the key is deleted only while the record holds every user the
92612
+ * settings carried; a record that cannot be read leaves the key in place.
92613
+ */
92614
+ function linksOf(value) {
92615
+ if (!Array.isArray(value)) return [];
92616
+ return value.flatMap((entry) => {
92617
+ const parsed = LinkedAccountSchema.safeParse(entry);
92618
+ return parsed.success ? [parsed.data] : [];
92619
+ });
92620
+ }
92621
+ async function moveInstanceAndLinks(ports) {
92622
+ const stored = await ports.readStored();
92623
+ const hasLinks = MOVED_LINKS_KEY in stored;
92624
+ const linkedAccounts = linksOf(stored[MOVED_LINKS_KEY]);
92625
+ const raw = stored[MOVED_LINKS_KEY];
92626
+ const understood = Array.isArray(raw) ? raw.length : 0;
92627
+ if (understood > linkedAccounts.length) ports.warn(`Google migration: ${understood - linkedAccounts.length} linked account(s) were not understood and are left out`);
92628
+ const home = await ports.putHome({ name: GOOGLE_HOME_NAME });
92629
+ const links = hasLinks ? await ports.putLinks({
92630
+ name: GOOGLE_LINKS_NAME,
92631
+ linkedAccounts
92632
+ }) : "exists";
92633
+ if (await ports.readHome() === null) throw new Error("the Google Home instance row is not there after it was written");
92634
+ if (links === "created") {
92635
+ const held = await ports.readLinks();
92636
+ if (held === null || canonical(held.linkedAccounts) !== canonical(linkedAccounts)) throw new Error("the Google links record does not match the legacy settings; nothing was cleared");
92637
+ }
92638
+ if (home === "exists" && links === "exists") return {
92639
+ outcome: "already-done",
92640
+ summary: { moved: false }
92641
+ };
92642
+ return {
92643
+ outcome: "done",
92644
+ summary: {
92645
+ instance: home === "created",
92646
+ linked: links === "created" ? linkedAccounts.length : 0
92647
+ }
92648
+ };
92649
+ }
92650
+ async function planDropMovedLinks(ports) {
92651
+ const stored = await ports.readStored();
92652
+ if (!("linkedAccounts" in stored)) return { edits: [] };
92653
+ const refuse = (reason) => {
92654
+ ports.warn(`Google migration: the legacy linkedAccounts key is kept: ${reason}`);
92655
+ throw new Error(`the legacy Google linkedAccounts key is not deleted: ${reason}`);
92656
+ };
92657
+ const held = await ports.readLinks();
92658
+ if (held === null) return refuse("no links record exists");
92659
+ const heldUsers = new Set(held.linkedAccounts.map((a) => a.userId));
92660
+ for (const account of linksOf(stored[MOVED_LINKS_KEY])) if (!heldUsers.has(account.userId)) return refuse(`the record lacks the user ${account.userId}`);
92661
+ const id = `${GOOGLE_INSTANCE_ID}.${MOVED_LINKS_KEY}`;
92662
+ return { edits: [{
92663
+ op: "deleteKeys",
92664
+ scope: ADDON_SETTINGS_TABLE,
92665
+ keys: [id],
92666
+ precondition: preconditionOf({ [id]: {
92667
+ addonId: GOOGLE_INSTANCE_ID,
92668
+ key: MOVED_LINKS_KEY,
92669
+ value: stored[MOVED_LINKS_KEY]
92670
+ } })
92671
+ }] };
92672
+ }
92673
+ //#endregion
92017
92674
  //#region src/migrations/index.ts
92018
92675
  var DROP_PUBLIC_HUB_URL_ID = "export-google/2026-11-02-drop-public-hub-url";
92019
92676
  var EXPOSURE_TO_RECORD_ID = "export-google/2026-11-04-exposure-to-record";
92020
92677
  var DROP_MOVED_EXPOSURE_ID = "export-google/2026-11-04-drop-moved-exposure";
92678
+ var INSTANCE_AND_LINKS_ID = "export-google/2026-11-04-instance-and-links";
92679
+ var DROP_MOVED_LINKS_ID = "export-google/2026-11-04-drop-moved-links";
92021
92680
  var FIXTURE_MARK = "the linked account list the migration does not know";
92022
92681
  /** The `export-google` catalogue (D987): offered to the engine when the addon initialises. */
92023
92682
  var ADDON_MIGRATIONS = [
@@ -92068,9 +92727,115 @@ var ADDON_MIGRATIONS = [
92068
92727
  fixtureMark: FIXTURE_MARK
92069
92728
  },
92070
92729
  plan: planDropMovedExposure
92730
+ },
92731
+ {
92732
+ meta: {
92733
+ id: INSTANCE_AND_LINKS_ID,
92734
+ owner: "export-google",
92735
+ level: "addon-state",
92736
+ seq: 4,
92737
+ dependsOn: [],
92738
+ store: "settings",
92739
+ scope: "cluster",
92740
+ onFailure: "block-owner",
92741
+ bodyKind: "procedure",
92742
+ description: "Create the first Google Home instance under the id export-google and move the linked accounts into its google-links record; both rows are read back before anything is deleted",
92743
+ fixtureMark: FIXTURE_MARK
92744
+ },
92745
+ procedure: moveInstanceAndLinks
92746
+ },
92747
+ {
92748
+ meta: {
92749
+ id: DROP_MOVED_LINKS_ID,
92750
+ owner: "export-google",
92751
+ level: "addon-state",
92752
+ seq: 5,
92753
+ dependsOn: [INSTANCE_AND_LINKS_ID],
92754
+ store: "settings",
92755
+ scope: "cluster",
92756
+ onFailure: "block-owner",
92757
+ bodyKind: "plan",
92758
+ description: "Delete the linkedAccounts settings key once the google-links record holds what it carried",
92759
+ fixtureMark: FIXTURE_MARK
92760
+ },
92761
+ plan: planDropMovedLinks
92071
92762
  }
92072
92763
  ];
92073
92764
  //#endregion
92765
+ //#region src/oauth-integration.ts
92766
+ /**
92767
+ * The `export-google` OAuth client — the descriptor behind
92768
+ * `/api/oauth2/authorize?integration=export-google`.
92769
+ *
92770
+ * Shaped exactly like `packages/addon-export-alexa/src/oauth-integration.ts`
92771
+ * and `packages/addon-provider-homeassistant/src/ha-export/oauth-integration.ts`,
92772
+ * which is the claim that file already makes and this one tests: a third
92773
+ * integration is CONFIGURATION, not framework work
92774
+ * ([D101](../../../docs/decisions/adr-0101.md)). Nothing in the kernel learned
92775
+ * the word "Google".
92776
+ */
92777
+ /**
92778
+ * Where Google lands after consent. Both origins are fixed and public and both
92779
+ * are needed: `oauth-redirect` is production, `oauth-redirect-sandbox` is what
92780
+ * the Actions console uses while the Action is in test mode — which is the ONLY
92781
+ * mode a self-hosted hub will ever be in, since publishing an Action requires
92782
+ * Google certification the operator cannot obtain for a private integration.
92783
+ *
92784
+ * Google appends the project id (`.../r/<project-id>`), so these stay prefixes.
92785
+ */
92786
+ var GOOGLE_REDIRECT_PREFIXES = ["https://oauth-redirect.googleusercontent.com/r/", "https://oauth-redirect-sandbox.googleusercontent.com/r/"];
92787
+ /**
92788
+ * What a linked Google Home NEEDS — the single meaning `requestedScopes`
92789
+ * carries everywhere (see `oauth-integration.cap.ts`).
92790
+ *
92791
+ * `category:device [view, create]`, and each half is consumed by a named check
92792
+ * in `fulfillment-router.ts`: `view` gates SYNC and QUERY, `create` gates
92793
+ * EXECUTE. It is a category rather than a `capability:` list because the trait
92794
+ * catalog is meant to grow, and a new trait row must not force every operator
92795
+ * to re-link.
92796
+ *
92797
+ * **No `addon:` grant, and that is measured rather than assumed.** The single
92798
+ * hub-side entry point, `POST /addon/export-google/fulfillment`, is
92799
+ * `access: 'public'` and authenticates the token itself via
92800
+ * `oauthVerifyAccessToken`, so it never passes through the
92801
+ * `access: 'authenticated'` gate that [D103](../../../docs/decisions/adr-0103.md)
92802
+ * checks an `addon:` grant on. Same field, same meaning, different routes.
92803
+ *
92804
+ * Google's smart-home account linking is a CONFIDENTIAL client — the client id
92805
+ * and secret live in the Actions console, which is why there is no
92806
+ * `requiresPkce` here. Note that the hub does not verify that secret either
92807
+ * ([D92](../../../docs/decisions/adr-0092.md)); the security of the link rests
92808
+ * on the authorization code and the redirect-prefix allow-list above.
92809
+ */
92810
+ function buildGoogleOauthIntegration() {
92811
+ return {
92812
+ integrationId: "export-google",
92813
+ displayName: "Google Home",
92814
+ requestedScopes: [{
92815
+ type: "category",
92816
+ target: "device",
92817
+ access: ["view", "create"]
92818
+ }],
92819
+ allowedRedirectPrefixes: [...GOOGLE_REDIRECT_PREFIXES],
92820
+ /**
92821
+ * No expiry, for the reason Alexa's descriptor spells out at length: a
92822
+ * smart-home link is meant to last until the user unlinks it, there is no
92823
+ * unattended re-link, and a 30-day refresh silently kills the integration a
92824
+ * month after setup.
92825
+ *
92826
+ * What bounds a leaked refresh token is revocation, not time — and for THIS
92827
+ * integration revocation bites on the very next call, because the one entry
92828
+ * point (`/fulfillment`) calls `oauthVerifyAccessToken` before doing any
92829
+ * work, and that refuses once the session carries `revokedAt`.
92830
+ *
92831
+ * Google also has its own severing path: `action.devices.DISCONNECT`, which
92832
+ * `fulfillment-router.ts` handles by dropping the linked-account record so
92833
+ * `getStatus` stops claiming the export is live.
92834
+ */
92835
+ refreshTokenTtlSec: "never"
92836
+ };
92837
+ }
92838
+ //#endregion
92074
92839
  //#region src/public-endpoint.ts
92075
92840
  /** The typed refusal when the role resolves to nothing. */
92076
92841
  var NO_PUBLIC_ENDPOINT_REASON = {
@@ -92110,6 +92875,7 @@ var buildConsoleSetupFromRole = async (input) => {
92110
92875
  }]
92111
92876
  };
92112
92877
  const origin = result.origin;
92878
+ const fulfillmentPath = input.instanceId === void 0 ? `/addon/${input.addonId}/fulfillment` : `/addon/${input.addonId}/fulfillment/${input.instanceId}`;
92113
92879
  return {
92114
92880
  note: [
92115
92881
  "In the Google Home Developer Console create a cloud-to-cloud integration, then paste these three URLs.",
@@ -92120,7 +92886,7 @@ var buildConsoleSetupFromRole = async (input) => {
92120
92886
  fields: [
92121
92887
  {
92122
92888
  label: "Fulfillment URL",
92123
- value: `${origin}/addon/${input.addonId}/fulfillment`
92889
+ value: `${origin}${fulfillmentPath}`
92124
92890
  },
92125
92891
  {
92126
92892
  label: "Authorization URL",
@@ -92139,7 +92905,7 @@ var buildConsoleSetupFromRole = async (input) => {
92139
92905
  };
92140
92906
  //#endregion
92141
92907
  //#region src/types.ts
92142
- var DEFAULT_SETTINGS = { linkedAccounts: [] };
92908
+ var DEFAULT_SETTINGS = {};
92143
92909
  //#endregion
92144
92910
  //#region src/export-google.addon.ts
92145
92911
  /**
@@ -92147,9 +92913,14 @@ var DEFAULT_SETTINGS = { linkedAccounts: [] };
92147
92913
  *
92148
92914
  * Architecture:
92149
92915
  *
92150
- * Google Home / Assistant --HTTPS--> POST /addon/export-google/fulfillment
92916
+ * Google Home / Assistant --HTTPS--> POST /addon/export-google/fulfillment/<instanceId>
92151
92917
  * (hub Fastify → addon-routes cap)
92152
92918
  *
92919
+ * The addon is MULTI-instance (planning#422): every Actions-console project is one
92920
+ * `integration-instances` row of the `google-homes` kind with its own exposure and its own
92921
+ * link ledger. The first instance keeps the id `export-google`, so the legacy
92922
+ * `/fulfillment` URL still answers for it. One OAuth client serves every instance.
92923
+ *
92153
92924
  * There is no cloud function in the middle. Google's smart-home platform calls
92154
92925
  * the fulfillment URL the operator configured, so the hub answers directly —
92155
92926
  * a shorter path than Alexa's, which needs an operator-owned Lambda because
@@ -92157,7 +92928,8 @@ var DEFAULT_SETTINGS = { linkedAccounts: [] };
92157
92928
  *
92158
92929
  * Capabilities registered:
92159
92930
  * - `device-export` — the operator picks which devices Google sees.
92160
- * - `addon-routes` — mounts `/addon/export-google/fulfillment`.
92931
+ * - `addon-routes` — mounts `/addon/export-google/fulfillment[/<instanceId>]`.
92932
+ * - `integration-instances` — the Google Home instances (role `services`).
92161
92933
  * - `oauth-integration` — declares this addon a linkable client of the
92162
92934
  * hub's core `/api/oauth2/*` server.
92163
92935
  *
@@ -92179,36 +92951,27 @@ var DEFAULT_SETTINGS = { linkedAccounts: [] };
92179
92951
  * decides, so widening scope is one row.
92180
92952
  */
92181
92953
  var ADDON_ID = "export-google";
92954
+ /** The per-device toggle key: `google:<instanceId>:<deviceId>:enabled`. */
92955
+ var DEVICE_KEY = /^google:([^:]+):(\d+):enabled$/;
92956
+ var deviceKey = (instanceId, deviceId) => `google:${instanceId}:${deviceId}:enabled`;
92182
92957
  var ExportGoogleAddon = class extends BaseAddon {
92183
92958
  gateway = null;
92184
- /**
92185
- * The `google-exports` record: what Google syncs. Loaded once at boot after the migrations;
92186
- * this addon is its only writer, so the in-memory copy is the synchronous read the fulfillment
92187
- * path needs. No settings key backs it.
92188
- */
92189
- exportsRow = EMPTY_GOOGLE_EXPORTS;
92190
- exportsHandle = null;
92191
- get exposedDevices() {
92192
- return this.exportsRow.devices;
92193
- }
92194
- /** Persist a change of the exposure: the record first, the in-memory copy after it landed. */
92195
- async writeExports(patch) {
92196
- const handle = this.exportsHandle;
92197
- if (handle === null) throw new Error("export-google: the exposure record is not open");
92198
- const next = {
92199
- name: this.exportsRow.name,
92200
- devices: patch.devices ?? this.exportsRow.devices,
92201
- actions: patch.actions ?? this.exportsRow.actions
92202
- };
92203
- await handle.put({
92204
- id: GOOGLE_INSTANCE_ID,
92205
- data: next
92206
- });
92207
- this.exportsRow = next;
92208
- }
92959
+ registry = null;
92960
+ instances = null;
92961
+ fulfillments = /* @__PURE__ */ new WeakMap();
92209
92962
  constructor() {
92210
92963
  super({ ...DEFAULT_SETTINGS });
92211
92964
  }
92965
+ requireRegistry() {
92966
+ if (this.registry === null) throw new Error("export-google: addon not initialized");
92967
+ return this.registry;
92968
+ }
92969
+ /** The instance or a typed refusal naming it: a device-export call never guesses one. */
92970
+ async requireInstance(instanceId) {
92971
+ const instance = await this.requireRegistry().get(instanceId);
92972
+ if (instance === null) throw new ExportInstanceUnknownError(ADDON_ID, instanceId);
92973
+ return instance;
92974
+ }
92212
92975
  async onInitialize() {
92213
92976
  const gateway = createApiDeviceGateway({
92214
92977
  api: this.ctx.api,
@@ -92217,9 +92980,53 @@ var ExportGoogleAddon = class extends BaseAddon {
92217
92980
  this.gateway = gateway;
92218
92981
  const records = this.ctx.records;
92219
92982
  if (records === void 0) throw new Error("export-google needs ctx.records — check execution.placement (hub-only)");
92220
- await records.declare({ "google-exports": googleExportsKind });
92221
- const exportsHandle = records.kind(googleExportsKind);
92222
- this.exportsHandle = exportsHandle;
92983
+ await records.declare({
92984
+ "google-homes": googleHomesKind,
92985
+ "google-exports": googleExportsKind,
92986
+ "google-links": googleLinksKind
92987
+ });
92988
+ const stores = {
92989
+ homes: records.kind(googleHomesKind),
92990
+ exports: records.kind(googleExportsKind),
92991
+ links: records.kind(googleLinksKind)
92992
+ };
92993
+ const registry = new GoogleInstanceRegistry(stores, this.ctx.logger, (persist, initial) => new ActionSceneExports({
92994
+ api: this.ctx.api,
92995
+ logger: this.ctx.logger,
92996
+ isAdminUser: async (userId) => {
92997
+ return (await this.ctx.api.userManagement.listUsers.query()).some((u) => u.id === userId && u.isAdmin);
92998
+ },
92999
+ persist
93000
+ }, initial));
93001
+ this.registry = registry;
93002
+ this.instances = new RecordIntegrationInstances(records, googleHomesKind, {
93003
+ description: {
93004
+ role: "services",
93005
+ instanceMode: "multiple",
93006
+ kind: "homes",
93007
+ canTest: false
93008
+ },
93009
+ formSchema: (id) => this.homeForm(id),
93010
+ initialBody: (name) => ({ name }),
93011
+ mintId: () => `google-home-${randomUUID().slice(0, 8)}`,
93012
+ health: (body, id) => {
93013
+ if (body.enabled === false) return { status: {
93014
+ state: "off",
93015
+ label: "Off"
93016
+ } };
93017
+ const linked = registry.peek(id)?.linkedAccounts.length;
93018
+ if (linked === void 0) return { status: { state: "unknown" } };
93019
+ return linked > 0 ? { status: {
93020
+ state: "ok",
93021
+ label: `${linked} linked account(s)`
93022
+ } } : { status: {
93023
+ state: "unknown",
93024
+ label: "Not linked yet"
93025
+ } };
93026
+ },
93027
+ configured: () => true,
93028
+ onChanged: (id, change) => this.onInstanceChanged(id, change)
93029
+ });
92223
93030
  await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, {
92224
93031
  readStored: async () => this.resolveGlobalStore(),
92225
93032
  warn: (message) => {
@@ -92229,9 +93036,9 @@ var ExportGoogleAddon = class extends BaseAddon {
92229
93036
  } });
92230
93037
  },
92231
93038
  putExports: async (body) => {
92232
- if (await exportsHandle.get("export-google") !== null) return "exists";
93039
+ if (await stores.exports.get("export-google") !== null) return "exists";
92233
93040
  try {
92234
- await exportsHandle.put({
93041
+ await stores.exports.put({
92235
93042
  id: GOOGLE_INSTANCE_ID,
92236
93043
  data: body
92237
93044
  }, { ifRev: 0 });
@@ -92241,108 +93048,55 @@ var ExportGoogleAddon = class extends BaseAddon {
92241
93048
  }
92242
93049
  return "created";
92243
93050
  },
92244
- readExports: async () => (await exportsHandle.get("export-google"))?.data ?? null
92245
- }));
92246
- this.exportsRow = (await exportsHandle.get("export-google"))?.data ?? EMPTY_GOOGLE_EXPORTS;
92247
- const actionScenes = new ActionSceneExports({
92248
- api: this.ctx.api,
92249
- logger: this.ctx.logger,
92250
- isAdminUser: async (userId) => {
92251
- return (await this.ctx.api.userManagement.listUsers.query()).some((u) => u.id === userId && u.isAdmin);
92252
- },
92253
- persist: (entries) => this.writeExports({ actions: [...entries] })
92254
- }, this.exportsRow.actions);
92255
- actionScenes.reconcile().catch((err) => {
92256
- this.ctx.logger.warn("export-google: action scene reconcile at boot failed", { meta: { error: errMsg$1(err) } });
92257
- });
92258
- const ownInstance = (instanceId) => assertOwnExportInstance("export-google", ADDON_ID, instanceId);
92259
- const deviceExportProvider = {
92260
- getStatus: async (input) => {
92261
- ownInstance(statusInstanceOf(input));
92262
- return {
92263
- linkState: this.config.linkedAccounts.length > 0 ? "linked" : "unlinked",
92264
- exposedDeviceCount: this.exposedDevices.length,
92265
- setup: await this.buildSetupBlock()
92266
- };
92267
- },
92268
- listInstances: async () => [{
92269
- instanceId: ADDON_ID,
92270
- name: "Google Home",
92271
- enabled: true,
92272
- kind: "google-home"
92273
- }],
92274
- listSupportedDeviceKinds: async ({ instanceId }) => {
92275
- ownInstance(instanceId);
92276
- return [...SUPPORTED_DEVICE_KINDS];
92277
- },
92278
- listExposedDevices: async ({ instanceId }) => {
92279
- ownInstance(instanceId);
92280
- return this.exposedDevices.map((entry) => ({ deviceId: String(entry.deviceId) }));
92281
- },
92282
- exposeDevice: async ({ instanceId, deviceId }) => {
92283
- ownInstance(instanceId);
92284
- return this.exposeDevice(deviceId);
92285
- },
92286
- unexposeDevice: async ({ instanceId, deviceId }) => {
92287
- ownInstance(instanceId);
92288
- return this.unexposeDevice(deviceId);
92289
- },
92290
- listSupportedEntityKinds: async () => ["device", "action"],
92291
- listExposedEntities: async ({ instanceId }) => {
92292
- ownInstance(instanceId);
92293
- await actionScenes.reconcile();
92294
- return [...this.exposedDevices.map((entry) => ({ entity: {
92295
- kind: "device",
92296
- deviceId: String(entry.deviceId)
92297
- } })), ...actionScenes.list()];
92298
- },
92299
- exposeEntity: async ({ instanceId, entity }) => {
92300
- ownInstance(instanceId);
92301
- if (entity.kind === "device") return this.exposeDevice(entity.deviceId);
92302
- if (entity.kind === "action") return actionScenes.expose(entity.actionId);
92303
- throw new Error("export-google: a notification target cannot be exported to Google Home");
93051
+ readExports: async () => (await stores.exports.get("export-google"))?.data ?? null,
93052
+ putHome: async (body) => {
93053
+ if (await stores.homes.get("export-google") !== null) return "exists";
93054
+ try {
93055
+ await stores.homes.put({
93056
+ id: GOOGLE_INSTANCE_ID,
93057
+ data: body
93058
+ }, { ifRev: 0 });
93059
+ } catch (err) {
93060
+ if (err instanceof RevConflictError) return "exists";
93061
+ throw err;
93062
+ }
93063
+ return "created";
92304
93064
  },
92305
- unexposeEntity: async ({ instanceId, entity }) => {
92306
- ownInstance(instanceId);
92307
- if (entity.kind === "device") return this.unexposeDevice(entity.deviceId);
92308
- if (entity.kind === "action") return actionScenes.unexpose(entity.actionId);
92309
- throw new Error("export-google: a notification target cannot be exported to Google Home");
93065
+ putLinks: async (body) => {
93066
+ if (await stores.links.get("export-google") !== null) return "exists";
93067
+ try {
93068
+ await stores.links.put({
93069
+ id: GOOGLE_INSTANCE_ID,
93070
+ data: body
93071
+ }, { ifRev: 0 });
93072
+ } catch (err) {
93073
+ if (err instanceof RevConflictError) return "exists";
93074
+ throw err;
93075
+ }
93076
+ return "created";
92310
93077
  },
92311
- getDeviceSettingsContribution: (input) => this.buildDeviceSettingsContribution(Number(input.deviceId)),
92312
- getDeviceLiveContribution: async () => null,
92313
- applyDeviceSettingsPatch: (input) => this.applyDeviceSettingsPatch(Number(input.deviceId), input.patch)
92314
- };
93078
+ readHome: async () => (await stores.homes.get("export-google"))?.data ?? null,
93079
+ readLinks: async () => (await stores.links.get("export-google"))?.data ?? null
93080
+ }));
93081
+ for (const row of await registry.list()) {
93082
+ const instance = await registry.get(row.id);
93083
+ if (instance === null) continue;
93084
+ instance.scenes.reconcile().catch((err) => {
93085
+ this.ctx.logger.warn("export-google: action scene reconcile at boot failed", { meta: {
93086
+ instanceId: instance.id,
93087
+ error: errMsg$1(err)
93088
+ } });
93089
+ });
93090
+ }
93091
+ const deviceExportProvider = this.buildDeviceExportProvider();
92315
93092
  const routeProvider = buildAddonRouteProvider(ADDON_ID, buildRoutes({
92316
93093
  ctx: this.ctx,
92317
93094
  logger: this.ctx.logger,
92318
- fulfillment: {
92319
- logger: this.ctx.logger,
92320
- sync: {
92321
- gateway,
92322
- logger: this.ctx.logger,
92323
- listExposed: () => this.exposedDevices.map((entry) => entry.deviceId),
92324
- actions: actionScenes
92325
- },
92326
- query: {
92327
- gateway,
92328
- logger: this.ctx.logger,
92329
- isExposed: (deviceId) => this.isExposed(deviceId),
92330
- actions: actionScenes
92331
- },
92332
- execute: {
92333
- gateway,
92334
- logger: this.ctx.logger,
92335
- isExposed: (deviceId) => this.isExposed(deviceId),
92336
- actions: actionScenes
92337
- },
92338
- recordLink: (caller) => this.recordLink(caller),
92339
- removeLink: (userId) => this.removeLink(userId)
92340
- }
93095
+ resolveFulfillment: (instanceId) => this.resolveFulfillment(instanceId)
92341
93096
  }));
92342
93097
  const oauthIntegrationProvider = { getDescriptor: async () => buildGoogleOauthIntegration() };
92343
93098
  this.ctx.logger.info("export-google: initialized", { meta: {
92344
- exposedCount: this.exposedDevices.length,
92345
- linkedAccounts: this.config.linkedAccounts.length,
93099
+ instances: (await registry.list()).length,
92346
93100
  willReportState: false
92347
93101
  } });
92348
93102
  return [
@@ -92357,16 +93111,151 @@ var ExportGoogleAddon = class extends BaseAddon {
92357
93111
  {
92358
93112
  capability: oauthIntegrationCapability,
92359
93113
  provider: oauthIntegrationProvider
93114
+ },
93115
+ {
93116
+ capability: integrationInstancesCapability,
93117
+ provider: this.instances.toProvider()
92360
93118
  }
92361
93119
  ];
92362
93120
  }
92363
93121
  async onShutdown() {
92364
93122
  this.gateway = null;
93123
+ this.registry = null;
92365
93124
  }
92366
- isExposed(deviceId) {
92367
- return this.exposedDevices.some((entry) => entry.deviceId === deviceId);
93125
+ async onInstanceChanged(id, change) {
93126
+ const registry = this.requireRegistry();
93127
+ if (change === "deleted") await registry.remove(id);
93128
+ else if (change === "created") await registry.get(id);
93129
+ else await registry.refreshHome(id);
92368
93130
  }
92369
- async exposeDevice(deviceIdRaw) {
93131
+ homeForm(id) {
93132
+ const target = id === null ? "<instance id>" : id;
93133
+ return this.schema({ sections: [{
93134
+ id: ADDON_ID,
93135
+ title: "Connection",
93136
+ description: "Publishes switches, dimmable lights, locks and covers to Google Home. The hub answers Google directly — no cloud function, and no Google credential is stored here.",
93137
+ columns: 1,
93138
+ fields: [{
93139
+ type: "info",
93140
+ key: "__google-setup-banner",
93141
+ label: "Setup overview",
93142
+ variant: "info",
93143
+ content: [
93144
+ "This hub must be reachable from the public internet over HTTPS (Cloudflare Tunnel, Tailscale Funnel, …) — Google calls the fulfillment URL from its own cloud.",
93145
+ `Create a cloud-to-cloud integration in the Google Home Developer Console, paste the three URLs from the Export panel (the fulfillment URL ends in /fulfillment/${target}), and link your account from the Home app.`,
93146
+ "Each Google Home instance is one Actions-console project with its own devices and linked accounts.",
93147
+ "Cameras are not exported, and state is not pushed: Google polls. Ask \"Hey Google, sync my devices\" after exposing something new."
93148
+ ].join("\n")
93149
+ }]
93150
+ }] });
93151
+ }
93152
+ async resolveFulfillment(instanceId) {
93153
+ const instance = await this.requireRegistry().get(instanceId);
93154
+ if (instance === null) return {
93155
+ ok: false,
93156
+ code: "unknown_instance"
93157
+ };
93158
+ if (!instance.enabled) return {
93159
+ ok: false,
93160
+ code: "instance_disabled"
93161
+ };
93162
+ return {
93163
+ ok: true,
93164
+ deps: this.fulfillmentFor(instance)
93165
+ };
93166
+ }
93167
+ /** The fulfillment wiring of ONE instance: its exposure, its links, nobody else's. */
93168
+ fulfillmentFor(instance) {
93169
+ const cached = this.fulfillments.get(instance);
93170
+ if (cached !== void 0) return cached;
93171
+ const gateway = this.requireGateway();
93172
+ const logger = this.ctx.logger;
93173
+ const deps = {
93174
+ logger,
93175
+ sync: {
93176
+ gateway,
93177
+ logger,
93178
+ listExposed: () => instance.devices.map((entry) => entry.deviceId),
93179
+ actions: instance.scenes
93180
+ },
93181
+ query: {
93182
+ gateway,
93183
+ logger,
93184
+ isExposed: (deviceId) => instance.isExposed(deviceId),
93185
+ actions: instance.scenes
93186
+ },
93187
+ execute: {
93188
+ gateway,
93189
+ logger,
93190
+ isExposed: (deviceId) => instance.isExposed(deviceId),
93191
+ actions: instance.scenes
93192
+ },
93193
+ recordLink: (caller) => instance.recordLink(caller),
93194
+ removeLink: (userId) => instance.removeLink(userId)
93195
+ };
93196
+ this.fulfillments.set(instance, deps);
93197
+ return deps;
93198
+ }
93199
+ buildDeviceExportProvider() {
93200
+ return {
93201
+ getStatus: async (input) => {
93202
+ const requested = statusInstanceOf(input);
93203
+ const rows = await this.requireRegistry().list();
93204
+ const target = requested ?? rows[0]?.id;
93205
+ if (target === void 0) return {
93206
+ linkState: "unlinked",
93207
+ exposedDeviceCount: 0,
93208
+ setup: await this.buildSetupBlock(void 0, 0)
93209
+ };
93210
+ const instance = await this.requireInstance(target);
93211
+ return {
93212
+ linkState: instance.linkedAccounts.length > 0 ? "linked" : "unlinked",
93213
+ exposedDeviceCount: instance.devices.length,
93214
+ setup: await this.buildSetupBlock(instance.id, instance.linkedAccounts.length)
93215
+ };
93216
+ },
93217
+ listInstances: async () => (await this.requireRegistry().list()).map((row) => ({
93218
+ instanceId: row.id,
93219
+ name: row.body.name,
93220
+ enabled: row.body.enabled !== false,
93221
+ kind: "google-home"
93222
+ })),
93223
+ listSupportedDeviceKinds: async ({ instanceId }) => {
93224
+ await this.requireInstance(instanceId ?? "export-google");
93225
+ return [...SUPPORTED_DEVICE_KINDS];
93226
+ },
93227
+ listExposedDevices: async ({ instanceId }) => {
93228
+ return (await this.requireInstance(instanceId ?? "export-google")).devices.map((entry) => ({ deviceId: String(entry.deviceId) }));
93229
+ },
93230
+ exposeDevice: async ({ instanceId, deviceId }) => this.exposeDevice(await this.requireInstance(instanceId ?? "export-google"), deviceId),
93231
+ unexposeDevice: async ({ instanceId, deviceId }) => this.unexposeDevice(await this.requireInstance(instanceId ?? "export-google"), deviceId),
93232
+ listSupportedEntityKinds: async () => ["device", "action"],
93233
+ listExposedEntities: async ({ instanceId }) => {
93234
+ const instance = await this.requireInstance(instanceId ?? "export-google");
93235
+ await instance.scenes.reconcile();
93236
+ return [...instance.devices.map((entry) => ({ entity: {
93237
+ kind: "device",
93238
+ deviceId: String(entry.deviceId)
93239
+ } })), ...instance.scenes.list()];
93240
+ },
93241
+ exposeEntity: async ({ instanceId, entity }) => {
93242
+ const instance = await this.requireInstance(instanceId ?? "export-google");
93243
+ if (entity.kind === "device") return this.exposeDevice(instance, entity.deviceId);
93244
+ if (entity.kind === "action") return instance.scenes.expose(entity.actionId);
93245
+ throw new Error("export-google: a notification target cannot be exported to Google Home");
93246
+ },
93247
+ unexposeEntity: async ({ instanceId, entity }) => {
93248
+ const instance = await this.requireInstance(instanceId ?? "export-google");
93249
+ if (entity.kind === "device") return this.unexposeDevice(instance, entity.deviceId);
93250
+ if (entity.kind === "action") return instance.scenes.unexpose(entity.actionId);
93251
+ throw new Error("export-google: a notification target cannot be exported to Google Home");
93252
+ },
93253
+ getDeviceSettingsContribution: (input) => this.buildDeviceSettingsContribution(Number(input.deviceId)),
93254
+ getDeviceLiveContribution: async () => null,
93255
+ applyDeviceSettingsPatch: (input) => this.applyDeviceSettingsPatch(Number(input.deviceId), input.patch)
93256
+ };
93257
+ }
93258
+ async exposeDevice(instance, deviceIdRaw) {
92370
93259
  const deviceId = Number.parseInt(deviceIdRaw, 10);
92371
93260
  if (!Number.isFinite(deviceId)) throw new Error(`export-google: deviceId must be numeric — got "${deviceIdRaw}"`);
92372
93261
  const facts = await this.requireGateway().loadFacts(deviceId).catch((err) => {
@@ -92377,47 +93266,38 @@ var ExportGoogleAddon = class extends BaseAddon {
92377
93266
  this.ctx.logger.warn("export-google: refused to expose — no exported capability", {
92378
93267
  tags: { deviceId },
92379
93268
  meta: {
93269
+ instanceId: instance.id,
92380
93270
  deviceType: facts.deviceType,
92381
93271
  capNames: facts.capNames
92382
93272
  }
92383
93273
  });
92384
93274
  throw new Error(`export-google: device ${deviceId} has no capability this addon exports (bound: ${facts.capNames.join(", ") || "none"})`);
92385
93275
  }
92386
- const next = this.exposedDevices.filter((e) => e.deviceId !== deviceId);
92387
- next.push({
93276
+ const next = instance.devices.filter((e) => e.deviceId !== deviceId);
93277
+ await instance.writeExports({ devices: [...next, {
92388
93278
  deviceId,
92389
93279
  exposedAt: Date.now()
93280
+ }] });
93281
+ this.ctx.logger.info("export-google: exposed device — visible after the next Google SYNC (\"Hey Google, sync my devices\")", {
93282
+ tags: { deviceId },
93283
+ meta: { instanceId: instance.id }
92390
93284
  });
92391
- await this.writeExports({ devices: next });
92392
- this.ctx.logger.info("export-google: exposed device — visible after the next Google SYNC (\"Hey Google, sync my devices\")", { tags: { deviceId } });
92393
93285
  }
92394
- async unexposeDevice(deviceIdRaw) {
93286
+ async unexposeDevice(instance, deviceIdRaw) {
92395
93287
  const deviceId = Number.parseInt(deviceIdRaw, 10);
92396
93288
  if (!Number.isFinite(deviceId)) return;
92397
- const next = this.exposedDevices.filter((e) => e.deviceId !== deviceId);
92398
- if (next.length === this.exposedDevices.length) return;
92399
- await this.writeExports({ devices: next });
92400
- this.ctx.logger.info("export-google: unexposed device — removed from Google on its next SYNC", { tags: { deviceId } });
93289
+ const next = instance.devices.filter((e) => e.deviceId !== deviceId);
93290
+ if (next.length === instance.devices.length) return;
93291
+ await instance.writeExports({ devices: next });
93292
+ this.ctx.logger.info("export-google: unexposed device — removed from Google on its next SYNC", {
93293
+ tags: { deviceId },
93294
+ meta: { instanceId: instance.id }
93295
+ });
92401
93296
  }
92402
93297
  requireGateway() {
92403
93298
  if (this.gateway === null) throw new Error("export-google: addon not initialized");
92404
93299
  return this.gateway;
92405
93300
  }
92406
- async recordLink(caller) {
92407
- if (this.config.linkedAccounts.some((account) => account.userId === caller.userId)) return;
92408
- const next = [...this.config.linkedAccounts, {
92409
- userId: caller.userId,
92410
- username: caller.username,
92411
- linkedAt: Date.now()
92412
- }];
92413
- await this.updateGlobalSettings({ linkedAccounts: next });
92414
- this.ctx.logger.info("export-google: recorded linked account", { meta: { userId: caller.userId } });
92415
- }
92416
- async removeLink(userId) {
92417
- const next = this.config.linkedAccounts.filter((account) => account.userId !== userId);
92418
- if (next.length === this.config.linkedAccounts.length) return;
92419
- await this.updateGlobalSettings({ linkedAccounts: next });
92420
- }
92421
93301
  /**
92422
93302
  * The three URLs the operator pastes into the Actions console, plus the
92423
93303
  * linked-account count.
@@ -92427,88 +93307,85 @@ var ExportGoogleAddon = class extends BaseAddon {
92427
93307
  * value still travels in the `getStatus` response — so it would be the wrong
92428
93308
  * tool for a real credential anyway (docs/decisions/adr-0269-a-google-export-that-holds-no-google-credential.md).
92429
93309
  */
92430
- async buildSetupBlock() {
93310
+ async buildSetupBlock(instanceId, linkedAccounts) {
92431
93311
  return buildConsoleSetupFromRole({
92432
93312
  addonId: ADDON_ID,
92433
- linkedAccounts: this.config.linkedAccounts.length,
93313
+ ...instanceId !== void 0 ? { instanceId } : {},
93314
+ linkedAccounts,
92434
93315
  read: () => this.ctx.api.localNetwork.getAddresses.query()
92435
93316
  });
92436
93317
  }
92437
- globalSettingsSchema() {
92438
- return this.schema({ sections: [{
92439
- id: ADDON_ID,
92440
- title: "Connection",
92441
- description: "Publishes switches, dimmable lights, locks and covers to Google Home. The hub answers Google directly — no cloud function, and no Google credential is stored here.",
92442
- columns: 1,
92443
- fields: [{
92444
- type: "info",
92445
- key: "__google-setup-banner",
92446
- label: "Setup overview",
92447
- variant: "info",
92448
- content: [
92449
- "This hub must be reachable from the public internet over HTTPS (Cloudflare Tunnel, Tailscale Funnel, …) — Google calls the fulfillment URL from its own cloud.",
92450
- "Create a cloud-to-cloud integration in the Google Home Developer Console, paste the three URLs from the Export panel, and link your account from the Home app.",
92451
- "Cameras are not exported, and state is not pushed: Google polls. Ask \"Hey Google, sync my devices\" after exposing something new."
92452
- ].join("\n")
92453
- }]
92454
- }] });
92455
- }
92456
93318
  /**
92457
- * Per-device "Export" panel. Offered only for devices this addon can actually
92458
- * represent — a toggle on a camera would be a switch that promises something
92459
- * `buildSyncDevice` then refuses.
93319
+ * Per-device "Export" panel: one section per enabled instance. Offered only for devices this
93320
+ * addon can actually represent — a toggle on a camera would be a switch that promises
93321
+ * something `buildSyncDevice` then refuses.
92460
93322
  */
92461
93323
  async buildDeviceSettingsContribution(deviceId) {
92462
93324
  const facts = await this.requireGateway().loadFacts(deviceId).catch(() => null);
92463
93325
  if (facts === null) return null;
92464
93326
  const descriptors = traitsForCaps(facts.capNames);
92465
93327
  if (descriptors.length === 0) return null;
92466
- const enabled = this.isExposed(deviceId);
92467
- const linked = this.config.linkedAccounts.length;
92468
- const enabledKey = `google:${deviceId}:enabled`;
92469
- return {
92470
- tabs: [{
92471
- id: "export",
92472
- label: "Export",
92473
- icon: "share-2",
92474
- order: 80
92475
- }],
92476
- sections: [{
92477
- id: ADDON_ID,
92478
- title: "Google Home Export",
93328
+ const registry = this.requireRegistry();
93329
+ const rows = (await registry.list()).filter((row) => row.body.enabled !== false);
93330
+ const sections = [];
93331
+ for (const row of rows) {
93332
+ const instance = await registry.get(row.id);
93333
+ if (instance === null) continue;
93334
+ const enabled = instance.isExposed(deviceId);
93335
+ const linked = instance.linkedAccounts.length;
93336
+ const statusLabel = enabled ? `Exposed as ${descriptors.map((d) => d.trait.replace("action.devices.traits.", "")).join(" + ")}${linked > 0 ? `, ${linked} linked Google account(s)` : " (no linked Google account yet)"}` : "Not exposed";
93337
+ sections.push({
93338
+ id: `${ADDON_ID}:${instance.id}`,
93339
+ title: rows.length === 1 ? "Google Home Export" : `Google Home Export — ${instance.name}`,
92479
93340
  description: "Surface this device to the linked Google Home account.",
92480
93341
  tab: "export",
92481
93342
  columns: 1,
92482
- order: 30,
93343
+ order: 30 + sections.length,
92483
93344
  fields: [{
92484
93345
  type: "info",
92485
- key: "__google-status",
93346
+ key: `__google-status:${instance.id}`,
92486
93347
  label: "Status",
92487
- content: enabled ? `Exposed as ${descriptors.map((d) => d.trait.replace("action.devices.traits.", "")).join(" + ")}${linked > 0 ? `, ${linked} linked Google account(s)` : " (no linked Google account yet)"}` : "Not exposed",
93348
+ content: statusLabel,
92488
93349
  variant: "info"
92489
93350
  }, {
92490
93351
  type: "boolean",
92491
- key: enabledKey,
93352
+ key: deviceKey(instance.id, deviceId),
92492
93353
  label: "Expose to Google Home",
92493
93354
  description: "Google picks the change up on its next sync — say \"Hey Google, sync my devices\" to force one.",
92494
93355
  style: "switch",
92495
93356
  value: enabled,
92496
93357
  immediate: true
92497
93358
  }]
92498
- }]
93359
+ });
93360
+ }
93361
+ if (sections.length === 0) return null;
93362
+ return {
93363
+ tabs: [{
93364
+ id: "export",
93365
+ label: "Export",
93366
+ icon: "share-2",
93367
+ order: 80
93368
+ }],
93369
+ sections
92499
93370
  };
92500
93371
  }
92501
93372
  async applyDeviceSettingsPatch(deviceId, patch) {
92502
- const enabledKey = `google:${deviceId}:enabled`;
92503
- if (!(enabledKey in patch)) return { success: true };
92504
- const next = patch[enabledKey];
92505
- if (typeof next !== "boolean") {
92506
- this.ctx.logger.warn("export-google: ignored export toggle — value was not a boolean", { tags: { deviceId } });
92507
- return { success: true };
93373
+ for (const [key, next] of Object.entries(patch)) {
93374
+ const match = DEVICE_KEY.exec(key);
93375
+ if (match === null || Number(match[2]) !== deviceId) continue;
93376
+ const instanceId = match[1] ?? "";
93377
+ if (typeof next !== "boolean") {
93378
+ this.ctx.logger.warn("export-google: ignored export toggle — value was not a boolean", {
93379
+ tags: { deviceId },
93380
+ meta: { instanceId }
93381
+ });
93382
+ continue;
93383
+ }
93384
+ const instance = await this.requireInstance(instanceId);
93385
+ if (next === instance.isExposed(deviceId)) continue;
93386
+ if (next) await this.exposeDevice(instance, String(deviceId));
93387
+ else await this.unexposeDevice(instance, String(deviceId));
92508
93388
  }
92509
- if (next === this.isExposed(deviceId)) return { success: true };
92510
- if (next) await this.exposeDevice(String(deviceId));
92511
- else await this.unexposeDevice(String(deviceId));
92512
93389
  return { success: true };
92513
93390
  }
92514
93391
  };