@camstack/addon-export-google 0.1.121 → 0.1.122

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.
@@ -5913,7 +5913,7 @@ var ZodIssueCode = {
5913
5913
  var ZodFirstPartyTypeKind;
5914
5914
  ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {});
5915
5915
  //#endregion
5916
- //#region ../types/dist/sleep-B-vp7x15.mjs
5916
+ //#region ../types/dist/sleep-Bei295Bz.mjs
5917
5917
  /**
5918
5918
  * The audio chunk plane's byte format, and the ONE expansion from a coded
5919
5919
  * window to float samples (D455).
@@ -6429,6 +6429,53 @@ function emitReadiness(bus, params) {
6429
6429
  ts
6430
6430
  }));
6431
6431
  }
6432
+ /** Why a catalogue entry is not a runnable body of its declared kind. */
6433
+ var AddonMigrationDefinitionError = class extends Error {
6434
+ id;
6435
+ constructor(id, message) {
6436
+ super(`${id}: ${message}`);
6437
+ this.id = id;
6438
+ this.name = "AddonMigrationDefinitionError";
6439
+ }
6440
+ };
6441
+ /**
6442
+ * Bind a catalogue to the addon's ports. Throws {@link AddonMigrationDefinitionError} when
6443
+ * an entry's `bodyKind` does not match the body it carries, or is `sql` (a hub-only
6444
+ * body). A throwing body never escapes `execute`: it is reported as a failed result.
6445
+ */
6446
+ function defineAddonMigrations(catalogue, ports) {
6447
+ return catalogue.map((entry) => {
6448
+ const { meta } = entry;
6449
+ if ("plan" in entry) {
6450
+ if (meta.bodyKind !== "plan") throw new AddonMigrationDefinitionError(meta.id, `carries a plan body but declares "${meta.bodyKind}"`);
6451
+ return {
6452
+ meta,
6453
+ execute: () => guarded(async () => ({
6454
+ kind: "plan",
6455
+ plan: await entry.plan(ports)
6456
+ }))
6457
+ };
6458
+ }
6459
+ if (meta.bodyKind !== "procedure") throw new AddonMigrationDefinitionError(meta.id, `carries a procedure body but declares "${meta.bodyKind}"`);
6460
+ return {
6461
+ meta,
6462
+ execute: () => guarded(async () => ({
6463
+ kind: "procedure",
6464
+ result: await entry.procedure(ports)
6465
+ }))
6466
+ };
6467
+ });
6468
+ }
6469
+ async function guarded(work) {
6470
+ try {
6471
+ return await work();
6472
+ } catch (err) {
6473
+ return {
6474
+ kind: "failed",
6475
+ error: errMsg$1(err)
6476
+ };
6477
+ }
6478
+ }
6432
6479
  var NOT_RUN = {
6433
6480
  declared: false,
6434
6481
  snapshot: null,
@@ -9269,28 +9316,6 @@ var PipelineRunResultBridge = custom();
9269
9316
  var StaticDirOutputSchema = object({ staticDir: string() });
9270
9317
  var VersionOutputSchema = object({ version: string() });
9271
9318
  method(_void(), StaticDirOutputSchema, { auth: "admin" }), method(_void(), VersionOutputSchema, { auth: "admin" });
9272
- /**
9273
- * Identity — preserves literal types for downstream inference.
9274
- *
9275
- * The constraint is `Record<string, unknown>` (not `CustomActionsSpec`) so
9276
- * TypeScript does not widen each entry's literal `kind`/`auth` fields to
9277
- * the broader unions declared on `CustomActionSpec`'s default generics.
9278
- * Shape validity is enforced separately by the `customAction(...)` helper
9279
- * whose return type is already a `CustomActionSpec<...>`.
9280
- */
9281
- function defineCustomActions(spec) {
9282
- return spec;
9283
- }
9284
- function customAction(input, output, options) {
9285
- return {
9286
- input,
9287
- output,
9288
- kind: options?.kind ?? "query",
9289
- auth: options?.auth ?? "protected",
9290
- scope: options?.scope ?? { kind: "system" },
9291
- ...options?.caller ? { caller: "required" } : {}
9292
- };
9293
- }
9294
9319
  Object.freeze({ "doorbell": "lastPressedAt" });
9295
9320
  /** Every capability name, so addon code can check a name without the schema graph. */
9296
9321
  var CAP_NAMES = Object.freeze([
@@ -13739,6 +13764,16 @@ var MigrationPlanSchema = object({ edits: array(discriminatedUnion("op", [
13739
13764
  precondition: PreconditionSchema
13740
13765
  })
13741
13766
  ])) });
13767
+ /** `JSON.stringify` with object keys sorted, so equal values spell the same. */
13768
+ function canonicalJson(value) {
13769
+ if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item)).join(",")}]`;
13770
+ if (typeof value === "object" && value !== null) return `{${Object.entries(value).filter(([, item]) => item !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => `${JSON.stringify(key)}:${canonicalJson(item)}`).join(",")}}`;
13771
+ return JSON.stringify(value) ?? "null";
13772
+ }
13773
+ /** The precondition string for a value a plan read (`null` when it read nothing). */
13774
+ function preconditionOf(value) {
13775
+ return canonicalJson(value ?? null);
13776
+ }
13742
13777
  /**
13743
13778
  * What a `procedure` body reports. `already-done` means the rerun observed the
13744
13779
  * work finished (a crash between the work and the ledger row, or a manual fix)
@@ -15687,8 +15722,18 @@ var LogChannelDescriptorSchema = object({
15687
15722
  * the operator narrows to one camera, sees nothing, and concludes the code
15688
15723
  * path was never taken.
15689
15724
  */
15690
- perDevice: boolean()
15691
- });
15725
+ perDevice: boolean(),
15726
+ /**
15727
+ * What the channel is FOR, so the UI can list the channels an addon offers.
15728
+ *
15729
+ * - `diagnostic` (the default): a per-component diagnostic armed from the
15730
+ * Levels page, emitted at its declared level.
15731
+ * - `debug`: a `debug.<channel>` dump watched live for a short window
15732
+ * (`ctx.debug`). Always per-device, and its lines are denied by the log
15733
+ * ring unless somebody is watching that device.
15734
+ */
15735
+ kind: _enum(["diagnostic", "debug"]).default("diagnostic")
15736
+ }).refine((d) => d.kind !== "debug" || d.name.startsWith("debug.") && d.perDevice, { message: "a debug channel is named debug.<channel> and is per-device" });
15692
15737
  /**
15693
15738
  * An armed window over one channel, as the document hands it to a mirror.
15694
15739
  *
@@ -49517,6 +49562,45 @@ method(_void(), _void(), { kind: "mutation" }), method(_void(), _void(), { kind:
49517
49562
  auth: "admin"
49518
49563
  });
49519
49564
  /**
49565
+ * What the passive listener of `local-network` saw on the wire, before any
49566
+ * provider classified it. Device-manager turns an observation into the hits
49567
+ * of the providers whose declared discovery modes it matches.
49568
+ */
49569
+ var DiscoveryObservationSchema = discriminatedUnion("kind", [object({
49570
+ kind: literal("mdns"),
49571
+ /** Normalised DNS-SD service type, e.g. `_esphomelib._tcp`. */
49572
+ serviceType: string(),
49573
+ instance: string(),
49574
+ host: string(),
49575
+ /** The A record address when the announcement carried one. */
49576
+ address: string().nullable(),
49577
+ port: number().int(),
49578
+ txt: record(string(), string())
49579
+ }), object({
49580
+ kind: literal("ssdp"),
49581
+ /** Sender address of the datagram. */
49582
+ host: string(),
49583
+ port: number().int(),
49584
+ /** `NT` of a NOTIFY, `ST` of a search response. */
49585
+ target: string(),
49586
+ headers: record(string(), string())
49587
+ })]);
49588
+ object({
49589
+ addonId: string(),
49590
+ candidate: DiscoveryCandidateSchema,
49591
+ firstSeenAt: number(),
49592
+ lastSeenAt: number(),
49593
+ dismissed: boolean()
49594
+ });
49595
+ var DiscoveryProposalSchema = object({
49596
+ id: string(),
49597
+ addonId: string(),
49598
+ candidate: DiscoveryCandidateSchema,
49599
+ firstSeenAt: number(),
49600
+ lastSeenAt: number(),
49601
+ dismissed: boolean()
49602
+ });
49603
+ /**
49520
49604
  * Device Manager capability — hub-side singleton that unifies device persistence,
49521
49605
  * live registry access, and all management operations into a single tRPC surface.
49522
49606
  *
@@ -50245,6 +50329,19 @@ method(object({
50245
50329
  }), object({ candidates: array(DiscoveryCandidateSchema).readonly() }), {
50246
50330
  kind: "mutation",
50247
50331
  auth: "admin"
50332
+ }), method(object({}), object({ proposals: array(DiscoveryProposalSchema).readonly() }), { auth: "admin" }), method(object({ id: string() }), object({ dismissed: boolean() }), {
50333
+ kind: "mutation",
50334
+ auth: "admin"
50335
+ }), method(object({ observations: array(DiscoveryObservationSchema).max(512) }), object({ proposed: number().int() }), {
50336
+ kind: "mutation",
50337
+ auth: "admin"
50338
+ }), method(object({}), object({
50339
+ providers: number().int(),
50340
+ proposed: number().int()
50341
+ }), {
50342
+ kind: "mutation",
50343
+ auth: "admin",
50344
+ timeoutMs: 12e4
50248
50345
  }), method(object({ addonId: string() }), object({ deviceType: _enum(DeviceType).nullable() }), { auth: "admin" }), method(object({ addonId: string() }), unknown(), { auth: "admin" }), method(object({
50249
50346
  deviceId: number(),
50250
50347
  key: string(),
@@ -72054,6 +72151,40 @@ var LoggingSettingsStateSchema = object({
72054
72151
  opsLogRetentionDays: number().int().min(0),
72055
72152
  persisted: boolean()
72056
72153
  });
72154
+ /**
72155
+ * Debug WATCH — a short, per-device window over `debug.<channel>` lines.
72156
+ *
72157
+ * `start` opens (or re-arms) a 10 minute window; `rearm` extends a LIVE one
72158
+ * and never revives a lapsed one; `stop` closes it; `list` only reads. No
72159
+ * chain of re-arms outlives 60 minutes from the first start. The hub holds the
72160
+ * watches in memory and pushes the interest to every node, so a watch lapses
72161
+ * by itself and survives nothing — a restart is a stop.
72162
+ */
72163
+ var DebugWatchInputSchema = object({
72164
+ action: _enum([
72165
+ "list",
72166
+ "start",
72167
+ "rearm",
72168
+ "stop"
72169
+ ]),
72170
+ /** Full channel names, `debug.<channel>`, each declared with `kind: 'debug'`. */
72171
+ channels: array(string().min(1)).readonly().default([]),
72172
+ /** Numeric device ids. Required (non-empty) for `start`. */
72173
+ deviceIds: array(number().int()).readonly().default([])
72174
+ });
72175
+ var DebugWatchStateSchema = object({
72176
+ channel: string(),
72177
+ deviceIds: array(number().int()).readonly(),
72178
+ startedAtMs: number(),
72179
+ untilMs: number(),
72180
+ capAtMs: number()
72181
+ });
72182
+ var DebugWatchResultSchema = object({
72183
+ nowMs: number(),
72184
+ watches: array(DebugWatchStateSchema).readonly(),
72185
+ /** Channels a `rearm` found already lapsed: nothing was revived. */
72186
+ lapsed: array(string()).readonly()
72187
+ });
72057
72188
  method(_void(), SystemInfoSchema), method(_void(), HealthStatusSchema), method(_void(), FeatureManifestSchema), method(_void(), array(NetworkAddressSchema).readonly()), method(_void(), unknown().nullable(), { auth: "admin" }), method(record(string(), unknown()), _null(), {
72058
72189
  kind: "mutation",
72059
72190
  auth: "admin"
@@ -72069,6 +72200,9 @@ method(_void(), SystemInfoSchema), method(_void(), HealthStatusSchema), method(_
72069
72200
  }), method(_void(), RequestCensusStatusSchema, { auth: "admin" }), method(_void(), array(ReportedLoadContributionSchema).readonly(), { auth: "admin" }), method(_void(), array(ReportedFailureContributionSchema).readonly(), { auth: "admin" }), method(GetLoggingSettingsInputSchema, LoggingSettingsStateSchema, { auth: "admin" }), method(SetLoggingSettingsInputSchema, LoggingSettingsStateSchema, {
72070
72201
  kind: "mutation",
72071
72202
  auth: "admin"
72203
+ }), method(DebugWatchInputSchema, DebugWatchResultSchema, {
72204
+ kind: "mutation",
72205
+ auth: "admin"
72072
72206
  });
72073
72207
  object({
72074
72208
  /** True when the device's tamper switch / case-open contact is
@@ -76942,6 +77076,13 @@ Object.freeze({
76942
77076
  access: "view",
76943
77077
  role: "admin"
76944
77078
  },
77079
+ "deviceManager.dismissDiscoveryProposal": {
77080
+ capName: "device-manager",
77081
+ capScope: "system",
77082
+ addonId: null,
77083
+ access: "create",
77084
+ role: "admin"
77085
+ },
76945
77086
  "deviceManager.enable": {
76946
77087
  capName: "device-manager",
76947
77088
  capScope: "system",
@@ -77124,6 +77265,13 @@ Object.freeze({
77124
77265
  access: "view",
77125
77266
  role: "viewer"
77126
77267
  },
77268
+ "deviceManager.listDiscoveryProposals": {
77269
+ capName: "device-manager",
77270
+ capScope: "system",
77271
+ addonId: null,
77272
+ access: "view",
77273
+ role: "admin"
77274
+ },
77127
77275
  "deviceManager.listLocationDescriptions": {
77128
77276
  capName: "device-manager",
77129
77277
  capScope: "system",
@@ -77278,6 +77426,13 @@ Object.freeze({
77278
77426
  access: "create",
77279
77427
  role: "admin"
77280
77428
  },
77429
+ "deviceManager.reportDiscoveryObservations": {
77430
+ capName: "device-manager",
77431
+ capScope: "system",
77432
+ addonId: null,
77433
+ access: "create",
77434
+ role: "admin"
77435
+ },
77281
77436
  "deviceManager.runDeviceAction": {
77282
77437
  capName: "device-manager",
77283
77438
  capScope: "system",
@@ -77285,6 +77440,13 @@ Object.freeze({
77285
77440
  access: "create",
77286
77441
  role: "admin"
77287
77442
  },
77443
+ "deviceManager.runDiscoverySweep": {
77444
+ capName: "device-manager",
77445
+ capScope: "system",
77446
+ addonId: null,
77447
+ access: "create",
77448
+ role: "admin"
77449
+ },
77288
77450
  "deviceManager.setChildLayout": {
77289
77451
  capName: "device-manager",
77290
77452
  capScope: "system",
@@ -83872,6 +84034,13 @@ Object.freeze({
83872
84034
  access: "create",
83873
84035
  role: "viewer"
83874
84036
  },
84037
+ "system.debugWatch": {
84038
+ capName: "system",
84039
+ capScope: "system",
84040
+ addonId: null,
84041
+ access: "create",
84042
+ role: "admin"
84043
+ },
83875
84044
  "system.detectSiteLocation": {
83876
84045
  capName: "system",
83877
84046
  capScope: "system",
@@ -87815,6 +87984,11 @@ Object.freeze({
87815
87984
  form: "single",
87816
87985
  optional: false
87817
87986
  }],
87987
+ "system.debugWatch": [{
87988
+ name: "deviceIds",
87989
+ form: "array",
87990
+ optional: true
87991
+ }],
87818
87992
  "tamper.getStatus": [{
87819
87993
  name: "deviceId",
87820
87994
  form: "single",
@@ -89707,38 +89881,6 @@ var ActionSceneExports = class {
89707
89881
  }
89708
89882
  };
89709
89883
  //#endregion
89710
- //#region src/custom-actions.ts
89711
- /**
89712
- * Google Home Export — customActions catalog.
89713
- *
89714
- * One entry. The settings form's `addon-action-button` dispatches through the
89715
- * generic `api.addons.custom.mutate({ addonId, action, input })` channel and
89716
- * shows the result under the button, so a button here costs no capability, no
89717
- * codegen and no framework publish train — the catalog travels inside this
89718
- * addon's own bundle. Admin-only: it writes this addon's settings.
89719
- */
89720
- var exportGoogleActions = defineCustomActions({
89721
- /**
89722
- * Re-scan the connected `network-access` providers and refresh the address
89723
- * shown under the field.
89724
- *
89725
- * Deliberately NOT the same contract as `export-alexa`'s action of the same
89726
- * shape: that one replaces a manual override when it is no longer detected,
89727
- * because Alexa ROUTES on the value. Nothing routes on this one — it is what
89728
- * the operator already pasted into Google's console — so this only fills the
89729
- * field when it is empty. `filled` says whether it did.
89730
- */
89731
- detectPublicHubUrl: customAction(object({}).optional(), object({
89732
- publicHubUrl: string(),
89733
- detectedPublicHubUrl: string(),
89734
- filled: boolean(),
89735
- /** One sentence saying what happened, for the button. */
89736
- summary: string()
89737
- }), {
89738
- kind: "mutation",
89739
- auth: "admin"
89740
- }) });
89741
- //#endregion
89742
89884
  //#region src/google-home/trait-catalog.ts
89743
89885
  /**
89744
89886
  * The trait catalog — one ROW per camstack capability, and that row is the
@@ -90535,217 +90677,93 @@ function buildGoogleOauthIntegration() {
90535
90677
  };
90536
90678
  }
90537
90679
  //#endregion
90538
- //#region src/public-hub-url.ts
90539
- /**
90540
- * The hub's public HTTPS origin — detected, never invented.
90541
- *
90542
- * `publicHubUrl` is the single operator-facing value in this addon, and the
90543
- * three URLs pasted into the Google Home Developer Console (fulfillment,
90544
- * authorization, token) are all rendered from it. Nothing ROUTES on it: Google
90545
- * calls the fulfillment URL it was configured with. A wrong value therefore
90546
- * fails at paste time, in the console, hours before anything here notices —
90547
- * which is exactly why the field has to say where its content came from.
90548
- *
90549
- * ## Where the URL comes from
90550
- *
90551
- * The `network-access` capability, same source `addon-export-alexa` uses. It is
90552
- * a codegen'd collection cap with `scope: 'system'`, so it is reachable
90553
- * cross-process through `ctx.api` — unlike the `addons` core router, which a
90554
- * forked addon calling `ctx.api.addons.*` would wait on forever.
90555
- *
90556
- * **Not** the hub's own address from `local-network` (`getAddresses().roles`). That
90557
- * answers a different question — which address an agent or a browser on the
90558
- * LAN reaches — and it is routinely a LAN address; the backend's
90559
- * `publicHubUrl()` fallback is localhost in dev. Google calls from its own
90560
- * cloud, so a LAN answer here is worse than no answer — it produces three
90561
- * console URLs that look complete and can never be reached.
90562
- *
90563
- * ## Why this is a second copy of Alexa's mechanism
90564
- *
90565
- * Alexa's lives in `packages/addon-export-alexa/src/export-alexa.addon.ts` as
90566
- * private methods, and addons never import each other. The only shared home
90567
- * would be `@camstack/types` or `@camstack/server/system` — both stay host-resolved in
90568
- * an addon bundle (`tools/build/vite-lib.preset.ts`), so putting it there would
90569
- * put this addon on the framework publish train and destroy the one property
90570
- * that makes it attractive: `camstack deploy packages/addon-export-google` and
90571
- * nothing else. The SOURCE and the POLICY are Alexa's; two behaviours diverge
90572
- * on purpose and both are named below.
90573
- *
90574
- * ## Two deliberate divergences from Alexa
90575
- *
90576
- * 1. **Refresh never clobbers.** Alexa's `redetectPublicHubUrl` replaces a
90577
- * manual override whenever it is not among the detected endpoints — sound
90578
- * there, because the URL is baked into every Alexa-bound JWT as a routing
90579
- * claim and a stale one breaks routing. Here the value is what the operator
90580
- * already pasted into Google's console; silently rewriting it would leave
90581
- * the console and the hub disagreeing with no visible cause. Detection fills
90582
- * an EMPTY field and does nothing else.
90583
- * 2. **A non-routable origin is dropped.** Alexa forwards whatever the cap
90584
- * reports. See {@link isPubliclyRoutableOrigin}.
90585
- */
90586
- /** Trailing slashes off, surrounding space off. Nothing else is rewritten. */
90587
- var normalisePublicHubUrl = (raw) => raw.trim().replace(/\/+$/, "");
90588
- var LOOPBACK_HOSTS = [
90589
- "localhost",
90590
- "127.0.0.1",
90591
- "::1",
90592
- "[::1]",
90593
- "0.0.0.0"
90594
- ];
90595
- /**
90596
- * Whether Google's cloud could plausibly reach this origin.
90597
- *
90598
- * The `network-access` providers this hub ships (Cloudflare Tunnel, Tailscale
90599
- * Funnel) publish public FQDNs, but the cap does not promise it: a provider is
90600
- * free to report an HTTPS ingress on a private address. Defaulting the field to
90601
- * one of those would hand the operator three console URLs that look finished
90602
- * and can never answer — strictly worse than an empty field, because an empty
90603
- * field is visibly unfinished.
90604
- *
90605
- * Conservative on purpose: only loopback, RFC1918, link-local, `.local` and
90606
- * dotless hostnames are refused. A public tunnel hostname always has a dot.
90607
- */
90608
- var isPubliclyRoutableOrigin = (origin) => {
90609
- let host;
90610
- try {
90611
- host = new URL(origin).hostname.toLowerCase();
90612
- } catch {
90613
- return false;
90614
- }
90615
- if (host.length === 0) return false;
90616
- if (LOOPBACK_HOSTS.includes(host)) return false;
90617
- if (host.startsWith("127.") || host.startsWith("169.254.")) return false;
90618
- if (host.startsWith("10.") || host.startsWith("192.168.")) return false;
90619
- if (/^172\.(1[6-9]|2\d|3[01])\./.test(host)) return false;
90620
- if (host.endsWith(".local") || host.endsWith(".internal") || host.endsWith(".lan")) return false;
90621
- if (!host.includes(".")) return false;
90622
- return true;
90623
- };
90624
- /**
90625
- * Every publicly routable HTTPS origin the `network-access` cap reports, in the
90626
- * cap's own order, deduped. Empty when there is none — the caller leaves the
90627
- * field alone rather than inventing a value.
90628
- */
90629
- var detectPublicHubOrigins = async (deps) => {
90630
- const fromList = await originsFromListEndpoints(deps);
90631
- if (fromList.length > 0) return fromList;
90632
- const fromStatus = await originFromGetStatus(deps);
90633
- if (fromStatus.length > 0) return [fromStatus];
90634
- deps.logger.warn("export-google: no connected HTTPS external address — the public hub URL cannot be derived, so the Google console URLs stay unrendered. Set up remote access (Cloudflare Tunnel, Tailscale Funnel, …) and press \"Detect external address\", or type the URL on the settings form.");
90635
- return [];
90636
- };
90637
- var usableOrigins = (candidates, logger) => {
90638
- const out = /* @__PURE__ */ new Set();
90639
- for (const candidate of candidates) {
90640
- if (candidate.protocol !== "https" || candidate.url.length === 0) continue;
90641
- const origin = normalisePublicHubUrl(candidate.url);
90642
- if (!isPubliclyRoutableOrigin(origin)) {
90643
- logger.info("export-google: ignored an external address that is not reachable from the internet — Google calls the fulfillment URL from its own cloud", { meta: { origin } });
90644
- continue;
90645
- }
90646
- out.add(origin);
90647
- }
90648
- return [...out];
90649
- };
90650
- var originsFromListEndpoints = async (deps) => {
90651
- try {
90652
- return usableOrigins(await deps.network.listEndpoints(), deps.logger);
90653
- } catch (err) {
90654
- deps.logger.debug("export-google: networkAccess.listEndpoints failed", { meta: { error: errMsg$1(err) } });
90655
- return [];
90656
- }
90657
- };
90658
- var originFromGetStatus = async (deps) => {
90659
- try {
90660
- const status = await deps.network.getStatus();
90661
- if (status === null || !status.connected || status.endpoint === null) return "";
90662
- return usableOrigins([status.endpoint], deps.logger)[0] ?? "";
90663
- } catch (err) {
90664
- deps.logger.debug("export-google: networkAccess.getStatus failed", { meta: { error: errMsg$1(err) } });
90665
- return "";
90666
- }
90680
+ //#region src/migrations/drop-public-hub-url.ts
90681
+ /**
90682
+ * The hub's public URL is no longer a setting of this addon (D986 §5): Google reads the
90683
+ * `publicEndpoint` role of the local-network palette on every use. The two keys older
90684
+ * versions persisted are deleted. Every other key is left exactly as stored.
90685
+ *
90686
+ * Idempotent: a store without either key yields an empty plan, which writes nothing.
90687
+ */
90688
+ /** The settings scope of this addon (`<addonId>:addon-settings`). */
90689
+ var GOOGLE_SETTINGS_SCOPE = "export-google:addon-settings";
90690
+ var RETIRED_PUBLIC_URL_KEYS = ["publicHubUrl", "detectedPublicHubUrl"];
90691
+ async function planDropPublicHubUrl(ports) {
90692
+ const stored = await ports.readStored();
90693
+ const present = RETIRED_PUBLIC_URL_KEYS.filter((key) => key in stored);
90694
+ if (present.length === 0) return { edits: [] };
90695
+ return { edits: [{
90696
+ op: "deleteKeys",
90697
+ scope: GOOGLE_SETTINGS_SCOPE,
90698
+ keys: [...present],
90699
+ precondition: preconditionOf(Object.fromEntries(present.map((key) => [key, stored[key]])))
90700
+ }] };
90701
+ }
90702
+ //#endregion
90703
+ //#region src/migrations/index.ts
90704
+ /** The `export-google` catalogue (D987): offered to the engine when the addon initialises. */
90705
+ var ADDON_MIGRATIONS = [{
90706
+ meta: {
90707
+ id: "export-google/2026-11-02-drop-public-hub-url",
90708
+ owner: "export-google",
90709
+ level: "addon-state",
90710
+ seq: 1,
90711
+ dependsOn: [],
90712
+ store: "settings",
90713
+ scope: "cluster",
90714
+ onFailure: "tolerate",
90715
+ bodyKind: "plan",
90716
+ description: "Delete the retired publicHubUrl and detectedPublicHubUrl settings; the public URL is the publicEndpoint role",
90717
+ fixtureMark: "the exposed device list the migration does not know"
90718
+ },
90719
+ plan: planDropPublicHubUrl
90720
+ }];
90721
+ //#endregion
90722
+ //#region src/public-endpoint.ts
90723
+ /** The typed refusal when the role resolves to nothing. */
90724
+ var NO_PUBLIC_ENDPOINT_REASON = {
90725
+ code: "no-public-endpoint",
90726
+ message: "The hub has no public endpoint. Set up remote access (a tunnel) and flag an address as \"Public endpoint\" on the Network page; Google calls this hub from its own cloud."
90667
90727
  };
90668
- /**
90669
- * Apply the default-not-override policy.
90670
- *
90671
- * The operator's value is never in the returned patch. Detection's own answer
90672
- * always is, because the settings panel needs it to say "you set this one, and
90673
- * a different one is detected".
90674
- */
90675
- var resolvePublicHubUrl = (current, detected) => {
90676
- const detectedPublicHubUrl = detected[0] ?? "";
90677
- if (current.length > 0) return {
90678
- patch: { detectedPublicHubUrl },
90679
- publicHubUrl: current,
90680
- detectedPublicHubUrl,
90681
- defaulted: false
90682
- };
90683
- if (detectedPublicHubUrl.length === 0) return {
90684
- patch: { detectedPublicHubUrl },
90685
- publicHubUrl: "",
90686
- detectedPublicHubUrl,
90687
- defaulted: false
90728
+ /** Trailing slashes off, surrounding space off. Nothing else is rewritten. */
90729
+ var normaliseOrigin = (raw) => raw.trim().replace(/\/+$/, "");
90730
+ var resolvePublicEndpoint = (book) => {
90731
+ const resolved = book.roles.publicEndpoint.resolved;
90732
+ const origin = resolved === null ? "" : normaliseOrigin(resolved);
90733
+ if (origin.length === 0) return {
90734
+ ok: false,
90735
+ reason: NO_PUBLIC_ENDPOINT_REASON
90688
90736
  };
90689
90737
  return {
90690
- patch: {
90691
- publicHubUrl: detectedPublicHubUrl,
90692
- detectedPublicHubUrl
90693
- },
90694
- publicHubUrl: detectedPublicHubUrl,
90695
- detectedPublicHubUrl,
90696
- defaulted: true
90738
+ ok: true,
90739
+ origin
90697
90740
  };
90698
90741
  };
90699
- /** Which of the two authored the value currently in the field. */
90700
- var publicHubUrlSource = (state) => {
90701
- if (state.publicHubUrl.length === 0) return "unset";
90702
- if (state.detectedPublicHubUrl.length > 0 && state.publicHubUrl === state.detectedPublicHubUrl) return "derived";
90703
- return "operator-set";
90704
- };
90705
- /**
90706
- * The line under the field. A URL that appeared by itself with no provenance is
90707
- * worse than a blank field: the operator cannot tell whether it is right.
90708
- */
90709
- var buildPublicHubUrlNotice = (state) => {
90710
- switch (publicHubUrlSource(state)) {
90711
- case "derived": return {
90712
- variant: "info",
90713
- content: `Derived from remote access — ${state.publicHubUrl} is the first HTTPS address the network-access capability reports. Edit the field to override it; nothing here ever overwrites a value you set.`
90714
- };
90715
- case "operator-set": return {
90716
- variant: "info",
90717
- content: state.detectedPublicHubUrl.length > 0 ? `Set by you — ${state.publicHubUrl}. The address currently detected from remote access is ${state.detectedPublicHubUrl}; paste it in yourself if you want to switch, detection will not do it for you.` : `Set by you — ${state.publicHubUrl}. No external HTTPS address is detected right now, so nothing is corroborating it.`
90718
- };
90719
- case "unset": return state.detectedPublicHubUrl.length > 0 ? {
90720
- variant: "info",
90721
- content: `Detected external address: ${state.detectedPublicHubUrl}. Press "Detect external address" to fill the field with it.`
90722
- } : {
90723
- variant: "warning",
90724
- content: "No public HTTPS address detected — no network-access provider on this hub reports a connected HTTPS endpoint, so there is nothing to derive from. Set up remote access (Cloudflare Tunnel, Tailscale Funnel, …) and press \"Detect external address\", or type the URL yourself. An address on your own network will not do: Google calls this URL from its own cloud."
90725
- };
90726
- }
90727
- };
90728
90742
  /**
90729
90743
  * The `device-export` setup block: the three console URLs plus the
90730
- * linked-account count. All three come off the SAME origin, so they can never
90731
- * disagree with each other.
90744
+ * linked-account count, all off the SAME origin so they cannot disagree.
90745
+ * A read that fails is the same refusal as a role that resolves to nothing.
90732
90746
  */
90733
- var buildConsoleSetup = (input) => {
90734
- const origin = normalisePublicHubUrl(input.publicHubUrl);
90747
+ var buildConsoleSetupFromRole = async (input) => {
90735
90748
  const linked = String(input.linkedAccounts);
90736
- if (origin.length === 0) return {
90737
- note: ["Set the public hub URL on the settings form first — every URL Google needs is derived from it.", buildPublicHubUrlNotice(input).content].join("\n"),
90749
+ const result = await input.read().then(resolvePublicEndpoint).catch(() => ({
90750
+ ok: false,
90751
+ reason: NO_PUBLIC_ENDPOINT_REASON
90752
+ }));
90753
+ if (!result.ok) return {
90754
+ note: `Refused (${result.reason.code}): ${result.reason.message}`,
90738
90755
  fields: [{
90739
90756
  label: "Linked Google accounts",
90740
90757
  value: linked
90741
90758
  }]
90742
90759
  };
90760
+ const origin = result.origin;
90743
90761
  return {
90744
90762
  note: [
90745
90763
  "In the Google Home Developer Console create a cloud-to-cloud integration, then paste these three URLs.",
90746
90764
  "The integration stays in test mode: publishing requires Google certification, which a private hub cannot obtain.",
90747
90765
  "This hub pushes nothing to Google — state is read by polling, so a change made outside the Home app appears on the next query, not instantly.",
90748
- buildPublicHubUrlNotice(input).content
90766
+ `The URLs follow the "Public endpoint" role on the Network page (${origin}).`
90749
90767
  ].join("\n"),
90750
90768
  fields: [
90751
90769
  {
@@ -90767,37 +90785,9 @@ var buildConsoleSetup = (input) => {
90767
90785
  ]
90768
90786
  };
90769
90787
  };
90770
- /**
90771
- * Detect, apply the policy, persist, and say out loud what happened.
90772
- *
90773
- * Every branch here logs: a fill names the URL it picked and the source it came
90774
- * from, and a miss that leaves the field empty says so rather than passing for
90775
- * "never ran".
90776
- */
90777
- var refreshPublicHubUrl = async (deps) => {
90778
- const detected = await deps.detect();
90779
- const resolution = resolvePublicHubUrl(deps.current().publicHubUrl, detected);
90780
- await deps.persist(resolution.patch);
90781
- if (resolution.defaulted) deps.logger.info("export-google: defaulted public hub URL to the detected external address", { meta: {
90782
- publicHubUrl: resolution.publicHubUrl,
90783
- source: "network-access"
90784
- } });
90785
- else if (resolution.publicHubUrl.length === 0) deps.logger.warn("export-google: public hub URL still unset after detection — the Google console URLs cannot be rendered until one is available", { meta: { detectedCount: detected.length } });
90786
- return resolution;
90787
- };
90788
- /** What "Detect external address" did, in one sentence for the button. */
90789
- function describeDetectResult(result) {
90790
- const { publicHubUrl, detectedPublicHubUrl, filled } = result;
90791
- if (filled) return `Filled in ${publicHubUrl}.`;
90792
- if (detectedPublicHubUrl.length === 0) return publicHubUrl.length > 0 ? `No public HTTPS address detected; your value ${publicHubUrl} was kept.` : "No public HTTPS address detected. Set up remote access first.";
90793
- if (detectedPublicHubUrl === publicHubUrl) return `Detected ${publicHubUrl}, already in use.`;
90794
- return `Detected ${detectedPublicHubUrl}; your value ${publicHubUrl} was kept.`;
90795
- }
90796
90788
  //#endregion
90797
90789
  //#region src/types.ts
90798
90790
  var DEFAULT_SETTINGS = {
90799
- publicHubUrl: "",
90800
- detectedPublicHubUrl: "",
90801
90791
  exposed: [],
90802
90792
  exposedActions: [],
90803
90793
  linkedAccounts: []
@@ -90852,9 +90842,7 @@ var ExportGoogleAddon = class extends BaseAddon {
90852
90842
  logger: this.ctx.logger
90853
90843
  });
90854
90844
  this.gateway = gateway;
90855
- this.detectPublicHubUrl().catch((err) => {
90856
- this.ctx.logger.warn("export-google: public hub URL auto-detect failed", { meta: { error: errMsg$1(err) } });
90857
- });
90845
+ await this.runMigrations(defineAddonMigrations(ADDON_MIGRATIONS, { readStored: async () => this.resolveGlobalStore() }));
90858
90846
  const actionScenes = new ActionSceneExports({
90859
90847
  api: this.ctx.api,
90860
90848
  logger: this.ctx.logger,
@@ -90870,7 +90858,7 @@ var ExportGoogleAddon = class extends BaseAddon {
90870
90858
  getStatus: async () => ({
90871
90859
  linkState: this.config.linkedAccounts.length > 0 ? "linked" : "unlinked",
90872
90860
  exposedDeviceCount: this.config.exposed.length,
90873
- setup: this.buildSetupBlock()
90861
+ setup: await this.buildSetupBlock()
90874
90862
  }),
90875
90863
  listSupportedDeviceKinds: async () => [...SUPPORTED_DEVICE_KINDS],
90876
90864
  listExposedDevices: async () => this.config.exposed.map((entry) => ({ deviceId: String(entry.deviceId) })),
@@ -90926,97 +90914,25 @@ var ExportGoogleAddon = class extends BaseAddon {
90926
90914
  }
90927
90915
  }));
90928
90916
  const oauthIntegrationProvider = { getDescriptor: async () => buildGoogleOauthIntegration() };
90929
- const offTunnelStarted = this.ctx.eventBus.subscribe({ category: EventCategory.NetworkTunnelStarted }, () => {
90930
- this.detectPublicHubUrl().catch((err) => {
90931
- this.ctx.logger.warn("export-google: public hub URL detect after tunnel connect failed", { meta: { error: errMsg$1(err) } });
90932
- });
90933
- });
90934
- this.ctx.addDisposer(async () => offTunnelStarted());
90935
90917
  this.ctx.logger.info("export-google: initialized", { meta: {
90936
90918
  exposedCount: this.config.exposed.length,
90937
90919
  linkedAccounts: this.config.linkedAccounts.length,
90938
- publicHubUrlSet: this.config.publicHubUrl.length > 0,
90939
90920
  willReportState: false
90940
90921
  } });
90941
- return {
90942
- providers: [
90943
- {
90944
- capability: deviceExportCapability,
90945
- provider: deviceExportProvider
90946
- },
90947
- {
90948
- capability: addonRoutesCapability,
90949
- provider: routeProvider
90950
- },
90951
- {
90952
- capability: oauthIntegrationCapability,
90953
- provider: oauthIntegrationProvider
90954
- }
90955
- ],
90956
- customActions: exportGoogleActions,
90957
- actionHandlers: { detectPublicHubUrl: async () => this.detectPublicHubUrl() }
90958
- };
90959
- }
90960
- /** This addon's slice of `PublicHubUrlState`. */
90961
- publicHubUrlState() {
90962
- return {
90963
- publicHubUrl: this.config.publicHubUrl,
90964
- detectedPublicHubUrl: this.config.detectedPublicHubUrl
90965
- };
90966
- }
90967
- /**
90968
- * Adapter from the codegen'd `network-access` router onto the narrow reader
90969
- * `public-hub-url.ts` consumes. Fields are copied one by one rather than
90970
- * passed through, so the module never depends on the cap's wider shape and a
90971
- * test double for it needs no cast.
90972
- */
90973
- networkAccessReader() {
90974
- return {
90975
- listEndpoints: async () => {
90976
- return (await this.ctx.api.networkAccess.listEndpoints.query({})).map((entry) => ({
90977
- url: entry.url,
90978
- protocol: entry.protocol
90979
- }));
90922
+ return [
90923
+ {
90924
+ capability: deviceExportCapability,
90925
+ provider: deviceExportProvider
90980
90926
  },
90981
- getStatus: async () => {
90982
- const status = await this.ctx.api.networkAccess.getStatus.query({});
90983
- return {
90984
- connected: status.connected,
90985
- endpoint: status.endpoint === null ? null : {
90986
- url: status.endpoint.url,
90987
- protocol: status.endpoint.protocol
90988
- }
90989
- };
90927
+ {
90928
+ capability: addonRoutesCapability,
90929
+ provider: routeProvider
90930
+ },
90931
+ {
90932
+ capability: oauthIntegrationCapability,
90933
+ provider: oauthIntegrationProvider
90990
90934
  }
90991
- };
90992
- }
90993
- /**
90994
- * Refresh the detected address and DEFAULT the field to it when it is empty.
90995
- * Backs both the boot-time detect and the "Detect external address" button.
90996
- *
90997
- * Never replaces a value the operator set — that value is what they already
90998
- * pasted into the Google console, and rewriting it here would leave the two
90999
- * sides disagreeing with nothing on screen to say so.
91000
- */
91001
- async detectPublicHubUrl() {
91002
- const resolution = await refreshPublicHubUrl({
91003
- current: () => this.publicHubUrlState(),
91004
- detect: () => detectPublicHubOrigins({
91005
- network: this.networkAccessReader(),
91006
- logger: this.ctx.logger
91007
- }),
91008
- persist: (patch) => this.updateGlobalSettings(patch),
91009
- logger: this.ctx.logger
91010
- });
91011
- const result = {
91012
- publicHubUrl: resolution.publicHubUrl,
91013
- detectedPublicHubUrl: resolution.detectedPublicHubUrl,
91014
- filled: resolution.defaulted
91015
- };
91016
- return {
91017
- ...result,
91018
- summary: describeDetectResult(result)
91019
- };
90935
+ ];
91020
90936
  }
91021
90937
  async onShutdown() {
91022
90938
  this.gateway = null;
@@ -91085,11 +91001,11 @@ var ExportGoogleAddon = class extends BaseAddon {
91085
91001
  * value still travels in the `getStatus` response — so it would be the wrong
91086
91002
  * tool for a real credential anyway (docs/decisions/adr-0269-a-google-export-that-holds-no-google-credential.md).
91087
91003
  */
91088
- buildSetupBlock() {
91089
- return buildConsoleSetup({
91004
+ async buildSetupBlock() {
91005
+ return buildConsoleSetupFromRole({
91090
91006
  addonId: ADDON_ID,
91091
- ...this.publicHubUrlState(),
91092
- linkedAccounts: this.config.linkedAccounts.length
91007
+ linkedAccounts: this.config.linkedAccounts.length,
91008
+ read: () => this.ctx.api.localNetwork.getAddresses.query()
91093
91009
  });
91094
91010
  }
91095
91011
  globalSettingsSchema() {
@@ -91098,44 +91014,17 @@ var ExportGoogleAddon = class extends BaseAddon {
91098
91014
  title: "Connection",
91099
91015
  description: "Publishes switches, dimmable lights, locks and covers to Google Home. The hub answers Google directly — no cloud function, and no Google credential is stored here.",
91100
91016
  columns: 1,
91101
- fields: [
91102
- {
91103
- type: "info",
91104
- key: "__google-setup-banner",
91105
- label: "Setup overview",
91106
- variant: "info",
91107
- content: [
91108
- "This hub must be reachable from the public internet over HTTPS (Cloudflare Tunnel, Tailscale Funnel, …) — Google calls the fulfillment URL from its own cloud.",
91109
- "Create a cloud-to-cloud integration in the Google Home Developer Console, paste the three URLs from the Export panel, and link your account from the Home app.",
91110
- "Cameras are not exported, and state is not pushed: Google polls. Ask \"Hey Google, sync my devices\" after exposing something new."
91111
- ].join("\n")
91112
- },
91113
- this.field({
91114
- type: "text",
91115
- key: "publicHubUrl",
91116
- label: "Public hub URL",
91117
- description: "HTTPS origin Google reaches this hub on, e.g. https://hub.example.com. Used to render the URLs you paste into the Google console. Left empty, it defaults to the first external address remote access reports; once it holds a value, nothing overwrites it.",
91118
- placeholder: "https://hub.example.com",
91119
- default: DEFAULT_SETTINGS.publicHubUrl
91120
- }),
91121
- {
91122
- type: "info",
91123
- key: "__public-hub-url-source",
91124
- label: "Where this came from",
91125
- ...buildPublicHubUrlNotice(this.publicHubUrlState())
91126
- },
91127
- {
91128
- type: "addon-action-button",
91129
- addonId: ADDON_ID,
91130
- key: "__detect-public-hub-url",
91131
- label: "External address",
91132
- description: "Re-scan the connected remote-access providers. Fills the field above when it is empty; a value you set is left exactly as it is.",
91133
- buttonLabel: "Detect external address",
91134
- action: "detectPublicHubUrl",
91135
- variant: "default",
91136
- successMessage: "{summary}"
91137
- }
91138
- ]
91017
+ fields: [{
91018
+ type: "info",
91019
+ key: "__google-setup-banner",
91020
+ label: "Setup overview",
91021
+ variant: "info",
91022
+ content: [
91023
+ "This hub must be reachable from the public internet over HTTPS (Cloudflare Tunnel, Tailscale Funnel, …) — Google calls the fulfillment URL from its own cloud.",
91024
+ "Create a cloud-to-cloud integration in the Google Home Developer Console, paste the three URLs from the Export panel, and link your account from the Home app.",
91025
+ "Cameras are not exported, and state is not pushed: Google polls. Ask \"Hey Google, sync my devices\" after exposing something new."
91026
+ ].join("\n")
91027
+ }]
91139
91028
  }] });
91140
91029
  }
91141
91030
  /**