@camstack/addon-admin-ui 1.2.22 → 1.2.24

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.
Files changed (88) hide show
  1. package/dist/assets/{AddLocationWizard-CXH0Vd7P.js → AddLocationWizard-CgB5ALok.js} +1 -1
  2. package/dist/assets/{AddonCollectionPage-BDrreBA_.js → AddonCollectionPage-I9ngkQ84.js} +1 -1
  3. package/dist/assets/{Addons-BBee3W_5.js → Addons-Ub09GUoM.js} +1 -1
  4. package/dist/assets/{AdminTabs-C2h2Ess6.js → AdminTabs-DF-cmHVR.js} +1 -1
  5. package/dist/assets/{AiProfiles-CaMvgEcu.js → AiProfiles-Cpq2EqRN.js} +1 -1
  6. package/dist/assets/{BrokerForm-Dg4179gd.js → BrokerForm-CO4m8BGx.js} +1 -1
  7. package/dist/assets/{Capabilities-CTViRMUz.js → Capabilities-ncknL-cJ.js} +1 -1
  8. package/dist/assets/{CapabilityBadges-CWTCenZn.js → CapabilityBadges-DCp3HETl.js} +1 -1
  9. package/dist/assets/{Cluster-CyCE0oc3.js → Cluster-CMN6Euut.js} +1 -1
  10. package/dist/assets/{ClusterRecordingTab-BFeUBRQL.js → ClusterRecordingTab-BSX2nCPb.js} +1 -1
  11. package/dist/assets/{Dashboard-kAuj8Qql.js → Dashboard-XQiQ_Lg-.js} +1 -1
  12. package/dist/assets/{Data-cxkPOpjt.js → Data-Cb_aElt7.js} +1 -1
  13. package/dist/assets/{DetectionIntelligence-BhkMTGhd.js → DetectionIntelligence-eCwufqeU.js} +1 -1
  14. package/dist/assets/{DeviceAggregateSection-nG_okgKX.js → DeviceAggregateSection-C8Bk2yJE.js} +1 -1
  15. package/dist/assets/{DeviceDetail-Bn6Ds2YE.js → DeviceDetail-CEGDs4jR.js} +2 -2
  16. package/dist/assets/{Devices-B95hLZbr.js → Devices-kiE5g8bT.js} +1 -1
  17. package/dist/assets/{EmbedPlayerPage-D7BKC58D.js → EmbedPlayerPage-DWb2EdAN.js} +1 -1
  18. package/dist/assets/Events-C0yucTk2.js +1 -0
  19. package/dist/assets/{FormBuilder-DjEl_aGp.js → FormBuilder-DkGEsqWw.js} +1 -1
  20. package/dist/assets/{Identity-60VJAx02.js → Identity-CvUP3bvU.js} +1 -1
  21. package/dist/assets/{IntegrationDetail-BjZloyK4.js → IntegrationDetail-B1ayr0Ls.js} +1 -1
  22. package/dist/assets/{Integrations-CxEpaCLq.js → Integrations-BRCLFljo.js} +1 -1
  23. package/dist/assets/{Integrations-D9v-_8r-.js → Integrations-BvZls46H.js} +1 -1
  24. package/dist/assets/{Logs-C7F-ma4x.js → Logs-DR3tC8jQ.js} +1 -1
  25. package/dist/assets/{MotionZonesSettings-DSIn5-s5.js → MotionZonesSettings-vvcuI785.js} +1 -1
  26. package/dist/assets/{MyAccess-t85_pORz.js → MyAccess-Bb3hweWF.js} +1 -1
  27. package/dist/assets/{Network-D7V-dc6V.js → Network-D2Sahtb3.js} +1 -1
  28. package/dist/assets/{NodeAddonsSettingsPanel-ujvGtNzi.js → NodeAddonsSettingsPanel-Bc019Nxo.js} +1 -1
  29. package/dist/assets/{NodeInferenceDevices-fwySdAtB.js → NodeInferenceDevices--X2ZBi8J.js} +1 -1
  30. package/dist/assets/Notifications-ClSRJKG1.js +1 -0
  31. package/dist/assets/{Pipeline-CA-9DIEs.js → Pipeline-4g8p1bSW.js} +1 -1
  32. package/dist/assets/{Plates-BWcRlxDR.js → Plates-DMFRbk4F.js} +1 -1
  33. package/dist/assets/{PrivacyMaskSettings-Bfj57HiI.js → PrivacyMaskSettings-B6nNr_2h.js} +1 -1
  34. package/dist/assets/{ProviderIcon-Bu6M7fez.js → ProviderIcon-BoDEYsXZ.js} +1 -1
  35. package/dist/assets/{Recordings-DqkJ9Ane.js → Recordings-BrEh7_wl.js} +1 -1
  36. package/dist/assets/{ScanNetworkModal-CkeHCFgJ.js → ScanNetworkModal-DWkO7wZJ.js} +1 -1
  37. package/dist/assets/{Settings-CTvsgafi.js → Settings-BVn0t4hg.js} +1 -1
  38. package/dist/assets/{Showroom-B43mwuk7.js → Showroom-B-Ux9V_z.js} +1 -1
  39. package/dist/assets/{Terminal-BDSI390X.js → Terminal-Gh0oz9Yc.js} +1 -1
  40. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-W4TOU_HF.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-DOCRSFyJ.js} +1 -1
  41. package/dist/assets/{build-cluster-graph-C4zGQLGF.js → build-cluster-graph-CUr-nl71.js} +1 -1
  42. package/dist/assets/circle-check-big-fNboDlgj.js +1 -0
  43. package/dist/assets/clock-CAu-89mc.js +1 -0
  44. package/dist/assets/{copy-BgYRNf8b.js → copy-q2X4KVh5.js} +1 -1
  45. package/dist/assets/{debounced-invalidate-o_asci0-.js → debounced-invalidate-CpgU0hhF.js} +1 -1
  46. package/dist/assets/dist-CA_1rlan.js +7 -0
  47. package/dist/assets/{dist-CYCjmuN8.js → dist-DbYf3Te7.js} +1 -1
  48. package/dist/assets/{download-CdPioKV1.js → download-DrPLvRE4.js} +1 -1
  49. package/dist/assets/{face-bbox-BpDfTsFx.js → face-bbox-BdKwq6zH.js} +1 -1
  50. package/dist/assets/{hostInit-DJ_7rd1-.js → hostInit-BsLsKkXH.js} +1 -1
  51. package/dist/assets/{index-D0JhMwHm.js → index-CLX20uzg.js} +3 -3
  52. package/dist/assets/{key-round-DDzoqyJC.js → key-round-DVWi8Yi8.js} +1 -1
  53. package/dist/assets/{mf-entry-bootstrap-0-7d8a6853.js → mf-entry-bootstrap-0-524d38f3.js} +2 -2
  54. package/dist/assets/{pencil-DjXB5Bxq.js → pencil-lnjhp8cI.js} +1 -1
  55. package/dist/assets/{player-overlays-BfUh6z3V.js → player-overlays-vzsKaS7H.js} +1 -1
  56. package/dist/assets/plus-B6wbhFAQ.js +1 -0
  57. package/dist/assets/{radio-DdH4qqug.js → radio-2fUydobf.js} +1 -1
  58. package/dist/assets/{refresh-cw-BSTOsxS_.js → refresh-cw-DUdl_39U.js} +1 -1
  59. package/dist/assets/remoteEntry-D5KY8VHd.js +1 -0
  60. package/dist/assets/{rotate-ccw-DIwpplTj.js → rotate-ccw-CD_GOnzF.js} +1 -1
  61. package/dist/assets/rotate-cw-zPUlFGEb.js +1 -0
  62. package/dist/assets/search-DvH2G5kM.js +1 -0
  63. package/dist/assets/{send-CcHJh0KO.js → send-BEeC9iCi.js} +1 -1
  64. package/dist/assets/{server-DwOZ36mY.js → server-At2O0gqf.js} +1 -1
  65. package/dist/assets/{square-check-big-D7LCZj5L.js → square-check-big-BBq340ze.js} +1 -1
  66. package/dist/assets/square-xoDen5l2.js +1 -0
  67. package/dist/assets/src-BzjlKhkF.js +7 -0
  68. package/dist/assets/src-DtiRwjyP.js +67 -0
  69. package/dist/assets/{upload-Tv3ztf7H.js → upload-BE7lrxW5.js} +1 -1
  70. package/dist/assets/{useEventInvalidation-CQK0jRw6.js → useEventInvalidation-BqsGizNE.js} +1 -1
  71. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-B_wRVm4F.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-CGirr1QS.js} +2 -2
  72. package/dist/assets/{wifi-C6b9pnss.js → wifi-BiNIrgv1.js} +1 -1
  73. package/dist/assets/{zap-CWvZQmfa.js → zap-DdVdoFv8.js} +1 -1
  74. package/dist/index.html +5 -5
  75. package/dist/server/addon.js +245 -12
  76. package/package.json +1 -1
  77. package/dist/assets/Events-CQFwNvkG.js +0 -1
  78. package/dist/assets/Notifications-CUekQNjA.js +0 -1
  79. package/dist/assets/circle-check-big-C-IoJG5A.js +0 -1
  80. package/dist/assets/clock-J8ftFeJL.js +0 -1
  81. package/dist/assets/dist-ygAVnmuC.js +0 -7
  82. package/dist/assets/plus-BEbdi_Iz.js +0 -1
  83. package/dist/assets/remoteEntry-BVkvjsQm.js +0 -1
  84. package/dist/assets/rotate-cw-EHQK_WNV.js +0 -1
  85. package/dist/assets/search-BK_1ulaR.js +0 -1
  86. package/dist/assets/square-nYV2-xBc.js +0 -1
  87. package/dist/assets/src-D11G7q5Q.js +0 -7
  88. package/dist/assets/src-DmLu_IGX.js +0 -67
@@ -1,6 +1,6 @@
1
1
  import path from "node:path";
2
2
  import { fileURLToPath } from "node:url";
3
- //#region ../types/dist/event-category-Bz24uP1U.mjs
3
+ //#region ../types/dist/event-category-41fKf-q9.mjs
4
4
  var EventCategory = /* @__PURE__ */ function(EventCategory) {
5
5
  EventCategory["SystemBoot"] = "system.boot";
6
6
  EventCategory["SystemAddonsReady"] = "system.addons-ready";
@@ -60,6 +60,26 @@ var EventCategory = /* @__PURE__ */ function(EventCategory) {
60
60
  */
61
61
  EventCategory["AddonRetryScheduled"] = "addon.retry-scheduled";
62
62
  /**
63
+ * A liveness invariant of this node is false — it has no devices, every
64
+ * camera is offline, or a camera that was recording has stopped producing
65
+ * segments. Emitted by the `liveness-monitor` builtin, once per fault (the
66
+ * `findingId` is stable across ticks), only after its boot grace period.
67
+ * AlertCenter raises a persistent operator-visible alert.
68
+ *
69
+ * It exists because on 2026-08-03 the hub ran four hours with zero devices
70
+ * and zero recordings while every surface stayed quiet.
71
+ *
72
+ * Payload: `{ findingId, severity, title, message, deviceId? }`.
73
+ */
74
+ EventCategory["SystemLivenessFailed"] = "system.liveness-failed";
75
+ /**
76
+ * A previously reported liveness fault is true again. AlertCenter dismisses
77
+ * the matching `SystemLivenessFailed` alert.
78
+ *
79
+ * Payload: `{ findingId }`.
80
+ */
81
+ EventCategory["SystemLivenessRecovered"] = "system.liveness-recovered";
82
+ /**
63
83
  * Monitor is attempting to reload a failed addon NOW. UI uses this
64
84
  * to show a spinner during the retry attempt. Same transient nature
65
85
  * as AddonRetryScheduled.
@@ -9100,11 +9120,13 @@ var NcZoneConditionSchema = object({
9100
9120
  /** Quantifier over `ids` — at least one / every one visited. */
9101
9121
  match: _enum(["any", "all"]).default("any")
9102
9122
  });
9103
- /**
9104
- * The P1 condition set — a flat AND of groups; absent group = pass;
9105
- * membership lists are OR within the list (spec §2.3).
9106
- */
9107
9123
  var NcConditionsSchema = object({
9124
+ /** Gate on ANOTHER device's current state (the alarm armed, a switch on). */
9125
+ deviceState: object({
9126
+ deviceId: number().int(),
9127
+ /** Any of these matches. */
9128
+ states: array(string().min(1)).min(1)
9129
+ }).optional(),
9108
9130
  /** Device scope — absent = all devices. */
9109
9131
  devices: array(number()).optional(),
9110
9132
  /** Detector class names (any overlap with the record's class set). */
@@ -9305,6 +9327,14 @@ var NcMediaPolicySchema = object({
9305
9327
  clipPreRollSec: number().int().min(0).max(30).optional(),
9306
9328
  clipPostRollSec: number().int().min(0).max(30).optional(),
9307
9329
  /**
9330
+ * Playback rate of the attached gif / clip. Absent = 2x.
9331
+ *
9332
+ * A notification clip is GLANCED at on a lock screen, not watched: at real
9333
+ * time an eight-second passage is eight seconds of the recipient's attention
9334
+ * and twice the bytes. 1 is real time for the operator who wants it.
9335
+ */
9336
+ clipSpeed: number().min(1).max(8).optional(),
9337
+ /**
9308
9338
  * Which stream profile the footage is cut from. Absent = the CHEAPEST
9309
9339
  * assigned profile: a notification is watched on a phone, so the 4K
9310
9340
  * rendition would burn CPU to produce a file the client downscales anyway.
@@ -9376,7 +9406,21 @@ var NcRuleInputSchema = object({
9376
9406
  * behaviour, visible to all, read-only in the viewer). Present = personal
9377
9407
  * rule owned by this userId. Server-stamped; never trusted from a client.
9378
9408
  */
9379
- ownerUserId: string().optional()
9409
+ ownerUserId: string().optional(),
9410
+ /**
9411
+ * May a non-admin snooze this rule for EVERYONE, not just themselves?
9412
+ *
9413
+ * A snooze is personal by default — it silences the person who set it. This
9414
+ * opts THIS rule into the "the gardener is here all afternoon" case, where
9415
+ * silencing the camera for the whole household is legitimate. It silences
9416
+ * other people, so it is off unless a rule deliberately allows it.
9417
+ *
9418
+ * `.optional()`, deliberately NOT `.default()`: a Zod default does not run on
9419
+ * the addon cap path (three production failures in one day), so absent is
9420
+ * read as `false` by {@link canSetGlobal} in the engine. Admins are not bound
9421
+ * by this flag — see the scope rules on that function.
9422
+ */
9423
+ snoozeAllowGlobal: boolean().optional()
9380
9424
  });
9381
9425
  /**
9382
9426
  * Partial patch for `updateRule` — any subset of the input fields, plus the
@@ -9447,7 +9491,8 @@ var NcConditionDescriptorSchema = object({
9447
9491
  "packagePhase",
9448
9492
  "crossingSelect",
9449
9493
  "polygonDraw",
9450
- "occupancy"
9494
+ "occupancy",
9495
+ "deviceState"
9451
9496
  ]),
9452
9497
  operator: _enum([
9453
9498
  "in",
@@ -9461,7 +9506,28 @@ var NcConditionDescriptorSchema = object({
9461
9506
  /** Which delivery kinds the condition applies to. */
9462
9507
  appliesTo: array(NcDeliverySchema),
9463
9508
  phase: string(),
9464
- description: string().optional()
9509
+ description: string().optional(),
9510
+ /**
9511
+ * The CHOICES for a single-choice widget (`sourceSelect`, `crossingSelect`,
9512
+ * `packagePhase`, …), served with the descriptor.
9513
+ *
9514
+ * Before this the descriptor said which widget to render and not what to put
9515
+ * in it, so every option list lived in three places: this file's enums, the
9516
+ * admin's `NC_*_OPTIONS` and the viewer's `NC_*_VALUES`. That triple mirror
9517
+ * is the drift that emptied the viewer's rule editor on 2026-08-04 — the app
9518
+ * mirrors the cap by hand, so it is only ever as current as its last build.
9519
+ *
9520
+ * With the options on the wire, a condition of an EXISTING `valueType` costs
9521
+ * zero client changes. Clients keep a local fallback for an older hub that
9522
+ * does not send them; absent here is "use your own list", not "no choices".
9523
+ */
9524
+ options: array(object({
9525
+ /** Written to the rule verbatim. `''` means the ABSENT state. */
9526
+ value: string(),
9527
+ label: string(),
9528
+ /** What THIS choice matches — shown one at a time, under the control. */
9529
+ hint: string().optional()
9530
+ })).readonly().optional()
9465
9531
  });
9466
9532
  /**
9467
9533
  * The delivery lifecycle status of a history row — a straight read of the
@@ -9546,6 +9612,74 @@ var NcHistoryFilterSchema = object({
9546
9612
  until: number().optional(),
9547
9613
  limit: number().int().min(1).max(500).default(100)
9548
9614
  });
9615
+ /**
9616
+ * What a snooze covers. Broader scopes win when several overlap, so one window
9617
+ * leaves ONE digest rather than a rule snooze and a whole-feed snooze both
9618
+ * summarising the same silence.
9619
+ */
9620
+ var NcSnoozeScopeSchema = _enum([
9621
+ "rule",
9622
+ "device",
9623
+ "all"
9624
+ ]);
9625
+ /**
9626
+ * Client-authored snooze. The server stamps `userId`, `startedAt` and
9627
+ * `expiresAt` — a DURATION is sent rather than an instant so a client with a
9628
+ * skewed clock cannot author a window that is already over, or never ends.
9629
+ */
9630
+ var NcSnoozeInputSchema = object({
9631
+ scope: NcSnoozeScopeSchema,
9632
+ /** Required when `scope: 'rule'` — a scoped snooze with no id matches
9633
+ * NOTHING rather than degrading to "everything". */
9634
+ ruleId: string().optional(),
9635
+ /** Required when `scope: 'device'`. */
9636
+ deviceId: number().int().optional(),
9637
+ durationMinutes: number().int().min(1).max(1440),
9638
+ /**
9639
+ * Silence this for EVERY recipient, not just the caller. Permission is
9640
+ * checked server-side (the rule's `snoozeAllowGlobal`, or admin for the
9641
+ * broader scopes). Absent = personal.
9642
+ */
9643
+ global: boolean().optional(),
9644
+ /**
9645
+ * Deliver a summary of what was suppressed when the window ends. Absent =
9646
+ * ON: someone silencing a nuisance camera wants it off, someone silencing a
9647
+ * SECURITY camera wants to know what they missed, and choosing "off" for
9648
+ * everybody is how a snooze becomes an outage. Resolved to a concrete
9649
+ * boolean by the server at create time — never left to a Zod default, which
9650
+ * does not run on the addon cap path.
9651
+ */
9652
+ summary: boolean().optional()
9653
+ });
9654
+ /** A persisted snooze window. */
9655
+ var NcSnoozeSchema = object({
9656
+ id: string(),
9657
+ /** Who set it. Also who it silences, unless `global`. */
9658
+ userId: string(),
9659
+ scope: NcSnoozeScopeSchema,
9660
+ ruleId: string().optional(),
9661
+ deviceId: number().int().optional(),
9662
+ startedAt: number(),
9663
+ /** Exclusive: at exactly this instant the snooze is over. Expiry is a
9664
+ * COMPARISON, not a job — no sweeper can leave the operator silenced. */
9665
+ expiresAt: number(),
9666
+ global: boolean(),
9667
+ summary: boolean(),
9668
+ /** When the end-of-window digest went out. Absent = not sent (yet, or the
9669
+ * window has not closed, or `summary` is false). */
9670
+ digestSentAt: number().optional()
9671
+ });
9672
+ object({
9673
+ snoozeId: string(),
9674
+ targetId: string(),
9675
+ ruleId: string(),
9676
+ ruleName: string(),
9677
+ deviceId: number().int(),
9678
+ /** How many notifications this snooze hid for that pair. */
9679
+ count: number().int(),
9680
+ firstAt: number(),
9681
+ lastAt: number()
9682
+ });
9549
9683
  method(object({}), object({ rules: array(NcRuleSchema) }), { auth: "admin" }), method(object({ ruleId: string() }), object({ rule: NcRuleSchema.nullable() }), { auth: "admin" }), method(object({ rule: NcRuleInputSchema }), object({ rule: NcRuleSchema }), {
9550
9684
  kind: "mutation",
9551
9685
  auth: "admin",
@@ -9575,7 +9709,13 @@ method(object({}), object({ rules: array(NcRuleSchema) }), { auth: "admin" }), m
9575
9709
  }), method(object({}), object({
9576
9710
  catalog: array(NcConditionDescriptorSchema),
9577
9711
  taxonomy: NcTaxonomySchema.optional()
9578
- })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" });
9712
+ })), method(object({ filter: NcHistoryFilterSchema.default({ limit: 100 }) }), object({ entries: array(NcHistoryEntrySchema) }), { auth: "admin" }), method(object({}), object({ snoozes: array(NcSnoozeSchema) }), { caller: "required" }), method(object({ snooze: NcSnoozeInputSchema }), object({ snooze: NcSnoozeSchema }), {
9713
+ kind: "mutation",
9714
+ caller: "required"
9715
+ }), method(object({ snoozeId: string() }), object({ success: literal(true) }), {
9716
+ kind: "mutation",
9717
+ caller: "required"
9718
+ });
9579
9719
  /**
9580
9720
  * TimelapseRule — the STANDALONE scheduled timelapse producer's rule model.
9581
9721
  *
@@ -10323,7 +10463,15 @@ method(object({
10323
10463
  format: _enum(["gif", "mp4"]).default("gif"),
10324
10464
  maxWidth: number().int().min(120).max(1920).default(480),
10325
10465
  /** GIF only — MP4 keeps the source cadence. */
10326
- fps: number().int().min(1).max(15).default(5)
10466
+ fps: number().int().min(1).max(15).default(5),
10467
+ /**
10468
+ * Playback rate. A notification clip is GLANCED at on a lock screen,
10469
+ * not watched, so 2x is the default: the recipient sees the whole
10470
+ * passage in half the time and the GIF is half the bytes. `1` is real
10471
+ * time. Applies to MP4 as well — the operator set a speed, not a GIF
10472
+ * speed.
10473
+ */
10474
+ speed: number().min(1).max(8).default(2)
10327
10475
  }), object({
10328
10476
  base64: string(),
10329
10477
  mime: string(),
@@ -15082,6 +15230,20 @@ var QueryFilterSchema = object({
15082
15230
  limit: number().optional(),
15083
15231
  offset: number().optional()
15084
15232
  });
15233
+ /**
15234
+ * The predicate half of a filter, for BULK MUTATIONS.
15235
+ *
15236
+ * Deliberately not `QueryFilterSchema`: `orderBy` / `limit` / `offset` have no
15237
+ * meaning for a statement that rewrites a set, and accepting them would invite
15238
+ * a caller to believe `limit` bounds the damage. Every field is optional here
15239
+ * only so the shape stays composable — the implementation REJECTS a filter
15240
+ * that compiles to no predicate, because that is the whole collection.
15241
+ */
15242
+ var MutationFilterSchema = object({
15243
+ where: record(string(), unknown()).optional(),
15244
+ whereIn: record(string(), array(unknown())).optional(),
15245
+ whereBetween: record(string(), tuple([unknown(), unknown()])).optional()
15246
+ });
15085
15247
  /** A single stored record: `{ id, data }`. */
15086
15248
  var SettingsRecordSchema = object({
15087
15249
  id: string(),
@@ -15107,7 +15269,18 @@ var CollectionColumnSchema = object({
15107
15269
  ]),
15108
15270
  primaryKey: boolean().optional(),
15109
15271
  notNull: boolean().optional(),
15110
- unique: boolean().optional()
15272
+ unique: boolean().optional(),
15273
+ /**
15274
+ * Column DEFAULT. Required for B2: the four `ensureTable` consumers declare
15275
+ * columns like `enabled INTEGER NOT NULL DEFAULT 1`, and without this the
15276
+ * collection surface simply cannot express their existing tables — which is
15277
+ * why they were still on the uncapped `table*` API.
15278
+ */
15279
+ defaultValue: union([
15280
+ string(),
15281
+ number(),
15282
+ boolean()
15283
+ ]).optional()
15111
15284
  });
15112
15285
  var CollectionIndexSchema = object({
15113
15286
  name: string(),
@@ -15141,6 +15314,15 @@ method(object({
15141
15314
  collection: string(),
15142
15315
  key: string()
15143
15316
  }), _void(), { kind: "mutation" }), method(object({
15317
+ namespace: string().optional(),
15318
+ collection: string(),
15319
+ filter: MutationFilterSchema
15320
+ }), object({ deleted: number().int() }), { kind: "mutation" }), method(object({
15321
+ namespace: string().optional(),
15322
+ collection: string(),
15323
+ filter: MutationFilterSchema,
15324
+ data: record(string(), unknown())
15325
+ }), object({ updated: number().int() }), { kind: "mutation" }), method(object({
15144
15326
  namespace: string().optional(),
15145
15327
  collection: string(),
15146
15328
  filter: QueryFilterSchema.optional()
@@ -15207,6 +15389,15 @@ method(_void(), EngineInfoSchema), method(object({
15207
15389
  collection: string(),
15208
15390
  key: string()
15209
15391
  }), _void(), { kind: "mutation" }), method(object({
15392
+ namespace: string().optional(),
15393
+ collection: string(),
15394
+ filter: MutationFilterSchema
15395
+ }), object({ deleted: number().int() }), { kind: "mutation" }), method(object({
15396
+ namespace: string().optional(),
15397
+ collection: string(),
15398
+ filter: MutationFilterSchema,
15399
+ data: record(string(), unknown())
15400
+ }), object({ updated: number().int() }), { kind: "mutation" }), method(object({
15210
15401
  namespace: string().optional(),
15211
15402
  collection: string(),
15212
15403
  filter: QueryFilterSchema.optional()
@@ -22475,6 +22666,12 @@ Object.freeze({
22475
22666
  addonId: null,
22476
22667
  access: "delete"
22477
22668
  },
22669
+ "dataStoreProvider.deleteWhere": {
22670
+ capName: "data-store-provider",
22671
+ capScope: "system",
22672
+ addonId: null,
22673
+ access: "delete"
22674
+ },
22478
22675
  "dataStoreProvider.get": {
22479
22676
  capName: "data-store-provider",
22480
22677
  capScope: "system",
@@ -22523,6 +22720,12 @@ Object.freeze({
22523
22720
  addonId: null,
22524
22721
  access: "create"
22525
22722
  },
22723
+ "dataStoreProvider.updateWhere": {
22724
+ capName: "data-store-provider",
22725
+ capScope: "system",
22726
+ addonId: null,
22727
+ access: "create"
22728
+ },
22526
22729
  "dayNight.getOptions": {
22527
22730
  capName: "day-night",
22528
22731
  capScope: "device",
@@ -24317,12 +24520,24 @@ Object.freeze({
24317
24520
  addonId: null,
24318
24521
  access: "create"
24319
24522
  },
24523
+ "notificationRules.cancelSnooze": {
24524
+ capName: "notification-rules",
24525
+ capScope: "system",
24526
+ addonId: null,
24527
+ access: "create"
24528
+ },
24320
24529
  "notificationRules.createRule": {
24321
24530
  capName: "notification-rules",
24322
24531
  capScope: "system",
24323
24532
  addonId: null,
24324
24533
  access: "create"
24325
24534
  },
24535
+ "notificationRules.createSnooze": {
24536
+ capName: "notification-rules",
24537
+ capScope: "system",
24538
+ addonId: null,
24539
+ access: "create"
24540
+ },
24326
24541
  "notificationRules.deleteRule": {
24327
24542
  capName: "notification-rules",
24328
24543
  capScope: "system",
@@ -24353,6 +24568,12 @@ Object.freeze({
24353
24568
  addonId: null,
24354
24569
  access: "view"
24355
24570
  },
24571
+ "notificationRules.listSnoozes": {
24572
+ capName: "notification-rules",
24573
+ capScope: "system",
24574
+ addonId: null,
24575
+ access: "view"
24576
+ },
24356
24577
  "notificationRules.setRuleEnabled": {
24357
24578
  capName: "notification-rules",
24358
24579
  capScope: "system",
@@ -25601,6 +25822,12 @@ Object.freeze({
25601
25822
  addonId: null,
25602
25823
  access: "delete"
25603
25824
  },
25825
+ "settingsStore.deleteWhere": {
25826
+ capName: "settings-store",
25827
+ capScope: "system",
25828
+ addonId: null,
25829
+ access: "delete"
25830
+ },
25604
25831
  "settingsStore.get": {
25605
25832
  capName: "settings-store",
25606
25833
  capScope: "system",
@@ -25643,6 +25870,12 @@ Object.freeze({
25643
25870
  addonId: null,
25644
25871
  access: "create"
25645
25872
  },
25873
+ "settingsStore.updateWhere": {
25874
+ capName: "settings-store",
25875
+ capScope: "system",
25876
+ addonId: null,
25877
+ access: "create"
25878
+ },
25646
25879
  "smtpProvider.getStatus": {
25647
25880
  capName: "smtp-provider",
25648
25881
  capScope: "system",
@@ -26686,7 +26919,7 @@ var AdminUIAddon = class extends BaseAddon {
26686
26919
  capability: adminUiCapability,
26687
26920
  provider: {
26688
26921
  getStaticDir: async () => ({ staticDir: resolveAdminUiDistDir() }),
26689
- getVersion: async () => ({ version: "1.2.22" })
26922
+ getVersion: async () => ({ version: "1.2.24" })
26690
26923
  }
26691
26924
  }];
26692
26925
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@camstack/addon-admin-ui",
3
- "version": "1.2.22",
3
+ "version": "1.2.24",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "description": "Admin UI — Vite frontend build and server-side addon",
@@ -1 +0,0 @@
1
- import{Ao as e,B as t,Jr as n,Mn as r,Pr as i,Qa as a,Va as o,Xr as s,Zr as c,bo as l,ei as u,q as d,qr as f,xt as p,yo as m,z as h}from"./src-DmLu_IGX.js";import{I as g,K as _,Q as v,S as y,W as b,b as x,i as S,o as C,q as w,x as T,z as E}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DTufy7Ue.js";import{K as D,L as O,k,s as A}from"./src-D11G7q5Q.js";import{p as j}from"./player-overlays-BfUh6z3V.js";import{t as M}from"./clock-J8ftFeJL.js";import{t as N}from"./copy-BgYRNf8b.js";import{a as ee,c as te,d as ne,f as P,i as F,m as I,n as re,o as L,p as R,r as ie,s as z,t as B}from"./debounced-invalidate-o_asci0-.js";import{t as V}from"./search-BK_1ulaR.js";import{t as ae}from"./square-check-big-D7LCZj5L.js";import{t as H}from"./square-nYV2-xBc.js";import{E as U,I as W,L as oe,P as se,S as G,U as K,W as q,i as ce,s as le,t as ue}from"./index-D0JhMwHm.js";import{t as de}from"./AdminPage-Dq33XE9j.js";import{r as fe,t as pe}from"./authed-media-XfBD4Ma-.js";var me=q(`arrow-down-wide-narrow`,[[`path`,{d:`m3 16 4 4 4-4`,key:`1co6wj`}],[`path`,{d:`M7 20V4`,key:`1yoxec`}],[`path`,{d:`M11 4h10`,key:`1w87gc`}],[`path`,{d:`M11 8h7`,key:`djye34`}],[`path`,{d:`M11 12h4`,key:`q8tih4`}]]),he=q(`square-parking`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M9 17V7h4a3 3 0 0 1 0 6H9`,key:`1dfk2c`}]]),ge=q(`tag`,[[`path`,{d:`M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z`,key:`vktsd0`}],[`circle`,{cx:`7.5`,cy:`7.5`,r:`.5`,fill:`currentColor`,key:`kqv944`}]]);v();var _e=720*60*60*1e3;function ve(e){let t=[];for(let n of e)t.push(...n);return t}function ye(e,t){let n=[...e];return n.sort((e,n)=>t===`importance`?n.importance-e.importance:n.timestamp-e.timestamp),n}function be(e,t){return e.filter(e=>!(e.importance<t.minImportance||t.cameras.size>0&&!t.cameras.has(e.deviceId)||t.classes.size>0&&!t.classes.has(e.className)))}function J(e,t){return`${String(e)}:${t}`}function xe(e,t){let n=new Map,r=new Set;for(let i of e){let e=J(i.deviceId,i.trackId);if(!t.has(e)||r.has(e))continue;r.add(e);let a=n.get(i.deviceId);a?a.push(i.trackId):n.set(i.deviceId,[i.trackId])}return n}function Se(e,t){return{since:e.fromMs??t-_e,until:e.toMs??t}}var Y=typeof f==`function`,Ce=`Track deletion arrives with the next server update`;function we(){return{mutateAsync:async()=>{throw Error(`deleteTracks unavailable`)},isPending:!1}}var Te=Y?f:we,Ee=200,De=3e4;function Oe(e){let t=j(),n=S({queries:e.deviceIds.map(n=>({queryKey:[`events-feed`,n,e.since,e.until,e.minImportance??null,e.classFilter??null],staleTime:De,refetchInterval:De,queryFn:async()=>(await t.trpcClient.pipelineAnalytics.getKeyEvents.query({deviceId:n,since:e.since,until:e.until,limit:Ee,...e.minImportance===void 0?{}:{minImportance:e.minImportance},...e.classFilter===void 0?{}:{classFilter:e.classFilter}})).map(e=>({...e,deviceId:n}))}))});return{rows:ye(ve(n.map(e=>e.data??[])),`importance`),isLoading:n.some(e=>e.isLoading)}}var ke=[`events-feed`],Ae=2e3;function je(e){let t=C(),n=e?.paused===!0,r=_(t);r.current=t;let i=_(n);i.current=n;let[o,s]=w(!1),c=g(()=>{r.current.invalidateQueries({queryKey:ke})},[]),l=_(void 0);l.current||=B({delayMs:Ae,invalidate:()=>{i.current?s(!0):c()}}),E(()=>()=>l.current?.cancel(),[]),E(()=>{n||!o||(s(!1),c())},[n,o,c]);let u=g(()=>{s(!1),c()},[c]);return a(D.PipelineAnalyticsDetectionEvent,()=>{l.current?.trigger()}),a(D.PipelineAnalyticsTrackEnded,()=>{l.current?.trigger()}),{pending:o,refreshNow:u}}v();function Me(){return Object.values(O).filter(e=>e.level===`macro`).map(e=>({macro:e,subs:Object.values(O).filter(t=>t.parentKind===e.kind).sort((e,t)=>e.label.localeCompare(t.label))})).sort((e,t)=>e.macro.label.localeCompare(t.macro.label))}function Ne({selected:e,onChange:n}){let{t:r}=ue(),[i,a]=w(!1),[o,s]=w(``),[c,l]=w(new Set),u=b(Me,[]),d=o.trim().toLowerCase(),f=e=>d.length===0||h(e,r).toLowerCase().includes(d),p=b(()=>u.map(e=>({macro:e.macro,subs:e.subs.filter(t=>f(t)||f(e.macro))})).filter(e=>f(e.macro)||e.subs.length>0),[u,d]),m=e=>l(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),g=t=>{let r=new Set(e),i=e.has(t.macro.kind)&&t.subs.every(t=>e.has(t.kind)),a=[t.macro.kind,...t.subs.map(e=>e.kind)];if(i)for(let e of a)r.delete(e);else for(let e of a)r.add(e);n(r)},_=t=>{let r=new Set(e);r.has(t)?r.delete(t):r.add(t),n(r)},v=()=>n(new Set),x=e.size;return y(`div`,{className:`relative`,children:[y(`button`,{type:`button`,onClick:()=>a(e=>!e),className:`flex items-center gap-1 rounded-md px-2.5 py-1 text-xs transition-colors ${x>0?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[T(ge,{className:`h-3.5 w-3.5`}),x>0?`Kinds (${String(x)})`:`Kinds`,T(W,{className:`h-3 w-3`})]}),i&&y(`div`,{className:`absolute z-20 mt-1 max-h-80 w-64 overflow-auto rounded-md border border-border bg-surface p-2 shadow-lg`,children:[y(`div`,{className:`mb-2 flex items-center gap-1 rounded border border-border px-1.5`,children:[T(V,{className:`h-3.5 w-3.5 text-foreground-subtle`}),T(`input`,{type:`text`,value:o,onChange:e=>s(e.target.value),placeholder:`Search kinds…`,className:`w-full bg-transparent py-1 text-xs outline-none`}),x>0&&T(`button`,{type:`button`,onClick:v,className:`text-[10px] text-foreground-subtle hover:text-foreground`,children:`Clear`})]}),p.map(n=>{let i=t(n.macro.iconId),a=c.has(n.macro.kind)||d.length>0,o=e.has(n.macro.kind);return y(`div`,{className:`mb-0.5`,children:[y(`div`,{className:`flex items-center gap-1`,children:[n.subs.length>0?T(`button`,{type:`button`,onClick:()=>m(n.macro.kind),className:`text-foreground-subtle hover:text-foreground`,"aria-label":`Expand`,children:T(a?W:se,{className:`h-3 w-3`})}):T(`span`,{className:`w-3`}),y(`label`,{className:`flex flex-1 cursor-pointer items-center gap-1.5 rounded px-1 py-0.5 text-xs hover:bg-surface-hover`,children:[T(`input`,{type:`checkbox`,checked:o,onChange:()=>g(n),className:`accent-primary`}),T(i,{className:`h-3.5 w-3.5`,style:{color:n.macro.color}}),T(`span`,{className:`font-medium`,children:h(n.macro,r)})]})]}),a&&n.subs.map(n=>{let i=t(n.iconId);return y(`label`,{className:`ml-5 flex cursor-pointer items-center gap-1.5 rounded px-1 py-0.5 text-xs hover:bg-surface-hover`,children:[T(`input`,{type:`checkbox`,checked:e.has(n.kind),onChange:()=>_(n.kind),className:`accent-primary`}),T(i,{className:`h-3.5 w-3.5`,style:{color:n.color}}),T(`span`,{children:h(n,r)})]},n.kind)})]},n.macro.kind)})]})]})}var X=100,Pe=120,Fe={polyline:``,points:[],snapshots:[],start:null,end:null,peakBox:null},Z=e=>e<0?0:e>1?1:e,Q=e=>Math.round(e*100)/100;function Ie(e,t){if(e.length<=t)return[...e];let n=(e.length-1)/(t-1),r=[];for(let i=0;i<t;i++)r.push(e[Math.round(i*n)]);return r[r.length-1]=e[e.length-1],r}function Le(e,t,n){if(e.length===0||t===null)return Fe;let{width:r,height:i}=t;if(!Number.isFinite(r)||!Number.isFinite(i)||r<=0||i<=0)return Fe;let a=Ie(e,n?.maxPoints??Pe).map(e=>({x:Q(Z(e.x/r)*X),y:Q(Z(e.y/i)*X)})),o=a[0]??null,s=a[a.length-1]??null,c=a.length>=2?a.map(e=>`${e.x},${e.y}`).join(` `):``,l=(n?.snapshots??[]).map(e=>({x:Q(Z(e.x/r)*X),y:Q(Z(e.y/i)*X),mediaKey:e.mediaKey})),u=null,d=-1;for(let t of e){let e=Z(t.bbox.w/r)*Z(t.bbox.h/i);e>d&&(d=e,u=t)}return{polyline:c,points:a,snapshots:l,start:o,end:s,peakBox:u?{x:Q(Z(u.bbox.x/r)*X),y:Q(Z(u.bbox.y/i)*X),w:Q(Z(u.bbox.w/r)*X),h:Q(Z(u.bbox.h/i)*X)}:null}}var Re={firstFrame:`First frame (track start)`,lastFrame:`Last frame (track end)`,thumbnail:`Best detection`,thumbnailSmall:`Best detection (480)`,snapshot:`Snapshot`,keyFrame:`Key frame (native-res)`,keyFrameSmall:`Key frame (960)`,crop:`Object crop`,fullFrame:`Full frame`,fullFrameBoxed:`Full frame (boxed)`,faceCrop:`Face crop`,plateCrop:`Plate crop`};function ze(e){return e in Re}function Be(e){return ze(e)?Re[e]:e}function Ve(e,t){return`${e}${pe}/${encodeURIComponent(t)}`}v();var He=1400,Ue=`Admin-gated URL — opens only inside an authenticated session`;function We({label:e,value:t,title:n}){let[r,i]=w(!1);return E(()=>{if(!r)return;let e=setTimeout(()=>i(!1),He);return()=>clearTimeout(e)},[r]),y(`button`,{type:`button`,onClick:g(()=>{(async()=>{try{await navigator.clipboard.writeText(t),i(!0)}catch{window.prompt(`Copy the media URL:`,t)}})()},[t]),title:n,"aria-label":`Copy ${e} URL`,className:`flex min-w-0 items-center gap-1 rounded border px-1.5 py-0.5 text-[10px] font-medium transition-colors ${r?`border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300`:`border-border text-foreground-subtle hover:border-primary hover:text-foreground`}`,children:[T(r?oe:N,{className:`h-2.5 w-2.5 shrink-0`}),T(`span`,{className:`truncate`,children:r?`Copied`:e})]})}function Ge({localUrl:e,publicUrl:t}){return y(`div`,{className:`flex flex-wrap gap-1`,children:[T(We,{label:`Local`,value:e,title:`Copy LAN URL — ${Ue}`}),t&&T(We,{label:`Public`,value:t,title:`Copy public URL — ${Ue}`})]})}v();var Ke=3e4;function qe(e){let[t,n]=w(null),r=g(e=>{n(t=>t??e)},[]);return E(()=>{e||n(null)},[e]),{publicOrigin:t,probes:e?T(Je,{onOrigin:r}):null}}function Je({onOrigin:e}){let{data:t}=p({capName:`network-access`});return T(x,{children:(t??[]).map(t=>T(Ye,{addonId:t.addonId,onOrigin:e},t.addonId))})}function Ye({addonId:e,onOrigin:t}){let{data:n}=i({addonId:e},{refetchInterval:Ke,retry:!1});return E(()=>{let e=n?A.safeParse(n):null,r=e?.success?e.data.endpoint?.url:void 0;if(r)try{t(new URL(r).origin)}catch{}},[n,t]),null}v();var Xe=15e3,Ze=window.location.origin,Qe=new Set([`firstFrame`,`lastFrame`,`thumbnail`,`snapshot`]),$e=new Set([`keyFrame`,`fullFrame`,`fullFrameBoxed`,`firstFrame`,`lastFrame`,`thumbnail`,`snapshot`]);function et(e){let[t,n]=w(null);return E(()=>{if(n(null),!e)return;let t=!1,r=new Image;return r.onload=()=>{t||n({width:r.naturalWidth,height:r.naturalHeight})},r.src=e,()=>{t=!0,r.onload=null}},[e]),t}function tt({overlay:e,onPickSnapshot:t}){return!e.polyline&&!e.peakBox&&e.snapshots.length===0?null:y(`svg`,{viewBox:`0 0 100 100`,preserveAspectRatio:`none`,className:`pointer-events-none absolute inset-0 h-full w-full`,children:[e.peakBox&&T(`rect`,{x:e.peakBox.x,y:e.peakBox.y,width:e.peakBox.w,height:e.peakBox.h,fill:`none`,stroke:`#f59e0b`,strokeWidth:2,vectorEffect:`non-scaling-stroke`,rx:1}),e.polyline&&T(`polyline`,{points:e.polyline,fill:`none`,stroke:`#38bdf8`,strokeWidth:2,strokeLinejoin:`round`,strokeLinecap:`round`,strokeOpacity:.85,vectorEffect:`non-scaling-stroke`}),e.points.map((e,t)=>T(`circle`,{cx:e.x,cy:e.y,r:1,fill:`#38bdf8`,fillOpacity:.6,vectorEffect:`non-scaling-stroke`},`${String(e.x)}-${String(e.y)}-${String(t)}`)),e.snapshots.map((e,n)=>T(`circle`,{cx:e.x,cy:e.y,r:1.9,fill:`#0ea5e9`,fillOpacity:.95,stroke:`#082f49`,strokeWidth:.7,vectorEffect:`non-scaling-stroke`,className:t?`pointer-events-auto cursor-pointer`:void 0,onClick:t?n=>{n.stopPropagation(),t(e.mediaKey)}:void 0,children:T(`title`,{children:`Snapshot checkpoint — click to view this frame`})},`snap-${e.mediaKey}-${String(n)}`)),e.start&&T(`circle`,{cx:e.start.x,cy:e.start.y,r:2.4,fill:`#22c55e`,stroke:`#052e16`,strokeWidth:.6,vectorEffect:`non-scaling-stroke`}),e.end&&T(`circle`,{cx:e.end.x,cy:e.end.y,r:2.4,fill:`#ef4444`,stroke:`#450a0a`,strokeWidth:.6,vectorEffect:`non-scaling-stroke`})]})}function $({label:e,value:t,mono:n}){return y(`div`,{className:`flex items-baseline justify-between gap-3 border-b border-border/60 py-1.5 last:border-0`,children:[T(`span`,{className:`shrink-0 text-[11px] uppercase tracking-wide text-foreground-subtle`,children:e}),T(`span`,{className:`min-w-0 truncate text-right text-xs font-medium text-foreground ${n?`font-mono text-[11px]`:``}`,title:t,children:t})]})}function nt({row:t,cameraName:r,deleteAvailable:i,onClose:a,onDeleted:u}){let d=j(),f=Te(),p=t!==null,h=t?.deviceId??0,_=t?.trackId??``,v=t?.bestEventId??``,S=t?.timestamp??0,C=t?.windowMs??0,{data:D}=s({deviceId:h,trackId:_},{enabled:p}),{data:O}=c({trackId:_},{enabled:p}),{data:k}=n({eventId:v},{enabled:p&&v!==``}),{data:A}=o({deviceId:h,since:S-Xe,until:S+C+Xe},{enabled:p}),[M,N]=w(null),[ee,te]=w(!1),{publicOrigin:P,probes:re}=qe(p);E(()=>{N(null)},[h,_]);let L=b(()=>{let e=O??[],t=k??[];return e.find(e=>e.kind===`keyFrame`)||t.find(e=>e.kind===`fullFrameBoxed`)||([...t,...e].find(e=>e.kind===`crop`)??null)},[O,k]),ie=fe(L?`${pe}/${encodeURIComponent(L.key)}`:void 0),z=b(()=>{let e=new Set,t=[];for(let n of[...k??[],...O??[]])!n.base64||e.has(n.key)||(e.add(n.key),t.push(n));return t},[k,O]),B=b(()=>z.find(e=>Qe.has(e.kind))??null,[z]),V=et(B?`data:image/jpeg;base64,${B.base64}`:null),ae=b(()=>Le(D?.positions??[],V,{snapshots:(D?.snapshots??[]).map(e=>({x:e.position.x,y:e.position.y,mediaKey:e.mediaKey}))}),[D?.positions,D?.snapshots,V]),H=g(e=>{let t=z.find(t=>t.key===e);t&&N(t)},[z]);if(t===null)return null;let W=M?`data:image/jpeg;base64,${M.base64}`:ie.src,oe=M?.kind??L?.kind,se=oe!==void 0&&$e.has(oe)&&V!==null&&(D?.positions.length??0)>=2,K=A&&A.length>0?A[0]:null,q=()=>{K&&(te(!0),(async()=>{try{let e=await d.trpcClient.videoclips.getClipPlayback.query({deviceId:t.deviceId,clipId:K.id});window.open(e.playbackUrl,`_blank`,`noopener`)}catch{window.alert(`Could not resolve clip playback. Check the server logs.`)}finally{te(!1)}})())},ue=()=>{!i||f.isPending||window.confirm(`Delete this track and all its media? This cannot be undone.`)&&(async()=>{try{await f.mutateAsync({deviceId:t.deviceId,trackIds:[t.trackId]}),u()}catch{window.alert(`Failed to delete this track. Check the server logs.`)}})()},de=Math.round(t.importance*100),me=D?.importanceReason?`${String(de)}% · ${D.importanceReason}`:`${String(de)}%`,he=D?.zonesVisited&&D.zonesVisited.length>0?D.zonesVisited.join(`, `):`—`,ge=D?.audioLabels&&D.audioLabels.length>0?D.audioLabels.map(e=>`${e.label} ×${String(e.count)} (${String(Math.round(e.peakScore*100))}%)`).join(` · `):`—`,_e=D?D.totalDistance.toFixed(2):`—`,ve=R(D?D.firstSeen:S),ye=D?R(D.lastSeen):`—`;return T(m,{open:!0,onOpenChange:e=>!e&&a(),children:y(l,{width:`lg`,placement:`sheet-on-mobile`,"aria-label":`Event detail`,className:`flex h-[92dvh] flex-col gap-0 overflow-hidden p-0 bottom-0 left-0 right-0 top-auto w-full max-w-full translate-x-0 translate-y-0 rounded-b-none md:bottom-auto md:left-1/2 md:right-auto md:top-1/2 md:h-auto md:w-[calc(100vw-2rem)] md:max-w-xl md:-translate-x-1/2 md:-translate-y-1/2 md:rounded-lg md:max-h-[calc(100dvh-2rem)]`,children:[y(`header`,{className:`flex shrink-0 items-start justify-between gap-2 border-b border-border px-4 py-3`,children:[y(`div`,{className:`min-w-0`,children:[y(`div`,{className:`truncate text-sm font-semibold text-foreground`,children:[t.className,t.label?y(`span`,{className:`text-foreground-subtle`,children:[` · `,t.label]}):null]}),T(`div`,{className:`mt-0.5 truncate text-[11px] text-foreground-subtle`,children:r})]}),T(`button`,{type:`button`,onClick:a,className:`rounded p-1 text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,"aria-label":`Close`,children:T(ce,{className:`h-4 w-4`})})]}),y(`div`,{className:`min-h-0 flex-1 space-y-3 overflow-y-auto overscroll-contain px-4 py-3`,children:[W?T(`div`,{className:`overflow-hidden rounded-lg border border-border bg-background`,children:T(F,{src:W,alt:`Key frame from ${r}`,fit:`natural`,className:`w-full`,overlay:se?T(tt,{overlay:ae,onPickSnapshot:H}):void 0})}):T(`div`,{className:`flex aspect-video w-full flex-col items-center justify-center gap-1.5 rounded-lg border border-border bg-surface-hover text-foreground-subtle`,children:ie.failed?y(x,{children:[T(I,{className:`h-8 w-8 opacity-60`}),T(`span`,{className:`text-[11px]`,children:`Key-frame media unavailable`})]}):T(G,{className:`h-6 w-6 animate-spin opacity-70`})}),z.length>0&&T(`div`,{className:`-mx-1 flex gap-2 overflow-x-auto px-1 pb-1`,children:z.map(e=>{let t=`data:image/jpeg;base64,${e.base64}`,n=Be(e.kind),r=Ve(Ze,e.key),i=P?Ve(P,e.key):null;return y(`figure`,{className:`flex w-32 shrink-0 flex-col gap-1`,children:[T(`button`,{type:`button`,onClick:()=>N(e),className:`relative h-16 w-full overflow-hidden rounded border border-border hover:border-primary`,title:`${n} · ${R(e.timestamp)}`,children:T(`img`,{src:t,alt:n,className:`h-full w-full object-cover`})}),y(`figcaption`,{className:`min-w-0 px-0.5`,children:[T(`div`,{className:`truncate text-[10px] font-medium leading-tight text-foreground`,title:n,children:n}),T(`div`,{className:`text-[10px] leading-tight text-foreground-subtle`,title:R(e.timestamp),children:ne(e.timestamp)})]}),T(Ge,{localUrl:r,publicUrl:i})]},e.key)})}),re,K&&y(e,{variant:`secondary`,onClick:q,disabled:ee,children:[ee?T(G,{className:`h-3.5 w-3.5 animate-spin`}):T(U,{className:`h-3.5 w-3.5`}),` `,`View clip`]}),y(`div`,{className:`rounded-lg border border-border bg-surface px-3 py-1`,children:[T($,{label:`Camera`,value:r}),T($,{label:`Class`,value:t.className}),T($,{label:`Label`,value:t.label??`—`}),T($,{label:`Importance`,value:me}),T($,{label:`Zones visited`,value:he}),T($,{label:`Audio heard`,value:ge}),T($,{label:`Total distance`,value:_e}),T($,{label:`First seen`,value:ve}),T($,{label:`Last seen`,value:ye}),T($,{label:`Track`,value:t.trackId,mono:!0})]})]}),T(`footer`,{className:`flex shrink-0 items-center justify-end gap-2 border-t border-border px-4 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))]`,children:T(`span`,{title:i?void 0:Ce,children:y(e,{variant:`secondary`,onClick:ue,disabled:!i||f.isPending,children:[f.isPending?T(G,{className:`h-3.5 w-3.5 animate-spin`}):T(le,{className:`h-3.5 w-3.5`}),` `,`Delete track`]})})})]})})}function rt(e){if(e===void 0||!Number.isFinite(e)||e<=0)return``;let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60),r=Math.round(t%60);return`${String(n)}m ${String(r).padStart(2,`0`)}s`}function it({row:e,cameraName:t,nowMs:n,onOpenDetail:r,selected:i=!1,onToggleSelect:a,score:o}){let s=fe(e.bestEventId?`${pe}/${e.bestEventId}`:void 0),c=Math.round(e.importance*100),l=o===void 0?void 0:Math.round(o*100),u=rt(e.windowMs),d=()=>r(e);return y(`div`,{className:`relative flex flex-col rounded-md border bg-surface overflow-hidden ${i?`border-primary ring-1 ring-primary`:`border-border`}`,children:[y(`div`,{className:`aspect-video relative overflow-hidden bg-surface-hover`,children:[s.src?T(`img`,{src:s.src,alt:`Event from ${t}`,onClick:d,className:`h-full w-full cursor-zoom-in object-cover`}):T(`button`,{type:`button`,onClick:d,className:`flex h-full w-full flex-col items-center justify-center gap-1 bg-surface-hover text-foreground-subtle`,title:s.failed?`Key-event media unavailable`:`No key-event media`,children:T(I,{className:`h-6 w-6 opacity-60`})}),a&&T(`button`,{type:`button`,onClick:t=>{t.stopPropagation(),a(J(e.deviceId,e.trackId))},className:`absolute left-0 top-0 z-10 rounded-br-md bg-black/50 p-1.5 text-white hover:bg-black/70`,"aria-label":i?`Deselect`:`Select`,children:i?T(ae,{className:`h-4 w-4 text-primary`}):T(H,{className:`h-4 w-4`})}),l!==void 0&&y(`span`,{className:`absolute left-1 top-1 z-10 rounded bg-primary/85 px-1.5 py-0.5 text-[10px] font-semibold text-white tabular-nums`,title:`CLIP semantic-match score`,children:[String(l),`%`]}),c>0&&T(`span`,{className:`absolute right-1 top-1 z-10 rounded bg-black/60 px-1.5 py-0.5 text-[10px] font-semibold text-white`,children:String(c)})]}),y(`button`,{type:`button`,onClick:d,className:`min-w-0 px-2 py-1.5 text-left space-y-0.5`,children:[y(`p`,{className:`text-[11px] font-medium text-foreground truncate`,title:e.className,children:[e.className,e.label?y(`span`,{className:`text-foreground-subtle`,children:[` · `,e.label]}):null]}),T(`p`,{className:`text-[10px] text-foreground-subtle truncate`,title:t,children:t}),y(`div`,{className:`flex items-center justify-between gap-2`,children:[T(`span`,{className:`text-[10px] text-foreground-subtle truncate`,children:P(e.timestamp,n)}),u&&T(`span`,{className:`text-[10px] text-foreground-subtle shrink-0`,children:u})]})]})]})}v();function at(){let[e,t]=w(!1),n=_(null),[r,i]=w(0),a=g(e=>{n.current!==e&&(n.current=e,i(e=>e+1))},[]);return E(()=>{let e=n.current;if(!e||typeof IntersectionObserver>`u`){t(!1);return}let r=new IntersectionObserver(e=>{let n=e[e.length-1];n&&t(!n.isIntersecting)},{rootMargin:`64px 0px 0px 0px`,threshold:0});return r.observe(e),()=>r.disconnect()},[r]),{ref:a,scrolledPast:e}}v();var ot=[`events-feed`],st=60,ct=[{value:`importance`,label:`Importance`,icon:me},{value:`time`,label:`Recent`,icon:M}];function lt(){let t=C(),[n,i]=w(z),[a,o]=w(new Set),[s,c]=w(new Set),[l,u]=w(0),[d,f]=w(`time`),[p,m]=w(new Set),[h,g]=w(null),[_,v]=w(()=>Date.now());E(()=>{let e=setInterval(()=>v(Date.now()),6e4);return()=>clearInterval(e)},[]);let{since:S,until:D}=b(()=>Se({fromMs:n.fromMs,toMs:n.toMs},_),[n.fromMs,n.toMs,_]),O=at(),{pending:A,refreshNow:j}=je({paused:h!==null||p.size>0||O.scrolledPast}),{data:M}=r({}),N=b(()=>(M??[]).filter(e=>e.type===k.Camera),[M]),ne=b(()=>N.map(e=>e.id),[N]),P=Te(),F=P.isPending,{rows:I,isLoading:R}=Oe({deviceIds:ne,since:S,until:D,minImportance:l>0?l:void 0,classFilter:s.size===1?[...s][0]:void 0}),B=b(()=>{let e=new Map;for(let t of N??[])e.set(t.id,t.name);return e},[N]),V=e=>B.get(e)??`Camera #${String(e)}`,ae=b(()=>te(I).map(e=>({id:e,name:V(e)})).sort((e,t)=>e.name.localeCompare(t.name)),[I,B]),H=b(()=>ye(be(I,{cameras:a,classes:s,minImportance:l}),d),[I,a,s,l,d]),U=re(H,st,b(()=>JSON.stringify([[...a].sort((e,t)=>e-t),[...s].sort(),l,d,S,D]),[a,s,l,d,S,D])),W=()=>{t.invalidateQueries({queryKey:ot})},oe=()=>m(new Set);function se(e){m(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})}function K(){if(p.size===0||!Y)return;let e=xe(I,p),t=[...e.values()].reduce((e,t)=>e+t.length,0);if(t===0||!window.confirm(`Delete ${String(t)} track${t===1?``:`s`} and all their media? This cannot be undone.`))return;let n=[...e];Promise.allSettled(n.map(([e,t])=>P.mutateAsync({deviceId:e,trackIds:t}))).then(e=>{W();let t=[],r=new Set;if(e.forEach((e,i)=>{let a=n[i];if(!a)return;let[o,s]=a;if(e.status===`fulfilled`)for(let e of s)r.add(J(o,e));else t.push(o)}),m(e=>{let t=new Set(e);for(let e of r)t.delete(e);return t}),t.length>0){let e=t.map(e=>V(e)).join(`, `);window.alert(`Failed to delete tracks on: ${e}. They remain selected — retry, or check the server logs.`)}})}let q=H.length!==I.length;return y(`div`,{className:`relative space-y-3`,children:[y(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[T(ee,{onChange:i}),T(L,{cameras:ae,selected:a,onChange:o}),T(Ne,{selected:s,onChange:c}),y(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[T(`span`,{children:`Min score`}),T(`input`,{type:`range`,min:0,max:1,step:.05,value:l,onChange:e=>u(Number(e.target.value)),className:`h-1 w-24 cursor-pointer accent-primary`,"aria-label":`Minimum importance`}),T(`span`,{className:`w-6 tabular-nums text-foreground`,children:Math.round(l*100)})]}),T(`div`,{className:`flex items-center gap-1 rounded-md border border-border p-0.5`,children:ct.map(e=>{let t=e.icon;return y(`button`,{type:`button`,onClick:()=>f(e.value),className:`flex items-center gap-1 rounded px-2 py-1 text-[11px] transition-colors ${d===e.value?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:[T(t,{className:`h-3.5 w-3.5`}),` `,e.label]},e.value)})}),!R&&T(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:q?`${String(H.length)} of ${String(I.length)} events`:`${String(H.length)} event${H.length===1?``:`s`}`})]}),p.size>0&&y(`div`,{className:`flex flex-wrap items-center gap-2 rounded-md border border-primary/40 bg-primary/8 px-3 py-2`,children:[y(`span`,{className:`text-xs font-medium text-foreground`,children:[p.size,` selected`]}),y(`div`,{className:`ml-auto flex flex-wrap items-center gap-1.5`,children:[T(`span`,{title:Y?void 0:`Track deletion arrives with the next server update`,children:y(e,{variant:`secondary`,onClick:K,disabled:!Y||F,children:[F?T(G,{className:`h-3.5 w-3.5 animate-spin`}):T(le,{className:`h-3.5 w-3.5`}),` `,`Delete`]})}),T(e,{variant:`ghost`,onClick:oe,disabled:F,children:T(ce,{className:`h-3.5 w-3.5`})})]})]}),R&&y(`div`,{className:`flex items-center gap-2 py-4 text-xs text-foreground-subtle`,children:[T(G,{className:`h-4 w-4 animate-spin`}),` Loading events…`]}),!R&&H.length===0&&T(`p`,{className:`py-4 text-xs text-foreground-subtle`,children:`No key events in this window.`}),A&&T(`div`,{className:`sticky top-2 z-20 flex justify-center`,children:T(`button`,{type:`button`,onClick:j,className:`rounded-full border border-primary/40 bg-surface px-3 py-1 text-[11px] font-medium text-primary shadow-sm hover:bg-primary/10`,children:`New events — refresh`})}),!R&&H.length>0&&y(x,{children:[T(`div`,{ref:O.ref,"aria-hidden":!0,className:`h-0`}),T(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-2`,children:U.pageItems.map(e=>T(it,{row:e,cameraName:V(e.deviceId),nowMs:_,selected:p.has(J(e.deviceId,e.trackId)),onToggleSelect:se,onOpenDetail:g},J(e.deviceId,e.trackId)))}),T(ie,{currentPage:U.page,totalItems:U.totalItems,pageSize:U.pageSize,onPageChange:U.setPage,itemNoun:`events`})]}),h&&T(nt,{row:h,cameraName:V(h.deviceId),deleteAvailable:Y,onClose:()=>g(null),onDeleted:()=>{W(),g(null)}})]})}v();var ut=50,dt=350,ft=[`person`,`vehicle`,`animal`],pt=[{value:.2,label:`Loose`},{value:.25,label:`Balanced`},{value:.3,label:`Strict`}];function mt(e){return{id:e.id,trackId:e.trackId??e.id,deviceId:e.deviceId,timestamp:e.timestamp,className:e.className,label:e.label,importance:e.importance??0,bestEventId:e.mediaKey??e.trackId??e.id,windowMs:void 0}}function ht({onActiveChange:e}){let[t,n]=w(``),[i,a]=w(.2),[o,s]=w(null),[c,l]=w(null),[f,p]=w(null),m=d(t,dt).trim(),h=m.length>0;E(()=>{e(h)},[h,e]);let[g,_]=w(()=>Date.now());E(()=>{let e=setInterval(()=>_(Date.now()),6e4);return()=>clearInterval(e)},[]);let{data:v}=r({}),x=b(()=>(v??[]).filter(e=>e.type===k.Camera),[v]),S=b(()=>{let e=new Map;for(let t of v??[])e.set(t.id,t.name);return e},[v]),C=e=>S.get(e)??`Camera #${String(e)}`,{data:D,isFetching:O,isError:A,error:j}=u({text:m,minScore:i,limit:ut,classFilter:o??void 0,deviceId:c??void 0},{enabled:h}),M=b(()=>[...D??[]].sort((e,t)=>t.score-e.score).map(e=>({...mt(e),score:e.score})),[D]);function N(e){s(t=>t===e?null:e)}return y(`div`,{className:`space-y-3`,children:[y(`div`,{className:`rounded-lg border border-border bg-surface p-3 space-y-3`,children:[y(`div`,{className:`flex flex-wrap items-center gap-2`,children:[y(`div`,{className:`relative min-w-[16rem] flex-1`,children:[T(V,{className:`pointer-events-none absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-foreground-subtle`}),T(`input`,{type:`text`,value:t,onChange:e=>n(e.target.value),placeholder:`Semantic search — describe what you're looking for…`,className:`h-9 w-full rounded-md border border-border bg-background pl-8 pr-8 text-sm text-foreground placeholder:text-foreground-subtle focus:border-primary focus:outline-none focus:ring-1 focus:ring-primary`,"aria-label":`Semantic event search`}),t&&T(`button`,{type:`button`,onClick:()=>n(``),className:`absolute right-2 top-1/2 -translate-y-1/2 rounded p-0.5 text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,"aria-label":`Clear search`,children:T(ce,{className:`h-3.5 w-3.5`})})]}),O&&h&&T(G,{className:`h-4 w-4 shrink-0 animate-spin text-foreground-subtle`})]}),y(`div`,{className:`flex flex-wrap items-center gap-x-4 gap-y-2`,children:[T(`div`,{className:`flex items-center gap-1`,children:ft.map(e=>T(`button`,{type:`button`,onClick:()=>N(e),className:`rounded-md px-2.5 py-1 text-xs capitalize transition-colors ${o===e?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,children:e},e))}),y(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[T(`span`,{children:`Camera`}),y(`select`,{value:c===null?``:String(c),onChange:e=>l(e.target.value===``?null:Number(e.target.value)),className:`h-7 rounded-md border border-border bg-background px-1.5 text-xs text-foreground focus:border-primary focus:outline-none`,"aria-label":`Filter by camera`,children:[T(`option`,{value:``,children:`All`}),x.map(e=>T(`option`,{value:String(e.id),children:e.name},e.id))]})]}),y(`div`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[T(`span`,{children:`Match`}),T(`div`,{className:`flex items-center gap-1 rounded-md border border-border p-0.5`,children:pt.map(e=>T(`button`,{type:`button`,onClick:()=>a(e.value),className:`rounded px-2 py-1 text-[11px] transition-colors ${i===e.value?`bg-primary/12 text-primary font-medium`:`text-foreground-subtle hover:bg-surface-hover hover:text-foreground`}`,title:`Minimum CLIP score ${e.value.toFixed(2)}`,children:e.label},e.value))})]}),h&&!O&&!A&&y(`span`,{className:`ml-auto text-[10px] text-foreground-subtle`,children:[M.length,` match`,M.length===1?``:`es`]})]})]}),h&&y(`div`,{className:`space-y-3`,children:[A&&y(`p`,{className:`py-4 text-xs text-danger`,children:[`Search failed: `,j instanceof Error?j.message:`unknown error`,`. Check that the CLIP embedding step is enabled.`]}),!A&&O&&M.length===0&&y(`div`,{className:`flex items-center gap-2 py-4 text-xs text-foreground-subtle`,children:[T(G,{className:`h-4 w-4 animate-spin`}),` Searching…`]}),!A&&!O&&M.length===0&&y(`p`,{className:`py-4 text-xs text-foreground-subtle`,children:[`No semantic matches for “`,m,`”. Try a looser match threshold or a different phrasing.`]}),!A&&M.length>0&&T(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(11rem,1fr))] gap-2`,children:M.map(e=>T(it,{row:e,cameraName:C(e.deviceId),nowMs:g,score:e.score,onOpenDetail:p},e.id))})]}),f&&T(nt,{row:f,cameraName:C(f.deviceId),deleteAvailable:Y,onClose:()=>p(null),onDeleted:()=>p(null)})]})}var gt=15e3;function _t(e){let t=j(),n=S({queries:e.map(e=>({queryKey:[`stationary-objects`,e],staleTime:gt,refetchInterval:gt,queryFn:async()=>((await t.trpcClient.zoneAnalytics.getCurrentSnapshot.query({deviceId:e}))?.stationaryObjects??[]).map(t=>({...t,deviceId:e}))}))});return{rows:n.flatMap(e=>e.data??[]).toSorted((e,t)=>t.becameStationaryAt-e.becameStationaryAt),isLoading:n.some(e=>e.isLoading)}}v();function vt(e,t){let n=Math.max(0,Math.round((e-t)/6e4));if(n<1)return`just now`;if(n<60)return`${String(n)}m`;let r=Math.floor(n/60);return`${String(r)}h ${String(n%60)}m`}function yt({row:e,cameraName:t,nowMs:n}){let r=e.keyFrameMediaKey?.startsWith(`track:`)?e.keyFrameMediaKey.split(`:`)[1]:e.keyFrameMediaKey,i=fe(r?`${pe}/${r}`:void 0);return y(`div`,{className:`flex flex-col overflow-hidden rounded-md border border-border bg-surface`,children:[y(`div`,{className:`relative aspect-video overflow-hidden bg-surface-hover`,children:[i.src?T(`img`,{src:i.src,alt:`Parked ${e.className} on ${t}`,className:`h-full w-full object-cover`}):T(`div`,{className:`flex h-full w-full items-center justify-center text-foreground-subtle`,children:T(he,{className:`h-6 w-6`})}),T(`span`,{className:`absolute left-1 top-1 rounded bg-black/60 px-1.5 py-0.5 text-[10px] font-medium capitalize text-white`,children:e.label??e.className})]}),y(`div`,{className:`flex flex-col gap-0.5 p-1.5`,children:[T(`span`,{className:`truncate text-[11px] text-foreground`,children:t}),y(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`parked `,vt(n,e.becameStationaryAt)]})]})]})}function bt(){let[e,t]=w(!1),n=Date.now(),{data:i}=r({}),a=b(()=>(i??[]).filter(e=>e.type===k.Camera),[i]),o=b(()=>a.map(e=>e.id),[a]),s=b(()=>{let e=new Map;for(let t of a)e.set(t.id,t.name);return e},[a]),{rows:c}=_t(o);return c.length===0?null:y(`div`,{className:`rounded-md border border-border bg-surface/40`,children:[y(`button`,{type:`button`,onClick:()=>t(e=>!e),className:`flex w-full items-center gap-2 px-3 py-2 text-left`,children:[T(e?W:se,{className:`h-4 w-4 text-foreground-subtle`}),T(he,{className:`h-4 w-4 text-foreground-subtle`}),T(`span`,{className:`text-sm font-semibold text-foreground`,children:`Stationary`}),T(`span`,{className:`rounded-full bg-surface-hover px-2 py-0.5 text-[10px] font-medium text-foreground-subtle`,children:c.length}),T(`span`,{className:`ml-2 text-[11px] text-foreground-subtle`,children:`Parked objects — kept out of the event feed`})]}),e&&T(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(9rem,1fr))] gap-2 p-3 pt-0`,children:c.map(e=>T(yt,{row:e,cameraName:s.get(e.deviceId)??`Camera #${String(e.deviceId)}`,nowMs:n},e.id))})]})}v();function xt(){let[e,t]=w(!1);return T(de,{icon:K,title:`Events`,subtitle:`Every captured key event across all cameras — trajectory, media, and clips.`,children:y(`section`,{className:`space-y-3`,children:[T(ht,{onActiveChange:t}),!e&&T(bt,{}),!e&&T(lt,{})]})})}export{xt as EventsPage};
@@ -1 +0,0 @@
1
- import{$n as e,Ao as t,Co as n,Do as r,Eo as i,Ka as a,Ki as o,Oo as s,S as c,So as l,To as u,bo as d,ko as f,oo as p,wo as m,yo as h}from"./src-DmLu_IGX.js";import{Q as g,S as _,W as v,a as y,b,i as x,q as S,t as C,x as w}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-DTufy7Ue.js";import{E as T,T as E,k as D,w as O}from"./src-D11G7q5Q.js";import{p as k}from"./player-overlays-BfUh6z3V.js";import{t as A}from"./circle-check-big-C-IoJG5A.js";import{t as j}from"./copy-BgYRNf8b.js";import{t as ee}from"./pencil-DjXB5Bxq.js";import{t as M}from"./plus-BEbdi_Iz.js";import{t as N}from"./refresh-cw-BSTOsxS_.js";import{t as te}from"./search-BK_1ulaR.js";import{t as P}from"./send-CcHJh0KO.js";import{N as ne,S as F,V as re,W as I,i as ie,s as L}from"./index-D0JhMwHm.js";import{t as R}from"./AdminPage-Dq33XE9j.js";import{t as ae}from"./AdminTabs-C2h2Ess6.js";var oe=I(`bell-ring`,[[`path`,{d:`M10.268 21a2 2 0 0 0 3.464 0`,key:`vwvbt9`}],[`path`,{d:`M22 8c0-2.3-.8-4.3-2-6`,key:`5bb3ad`}],[`path`,{d:`M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326`,key:`11g9vi`}],[`path`,{d:`M4 2C2.8 3.7 2 5.7 2 8`,key:`tap9e0`}]]),se=I(`flask-conical`,[[`path`,{d:`M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2`,key:`18mbvz`}],[`path`,{d:`M6.453 15h11.094`,key:`3shlmq`}],[`path`,{d:`M8.5 2h7`,key:`csnxdl`}]]),z=I(`history`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}],[`path`,{d:`M12 7v5l4 2`,key:`1fdv2h`}]]);g();var B=e=>typeof e==`string`&&e.length>0;function ce(e){return{levels:e.levels,formats:e.format,bodyMaxLen:e.bodyMaxLen,attachmentSlots:e.attachments.mediaTypes,attachmentMode:e.attachments.mode,attachmentMax:e.attachments.max,attachmentMaxBytes:e.attachments.maxBytes,maxActions:e.actions,showActions:e.actions>0,showClickUrl:e.clickUrl,showSound:e.sound,showTtl:e.ttl,showTag:!0}}function le(e,t){return e.format.includes(t)?t:e.format[0]??`text`}function ue(e,t){let n=[];for(let r of e.attachments.mediaTypes){if(n.length>=e.attachments.max)break;let i=t[r];B(i)&&n.push({mediaType:r,url:i})}return n}function de(e,t){if(e.actions<=0)return[];let n=[];for(let r of t){if(n.length>=e.actions)break;let t=B(r.label),i=B(r.url);!t&&!i||n.push({id:`test-${n.length+1}`,label:t?r.label:`Action ${n.length+1}`,...i?{url:r.url}:{}})}return n}function fe(e,t){let n=e.levels.some(e=>e.id===t.level)?t.level:void 0,r=ue(e,t.attachmentUrls),i=de(e,t.actions),a=e.ttl&&B(t.ttl)?Number(t.ttl):void 0;return{body:t.body,format:le(e,t.format),priority:pe(t.priority),...B(t.title)?{title:t.title}:{},...n?{level:n}:{},...r.length>0?{attachments:r}:{},...i.length>0?{actions:i}:{},...e.clickUrl&&B(t.clickUrl)?{clickUrl:t.clickUrl}:{},...e.sound&&B(t.sound)?{sound:t.sound}:{},...a!==void 0&&Number.isFinite(a)?{ttl:a}:{},...B(t.tag)?{tag:t.tag}:{}}}function pe(e){return Number.isFinite(e)?Math.min(5,Math.max(1,Math.round(e))):3}function me(e){return e.levels.find(e=>e.flags?.critical===!0)||e.levels.filter(e=>typeof e.ordinal==`number`).sort((e,t)=>t.ordinal-e.ordinal)[0]}function V(e){return{level:``,priority:3,format:e.format[0]??`text`,title:``,body:``,attachmentUrls:{},actions:[],clickUrl:``,sound:``,ttl:``,tag:``}}var he={image:`/addon/notifiers/samples/image`,video:`/addon/notifiers/samples/video`,gif:`/addon/notifiers/samples/gif`,audio:`/addon/notifiers/samples/audio`,icon:`/addon/notifiers/samples/icon`};function ge(e,t){return e.attachments.max>0&&e.attachments.mediaTypes.includes(t)}function _e(e){let t=[`text`];for(let n of[`image`,`gif`,`video`,`audio`])ge(e,n)&&t.push(n);return e.actions>0&&t.push(`actions`),e.levels.length>0&&t.push(`critical`),t.push(`overflow`),t}function H(e,t,n){let r=V(e);return ge(e,t)?{...r,body:n,attachmentUrls:{[t]:he[t]}}:{...r,body:n}}function ve(e,t){let n=V(e);switch(t){case`text`:return{...n,title:`CamStack`,body:`Test notification — text only.`};case`image`:return H(e,`image`,`Test notification with an image.`);case`gif`:return H(e,`gif`,`Test notification with an animation.`);case`video`:return H(e,`video`,`Test notification with a video.`);case`audio`:return H(e,`audio`,`Test notification with audio.`);case`actions`:{let t=Array.from({length:e.actions},(e,t)=>({label:`Action ${t+1}`,url:`/`}));return{...n,title:`CamStack`,body:`Test notification with action buttons.`,actions:t,...e.clickUrl?{clickUrl:`/`}:{}}}case`critical`:{let t=me(e);return{...n,title:`CamStack`,body:`Critical test notification.`,priority:5,level:t?.id??``}}case`overflow`:return{...n,body:`X`.repeat(e.bodyMaxLen+50)}}}var ye={text:`Text only`,image:`With image`,gif:`With GIF`,video:`With video`,audio:`With audio`,actions:`With buttons`,critical:`Critical`,overflow:`Overflow (advanced)`},U=`w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none`,W=`block text-[11px] font-medium text-foreground mb-1`;function be({target:e,kind:r,open:i,onClose:a}){let o=k(),s=v(()=>ce(r.caps),[r.caps]),c=v(()=>_e(r.caps),[r.caps]),[u,p]=S(()=>V(r.caps)),[g,y]=S(null),b=v(()=>fe(r.caps,u),[r.caps,u]),x=u.body.length,T=x>s.bodyMaxLen,E=e=>p(t=>({...t,...e})),D=C({mutationFn:()=>o.trpcClient.notificationOutput.testTarget.mutate({addonId:e.addonId,targetId:e.id,sample:fe(r.caps,u)}),onMutate:()=>y(null),onSuccess:e=>y(e),onError:e=>y({success:!1,error:e instanceof Error?e.message:`Test failed`})}),O=e=>{p(ve(r.caps,e)),y(null)},A=(e,t,n)=>{let r=u.actions.length>0?[...u.actions]:[];for(;r.length<=e;)r.push({label:``,url:``});r[e]={...r[e],[t]:n},E({actions:r})};return w(h,{open:i,onOpenChange:e=>!e&&a(),children:_(d,{width:`lg`,className:`!max-w-2xl`,children:[w(n,{children:_(m,{children:[`Test "`,e.name,`" (`,r.label,`)`]})}),_(`div`,{className:`space-y-4 max-h-[60vh] overflow-y-auto pr-1`,children:[w(`div`,{className:`flex flex-wrap gap-1.5`,children:c.map(e=>w(t,{size:`sm`,variant:`outline`,type:`button`,onClick:()=>O(e),children:ye[e]},e))}),_(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[s.levels.length>0&&_(`div`,{children:[w(`label`,{className:W,children:`Level`}),_(`select`,{className:U,value:u.level,onChange:e=>E({level:e.target.value}),children:[w(`option`,{value:``,children:`— derive from priority —`}),s.levels.map(e=>_(`option`,{value:e.id,children:[e.label,e.ordinal===null?` (qualitative)`:` (p${e.ordinal})`]},e.id))]}),(()=>{let e=s.levels.find(e=>e.id===u.level);return e?_(`div`,{className:`mt-1 space-y-1`,children:[e.description&&w(`p`,{className:`text-[10px] text-foreground-subtle`,children:e.description}),_(`div`,{className:`flex flex-wrap gap-1`,children:[e.flags?.critical&&w(f,{variant:`danger`,"data-testid":`flag-critical`,children:`critical`}),e.flags?.silent&&w(f,{variant:`info`,children:`silent`}),e.flags?.noPush&&w(f,{variant:`warning`,children:`no-push`})]}),e.requires&&e.requires.length>0&&_(`p`,{className:`text-[10px] text-warning`,children:[`Requires target config: `,e.requires.join(`, `)]})]}):null})()]}),_(`div`,{children:[_(`label`,{className:W,children:[`Priority (ordinal): `,u.priority]}),w(`input`,{type:`range`,min:1,max:5,step:1,value:u.priority,onChange:e=>E({priority:Number(e.target.value)}),className:`w-full accent-primary`,"aria-label":`priority`})]})]}),s.formats.length>0&&_(`div`,{children:[w(`label`,{className:W,children:`Format`}),w(`div`,{className:`flex flex-wrap gap-2`,children:s.formats.map(e=>_(`label`,{className:`flex items-center gap-1.5 text-xs text-foreground cursor-pointer`,children:[w(`input`,{type:`radio`,name:`format`,className:`accent-primary`,checked:u.format===e,onChange:()=>E({format:e})}),e]},e))})]}),_(`div`,{children:[w(`label`,{className:W,children:`Title`}),w(`input`,{className:U,value:u.title,onChange:e=>E({title:e.target.value})})]}),_(`div`,{children:[_(`label`,{className:W,children:[`Body`,` `,_(`span`,{className:T?`text-danger`:`text-foreground-subtle`,children:[`(`,x,`/`,s.bodyMaxLen,T?` — overflow`:``,`)`]})]}),w(`textarea`,{className:`${U} min-h-[80px] resize-y`,value:u.body,onChange:e=>E({body:e.target.value})})]}),s.attachmentSlots.length>0&&_(`div`,{children:[_(`label`,{className:W,children:[`Attachments`,` `,_(`span`,{className:`text-foreground-subtle`,children:[`(mode: `,s.attachmentMode,`, max `,s.attachmentMax,s.attachmentMaxBytes?`, ≤${Math.round(s.attachmentMaxBytes/1024/1024)}MB`:``,`)`]})]}),w(`div`,{className:`space-y-1.5`,children:s.attachmentSlots.map(e=>_(`div`,{className:`flex items-center gap-2`,children:[w(`span`,{className:`text-[10px] w-12 shrink-0 text-foreground-subtle`,children:e}),w(`input`,{className:U,placeholder:`${e} URL`,value:u.attachmentUrls[e]??``,onChange:t=>E({attachmentUrls:{...u.attachmentUrls,[e]:t.target.value}})})]},e))})]}),s.showActions&&_(`div`,{children:[_(`label`,{className:W,children:[`Actions (up to `,s.maxActions,`)`]}),w(`div`,{className:`space-y-1.5`,children:Array.from({length:Math.min(s.maxActions,3)},(e,t)=>_(`div`,{className:`flex items-center gap-2`,children:[w(`input`,{className:U,placeholder:`label`,value:u.actions[t]?.label??``,onChange:e=>A(t,`label`,e.target.value)}),w(`input`,{className:U,placeholder:`url`,value:u.actions[t]?.url??``,onChange:e=>A(t,`url`,e.target.value)})]},t))})]}),_(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[s.showClickUrl&&_(`div`,{children:[w(`label`,{className:W,children:`Click URL`}),w(`input`,{className:U,value:u.clickUrl,onChange:e=>E({clickUrl:e.target.value})})]}),s.showSound&&_(`div`,{children:[w(`label`,{className:W,children:`Sound`}),w(`input`,{className:U,value:u.sound,onChange:e=>E({sound:e.target.value})})]}),s.showTtl&&_(`div`,{children:[w(`label`,{className:W,children:`TTL (seconds)`}),w(`input`,{className:U,type:`number`,value:u.ttl,onChange:e=>E({ttl:e.target.value})})]}),s.showTag&&_(`div`,{children:[w(`label`,{className:W,children:`Tag`}),w(`input`,{className:U,value:u.tag,onChange:e=>E({tag:e.target.value})})]})]}),g&&w(xe,{result:g}),_(`details`,{className:`text-[10px]`,children:[w(`summary`,{className:`cursor-pointer text-foreground-subtle`,children:`Payload preview`}),w(`pre`,{className:`mt-1 overflow-x-auto rounded bg-surface p-2 text-foreground-subtle`,children:JSON.stringify(b,null,2)})]})]}),_(l,{children:[w(t,{variant:`secondary`,size:`sm`,type:`button`,onClick:a,children:`Close`}),_(t,{size:`sm`,type:`button`,disabled:D.isPending||u.body.length===0,onClick:()=>D.mutate(),children:[D.isPending?w(F,{className:`h-3.5 w-3.5 animate-spin`}):w(P,{className:`h-3.5 w-3.5`}),`Send test`]})]})]})})}function xe({result:e}){let t=e.renderedAs;return _(`div`,{className:`rounded-md border px-3 py-2 text-xs ${e.success?`border-success/40 bg-success/10`:`border-danger/40 bg-danger/10`}`,"data-testid":`test-result`,children:[_(`div`,{className:`flex items-center gap-2 font-medium`,children:[e.success?w(A,{className:`h-3.5 w-3.5 text-success`}):w(ne,{className:`h-3.5 w-3.5 text-danger`}),w(`span`,{children:e.success?`Delivered`:`Failed`})]}),e.error&&w(`p`,{className:`mt-1 text-danger`,children:e.error}),t&&_(`dl`,{className:`mt-2 grid grid-cols-2 gap-x-3 gap-y-0.5 text-[11px] text-foreground-subtle`,children:[w(`dt`,{children:`Resolved level`}),w(`dd`,{className:`text-foreground`,children:t.level}),w(`dt`,{children:`Format sent`}),w(`dd`,{className:`text-foreground`,children:t.format}),w(`dt`,{children:`Attachments sent`}),w(`dd`,{className:`text-foreground`,children:t.attachmentsSent}),w(`dt`,{children:`Actions sent`}),w(`dd`,{className:`text-foreground`,children:t.actionsSent}),w(`dt`,{children:`Truncated`}),w(`dd`,{className:`text-foreground`,children:t.truncated?`yes`:`no`}),w(`dt`,{children:`Dropped`}),w(`dd`,{className:`text-foreground`,children:t.dropped.length>0?t.dropped.join(`, `):`—`})]})]})}function Se(e){let t=[],n=new Map;for(let r of e){let e=n.get(r.addonId);e?e.push(r):(n.set(r.addonId,[r]),t.push(r.addonId))}return t.map(e=>({addonId:e,kinds:n.get(e)??[]}))}function Ce(e){let t=[],n=e=>{for(let r of e){if(r.type===`password`){t.push(r.key);continue}if(r.type===`group`){n(r.fields);continue}if(r.type===`sub-tabs`)for(let e of r.tabs)n(e.fields)}};for(let t of e.sections)n(t.fields);return t}function we(e,t,n){let r=new Set(n),i={};for(let[n,a]of Object.entries(e)){if(!r.has(n)){i[n]=a;continue}a==null||a===``||a!==t[n]&&(i[n]=a)}return i}function Te(e,t){let n=new Set(t),r={};for(let[t,i]of Object.entries(e))r[t]=n.has(t)?``:i;return r}g();var Ee=[`notificationOutput`,`listTargets`],De=[`notificationOutput`,`listTargetKinds`],Oe=[`userManagement`,`listUsers`],G=`ownerUserId`;function ke(e){let t=e.config[G];return typeof t==`string`&&t.length>0?t:null}function Ae(e){return[{key:`name`,header:`Target`,render:t=>{let n=e.kindByKey.get(t.kind);return _(`span`,{className:`flex items-center gap-2`,children:[w(`span`,{className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-md bg-surface text-xs`,title:n?.label??t.kind,children:w(K,{kind:n,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:``})}),w(`span`,{className:`truncate text-sm font-medium text-foreground`,children:t.name}),!t.enabled&&w(f,{variant:`warning`,children:`disabled`})]})}},{key:`kind`,header:`Kind`,nowrap:!0,render:t=>w(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.kindByKey.get(t.kind)?.label??t.kind})},{key:`owner`,header:`Owner`,nowrap:!0,render:t=>{let n=ke(t);return n===null?w(f,{variant:`default`,children:`system`}):w(`span`,{className:`text-[11px] text-foreground`,children:e.userNameById.get(n)??n})}},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>w(u,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>{let r=e.kindByKey.get(n.kind);return _(`span`,{className:`flex items-center justify-end gap-1`,children:[w(t,{size:`sm`,variant:`ghost`,type:`button`,disabled:!r,onClick:()=>e.onTest(n),title:`Test`,children:w(P,{className:`h-3.5 w-3.5`})}),w(t,{size:`sm`,variant:`ghost`,type:`button`,disabled:!r,onClick:()=>r&&e.onEdit(n,r),title:`Edit`,children:w(ee,{className:`h-3.5 w-3.5`})}),w(t,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDelete(n),title:`Delete`,children:w(L,{className:`h-3.5 w-3.5 text-danger`})})]})}}]}function K({kind:e,imgClassName:t,fallbackClassName:n}){return e?.iconUrl?w(`img`,{src:e.iconUrl,alt:e.label,className:t,loading:`lazy`,draggable:!1}):w(`span`,{className:n,children:e?.icon??`🔔`})}function je(){let e=k(),[n,r]=S({mode:`closed`}),[i,o]=S(null),c=y({queryKey:Ee,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),l=y({queryKey:De,queryFn:async()=>(await e.trpcClient.notificationOutput.listTargetKinds.query({})).map(e=>{let t=e.iconUrl;return{...e,configSchema:e.configSchema,iconUrl:t}})}),u=v(()=>l.data??[],[l.data]),d=v(()=>{let e=new Map;for(let t of u)e.set(t.kind,t);return e},[u]),f=y({queryKey:Oe,queryFn:()=>e.trpcClient.userManagement.listUsers.query()}),m=v(()=>{let e=new Map;for(let t of f.data??[])e.set(t.id,t.username);return e},[f.data]),h=C({mutationFn:t=>e.trpcClient.notificationOutput.setTargetEnabled.mutate({addonId:t.target.addonId,targetId:t.target.id,enabled:t.enabled}),onSuccess:()=>void c.refetch()}),g=C({mutationFn:t=>e.trpcClient.notificationOutput.deleteTarget.mutate({addonId:t.addonId,targetId:t.id}),onSuccess:()=>void c.refetch()}),b=i?d.get(i.kind):void 0;return _(R,{icon:re,title:`Notification Targets`,subtitle:`Deliver notifications to ntfy, Pushover, Telegram, Home Assistant and more. Each target's kind declares its capabilities; the test panel shows exactly what a message degrades to.`,actions:_(t,{size:`sm`,type:`button`,onClick:()=>r({mode:`pick-kind`}),children:[w(M,{className:`h-3.5 w-3.5`}),`Add target`]}),children:[c.isLoading&&w(`div`,{className:`flex items-center justify-center py-16`,children:w(F,{className:`h-6 w-6 animate-spin text-primary`})}),c.isError&&!c.isLoading&&w(a,{title:`Failed to load targets`,message:c.error instanceof Error?c.error.message:`Unknown error`,onRetry:()=>void c.refetch()}),!c.isLoading&&!c.isError&&(c.data??[]).length===0&&w(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,children:`No notification targets yet. Click "Add target" to configure one.`}),(c.data??[]).length>0&&w(s,{children:w(p,{columns:Ae({kindByKey:d,userNameById:m,onToggle:(e,t)=>h.mutate({target:e,enabled:t}),onTest:o,onEdit:(e,t)=>r({mode:`form`,kind:t,target:e}),onDelete:e=>g.mutate(e)}),rows:c.data??[],rowKey:e=>e.id,minWidthPx:720,bordered:!1})}),n.mode===`pick-kind`&&w(Me,{kinds:u,onCancel:()=>r({mode:`closed`}),onPick:e=>r({mode:`form`,kind:e,target:null})}),n.mode===`form`&&w(Ne,{kind:n.kind,target:n.target,users:f.data??[],onCancel:()=>r({mode:`closed`}),onSaved:()=>{r({mode:`closed`}),c.refetch()}}),i&&b&&w(be,{target:i,kind:b,open:!0,onClose:()=>o(null)})]})}function Me({kinds:e,onPick:n,onCancel:r}){let i=v(()=>Se(e),[e]);return _(s,{className:`p-4 space-y-4`,children:[_(`div`,{className:`flex items-center justify-between`,children:[w(`h3`,{className:`text-sm font-semibold text-foreground`,children:`Choose a notification kind`}),w(t,{size:`sm`,variant:`ghost`,type:`button`,onClick:r,children:`Cancel`})]}),i.length===0&&w(`p`,{className:`text-xs text-foreground-subtle`,children:`No notification providers are installed. Install the notifiers addon (or connect Home Assistant) to add targets.`}),i.map(e=>_(`div`,{children:[w(`div`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle mb-1.5`,children:e.addonId}),w(`div`,{className:`grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-2`,children:e.kinds.map(t=>_(`button`,{type:`button`,onClick:()=>n(t),className:`flex flex-col items-center gap-1.5 rounded-lg border border-border bg-surface px-3 py-3 text-xs hover:border-primary/50 hover:bg-surface-hover transition-colors`,children:[w(K,{kind:t,imgClassName:`h-7 w-7 object-contain`,fallbackClassName:`text-lg leading-7`}),w(`span`,{className:`font-medium text-foreground`,children:t.label}),t.supportsDiscovery&&w(f,{variant:`info`,style:`outline`,children:`discover`})]},`${e.addonId}:${t.kind}`))})]},e.addonId))]})}function Ne({kind:e,target:n,users:r,onSaved:a,onCancel:o}){let l=k(),u=v(()=>Ce(e.configSchema),[e.configSchema]),d=v(()=>n?.config??{},[n]),[f,p]=S(n?.name??e.label),[m,h]=S(()=>n?Te(n.config,u):{}),[g,y]=S(null),[b,x]=S(null),[T,E]=S(n?ke(n)??``:``),D=C({mutationFn:()=>l.trpcClient.notificationOutput.discoverTargets.query({addonId:e.addonId,kind:e.kind,config:m}),onSuccess:e=>y(e),onError:e=>x(e instanceof Error?e.message:`Discovery failed`)}),O=C({mutationFn:()=>{let{[G]:t,...r}=we(m,d,u),i=T===``?r:{...r,[G]:T},a={id:n?.id??`${e.kind}-${Date.now()}`,name:f,kind:e.kind,addonId:e.addonId,enabled:n?.enabled??!0,config:i};return l.trpcClient.notificationOutput.upsertTarget.mutate({addonId:e.addonId,target:a})},onSuccess:a,onError:e=>x(e instanceof Error?e.message:`Save failed`)}),A=e=>{p(e.suggestedName),h(t=>({...t,...e.config})),y(null)};return _(s,{className:`p-4 space-y-4`,children:[_(`div`,{className:`flex items-center justify-between`,children:[_(`h3`,{className:`text-sm font-semibold text-foreground flex items-center gap-2`,children:[w(K,{kind:e,imgClassName:`h-5 w-5 object-contain`,fallbackClassName:`text-lg`}),n?`Edit ${n.name}`:`Add ${e.label} target`]}),w(t,{size:`sm`,variant:`ghost`,type:`button`,onClick:o,children:`Cancel`})]}),b&&w(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger`,children:b}),_(`div`,{children:[w(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Name`}),w(`input`,{className:`w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none`,value:f,onChange:e=>p(e.target.value)})]}),_(`div`,{children:[w(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Owner`}),w(i,{value:T,options:[{value:``,label:`System (shared, admin-managed)`},...r.map(e=>({value:e.id,label:e.username}))],onChange:e=>E(e.target.value)}),w(`p`,{className:`mt-0.5 text-[10px] text-foreground-subtle`,children:`A user-owned target belongs to that user: it shows in their viewer and their own rules may deliver to it. System targets stay admin-managed.`})]}),e.supportsDiscovery&&_(`div`,{className:`space-y-2`,children:[_(t,{size:`sm`,variant:`outline`,type:`button`,disabled:D.isPending,onClick:()=>{x(null),D.mutate()},children:[D.isPending?w(F,{className:`h-3.5 w-3.5 animate-spin`}):w(te,{className:`h-3.5 w-3.5`}),`Discover`]}),g&&g.length===0&&w(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No candidates discovered.`}),g&&g.length>0&&w(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:g.map((e,t)=>_(`button`,{type:`button`,onClick:()=>A(e),className:`flex w-full items-center justify-between px-3 py-1.5 text-xs hover:bg-surface-hover`,children:[w(`span`,{className:`text-foreground`,children:e.suggestedName}),w(`span`,{className:`text-[10px] text-primary`,children:`use`})]},`${e.suggestedName}-${t}`))})]}),u.length>0&&n&&w(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Secret fields are hidden. Leave them blank to keep the stored value; type a new value to replace it.`}),w(c,{schema:e.configSchema,values:m,onChange:h}),_(`div`,{className:`flex justify-end gap-2`,children:[w(t,{variant:`secondary`,size:`sm`,type:`button`,onClick:o,children:`Cancel`}),_(t,{size:`sm`,type:`button`,disabled:O.isPending||f.trim().length===0,onClick:()=>{x(null),O.mutate()},children:[O.isPending&&w(F,{className:`h-3.5 w-3.5 animate-spin`}),n?`Save changes`:`Create target`]})]})]})}function q(e){return t=>Object.prototype.hasOwnProperty.call(e,t)}var Pe=q({devices:!0}),Fe=q({classes:!0,classesExclude:!0,labelEquals:!0,identities:!0,identitiesExclude:!0,eventTypeTokens:!0,sensorKinds:!0}),Ie=q({zonesExclude:!0}),Le=q({minConfidence:!0,minImportance:!0,minLabelConfidence:!0}),Re=q({minDwellSeconds:!0}),ze=q({source:!0}),Be=q({crossing:!0}),Ve=q({packagePhase:!0}),He=q({zones:!0}),Ue=q({plates:!0}),We=q({occupancy:!0});function J(e,t){let n=e[t];return Array.isArray(n)?n:[]}function Ge(e,t){let n=e[t];return typeof n==`number`?n:void 0}var Ke=[{id:`scope`,label:`Scope`},{id:`class`,label:`Classes`},{id:`zones`,label:`Zones`},{id:`quality`,label:`Quality`},{id:`label`,label:`Identity & plates`},{id:`device`,label:`Device event`},{id:`package`,label:`Package`},{id:`occupancy`,label:`Occupancy`},{id:`schedule`,label:`Schedule`}];function qe(e){let t=e.replace(/[-_]/g,` `);return t.charAt(0).toUpperCase()+t.slice(1)}function Je(e,t){let n=e.filter(t),r=new Set(Ke.map(e=>e.id)),i=[];for(let e of Ke){let t=n.filter(t=>t.group===e.id);t.length>0&&i.push({id:e.id,label:e.label,descriptors:t})}let a=[];for(let e of n)r.has(e.group)||a.includes(e.group)||a.push(e.group);for(let e of a)i.push({id:e,label:qe(e),descriptors:n.filter(t=>t.group===e)});return i}g();function Ye(e,t){let n=k().trpcClient,r=x({queries:e.map(e=>({queryKey:[[`nc-pickers`,`zones`],{deviceId:e}],staleTime:3e4,queryFn:async()=>({deviceId:e,zones:(await n.zones.listZones.query({deviceId:e})).map(e=>({id:e.id,name:e.name}))})}))});return v(()=>{let e=[],n=new Set;for(let i of r){if(!i.data)continue;let r=t.find(e=>e.id===i.data.deviceId)?.name;for(let t of i.data.zones)n.has(t.id)||(n.add(t.id),e.push({value:t.id,label:t.name,...r===void 0?{}:{hint:r}}))}return{options:e,loading:r.some(e=>e.isLoading)}},[r,t])}function Xe(e){let t=k().trpcClient,n=x({queries:e.map(e=>({queryKey:[[`nc-pickers`,`event-kinds`],{deviceId:e}],staleTime:6e4,queryFn:async()=>(await t.pipelineAnalytics.listEventKinds.query({deviceId:e})).map(e=>({kind:e.kind,label:e.label}))}))});return v(()=>{let e=new Map;for(let t of n)for(let n of t.data??[])e.has(n.kind)||e.set(n.kind,n.label);let t=[...e.entries()].map(([e,t])=>({value:e,label:t}));return t.sort((e,t)=>e.label.localeCompare(t.label)),{options:t,loading:n.some(e=>e.isLoading)}},[n])}function Ze(){let t=e();return v(()=>({options:(t.data??[]).map(e=>({value:e.name,label:e.name})),loading:t.isLoading}),[t.data,t.isLoading])}function Qe(){let e=o({limit:200});return v(()=>{let t=new Set;for(let n of e.data??[])n.text.trim().length>0&&t.add(n.text);return[...t].sort()},[e.data])}function Y({options:e,value:t,onChange:n,loading:r,emptyHint:i,placeholder:a}){let[o,s]=S(``),c=v(()=>new Set(e.map(e=>e.value)),[e]),l=v(()=>new Set(t),[t]),u=t.filter(e=>!c.has(e)),d=e=>{n(l.has(e)?t.filter(t=>t!==e):[...t,e])},f=()=>{let e=o.trim();e.length===0||t.includes(e)||(n([...t,e]),s(``))};return _(`div`,{className:`mt-1 space-y-1.5`,children:[u.length>0&&w(`div`,{className:`flex flex-wrap gap-1`,children:u.map(e=>_(`button`,{type:`button`,onClick:()=>n(t.filter(t=>t!==e)),className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5 text-[10px] text-foreground hover:bg-surface-hover`,title:`Custom value — click to remove`,children:[e,` ×`]},e))}),e.length>0?w(`div`,{className:`max-h-40 overflow-y-auto rounded-md border border-border divide-y divide-border`,children:e.map(e=>_(`label`,{className:`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground cursor-pointer hover:bg-surface-hover`,children:[w(`input`,{type:`checkbox`,checked:l.has(e.value),onChange:()=>d(e.value),className:`accent-primary`}),w(`span`,{className:`flex-1 truncate`,children:e.label}),e.hint!==void 0&&w(`span`,{className:`text-[10px] text-foreground-subtle`,children:e.hint})]},e.value))}):w(`p`,{className:`text-[10px] text-foreground-subtle`,children:r===!0?`Loading…`:i}),w(`input`,{value:o,onChange:e=>s(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),f())},placeholder:a,className:`w-full rounded-md border border-border bg-background px-2 py-1 text-xs text-foreground placeholder:text-foreground-subtle`})]})}var X=[{value:`immediate`,label:`Immediate`,hint:`Fires on the first matching detection of a track (lowest latency).`},{value:`track-end`,label:`Track end`,hint:`Evaluates the finalised track record when it closes.`},{value:`device-event`,label:`Device event`,hint:`Doorbell press / sensor state change on a linked device.`},{value:`package-event`,label:`Package event`,hint:`A parcel delivery or pick-up.`}];function $e(e){return X.find(t=>t.value===e)?.label??e}function et(e){return X.find(t=>t.value===e)?.value}var Z=[{value:`best`,label:`Best available image`,description:`The best subject crop available when the notification is sent.`},{value:`best-matching`,label:`Best matching image`,description:`The image that explains why the rule fired — the face crop for an identity rule, the plate crop for a plate rule; falls back to the best image otherwise.`},{value:`keyFrame`,label:`Key frame`,description:`The clean full scene frame with no subject box.`},{value:`none`,label:`No attachment`,description:`Send the notification with no image.`}];function tt(e){return Z.find(t=>t.value===e)?.value}var nt=[{value:``,label:`Automatic`},{value:`cropped`,label:`Cropped on the subject`},{value:`full`,label:`Full frame`},{value:`boxed`,label:`Full frame with boxes`}];function rt(e){let t=nt.find(t=>t.value===e)?.value;return t===``?void 0:t}var it=[{value:``,label:`Lowest available`},{value:`low`,label:`Low`},{value:`mid`,label:`Medium`},{value:`high`,label:`High`}];function at(e){let t=it.find(t=>t.value===e)?.value;return t===``?void 0:t}var ot=[{value:`any`,label:`Any source`},{value:`pipeline`,label:`Pipeline`},{value:`onboard`,label:`Onboard (camera)`},{value:`sensor`,label:`Sensor`}],st=[{value:`delivered`,label:`Delivered`},{value:`picked-up`,label:`Picked up`},{value:`both`,label:`Both`}],Q=[{value:``,label:`Not set — entering`,hint:`Entries, and every detection that is not a crossing at all. Exits are excluded. This is what a rule without a crossing condition already does, and choosing it writes nothing to the rule.`},{value:`enter`,label:`Entered a zone`,hint:`The same matches as "not set", stated explicitly: entries and non-crossing detections pass, exits do not.`},{value:`exit`,label:`Left a zone`,hint:`ONLY an exit crossing. A detection that is not a crossing fails, so this rule cannot fire on ordinary movement — pair it with the zones the subject must have left.`},{value:`any`,label:`Entered or left`,hint:`No direction filter: entries, exits and non-crossing detections alike. This is the only choice that adds exits to what the rule already matched.`}];function ct(e){let t=Q.find(t=>t.value===e)?.value;return t===``||t===void 0?void 0:t}var lt=[{value:`any`,label:`Any of`},{value:`all`,label:`All of`}],ut=[{value:1,label:`1 — Min`},{value:2,label:`2 — Low`},{value:3,label:`3 — Default`},{value:4,label:`4 — High`},{value:5,label:`5 — Max`}];function dt(){return{name:``,enabled:!0,delivery:`immediate`,targetIds:[],targetUsers:[],targetParams:{},priority:3,mediaAttach:`best`,mediaZoneCrop:!1,mediaFrame:void 0,mediaGif:!1,mediaClip:!1,mediaProfile:void 0,templateTitle:``,templateBody:``,conditions:{},schedule:void 0}}function ft(e){let t={};for(let n of e.targets)n.params&&Object.keys(n.params).length>0&&(t[n.targetId]=n.params);return{name:e.name,enabled:e.enabled,delivery:e.delivery,targetIds:e.targets.map(e=>e.targetId),targetUsers:e.targetUsers??[],targetParams:t,priority:e.priority,mediaAttach:e.media.attach,mediaZoneCrop:e.media.zoneCrop===!0,mediaFrame:e.media.frame,mediaGif:e.media.gif===!0,mediaClip:e.media.clip===!0,mediaProfile:e.media.profile,templateTitle:e.template?.title??``,templateBody:e.template?.body??``,conditions:e.conditions,schedule:e.schedule}}function pt(e){return e.name.trim().length>0&&(e.targetIds.length>0||e.targetUsers.length>0)}function mt(e,t){return e.appliesTo.includes(t)}var ht={source:`any`};function gt(e,t){if(t==null)return!0;if(Array.isArray(t))return t.length===0;if(typeof t==`string`)return t.length===0||ht[e]===t;if(typeof t==`number`)return!Number.isFinite(t);if(typeof t==`object`){if(`ids`in t){let e=t.ids;return!Array.isArray(e)||e.length===0}if(`values`in t){let e=t.values;return!Array.isArray(e)||e.length===0}return!1}return!1}function _t(e,t,n){let r=n.length===0?null:new Set(n.filter(e=>e.id!==`schedule`&&mt(e,t)).map(e=>e.id)),i={};for(let[t,n]of Object.entries(e))r!==null&&!r.has(t)||gt(t,n)||(i[t]=n);return i}function vt(e){return e!==void 0&&e.windows.length>0}function yt(e,t,n=[]){let r=e.templateTitle.trim(),i=e.templateBody.trim(),a=r.length>0||i.length>0?{...r.length>0?{title:r}:{},...i.length>0?{body:i}:{}}:void 0,o=(n.length===0||n.some(t=>t.id===`schedule`&&mt(t,e.delivery)))&&vt(e.schedule)?e.schedule:void 0;return{name:e.name.trim(),enabled:e.enabled,delivery:e.delivery,conditions:_t(e.conditions,e.delivery,n),...o?{schedule:o}:{},targets:e.targetIds.map(t=>{let n=e.targetParams[t];return n&&Object.keys(n).length>0?{targetId:t,params:n}:{targetId:t}}),...e.targetUsers.length>0?{targetUsers:[...e.targetUsers]}:{},media:{attach:e.mediaAttach,...e.mediaZoneCrop?{zoneCrop:!0}:{},...e.mediaFrame===void 0?{}:{frame:e.mediaFrame},...e.mediaGif?{gif:!0}:{},...e.mediaClip?{clip:!0}:{},...e.mediaProfile===void 0?{}:{profile:e.mediaProfile}},throttle:t?.throttle??{cooldownSec:60,scope:`rule-device`},priority:e.priority,...a?{template:a}:{}}}g();var bt=`block text-[11px] font-medium text-foreground`,$=`text-[10px] text-foreground-subtle mt-0.5`;function xt({cameras:e,value:t,onChange:n}){if(e.length===0)return w(`p`,{className:$,children:`No cameras available — the rule applies to all devices.`});let r=e=>n(t.includes(e)?t.filter(t=>t!==e):[...t,e]);return w(`div`,{className:`mt-1 max-h-40 overflow-y-auto rounded-md border border-border divide-y divide-border`,children:e.map(e=>_(`label`,{className:`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground cursor-pointer hover:bg-surface-hover`,children:[w(`input`,{type:`checkbox`,checked:t.includes(e.id),onChange:()=>r(e.id),className:`accent-primary`}),w(`span`,{className:`flex-1 truncate`,children:e.name})]},e.id))})}function St({value:e,placeholder:t,onChange:n}){let[i,a]=S(``),o=()=>{let t=i.trim();if(t.length===0||e.includes(t)){a(``);return}n([...e,t]),a(``)},s=t=>n(e.filter(e=>e!==t));return _(`div`,{className:`mt-1 space-y-1.5`,children:[e.length>0&&w(`div`,{className:`flex flex-wrap gap-1`,children:e.map(e=>_(`span`,{className:`inline-flex items-center gap-1 rounded bg-surface-hover px-1.5 py-0.5 text-[11px] text-foreground`,children:[e,w(`button`,{type:`button`,onClick:()=>s(e),"aria-label":`remove ${e}`,className:`text-foreground-subtle hover:text-danger`,children:w(ie,{className:`h-3 w-3`})})]},e))}),w(r,{value:i,placeholder:t,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),o())},onBlur:o})]})}function Ct({picker:e,value:t,onChange:n}){let r=v(()=>E(e),[e]),i=v(()=>new Set(t),[t]),a=t.filter(e=>!r.has(e)),o=e=>{n(i.has(e)?t.filter(t=>t!==e):[...t,e])};return _(`div`,{className:`space-y-2`,children:[a.length>0&&w(`div`,{className:`flex flex-wrap gap-1`,children:a.map(e=>_(`button`,{type:`button`,onClick:()=>n(t.filter(t=>t!==e)),className:`inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5 text-[10px] text-foreground hover:bg-surface-hover`,title:`Custom value — click to remove`,children:[e,` ×`]},e))}),e.groups.map(e=>_(`div`,{children:[w(`div`,{className:`text-[10px] uppercase tracking-wide text-foreground-muted mb-1`,children:e.fallbackLabel}),w(`div`,{className:`flex flex-wrap gap-1`,children:e.options.map(e=>{let t=i.has(e.value);return w(`button`,{type:`button`,"aria-pressed":t,onClick:()=>o(e.value),className:t?`rounded border border-primary bg-primary/15 px-1.5 py-0.5 text-[10px] text-foreground`:`rounded border border-border px-1.5 py-0.5 text-[10px] text-foreground hover:bg-surface-hover`,children:e.label},e.value)})})]},e.key))]})}function wt({value:e,min:t,max:n,step:i,onChange:a}){return _(`div`,{className:`mt-1 flex items-center gap-2`,children:[w(r,{type:`number`,value:e??``,min:t,max:n,step:i,className:`max-w-[8rem]`,onChange:e=>{let t=e.target.value;if(t===``){a(void 0);return}let n=Number(t);a(Number.isFinite(n)?n:void 0)}}),e!==void 0&&n!==void 0&&w(`input`,{type:`range`,min:t,max:n,step:i,value:e,onChange:e=>a(Number(e.target.value)),className:`flex-1 accent-primary`,"aria-label":`value`})]})}function Tt({value:e,onChange:t}){let n=e??``,r=Q.find(e=>e.value===n);return _(`div`,{className:`mt-1 space-y-1`,children:[w(i,{value:n,options:Q.map(e=>({value:e.value,label:e.label})),onChange:e=>t(ct(e.target.value))}),r!==void 0&&w(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:r.hint})]})}function Et({deviceIds:e,cameras:t,value:n,onChange:r}){let a=n?.ids??[],o=n?.match??`any`,s=e=>r(e.length>0?{ids:e,match:o}:void 0),c=e=>r(a.length>0?{ids:a,match:e}:void 0);return _(`div`,{className:`mt-1 space-y-1.5`,children:[w(`div`,{className:`max-w-[10rem]`,children:w(i,{value:o,options:lt.map(e=>({value:e.value,label:e.label})),onChange:e=>c(e.target.value===`all`?`all`:`any`)})}),w(Dt,{deviceIds:e,cameras:t,value:a,onChange:s})]})}function Dt({deviceIds:e,cameras:t,value:n,onChange:r}){let{options:i,loading:a}=Ye(e,t);return w(Y,{options:i,value:n,onChange:r,loading:a,emptyHint:e.length===0?`Select cameras above to pick their zones by name — or type a zone id.`:`The selected cameras have no zones — type a zone id if you know one.`,placeholder:`Zone id…`})}function Ot({value:e,onChange:t}){let{options:n,loading:r}=Ze();return w(Y,{options:n,value:e,onChange:t,loading:r,emptyHint:`No identities in the face gallery yet — type a name.`,placeholder:`Identity name…`})}function kt({deviceIds:e,value:t,onChange:n}){let{options:r,loading:i}=Xe(e);return w(Y,{options:r,value:t,onChange:n,loading:i,emptyHint:e.length===0?`Select cameras above to pick their event kinds — or type a token.`:`No event kinds reported for the selected cameras — type a token.`,placeholder:`Event token…`})}var At=[{value:`became-occupied`,label:`Became occupied`},{value:`became-free`,label:`Became free`},{value:`>=`,label:`Count ≥`},{value:`<=`,label:`Count ≤`}],jt={op:`became-occupied`,count:1,sustainSeconds:15};function Mt({deviceIds:e,cameras:t,classOptions:n,value:a,onChange:o}){let{options:s,loading:c}=Ye(e,t),l=a??jt,u=e=>o({...l,...e}),d=l.op===`became-occupied`||l.op===`became-free`;return _(`div`,{className:`mt-1 space-y-1.5`,children:[_(`div`,{className:`flex flex-wrap items-center gap-1.5`,children:[w(`div`,{className:`min-w-[10rem]`,children:w(i,{value:l.zoneId??``,options:[{value:``,label:c?`Loading zones…`:`— whole frame —`},...s.map(e=>({value:e.value,label:e.label}))],onChange:e=>u({zoneId:e.target.value===``?void 0:e.target.value})})}),w(`div`,{className:`min-w-[9rem]`,children:w(i,{value:l.className??``,options:[{value:``,label:`— any class —`},...n.map(e=>({value:e.value,label:e.label}))],onChange:e=>u({className:e.target.value===``?void 0:e.target.value})})}),w(`div`,{className:`min-w-[9rem]`,children:w(i,{value:l.op,options:At.map(e=>({value:e.value,label:e.label})),onChange:e=>{let t=At.find(t=>t.value===e.target.value);t&&u({op:t.value})}})})]}),_(`div`,{className:`flex flex-wrap items-center gap-3 text-xs text-foreground-subtle`,children:[_(`label`,{className:`flex items-center gap-1`,children:[d?`Threshold`:`Count`,w(r,{type:`number`,min:0,className:`w-16`,value:String(l.count),onChange:e=>u({count:Math.max(0,Number(e.target.value)||0)})})]}),_(`label`,{className:`flex items-center gap-1`,children:[`Hold for`,w(r,{type:`number`,min:0,max:3600,className:`w-16`,value:String(l.sustainSeconds),onChange:e=>u({sustainSeconds:Math.min(3600,Math.max(0,Number(e.target.value)||0))})}),`s`]}),a===void 0?null:w(`button`,{type:`button`,onClick:()=>o(void 0),className:`underline hover:text-foreground`,children:`Clear`})]}),w(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Counts confirmed tracked objects from zone analytics. The change must hold for the sustain window before it fires; with no snapshot for the camera or zone the rule never fires.`})]})}function Nt({value:e,onChange:t}){let n=e?.values??[],i=e?.maxDistance??1,a=e=>t(e.length>0?{values:e,maxDistance:i}:void 0),o=e=>t(n.length>0?{values:n,maxDistance:e}:void 0),s=Qe().filter(e=>!n.includes(e));return _(`div`,{className:`mt-1 space-y-1.5`,children:[w(St,{value:n,placeholder:`Plate text…`,onChange:a}),s.length>0&&_(`div`,{className:`flex flex-wrap items-center gap-1`,children:[w(`span`,{className:`text-[10px] text-foreground-subtle`,children:`Seen:`}),s.slice(0,12).map(e=>w(`button`,{type:`button`,onClick:()=>a([...n,e]),className:`rounded border border-border px-1.5 py-0.5 text-[10px] text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,children:e},e))]}),_(`label`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[`Max distance`,w(r,{type:`number`,min:0,max:3,step:1,value:i,className:`max-w-[5rem]`,onChange:e=>{let t=Number(e.target.value);o(Number.isFinite(t)?Math.max(0,Math.min(3,t)):1)}})]})]})}var Pt=[{value:1,label:`Mon`},{value:2,label:`Tue`},{value:3,label:`Wed`},{value:4,label:`Thu`},{value:5,label:`Fri`},{value:6,label:`Sat`},{value:0,label:`Sun`}];function Ft(e){let t=Math.floor(e/60),n=e%60;return`${String(t).padStart(2,`0`)}:${String(n).padStart(2,`0`)}`}function It(e){let[t,n]=e.split(`:`),r=Number(t)*60+Number(n);return Number.isFinite(r)?Math.max(0,Math.min(1439,r)):0}function Lt(){return{days:[1,2,3,4,5],startMinute:540,endMinute:1080}}function Rt({value:e,onChange:t}){let n=e?.windows??[],r=e?.invert??!1,i=(n,r)=>{if(n.length===0){t(void 0);return}t({windows:n,...r?{invert:!0}:{},...e?.timezone?{timezone:e.timezone}:{}})},a=()=>i([...n,Lt()],r),o=e=>i(n.filter((t,n)=>n!==e),r),s=(e,t)=>i(n.map((n,r)=>r===e?t:n),r);return _(`div`,{className:`mt-1 space-y-2`,children:[n.length===0?w(`p`,{className:$,children:`Always active — add a window to restrict when the rule fires.`}):n.map((e,t)=>w(zt,{window:e,onChange:e=>s(t,e),onRemove:()=>o(t)},t)),_(`div`,{className:`flex items-center gap-3`,children:[_(`button`,{type:`button`,onClick:a,className:`flex items-center gap-1 rounded-md bg-surface-hover px-2 py-1 text-[11px] text-foreground-subtle hover:text-foreground`,children:[w(M,{className:`h-3 w-3`}),` Add window`]}),n.length>0&&_(`label`,{className:`flex items-center gap-1.5 text-[11px] text-foreground-subtle`,children:[w(`input`,{type:`checkbox`,checked:r,onChange:e=>i([...n],e.target.checked),className:`accent-primary`}),`Active outside the windows`]})]})]})}function zt({window:e,onChange:t,onRemove:n}){let r=n=>{let r=e.days.includes(n)?e.days.filter(e=>e!==n):[...e.days,n];r.length!==0&&t({...e,days:r})};return _(`div`,{className:`space-y-1.5 rounded-md border border-border p-2`,children:[_(`div`,{className:`flex items-center gap-2 text-xs`,children:[w(`input`,{type:`time`,value:Ft(e.startMinute),onChange:n=>t({...e,startMinute:It(n.target.value)}),className:`rounded-md border border-border bg-background px-1 py-0.5`}),w(`span`,{className:`text-foreground-subtle`,children:`→`}),w(`input`,{type:`time`,value:Ft(e.endMinute),onChange:n=>t({...e,endMinute:It(n.target.value)}),className:`rounded-md border border-border bg-background px-1 py-0.5`}),w(`span`,{className:`flex-1`}),w(`button`,{type:`button`,onClick:n,"aria-label":`Remove window`,className:`text-foreground-subtle hover:text-danger`,children:w(L,{className:`h-3.5 w-3.5`})})]}),w(`div`,{className:`flex flex-wrap gap-1`,children:Pt.map(t=>w(`button`,{type:`button`,onClick:()=>r(t.value),className:`rounded px-1.5 py-0.5 text-[10px] ${e.days.includes(t.value)?`bg-primary text-primary-foreground`:`bg-surface-hover text-foreground-subtle`}`,children:t.label},t.value))})]})}g();function Bt({catalog:e,taxonomy:t,delivery:n,conditions:r,schedule:i,cameras:a,onConditionsChange:o,onScheduleChange:s}){let c=(e,t)=>{let n={...r};t===void 0?delete n[e]:n[e]=t,o(n)},l=v(()=>Je(e,e=>O(e.id)),[e]),u=v(()=>Je(e,e=>!O(e.id)),[e]),[d,p]=S(()=>{if(Ht(r,i))return!0;try{return localStorage.getItem(Vt)===`1`}catch{return!1}}),m=()=>{let e=!d;p(e);try{localStorage.setItem(Vt,e?`1`:`0`)}catch{}},h=e=>e.map(e=>_(`div`,{className:`space-y-2.5`,children:[w(`div`,{className:`text-[11px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:e.label}),e.descriptors.map(e=>{let o=mt(e,n);return _(`div`,{className:o?``:`opacity-50`,"data-testid":`condition-${e.id}`,children:[_(`div`,{className:`flex items-center justify-between gap-2`,children:[w(`label`,{className:bt,children:e.label}),!o&&_(f,{variant:`default`,children:[`not for `,e.appliesTo.join(` / `)]})]}),o?w(Ut,{descriptor:e,taxonomy:t,conditions:r,schedule:i,cameras:a,onFieldChange:c,onScheduleChange:s}):w(`p`,{className:$,children:`Not evaluated for the selected trigger — switch the trigger to use it.`}),o&&e.description&&w(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:e.description})]},e.id)})]},e.id));return _(`div`,{className:`space-y-4`,children:[h(l),u.length>0&&w(`button`,{type:`button`,onClick:m,"data-testid":`nc-advanced-toggle`,className:`w-full rounded-md border border-border px-3 py-1.5 text-left text-[11px] font-medium text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,children:d?`▾ Hide advanced configurations`:`▸ Show more configurations`}),d&&h(u)]})}var Vt=`camstack.nc.showAdvanced`;function Ht(e,t){for(let[t,n]of Object.entries(e))if(!O(t)&&n!==void 0&&!(Array.isArray(n)&&n.length===0))return!0;return t!==void 0&&t.windows.length>0}function Ut({descriptor:e,taxonomy:t,conditions:n,schedule:r,cameras:a,onFieldChange:o,onScheduleChange:s}){switch(e.valueType){case`deviceIdList`:{if(!Pe(e.id))break;let t=e.id;return w(xt,{cameras:a,value:n[t]??[],onChange:e=>o(t,e.length>0?e:void 0)})}case`stringList`:{if(!Fe(e.id))break;let r=e.id,i=e=>o(r,e.length>0?e:void 0);if(r===`identities`||r===`identitiesExclude`)return w(Ot,{value:J(n,r),onChange:i});if(r===`eventTypeTokens`)return w(kt,{deviceIds:n.devices??[],value:J(n,r),onChange:i});let a=T(r,t);return a===null?w(St,{value:J(n,r),placeholder:`Add value…`,onChange:i}):w(Ct,{picker:a,value:J(n,r),onChange:i})}case`zoneIdList`:{if(!Ie(e.id))break;let t=e.id;return w(Dt,{deviceIds:n.devices??[],cameras:a,value:J(n,t),onChange:e=>o(t,e.length>0?e:void 0)})}case`number01`:{if(!Le(e.id))break;let t=e.id;return w(wt,{value:Ge(n,t),min:0,max:1,step:.05,onChange:e=>o(t,e)})}case`number`:{if(!Re(e.id))break;let t=e.id;return w(wt,{value:Ge(n,t),min:0,step:1,onChange:e=>o(t,e)})}case`sourceSelect`:{if(!ze(e.id))break;let t=e.id;return w(i,{value:n[t]??`any`,options:ot.map(e=>({value:e.value,label:e.label})),onChange:e=>o(t,Kt(e.target.value))})}case`crossingSelect`:{if(!Be(e.id))break;let t=e.id;return w(Tt,{value:n[t],onChange:e=>o(t,e)})}case`packagePhase`:{if(!Ve(e.id))break;let t=e.id;return w(i,{value:n[t]??``,options:[{value:``,label:`— any phase —`},...st.map(e=>({value:e.value,label:e.label}))],onChange:e=>o(t,qt(e.target.value))})}case`zoneSelection`:{if(!He(e.id))break;let t=e.id;return w(Et,{deviceIds:n.devices??[],cameras:a,value:n[t],onChange:e=>o(t,e)})}case`plateMatcher`:{if(!Ue(e.id))break;let t=e.id;return w(Nt,{value:n[t],onChange:e=>o(t,e)})}case`occupancy`:{if(!We(e.id))break;let r=e.id;return w(Mt,{deviceIds:n.devices??[],cameras:a,classOptions:Wt(t),value:n[r],onChange:e=>o(r,e)})}case`schedule`:return w(Rt,{value:r,onChange:s});default:break}return w(Gt,{descriptor:e,conditions:n})}function Wt(e){let t=T(`classes`,e);return t===null?[]:t.groups.flatMap(e=>e.options)}function Gt({descriptor:e,conditions:t}){let n=Object.entries(t).find(([t])=>t===e.id);return _(`p`,{className:$,children:[n!==void 0&&n[1]!==void 0?`Authored elsewhere and preserved — this admin editor cannot change it yet.`:`Not editable here yet — this condition has no admin editor.`,` `,_(`span`,{className:`text-foreground-muted`,children:[`(`,e.valueType,`)`]})]})}function Kt(e){if(e===`pipeline`||e===`onboard`||e===`sensor`||e===`any`)return e}function qt(e){return st.find(t=>t.value===e)?.value}g();var Jt=[`notificationRules`,`listRules`],Yt=[`notificationOutput`,`listTargets`,`forRules`],Xt=[`notificationRules`,`getConditionCatalog`],Zt=[`deviceManager`,`listAll`,`forRules`];function Qt(){let e=k(),[n,r]=S({mode:`closed`}),[i,o]=S(null),c=y({queryKey:Jt,queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),l=y({queryKey:Yt,queryFn:()=>e.trpcClient.notificationOutput.listTargets.query({})}),u=y({queryKey:Xt,queryFn:()=>e.trpcClient.notificationRules.getConditionCatalog.query({})}),d=y({queryKey:Zt,queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({})).filter(e=>e.type===D.Camera).map(e=>({id:e.id,name:e.name}))}),f=v(()=>{let e=new Map;for(let t of l.data??[])e.set(t.id,t.name);return e},[l.data]),m=C({mutationFn:t=>e.trpcClient.notificationRules.setRuleEnabled.mutate(t),onSuccess:()=>void c.refetch()}),h=C({mutationFn:t=>e.trpcClient.notificationRules.deleteRule.mutate({ruleId:t}),onSuccess:()=>{o(null),c.refetch()}}),g=c.data??[];return _(R,{icon:oe,title:`Notification Rules`,subtitle:`Author rules that turn detections, doorbell presses and package events into notifications. Each rule picks a trigger, matches conditions and fans out to one or more delivery targets.`,actions:_(t,{size:`sm`,type:`button`,onClick:()=>r({mode:`form`,rule:null}),children:[w(M,{className:`h-3.5 w-3.5`}),`New rule`]}),children:[c.isLoading&&w(`div`,{className:`flex items-center justify-center py-16`,children:w(F,{className:`h-6 w-6 animate-spin text-primary`})}),c.isError&&!c.isLoading&&w(a,{title:`Failed to load rules`,message:c.error instanceof Error?c.error.message:`Unknown error`,onRetry:()=>void c.refetch()}),!c.isLoading&&!c.isError&&g.length===0&&w(`div`,{className:`text-xs text-foreground-subtle text-center py-16`,children:`No notification rules yet. Click "New rule" to author one.`}),g.length>0&&w(s,{children:w(p,{columns:$t({targetNameById:f,confirmDeleteId:i,deletePending:h.isPending,onToggle:(e,t)=>m.mutate({ruleId:e.id,enabled:t}),onEdit:e=>r({mode:`form`,rule:e}),onDuplicate:e=>r({mode:`form`,rule:{...e,id:``,name:`${e.name} (copy)`}}),onAskDelete:o,onConfirmDelete:e=>h.mutate(e.id)}),rows:g,rowKey:e=>e.id,minWidthPx:760,bordered:!1})}),n.mode===`form`&&w(en,{rule:n.rule,targets:l.data??[],catalog:u.data?.catalog??[],taxonomy:u.data?.taxonomy,cameras:d.data??[],onCancel:()=>r({mode:`closed`}),onSaved:()=>{r({mode:`closed`}),c.refetch()}})]})}function $t(e){return[{key:`name`,header:`Rule`,render:e=>_(`span`,{className:`flex items-center gap-2`,children:[w(`span`,{className:`truncate text-sm font-medium text-foreground`,children:e.name}),!e.enabled&&w(f,{variant:`warning`,children:`disabled`})]})},{key:`trigger`,header:`Trigger`,nowrap:!0,render:e=>w(`span`,{className:`text-[11px] text-foreground-subtle`,children:$e(e.delivery)})},{key:`targets`,header:`Targets`,render:t=>{let n=t.targets[0],r=n?e.targetNameById.get(n.targetId)??n.targetId:null;return w(`span`,{className:`text-[11px] text-foreground-subtle`,children:t.targets.length===1&&r?r:`${t.targets.length} target${t.targets.length===1?``:`s`}`})}},{key:`priority`,header:`Priority`,align:`center`,nowrap:!0,render:e=>w(`span`,{className:`text-[11px] text-foreground-subtle`,children:e.priority})},{key:`enabled`,header:`On`,align:`center`,nowrap:!0,render:t=>w(u,{checked:t.enabled,onCheckedChange:n=>e.onToggle(t,n),"aria-label":`toggle ${t.name}`})},{key:`actions`,header:``,align:`right`,nowrap:!0,render:n=>_(`span`,{className:`flex items-center justify-end gap-1`,children:[w(t,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onEdit(n),title:`Edit`,children:w(ee,{className:`h-3.5 w-3.5`})}),w(t,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onDuplicate(n),title:`Duplicate`,children:w(j,{className:`h-3.5 w-3.5`})}),e.confirmDeleteId===n.id?_(b,{children:[_(t,{size:`sm`,variant:`danger`,type:`button`,disabled:e.deletePending,onClick:()=>e.onConfirmDelete(n),children:[e.deletePending&&w(F,{className:`h-3.5 w-3.5 animate-spin`}),`Confirm`]}),w(t,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(null),children:`Cancel`})]}):w(t,{size:`sm`,variant:`ghost`,type:`button`,onClick:()=>e.onAskDelete(n.id),title:`Delete`,children:w(L,{className:`h-3.5 w-3.5 text-danger`})})]})}]}function en({rule:e,targets:n,catalog:a,taxonomy:o,cameras:s,onSaved:c,onCancel:l}){let p=k(),m=e!=null&&e.id.length>0,[g,v]=S(()=>e?ft(e):dt()),[b,x]=S(null),[T,E]=S(null),D=e=>v(t=>({...t,...e})),O=m&&e?{throttle:e.throttle}:void 0,A=C({mutationFn:async()=>{let t=yt(g,O,a);m&&e?await p.trpcClient.notificationRules.updateRule.mutate({ruleId:e.id,patch:t}):await p.trpcClient.notificationRules.createRule.mutate({rule:t})},onSuccess:c,onError:e=>x(e instanceof Error?e.message:`Save failed`)}),j=C({mutationFn:async()=>{let e=yt(g,O,a);return(await p.trpcClient.notificationRules.testRule.mutate({rule:e,lookbackMinutes:60})).results},onMutate:()=>E(null),onSuccess:e=>E(e),onError:e=>x(e instanceof Error?e.message:`Test failed`)}),ee=g.targetIds.map(e=>n.find(t=>t.id===e)?.name??e),M=e=>D({targetIds:g.targetIds.includes(e)?g.targetIds.filter(t=>t!==e):[...g.targetIds,e]}),N=y({queryKey:[`userManagement`,`listUsers`],queryFn:()=>p.trpcClient.userManagement.listUsers.query()}).data,te=e=>D({targetUsers:g.targetUsers.includes(e)?g.targetUsers.filter(t=>t!==e):[...g.targetUsers,e]}),P=X.find(e=>e.value===g.delivery)?.hint;return w(h,{open:!0,onOpenChange:e=>!e&&l(),children:_(d,{width:`lg`,placement:`sheet-on-mobile`,children:[_(`div`,{className:`flex items-center justify-between mb-3`,children:[_(`h3`,{className:`text-sm font-semibold text-foreground flex items-center gap-2`,children:[w(oe,{className:`h-4 w-4 text-foreground-subtle`}),m?`Edit ${e?.name}`:`New notification rule`]}),w(t,{size:`sm`,variant:`ghost`,type:`button`,onClick:l,children:`Cancel`})]}),b&&w(`div`,{className:`rounded-md border border-danger/40 bg-danger/10 px-3 py-2 text-xs text-danger mb-3`,children:b}),_(`div`,{className:`space-y-4`,children:[_(`div`,{className:`flex items-end gap-3`,children:[_(`div`,{className:`min-w-0 flex-1`,children:[w(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Name`}),w(r,{value:g.name,onChange:e=>D({name:e.target.value}),placeholder:`e.g. Front door package`})]}),_(`label`,{className:`flex items-center gap-2 pb-1.5 text-[11px] font-medium text-foreground`,children:[w(u,{checked:g.enabled,onCheckedChange:e=>D({enabled:e}),"aria-label":`enabled`}),`Enabled`]})]}),_(`div`,{children:[w(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Trigger`}),w(i,{value:g.delivery,onChange:e=>{let t=et(e.target.value);t&&D({delivery:t})},options:X.map(e=>({value:e.value,label:e.label}))}),P&&w(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:P})]}),_(`div`,{children:[w(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Delivery targets`}),n.length===0?w(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No delivery targets configured. Add one under the Targets tab first.`}):w(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:n.map(e=>_(`label`,{className:`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground cursor-pointer hover:bg-surface-hover`,children:[w(`input`,{type:`checkbox`,checked:g.targetIds.includes(e.id),onChange:()=>M(e.id),className:`accent-primary`}),w(`span`,{className:`flex-1 truncate`,children:e.name}),!e.enabled&&w(f,{variant:`warning`,children:`disabled`})]},e.id))})]}),_(`div`,{children:[w(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Notify users`}),(N??[]).length===0?w(`p`,{className:`text-[11px] text-foreground-subtle`,children:`No users to notify.`}):w(`div`,{className:`rounded-md border border-border divide-y divide-border`,children:(N??[]).map(e=>_(`label`,{className:`flex items-center gap-2.5 px-3 py-1.5 text-xs text-foreground cursor-pointer hover:bg-surface-hover`,children:[w(`input`,{type:`checkbox`,checked:g.targetUsers.includes(e.id),onChange:()=>te(e.id),className:`accent-primary`}),w(`span`,{className:`flex-1 truncate`,children:e.username}),e.isAdmin&&w(f,{variant:`info`,children:`admin`})]},e.id))}),w(`p`,{className:`text-[10px] text-foreground-subtle mt-1`,children:`Delivers to the targets each user owns, only for cameras that user can access.`})]}),_(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 gap-3`,children:[_(`div`,{children:[w(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Priority`}),w(i,{value:String(g.priority),onChange:e=>D({priority:Number(e.target.value)}),options:ut.map(e=>({value:String(e.value),label:e.label}))})]}),_(`div`,{children:[w(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Media attachment`}),w(i,{value:g.mediaAttach,onChange:e=>{let t=tt(e.target.value);t&&D({mediaAttach:t})},options:Z.map(e=>({value:e.value,label:e.label}))}),w(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:Z.find(e=>e.value===g.mediaAttach)?.description}),_(`div`,{className:`mt-2 space-y-1`,children:[_(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[w(`input`,{type:`checkbox`,checked:g.mediaZoneCrop,onChange:e=>D({mediaZoneCrop:e.target.checked}),className:`accent-primary`}),`Crop the image to the rule's zone`]}),_(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[w(`input`,{type:`checkbox`,checked:g.mediaGif,onChange:e=>D({mediaGif:e.target.checked}),className:`accent-primary`}),`Attach a GIF around the event`]}),_(`label`,{className:`flex items-center gap-2 text-xs text-foreground cursor-pointer`,children:[w(`input`,{type:`checkbox`,checked:g.mediaClip,onChange:e=>D({mediaClip:e.target.checked}),className:`accent-primary`}),`Attach an MP4 clip around the event`]})]}),(g.mediaGif||g.mediaClip)&&_(`div`,{className:`mt-2`,children:[w(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Video quality`}),w(i,{value:g.mediaProfile??``,onChange:e=>D({mediaProfile:at(e.target.value)}),options:it.map(e=>({value:e.value,label:e.label}))}),w(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`A notification is watched on a phone — the cheapest stream is normally the right one, and the high profile only costs CPU to render.`})]})]}),_(`div`,{children:[w(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Image frame`}),w(i,{value:g.mediaFrame??``,onChange:e=>D({mediaFrame:rt(e.target.value)}),options:nt.map(e=>({value:e.value,label:e.label}))}),w(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`What the attached still shows. "Automatic" leaves it to the attachment mode above.`})]})]}),_(`div`,{className:`space-y-2`,children:[_(`div`,{children:[w(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Notification title`}),w(r,{value:g.templateTitle,onChange:e=>D({templateTitle:e.target.value}),placeholder:`{{camera}} — {{class}}`})]}),_(`div`,{children:[w(`label`,{className:`block text-[11px] font-medium text-foreground mb-1`,children:`Notification body`}),w(`textarea`,{value:g.templateBody,onChange:e=>D({templateBody:e.target.value}),rows:2,placeholder:`{{label}} seen in {{zone}} at {{time}}`,className:`w-full rounded-md border border-border bg-surface px-2.5 py-1.5 text-xs text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary`})]}),_(`p`,{className:`text-[10px] text-foreground-subtle`,children:[`Leave blank to use the backend default text. Supported variables include`,` `,w(`code`,{children:`{{camera}}`}),`, `,w(`code`,{children:`{{class}}`}),`, `,w(`code`,{children:`{{label}}`}),`,`,` `,w(`code`,{children:`{{zone}}`}),`, `,w(`code`,{children:`{{confidence}}`}),`, `,w(`code`,{children:`{{time}}`}),`.`]})]}),_(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[w(`div`,{className:`mb-2 text-[11px] font-semibold text-foreground`,children:`Conditions`}),a.length===0?w(`p`,{className:`text-[10px] text-foreground-subtle`,children:`Condition catalog unavailable — this rule matches on its trigger and targets alone.`}):w(Bt,{catalog:a,taxonomy:o,delivery:g.delivery,conditions:g.conditions,schedule:g.schedule,cameras:s,onConditionsChange:e=>D({conditions:e}),onScheduleChange:e=>D({schedule:e})})]}),_(`div`,{className:`rounded-md border border-border px-3 py-3`,children:[_(`div`,{className:`flex items-center justify-between gap-2`,children:[w(`div`,{className:`text-[11px] font-semibold text-foreground`,children:`Test rule`}),_(t,{size:`sm`,variant:`outline`,type:`button`,disabled:j.isPending||!pt(g),onClick:()=>{x(null),j.mutate()},children:[j.isPending?w(F,{className:`h-3.5 w-3.5 animate-spin`}):w(se,{className:`h-3.5 w-3.5`}),`Dry-run (last 60 min)`]})]}),w(`p`,{className:`mt-1 text-[10px] text-foreground-subtle`,children:`Evaluate the CURRENT (unsaved) rule against recently persisted records — no notification is sent.`}),T!==null&&w(tn,{delivery:g.delivery,results:T,targetNames:ee})]})]}),_(`div`,{className:`flex justify-end gap-2 mt-4`,children:[w(t,{variant:`secondary`,size:`sm`,type:`button`,onClick:l,children:`Cancel`}),_(t,{size:`sm`,type:`button`,disabled:A.isPending||!pt(g),onClick:()=>{x(null),A.mutate()},children:[A.isPending&&w(F,{className:`h-3.5 w-3.5 animate-spin`}),m?`Save changes`:`Create rule`]})]})]})})}function tn({delivery:e,results:t,targetNames:n}){if(e===`device-event`)return w(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:`Device-event rules cannot be dry-run: the sensor-event store has no cross-device scan surface, so a test returns no candidate records. The rule still fires live on a matching doorbell press / sensor change.`});if(t.length===0)return w(`p`,{className:`mt-2 text-[11px] text-foreground-subtle`,children:`No records in the last 60 minutes matched — nothing to evaluate.`});let r=t.filter(e=>e.wouldFire).length;return _(`div`,{className:`mt-2 space-y-1.5`,children:[_(`div`,{className:`text-[11px] text-foreground-subtle`,children:[r,` of `,t.length,` evaluated record`,t.length===1?``:`s`,` would fire.`]}),w(`ul`,{className:`divide-y divide-border rounded-md border border-border`,children:t.slice(0,50).map(e=>_(`li`,{className:`flex items-center gap-2 px-2.5 py-1.5 text-[11px]`,children:[e.wouldFire?w(A,{className:`h-3.5 w-3.5 shrink-0 text-success`}):w(ne,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),w(`span`,{className:`w-32 shrink-0 text-foreground-subtle`,children:new Date(e.timestamp).toLocaleString()}),_(`span`,{className:`w-14 shrink-0 text-foreground-subtle`,children:[`#`,e.deviceId]}),w(`span`,{className:`min-w-0 flex-1 truncate text-foreground`,children:e.label??e.className??`object`}),e.wouldFire?_(`span`,{className:`shrink-0 truncate text-success`,children:[`→ `,n.join(`, `)||`targets`]}):e.failedCondition&&_(`span`,{className:`shrink-0 text-foreground-subtle`,children:[`failed: `,e.failedCondition]})]},e.recordId))})]})}g();var nn=[{value:1,label:`Last hour`},{value:24,label:`Last 24 hours`},{value:168,label:`Last 7 days`},{value:0,label:`All time`}],rn=[{value:``,label:`Any status`},{value:`pending`,label:`Pending`},{value:`sent`,label:`Sent`},{value:`dead`,label:`Dead`}],an=[50,100,250,500];function on(){return{ruleId:``,deviceId:``,status:``,windowHours:24,limit:100}}function sn(e){return e===`pending`||e===`sent`||e===`dead`?e:void 0}function cn(e){switch(e){case`pending`:return`info`;case`sent`:return`success`;case`dead`:return`danger`}}function ln(){let e=k(),[t,n]=S(on),r=e=>n(t=>({...t,...e})),a=y({queryKey:[`notificationRules`,`listRules`,`forHistory`],queryFn:async()=>(await e.trpcClient.notificationRules.listRules.query({})).rules}),o=y({queryKey:[`deviceManager`,`listAll`,`forHistory`],queryFn:async()=>(await e.trpcClient.deviceManager.listAll.query({})).filter(e=>e.type===D.Camera).map(e=>({id:e.id,name:e.name}))}),c=Date.now(),l=y({queryKey:[`notificationRules`,`getHistory`,t],retry:!1,queryFn:async()=>{let n=t.windowHours>0?c-t.windowHours*36e5:void 0;return(await e.trpcClient.notificationRules.getHistory.query({filter:{limit:t.limit,...t.ruleId?{ruleId:t.ruleId}:{},...t.deviceId?{deviceId:Number(t.deviceId)}:{},...sn(t.status)?{status:sn(t.status)}:{},...n===void 0?{}:{since:n}}})).entries}}),u=v(()=>{let e=new Map;for(let t of o.data??[])e.set(t.id,t.name);return e},[o.data]),d=e=>u.get(e)??`Camera #${String(e)}`,f=l.data??[],m=l.isError;return _(R,{icon:z,title:`Delivery history`,subtitle:`A searchable log of every notification the rules delivered (or failed to deliver).`,children:[_(`div`,{className:`mb-4 grid grid-cols-2 gap-2 sm:grid-cols-5`,children:[_(`div`,{children:[w(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Rule`}),w(i,{value:t.ruleId,onChange:e=>r({ruleId:e.target.value}),options:[{value:``,label:`All rules`},...(a.data??[]).map(e=>({value:e.id,label:e.name}))]})]}),_(`div`,{children:[w(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Camera`}),w(i,{value:t.deviceId,onChange:e=>r({deviceId:e.target.value}),options:[{value:``,label:`All cameras`},...(o.data??[]).map(e=>({value:String(e.id),label:e.name}))]})]}),_(`div`,{children:[w(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Status`}),w(i,{value:t.status,onChange:e=>r({status:e.target.value}),options:rn.map(e=>({value:e.value,label:e.label}))})]}),_(`div`,{children:[w(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Window`}),w(i,{value:String(t.windowHours),onChange:e=>r({windowHours:Number(e.target.value)}),options:nn.map(e=>({value:String(e.value),label:e.label}))})]}),_(`div`,{children:[w(`label`,{className:`mb-1 block text-[10px] font-medium text-foreground-subtle`,children:`Limit`}),w(i,{value:String(t.limit),onChange:e=>r({limit:Number(e.target.value)}),options:an.map(e=>({value:String(e),label:String(e)}))})]})]}),l.isLoading&&w(`div`,{className:`flex items-center justify-center py-16`,children:w(F,{className:`h-6 w-6 animate-spin text-primary`})}),m&&!l.isLoading&&w(s,{children:_(`div`,{className:`flex flex-col items-center gap-2 px-4 py-14 text-center`,children:[w(z,{className:`h-6 w-6 text-foreground-subtle`}),w(`div`,{className:`text-sm font-medium text-foreground`,children:`Delivery history requires a server update`}),w(`p`,{className:`max-w-md text-xs text-foreground-subtle`,children:`The history query is not available on this hub yet. It becomes queryable after the next server update ships the notification-center history endpoint. Rules still deliver and record their outcome in the meantime.`}),_(`button`,{type:`button`,onClick:()=>void l.refetch(),className:`mt-1 inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-[11px] text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,children:[w(N,{className:`h-3 w-3`}),` Retry`]})]})}),!m&&!l.isLoading&&f.length===0&&w(`div`,{className:`py-16 text-center text-xs text-foreground-subtle`,children:`No deliveries match these filters.`}),!m&&f.length>0&&w(s,{children:w(p,{columns:un(d),rows:f,rowKey:e=>e.id,minWidthPx:720,bordered:!1})})]})}function un(e){return[{key:`when`,header:`When`,nowrap:!0,render:e=>w(`span`,{className:`text-[11px] text-foreground-subtle`,children:new Date(e.createdAt).toLocaleString()})},{key:`rule`,header:`Rule`,render:e=>w(`span`,{className:`text-xs font-medium text-foreground`,children:e.ruleName})},{key:`camera`,header:`Camera`,nowrap:!0,render:t=>w(`span`,{className:`text-[11px] text-foreground-subtle`,children:e(t.deviceId)})},{key:`subject`,header:`Subject`,render:e=>_(`span`,{className:`text-[11px] text-foreground-subtle`,children:[e.subject.label??e.subject.className,e.subject.confidence===void 0?``:` · ${Math.round(e.subject.confidence*100)}%`]})},{key:`status`,header:`Status`,nowrap:!0,render:e=>_(`span`,{className:`flex items-center gap-1.5`,children:[w(f,{variant:cn(e.status),children:e.status}),e.attempts>1?_(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`×`,e.attempts]}):null]})},{key:`error`,header:`Detail`,render:e=>e.error?w(`span`,{className:`text-[11px] text-danger`,children:e.error}):w(`span`,{className:`text-[11px] text-foreground-subtle`,children:`—`})}]}function dn(){return w(`div`,{className:`flex flex-col p-4`,children:w(ae,{tabs:[{id:`targets`,label:`Targets`,icon:re,content:w(je,{})},{id:`rules`,label:`Rules`,icon:oe,content:w(Qt,{})},{id:`history`,label:`History`,icon:z,content:w(ln,{})}]})})}export{dn as NotificationsPage,dn as default};