diff --git a/src/builder/index.ts b/src/builder/index.ts index ef0ae23..05f0bcd 100644 --- a/src/builder/index.ts +++ b/src/builder/index.ts @@ -22,7 +22,11 @@ function isQuoted(val: string): boolean { } function needsQuotes(val: string): boolean { - return !isQuoted(val) && !!val.match(/\[|]|{|}|\|\(|\)|,|;|\?|\*|=|!|@/)?.length; + if (isQuoted(val)) { + return false; + } + // the parser trims unquoted values, and reads a leading `'` or `"` as an opening quote + return val !== val.trim() || /^['"]/.test(val) || !!val.match(/\[|]|{|}|\|\(|\)|,|;|\?|\*|=|!|@/)?.length; } function encodeTuple(key: string, value: ValidDataTypes): [string, string] { @@ -44,6 +48,7 @@ function encodeTuple(key: string, value: ValidDataTypes): [string, string] { export function build(data: Record): string { return Object.entries(data).map(([key, value]) => { - return encodeTuple(key.trim(), value).join('='); + // `=` ends a key, so a literal `=` in a key is escaped as `==` + return encodeTuple(key.trim().replace(/=/g, '=='), value).join('='); }).join(';'); } diff --git a/src/parser/connection-string-parser.ts b/src/parser/connection-string-parser.ts index 669d65f..922403d 100644 --- a/src/parser/connection-string-parser.ts +++ b/src/parser/connection-string-parser.ts @@ -63,6 +63,11 @@ export default function connectionStringParser(connectionString: string, parserC return config().terminator === char; } + function isSkippable(char: string): boolean { + // whitespace before a key or value, or an extra `;` before a key + return !char.trim() || (collectionMode === CollectionMode.key && char === parserConfig.value.terminator); + } + function isStartQuote(char: string): boolean { return Object.keys(config().quotes).some((val: string) => char === val); } @@ -96,17 +101,16 @@ export default function connectionStringParser(connectionString: string, parserC while (pointer < connectionString.length) { const current = connectionString.charAt(pointer); if (!finished) { - if (!started) { - if (current.trim()) { - start(); - if (isStartQuote(current)) { - quoted = true; - quote = current; - } else { - push(current); - } - } + if (!started && isSkippable(current)) { + // nothing to collect yet + } else if (!started && isStartQuote(current)) { + start(); + quoted = true; + quote = current; } else { + // the first character can also be a terminator, for example in an + // empty value (`Key=;`) or in a key that starts with `==` + start(); if (quoted && isEndQuote(current)) { const next = connectionString.charAt(pointer + 1); if (current === next) { @@ -117,9 +121,12 @@ export default function connectionStringParser(connectionString: string, parserC } } else if (!quoted && isTerminator(current)) { const next = connectionString.charAt(pointer + 1); - if (current === next) { + // `==` is an escaped `=` in a key; a `;` always ends an unquoted value + if (collectionMode === CollectionMode.key && current === next) { push(current); pointer++; + } else if (collectionMode === CollectionMode.key && buffer === '') { + throw new Error('Malformed connection string'); } else { collect(); } diff --git a/test/builder/builder.test.ts b/test/builder/builder.test.ts index b637c81..5451127 100644 --- a/test/builder/builder.test.ts +++ b/test/builder/builder.test.ts @@ -1,8 +1,53 @@ import * as assert from 'node:assert'; import { describe, it } from 'node:test'; -import { build } from '../../src'; +import { build, parse } from '../../src'; describe('builder', () => { + it('quotes values with leading or trailing whitespace', () => { + const built = build({ + leading: ' value', + trailing: 'value ', + both: ' value ', + tab: '\tvalue', + newline: 'value\n', + inner: 'a value', + }); + assert.equal(built, 'leading={ value};trailing={value };both={ value };tab={\tvalue};newline={value\n};inner=a value'); + }); + + it('quotes values that start with a quote character', () => { + const built = build({ + single: '\'value', + double: '"value"', + inner: 'val\'ue"', + }); + assert.equal(built, 'single={\'value};double={"value"};inner=val\'ue"'); + }); + + it('builds values that parse back to the same value', () => { + const values = [' secret ', '\'abc', '"x"', '\'', '"', ' ', '\t', 'a value', 'val\'ue"', '{a}}b', 'a;b', 'a=b']; + values.forEach((value) => { + assert.equal(parse(build({ key: value })).get('key'), value, `round trip of ${JSON.stringify(value)}`); + }); + }); + + it('escapes `=` in keys', () => { + const built = build({ + 'a=b': '1', + '=start': '2', + 'end=': '3', + 'a==b': '4', + }); + assert.equal(built, 'a==b=1;==start=2;end===3;a====b=4'); + }); + + it('builds keys that parse back to the same key', () => { + const keys = ['a=b', '=start', 'end=', 'a==b', '=', 'a;b']; + keys.forEach((key) => { + assert.deepEqual([...parse(build({ [key]: 'value' })).entries()], [[key, 'value']], `round trip of ${JSON.stringify(key)}`); + }); + }); + it('builds a connection string', () => { const built = build({ strkey: 'value', diff --git a/test/parser/connection-string.test.ts b/test/parser/connection-string.test.ts index 8c05c03..0f284ff 100644 --- a/test/parser/connection-string.test.ts +++ b/test/parser/connection-string.test.ts @@ -40,5 +40,17 @@ describe('parser', () => { message: 'Connection string terminated unexpectedly', }); }); + + it('throws on an empty keyword', () => { + assert.throws(() => parse('=value'), { + message: 'Malformed connection string', + }); + }); + + it('throws on an empty keyword after another pair', () => { + assert.throws(() => parse('key=value; =other'), { + message: 'Malformed connection string', + }); + }); }); }); diff --git a/test/parser/fixture/connection-strings.json b/test/parser/fixture/connection-strings.json index abc6ac1..ae9df49 100644 --- a/test/parser/fixture/connection-strings.json +++ b/test/parser/fixture/connection-strings.json @@ -13,6 +13,52 @@ "keyword": "Value" } }, + { + "name": "parses a single value with repeated trailing semicolons", + "connection_string": "Keyword=Value;;", + "expected": { + "keyword": "Value" + } + }, + { + "name": "skips repeated semicolons between pairs", + "connection_string": "Server=h;;Database=d;;;User Id=u", + "expected": { + "server": "h", + "database": "d", + "user id": "u" + } + }, + { + "name": "skips leading semicolons", + "connection_string": ";; Server=h", + "expected": { + "server": "h" + } + }, + { + "name": "skips semicolons separated by whitespace", + "connection_string": "Server=h; ; Database=d", + "expected": { + "server": "h", + "database": "d" + } + }, + { + "name": "skips repeated semicolons after a quoted value", + "connection_string": "Password='p;w';;Server=h", + "expected": { + "password": "p;w", + "server": "h" + } + }, + { + "name": "parses keywords that contain `;`", + "connection_string": "Key;word=Value", + "expected": { + "key;word": "Value" + } + }, { "name": "parses keywords that contain `=`", "connection_string": "Key==word=Value", @@ -20,6 +66,62 @@ "key=word": "Value" } }, + { + "name": "parses keywords that start with `=`", + "connection_string": "==Key=Value", + "expected": { + "=key": "Value" + } + }, + { + "name": "parses keywords that end with `=`", + "connection_string": "Key===Value", + "expected": { + "key=": "Value" + } + }, + { + "name": "parses empty values", + "connection_string": "TrustServerCertificate=;Encrypt=true;Server=h", + "expected": { + "trustservercertificate": "", + "encrypt": "true", + "server": "h" + } + }, + { + "name": "parses empty values with whitespace", + "connection_string": "Key= ;Other=Value", + "expected": { + "key": "", + "other": "Value" + } + }, + { + "name": "parses an empty connection string", + "connection_string": "", + "expected": {} + }, + { + "name": "parses a connection string of only whitespace and semicolons", + "connection_string": " ;; ", + "expected": {} + }, + { + "name": "parses an empty value with a trailing semicolon", + "connection_string": "Key=;", + "expected": { + "key": "" + } + }, + { + "name": "parses values that start with `=`", + "connection_string": "Key= =Value;Other=x", + "expected": { + "key": "=Value", + "other": "x" + } + }, { "name": "parses values to contain `=`", "connection_string": "Keyword=Val=ue",