Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow customizing quoting behavior of emit (#34) #35

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 66 additions & 16 deletions packages/emitter/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,26 @@ import {

type Quote = '"' | "'";

interface EmitOptions {
/**
* The preferred quote character to use when `emit` encounters a comparison value that needs to be escaped by wrapping
* in quotes. Either `"` (the ASCII double quote character) or `'` (the ASCII single quote character). Defaults to `"`
* (the ASCII double quote character).
*/
preferredQuote?: Quote;
/**
* If `true`, `emit` will override the `preferredQuote` setting on a comparison value-by-comparison value basis if
* doing so would shorten the emitted RSQL. If `false`, `emit` will use the `preferredQuote` as the quote character
* for all comparison values encountered. Defaults to `true`.
*/
optimizeQuotes?: boolean;
}

const DEFAULT_EMIT_OPTIONS: Required<EmitOptions> = {
preferredQuote: '"',
optimizeQuotes: true,
piotr-oles marked this conversation as resolved.
Show resolved Hide resolved
};

const NEEDS_ESCAPING: { [Q in Quote]: RegExp } = {
'"': /"|\\/g,
"'": /'|\\/g,
Expand All @@ -25,12 +45,33 @@ function escapeQuotes(value: string, quote: Quote) {
return value.replace(NEEDS_ESCAPING[quote], "\\$&");
}

function escapeValue(value: string, quote: Quote) {
if (value === "") {
return quote + quote;
const QUOTE_COUNTER: { [Q in Quote]: RegExp } = {
'"': /"/g,
"'": /'/g,
};

function countQuote(value: string, quote: Quote) {
return value.match(QUOTE_COUNTER[quote])?.length ?? 0;
piotr-oles marked this conversation as resolved.
Show resolved Hide resolved
}

function selectQuote(
value: string,
{
preferredQuote = DEFAULT_EMIT_OPTIONS.preferredQuote,
optimizeQuotes = DEFAULT_EMIT_OPTIONS.optimizeQuotes,
}: EmitOptions
) {
if (optimizeQuotes) {
const otherQuote: Quote = preferredQuote === '"' ? "'" : '"';
return countQuote(value, otherQuote) < countQuote(value, preferredQuote) ? otherQuote : preferredQuote;
} else {
return preferredQuote;
}
}

if (ReservedChars.some((reservedChar) => value.includes(reservedChar))) {
function escapeValue(value: string, opts: EmitOptions) {
piotr-oles marked this conversation as resolved.
Show resolved Hide resolved
if (value === "" || ReservedChars.some((reservedChar) => value.includes(reservedChar))) {
const quote = selectQuote(value, opts);
return `${quote}${escapeQuotes(value, quote)}${quote}`;
}

Expand All @@ -41,19 +82,19 @@ function emitSelector(node: SelectorNode) {
return node.selector;
}

function emitValue(node: ValueNode, quote: Quote = '"') {
function emitValue(node: ValueNode, opts: EmitOptions) {
return Array.isArray(node.value)
? `(${node.value.map((value) => escapeValue(value, quote)).join(",")})`
: escapeValue(node.value, quote);
? `(${node.value.map((value) => escapeValue(value, opts)).join(",")})`
: escapeValue(node.value, opts);
}

function emitComparison(node: ComparisonNode) {
return `${emitSelector(node.left)}${node.operator}${emitValue(node.right)}`;
function emitComparison(node: ComparisonNode, opts: EmitOptions) {
return `${emitSelector(node.left)}${node.operator}${emitValue(node.right, opts)}`;
}

function emitLogic(node: LogicNode) {
let left = emit(node.left);
let right = emit(node.right);
function emitLogic(node: LogicNode, opts: EmitOptions) {
let left = emitWithoutOptsValidation(node.left, opts);
let right = emitWithoutOptsValidation(node.right, opts);

// handle operator precedence - as it's only the case for AND operator, we don't need a generic logic for that
if (isLogicOperator(node.operator, AND)) {
Expand All @@ -71,14 +112,23 @@ function emitLogic(node: LogicNode) {
return `${left}${operator}${right}`;
}

function emit(expression: ExpressionNode): string {
function emitWithoutOptsValidation(expression: ExpressionNode, opts: EmitOptions): string {
if (isComparisonNode(expression)) {
return emitComparison(expression);
return emitComparison(expression, opts);
} else if (isLogicNode(expression)) {
return emitLogic(expression);
return emitLogic(expression, opts);
}

throw new TypeError(`The "expression" has to be a valid "ExpressionNode", ${String(expression)} passed.`);
}

export { emit };
function emit(expression: ExpressionNode, opts: EmitOptions = {}) {
if (opts.preferredQuote !== undefined && opts.preferredQuote !== '"' && opts.preferredQuote !== "'") {
throw new TypeError(
`Invalid "preferredQuote" option: ${opts.preferredQuote}. Must be either " (the ASCII double quote character) or ' (the ASCII single quote character).`
);
}
return emitWithoutOptsValidation(expression, opts);
}

export { emit, EmitOptions, Quote };
22 changes: 21 additions & 1 deletion tests/emitter/emit.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ describe("emit", () => {

it.each([
["hi there!", '"hi there!"'],
['hi "there\\!', '"hi \\"there\\\\!"'],
['hi "there\\!', "'hi \"there\\\\!'"],
["Pěkný den!", '"Pěkný den!"'],
["Flynn's *", '"Flynn\'s *"'],
["o)'O'(o", "\"o)'O'(o\""],
Expand All @@ -52,6 +52,26 @@ describe("emit", () => {
expect(parsedAst).toEqual(ast);
});

it.each([
['hi "there!', { preferredQuote: '"' as const, optimizeQuotes: true }, "'hi \"there!'"],
['hi "there!', { preferredQuote: "'" as const, optimizeQuotes: true }, "'hi \"there!'"],
['hi "there!', { preferredQuote: '"' as const, optimizeQuotes: false }, '"hi \\"there!"'],
['hi "there!', { preferredQuote: "'" as const, optimizeQuotes: false }, "'hi \"there!'"],
["hi 'there!", { preferredQuote: '"' as const, optimizeQuotes: true }, '"hi \'there!"'],
["hi 'there!", { preferredQuote: "'" as const, optimizeQuotes: true }, '"hi \'there!"'],
["hi 'there!", { preferredQuote: '"' as const, optimizeQuotes: false }, '"hi \'there!"'],
["hi 'there!", { preferredQuote: "'" as const, optimizeQuotes: false }, "'hi \\'there!'"],
])('honors provided emit options "%p"', (value, opts, escapedValue) => {
const ast = builder.comparison("selector", "==", value);
const emittedRsql = emit(ast, opts);
const expectedRsql = `selector==${escapedValue}`;

expect(emittedRsql).toEqual(expectedRsql);

const parsedAst = parse(emittedRsql);
expect(parsedAst).toEqual(ast);
});

test('Empty string will be emitted as ""', () => {
const rsql = `selector==""`;
const ast = parse(rsql);
Expand Down