feat: add extractBalancedObject utility and tests; enhance dashboard parsing

This commit is contained in:
2025-11-15 14:46:44 +01:00
parent e3596f657b
commit 6be7763698
4 changed files with 226 additions and 46 deletions

View File

@@ -0,0 +1,47 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { extractBalancedObject } from '../src/util/core/Utils'
const wrap = (before: string, obj: string, after = ';') => `${before}${obj}${after}`
test('extractBalancedObject extracts simple object after string anchor', () => {
const obj = '{"a":1,"b":2}'
const text = wrap('var dashboard = ', obj)
const out = extractBalancedObject(text, 'var dashboard = ')
assert.equal(out, obj)
})
test('extractBalancedObject extracts with regex anchor and whitespace', () => {
const obj = '{"x": {"y": 3}}'
const text = wrap('dashboard = ', obj)
const out = extractBalancedObject(text, /dashboard\s*=\s*/)
assert.equal(out, obj)
})
test('extractBalancedObject handles nested braces and strings safely', () => {
const obj = '{"t":"{ not a brace }","n": {"inner": {"v": "} in string"}}}'
const text = wrap('var dashboard = ', obj)
const out = extractBalancedObject(text, 'var dashboard = ')
assert.equal(out, obj)
})
test('extractBalancedObject handles escaped quotes inside strings', () => {
const obj = '{"s":"\\"quoted\\" braces { }","k":1}'
const text = wrap('dashboard = ', obj)
const out = extractBalancedObject(text, 'dashboard = ')
assert.equal(out, obj)
})
test('extractBalancedObject returns null when anchor missing', () => {
const text = 'no object here'
const out = extractBalancedObject(text, 'var dashboard = ')
assert.equal(out, null)
})
test('extractBalancedObject returns null on imbalanced braces or limit', () => {
const start = 'var dashboard = '
const text = `${start}{"a": {"b": 1}` // missing final brace
const out = extractBalancedObject(text, start)
assert.equal(out, null)
})

27
tests/sanitize.test.ts Normal file
View File

@@ -0,0 +1,27 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { replaceUntilStable } from '../src/util/core/Utils'
test('remove HTML comments with repeated replacement', () => {
const input = '<!<!--- comment --->>'
const out = replaceUntilStable(input, /<!--|--!?>/g, '')
assert.equal(out.includes('<!--'), false)
assert.equal(out.includes('-->'), false)
// Remaining string should not contain full HTML comment delimiters
assert.equal(/<!--|-->/g.test(out), false)
})
test('path traversal: repeated removal of ../ sequences', () => {
const input = '/./.././'
const out = replaceUntilStable(input, /\.\.\//, '')
assert.equal(out.includes('..'), false)
})
test('enforces global flag if missing', () => {
const input = 'a<script>b</script>c<script>d</script>'
// remove tag brackets to neutralize tags (illustrative only)
const out = replaceUntilStable(input, /<|>/, '')
assert.equal(out.includes('<'), false)
assert.equal(out.includes('>'), false)
})