| 6 | import type { DataModel, LLMConfig, QueryDialect, TranslationResult } from '../types'; |
| 7 | |
| 8 | export class JavaScriptDialect implements QueryDialect { |
| 9 | readonly id = 'javascript'; |
| 10 | |
| 11 | readonly rules = `Code runs as a synchronous script with fresh copies of the loaded data. Assign the final output to a variable named result. Use the supplied data and helpers; avoid external files, network access and module loading. |
| 12 | You have access to a "data" array and a "stat" object with helper functions: |
| 13 | - stat.groupBy(arr, key) - Group array by key |
| 14 | - stat.sum(arr, key) - Sum values by key |
| 15 | - stat.avg(arr, key) - Average values by key |
| 16 | - stat.max(arr, key) - Max value by key |
| 17 | - stat.min(arr, key) - Min value by key |
| 18 | - stat.median(arr, key) - Median value by key |
| 19 | - stat.variance(arr, key) - Variance by key |
| 20 | - stat.stdDev(arr, key) - Standard deviation by key |
| 21 | - stat.distinct(arr, key) - Unique values by key |
| 22 | - stat.count(arr) - Count items |
| 23 | - stat.sortBy(arr, key, order) - Sort array ('asc' or 'desc') |
| 24 | - stat.filter(arr, predicate) - Filter array by condition |
| 25 | - stat.first(arr) - Get first element |
| 26 | - stat.last(arr) - Get last element |
| 27 | |
| 28 | Examples: |
| 29 | |
| 30 | 1. Grouping and aggregation: |
| 31 | const grouped = stat.groupBy(data, 'region'); |
| 32 | const result = Object.keys(grouped).map(region => ({ |
| 33 | region, |
| 34 | avgRevenue: stat.avg(grouped[region], 'revenue'), |
| 35 | totalSales: stat.sum(grouped[region], 'sales') |
| 36 | })); |
| 37 | |
| 38 | 2. Statistical analysis: |
| 39 | const result = { |
| 40 | mean: stat.avg(data, 'value'), |
| 41 | median: stat.median(data, 'value'), |
| 42 | stdDev: stat.stdDev(data, 'value') |
| 43 | }; |
| 44 | |
| 45 | 3. Filtering and sorting: |
| 46 | const filtered = stat.filter(data, item => item.score > 80); |
| 47 | const result = stat.sortBy(filtered, 'score', 'desc'); |
| 48 | |
| 49 | 4. Finding unique values and counts: |
| 50 | const categories = stat.distinct(data, 'category'); |
| 51 | const result = categories.map(cat => ({ |
| 52 | category: cat, |
| 53 | count: stat.count(stat.filter(data, item => item.category === cat)) |
| 54 | })); |
| 55 | |
| 56 | 5. Getting boundary elements: |
| 57 | const result = { |
| 58 | firstEntry: stat.first(data), |
| 59 | lastEntry: stat.last(data), |
| 60 | topScorer: stat.first(stat.sortBy(data, 'score', 'desc')) |
| 61 | };`; |
| 62 | |
| 63 | constructor(private readonly llmConfig: LLMConfig) {} |
| 64 | |
| 65 | async getDSL(query: string, dataModel: DataModel): Promise<TranslationResult> { |
nothing calls this directly
no outgoing calls
no test coverage detected