{"id":13007,"library":"cql-execution","title":"CQL Execution Framework","description":"cql-execution is a TypeScript/JavaScript library providing an execution framework for Clinical Quality Language (CQL) artifacts expressed as JSON ELM. Currently at stable version 3.3.0, the library focuses on the logical constructs of CQL, allowing for integration with external data model providers (`PatientSource` implementations) and terminology services (`CodeService` implementations), rather than implementing these directly. A significant architectural shift occurred in version 3.0.0, introducing an asynchronous execution flow that enables `PatientSource` and `CodeService` calls to leverage web services and databases more effectively. Subsequent releases have primarily focused on improving alignment with CQL 1.5 specifications, enhancing support for CodeSystems and ValueSets, and refining operator behaviors. The project maintains an active release cadence with regular minor updates addressing bug fixes and specification alignment. Its key differentiator is a lean, extensible core for CQL execution, delegating data and terminology specifics to companion libraries like `cqm-execution`, `cql-exec-fhir`, and `cql-exec-vsac`.","status":"active","version":"3.3.0","language":"javascript","source_language":"en","source_url":"https://github.com/cqframework/cql-execution","tags":["javascript","CQL","HL7","MITRE","CQM","typescript"],"install":[{"cmd":"npm install cql-execution","lang":"bash","label":"npm"},{"cmd":"yarn add cql-execution","lang":"bash","label":"yarn"},{"cmd":"pnpm add cql-execution","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Provides a FHIR-based data source for the execution engine. Often used together for FHIR-based CQL logic.","package":"cql-exec-fhir","optional":true},{"reason":"Provides a VSAC-enabled terminology service for looking up value sets. Often used together for terminology resolution.","package":"cql-exec-vsac","optional":true},{"reason":"A project built on cql-execution for executing electronic Clinical Quality Measures (eCQMs) using the QDM data model.","package":"cqm-execution","optional":true}],"imports":[{"note":"The primary class for executing ELM against data and terminology services. ESM import is standard, CJS is often problematic since v3.","wrong":"const Executor = require('cql-execution').Executor;","symbol":"Executor","correct":"import { Executor } from 'cql-execution';"},{"note":"An interface for providing patient data to the Executor. While referred to as `DataProvider` in some docs, the exported interface is `PatientSource`. Implementations must be asynchronous since v3.0.0.","wrong":"import { DataProvider } from 'cql-execution';","symbol":"PatientSource","correct":"import { PatientSource } from 'cql-execution';"},{"note":"An interface for providing terminology services (e.g., ValueSet resolution) to the Executor. Referred to as `TerminologyProvider` in some docs, the exported interface is `CodeService`. Implementations must be asynchronous since v3.0.0.","wrong":"import { TerminologyProvider } from 'cql-execution';","symbol":"CodeService","correct":"import { CodeService } from 'cql-execution';"}],"quickstart":{"code":"import { Executor, PatientSource, CodeService } from 'cql-execution';\n\n// 1. Define a simple ELM library (JSON representation of CQL)\nconst elm = {\n  library: {\n    identifier: { id: 'MyLibrary', version: '1.0.0' },\n    statements: {\n      def: [\n        {\n          name: 'TrueExpression',\n          context: 'Patient',\n          expression: { type: 'Literal', valueType: '{http://www.w3.org/2001/XMLSchema}boolean', value: 'true' }\n        },\n        {\n          name: 'PatientAge',\n          context: 'Patient',\n          expression: {\n            type: 'AgeInYears',\n            operand: {\n              type: 'SingletonFrom',\n              operand: {\n                type: 'Retrieve',\n                dataType: '{http://hl7.org/fhir/R4}Patient'\n              }\n            }\n          }\n        }\n      ]\n    }\n  }\n};\n\n// 2. Implement a mock PatientSource (DataProvider)\nclass MockPatientSource implements PatientSource {\n  private patients: any[];\n  constructor(patients: any[]) {\n    this.patients = patients;\n  }\n  async currentPatient(): Promise<any> { return this.patients[0]; }\n  async nextPatient(): Promise<any | undefined> { \n    this.patients.shift();\n    return this.patients[0];\n  }\n  async retrieve(patientId: string, dataType: string, template: string, codes: any[], dateRange: any): Promise<any[]> {\n    if (dataType === '{http://hl7.org/fhir/R4}Patient') {\n      // Mock patient data for AgeInYears calculation. Real impl would query a data source.\n      return [{ birthDate: '1990-01-01' }]; \n    }\n    return [];\n  }\n  async loadPatients(): Promise<void> { /* no-op for mock */ }\n  getPatientSourceIterator(): AsyncIterator<any> {\n    let index = 0;\n    const patients = this.patients;\n    return {\n      next: async () => {\n        if (index < patients.length) {\n          const value = patients[index++];\n          return { value, done: false };\n        } else {\n          return { value: undefined, done: true };\n        }\n      }\n    };\n  }\n  count(): number { return this.patients.length; }\n}\n\n// 3. Implement a mock CodeService (TerminologyProvider)\nclass MockCodeService implements CodeService {\n  async findValueSet(valueSetUrl: string, version?: string): Promise<any> { return { codes: [] }; }\n  async findCodes(code: any): Promise<any> { return []; }\n  async resolveValueSet(valueSet: any): Promise<any> { return { codes: [] }; }\n}\n\nasync function executeCql() {\n  const patientSource = new MockPatientSource([{ id: 'patient1', birthDate: '1990-01-01' }]);\n  const codeService = new MockCodeService();\n\n  const executor = new Executor(elm);\n  const results = await executor.execute(patientSource, codeService, {\n    // `executionDateTime` is crucial for date-related CQL operations.\n    executionDateTime: '2025-01-01T12:00:00Z',\n    verbose: true\n  });\n\n  console.log('Results for Patient 1:');\n  for (const patientId in results.patientResults) {\n    const patientResults = results.patientResults[patientId];\n    console.log(`  Patient ID: ${patientId}`);\n    console.log(`  TrueExpression: ${patientResults.TrueExpression}`);\n    console.log(`  PatientAge: ${patientResults.PatientAge}`);\n  }\n}\n\nexecuteCql().catch(console.error);","lang":"typescript","description":"Demonstrates how to load a simple ELM library, create mock `PatientSource` and `CodeService` implementations, and execute basic CQL logic for a single patient using the asynchronous execution engine."},"warnings":[{"fix":"Update all `PatientSource` and `CodeService` methods to be `async` and return `Promise` objects. Ensure `await` is used when calling these methods within the `Executor`.","message":"Version 3.0.0 introduced a significant breaking change by shifting the execution flow to be entirely asynchronous. All methods in custom `PatientSource` (formerly `DataProvider`) and `CodeService` (formerly `TerminologyProvider`) implementations must now return Promises. Code relying on synchronous data or terminology access will fail.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Replace `executor.exec(...)` with `executor.execute(...)` in your application code.","message":"In version 3.0.1, the core execution method was renamed from `exec` to `execute` for improved consistency. Direct calls to `executor.exec(...)` will no longer work.","severity":"breaking","affected_versions":">=3.0.1"},{"fix":"Be aware of these inherent JavaScript numerical limitations when writing CQL involving precise decimal calculations or large integers. Consider external validation for critical numerical results.","message":"Due to JavaScript's `Number` class being used for both CQL `Integer` and `Decimal` types, `cql-execution` may exhibit reduced precision and floating-point arithmetic issues, potentially treating decimals without a fractional part (e.g., `2.0`) as CQL `Integer`s.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Carefully review the changelogs and documentation for each new version, especially when upgrading minor or major releases, and adapt your custom implementations accordingly.","message":"The `PatientSource`, `CodeService`, and `Results` APIs are explicitly noted as evolving and subject to change. This means that minor or major version updates may introduce breaking changes to these interfaces or their expected behavior.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Consult the `CQL_Execution_Features.xlsx` spreadsheet (available in the GitHub repository) for a detailed list of supported features and avoid using unsupported CQL constructs in your ELM.","message":"The library does not fully implement all features of CQL 1.4 and 1.5. Key unsupported features include the `Long` datatype, fluent functions, retrieve search paths/includes, related context retrieves, unfiltered context retrieves, unfiltered context references to other libraries, and external functions.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Be prepared to use type assertions (`as any`) or augment types where necessary. Refer to the library's JavaScript source code for the definitive API structure in cases of ambiguous typing.","message":"Despite being written in TypeScript, the library does not yet have full-fledged type definitions across all modules. This may lead to situations where type `any` is inferred or specific type definitions are missing, potentially reducing TypeScript's compile-time safety.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Update the execution call from `executor.exec(...)` to `executor.execute(...)`.","cause":"Attempting to use the deprecated `exec` method for execution, which was renamed to `execute` in v3.0.1.","error":"TypeError: executor.exec is not a function"},{"fix":"Ensure all methods within your `PatientSource` and `CodeService` implementations are declared `async` and explicitly return `Promise` objects, even if the internal operation is synchronous (e.g., `return Promise.resolve(data);`).","cause":"Your custom `PatientSource` (or `CodeService`) implementation is not an `async` function and/or not returning a `Promise` for its methods, a requirement since v3.0.0.","error":"TypeError: patientSource.currentPatient is not a function"},{"fix":"Examine the `AnnotatedError` message for the specific CQL expression and location. Debug your CQL logic and verify the patient data or terminology provided to the `Executor`.","cause":"A runtime error occurred during CQL expression evaluation, often due to unexpected `null` or `undefined` data, an unsupported operation, or malformed ELM. The error message indicates the exact ELM path.","error":"AnnotatedError: Encountered unexpected error at Library.MyLibrary.1.0.0.TrueExpression: Cannot read properties of undefined (reading 'value')"},{"fix":"Switch to ESM `import` statements: `import { Executor } from 'cql-execution';`. Ensure your project's build configuration or Node.js environment is set up for ESM.","cause":"Attempting to use CommonJS `require()` syntax to import `cql-execution` in an ECMAScript Module (ESM) environment (e.g., a modern Node.js project with `\"type\": \"module\"` or browser bundlers).","error":"ReferenceError: require is not defined"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null,"cli_name":""}