32 lines
1.5 KiB
TypeScript
32 lines
1.5 KiB
TypeScript
/** RouterOS VLAN IDs and membership are sets, not row-order-sensitive strings.
|
|
* Never apply this normalization to interface names or arbitrary properties. */
|
|
export function canonicalBridgeVlanValue(field: string, value: unknown): unknown {
|
|
if (["tagged", "untagged"].includes(field)) {
|
|
if (value === undefined || value === "") return ""
|
|
if (typeof value !== "string") throw Error("Invalid VLAN members")
|
|
const names = value.split(",")
|
|
if (names.some(name => !name || name.trim() !== name) || new Set(names).size !== names.length) throw Error("Ambiguous VLAN members")
|
|
return names.sort().join(",")
|
|
}
|
|
if (field !== "vlan-ids") return value
|
|
if (typeof value !== "string" || !value.length) throw Error("Invalid VLAN IDs")
|
|
const ids = new Set<number>()
|
|
for (const part of value.split(",")) {
|
|
if (!/^[1-9]\d{0,3}(?:-[1-9]\d{0,3})?$/.test(part)) throw Error("Invalid VLAN IDs")
|
|
const [start, rawEnd] = part.split("-").map(Number), end = rawEnd ?? start
|
|
if (start < 1 || end > 4094 || end < start) throw Error("Invalid VLAN IDs")
|
|
for (let id = start; id <= end; id++) {
|
|
if (ids.has(id)) throw Error("Overlapping VLAN IDs")
|
|
ids.add(id)
|
|
}
|
|
}
|
|
const sorted = [...ids].sort((a, b) => a - b), ranges: string[] = []
|
|
for (let index = 0; index < sorted.length;) {
|
|
const start = sorted[index]
|
|
let end = start
|
|
while (++index < sorted.length && sorted[index] === end + 1) end = sorted[index]
|
|
ranges.push(start === end ? String(start) : `${start}-${end}`)
|
|
}
|
|
return ranges.join(",")
|
|
}
|