@camstack/types 1.2.565 → 1.2.567

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
@@ -91901,7 +91928,10 @@ var RemoteAssumedStateSchema = zod.z.object({
91901
91928
  value: zod.z.boolean(),
91902
91929
  at: zod.z.number()
91903
91930
  }).nullable(),
91904
- /** The declared source last sent; unknown after a power off or a channel step. */
91931
+ /**
91932
+ * Retired: a sent source is never a state (an infrared set cannot report its
91933
+ * input). Kept only so records written before parse; nothing writes or reads it.
91934
+ */
91905
91935
  source: zod.z.object({
91906
91936
  name: zod.z.string(),
91907
91937
  at: zod.z.number()
@@ -96582,6 +96612,22 @@ var temperatureSensorCapability = {
96582
96612
  * writes `<group>-<index>`, so a row's event leaf and the branch that reads it
96583
96613
  * (`triggered-by`) agree on one name.
96584
96614
  *
96615
+ * A group row may hold one more level of groups (a button row with a list of
96616
+ * events and a list of commands). Three bindings reach that level:
96617
+ * - a `rows` binding INSIDE a row's bindings appends one copy of its item per
96618
+ * nested row, at a path relative to the parent row's item (a branch's steps);
96619
+ * - a top-level `rows` binding with `nested` appends one item per nested row of
96620
+ * EVERY row, flat (one event leaf per event of every button);
96621
+ * - `row-ids` writes the ids of a row's nested rows
96622
+ * (`<group>-<index>-<nested>-<index>`), the same ids `row-id` gives those
96623
+ * nested rows, so a branch can name every leaf of its row.
96624
+ *
96625
+ * A `time-window` input is an optional limit on WHEN the automation may run. Its
96626
+ * `gate` binding wraps the tree at a path as `all[time-is, <that tree>]`; left
96627
+ * without a value the tree is not touched at all. A gate is declared after the
96628
+ * bindings that write into the tree it wraps, because it moves that tree one
96629
+ * level down.
96630
+ *
96585
96631
  * Everything here is pure: the admin UI expands on save and the hub re-expands
96586
96632
  * every instance when a template changes, with the same function.
96587
96633
  */
@@ -96654,7 +96700,27 @@ var BooleanInputSchema = zod.z.object({
96654
96700
  ...inputBase,
96655
96701
  default: zod.z.boolean().optional()
96656
96702
  });
96703
+ /** A limit on when the automation may run; only a `gate` binding reads it. */
96704
+ var TimeWindowInputSchema = zod.z.object({
96705
+ kind: zod.z.literal("time-window"),
96706
+ ...inputBase
96707
+ });
96708
+ var TEMPLATE_ENTRIES_MAX = 20;
96709
+ /**
96710
+ * A list of automation elements, verbatim: `trigger` entries are event leaves
96711
+ * of a `when` tree (`device-fired`), `step` entries are steps of a branch
96712
+ * (`command`, `wait`). `allow` names the kinds the list takes; each entry is
96713
+ * judged by the automation's own schema, then by `allow`.
96714
+ */
96715
+ var EntriesInputSchema = zod.z.object({
96716
+ kind: zod.z.literal("entries"),
96717
+ ...inputBase,
96718
+ entry: zod.z.enum(["trigger", "step"]),
96719
+ allow: zod.z.array(zod.z.string().min(1)).min(1).max(10),
96720
+ maxItems: zod.z.number().int().min(1).max(20).optional()
96721
+ });
96657
96722
  var TemplateScalarInputSchema = zod.z.discriminatedUnion("kind", [
96723
+ EntriesInputSchema,
96658
96724
  DeviceInputSchema,
96659
96725
  EventInputSchema,
96660
96726
  ActionInputSchema$1,
@@ -96662,15 +96728,27 @@ var TemplateScalarInputSchema = zod.z.discriminatedUnion("kind", [
96662
96728
  DurationInputSchema,
96663
96729
  TextInputSchema,
96664
96730
  SelectInputSchema,
96665
- BooleanInputSchema
96731
+ BooleanInputSchema,
96732
+ TimeWindowInputSchema
96666
96733
  ]);
96667
96734
  var TEMPLATE_GROUP_ROWS_MAX = 20;
96668
- var GroupInputSchema = zod.z.object({
96735
+ var groupBase = {
96669
96736
  kind: zod.z.literal("group"),
96670
96737
  ...inputBase,
96671
- inputs: zod.z.array(TemplateScalarInputSchema).min(1).max(10),
96738
+ /** What one row is, in the singular and lower case ("button"): "Add button". */
96739
+ rowLabel: zod.z.string().min(1).max(40).optional(),
96672
96740
  minRows: zod.z.number().int().min(0).max(20).optional(),
96673
96741
  maxRows: zod.z.number().int().min(1).max(20).optional()
96742
+ };
96743
+ /** A group inside a group row: its rows hold values only, never another group. */
96744
+ var NestedGroupInputSchema = zod.z.object({
96745
+ ...groupBase,
96746
+ inputs: zod.z.array(TemplateScalarInputSchema).min(1).max(10)
96747
+ });
96748
+ var TemplateRowInputSchema = zod.z.discriminatedUnion("kind", [...TemplateScalarInputSchema.options, NestedGroupInputSchema]);
96749
+ var GroupInputSchema = zod.z.object({
96750
+ ...groupBase,
96751
+ inputs: zod.z.array(TemplateRowInputSchema).min(1).max(10)
96674
96752
  });
96675
96753
  var TemplateInputSchema = zod.z.discriminatedUnion("kind", [...TemplateScalarInputSchema.options, GroupInputSchema]);
96676
96754
  var TemplatePathSchema = zod.z.array(zod.z.union([zod.z.string().min(1), zod.z.number().int().nonnegative()])).max(24);
@@ -96685,40 +96763,161 @@ var TemplateRowIdBindingSchema = zod.z.object({
96685
96763
  kind: zod.z.literal("row-id"),
96686
96764
  path: TemplatePathSchema
96687
96765
  });
96688
- var TemplateRowItemBindingSchema = zod.z.discriminatedUnion("kind", [TemplateValueBindingSchema, TemplateRowIdBindingSchema]);
96766
+ /**
96767
+ * Appends an `entries` input's elements, verbatim, to the list at `path`. In a
96768
+ * row's bindings `input` is the row's own entries input and `path` is from the
96769
+ * row's item; at the top level, with `in`, it appends the `input` entries of
96770
+ * EVERY row of the group `in` (all buttons' triggers into one `when`), and
96771
+ * without `in` it appends a top-level entries input.
96772
+ */
96773
+ var TemplateEntriesBindingSchema = zod.z.object({
96774
+ kind: zod.z.literal("entries"),
96775
+ input: inputKey,
96776
+ path: TemplatePathSchema,
96777
+ in: inputKey.optional()
96778
+ });
96779
+ /** What fills the item of a row that holds values only. */
96780
+ var TemplateLeafRowBindingSchema = zod.z.discriminatedUnion("kind", [TemplateValueBindingSchema, TemplateRowIdBindingSchema]);
96781
+ /** The ids of a row's nested rows, as a list (a branch that reads every leaf of its row). */
96782
+ var TemplateRowIdsBindingSchema = zod.z.object({
96783
+ kind: zod.z.literal("row-ids"),
96784
+ /** The nested group whose rows are named. */
96785
+ input: inputKey,
96786
+ path: TemplatePathSchema
96787
+ });
96788
+ /** One copy of `item` per nested row, appended inside the parent row's item. */
96789
+ var TemplateNestedRowsBindingSchema = zod.z.object({
96790
+ kind: zod.z.literal("rows"),
96791
+ /** The nested group, declared by the parent row's group. */
96792
+ input: inputKey,
96793
+ /** The list the nested rows are appended to, from the parent row's item. */
96794
+ path: TemplatePathSchema,
96795
+ item: zod.z.unknown(),
96796
+ bindings: zod.z.array(TemplateLeafRowBindingSchema).max(40)
96797
+ });
96798
+ var TemplateRowItemBindingSchema = zod.z.discriminatedUnion("kind", [
96799
+ TemplateValueBindingSchema,
96800
+ TemplateEntriesBindingSchema,
96801
+ TemplateRowIdBindingSchema,
96802
+ TemplateRowIdsBindingSchema,
96803
+ TemplateNestedRowsBindingSchema
96804
+ ]);
96689
96805
  var TemplateRowsBindingSchema = zod.z.object({
96690
96806
  kind: zod.z.literal("rows"),
96691
96807
  input: inputKey,
96808
+ /**
96809
+ * A group the rows of `input` hold: the binding then appends one item per
96810
+ * NESTED row of every row, and its bindings read the nested row.
96811
+ */
96812
+ nested: inputKey.optional(),
96692
96813
  /** The list in the body the rows are appended to. */
96693
96814
  path: TemplatePathSchema,
96694
96815
  /** The JSON copied once per row. */
96695
96816
  item: zod.z.unknown(),
96696
96817
  bindings: zod.z.array(TemplateRowItemBindingSchema).max(40)
96697
96818
  });
96698
- var TemplateBindingSchema = zod.z.discriminatedUnion("kind", [TemplateValueBindingSchema, TemplateRowsBindingSchema]);
96819
+ /** Wraps the condition tree at `path` as `all[time-is, <tree>]` when the input has a value. */
96820
+ var TemplateGateBindingSchema = zod.z.object({
96821
+ kind: zod.z.literal("gate"),
96822
+ /** A top-level `time-window` input. */
96823
+ input: inputKey,
96824
+ path: TemplatePathSchema
96825
+ });
96826
+ var TemplateBindingSchema = zod.z.discriminatedUnion("kind", [
96827
+ TemplateValueBindingSchema,
96828
+ TemplateEntriesBindingSchema,
96829
+ TemplateRowsBindingSchema,
96830
+ TemplateGateBindingSchema
96831
+ ]);
96699
96832
  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",
96833
+ function scalarsOf(inputs) {
96834
+ return inputs.filter((input) => input.kind !== "group");
96835
+ }
96836
+ /** Twice-declared keys and event / action inputs that read no device beside them. */
96837
+ function levelProblems(inputs, path, inRow = false) {
96838
+ const issues = [];
96839
+ const seen = /* @__PURE__ */ new Set();
96840
+ for (const input of inputs) {
96841
+ if (seen.has(input.key)) issues.push({
96705
96842
  message: `input "${input.key}" is declared twice`,
96706
- path: ["inputs", index]
96843
+ path
96707
96844
  });
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
- });
96845
+ seen.add(input.key);
96846
+ if (input.kind === "group") {
96847
+ issues.push(...levelProblems(input.inputs, path, true));
96848
+ continue;
96849
+ }
96850
+ if (input.kind === "time-window" && inRow) issues.push({
96851
+ message: `time window "${input.key}" limits the whole automation: it is not a row input`,
96852
+ path
96853
+ });
96854
+ if (input.kind !== "event" && input.kind !== "action") continue;
96855
+ if (input.deviceInput === void 0) continue;
96856
+ const device = inputs.find((sibling) => sibling.key === input.deviceInput);
96857
+ if (device === void 0 || device.kind !== "device") issues.push({
96858
+ message: `"${input.key}" reads the device input "${input.deviceInput}", which is not a device input beside it`,
96859
+ path
96860
+ });
96861
+ }
96862
+ return issues;
96863
+ }
96864
+ function nestedGroupOf(group, key) {
96865
+ const found = group.inputs.find((input) => input.key === key);
96866
+ return found !== void 0 && found.kind === "group" ? found : void 0;
96867
+ }
96868
+ function leafBindingProblems(bindings, owner) {
96869
+ const issues = [];
96870
+ for (const row of bindings) {
96871
+ if (row.kind === "row-id") continue;
96872
+ if (row.kind === "value") {
96873
+ const input = owner.inputs.find((i) => i.key === row.input);
96874
+ if (input === void 0) issues.push(`row binding names "${row.input}", which group "${owner.key}" does not declare`);
96875
+ else if (input.kind === "group") issues.push(`group "${input.key}" is bound with rows, not a value`);
96876
+ else if (input.kind === "entries") issues.push(`entries "${input.key}" are bound with entries, not a value`);
96877
+ continue;
96878
+ }
96879
+ const nested = owner.inputs.find((i) => i.key === row.input);
96880
+ if (row.kind === "entries") {
96881
+ if (nested === void 0 || nested.kind !== "entries") issues.push(`"${row.input}" is not an entries input inside "${owner.key}"`);
96882
+ continue;
96719
96883
  }
96884
+ if (row.kind === "row-ids") {
96885
+ if (nested === void 0 || nested.kind !== "group" && nested.kind !== "entries") issues.push(`"${row.input}" is not a group or entries input inside "${owner.key}"`);
96886
+ continue;
96887
+ }
96888
+ if (nested === void 0 || nested.kind !== "group") {
96889
+ issues.push(`"${row.input}" is not a group inside "${owner.key}"`);
96890
+ continue;
96891
+ }
96892
+ issues.push(...leafBindingProblems(row.bindings, nested));
96893
+ }
96894
+ return issues;
96895
+ }
96896
+ function rowsBindingProblems(binding, group) {
96897
+ if (binding.nested === void 0) return leafBindingProblems(binding.bindings, group);
96898
+ const nested = nestedGroupOf(group, binding.nested);
96899
+ if (nested === void 0) return [`"${binding.nested}" is not a group inside "${group.key}"`];
96900
+ return leafBindingProblems(binding.bindings, nested);
96901
+ }
96902
+ function bindingProblems(payload, ctx) {
96903
+ const byKey = /* @__PURE__ */ new Map();
96904
+ for (const input of payload.inputs) byKey.set(input.key, input);
96905
+ for (const issue of levelProblems(payload.inputs, ["inputs"])) ctx.addIssue({
96906
+ code: "custom",
96907
+ message: issue.message,
96908
+ path: [...issue.path]
96720
96909
  });
96721
96910
  payload.bindings.forEach((binding, index) => {
96911
+ if (binding.kind === "entries" && binding.in !== void 0) {
96912
+ const group = byKey.get(binding.in);
96913
+ const entries = group !== void 0 && group.kind === "group" ? group.inputs.find((i) => i.key === binding.input) : void 0;
96914
+ if (entries === void 0 || entries.kind !== "entries") ctx.addIssue({
96915
+ code: "custom",
96916
+ message: `"${binding.input}" is not an entries input inside the group "${binding.in}"`,
96917
+ path: ["bindings", index]
96918
+ });
96919
+ return;
96920
+ }
96722
96921
  const input = byKey.get(binding.input);
96723
96922
  if (input === void 0) {
96724
96923
  ctx.addIssue({
@@ -96733,6 +96932,18 @@ function bindingProblems(payload, ctx) {
96733
96932
  message: `group "${input.key}" is bound with rows, not a value`,
96734
96933
  path: ["bindings", index]
96735
96934
  });
96935
+ if (binding.kind === "entries" !== (input.kind === "entries") && binding.kind !== "rows") {
96936
+ if (binding.kind === "entries" || binding.kind === "value") ctx.addIssue({
96937
+ code: "custom",
96938
+ 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`,
96939
+ path: ["bindings", index]
96940
+ });
96941
+ }
96942
+ if (binding.kind === "gate" !== (input.kind === "time-window")) ctx.addIssue({
96943
+ code: "custom",
96944
+ message: `a gate reads a time window and a time window is bound with a gate: "${input.key}" is ${input.kind}`,
96945
+ path: ["bindings", index]
96946
+ });
96736
96947
  if (binding.kind === "rows") {
96737
96948
  if (input.kind !== "group") {
96738
96949
  ctx.addIssue({
@@ -96742,9 +96953,9 @@ function bindingProblems(payload, ctx) {
96742
96953
  });
96743
96954
  return;
96744
96955
  }
96745
- for (const row of binding.bindings) if (row.kind === "value" && !input.inputs.some((i) => i.key === row.input)) ctx.addIssue({
96956
+ for (const message of rowsBindingProblems(binding, input)) ctx.addIssue({
96746
96957
  code: "custom",
96747
- message: `row binding names "${row.input}", which group "${input.key}" does not declare`,
96958
+ message,
96748
96959
  path: ["bindings", index]
96749
96960
  });
96750
96961
  }
@@ -96780,8 +96991,26 @@ function valueProblem(input, value) {
96780
96991
  return input.maxLength !== void 0 && value.length > input.maxLength ? `at most ${input.maxLength} characters` : null;
96781
96992
  case "select": return typeof value === "string" && input.options.some((o) => o.value === value) ? null : "pick one of the options";
96782
96993
  case "boolean": return typeof value === "boolean" ? null : "on or off";
96994
+ case "time-window": {
96995
+ const parsed = TemplateTimeWindowValueSchema.safeParse(value);
96996
+ return parsed.success ? null : parsed.error.issues[0]?.message ?? "pick a time window";
96997
+ }
96998
+ case "entries": return entriesProblem(input, value);
96783
96999
  }
96784
97000
  }
97001
+ /** Each entry is judged by the automation's own schema, then by the kinds the input allows. */
97002
+ function entriesProblem(input, value) {
97003
+ const list = TemplateEntriesValueSchema.safeParse(value);
97004
+ if (!list.success) return "a list of entries is required";
97005
+ if (list.data.length === 0) return "add at least one";
97006
+ if (input.maxItems !== void 0 && list.data.length > input.maxItems) return `at most ${input.maxItems}`;
97007
+ for (const entry of list.data) {
97008
+ const parsed = input.entry === "trigger" ? AutomationWhenSchema.safeParse(entry) : AutomationBranchStepSchema.safeParse(entry);
97009
+ if (!parsed.success) return parsed.error.issues[0]?.message ?? "an entry is not valid";
97010
+ if (!input.allow.includes(parsed.data.kind)) return `"${parsed.data.kind}" is not allowed here`;
97011
+ }
97012
+ return null;
97013
+ }
96785
97014
  function defaultOf(input) {
96786
97015
  switch (input.kind) {
96787
97016
  case "number":
@@ -96811,52 +97040,59 @@ function resolveScalars(inputs, values, prefix, problems) {
96811
97040
  });
96812
97041
  continue;
96813
97042
  }
96814
- const problem = isScalar(raw) ? valueProblem(input, raw) : "a single value is required";
96815
- if (problem !== null || !isScalar(raw)) {
97043
+ const problem = input.kind === "entries" || isScalar(raw) ? valueProblem(input, raw) : "a single value is required";
97044
+ if (problem !== null) {
96816
97045
  problems.push({
96817
97046
  code: "invalid-input",
96818
97047
  input: address,
96819
- detail: problem ?? "invalid value"
97048
+ detail: problem
96820
97049
  });
96821
97050
  continue;
96822
97051
  }
96823
- out.set(input.key, raw);
97052
+ if (input.kind === "entries") out.set(input.key, TemplateEntriesValueSchema.parse(raw));
97053
+ else if (isScalar(raw)) out.set(input.key, raw);
96824
97054
  }
96825
97055
  return out;
96826
97056
  }
96827
- function resolveValues(payload, values, problems) {
96828
- const scalars = resolveScalars(payload.inputs.filter((i) => i.kind !== "group"), values, "", problems);
97057
+ /** The rows of one group, each resolved; `null` when the list itself is refused. */
97058
+ function resolveRows(group, values, prefix, problems) {
97059
+ const address = `${prefix}${group.key}`;
97060
+ const raw = values[group.key] ?? [];
97061
+ if (!isRowList(raw)) {
97062
+ problems.push({
97063
+ code: "invalid-input",
97064
+ input: address,
97065
+ detail: "a list of rows is required"
97066
+ });
97067
+ return null;
97068
+ }
97069
+ const min = group.minRows ?? (group.optional === true ? 0 : 1);
97070
+ const max = group.maxRows ?? 20;
97071
+ if (raw.length < min) {
97072
+ problems.push({
97073
+ code: raw.length === 0 ? "missing-input" : "invalid-input",
97074
+ input: address,
97075
+ detail: `"${group.label}" needs at least ${min} row(s)`
97076
+ });
97077
+ return null;
97078
+ }
97079
+ if (raw.length > max) {
97080
+ problems.push({
97081
+ code: "invalid-input",
97082
+ input: address,
97083
+ detail: `"${group.label}" takes at most ${max} row(s)`
97084
+ });
97085
+ return null;
97086
+ }
97087
+ return raw.map((row, index) => resolveLevel$1(group.inputs, row, `${address}.${index}.`, problems));
97088
+ }
97089
+ function resolveLevel$1(inputs, values, prefix, problems) {
97090
+ const scalars = resolveScalars(scalarsOf(inputs), values, prefix, problems);
96829
97091
  const groups = /* @__PURE__ */ new Map();
96830
- for (const input of payload.inputs) {
97092
+ for (const input of inputs) {
96831
97093
  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)));
97094
+ const rows = resolveRows(input, values, prefix, problems);
97095
+ if (rows !== null) groups.set(input.key, rows);
96860
97096
  }
96861
97097
  return {
96862
97098
  scalars,
@@ -96924,30 +97160,100 @@ function writeValue(root, binding, input, value) {
96924
97160
  default: return setAt(root, binding.path, value);
96925
97161
  }
96926
97162
  }
96927
- function applyRows(root, binding, group, rows) {
96928
- const existing = getAt(root, binding.path);
97163
+ /** The tree at the path, under an `all` beside the window. */
97164
+ function writeGate(root, binding, value) {
97165
+ const window = TemplateTimeWindowValueSchema.parse(value);
97166
+ return setAt(root, binding.path, {
97167
+ kind: "all",
97168
+ children: [{
97169
+ kind: "time-is",
97170
+ ...window
97171
+ }, getAt(root, binding.path)]
97172
+ });
97173
+ }
97174
+ /** The name a row is known by: `buttons-0`, and `buttons-0-events-1` for a nested row. */
97175
+ function rowIdOf(parentId, groupKey, index) {
97176
+ const own = `${groupKey}-${index}`;
97177
+ return parentId === null ? own : `${parentId}-${own}`;
97178
+ }
97179
+ function appendAt(root, path, items, key) {
97180
+ const existing = getAt(root, path);
96929
97181
  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;
97182
+ if (!Array.isArray(list)) throw new PathError(`rows of "${key}" need a list`);
97183
+ return setAt(root, path, [...list, ...items]);
97184
+ }
97185
+ /** The entries a row holds under `key`, each trigger carrying the leaf id the `triggered-by` of its row reads. */
97186
+ function entriesOf$1(row, input, rowId) {
97187
+ const value = row.scalars.get(input.key);
97188
+ const parsed = TemplateEntriesValueSchema.safeParse(value);
97189
+ const entries = parsed.success ? parsed.data : [];
97190
+ if (input.entry !== "trigger") return entries;
97191
+ return entries.map((entry, index) => {
97192
+ const id = Reflect.get(entry, "id");
97193
+ return typeof id === "string" && EVENT_LEAF_ID_RE.test(id) ? entry : {
97194
+ ...entry,
97195
+ id: rowIdOf(rowId, input.key, index)
97196
+ };
96944
97197
  });
96945
- return setAt(root, binding.path, [...list, ...items]);
97198
+ }
97199
+ /** One row's item: the template JSON with the row's values, ids and nested rows written in. */
97200
+ function fillItem(template, bindings, group, row, rowId) {
97201
+ let item = template;
97202
+ for (const binding of bindings) {
97203
+ if (binding.kind === "row-id") {
97204
+ item = setAt(item, binding.path, rowId);
97205
+ continue;
97206
+ }
97207
+ if (binding.kind === "value") {
97208
+ const input = group.inputs.find((i) => i.key === binding.input);
97209
+ const value = row.scalars.get(binding.input);
97210
+ if (input === void 0 || input.kind === "group" || value === void 0) continue;
97211
+ item = writeValue(item, binding, input, value);
97212
+ continue;
97213
+ }
97214
+ const nested = group.inputs.find((i) => i.key === binding.input);
97215
+ if (binding.kind === "entries") {
97216
+ if (nested === void 0 || nested.kind !== "entries") continue;
97217
+ item = appendAt(item, binding.path, entriesOf$1(row, nested, rowId), nested.key);
97218
+ continue;
97219
+ }
97220
+ if (binding.kind === "row-ids" && nested !== void 0 && nested.kind === "entries") {
97221
+ item = setAt(item, binding.path, entriesOf$1(row, nested, rowId).map((entry) => Reflect.get(entry, "id")));
97222
+ continue;
97223
+ }
97224
+ if (nested === void 0 || nested.kind !== "group") continue;
97225
+ const nestedRows = row.groups.get(nested.key) ?? [];
97226
+ if (binding.kind === "row-ids") {
97227
+ item = setAt(item, binding.path, nestedRows.map((_, index) => rowIdOf(rowId, nested.key, index)));
97228
+ continue;
97229
+ }
97230
+ item = appendAt(item, binding.path, nestedRows.map((nestedRow, index) => fillItem(binding.item, binding.bindings, nested, nestedRow, rowIdOf(rowId, nested.key, index))), nested.key);
97231
+ }
97232
+ return item;
97233
+ }
97234
+ function applyRows(root, binding, group, rows) {
97235
+ if (binding.nested === void 0) {
97236
+ const items = rows.map((row, index) => fillItem(binding.item, binding.bindings, group, row, rowIdOf(null, group.key, index)));
97237
+ return appendAt(root, binding.path, items, group.key);
97238
+ }
97239
+ const nested = nestedGroupOf(group, binding.nested);
97240
+ if (nested === void 0) return root;
97241
+ 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))));
97242
+ return appendAt(root, binding.path, items, nested.key);
97243
+ }
97244
+ /** The `input` entries of EVERY row of the group `binding.in`, concatenated onto the list at the path. */
97245
+ function applyEntriesOfRows(root, binding, inputs, resolved) {
97246
+ const group = inputs.find((i) => i.key === binding.in);
97247
+ if (group === void 0 || group.kind !== "group") return root;
97248
+ const entries = group.inputs.find((i) => i.key === binding.input);
97249
+ if (entries === void 0 || entries.kind !== "entries") return root;
97250
+ const items = (resolved.groups.get(group.key) ?? []).flatMap((row, index) => entriesOf$1(row, entries, rowIdOf(null, group.key, index)));
97251
+ return appendAt(root, binding.path, items, entries.key);
96946
97252
  }
96947
97253
  /** The body with the values written in, as a recipe — or every reason it is not one. */
96948
97254
  function expandAutomationTemplate(payload, values) {
96949
97255
  const problems = [];
96950
- const resolved = resolveValues(payload, values, problems);
97256
+ const resolved = resolveLevel$1(payload.inputs, values, "", problems);
96951
97257
  if (problems.length > 0) return {
96952
97258
  ok: false,
96953
97259
  problems
@@ -96955,6 +97261,10 @@ function expandAutomationTemplate(payload, values) {
96955
97261
  let body = payload.body;
96956
97262
  try {
96957
97263
  for (const binding of payload.bindings) {
97264
+ if (binding.kind === "entries" && binding.in !== void 0) {
97265
+ body = applyEntriesOfRows(body, binding, payload.inputs, resolved);
97266
+ continue;
97267
+ }
96958
97268
  const input = payload.inputs.find((i) => i.key === binding.input);
96959
97269
  if (input === void 0) continue;
96960
97270
  if (binding.kind === "rows") {
@@ -96965,7 +97275,12 @@ function expandAutomationTemplate(payload, values) {
96965
97275
  if (input.kind === "group") continue;
96966
97276
  const value = resolved.scalars.get(input.key);
96967
97277
  if (value === void 0) continue;
96968
- body = writeValue(body, binding, input, value);
97278
+ if (binding.kind === "entries") {
97279
+ const list = TemplateEntriesValueSchema.safeParse(value);
97280
+ if (list.success) body = appendAt(body, binding.path, list.data, input.key);
97281
+ continue;
97282
+ }
97283
+ body = binding.kind === "gate" ? writeGate(body, binding, value) : writeValue(body, binding, input, value);
96969
97284
  }
96970
97285
  } catch (error) {
96971
97286
  if (!(error instanceof PathError)) throw error;
@@ -105272,12 +105587,30 @@ function flipperIrDraft(file, target) {
105272
105587
  * migration and nothing an operator saved is ever overwritten.
105273
105588
  */
105274
105589
  var BUILTIN_TEMPLATE_ID_PREFIX = "builtin:";
105590
+ /** One choose branch per row, so the rows a group takes are the branches a choose takes. */
105591
+ var BUTTON_ROWS_MAX = 6;
105592
+ var ROW_ENTRIES_MAX = 10;
105593
+ /** The optional limit both built-ins end with: no value, no limit. */
105594
+ var ACTIVE_WINDOW_KEY = "active";
105595
+ var activeWindowInput = {
105596
+ kind: "time-window",
105597
+ key: ACTIVE_WINDOW_KEY,
105598
+ label: "Only when",
105599
+ description: "Limit the automation to a time of day, to some days, or both.",
105600
+ optional: true
105601
+ };
105602
+ /** Declared last: it moves the tree the other bindings write into one level down. */
105603
+ var activeWindowGate = {
105604
+ kind: "gate",
105605
+ input: ACTIVE_WINDOW_KEY,
105606
+ path: ["when"]
105607
+ };
105275
105608
  var BUILTIN_AUTOMATION_TEMPLATES = [{
105276
105609
  id: `${BUILTIN_TEMPLATE_ID_PREFIX}buttons-to-devices`,
105277
105610
  name: "Buttons → devices",
105278
105611
  payload: {
105279
105612
  version: 1,
105280
- description: "Each row: when a button sends an event, run an action on a set of devices.",
105613
+ description: "Each button: when it sends an event, run one or more actions.",
105281
105614
  body: {
105282
105615
  when: {
105283
105616
  kind: "any",
@@ -105296,96 +105629,58 @@ var BUILTIN_AUTOMATION_TEMPLATES = [{
105296
105629
  kind: "group",
105297
105630
  key: "buttons",
105298
105631
  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" }]
105632
+ rowLabel: "button",
105633
+ maxRows: BUTTON_ROWS_MAX,
105634
+ inputs: [{
105635
+ kind: "entries",
105636
+ key: "when",
105637
+ label: "When",
105638
+ entry: "trigger",
105639
+ allow: ["device-fired"],
105640
+ maxItems: ROW_ENTRIES_MAX
105641
+ }, {
105642
+ kind: "entries",
105643
+ key: "do",
105644
+ label: "Actions",
105645
+ entry: "step",
105646
+ allow: ["command"],
105647
+ maxItems: ROW_ENTRIES_MAX
105648
+ }]
105649
+ }, activeWindowInput],
105650
+ bindings: [
105651
+ {
105652
+ kind: "entries",
105653
+ input: "when",
105654
+ in: "buttons",
105655
+ path: ["when", "children"]
105362
105656
  },
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"
105657
+ {
105658
+ kind: "rows",
105659
+ input: "buttons",
105660
+ path: [
105661
+ "actions",
105662
+ 0,
105663
+ "branches"
105664
+ ],
105665
+ item: {
105666
+ if: {
105667
+ kind: "triggered-by",
105668
+ leafIds: []
105669
+ },
105670
+ steps: []
105381
105671
  },
105382
- {
105383
- kind: "value",
105384
- input: "action",
105385
- path: ["steps", 0]
105386
- }
105387
- ]
105388
- }]
105672
+ bindings: [{
105673
+ kind: "row-ids",
105674
+ input: "when",
105675
+ path: ["if", "leafIds"]
105676
+ }, {
105677
+ kind: "entries",
105678
+ input: "do",
105679
+ path: ["steps"]
105680
+ }]
105681
+ },
105682
+ activeWindowGate
105683
+ ]
105389
105684
  }
105390
105685
  }, {
105391
105686
  id: `${BUILTIN_TEMPLATE_ID_PREFIX}motion-light`,
@@ -105437,7 +105732,8 @@ var BUILTIN_AUTOMATION_TEMPLATES = [{
105437
105732
  min: 10,
105438
105733
  max: 3600,
105439
105734
  default: 300
105440
- }
105735
+ },
105736
+ activeWindowInput
105441
105737
  ],
105442
105738
  bindings: [
105443
105739
  {
@@ -105473,7 +105769,8 @@ var BUILTIN_AUTOMATION_TEMPLATES = [{
105473
105769
  "target"
105474
105770
  ],
105475
105771
  as: "target"
105476
- }
105772
+ },
105773
+ activeWindowGate
105477
105774
  ]
105478
105775
  }
105479
105776
  }];
@@ -148279,6 +148576,7 @@ exports.SystemHeldSecretNameSchema = SystemHeldSecretNameSchema;
148279
148576
  exports.SystemMetricsSchema = SystemMetricsSchema;
148280
148577
  exports.SystemMirror = SystemMirror;
148281
148578
  exports.TARGET_OWNER_KEY = TARGET_OWNER_KEY;
148579
+ exports.TEMPLATE_ENTRIES_MAX = TEMPLATE_ENTRIES_MAX;
148282
148580
  exports.TEMPLATE_GROUP_ROWS_MAX = TEMPLATE_GROUP_ROWS_MAX;
148283
148581
  exports.TEMPLATE_INPUT_KEY_RE = TEMPLATE_INPUT_KEY_RE;
148284
148582
  exports.TEMPLATE_INSTANCE_PROBLEM_CODES = TEMPLATE_INSTANCE_PROBLEM_CODES;
@@ -148310,21 +148608,32 @@ exports.TemplateAutomationUserSchema = TemplateAutomationUserSchema;
148310
148608
  exports.TemplateBindingSchema = TemplateBindingSchema;
148311
148609
  exports.TemplateDeleteResultSchema = TemplateDeleteResultSchema;
148312
148610
  exports.TemplateDeviceFilterSchema = TemplateDeviceFilterSchema;
148611
+ exports.TemplateEntriesBindingSchema = TemplateEntriesBindingSchema;
148612
+ exports.TemplateEntriesValueSchema = TemplateEntriesValueSchema;
148613
+ exports.TemplateEntrySchema = TemplateEntrySchema;
148313
148614
  exports.TemplateEventValueSchema = TemplateEventValueSchema;
148615
+ exports.TemplateGateBindingSchema = TemplateGateBindingSchema;
148314
148616
  exports.TemplateGroupRowSchema = TemplateGroupRowSchema;
148315
148617
  exports.TemplateInputSchema = TemplateInputSchema;
148316
148618
  exports.TemplateInputValueSchema = TemplateInputValueSchema;
148317
148619
  exports.TemplateInputValuesSchema = TemplateInputValuesSchema;
148318
148620
  exports.TemplateInstanceProblemSchema = TemplateInstanceProblemSchema;
148319
148621
  exports.TemplateKindSchema = TemplateKindSchema;
148622
+ exports.TemplateLeafRowBindingSchema = TemplateLeafRowBindingSchema;
148623
+ exports.TemplateNestedRowSchema = TemplateNestedRowSchema;
148624
+ exports.TemplateNestedRowsBindingSchema = TemplateNestedRowsBindingSchema;
148320
148625
  exports.TemplatePathSchema = TemplatePathSchema;
148321
148626
  exports.TemplateRecordSchema = TemplateRecordSchema;
148322
148627
  exports.TemplateRowIdBindingSchema = TemplateRowIdBindingSchema;
148628
+ exports.TemplateRowIdsBindingSchema = TemplateRowIdsBindingSchema;
148629
+ exports.TemplateRowInputSchema = TemplateRowInputSchema;
148323
148630
  exports.TemplateRowItemBindingSchema = TemplateRowItemBindingSchema;
148631
+ exports.TemplateRowValueSchema = TemplateRowValueSchema;
148324
148632
  exports.TemplateRowsBindingSchema = TemplateRowsBindingSchema;
148325
148633
  exports.TemplateScalarInputSchema = TemplateScalarInputSchema;
148326
148634
  exports.TemplateScalarValueSchema = TemplateScalarValueSchema;
148327
148635
  exports.TemplateSelectOptionSchema = TemplateSelectOptionSchema;
148636
+ exports.TemplateTimeWindowValueSchema = TemplateTimeWindowValueSchema;
148328
148637
  exports.TemplateUserSchema = TemplateUserSchema;
148329
148638
  exports.TemplateValueBindingSchema = TemplateValueBindingSchema;
148330
148639
  exports.TemplateWriteResultSchema = TemplateWriteResultSchema;