UNPKG

@homebridge-plugins/homebridge-resideo

Version:

The Resideo plugin allows you to access your Resideo device(s) from HomeKit.

109 lines 4.04 kB
import { Buffer } from 'node:buffer'; import { request as httpRequest } from 'node:http'; import { request as httpsRequest } from 'node:https'; export class NativeHttpClient { defaults; constructor(defaults) { this.defaults = defaults; } get(url, config = {}) { return this.request('GET', url, config); } post(url, data, config = {}) { return this.request('POST', url, { ...config, data }); } put(url, data, config = {}) { return this.request('PUT', url, { ...config, data }); } async request(method, url, config) { const merged = this.mergeConfig(config); const target = new URL(url); if (merged.params) { for (const [key, value] of Object.entries(merged.params)) { if (value !== undefined && value !== null) { target.searchParams.set(key, String(value)); } } } const headers = { ...merged.headers }; if (merged.auth) { const basic = Buffer.from(`${merged.auth.username}:${merged.auth.password}`).toString('base64'); headers.Authorization = `Basic ${basic}`; } let body; if (merged.data !== undefined) { if (typeof merged.data === 'string') { body = merged.data; } else { body = JSON.stringify(merged.data); } if (!headers['Content-Type']) { headers['Content-Type'] = 'application/json'; } headers['Content-Length'] = String(Buffer.byteLength(body)); } return await new Promise((resolve, reject) => { const req = (target.protocol === 'https:' ? httpsRequest : httpRequest)(target, { method, headers, }, (res) => { const chunks = []; res.on('data', (chunk) => { chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); }); res.on('end', () => { const raw = Buffer.concat(chunks).toString('utf8'); const responseType = merged.responseType ?? 'json'; const hasBody = raw.length > 0; const status = res.statusCode ?? 0; try { const parsed = responseType === 'json' ? (hasBody ? JSON.parse(raw) : {}) : raw; if (status >= 400) { const error = new Error(`Request failed with status code ${status}`); error.status = status; error.response = parsed; reject(error); return; } resolve({ data: parsed, status, headers: res.headers, }); } catch { reject(new Error(`Failed to parse response from ${target.toString()}`)); } }); }); req.on('error', (error) => { reject(error); }); if (body) { req.write(body); } req.end(); }); } mergeConfig(config) { const defaults = this.defaults?.() ?? {}; return { ...defaults, ...config, headers: { ...(defaults.headers ?? {}), ...(config.headers ?? {}), }, params: { ...(defaults.params ?? {}), ...(config.params ?? {}), }, auth: config.auth ?? defaults.auth, responseType: config.responseType ?? defaults.responseType, }; } } //# sourceMappingURL=http-client.js.map