Parse cddl2ts output into { interfaces, enums, aliases }.
(ts)
| 151 | |
| 152 | /** Parse cddl2ts output into { interfaces, enums, aliases }. */ |
| 153 | function parseCddl2ts(ts) { |
| 154 | const interfaces = {} |
| 155 | for (const m of ts.matchAll(/export interface (\w+)\s*\{/g)) { |
| 156 | const { body } = balancedBody(ts, m.index + m[0].length) |
| 157 | interfaces[m[1]] = topLevelFields(body) |
| 158 | } |
| 159 | const aliases = {} // name → raw RHS expression (for union/intersection types) |
| 160 | for (const m of ts.matchAll(/export type (\w+) = /g)) { |
| 161 | let i = m.index + m[0].length |
| 162 | let depth = 0 |
| 163 | const start = i |
| 164 | while (i < ts.length && !(depth === 0 && ts[i] === ';')) { |
| 165 | if (OPEN.includes(ts[i])) depth++ |
| 166 | else if (CLOSE.includes(ts[i])) depth-- |
| 167 | i++ |
| 168 | } |
| 169 | aliases[m[1]] = ts.slice(start, i) |
| 170 | } |
| 171 | // Enums are the aliases whose RHS is a pure string-literal union. Derived from |
| 172 | // the parsed aliases (linear) rather than a nested-quantifier regex. |
| 173 | const enums = {} |
| 174 | for (const [name, expr] of Object.entries(aliases)) { |
| 175 | const parts = splitTopLevel(expr, '|').map((p) => p.trim()) |
| 176 | if (parts.length && parts.every((p) => /^"[^"]*"$/.test(p))) enums[name] = new Set(parts.map((p) => p.slice(1, -1))) |
| 177 | } |
| 178 | return { interfaces, enums, aliases } |
| 179 | } |
| 180 | |
| 181 | /** Split `expr` on `sep` at bracket depth 0. */ |
| 182 | function splitTopLevel(expr, sep) { |
no test coverage detected