Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
44 changes: 44 additions & 0 deletions packages/search/src/ast.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* The query AST — the canonical representation a search compiles to. Everything
* downstream (optimizer, SQL builder) consumes this; nothing else parses text.
*/

/** Comparison operator for a metatag value. */
export type CompareOp = "eq" | "gt" | "gte" | "lt" | "lte" | "range";

/** Boolean AND of its children (the implicit top-level combinator). */
export interface AndNode {
type: "and";
children: QueryNode[];
}

/** Boolean OR of its children (formed from `~`-prefixed terms). */
export interface OrNode {
type: "or";
children: QueryNode[];
}

/** Negation of a single child (from a `-`-prefixed term). */
export interface NotNode {
type: "not";
child: QueryNode;
}

/** A bare tag match (may contain `*` wildcards). */
export interface TagNode {
type: "tag";
name: string;
}

/**
* A metatag filter, e.g. `rating:safe`, `score:>10`, `width:100..200`. For
* `op: "range"` the `value` is the raw `lo..hi` string.
*/
export interface MetatagNode {
type: "metatag";
key: string;
op: CompareOp;
value: string;
}

export type QueryNode = AndNode | OrNode | NotNode | TagNode | MetatagNode;
18 changes: 16 additions & 2 deletions packages/search/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,21 @@
* `@bunbooru/search` — the search engine: lexer → parser → AST → optimizer → SQL builder.
*
* Pure and self-contained: no HTTP, no Drizzle, no database. The AST is the
* canonical representation; everything downstream consumes it. The pipeline
* implementation lands in a later PR.
* canonical representation; everything downstream consumes it. The optimizer and
* SQL builder land once the DB exists.
*/
export const SEARCH_PACKAGE = "@bunbooru/search" as const;

export { tokenize } from "./token";
export type { Prefix, Token, TagToken, MetatagToken } from "./token";

export { parse } from "./parser";
export type {
AndNode,
CompareOp,
MetatagNode,
NotNode,
OrNode,
QueryNode,
TagNode,
} from "./ast";
65 changes: 65 additions & 0 deletions packages/search/src/parser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import type { AndNode, CompareOp, MetatagNode, QueryNode } from "./ast";
import { type Token, tokenize } from "./token";

/** Comparison symbols, longest first so `>=` beats `>`. */
const OPERATORS: ReadonlyArray<readonly [string, CompareOp]> = [
[">=", "gte"],
["<=", "lte"],
[">", "gt"],
["<", "lt"],
];

/**
* A range is `lo..hi` separated by exactly `..`, where neither side contains a
* scheme/path character — so URL values like `https://a..b` are NOT ranges.
*/
const RANGE_RE = /^[^:/]*\.\.[^:/]*$/;

/**
* Parse a booru query string into its AST. Semantics:
* - whitespace-separated terms are AND'd (the implicit top level);
* - `-term` negates a term;
* - `~term ~term` form a single OR group, AND'd with the other terms.
*/
export function parse(query: string): AndNode {
const andChildren: QueryNode[] = [];
const orChildren: QueryNode[] = [];

for (const token of tokenize(query)) {
const node = toNode(token);
if (token.prefix === "or") {
orChildren.push(node);
} else if (token.prefix === "not") {
andChildren.push({ type: "not", child: node });
} else {
andChildren.push(node);
}
}

if (orChildren.length === 1) {
const [only] = orChildren;
if (only) andChildren.push(only); // a lone ~term is just that term
} else if (orChildren.length > 1) {
andChildren.push({ type: "or", children: orChildren });
}

return { type: "and", children: andChildren };
}

function toNode(token: Token): QueryNode {
if (token.kind === "tag") return { type: "tag", name: token.name };
return parseMetatag(token.key, token.value);
}

function parseMetatag(key: string, raw: string): MetatagNode {
// Operators first, so an operator beats a range-looking value (e.g. >10..20).
for (const [symbol, op] of OPERATORS) {
if (raw.startsWith(symbol)) {
return { type: "metatag", key, op, value: raw.slice(symbol.length) };
}
}
if (RANGE_RE.test(raw)) {
return { type: "metatag", key, op: "range", value: raw };
}
return { type: "metatag", key, op: "eq", value: raw };
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
60 changes: 60 additions & 0 deletions packages/search/src/token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/**
* Lexer — turns a query string into a flat list of classified terms. Each
* whitespace-separated term is a tag or a metatag, carrying its modifier prefix.
*/

/** Term modifier prefix: plain, negated (`-`), or or-group member (`~`). */
export type Prefix = "none" | "not" | "or";

export interface TagToken {
kind: "tag";
prefix: Prefix;
name: string;
}

export interface MetatagToken {
kind: "metatag";
prefix: Prefix;
key: string;
value: string;
}

export type Token = TagToken | MetatagToken;

/** Tokenize a query string into classified terms (empty/blank terms dropped). */
export function tokenize(query: string): Token[] {
const tokens: Token[] = [];
for (const term of query.split(/\s+/)) {
const token = classify(term);
if (token) tokens.push(token);
}
return tokens;
}

function classify(term: string): Token | null {
let prefix: Prefix = "none";
let rest = term;

if (rest.startsWith("-")) {
prefix = "not";
rest = rest.slice(1);
} else if (rest.startsWith("~")) {
prefix = "or";
rest = rest.slice(1);
}

if (rest.length === 0) return null; // bare "", "-", or "~"

// A metatag has a non-empty key before the first colon.
const colon = rest.indexOf(":");
if (colon > 0) {
return {
kind: "metatag",
prefix,
key: rest.slice(0, colon).toLowerCase(),
value: rest.slice(colon + 1),
};
}

return { kind: "tag", prefix, name: rest.toLowerCase() };
}
119 changes: 119 additions & 0 deletions packages/search/test/parser.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import { describe, expect, it } from "bun:test";

import { parse } from "../src/parser";

describe("parse", () => {
it("empty query → empty AND", () => {
expect(parse("")).toEqual({ type: "and", children: [] });
});

it("single tag → AND[tag]", () => {
expect(parse("1girl")).toEqual({
type: "and",
children: [{ type: "tag", name: "1girl" }],
});
});

it("implicitly ANDs multiple tags", () => {
expect(parse("1girl solo")).toEqual({
type: "and",
children: [
{ type: "tag", name: "1girl" },
{ type: "tag", name: "solo" },
],
});
});

it("wraps a negated term in NOT", () => {
expect(parse("1girl -monochrome")).toEqual({
type: "and",
children: [
{ type: "tag", name: "1girl" },
{ type: "not", child: { type: "tag", name: "monochrome" } },
],
});
});

it("combines ~ terms into one OR group, AND'd with the rest", () => {
expect(parse("1girl ~blue_eyes ~green_eyes")).toEqual({
type: "and",
children: [
{ type: "tag", name: "1girl" },
{
type: "or",
children: [
{ type: "tag", name: "blue_eyes" },
{ type: "tag", name: "green_eyes" },
],
},
],
});
});

it("treats a lone ~term as just that term (no OR wrapper)", () => {
expect(parse("~solo")).toEqual({
type: "and",
children: [{ type: "tag", name: "solo" }],
});
});

it("parses an equality metatag", () => {
expect(parse("rating:safe")).toEqual({
type: "and",
children: [{ type: "metatag", key: "rating", op: "eq", value: "safe" }],
});
});

it("parses comparison metatags (longest operator first)", () => {
const op = (q: string) => parse(q).children[0];
expect(op("score:>10")).toEqual({ type: "metatag", key: "score", op: "gt", value: "10" });
expect(op("score:>=10")).toEqual({ type: "metatag", key: "score", op: "gte", value: "10" });
expect(op("score:<10")).toEqual({ type: "metatag", key: "score", op: "lt", value: "10" });
expect(op("score:<=10")).toEqual({ type: "metatag", key: "score", op: "lte", value: "10" });
});

it("parses a range metatag", () => {
expect(parse("width:100..200").children[0]).toEqual({
type: "metatag",
key: "width",
op: "range",
value: "100..200",
});
});

it("does not treat a URL value (with ..) as a range", () => {
expect(parse("source:https://example.com/a..b").children[0]).toEqual({
type: "metatag",
key: "source",
op: "eq",
value: "https://example.com/a..b",
});
});

it("lets an operator win over a range-looking value", () => {
expect(parse("score:>10..20").children[0]).toEqual({
type: "metatag",
key: "score",
op: "gt",
value: "10..20",
});
});

it("combines tags, OR, NOT and metatags (OR group appended last)", () => {
expect(parse("1girl ~blue_eyes ~green_eyes -monochrome rating:safe")).toEqual({
type: "and",
children: [
{ type: "tag", name: "1girl" },
{ type: "not", child: { type: "tag", name: "monochrome" } },
{ type: "metatag", key: "rating", op: "eq", value: "safe" },
{
type: "or",
children: [
{ type: "tag", name: "blue_eyes" },
{ type: "tag", name: "green_eyes" },
],
},
],
});
});
});
66 changes: 66 additions & 0 deletions packages/search/test/token.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { describe, expect, it } from "bun:test";

import { tokenize } from "../src/token";

describe("tokenize", () => {
it("splits whitespace-separated tags", () => {
expect(tokenize("1girl solo")).toEqual([
{ kind: "tag", prefix: "none", name: "1girl" },
{ kind: "tag", prefix: "none", name: "solo" },
]);
});

it("lowercases tag names", () => {
expect(tokenize("BlueEyes")).toEqual([{ kind: "tag", prefix: "none", name: "blueeyes" }]);
});

it("marks negation with the - prefix", () => {
expect(tokenize("-monochrome")).toEqual([
{ kind: "tag", prefix: "not", name: "monochrome" },
]);
});

it("marks or-group members with the ~ prefix", () => {
expect(tokenize("~a ~b")).toEqual([
{ kind: "tag", prefix: "or", name: "a" },
{ kind: "tag", prefix: "or", name: "b" },
]);
});

it("parses metatags into key/value with a lowercased key", () => {
expect(tokenize("Rating:safe")).toEqual([
{ kind: "metatag", prefix: "none", key: "rating", value: "safe" },
]);
});

it("keeps operator and range characters in the metatag value", () => {
expect(tokenize("score:>10")).toEqual([
{ kind: "metatag", prefix: "none", key: "score", value: ">10" },
]);
expect(tokenize("width:100..200")).toEqual([
{ kind: "metatag", prefix: "none", key: "width", value: "100..200" },
]);
});

it("carries the prefix onto metatags", () => {
expect(tokenize("-rating:explicit")).toEqual([
{ kind: "metatag", prefix: "not", key: "rating", value: "explicit" },
]);
});

it("ignores surrounding and repeated whitespace", () => {
expect(tokenize(" 1girl solo ")).toEqual([
{ kind: "tag", prefix: "none", name: "1girl" },
{ kind: "tag", prefix: "none", name: "solo" },
]);
});

it("returns nothing for blank input", () => {
expect(tokenize("")).toEqual([]);
expect(tokenize(" ")).toEqual([]);
});

it("drops a bare - or ~", () => {
expect(tokenize("- ~ 1girl")).toEqual([{ kind: "tag", prefix: "none", name: "1girl" }]);
});
});
Loading