### Real-World E-commerce Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md An example demonstrating how to extract book information with fallbacks and formatting. ```javascript // Main title with fallback '@css:.book-title@text || @css:.title@text || @text:Untitled' ``` ```javascript // Price with extraction '@css:.price@text##¥?([\d.]+)' ``` ```javascript // Rating with formula '@css:.rating@text || @js:0' ``` ```javascript // Description with length limit '@css:.description@text && @text: ... (Read more)' ``` -------------------------------- ### Text Selector Examples Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md Examples of using the text selector for fixed or constant text. ```javascript '@text:Default Title' // Returns "Default Title" '@text: - ' // Returns " - " (with spaces) '@text:\n' // Returns newline (escaped) '@text:"quoted"' // Returns including quotes ``` -------------------------------- ### Regular Expression Selector Examples Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md Examples of using regular expressions to match and extract text. ```javascript '@regex:\d+' // First number '@regex:\d+\.\d+' // Decimal number '@regex:[a-z]+@example\.com' // Email address '@regex:ISBN:([\d-]+)' // Capture ISBN after "ISBN:" '@regex:/\d+/g' // All numbers (global) '@regex:/price: \$(\d+)/i' // Case-insensitive price ``` -------------------------------- ### Installation & Import Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md How to install the package and import its components in different module systems. ```javascript // npm, pnpm, yarn npm install book-source-rule-parser // TypeScript/ESM import { RuleEngine, createRuleEngine, parseRule } from 'book-source-rule-parser'; // CommonJS const { RuleEngine } = require('book-source-rule-parser'); // Default export import createParser from 'book-source-rule-parser'; const engine = createParser(); ``` -------------------------------- ### Multi-Field Extraction Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md An example showing how to extract multiple fields in one batch call using a rules object. ```javascript const rules = { title: '@css:h1.title@text', author: '@css:.author@text || @text:Anonymous', price: '@css:.sale-price@text##\d+\.\d+', rating: '@css:.stars@text || @text:N/A', category: '@json:$.category || @text:Uncategorized' }; const results = await engine.parseBatch(html, rules); ``` -------------------------------- ### XPath Selector Examples Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md Examples of using XPath selectors to extract data from HTML elements. ```javascript '@xpath://h1/text()' // First h1 text '@xpath://div[@class="title"]//text()' // Text inside div.title '@xpath://a/@href' // href of all links '@xpath:(//p)[1]/text()' // Text of first p '@xpath://span[contains(text(), "Price")]' // Spans containing "Price" ``` -------------------------------- ### Nested/Complex Extraction Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md An example demonstrating how to extract data from nested JSON structures. ```javascript const rules = { books: [ { title: '@json:$.books[*].title', authors: '@json:$.books[*].authors[*]', price: '@json:$.books[*].price##\d+' } ] }; ``` -------------------------------- ### Example Usage Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/factory-functions.md An example demonstrating how to use the createBookSourceParser function. ```javascript import createBookSourceParser from 'book-source-rule-parser'; const engine = createBookSourceParser({ timeout: 8000 }); const result = await engine.parse(html, '@css:.title@text'); ``` -------------------------------- ### JavaScript Selector Examples Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md Examples of using JavaScript expressions to transform or extract data. ```javascript '@js:source.length' // Length of source '@js:source.toUpperCase()' // Uppercase the text '@js:source.match(/\d+/)[0]' // Extract first number '@js:source.split(",").length' // Count comma-separated items '@js:JSON.parse(source).name' // Parse JSON property '@js:source.slice(0, 50)' // First 50 characters ``` -------------------------------- ### CSS Selector Examples Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md Examples of using CSS selectors to extract data from HTML elements. ```javascript '@css:.title@text' // Text of element with class "title" '@css:#book-id@html' // HTML inside element with id "book-id" '@css:img.cover@src' // src attribute of img with class "cover" '@css:div.item > h2@text' // Text of h2 inside div.item '@css:p:nth-child(2)@text' // Text of second p element ``` -------------------------------- ### Empty Data Handling Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md Shows how to use fallbacks to handle potentially empty data (null, undefined, empty string, array, or object). ```javascript '@css:.missing@text || @text:N/A' ``` -------------------------------- ### Fallback Operator Examples Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md Examples demonstrating the use of the fallback operator (||) to try multiple selectors. ```javascript '@css:.title@text || @css:.name@text || @text:Unknown' // Try .title, if empty try .name, if empty return "Unknown" '@json:$.book.title || @json:$.title || @text:No Title' // Try nested path, then simpler path, then default '@css:.price@text || @regex:\d+\.\d+ || @text:TBD' // Try CSS, then regex on same source, then default ``` -------------------------------- ### Import Patterns - Get Everything Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/module-exports.md Example of importing all modules from the 'book-source-rule-parser' package. ```javascript import * as Parser from 'book-source-rule-parser'; const engine = new Parser.RuleEngine(); ``` -------------------------------- ### Complete Workflow Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md A comprehensive example demonstrating the typical workflow of using Legado Rule to parse HTML. ```javascript import { RuleEngine } from 'book-source-rule-parser'; // 1. Create engine const engine = new RuleEngine({ timeout: 5000, enableCache: true }); // 2. Define rules const rules = { title: '@css:.book-title@text', author: '@css:.author@text || @text:Anonymous', price: '@css:.price@text##\d+\.\d+', rating: '@css:.stars@text || @text:N/A' }; // 3. Parse HTML const html = /* fetched HTML */; const book = await engine.parseBatch(html, rules); // 4. Handle results if (book.title.success) { console.log(`${book.title.data} by ${book.author.data}`); console.log(`Price: $${book.price.data}`); console.log(`Rating: ${book.rating.data}`); } else { console.error('Failed to parse:', book.title.error); } // 5. Clear cache when done (optional) engine.clearCache(); ``` -------------------------------- ### Running Examples and Tests Source: https://github.com/legadoteam/legado-rule/blob/main/README.md Provides commands for running various examples and tests for the project. ```bash # 运行基础示例 pnpm run example:basic # 电商/小说/JSON 示例 pnpm run example:ecommerce pnpm run example:novel pnpm run example:json # 运行全部示例 pnpm run examples # 单元测试与覆盖率 pnpm test pnpm run coverage ``` -------------------------------- ### Concatenation Operator Examples Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md Examples demonstrating how to combine results from multiple selectors into a single string using the '&&' operator. ```javascript @css:.title@text && @text: - && @css:.author@text ``` ```javascript @text:【 && @css:.category@text && @text:】 ``` ```javascript @css:.first@text && @text: && @css:.last@text ``` -------------------------------- ### Graceful Fallbacks Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md Demonstrates providing fallback values for optional fields to ensure data availability. ```javascript // Good: Has default '@css:.thumbnail@src || @text:/images/no-cover.jpg' ``` ```javascript // Risky: May return null '@css:.thumbnail@src' ``` -------------------------------- ### Structured Data Extraction Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md An example of extracting structured data with formatting, combining text and CSS selectors. ```javascript '@text:📖 && @css:.title@text && @text: by && @css:.author@text && @text: - ¥ && @css:.price@text##\d+\.\d+' // Result: "📖 Title by Author - ¥29.99" ``` -------------------------------- ### API Usage Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md Demonstrates how to use the RuleEngine client-side to parse HTML. ```javascript const result = await engine.parse(htmlString, rule); // Process result locally, no network involved ``` -------------------------------- ### JSON Selector Examples Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md Examples of using JSON selectors (JSONPath) to extract data from JSON objects. ```javascript '@json:$.book.title' // Root book.title '@json:$.items[0].name' // First item's name '@json:$.items[*].price' // All prices from items '@json:$..title' // All title properties recursively '@json:$.items[?(@.price > 100)]' // Items with price > 100 ``` -------------------------------- ### RuleEngineOptions Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/types.md An example demonstrating how to configure RuleEngineOptions. ```typescript const options: RuleEngineOptions = { timeout: 10000, enableCache: true, cacheSize: 500, strictMode: false, customSelectors: { 'custom': customSelectorFunction } }; const engine = new RuleEngine(options); ``` -------------------------------- ### Attribute Suffix Examples Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/configuration.md Examples demonstrating how to use attribute suffixes like @text, @src, and @href with CSS selectors. ```javascript '@css:.title@text' // Text content of .title '@css:img@src' // src attribute of img '@css:a@href' // href attribute of link '@css:.price' // Element itself (or innerHTML) ``` -------------------------------- ### Contribution Setup Source: https://github.com/legadoteam/legado-rule/blob/main/README.md Instructions for setting up the project locally for contribution. ```bash git clone cd pnpm i pnpm test ``` -------------------------------- ### Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/RuleEngine.md Basic initialization and initialization with custom options for the RuleEngine. ```javascript import { RuleEngine } from 'book-source-rule-parser'; // Basic initialization const engine = new RuleEngine(); // With custom options const customEngine = new RuleEngine({ timeout: 10000, enableJS: true }); ``` -------------------------------- ### SelectorConfig Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/types.md Example of creating a SelectorConfig object. ```typescript const config: SelectorConfig = { type: SelectorType.CSS, expression: '.title', attribute: 'text' }; ``` -------------------------------- ### Regex Clean Operator Examples Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md Examples showing how to extract or filter text using regex patterns with the '##' operator. ```javascript @css:.price@text##\d+\.\d+ ``` ```javascript @css:.text@text##<[^>]*> ``` ```javascript @regex:\w+@text##\s+## ``` ```javascript @css:.content@html## ``` -------------------------------- ### Type Safety Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md Illustrates ensuring extracted data has the expected type, such as numbers or boolean-like values. ```javascript // Numbers should be extracted with regex '@css:.price@text##\d+\.\d+' ``` ```javascript // Boolean-like values '@css:.available@text || @text:No' ``` -------------------------------- ### parseBatch() Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/RuleEngine.md Example of using the parseBatch method to extract multiple fields. ```javascript const rules = { title: '@css:.title@text', author: '@css:.author@text', price: '@css:.price@text##\d+\.\d+' }; const results = await engine.parseBatch(html, rules); // { // title: { success: true, data: 'My Book', ... }, // author: { success: true, data: 'John Doe', ... }, // price: { success: true, data: '29.99', ... } // } ``` -------------------------------- ### Migration Guide: Old vs New Configuration Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/README.md Illustrates the breaking changes in configuration syntax from version 0.x to 1.0. ```javascript Old: ```javascript new RuleEngine(5000, true) // positional ``` New: ```javascript new RuleEngine({ timeout: 5000, enableJS: true }) // object-based ``` ``` -------------------------------- ### Formatted Output Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md Examples of combining extracted data with static text to create formatted output strings. ```javascript // "Title - Author" '@css:.title@text && @text: - && @css:.author@text' // "【Category】" '@text:【 && @css:.category@text && @text:】' ``` -------------------------------- ### getStats() Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/RuleEngine.md Illustrates how to retrieve performance statistics from the engine. ```javascript const stats = engine.getStats(); // { cacheSize: 42, cacheHits: 128, cacheMisses: 15, totalParses: 143 } ``` -------------------------------- ### RuleContext Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/types.md Example of creating and using a RuleContext. ```typescript const context: RuleContext = { source: '
test
', variables: { customVar: 'value' }, options: { timeout: 5000 } }; const result = await engine.parse(context.source, '@js:customVar', context); ``` -------------------------------- ### parse() Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/RuleEngine.md Examples of using the parse method with CSS selectors, fallback operators, and regex cleaning. ```javascript const html = '
My Book
'; // Simple CSS selector const result = await engine.parse(html, '@css:.title@text'); // { success: true, data: 'My Book', ... } // With fallback operator const withFallback = await engine.parse( html, '@css:.missing@text || @text:Default Title' ); // With regex cleaning const cleaned = await engine.parse( html, '@css:.title@text##\s+##' ); ``` -------------------------------- ### Custom Selector Registration Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/types.md Example of how to register a custom selector function with the RuleEngine. ```typescript import { SelectorFunction } from 'book-source-rule-parser'; const mySelector: SelectorFunction = (source, expr, context) => { // Custom implementation return result; }; const engine = new RuleEngine({ customSelectors: { 'mytype': mySelector } }); ``` -------------------------------- ### RuleParseError Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/types.md Example demonstrating how to catch and handle RuleParseError. ```typescript import { RuleParseError } from 'book-source-rule-parser'; try { await engine.parse(html, invalidRule); } catch (error) { if (error instanceof RuleParseError) { console.error(`[${error.code}] ${error.message}`); console.error('Rule:', error.rule); } } ``` -------------------------------- ### Set Appropriate Timeouts Best Practice Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/configuration.md Example of profiling rules to determine and set appropriate timeouts for the engine. ```javascript // Profile your rules to find appropriate timeout const start = Date.now(); const result = await engine.parse(data, rule); const duration = Date.now() - start; console.log(`Parse took ${duration}ms`); // Set timeout to 2-3x typical duration const engine = new RuleEngine({ timeout: duration * 3 }); ``` -------------------------------- ### SelectorFunction Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/types.md An example of implementing a custom selector function. ```typescript const customSelector: SelectorFunction = (source, expression, context) => { // Implementation return extractedData; }; const engine = new RuleEngine({ customSelectors: { custom: customSelector } }); ``` -------------------------------- ### Profile Timeout Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md Example of profiling to determine an appropriate timeout value. ```javascript const start = Date.now(); const result = await engine.parse(data, rule); const time = Date.now() - start; // Set timeout to time * 2-3 ``` -------------------------------- ### ParseResult Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/types.md Example of using the ParseResult interface. ```typescript const result: ParseResult = await engine.parse(html, '@css:.title@text'); if (result.success) { console.log('Title:', result.data); } else { console.error('Failed to parse:', result.error); } ``` -------------------------------- ### Monitor Cache Effectiveness Best Practice Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/configuration.md Example of monitoring the cache hit rate and logging a message if it's not effective. ```javascript // Check if caching is helping setInterval(() => { const stats = engine.getStats(); const hitRate = stats.cacheHits / (stats.cacheHits + stats.cacheMisses); console.log(`Cache hit rate: ${(hitRate * 100).toFixed(2)}%`); if (hitRate < 0.1) { console.log('Cache not effective, consider disabling'); } }, 60000); ``` -------------------------------- ### ParseBatchResult Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/types.md Example of using the ParseBatchResult type. ```typescript const results: ParseBatchResult<{title: string; author: string}> = await engine.parseBatch(html, { title: '@css:.title@text', author: '@css:.author@text' }); console.log(results.title.data); // 'Book Title' console.log(results.author.data); // 'John Doe' ``` -------------------------------- ### Production Configuration Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/README.md Example of a production-ready configuration for RuleEngine, including caching. ```javascript new RuleEngine({ timeout: 10000, enableCache: true, cacheSize: 1000, strictMode: false, debug: false }) ``` -------------------------------- ### Increase Timeout Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md Example of increasing the timeout setting for the RuleEngine. ```javascript new RuleEngine({ timeout: 10000 }) ``` -------------------------------- ### OperatorFunction Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/types.md An example of implementing a custom operator function. ```typescript const customOperator: OperatorFunction = (left, right, context) => { // Custom logic combining left and right results return combined; }; const engine = new RuleEngine({ customOperators: { custom: customOperator } }); ``` -------------------------------- ### Use Caching for Repeated Patterns Best Practice Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/configuration.md Example of enabling and configuring caching for scenarios where the same rule is parsed multiple times. ```javascript // If parsing same rule multiple times const engine = new RuleEngine({ enableCache: true, cacheSize: 500 }); ``` -------------------------------- ### validateRule() Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/RuleEngine.md Demonstrates how to validate rule syntax using the validateRule method. ```javascript const validation = engine.validateRule('@css:.title@text'); // { valid: true, errors: [], warnings: [] } const badRule = engine.validateRule('@css:invalid@@text'); // { valid: false, errors: [...], warnings: [...] } ``` -------------------------------- ### PRESET_CLEAN_PATTERNS Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/operators.md Example of importing and accessing a preset cleaning pattern from PRESET_CLEAN_PATTERNS. ```javascript import { PRESET_CLEAN_PATTERNS } from 'book-source-rule-parser'; const pattern = PRESET_CLEAN_PATTERNS.htmlTags; // { pattern: '<[^>]*>', replacement: '' } ``` -------------------------------- ### Single Rule Parsing Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md Examples of parsing a single rule using either an instance method or a static function, including parsing with context. ```javascript // Instance method const result = await engine.parse(source, rule); // Static function const result = await parseRule(source, rule); // With context const result = await engine.parse(source, rule, { customVar: 'value' }); ``` -------------------------------- ### clearCache() Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/RuleEngine.md Shows how to clear the internal rule execution cache. ```javascript engine.clearCache(); ``` -------------------------------- ### parseArray() Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/RuleEngine.md Example of using the parseArray method to extract a list of book items with their titles and authors. ```javascript const html = '

Book 1

Author 1

Book 2

Author 2

'; const items = await engine.parseArray(html, '@css:.book', { title: '@css:h3@text', author: '@css:p@text' }); // [ // { title: 'Book 1', author: 'Author 1' }, // { title: 'Book 2', author: 'Author 2' } // ] ``` -------------------------------- ### Error Handling Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/RuleEngine.md Demonstrates how to catch and handle RuleParseError exceptions. ```javascript try { const result = await engine.parse(html, '@invalid:selector'); } catch (error) { if (error instanceof RuleParseError) { console.error('Parse error:', error.message); console.error('Selector:', error.selector); } } ``` -------------------------------- ### Creating an Engine Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md Demonstrates creating a new RuleEngine instance with minimal configuration or with custom options. ```javascript // Minimal const engine = new RuleEngine(); // With options const engine = new RuleEngine({ timeout: 10000, enableCache: true }); // Factory function const engine = createRuleEngine(options); ``` -------------------------------- ### Error Handling Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md Provides an example of how to handle potential errors during rule parsing using try-catch blocks. ```javascript try { const result = await engine.parse(html, rule); if (result.success) { console.log(result.data); } else { console.error(result.error); } } catch (error) { if (error instanceof RuleParseError) { console.error(`[${error.code}] ${error.message}`); } } ``` -------------------------------- ### presetCleanOperator Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/operators.md Example usage of presetCleanOperator with multiple preset names. ```javascript import { presetCleanOperator } from 'book-source-rule-parser'; const result = presetCleanOperator('

Hello world

', ['htmlTags', 'multipleSpaces']); // { success: true, data: 'Hello world', ... } ``` -------------------------------- ### jsMapSelector Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/selectors.md An example showing how to use jsMapSelector to convert an array of strings to lowercase. ```javascript const html = ['Item1', 'Item2', 'Item3']; const result = jsMapSelector(html, 'item.toLowerCase()'); // { success: true, data: ['item1', 'item2', 'item3'], ... } ``` -------------------------------- ### Attribute Extraction Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md Examples of extracting different types of content from HTML attributes. ```javascript // Text content '@css:.title@text' // HTML content '@css:.content@html' // Specific attribute '@css:img@src' // src attribute '@css:a@href' // href attribute '@css:div@class' // class attribute '@css:.item@data-id' // data-* attribute ``` -------------------------------- ### XPath Extraction Example Source: https://github.com/legadoteam/legado-rule/blob/main/README.md Demonstrates how to extract data from HTML using XPath selectors. ```javascript const html = `

深入理解计算机系统

Randal E. Bryant 139元

`; const title = await engine.parse(html, '@xpath://h1/text()'); // => "深入理解计算机系统" const author = await engine.parse(html, '@xpath://span[@class="author"]/text()'); // => "Randal E. Bryant" ``` -------------------------------- ### Import Patterns - Direct Selector Access Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/module-exports.md Example of importing and using selector functions for direct access. ```javascript import { cssSelector, regexSelector, jsonSelector } from 'book-source-rule-parser'; const result = cssSelector(html, '.title@text'); ``` -------------------------------- ### Import Patterns - Operator Access Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/module-exports.md Example of importing operator functions. ```javascript import { fallbackOperator, concatOperator } from 'book-source-rule-parser'; ``` -------------------------------- ### smartCleanOperator Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/operators.md Example usage of smartCleanOperator with options for aggressive cleaning and content detection. ```javascript const result = smartCleanOperator('

Hello

', { aggressive: true, detectContent: true }); // { success: true, data: 'Hello', detectedPatterns: ['HTML tags detected', ...] } ``` -------------------------------- ### Specific Selectors Performance Tip Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md A performance tip recommending the use of specific CSS selectors over general ones. ```javascript // Slower: Finds all divs then filters '@css:div' ``` ```javascript // Faster: Direct class selection '@css:.book-item' ``` -------------------------------- ### parseFallbackRule Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/operators.md Example showing how parseFallbackRule splits a rule string containing '||'. ```javascript import { parseFallbackRule } from 'book-source-rule-parser'; const rules = parseFallbackRule('@css:.title@text || @css:.name@text || @text:Default'); // ['@css:.title@text', '@css:.name@text', '@text:Default'] ``` -------------------------------- ### Batch Parsing with Types Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/types.md Shows how to perform batch parsing with type safety for the results. ```typescript interface Rules { title: string; author: string; price: string; } const results = await engine.parseBatch(html, { title: '@css:.title@text', author: '@css:.author@text', price: '@css:.price@text##\d+\.\d+' }); // Type-safe access if (results.title.success) { console.log(results.title.data); } ``` -------------------------------- ### jsSelector() Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/selectors.md Provides examples of using jsSelector to execute JavaScript code for data extraction and manipulation. ```javascript import { jsSelector } from 'book-source-rule-parser'; const html = '
5 items
'; // Extract number from HTML const result = jsSelector(html, 'source.match(/\d+/)[0]'); // { success: true, data: '5', ... } // Use context variables const result2 = jsSelector(html, 'multiplier * parseInt(source)', { multiplier: 2 }); // { success: true, data: 10, ... } ``` -------------------------------- ### concatOperator Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/operators.md Example demonstrating the usage of concatOperator to join text from multiple CSS selectors with a separator. ```javascript import { concatOperator } from 'book-source-rule-parser'; const html = '

Title

Author

'; const selectors = [ { rule: '@css:h1@text', execute: (s) => ({ success: true, data: 'Title' }) }, { rule: '@css:p@text', execute: (s) => ({ success: true, data: 'Author' }) } ]; const result = concatOperator(selectors, html, {}, { separator: ' - ' }); // { success: true, data: 'Title - Author', ... } ``` -------------------------------- ### Import Patterns - Specific Imports Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/module-exports.md Example of importing specific functions and classes from 'book-source-rule-parser'. ```javascript import { RuleEngine, parseRule, isEmpty } from 'book-source-rule-parser'; ``` -------------------------------- ### Syntax Validation Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md Shows how to validate a rule using the engine.validateRule method and handle potential errors. ```javascript const validation = engine.validateRule('@css:.title@text'); if (!validation.valid) { console.error('Invalid rule:', validation.errors); } ``` -------------------------------- ### Caching Repeated Rules Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md Demonstrates how to enable caching in the RuleEngine to improve performance when parsing the same rule multiple times. ```javascript const engine = new RuleEngine({ enableCache: true }); // First call parses const result1 = await engine.parse(html1, rule); // Second call with same rule uses cache const result2 = await engine.parse(html2, rule); ``` -------------------------------- ### High Performance Configuration Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md Configuration preset for optimizing performance with caching enabled. ```javascript new RuleEngine({ enableCache: true, cacheSize: 5000, timeout: 5000 }) ``` -------------------------------- ### Decreasing Timeout Configuration Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/configuration.md Example of decreasing the engine's timeout for quick fail-fast behavior. ```javascript // For quick fail-fast behavior const engine = new RuleEngine({ timeout: 1000 // 1 second }); ``` -------------------------------- ### Development Configuration Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md Configuration preset for development environments, enabling debugging and disabling caching. ```javascript new RuleEngine({ debug: true, strictMode: true, enableCache: false }) ``` -------------------------------- ### Caching Configuration Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/README.md Example of enabling and configuring caching for high-volume operations. ```javascript const engine = new RuleEngine({ enableCache: true, cacheSize: 5000 }); ``` -------------------------------- ### Type-Safe Rule Parsing Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/types.md Demonstrates type-safe rule parsing using generic types with RuleEngine. ```typescript import { RuleEngine, RuleEngineOptions, ParseResult } from 'book-source-rule-parser'; interface BookData { title: string; author: string; price: number; } const engine = new RuleEngine({ timeout: 5000, strictMode: false } as RuleEngineOptions); const result: ParseResult = await engine.parse( html, '@css:.title@text' ); if (result.success) { const book: BookData = { title: result.data, author: '', price: 0 }; } ``` -------------------------------- ### Get Cache Statistics Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/configuration.md Retrieves statistics about the engine's cache. ```javascript const stats = engine.getStats(); // { // cacheSize: 42, // Current entries in cache // cacheHits: 128, // Times result came from cache // cacheMisses: 15, // Times cache missed // totalParses: 143 // Total parse operations // } ``` -------------------------------- ### URL Extraction Pattern Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md A common regex pattern for extracting URLs. ```javascript '@regex:https?://[^\s]+' ``` -------------------------------- ### Date Extraction Patterns Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md Common regex patterns for extracting dates in different formats. ```javascript '@regex:\d{4}-\d{2}-\d{2}' // YYYY-MM-DD ``` ```javascript '@regex:\d{1,2}/\d{1,2}/\d{4}' // MM/DD/YYYY ``` -------------------------------- ### jsReduceSelector Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/selectors.md An example showing jsReduceSelector used to sum the elements of an array, starting with an initial value of 0. ```javascript const result = jsReduceSelector([1, 2, 3], 'accumulator + item', 0); // { success: true, data: 6, ... } ``` -------------------------------- ### Error Handling Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/README.md Demonstrates how to handle potential errors during rule parsing using a try-catch block. ```javascript try { const result = await engine.parse(html, rule); if (result.success) { console.log('Data:', result.data); } else { console.error('Parse failed:', result.error); } } catch (error) { if (error instanceof RuleParseError) { console.error(`[${error.code}] ${error.message}`); } } ``` -------------------------------- ### Migration from Version 0.x to 1.0 Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/configuration.md Illustrates the change in configuration format from positional arguments in version 0.x to an object-based approach in version 1.0+. ```javascript // Old (0.x) const engine = new RuleEngine(5000, 10); // positional args // New (1.0+) const engine = new RuleEngine({ timeout: 5000, maxDepth: 10 }); ``` -------------------------------- ### Increasing Timeout Configuration Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/configuration.md Example of increasing the engine's timeout for complex operations. ```javascript // For complex rules or slow DOM operations const engine = new RuleEngine({ timeout: 15000 // 15 seconds }); ``` -------------------------------- ### Avoid Global Regex Performance Tip Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md A performance tip advising against the use of global regex flags when a single match is sufficient. ```javascript // Slower: Matches everywhere '@regex:g:\d+' ``` ```javascript // Faster: Single match '@regex:\d+' ``` -------------------------------- ### Use Specific Selectors Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md Demonstrates the difference between specific and general CSS selectors for performance. ```javascript // Good '@css:.book-title@text' // Slow '@css:div@text' ``` -------------------------------- ### Common Spacing Patterns for Concatenation Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md Illustrates different spacing patterns when concatenating strings using the '&&' operator. ```javascript // Concatenate with space '@css:.title@text && @text: && @css:.author@text' ``` ```javascript // Concatenate with no space '@css:.first@text && @css:.last@text' ``` ```javascript // Concatenate with punctuation '@css:.title@text && @text:, && @css:.author@text' ``` -------------------------------- ### regexSelector() Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/selectors.md Demonstrates how to use regexSelector to extract data and perform global matching. ```javascript import { regexSelector } from 'book-source-rule-parser'; const text = 'Price: $29.99'; const result = regexSelector(text, '\$(\d+\.\d+)'); // { success: true, data: '29.99', ... } // Global matching const html = '

Item 1

Item 2

'; const items = regexSelector(html, '

([^<]+)

'); // { success: true, data: ['Item 1', 'Item 2'], ... } ``` -------------------------------- ### regexMultiPatternSelector() Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/selectors.md Shows how regexMultiPatternSelector tries multiple patterns. ```javascript const result = regexMultiPatternSelector('Order #123', [ '#(\d+)', // Try hash format 'Order (\d+)' // Try text format ]); ``` -------------------------------- ### Common Regex Patterns for Cleaning Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/rule-syntax.md A list of common regex patterns used with the '##' operator for extraction and cleaning. ```javascript '##\d+' ``` ```javascript '##[a-zA-Z0-9-_]+' ``` ```javascript '##\S+' ``` ```javascript '##\s+' ``` ```javascript '##^\s+##' ``` ```javascript '##\s+$##' ``` ```javascript '##<[^>]*>' ``` -------------------------------- ### Custom Context for @js: Selectors Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/configuration.md Example of passing custom context variables to the parse operation for use in @js: selectors. ```javascript const context = { // Custom variables available in @js: selectors customVar: 'value', multiplier: 2 }; const result = await engine.parse(html, '@js:multiplier * 5', context); // Returns 10 (uses context.multiplier) ``` -------------------------------- ### regexReplaceSelector() Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/selectors.md Shows how to use regexReplaceSelector to replace text matching a pattern. ```javascript const result = regexReplaceSelector('Hello World', '\s+', ' '); // { success: true, data: 'Hello World', ... } ``` -------------------------------- ### Extract Single Field Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/README.md Example demonstrating how to extract a single field from an HTML source using the RuleEngine. ```javascript import { RuleEngine } from 'book-source-rule-parser'; const engine = new RuleEngine(); const result = await engine.parse(html, '@css:.title@text'); console.log(result.data); ``` -------------------------------- ### Enable Caching Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md Enables caching for batch operations to improve performance. ```javascript const engine = new RuleEngine({ enableCache: true }); ``` -------------------------------- ### Extract Multiple Fields Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/README.md Example showing how to extract multiple fields from an HTML source simultaneously using parseBatch. ```javascript const results = await engine.parseBatch(html, { title: '@css:.title@text', author: '@css:.author@text', price: '@css:.price@text##\d+\.\d+' }); ``` -------------------------------- ### Default Configuration Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/configuration.md Instantiates RuleEngine with all default options. ```javascript import { RuleEngine } from 'book-source-rule-parser'; const engine = new RuleEngine(); // Uses all defaults: 5000ms timeout, no caching, JS enabled ``` -------------------------------- ### templateTextSelector Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/selectors.md Example usage of templateTextSelector for variable substitution. ```javascript const result = templateTextSelector(html, 'Hello {name}, you have {count} items', { name: 'John', count: 5 }); // { success: true, data: 'Hello John, you have 5 items', ... } ``` -------------------------------- ### smartConcatOperator() Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/operators.md Example usage of `smartConcatOperator` with a template strategy. ```javascript const result = smartConcatOperator(selectors, html, {}, { strategy: 'template', template: '{0} by {1}' }); // { success: true, data: 'Title by Author', ... } ``` -------------------------------- ### conditionalFallbackOperator Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/operators.md Example illustrating the structure of conditionalSelectors for conditionalFallbackOperator. ```javascript const selectors = [ { condition: 'source.length > 100', selector: { rule: '@css:.long@text', execute: () => {...} } }, { selector: { rule: '@css:.short@text', execute: () => {...} } } ]; const result = conditionalFallbackOperator(selectors, html); ``` -------------------------------- ### validateFallbackRules Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/operators.md Example demonstrating the validation of fallback rules. ```javascript const validation = validateFallbackRules(['@css:.title@text', '@text:Default']); // { valid: true, errors: [], warnings: [...] } ``` -------------------------------- ### multilineTextSelector Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/selectors.md Example usage of multilineTextSelector with trimLines and preserveWhitespace options. ```javascript const result = multilineTextSelector(html, 'Line 1\nLine 2', {}, { trimLines: true, preserveWhitespace: false }); ``` -------------------------------- ### batchRegexCleanOperator Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/operators.md Example usage of batchRegexCleanOperator with an array of cleaning rules. ```javascript const rules = [ { pattern: '\\s+', replacement: ' ' }, { pattern: '^\\s+', replacement: '' }, { pattern: '\\s+$', replacement: '' } ]; const result = batchRegexCleanOperator(' hello world ', rules); // { success: true, data: 'hello world', ... } ``` -------------------------------- ### regexCleanOperator() Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/operators.md Example usage of `regexCleanOperator` to remove non-digit characters. ```javascript import { regexCleanOperator } from 'book-source-rule-parser'; const result = regexCleanOperator('Price: ¥89.00', '\\D', ''); // { success: true, data: '8900', ... } ``` -------------------------------- ### Batch Parsing Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md How to parse multiple rules from a source simultaneously and access the results. ```javascript const results = await engine.parseBatch(source, { title: '@css:.title@text', author: '@css:.author@text' }); console.log(results.title.data); console.log(results.author.data); ``` -------------------------------- ### conditionalConcatOperator() Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/operators.md Example usage of `conditionalConcatOperator` with conditional selectors and affixes. ```javascript const selectors = [ { condition: 'hasTitle', selector: { rule: '@css:.title@text', execute: () => {...} }, prefix: 'Title: ', suffix: ' | ' }, { selector: { rule: '@css:.author@text', execute: () => {...} } } ]; const result = conditionalConcatOperator(selectors, html); ``` -------------------------------- ### parseConcatRule() Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/operators.md Example usage of `parseConcatRule` to split a rule string. ```javascript import { parseConcatRule } from 'book-source-rule-parser'; const rules = parseConcatRule('@css:.title@text && @text: - && @css:.author@text'); // ['@css:.title@text', '@text: - ', '@css:.author@text'] ``` -------------------------------- ### File Structure Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md Overview of the Legado Rule project's directory structure. ```plaintext legado-rule/ ├── index.ts # Main TypeScript entry point ├── src/ │ ├── engine.js # Core implementation │ ├── rule-engine.js # Async wrapper │ ├── types.js # Type definitions │ ├── selectors/ │ │ ├── css.js │ │ ├── xpath.js │ │ ├── json.js │ │ ├── regex.js │ │ ├── js.js │ │ └── text.js │ └── operators/ │ ├── fallback.js │ ├── concat.js │ ├── regex-clean.js │ ├── attribute.js │ └── array-index.js └── dist/ # Compiled output ``` -------------------------------- ### Default Values Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md Demonstrates how to provide default values when an extraction fails. ```javascript '@css:.title@text || @text:Untitled' '@json:$.price || @text:TBD' ``` -------------------------------- ### Correct Operator Spacing Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md Illustrates the correct spacing required for `&&` and `||` operators. ```javascript // Correct '@css:.a@text && @css:.b@text' // Wrong '@css:.a@text&&@css:.b@text' // No spaces '@css:.a@text &&@css:.b@text' // Missing space ``` -------------------------------- ### attributeOperator Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/operators.md Example usage of attributeOperator to extract the text content of an element. ```javascript import { attributeOperator } from 'book-source-rule-parser'; const result = attributeOperator(element, 'text'); // { success: true, data: 'element text content', ... } ``` -------------------------------- ### quotedTextSelector Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/selectors.md An example showing quotedTextSelector processing a string with newline escape sequences. ```javascript const result = quotedTextSelector(html, '"Line 1\nLine 2"'); // { success: true, data: 'Line 1\nLine 2', ... } ``` -------------------------------- ### External Dependencies Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md Lists the external libraries that Legado Rule depends on. ```plaintext - cheerio - HTML parsing and CSS selectors - xpath - XPath implementation - jsdom - DOM emulation for XPath - jsonpath - JSONPath queries ``` -------------------------------- ### textSelector Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/selectors.md An example demonstrating textSelector to return a default title, useful as a fallback. ```javascript import { textSelector } from 'book-source-rule-parser'; const result = textSelector(html, 'Default Title'); // { success: true, data: 'Default Title', ... } ``` -------------------------------- ### parseCleanRule() Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/operators.md Example usage of `parseCleanRule` to parse a rule string for cleaning whitespace. ```javascript import { parseCleanRule } from 'book-source-rule-parser'; const parsed = parseCleanRule('##\\s{2,}## '); // { pattern: '\\s{2,}', replacement: ' ' } ``` -------------------------------- ### Caching Strategy - High-Volume Batch Operations Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/configuration.md Demonstrates using RuleEngine with caching enabled and a large cache size for high-volume batch operations where rules are parsed repeatedly. ```javascript const engine = new RuleEngine({ enableCache: true, cacheSize: 5000, // Large cache for frequently-used rules timeout: 5000 }); // Parse same rules repeatedly const results = []; for (let i = 0; i < 1000; i++) { results.push(await engine.parse(data[i], '@css:.title@text')); // After first parse, subsequent identical rules use cache } ``` -------------------------------- ### Fallback Operator Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/operators.md Example demonstrating the usage of fallbackOperator to extract text from HTML. ```javascript import { fallbackOperator } from 'book-source-rule-parser'; const html = '

Title

'; const selectors = [ { rule: '@css:.missing@text', execute: (source) => ({ success: false, data: null }) }, { rule: '@css:h1@text', execute: (source) => ({ success: true, data: 'Title' }) } ]; const result = fallbackOperator(selectors, html); // { success: true, data: 'Title', usedRule: '@css:h1@text', fallbackIndex: 1, ... } ``` -------------------------------- ### Enable JavaScript Execution Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md Enables JavaScript execution within the rule engine. ```javascript new RuleEngine({ enableJS: true }) ``` -------------------------------- ### Constructor Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/RuleEngine.md Creates a new RuleEngine instance with optional configuration. ```typescript new RuleEngine(options?: RuleEngineOptions) ``` -------------------------------- ### jsFilterSelector Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/selectors.md An example demonstrating jsFilterSelector to filter an array of numbers, keeping only those greater than 2. ```javascript const result = jsFilterSelector([1, 2, 3, 4, 5], 'item > 2'); // { success: true, data: [3, 4, 5], ... } ``` -------------------------------- ### jsConditionalSelector Example Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/api-reference/selectors.md An example demonstrating the usage of jsConditionalSelector to determine if a source's length is greater than 100 and return 'Long' or 'Short' accordingly. ```javascript const result = jsConditionalSelector(html, 'source.length > 100', 'Long', 'Short'); ``` -------------------------------- ### OperatorType Usage Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/types.md Example usage of the OperatorType enum. ```typescript import { OperatorType } from 'book-source-rule-parser'; if (rule.includes(OperatorType.FALLBACK)) { // Process fallback rule } ``` -------------------------------- ### SelectorType Usage Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/types.md Example usage of the SelectorType enum. ```typescript import { SelectorType } from 'book-source-rule-parser'; if (selectorType === SelectorType.CSS) { // Handle CSS selector } ``` -------------------------------- ### Cache Management Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md Operations for clearing the cache and retrieving cache statistics. ```javascript // Clear cache engine.clearCache(); // Get stats const stats = engine.getStats(); console.log(stats.cacheHits); console.log(stats.cacheMisses); ``` -------------------------------- ### High Security Configuration Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md Configuration preset for enhancing security by disabling JavaScript execution and enabling strict mode. ```javascript new RuleEngine({ enableJS: false, timeout: 2000, strictMode: true }) ``` -------------------------------- ### Default Configuration Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/README.md Shows the default configuration options for the RuleEngine. ```javascript new RuleEngine() // timeout: 5000ms // enableJS: true // enableXPath: true // strictMode: false ``` -------------------------------- ### Caching Strategy - Single-Use Operations Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/configuration.md Demonstrates using RuleEngine with caching disabled for single-use operations to save memory. ```javascript const engine = new RuleEngine({ enableCache: false, // Save memory timeout: 10000 }); const result = await engine.parse(html, '@css:.title@text'); ``` -------------------------------- ### Small Cache Size Configuration Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/configuration.md Configures the engine with a small cache size, suitable for memory-constrained environments. ```javascript const engine = new RuleEngine({ enableCache: true, cacheSize: 50 // Only cache 50 results }); ``` -------------------------------- ### Module Exports Source: https://github.com/legadoteam/legado-rule/blob/main/_autodocs/quick-reference.md Lists the main exports from the Legado Rule library. ```javascript // Main class export { RuleEngine, BookSourceRuleEngine } // Factory export { createRuleEngine } // Static functions export { parseRule, parseRules } // Utilities export { isEmpty, RuleParseError } // Types export { SelectorType, OperatorType } // Selectors export { cssSelector, xpathSelector, jsonSelector, ... } // Operators export { fallbackOperator, concatOperator, regexCleanOperator, ... ```