@camstack/types 1.2.565 → 1.2.566

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -31321,74 +31321,6 @@ function findVocabularyEntry(vocabulary, eventType, sourceId) {
31321
31321
  return vocabulary.find((entry) => entry.id === eventType && entry.source?.id === sourceId);
31322
31322
  }
31323
31323
  //#endregion
31324
- //#region src/automation/template-link.ts
31325
- /**
31326
- * The link an automation made FROM a template carries (#527): which template,
31327
- * the values the operator filled in, and — when the template has since changed
31328
- * so that those values no longer fit — the problems that say why.
31329
- *
31330
- * It lives inside the recipe (`AutomationRecipe.template`), so the one row in
31331
- * `core_blocks` stays the one artefact: there is no second store of instances
31332
- * to drift from the blocks, and deleting the automation deletes the link.
31333
- * "Convert to a free automation" is dropping this field.
31334
- *
31335
- * This file depends on nothing in `recipe.ts`, so the recipe can embed it and
31336
- * the template engine (`template/automation-template.ts`) can import both.
31337
- */
31338
- /** An `event` input's value: the same three narrowing lists a `device-fired` row takes. */
31339
- var TemplateEventValueSchema = zod.z.object({
31340
- eventIds: zod.z.array(zod.z.string().min(1)).min(1).max(64).optional(),
31341
- sourceIds: zod.z.array(zod.z.string().min(1)).min(1).max(64).optional(),
31342
- kinds: zod.z.array(EventVocabularyKindSchema).min(1).optional()
31343
- }).refine((value) => value.eventIds !== void 0 || value.sourceIds !== void 0 || value.kinds !== void 0, { message: "an event names at least one event, part or kind" });
31344
- /** An `action` input's value: a vocabulary action and its open args. */
31345
- var TemplateActionValueSchema = zod.z.object({
31346
- actionId: zod.z.string().min(1),
31347
- args: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
31348
- });
31349
- /** The value of one non-group input. Which member is right is the input kind's to judge. */
31350
- var TemplateScalarValueSchema = zod.z.union([
31351
- zod.z.number(),
31352
- zod.z.string(),
31353
- zod.z.boolean(),
31354
- zod.z.array(zod.z.number().int().nonnegative()),
31355
- TemplateEventValueSchema,
31356
- TemplateActionValueSchema
31357
- ]);
31358
- /** One row of a repeatable group: row-input key → value. */
31359
- var TemplateGroupRowSchema = zod.z.record(zod.z.string(), TemplateScalarValueSchema);
31360
- var TemplateInputValueSchema = zod.z.union([TemplateScalarValueSchema, zod.z.array(TemplateGroupRowSchema)]);
31361
- /** Input key → value. */
31362
- var TemplateInputValuesSchema = zod.z.record(zod.z.string(), TemplateInputValueSchema);
31363
- var TEMPLATE_INSTANCE_PROBLEM_CODES = [
31364
- "missing-input",
31365
- "invalid-input",
31366
- "invalid-recipe",
31367
- "missing-template",
31368
- "edited-by-hand"
31369
- ];
31370
- var TemplateInstanceProblemSchema = zod.z.object({
31371
- code: zod.z.enum(TEMPLATE_INSTANCE_PROBLEM_CODES),
31372
- /** Dotted input address (`buttons.2.targets`); absent for a whole-recipe problem. */
31373
- input: zod.z.string().optional(),
31374
- detail: zod.z.string()
31375
- });
31376
- var AutomationTemplateLinkSchema = zod.z.object({
31377
- templateId: zod.z.string().min(1),
31378
- values: TemplateInputValuesSchema,
31379
- /**
31380
- * Fingerprint of the generated code with this literal blanked
31381
- * (`instanceCodeHash`), stamped by `generateAutomationBlock`. Code that no
31382
- * longer matches it was edited by hand, and is never regenerated over.
31383
- */
31384
- codeHash: zod.z.string().optional(),
31385
- /**
31386
- * Present when the last re-expansion refused these values. The automation
31387
- * keeps running the body of its last good expansion; nothing is dropped.
31388
- */
31389
- problems: zod.z.array(TemplateInstanceProblemSchema).min(1).optional()
31390
- });
31391
- //#endregion
31392
31324
  //#region src/expression/binding-source.ts
31393
31325
  /**
31394
31326
  * What an expression's named bindings READ from.
@@ -31465,6 +31397,308 @@ var ExpressionSourceSchema = zod.z.object({
31465
31397
  });
31466
31398
  });
31467
31399
  //#endregion
31400
+ //#region src/time/solar.ts
31401
+ /**
31402
+ * Where the sun is, from a latitude and a longitude — the one solar
31403
+ * calculation in the repo. Compact NOAA sunrise equation (accurate to about a
31404
+ * minute away from the poles), so no astronomy dependency is needed.
31405
+ *
31406
+ * Two consumers read it: the scene-condition resolver (day / night / dawn /
31407
+ * dusk of a camera) and a schedule's sun time (`time-spec.ts`).
31408
+ */
31409
+ var DEG = Math.PI / 180;
31410
+ /** The sun's upper limb on the horizon, refraction included: sunrise and sunset. */
31411
+ var SUNRISE_ALTITUDE_DEG = -.833;
31412
+ /** The sun's centre 6 degrees below the horizon: civil dawn and civil dusk. */
31413
+ var CIVIL_TWILIGHT_ALTITUDE_DEG = -6;
31414
+ /** Julian day number for a JS Date (UTC). */
31415
+ function toJulian(date) {
31416
+ return date.getTime() / 864e5 + 2440587.5;
31417
+ }
31418
+ /** Julian day → epoch ms (UTC). */
31419
+ function fromJulian(j) {
31420
+ return (j - 2440587.5) * 864e5;
31421
+ }
31422
+ /**
31423
+ * When the sun crosses `altitudeDeg` on the day `date` falls in at this place.
31424
+ * Pass an instant near local midday of the civil day you mean: the day is
31425
+ * chosen from the instant, and midday is the one that never straddles two.
31426
+ *
31427
+ * `null` when the sun never crosses that altitude that day (polar day or polar
31428
+ * night, or — for a twilight altitude — a summer night that never gets dark
31429
+ * enough). The caller decides what that means; nothing here guesses.
31430
+ */
31431
+ function sunCrossings(lat, lng, date, altitudeDeg) {
31432
+ const jDate = toJulian(date);
31433
+ const jStar = Math.round(jDate - 2451545 + 8e-4) - lng / 360;
31434
+ const m = (357.5291 + .98560028 * jStar) % 360;
31435
+ const mRad = m * DEG;
31436
+ const lambda = (m + (1.9148 * Math.sin(mRad) + .02 * Math.sin(2 * mRad) + 3e-4 * Math.sin(3 * mRad)) + 180 + 102.9372) % 360 * DEG;
31437
+ const jTransit = 2451545 + jStar + .0053 * Math.sin(mRad) - .0069 * Math.sin(2 * lambda);
31438
+ const declination = Math.asin(Math.sin(lambda) * Math.sin(23.44 * DEG));
31439
+ const latRad = lat * DEG;
31440
+ const cosOmega = (Math.sin(altitudeDeg * DEG) - Math.sin(latRad) * Math.sin(declination)) / (Math.cos(latRad) * Math.cos(declination));
31441
+ if (cosOmega > 1 || cosOmega < -1) return null;
31442
+ const omega = Math.acos(cosOmega) / DEG;
31443
+ return {
31444
+ rise: fromJulian(jTransit - omega / 360),
31445
+ set: fromJulian(jTransit + omega / 360)
31446
+ };
31447
+ }
31448
+ /**
31449
+ * Sunrise and sunset (UTC epoch ms) for a place and date; `null` for the polar
31450
+ * cases (the sun never rises or sets that day).
31451
+ */
31452
+ function sunTimes(lat, lng, date) {
31453
+ return sunCrossings(lat, lng, date, SUNRISE_ALTITUDE_DEG);
31454
+ }
31455
+ /** Civil dawn and dusk (UTC epoch ms); `null` when the sun never gets that low or that high. */
31456
+ function twilightTimes(lat, lng, date) {
31457
+ return sunCrossings(lat, lng, date, -6);
31458
+ }
31459
+ //#endregion
31460
+ //#region src/time/time-spec.ts
31461
+ /**
31462
+ * WHEN something happens, as data (D983) — the one time vocabulary of the
31463
+ * scheduler and of an automation's schedule leaf. Three shapes, no cron:
31464
+ *
31465
+ * - `clock` — a wall-clock time every day (`07:30`), read in the site's zone;
31466
+ * - `sun` — a sun event (`sunrise`, `sunset`, `dawn`, `dusk`) plus or minus
31467
+ * up to twelve hours, from the site's coordinates;
31468
+ * - `date` — one local date and time (`2026-12-24T18:00`), once.
31469
+ *
31470
+ * A site is a place and its IANA zone ({@link TimeSite}). Every function here
31471
+ * is pure: the zone arithmetic uses `Intl`, no date library.
31472
+ *
31473
+ * Wall-clock honesty across a DST change: a local time that does not exist
31474
+ * (02:30 on the spring-forward day) happens at the first minute that does
31475
+ * (03:00); one that happens twice (02:30 on the fall-back day) happens at its
31476
+ * FIRST occurrence.
31477
+ */
31478
+ var SunEventSchema = zod.z.enum([
31479
+ "sunrise",
31480
+ "sunset",
31481
+ "dawn",
31482
+ "dusk"
31483
+ ]);
31484
+ var LOCAL_DATE = /^\d{4}-\d{2}-\d{2}$/;
31485
+ var LOCAL_DATE_TIME = /^(\d{4}-\d{2}-\d{2})T([01]\d|2[0-3]):([0-5]\d)$/;
31486
+ var TimeSpecSchema = zod.z.discriminatedUnion("kind", [
31487
+ zod.z.object({
31488
+ kind: zod.z.literal("clock"),
31489
+ hh: zod.z.number().int().min(0).max(23),
31490
+ mm: zod.z.number().int().min(0).max(59)
31491
+ }),
31492
+ zod.z.object({
31493
+ kind: zod.z.literal("sun"),
31494
+ event: SunEventSchema,
31495
+ /** Minutes after the event (negative: before). */
31496
+ offsetMin: zod.z.number().int().min(-720).max(720)
31497
+ }),
31498
+ zod.z.object({
31499
+ kind: zod.z.literal("date"),
31500
+ /** `YYYY-MM-DDTHH:mm`, site-local. */
31501
+ local: zod.z.string().regex(LOCAL_DATE_TIME, "expected YYYY-MM-DDTHH:mm")
31502
+ })
31503
+ ]);
31504
+ /** A day of the week as a schedule names it. */
31505
+ var WeekdayKeySchema = zod.z.enum([
31506
+ "mon",
31507
+ "tue",
31508
+ "wed",
31509
+ "thu",
31510
+ "fri",
31511
+ "sat",
31512
+ "sun"
31513
+ ]);
31514
+ var WEEKDAY_BY_INDEX = [
31515
+ "sun",
31516
+ "mon",
31517
+ "tue",
31518
+ "wed",
31519
+ "thu",
31520
+ "fri",
31521
+ "sat"
31522
+ ];
31523
+ var MINUTE_MS$3 = 6e4;
31524
+ var DAY_MS$1 = 864e5;
31525
+ var formatters = /* @__PURE__ */ new Map();
31526
+ function formatterFor$1(timeZone) {
31527
+ const cached = formatters.get(timeZone);
31528
+ if (cached !== void 0) return cached;
31529
+ const created = new Intl.DateTimeFormat("en-US", {
31530
+ timeZone,
31531
+ hourCycle: "h23",
31532
+ year: "numeric",
31533
+ month: "2-digit",
31534
+ day: "2-digit",
31535
+ hour: "2-digit",
31536
+ minute: "2-digit",
31537
+ second: "2-digit"
31538
+ });
31539
+ formatters.set(timeZone, created);
31540
+ return created;
31541
+ }
31542
+ function wallClockOf(epochMs, timeZone) {
31543
+ const out = {};
31544
+ for (const part of formatterFor$1(timeZone).formatToParts(new Date(epochMs))) if (part.type !== "literal") out[part.type] = Number(part.value);
31545
+ return {
31546
+ year: out["year"] ?? 0,
31547
+ month: out["month"] ?? 0,
31548
+ day: out["day"] ?? 0,
31549
+ hour: out["hour"] ?? 0,
31550
+ minute: out["minute"] ?? 0,
31551
+ second: out["second"] ?? 0
31552
+ };
31553
+ }
31554
+ /** The zone's offset from UTC at an instant, in ms (positive east of Greenwich). */
31555
+ function offsetMs(epochMs, timeZone) {
31556
+ const w = wallClockOf(epochMs, timeZone);
31557
+ return Date.UTC(w.year, w.month - 1, w.day, w.hour, w.minute, w.second) - Math.floor(epochMs / 1e3) * 1e3;
31558
+ }
31559
+ /** Is `timeZone` a zone this runtime knows? */
31560
+ function isKnownTimeZone(timeZone) {
31561
+ try {
31562
+ formatterFor$1(timeZone);
31563
+ return true;
31564
+ } catch {
31565
+ return false;
31566
+ }
31567
+ }
31568
+ /** `YYYY-MM-DD` of an instant, read in the zone. */
31569
+ function localDateOf(epochMs, timeZone) {
31570
+ const w = wallClockOf(epochMs, timeZone);
31571
+ return `${String(w.year).padStart(4, "0")}-${String(w.month).padStart(2, "0")}-${String(w.day).padStart(2, "0")}`;
31572
+ }
31573
+ function parseLocalDate(localDate) {
31574
+ if (!LOCAL_DATE.test(localDate)) throw new Error(`not a local date (YYYY-MM-DD): ${localDate}`);
31575
+ const [y, m, d] = localDate.split("-").map(Number);
31576
+ return {
31577
+ y: y ?? 0,
31578
+ m: m ?? 1,
31579
+ d: d ?? 1
31580
+ };
31581
+ }
31582
+ /** The weekday of a `YYYY-MM-DD` civil date (zone-independent). */
31583
+ function weekdayOfLocalDate(localDate) {
31584
+ const { y, m, d } = parseLocalDate(localDate);
31585
+ return WEEKDAY_BY_INDEX[new Date(Date.UTC(y, m - 1, d)).getUTCDay()] ?? "sun";
31586
+ }
31587
+ function addDays$1(localDate, days) {
31588
+ const { y, m, d } = parseLocalDate(localDate);
31589
+ return new Date(Date.UTC(y, m - 1, d + days)).toISOString().slice(0, 10);
31590
+ }
31591
+ /**
31592
+ * The instant a wall-clock time happens in a zone. A time that does not exist
31593
+ * happens at the first minute that does; one that happens twice, at its first
31594
+ * occurrence.
31595
+ */
31596
+ function wallToEpoch(localDate, hh, mm, timeZone) {
31597
+ const { y, m, d } = parseLocalDate(localDate);
31598
+ const wall = Date.UTC(y, m - 1, d, hh, mm);
31599
+ const before = offsetMs(wall - DAY_MS$1, timeZone);
31600
+ const after = offsetMs(wall + DAY_MS$1, timeZone);
31601
+ const valid = [wall - before, wall - after].filter((c) => c + offsetMs(c, timeZone) === wall);
31602
+ if (valid.length > 0) return Math.min(...valid);
31603
+ let lo = wall - DAY_MS$1;
31604
+ let hi = wall + DAY_MS$1;
31605
+ while (hi - lo > MINUTE_MS$3) {
31606
+ const mid = Math.floor((lo + hi) / 2 / MINUTE_MS$3) * MINUTE_MS$3;
31607
+ if (offsetMs(mid, timeZone) === before) lo = mid;
31608
+ else hi = mid;
31609
+ }
31610
+ return hi;
31611
+ }
31612
+ function sunEventAltitude(event) {
31613
+ return event === "sunrise" || event === "sunset" ? SUNRISE_ALTITUDE_DEG : -6;
31614
+ }
31615
+ /**
31616
+ * The moment `spec` happens on the site-local date `localDate` (`YYYY-MM-DD`).
31617
+ * See {@link Occurrence} for what `null` means.
31618
+ */
31619
+ function occurrenceOn(spec, localDate, site) {
31620
+ switch (spec.kind) {
31621
+ case "clock": return wallToEpoch(localDate, spec.hh, spec.mm, site.timeZone);
31622
+ case "date": {
31623
+ const match = LOCAL_DATE_TIME.exec(spec.local);
31624
+ if (match === null || match[1] !== localDate) return null;
31625
+ return wallToEpoch(localDate, Number(match[2]), Number(match[3]), site.timeZone);
31626
+ }
31627
+ case "sun": {
31628
+ const midday = new Date(wallToEpoch(localDate, 12, 0, site.timeZone));
31629
+ const crossings = sunCrossings(site.lat, site.lon, midday, sunEventAltitude(spec.event));
31630
+ if (crossings === null) return null;
31631
+ return (spec.event === "sunrise" || spec.event === "dawn" ? crossings.rise : crossings.set) + spec.offsetMin * MINUTE_MS$3;
31632
+ }
31633
+ }
31634
+ }
31635
+ /** How far ahead {@link nextOccurrence} looks before giving up: a polar winter fits. */
31636
+ var NEXT_OCCURRENCE_HORIZON_DAYS = 400;
31637
+ /**
31638
+ * The first moment strictly after `afterMs` at which `spec` happens, or `null`
31639
+ * when none does within {@link NEXT_OCCURRENCE_HORIZON_DAYS} (a `date` spec in
31640
+ * the past, a sun event that never happens, an empty `days` list).
31641
+ */
31642
+ function nextOccurrence(spec, afterMs, site, options = {}) {
31643
+ const days = options.days;
31644
+ if (days !== void 0 && days.length === 0) return null;
31645
+ if (spec.kind === "date") {
31646
+ const own = LOCAL_DATE_TIME.exec(spec.local)?.[1];
31647
+ if (own === void 0 || days !== void 0 && !days.includes(weekdayOfLocalDate(own))) return null;
31648
+ const at = occurrenceOn(spec, own, site);
31649
+ return at !== null && at > afterMs ? at : null;
31650
+ }
31651
+ const first = addDays$1(localDateOf(afterMs, site.timeZone), -1);
31652
+ for (let i = 0; i < 400; i += 1) {
31653
+ const localDate = addDays$1(first, i);
31654
+ if (days !== void 0 && !days.includes(weekdayOfLocalDate(localDate))) continue;
31655
+ const at = occurrenceOn(spec, localDate, site);
31656
+ if (at !== null && at > afterMs) return at;
31657
+ }
31658
+ return null;
31659
+ }
31660
+ /**
31661
+ * Can `spec` be scheduled at this site? A sun spec without a location is
31662
+ * REFUSED with its reason — never read as a guessed sunrise. A clock or date
31663
+ * spec needs only a zone, and `site` is `null` in that case when there is no
31664
+ * location (it is not needed to place them; use {@link siteFor} to read them).
31665
+ */
31666
+ function validateTimeSpecForSite(spec, reading) {
31667
+ if (!isKnownTimeZone(reading.timeZone)) return {
31668
+ ok: false,
31669
+ reason: "unknown-time-zone",
31670
+ message: `the site time zone "${reading.timeZone}" is not a known IANA zone`
31671
+ };
31672
+ const site = siteFor(reading);
31673
+ if (spec.kind === "sun" && site === null) return {
31674
+ ok: false,
31675
+ reason: "sun-needs-site-location",
31676
+ message: `a ${spec.event} time needs the site location, and none is set — set it in Settings, or use a clock time`
31677
+ };
31678
+ return {
31679
+ ok: true,
31680
+ site
31681
+ };
31682
+ }
31683
+ /** The site, when it has a location; a clock spec on a site without one uses {@link zoneOnlySite}. */
31684
+ function siteFor(reading) {
31685
+ if (reading.location === null) return null;
31686
+ return {
31687
+ lat: reading.location.latitude,
31688
+ lon: reading.location.longitude,
31689
+ timeZone: reading.timeZone
31690
+ };
31691
+ }
31692
+ /** A site that can place a clock or date spec but no sun event (coordinates are unused by those). */
31693
+ function zoneOnlySite(timeZone) {
31694
+ return {
31695
+ lat: 0,
31696
+ lon: 0,
31697
+ timeZone,
31698
+ zoneOnly: true
31699
+ };
31700
+ }
31701
+ //#endregion
31468
31702
  //#region src/device/schema-fields.ts
31469
31703
  /** Unwrap ZodNullable / ZodOptional / ZodDefault wrappers to reach the inner type.
31470
31704
  * Zod v4 exposes `.unwrap()` on all three wrapper classes. */
@@ -32438,308 +32672,6 @@ function anySubjectMatches(subjects, observed) {
32438
32672
  };
32439
32673
  }
32440
32674
  //#endregion
32441
- //#region src/time/solar.ts
32442
- /**
32443
- * Where the sun is, from a latitude and a longitude — the one solar
32444
- * calculation in the repo. Compact NOAA sunrise equation (accurate to about a
32445
- * minute away from the poles), so no astronomy dependency is needed.
32446
- *
32447
- * Two consumers read it: the scene-condition resolver (day / night / dawn /
32448
- * dusk of a camera) and a schedule's sun time (`time-spec.ts`).
32449
- */
32450
- var DEG = Math.PI / 180;
32451
- /** The sun's upper limb on the horizon, refraction included: sunrise and sunset. */
32452
- var SUNRISE_ALTITUDE_DEG = -.833;
32453
- /** The sun's centre 6 degrees below the horizon: civil dawn and civil dusk. */
32454
- var CIVIL_TWILIGHT_ALTITUDE_DEG = -6;
32455
- /** Julian day number for a JS Date (UTC). */
32456
- function toJulian(date) {
32457
- return date.getTime() / 864e5 + 2440587.5;
32458
- }
32459
- /** Julian day → epoch ms (UTC). */
32460
- function fromJulian(j) {
32461
- return (j - 2440587.5) * 864e5;
32462
- }
32463
- /**
32464
- * When the sun crosses `altitudeDeg` on the day `date` falls in at this place.
32465
- * Pass an instant near local midday of the civil day you mean: the day is
32466
- * chosen from the instant, and midday is the one that never straddles two.
32467
- *
32468
- * `null` when the sun never crosses that altitude that day (polar day or polar
32469
- * night, or — for a twilight altitude — a summer night that never gets dark
32470
- * enough). The caller decides what that means; nothing here guesses.
32471
- */
32472
- function sunCrossings(lat, lng, date, altitudeDeg) {
32473
- const jDate = toJulian(date);
32474
- const jStar = Math.round(jDate - 2451545 + 8e-4) - lng / 360;
32475
- const m = (357.5291 + .98560028 * jStar) % 360;
32476
- const mRad = m * DEG;
32477
- const lambda = (m + (1.9148 * Math.sin(mRad) + .02 * Math.sin(2 * mRad) + 3e-4 * Math.sin(3 * mRad)) + 180 + 102.9372) % 360 * DEG;
32478
- const jTransit = 2451545 + jStar + .0053 * Math.sin(mRad) - .0069 * Math.sin(2 * lambda);
32479
- const declination = Math.asin(Math.sin(lambda) * Math.sin(23.44 * DEG));
32480
- const latRad = lat * DEG;
32481
- const cosOmega = (Math.sin(altitudeDeg * DEG) - Math.sin(latRad) * Math.sin(declination)) / (Math.cos(latRad) * Math.cos(declination));
32482
- if (cosOmega > 1 || cosOmega < -1) return null;
32483
- const omega = Math.acos(cosOmega) / DEG;
32484
- return {
32485
- rise: fromJulian(jTransit - omega / 360),
32486
- set: fromJulian(jTransit + omega / 360)
32487
- };
32488
- }
32489
- /**
32490
- * Sunrise and sunset (UTC epoch ms) for a place and date; `null` for the polar
32491
- * cases (the sun never rises or sets that day).
32492
- */
32493
- function sunTimes(lat, lng, date) {
32494
- return sunCrossings(lat, lng, date, SUNRISE_ALTITUDE_DEG);
32495
- }
32496
- /** Civil dawn and dusk (UTC epoch ms); `null` when the sun never gets that low or that high. */
32497
- function twilightTimes(lat, lng, date) {
32498
- return sunCrossings(lat, lng, date, -6);
32499
- }
32500
- //#endregion
32501
- //#region src/time/time-spec.ts
32502
- /**
32503
- * WHEN something happens, as data (D983) — the one time vocabulary of the
32504
- * scheduler and of an automation's schedule leaf. Three shapes, no cron:
32505
- *
32506
- * - `clock` — a wall-clock time every day (`07:30`), read in the site's zone;
32507
- * - `sun` — a sun event (`sunrise`, `sunset`, `dawn`, `dusk`) plus or minus
32508
- * up to twelve hours, from the site's coordinates;
32509
- * - `date` — one local date and time (`2026-12-24T18:00`), once.
32510
- *
32511
- * A site is a place and its IANA zone ({@link TimeSite}). Every function here
32512
- * is pure: the zone arithmetic uses `Intl`, no date library.
32513
- *
32514
- * Wall-clock honesty across a DST change: a local time that does not exist
32515
- * (02:30 on the spring-forward day) happens at the first minute that does
32516
- * (03:00); one that happens twice (02:30 on the fall-back day) happens at its
32517
- * FIRST occurrence.
32518
- */
32519
- var SunEventSchema = zod.z.enum([
32520
- "sunrise",
32521
- "sunset",
32522
- "dawn",
32523
- "dusk"
32524
- ]);
32525
- var LOCAL_DATE = /^\d{4}-\d{2}-\d{2}$/;
32526
- var LOCAL_DATE_TIME = /^(\d{4}-\d{2}-\d{2})T([01]\d|2[0-3]):([0-5]\d)$/;
32527
- var TimeSpecSchema = zod.z.discriminatedUnion("kind", [
32528
- zod.z.object({
32529
- kind: zod.z.literal("clock"),
32530
- hh: zod.z.number().int().min(0).max(23),
32531
- mm: zod.z.number().int().min(0).max(59)
32532
- }),
32533
- zod.z.object({
32534
- kind: zod.z.literal("sun"),
32535
- event: SunEventSchema,
32536
- /** Minutes after the event (negative: before). */
32537
- offsetMin: zod.z.number().int().min(-720).max(720)
32538
- }),
32539
- zod.z.object({
32540
- kind: zod.z.literal("date"),
32541
- /** `YYYY-MM-DDTHH:mm`, site-local. */
32542
- local: zod.z.string().regex(LOCAL_DATE_TIME, "expected YYYY-MM-DDTHH:mm")
32543
- })
32544
- ]);
32545
- /** A day of the week as a schedule names it. */
32546
- var WeekdayKeySchema = zod.z.enum([
32547
- "mon",
32548
- "tue",
32549
- "wed",
32550
- "thu",
32551
- "fri",
32552
- "sat",
32553
- "sun"
32554
- ]);
32555
- var WEEKDAY_BY_INDEX = [
32556
- "sun",
32557
- "mon",
32558
- "tue",
32559
- "wed",
32560
- "thu",
32561
- "fri",
32562
- "sat"
32563
- ];
32564
- var MINUTE_MS$3 = 6e4;
32565
- var DAY_MS$1 = 864e5;
32566
- var formatters = /* @__PURE__ */ new Map();
32567
- function formatterFor$1(timeZone) {
32568
- const cached = formatters.get(timeZone);
32569
- if (cached !== void 0) return cached;
32570
- const created = new Intl.DateTimeFormat("en-US", {
32571
- timeZone,
32572
- hourCycle: "h23",
32573
- year: "numeric",
32574
- month: "2-digit",
32575
- day: "2-digit",
32576
- hour: "2-digit",
32577
- minute: "2-digit",
32578
- second: "2-digit"
32579
- });
32580
- formatters.set(timeZone, created);
32581
- return created;
32582
- }
32583
- function wallClockOf(epochMs, timeZone) {
32584
- const out = {};
32585
- for (const part of formatterFor$1(timeZone).formatToParts(new Date(epochMs))) if (part.type !== "literal") out[part.type] = Number(part.value);
32586
- return {
32587
- year: out["year"] ?? 0,
32588
- month: out["month"] ?? 0,
32589
- day: out["day"] ?? 0,
32590
- hour: out["hour"] ?? 0,
32591
- minute: out["minute"] ?? 0,
32592
- second: out["second"] ?? 0
32593
- };
32594
- }
32595
- /** The zone's offset from UTC at an instant, in ms (positive east of Greenwich). */
32596
- function offsetMs(epochMs, timeZone) {
32597
- const w = wallClockOf(epochMs, timeZone);
32598
- return Date.UTC(w.year, w.month - 1, w.day, w.hour, w.minute, w.second) - Math.floor(epochMs / 1e3) * 1e3;
32599
- }
32600
- /** Is `timeZone` a zone this runtime knows? */
32601
- function isKnownTimeZone(timeZone) {
32602
- try {
32603
- formatterFor$1(timeZone);
32604
- return true;
32605
- } catch {
32606
- return false;
32607
- }
32608
- }
32609
- /** `YYYY-MM-DD` of an instant, read in the zone. */
32610
- function localDateOf(epochMs, timeZone) {
32611
- const w = wallClockOf(epochMs, timeZone);
32612
- return `${String(w.year).padStart(4, "0")}-${String(w.month).padStart(2, "0")}-${String(w.day).padStart(2, "0")}`;
32613
- }
32614
- function parseLocalDate(localDate) {
32615
- if (!LOCAL_DATE.test(localDate)) throw new Error(`not a local date (YYYY-MM-DD): ${localDate}`);
32616
- const [y, m, d] = localDate.split("-").map(Number);
32617
- return {
32618
- y: y ?? 0,
32619
- m: m ?? 1,
32620
- d: d ?? 1
32621
- };
32622
- }
32623
- /** The weekday of a `YYYY-MM-DD` civil date (zone-independent). */
32624
- function weekdayOfLocalDate(localDate) {
32625
- const { y, m, d } = parseLocalDate(localDate);
32626
- return WEEKDAY_BY_INDEX[new Date(Date.UTC(y, m - 1, d)).getUTCDay()] ?? "sun";
32627
- }
32628
- function addDays$1(localDate, days) {
32629
- const { y, m, d } = parseLocalDate(localDate);
32630
- return new Date(Date.UTC(y, m - 1, d + days)).toISOString().slice(0, 10);
32631
- }
32632
- /**
32633
- * The instant a wall-clock time happens in a zone. A time that does not exist
32634
- * happens at the first minute that does; one that happens twice, at its first
32635
- * occurrence.
32636
- */
32637
- function wallToEpoch(localDate, hh, mm, timeZone) {
32638
- const { y, m, d } = parseLocalDate(localDate);
32639
- const wall = Date.UTC(y, m - 1, d, hh, mm);
32640
- const before = offsetMs(wall - DAY_MS$1, timeZone);
32641
- const after = offsetMs(wall + DAY_MS$1, timeZone);
32642
- const valid = [wall - before, wall - after].filter((c) => c + offsetMs(c, timeZone) === wall);
32643
- if (valid.length > 0) return Math.min(...valid);
32644
- let lo = wall - DAY_MS$1;
32645
- let hi = wall + DAY_MS$1;
32646
- while (hi - lo > MINUTE_MS$3) {
32647
- const mid = Math.floor((lo + hi) / 2 / MINUTE_MS$3) * MINUTE_MS$3;
32648
- if (offsetMs(mid, timeZone) === before) lo = mid;
32649
- else hi = mid;
32650
- }
32651
- return hi;
32652
- }
32653
- function sunEventAltitude(event) {
32654
- return event === "sunrise" || event === "sunset" ? SUNRISE_ALTITUDE_DEG : -6;
32655
- }
32656
- /**
32657
- * The moment `spec` happens on the site-local date `localDate` (`YYYY-MM-DD`).
32658
- * See {@link Occurrence} for what `null` means.
32659
- */
32660
- function occurrenceOn(spec, localDate, site) {
32661
- switch (spec.kind) {
32662
- case "clock": return wallToEpoch(localDate, spec.hh, spec.mm, site.timeZone);
32663
- case "date": {
32664
- const match = LOCAL_DATE_TIME.exec(spec.local);
32665
- if (match === null || match[1] !== localDate) return null;
32666
- return wallToEpoch(localDate, Number(match[2]), Number(match[3]), site.timeZone);
32667
- }
32668
- case "sun": {
32669
- const midday = new Date(wallToEpoch(localDate, 12, 0, site.timeZone));
32670
- const crossings = sunCrossings(site.lat, site.lon, midday, sunEventAltitude(spec.event));
32671
- if (crossings === null) return null;
32672
- return (spec.event === "sunrise" || spec.event === "dawn" ? crossings.rise : crossings.set) + spec.offsetMin * MINUTE_MS$3;
32673
- }
32674
- }
32675
- }
32676
- /** How far ahead {@link nextOccurrence} looks before giving up: a polar winter fits. */
32677
- var NEXT_OCCURRENCE_HORIZON_DAYS = 400;
32678
- /**
32679
- * The first moment strictly after `afterMs` at which `spec` happens, or `null`
32680
- * when none does within {@link NEXT_OCCURRENCE_HORIZON_DAYS} (a `date` spec in
32681
- * the past, a sun event that never happens, an empty `days` list).
32682
- */
32683
- function nextOccurrence(spec, afterMs, site, options = {}) {
32684
- const days = options.days;
32685
- if (days !== void 0 && days.length === 0) return null;
32686
- if (spec.kind === "date") {
32687
- const own = LOCAL_DATE_TIME.exec(spec.local)?.[1];
32688
- if (own === void 0 || days !== void 0 && !days.includes(weekdayOfLocalDate(own))) return null;
32689
- const at = occurrenceOn(spec, own, site);
32690
- return at !== null && at > afterMs ? at : null;
32691
- }
32692
- const first = addDays$1(localDateOf(afterMs, site.timeZone), -1);
32693
- for (let i = 0; i < 400; i += 1) {
32694
- const localDate = addDays$1(first, i);
32695
- if (days !== void 0 && !days.includes(weekdayOfLocalDate(localDate))) continue;
32696
- const at = occurrenceOn(spec, localDate, site);
32697
- if (at !== null && at > afterMs) return at;
32698
- }
32699
- return null;
32700
- }
32701
- /**
32702
- * Can `spec` be scheduled at this site? A sun spec without a location is
32703
- * REFUSED with its reason — never read as a guessed sunrise. A clock or date
32704
- * spec needs only a zone, and `site` is `null` in that case when there is no
32705
- * location (it is not needed to place them; use {@link siteFor} to read them).
32706
- */
32707
- function validateTimeSpecForSite(spec, reading) {
32708
- if (!isKnownTimeZone(reading.timeZone)) return {
32709
- ok: false,
32710
- reason: "unknown-time-zone",
32711
- message: `the site time zone "${reading.timeZone}" is not a known IANA zone`
32712
- };
32713
- const site = siteFor(reading);
32714
- if (spec.kind === "sun" && site === null) return {
32715
- ok: false,
32716
- reason: "sun-needs-site-location",
32717
- message: `a ${spec.event} time needs the site location, and none is set — set it in Settings, or use a clock time`
32718
- };
32719
- return {
32720
- ok: true,
32721
- site
32722
- };
32723
- }
32724
- /** The site, when it has a location; a clock spec on a site without one uses {@link zoneOnlySite}. */
32725
- function siteFor(reading) {
32726
- if (reading.location === null) return null;
32727
- return {
32728
- lat: reading.location.latitude,
32729
- lon: reading.location.longitude,
32730
- timeZone: reading.timeZone
32731
- };
32732
- }
32733
- /** A site that can place a clock or date spec but no sun event (coordinates are unused by those). */
32734
- function zoneOnlySite(timeZone) {
32735
- return {
32736
- lat: 0,
32737
- lon: 0,
32738
- timeZone,
32739
- zoneOnly: true
32740
- };
32741
- }
32742
- //#endregion
32743
32675
  //#region src/automation/hold.ts
32744
32676
  /**
32745
32677
  * Hold semantics — "for N seconds" on a leaf of the `when` tree (#498).
@@ -33289,24 +33221,33 @@ var StationaryPresentLeafSchema = zod.z.object({
33289
33221
  * (`kind: 'date'`) is refused: only a clock time or a sun event makes a window
33290
33222
  * that repeats every day.
33291
33223
  */
33292
- var TimeIsLeafSchema = zod.z.object({
33293
- kind: zod.z.literal("time-is"),
33224
+ var timeIsWindowShape = {
33294
33225
  between: zod.z.object({
33295
33226
  from: TimeSpecSchema,
33296
33227
  to: TimeSpecSchema
33297
33228
  }).optional(),
33298
33229
  days: zod.z.array(WeekdayKeySchema).min(1).max(7).optional()
33299
- }).superRefine((leaf, ctx) => {
33300
- if (leaf.between === void 0 && leaf.days === void 0) ctx.addIssue({
33230
+ };
33231
+ function timeIsWindowProblems(window, ctx) {
33232
+ if (window.between === void 0 && window.days === void 0) ctx.addIssue({
33301
33233
  code: "custom",
33302
33234
  message: "a time-is leaf needs a between window, days, or both"
33303
33235
  });
33304
- for (const end of ["from", "to"]) if (leaf.between?.[end].kind === "date") ctx.addIssue({
33236
+ for (const end of ["from", "to"]) if (window.between?.[end].kind === "date") ctx.addIssue({
33305
33237
  code: "custom",
33306
33238
  message: "a one-date time cannot bound a daily window: use a clock time or a sun event",
33307
33239
  path: ["between", end]
33308
33240
  });
33309
- });
33241
+ }
33242
+ /**
33243
+ * What a `time-is` leaf holds beside its kind, judged by the leaf's own rules.
33244
+ * A template's time-window input stores exactly this.
33245
+ */
33246
+ var TimeIsWindowSchema = zod.z.object(timeIsWindowShape).superRefine(timeIsWindowProblems);
33247
+ var TimeIsLeafSchema = zod.z.object({
33248
+ kind: zod.z.literal("time-is"),
33249
+ ...timeIsWindowShape
33250
+ }).superRefine(timeIsWindowProblems);
33310
33251
  /** How many event leaves one `triggered-by` names. */
33311
33252
  var TRIGGERED_BY_MAX_IDS = 20;
33312
33253
  /**
@@ -33534,6 +33475,92 @@ function validateWhenTree(when) {
33534
33475
  return null;
33535
33476
  }
33536
33477
  //#endregion
33478
+ //#region src/automation/template-link.ts
33479
+ /**
33480
+ * The link an automation made FROM a template carries (#527): which template,
33481
+ * the values the operator filled in, and — when the template has since changed
33482
+ * so that those values no longer fit — the problems that say why.
33483
+ *
33484
+ * It lives inside the recipe (`AutomationRecipe.template`), so the one row in
33485
+ * `core_blocks` stays the one artefact: there is no second store of instances
33486
+ * to drift from the blocks, and deleting the automation deletes the link.
33487
+ * "Convert to a free automation" is dropping this field.
33488
+ *
33489
+ * This file depends on nothing in `recipe.ts`, so the recipe can embed it and
33490
+ * the template engine (`template/automation-template.ts`) can import both.
33491
+ */
33492
+ /** An `event` input's value: the same three narrowing lists a `device-fired` row takes. */
33493
+ var TemplateEventValueSchema = zod.z.object({
33494
+ eventIds: zod.z.array(zod.z.string().min(1)).min(1).max(64).optional(),
33495
+ sourceIds: zod.z.array(zod.z.string().min(1)).min(1).max(64).optional(),
33496
+ kinds: zod.z.array(EventVocabularyKindSchema).min(1).optional()
33497
+ }).refine((value) => value.eventIds !== void 0 || value.sourceIds !== void 0 || value.kinds !== void 0, { message: "an event names at least one event, part or kind" });
33498
+ /** An `action` input's value: a vocabulary action and its open args. */
33499
+ var TemplateActionValueSchema = zod.z.object({
33500
+ actionId: zod.z.string().min(1),
33501
+ args: zod.z.record(zod.z.string(), zod.z.unknown()).optional()
33502
+ });
33503
+ /**
33504
+ * A `time-window` input's value: what a `time-is` leaf holds beside its kind.
33505
+ * "No limit" is the input left without a value, never an empty object.
33506
+ */
33507
+ var TemplateTimeWindowValueSchema = TimeIsWindowSchema;
33508
+ /**
33509
+ * An `entries` input's value: automation elements VERBATIM — event leaves of a
33510
+ * `when` tree, or steps of a branch. Judged with the automation's own schemas
33511
+ * (`valueProblem` in the template engine), so there is no second shape here.
33512
+ */
33513
+ var TemplateEntrySchema = zod.z.record(zod.z.string(), zod.z.unknown());
33514
+ var TemplateEntriesValueSchema = zod.z.array(TemplateEntrySchema);
33515
+ /** The value of one non-group input. Which member is right is the input kind's to judge. */
33516
+ var TemplateScalarValueSchema = zod.z.union([
33517
+ zod.z.number(),
33518
+ zod.z.string(),
33519
+ zod.z.boolean(),
33520
+ zod.z.array(zod.z.number().int().nonnegative()),
33521
+ TemplateEventValueSchema,
33522
+ TemplateActionValueSchema,
33523
+ TemplateTimeWindowValueSchema,
33524
+ TemplateEntriesValueSchema
33525
+ ]);
33526
+ /** One row of a group inside a group row: row-input key → value. */
33527
+ var TemplateNestedRowSchema = zod.z.record(zod.z.string(), TemplateScalarValueSchema);
33528
+ /** What a group row holds under one key: a value, or the rows of a group it nests. */
33529
+ var TemplateRowValueSchema = zod.z.union([TemplateScalarValueSchema, zod.z.array(TemplateNestedRowSchema)]);
33530
+ /** One row of a repeatable group: row-input key → value. */
33531
+ var TemplateGroupRowSchema = zod.z.record(zod.z.string(), TemplateRowValueSchema);
33532
+ var TemplateInputValueSchema = zod.z.union([TemplateScalarValueSchema, zod.z.array(TemplateGroupRowSchema)]);
33533
+ /** Input key → value. */
33534
+ var TemplateInputValuesSchema = zod.z.record(zod.z.string(), TemplateInputValueSchema);
33535
+ var TEMPLATE_INSTANCE_PROBLEM_CODES = [
33536
+ "missing-input",
33537
+ "invalid-input",
33538
+ "invalid-recipe",
33539
+ "missing-template",
33540
+ "edited-by-hand"
33541
+ ];
33542
+ var TemplateInstanceProblemSchema = zod.z.object({
33543
+ code: zod.z.enum(TEMPLATE_INSTANCE_PROBLEM_CODES),
33544
+ /** Dotted input address (`buttons.2.targets`, `buttons.0.commands.1.targets`); absent for a whole-recipe problem. */
33545
+ input: zod.z.string().optional(),
33546
+ detail: zod.z.string()
33547
+ });
33548
+ var AutomationTemplateLinkSchema = zod.z.object({
33549
+ templateId: zod.z.string().min(1),
33550
+ values: TemplateInputValuesSchema,
33551
+ /**
33552
+ * Fingerprint of the generated code with this literal blanked
33553
+ * (`instanceCodeHash`), stamped by `generateAutomationBlock`. Code that no
33554
+ * longer matches it was edited by hand, and is never regenerated over.
33555
+ */
33556
+ codeHash: zod.z.string().optional(),
33557
+ /**
33558
+ * Present when the last re-expansion refused these values. The automation
33559
+ * keeps running the body of its last good expansion; nothing is dropped.
33560
+ */
33561
+ problems: zod.z.array(TemplateInstanceProblemSchema).min(1).optional()
33562
+ });
33563
+ //#endregion
33537
33564
  //#region src/automation/legacy-recipe.ts
33538
33565
  /**
33539
33566
  * The recipe shape before the single `when` tree: a flat list of triggers
@@ -96582,6 +96609,22 @@ var temperatureSensorCapability = {
96582
96609
  * writes `<group>-<index>`, so a row's event leaf and the branch that reads it
96583
96610
  * (`triggered-by`) agree on one name.
96584
96611
  *
96612
+ * A group row may hold one more level of groups (a button row with a list of
96613
+ * events and a list of commands). Three bindings reach that level:
96614
+ * - a `rows` binding INSIDE a row's bindings appends one copy of its item per
96615
+ * nested row, at a path relative to the parent row's item (a branch's steps);
96616
+ * - a top-level `rows` binding with `nested` appends one item per nested row of
96617
+ * EVERY row, flat (one event leaf per event of every button);
96618
+ * - `row-ids` writes the ids of a row's nested rows
96619
+ * (`<group>-<index>-<nested>-<index>`), the same ids `row-id` gives those
96620
+ * nested rows, so a branch can name every leaf of its row.
96621
+ *
96622
+ * A `time-window` input is an optional limit on WHEN the automation may run. Its
96623
+ * `gate` binding wraps the tree at a path as `all[time-is, <that tree>]`; left
96624
+ * without a value the tree is not touched at all. A gate is declared after the
96625
+ * bindings that write into the tree it wraps, because it moves that tree one
96626
+ * level down.
96627
+ *
96585
96628
  * Everything here is pure: the admin UI expands on save and the hub re-expands
96586
96629
  * every instance when a template changes, with the same function.
96587
96630
  */
@@ -96654,7 +96697,27 @@ var BooleanInputSchema = zod.z.object({
96654
96697
  ...inputBase,
96655
96698
  default: zod.z.boolean().optional()
96656
96699
  });
96700
+ /** A limit on when the automation may run; only a `gate` binding reads it. */
96701
+ var TimeWindowInputSchema = zod.z.object({
96702
+ kind: zod.z.literal("time-window"),
96703
+ ...inputBase
96704
+ });
96705
+ var TEMPLATE_ENTRIES_MAX = 20;
96706
+ /**
96707
+ * A list of automation elements, verbatim: `trigger` entries are event leaves
96708
+ * of a `when` tree (`device-fired`), `step` entries are steps of a branch
96709
+ * (`command`, `wait`). `allow` names the kinds the list takes; each entry is
96710
+ * judged by the automation's own schema, then by `allow`.
96711
+ */
96712
+ var EntriesInputSchema = zod.z.object({
96713
+ kind: zod.z.literal("entries"),
96714
+ ...inputBase,
96715
+ entry: zod.z.enum(["trigger", "step"]),
96716
+ allow: zod.z.array(zod.z.string().min(1)).min(1).max(10),
96717
+ maxItems: zod.z.number().int().min(1).max(20).optional()
96718
+ });
96657
96719
  var TemplateScalarInputSchema = zod.z.discriminatedUnion("kind", [
96720
+ EntriesInputSchema,
96658
96721
  DeviceInputSchema,
96659
96722
  EventInputSchema,
96660
96723
  ActionInputSchema$1,
@@ -96662,15 +96725,27 @@ var TemplateScalarInputSchema = zod.z.discriminatedUnion("kind", [
96662
96725
  DurationInputSchema,
96663
96726
  TextInputSchema,
96664
96727
  SelectInputSchema,
96665
- BooleanInputSchema
96728
+ BooleanInputSchema,
96729
+ TimeWindowInputSchema
96666
96730
  ]);
96667
96731
  var TEMPLATE_GROUP_ROWS_MAX = 20;
96668
- var GroupInputSchema = zod.z.object({
96732
+ var groupBase = {
96669
96733
  kind: zod.z.literal("group"),
96670
96734
  ...inputBase,
96671
- inputs: zod.z.array(TemplateScalarInputSchema).min(1).max(10),
96735
+ /** What one row is, in the singular and lower case ("button"): "Add button". */
96736
+ rowLabel: zod.z.string().min(1).max(40).optional(),
96672
96737
  minRows: zod.z.number().int().min(0).max(20).optional(),
96673
96738
  maxRows: zod.z.number().int().min(1).max(20).optional()
96739
+ };
96740
+ /** A group inside a group row: its rows hold values only, never another group. */
96741
+ var NestedGroupInputSchema = zod.z.object({
96742
+ ...groupBase,
96743
+ inputs: zod.z.array(TemplateScalarInputSchema).min(1).max(10)
96744
+ });
96745
+ var TemplateRowInputSchema = zod.z.discriminatedUnion("kind", [...TemplateScalarInputSchema.options, NestedGroupInputSchema]);
96746
+ var GroupInputSchema = zod.z.object({
96747
+ ...groupBase,
96748
+ inputs: zod.z.array(TemplateRowInputSchema).min(1).max(10)
96674
96749
  });
96675
96750
  var TemplateInputSchema = zod.z.discriminatedUnion("kind", [...TemplateScalarInputSchema.options, GroupInputSchema]);
96676
96751
  var TemplatePathSchema = zod.z.array(zod.z.union([zod.z.string().min(1), zod.z.number().int().nonnegative()])).max(24);
@@ -96685,40 +96760,161 @@ var TemplateRowIdBindingSchema = zod.z.object({
96685
96760
  kind: zod.z.literal("row-id"),
96686
96761
  path: TemplatePathSchema
96687
96762
  });
96688
- var TemplateRowItemBindingSchema = zod.z.discriminatedUnion("kind", [TemplateValueBindingSchema, TemplateRowIdBindingSchema]);
96763
+ /**
96764
+ * Appends an `entries` input's elements, verbatim, to the list at `path`. In a
96765
+ * row's bindings `input` is the row's own entries input and `path` is from the
96766
+ * row's item; at the top level, with `in`, it appends the `input` entries of
96767
+ * EVERY row of the group `in` (all buttons' triggers into one `when`), and
96768
+ * without `in` it appends a top-level entries input.
96769
+ */
96770
+ var TemplateEntriesBindingSchema = zod.z.object({
96771
+ kind: zod.z.literal("entries"),
96772
+ input: inputKey,
96773
+ path: TemplatePathSchema,
96774
+ in: inputKey.optional()
96775
+ });
96776
+ /** What fills the item of a row that holds values only. */
96777
+ var TemplateLeafRowBindingSchema = zod.z.discriminatedUnion("kind", [TemplateValueBindingSchema, TemplateRowIdBindingSchema]);
96778
+ /** The ids of a row's nested rows, as a list (a branch that reads every leaf of its row). */
96779
+ var TemplateRowIdsBindingSchema = zod.z.object({
96780
+ kind: zod.z.literal("row-ids"),
96781
+ /** The nested group whose rows are named. */
96782
+ input: inputKey,
96783
+ path: TemplatePathSchema
96784
+ });
96785
+ /** One copy of `item` per nested row, appended inside the parent row's item. */
96786
+ var TemplateNestedRowsBindingSchema = zod.z.object({
96787
+ kind: zod.z.literal("rows"),
96788
+ /** The nested group, declared by the parent row's group. */
96789
+ input: inputKey,
96790
+ /** The list the nested rows are appended to, from the parent row's item. */
96791
+ path: TemplatePathSchema,
96792
+ item: zod.z.unknown(),
96793
+ bindings: zod.z.array(TemplateLeafRowBindingSchema).max(40)
96794
+ });
96795
+ var TemplateRowItemBindingSchema = zod.z.discriminatedUnion("kind", [
96796
+ TemplateValueBindingSchema,
96797
+ TemplateEntriesBindingSchema,
96798
+ TemplateRowIdBindingSchema,
96799
+ TemplateRowIdsBindingSchema,
96800
+ TemplateNestedRowsBindingSchema
96801
+ ]);
96689
96802
  var TemplateRowsBindingSchema = zod.z.object({
96690
96803
  kind: zod.z.literal("rows"),
96691
96804
  input: inputKey,
96805
+ /**
96806
+ * A group the rows of `input` hold: the binding then appends one item per
96807
+ * NESTED row of every row, and its bindings read the nested row.
96808
+ */
96809
+ nested: inputKey.optional(),
96692
96810
  /** The list in the body the rows are appended to. */
96693
96811
  path: TemplatePathSchema,
96694
96812
  /** The JSON copied once per row. */
96695
96813
  item: zod.z.unknown(),
96696
96814
  bindings: zod.z.array(TemplateRowItemBindingSchema).max(40)
96697
96815
  });
96698
- var TemplateBindingSchema = zod.z.discriminatedUnion("kind", [TemplateValueBindingSchema, TemplateRowsBindingSchema]);
96816
+ /** Wraps the condition tree at `path` as `all[time-is, <tree>]` when the input has a value. */
96817
+ var TemplateGateBindingSchema = zod.z.object({
96818
+ kind: zod.z.literal("gate"),
96819
+ /** A top-level `time-window` input. */
96820
+ input: inputKey,
96821
+ path: TemplatePathSchema
96822
+ });
96823
+ var TemplateBindingSchema = zod.z.discriminatedUnion("kind", [
96824
+ TemplateValueBindingSchema,
96825
+ TemplateEntriesBindingSchema,
96826
+ TemplateRowsBindingSchema,
96827
+ TemplateGateBindingSchema
96828
+ ]);
96699
96829
  var AUTOMATION_TEMPLATE_VERSION = 1;
96700
- function bindingProblems(payload, ctx) {
96701
- const byKey = /* @__PURE__ */ new Map();
96702
- payload.inputs.forEach((input, index) => {
96703
- if (byKey.has(input.key)) ctx.addIssue({
96704
- code: "custom",
96830
+ function scalarsOf(inputs) {
96831
+ return inputs.filter((input) => input.kind !== "group");
96832
+ }
96833
+ /** Twice-declared keys and event / action inputs that read no device beside them. */
96834
+ function levelProblems(inputs, path, inRow = false) {
96835
+ const issues = [];
96836
+ const seen = /* @__PURE__ */ new Set();
96837
+ for (const input of inputs) {
96838
+ if (seen.has(input.key)) issues.push({
96705
96839
  message: `input "${input.key}" is declared twice`,
96706
- path: ["inputs", index]
96840
+ path
96707
96841
  });
96708
- byKey.set(input.key, input);
96709
- const siblings = input.kind === "group" ? input.inputs : payload.inputs;
96710
- for (const scalar of input.kind === "group" ? input.inputs : [input]) {
96711
- if (scalar.kind !== "event" && scalar.kind !== "action") continue;
96712
- if (scalar.deviceInput === void 0) continue;
96713
- const device = siblings.find((s) => s.key === scalar.deviceInput);
96714
- if (device === void 0 || device.kind !== "device") ctx.addIssue({
96715
- code: "custom",
96716
- message: `"${scalar.key}" reads the device input "${scalar.deviceInput}", which is not a device input beside it`,
96717
- path: ["inputs", index]
96718
- });
96842
+ seen.add(input.key);
96843
+ if (input.kind === "group") {
96844
+ issues.push(...levelProblems(input.inputs, path, true));
96845
+ continue;
96846
+ }
96847
+ if (input.kind === "time-window" && inRow) issues.push({
96848
+ message: `time window "${input.key}" limits the whole automation: it is not a row input`,
96849
+ path
96850
+ });
96851
+ if (input.kind !== "event" && input.kind !== "action") continue;
96852
+ if (input.deviceInput === void 0) continue;
96853
+ const device = inputs.find((sibling) => sibling.key === input.deviceInput);
96854
+ if (device === void 0 || device.kind !== "device") issues.push({
96855
+ message: `"${input.key}" reads the device input "${input.deviceInput}", which is not a device input beside it`,
96856
+ path
96857
+ });
96858
+ }
96859
+ return issues;
96860
+ }
96861
+ function nestedGroupOf(group, key) {
96862
+ const found = group.inputs.find((input) => input.key === key);
96863
+ return found !== void 0 && found.kind === "group" ? found : void 0;
96864
+ }
96865
+ function leafBindingProblems(bindings, owner) {
96866
+ const issues = [];
96867
+ for (const row of bindings) {
96868
+ if (row.kind === "row-id") continue;
96869
+ if (row.kind === "value") {
96870
+ const input = owner.inputs.find((i) => i.key === row.input);
96871
+ if (input === void 0) issues.push(`row binding names "${row.input}", which group "${owner.key}" does not declare`);
96872
+ else if (input.kind === "group") issues.push(`group "${input.key}" is bound with rows, not a value`);
96873
+ else if (input.kind === "entries") issues.push(`entries "${input.key}" are bound with entries, not a value`);
96874
+ continue;
96875
+ }
96876
+ const nested = owner.inputs.find((i) => i.key === row.input);
96877
+ if (row.kind === "entries") {
96878
+ if (nested === void 0 || nested.kind !== "entries") issues.push(`"${row.input}" is not an entries input inside "${owner.key}"`);
96879
+ continue;
96880
+ }
96881
+ if (row.kind === "row-ids") {
96882
+ if (nested === void 0 || nested.kind !== "group" && nested.kind !== "entries") issues.push(`"${row.input}" is not a group or entries input inside "${owner.key}"`);
96883
+ continue;
96884
+ }
96885
+ if (nested === void 0 || nested.kind !== "group") {
96886
+ issues.push(`"${row.input}" is not a group inside "${owner.key}"`);
96887
+ continue;
96719
96888
  }
96889
+ issues.push(...leafBindingProblems(row.bindings, nested));
96890
+ }
96891
+ return issues;
96892
+ }
96893
+ function rowsBindingProblems(binding, group) {
96894
+ if (binding.nested === void 0) return leafBindingProblems(binding.bindings, group);
96895
+ const nested = nestedGroupOf(group, binding.nested);
96896
+ if (nested === void 0) return [`"${binding.nested}" is not a group inside "${group.key}"`];
96897
+ return leafBindingProblems(binding.bindings, nested);
96898
+ }
96899
+ function bindingProblems(payload, ctx) {
96900
+ const byKey = /* @__PURE__ */ new Map();
96901
+ for (const input of payload.inputs) byKey.set(input.key, input);
96902
+ for (const issue of levelProblems(payload.inputs, ["inputs"])) ctx.addIssue({
96903
+ code: "custom",
96904
+ message: issue.message,
96905
+ path: [...issue.path]
96720
96906
  });
96721
96907
  payload.bindings.forEach((binding, index) => {
96908
+ if (binding.kind === "entries" && binding.in !== void 0) {
96909
+ const group = byKey.get(binding.in);
96910
+ const entries = group !== void 0 && group.kind === "group" ? group.inputs.find((i) => i.key === binding.input) : void 0;
96911
+ if (entries === void 0 || entries.kind !== "entries") ctx.addIssue({
96912
+ code: "custom",
96913
+ message: `"${binding.input}" is not an entries input inside the group "${binding.in}"`,
96914
+ path: ["bindings", index]
96915
+ });
96916
+ return;
96917
+ }
96722
96918
  const input = byKey.get(binding.input);
96723
96919
  if (input === void 0) {
96724
96920
  ctx.addIssue({
@@ -96733,6 +96929,18 @@ function bindingProblems(payload, ctx) {
96733
96929
  message: `group "${input.key}" is bound with rows, not a value`,
96734
96930
  path: ["bindings", index]
96735
96931
  });
96932
+ if (binding.kind === "entries" !== (input.kind === "entries") && binding.kind !== "rows") {
96933
+ if (binding.kind === "entries" || binding.kind === "value") ctx.addIssue({
96934
+ code: "custom",
96935
+ message: binding.kind === "entries" ? `entries bindings read an entries input: "${input.key}" is ${input.kind}` : `entries "${input.key}" are bound with entries, not a value`,
96936
+ path: ["bindings", index]
96937
+ });
96938
+ }
96939
+ if (binding.kind === "gate" !== (input.kind === "time-window")) ctx.addIssue({
96940
+ code: "custom",
96941
+ message: `a gate reads a time window and a time window is bound with a gate: "${input.key}" is ${input.kind}`,
96942
+ path: ["bindings", index]
96943
+ });
96736
96944
  if (binding.kind === "rows") {
96737
96945
  if (input.kind !== "group") {
96738
96946
  ctx.addIssue({
@@ -96742,9 +96950,9 @@ function bindingProblems(payload, ctx) {
96742
96950
  });
96743
96951
  return;
96744
96952
  }
96745
- for (const row of binding.bindings) if (row.kind === "value" && !input.inputs.some((i) => i.key === row.input)) ctx.addIssue({
96953
+ for (const message of rowsBindingProblems(binding, input)) ctx.addIssue({
96746
96954
  code: "custom",
96747
- message: `row binding names "${row.input}", which group "${input.key}" does not declare`,
96955
+ message,
96748
96956
  path: ["bindings", index]
96749
96957
  });
96750
96958
  }
@@ -96780,7 +96988,25 @@ function valueProblem(input, value) {
96780
96988
  return input.maxLength !== void 0 && value.length > input.maxLength ? `at most ${input.maxLength} characters` : null;
96781
96989
  case "select": return typeof value === "string" && input.options.some((o) => o.value === value) ? null : "pick one of the options";
96782
96990
  case "boolean": return typeof value === "boolean" ? null : "on or off";
96991
+ case "time-window": {
96992
+ const parsed = TemplateTimeWindowValueSchema.safeParse(value);
96993
+ return parsed.success ? null : parsed.error.issues[0]?.message ?? "pick a time window";
96994
+ }
96995
+ case "entries": return entriesProblem(input, value);
96996
+ }
96997
+ }
96998
+ /** Each entry is judged by the automation's own schema, then by the kinds the input allows. */
96999
+ function entriesProblem(input, value) {
97000
+ const list = TemplateEntriesValueSchema.safeParse(value);
97001
+ if (!list.success) return "a list of entries is required";
97002
+ if (list.data.length === 0) return "add at least one";
97003
+ if (input.maxItems !== void 0 && list.data.length > input.maxItems) return `at most ${input.maxItems}`;
97004
+ for (const entry of list.data) {
97005
+ const parsed = input.entry === "trigger" ? AutomationWhenSchema.safeParse(entry) : AutomationBranchStepSchema.safeParse(entry);
97006
+ if (!parsed.success) return parsed.error.issues[0]?.message ?? "an entry is not valid";
97007
+ if (!input.allow.includes(parsed.data.kind)) return `"${parsed.data.kind}" is not allowed here`;
96783
97008
  }
97009
+ return null;
96784
97010
  }
96785
97011
  function defaultOf(input) {
96786
97012
  switch (input.kind) {
@@ -96811,52 +97037,59 @@ function resolveScalars(inputs, values, prefix, problems) {
96811
97037
  });
96812
97038
  continue;
96813
97039
  }
96814
- const problem = isScalar(raw) ? valueProblem(input, raw) : "a single value is required";
96815
- if (problem !== null || !isScalar(raw)) {
97040
+ const problem = input.kind === "entries" || isScalar(raw) ? valueProblem(input, raw) : "a single value is required";
97041
+ if (problem !== null) {
96816
97042
  problems.push({
96817
97043
  code: "invalid-input",
96818
97044
  input: address,
96819
- detail: problem ?? "invalid value"
97045
+ detail: problem
96820
97046
  });
96821
97047
  continue;
96822
97048
  }
96823
- out.set(input.key, raw);
97049
+ if (input.kind === "entries") out.set(input.key, TemplateEntriesValueSchema.parse(raw));
97050
+ else if (isScalar(raw)) out.set(input.key, raw);
96824
97051
  }
96825
97052
  return out;
96826
97053
  }
96827
- function resolveValues(payload, values, problems) {
96828
- const scalars = resolveScalars(payload.inputs.filter((i) => i.kind !== "group"), values, "", problems);
97054
+ /** The rows of one group, each resolved; `null` when the list itself is refused. */
97055
+ function resolveRows(group, values, prefix, problems) {
97056
+ const address = `${prefix}${group.key}`;
97057
+ const raw = values[group.key] ?? [];
97058
+ if (!isRowList(raw)) {
97059
+ problems.push({
97060
+ code: "invalid-input",
97061
+ input: address,
97062
+ detail: "a list of rows is required"
97063
+ });
97064
+ return null;
97065
+ }
97066
+ const min = group.minRows ?? (group.optional === true ? 0 : 1);
97067
+ const max = group.maxRows ?? 20;
97068
+ if (raw.length < min) {
97069
+ problems.push({
97070
+ code: raw.length === 0 ? "missing-input" : "invalid-input",
97071
+ input: address,
97072
+ detail: `"${group.label}" needs at least ${min} row(s)`
97073
+ });
97074
+ return null;
97075
+ }
97076
+ if (raw.length > max) {
97077
+ problems.push({
97078
+ code: "invalid-input",
97079
+ input: address,
97080
+ detail: `"${group.label}" takes at most ${max} row(s)`
97081
+ });
97082
+ return null;
97083
+ }
97084
+ return raw.map((row, index) => resolveLevel$1(group.inputs, row, `${address}.${index}.`, problems));
97085
+ }
97086
+ function resolveLevel$1(inputs, values, prefix, problems) {
97087
+ const scalars = resolveScalars(scalarsOf(inputs), values, prefix, problems);
96829
97088
  const groups = /* @__PURE__ */ new Map();
96830
- for (const input of payload.inputs) {
97089
+ for (const input of inputs) {
96831
97090
  if (input.kind !== "group") continue;
96832
- const raw = values[input.key] ?? [];
96833
- if (!isRowList(raw)) {
96834
- problems.push({
96835
- code: "invalid-input",
96836
- input: input.key,
96837
- detail: "a list of rows is required"
96838
- });
96839
- continue;
96840
- }
96841
- const min = input.minRows ?? (input.optional === true ? 0 : 1);
96842
- const max = input.maxRows ?? 20;
96843
- if (raw.length < min) {
96844
- problems.push({
96845
- code: raw.length === 0 ? "missing-input" : "invalid-input",
96846
- input: input.key,
96847
- detail: `"${input.label}" needs at least ${min} row(s)`
96848
- });
96849
- continue;
96850
- }
96851
- if (raw.length > max) {
96852
- problems.push({
96853
- code: "invalid-input",
96854
- input: input.key,
96855
- detail: `"${input.label}" takes at most ${max} row(s)`
96856
- });
96857
- continue;
96858
- }
96859
- groups.set(input.key, raw.map((row, index) => resolveScalars(input.inputs, row, `${input.key}.${index}.`, problems)));
97091
+ const rows = resolveRows(input, values, prefix, problems);
97092
+ if (rows !== null) groups.set(input.key, rows);
96860
97093
  }
96861
97094
  return {
96862
97095
  scalars,
@@ -96924,30 +97157,100 @@ function writeValue(root, binding, input, value) {
96924
97157
  default: return setAt(root, binding.path, value);
96925
97158
  }
96926
97159
  }
96927
- function applyRows(root, binding, group, rows) {
96928
- const existing = getAt(root, binding.path);
97160
+ /** The tree at the path, under an `all` beside the window. */
97161
+ function writeGate(root, binding, value) {
97162
+ const window = TemplateTimeWindowValueSchema.parse(value);
97163
+ return setAt(root, binding.path, {
97164
+ kind: "all",
97165
+ children: [{
97166
+ kind: "time-is",
97167
+ ...window
97168
+ }, getAt(root, binding.path)]
97169
+ });
97170
+ }
97171
+ /** The name a row is known by: `buttons-0`, and `buttons-0-events-1` for a nested row. */
97172
+ function rowIdOf(parentId, groupKey, index) {
97173
+ const own = `${groupKey}-${index}`;
97174
+ return parentId === null ? own : `${parentId}-${own}`;
97175
+ }
97176
+ function appendAt(root, path, items, key) {
97177
+ const existing = getAt(root, path);
96929
97178
  const list = existing === void 0 ? [] : existing;
96930
- if (!Array.isArray(list)) throw new PathError(`rows of "${group.key}" need a list`);
96931
- const items = rows.map((row, index) => {
96932
- let item = binding.item;
96933
- for (const rowBinding of binding.bindings) {
96934
- if (rowBinding.kind === "row-id") {
96935
- item = setAt(item, rowBinding.path, `${group.key}-${index}`);
96936
- continue;
96937
- }
96938
- const input = group.inputs.find((i) => i.key === rowBinding.input);
96939
- const value = row.get(rowBinding.input);
96940
- if (input === void 0 || value === void 0) continue;
96941
- item = writeValue(item, rowBinding, input, value);
96942
- }
96943
- return item;
97179
+ if (!Array.isArray(list)) throw new PathError(`rows of "${key}" need a list`);
97180
+ return setAt(root, path, [...list, ...items]);
97181
+ }
97182
+ /** The entries a row holds under `key`, each trigger carrying the leaf id the `triggered-by` of its row reads. */
97183
+ function entriesOf$1(row, input, rowId) {
97184
+ const value = row.scalars.get(input.key);
97185
+ const parsed = TemplateEntriesValueSchema.safeParse(value);
97186
+ const entries = parsed.success ? parsed.data : [];
97187
+ if (input.entry !== "trigger") return entries;
97188
+ return entries.map((entry, index) => {
97189
+ const id = Reflect.get(entry, "id");
97190
+ return typeof id === "string" && EVENT_LEAF_ID_RE.test(id) ? entry : {
97191
+ ...entry,
97192
+ id: rowIdOf(rowId, input.key, index)
97193
+ };
96944
97194
  });
96945
- return setAt(root, binding.path, [...list, ...items]);
97195
+ }
97196
+ /** One row's item: the template JSON with the row's values, ids and nested rows written in. */
97197
+ function fillItem(template, bindings, group, row, rowId) {
97198
+ let item = template;
97199
+ for (const binding of bindings) {
97200
+ if (binding.kind === "row-id") {
97201
+ item = setAt(item, binding.path, rowId);
97202
+ continue;
97203
+ }
97204
+ if (binding.kind === "value") {
97205
+ const input = group.inputs.find((i) => i.key === binding.input);
97206
+ const value = row.scalars.get(binding.input);
97207
+ if (input === void 0 || input.kind === "group" || value === void 0) continue;
97208
+ item = writeValue(item, binding, input, value);
97209
+ continue;
97210
+ }
97211
+ const nested = group.inputs.find((i) => i.key === binding.input);
97212
+ if (binding.kind === "entries") {
97213
+ if (nested === void 0 || nested.kind !== "entries") continue;
97214
+ item = appendAt(item, binding.path, entriesOf$1(row, nested, rowId), nested.key);
97215
+ continue;
97216
+ }
97217
+ if (binding.kind === "row-ids" && nested !== void 0 && nested.kind === "entries") {
97218
+ item = setAt(item, binding.path, entriesOf$1(row, nested, rowId).map((entry) => Reflect.get(entry, "id")));
97219
+ continue;
97220
+ }
97221
+ if (nested === void 0 || nested.kind !== "group") continue;
97222
+ const nestedRows = row.groups.get(nested.key) ?? [];
97223
+ if (binding.kind === "row-ids") {
97224
+ item = setAt(item, binding.path, nestedRows.map((_, index) => rowIdOf(rowId, nested.key, index)));
97225
+ continue;
97226
+ }
97227
+ item = appendAt(item, binding.path, nestedRows.map((nestedRow, index) => fillItem(binding.item, binding.bindings, nested, nestedRow, rowIdOf(rowId, nested.key, index))), nested.key);
97228
+ }
97229
+ return item;
97230
+ }
97231
+ function applyRows(root, binding, group, rows) {
97232
+ if (binding.nested === void 0) {
97233
+ const items = rows.map((row, index) => fillItem(binding.item, binding.bindings, group, row, rowIdOf(null, group.key, index)));
97234
+ return appendAt(root, binding.path, items, group.key);
97235
+ }
97236
+ const nested = nestedGroupOf(group, binding.nested);
97237
+ if (nested === void 0) return root;
97238
+ const items = rows.flatMap((row, index) => (row.groups.get(nested.key) ?? []).map((nestedRow, nestedIndex) => fillItem(binding.item, binding.bindings, nested, nestedRow, rowIdOf(rowIdOf(null, group.key, index), nested.key, nestedIndex))));
97239
+ return appendAt(root, binding.path, items, nested.key);
97240
+ }
97241
+ /** The `input` entries of EVERY row of the group `binding.in`, concatenated onto the list at the path. */
97242
+ function applyEntriesOfRows(root, binding, inputs, resolved) {
97243
+ const group = inputs.find((i) => i.key === binding.in);
97244
+ if (group === void 0 || group.kind !== "group") return root;
97245
+ const entries = group.inputs.find((i) => i.key === binding.input);
97246
+ if (entries === void 0 || entries.kind !== "entries") return root;
97247
+ const items = (resolved.groups.get(group.key) ?? []).flatMap((row, index) => entriesOf$1(row, entries, rowIdOf(null, group.key, index)));
97248
+ return appendAt(root, binding.path, items, entries.key);
96946
97249
  }
96947
97250
  /** The body with the values written in, as a recipe — or every reason it is not one. */
96948
97251
  function expandAutomationTemplate(payload, values) {
96949
97252
  const problems = [];
96950
- const resolved = resolveValues(payload, values, problems);
97253
+ const resolved = resolveLevel$1(payload.inputs, values, "", problems);
96951
97254
  if (problems.length > 0) return {
96952
97255
  ok: false,
96953
97256
  problems
@@ -96955,6 +97258,10 @@ function expandAutomationTemplate(payload, values) {
96955
97258
  let body = payload.body;
96956
97259
  try {
96957
97260
  for (const binding of payload.bindings) {
97261
+ if (binding.kind === "entries" && binding.in !== void 0) {
97262
+ body = applyEntriesOfRows(body, binding, payload.inputs, resolved);
97263
+ continue;
97264
+ }
96958
97265
  const input = payload.inputs.find((i) => i.key === binding.input);
96959
97266
  if (input === void 0) continue;
96960
97267
  if (binding.kind === "rows") {
@@ -96965,7 +97272,12 @@ function expandAutomationTemplate(payload, values) {
96965
97272
  if (input.kind === "group") continue;
96966
97273
  const value = resolved.scalars.get(input.key);
96967
97274
  if (value === void 0) continue;
96968
- body = writeValue(body, binding, input, value);
97275
+ if (binding.kind === "entries") {
97276
+ const list = TemplateEntriesValueSchema.safeParse(value);
97277
+ if (list.success) body = appendAt(body, binding.path, list.data, input.key);
97278
+ continue;
97279
+ }
97280
+ body = binding.kind === "gate" ? writeGate(body, binding, value) : writeValue(body, binding, input, value);
96969
97281
  }
96970
97282
  } catch (error) {
96971
97283
  if (!(error instanceof PathError)) throw error;
@@ -105272,12 +105584,30 @@ function flipperIrDraft(file, target) {
105272
105584
  * migration and nothing an operator saved is ever overwritten.
105273
105585
  */
105274
105586
  var BUILTIN_TEMPLATE_ID_PREFIX = "builtin:";
105587
+ /** One choose branch per row, so the rows a group takes are the branches a choose takes. */
105588
+ var BUTTON_ROWS_MAX = 6;
105589
+ var ROW_ENTRIES_MAX = 10;
105590
+ /** The optional limit both built-ins end with: no value, no limit. */
105591
+ var ACTIVE_WINDOW_KEY = "active";
105592
+ var activeWindowInput = {
105593
+ kind: "time-window",
105594
+ key: ACTIVE_WINDOW_KEY,
105595
+ label: "Only when",
105596
+ description: "Limit the automation to a time of day, to some days, or both.",
105597
+ optional: true
105598
+ };
105599
+ /** Declared last: it moves the tree the other bindings write into one level down. */
105600
+ var activeWindowGate = {
105601
+ kind: "gate",
105602
+ input: ACTIVE_WINDOW_KEY,
105603
+ path: ["when"]
105604
+ };
105275
105605
  var BUILTIN_AUTOMATION_TEMPLATES = [{
105276
105606
  id: `${BUILTIN_TEMPLATE_ID_PREFIX}buttons-to-devices`,
105277
105607
  name: "Buttons → devices",
105278
105608
  payload: {
105279
105609
  version: 1,
105280
- description: "Each row: when a button sends an event, run an action on a set of devices.",
105610
+ description: "Each button: when it sends an event, run one or more actions.",
105281
105611
  body: {
105282
105612
  when: {
105283
105613
  kind: "any",
@@ -105296,96 +105626,58 @@ var BUILTIN_AUTOMATION_TEMPLATES = [{
105296
105626
  kind: "group",
105297
105627
  key: "buttons",
105298
105628
  label: "Buttons",
105299
- maxRows: 6,
105300
- inputs: [
105301
- {
105302
- kind: "device",
105303
- key: "button",
105304
- label: "Button",
105305
- filter: { capability: "event-emitter" }
105306
- },
105307
- {
105308
- kind: "event",
105309
- key: "event",
105310
- label: "Event",
105311
- deviceInput: "button"
105312
- },
105313
- {
105314
- kind: "device",
105315
- key: "targets",
105316
- label: "Devices",
105317
- multiple: true
105318
- },
105319
- {
105320
- kind: "action",
105321
- key: "action",
105322
- label: "Action",
105323
- deviceInput: "targets"
105324
- }
105325
- ]
105326
- }],
105327
- bindings: [{
105328
- kind: "rows",
105329
- input: "buttons",
105330
- path: ["when", "children"],
105331
- item: { kind: "device-fired" },
105332
- bindings: [
105333
- {
105334
- kind: "row-id",
105335
- path: ["id"]
105336
- },
105337
- {
105338
- kind: "value",
105339
- input: "button",
105340
- path: ["deviceId"]
105341
- },
105342
- {
105343
- kind: "value",
105344
- input: "event",
105345
- path: []
105346
- }
105347
- ]
105348
- }, {
105349
- kind: "rows",
105350
- input: "buttons",
105351
- path: [
105352
- "actions",
105353
- 0,
105354
- "branches"
105355
- ],
105356
- item: {
105357
- if: {
105358
- kind: "triggered-by",
105359
- leafIds: []
105360
- },
105361
- steps: [{ kind: "command" }]
105629
+ rowLabel: "button",
105630
+ maxRows: BUTTON_ROWS_MAX,
105631
+ inputs: [{
105632
+ kind: "entries",
105633
+ key: "when",
105634
+ label: "When",
105635
+ entry: "trigger",
105636
+ allow: ["device-fired"],
105637
+ maxItems: ROW_ENTRIES_MAX
105638
+ }, {
105639
+ kind: "entries",
105640
+ key: "do",
105641
+ label: "Actions",
105642
+ entry: "step",
105643
+ allow: ["command"],
105644
+ maxItems: ROW_ENTRIES_MAX
105645
+ }]
105646
+ }, activeWindowInput],
105647
+ bindings: [
105648
+ {
105649
+ kind: "entries",
105650
+ input: "when",
105651
+ in: "buttons",
105652
+ path: ["when", "children"]
105362
105653
  },
105363
- bindings: [
105364
- {
105365
- kind: "row-id",
105366
- path: [
105367
- "if",
105368
- "leafIds",
105369
- 0
105370
- ]
105371
- },
105372
- {
105373
- kind: "value",
105374
- input: "targets",
105375
- path: [
105376
- "steps",
105377
- 0,
105378
- "target"
105379
- ],
105380
- as: "target"
105654
+ {
105655
+ kind: "rows",
105656
+ input: "buttons",
105657
+ path: [
105658
+ "actions",
105659
+ 0,
105660
+ "branches"
105661
+ ],
105662
+ item: {
105663
+ if: {
105664
+ kind: "triggered-by",
105665
+ leafIds: []
105666
+ },
105667
+ steps: []
105381
105668
  },
105382
- {
105383
- kind: "value",
105384
- input: "action",
105385
- path: ["steps", 0]
105386
- }
105387
- ]
105388
- }]
105669
+ bindings: [{
105670
+ kind: "row-ids",
105671
+ input: "when",
105672
+ path: ["if", "leafIds"]
105673
+ }, {
105674
+ kind: "entries",
105675
+ input: "do",
105676
+ path: ["steps"]
105677
+ }]
105678
+ },
105679
+ activeWindowGate
105680
+ ]
105389
105681
  }
105390
105682
  }, {
105391
105683
  id: `${BUILTIN_TEMPLATE_ID_PREFIX}motion-light`,
@@ -105437,7 +105729,8 @@ var BUILTIN_AUTOMATION_TEMPLATES = [{
105437
105729
  min: 10,
105438
105730
  max: 3600,
105439
105731
  default: 300
105440
- }
105732
+ },
105733
+ activeWindowInput
105441
105734
  ],
105442
105735
  bindings: [
105443
105736
  {
@@ -105473,7 +105766,8 @@ var BUILTIN_AUTOMATION_TEMPLATES = [{
105473
105766
  "target"
105474
105767
  ],
105475
105768
  as: "target"
105476
- }
105769
+ },
105770
+ activeWindowGate
105477
105771
  ]
105478
105772
  }
105479
105773
  }];
@@ -148279,6 +148573,7 @@ exports.SystemHeldSecretNameSchema = SystemHeldSecretNameSchema;
148279
148573
  exports.SystemMetricsSchema = SystemMetricsSchema;
148280
148574
  exports.SystemMirror = SystemMirror;
148281
148575
  exports.TARGET_OWNER_KEY = TARGET_OWNER_KEY;
148576
+ exports.TEMPLATE_ENTRIES_MAX = TEMPLATE_ENTRIES_MAX;
148282
148577
  exports.TEMPLATE_GROUP_ROWS_MAX = TEMPLATE_GROUP_ROWS_MAX;
148283
148578
  exports.TEMPLATE_INPUT_KEY_RE = TEMPLATE_INPUT_KEY_RE;
148284
148579
  exports.TEMPLATE_INSTANCE_PROBLEM_CODES = TEMPLATE_INSTANCE_PROBLEM_CODES;
@@ -148310,21 +148605,32 @@ exports.TemplateAutomationUserSchema = TemplateAutomationUserSchema;
148310
148605
  exports.TemplateBindingSchema = TemplateBindingSchema;
148311
148606
  exports.TemplateDeleteResultSchema = TemplateDeleteResultSchema;
148312
148607
  exports.TemplateDeviceFilterSchema = TemplateDeviceFilterSchema;
148608
+ exports.TemplateEntriesBindingSchema = TemplateEntriesBindingSchema;
148609
+ exports.TemplateEntriesValueSchema = TemplateEntriesValueSchema;
148610
+ exports.TemplateEntrySchema = TemplateEntrySchema;
148313
148611
  exports.TemplateEventValueSchema = TemplateEventValueSchema;
148612
+ exports.TemplateGateBindingSchema = TemplateGateBindingSchema;
148314
148613
  exports.TemplateGroupRowSchema = TemplateGroupRowSchema;
148315
148614
  exports.TemplateInputSchema = TemplateInputSchema;
148316
148615
  exports.TemplateInputValueSchema = TemplateInputValueSchema;
148317
148616
  exports.TemplateInputValuesSchema = TemplateInputValuesSchema;
148318
148617
  exports.TemplateInstanceProblemSchema = TemplateInstanceProblemSchema;
148319
148618
  exports.TemplateKindSchema = TemplateKindSchema;
148619
+ exports.TemplateLeafRowBindingSchema = TemplateLeafRowBindingSchema;
148620
+ exports.TemplateNestedRowSchema = TemplateNestedRowSchema;
148621
+ exports.TemplateNestedRowsBindingSchema = TemplateNestedRowsBindingSchema;
148320
148622
  exports.TemplatePathSchema = TemplatePathSchema;
148321
148623
  exports.TemplateRecordSchema = TemplateRecordSchema;
148322
148624
  exports.TemplateRowIdBindingSchema = TemplateRowIdBindingSchema;
148625
+ exports.TemplateRowIdsBindingSchema = TemplateRowIdsBindingSchema;
148626
+ exports.TemplateRowInputSchema = TemplateRowInputSchema;
148323
148627
  exports.TemplateRowItemBindingSchema = TemplateRowItemBindingSchema;
148628
+ exports.TemplateRowValueSchema = TemplateRowValueSchema;
148324
148629
  exports.TemplateRowsBindingSchema = TemplateRowsBindingSchema;
148325
148630
  exports.TemplateScalarInputSchema = TemplateScalarInputSchema;
148326
148631
  exports.TemplateScalarValueSchema = TemplateScalarValueSchema;
148327
148632
  exports.TemplateSelectOptionSchema = TemplateSelectOptionSchema;
148633
+ exports.TemplateTimeWindowValueSchema = TemplateTimeWindowValueSchema;
148328
148634
  exports.TemplateUserSchema = TemplateUserSchema;
148329
148635
  exports.TemplateValueBindingSchema = TemplateValueBindingSchema;
148330
148636
  exports.TemplateWriteResultSchema = TemplateWriteResultSchema;