### Install Jexl - Shell Source: https://github.com/pawel-up/jexl/blob/main/README.md Provides the command to install the Jexl library from npm. This is the first step to start using the library in a project. ```shell npm install @pawel-up/jexl --save ``` -------------------------------- ### Create function schema with TypeScript Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/schemas/README.md Demonstrates how to create a new function schema using helper utilities from @pawel-up/jexl. Includes parameter definitions, return type, and examples. ```typescript import { createFunctionSchema, createParameter, createLibrarySchema } from '@pawel-up/jexl/schemas/utils.js' const myFunction = createFunctionSchema( 'myFunction', 'Description of my function', 'category', [ createParameter('param1', 'Description of param1', { type: 'string' }), createParameter('param2', 'Description of param2', { type: 'number' }, false), ], { type: 'boolean', description: 'Description of return value' }, { examples: ['myFunction("test", 42) // true'], } ) const myLibrary = createLibrarySchema( { myFunction }, { category: 'custom', title: 'My Custom Library', description: 'Custom functions for my use case', version: '1.0.0', } ) ``` -------------------------------- ### Generate Markdown Documentation (TypeScript) Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/schemas/README.md This function generates Markdown documentation from the array library schema, including function details and examples. It depends on the JEXL schemas module. Input is none; output is a string of Markdown. Limitations: Output format is fixed and requires schema examples to be present for full documentation. ```typescript import { arrayLibrarySchema } from '@pawel-up/jexl/schemas/schemas/array.schema.js' // Generate markdown documentation export function generateMarkdownDocs(): string { const functions = Object.values(arrayLibrarySchema.functions) return [ `# ${arrayLibrarySchema.title}`, '', arrayLibrarySchema.description, '', '## Functions', '', ...functions .map((func) => [ `### ${func.name}`, '', func.description, '', '**Parameters:**', '', ...func.parameters.map((p) => `- \`${p.name}\` (${p.type}${p.required ? '' : '?'}) - ${p.description}`), '', `**Returns:** ${func.returns.type} - ${func.returns.description}`, '', ...(func.examples ? ['**Examples:**', '', ...func.examples.map((ex) => `\`\`\`typescript\n${ex}\n\`\`\``), ''] : []), ]) .flat(), ].join('\n') } ``` -------------------------------- ### Get Completion Items for LSP (TypeScript) Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/schemas/README.md This function generates completion items for the Language Server Protocol (LSP) using VSCode Language Server, based on the array library schema. It requires the JEXL schemas module and VSCode Language Server types. Input is none; output is an array of CompletionItem objects. Limitations include dependence on schema availability and LSP client support. ```typescript import { arrayLibrarySchema } from '@pawel-up/jexl/schemas/schemas/array.schema.js' import { CompletionItem, CompletionItemKind } from 'vscode-languageserver' export function getCompletionItems(): CompletionItem[] { return Object.values(arrayLibrarySchema.functions).map((func) => ({ label: func.name, kind: CompletionItemKind.Function, detail: func.description, documentation: { kind: 'markdown', value: [ `**${func.name}**(${func.parameters.map((p) => `${p.name}: ${p.type}`).join(', ')}) → ${func.returns.type}`, '', func.description, '', ...(func.examples ? ['**Examples:**', ...func.examples.map((ex) => `\`${ex}\``)] : []), ].join('\n'), }, })) } ``` -------------------------------- ### Import Array Library Schemas (TypeScript) Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/schemas/README.md This import statement demonstrates how to access the array library schema and function schemas from the JEXL package. It has no dependencies beyond the JEXL module. Input is none; output allows access to schemas. Limitations: Requires the JEXL package to be installed and available. ```typescript import { arrayLibrarySchema, arrayFunctionSchemas } from '@pawel-up/jexl/schemas/schemas/array.schema.js' ``` -------------------------------- ### VS Code extension integration with TypeScript Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/schemas/README.md Shows how to provide autocompletion for function schemas in VS Code extensions. Includes function details, parameter info, and example formatting. ```typescript import { arrayLibrarySchema } from '@pawel-up/jexl/schemas/schemas/array.schema.js' import * as vscode from 'vscode' // Provide autocompletion export function provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) { const completionItems: vscode.CompletionItem[] = [] Object.values(arrayLibrarySchema.functions).forEach((func) => { const item = new vscode.CompletionItem(func.name, vscode.CompletionItemKind.Function) item.detail = func.description item.documentation = new vscode.MarkdownString() // Add parameters info const params = func.parameters.map((p) => `${p.name}: ${p.type}`).join(', ') item.documentation.appendMarkdown(`**${func.name}**(${params}) → ${func.returns.type}\n\n`) item.documentation.appendMarkdown(`${func.description}\n\n`) // Add examples if (func.examples) { item.documentation.appendMarkdown('**Examples:**\n') func.examples.forEach((example) => { item.documentation.appendMarkdown(`\`\`\`typescript\n${example}\n\`\`\`\n`) }) } completionItems.push(item) }) return completionItems } ``` -------------------------------- ### Check String Starts With Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/README.md This endpoint checks if a string starts with a specified substring. ```APIDOC ## POST /string/startswith ### Description Checks if a string starts with a specified substring. ### Method POST ### Endpoint /string/startswith ### Parameters #### Path Parameters - **None** #### Query Parameters - **None** #### Request Body - **val** (string) - Required - The string to check. - **searchString** (string) - Required - The substring to search for at the beginning. ### Request Example { "val": "HelloWorld", "searchString": "Hello" } ### Response #### Success Response (200) - **startsWith** (boolean) - True if the string starts with the search string, false otherwise. #### Response Example { "startsWith": true } ``` -------------------------------- ### CodeMirror integration with TypeScript Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/schemas/README.md Illustrates how to implement autocompletion for function schemas in CodeMirror. Includes function name matching and completion options generation. ```typescript import { arrayLibrarySchema } from '@pawel-up/jexl/schemas/schemas/array.schema.js' import { CompletionContext, CompletionResult } from '@codemirror/autocomplete' // CodeMirror autocompletion export function jexlCompletion(context: CompletionContext): CompletionResult | null { const word = context.matchBefore(/\w*/) if (!word) return null const options = Object.values(arrayLibrarySchema.functions).map((func) => ({ label: func.name, type: 'function', info: func.description, detail: `${func.name}(${func.parameters.map((p) => p.name).join(', ')}) → ${func.returns.type}`, apply: func.name, })) return { from: word.from, options, } } ``` -------------------------------- ### Defining and Loading JEXL Array Schema Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/schemas/README.md This schema outlines JEXL array functions like length, supporting validation and tooling integration. It is imported as a JSON string from the @pawel-up/jexl package and parsed into an object for runtime use. Inputs include the schema file path or string; outputs are a parsed schema object for function validation. Limitations include reliance on JSON Schema draft-07 and partial parameter definitions in examples. ```json { "$schema": "http://json-schema.org/draft-07/schema#", "$id": "https://github.com/pawel-up/jexl/schemas/array.schema.json", "title": "Jexl Array Functions", "functions": { "length": { "name": "length", "description": "Gets the length of an array", "parameters": [...] } } } ``` ```typescript import { arrayLibrarySchemaJSON } from '@pawel-up/jexl/schemas/schemas/array.schema.js' const schema = JSON.parse(arrayLibrarySchemaJSON) ``` -------------------------------- ### Array Operations in TypeScript Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/README.md Provides examples of basic array operations like getting length, first and last elements, accessing elements by index, and checking for containment. These are fundamental array manipulation techniques. ```TypeScript await jexl.eval('length([1, 2, 3])') ``` ```TypeScript await jexl.eval('first([1, 2, 3])') ``` ```TypeScript await jexl.eval('last([1, 2, 3])') ``` ```TypeScript await jexl.eval('at([1, 2, 3], 1)') ``` ```TypeScript await jexl.eval('contains([1, 2, 3], 2)') ``` -------------------------------- ### Install modern Jexl package (bash) Source: https://github.com/pawel-up/jexl/blob/main/README.md Removes the legacy Jexl package and installs the new TypeScript‑first fork via npm. Use this before updating imports in your project. ```bash # Remove old package npm uninstall jexl # Install modern version npm install @pawel-up/jexl ``` -------------------------------- ### Date Utilities in TypeScript Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/README.md Illustrates utility functions for date manipulation, including determining if a date falls on a weekend, getting the start of a month, finding the end of a year, and calculating age. ```TypeScript await jexl.eval('isWeekend(now())') ``` ```TypeScript await jexl.eval('startOfMonth(now())') ``` ```TypeScript await jexl.eval('endOfYear(now())') ``` ```TypeScript await jexl.eval('getAge(birthDate)') ``` -------------------------------- ### Example Context Object - JavaScript Source: https://github.com/pawel-up/jexl/blob/main/README.md Demonstrates an example context object used with Jexl expressions. The object includes nested properties and arrays for traversal in expressions. ```javascript { name: { first: "Malory", last: "Archer" }, exes: [ "Nikolai Jakov", "Len Trexler", "Burt Reynolds" ], lastEx: 2 } ``` -------------------------------- ### Jexl Validation Rules with JavaScript Source: https://github.com/pawel-up/jexl/blob/main/examples/README.md Evaluates business validation rules using Jexl expressions. This example demonstrates checks for user age, email validity, and agreement to terms, along with purchase eligibility and membership level determination. It requires a Jexl instance and a context object. ```javascript await jexl.eval( ` { isValid: user.age >= 18 && isValidEmail(user.email) && user.agreeToTerms, canPurchase: user.age >= 18 && user.paymentMethod && user.address, membershipLevel: user.totalSpent > 1000 ? "gold" : user.totalSpent > 500 ? "silver" : "bronze" } `, context ) ``` -------------------------------- ### Trim Start Whitespace Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/README.md This endpoint removes whitespace from the beginning of a string. ```APIDOC ## POST /string/trimStart ### Description Removes whitespace from the beginning of a string. ### Method POST ### Endpoint /string/trimStart ### Parameters #### Path Parameters - **None** #### Query Parameters - **None** #### Request Body - **val** (string) - Required - The string to trim. ### Request Example { "val": " this is a string " } ### Response #### Success Response (200) - **trimmedString** (string) - The trimmed string. #### Response Example { "trimmedString": "this is a string " } ``` -------------------------------- ### Best Practices for Organizing Namespaces in JEXL (JavaScript) Source: https://github.com/pawel-up/jexl/blob/main/README.md Examples of registering functions and transforms by domain (User, Product), data type (String, Array, Date), or utility (Validation, Format). Uses jexl.addFunction and addTransform; promotes modular code without runtime evaluation shown. Best for large projects to avoid flat namespace clutter. ```javascript // By domain jexl.addFunction('User.authenticate', authenticateUser) jexl.addFunction('User.authorize', authorizeUser) jexl.addFunction('Product.getPrice', getProductPrice) jexl.addFunction('Order.calculate', calculateOrder) // By data type jexl.addTransform('String.capitalize', capitalizeString) jexl.addTransform('String.truncate', truncateString) jexl.addTransform('Array.unique', uniqueArray) jexl.addTransform('Array.flatten', flattenArray) jexl.addTransform('Date.format', formatDate) jexl.addTransform('Date.addDays', addDaysToDate) // By utility category jexl.addFunction('Validation.isEmail', isValidEmail) jexl.addFunction('Validation.isPhoneNumber', isValidPhoneNumber) jexl.addTransform('Format.currency', formatCurrency) jexl.addTransform('Format.percentage', formatPercentage) ``` -------------------------------- ### Batch Operations with addTransforms() and addFunctions() - Jexl Source: https://context7.com/pawel-up/jexl/llms.txt Demonstrates using Jexl's addTransforms() and addFunctions() methods to register multiple string, number, and array utilities in a single call. Shows practical examples including string manipulation, mathematical operations, array processing, and context-based evaluation. ```typescript const jexl = new Jexl() // Add multiple transforms jexl.addTransforms({ // String transforms upper: (str: string) => str.toUpperCase(), lower: (str: string) => str.toLowerCase(), trim: (str: string) => str.trim(), // Number transforms abs: (num: number) => Math.abs(num), round: (num: number, places = 0) => Number(num.toFixed(places)), // Array transforms reverse: (arr: any[]) => [...arr].reverse(), unique: (arr: any[]) => [...new Set(arr)], length: (arr: any[]) => arr.length }) await jexl.eval('" Hello World "|trim|upper') // "HELLO WORLD" await jexl.eval('3.14159|round(2)') // 3.14 await jexl.eval('[1, 2, 2, 3]|unique|length') // 3 // Add multiple functions jexl.addFunctions({ // Math utilities square: (n: number) => n * n, cube: (n: number) => n * n * n, // String utilities reverse: (str: string) => str.split('').reverse().join(''), titleCase: (str: string) => str.charAt(0).toUpperCase() + str.slice(1), // Array utilities first: (arr: any[]) => arr[0], last: (arr: any[]) => arr[arr.length - 1], sum: (arr: number[]) => arr.reduce((a, b) => a + b, 0) }) await jexl.eval('square(5)') // 25 await jexl.eval('reverse("hello")') // "olleh" await jexl.eval('sum([1, 2, 3, 4, 5])') // 15 await jexl.eval('first([10, 20, 30])') // 10 // Combine with context const context = { scores: [85, 92, 78, 95, 88] } await jexl.eval('sum(scores) / scores|length', context) // 87.6 ``` -------------------------------- ### Set Operations in TypeScript Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/README.md Provides examples of set operations like concatenation, union, intersection, and difference. These functions are useful for combining, comparing, and filtering sets of data. ```TypeScript await jexl.eval('concat([1, 2], [3, 4])') ``` ```TypeScript await jexl.eval('union([1, 2], [2, 3])') ``` ```TypeScript await jexl.eval('intersection([1, 2, 3], [2, 3, 4])') ``` ```TypeScript await jexl.eval('difference([1, 2, 3], [2, 4])') ``` -------------------------------- ### Register JEXL Language in Monaco Editor (TypeScript) Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/schemas/README.md This function registers a custom JEXL language in Monaco Editor with autocompletion suggestions based on the array library schema functions. It depends on Monaco Editor and the JEXL schemas module. Input is none; output is a registered language provider. Limitations include reliance on the schema's function definitions and Monaco's API. ```typescript import * as monaco from 'monaco-editor' import { arrayLibrarySchema } from '@pawel-up/jexl/schemas/schemas/array.schema.js' // Monaco Editor autocompletion export function registerJexlLanguage() { monaco.languages.register({ id: 'jexl' }) monaco.languages.registerCompletionItemProvider('jexl', { provideCompletionItems: () => { const suggestions = Object.values(arrayLibrarySchema.functions).map((func) => ({ label: func.name, kind: monaco.languages.CompletionItemKind.Function, detail: func.description, documentation: { value: [ `**${func.name}**(${func.parameters.map((p) => `${p.name}: ${p.type}`).join(', ')}) → ${func.returns.type}`, '', func.description, '', ...(func.examples ? ['**Examples:**', ...func.examples.map((ex) => `\`${ex}\``)] : []), ].join('\n'), }, insertText: func.name, })) return { suggestions } }, }) } ``` -------------------------------- ### Register Functions from Schema at Runtime (TypeScript) Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/schemas/README.md This function dynamically registers JEXL functions based on the schema, adding metadata for introspection. It requires JEXL instance, schemas, and array functions module. Input is a JEXL object; output is registered functions with schema metadata. Limitations: Assumes functions exist in the array module and schema is accurate. ```typescript import { arrayLibrarySchema } from '@pawel-up/jexl/schemas/schemas/array.schema.js' import * as arrayFunctions from './array' // Dynamically register functions based on schema export function registerFunctionsFromSchema(jexl: any) { Object.entries(arrayLibrarySchema.functions).forEach(([name, schema]) => { const func = (arrayFunctions as any)[name] if (func) { jexl.addFunction(name, func) // Add metadata for runtime introspection func._schema = schema func._category = schema.category func._parameters = schema.parameters func._returns = schema.returns } }) } ``` -------------------------------- ### Create and Validate Function Call Schema (TypeScript) Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/schemas/README.md These functions create a JSON schema for validating function calls and validate arguments using Ajv, based on the array library schema. Dependencies include JEXL schemas and Ajv library. Inputs are function name and arguments; outputs are schema object and validation result. Limitations: Assumes valid schema and handles variadic parameters up to a point. ```typescript import { arrayLibrarySchema } from '@pawel-up/jexl/schemas/schemas/array.schema.js' import Ajv from 'ajv' // Create JSON Schema for function call validation export function createFunctionCallSchema(functionName: string) { const func = arrayLibrarySchema.functions[functionName] if (!func) throw new Error(`Function ${functionName} not found`) return { type: 'object', properties: { function: { const: functionName }, arguments: { type: 'array', items: func.parameters.map((param) => ({ type: param.type === 'any' ? undefined : param.type, description: param.description, })), minItems: func.parameters.filter((p) => p.required).length, maxItems: func.parameters.some((p) => p.variadic) ? undefined : func.parameters.length, }, }, required: ['function', 'arguments'], } } // Validate function calls export function validateFunctionCall(functionName: string, args: unknown[]) { const schema = createFunctionCallSchema(functionName) const ajv = new Ajv() const validate = ajv.compile(schema) return validate({ function: functionName, arguments: args }) } ``` -------------------------------- ### Add Namespaced Transform - TypeScript Source: https://github.com/pawel-up/jexl/blob/main/README.md Shows how to add namespaced transform functions for better organization. Examples include Math.multiply and String.upper transforms with TypeScript type annotations. ```typescript jexl.addTransform('Math.multiply', (val: number, factor: number): number => val * factor) jexl.addTransform('String.upper', (val: string): string => val.toUpperCase()) ``` -------------------------------- ### Add custom functions in JEXL (TypeScript) Source: https://context7.com/pawel-up/jexl/llms.txt Shows how to add custom functions that can be called within JEXL expressions. Includes examples for mathematical operations, string manipulation, array processing, business logic, and async operations. Functions support multiple arguments and default parameters. ```typescript const jexl = new Jexl() // Mathematical functions jexl.addFunction('max', (...args: number[]) => Math.max(...args)) jexl.addFunction('min', (...args: number[]) => Math.min(...args)) await jexl.eval('max(10, 25, 5, 30, 15)') // 30 await jexl.eval('min(10, 25, 5, 30, 15)') // 5 // String functions jexl.addFunction('concat', (...strings: string[]) => strings.join('')) await jexl.eval('concat("Hello", " ", "World", "!")') // "Hello World!" jexl.addFunction('slugify', (text: string) => text.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') ) await jexl.eval('slugify("Hello World! This is a Test")') // "hello-world-this-is-a-test" // Array functions jexl.addFunction('average', (arr: number[]) => arr.reduce((sum, val) => sum + val, 0) / arr.length ) const context = { scores: [85, 92, 78, 95, 88] } await jexl.eval('average(scores)', context) // 87.6 // Business logic functions jexl.addFunction('calculateTax', (amount: number, rate = 0.08) => Math.round(amount * rate * 100) / 100 ) jexl.addFunction('applyDiscount', (price: number, discountPercent: number) => price * (1 - discountPercent / 100) ) await jexl.eval('calculateTax(1000, 0.085)') // 85 await jexl.eval('calculateTax(applyDiscount(1000, 15), 0.08)') // 68 // Async functions jexl.addFunction('fetchUser', async (userId: number) => { await new Promise(resolve => setTimeout(resolve, 100)) return { id: userId, name: `User ${userId}`, email: `user${userId}@example.com` } }) await jexl.eval('fetchUser(123)') // { id: 123, name: 'User 123', email: 'user123@example.com' } ``` -------------------------------- ### Add custom transforms in JEXL (TypeScript) Source: https://context7.com/pawel-up/jexl/llms.txt Demonstrates adding custom transform functions that process values using JEXL's pipe operator. Includes examples for string manipulation, mathematical operations, array processing, and async operations. Transforms can be chained and accept arguments. ```typescript const jexl = new Jexl() // Simple transform without arguments jexl.addTransform('upper', (val: string) => val.toUpperCase()) await jexl.eval('"hello"|upper') // "HELLO" // Transform with arguments jexl.addTransform('multiply', (val: number, factor: number) => val * factor) await jexl.eval('5|multiply(3)') // 15 jexl.addTransform('truncate', (str: string, length: number) => str.length > length ? str.slice(0, length) + '...' : str ) await jexl.eval('"Hello World"|truncate(5)') // "Hello..." // Array transforms jexl.addTransform('sum', (arr: number[]) => arr.reduce((a, b) => a + b, 0)) jexl.addTransform('map', (arr: any[], property: string) => arr.map(item => item[property])) const context = { orders: [ { id: 1, total: 150 }, { id: 2, total: 89.99 }, { id: 3, total: 234.5 } ] } await jexl.eval('orders|map("total")|sum', context) // 474.49 // Chaining transforms jexl.addTransform('sort', (arr: any[]) => [...arr].sort()) jexl.addTransform('reverse', (arr: any[]) => [...arr].reverse()) await jexl.eval('[3, 1, 4, 2]|sort|reverse') // [4, 3, 2, 1] // Async transforms jexl.addTransform('fetchUserData', async (userId: number) => { // Simulate API call await new Promise(resolve => setTimeout(resolve, 100)) return { id: userId, name: `User ${userId}`, active: true } }) await jexl.eval('123|fetchUserData') // { id: 123, name: 'User 123', active: true } ``` -------------------------------- ### Add Namespaced Function - TypeScript Source: https://github.com/pawel-up/jexl/blob/main/README.md Illustrates adding a namespaced utility function with TypeScript type safety. The example demonstrates a slugify function for strings with explicit string type annotations. ```typescript jexl.addFunction('Utils.String.slugify', (text: string): string => text .toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/^-|-$/g, '') ) ``` -------------------------------- ### Initialize and Evaluate Basic Jexl Expressions Source: https://context7.com/pawel-up/jexl/llms.txt Demonstrates initializing a Jexl instance and performing basic expression evaluations, including arithmetic and context-based data access. It shows how to access nested properties and filter arrays based on conditions. ```typescript import { Jexl } from '@pawel-up/jexl' const jexl = new Jexl() // Basic expression evaluation const result = await jexl.eval('2 + 3 * 4') console.log(result) // 14 // Evaluation with context const context = { user: { name: 'John Doe', age: 30 }, orders: [ { id: 1, total: 150, status: 'completed' }, { id: 2, total: 89.99, status: 'pending' } ] } const userName = await jexl.eval('user.name', context) console.log(userName) // "John Doe" const completedOrders = await jexl.eval('orders[.status == "completed"]', context) console.log(completedOrders) // [{ id: 1, total: 150, status: 'completed' }] ``` -------------------------------- ### Add selected Jexl functions individually Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/README.md Demonstrates importing specific functions from the extension libraries and registering them manually with a Jexl instance. Useful for reducing bundle size or avoiding naming collisions. ```typescript import { round, avg, sum } from '@pawel-up/jexl/math' import { capitalize, titleCase } from '@pawel-up/jexl/string' import { now, format } from '@pawel-up/jexl/date' const jexl = new Jexl.Jexl() // Add only specific functions jexl.addFunction('round', round) jexl.addFunction('avg', avg) jexl.addFunction('sum', sum) jexl.addFunction('capitalize', capitalize) jexl.addFunction('titleCase', titleCase) jexl.addFunction('now', now) jexl.addFunction('format', format) ``` -------------------------------- ### Add all Jexl extension libraries to a Jexl instance Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/README.md Imports all available Jexl extension modules and registers each function with a Jexl instance using a helper that optionally prefixes function names. No external dependencies beyond the Jexl package itself. ```typescript import { Jexl } from '@pawel-up/jexl' import * as math from '@paw-up/jexl/math.js' import * as string from '@pawel-up/jexl/string.js' import * as date from '@pawel-up/jexl/date.js' import * as array from '@pawel-up/jexl/array.js' import * as operators from '@pawel-up/jexl/operators.js' // Helper function to add all functions from a module function addModule(jexl: Jexl, module: Record, prefix = '') { Object.keys(module).forEach((key) => { const functionName = prefix ? `${prefix}_${key}` : key jexl.addFunction(functionName, module[key]) }) } const jexl = new Jexl() // Add all libraries addModule(jexl, math) addModule(jexl, string) addModule(jexl, date) addModule(jexl, array) addModule(jexl, operators) // Or add with prefixes to avoid naming conflicts // addModule(jexl, math, 'math'); // addModule(jexl, string, 'str'); ``` -------------------------------- ### Namespace Functions and Transforms in JavaScript Source: https://github.com/pawel-up/jexl/blob/main/examples/README.md Implement namespaced functions and transforms using dot notation for better organization. Supports hierarchical namespaces, chaining transforms, and mixed usage with regular functions. Dependencies include jexl library loaded in the environment. ```javascript // Add namespace functions jexl.addFunction('Math.max', (a, b) => Math.max(a, b)) jexl.addFunction('Utils.String.slugify', (text) => text .toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/^-|-$/g, '') ) // Add namespace transforms jexl.addTransform('String.upper', (val) => val.toUpperCase()) jexl.addTransform('Array.unique', (arr) => [...new Set(arr)]) // Use namespace functions await jexl.eval('Math.max(10, 25)') await jexl.eval('Utils.String.slugify("Hello World!")') // Use namespace transforms await jexl.eval('"hello"|String.upper') await jexl.eval('[1,2,2,3,3,3]|Array.unique') // Chain namespace transforms await jexl.eval('" hello world "|String.upper|String.reverse') ``` -------------------------------- ### Jexl compile() - Compile Expressions for Performance Source: https://context7.com/pawel-up/jexl/llms.txt Demonstrates how to use the `compile()` method to pre-parse expressions for improved performance when evaluating the same expression multiple times with different contexts. This is useful for frequently used or complex expressions. ```typescript const jexl = new Jexl() // Compile expression once const compiled = jexl.compile('user.orders | length') // Evaluate with different contexts (no re-parsing) await compiled.eval({ user: { orders: [1, 2, 3] } }) // 3 await compiled.eval({ user: { orders: [1, 2] } }) // 2 await compiled.eval({ user: { orders: [] } }) // 0 // Complex expression compilation const filterExpr = jexl.compile('items[price > threshold && inStock == true]') const context1 = { items: [ { name: 'Laptop', price: 1200, inStock: true }, { name: 'Mouse', price: 25, inStock: false }, { name: 'Monitor', price: 300, inStock: true } ], threshold: 100 } await filterExpr.eval(context1) // [{ name: 'Laptop', price: 1200, inStock: true }, { name: 'Monitor', price: 300, inStock: true }] const context2 = { items: [{ name: 'Keyboard', price: 80, inStock: true }], threshold: 50 } await filterExpr.eval(context2) // [{ name: 'Keyboard', price: 80, inStock: true }] ``` -------------------------------- ### Add Transform with TypeScript - TypeScript Source: https://github.com/pawel-up/jexl/blob/main/README.md Demonstrates how to add a transform function with TypeScript type safety. The example shows a multiply transform function with explicit number types for inputs and output. ```typescript jexl.addTransform('multiply', (val: number, factor: number): number => val * factor) ``` -------------------------------- ### User Profile Processing with Jexl Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/README.md Demonstrates user profile processing using Jexl expressions in TypeScript. Shows how to format display names, check user roles, calculate age, safely access properties, and generate initials. Requires a userContext object with user data structure. ```typescript const userContext = { user: { firstName: 'john', lastName: 'doe', email: 'john.doe@company.com', birthDate: new Date('1990-05-15'), roles: ['user', 'contributor'], profile: { bio: 'Software developer with 5+ years of experience', preferences: { theme: 'dark', notifications: true, }, }, }, } // Format user display name await jexl.eval('titleCase(user.firstName + " " + user.lastName)', userContext) // "John Doe" // Check if user is admin await jexl.eval('inOp("admin", user.roles)', userContext) // false // Calculate age await jexl.eval('getAge(user.birthDate)', userContext) // 35 // Safe property access await jexl.eval('safeGet(user, "profile.preferences.theme")', userContext) // "dark" // Generate initials await jexl.eval('initials(user.firstName + " " + user.lastName)', userContext) // "JD" ``` -------------------------------- ### Get Transform Function from Jexl Source: https://github.com/pawel-up/jexl/blob/main/README.md Retrieves previously registered transform function by name. Returns function if exists, undefined otherwise. Useful for checking if transforms are available or reusing existing transforms. ```javascript jexl.getTransform(name) ``` -------------------------------- ### Advanced Transforms with XML in Jexl (JavaScript) Source: https://github.com/pawel-up/jexl/blob/main/README.md This example illustrates advanced transforms by integrating external libraries like xml2json to parse XML into JSON for traversal. It adds an 'xml' transform and evaluates nested properties; requires the xml2json module and XML data in context. Outputs transformed objects; limited to successful parsing and does not handle XML schema validation. ```javascript const xml2json = require('xml2json') jexl.addTransform('xml', (val) => xml2json.toJson(val, { object: true })) const context = { xmlDoc: ` Cheryl Tunt Cyril Figgis `, } var expr = 'xmlDoc|xml.Employees.Employee[.LastName == "Figgis"].FirstName' jexl.eval(expr, context).then(console.log) // Output: Cyril ``` -------------------------------- ### Date and Time Operations with Jexl Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/README.md Shows date and time operations using Jexl expressions in TypeScript. Includes date formatting, duration calculations, weekend checking, and date arithmetic. Requires dateContext with startDate, endDate, and events array containing date objects. ```typescript const dateContext = { startDate: new Date('2025-01-01'), endDate: new Date('2025-12-31'), events: [ { name: 'Conference', date: new Date('2025-06-15') }, { name: 'Workshop', date: new Date('2025-08-20') }, ], } // Format dates await jexl.eval('format(startDate, "MMMM DD, YYYY")', dateContext) // "January 01, 2025" // Calculate duration await jexl.eval('diffDays(startDate, endDate)', dateContext) // 364 // Check if event is on weekend await jexl.eval('isWeekend(events[0].date)', dateContext) // true/false // Get quarter start await jexl.eval('startOfMonth(addMonths(startDate, 3))', dateContext) // April 1, 2025 ``` -------------------------------- ### Slugify String Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/README.md This endpoint converts a string to a slug (URL-friendly format). It utilizes the `slug` function from the Jexl library. ```APIDOC ## POST /string/slugify ### Description Converts a string to a slug (URL-friendly format). ### Method POST ### Endpoint /string/slugify ### Parameters #### Path Parameters - **None** #### Query Parameters - **None** #### Request Body - **val** (string) - Required - The string to slugify. ### Request Example { "val": "This is a string to slugify!" } ### Response #### Success Response (200) - **slug** (string) - The slugified string. #### Response Example { "slug": "this-is-a-string-to-slugify" } ``` -------------------------------- ### Data Validation and Processing with Jexl Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/README.md Illustrates data validation and processing techniques using Jexl expressions in TypeScript. Covers statistical calculations, email validation with regex, and product data processing. Requires dataContext with scores, emails, and products arrays. ```typescript const dataContext = { scores: [85, 92, 78, 96, 88, 91], emails: ['user1@test.com', 'invalid-email', 'user2@company.org'], products: [ { name: 'laptop', price: 999.99, inStock: true }, { name: 'mouse', price: 29.99, inStock: false }, { name: 'keyboard', price: 79.99, inStock: true }, ], } // Calculate statistics await jexl.eval('avg(scores)', dataContext) // 88.33 await jexl.eval('max(scores)', dataContext) // 96 await jexl.eval('stddev(scores)', dataContext) // 6.26 // Validate emails await jexl.eval('regex(emails[0], "^[^@]+@[^@]+\\.[^@]+$")', dataContext) // true // Process product data await jexl.eval('sum(products.*.price)', dataContext) // Would need custom transform // Alternative: sum([999.99, 29.99, 79.99]) = 1109.97 ``` -------------------------------- ### Use Math functions in Jexl expressions Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/README.md Shows how to evaluate a variety of mathematical operations, statistical calculations, and utility functions using Jexl's eval method after the math library has been added. ```typescript await jexl.eval('abs(-5)') // 5 await jexl.eval('round(3.7)') // 4 await jexl.eval('max(1, 5, 3)') // 5 await jexl.eval('sqrt(16)') // 4 await jexl.eval('sum([1, 2, 3, 4])') // 10 await jexl.eval('sum(1, 2, 3, 4)') // 10 (spread arguments) await jexl.eval('avg([10, 20, 30])') // 20 await jexl.eval('median([1, 3, 2, 5, 4])') // 3 await jexl.eval('variance([1, 2, 3, 4, 5])') // 2 await jexl.eval('stddev([1, 2, 3, 4, 5])') // 1.58... await jexl.eval('mode([1, 2, 2, 3, 2])') // 2await jexl('clamp(15, 0, 10)') // 10 await jexl.eval('lerp(0, 100, 0.5)') // 50 await jexl.eval('toRadians(180)') // 3.14159... await jexl.eval('factorial(5)') // 120 await jexl.eval('isPrime(17)') // true ``` -------------------------------- ### Use String functions in Jexl expressions Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/README.md Illustrates various string transformation, case conversion, manipulation, and validation utilities provided by the string library when used within Jexl expressions. ```typescript await jexl.eval('upper("hello")') // "HELLO" await jexl.eval('lower("WORLD")') // "world" await jexl.eval('capitalize("hello world")') // "Hello world" await jexl.eval('titleCase("hello world")') // "Hello World" await jexl.eval('camelCase("hello world")') // "helloWorld" await jexl.eval('pascalCase("hello world")') // "HelloWorld" await jexl.eval('snakeCase("Hello World")') // "hello_world" await jexl.eval('kebabCase("Hello World")') // "hello-world" await jexl.eval('truncate("long text", 5)') // "lo..." await jexl.eval('reverse("hello")') // "olleh" await jexl.eval('mask("password123", "*", 2, 2)') // "pa*******23" await jexl.eval('slug("Hello World!")') // "hello-world" await jexl.eval('startsWith("hello", "he")') // true await jexl.eval('contains("hello world", "wor")') // true await jexl.eval('isEmpty("")') // true await jexl.eval('wordCount("hello world")') // 2 ``` -------------------------------- ### HR Performance Analysis in JavaScript Source: https://github.com/pawel-up/jexl/blob/main/examples/README.md Implement HR systems functionality for employee management and performance analysis using Jexl expressions. Maps employee data to calculate years of service and extract current performance ratings. Dependencies include employee data with startDate and performance arrays. ```javascript // HR performance analysis await jexl.eval( ` employees.map(e => { name: e.name, yearsOfService: yearsOfService(e.startDate, company.currentYear), currentRating: e.performance[e.performance.length - 1].rating }) `, context ) ``` -------------------------------- ### Real-world E-commerce Filtering in JavaScript Source: https://github.com/pawel-up/jexl/blob/main/examples/README.md Apply Jexl expressions for practical e-commerce scenarios including product filtering by category, price range, and stock status. Requires context object containing products array and filters object with filtering criteria. ```javascript // E-commerce product filtering await jexl.eval( ` products[ .category == filters.category && .price >= filters.minPrice && .inStock == true ] `, context ) ``` -------------------------------- ### Namespace Transforms with Arguments in JEXL (JavaScript) Source: https://github.com/pawel-up/jexl/blob/main/README.md Shows transforms supporting multiple arguments like String.padStart and Array.slice, registered via jexl.addTransform. JEXL dependency; inputs include values and params, outputs padded strings or array slices. Arguments must match transform signature; no default values. ```javascript // Transforms with multiple arguments jexl.addTransform('String.padStart', (val, length, padString) => val.padStart(length, padString)) jexl.addTransform('Array.slice', (arr, start, end) => arr.slice(start, end)) // Usage with arguments await jexl.eval('"5"|String.padStart(3, "0")') // "005" await jexl.eval('[1,2,3,4,5]|Array.slice(1, 4)') // [2,3,4] ``` -------------------------------- ### Registering and Using Basic Namespace Transforms in JEXL (JavaScript) Source: https://github.com/pawel-up/jexl/blob/main/README.md This snippet demonstrates registering namespace transforms like String.upper and Utils.Text.capitalize using jexl.addTransform. It requires the JEXL library and shows evaluation of expressions with pipe operators for transforming strings and dates. Outputs are uppercase, lowercase, repeated, capitalized, or ISO-formatted strings; limitations include single-value inputs only. ```javascript // Register namespace transforms jexl.addTransform('String.upper', (val) => val.toUpperCase()) jexl.addTransform('String.lower', (val) => val.toLowerCase()) jexl.addTransform('String.repeat', (val, times) => val.repeat(times)) jexl.addTransform('Utils.Text.capitalize', (text) => text.charAt(0).toUpperCase() + text.slice(1).toLowerCase()) jexl.addTransform('Format.Date.iso', (date) => new Date(date).toISOString()) // Use namespace transforms in expressions await jexl.eval('"hello world"|String.upper') // "HELLO WORLD" await jexl.eval('"HELLO WORLD"|String.lower') // "hello world" await jexl.eval('"hi"|String.repeat(3)') // "hihihi" await jexl.eval('"hello world"|Utils.Text.capitalize') // "Hello world" await jexl.eval('"2024-01-01"|Format.Date.iso') // "2024-01-01T00:00:00.000Z" ``` -------------------------------- ### Convert to Uppercase Source: https://github.com/pawel-up/jexl/blob/main/src/definitions/README.md This endpoint converts a string to uppercase. ```APIDOC ## POST /string/upper ### Description Converts a string to uppercase. ### Method POST ### Endpoint /string/upper ### Parameters #### Path Parameters - **None** #### Query Parameters - **None** #### Request Body - **val** (string) - Required - The string to convert. ### Request Example { "val": "this is a string" } ### Response #### Success Response (200) - **uppercaseString** (string) - The uppercase converted string. #### Response Example { "uppercaseString": "THIS IS A STRING" } ```