@camstack/addon-provider-dreo 0.1.5 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/addon.mjs CHANGED
@@ -14803,83 +14803,34 @@ var GetStateInputSchema = object({
14803
14803
  * HA: entity_id (returns the cached entity state). */
14804
14804
  key: string()
14805
14805
  });
14806
- var brokerCapability = {
14807
- name: "broker",
14808
- scope: "system",
14809
- mode: "collection",
14810
- providerKind: "broker",
14811
- status: {
14812
- schema: RegistryStatusSchema,
14813
- kind: "poll"
14814
- },
14815
- methods: {
14816
- list: method(ListInputSchema, array(BrokerInfoSchema$1)),
14817
- get: method(GetInputSchema, BrokerInfoSchema$1.nullable()),
14818
- /** Enumerate which addon provides which broker kind(s) for the
14819
- * unified create picker. The auto-mount fans this array across
14820
- * every registered `broker` provider (array-output method), so the
14821
- * picker sees every kind from every provider in one call. */
14822
- listProviders: method(_void(), array(BrokerProviderInfoSchema), { auth: "admin" }),
14823
- add: method(AddInputSchema, AddResultSchema, {
14824
- kind: "mutation",
14825
- auth: "admin"
14826
- }),
14827
- remove: method(RemoveInputSchema, _void(), {
14828
- kind: "mutation",
14829
- auth: "admin"
14830
- }),
14831
- testConnection: method(GetInputSchema, TestConnectionResultSchema, {
14832
- kind: "mutation",
14833
- auth: "admin"
14834
- }),
14835
- /** Read the persisted settings record for a broker (kind-specific
14836
- * shape). Admin-only — settings may contain secrets. Returns `null`
14837
- * when the broker id is unknown to the provider (the collection
14838
- * fallback may route a foreign id to the first provider). */
14839
- getSettings: method(GetInputSchema, SettingsRecordSchema$1.nullable(), { auth: "admin" }),
14840
- /** Overwrite the persisted settings record. The kind-specific
14841
- * provider validates the shape and applies the change (reconnects
14842
- * if credentials changed). */
14843
- setSettings: method(object({
14844
- id: string(),
14845
- settings: SettingsRecordSchema$1
14846
- }), _void(), {
14847
- kind: "mutation",
14848
- auth: "admin"
14849
- }),
14850
- /** Returns the kind-specific connection config the consumer needs
14851
- * to open its own client (MQTT pattern: `{url, username, password,
14852
- * clientIdPrefix}`). HA providers MAY return the auth envelope
14853
- * but typical HA consumers use `publish` / `subscribe` instead.
14854
- * Returns `null` when the broker id is unknown to the provider. */
14855
- getBrokerConfig: method(GetInputSchema, SettingsRecordSchema$1.nullable(), { auth: "admin" }),
14856
- getSettingsSchema: method(SettingsSchemaInputSchema, SettingsSchemaResultSchema, { auth: "admin" }),
14857
- testSettings: method(TestSettingsInputSchema, TestSettingsResultSchema, {
14858
- kind: "mutation",
14859
- auth: "admin"
14860
- }),
14861
- publish: method(PublishInputSchema, unknown(), {
14862
- kind: "mutation",
14863
- auth: "admin"
14864
- }),
14865
- subscribe: method(SubscribeInputSchema, SubscribeResultSchema, {
14866
- kind: "mutation",
14867
- auth: "admin"
14868
- }),
14869
- unsubscribe: method(UnsubscribeInputSchema, _void(), {
14870
- kind: "mutation",
14871
- auth: "admin"
14872
- }),
14873
- /** Read the broker's cached state for a key. Returns `null` when
14874
- * unknown to the broker (never published / unknown entity). */
14875
- getState: method(GetStateInputSchema, unknown().nullable()),
14876
- /** Status method — explicit registration with a `z.void()` input so
14877
- * the codegen-generated tRPC router types its input as
14878
- * `{addonId?: string, nodeId?: string}` (system-scoped collection
14879
- * shape) instead of the device-scoped `{deviceId}` fallback. */
14880
- getStatus: method(_void(), RegistryStatusSchema)
14881
- }
14882
- };
14806
+ method(ListInputSchema, array(BrokerInfoSchema$1)), method(GetInputSchema, BrokerInfoSchema$1.nullable()), method(_void(), array(BrokerProviderInfoSchema), { auth: "admin" }), method(AddInputSchema, AddResultSchema, {
14807
+ kind: "mutation",
14808
+ auth: "admin"
14809
+ }), method(RemoveInputSchema, _void(), {
14810
+ kind: "mutation",
14811
+ auth: "admin"
14812
+ }), method(GetInputSchema, TestConnectionResultSchema, {
14813
+ kind: "mutation",
14814
+ auth: "admin"
14815
+ }), method(GetInputSchema, SettingsRecordSchema$1.nullable(), { auth: "admin" }), method(object({
14816
+ id: string(),
14817
+ settings: SettingsRecordSchema$1
14818
+ }), _void(), {
14819
+ kind: "mutation",
14820
+ auth: "admin"
14821
+ }), method(GetInputSchema, SettingsRecordSchema$1.nullable(), { auth: "admin" }), method(SettingsSchemaInputSchema, SettingsSchemaResultSchema, { auth: "admin" }), method(TestSettingsInputSchema, TestSettingsResultSchema, {
14822
+ kind: "mutation",
14823
+ auth: "admin"
14824
+ }), method(PublishInputSchema, unknown(), {
14825
+ kind: "mutation",
14826
+ auth: "admin"
14827
+ }), method(SubscribeInputSchema, SubscribeResultSchema, {
14828
+ kind: "mutation",
14829
+ auth: "admin"
14830
+ }), method(UnsubscribeInputSchema, _void(), {
14831
+ kind: "mutation",
14832
+ auth: "admin"
14833
+ }), method(GetStateInputSchema, unknown().nullable()), method(_void(), RegistryStatusSchema);
14883
14834
  DeviceType.Camera;
14884
14835
  /**
14885
14836
  * `custom-model-registry` — collection cap exposing operator-registered
@@ -18334,6 +18285,17 @@ var AvailableIntegrationTypeSchema = object({
18334
18285
  iconUrl: string().nullable(),
18335
18286
  color: string(),
18336
18287
  instanceMode: string(),
18288
+ /**
18289
+ * Integration wizard `mode` (LOCKED MODEL): `standalone` (create
18290
+ * immediately then add devices, no config step/button), `account` (config
18291
+ * step), or `broker` (broker step). Derived server-side by
18292
+ * `getAvailableTypes` when the addon manifest omits an explicit `mode`.
18293
+ */
18294
+ mode: _enum([
18295
+ "standalone",
18296
+ "account",
18297
+ "broker"
18298
+ ]),
18337
18299
  discoveryMode: string(),
18338
18300
  /**
18339
18301
  * Which integration-marker cap the addon declared, so the wizard can
@@ -24052,6 +24014,89 @@ object({
24052
24014
  schemaVersion: literal(1)
24053
24015
  });
24054
24016
  //#endregion
24017
+ //#region src/config.ts
24018
+ /**
24019
+ * Dreo cloud regions the wrapped `@apocaliss92/nodedreo` client accepts. The
24020
+ * library does not export a region enum (region is a free `opts.region` string),
24021
+ * so we mirror the common Dreo regions locally and validate the operator-supplied
24022
+ * value at the system boundary. `us` is the default (the most common Dreo cloud).
24023
+ */
24024
+ var DREO_REGIONS = ["us", "eu"];
24025
+ var DreoRegionSchema = _enum(DREO_REGIONS);
24026
+ /**
24027
+ * Operator-supplied Dreo account settings for ONE integration (= one cloud
24028
+ * account). The Dreo integration is cloud-only (REST auth + a persistent
24029
+ * WebSocket push), so the connection is just account credentials plus a region.
24030
+ */
24031
+ var dreoConfigSchema = object({
24032
+ email: string().min(1).describe("Dreo account email"),
24033
+ password: string().min(1).describe("Dreo account password"),
24034
+ region: DreoRegionSchema.default("us").describe("Dreo cloud region")
24035
+ });
24036
+ /**
24037
+ * Split the validated addon config into the two arguments the `Nodedreo`
24038
+ * constructor expects (`creds`, `opts`). Pure: same config in → same args out.
24039
+ */
24040
+ function toDreoConstructorArgs(config) {
24041
+ return {
24042
+ creds: {
24043
+ email: config.email,
24044
+ password: config.password
24045
+ },
24046
+ opts: { region: config.region }
24047
+ };
24048
+ }
24049
+ /**
24050
+ * Parse an integration's settings into a connection, or null when the mandatory
24051
+ * credentials (email + password) are missing. Used by the boot/lifecycle
24052
+ * reconcile to skip an integration whose account form was not completed.
24053
+ */
24054
+ function connectionFromSettings(settings) {
24055
+ const parsed = dreoConfigSchema.safeParse(settings);
24056
+ return parsed.success ? parsed.data : null;
24057
+ }
24058
+ /**
24059
+ * Hand-written connection form for the account/integration creation UI — the
24060
+ * wizard's `account` config step renders this via `getGlobalSettings`. A flat
24061
+ * set of sections the admin UI renders into the "Add Dreo account" modal.
24062
+ */
24063
+ function buildConnectionFormSchema() {
24064
+ return { sections: [{
24065
+ id: "credentials",
24066
+ title: "Dreo account",
24067
+ description: "Sign in with your Dreo app account credentials.",
24068
+ columns: 1,
24069
+ fields: [{
24070
+ type: "text",
24071
+ key: "email",
24072
+ label: "Email",
24073
+ required: true,
24074
+ placeholder: "you@example.com"
24075
+ }, {
24076
+ type: "password",
24077
+ key: "password",
24078
+ label: "Password",
24079
+ required: true,
24080
+ showToggle: true
24081
+ }]
24082
+ }, {
24083
+ id: "region",
24084
+ title: "Region",
24085
+ description: "Select the Dreo cloud region your account is registered in.",
24086
+ columns: 1,
24087
+ fields: [{
24088
+ type: "select",
24089
+ key: "region",
24090
+ label: "Region",
24091
+ default: "us",
24092
+ options: DREO_REGIONS.map((r) => ({
24093
+ value: r,
24094
+ label: r.toUpperCase()
24095
+ }))
24096
+ }]
24097
+ }] };
24098
+ }
24099
+ //#endregion
24055
24100
  //#region ../../node_modules/ws/lib/constants.js
24056
24101
  var require_constants = /* @__PURE__ */ __commonJSMin(((exports, module) => {
24057
24102
  var BINARY_TYPES = [
@@ -28897,99 +28942,6 @@ var Nodedreo = class {
28897
28942
  }
28898
28943
  };
28899
28944
  //#endregion
28900
- //#region src/config.ts
28901
- /**
28902
- * Dreo cloud regions the wrapped `@apocaliss92/nodedreo` client accepts. The
28903
- * library does not export a region enum (region is a free `opts.region` string),
28904
- * so we mirror the common Dreo regions locally and validate the operator-supplied
28905
- * value at the system boundary. `us` is the default (the most common Dreo cloud).
28906
- */
28907
- var DREO_REGIONS = ["us", "eu"];
28908
- var DreoRegionSchema = _enum(DREO_REGIONS);
28909
- /**
28910
- * Operator-supplied Dreo account settings for ONE broker (= one cloud account).
28911
- * The Dreo integration is cloud-only (REST auth + a persistent WebSocket push),
28912
- * so the connection is just account credentials plus a region.
28913
- */
28914
- var dreoConfigSchema = object({
28915
- email: string().min(1).describe("Dreo account email"),
28916
- password: string().min(1).describe("Dreo account password"),
28917
- region: DreoRegionSchema.default("us").describe("Dreo cloud region")
28918
- });
28919
- /**
28920
- * Split the validated addon config into the two arguments the `Nodedreo`
28921
- * constructor expects (`creds`, `opts`). Pure: same config in → same args out.
28922
- */
28923
- function toDreoConstructorArgs(config) {
28924
- return {
28925
- creds: {
28926
- email: config.email,
28927
- password: config.password
28928
- },
28929
- opts: { region: config.region }
28930
- };
28931
- }
28932
- /** Top-level addon config — an ordered list of broker entries (default empty). */
28933
- var dreoAddonConfigSchema = object({ brokers: array(object({
28934
- /** Stable opaque identifier — e.g. 'dreo_001', 'dreo_002'. */
28935
- id: string().min(1),
28936
- /** Human-readable label shown in the admin UI. */
28937
- name: string().min(1),
28938
- /** Validated account connection settings. */
28939
- connection: dreoConfigSchema,
28940
- /** FK to the spawning integration — auto-cleanup on integration delete. */
28941
- integrationId: string().optional()
28942
- })).default([]) });
28943
- /**
28944
- * Coerce a loose settings blob (from the broker `add`/`setSettings` cap) through
28945
- * the connection schema, applying all defaults. Throws a `ZodError` on invalid
28946
- * input so the caller surfaces a clear error at the system boundary.
28947
- */
28948
- function settingsToDreoConfig(settings) {
28949
- return dreoConfigSchema.parse(settings ?? {});
28950
- }
28951
- /**
28952
- * Hand-written connection form for the broker/integration creation UI. Mirrors
28953
- * the Dreame / Homematic broker-settings form shape — a flat set of sections the
28954
- * admin UI renders into the "Add Dreo account" modal.
28955
- */
28956
- function buildConnectionFormSchema() {
28957
- return { sections: [{
28958
- id: "credentials",
28959
- title: "Dreo account",
28960
- description: "Sign in with your Dreo app account credentials.",
28961
- columns: 1,
28962
- fields: [{
28963
- type: "text",
28964
- key: "email",
28965
- label: "Email",
28966
- required: true,
28967
- placeholder: "you@example.com"
28968
- }, {
28969
- type: "password",
28970
- key: "password",
28971
- label: "Password",
28972
- required: true,
28973
- showToggle: true
28974
- }]
28975
- }, {
28976
- id: "region",
28977
- title: "Region",
28978
- description: "Select the Dreo cloud region your account is registered in.",
28979
- columns: 1,
28980
- fields: [{
28981
- type: "select",
28982
- key: "region",
28983
- label: "Region",
28984
- default: "us",
28985
- options: DREO_REGIONS.map((r) => ({
28986
- value: r,
28987
- label: r.toUpperCase()
28988
- }))
28989
- }]
28990
- }] };
28991
- }
28992
- //#endregion
28993
28945
  //#region src/dreo-integration-manager.ts
28994
28946
  function defaultFacade(config) {
28995
28947
  const { creds, opts } = toDreoConstructorArgs(config);
@@ -29147,15 +29099,20 @@ function sameConnection(a, b) {
29147
29099
  //#endregion
29148
29100
  //#region src/dreo-gateway.ts
29149
29101
  /**
29150
- * Per-broker registry that device classes use to reach a live Dreo device
29102
+ * Per-integration registry that device classes use to reach a live Dreo device
29151
29103
  * handle (and the discovery info) for a given Dreo account.
29152
29104
  *
29105
+ * `mode: account`: keyed by `integrationId`. The string key is generically named
29106
+ * `brokerId` in the method signatures below because the device classes pass their
29107
+ * persisted `brokerId` config field — which now holds the integrationId
29108
+ * (unchanged device-side code, see the addon migration note).
29109
+ *
29153
29110
  * The kernel constructs device classes with only a `DeviceContext` — it cannot
29154
29111
  * thread the handle in as a constructor arg. Like the Dreame addon's
29155
29112
  * `dreameFacades`, we keep it simple and in-process: the integration manager
29156
29113
  * owns the connection surface per registered account and publishes it here;
29157
29114
  * device classes resolve their live `BaseDevice` handle by `(brokerId,
29158
- * deviceId)`.
29115
+ * deviceId)` where `brokerId` = integrationId.
29159
29116
  */
29160
29117
  var DreoConnectionResolver = class {
29161
29118
  #surfaces = /* @__PURE__ */ new Map();
@@ -29192,31 +29149,51 @@ var DreoConnectionResolver = class {
29192
29149
  this.#surfaces.clear();
29193
29150
  }
29194
29151
  };
29195
- /** The single in-process per-broker connection resolver shared between the
29196
- * registry/manager and device instances. */
29152
+ /** The single in-process per-integration connection resolver shared between the
29153
+ * client registry/manager and device instances (keyed by integrationId). */
29197
29154
  var dreoConnections = new DreoConnectionResolver();
29198
29155
  //#endregion
29199
- //#region src/dreo-broker-registry.ts
29156
+ //#region src/dreo-client-registry.ts
29200
29157
  /**
29201
- * Manages N live Dreo account connections ("brokers"), each backed by a
29202
- * {@link DreoIntegrationManager}. Allocates stable ids (`dreo_001`, …), supports
29203
- * CRUD, an integration FK index for cascade-delete, and lifecycle helpers.
29204
- * Mirrors `DreameBrokerRegistry`.
29158
+ * Per-integration Dreo connection registry (account mode).
29159
+ *
29160
+ * Under the LOCKED integration/adoption model (design §7.1), Dreo is a
29161
+ * `mode: account` addon: each Dreo integration carries its own Dreo cloud
29162
+ * account credentials in its `integration.settings`, and this registry holds one
29163
+ * {@link DreoIntegrationManager} per `integrationId`
29164
+ * (`Map<integrationId, DreoIntegrationManager>`). Multi-account = multiple
29165
+ * integrations; there is NO shared broker.
29166
+ *
29167
+ * The live Dreo connection surface each manager owns (discovery info + per-device
29168
+ * handles) is published on the in-process {@link dreoConnections} resolver KEYED
29169
+ * BY `integrationId` — the manager's id IS the integrationId. Device classes
29170
+ * resolve their live handle by the `brokerId` config field they persist, which
29171
+ * now holds the integrationId (unchanged device-side code, see the addon
29172
+ * migration note). The WebSocket push lifecycle stays entirely inside the manager
29173
+ * + library (no leak): the registry only starts/stops managers.
29174
+ */
29175
+ /**
29176
+ * Owns the `Map<integrationId, DreoIntegrationManager>`. Callers reconcile the
29177
+ * map against the live integration list on boot + on every integration lifecycle
29178
+ * event; device classes + the adoption provider resolve their surface by
29179
+ * `integrationId` through {@link dreoConnections}.
29180
+ *
29181
+ * Structural twin of `DreameClientRegistry` / `WyzeClientRegistry` — `upsert` is
29182
+ * session-preserving when credentials are unchanged, `retain` drops vanished
29183
+ * integrations.
29205
29184
  */
29206
- var DreoBrokerRegistry = class {
29185
+ var DreoClientRegistry = class {
29207
29186
  #logger;
29208
- #onBrokerConnected;
29209
- #onBrokerDisconnected;
29187
+ #onConnected;
29188
+ #onDisconnected;
29210
29189
  #makeManager;
29211
- #managers = /* @__PURE__ */ new Map();
29212
- #integrationToBroker = /* @__PURE__ */ new Map();
29213
- #nextId = 1;
29190
+ #entries = /* @__PURE__ */ new Map();
29214
29191
  constructor(logger, deps = {}) {
29215
29192
  this.#logger = logger;
29216
- this.#onBrokerConnected = deps.onBrokerConnected ?? (() => void 0);
29217
- this.#onBrokerDisconnected = deps.onBrokerDisconnected ?? (() => void 0);
29193
+ this.#onConnected = deps.onConnected ?? (() => void 0);
29194
+ this.#onDisconnected = deps.onDisconnected ?? (() => void 0);
29218
29195
  this.#makeManager = deps.makeManager ?? ((opts) => new DreoIntegrationManager({
29219
- id: opts.id,
29196
+ id: opts.integrationId,
29220
29197
  name: opts.name,
29221
29198
  connection: opts.connection,
29222
29199
  logger: opts.logger,
@@ -29225,259 +29202,119 @@ var DreoBrokerRegistry = class {
29225
29202
  surfaceSink: dreoConnections
29226
29203
  }));
29227
29204
  }
29228
- /** Restore persisted broker entries on boot (best-effort per manager). */
29229
- async restore(entries) {
29230
- for (const entry of entries) this.#seedCounter(entry.id);
29231
- for (const entry of entries) try {
29232
- await this.#startManager(entry);
29233
- } catch (err) {
29234
- this.#logger.warn("DreoBrokerRegistry: failed to restore manager", {
29235
- tags: { brokerId: entry.id },
29236
- meta: { error: errMsg(err) }
29237
- });
29238
- }
29205
+ setOnConnected(cb) {
29206
+ this.#onConnected = cb;
29239
29207
  }
29240
- /** Stop all managers and clear state. */
29241
- async shutdown() {
29242
- const ids = Array.from(this.#managers.keys());
29243
- await Promise.all(ids.map(async (id) => {
29208
+ setOnDisconnected(cb) {
29209
+ this.#onDisconnected = cb;
29210
+ }
29211
+ /**
29212
+ * Ensure a manager exists for `integrationId` with the given credentials.
29213
+ * Idempotent: an existing entry with identical credentials is preserved (keeps
29214
+ * its live WebSocket session); a credentials change re-applies the connection
29215
+ * atomically (stop + start). Best-effort start — a failed login leaves the
29216
+ * entry registered so a later reconcile / lifecycle event retries.
29217
+ */
29218
+ async upsert(integrationId, name, connection) {
29219
+ const existing = this.#entries.get(integrationId);
29220
+ if (existing) {
29221
+ if (sameConnection(existing.connection, connection)) return;
29244
29222
  try {
29245
- await this.#managers.get(id)?.stop();
29223
+ await existing.manager.applyConnection(connection);
29224
+ this.#entries.set(integrationId, {
29225
+ manager: existing.manager,
29226
+ connection
29227
+ });
29246
29228
  } catch (err) {
29247
- this.#logger.warn("DreoBrokerRegistry: shutdown stop failed", {
29248
- tags: { brokerId: id },
29229
+ this.#logger.warn("DreoClientRegistry: applyConnection failed", {
29230
+ tags: { integrationId },
29249
29231
  meta: { error: errMsg(err) }
29250
29232
  });
29251
29233
  }
29252
- }));
29253
- this.#managers.clear();
29254
- this.#integrationToBroker.clear();
29255
- dreoConnections.clear();
29256
- }
29257
- setOnBrokerConnected(cb) {
29258
- this.#onBrokerConnected = cb;
29259
- }
29260
- setOnBrokerDisconnected(cb) {
29261
- this.#onBrokerDisconnected = cb;
29262
- }
29263
- async createEntry(name, connection, opts = {}) {
29264
- const id = this.#allocateId();
29265
- const entry = {
29266
- id,
29234
+ return;
29235
+ }
29236
+ const manager = this.#makeManager({
29237
+ integrationId,
29267
29238
  name,
29268
29239
  connection,
29269
- ...opts.integrationId !== void 0 ? { integrationId: opts.integrationId } : {}
29270
- };
29271
- await this.#startManager(entry);
29272
- if (opts.integrationId !== void 0) this.#integrationToBroker.set(opts.integrationId, id);
29273
- return entry;
29274
- }
29275
- async removeEntry(id) {
29276
- const mgr = this.#managers.get(id);
29277
- if (!mgr) throw new Error(`DreoBrokerRegistry: unknown broker id "${id}"`);
29278
- for (const [integrationId, brokerId] of this.#integrationToBroker.entries()) if (brokerId === id) this.#integrationToBroker.delete(integrationId);
29279
- this.#managers.delete(id);
29240
+ logger: this.#logger,
29241
+ onConnected: (id) => this.#onConnected(id),
29242
+ onDisconnected: (id) => this.#onDisconnected(id)
29243
+ });
29244
+ this.#entries.set(integrationId, {
29245
+ manager,
29246
+ connection
29247
+ });
29280
29248
  try {
29281
- await mgr.stop();
29249
+ await manager.start();
29282
29250
  } catch (err) {
29283
- this.#logger.warn("DreoBrokerRegistry: removeEntry stop failed", {
29284
- tags: { brokerId: id },
29251
+ this.#logger.warn("DreoClientRegistry: manager start failed", {
29252
+ tags: { integrationId },
29285
29253
  meta: { error: errMsg(err) }
29286
29254
  });
29287
29255
  }
29288
29256
  }
29289
- async updateEntry(id, connection) {
29290
- const mgr = this.#managers.get(id);
29291
- if (!mgr) throw new Error(`DreoBrokerRegistry: unknown broker id "${id}"`);
29292
- await mgr.applyConnection(connection);
29293
- return {
29294
- id,
29295
- name: mgr.getInfo().name,
29296
- connection
29297
- };
29257
+ /** Stop + drop the manager for an integration that no longer exists. */
29258
+ async remove(integrationId) {
29259
+ const entry = this.#entries.get(integrationId);
29260
+ if (!entry) return;
29261
+ this.#entries.delete(integrationId);
29262
+ try {
29263
+ await entry.manager.stop();
29264
+ } catch (err) {
29265
+ this.#logger.warn("DreoClientRegistry: remove stop failed", {
29266
+ tags: { integrationId },
29267
+ meta: { error: errMsg(err) }
29268
+ });
29269
+ }
29298
29270
  }
29299
- linkIntegration(integrationId, brokerId) {
29300
- this.#integrationToBroker.set(integrationId, brokerId);
29271
+ /** Stop + drop every manager whose integrationId is not in `keep`. */
29272
+ async retain(keep) {
29273
+ const stale = [...this.#entries.keys()].filter((id) => !keep.has(id));
29274
+ for (const id of stale) await this.remove(id);
29301
29275
  }
29302
- getBrokerIdByIntegrationId(integrationId) {
29303
- const brokerId = this.#integrationToBroker.get(integrationId);
29304
- if (brokerId === void 0) throw new Error(`DreoBrokerRegistry: no broker linked for integration id "${integrationId}"`);
29305
- return brokerId;
29276
+ /** Stop every manager and clear all state (full shutdown). */
29277
+ async shutdown() {
29278
+ const ids = [...this.#entries.keys()];
29279
+ await Promise.all(ids.map(async (id) => {
29280
+ try {
29281
+ await this.#entries.get(id)?.manager.stop();
29282
+ } catch (err) {
29283
+ this.#logger.warn("DreoClientRegistry: shutdown stop failed", {
29284
+ tags: { integrationId: id },
29285
+ meta: { error: errMsg(err) }
29286
+ });
29287
+ }
29288
+ }));
29289
+ this.#entries.clear();
29290
+ dreoConnections.clear();
29306
29291
  }
29292
+ /** True when a manager is registered for the integration. */
29293
+ has(integrationId) {
29294
+ return this.#entries.has(integrationId);
29295
+ }
29296
+ /** The registered integration ids (one per account). */
29307
29297
  list() {
29308
- return Array.from(this.#managers.values()).map((m) => m.getInfo());
29298
+ return [...this.#entries.keys()];
29309
29299
  }
29310
- get(id) {
29311
- return this.#managers.get(id)?.getInfo() ?? null;
29300
+ /** The current connection an integration's manager is configured with. */
29301
+ getConnection(integrationId) {
29302
+ return this.#entries.get(integrationId)?.connection ?? null;
29312
29303
  }
29313
- getConnection(id) {
29314
- return this.#managers.get(id)?.getConnection() ?? null;
29304
+ /** Immutable status snapshot for an integration's manager. */
29305
+ getInfo(integrationId) {
29306
+ return this.#entries.get(integrationId)?.manager.getInfo() ?? null;
29315
29307
  }
29316
29308
  size() {
29317
- return this.#managers.size;
29309
+ return this.#entries.size;
29318
29310
  }
29319
29311
  connectedCount() {
29320
29312
  let count = 0;
29321
- for (const mgr of this.#managers.values()) if (mgr.getInfo().status === "connected") count++;
29313
+ for (const entry of this.#entries.values()) if (entry.manager.getInfo().status === "connected") count++;
29322
29314
  return count;
29323
29315
  }
29324
- async #startManager(entry) {
29325
- if (this.#managers.has(entry.id)) {
29326
- if (entry.integrationId !== void 0) this.#integrationToBroker.set(entry.integrationId, entry.id);
29327
- return;
29328
- }
29329
- const mgr = this.#makeManager({
29330
- id: entry.id,
29331
- name: entry.name,
29332
- connection: entry.connection,
29333
- logger: this.#logger,
29334
- onConnected: (id) => this.#onBrokerConnected(id),
29335
- onDisconnected: (id) => this.#onBrokerDisconnected(id)
29336
- });
29337
- this.#managers.set(entry.id, mgr);
29338
- if (entry.integrationId !== void 0) this.#integrationToBroker.set(entry.integrationId, entry.id);
29339
- await mgr.start();
29340
- }
29341
- #allocateId() {
29342
- const id = `dreo_${String(this.#nextId).padStart(3, "0")}`;
29343
- this.#nextId++;
29344
- return id;
29345
- }
29346
- #seedCounter(id) {
29347
- const match = /^dreo_(\d+)$/.exec(id);
29348
- if (match === null || match[1] === void 0) return;
29349
- const n = parseInt(match[1], 10);
29350
- if (!isNaN(n)) this.#nextId = Math.max(this.#nextId, n + 1);
29351
- }
29352
29316
  };
29353
29317
  //#endregion
29354
- //#region src/dreo-broker-provider.ts
29355
- /** Kind tag registered by this provider — matches the `listProviders` entry. */
29356
- var DREO_KIND = "dreo";
29357
- /**
29358
- * Construct the `broker` cap provider for the Dreo addon. Pure builder: all
29359
- * side-effecting deps are injected so the returned object is unit-testable.
29360
- * Mirrors `buildDreameBrokerProvider`.
29361
- */
29362
- function buildDreoBrokerProvider(deps) {
29363
- const { ownerAddonId, registry, getBrokers, persistBrokers, cascadeRemoveDevices, logger } = deps;
29364
- const owns = (id) => getBrokers().some((b) => b.id === id);
29365
- return {
29366
- list: async ({ kind }) => {
29367
- if (kind && kind !== DREO_KIND) return [];
29368
- return registry.list().map((info) => ({
29369
- ...info,
29370
- addonId: ownerAddonId
29371
- }));
29372
- },
29373
- get: async ({ id }) => {
29374
- const info = registry.get(id);
29375
- return info ? {
29376
- ...info,
29377
- addonId: ownerAddonId
29378
- } : null;
29379
- },
29380
- listProviders: async () => [{
29381
- addonId: ownerAddonId,
29382
- kinds: [{
29383
- kind: DREO_KIND,
29384
- label: "Dreo"
29385
- }]
29386
- }],
29387
- add: async ({ kind, name, settings }) => {
29388
- if (kind !== DREO_KIND) throw new Error(`provider-dreo: only kind '${DREO_KIND}' is handled here (got '${kind}')`);
29389
- const entry = await registry.createEntry(name, settingsToDreoConfig(settings));
29390
- await persistBrokers([...getBrokers(), entry]);
29391
- return { id: entry.id };
29392
- },
29393
- remove: async ({ id }) => {
29394
- if (!owns(id)) return;
29395
- await registry.removeEntry(id);
29396
- await cascadeRemoveDevices(id).catch((err) => {
29397
- logger.warn("dreo: broker cascade-remove threw", {
29398
- tags: { brokerId: id },
29399
- meta: { error: errMsg(err) }
29400
- });
29401
- });
29402
- await persistBrokers(getBrokers().filter((b) => b.id !== id));
29403
- },
29404
- testConnection: async ({ id }) => {
29405
- if (!owns(id)) return {
29406
- ok: false,
29407
- error: "unknown broker"
29408
- };
29409
- const info = registry.get(id);
29410
- if (!info) return {
29411
- ok: false,
29412
- error: "unknown broker"
29413
- };
29414
- if (info.status === "connected") return {
29415
- ok: true,
29416
- latencyMs: info.lastCheckedAt ? Math.max(0, Date.now() - info.lastCheckedAt) : 0
29417
- };
29418
- return {
29419
- ok: false,
29420
- error: info.error ?? `status: ${info.status}`
29421
- };
29422
- },
29423
- getSettings: async ({ id }) => {
29424
- const entry = getBrokers().find((b) => b.id === id);
29425
- if (!entry) return null;
29426
- return {
29427
- ...entry.connection,
29428
- password: ""
29429
- };
29430
- },
29431
- setSettings: async ({ id, settings }) => {
29432
- if (!owns(id)) return;
29433
- const existing = getBrokers().find((b) => b.id === id);
29434
- if (!existing) return;
29435
- const parsed = settingsToDreoConfig(settings);
29436
- const merged = {
29437
- ...parsed,
29438
- password: parsed.password.length > 0 ? parsed.password : existing.connection.password
29439
- };
29440
- const updated = await registry.updateEntry(id, merged);
29441
- await persistBrokers(getBrokers().map((b) => b.id === id ? updated : b));
29442
- },
29443
- getBrokerConfig: async ({ id }) => {
29444
- const entry = getBrokers().find((b) => b.id === id);
29445
- if (!entry) return null;
29446
- return {
29447
- ...entry.connection,
29448
- password: ""
29449
- };
29450
- },
29451
- getSettingsSchema: async ({ kind }) => {
29452
- if (kind !== DREO_KIND) return null;
29453
- return buildConnectionFormSchema();
29454
- },
29455
- testSettings: async ({ kind, settings }) => {
29456
- if (kind !== DREO_KIND) return {
29457
- ok: false,
29458
- error: `unsupported kind: ${kind}`
29459
- };
29460
- try {
29461
- settingsToDreoConfig(settings);
29462
- return { ok: true };
29463
- } catch (err) {
29464
- return {
29465
- ok: false,
29466
- error: errMsg(err)
29467
- };
29468
- }
29469
- },
29470
- publish: async () => null,
29471
- subscribe: async () => ({ subscriptionId: "" }),
29472
- unsubscribe: async () => void 0,
29473
- getState: async () => null,
29474
- getStatus: async () => ({
29475
- brokerCount: registry.size(),
29476
- connectedCount: registry.connectedCount()
29477
- })
29478
- };
29479
- }
29480
- //#endregion
29481
29318
  //#region src/dreo-domain-mapping.ts
29482
29319
  /** Library device-type strings we treat as a CamStack `fan` kind. */
29483
29320
  var FAN_LIB_TYPES = new Set([
@@ -29599,11 +29436,11 @@ var DEVICES_FILTER = {
29599
29436
  label: "Devices",
29600
29437
  isDefault: true
29601
29438
  };
29602
- /** Build a `dreoDeviceId → CamStack deviceId` map for a single broker. */
29603
- async function adoptedMapForBroker(brokerId, listAdoptedDreo) {
29439
+ /** Build a `dreoDeviceId → CamStack deviceId` map for a single integration. */
29440
+ async function adoptedMapForIntegration(integrationId, listAdoptedDreo) {
29604
29441
  const all = await listAdoptedDreo();
29605
29442
  const map = /* @__PURE__ */ new Map();
29606
- for (const device of all) if (device.config["system"] === "dreo" && device.config["brokerId"] === brokerId) {
29443
+ for (const device of all) if (device.config["system"] === "dreo" && device.config["brokerId"] === integrationId) {
29607
29444
  const dreoId = device.config["dreoDeviceId"];
29608
29445
  if (typeof dreoId === "string") map.set(dreoId, device.id);
29609
29446
  }
@@ -29611,15 +29448,15 @@ async function adoptedMapForBroker(brokerId, listAdoptedDreo) {
29611
29448
  }
29612
29449
  /**
29613
29450
  * Construct the `device-adoption` cap provider for the Dreo addon. Pure builder:
29614
- * all side-effecting deps are injected. Mirrors `buildDreameAdoptionProvider`
29615
- * with a single `devices` granularity (one Container per cloud device).
29451
+ * all side-effecting deps are injected. Single `devices` granularity (one
29452
+ * Container per cloud device); resolves each account by `integrationId`.
29616
29453
  */
29617
29454
  function buildDreoAdoptionProvider(deps) {
29618
- const { registry, getBrokerIdForIntegration, listAdoptedDreo, adoptDevice, removeDevice, findDeviceConfig, logger } = deps;
29619
- async function allCandidatesForBroker(brokerId) {
29455
+ const { registry, hasIntegration, listIntegrations, listAdoptedDreo, adoptDevice, removeDevice, findDeviceConfig, logger } = deps;
29456
+ async function allCandidatesForIntegration(integrationId) {
29620
29457
  return buildDreoCandidates({
29621
- devices: registry.infos(brokerId),
29622
- adopted: await adoptedMapForBroker(brokerId, listAdoptedDreo)
29458
+ devices: registry.infos(integrationId),
29459
+ adopted: await adoptedMapForIntegration(integrationId, listAdoptedDreo)
29623
29460
  });
29624
29461
  }
29625
29462
  function applyCandidateTextFilter(cands, filterText) {
@@ -29637,7 +29474,7 @@ function buildDreoAdoptionProvider(deps) {
29637
29474
  return {
29638
29475
  listCandidateFilters: async () => ({ filters: [DEVICES_FILTER] }),
29639
29476
  listCandidates: async ({ integrationId, page, pageSize, filterText }) => {
29640
- const filtered = applyCandidateTextFilter(await allCandidatesForBroker(await getBrokerIdForIntegration(integrationId)), filterText);
29477
+ const filtered = applyCandidateTextFilter(await allCandidatesForIntegration(integrationId), filterText);
29641
29478
  const start = (page - 1) * pageSize;
29642
29479
  return {
29643
29480
  candidates: filtered.slice(start, start + pageSize),
@@ -29647,13 +29484,12 @@ function buildDreoAdoptionProvider(deps) {
29647
29484
  };
29648
29485
  },
29649
29486
  getCandidate: async ({ integrationId, childNativeId }) => {
29650
- return (await allCandidatesForBroker(await getBrokerIdForIntegration(integrationId))).find((c) => c.childNativeId === childNativeId) ?? null;
29487
+ return (await allCandidatesForIntegration(integrationId)).find((c) => c.childNativeId === childNativeId) ?? null;
29651
29488
  },
29652
29489
  getStatus: async () => {
29653
29490
  try {
29654
- const brokers = registry.list();
29655
29491
  let candidateCount = 0;
29656
- for (const broker of brokers) candidateCount += (await allCandidatesForBroker(broker.id)).length;
29492
+ for (const integrationId of listIntegrations()) candidateCount += (await allCandidatesForIntegration(integrationId)).length;
29657
29493
  const adoptedCount = (await listAdoptedDreo()).filter((d) => d.config["system"] === "dreo").length;
29658
29494
  return {
29659
29495
  lastDiscoveryAt: Date.now(),
@@ -29672,9 +29508,8 @@ function buildDreoAdoptionProvider(deps) {
29672
29508
  }
29673
29509
  },
29674
29510
  refresh: async ({ integrationId }) => {
29675
- const brokerId = await getBrokerIdForIntegration(integrationId);
29676
- const candidateCount = (await allCandidatesForBroker(brokerId)).length;
29677
- const adoptedCount = (await listAdoptedDreo()).filter((d) => d.config["system"] === "dreo" && d.config["brokerId"] === brokerId).length;
29511
+ const candidateCount = (await allCandidatesForIntegration(integrationId)).length;
29512
+ const adoptedCount = (await adoptedMapForIntegration(integrationId, listAdoptedDreo)).size;
29678
29513
  return {
29679
29514
  lastDiscoveryAt: Date.now(),
29680
29515
  candidateCount,
@@ -29683,17 +29518,16 @@ function buildDreoAdoptionProvider(deps) {
29683
29518
  };
29684
29519
  },
29685
29520
  adopt: async ({ integrationId, childNativeIds, perCandidate }) => {
29686
- const brokerId = await getBrokerIdForIntegration(integrationId);
29687
- if (!registry.has(brokerId)) throw new Error(`dreo adopt: broker ${brokerId} not connected`);
29688
- const devices = registry.infos(brokerId);
29521
+ if (!registry.has(integrationId)) throw new Error(`dreo adopt: integration ${integrationId} not connected`);
29522
+ const devices = registry.infos(integrationId);
29689
29523
  const adopted = [];
29690
29524
  let failures = 0;
29691
29525
  for (const dreoDeviceId of childNativeIds) try {
29692
29526
  const dev = devices.find((d) => d.deviceId === dreoDeviceId);
29693
29527
  if (dev === void 0) {
29694
- logger.warn("dreo adopt: device not found on broker — skipping", { meta: {
29528
+ logger.warn("dreo adopt: device not found on integration — skipping", { meta: {
29695
29529
  dreoDeviceId,
29696
- brokerId
29530
+ integrationId
29697
29531
  } });
29698
29532
  failures++;
29699
29533
  continue;
@@ -29705,7 +29539,7 @@ function buildDreoAdoptionProvider(deps) {
29705
29539
  if (candidate === void 0) {
29706
29540
  logger.warn("dreo adopt: device model unsupported — skipping", { meta: {
29707
29541
  dreoDeviceId,
29708
- brokerId,
29542
+ integrationId,
29709
29543
  model: dev.model
29710
29544
  } });
29711
29545
  failures++;
@@ -29714,7 +29548,6 @@ function buildDreoAdoptionProvider(deps) {
29714
29548
  const name = perCandidate?.[dreoDeviceId]?.name ?? dev.name ?? dreoDeviceId;
29715
29549
  const { deviceId, accessoryDeviceIds } = await adoptDevice({
29716
29550
  dreoDeviceId,
29717
- brokerId,
29718
29551
  integrationId,
29719
29552
  type: candidate.type,
29720
29553
  name,
@@ -29728,7 +29561,7 @@ function buildDreoAdoptionProvider(deps) {
29728
29561
  } catch (err) {
29729
29562
  logger.warn("dreo adopt: failed to adopt device", { meta: {
29730
29563
  dreoDeviceId,
29731
- brokerId,
29564
+ integrationId,
29732
29565
  error: errMsg(err)
29733
29566
  } });
29734
29567
  failures++;
@@ -29743,9 +29576,10 @@ function buildDreoAdoptionProvider(deps) {
29743
29576
  const cfg = await findDeviceConfig(camDeviceId);
29744
29577
  if (cfg === null) throw new Error(`dreo resync: device ${camDeviceId} not found`);
29745
29578
  if (cfg["system"] !== "dreo") throw new Error(`dreo resync: device ${camDeviceId} is not a Dreo device`);
29746
- const brokerId = String(cfg["brokerId"]);
29579
+ const integrationId = String(cfg["brokerId"]);
29747
29580
  const dreoDeviceId = String(cfg["dreoDeviceId"]);
29748
- if (!registry.infos(brokerId).some((d) => d.deviceId === dreoDeviceId)) throw new Error(`dreo resync: device ${dreoDeviceId} no longer present on broker ${brokerId}`);
29581
+ if (!hasIntegration(integrationId)) throw new Error(`dreo resync: integration ${integrationId} not connected`);
29582
+ if (!registry.infos(integrationId).some((d) => d.deviceId === dreoDeviceId)) throw new Error(`dreo resync: device ${dreoDeviceId} no longer present on integration ${integrationId}`);
29749
29583
  return {
29750
29584
  changed: false,
29751
29585
  rebuiltChildren: 0
@@ -29754,29 +29588,31 @@ function buildDreoAdoptionProvider(deps) {
29754
29588
  };
29755
29589
  }
29756
29590
  //#endregion
29757
- //#region src/dreo-broker-device-cascade.ts
29591
+ //#region src/dreo-integration-device-cascade.ts
29758
29592
  /**
29759
29593
  * Remove every adopted Dreo PARENT device (children cascade via the kernel)
29760
- * whose persisted config carries `{ system: 'dreo', brokerId }`. Used when a
29761
- * broker is removed (broker.remove) and when its spawning integration is
29762
- * deleted. Best-effort per device; returns the count removed. Mirrors the
29763
- * Dreame cascade helper.
29594
+ * whose persisted config carries `{ system: 'dreo', brokerId: integrationId }`.
29595
+ * Used when an integration is deleted/disabled. Best-effort per device; returns
29596
+ * the count removed.
29597
+ *
29598
+ * NOTE: the persisted config field is still named `brokerId` (unchanged
29599
+ * device-side schema) but under the account model it holds the `integrationId`.
29764
29600
  */
29765
- async function cascadeRemoveDevicesForBroker(input) {
29766
- const { reg, devices, addonId, brokerId, logger } = input;
29601
+ async function cascadeRemoveDevicesForIntegration(input) {
29602
+ const { reg, devices, addonId, integrationId, logger } = input;
29767
29603
  let removed = 0;
29768
29604
  for (const d of reg.getAllForAddon(addonId)) {
29769
29605
  if (d.parentDeviceId !== null) continue;
29770
29606
  const cfg = await devices.loadConfig(d.id).catch(() => ({}));
29771
- if (cfg["system"] !== "dreo" || cfg["brokerId"] !== brokerId) continue;
29607
+ if (cfg["system"] !== "dreo" || cfg["brokerId"] !== integrationId) continue;
29772
29608
  try {
29773
29609
  await devices.remove(d.id);
29774
29610
  removed += 1;
29775
29611
  } catch (err) {
29776
- logger.warn("dreo: broker cascade-remove failed", {
29612
+ logger.warn("dreo: integration cascade-remove failed", {
29777
29613
  tags: { deviceId: d.id },
29778
29614
  meta: {
29779
- brokerId,
29615
+ integrationId,
29780
29616
  error: errMsg(err)
29781
29617
  }
29782
29618
  });
@@ -29785,20 +29621,21 @@ async function cascadeRemoveDevicesForBroker(input) {
29785
29621
  return removed;
29786
29622
  }
29787
29623
  //#endregion
29788
- //#region src/dreo-broker-offline.ts
29624
+ //#region src/dreo-integration-offline.ts
29789
29625
  /**
29790
- * Set every Dreo device belonging to `brokerId` to the requested online state.
29791
- * `devices` is the addon-scoped device list; every Dreo top-level Container
29792
- * carries `{ system: 'dreo', brokerId }` in its config blob.
29626
+ * Set every Dreo device belonging to `integrationId` to the requested online
29627
+ * state. `devices` is the addon-scoped device list; every Dreo top-level
29628
+ * Container carries `{ system: 'dreo', brokerId: integrationId }` in its config
29629
+ * blob (the `brokerId` field name is unchanged; it now holds the integrationId).
29793
29630
  *
29794
29631
  * Churn-free: skips any device already in the target state. Returns the count of
29795
- * devices actually transitioned. Mirrors the Dreame offline helper.
29632
+ * devices actually transitioned.
29796
29633
  */
29797
- function setBrokerDevicesOnline(devices, brokerId, online) {
29634
+ function setIntegrationDevicesOnline(devices, integrationId, online) {
29798
29635
  let count = 0;
29799
29636
  for (const dev of devices) {
29800
29637
  if (dev.config.get("system") !== "dreo") continue;
29801
- if (dev.config.get("brokerId") !== brokerId) continue;
29638
+ if (dev.config.get("brokerId") !== integrationId) continue;
29802
29639
  if (dev.online === online) continue;
29803
29640
  dev.markOnline(online);
29804
29641
  count += 1;
@@ -30344,199 +30181,137 @@ var DreoContainerDevice = class extends BaseDevice$1 {
30344
30181
  };
30345
30182
  //#endregion
30346
30183
  //#region src/addon.ts
30347
- /** Default multi-broker config — a fresh install starts with no accounts. */
30348
- var DEFAULTS = { brokers: [] };
30349
30184
  /**
30350
- * Dreo device-provider addon (multi-account).
30185
+ * Dreo device-provider addon — `mode: account` (multi-account, broker-less).
30351
30186
  *
30352
- * Wraps the `@apocaliss92/nodedreo` Dreo cloud client (REST + WebSocket). One
30353
- * registered account = one "broker"; each adopted cloud device becomes a
30354
- * {@link DeviceType.Container} parent that fans out a single typed accessory
30355
- * child (fan / purifier / heater / humidifier). Modelled directly on the Dreame
30356
- * device-provider template: `broker` + `device-adoption` cap providers for
30357
- * connection + adoption, the `device-provider` cap from the base class, and an
30358
- * in-process connection resolver (`dreoConnections`) the device classes read.
30187
+ * Wraps the `@apocaliss92/nodedreo` Dreo cloud client (REST + WebSocket). Each
30188
+ * Dreo integration carries its own account credentials in its
30189
+ * `integration.settings`; the addon holds one {@link DreoIntegrationManager} per
30190
+ * `integrationId` in {@link DreoClientRegistry} (`Map<integrationId, manager>`).
30191
+ * There is NO shared broker. The live connection surface each manager owns
30192
+ * (discovery info + per-device handles) is published on the in-process
30193
+ * {@link dreoConnections} resolver KEYED BY `integrationId`.
30194
+ *
30195
+ * A `device-adoption` cap provider enumerates each account's cloud devices and
30196
+ * adopts them; each adopted cloud device becomes a {@link DeviceType.Container}
30197
+ * parent that fans out a single typed accessory child (fan / purifier / heater /
30198
+ * humidifier) and its entity children. The device classes resolve their live
30199
+ * handle by the `brokerId` config field — UNCHANGED device-side code; that field
30200
+ * now holds the integrationId (see the migration note in the addon docs).
30359
30201
  *
30360
30202
  * Placement: hub-only — the Dreo cloud is reached over outbound HTTPS + a
30361
30203
  * persistent WebSocket from a single account session; no LAN proximity matters,
30362
- * so (like Dreame) the broker lives on the hub.
30204
+ * so (like Dreame) the connection lives on the hub.
30363
30205
  */
30364
30206
  var DreoProviderAddon = class extends BaseDeviceProvider {
30365
30207
  addonId = "provider-dreo";
30366
30208
  providerName = "Dreo";
30367
30209
  deviceClasses = { [DeviceType.Container]: DreoContainerDevice };
30368
- registry = null;
30210
+ clients = null;
30369
30211
  constructor() {
30370
- super({ ...DEFAULTS });
30212
+ super({});
30371
30213
  }
30372
30214
  async onInitialize() {
30373
30215
  const regs = await super.onInitialize();
30374
- this.registry = new DreoBrokerRegistry(this.ctx.logger);
30375
- this.registry.setOnBrokerConnected((brokerId) => {
30376
- this.ctx.logger.info("Dreo: broker connected", { meta: { brokerId } });
30377
- this.setBrokerDevicesOnline(brokerId, true);
30216
+ this.clients = new DreoClientRegistry(this.ctx.logger);
30217
+ this.clients.setOnConnected((integrationId) => {
30218
+ this.ctx.logger.info("Dreo: integration connected", { meta: { integrationId } });
30219
+ this.setIntegrationDevicesOnline(integrationId, true);
30378
30220
  });
30379
- this.registry.setOnBrokerDisconnected((brokerId) => {
30380
- this.setBrokerDevicesOnline(brokerId, false);
30221
+ this.clients.setOnDisconnected((integrationId) => {
30222
+ this.setIntegrationDevicesOnline(integrationId, false);
30381
30223
  });
30382
- await this.registry.restore(this.config.brokers);
30383
- this.ctx.logger.info("Dreo: provider initialised", { meta: { brokerCount: this.config.brokers.length } });
30384
- await this.reconcileIntegrationsToBrokers();
30224
+ await this.reconcileIntegrations();
30385
30225
  this.subscribeIntegrationLifecycle();
30386
- return [
30387
- ...regs,
30388
- {
30389
- capability: brokerCapability,
30390
- provider: this.buildBrokerProvider()
30391
- },
30392
- {
30393
- capability: deviceAdoptionCapability,
30394
- provider: this.buildAdoptionProvider()
30395
- }
30396
- ];
30397
- }
30398
- /** Reconcile the live registry against the persisted `brokers` array after a
30399
- * settings write (UI save or `broker.*` cap). Mirrors the Dreame addon. */
30400
- async onConfigChanged() {
30401
- const reg = this.registry;
30402
- if (!reg) return;
30403
- const persisted = this.config.brokers;
30404
- const liveIds = new Set(reg.list().map((b) => b.id));
30405
- const persistedIds = new Set(persisted.map((e) => e.id));
30406
- for (const liveId of liveIds) if (!persistedIds.has(liveId)) try {
30407
- await reg.removeEntry(liveId);
30408
- } catch (err) {
30409
- this.ctx.logger.warn("Dreo onConfigChanged: removeEntry failed", { meta: {
30410
- brokerId: liveId,
30411
- error: errMsg(err)
30412
- } });
30413
- }
30414
- for (const entry of persisted) {
30415
- if (entry.id && liveIds.has(entry.id)) {
30416
- if (sameConnection(entry.connection, reg.getConnection(entry.id))) continue;
30417
- try {
30418
- await reg.updateEntry(entry.id, entry.connection);
30419
- } catch (err) {
30420
- this.ctx.logger.warn("Dreo onConfigChanged: updateEntry failed", { meta: {
30421
- brokerId: entry.id,
30422
- error: errMsg(err)
30423
- } });
30424
- }
30425
- continue;
30426
- }
30427
- try {
30428
- const created = await reg.createEntry(entry.name, entry.connection);
30429
- if (created.id !== entry.id) {
30430
- const next = persisted.map((b) => b === entry ? {
30431
- ...b,
30432
- id: created.id
30433
- } : b);
30434
- await this.updateGlobalSettings({ brokers: next });
30435
- }
30436
- } catch (err) {
30437
- this.ctx.logger.warn("Dreo onConfigChanged: failed to start new broker", { meta: {
30438
- brokerName: entry.name,
30439
- error: errMsg(err)
30440
- } });
30441
- }
30442
- }
30226
+ this.ctx.logger.info("Dreo: provider initialised", { meta: { integrationCount: this.requireClients().size() } });
30227
+ return [...regs, {
30228
+ capability: deviceAdoptionCapability,
30229
+ provider: this.buildAdoptionProvider()
30230
+ }];
30443
30231
  }
30444
30232
  async onShutdown() {
30445
30233
  try {
30446
- await this.registry?.shutdown();
30234
+ await this.clients?.shutdown();
30447
30235
  } catch (err) {
30448
30236
  this.ctx.logger.warn("Dreo: provider shutdown error", { meta: { error: errMsg(err) } });
30449
30237
  }
30450
- this.registry = null;
30238
+ this.clients = null;
30451
30239
  await super.onShutdown();
30452
30240
  }
30453
- /** Stable id, broker-scoped so two accounts exposing the same device id don't
30454
- * collide (mirrors the Dreame broker-scoping). */
30241
+ requireClients() {
30242
+ if (!this.clients) throw new Error("Dreo provider not initialised");
30243
+ return this.clients;
30244
+ }
30245
+ /**
30246
+ * Stable id, integration-scoped so two accounts exposing the same cloud device
30247
+ * id don't collide. `brokerId` in the config is the integrationId (unchanged
30248
+ * field name).
30249
+ */
30455
30250
  generateStableId(_type, config) {
30456
30251
  return `dreo:${String(config?.["brokerId"] ?? "unknown")}:${String(config?.["dreoDeviceId"] ?? Date.now())}`;
30457
30252
  }
30458
- buildBrokerProvider() {
30459
- return buildDreoBrokerProvider({
30460
- ownerAddonId: this.ctx.id,
30461
- registry: this.requireRegistry(),
30462
- getBrokers: () => this.config.brokers,
30463
- persistBrokers: (brokers) => this.updateGlobalSettings({ brokers: [...brokers] }),
30464
- cascadeRemoveDevices: (brokerId) => this.cascadeRemoveDevicesForBroker(brokerId),
30465
- logger: this.ctx.logger
30466
- });
30467
- }
30468
- async cascadeRemoveDevicesForBroker(brokerId) {
30469
- const reg = this.ctx.kernel.deviceRegistry;
30470
- const devices = this.ctx.kernel.devices;
30471
- if (!reg || !devices) return;
30472
- await cascadeRemoveDevicesForBroker({
30473
- reg,
30474
- devices,
30475
- addonId: this.addonId,
30476
- brokerId,
30477
- logger: this.ctx.logger
30478
- });
30479
- }
30480
30253
  /**
30481
- * Link each surviving integration (carrying `{ brokerId }` in its settings) to
30482
- * its broker so the generic `device-adoption` cap resolves the account, and
30483
- * cascade-clean brokers (+ their adopted devices) whose spawning integration
30484
- * was deleted. Idempotent; runs on boot + on every integration lifecycle event.
30485
- * Guarded so a failure never fails init.
30254
+ * Rebuild the `Map<integrationId, manager>` from the live integration list:
30255
+ * for each surviving Dreo integration read its settings and upsert a manager
30256
+ * (session-preserving if credentials are unchanged); drop managers whose
30257
+ * integration was deleted/disabled cascade-removing their adopted devices.
30258
+ * Idempotent; runs on boot + on every integration lifecycle event. Guarded so
30259
+ * a failure never fails init.
30486
30260
  */
30487
- async reconcileIntegrationsToBrokers() {
30261
+ async reconcileIntegrations() {
30262
+ const reg = this.requireClients();
30488
30263
  try {
30489
- const mine = (await this.ctx.api.integrations.list.query()).filter((i) => i.addonId === this.ctx.id);
30490
- const surviving = new Set(mine.map((i) => i.id));
30491
- for (const integration of mine) {
30492
- const settings = await this.ctx.api.integrations.getSettings.query({ id: integration.id });
30493
- const brokerId = typeof settings["brokerId"] === "string" ? settings["brokerId"] : void 0;
30494
- if (brokerId === void 0) continue;
30495
- if (!this.config.brokers.some((b) => b.id === brokerId)) {
30496
- this.ctx.logger.warn("Dreo integration→broker: linked broker not found", { meta: {
30497
- integrationId: integration.id,
30498
- brokerId
30499
- } });
30264
+ const mine = (await this.ctx.api.integrations.list.query()).filter((i) => i.addonId === this.ctx.id && i.enabled);
30265
+ const surviving = /* @__PURE__ */ new Set();
30266
+ for (const integration of mine) try {
30267
+ const connection = connectionFromSettings(await this.ctx.api.integrations.getSettings.query({ id: integration.id }));
30268
+ if (!connection) {
30269
+ this.ctx.logger.warn("Dreo integration has no complete credentials — skipping", { meta: { integrationId: integration.id } });
30500
30270
  continue;
30501
30271
  }
30502
- this.requireRegistry().linkIntegration(integration.id, brokerId);
30503
- }
30504
- const toRemove = this.config.brokers.filter((b) => b.integrationId !== void 0 && !surviving.has(b.integrationId)).map((b) => b.id);
30505
- if (toRemove.length === 0) return;
30506
- for (const id of toRemove) try {
30507
- await this.requireRegistry().removeEntry(id);
30508
- await this.cascadeRemoveDevicesForBroker(id);
30272
+ await reg.upsert(integration.id, integration.name, connection);
30273
+ surviving.add(integration.id);
30509
30274
  } catch (err) {
30510
- this.ctx.logger.warn("Dreo integration→broker: broker cleanup failed", { meta: {
30511
- brokerId: id,
30275
+ this.ctx.logger.warn("Dreo reconcile: failed to read integration settings", { meta: {
30276
+ integrationId: integration.id,
30512
30277
  error: errMsg(err)
30513
30278
  } });
30514
30279
  }
30515
- const nextBrokers = this.config.brokers.filter((b) => !toRemove.includes(b.id));
30516
- await this.updateGlobalSettings({ brokers: nextBrokers });
30280
+ const vanished = reg.list().filter((id) => !surviving.has(id));
30281
+ await reg.retain(surviving);
30282
+ for (const integrationId of vanished) await this.cascadeRemoveDevicesForIntegration(integrationId);
30517
30283
  } catch (err) {
30518
- this.ctx.logger.warn("Dreo integration→broker reconcile failed", { meta: { error: errMsg(err) } });
30284
+ this.ctx.logger.warn("Dreo integration reconcile failed", { meta: { error: errMsg(err) } });
30519
30285
  }
30520
30286
  }
30521
30287
  subscribeIntegrationLifecycle() {
30522
30288
  const handler = (event) => {
30523
30289
  const addonId = event.data["addonId"];
30524
30290
  if (typeof addonId === "string" && addonId !== this.ctx.id) return;
30525
- this.reconcileIntegrationsToBrokers();
30291
+ this.reconcileIntegrations();
30526
30292
  };
30527
30293
  this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationEnabled }, handler);
30528
30294
  this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationDisabled }, handler);
30529
30295
  this.ctx.eventBus.subscribe({ category: EventCategory.IntegrationDeleted }, handler);
30530
30296
  }
30297
+ async cascadeRemoveDevicesForIntegration(integrationId) {
30298
+ const reg = this.ctx.kernel.deviceRegistry;
30299
+ const devices = this.ctx.kernel.devices;
30300
+ if (!reg || !devices) return;
30301
+ await cascadeRemoveDevicesForIntegration({
30302
+ reg,
30303
+ devices,
30304
+ addonId: this.addonId,
30305
+ integrationId,
30306
+ logger: this.ctx.logger
30307
+ });
30308
+ }
30531
30309
  buildAdoptionProvider() {
30532
30310
  return buildDreoAdoptionProvider({
30533
30311
  registry: dreoConnections,
30534
30312
  logger: this.ctx.logger,
30535
- getBrokerIdForIntegration: async (id) => {
30536
- const brokerId = (await this.ctx.api.integrations.getSettings.query({ id }))["brokerId"];
30537
- if (typeof brokerId !== "string") throw new Error(`integration ${id} has no linked brokerId`);
30538
- return brokerId;
30539
- },
30313
+ hasIntegration: (integrationId) => this.requireClients().has(integrationId),
30314
+ listIntegrations: () => this.requireClients().list(),
30540
30315
  listAdoptedDreo: async () => {
30541
30316
  const reg = this.ctx.kernel.deviceRegistry;
30542
30317
  const devices = this.ctx.kernel.devices;
@@ -30552,12 +30327,12 @@ var DreoProviderAddon = class extends BaseDeviceProvider {
30552
30327
  }
30553
30328
  return out;
30554
30329
  },
30555
- adoptDevice: async ({ dreoDeviceId, brokerId, integrationId, name, model }) => {
30330
+ adoptDevice: async ({ dreoDeviceId, integrationId, name, model }) => {
30556
30331
  const devices = this.ctx.kernel.devices;
30557
30332
  if (!devices) throw new Error("dreo adopt: kernel.devices unavailable");
30558
30333
  const config = {
30559
30334
  dreoDeviceId,
30560
- brokerId,
30335
+ brokerId: integrationId,
30561
30336
  model,
30562
30337
  system: "dreo",
30563
30338
  integrationId,
@@ -30586,18 +30361,7 @@ var DreoProviderAddon = class extends BaseDeviceProvider {
30586
30361
  });
30587
30362
  }
30588
30363
  globalSettingsSchema() {
30589
- return this.schema({ sections: [{
30590
- id: "dreo-broker",
30591
- title: "Dreo account",
30592
- description: "Dreo accounts are managed in the External systems → Brokers tab.",
30593
- columns: 1,
30594
- fields: [{
30595
- type: "info",
30596
- key: "brokerHelp",
30597
- label: "Accounts are managed separately",
30598
- content: "This integration links to a Dreo account broker. Add, edit, or remove accounts from External systems → Brokers. The integration only stores a reference to its broker — credentials live on the broker."
30599
- }]
30600
- }] });
30364
+ return buildConnectionFormSchema();
30601
30365
  }
30602
30366
  async supportsManualCreation() {
30603
30367
  return false;
@@ -30608,19 +30372,15 @@ var DreoProviderAddon = class extends BaseDeviceProvider {
30608
30372
  async onCreateDevice(_type, _config) {
30609
30373
  throw new Error("Dreo devices are adopted from the cloud, not created manually");
30610
30374
  }
30611
- setBrokerDevicesOnline(brokerId, online) {
30375
+ setIntegrationDevicesOnline(integrationId, online) {
30612
30376
  const reg = this.ctx.kernel.deviceRegistry;
30613
30377
  if (!reg) return;
30614
- const n = setBrokerDevicesOnline(reg.getAllForAddon(this.addonId), brokerId, online);
30615
- if (n > 0) this.ctx.logger.info("Dreo: broker devices " + (online ? "online" : "offline"), { meta: {
30616
- brokerId,
30378
+ const n = setIntegrationDevicesOnline(reg.getAllForAddon(this.addonId), integrationId, online);
30379
+ if (n > 0) this.ctx.logger.info("Dreo: integration devices " + (online ? "online" : "offline"), { meta: {
30380
+ integrationId,
30617
30381
  count: n
30618
30382
  } });
30619
30383
  }
30620
- requireRegistry() {
30621
- if (!this.registry) throw new Error("Dreo provider not initialised");
30622
- return this.registry;
30623
- }
30624
30384
  };
30625
30385
  //#endregion
30626
- export { DreoProviderAddon, classifyDreoModel as a, percentageStep as c, dreoAddonConfigSchema as d, dreoConfigSchema as f, clampPercent as i, percentageToLevel as l, DREO_MAX_FAN_LEVEL as n, deviceTypeForKind as o, toDreoConstructorArgs as p, capsForKind as r, levelToPercentage as s, buildDreoCandidates as t, buildConnectionFormSchema as u };
30386
+ export { DreoProviderAddon, classifyDreoModel as a, percentageStep as c, connectionFromSettings as d, dreoConfigSchema as f, clampPercent as i, percentageToLevel as l, DREO_MAX_FAN_LEVEL as n, deviceTypeForKind as o, toDreoConstructorArgs as p, capsForKind as r, levelToPercentage as s, buildDreoCandidates as t, buildConnectionFormSchema as u };