node-red-contrib-unifi-ultimate 0.1.0-beta.1

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.
@@ -0,0 +1,1541 @@
1
+ "use strict";
2
+
3
+ const DEVICE_TYPE_DEFINITIONS = {
4
+ camera: {
5
+ type: "camera",
6
+ label: "Camera",
7
+ modelKey: "camera",
8
+ listPath: "/v1/cameras",
9
+ detailPath: "/v1/cameras/:id"
10
+ },
11
+ sensor: {
12
+ type: "sensor",
13
+ label: "Sensor",
14
+ modelKey: "sensor",
15
+ listPath: "/v1/sensors",
16
+ detailPath: "/v1/sensors/:id"
17
+ },
18
+ light: {
19
+ type: "light",
20
+ label: "Light",
21
+ modelKey: "light",
22
+ listPath: "/v1/lights",
23
+ detailPath: "/v1/lights/:id"
24
+ },
25
+ chime: {
26
+ type: "chime",
27
+ label: "Chime",
28
+ modelKey: "chime",
29
+ listPath: "/v1/chimes",
30
+ detailPath: "/v1/chimes/:id"
31
+ },
32
+ viewer: {
33
+ type: "viewer",
34
+ label: "Viewer",
35
+ modelKey: "viewer",
36
+ listPath: "/v1/viewers",
37
+ detailPath: "/v1/viewers/:id"
38
+ },
39
+ liveview: {
40
+ type: "liveview",
41
+ label: "Live View",
42
+ modelKey: "liveview",
43
+ listPath: "/v1/liveviews",
44
+ detailPath: "/v1/liveviews/:id"
45
+ },
46
+ nvr: {
47
+ type: "nvr",
48
+ label: "NVR",
49
+ modelKey: "nvr",
50
+ listPath: "/v1/nvrs",
51
+ detailPath: "/v1/nvrs"
52
+ }
53
+ };
54
+
55
+ const COMMON_CAPABILITIES = [
56
+ {
57
+ id: "observe",
58
+ label: "Observe",
59
+ description: "Fetch current state and keep listening to Protect streams.",
60
+ method: "GET",
61
+ pathKind: "detail",
62
+ mode: "observe"
63
+ },
64
+ {
65
+ id: "getDetails",
66
+ label: "Get details",
67
+ description: "Fetch the full object payload once.",
68
+ method: "GET",
69
+ pathKind: "detail",
70
+ mode: "request"
71
+ },
72
+ {
73
+ id: "patchSettings",
74
+ label: "Patch settings",
75
+ description: "PATCH the selected device using msg.payload.",
76
+ method: "PATCH",
77
+ pathKind: "detail",
78
+ mode: "request"
79
+ }
80
+ ];
81
+
82
+ const RTSPS_QUALITY_OPTIONS = ["high", "medium", "low", "package"].map((quality) => ({
83
+ value: quality,
84
+ label: quality
85
+ }));
86
+
87
+ const SENSOR_OBSERVABLE_DEFINITIONS = [
88
+ {
89
+ id: "contact",
90
+ label: "Contact open/closed",
91
+ eventTypes: ["sensorOpened", "sensorClosed"]
92
+ },
93
+ {
94
+ id: "motion",
95
+ label: "Motion",
96
+ eventTypes: ["sensorMotion"]
97
+ },
98
+ {
99
+ id: "alarm",
100
+ label: "Alarm",
101
+ eventTypes: ["sensorAlarm"]
102
+ },
103
+ {
104
+ id: "waterLeak",
105
+ label: "Water leak",
106
+ eventTypes: ["sensorWaterLeak"]
107
+ },
108
+ {
109
+ id: "batteryLow",
110
+ label: "Battery low",
111
+ eventTypes: ["sensorBatteryLow"]
112
+ },
113
+ {
114
+ id: "tamper",
115
+ label: "Tamper",
116
+ eventTypes: ["sensorTamper"]
117
+ },
118
+ {
119
+ id: "smokeTest",
120
+ label: "Smoke test",
121
+ eventTypes: ["sensorSmokeTest"]
122
+ }
123
+ ];
124
+
125
+ const CAMERA_OBSERVABLE_DEFINITIONS = [
126
+ {
127
+ id: "ring",
128
+ label: "Ring",
129
+ eventTypes: ["ring"]
130
+ },
131
+ {
132
+ id: "motion",
133
+ label: "Motion",
134
+ eventTypes: ["motion"]
135
+ },
136
+ {
137
+ id: "smartAudioDetect",
138
+ label: "Smart audio detect",
139
+ eventTypes: ["smartAudioDetect"]
140
+ },
141
+ {
142
+ id: "smartDetectZone",
143
+ label: "Smart detect zone",
144
+ eventTypes: ["smartDetectZone"]
145
+ },
146
+ {
147
+ id: "smartDetectLine",
148
+ label: "Smart detect line",
149
+ eventTypes: ["smartDetectLine"]
150
+ },
151
+ {
152
+ id: "smartDetectLoiterZone",
153
+ label: "Smart detect loiter",
154
+ eventTypes: ["smartDetectLoiterZone"]
155
+ }
156
+ ];
157
+
158
+ const LIGHT_OBSERVABLE_DEFINITIONS = [
159
+ {
160
+ id: "motion",
161
+ label: "Motion",
162
+ eventTypes: ["lightMotion"]
163
+ },
164
+ {
165
+ id: "lightOn",
166
+ label: "Light on",
167
+ eventTypes: []
168
+ }
169
+ ];
170
+
171
+ function createSetPropertyCapability() {
172
+ return {
173
+ id: "setProperty",
174
+ label: "Set property",
175
+ description: "Patch a single property discovered from the selected device.",
176
+ method: "PATCH",
177
+ pathKind: "detail",
178
+ mode: "request",
179
+ ignoreInputPayload: true,
180
+ useConfiguredPayload: true,
181
+ editor: {
182
+ fields: [
183
+ {
184
+ id: "propertyPath",
185
+ label: "Property",
186
+ type: "select",
187
+ placeholder: "Select a property",
188
+ reloadOnChange: true
189
+ },
190
+ {
191
+ id: "valueType",
192
+ type: "hidden"
193
+ },
194
+ {
195
+ id: "propertyValue",
196
+ label: "Value",
197
+ type: "text",
198
+ placeholder: "Select a property first"
199
+ }
200
+ ]
201
+ },
202
+ requestComposer: ({ capabilityConfig }) => ({
203
+ payload: buildNestedPatchPayload(
204
+ capabilityConfig.propertyPath,
205
+ parseConfiguredPropertyValue(capabilityConfig.propertyValue, capabilityConfig.valueType)
206
+ )
207
+ })
208
+ };
209
+ }
210
+
211
+ const TYPE_CAPABILITIES = {
212
+ camera: [
213
+ {
214
+ id: "getSnapshot",
215
+ label: "Get snapshot",
216
+ description: "Fetch a JPEG snapshot for the selected camera.",
217
+ method: "GET",
218
+ path: "/v1/cameras/:id/snapshot",
219
+ mode: "request",
220
+ ignoreInputPayload: true,
221
+ editor: {
222
+ fields: [
223
+ {
224
+ id: "forceHighQuality",
225
+ label: "High quality",
226
+ type: "select",
227
+ allowEmpty: true,
228
+ emptyLabel: "Default",
229
+ options: [
230
+ { value: "true", label: "True" },
231
+ { value: "false", label: "False" }
232
+ ]
233
+ }
234
+ ]
235
+ },
236
+ requestComposer: ({ capabilityConfig }) => ({
237
+ query: capabilityConfig.forceHighQuality
238
+ ? { forceHighQuality: capabilityConfig.forceHighQuality }
239
+ : {}
240
+ })
241
+ },
242
+ {
243
+ id: "getRtspsStreams",
244
+ label: "Get RTSPS streams",
245
+ description: "Fetch current RTSPS streams for the selected camera.",
246
+ method: "GET",
247
+ path: "/v1/cameras/:id/rtsps-stream",
248
+ mode: "request"
249
+ },
250
+ {
251
+ id: "createRtspsStreams",
252
+ label: "Create RTSPS streams",
253
+ description: "Create RTSPS streams using msg.payload.",
254
+ method: "POST",
255
+ path: "/v1/cameras/:id/rtsps-stream",
256
+ mode: "request"
257
+ },
258
+ {
259
+ id: "deleteRtspsStreams",
260
+ label: "Delete RTSPS streams",
261
+ description: "Delete RTSPS streams using msg.payload or msg.query.",
262
+ method: "DELETE",
263
+ path: "/v1/cameras/:id/rtsps-stream",
264
+ mode: "request"
265
+ },
266
+ {
267
+ id: "createTalkbackSession",
268
+ label: "Create talkback session",
269
+ description: "Create a talkback session using msg.payload.",
270
+ method: "POST",
271
+ path: "/v1/cameras/:id/talkback-session",
272
+ mode: "request"
273
+ },
274
+ {
275
+ id: "disableMicPermanently",
276
+ label: "Disable microphone permanently",
277
+ description: "Permanently disable the selected camera microphone.",
278
+ method: "POST",
279
+ path: "/v1/cameras/:id/disable-mic-permanently",
280
+ mode: "request",
281
+ ignoreInputPayload: true
282
+ },
283
+ {
284
+ id: "startPtzPatrol",
285
+ label: "Start PTZ patrol",
286
+ description: "Start a PTZ patrol.",
287
+ method: "POST",
288
+ path: "/v1/cameras/:id/ptz/patrol/start/:slot",
289
+ mode: "request",
290
+ parameterNames: ["slot"],
291
+ ignoreInputPayload: true,
292
+ editor: {
293
+ fields: [
294
+ {
295
+ id: "slot",
296
+ label: "Patrol slot",
297
+ type: "select",
298
+ options: [
299
+ { value: "0", label: "Patrol 0" },
300
+ { value: "1", label: "Patrol 1" },
301
+ { value: "2", label: "Patrol 2" },
302
+ { value: "3", label: "Patrol 3" },
303
+ { value: "4", label: "Patrol 4" }
304
+ ]
305
+ }
306
+ ]
307
+ },
308
+ requestComposer: ({ capabilityConfig }) => ({
309
+ params: {
310
+ slot: capabilityConfig.slot
311
+ }
312
+ })
313
+ },
314
+ {
315
+ id: "stopPtzPatrol",
316
+ label: "Stop PTZ patrol",
317
+ description: "Stop the active PTZ patrol.",
318
+ method: "POST",
319
+ path: "/v1/cameras/:id/ptz/patrol/stop",
320
+ mode: "request"
321
+ },
322
+ {
323
+ id: "gotoPtzPreset",
324
+ label: "Go to PTZ preset",
325
+ description: "Move the PTZ camera to a preset.",
326
+ method: "POST",
327
+ path: "/v1/cameras/:id/ptz/goto/:slot",
328
+ mode: "request",
329
+ parameterNames: ["slot"],
330
+ ignoreInputPayload: true,
331
+ editor: {
332
+ fields: [
333
+ {
334
+ id: "slot",
335
+ label: "PTZ preset",
336
+ type: "select",
337
+ placeholder: "Select a preset"
338
+ }
339
+ ]
340
+ },
341
+ requestComposer: ({ capabilityConfig }) => ({
342
+ params: {
343
+ slot: capabilityConfig.slot
344
+ }
345
+ })
346
+ },
347
+ {
348
+ id: "setDoorbellMessage",
349
+ label: "Set doorbell message",
350
+ description: "Set a predefined, custom, or image message on the camera doorbell.",
351
+ method: "PATCH",
352
+ pathKind: "detail",
353
+ mode: "request",
354
+ ignoreInputPayload: true,
355
+ useConfiguredPayload: true,
356
+ editor: {
357
+ fields: [
358
+ {
359
+ id: "messageType",
360
+ label: "Message type",
361
+ type: "select",
362
+ reloadOnChange: true,
363
+ options: [
364
+ { value: "DO_NOT_DISTURB", label: "Do not disturb" },
365
+ { value: "LEAVE_PACKAGE_AT_DOOR", label: "Leave package at door" },
366
+ { value: "CUSTOM_MESSAGE", label: "Custom message" },
367
+ { value: "IMAGE", label: "Image" }
368
+ ]
369
+ },
370
+ {
371
+ id: "messageText",
372
+ label: "Text",
373
+ type: "text",
374
+ placeholder: "Hello"
375
+ },
376
+ {
377
+ id: "messageImage",
378
+ label: "Image asset",
379
+ type: "select",
380
+ placeholder: "Select an asset"
381
+ },
382
+ {
383
+ id: "resetAt",
384
+ label: "Reset at",
385
+ type: "text",
386
+ placeholder: "empty=default, null=forever, or unix timestamp"
387
+ }
388
+ ]
389
+ },
390
+ requestComposer: ({ capabilityConfig }) => ({
391
+ payload: {
392
+ lcdMessage: buildDoorbellMessagePayload(capabilityConfig)
393
+ }
394
+ })
395
+ },
396
+ createSetPropertyCapability()
397
+ ],
398
+ liveview: [
399
+ createSetPropertyCapability()
400
+ ],
401
+ sensor: [
402
+ createSetPropertyCapability()
403
+ ],
404
+ light: [
405
+ createSetPropertyCapability()
406
+ ],
407
+ chime: [
408
+ createSetPropertyCapability()
409
+ ],
410
+ viewer: [
411
+ {
412
+ id: "setLiveview",
413
+ label: "Set live view",
414
+ description: "Assign the selected live view to the viewer.",
415
+ method: "PATCH",
416
+ pathKind: "detail",
417
+ mode: "request",
418
+ editor: {
419
+ fields: [
420
+ {
421
+ id: "liveview",
422
+ label: "Live view",
423
+ type: "select",
424
+ placeholder: "Select a live view",
425
+ allowEmpty: true,
426
+ emptyLabel: "No live view"
427
+ }
428
+ ]
429
+ },
430
+ requestComposer: ({ capabilityConfig }) => ({
431
+ payload: {
432
+ liveview: capabilityConfig.liveview ? capabilityConfig.liveview : null
433
+ }
434
+ }),
435
+ useConfiguredPayload: true
436
+ },
437
+ createSetPropertyCapability()
438
+ ],
439
+ nvr: []
440
+ };
441
+
442
+ function getDeviceTypes() {
443
+ return Object.values(DEVICE_TYPE_DEFINITIONS);
444
+ }
445
+
446
+ function getDeviceTypeDefinition(deviceType) {
447
+ return DEVICE_TYPE_DEFINITIONS[String(deviceType || "").trim()] || null;
448
+ }
449
+
450
+ function getCapabilitiesForType(deviceType) {
451
+ const definition = getDeviceTypeDefinition(deviceType);
452
+ if (!definition) {
453
+ return [];
454
+ }
455
+
456
+ return COMMON_CAPABILITIES.concat(TYPE_CAPABILITIES[definition.type] || []).map((capability) => ({
457
+ ...capability,
458
+ hasConfiguration: Boolean(capability.editor && Array.isArray(capability.editor.fields) && capability.editor.fields.length > 0)
459
+ }));
460
+ }
461
+
462
+ function getCapabilityDefinition(deviceType, capabilityId) {
463
+ return getCapabilitiesForType(deviceType).find((capability) => capability.id === capabilityId) || null;
464
+ }
465
+
466
+ function buildDevicePath(deviceType, kind, deviceId, params) {
467
+ const definition = getDeviceTypeDefinition(deviceType);
468
+ if (!definition) {
469
+ throw new Error(`Unsupported device type: ${deviceType}`);
470
+ }
471
+
472
+ let path;
473
+ if (kind === "list") {
474
+ path = definition.listPath;
475
+ } else {
476
+ path = definition.detailPath;
477
+ }
478
+
479
+ if (path.includes(":id")) {
480
+ if (!deviceId) {
481
+ throw new Error(`Device type '${deviceType}' requires a device id.`);
482
+ }
483
+ path = path.replace(":id", encodeURIComponent(String(deviceId)));
484
+ }
485
+
486
+ Object.entries(params || {}).forEach(([key, value]) => {
487
+ if (value === undefined || value === null || value === "") {
488
+ return;
489
+ }
490
+ path = path.replace(`:${key}`, encodeURIComponent(String(value)));
491
+ });
492
+
493
+ if (path.includes(":")) {
494
+ throw new Error(`Missing required path parameters for ${path}`);
495
+ }
496
+
497
+ return path;
498
+ }
499
+
500
+ function buildCapabilityRequest(deviceType, capabilityId, deviceId, params) {
501
+ const capability = getCapabilityDefinition(deviceType, capabilityId);
502
+ if (!capability) {
503
+ throw new Error(`Unsupported capability '${capabilityId}' for device type '${deviceType}'.`);
504
+ }
505
+
506
+ const path = capability.path
507
+ ? buildPathFromTemplate(capability.path, deviceId, params)
508
+ : buildDevicePath(deviceType, capability.pathKind === "list" ? "list" : "detail", deviceId, params);
509
+
510
+ return {
511
+ capability,
512
+ method: capability.method,
513
+ path
514
+ };
515
+ }
516
+
517
+ function composeCapabilityExecution(deviceType, capabilityId, capabilityConfig, msg) {
518
+ const capability = getCapabilityDefinition(deviceType, capabilityId);
519
+ if (!capability) {
520
+ throw new Error(`Unsupported capability '${capabilityId}' for device type '${deviceType}'.`);
521
+ }
522
+
523
+ if (typeof capability.requestComposer !== "function") {
524
+ return {
525
+ params: normalizeObject(msg && msg.params),
526
+ query: normalizeObject(msg && msg.query),
527
+ headers: normalizeObject(msg && msg.headers),
528
+ payload: msg ? msg.payload : undefined
529
+ };
530
+ }
531
+
532
+ const composedRequest = capability.requestComposer({
533
+ capabilityConfig: normalizeObject(capabilityConfig),
534
+ msg: msg || {}
535
+ }) || {};
536
+
537
+ const params = {
538
+ ...normalizeObject(composedRequest.params),
539
+ ...normalizeObject(msg && msg.params)
540
+ };
541
+ const query = {
542
+ ...normalizeObject(composedRequest.query),
543
+ ...normalizeObject(msg && msg.query)
544
+ };
545
+ const headers = {
546
+ ...normalizeObject(composedRequest.headers),
547
+ ...normalizeObject(msg && msg.headers)
548
+ };
549
+
550
+ let payload;
551
+ if (capability.useConfiguredPayload) {
552
+ payload = Object.prototype.hasOwnProperty.call(composedRequest, "payload")
553
+ ? composedRequest.payload
554
+ : undefined;
555
+ } else if (capability.ignoreInputPayload) {
556
+ payload = Object.prototype.hasOwnProperty.call(composedRequest, "payload")
557
+ ? composedRequest.payload
558
+ : undefined;
559
+ } else if (Object.prototype.hasOwnProperty.call(msg || {}, "payload")) {
560
+ payload = msg.payload;
561
+ } else if (Object.prototype.hasOwnProperty.call(composedRequest, "payload")) {
562
+ payload = composedRequest.payload;
563
+ }
564
+
565
+ return {
566
+ params,
567
+ query,
568
+ headers,
569
+ payload
570
+ };
571
+ }
572
+
573
+ async function getCapabilityOptions(deviceType, capabilityId, context) {
574
+ if (capabilityId === "observe") {
575
+ const observableDefinitions = getObservableDefinitions(deviceType);
576
+ if (observableDefinitions.length > 0) {
577
+ return buildObservableFields(deviceType, context);
578
+ }
579
+ }
580
+
581
+ const capability = getCapabilityDefinition(deviceType, capabilityId);
582
+ if (!capability || !capability.editor || !Array.isArray(capability.editor.fields) || capability.editor.fields.length === 0) {
583
+ return {
584
+ capabilityId,
585
+ fields: []
586
+ };
587
+ }
588
+
589
+ if (deviceType === "camera" && capabilityId === "gotoPtzPreset") {
590
+ if (!context || !context.deviceId) {
591
+ return {
592
+ capabilityId,
593
+ fields: [{
594
+ ...capability.editor.fields[0],
595
+ type: "text",
596
+ placeholder: "Select a camera first",
597
+ helpText: "Select a camera to discover available PTZ presets, or enter the slot manually."
598
+ }]
599
+ };
600
+ }
601
+
602
+ const camera = context && typeof context.fetchDevice === "function"
603
+ ? await context.fetchDevice("camera", context.deviceId)
604
+ : null;
605
+ return {
606
+ capabilityId,
607
+ fields: [buildPtzPresetField(camera, capability.editor.fields[0])]
608
+ };
609
+ }
610
+
611
+ if (deviceType === "viewer" && capabilityId === "setLiveview") {
612
+ const liveviews = context && typeof context.fetchDevices === "function"
613
+ ? await context.fetchDevices("liveview")
614
+ : [];
615
+ return {
616
+ capabilityId,
617
+ fields: [buildLiveviewField(liveviews, capability.editor.fields[0])]
618
+ };
619
+ }
620
+
621
+ if (deviceType === "camera" && capabilityId === "setDoorbellMessage") {
622
+ return buildDoorbellMessageFields(context, capability);
623
+ }
624
+
625
+ if (capabilityId === "setProperty") {
626
+ return buildSetPropertyFields(deviceType, context, capability);
627
+ }
628
+
629
+ return {
630
+ capabilityId,
631
+ fields: capability.editor.fields.map((field) => ({ ...field }))
632
+ };
633
+ }
634
+
635
+ function buildPathFromTemplate(pathTemplate, deviceId, params) {
636
+ let path = String(pathTemplate || "");
637
+
638
+ if (path.includes(":id")) {
639
+ if (!deviceId) {
640
+ throw new Error("This capability requires a device id.");
641
+ }
642
+ path = path.replace(":id", encodeURIComponent(String(deviceId)));
643
+ }
644
+
645
+ Object.entries(params || {}).forEach(([key, value]) => {
646
+ if (value === undefined || value === null || value === "") {
647
+ return;
648
+ }
649
+ path = path.replace(`:${key}`, encodeURIComponent(String(value)));
650
+ });
651
+
652
+ if (path.includes(":")) {
653
+ throw new Error(`Missing required path parameters for ${path}`);
654
+ }
655
+
656
+ return path;
657
+ }
658
+
659
+ function normalizeDeviceCollection(deviceType, payload) {
660
+ const definition = getDeviceTypeDefinition(deviceType);
661
+ if (!definition) {
662
+ return [];
663
+ }
664
+
665
+ if (Array.isArray(payload)) {
666
+ return payload;
667
+ }
668
+
669
+ if (payload && typeof payload === "object") {
670
+ return [payload];
671
+ }
672
+
673
+ return [];
674
+ }
675
+
676
+ function summarizeDevice(deviceType, device) {
677
+ const definition = getDeviceTypeDefinition(deviceType);
678
+ const modelKey = definition ? definition.modelKey : String(deviceType || "");
679
+ const fallbackId = `${deviceType || "device"}`;
680
+
681
+ return {
682
+ id: String(device && device.id ? device.id : fallbackId),
683
+ name: String((device && (device.name || device.displayName)) || (device && device.id) || fallbackId),
684
+ modelKey,
685
+ state: String((device && device.state) || ""),
686
+ mac: String((device && device.mac) || ""),
687
+ raw: device
688
+ };
689
+ }
690
+
691
+ function buildPtzPresetField(camera, baseField) {
692
+ const options = extractPtzPresetOptions(camera);
693
+ if (options.length > 0) {
694
+ return {
695
+ ...baseField,
696
+ type: "select",
697
+ options
698
+ };
699
+ }
700
+
701
+ return {
702
+ ...baseField,
703
+ type: "text",
704
+ placeholder: "Preset slot",
705
+ helpText: "No preset list was discovered on this camera. Enter the PTZ preset slot manually."
706
+ };
707
+ }
708
+
709
+ function buildLiveviewField(liveviews, baseField) {
710
+ return {
711
+ ...baseField,
712
+ type: "select",
713
+ options: buildLiveviewOptions(liveviews, baseField.allowEmpty, baseField.emptyLabel)
714
+ };
715
+ }
716
+
717
+ function buildLiveviewOptions(liveviews, allowEmpty, emptyLabel) {
718
+ const options = Array.isArray(liveviews)
719
+ ? liveviews.map((liveview) => ({
720
+ value: String(liveview && liveview.id ? liveview.id : ""),
721
+ label: String((liveview && (liveview.name || liveview.displayName)) || (liveview && liveview.id) || "Live view")
722
+ })).filter((option) => option.value)
723
+ : [];
724
+
725
+ if (allowEmpty) {
726
+ options.unshift({
727
+ value: "",
728
+ label: emptyLabel || "None"
729
+ });
730
+ }
731
+
732
+ return options;
733
+ }
734
+
735
+ async function buildDoorbellMessageFields(context, capability) {
736
+ const capabilityConfig = normalizeObject(context && context.capabilityConfig);
737
+ const messageType = String(capabilityConfig.messageType || "DO_NOT_DISTURB").trim() || "DO_NOT_DISTURB";
738
+ const fields = [
739
+ {
740
+ ...capability.editor.fields[0],
741
+ defaultValue: messageType
742
+ }
743
+ ];
744
+
745
+ if (messageType === "CUSTOM_MESSAGE") {
746
+ fields.push({
747
+ ...capability.editor.fields[1],
748
+ defaultValue: capabilityConfig.messageText || ""
749
+ });
750
+ }
751
+
752
+ if (messageType === "IMAGE") {
753
+ const files = context && typeof context.fetchAssetFiles === "function"
754
+ ? await context.fetchAssetFiles("animations")
755
+ : [];
756
+ fields.push({
757
+ ...capability.editor.fields[2],
758
+ options: buildAssetFileOptions(files),
759
+ defaultValue: capabilityConfig.messageImage || ""
760
+ });
761
+ }
762
+
763
+ fields.push({
764
+ ...capability.editor.fields[3],
765
+ defaultValue: capabilityConfig.resetAt !== undefined ? String(capabilityConfig.resetAt) : ""
766
+ });
767
+
768
+ return {
769
+ capabilityId: capability.id,
770
+ fields
771
+ };
772
+ }
773
+
774
+ function buildAssetFileOptions(files) {
775
+ return Array.isArray(files)
776
+ ? files.map((file) => ({
777
+ value: String(file && file.name ? file.name : ""),
778
+ label: String((file && (file.originalName || file.name)) || "Asset")
779
+ })).filter((option) => option.value)
780
+ : [];
781
+ }
782
+
783
+ function buildObservableFields(deviceType, context) {
784
+ const capabilityConfig = normalizeObject(context && context.capabilityConfig);
785
+ const observableOptions = getObservableOptions(deviceType);
786
+
787
+ return {
788
+ capabilityId: "observe",
789
+ fields: [
790
+ {
791
+ id: "observable",
792
+ label: "Observable",
793
+ type: "select",
794
+ options: observableOptions,
795
+ defaultValue: resolveSelectedObservable(observableOptions, capabilityConfig.observable)
796
+ }
797
+ ]
798
+ };
799
+ }
800
+
801
+ async function buildSetPropertyFields(deviceType, context, capability) {
802
+ if (!context || !context.deviceId || typeof context.fetchDevice !== "function") {
803
+ return {
804
+ capabilityId: capability.id,
805
+ fields: [{
806
+ id: "propertyPath",
807
+ label: "Property",
808
+ type: "text",
809
+ placeholder: "Select a device first",
810
+ helpText: "Select a device to discover configurable properties."
811
+ }]
812
+ };
813
+ }
814
+
815
+ const device = await context.fetchDevice(deviceType, context.deviceId);
816
+ const capabilityConfig = normalizeObject(context.capabilityConfig);
817
+ const propertyOptions = collectConfigurablePropertyOptions(deviceType, device);
818
+ const selectedPath = resolveSelectedPropertyPath(propertyOptions, capabilityConfig.propertyPath);
819
+ const liveviews = deviceType === "viewer" && typeof context.fetchDevices === "function"
820
+ ? await context.fetchDevices("liveview")
821
+ : [];
822
+
823
+ const fields = [
824
+ {
825
+ id: "propertyPath",
826
+ label: "Property",
827
+ type: "select",
828
+ placeholder: "Select a property",
829
+ reloadOnChange: true,
830
+ options: propertyOptions
831
+ }
832
+ ];
833
+
834
+ if (!selectedPath) {
835
+ return {
836
+ capabilityId: capability.id,
837
+ fields
838
+ };
839
+ }
840
+
841
+ const fieldDefinition = buildPropertyValueFields(deviceType, device, selectedPath, capabilityConfig, {
842
+ liveviews
843
+ });
844
+ return {
845
+ capabilityId: capability.id,
846
+ fields: fields.concat(fieldDefinition)
847
+ };
848
+ }
849
+
850
+ function resolveSelectedPropertyPath(propertyOptions, configuredPath) {
851
+ const normalizedPath = String(configuredPath || "").trim();
852
+ if (!normalizedPath) {
853
+ return "";
854
+ }
855
+
856
+ return propertyOptions.some((option) => option.value === normalizedPath)
857
+ ? normalizedPath
858
+ : "";
859
+ }
860
+
861
+ function buildPropertyValueFields(deviceType, device, propertyPath, capabilityConfig, extra) {
862
+ const currentValue = getValueAtPath(device, propertyPath);
863
+ const descriptor = inferPropertyDescriptor(deviceType, propertyPath, currentValue, extra);
864
+
865
+ return [
866
+ {
867
+ id: "valueType",
868
+ type: "hidden",
869
+ defaultValue: descriptor.valueType
870
+ },
871
+ {
872
+ id: "propertyValue",
873
+ label: "Value",
874
+ ...descriptor.field,
875
+ defaultValue: normalizeDefaultPropertyValue(capabilityConfig.propertyValue, descriptor, currentValue)
876
+ }
877
+ ];
878
+ }
879
+
880
+ function inferPropertyDescriptor(deviceType, propertyPath, currentValue, extra) {
881
+ if (deviceType === "viewer" && propertyPath === "liveview") {
882
+ return {
883
+ valueType: "string",
884
+ field: {
885
+ type: "select",
886
+ allowEmpty: true,
887
+ emptyLabel: "No live view",
888
+ options: buildLiveviewOptions(extra && extra.liveviews, true, "No live view")
889
+ }
890
+ };
891
+ }
892
+
893
+ if (deviceType === "camera" && propertyPath === "lcdMessage.type") {
894
+ return {
895
+ valueType: "string",
896
+ field: {
897
+ type: "select",
898
+ options: [
899
+ { value: "DO_NOT_DISTURB", label: "Do not disturb" },
900
+ { value: "LEAVE_PACKAGE_AT_DOOR", label: "Leave package at door" },
901
+ { value: "CUSTOM_MESSAGE", label: "Custom message" },
902
+ { value: "IMAGE", label: "Image" }
903
+ ]
904
+ }
905
+ };
906
+ }
907
+
908
+ if (typeof currentValue === "boolean") {
909
+ return {
910
+ valueType: "boolean",
911
+ field: {
912
+ type: "select",
913
+ options: [
914
+ { value: "true", label: "True" },
915
+ { value: "false", label: "False" }
916
+ ]
917
+ }
918
+ };
919
+ }
920
+
921
+ if (typeof currentValue === "number") {
922
+ return {
923
+ valueType: "number",
924
+ field: {
925
+ type: "number"
926
+ }
927
+ };
928
+ }
929
+
930
+ if (currentValue === null) {
931
+ return {
932
+ valueType: "nullish-string",
933
+ field: {
934
+ type: "text",
935
+ placeholder: "Value"
936
+ }
937
+ };
938
+ }
939
+
940
+ return {
941
+ valueType: "string",
942
+ field: {
943
+ type: "text",
944
+ placeholder: "Value"
945
+ }
946
+ };
947
+ }
948
+
949
+ function normalizeDefaultPropertyValue(configuredValue, descriptor, currentValue) {
950
+ if (configuredValue !== undefined && configuredValue !== null && configuredValue !== "") {
951
+ return configuredValue;
952
+ }
953
+
954
+ if (descriptor.valueType === "boolean") {
955
+ return currentValue === true ? "true" : "false";
956
+ }
957
+
958
+ if (descriptor.valueType === "number" && typeof currentValue === "number") {
959
+ return String(currentValue);
960
+ }
961
+
962
+ if (currentValue === null || currentValue === undefined) {
963
+ return "";
964
+ }
965
+
966
+ return typeof currentValue === "string"
967
+ ? currentValue
968
+ : String(currentValue);
969
+ }
970
+
971
+ function collectConfigurablePropertyOptions(deviceType, device) {
972
+ const collected = [];
973
+ const visited = new Set();
974
+
975
+ function walk(value, pathSegments) {
976
+ if (value && typeof value === "object") {
977
+ if (visited.has(value)) {
978
+ return;
979
+ }
980
+ visited.add(value);
981
+ }
982
+
983
+ if (pathSegments.length > 0 && isPrimitivePatchValue(value) && isConfigurablePath(pathSegments)) {
984
+ const path = pathSegments.join(".");
985
+ collected.push({
986
+ value: path,
987
+ label: `${formatPropertyLabel(pathSegments)} (${formatCurrentValue(value)})`
988
+ });
989
+ }
990
+
991
+ if (!value || typeof value !== "object" || Array.isArray(value) || pathSegments.length >= 4) {
992
+ return;
993
+ }
994
+
995
+ Object.entries(value).forEach(([key, nestedValue]) => {
996
+ walk(nestedValue, pathSegments.concat(key));
997
+ });
998
+ }
999
+
1000
+ walk(device, []);
1001
+
1002
+ return deduplicateOptions(collected)
1003
+ .sort((left, right) => left.label.localeCompare(right.label))
1004
+ .filter((option) => filterPropertyOption(deviceType, option.value));
1005
+ }
1006
+
1007
+ function filterPropertyOption(deviceType, propertyPath) {
1008
+ if (deviceType === "viewer" && propertyPath === "liveview") {
1009
+ return true;
1010
+ }
1011
+
1012
+ if (deviceType === "camera" && propertyPath.startsWith("lcdMessage.")) {
1013
+ return true;
1014
+ }
1015
+
1016
+ return true;
1017
+ }
1018
+
1019
+ function isPrimitivePatchValue(value) {
1020
+ return value === null || ["string", "number", "boolean"].includes(typeof value);
1021
+ }
1022
+
1023
+ function isConfigurablePath(pathSegments) {
1024
+ const lastSegment = String(pathSegments[pathSegments.length - 1] || "");
1025
+ const normalizedPath = pathSegments.join(".");
1026
+ const lowerSegments = pathSegments.map((segment) => String(segment).toLowerCase());
1027
+ const readonlyNames = new Set([
1028
+ "id", "modelkey", "type", "state", "mac", "host", "guid", "serial", "version",
1029
+ "hardwarerevision", "firmwareversion", "lastseen", "connectedsince", "uptime",
1030
+ "marketname", "ip", "bridge", "bluetoothconnectionstate", "wificonnectionstate",
1031
+ "connectionstate", "isconnected", "isadopted", "isattemptingtoconnect", "isupdating"
1032
+ ]);
1033
+
1034
+ if (readonlyNames.has(lastSegment.toLowerCase())) {
1035
+ return false;
1036
+ }
1037
+
1038
+ if (lowerSegments.some((segment) => readonlyNames.has(segment))) {
1039
+ return false;
1040
+ }
1041
+
1042
+ if (lowerSegments.some((segment) => /stats?$|channels?$|zones?$|features?$|capabilities?$|permissions?$|events?$/.test(segment))) {
1043
+ return false;
1044
+ }
1045
+
1046
+ if (/\.\d+(\.|$)/.test(normalizedPath)) {
1047
+ return false;
1048
+ }
1049
+
1050
+ return true;
1051
+ }
1052
+
1053
+ function formatPropertyLabel(pathSegments) {
1054
+ return pathSegments.map((segment) => String(segment).replace(/([a-z0-9])([A-Z])/g, "$1 $2")).join(" > ");
1055
+ }
1056
+
1057
+ function formatCurrentValue(value) {
1058
+ if (value === null) {
1059
+ return "null";
1060
+ }
1061
+ if (typeof value === "boolean") {
1062
+ return value ? "true" : "false";
1063
+ }
1064
+ const text = String(value);
1065
+ return text.length > 24 ? `${text.slice(0, 21)}...` : text;
1066
+ }
1067
+
1068
+ function deduplicateOptions(options) {
1069
+ const seen = new Map();
1070
+ options.forEach((option) => {
1071
+ if (!seen.has(option.value)) {
1072
+ seen.set(option.value, option);
1073
+ }
1074
+ });
1075
+ return Array.from(seen.values());
1076
+ }
1077
+
1078
+ function getValueAtPath(value, propertyPath) {
1079
+ return String(propertyPath || "").split(".").filter(Boolean).reduce((current, segment) => {
1080
+ if (!current || typeof current !== "object") {
1081
+ return undefined;
1082
+ }
1083
+ return current[segment];
1084
+ }, value);
1085
+ }
1086
+
1087
+ function buildNestedPatchPayload(propertyPath, propertyValue) {
1088
+ const segments = String(propertyPath || "").split(".").filter(Boolean);
1089
+ if (segments.length === 0) {
1090
+ return {};
1091
+ }
1092
+
1093
+ const payload = {};
1094
+ let cursor = payload;
1095
+
1096
+ segments.forEach((segment, index) => {
1097
+ if (index === segments.length - 1) {
1098
+ cursor[segment] = propertyValue;
1099
+ return;
1100
+ }
1101
+
1102
+ cursor[segment] = {};
1103
+ cursor = cursor[segment];
1104
+ });
1105
+
1106
+ return payload;
1107
+ }
1108
+
1109
+ function parseConfiguredPropertyValue(value, valueType) {
1110
+ if (valueType === "boolean") {
1111
+ return value === true || value === "true";
1112
+ }
1113
+
1114
+ if (valueType === "number") {
1115
+ const parsed = Number(value);
1116
+ return Number.isFinite(parsed) ? parsed : 0;
1117
+ }
1118
+
1119
+ return value;
1120
+ }
1121
+
1122
+ function buildDoorbellMessagePayload(capabilityConfig) {
1123
+ const messageType = String(capabilityConfig.messageType || "").trim();
1124
+ const payload = {
1125
+ type: messageType || "DO_NOT_DISTURB"
1126
+ };
1127
+
1128
+ const resetAtValue = parseResetAtValue(capabilityConfig.resetAt);
1129
+ if (resetAtValue !== undefined) {
1130
+ payload.resetAt = resetAtValue;
1131
+ }
1132
+
1133
+ if (payload.type === "CUSTOM_MESSAGE") {
1134
+ payload.text = String(capabilityConfig.messageText || "").trim();
1135
+ }
1136
+
1137
+ if (payload.type === "IMAGE") {
1138
+ payload.text = String(capabilityConfig.messageImage || "").trim();
1139
+ }
1140
+
1141
+ return payload;
1142
+ }
1143
+
1144
+ function parseResetAtValue(value) {
1145
+ const normalized = String(value === undefined || value === null ? "" : value).trim();
1146
+ if (normalized === "") {
1147
+ return undefined;
1148
+ }
1149
+ if (normalized.toLowerCase() === "null") {
1150
+ return null;
1151
+ }
1152
+
1153
+ const parsed = Number(normalized);
1154
+ return Number.isFinite(parsed) ? parsed : undefined;
1155
+ }
1156
+
1157
+ function getObservableDefinitions(deviceType) {
1158
+ const definitionsByDeviceType = {
1159
+ sensor: SENSOR_OBSERVABLE_DEFINITIONS,
1160
+ camera: CAMERA_OBSERVABLE_DEFINITIONS,
1161
+ light: LIGHT_OBSERVABLE_DEFINITIONS
1162
+ };
1163
+
1164
+ return definitionsByDeviceType[String(deviceType || "").trim()] || [];
1165
+ }
1166
+
1167
+ function getObservableOptions(deviceType) {
1168
+ return getObservableDefinitions(deviceType).map((definition) => ({
1169
+ value: definition.id,
1170
+ label: definition.label
1171
+ }));
1172
+ }
1173
+
1174
+ function resolveSelectedObservable(options, configuredObservable) {
1175
+ const normalized = String(configuredObservable || "").trim();
1176
+ if (normalized && options.some((option) => option.value === normalized)) {
1177
+ return normalized;
1178
+ }
1179
+
1180
+ return options.length > 0 ? options[0].value : "";
1181
+ }
1182
+
1183
+ function resolveObservableState(deviceType, device, observable, fallbackValue) {
1184
+ if (deviceType === "sensor") {
1185
+ return resolveSensorObservableState(device, observable, fallbackValue);
1186
+ }
1187
+
1188
+ if (deviceType === "camera") {
1189
+ return resolveCameraObservableState(device, observable, fallbackValue);
1190
+ }
1191
+
1192
+ if (deviceType === "light") {
1193
+ return resolveLightObservableState(device, observable, fallbackValue);
1194
+ }
1195
+
1196
+ return fallbackValue;
1197
+ }
1198
+
1199
+ function resolveSensorObservableState(sensor, observable, fallbackValue) {
1200
+ const definition = getObservableDefinitions("sensor").find((entry) => entry.id === observable);
1201
+ if (!definition) {
1202
+ return fallbackValue;
1203
+ }
1204
+
1205
+ const directValueResolvers = {
1206
+ contact: () => firstDefinedValue(sensor, [
1207
+ "isOpened",
1208
+ "opened",
1209
+ "open",
1210
+ "status.isOpened",
1211
+ "stats.isOpened"
1212
+ ]),
1213
+ motion: () => firstDefinedValue(sensor, [
1214
+ "isMotionDetected",
1215
+ "motionDetected",
1216
+ "status.motionDetected"
1217
+ ]),
1218
+ alarm: () => firstDefinedValue(sensor, [
1219
+ "isAlarmDetected",
1220
+ "alarmDetected",
1221
+ "status.alarmDetected"
1222
+ ]),
1223
+ waterLeak: () => firstDefinedValue(sensor, [
1224
+ "isWaterLeakDetected",
1225
+ "waterLeakDetected",
1226
+ "status.waterLeakDetected"
1227
+ ]),
1228
+ batteryLow: () => {
1229
+ const direct = firstDefinedValue(sensor, [
1230
+ "isBatteryLow",
1231
+ "batteryLow",
1232
+ "status.batteryLow"
1233
+ ]);
1234
+ if (direct !== undefined) {
1235
+ return direct;
1236
+ }
1237
+
1238
+ const batteryStatus = firstDefinedValue(sensor, ["batteryStatus", "status.batteryStatus"]);
1239
+ if (typeof batteryStatus === "string") {
1240
+ return ["low", "critical"].includes(batteryStatus.toLowerCase());
1241
+ }
1242
+
1243
+ return undefined;
1244
+ },
1245
+ tamper: () => firstDefinedValue(sensor, [
1246
+ "isTampered",
1247
+ "tampered",
1248
+ "status.tampered"
1249
+ ]),
1250
+ smokeTest: () => firstDefinedValue(sensor, [
1251
+ "isSmokeTestRunning",
1252
+ "smokeTestRunning",
1253
+ "status.smokeTestRunning"
1254
+ ])
1255
+ };
1256
+
1257
+ const rawValue = typeof directValueResolvers[observable] === "function"
1258
+ ? directValueResolvers[observable]()
1259
+ : undefined;
1260
+
1261
+ if (rawValue === undefined) {
1262
+ return fallbackValue;
1263
+ }
1264
+
1265
+ return normalizeBooleanState(rawValue, fallbackValue);
1266
+ }
1267
+
1268
+ function resolveCameraObservableState(camera, observable, fallbackValue) {
1269
+ const definition = getObservableDefinitions("camera").find((entry) => entry.id === observable);
1270
+ if (!definition) {
1271
+ return fallbackValue;
1272
+ }
1273
+
1274
+ const directValueResolvers = {
1275
+ ring: () => firstDefinedValue(camera, ["isRinging", "ringing", "status.ringing"]),
1276
+ motion: () => firstDefinedValue(camera, ["isMotionDetected", "motionDetected", "status.motionDetected"]),
1277
+ smartAudioDetect: () => firstDefinedValue(camera, ["isSmartAudioDetected", "smartAudioDetected", "status.smartAudioDetected"]),
1278
+ smartDetectZone: () => firstDefinedValue(camera, ["isSmartDetecting", "smartDetecting", "status.smartDetecting"]),
1279
+ smartDetectLine: () => firstDefinedValue(camera, ["isSmartDetecting", "smartDetecting", "status.smartDetecting"]),
1280
+ smartDetectLoiterZone: () => firstDefinedValue(camera, ["isSmartDetecting", "smartDetecting", "status.smartDetecting"])
1281
+ };
1282
+
1283
+ const rawValue = typeof directValueResolvers[observable] === "function"
1284
+ ? directValueResolvers[observable]()
1285
+ : undefined;
1286
+
1287
+ if (rawValue === undefined) {
1288
+ return fallbackValue;
1289
+ }
1290
+
1291
+ return normalizeBooleanState(rawValue, fallbackValue);
1292
+ }
1293
+
1294
+ function resolveLightObservableState(light, observable, fallbackValue) {
1295
+ const definition = getObservableDefinitions("light").find((entry) => entry.id === observable);
1296
+ if (!definition) {
1297
+ return fallbackValue;
1298
+ }
1299
+
1300
+ const directValueResolvers = {
1301
+ motion: () => firstDefinedValue(light, ["isMotionDetected", "motionDetected", "status.motionDetected"]),
1302
+ lightOn: () => firstDefinedValue(light, ["isLightOn", "lightOn", "status.lightOn", "isOn", "on"])
1303
+ };
1304
+
1305
+ const rawValue = typeof directValueResolvers[observable] === "function"
1306
+ ? directValueResolvers[observable]()
1307
+ : undefined;
1308
+
1309
+ if (rawValue === undefined) {
1310
+ return fallbackValue;
1311
+ }
1312
+
1313
+ return normalizeBooleanState(rawValue, fallbackValue);
1314
+ }
1315
+
1316
+ function resolveObservableEventValue(deviceType, event, observable) {
1317
+ if (deviceType === "sensor") {
1318
+ return resolveSensorObservableEventValue(event, observable);
1319
+ }
1320
+
1321
+ if (deviceType === "camera") {
1322
+ return resolveCameraObservableEventValue(event, observable);
1323
+ }
1324
+
1325
+ if (deviceType === "light") {
1326
+ return resolveLightObservableEventValue(event, observable);
1327
+ }
1328
+
1329
+ return { matched: false };
1330
+ }
1331
+
1332
+ function resolveSensorObservableEventValue(event, observable) {
1333
+ if (!event || typeof event !== "object") {
1334
+ return { matched: false };
1335
+ }
1336
+
1337
+ const eventType = String(event.type || "").trim();
1338
+ if (!eventType) {
1339
+ return { matched: false };
1340
+ }
1341
+
1342
+ if (observable === "contact") {
1343
+ if (eventType === "sensorOpened") {
1344
+ return { matched: true, value: true };
1345
+ }
1346
+ if (eventType === "sensorClosed") {
1347
+ return { matched: true, value: false };
1348
+ }
1349
+ return { matched: false };
1350
+ }
1351
+
1352
+ const definition = SENSOR_OBSERVABLE_DEFINITIONS.find((entry) => entry.id === observable);
1353
+ if (!definition || !definition.eventTypes.includes(eventType)) {
1354
+ return { matched: false };
1355
+ }
1356
+
1357
+ return {
1358
+ matched: true,
1359
+ value: event.end === null || event.end === undefined
1360
+ };
1361
+ }
1362
+
1363
+ function resolveCameraObservableEventValue(event, observable) {
1364
+ if (!event || typeof event !== "object") {
1365
+ return { matched: false };
1366
+ }
1367
+
1368
+ const eventType = String(event.type || "").trim();
1369
+ const definition = getObservableDefinitions("camera").find((entry) => entry.id === observable);
1370
+ if (!definition || !definition.eventTypes.includes(eventType)) {
1371
+ return { matched: false };
1372
+ }
1373
+
1374
+ return {
1375
+ matched: true,
1376
+ value: event.end === null || event.end === undefined
1377
+ };
1378
+ }
1379
+
1380
+ function resolveLightObservableEventValue(event, observable) {
1381
+ if (!event || typeof event !== "object") {
1382
+ return { matched: false };
1383
+ }
1384
+
1385
+ const eventType = String(event.type || "").trim();
1386
+ if (observable === "motion" && eventType === "lightMotion") {
1387
+ return {
1388
+ matched: true,
1389
+ value: event.end === null || event.end === undefined
1390
+ };
1391
+ }
1392
+
1393
+ return { matched: false };
1394
+ }
1395
+
1396
+ function normalizeBooleanState(value, fallbackValue) {
1397
+ if (typeof value === "boolean") {
1398
+ return value;
1399
+ }
1400
+ if (typeof value === "number") {
1401
+ return value > 0;
1402
+ }
1403
+ if (typeof value === "string") {
1404
+ const normalized = value.trim().toLowerCase();
1405
+ if (["true", "on", "open", "opened", "active", "detected", "alarm", "running", "low", "critical"].includes(normalized)) {
1406
+ return true;
1407
+ }
1408
+ if (["false", "off", "closed", "inactive", "normal", "ok"].includes(normalized)) {
1409
+ return false;
1410
+ }
1411
+ }
1412
+
1413
+ return fallbackValue;
1414
+ }
1415
+
1416
+ function firstDefinedValue(value, paths) {
1417
+ for (const path of paths) {
1418
+ const current = getValueAtPath(value, path);
1419
+ if (current !== undefined) {
1420
+ return current;
1421
+ }
1422
+ }
1423
+ return undefined;
1424
+ }
1425
+
1426
+ function extractPtzPresetOptions(camera) {
1427
+ const optionsByValue = new Map();
1428
+ const visited = new Set();
1429
+
1430
+ function addOption(slotValue, labelValue) {
1431
+ const value = slotValue === undefined || slotValue === null ? "" : String(slotValue).trim();
1432
+ if (!value || !/^-?\d+$/.test(value)) {
1433
+ return;
1434
+ }
1435
+
1436
+ if (!optionsByValue.has(value)) {
1437
+ optionsByValue.set(value, {
1438
+ value,
1439
+ label: String(labelValue || `Preset ${value}`).trim() || `Preset ${value}`
1440
+ });
1441
+ }
1442
+ }
1443
+
1444
+ function walk(value, pathSegments) {
1445
+ if (!value || typeof value !== "object" || visited.has(value)) {
1446
+ return;
1447
+ }
1448
+ visited.add(value);
1449
+
1450
+ const inPresetBranch = pathSegments.some((segment) => /preset/i.test(segment));
1451
+
1452
+ if (Array.isArray(value)) {
1453
+ if (inPresetBranch) {
1454
+ value.forEach((entry) => {
1455
+ const slot = getPresetSlot(entry);
1456
+ if (slot !== null) {
1457
+ addOption(slot, getPresetLabel(entry, slot));
1458
+ }
1459
+ });
1460
+ }
1461
+
1462
+ value.forEach((entry, index) => {
1463
+ walk(entry, pathSegments.concat(String(index)));
1464
+ });
1465
+ return;
1466
+ }
1467
+
1468
+ if (inPresetBranch) {
1469
+ Object.entries(value).forEach(([key, entry]) => {
1470
+ if (/^-?\d+$/.test(String(key))) {
1471
+ addOption(key, getPresetLabel(entry, key));
1472
+ }
1473
+
1474
+ const slot = getPresetSlot(entry);
1475
+ if (slot !== null) {
1476
+ addOption(slot, getPresetLabel(entry, slot));
1477
+ }
1478
+ });
1479
+ }
1480
+
1481
+ Object.entries(value).forEach(([key, entry]) => {
1482
+ walk(entry, pathSegments.concat(key));
1483
+ });
1484
+ }
1485
+
1486
+ walk(camera, []);
1487
+
1488
+ return Array.from(optionsByValue.values()).sort((left, right) => Number(left.value) - Number(right.value));
1489
+ }
1490
+
1491
+ function getPresetSlot(entry) {
1492
+ if (!entry || typeof entry !== "object") {
1493
+ return null;
1494
+ }
1495
+
1496
+ const candidateKeys = ["slot", "presetSlot", "slotId", "presetIndex", "index"];
1497
+ for (const key of candidateKeys) {
1498
+ if (entry[key] !== undefined && entry[key] !== null && String(entry[key]).trim() !== "") {
1499
+ return entry[key];
1500
+ }
1501
+ }
1502
+
1503
+ return null;
1504
+ }
1505
+
1506
+ function getPresetLabel(entry, fallbackValue) {
1507
+ if (!entry || typeof entry !== "object") {
1508
+ return `Preset ${fallbackValue}`;
1509
+ }
1510
+
1511
+ const candidateKeys = ["name", "displayName", "label", "presetName"];
1512
+ for (const key of candidateKeys) {
1513
+ if (entry[key] !== undefined && entry[key] !== null && String(entry[key]).trim() !== "") {
1514
+ return entry[key];
1515
+ }
1516
+ }
1517
+
1518
+ return `Preset ${fallbackValue}`;
1519
+ }
1520
+
1521
+ function normalizeObject(value) {
1522
+ return value && typeof value === "object" && !Array.isArray(value)
1523
+ ? value
1524
+ : {};
1525
+ }
1526
+
1527
+ module.exports = {
1528
+ getDeviceTypes,
1529
+ getDeviceTypeDefinition,
1530
+ getCapabilitiesForType,
1531
+ getCapabilityDefinition,
1532
+ buildDevicePath,
1533
+ buildCapabilityRequest,
1534
+ composeCapabilityExecution,
1535
+ getCapabilityOptions,
1536
+ getObservableOptions,
1537
+ resolveObservableState,
1538
+ resolveObservableEventValue,
1539
+ normalizeDeviceCollection,
1540
+ summarizeDevice
1541
+ };