@camstack/addon-google-services 0.2.38 → 0.2.39

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.
@@ -5981,7 +5981,7 @@ var ZodIssueCode = {
5981
5981
  var ZodFirstPartyTypeKind;
5982
5982
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5983
5983
  //#endregion
5984
- //#region ../types/dist/sleep-BaWhXZFm.mjs
5984
+ //#region ../types/dist/sleep-BX_MqzUe.mjs
5985
5985
  /**
5986
5986
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5987
5987
  * window to float samples (D455).
@@ -6581,7 +6581,7 @@ var NOT_RUN = {
6581
6581
  * throws: an unreachable or refusing engine is logged and reported `declared: false`,
6582
6582
  * because the hub (and this addon's boot) must not hang on a migration.
6583
6583
  */
6584
- async function runAddonMigrations(host, migrations, logger) {
6584
+ async function runAddonMigrations(host, migrations, logger, options = {}) {
6585
6585
  const first = migrations[0];
6586
6586
  if (first === void 0) return NOT_RUN;
6587
6587
  const owner = first.meta.owner;
@@ -6610,7 +6610,9 @@ async function runAddonMigrations(host, migrations, logger) {
6610
6610
  else if (status === "blocked") blocked.push(id);
6611
6611
  else skipped.push(id);
6612
6612
  };
6613
+ const selected = options.only === void 0 ? null : new Set(options.only);
6613
6614
  for (const step of declaration.steps) {
6615
+ if (selected !== null && !selected.has(step.id)) continue;
6614
6616
  const bound = byId.get(step.id);
6615
6617
  if (bound === void 0 || step.action === "skip") {
6616
6618
  skipped.push(step.id);
@@ -6788,6 +6790,12 @@ function projectStore(store, perNodeKeys, nodeId) {
6788
6790
  }
6789
6791
  return out;
6790
6792
  }
6793
+ /** Every scope, in the order the guard and the docs list them. */
6794
+ var SCOPED_SETTINGS_SCOPES = [
6795
+ "cluster",
6796
+ "device-defaults",
6797
+ "node"
6798
+ ];
6791
6799
  /**
6792
6800
  * The address of one keychain value: `secret://<owner>/<scope>/<fieldPath>`.
6793
6801
  *
@@ -7602,6 +7610,28 @@ var SECRET_RETRY_MAX_MS = 5 * 6e4;
7602
7610
  /** Coalesces a burst of `keychain.changed` events into one re-resolve. */
7603
7611
  var SECRET_CHANGE_DEBOUNCE_MS = 250;
7604
7612
  /**
7613
+ * Pair a catalogue with the function that builds its ports FROM THE MIGRATION API. The one
7614
+ * place a catalogue is bound: a migration reaches nothing a ports binder cannot reach
7615
+ * through `api` (guard `check-migration-ports-surface`).
7616
+ */
7617
+ function migrationSet(catalogue, bindPorts) {
7618
+ return { bind: (api) => defineAddonMigrations(catalogue, bindPorts(api)) };
7619
+ }
7620
+ /** A mixed array is a mistake: the other kind would be dropped without a word. */
7621
+ function refuseMixed(form, kept, dropped) {
7622
+ if (dropped > 0) throw new Error(`runMigrations(${form}): ${dropped} of ${kept + dropped} entries are of the other kind and would be dropped; pass one kind per call`);
7623
+ }
7624
+ function catalogueOf(list) {
7625
+ const kept = list.filter((entry) => !("execute" in entry));
7626
+ refuseMixed("catalogue, (api) => ports", kept.length, list.length - kept.length);
7627
+ return kept;
7628
+ }
7629
+ function boundOf(list) {
7630
+ const kept = list.filter((entry) => "execute" in entry);
7631
+ refuseMixed("bound migrations", kept.length, list.length - kept.length);
7632
+ return kept;
7633
+ }
7634
+ /**
7605
7635
  * Base class for CamStack addons. Eliminates settings boilerplate:
7606
7636
  *
7607
7637
  * - Typed `config` property with automatic resolution from store + defaults
@@ -7679,6 +7709,13 @@ var BaseAddon = class {
7679
7709
  */
7680
7710
  secretStatePaths = [];
7681
7711
  _addonSecretTree = null;
7712
+ /**
7713
+ * D986 M4: the scoped schemas this addon declared, resolved once per capability
7714
+ * (`loadScopedSchemas`) so the sync readers (`perNodeKeys`, the secret tree, the restart check)
7715
+ * see them. Empty until loaded: the readers then fall back to {@link globalSettingsSchema}.
7716
+ */
7717
+ _scopedByCap = /* @__PURE__ */ new Map();
7718
+ _nodeKeysByCap = /* @__PURE__ */ new Map();
7682
7719
  _deviceSecretTree = null;
7683
7720
  /** Refs the last resolved config pointed at — a change to one re-resolves. */
7684
7721
  _configSecretRefs = /* @__PURE__ */ new Set();
@@ -7748,6 +7785,7 @@ var BaseAddon = class {
7748
7785
  this._ctx = context;
7749
7786
  this._secretSettings = null;
7750
7787
  }
7788
+ await this.loadScopedSchemas();
7751
7789
  await this.resolveConfig();
7752
7790
  if (secrets !== void 0) this._secretChangeUnsub = secrets.onChange((ref) => {
7753
7791
  if (this._configSecretRefs.has(ref)) this.scheduleSecretReresolve(SECRET_CHANGE_DEBOUNCE_MS);
@@ -7757,27 +7795,30 @@ var BaseAddon = class {
7757
7795
  const normalized = normalizeAddonInitResult(result);
7758
7796
  const providers = normalized && "providers" in normalized && normalized.providers ? normalized.providers : [];
7759
7797
  this._registeredCapNames = providers.map((p) => p.capability.name);
7798
+ await this.loadScopedSchemas();
7760
7799
  return normalized;
7761
7800
  }
7801
+ async runMigrations(first, second, third) {
7802
+ if (typeof second === "function") return this.runMigrationSets([migrationSet(catalogueOf(first), second)], third);
7803
+ return this.runBound(boundOf(first), second);
7804
+ }
7762
7805
  /**
7763
- * Run this addon's migration catalogue (D987 M3) through the hub's `migrations`
7764
- * engine. Call it at the point of the boot where the data must already have the new
7765
- * shape — `onInitialize`, or `onRestoreDevices` for a migration that needs the
7766
- * restored devices — with the catalogue bound to the addon's ports
7767
- * (`defineAddonMigrations(ADDON_MIGRATIONS, ports)`).
7768
- *
7769
- * An engine that cannot be reached or refuses the catalogue is logged and runs
7770
- * nothing; the boot continues. A migration that FAILED (or was blocked by one)
7771
- * and declares `onFailure: 'block-owner'` makes this throw, so the addon does not
7772
- * serve data whose shape it cannot trust; `tolerate` migrations never do.
7806
+ * Several catalogues of ONE owner in one declaration (the engine replaces an owner's
7807
+ * catalogue on every declare, so two calls would each judge the other's ids "newer").
7808
+ * Build each entry with `migrationSet(catalogue, (api) => ports)`.
7773
7809
  */
7774
- async runMigrations(migrations) {
7810
+ async runMigrationSets(sets, options) {
7811
+ const api = this.ctx.migrationApi;
7812
+ if (api === void 0) throw new Error(`${this.ctx.id}: the migration API is not available on this context`);
7813
+ return this.runBound(sets.flatMap((set) => set.bind(api)), options);
7814
+ }
7815
+ async runBound(migrations, options) {
7775
7816
  const api = this.ctx.api.migrations;
7776
7817
  const report = await runAddonMigrations({
7777
7818
  declareOwner: (input) => api.declareOwner.mutate(input),
7778
7819
  startMigration: (input) => api.startMigration.mutate(input),
7779
7820
  finishMigration: (input) => api.finishMigration.mutate(input)
7780
- }, migrations, this.ctx.logger);
7821
+ }, migrations, this.ctx.logger, options);
7781
7822
  if (report.blockOwner.length > 0) throw new AddonMigrationsBlockedError(report.blockOwner);
7782
7823
  return report;
7783
7824
  }
@@ -7841,6 +7882,16 @@ var BaseAddon = class {
7841
7882
  schema(schema) {
7842
7883
  return schema;
7843
7884
  }
7885
+ /**
7886
+ * The capability names whose scoped settings schemas ({@link clusterSettingsSchema},
7887
+ * {@link nodeSettingsSchema}, {@link deviceDefaultsSchema}) this addon declares. Read BEFORE
7888
+ * `onInitialize`, when the providers it registers are not known yet: the first config resolve
7889
+ * must already know which keys are per node. Names the providers register at init are added
7890
+ * once known.
7891
+ */
7892
+ scopedSettingsCapabilities() {
7893
+ return [];
7894
+ }
7844
7895
  /** Override to provide global-level settings UI schema. */
7845
7896
  globalSettingsSchema(_cap) {
7846
7897
  return null;
@@ -7884,7 +7935,8 @@ var BaseAddon = class {
7884
7935
  return [];
7885
7936
  }
7886
7937
  async getGlobalSettings(overlay, cap, nodeId) {
7887
- const schema = this.globalSettingsSchema(cap);
7938
+ await this.loadScopedSchemas(cap);
7939
+ const schema = this.globalSettingsSchema(cap) ?? this.scopedFormSchema(cap);
7888
7940
  if (!schema) return { sections: [] };
7889
7941
  const projected = await this.readRawProjectedStore(nodeId, cap);
7890
7942
  return hydrateSchema(schema, overlay ? await this.overlayKeepingMarkers(projected, overlay) : projected, { inlineSecretsAsViews: true });
@@ -7919,10 +7971,9 @@ var BaseAddon = class {
7919
7971
  *
7920
7972
  * Override it only when an `instanceMode: multiple` addon's instances differ: an NVR integration
7921
7973
  * needs its connection fields, the default integration the addon's own sections. It is the
7922
- * SHAPE of the form only — the values live in `integrations.getSettings`, and the write path is
7923
- * unchanged (`integrations.setSettings` for an account integration).
7974
+ * SHAPE of the form only — the values live on the instance record.
7924
7975
  */
7925
- async integrationSettingsSchema(_instance) {
7976
+ async integrationFormSchema(_instance) {
7926
7977
  return null;
7927
7978
  }
7928
7979
  /**
@@ -7968,7 +8019,7 @@ var BaseAddon = class {
7968
8019
  * per-instance schema when it declares one, else its global schema (what they always showed).
7969
8020
  */
7970
8021
  async getIntegrationFormSchema(instance, nodeId) {
7971
- const scoped = await this.integrationSettingsSchema(instance);
8022
+ const scoped = await this.integrationFormSchema(instance);
7972
8023
  if (scoped === null) return this.getGlobalSettings(void 0, void 0, nodeId);
7973
8024
  return hydrateSchema(scoped, {}, { inlineSecretsAsViews: true });
7974
8025
  }
@@ -8016,6 +8067,7 @@ var BaseAddon = class {
8016
8067
  * resolved blob back is a no-op for every unchanged secret.
8017
8068
  */
8018
8069
  async resolveGlobalStore(nodeId, cap) {
8070
+ await this.loadScopedSchemas(cap);
8019
8071
  const raw = await this._ctx?.settings?.readAddonStore() ?? {};
8020
8072
  return this.projectForNode(raw, nodeId, cap);
8021
8073
  }
@@ -8026,6 +8078,7 @@ var BaseAddon = class {
8026
8078
  }
8027
8079
  /** The PROJECTED store with its markers — the form hydrate only (D798). */
8028
8080
  async readRawProjectedStore(nodeId, cap) {
8081
+ await this.loadScopedSchemas(cap);
8029
8082
  const raw = await this.rawSettings()?.readAddonStore() ?? {};
8030
8083
  return this.projectForNode(raw, nodeId, cap);
8031
8084
  }
@@ -8128,6 +8181,7 @@ var BaseAddon = class {
8128
8181
  await this.applyGlobalPatch(patch, nodeId);
8129
8182
  }
8130
8183
  async applyGlobalPatch(barePatch, nodeId) {
8184
+ await this.loadScopedSchemas();
8131
8185
  const keys = this.perNodeKeys();
8132
8186
  const localNode = normalizeNodeId(this._ctx?.kernel?.localNodeId);
8133
8187
  const target = normalizeNodeId(nodeId ?? this._ctx?.kernel?.localNodeId);
@@ -8141,7 +8195,8 @@ var BaseAddon = class {
8141
8195
  await this.resolveConfig();
8142
8196
  await this.onConfigChanged();
8143
8197
  this.emitLifecycle(EventCategory.AddonUpdated, { level: "global" });
8144
- this.maybeAutoRestart(Object.keys(barePatch), this.globalSettingsSchema());
8198
+ const legacy = this.globalSettingsSchema();
8199
+ this.maybeAutoRestart(Object.keys(barePatch), [...legacy === null ? [] : [legacy], ...this.loadedScopedSchemas().map((entry) => entry.schema)]);
8145
8200
  }
8146
8201
  /**
8147
8202
  * The set of field keys the global settings schema declares `perNode: true`
@@ -8149,14 +8204,67 @@ var BaseAddon = class {
8149
8204
  * declarations). Empty set ⇒ every per-node code path is bypassed and the
8150
8205
  * settings API behaves exactly like the legacy node-agnostic one.
8151
8206
  */
8152
- _perNodeKeysCache = /* @__PURE__ */ new Map();
8207
+ /**
8208
+ * Load the scoped schemas of every capability this addon declares (the override and the
8209
+ * providers registered at init, plus `extraCap`) that is not loaded yet, then drop what was
8210
+ * derived from the previous set. Idempotent.
8211
+ */
8212
+ async loadScopedSchemas(extraCap) {
8213
+ const caps = new Set([
8214
+ ...this.scopedSettingsCapabilities(),
8215
+ ...this._registeredCapNames,
8216
+ ...extraCap === void 0 ? [] : [extraCap]
8217
+ ]);
8218
+ let added = false;
8219
+ for (const cap of caps) {
8220
+ if (this._scopedByCap.has(cap)) continue;
8221
+ const loaded = [];
8222
+ for (const scope of SCOPED_SETTINGS_SCOPES) {
8223
+ const schema = await this.getScopedSettingsSchema(scope, cap);
8224
+ if (schema !== null) loaded.push({
8225
+ scope,
8226
+ schema
8227
+ });
8228
+ }
8229
+ this._scopedByCap.set(cap, loaded);
8230
+ added = true;
8231
+ }
8232
+ if (!added) return;
8233
+ this._nodeKeysByCap = /* @__PURE__ */ new Map();
8234
+ this._addonSecretTree = null;
8235
+ }
8236
+ /**
8237
+ * The form the settings API serves while an addon declares no {@link globalSettingsSchema}: the
8238
+ * sections of its scoped schemas, so dropping the old hook does not blank the form.
8239
+ */
8240
+ scopedFormSchema(cap) {
8241
+ const byId = /* @__PURE__ */ new Map();
8242
+ for (const entry of this.loadedScopedSchemas(cap)) for (const section of entry.schema.sections) if (!byId.has(section.id)) byId.set(section.id, section);
8243
+ return byId.size === 0 ? null : { sections: [...byId.values()] };
8244
+ }
8245
+ /** Every loaded scoped schema of `cap`, or of every loaded capability. */
8246
+ loadedScopedSchemas(cap) {
8247
+ if (cap !== void 0) return this._scopedByCap.get(cap) ?? [];
8248
+ return [...this._scopedByCap.values()].flat();
8249
+ }
8250
+ /**
8251
+ * The field keys that are stored per node: every field of a {@link nodeSettingsSchema}, plus
8252
+ * the fields the legacy {@link globalSettingsSchema} still marks `perNode: true`. Derived once
8253
+ * per `cap` argument and memoized (schemas are static declarations). Empty set ⇒ every
8254
+ * per-node code path is bypassed and the settings API behaves like the node-agnostic one.
8255
+ * Call {@link loadScopedSchemas} first (the async seams do).
8256
+ */
8153
8257
  perNodeKeys(cap) {
8154
8258
  const cacheKey = cap ?? "";
8155
- const cached = this._perNodeKeysCache.get(cacheKey);
8259
+ const cached = this._nodeKeysByCap.get(cacheKey);
8156
8260
  if (cached) return cached;
8157
- const schema = this.globalSettingsSchema(cap);
8158
- const keys = new Set(schema ? schema.sections.flatMap((section) => collectPerNodeFieldKeys(section.fields)) : []);
8159
- this._perNodeKeysCache.set(cacheKey, keys);
8261
+ const legacy = this.globalSettingsSchema(cap);
8262
+ const keys = new Set(legacy ? legacy.sections.flatMap((section) => collectPerNodeFieldKeys(section.fields)) : []);
8263
+ for (const { scope, schema } of this.loadedScopedSchemas(cap)) {
8264
+ if (scope !== "node") continue;
8265
+ for (const section of schema.sections) for (const key of collectValueFieldKeys(section.fields)) keys.add(key);
8266
+ }
8267
+ this._nodeKeysByCap.set(cacheKey, keys);
8160
8268
  return keys;
8161
8269
  }
8162
8270
  /**
@@ -8166,10 +8274,9 @@ var BaseAddon = class {
8166
8274
  * time to return its response before the addon is torn down and
8167
8275
  * re-initialised by `AddonRegistryService.restartAddon`.
8168
8276
  */
8169
- maybeAutoRestart(patchKeys, schema) {
8170
- if (!schema) return;
8277
+ maybeAutoRestart(patchKeys, schemas) {
8171
8278
  const restartKeys = /* @__PURE__ */ new Set();
8172
- for (const section of schema.sections) for (const field of section.fields) {
8279
+ for (const schema of schemas) for (const section of schema.sections) for (const field of section.fields) {
8173
8280
  if (field.type === "separator" || field.type === "info") continue;
8174
8281
  if (field.requiresRestart) restartKeys.add(field.key);
8175
8282
  }
@@ -8365,12 +8472,14 @@ var BaseAddon = class {
8365
8472
  * here, in the addon's own process, so the hub keeps no copy of it.
8366
8473
  */
8367
8474
  async getDeclaredSettingsKeys() {
8475
+ await this.loadScopedSchemas();
8368
8476
  return { keys: [...this.declaredKeySet()].toSorted() };
8369
8477
  }
8370
8478
  declaredKeySet() {
8371
8479
  const keys = new Set(Object.keys(this.defaults));
8372
8480
  const schema = this.globalSettingsSchema();
8373
8481
  if (schema) for (const section of schema.sections) for (const key of collectFieldKeys(section.fields)) keys.add(key);
8482
+ for (const { schema: scoped } of this.loadedScopedSchemas()) for (const section of scoped.sections) for (const key of collectFieldKeys(section.fields)) keys.add(key);
8374
8483
  for (const key of this._declaredStateKeys) keys.add(key);
8375
8484
  for (const path of this.secretStatePaths) {
8376
8485
  const root = path.split(/[.[]/, 1)[0];
@@ -8466,7 +8575,11 @@ var BaseAddon = class {
8466
8575
  }
8467
8576
  /** The addon store's secret tree: schema fields by TYPE, plus `secretStatePaths`. */
8468
8577
  addonSecretTree() {
8469
- this._addonSecretTree ??= mergeSecretStatePaths(secretTreeFromSchema(this.globalSettingsSchema()), this.secretStatePaths);
8578
+ if (this._addonSecretTree === null) {
8579
+ const tree = new Map(secretTreeFromSchema(this.globalSettingsSchema()));
8580
+ for (const { schema } of this.loadedScopedSchemas()) for (const [key, node] of secretTreeFromSchema(schema)) tree.set(key, node);
8581
+ this._addonSecretTree = mergeSecretStatePaths(tree, this.secretStatePaths);
8582
+ }
8470
8583
  return this._addonSecretTree;
8471
8584
  }
8472
8585
  deviceSecretTree() {
@@ -8716,6 +8829,23 @@ function dropPerNodeFields(fields) {
8716
8829
  }
8717
8830
  return kept;
8718
8831
  }
8832
+ /** The keys of the value-holding fields, recursing into layout containers. */
8833
+ function collectValueFieldKeys(fields) {
8834
+ const collected = [];
8835
+ for (const field of fields) {
8836
+ if (field.type === "group") {
8837
+ collected.push(...collectValueFieldKeys(field.fields));
8838
+ continue;
8839
+ }
8840
+ if (field.type === "sub-tabs") {
8841
+ for (const tab of field.tabs) collected.push(...collectValueFieldKeys(tab.fields));
8842
+ continue;
8843
+ }
8844
+ if (field.type === "separator" || field.type === "info") continue;
8845
+ if ("key" in field && typeof field.key === "string") collected.push(field.key);
8846
+ }
8847
+ return collected;
8848
+ }
8719
8849
  function collectFieldKeys(fields) {
8720
8850
  const collected = [];
8721
8851
  for (const field of fields) {
@@ -9242,6 +9372,7 @@ function defineEntryKind(name, spec) {
9242
9372
  class: "config",
9243
9373
  writeTrigger: spec.writeTrigger ?? "an operator adds or edits an entry in the entries UI",
9244
9374
  retention: { none: "an entry goes only when the operator deletes it" },
9375
+ ...spec.maxDataBytes === void 0 ? {} : { maxDataBytes: spec.maxDataBytes },
9245
9376
  ...spec.database === void 0 ? {} : { database: spec.database },
9246
9377
  ...spec.indexes === void 0 ? {} : { indexes: spec.indexes },
9247
9378
  ...spec.secretArrayKeys === void 0 ? {} : { secretArrayKeys: spec.secretArrayKeys },
@@ -11921,7 +12052,7 @@ function userError(code, params, englishFallback) {
11921
12052
  return new CamstackError(code, params, englishFallback);
11922
12053
  }
11923
12054
  //#endregion
11924
- //#region ../types/dist/composition-CRNwcFYY.mjs
12055
+ //#region ../types/dist/composition-pOHbTzRB.mjs
11925
12056
  /**
11926
12057
  * The ffmpeg build every CamStack node downloads, per platform and arch.
11927
12058
  *
@@ -13519,7 +13650,7 @@ var RecordIntegrationInstances = class {
13519
13650
  return record === null ? null : this.viewOf(record);
13520
13651
  };
13521
13652
  /** Insert ONE row (`ifRev: 0`: an existing id is refused, never overwritten). */
13522
- createInstance = async ({ id, name, kind }) => {
13653
+ createInstance = async ({ id, name, kind, values }) => {
13523
13654
  const minted = id ?? this.hooks.mintId?.({
13524
13655
  name,
13525
13656
  ...kind !== void 0 ? { kind } : {}
@@ -13529,10 +13660,20 @@ var RecordIntegrationInstances = class {
13529
13660
  id: minted,
13530
13661
  data: this.hooks.initialBody(name, kind)
13531
13662
  }, { ifRev: 0 });
13663
+ const patch = this.patchOf(values ?? {});
13664
+ if (Object.keys(patch).length > 0) await this.handle.patch(minted, patch);
13532
13665
  await this.hooks.onChanged?.(minted, "created");
13533
13666
  return { id: minted };
13534
13667
  };
13535
13668
  updateInstance = async ({ id, name, values }) => {
13669
+ const patch = this.patchOf(values);
13670
+ if (name !== void 0) patch[this.nameField] = name;
13671
+ await this.handle.patch(id, patch);
13672
+ await this.hooks.onChanged?.(id, "updated");
13673
+ return { ok: true };
13674
+ };
13675
+ /** The record patch a form `values` object means: secrets kept, cleared or replaced. */
13676
+ patchOf(values) {
13536
13677
  const patch = {};
13537
13678
  for (const [key, value] of Object.entries(values)) {
13538
13679
  if (value === void 0) continue;
@@ -13543,11 +13684,8 @@ var RecordIntegrationInstances = class {
13543
13684
  else if (isSecretClear(value)) patch[key] = null;
13544
13685
  else if (typeof value === "string" && value !== "" && value !== "__camstack_redacted__" && !isSecretFieldView(value)) patch[key] = value;
13545
13686
  }
13546
- if (name !== void 0) patch[this.nameField] = name;
13547
- await this.handle.patch(id, patch);
13548
- await this.hooks.onChanged?.(id, "updated");
13549
- return { ok: true };
13550
- };
13687
+ return patch;
13688
+ }
13551
13689
  /** The switch lives in the record body; the addon is told so it applies it (D996). */
13552
13690
  setInstanceEnabled = async ({ id, enabled }) => {
13553
13691
  if (this.registryOwnsEnabled) throw new Error(`instance "${id}": the integrations registry owns the on/off switch of this addon; set it with integrations.update`);
@@ -14629,7 +14767,13 @@ var MigrationLedgerEntrySchema = object({
14629
14767
  * joined by the engine from the catalogues it knows this boot. Absent when no
14630
14768
  * catalogue lists the id (a newer database).
14631
14769
  */
14632
- meta: MigrationMetaSchema.optional()
14770
+ meta: MigrationMetaSchema.optional(),
14771
+ /**
14772
+ * Set when this is an applied row of an addon owner whose catalogue the answering
14773
+ * process has not loaded (the owner has not declared yet): the row is applied, the
14774
+ * process just cannot judge it. Never `skipped-newer` — that needs the owner loaded.
14775
+ */
14776
+ ownerNotLoaded: boolean().optional()
14633
14777
  });
14634
14778
  /** A catalogued migration that is not applied, with where it stands. */
14635
14779
  var MigrationPendingEntrySchema = object({
@@ -15750,6 +15894,39 @@ var UnstampedEventMediaCountSchema = object({
15750
15894
  /** Sum across both, or `null` when either lane could not be counted. */
15751
15895
  total: number().int().nonnegative().nullable()
15752
15896
  }).nullable();
15897
+ /**
15898
+ * Where the stored event media sits, per storage location: how many media rows
15899
+ * and how many bytes carry each location id, how many carry none (legacy,
15900
+ * resolved to the default `eventMedia` location), and how many name a location
15901
+ * that was not asked about (a deleted or never-listed one).
15902
+ *
15903
+ * One covering-index aggregate per asked location plus the NULL one, and one
15904
+ * unfiltered total that scans the covering index: O(rows), not a walk of the
15905
+ * rows themselves. `unlisted` is total minus the ASKED locations minus NULL, so
15906
+ * it is a deleted location only when every location id was asked.
15907
+ * `null` is "could not be measured", never zero.
15908
+ */
15909
+ var MediaLocationCensusInputSchema = object({ locationIds: array(string().min(1)).max(50).readonly() });
15910
+ var MediaLocationCensusSchema = object({
15911
+ locations: array(object({
15912
+ locationId: string(),
15913
+ rows: number().int().nonnegative(),
15914
+ bytes: number().nonnegative()
15915
+ })).readonly(),
15916
+ unstamped: object({
15917
+ rows: number().int().nonnegative(),
15918
+ bytes: number().nonnegative()
15919
+ }),
15920
+ /** Rows stamped with a location id that was not in the asked list. */
15921
+ unlisted: object({
15922
+ rows: number().int().nonnegative(),
15923
+ bytes: number().nonnegative()
15924
+ }),
15925
+ total: object({
15926
+ rows: number().int().nonnegative(),
15927
+ bytes: number().nonnegative()
15928
+ })
15929
+ });
15753
15930
  var StorageMigrationMediaMoveInputSchema = RelocateMediaInputSchema.extend({ leaseId: string().min(1) });
15754
15931
  /** The independently selectable logical storage classes — every class
15755
15932
  * `storage.listLocationDeclarations` reports, so an operator never meets a
@@ -46289,52 +46466,7 @@ DeviceType.Light, method(object({
46289
46466
  level: number().min(0).max(100),
46290
46467
  lastChangedAt: number()
46291
46468
  });
46292
- /**
46293
- * `broker` — unified pub/sub broker registry, system-scoped collection.
46294
- *
46295
- * The cap models any kind-tagged message broker the user wants to
46296
- * register and that other addons might consume. The first two kinds
46297
- * are MQTT (mosquitto / aedes embedded / cloud bridge) and
46298
- * Home Assistant (HA WebSocket — subscribe_entities + call_service).
46299
- * Future kinds (Zigbee2MQTT bridge, ZHA, KNX, Telegram, …) plug in
46300
- * the same surface.
46301
- *
46302
- * Why one cap, not one cap per kind:
46303
- * - The integrations page wants a single table of "every broker"
46304
- * across kinds; a unified cap drives it without join logic.
46305
- * - Generic admin operations (add / remove / test / status) are
46306
- * identical across kinds — duplicating them per cap was busywork.
46307
- * - The `network-access` cap precedent: same interface, many
46308
- * `providerKind: 'ingress'` implementations (Tailscale, ngrok, …).
46309
- *
46310
- * What stays kind-specific:
46311
- * - `getBrokerConfig` payload (kind decides whether it returns
46312
- * mqtt URL+creds, HA baseUrl+token, …) — typed as
46313
- * `Record<string, unknown>` at the wire; consumers narrow.
46314
- * - `publish` / `subscribe` / `getState` arguments (target / filter /
46315
- * key) — also typed as `Record<string, unknown>` so each kind can
46316
- * evolve its surface (MQTT topic+qos vs HA entity_id+domain)
46317
- * without rebreaking the cap signature.
46318
- * - `add` `settings` payload (different fields per kind, validated by
46319
- * the kind-specific provider).
46320
- *
46321
- * Bidirectionality:
46322
- * - `publish` is RPC — synchronous result (provider-defined).
46323
- * - `subscribe` returns a subscription handle; the actual message
46324
- * stream flows over the typed event-bus as `broker.message` events
46325
- * keyed by `(brokerId, subscriptionId)`. Consumers filter in their
46326
- * event handler. Subscriptions persist across reconnects — the
46327
- * provider re-subscribes upstream after a transport drop.
46328
- *
46329
- * Why event-bus push (not a subscription RPC stream):
46330
- * - Matches the rest of CamStack's D8 contract — events for telemetry,
46331
- * RPC for loss-is-a-bug. Broker messages are telemetry (a single
46332
- * drop is recoverable via `getState({key})`).
46333
- * - Frees `broker.subscribe` from holding a long-lived RPC channel.
46334
- * - Cross-process: events already route through `$event-bus`; no
46335
- * per-broker wire-shaping needed.
46336
- */
46337
- var BrokerStatusEnum = _enum([
46469
+ _enum([
46338
46470
  "connected",
46339
46471
  "disconnected",
46340
46472
  "connecting",
@@ -46342,141 +46474,12 @@ var BrokerStatusEnum = _enum([
46342
46474
  "unreachable",
46343
46475
  "error"
46344
46476
  ]);
46345
- var BrokerInfoSchema = object({
46346
- /** Stable broker id. Persisted; survives addon restarts. */
46347
- id: string(),
46348
- /** Addon id of the provider that OWNS this broker.
46349
- *
46350
- * The `broker` cap is a system-scoped collection: several addons
46351
- * register a `broker` provider, each owning a DISJOINT set of
46352
- * brokers (mqtt-broker owns `mqtt_*`, provider-homeassistant owns
46353
- * `ha_*`). A broker therefore belongs to exactly one addon — like a
46354
- * device belongs to one integration. The admin UI threads this id
46355
- * back as the `{ addonId }` system-collection selector on every
46356
- * id-keyed call (`get` / `getSettings` / `setSettings` / `remove` /
46357
- * `testConnection`), so the call routes to the OWNING provider
46358
- * instead of defaulting to the first-registered one. */
46359
- addonId: string(),
46360
- /** Human-readable name (operator-chosen at add-time). */
46361
- name: string(),
46362
- /** Provider-defined kind tag — `mqtt` / `home-assistant` / future. */
46363
- kind: string(),
46364
- status: BrokerStatusEnum,
46365
- /** Free-form provider-specific info (HA version, MQTT broker
46366
- * flavour, latency, mTLS active, …). */
46367
- info: record(string(), unknown()),
46368
- /** Ms epoch of the last connection probe / status update. */
46369
- lastCheckedAt: number().nullable(),
46370
- /** Last error message, when `status` indicates failure. */
46371
- error: string().nullable()
46372
- });
46373
46477
  var RegistryStatusSchema = object({
46374
46478
  brokerCount: number().int().nonnegative(),
46375
46479
  connectedCount: number().int().nonnegative()
46376
46480
  });
46377
- /**
46378
- * One entry per `broker` provider — which addon provides which broker
46379
- * kind(s). The unified create picker reads this to know, for each
46380
- * (addonId, kind) pair the operator can pick, where to route the
46381
- * follow-up `getSettingsSchema` / `testSettings` / `add` calls (via the
46382
- * `{ addonId }` selector). A provider only advertises a kind here when
46383
- * it implements `getSettingsSchema` for that kind (so the picker never
46384
- * offers a kind whose creation form can't be rendered).
46385
- */
46386
- var BrokerProviderInfoSchema = object({
46387
- /** Addon id of the `broker` provider this entry describes. */
46388
- addonId: string(),
46389
- /** Broker kinds this provider can create, with a display label. */
46390
- kinds: array(object({
46391
- kind: string(),
46392
- label: string(),
46393
- /**
46394
- * Relative hub path to start an interactive account link (OAuth popup).
46395
- * May include `{{brokerId}}`; admin-ui substitutes and appends `?popup=1`.
46396
- */
46397
- interactiveConnectPath: string().min(1).optional(),
46398
- /** Relative hub path to disconnect the linked account (same popup pattern). */
46399
- interactiveDisconnectPath: string().min(1).optional(),
46400
- /**
46401
- * The kind signs in through a server-held interactive session instead of
46402
- * (or before) typed credentials. `basePath` is a hub-relative route set
46403
- * served by the owning addon (`/addon/<id>/...`) speaking the sign-in
46404
- * contract: `POST {basePath}/start` (body: the form's settings) answers
46405
- * `{ sessionId, loginUrl }`; `GET {basePath}/status?sessionId=` answers
46406
- * `{ phase: 'starting' | 'awaiting-login' | 'captured' | 'error' |
46407
- * 'cancelled', loginUrl, error }`; `POST {basePath}/commit`
46408
- * (`{ sessionId, name, brokerId? }`) stores the credentials on a new or
46409
- * existing broker and answers `{ brokerId }`; `POST {basePath}/cancel`
46410
- * (`{ sessionId }`) drops the session. The dialog that edits a broker
46411
- * offers it as the default path; the fields the session fills are
46412
- * marked `filledBySignIn` in the kind's settings schema.
46413
- *
46414
- * `methods` lists the ways the session can sign in, recommended first:
46415
- * `'device-code'` adds `POST {basePath}/code/start` (body: the form's
46416
- * settings) answering `{ sessionId, userCode, verificationUrl,
46417
- * expiresAt }` — the operator types `userCode` at `verificationUrl` on
46418
- * any device, and the same `status` / `commit` / `cancel` routes follow
46419
- * (status then carries `method`, `userCode`, `verificationUrl`,
46420
- * `expiresAt` and the phases `'awaiting-code'` / `'expired'`);
46421
- * `'proxy'` is the `{basePath}/start` flow above. Absent means
46422
- * `['proxy']`.
46423
- */
46424
- signIn: object({
46425
- basePath: string().min(1),
46426
- methods: array(_enum(["device-code", "proxy"])).optional()
46427
- }).optional()
46428
- }))
46429
- });
46430
- var ListInputSchema = object({
46431
- /** Optional kind filter — `list({kind:'home-assistant'})` returns
46432
- * only HA brokers. Omit to list every broker. */
46433
- kind: string().optional() });
46434
46481
  var GetInputSchema = object({ id: string() });
46435
- var AddInputSchema = object({
46436
- kind: string().min(1),
46437
- name: string().min(1),
46438
- /**
46439
- * ADOPT an existing id instead of minting a new one.
46440
- *
46441
- * Written the day this cost an outage. A broker's id is not a detail: HA
46442
- * devices carry it inside their `stableId` (`ha:ha_004:dev:…`), so a broker
46443
- * lost from config and re-added as `ha_001` leaves every one of its devices
46444
- * bound to a broker that no longer exists. Re-entering the password under the
46445
- * ORIGINAL id turns a multi-step device migration back into re-entering a
46446
- * password.
46447
- *
46448
- * A provider MUST refuse an id that is already in use — adopting a live
46449
- * broker's id would silently take it over.
46450
- */
46451
- id: string().min(1).optional(),
46452
- /** Kind-specific settings (e.g. MQTT `{url,username,password}` or HA
46453
- * `{baseUrl,accessToken}`). Validated by the kind-specific provider
46454
- * branch on receipt — invalid shape rejects the add. */
46455
- settings: record(string(), unknown())
46456
- });
46457
- var AddResultSchema = object({ id: string() });
46458
- var RemoveInputSchema = object({ id: string() });
46459
- var TestConnectionResultSchema = discriminatedUnion("ok", [object({
46460
- ok: literal(true),
46461
- latencyMs: number().nonnegative()
46462
- }), object({
46463
- ok: literal(false),
46464
- error: string()
46465
- })]);
46466
46482
  var SettingsRecordSchema$1 = record(string(), unknown());
46467
- var SettingsSchemaInputSchema = object({ kind: string() });
46468
- var TestSettingsInputSchema = object({
46469
- kind: string(),
46470
- settings: SettingsRecordSchema$1
46471
- });
46472
- var TestSettingsResultSchema = discriminatedUnion("ok", [object({
46473
- ok: literal(true),
46474
- latencyMs: number().nonnegative().optional()
46475
- }).strict(), object({
46476
- ok: literal(false),
46477
- error: string()
46478
- })]);
46479
- var SettingsSchemaResultSchema = unknown().nullable();
46480
46483
  var PublishInputSchema = object({
46481
46484
  brokerId: string(),
46482
46485
  /** Kind-specific routing target.
@@ -46520,51 +46523,12 @@ var brokerCapability = {
46520
46523
  kind: "poll"
46521
46524
  },
46522
46525
  methods: {
46523
- list: method(ListInputSchema, array(BrokerInfoSchema)),
46524
- get: method(GetInputSchema, BrokerInfoSchema.nullable()),
46525
- /** Enumerate which addon provides which broker kind(s) for the
46526
- * unified create picker. The auto-mount fans this array across
46527
- * every registered `broker` provider (array-output method), so the
46528
- * picker sees every kind from every provider in one call. */
46529
- listProviders: method(_void(), array(BrokerProviderInfoSchema), { auth: "admin" }),
46530
- add: method(AddInputSchema, AddResultSchema, {
46531
- kind: "mutation",
46532
- auth: "admin"
46533
- }),
46534
- remove: method(RemoveInputSchema, _void(), {
46535
- kind: "mutation",
46536
- auth: "admin"
46537
- }),
46538
- testConnection: method(GetInputSchema, TestConnectionResultSchema, {
46539
- kind: "mutation",
46540
- auth: "admin"
46541
- }),
46542
- /** Read the persisted settings record for a broker (kind-specific
46543
- * shape). Admin-only — settings may contain secrets. Returns `null`
46544
- * when the broker id is unknown to the provider (the collection
46545
- * fallback may route a foreign id to the first provider). */
46546
- getSettings: method(GetInputSchema, SettingsRecordSchema$1.nullable(), { auth: "admin" }),
46547
- /** Overwrite the persisted settings record. The kind-specific
46548
- * provider validates the shape and applies the change (reconnects
46549
- * if credentials changed). */
46550
- setSettings: method(object({
46551
- id: string(),
46552
- settings: SettingsRecordSchema$1
46553
- }), _void(), {
46554
- kind: "mutation",
46555
- auth: "admin"
46556
- }),
46557
46526
  /** Returns the kind-specific connection config the consumer needs
46558
46527
  * to open its own client (MQTT pattern: `{url, username, password,
46559
46528
  * clientIdPrefix}`). HA providers MAY return the auth envelope
46560
46529
  * but typical HA consumers use `publish` / `subscribe` instead.
46561
46530
  * Returns `null` when the broker id is unknown to the provider. */
46562
46531
  getBrokerConfig: method(GetInputSchema, SettingsRecordSchema$1.nullable(), { auth: "admin" }),
46563
- getSettingsSchema: method(SettingsSchemaInputSchema, SettingsSchemaResultSchema, { auth: "admin" }),
46564
- testSettings: method(TestSettingsInputSchema, TestSettingsResultSchema, {
46565
- kind: "mutation",
46566
- auth: "admin"
46567
- }),
46568
46532
  publish: method(PublishInputSchema, unknown(), {
46569
46533
  kind: "mutation",
46570
46534
  auth: "admin"
@@ -49198,6 +49162,9 @@ var RunningProposalEvidenceSchema = object({
49198
49162
  runsFound: number().int().nonnegative(),
49199
49163
  pausesFound: number().int().nonnegative(),
49200
49164
  longestPauseMs: number().nonnegative(),
49165
+ /** Episodes shorter than ~90 s (an anti-crease pulse, a display waking): never a run, never a pause. */
49166
+ pulsesFound: number().int().nonnegative(),
49167
+ longestPulseMs: number().nonnegative(),
49201
49168
  idleFloorW: number(),
49202
49169
  noiseCeilingW: number(),
49203
49170
  plateauW: number(),
@@ -50644,7 +50611,14 @@ var DiscoveryCandidateSchema = object({
50644
50611
  /** `stableId` of the gateway candidate this device was found BEHIND. */
50645
50612
  parentStableId: string().optional(),
50646
50613
  /** `false` = shown for context but not pickable. Default true. */
50647
- selectable: boolean().optional()
50614
+ selectable: boolean().optional(),
50615
+ /**
50616
+ * Keys of the provider's creation form (`getChildCreationSchema`) this candidate
50617
+ * cannot be adopted without — a key for an encrypted board, a pairing code. The
50618
+ * admin asks for exactly these, on the creation form prefilled with
50619
+ * `prefilledConfig`, before it adopts. Absent or empty = adopt as it is.
50620
+ */
50621
+ needsParams: array(string()).optional()
50648
50622
  });
50649
50623
  /**
50650
50624
  * Flat device summary returned by `createDevice` / `adoptDiscoveredDevice`.
@@ -50703,12 +50677,24 @@ method(_void(), _void(), { kind: "mutation" }), method(_void(), _void(), { kind:
50703
50677
  }), array(DiscoveryCandidateSchema), {
50704
50678
  kind: "mutation",
50705
50679
  auth: "admin"
50706
- }), method(object({}), CreationSchemaOutputSchema), method(object({}), object({ deviceType: _enum(DeviceType).nullable() })), method(object({ candidate: DiscoveryCandidateSchema }), DeviceSummarySchema, {
50680
+ }), method(object({}), CreationSchemaOutputSchema), method(object({
50681
+ /** The integration asked about; a provider whose integrations differ answers per one. */
50682
+ integrationId: string().optional() }), object({ deviceType: _enum(DeviceType).nullable() })), method(object({
50683
+ candidate: DiscoveryCandidateSchema,
50684
+ /** The integration the operator adopts into; a provider with several instances needs it. */
50685
+ integrationId: string().optional()
50686
+ }), DeviceSummarySchema, {
50707
50687
  kind: "mutation",
50708
50688
  auth: "admin"
50709
- }), method(object({}), boolean()), method(object({ type: _enum(DeviceType) }), CreationSchemaOutputSchema), method(object({
50689
+ }), method(object({}), boolean()), method(object({
50710
50690
  type: _enum(DeviceType),
50711
- config: record(string(), unknown())
50691
+ /** The integration asked about; a provider whose integrations differ answers per one. */
50692
+ integrationId: string().optional()
50693
+ }), CreationSchemaOutputSchema), method(object({
50694
+ type: _enum(DeviceType),
50695
+ config: record(string(), unknown()),
50696
+ /** The integration the operator adds the device to; a provider with several instances needs it. */
50697
+ integrationId: string().optional()
50712
50698
  }), DeviceSummarySchema, {
50713
50699
  kind: "mutation",
50714
50700
  auth: "admin"
@@ -51418,7 +51404,10 @@ method(object({
51418
51404
  auth: "admin"
51419
51405
  }), method(object({
51420
51406
  addonId: string(),
51421
- type: _enum(DeviceType)
51407
+ type: _enum(DeviceType),
51408
+ /** The integration the form is for; a provider whose integrations differ (a hub
51409
+ * integration takes no manual add) answers per integration. Absent = the addon's own. */
51410
+ integrationId: string().optional()
51422
51411
  }), unknown().nullable()), method(object({
51423
51412
  addonId: string(),
51424
51413
  type: _enum(DeviceType),
@@ -51502,7 +51491,11 @@ method(object({
51502
51491
  kind: "mutation",
51503
51492
  auth: "admin",
51504
51493
  timeoutMs: 12e4
51505
- }), method(object({ addonId: string() }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
51494
+ }), method(object({
51495
+ addonId: string(),
51496
+ /** The integration the Add-Device dialog is open on; absent = the addon's own. */
51497
+ integrationId: string().optional()
51498
+ }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
51506
51499
  deviceId: number(),
51507
51500
  key: string(),
51508
51501
  value: unknown()
@@ -54098,7 +54091,7 @@ var TestConnectionStatusEnum = _enum([
54098
54091
  "inconclusive",
54099
54092
  "unsupported"
54100
54093
  ]);
54101
- var TestConnectionResultSchema$1 = object({
54094
+ var TestConnectionResultSchema = object({
54102
54095
  /** True ONLY for `validated`. Never true for a test that did not run. */
54103
54096
  success: boolean(),
54104
54097
  error: string().optional(),
@@ -54119,11 +54112,7 @@ var CreateIntegrationInputSchema = object({
54119
54112
  info: record(string(), unknown()).optional(),
54120
54113
  /** `stableId` of the discovery candidate the form was seeded from (D984). */
54121
54114
  originStableId: string().optional(),
54122
- settings: record(string(), unknown()).optional(),
54123
- /** Keys of `settings` the form's schema declares secret (by type) — kept in
54124
- * the keychain, not the table (D787). */
54125
- secretKeys: array(string()).optional(),
54126
- skipRestart: boolean().optional()
54115
+ settings: record(string(), unknown()).optional()
54127
54116
  });
54128
54117
  var UpdateIntegrationInputSchema = object({
54129
54118
  id: string(),
@@ -54144,20 +54133,10 @@ method(_void(), array(IntegrationWithStateSchema)), method(object({ id: string()
54144
54133
  }), method(object({ id: string() }), DeleteIntegrationResultSchema, {
54145
54134
  kind: "mutation",
54146
54135
  auth: "admin"
54147
- }), method(object({ id: string() }), record(string(), unknown()), { auth: "admin" }), method(object({
54148
- id: string(),
54149
- settings: record(string(), unknown()),
54150
- /** Keys the form's schema declares secret (by type) — keychain-stored (D787). */
54151
- secretKeys: array(string()).optional(),
54152
- /** The integration's own addon applies the change in-process and asks the hub not to respawn it. */
54153
- skipRestart: boolean().optional()
54154
- }), object({ success: boolean() }), {
54155
- kind: "mutation",
54156
- auth: "admin"
54157
54136
  }), method(_void(), array(AvailableIntegrationTypeSchema), { auth: "admin" }), method(object({
54158
54137
  addonId: string(),
54159
54138
  settings: record(string(), unknown())
54160
- }), TestConnectionResultSchema$1, {
54139
+ }), TestConnectionResultSchema, {
54161
54140
  kind: "mutation",
54162
54141
  auth: "admin"
54163
54142
  });
@@ -54184,6 +54163,14 @@ var ConfigSchemaPassthrough$3 = custom();
54184
54163
  var IntegrationInstanceIdSchema = string().min(1);
54185
54164
  var IntegrationInstanceModeSchema = _enum(["single", "multiple"]);
54186
54165
  /**
54166
+ * What the addon's instances ARE for the Integrations page (planning#416). `devices`: each
54167
+ * instance is an integration that brings devices (the registry owns its on/off switch);
54168
+ * `services`: a connection configured from the addon's own function page, never listed on
54169
+ * Integrations.
54170
+ * It is the same vocabulary as the manifest's `integrationRole`, which stays as an override.
54171
+ */
54172
+ var IntegrationInstanceRoleSchema = _enum(["devices", "services"]);
54173
+ /**
54187
54174
  * One kind of instance a provider can create (an adapter, an account type). The sign-in and
54188
54175
  * connect fields follow the `broker` contract (`broker.cap.ts`): `signIn.basePath` is a
54189
54176
  * hub-relative route set speaking the sign-in contract, `connectPath` / `disconnectPath` open an
@@ -54194,6 +54181,22 @@ var IntegrationInstanceKindSchema = object({
54194
54181
  /** Stable id of the kind, sent back as `createInstance.kind`. */
54195
54182
  id: string().min(1),
54196
54183
  label: string().min(1),
54184
+ /**
54185
+ * The function capability this kind is configured for (`broker`, `smtp-provider`,
54186
+ * `device-provider`, ...). A page section is the kinds whose `functionCap` it names (D1013); a
54187
+ * provider with more than one section must name it on every kind.
54188
+ */
54189
+ functionCap: string().min(1),
54190
+ /**
54191
+ * For `functionCap: 'broker'`: the registry kind of the broker an instance of this kind is
54192
+ * (`matter`, `home-assistant`, ...). A caller that needs a broker of one kind (a link field)
54193
+ * finds the instances whose kind names it; absent takes the kind `id`.
54194
+ */
54195
+ brokerKind: string().min(1).optional(),
54196
+ /** What instances of this kind are for the Integrations page; absent takes the provider's `role`. */
54197
+ role: IntegrationInstanceRoleSchema.optional(),
54198
+ /** `testInstance` really probes the remote for this kind; absent takes the provider's `canTest`. */
54199
+ canTest: boolean().optional(),
54197
54200
  /** The kind signs in through a server-held interactive session. */
54198
54201
  signIn: object({
54199
54202
  basePath: string().min(1),
@@ -54206,11 +54209,7 @@ var IntegrationInstanceKindSchema = object({
54206
54209
  });
54207
54210
  var IntegrationInstanceDescriptionSchema = object({
54208
54211
  /** What the instances are for the Integrations page; see {@link IntegrationInstanceRoleSchema}. */
54209
- role: _enum([
54210
- "devices",
54211
- "services",
54212
- "both"
54213
- ]),
54212
+ role: IntegrationInstanceRoleSchema,
54214
54213
  /** How the devices of an instance are found; absent means `{ mode: 'none' }`. */
54215
54214
  discovery: object({
54216
54215
  mode: _enum([
@@ -54285,7 +54284,11 @@ var integrationInstancesCapability = {
54285
54284
  methods: {
54286
54285
  describe: method(_void(), IntegrationInstanceDescriptionSchema, { auth: "admin" }),
54287
54286
  /** The form; `id: null` is the create form. */
54288
- instanceFormSchema: method(object({ id: IntegrationInstanceIdSchema.nullable() }), ConfigSchemaPassthrough$3, { auth: "admin" }),
54287
+ instanceFormSchema: method(object({
54288
+ id: IntegrationInstanceIdSchema.nullable(),
54289
+ /** The kind of the create form (`id: null`) of a provider with several. */
54290
+ kind: string().min(1).optional()
54291
+ }), ConfigSchemaPassthrough$3, { auth: "admin" }),
54289
54292
  listInstances: method(_void(), array(IntegrationInstanceSchema).readonly(), { auth: "admin" }),
54290
54293
  getInstance: method(object({ id: IntegrationInstanceIdSchema }), IntegrationInstanceSchema.nullable(), { auth: "admin" }),
54291
54294
  /**
@@ -54295,7 +54298,9 @@ var integrationInstancesCapability = {
54295
54298
  createInstance: method(object({
54296
54299
  id: IntegrationInstanceIdSchema.optional(),
54297
54300
  name: string().min(1),
54298
- kind: string().min(1).optional()
54301
+ kind: string().min(1).optional(),
54302
+ /** Form values written with the record (a link picked in the create dialog). */
54303
+ values: record(string(), unknown()).optional()
54299
54304
  }), object({ id: string() }), {
54300
54305
  kind: "mutation",
54301
54306
  auth: "admin"
@@ -54322,8 +54327,10 @@ var integrationInstancesCapability = {
54322
54327
  }),
54323
54328
  testInstance: optionalMethod(object({
54324
54329
  id: IntegrationInstanceIdSchema.nullable(),
54325
- values: record(string(), unknown())
54326
- }), TestConnectionResultSchema$1, {
54330
+ values: record(string(), unknown()),
54331
+ /** The kind to test when `id` is null and the provider has several. */
54332
+ kind: string().min(1).optional()
54333
+ }), TestConnectionResultSchema, {
54327
54334
  kind: "mutation",
54328
54335
  auth: "admin"
54329
54336
  })
@@ -56828,6 +56835,380 @@ var SystemMetricsSchema = object({
56828
56835
  gpuMemoryPercent: number().optional()
56829
56836
  });
56830
56837
  method(_void(), SystemResourceSnapshotSchema), method(_void(), SystemResourceSnapshotSchema.nullable()), method(_void(), SystemMetricsSchema), method(object({ dirPath: string() }), DiskSpaceInfoSchema), method(_void(), MetricsGpuInfoSchema.nullable()), method(_void(), number().nullable()), method(object({ pids: array(number()) }), array(PidResourceStatsSchema)), method(_void(), array(AddonInstanceSchema).readonly()), method(object({ addonId: string() }), PidResourceStatsSchema.nullable()), method(_void(), array(NodeProcessSchema).readonly()), method(GetLoadSeriesInputSchema, NodeLoadSeriesSchema);
56838
+ /**
56839
+ * records - an addon's own facts and documents (D881): ledgers, audit rows,
56840
+ * config documents, mirrors. The third storage API next to `ctx.settings`
56841
+ * (operator intent, D870) and device-history (numbers over time, D850).
56842
+ *
56843
+ * Who the OWNER is: `callerAddonId`, stamped by the transport on a call that
56844
+ * crossed a process and stated by a hub in-process caller (`ctx.records` does
56845
+ * that with the addon id closed over). It is deliberately NOT in any input
56846
+ * schema, so a session can never supply it, and a call with no stamp is refused
56847
+ * `records/no-caller`. A kind is readable and writable only by its owner; other
56848
+ * addons go through the owner's capability.
56849
+ *
56850
+ * Every read is three-way: a row, `null`, or the call THROWS. A failed read is
56851
+ * never `[]`. Secret fields are never on the wire: a read shows the
56852
+ * redaction token, `secretRefs` hands the owner's `ctx.secrets` the refs it
56853
+ * resolves itself, and a write may carry only a keychain marker bound to the
56854
+ * row's own ref.
56855
+ *
56856
+ * Internal: addons reach it through `ctx.records`, never directly.
56857
+ */
56858
+ var RecordIdSchema = string().min(1).max(256);
56859
+ /** A JSON object body. Size is the engine's check (`maxDataBytes`), not a schema's. */
56860
+ var RecordBodySchema = record(string(), unknown());
56861
+ var RecordInputSchema = object({
56862
+ id: RecordIdSchema,
56863
+ /** The device this row belongs to (D865 removal, per-device reads). */
56864
+ deviceId: number().int().optional(),
56865
+ /** The domain clock, ms: observed / created / opened. */
56866
+ at: number().int().optional(),
56867
+ /** Producer-set expiry, ms. Refused on a kind whose retention is an engine TTL. */
56868
+ expiresAt: number().int().optional(),
56869
+ data: RecordBodySchema
56870
+ });
56871
+ var RecordViewSchema = object({
56872
+ id: string(),
56873
+ deviceId: number().int().nullable(),
56874
+ at: number().nullable(),
56875
+ expiresAt: number().nullable(),
56876
+ rev: number().int(),
56877
+ updatedAt: number(),
56878
+ data: RecordBodySchema
56879
+ });
56880
+ /** Declared index fields only. Anything else does not compile, by design. */
56881
+ var RecordWhereSchema = record(RecordFieldPathSchema, union([
56882
+ string(),
56883
+ number(),
56884
+ boolean(),
56885
+ object({ in: array(union([
56886
+ string(),
56887
+ number(),
56888
+ boolean()
56889
+ ])).min(1).max(RECORD_BATCH_MAX) }),
56890
+ object({
56891
+ gt: union([string(), number()]).optional(),
56892
+ gte: union([string(), number()]).optional(),
56893
+ lt: union([string(), number()]).optional(),
56894
+ lte: union([string(), number()]).optional()
56895
+ }).refine((r) => Object.keys(r).length > 0, { message: "name at least one bound" })
56896
+ ]));
56897
+ var KindShape = { kind: RecordKindNameSchema };
56898
+ var TimeWindowShape = {
56899
+ deviceId: number().int().optional(),
56900
+ atFrom: number().optional(),
56901
+ atTo: number().optional()
56902
+ };
56903
+ var RecordQueryInputSchema = object({
56904
+ ...KindShape,
56905
+ ...TimeWindowShape,
56906
+ where: RecordWhereSchema.optional(),
56907
+ /** Without `where`: `at` (default for a kind with a clock) or `id`. With `where` the order is the index's. */
56908
+ order: _enum(["at", "id"]).optional(),
56909
+ desc: boolean().optional(),
56910
+ limit: number().int().min(1).max(RECORD_QUERY_MAX).default(100),
56911
+ /** Opaque keyset cursor from a previous answer. There is no offset. */
56912
+ cursor: string().min(1).optional()
56913
+ });
56914
+ var RecordQueryResultSchema = object({
56915
+ records: array(RecordViewSchema),
56916
+ nextCursor: string().nullable()
56917
+ });
56918
+ var RecordKindStateSchema = _enum([
56919
+ "created",
56920
+ "unchanged",
56921
+ "updated"
56922
+ ]);
56923
+ var DeclareKindResultSchema = object({
56924
+ kindId: number().int(),
56925
+ state: RecordKindStateSchema,
56926
+ createdIndexes: array(string())
56927
+ });
56928
+ /** Keychain refs a write released (the old marker is gone from the row): the owner deletes the values. */
56929
+ var SecretRefsList = array(string());
56930
+ /**
56931
+ * One op of a `transact`: the single-row writes, each on a kind of the caller.
56932
+ * All ops of one call share ONE database file and ONE `transactFamily`.
56933
+ */
56934
+ var RecordTransactOpSchema = discriminatedUnion("op", [
56935
+ object({
56936
+ op: literal("put"),
56937
+ kind: RecordKindNameSchema,
56938
+ record: RecordInputSchema,
56939
+ ifRev: number().int().min(0).optional()
56940
+ }),
56941
+ object({
56942
+ op: literal("patch"),
56943
+ kind: RecordKindNameSchema,
56944
+ id: RecordIdSchema,
56945
+ data: RecordBodySchema,
56946
+ at: number().int().nullable().optional(),
56947
+ expiresAt: number().int().nullable().optional(),
56948
+ ifRev: number().int().min(1).optional()
56949
+ }),
56950
+ object({
56951
+ op: literal("delete"),
56952
+ kind: RecordKindNameSchema,
56953
+ id: RecordIdSchema
56954
+ })
56955
+ ]);
56956
+ var RecordSecretRefsSchema = record(string(), record(string(), string()));
56957
+ method(object({ kinds: record(RecordKindNameSchema, RecordKindDeclarationSchema) }), object({ kinds: record(string(), DeclareKindResultSchema) }), {
56958
+ kind: "mutation",
56959
+ auth: "admin"
56960
+ }), method(object({
56961
+ ...KindShape,
56962
+ id: RecordIdSchema
56963
+ }), RecordViewSchema.nullable(), { auth: "admin" }), method(object({
56964
+ ...KindShape,
56965
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
56966
+ }), array(RecordViewSchema), { auth: "admin" }), method(object({
56967
+ ...KindShape,
56968
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
56969
+ }), RecordSecretRefsSchema, { auth: "admin" }), method(object({
56970
+ ...KindShape,
56971
+ record: RecordInputSchema,
56972
+ /** Compare-and-set. `0` means "the row must not exist". */
56973
+ ifRev: number().int().min(0).optional()
56974
+ }), object({
56975
+ rev: number().int(),
56976
+ releasedRefs: SecretRefsList
56977
+ }), {
56978
+ kind: "mutation",
56979
+ auth: "admin"
56980
+ }), method(object({
56981
+ ...KindShape,
56982
+ records: array(RecordInputSchema).min(1).max(RECORD_BATCH_MAX)
56983
+ }), object({
56984
+ count: number().int(),
56985
+ releasedRefs: SecretRefsList
56986
+ }), {
56987
+ kind: "mutation",
56988
+ auth: "admin"
56989
+ }), method(object({
56990
+ ...KindShape,
56991
+ id: RecordIdSchema,
56992
+ data: RecordBodySchema,
56993
+ at: number().int().nullable().optional(),
56994
+ expiresAt: number().int().nullable().optional(),
56995
+ ifRev: number().int().min(1).optional()
56996
+ }), object({
56997
+ rev: number().int(),
56998
+ releasedRefs: SecretRefsList
56999
+ }), {
57000
+ kind: "mutation",
57001
+ auth: "admin"
57002
+ }), method(object({
57003
+ ...KindShape,
57004
+ id: RecordIdSchema
57005
+ }), object({
57006
+ deleted: boolean(),
57007
+ secretRefs: SecretRefsList
57008
+ }), {
57009
+ kind: "mutation",
57010
+ auth: "admin"
57011
+ }), method(object({
57012
+ ...KindShape,
57013
+ ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
57014
+ }), object({
57015
+ deleted: number().int(),
57016
+ secretRefs: SecretRefsList
57017
+ }), {
57018
+ kind: "mutation",
57019
+ auth: "admin"
57020
+ }), method(RecordQueryInputSchema, RecordQueryResultSchema, { auth: "admin" }), method(object({
57021
+ ...KindShape,
57022
+ ...TimeWindowShape,
57023
+ where: RecordWhereSchema.optional()
57024
+ }), object({ count: number().int() }), { auth: "admin" }), method(object({
57025
+ ...KindShape,
57026
+ deviceId: number().int().optional(),
57027
+ from: number(),
57028
+ to: number(),
57029
+ bucketMs: number().int().positive()
57030
+ }), object({ buckets: array(object({
57031
+ bucketStart: number(),
57032
+ count: number().int()
57033
+ })) }), { auth: "admin" }), method(object({
57034
+ ...KindShape,
57035
+ op: _enum([
57036
+ "sum",
57037
+ "min",
57038
+ "max",
57039
+ "count"
57040
+ ]),
57041
+ field: RecordFieldPathSchema.optional(),
57042
+ groupBy: RecordFieldPathSchema.optional(),
57043
+ where: RecordWhereSchema.optional()
57044
+ }), object({ rows: array(object({
57045
+ group: union([
57046
+ string(),
57047
+ number(),
57048
+ _null()
57049
+ ]),
57050
+ value: number().nullable()
57051
+ })) }), { auth: "admin" }), method(object({
57052
+ ...KindShape,
57053
+ deviceId: number().int().optional(),
57054
+ atBefore: number().optional(),
57055
+ where: RecordWhereSchema.optional()
57056
+ }), object({
57057
+ deleted: number().int(),
57058
+ secretRefs: SecretRefsList
57059
+ }), {
57060
+ kind: "mutation",
57061
+ auth: "admin"
57062
+ }), method(object({ ops: array(RecordTransactOpSchema).min(1).max(RECORD_BATCH_MAX) }), object({
57063
+ results: array(object({
57064
+ rev: number().int().nullable(),
57065
+ deleted: boolean()
57066
+ })),
57067
+ releasedRefs: SecretRefsList,
57068
+ secretRefs: SecretRefsList
57069
+ }), {
57070
+ kind: "mutation",
57071
+ auth: "admin"
57072
+ }), method(object({
57073
+ deviceId: number().int(),
57074
+ kinds: array(RecordKindNameSchema).optional()
57075
+ }), object({
57076
+ deleted: record(string(), number().int()),
57077
+ secretRefs: SecretRefsList
57078
+ }), {
57079
+ kind: "mutation",
57080
+ auth: "admin"
57081
+ }), method(object(KindShape), object({ id: number().int() }), {
57082
+ kind: "mutation",
57083
+ auth: "admin"
57084
+ });
57085
+ /**
57086
+ * The wire shapes of the migration API, version 1 (planning#447).
57087
+ *
57088
+ * A migration is code that outlives the server it was written against: an addon at
57089
+ * version 1.4 that is brought to 1.9 in one jump still runs its 1.4 catalogue, against
57090
+ * the 1.9 kernel. The only thing that code may call is {@link MigrationApiV1}; this file
57091
+ * is the contract of every method of it, one Zod pair per method.
57092
+ *
57093
+ * APPEND-ONLY. A released method is never removed and never changes meaning: an input
57094
+ * field is never removed or made required, an enum never narrows, an output field is
57095
+ * never removed. A change that cannot be expressed that way is `migration-api.v2`, next
57096
+ * to this file. `scripts/check-migration-api-append-only.ts` holds the line against
57097
+ * `scripts/migration-api-contract.json`, and every `behaviours` id below must have an
57098
+ * `it('<id>'` in `migration-api.contract.spec.ts`.
57099
+ */
57100
+ var Rows = record(string(), unknown());
57101
+ var IntegrationId = object({ integrationId: string().min(1) });
57102
+ var RecordId = object({ id: string().min(1) });
57103
+ var RecordRowSchema = object({
57104
+ id: string(),
57105
+ deviceId: number().int().nullable(),
57106
+ at: number().nullable(),
57107
+ expiresAt: number().nullable(),
57108
+ rev: number().int(),
57109
+ updatedAt: number(),
57110
+ data: Rows
57111
+ });
57112
+ var RecordPutShape = {
57113
+ id: string().min(1),
57114
+ deviceId: number().int().optional(),
57115
+ at: number().int().optional(),
57116
+ expiresAt: number().int().optional(),
57117
+ data: Rows
57118
+ };
57119
+ var MigrationIntegrationSchema = object({
57120
+ id: string(),
57121
+ addonId: string(),
57122
+ name: string(),
57123
+ info: Rows,
57124
+ originStableId: string().optional()
57125
+ });
57126
+ var MigrationDeviceSchema = object({
57127
+ id: number().int(),
57128
+ integrationId: string().nullable().optional(),
57129
+ /** The owning device; null or absent for a root. */
57130
+ parentDeviceId: number().int().nullable().optional(),
57131
+ type: string().optional(),
57132
+ name: string().optional(),
57133
+ stableId: string().optional()
57134
+ });
57135
+ /** What the engine says about the migration API it serves: lets an addon notice an older server. */
57136
+ var MigrationApiInfoSchema = object({
57137
+ version: number().int(),
57138
+ methods: array(string())
57139
+ });
57140
+ object({
57141
+ message: string(),
57142
+ meta: Rows.optional(),
57143
+ /** Grouping tags of the line; a line about a device carries `{ deviceId }`. */
57144
+ tags: object({ deviceId: number().int().optional() }).optional()
57145
+ });
57146
+ object({
57147
+ owner: string().min(1),
57148
+ metas: array(MigrationMetaSchema)
57149
+ }), object({
57150
+ bootId: string(),
57151
+ snapshot: _enum([
57152
+ "none",
57153
+ "written",
57154
+ "refused"
57155
+ ]),
57156
+ steps: array(MigrationOwnerStepSchema),
57157
+ /** The migration API the engine serves; absent from a server that predates it. */
57158
+ migrationApi: MigrationApiInfoSchema.optional()
57159
+ }), object({ id: string().min(1) }), object({
57160
+ proceed: boolean(),
57161
+ state: union([literal("pending"), MigrationStatusSchema]),
57162
+ reason: string().nullable()
57163
+ }), object({
57164
+ id: string().min(1),
57165
+ result: MigrationOwnerResultSchema
57166
+ }), object({
57167
+ status: MigrationStatusSchema,
57168
+ error: string().nullable(),
57169
+ rowsChanged: number().int().nonnegative()
57170
+ }), object({
57171
+ rows: number().int().nonnegative(),
57172
+ secrets: number().int().nonnegative()
57173
+ }), IntegrationId.extend({ patch: Rows }), object({ written: boolean() }), IntegrationId.extend({ keys: array(string().min(1)) }), object({
57174
+ present: boolean(),
57175
+ removed: Rows
57176
+ }), RecordRowSchema.nullable(), RecordRowSchema.nullable(), object({
57177
+ ...RecordPutShape,
57178
+ ifRev: number().int().optional()
57179
+ }), object({ rev: number().int() }), object({ records: array(object(RecordPutShape)) }), object({ count: number().int().nonnegative() }), RecordId.extend({
57180
+ partial: Rows,
57181
+ ifRev: number().int().optional()
57182
+ }), object({ rev: number().int() }), object({ deleted: boolean() }), object({
57183
+ deviceId: number().int().optional(),
57184
+ atFrom: number().optional(),
57185
+ atTo: number().optional(),
57186
+ where: RecordWhereSchema.optional(),
57187
+ limit: number().int().min(1).optional(),
57188
+ cursor: string().min(1).optional(),
57189
+ resolveSecrets: boolean().optional()
57190
+ }), object({
57191
+ records: array(RecordRowSchema),
57192
+ nextCursor: string().nullable()
57193
+ }), object({
57194
+ deviceId: number().int().optional(),
57195
+ atBefore: number().optional(),
57196
+ where: RecordWhereSchema.optional()
57197
+ }), object({ count: number().int().nonnegative() }), object({}), object({ store: Rows }), object({ patch: Rows }), object({}), object({ keys: array(string().min(1)) }), object({ removed: array(string()) }), object({ refs: array(string()) }), object({ values: record(string(), string().nullable()) }), object({
57198
+ ref: string().min(1),
57199
+ value: string()
57200
+ }), object({}), object({ refs: array(string()) }), object({ deleted: number().int().nonnegative() }), object({}), object({ integrations: array(MigrationIntegrationSchema) }), object({ id: string().min(1) }), MigrationIntegrationSchema.nullable(), object({
57201
+ addonId: string().min(1),
57202
+ integrationId: string().min(1).optional()
57203
+ }), object({ devices: array(MigrationDeviceSchema) }), object({ deviceId: number().int() }), object({
57204
+ id: number().int(),
57205
+ integrationId: string().nullable(),
57206
+ /** Whether the device carries any stored config; its content is not offered. */
57207
+ hasConfig: boolean()
57208
+ }).nullable(), object({
57209
+ deviceId: number().int(),
57210
+ integrationId: string().min(1)
57211
+ }), object({}), object({}), object({ nodeId: string() }), object({}), object({});
56831
57212
  method(object({}), object({ entries: array(MigrationLedgerEntrySchema) }), { auth: "admin" }), method(object({ owner: string().optional() }), object({ pending: array(MigrationPendingEntrySchema) }), { auth: "admin" }), method(object({ id: string().min(1) }), MigrationDryRunResultSchema, { auth: "admin" }), method(object({
56832
57213
  id: string().min(1),
56833
57214
  error: string().min(1)
@@ -56857,7 +57238,9 @@ method(object({}), object({ entries: array(MigrationLedgerEntrySchema) }), { aut
56857
57238
  "written",
56858
57239
  "refused"
56859
57240
  ]),
56860
- steps: array(MigrationOwnerStepSchema)
57241
+ steps: array(MigrationOwnerStepSchema),
57242
+ /** The migration API this engine serves (additive: a server that predates it omits it). */
57243
+ migrationApi: MigrationApiInfoSchema.optional()
56861
57244
  }), {
56862
57245
  kind: "mutation",
56863
57246
  auth: "admin"
@@ -56878,6 +57261,27 @@ method(object({}), object({ entries: array(MigrationLedgerEntrySchema) }), { aut
56878
57261
  }), {
56879
57262
  kind: "mutation",
56880
57263
  auth: "admin"
57264
+ }), method(object({ integrationId: string().min(1) }), record(string(), unknown()), { auth: "admin" }), method(object({ integrationId: string().min(1) }), object({
57265
+ rows: number().int().nonnegative(),
57266
+ secrets: number().int().nonnegative()
57267
+ }), {
57268
+ kind: "mutation",
57269
+ auth: "admin"
57270
+ }), method(object({
57271
+ integrationId: string().min(1),
57272
+ patch: record(string(), unknown())
57273
+ }), object({ written: boolean() }), {
57274
+ kind: "mutation",
57275
+ auth: "admin"
57276
+ }), method(object({
57277
+ integrationId: string().min(1),
57278
+ keys: array(string().min(1))
57279
+ }), object({
57280
+ present: boolean(),
57281
+ removed: record(string(), unknown())
57282
+ }), {
57283
+ kind: "mutation",
57284
+ auth: "admin"
56881
57285
  });
56882
57286
  method(object({
56883
57287
  sourceUrl: string(),
@@ -59503,7 +59907,10 @@ DeviceType.Camera, method(object({ deviceId: number() }), array(TrackSchema).rea
59503
59907
  }), method(RelocateMediaInputSchema, object({ jobId: string() }), {
59504
59908
  kind: "mutation",
59505
59909
  auth: "admin"
59506
- }), method(object({}), UnstampedEventMediaCountSchema, { auth: "admin" }), method(RelocatableMediaCountInputSchema, RelocatableMediaCountSchema, {
59910
+ }), method(object({}), UnstampedEventMediaCountSchema, { auth: "admin" }), method(MediaLocationCensusInputSchema, MediaLocationCensusSchema, {
59911
+ kind: "query",
59912
+ auth: "admin"
59913
+ }), method(RelocatableMediaCountInputSchema, RelocatableMediaCountSchema, {
59507
59914
  kind: "query",
59508
59915
  auth: "admin"
59509
59916
  }), method(object({}), array(RelocateJobSchema).readonly(), {
@@ -61910,7 +62317,7 @@ var BrokerStatusSchema$1 = _enum([
61910
62317
  "unreachable",
61911
62318
  "tls-error"
61912
62319
  ]);
61913
- var BrokerInfoSchema$1 = object({
62320
+ var BrokerInfoSchema = object({
61914
62321
  id: string(),
61915
62322
  name: string(),
61916
62323
  url: string(),
@@ -61973,7 +62380,7 @@ var StatusSchema = object({
61973
62380
  brokerCount: number(),
61974
62381
  embeddedRunning: boolean()
61975
62382
  });
61976
- method(_void(), array(BrokerInfoSchema$1)), method(IdInputSchema, BrokerConnectionDetailsSchema, { auth: "admin" }), method(AddBrokerInputSchema, AddBrokerResultSchema, {
62383
+ method(_void(), array(BrokerInfoSchema)), method(IdInputSchema, BrokerConnectionDetailsSchema, { auth: "admin" }), method(AddBrokerInputSchema, AddBrokerResultSchema, {
61977
62384
  kind: "mutation",
61978
62385
  auth: "admin"
61979
62386
  }), method(IdInputSchema, _void(), {
@@ -68291,253 +68698,6 @@ DeviceType.Camera, DeviceType.Sensor, DeviceType.Switch, DeviceType.Gateway, met
68291
68698
  auth: "admin"
68292
68699
  });
68293
68700
  /**
68294
- * records - an addon's own facts and documents (D881): ledgers, audit rows,
68295
- * config documents, mirrors. The third storage API next to `ctx.settings`
68296
- * (operator intent, D870) and device-history (numbers over time, D850).
68297
- *
68298
- * Who the OWNER is: `callerAddonId`, stamped by the transport on a call that
68299
- * crossed a process and stated by a hub in-process caller (`ctx.records` does
68300
- * that with the addon id closed over). It is deliberately NOT in any input
68301
- * schema, so a session can never supply it, and a call with no stamp is refused
68302
- * `records/no-caller`. A kind is readable and writable only by its owner; other
68303
- * addons go through the owner's capability.
68304
- *
68305
- * Every read is three-way: a row, `null`, or the call THROWS. A failed read is
68306
- * never `[]`. Secret fields are never on the wire: a read shows the
68307
- * redaction token, `secretRefs` hands the owner's `ctx.secrets` the refs it
68308
- * resolves itself, and a write may carry only a keychain marker bound to the
68309
- * row's own ref.
68310
- *
68311
- * Internal: addons reach it through `ctx.records`, never directly.
68312
- */
68313
- var RecordIdSchema = string().min(1).max(256);
68314
- /** A JSON object body. Size is the engine's check (`maxDataBytes`), not a schema's. */
68315
- var RecordBodySchema = record(string(), unknown());
68316
- var RecordInputSchema = object({
68317
- id: RecordIdSchema,
68318
- /** The device this row belongs to (D865 removal, per-device reads). */
68319
- deviceId: number().int().optional(),
68320
- /** The domain clock, ms: observed / created / opened. */
68321
- at: number().int().optional(),
68322
- /** Producer-set expiry, ms. Refused on a kind whose retention is an engine TTL. */
68323
- expiresAt: number().int().optional(),
68324
- data: RecordBodySchema
68325
- });
68326
- var RecordViewSchema = object({
68327
- id: string(),
68328
- deviceId: number().int().nullable(),
68329
- at: number().nullable(),
68330
- expiresAt: number().nullable(),
68331
- rev: number().int(),
68332
- updatedAt: number(),
68333
- data: RecordBodySchema
68334
- });
68335
- /** Declared index fields only. Anything else does not compile, by design. */
68336
- var RecordWhereSchema = record(RecordFieldPathSchema, union([
68337
- string(),
68338
- number(),
68339
- boolean(),
68340
- object({ in: array(union([
68341
- string(),
68342
- number(),
68343
- boolean()
68344
- ])).min(1).max(RECORD_BATCH_MAX) }),
68345
- object({
68346
- gt: union([string(), number()]).optional(),
68347
- gte: union([string(), number()]).optional(),
68348
- lt: union([string(), number()]).optional(),
68349
- lte: union([string(), number()]).optional()
68350
- }).refine((r) => Object.keys(r).length > 0, { message: "name at least one bound" })
68351
- ]));
68352
- var KindShape = { kind: RecordKindNameSchema };
68353
- var TimeWindowShape = {
68354
- deviceId: number().int().optional(),
68355
- atFrom: number().optional(),
68356
- atTo: number().optional()
68357
- };
68358
- var RecordQueryInputSchema = object({
68359
- ...KindShape,
68360
- ...TimeWindowShape,
68361
- where: RecordWhereSchema.optional(),
68362
- /** Without `where`: `at` (default for a kind with a clock) or `id`. With `where` the order is the index's. */
68363
- order: _enum(["at", "id"]).optional(),
68364
- desc: boolean().optional(),
68365
- limit: number().int().min(1).max(RECORD_QUERY_MAX).default(100),
68366
- /** Opaque keyset cursor from a previous answer. There is no offset. */
68367
- cursor: string().min(1).optional()
68368
- });
68369
- var RecordQueryResultSchema = object({
68370
- records: array(RecordViewSchema),
68371
- nextCursor: string().nullable()
68372
- });
68373
- var RecordKindStateSchema = _enum([
68374
- "created",
68375
- "unchanged",
68376
- "updated"
68377
- ]);
68378
- var DeclareKindResultSchema = object({
68379
- kindId: number().int(),
68380
- state: RecordKindStateSchema,
68381
- createdIndexes: array(string())
68382
- });
68383
- /** Keychain refs a write released (the old marker is gone from the row): the owner deletes the values. */
68384
- var SecretRefsList = array(string());
68385
- /**
68386
- * One op of a `transact`: the single-row writes, each on a kind of the caller.
68387
- * All ops of one call share ONE database file and ONE `transactFamily`.
68388
- */
68389
- var RecordTransactOpSchema = discriminatedUnion("op", [
68390
- object({
68391
- op: literal("put"),
68392
- kind: RecordKindNameSchema,
68393
- record: RecordInputSchema,
68394
- ifRev: number().int().min(0).optional()
68395
- }),
68396
- object({
68397
- op: literal("patch"),
68398
- kind: RecordKindNameSchema,
68399
- id: RecordIdSchema,
68400
- data: RecordBodySchema,
68401
- at: number().int().nullable().optional(),
68402
- expiresAt: number().int().nullable().optional(),
68403
- ifRev: number().int().min(1).optional()
68404
- }),
68405
- object({
68406
- op: literal("delete"),
68407
- kind: RecordKindNameSchema,
68408
- id: RecordIdSchema
68409
- })
68410
- ]);
68411
- var RecordSecretRefsSchema = record(string(), record(string(), string()));
68412
- method(object({ kinds: record(RecordKindNameSchema, RecordKindDeclarationSchema) }), object({ kinds: record(string(), DeclareKindResultSchema) }), {
68413
- kind: "mutation",
68414
- auth: "admin"
68415
- }), method(object({
68416
- ...KindShape,
68417
- id: RecordIdSchema
68418
- }), RecordViewSchema.nullable(), { auth: "admin" }), method(object({
68419
- ...KindShape,
68420
- ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
68421
- }), array(RecordViewSchema), { auth: "admin" }), method(object({
68422
- ...KindShape,
68423
- ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
68424
- }), RecordSecretRefsSchema, { auth: "admin" }), method(object({
68425
- ...KindShape,
68426
- record: RecordInputSchema,
68427
- /** Compare-and-set. `0` means "the row must not exist". */
68428
- ifRev: number().int().min(0).optional()
68429
- }), object({
68430
- rev: number().int(),
68431
- releasedRefs: SecretRefsList
68432
- }), {
68433
- kind: "mutation",
68434
- auth: "admin"
68435
- }), method(object({
68436
- ...KindShape,
68437
- records: array(RecordInputSchema).min(1).max(RECORD_BATCH_MAX)
68438
- }), object({
68439
- count: number().int(),
68440
- releasedRefs: SecretRefsList
68441
- }), {
68442
- kind: "mutation",
68443
- auth: "admin"
68444
- }), method(object({
68445
- ...KindShape,
68446
- id: RecordIdSchema,
68447
- data: RecordBodySchema,
68448
- at: number().int().nullable().optional(),
68449
- expiresAt: number().int().nullable().optional(),
68450
- ifRev: number().int().min(1).optional()
68451
- }), object({
68452
- rev: number().int(),
68453
- releasedRefs: SecretRefsList
68454
- }), {
68455
- kind: "mutation",
68456
- auth: "admin"
68457
- }), method(object({
68458
- ...KindShape,
68459
- id: RecordIdSchema
68460
- }), object({
68461
- deleted: boolean(),
68462
- secretRefs: SecretRefsList
68463
- }), {
68464
- kind: "mutation",
68465
- auth: "admin"
68466
- }), method(object({
68467
- ...KindShape,
68468
- ids: array(RecordIdSchema).min(1).max(RECORD_BATCH_MAX)
68469
- }), object({
68470
- deleted: number().int(),
68471
- secretRefs: SecretRefsList
68472
- }), {
68473
- kind: "mutation",
68474
- auth: "admin"
68475
- }), method(RecordQueryInputSchema, RecordQueryResultSchema, { auth: "admin" }), method(object({
68476
- ...KindShape,
68477
- ...TimeWindowShape,
68478
- where: RecordWhereSchema.optional()
68479
- }), object({ count: number().int() }), { auth: "admin" }), method(object({
68480
- ...KindShape,
68481
- deviceId: number().int().optional(),
68482
- from: number(),
68483
- to: number(),
68484
- bucketMs: number().int().positive()
68485
- }), object({ buckets: array(object({
68486
- bucketStart: number(),
68487
- count: number().int()
68488
- })) }), { auth: "admin" }), method(object({
68489
- ...KindShape,
68490
- op: _enum([
68491
- "sum",
68492
- "min",
68493
- "max",
68494
- "count"
68495
- ]),
68496
- field: RecordFieldPathSchema.optional(),
68497
- groupBy: RecordFieldPathSchema.optional(),
68498
- where: RecordWhereSchema.optional()
68499
- }), object({ rows: array(object({
68500
- group: union([
68501
- string(),
68502
- number(),
68503
- _null()
68504
- ]),
68505
- value: number().nullable()
68506
- })) }), { auth: "admin" }), method(object({
68507
- ...KindShape,
68508
- deviceId: number().int().optional(),
68509
- atBefore: number().optional(),
68510
- where: RecordWhereSchema.optional()
68511
- }), object({
68512
- deleted: number().int(),
68513
- secretRefs: SecretRefsList
68514
- }), {
68515
- kind: "mutation",
68516
- auth: "admin"
68517
- }), method(object({ ops: array(RecordTransactOpSchema).min(1).max(RECORD_BATCH_MAX) }), object({
68518
- results: array(object({
68519
- rev: number().int().nullable(),
68520
- deleted: boolean()
68521
- })),
68522
- releasedRefs: SecretRefsList,
68523
- secretRefs: SecretRefsList
68524
- }), {
68525
- kind: "mutation",
68526
- auth: "admin"
68527
- }), method(object({
68528
- deviceId: number().int(),
68529
- kinds: array(RecordKindNameSchema).optional()
68530
- }), object({
68531
- deleted: record(string(), number().int()),
68532
- secretRefs: SecretRefsList
68533
- }), {
68534
- kind: "mutation",
68535
- auth: "admin"
68536
- }), method(object(KindShape), object({ id: number().int() }), {
68537
- kind: "mutation",
68538
- auth: "admin"
68539
- });
68540
- /**
68541
68701
  * record-entries - the ONE admin surface for every list of user-created entries
68542
68702
  * (D881): notification targets, brokers, LLM profiles, anything an addon
68543
68703
  * declares as an ENTRY kind (`entry: { title }` in `defineRecordKinds`).
@@ -76052,11 +76212,15 @@ discriminatedUnion("kind", [object({
76052
76212
  * 1. idle floor F = time-weighted median; noise ceiling N = highest value seen
76053
76213
  * near F. A device that is not near one level most of the time has no floor.
76054
76214
  * 2. coarse activity = above max(2N, N + 5 W); consecutive stretches are episodes.
76055
- * 3. gaps between episodes split in two by the largest log-scale jump (>= 3x):
76056
- * the short ones are pauses INSIDE a run (a soak), the long ones separate runs.
76215
+ * 3. an episode shorter than `PULSE_MAX_MS` is a PULSE (an anti-crease tumble, a
76216
+ * display waking): it is neither a run nor a pause. Among the remaining
76217
+ * episodes, gaps over `PAUSE_MAX_MS` always separate runs; the rest split in
76218
+ * two by the largest log-scale jump (>= 3x): the short ones are pauses INSIDE
76219
+ * a run (a soak), the long ones separate runs. A stretch under `MIN_RUN_MS`
76220
+ * is no run.
76057
76221
  * 4. T = geometric mean of N and the plateau's 10th percentile, snapped to a
76058
- * grid a person would type; stop dwell covers the longest pause; start dwell
76059
- * covers the longest standby blip above T.
76222
+ * grid a person would type; stop dwell covers the longest pause and the
76223
+ * kind's floor; start dwell covers the longest pulse and standby blip above T.
76060
76224
  * 5. the numbers are proved by REPLAY through the real `dwell` evaluation: each
76061
76225
  * run must hold exactly one true interval and nothing may flap outside.
76062
76226
  */
@@ -76067,6 +76231,10 @@ var MINUTE_MS$1 = 60 * SECOND_MS;
76067
76231
  30 * SECOND_MS;
76068
76232
  60 * SECOND_MS;
76069
76233
  20 * MINUTE_MS$1;
76234
+ 90 * SECOND_MS;
76235
+ 30 * MINUTE_MS$1;
76236
+ 10 * MINUTE_MS$1;
76237
+ DeviceType.Dryer, 3 * MINUTE_MS$1, DeviceType.Dishwasher, 3 * MINUTE_MS$1, DeviceType.Washer, 10 * MINUTE_MS$1;
76070
76238
  10 * SECOND_MS;
76071
76239
  10 * SECOND_MS;
76072
76240
  DeviceFeature.FanSpeed, DeviceFeature.FanPreset, DeviceFeature.FanDirection, DeviceFeature.FanOscillating, DeviceFeature.CoverStoppable, DeviceFeature.CoverPositionable, DeviceFeature.CoverTilt, DeviceFeature.ValvePositionable, DeviceFeature.MediaPlayerVolume, DeviceFeature.ClimateFanMode;
@@ -77085,20 +77253,6 @@ Object.freeze({
77085
77253
  access: "create",
77086
77254
  role: "viewer"
77087
77255
  },
77088
- "broker.add": {
77089
- capName: "broker",
77090
- capScope: "system",
77091
- addonId: null,
77092
- access: "create",
77093
- role: "admin"
77094
- },
77095
- "broker.get": {
77096
- capName: "broker",
77097
- capScope: "system",
77098
- addonId: null,
77099
- access: "view",
77100
- role: "admin"
77101
- },
77102
77256
  "broker.getBrokerConfig": {
77103
77257
  capName: "broker",
77104
77258
  capScope: "system",
@@ -77106,20 +77260,6 @@ Object.freeze({
77106
77260
  access: "view",
77107
77261
  role: "admin"
77108
77262
  },
77109
- "broker.getSettings": {
77110
- capName: "broker",
77111
- capScope: "system",
77112
- addonId: null,
77113
- access: "view",
77114
- role: "admin"
77115
- },
77116
- "broker.getSettingsSchema": {
77117
- capName: "broker",
77118
- capScope: "system",
77119
- addonId: null,
77120
- access: "view",
77121
- role: "admin"
77122
- },
77123
77263
  "broker.getState": {
77124
77264
  capName: "broker",
77125
77265
  capScope: "system",
@@ -77134,20 +77274,6 @@ Object.freeze({
77134
77274
  access: "view",
77135
77275
  role: "admin"
77136
77276
  },
77137
- "broker.list": {
77138
- capName: "broker",
77139
- capScope: "system",
77140
- addonId: null,
77141
- access: "view",
77142
- role: "admin"
77143
- },
77144
- "broker.listProviders": {
77145
- capName: "broker",
77146
- capScope: "system",
77147
- addonId: null,
77148
- access: "view",
77149
- role: "admin"
77150
- },
77151
77277
  "broker.publish": {
77152
77278
  capName: "broker",
77153
77279
  capScope: "system",
@@ -77155,20 +77281,6 @@ Object.freeze({
77155
77281
  access: "create",
77156
77282
  role: "admin"
77157
77283
  },
77158
- "broker.remove": {
77159
- capName: "broker",
77160
- capScope: "system",
77161
- addonId: null,
77162
- access: "delete",
77163
- role: "admin"
77164
- },
77165
- "broker.setSettings": {
77166
- capName: "broker",
77167
- capScope: "system",
77168
- addonId: null,
77169
- access: "create",
77170
- role: "admin"
77171
- },
77172
77284
  "broker.subscribe": {
77173
77285
  capName: "broker",
77174
77286
  capScope: "system",
@@ -77176,20 +77288,6 @@ Object.freeze({
77176
77288
  access: "create",
77177
77289
  role: "admin"
77178
77290
  },
77179
- "broker.testConnection": {
77180
- capName: "broker",
77181
- capScope: "system",
77182
- addonId: null,
77183
- access: "create",
77184
- role: "admin"
77185
- },
77186
- "broker.testSettings": {
77187
- capName: "broker",
77188
- capScope: "system",
77189
- addonId: null,
77190
- access: "create",
77191
- role: "admin"
77192
- },
77193
77291
  "broker.unsubscribe": {
77194
77292
  capName: "broker",
77195
77293
  capScope: "system",
@@ -79822,13 +79920,6 @@ Object.freeze({
79822
79920
  access: "view",
79823
79921
  role: "admin"
79824
79922
  },
79825
- "integrations.getSettings": {
79826
- capName: "integrations",
79827
- capScope: "system",
79828
- addonId: null,
79829
- access: "view",
79830
- role: "admin"
79831
- },
79832
79923
  "integrations.list": {
79833
79924
  capName: "integrations",
79834
79925
  capScope: "system",
@@ -79836,13 +79927,6 @@ Object.freeze({
79836
79927
  access: "view",
79837
79928
  role: "admin"
79838
79929
  },
79839
- "integrations.setSettings": {
79840
- capName: "integrations",
79841
- capScope: "system",
79842
- addonId: null,
79843
- access: "create",
79844
- role: "admin"
79845
- },
79846
79930
  "integrations.testConnection": {
79847
79931
  capName: "integrations",
79848
79932
  capScope: "system",
@@ -80837,6 +80921,13 @@ Object.freeze({
80837
80921
  access: "view",
80838
80922
  role: "admin"
80839
80923
  },
80924
+ "migrations.clearLegacyIntegrationRows": {
80925
+ capName: "migrations",
80926
+ capScope: "system",
80927
+ addonId: null,
80928
+ access: "delete",
80929
+ role: "admin"
80930
+ },
80840
80931
  "migrations.declareOwner": {
80841
80932
  capName: "migrations",
80842
80933
  capScope: "system",
@@ -80844,6 +80935,13 @@ Object.freeze({
80844
80935
  access: "create",
80845
80936
  role: "admin"
80846
80937
  },
80938
+ "migrations.deleteLegacyIntegrationRowKeys": {
80939
+ capName: "migrations",
80940
+ capScope: "system",
80941
+ addonId: null,
80942
+ access: "delete",
80943
+ role: "admin"
80944
+ },
80847
80945
  "migrations.dryRun": {
80848
80946
  capName: "migrations",
80849
80947
  capScope: "system",
@@ -80879,6 +80977,20 @@ Object.freeze({
80879
80977
  access: "create",
80880
80978
  role: "admin"
80881
80979
  },
80980
+ "migrations.patchLegacyIntegrationRows": {
80981
+ capName: "migrations",
80982
+ capScope: "system",
80983
+ addonId: null,
80984
+ access: "create",
80985
+ role: "admin"
80986
+ },
80987
+ "migrations.readLegacyIntegrationRows": {
80988
+ capName: "migrations",
80989
+ capScope: "system",
80990
+ addonId: null,
80991
+ access: "view",
80992
+ role: "admin"
80993
+ },
80882
80994
  "migrations.restorePreMigration": {
80883
80995
  capName: "migrations",
80884
80996
  capScope: "system",
@@ -82139,6 +82251,13 @@ Object.freeze({
82139
82251
  access: "view",
82140
82252
  role: "viewer"
82141
82253
  },
82254
+ "pipelineAnalytics.getMediaLocationCensus": {
82255
+ capName: "pipeline-analytics",
82256
+ capScope: "device",
82257
+ addonId: null,
82258
+ access: "view",
82259
+ role: "admin"
82260
+ },
82142
82261
  "pipelineAnalytics.getMediaReclaimStatus": {
82143
82262
  capName: "pipeline-analytics",
82144
82263
  capScope: "device",
@@ -91111,6 +91230,7 @@ object({
91111
91230
  delay: number().nonnegative().optional(),
91112
91231
  commands: record(string(), unknown())
91113
91232
  });
91233
+ entryBody({ brokerId: string() });
91114
91234
  //#endregion
91115
91235
  //#region src/google-types.ts
91116
91236
  /** One Google account connection (broker entry). Credentials for the OAuth
@@ -91196,6 +91316,10 @@ var OAUTH_START_PATH = `/addon/google-services/oauth/start`;
91196
91316
  var OAUTH_CALLBACK_SUFFIX = `/addon/google-services/oauth/callback`;
91197
91317
  //#endregion
91198
91318
  //#region src/google-broker-registry.ts
91319
+ /**
91320
+ * Google broker registry — N Google accounts under kind `google`.
91321
+ * No live WS; "connected" means a refresh token exists for the broker id.
91322
+ */
91199
91323
  var GoogleAddSettingsSchema = object({
91200
91324
  clientId: string().min(1),
91201
91325
  clientSecret: string().min(1).meta({ secret: true }),
@@ -91303,7 +91427,7 @@ function parseStampedCalendarId(stamped) {
91303
91427
  }
91304
91428
  /**
91305
91429
  * In-memory index over broker entries + oauth accounts. The addon owns
91306
- * persistence; this class only allocates ids and builds BrokerInfo rows.
91430
+ * persistence; this class only allocates ids and tracks the OAuth state.
91307
91431
  */
91308
91432
  var GoogleBrokerRegistry = class {
91309
91433
  nextIdCounter = 1;
@@ -91400,28 +91524,6 @@ var GoogleBrokerRegistry = class {
91400
91524
  this.entries = entries.map((e) => GoogleBrokerEntrySchema.parse(e));
91401
91525
  this.seedCounterFromEntries(this.entries);
91402
91526
  }
91403
- toBrokerInfo(entry, addonId) {
91404
- const oauth = this.oauthById.get(entry.id);
91405
- const connected = this.isConnected(entry.id);
91406
- const reauth = this.needsReauth(entry.id);
91407
- return {
91408
- id: entry.id,
91409
- addonId,
91410
- name: entry.name,
91411
- kind: GOOGLE_BROKER_KIND,
91412
- status: connected ? "connected" : reauth ? "auth-failed" : "disconnected",
91413
- info: {
91414
- accountEmail: oauth?.accountEmail ?? "",
91415
- hasClient: entry.clientId.length > 0
91416
- },
91417
- lastCheckedAt: connected ? Date.now() : null,
91418
- error: connected ? null : reauth ? "Google session expired — sign in again" : entry.clientId.length === 0 ? "Configure Client ID / secret, then Connect Google" : "Not connected — open Connect Google on this broker"
91419
- };
91420
- }
91421
- listBrokerInfos(addonId, kind) {
91422
- if (kind !== void 0 && kind !== "google") return [];
91423
- return this.entries.map((e) => this.toBrokerInfo(e, addonId));
91424
- }
91425
91527
  size() {
91426
91528
  return this.entries.length;
91427
91529
  }
@@ -91527,8 +91629,8 @@ function escapeHtml$1(s) {
91527
91629
  //#region src/google-broker-settings-schema.ts
91528
91630
  /**
91529
91631
  * Per-kind broker creation/edit form for kind=`google`.
91530
- * Account linking (Sign in) is driven by `listProviders.interactiveConnectPath`
91531
- * in BrokerManager — not a hard-coded Connect link in this form.
91632
+ * Account linking (Sign in) is driven by the kind's `connectPath`
91633
+ * on the instances page — not a hard-coded Connect link in this form.
91532
91634
  */
91533
91635
  function consoleLinksHtml() {
91534
91636
  return [
@@ -92161,6 +92263,8 @@ function buildGoogleInstances(records, deps) {
92161
92263
  kinds: [{
92162
92264
  id: GOOGLE_BROKER_KIND,
92163
92265
  label: GOOGLE_BROKER_KIND_LABEL,
92266
+ functionCap: "broker",
92267
+ brokerKind: GOOGLE_BROKER_KIND,
92164
92268
  connectPath: deps.connectPath,
92165
92269
  disconnectPath: deps.disconnectPath
92166
92270
  }],
@@ -92585,7 +92689,6 @@ var GoogleServicesAddon = class extends BaseAddon {
92585
92689
  }
92586
92690
  /** The accounts as `integration-instances`, over the same `brokers` records (planning#408 P3). */
92587
92691
  buildInstances(records) {
92588
- const brokerProvider = this.buildBrokerProvider();
92589
92692
  return buildGoogleInstances(records, {
92590
92693
  connectPath: `/addon/${ADDON_ID}${START_PATH}?brokerId={{brokerId}}`,
92591
92694
  disconnectPath: `/addon/${ADDON_ID}${DISCONNECT_PATH}?brokerId={{brokerId}}`,
@@ -92598,131 +92701,19 @@ var GoogleServicesAddon = class extends BaseAddon {
92598
92701
  this.registry.seedFrom(this.activeBrokers, accounts);
92599
92702
  await this.persistOauthAccounts();
92600
92703
  },
92601
- testSaved: async (id) => brokerProvider.testConnection({ id }),
92602
- testClient: async (clientId, clientSecret) => brokerProvider.testSettings({
92603
- kind: GOOGLE_BROKER_KIND,
92604
- settings: {
92605
- clientId,
92606
- clientSecret
92607
- }
92608
- })
92704
+ testSaved: (id) => this.probeSavedAccount(id),
92705
+ testClient: (clientId, clientSecret) => this.probeOauthClient(clientId, clientSecret)
92609
92706
  });
92610
92707
  }
92708
+ /**
92709
+ * The `broker` cap is the bus only (D1013): the accounts are the `integration-instances`
92710
+ * provider; calendar and mail go through their own caps, so publish and subscribe are refused.
92711
+ */
92611
92712
  buildBrokerProvider() {
92612
- const ownerAddonId = this.ctx.id;
92613
- const owns = (id) => this.registry.getEntry(id) !== null;
92614
92713
  const notSupported = async () => {
92615
92714
  throw new Error("google-services broker: publish/subscribe/getState are not supported — use calendar-source / smtp-provider");
92616
92715
  };
92617
92716
  return {
92618
- list: async ({ kind }) => this.registry.listBrokerInfos(ownerAddonId, kind),
92619
- get: async ({ id }) => {
92620
- const entry = this.registry.getEntry(id);
92621
- return entry ? this.registry.toBrokerInfo(entry, ownerAddonId) : null;
92622
- },
92623
- listProviders: async () => [{
92624
- addonId: ownerAddonId,
92625
- kinds: [{
92626
- kind: GOOGLE_BROKER_KIND,
92627
- label: GOOGLE_BROKER_KIND_LABEL,
92628
- interactiveConnectPath: `/addon/${ADDON_ID}${START_PATH}?brokerId={{brokerId}}`,
92629
- interactiveDisconnectPath: `/addon/${ADDON_ID}${DISCONNECT_PATH}?brokerId={{brokerId}}`
92630
- }]
92631
- }],
92632
- add: async ({ kind, name, settings, id }) => {
92633
- if (kind !== "google") throw new Error(`google-services: only kind '${GOOGLE_BROKER_KIND}' is handled here (got '${kind}')`);
92634
- const entry = this.registry.createEntry(name, settings, id !== void 0 ? { id } : {});
92635
- await this.persistBrokers();
92636
- return { id: entry.id };
92637
- },
92638
- remove: async ({ id }) => {
92639
- if (!owns(id)) return;
92640
- this.registry.removeEntry(id);
92641
- await this.persistBrokers();
92642
- await this.persistOauthAccounts();
92643
- },
92644
- testConnection: async ({ id }) => {
92645
- if (!owns(id)) return {
92646
- ok: false,
92647
- error: "unknown broker"
92648
- };
92649
- const entry = this.registry.getEntry(id);
92650
- if (entry === null) return {
92651
- ok: false,
92652
- error: "unknown broker"
92653
- };
92654
- if (!entry.clientId || !entry.clientSecret) return {
92655
- ok: false,
92656
- error: "Configure Client ID and Client secret first"
92657
- };
92658
- let redirectUri;
92659
- try {
92660
- redirectUri = await this.resolveRedirectUri();
92661
- } catch (err) {
92662
- return {
92663
- ok: false,
92664
- error: err instanceof Error ? err.message : String(err)
92665
- };
92666
- }
92667
- if (!this.registry.isConnected(id)) return probeGoogleOauthClient({
92668
- clientId: entry.clientId,
92669
- clientSecret: entry.clientSecret,
92670
- redirectUri
92671
- });
92672
- try {
92673
- const started = Date.now();
92674
- const token = await this.ensureAccessToken(id, { forceRefresh: true });
92675
- if (token.trim().length === 0) return {
92676
- ok: false,
92677
- error: "No access token after refresh — Sign out and Sign in again"
92678
- };
92679
- let res = await fetch(GOOGLE_CALENDAR_LIST_URL, { headers: { Authorization: `Bearer ${token}` } });
92680
- if (res.status === 401) {
92681
- const retryToken = await this.ensureAccessToken(id, { forceRefresh: true });
92682
- res = await fetch(GOOGLE_CALENDAR_LIST_URL, { headers: { Authorization: `Bearer ${retryToken}` } });
92683
- }
92684
- if (!res.ok) {
92685
- const text = await res.text();
92686
- return {
92687
- ok: false,
92688
- error: `Google Calendar probe failed (${res.status}): ${text.slice(0, 200)}`
92689
- };
92690
- }
92691
- const email = await this.fetchAccountEmail(token);
92692
- if (email.length > 0) {
92693
- const oauth = this.registry.getOauth(id);
92694
- if (oauth !== null && oauth.accountEmail !== email) {
92695
- this.registry.setOauth({
92696
- ...oauth,
92697
- accountEmail: email
92698
- });
92699
- await this.persistOauthAccounts();
92700
- }
92701
- }
92702
- return {
92703
- ok: true,
92704
- latencyMs: Date.now() - started
92705
- };
92706
- } catch (err) {
92707
- return {
92708
- ok: false,
92709
- error: err instanceof Error ? err.message : String(err)
92710
- };
92711
- }
92712
- },
92713
- getSettings: async ({ id }) => {
92714
- const entry = this.registry.getEntry(id);
92715
- if (entry === null) return null;
92716
- return {
92717
- ...brokerEntryToSettings(entry),
92718
- _calendarCatalog: await this.loadStampedCalendarCatalog(id)
92719
- };
92720
- },
92721
- setSettings: async ({ id, settings }) => {
92722
- if (!owns(id)) return;
92723
- this.registry.updateEntry(id, settings);
92724
- await this.persistBrokers();
92725
- },
92726
92717
  getBrokerConfig: async ({ id }) => {
92727
92718
  const entry = this.registry.getEntry(id);
92728
92719
  if (entry === null) return null;
@@ -92734,33 +92725,6 @@ var GoogleServicesAddon = class extends BaseAddon {
92734
92725
  connected: this.registry.isConnected(id)
92735
92726
  };
92736
92727
  },
92737
- getSettingsSchema: async ({ kind }) => {
92738
- if (kind !== "google") return null;
92739
- return buildGoogleBrokerSettingsSchema(this.publicOrigin);
92740
- },
92741
- testSettings: async ({ kind, settings }) => {
92742
- if (kind !== "google") return {
92743
- ok: false,
92744
- error: `unsupported kind: ${kind}`
92745
- };
92746
- try {
92747
- const parsed = object({
92748
- clientId: string().min(1),
92749
- clientSecret: string().min(1).meta({ secret: true })
92750
- }).parse(settings);
92751
- const redirectUri = await this.resolveRedirectUri();
92752
- return probeGoogleOauthClient({
92753
- clientId: parsed.clientId,
92754
- clientSecret: parsed.clientSecret,
92755
- redirectUri
92756
- });
92757
- } catch (err) {
92758
- return {
92759
- ok: false,
92760
- error: err instanceof Error ? err.message : String(err)
92761
- };
92762
- }
92763
- },
92764
92728
  publish: notSupported,
92765
92729
  subscribe: notSupported,
92766
92730
  unsubscribe: notSupported,
@@ -92771,6 +92735,95 @@ var GoogleServicesAddon = class extends BaseAddon {
92771
92735
  })
92772
92736
  };
92773
92737
  }
92738
+ /** Probe a saved account: the OAuth client, then (when signed in) a Calendar call. */
92739
+ async probeSavedAccount(id) {
92740
+ const entry = this.registry.getEntry(id);
92741
+ if (entry === null) return {
92742
+ ok: false,
92743
+ error: "unknown broker"
92744
+ };
92745
+ if (!entry.clientId || !entry.clientSecret) return {
92746
+ ok: false,
92747
+ error: "Configure Client ID and Client secret first"
92748
+ };
92749
+ let redirectUri;
92750
+ try {
92751
+ redirectUri = await this.resolveRedirectUri();
92752
+ } catch (err) {
92753
+ return {
92754
+ ok: false,
92755
+ error: err instanceof Error ? err.message : String(err)
92756
+ };
92757
+ }
92758
+ if (!this.registry.isConnected(id)) return probeGoogleOauthClient({
92759
+ clientId: entry.clientId,
92760
+ clientSecret: entry.clientSecret,
92761
+ redirectUri
92762
+ });
92763
+ try {
92764
+ const started = Date.now();
92765
+ const token = await this.ensureAccessToken(id, { forceRefresh: true });
92766
+ if (token.trim().length === 0) return {
92767
+ ok: false,
92768
+ error: "No access token after refresh — Sign out and Sign in again"
92769
+ };
92770
+ let res = await fetch(GOOGLE_CALENDAR_LIST_URL, { headers: { Authorization: `Bearer ${token}` } });
92771
+ if (res.status === 401) {
92772
+ const retryToken = await this.ensureAccessToken(id, { forceRefresh: true });
92773
+ res = await fetch(GOOGLE_CALENDAR_LIST_URL, { headers: { Authorization: `Bearer ${retryToken}` } });
92774
+ }
92775
+ if (!res.ok) {
92776
+ const text = await res.text();
92777
+ return {
92778
+ ok: false,
92779
+ error: `Google Calendar probe failed (${res.status}): ${text.slice(0, 200)}`
92780
+ };
92781
+ }
92782
+ const email = await this.fetchAccountEmail(token);
92783
+ if (email.length > 0) {
92784
+ const oauth = this.registry.getOauth(id);
92785
+ if (oauth !== null && oauth.accountEmail !== email) {
92786
+ this.registry.setOauth({
92787
+ ...oauth,
92788
+ accountEmail: email
92789
+ });
92790
+ await this.persistOauthAccounts();
92791
+ }
92792
+ }
92793
+ return {
92794
+ ok: true,
92795
+ latencyMs: Date.now() - started
92796
+ };
92797
+ } catch (err) {
92798
+ return {
92799
+ ok: false,
92800
+ error: err instanceof Error ? err.message : String(err)
92801
+ };
92802
+ }
92803
+ }
92804
+ /** Probe an OAuth client that is not saved yet. */
92805
+ async probeOauthClient(clientId, clientSecret) {
92806
+ try {
92807
+ const parsed = object({
92808
+ clientId: string().min(1),
92809
+ clientSecret: string().min(1).meta({ secret: true })
92810
+ }).parse({
92811
+ clientId,
92812
+ clientSecret
92813
+ });
92814
+ const redirectUri = await this.resolveRedirectUri();
92815
+ return probeGoogleOauthClient({
92816
+ clientId: parsed.clientId,
92817
+ clientSecret: parsed.clientSecret,
92818
+ redirectUri
92819
+ });
92820
+ } catch (err) {
92821
+ return {
92822
+ ok: false,
92823
+ error: err instanceof Error ? err.message : String(err)
92824
+ };
92825
+ }
92826
+ }
92774
92827
  async handleStart(req, reply) {
92775
92828
  const brokerIdRaw = req.query["brokerId"];
92776
92829
  const brokerId = typeof brokerIdRaw === "string" ? brokerIdRaw.trim() : "";