import { createHash } from 'node:crypto' import type { Configuration } from '#domain/configuration/configuration' /** * Computes a 12-character hex content hash of a Configuration's desired state. * The hash is based on the sorted desiredParameters and firmwareTarget. */ export function computeContentHash(config: Configuration): string { const payload = JSON.stringify({ desiredParameters: config.desiredParameters .slice() .sort((a, b) => a.name.localeCompare(b.name)), firmwareTarget: config.firmwareTarget || null, }) return createHash('sha256').update(payload).digest('hex').substring(0, 12) } /** * Builds the ProvisioningCode string for a Configuration. * Format: `(v)-` * Example: `BM632w-standard(v1.0.1)-a1b2c3d4e5f6` */ export function buildProvisioningCode(config: Configuration): string { const hash = computeContentHash(config) return `${config.identifier}(v${config.version})-${hash}` } /** * Parses an existing ProvisioningCode string. * Returns null if the format is invalid. */ export function parseProvisioningCode( code: string ): { identifier: string; version: string; hash: string } | null { const match = code.match(/^(.+)\(v(.+)\)-([a-f0-9]{12})$/) if (!match) return null return { identifier: match[1], version: match[2], hash: match[3] } }