iobroker.unraid 0.4.0

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,24 @@
1
+ <html>
2
+
3
+ <head>
4
+
5
+ <!-- Load ioBroker scripts and styles-->
6
+ <link rel="stylesheet" type="text/css" href="../../css/adapter.css" />
7
+ <script type="text/javascript" src="../../socket.io/socket.io.js"></script>
8
+
9
+ <!-- Load our own files -->
10
+ <link rel="stylesheet" type="text/css" href="style.css" />
11
+
12
+ </head>
13
+
14
+ <body>
15
+
16
+ <!-- this is where the React components are loaded into -->
17
+ <div class="m adapter-container" id="root"></div>
18
+
19
+ <!-- load compiled React scripts -->
20
+ <script type="text/javascript" src="build/index.js"></script>
21
+
22
+ </body>
23
+
24
+ </html>
@@ -0,0 +1,32 @@
1
+ /* You can delete those if you want. I just found them very helpful */
2
+ * {
3
+ box-sizing: border-box
4
+ }
5
+ .m {
6
+ /* Don't cut off dropdowns! */
7
+ overflow: initial;
8
+ }
9
+ .m.adapter-container,
10
+ .m.adapter-container > div.App {
11
+ /* Fix layout/scrolling issues with tabs */
12
+ height: 100%;
13
+ width: 100%;
14
+ position: relative;
15
+ }
16
+ .m .select-wrapper + label {
17
+ /* The positioning for dropdown labels is messed up */
18
+ transform: none !important;
19
+ }
20
+
21
+ label > i[title] {
22
+ /* Display the help cursor for the tooltip icons and fix their positioning */
23
+ cursor: help;
24
+ margin-left: 0.25em;
25
+ }
26
+
27
+ .dropdown-content {
28
+ /* Don't wrap text in dropdowns */
29
+ white-space: nowrap;
30
+ }
31
+
32
+ /* Add your styles here */
Binary file
@@ -0,0 +1,47 @@
1
+ export interface GraphQLClientOptions {
2
+ baseUrl: string;
3
+ token: string;
4
+ timeoutMs?: number;
5
+ allowSelfSigned?: boolean;
6
+ }
7
+ export type GraphQLErrorPayload = {
8
+ message?: string;
9
+ locations?: Array<{
10
+ line?: number;
11
+ column?: number;
12
+ }>;
13
+ extensions?: {
14
+ code?: string;
15
+ [key: string]: unknown;
16
+ };
17
+ };
18
+ export declare class GraphQLHttpError extends Error {
19
+ readonly status: number;
20
+ readonly body: string;
21
+ readonly json?: {
22
+ errors?: GraphQLErrorPayload[];
23
+ [key: string]: unknown;
24
+ };
25
+ constructor(status: number, body: string, json?: {
26
+ errors?: GraphQLErrorPayload[];
27
+ [key: string]: unknown;
28
+ });
29
+ }
30
+ export declare class GraphQLRequestError extends Error {
31
+ constructor(message: string);
32
+ }
33
+ export declare class GraphQLResponseError extends Error {
34
+ readonly errors: GraphQLErrorPayload[];
35
+ constructor(errors: GraphQLErrorPayload[]);
36
+ }
37
+ export declare class GraphQLClient {
38
+ private readonly endpoint;
39
+ private readonly token;
40
+ private readonly timeoutMs;
41
+ private readonly agent?;
42
+ constructor({ baseUrl, token, timeoutMs, allowSelfSigned }: GraphQLClientOptions);
43
+ query<T>(query: string): Promise<T>;
44
+ dispose(): Promise<void>;
45
+ private describeError;
46
+ }
47
+ //# sourceMappingURL=graphql-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graphql-client.d.ts","sourceRoot":"","sources":["../src/graphql-client.ts"],"names":[],"mappings":"AAEA,MAAM,WAAW,oBAAoB;IACjC,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,eAAe,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED,MAAM,MAAM,mBAAmB,GAAG;IAC9B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,SAAS,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACtD,UAAU,CAAC,EAAE;QACT,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC;KAC1B,CAAC;CACL,CAAC;AAEF,qBAAa,gBAAiB,SAAQ,KAAK;IACvC,SAAgB,MAAM,EAAE,MAAM,CAAC;IAC/B,SAAgB,IAAI,EAAE,MAAM,CAAC;IAC7B,SAAgB,IAAI,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,mBAAmB,EAAE,CAAC;QAAC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;KAAE,CAAC;gBAE/D,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE,mBAAmB,EAAE,CAAC;QAAC,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAA;KAAE;CAQrH;AAED,qBAAa,mBAAoB,SAAQ,KAAK;gBACvB,OAAO,EAAE,MAAM;CAIrC;AAED,qBAAa,oBAAqB,SAAQ,KAAK;IAC3C,SAAgB,MAAM,EAAE,mBAAmB,EAAE,CAAC;gBAE3B,MAAM,EAAE,mBAAmB,EAAE;CAKnD;AAOD,qBAAa,aAAa;IACtB,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAS;IAClC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAS;IAC/B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAS;IACnC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAQ;gBAEZ,EAAE,OAAO,EAAE,KAAK,EAAE,SAAS,EAAE,eAAe,EAAE,EAAE,oBAAoB;IAgB1E,KAAK,CAAC,CAAC,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,CAAC,CAAC;IAmEnC,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAMrC,OAAO,CAAC,aAAa;CA6BxB"}
@@ -0,0 +1,145 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GraphQLClient = exports.GraphQLResponseError = exports.GraphQLRequestError = exports.GraphQLHttpError = void 0;
4
+ const undici_1 = require("undici");
5
+ class GraphQLHttpError extends Error {
6
+ status;
7
+ body;
8
+ json;
9
+ constructor(status, body, json) {
10
+ const suffix = body ? `: ${body}` : '';
11
+ super(`HTTP ${status}${suffix}`);
12
+ this.name = 'GraphQLHttpError';
13
+ this.status = status;
14
+ this.body = body;
15
+ this.json = json;
16
+ }
17
+ }
18
+ exports.GraphQLHttpError = GraphQLHttpError;
19
+ class GraphQLRequestError extends Error {
20
+ constructor(message) {
21
+ super(message);
22
+ this.name = 'GraphQLRequestError';
23
+ }
24
+ }
25
+ exports.GraphQLRequestError = GraphQLRequestError;
26
+ class GraphQLResponseError extends Error {
27
+ errors;
28
+ constructor(errors) {
29
+ super(errors.map((error) => error.message).filter(Boolean).join('; ') || 'GraphQL response contained errors');
30
+ this.name = 'GraphQLResponseError';
31
+ this.errors = errors;
32
+ }
33
+ }
34
+ exports.GraphQLResponseError = GraphQLResponseError;
35
+ class GraphQLClient {
36
+ endpoint;
37
+ token;
38
+ timeoutMs;
39
+ agent;
40
+ constructor({ baseUrl, token, timeoutMs, allowSelfSigned }) {
41
+ const trimmedBaseUrl = baseUrl.replace(/\/$/, '');
42
+ this.endpoint = `${trimmedBaseUrl}/graphql`;
43
+ this.token = token;
44
+ this.timeoutMs = timeoutMs ?? 15000;
45
+ if (allowSelfSigned && this.endpoint.startsWith('https://')) {
46
+ // Accept self-signed certs by disabling TLS validation for this client only
47
+ this.agent = new undici_1.Agent({
48
+ connect: {
49
+ rejectUnauthorized: false,
50
+ },
51
+ });
52
+ }
53
+ }
54
+ async query(query) {
55
+ const controller = new AbortController();
56
+ const timeout = setTimeout(() => controller.abort(), this.timeoutMs);
57
+ try {
58
+ const headers = {
59
+ 'Content-Type': 'application/json',
60
+ Accept: 'application/json',
61
+ };
62
+ if (this.token) {
63
+ headers['x-api-key'] = this.token;
64
+ }
65
+ const requestInit = {
66
+ method: 'POST',
67
+ headers,
68
+ body: JSON.stringify({ query }),
69
+ signal: controller.signal,
70
+ };
71
+ if (this.agent) {
72
+ requestInit.dispatcher = this.agent;
73
+ }
74
+ const response = await fetch(this.endpoint, requestInit);
75
+ if (!response.ok) {
76
+ let bodyText = '';
77
+ try {
78
+ bodyText = await response.text();
79
+ }
80
+ catch (readError) {
81
+ const message = readError instanceof Error ? readError.message : String(readError);
82
+ throw new GraphQLHttpError(response.status, message || '');
83
+ }
84
+ let json;
85
+ try {
86
+ json = bodyText ? JSON.parse(bodyText) : undefined;
87
+ }
88
+ catch {
89
+ // ignore parse error, keep original body text
90
+ }
91
+ throw new GraphQLHttpError(response.status, bodyText.trim(), json);
92
+ }
93
+ const payload = (await response.json());
94
+ if (payload.errors?.length) {
95
+ throw new GraphQLResponseError(payload.errors);
96
+ }
97
+ if (!payload.data) {
98
+ throw new GraphQLRequestError('Empty response payload');
99
+ }
100
+ return payload.data;
101
+ }
102
+ catch (error) {
103
+ if (error instanceof GraphQLHttpError || error instanceof GraphQLRequestError || error instanceof GraphQLResponseError) {
104
+ throw error;
105
+ }
106
+ throw new GraphQLRequestError(`GraphQL request failed: ${this.describeError(error)}`);
107
+ }
108
+ finally {
109
+ clearTimeout(timeout);
110
+ }
111
+ }
112
+ async dispose() {
113
+ if (this.agent) {
114
+ await this.agent.close();
115
+ }
116
+ }
117
+ describeError(error) {
118
+ if (error instanceof Error) {
119
+ const segments = [];
120
+ if (error.message) {
121
+ segments.push(error.message);
122
+ }
123
+ const nodeError = error;
124
+ if (typeof nodeError.code === 'string') {
125
+ segments.push(`code=${nodeError.code}`);
126
+ }
127
+ if (typeof nodeError.syscall === 'string') {
128
+ segments.push(`syscall=${nodeError.syscall}`);
129
+ }
130
+ if ('address' in nodeError && typeof nodeError.address === 'string') {
131
+ segments.push(`address=${nodeError.address}`);
132
+ }
133
+ if ('port' in nodeError && typeof nodeError.port === 'number') {
134
+ segments.push(`port=${nodeError.port}`);
135
+ }
136
+ if (nodeError.cause) {
137
+ segments.push(`cause=${this.describeError(nodeError.cause)}`);
138
+ }
139
+ return segments.join(' ');
140
+ }
141
+ return String(error);
142
+ }
143
+ }
144
+ exports.GraphQLClient = GraphQLClient;
145
+ //# sourceMappingURL=graphql-client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graphql-client.js","sourceRoot":"","sources":["../src/graphql-client.ts"],"names":[],"mappings":";;;AAAA,mCAA+B;AAkB/B,MAAa,gBAAiB,SAAQ,KAAK;IACvB,MAAM,CAAS;IACf,IAAI,CAAS;IACb,IAAI,CAA8D;IAElF,YAAmB,MAAc,EAAE,IAAY,EAAE,IAAiE;QAC9G,MAAM,MAAM,GAAG,IAAI,CAAC,CAAC,CAAC,KAAK,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACvC,KAAK,CAAC,QAAQ,MAAM,GAAG,MAAM,EAAE,CAAC,CAAC;QACjC,IAAI,CAAC,IAAI,GAAG,kBAAkB,CAAC;QAC/B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACrB,CAAC;CACJ;AAbD,4CAaC;AAED,MAAa,mBAAoB,SAAQ,KAAK;IAC1C,YAAmB,OAAe;QAC9B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAC;IACtC,CAAC;CACJ;AALD,kDAKC;AAED,MAAa,oBAAqB,SAAQ,KAAK;IAC3B,MAAM,CAAwB;IAE9C,YAAmB,MAA6B;QAC5C,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,mCAAmC,CAAC,CAAC;QAC9G,IAAI,CAAC,IAAI,GAAG,sBAAsB,CAAC;QACnC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;CACJ;AARD,oDAQC;AAOD,MAAa,aAAa;IACL,QAAQ,CAAS;IACjB,KAAK,CAAS;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,CAAC,OAAO,EAAE,CAAC,CAAC;YAC3E,CAAC;YACD,IAAI,MAAM,IAAI,SAAS,IAAI,OAAQ,SAA+B,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBACnF,QAAQ,CAAC,IAAI,CAAC,QAAS,SAA8B,CAAC,IAAI,EAAE,CAAC,CAAC;YAClE,CAAC;YACD,IAAI,SAAS,CAAC,KAAK,EAAE,CAAC;gBAClB,QAAQ,CAAC,IAAI,CAAC,SAAS,IAAI,CAAC,aAAa,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;YAClE,CAAC;YAED,OAAO,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC9B,CAAC;QAED,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACzB,CAAC;CACJ;AA5HD,sCA4HC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=main.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"main.d.ts","sourceRoot":"","sources":["../src/main.ts"],"names":[],"mappings":""}
package/build/main.js ADDED
@@ -0,0 +1,384 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const adapter_core_1 = require("@iobroker/adapter-core");
4
+ const graphql_client_1 = require("./graphql-client");
5
+ const unraid_domains_1 = require("./shared/unraid-domains");
6
+ class GraphQLSelectionBuilder {
7
+ roots = new Map();
8
+ addSelections(selections) {
9
+ for (const selection of selections) {
10
+ if (!selection.fields.length) {
11
+ continue;
12
+ }
13
+ const rootNode = this.getOrCreateRoot(selection.root);
14
+ this.addFields(rootNode, selection.fields);
15
+ }
16
+ }
17
+ build() {
18
+ if (!this.roots.size) {
19
+ return null;
20
+ }
21
+ const sections = [];
22
+ const sortedRoots = Array.from(this.roots.keys()).sort((left, right) => left.localeCompare(right));
23
+ for (const root of sortedRoots) {
24
+ const node = this.roots.get(root);
25
+ if (!node) {
26
+ continue;
27
+ }
28
+ const body = this.printNode(node, 8);
29
+ const section = body
30
+ ? ` ${root} {\n${body}\n }`
31
+ : ` ${root}`;
32
+ sections.push(section);
33
+ }
34
+ const queryBody = sections.join('\n');
35
+ return `query UnraidAdapterFetch {\n${queryBody}\n}`;
36
+ }
37
+ getOrCreateRoot(root) {
38
+ const existing = this.roots.get(root);
39
+ if (existing) {
40
+ return existing;
41
+ }
42
+ const node = new Map();
43
+ this.roots.set(root, node);
44
+ return node;
45
+ }
46
+ addFields(target, fields) {
47
+ for (const field of fields) {
48
+ let child = target.get(field.name);
49
+ if (!child) {
50
+ child = new Map();
51
+ target.set(field.name, child);
52
+ }
53
+ if (field.selection?.length) {
54
+ this.addFields(child, field.selection);
55
+ }
56
+ }
57
+ }
58
+ printNode(node, indent) {
59
+ if (!node.size) {
60
+ return '';
61
+ }
62
+ const indentString = ' '.repeat(indent);
63
+ const entries = Array.from(node.entries()).sort((left, right) => left[0].localeCompare(right[0]));
64
+ return entries
65
+ .map(([name, child]) => {
66
+ if (!child.size) {
67
+ return `${indentString}${name}`;
68
+ }
69
+ const body = this.printNode(child, indent + 4);
70
+ if (!body) {
71
+ return `${indentString}${name}`;
72
+ }
73
+ return `${indentString}${name} {\n${body}\n${indentString}}`;
74
+ })
75
+ .join('\n');
76
+ }
77
+ }
78
+ class UnraidAdapter extends adapter_core_1.Adapter {
79
+ pollIntervalMs = 60000;
80
+ pollTimer;
81
+ stopRequested = false;
82
+ client;
83
+ rawSelection = new Set();
84
+ effectiveSelection = new Set();
85
+ selectedDefinitions = [];
86
+ staticObjectIds = new Set();
87
+ createdChannels = new Set();
88
+ createdStates = new Set();
89
+ constructor(options = {}) {
90
+ super({
91
+ ...options,
92
+ name: 'unraid',
93
+ });
94
+ this.on('ready', this.onReady.bind(this));
95
+ this.on('unload', this.onUnload.bind(this));
96
+ this.on('stateChange', this.onStateChange.bind(this));
97
+ }
98
+ async onReady() {
99
+ try {
100
+ const settings = this.validateSettings();
101
+ if (!settings) {
102
+ this.log.warn('Adapter is idle because the configuration is incomplete.');
103
+ return;
104
+ }
105
+ this.configureSelection(settings.enabledDomains);
106
+ if (!this.selectedDefinitions.length) {
107
+ this.log.warn('No domains selected. Configure at least one domain in the adapter settings.');
108
+ return;
109
+ }
110
+ this.client = new graphql_client_1.GraphQLClient({
111
+ baseUrl: settings.baseUrl,
112
+ token: settings.apiToken,
113
+ allowSelfSigned: settings.allowSelfSigned,
114
+ });
115
+ this.pollIntervalMs = settings.pollIntervalSeconds * 1000;
116
+ await this.cleanupObjectTree(this.staticObjectIds);
117
+ await this.initializeStaticStates(this.selectedDefinitions);
118
+ await this.pollOnce();
119
+ this.scheduleNextPoll();
120
+ }
121
+ catch (error) {
122
+ this.log.error(`Failed to initialise adapter: ${this.describeError(error)}`);
123
+ }
124
+ }
125
+ configureSelection(enabledDomains) {
126
+ this.rawSelection = new Set(enabledDomains);
127
+ this.effectiveSelection = (0, unraid_domains_1.expandSelection)(this.rawSelection);
128
+ const definitions = [];
129
+ for (const id of this.effectiveSelection) {
130
+ const definition = unraid_domains_1.domainDefinitionById.get(id);
131
+ if (definition) {
132
+ definitions.push(definition);
133
+ }
134
+ }
135
+ this.selectedDefinitions = definitions;
136
+ this.staticObjectIds = this.collectStaticObjectIds(definitions);
137
+ }
138
+ collectStaticObjectIds(definitions) {
139
+ const ids = new Set();
140
+ const addPrefixes = (identifier) => {
141
+ const parts = identifier.split('.');
142
+ for (let index = 1; index <= parts.length; index += 1) {
143
+ ids.add(parts.slice(0, index).join('.'));
144
+ }
145
+ };
146
+ for (const definition of definitions) {
147
+ addPrefixes(definition.id);
148
+ for (const state of definition.states) {
149
+ addPrefixes(state.id);
150
+ }
151
+ }
152
+ return ids;
153
+ }
154
+ validateSettings() {
155
+ const baseUrl = (this.config.baseUrl ?? '').trim();
156
+ const apiToken = (this.config.apiToken ?? '').trim();
157
+ const pollIntervalSecondsRaw = Number(this.config.pollIntervalSeconds ?? 60);
158
+ const pollIntervalSeconds = Number.isFinite(pollIntervalSecondsRaw) && pollIntervalSecondsRaw > 0 ? pollIntervalSecondsRaw : 60;
159
+ const allowSelfSigned = Boolean(this.config.allowSelfSigned);
160
+ const enabledDomainsRaw = Array.isArray(this.config.enabledDomains)
161
+ ? this.config.enabledDomains
162
+ : [...unraid_domains_1.defaultEnabledDomains];
163
+ const knownIds = new Set(unraid_domains_1.allDomainIds);
164
+ const enabledDomains = [];
165
+ for (const id of enabledDomainsRaw) {
166
+ if (knownIds.has(id)) {
167
+ enabledDomains.push(id);
168
+ }
169
+ }
170
+ if (!enabledDomains.length) {
171
+ enabledDomains.push(...unraid_domains_1.defaultEnabledDomains);
172
+ }
173
+ if (!baseUrl) {
174
+ this.log.error('Base URL is not configured.');
175
+ return null;
176
+ }
177
+ if (!apiToken) {
178
+ this.log.error('API token is not configured.');
179
+ return null;
180
+ }
181
+ return {
182
+ baseUrl,
183
+ apiToken,
184
+ pollIntervalSeconds,
185
+ allowSelfSigned,
186
+ enabledDomains,
187
+ };
188
+ }
189
+ scheduleNextPoll() {
190
+ if (this.stopRequested) {
191
+ return;
192
+ }
193
+ this.pollTimer = this.setTimeout(() => {
194
+ void this.pollOnce()
195
+ .catch((error) => {
196
+ this.log.error(`Polling failed: ${this.describeError(error)}`);
197
+ })
198
+ .finally(() => {
199
+ this.scheduleNextPoll();
200
+ });
201
+ }, this.pollIntervalMs);
202
+ }
203
+ async pollOnce() {
204
+ if (!this.client) {
205
+ throw new Error('GraphQL client is not initialised');
206
+ }
207
+ if (!this.selectedDefinitions.length) {
208
+ this.log.debug('Skipping poll because no domains are selected.');
209
+ return;
210
+ }
211
+ const query = this.buildQuery(this.selectedDefinitions);
212
+ if (!query) {
213
+ this.log.warn('No query could be built for the current selection.');
214
+ return;
215
+ }
216
+ try {
217
+ const data = await this.client.query(query);
218
+ this.logGraphQLResponse(data);
219
+ await this.applyData(data);
220
+ }
221
+ catch (error) {
222
+ if (error instanceof graphql_client_1.GraphQLHttpError) {
223
+ throw new Error(`GraphQL HTTP error ${error.status}: ${error.body || error.message}`);
224
+ }
225
+ if (error instanceof graphql_client_1.GraphQLRequestError || error instanceof graphql_client_1.GraphQLResponseError) {
226
+ throw new Error(error.message);
227
+ }
228
+ throw error;
229
+ }
230
+ }
231
+ buildQuery(definitions) {
232
+ const builder = new GraphQLSelectionBuilder();
233
+ for (const definition of definitions) {
234
+ builder.addSelections(definition.selection);
235
+ }
236
+ return builder.build();
237
+ }
238
+ async applyData(data) {
239
+ for (const definition of this.selectedDefinitions) {
240
+ await this.applyDefinition(definition, data);
241
+ }
242
+ }
243
+ async initializeStaticStates(definitions) {
244
+ for (const definition of definitions) {
245
+ for (const mapping of definition.states) {
246
+ await this.writeState(mapping.id, mapping.common, null);
247
+ }
248
+ }
249
+ }
250
+ async applyDefinition(definition, data) {
251
+ for (const mapping of definition.states) {
252
+ const rawValue = this.resolveValue(data, mapping.path);
253
+ const transformed = mapping.transform ? mapping.transform(rawValue) : rawValue;
254
+ await this.writeState(mapping.id, mapping.common, transformed);
255
+ }
256
+ }
257
+ resolveValue(source, path) {
258
+ let current = source;
259
+ for (const segment of path) {
260
+ if (!current || typeof current !== 'object') {
261
+ return null;
262
+ }
263
+ current = current[segment];
264
+ }
265
+ return current === undefined ? null : current;
266
+ }
267
+ async cleanupObjectTree(allowedIds) {
268
+ const objects = await this.getAdapterObjectsAsync();
269
+ for (const fullId of Object.keys(objects)) {
270
+ const relativeId = fullId.startsWith(`${this.namespace}.`)
271
+ ? fullId.slice(this.namespace.length + 1)
272
+ : fullId;
273
+ if (!relativeId) {
274
+ continue;
275
+ }
276
+ if (!this.shouldKeepObject(relativeId, allowedIds)) {
277
+ try {
278
+ await this.delObjectAsync(relativeId, { recursive: true });
279
+ }
280
+ catch (error) {
281
+ this.log.warn(`Failed to remove object ${relativeId}: ${this.describeError(error)}`);
282
+ }
283
+ }
284
+ }
285
+ this.createdChannels.clear();
286
+ this.createdStates.clear();
287
+ }
288
+ shouldKeepObject(objectId, allowedIds) {
289
+ if (allowedIds.has(objectId)) {
290
+ return true;
291
+ }
292
+ const parts = objectId.split('.');
293
+ for (let index = parts.length - 1; index > 0; index -= 1) {
294
+ const candidate = parts.slice(0, index).join('.');
295
+ if (allowedIds.has(candidate)) {
296
+ return true;
297
+ }
298
+ }
299
+ return false;
300
+ }
301
+ async ensureChannelHierarchy(id) {
302
+ const parts = id.split('.');
303
+ for (let index = 1; index < parts.length; index += 1) {
304
+ const channelId = parts.slice(0, index).join('.');
305
+ if (this.createdChannels.has(channelId)) {
306
+ continue;
307
+ }
308
+ const labelKey = unraid_domains_1.domainNodeById.get(channelId)?.label ?? channelId;
309
+ await this.setObjectNotExistsAsync(channelId, {
310
+ type: 'channel',
311
+ common: {
312
+ name: labelKey,
313
+ },
314
+ native: {},
315
+ });
316
+ this.createdChannels.add(channelId);
317
+ }
318
+ }
319
+ async writeState(id, common, value) {
320
+ await this.ensureChannelHierarchy(id);
321
+ if (!this.createdStates.has(id)) {
322
+ await this.setObjectNotExistsAsync(id, {
323
+ type: 'state',
324
+ common: {
325
+ name: id,
326
+ role: common.role,
327
+ type: common.type,
328
+ unit: common.unit,
329
+ read: true,
330
+ write: false,
331
+ },
332
+ native: {},
333
+ });
334
+ this.createdStates.add(id);
335
+ }
336
+ const normalizedValue = value === undefined ? null : value;
337
+ await this.setStateAsync(id, { val: normalizedValue, ack: true });
338
+ }
339
+ logGraphQLResponse(data) {
340
+ try {
341
+ const serialized = JSON.stringify(data);
342
+ const maxLength = 3000;
343
+ const output = serialized.length > maxLength ? `${serialized.slice(0, maxLength)}…` : serialized;
344
+ this.log.debug(`GraphQL response: ${output}`);
345
+ }
346
+ catch (error) {
347
+ this.log.debug(`GraphQL response received but could not be stringified: ${this.describeError(error)}`);
348
+ }
349
+ }
350
+ onStateChange(id, state) {
351
+ if (state) {
352
+ this.log.debug(`State ${id} changed: ${state.val} (ack=${state.ack})`);
353
+ }
354
+ }
355
+ describeError(error) {
356
+ if (error instanceof Error) {
357
+ return error.message;
358
+ }
359
+ return String(error);
360
+ }
361
+ onUnload(callback) {
362
+ this.stopRequested = true;
363
+ try {
364
+ if (this.pollTimer) {
365
+ this.clearTimeout(this.pollTimer);
366
+ }
367
+ if (this.client) {
368
+ void this.client.dispose().catch((error) => {
369
+ this.log.warn(`Failed to dispose GraphQL client: ${this.describeError(error)}`);
370
+ });
371
+ }
372
+ }
373
+ finally {
374
+ callback();
375
+ }
376
+ }
377
+ }
378
+ if (module.parent) {
379
+ module.exports = (options) => new UnraidAdapter(options);
380
+ }
381
+ else {
382
+ (() => new UnraidAdapter())();
383
+ }
384
+ //# sourceMappingURL=main.js.map