{"version":3,"sources":["../src/index.ts","../src/SDCPopulateQuestionnaireOperation/utils/typePredicates.ts","../src/SDCPopulateQuestionnaireOperation/utils/operationOutcome.ts","../src/SDCPopulateQuestionnaireOperation/api/fetchQuestionnaire.ts","../src/SDCPopulateQuestionnaireOperation/utils/createFhirPathContext.ts","../src/globals.ts","../src/SDCPopulateQuestionnaireOperation/utils/emptyResource.ts","../src/SDCPopulateQuestionnaireOperation/utils/createContextTuples.ts","../src/SDCPopulateQuestionnaireOperation/utils/readPopulationExpressions.ts","../src/SDCPopulateQuestionnaireOperation/utils/evaluateExpressions.ts","../src/SDCPopulateQuestionnaireOperation/utils/codingProperties.ts","../src/SDCPopulateQuestionnaireOperation/utils/processValueSets.ts","../src/SDCPopulateQuestionnaireOperation/utils/constructResponse.ts","../src/SDCPopulateQuestionnaireOperation/utils/createQuestionnaireReference.ts","../src/SDCPopulateQuestionnaireOperation/utils/answerOption.ts","../src/SDCPopulateQuestionnaireOperation/utils/parse.ts","../src/SDCPopulateQuestionnaireOperation/api/defaultTerminologyRequest.ts","../src/SDCPopulateQuestionnaireOperation/api/expandValueSet.ts","../src/SDCPopulateQuestionnaireOperation/utils/humanName.ts","../src/SDCPopulateQuestionnaireOperation/utils/createOutputParameters.ts","../src/SDCPopulateQuestionnaireOperation/utils/misc.ts","../src/SDCPopulateQuestionnaireOperation/utils/genericRecursive.ts","../src/SDCPopulateQuestionnaireOperation/utils/removeEmptyAnswers.ts","../src/SDCPopulateQuestionnaireOperation/api/lookupCodeSystem.ts","../src/SDCPopulateQuestionnaireOperation/utils/resolveLookupPromises.ts","../src/SDCPopulateQuestionnaireOperation/utils/addDisplayToCodings.ts","../src/SDCPopulateQuestionnaireOperation/utils/populate.ts","../src/inAppPopulation/utils/populateQuestionnaire.ts","../src/inAppPopulation/utils/isRecord.ts","../src/inAppPopulation/utils/resolveFhirContexts.ts","../src/inAppPopulation/utils/inputParameters.ts"],"sourcesContent":["/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport * from './SDCPopulateQuestionnaireOperation';\nexport * from './inAppPopulation';\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Parameters, ParametersParameter } from 'fhir/r4';\nimport type {\n  CanonicalParameter,\n  ContextParameter,\n  InputParameters,\n  QuestionnaireDataParameter,\n  SubjectParameter\n} from '../interfaces/inputParameters.interface';\nimport type { OutputParameters, ResponseParameter } from '../interfaces';\n\n/**\n * Checks if the parameters passed satisfies the conditions of populateInputParameters.\n * Returns true if both questionnaire and subject are present.\n *\n * @author Sean Fong\n */\nexport function isInputParameters(parameters: Parameters): parameters is InputParameters {\n  const questionnairePresent = !!parameters.parameter?.find(isQuestionnaireDataParameter);\n\n  const subjectPresent = !!parameters.parameter?.find(isSubjectParameter);\n\n  return questionnairePresent && subjectPresent;\n}\n\n/**\n * Checks if a parameter is a QuestionnaireDataParameter (identifier, questionnaire, or questionnaireRef).\n */\nexport function isQuestionnaireDataParameter(\n  parameter: ParametersParameter\n): parameter is QuestionnaireDataParameter {\n  return (\n    (parameter.name === 'identifier' && !!parameter.valueIdentifier) ||\n    (parameter.name === 'questionnaire' && parameter.resource?.resourceType === 'Questionnaire') ||\n    (parameter.name === 'questionnaireRef' && !!parameter.valueReference)\n  );\n}\n\n/**\n * Checks if a parameter is a CanonicalParameter (has canonical value).\n */\nexport function isCanonicalParameter(\n  parameter: ParametersParameter\n): parameter is CanonicalParameter {\n  return parameter.name === 'canonical' && !!parameter.valueCanonical;\n}\n\n/**\n * Checks if a parameter is a SubjectParameter (has subject reference).\n */\nexport function isSubjectParameter(parameter: ParametersParameter): parameter is SubjectParameter {\n  return parameter.name === 'subject' && !!parameter.valueReference;\n}\n\nexport function isUserContextParameter(\n  parameter: ParametersParameter\n): parameter is ContextParameter {\n  return (\n    parameter.name === 'context' &&\n    parameter.part?.[0]?.name === 'name' &&\n    parameter.part?.[0]?.valueString === 'user' &&\n    parameter.part?.[1]?.name === 'content' &&\n    !!parameter.part?.[1]?.resource\n  );\n}\n\nexport function isEncounterContextParameter(\n  parameter: ParametersParameter\n): parameter is ContextParameter {\n  return (\n    parameter.name === 'context' &&\n    parameter.part?.[0]?.name === 'name' &&\n    parameter.part?.[0]?.valueString === 'encounter' &&\n    parameter.part?.[1]?.name === 'content' &&\n    !!parameter.part?.[1]?.resource\n  );\n}\n\nexport function isContextParameter(parameter: ParametersParameter): parameter is ContextParameter {\n  return (\n    parameter.name === 'context' &&\n    parameter.part?.[0]?.name === 'name' &&\n    !!parameter.part?.[0]?.valueString &&\n    parameter.part?.[1]?.name === 'content' &&\n    !!(parameter.part?.[1]?.resource || parameter.part?.[1]?.valueReference)\n  );\n}\n\nexport function isOutputParameters(parameters: Parameters): parameters is OutputParameters {\n  return !!parameters.parameter?.find(isResponseParameter);\n}\n\nexport function isResponseParameter(\n  parameter: ParametersParameter\n): parameter is ResponseParameter {\n  return (\n    parameter.name === 'response' && parameter.resource?.resourceType === 'QuestionnaireResponse'\n  );\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { OperationOutcome, OperationOutcomeIssue } from 'fhir/r4';\n\n/**\n * Create an OperationOutcome error with a supplied error message\n *\n * @author Sean Fong\n */\nexport function createErrorOutcome(errorMessage: string): OperationOutcome {\n  return {\n    resourceType: 'OperationOutcome',\n    issue: [\n      {\n        severity: 'error',\n        code: 'invalid',\n        details: { text: errorMessage }\n      }\n    ]\n  };\n}\n\n/**\n * Create an OperationOutcome issue of severity \"warning\" and code \"invalid\" with a supplied warning message\n *\n * @author Sean Fong\n */\nexport function createInvalidWarningIssue(warningMessage: string): OperationOutcomeIssue {\n  return {\n    severity: 'warning',\n    code: 'invalid',\n    details: { text: warningMessage }\n  };\n}\n\n/**\n * Create an OperationOutcome issue of severity \"warning\" and code \"not-found\" with a supplied warning message\n *\n * @author Sean Fong\n */\nexport function createNotFoundWarningIssue(warningMessage: string): OperationOutcomeIssue {\n  return {\n    severity: 'warning',\n    code: 'not-found',\n    details: { text: warningMessage }\n  };\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n  FetchResourceCallback,\n  FetchResourceRequestConfig,\n  IdentifierParameter,\n  InputParameters,\n  QuestionnaireRefParameter\n} from '../interfaces';\nimport { isCanonicalParameter } from '../utils';\nimport type { Bundle, OperationOutcome, Questionnaire } from 'fhir/r4';\nimport { createErrorOutcome } from '../utils/operationOutcome';\n\n/**\n * Fetches a Questionnaire resource using input parameters and a callback.\n * Handles canonical, direct, and bundle-based questionnaire retrieval.\n */\nexport async function fetchQuestionnaire(\n  parameters: InputParameters,\n  fetchQuestionnaireCallback: FetchResourceCallback,\n  fetchResourceRequestConfig: FetchResourceRequestConfig\n): Promise<Questionnaire | OperationOutcome> {\n  const questionnaireData = parameters.parameter[0];\n  if (questionnaireData.name === 'questionnaire') {\n    return questionnaireData.resource;\n  }\n\n  const canonicalParam = parameters.parameter.find((param) => isCanonicalParameter(param));\n  const canonical = canonicalParam?.valueCanonical;\n  const query = getQueryString(questionnaireData, canonical);\n  const response: Questionnaire | Bundle | OperationOutcome = await fetchQuestionnaireCallback(\n    query,\n    fetchResourceRequestConfig\n  );\n\n  if (response.resourceType === 'Questionnaire') {\n    // Return response as Questionnaire\n    return response;\n  } else if (response.resourceType === 'Bundle') {\n    // Return first Questionnaire in Bundle\n    const firstQuestionnaire = response.entry?.find(\n      (entry) => entry.resource?.resourceType === 'Questionnaire'\n    )?.resource as Questionnaire | undefined;\n    return (\n      firstQuestionnaire ?? createErrorOutcome(`Unable to fetch questionnaire with query ${query}`)\n    );\n  } else if (response.resourceType === 'OperationOutcome') {\n    // Return response as FHIR OperationOutcomes OperationOutcome\n    return response;\n  } else {\n    // Most likely an error, return error as OperationOutcome\n    return createErrorOutcome(JSON.stringify(response));\n  }\n}\n\nfunction getQueryString(\n  searchParam: IdentifierParameter | QuestionnaireRefParameter,\n  canonical?: string\n): string {\n  if (searchParam.name === 'identifier') {\n    const identifier = searchParam.valueIdentifier;\n    const identifierSystem = identifier.system ?? '';\n    const identifierValue = identifier.value ?? '';\n\n    if (identifierSystem || identifierValue) {\n      return `Questionnaire?identifier=${identifierSystem}|${identifierValue}`;\n    }\n  }\n\n  if (searchParam.name === 'questionnaireRef') {\n    const questionnaireRef = searchParam.valueReference;\n    if (questionnaireRef.reference) {\n      return questionnaireRef.reference;\n    }\n  }\n\n  // Fallback to canonical url\n  if (canonical) {\n    canonical = safeReplaceCanonicalVersion(canonical);\n  }\n  return `Questionnaire?url=${canonical}`;\n}\n\nexport function safeReplaceCanonicalVersion(canonical: string): string {\n  const [base, version] = canonical.split('|');\n\n  if (version) {\n    // Append version as a URL param safely\n    return `${base}&version=${encodeURIComponent(version)}`;\n  }\n\n  return canonical;\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n  InputParameters,\n  ReferenceContext,\n  ResourceContext\n} from '../interfaces/inputParameters.interface';\nimport { isContextParameter } from './typePredicates';\nimport fhirpath from 'fhirpath';\n// Need to specifically import from 'index.js' to get it working with ts\nimport fhirpath_r4_model from 'fhirpath/fhir-context/r4/index.js';\nimport type {\n  Bundle,\n  Expression,\n  Extension,\n  FhirResource,\n  OperationOutcomeIssue,\n  Questionnaire,\n  QuestionnaireItem\n} from 'fhir/r4';\nimport type {\n  FetchResourceCallback,\n  FetchResourceRequestConfig,\n  FetchTerminologyRequestConfig\n} from '../interfaces';\nimport { createInvalidWarningIssue, createNotFoundWarningIssue } from './operationOutcome';\nimport { TERMINOLOGY_SERVER_URL } from '../../globals';\nimport { emptyResponse } from './emptyResource';\nimport { createReferenceContextTuple, createResourceContextTuple } from './createContextTuples';\n\n/**\n * Creates a comprehensive FHIRPath evaluation context for questionnaire population operations.\n * This context includes launch contexts, resolved FHIR resources, and evaluated variables that can be referenced\n * in FHIRPath expressions throughout the questionnaire. It handles both direct resource contexts and reference-based\n * contexts that need to be fetched from external FHIR servers during the population process.\n */\nexport async function createFhirPathContext(\n  parameters: InputParameters,\n  questionnaire: Questionnaire,\n  fetchResourceCallback: FetchResourceCallback,\n  fetchResourceRequestConfig: FetchResourceRequestConfig,\n  issues: OperationOutcomeIssue[],\n  fetchTerminologyRequestConfig?: FetchTerminologyRequestConfig\n): Promise<Record<string, any>> {\n  const { launchContexts, updatedReferenceContexts, updatedContainedBatchContexts } =\n    await replaceFhirPathEmbeddings(\n      parameters,\n      questionnaire,\n      fetchTerminologyRequestConfig,\n      fetchResourceRequestConfig\n    );\n\n  const fhirPathContext: Record<string, any> = {\n    resource: structuredClone(emptyResponse),\n    rootResource: structuredClone(emptyResponse)\n  };\n\n  // Add launch contexts and contained batch contexts to contextMap\n  for (const launchContext of launchContexts) {\n    fhirPathContext[launchContext.part[0].valueString] = launchContext.part[1].resource;\n  }\n\n  for (const containedBatchContext of updatedContainedBatchContexts) {\n    fhirPathContext[containedBatchContext.part[0].valueString] =\n      containedBatchContext.part[1].resource;\n  }\n\n  // Resolve and populate reference context resources into contextMap\n  await populateReferenceContextsIntoContextMap(\n    updatedReferenceContexts,\n    fhirPathContext,\n    fetchResourceCallback,\n    fetchResourceRequestConfig,\n    issues\n  );\n\n  // Resolve and populate contained batch resources into contextMap\n  await populateBatchContextsIntoContextMap(\n    updatedContainedBatchContexts,\n    fhirPathContext,\n    fetchResourceCallback,\n    fetchResourceRequestConfig,\n    issues\n  );\n\n  // Extract and evaluate FHIRPath variables\n  await extractAndEvaluateFhirPathVariables(\n    questionnaire,\n    fhirPathContext,\n    issues,\n    fetchTerminologyRequestConfig,\n    fetchResourceRequestConfig\n  );\n\n  return fhirPathContext;\n}\n\n/**\n * Extracts and evaluates all FHIRPath variables defined in a questionnaire at both questionnaire and item levels.\n * FHIRPath variables allow questionnaires to define reusable expressions that can be referenced throughout\n * the form using %variableName syntax. This function processes variable extensions and makes their evaluated\n * results available in the FHIRPath context for use in other expressions like initialExpression or calculatedExpression.\n */\nexport async function extractAndEvaluateFhirPathVariables(\n  questionnaire: Questionnaire,\n  fhirPathContext: Record<string, any>,\n  issues: OperationOutcomeIssue[],\n  fetchTerminologyRequestConfig?: FetchTerminologyRequestConfig,\n  fetchResourceRequestConfig?: FetchResourceRequestConfig\n) {\n  if (!questionnaire.extension || questionnaire.extension.length === 0) {\n    return;\n  }\n\n  // Extract and evaluate FHIRPath variables from questionnaire-level\n  const questionnaireLevelVariables = getFhirPathVariables(questionnaire.extension);\n  await evaluateFhirPathVariables(\n    questionnaireLevelVariables,\n    fhirPathContext,\n    issues,\n    fetchTerminologyRequestConfig,\n    fetchResourceRequestConfig\n  );\n\n  // Extract and evaluate FHIRPath variables from item-level\n  let itemLevelVariables: Record<string, any> = {};\n  itemLevelVariables = extractItemLevelFhirPathVariables(questionnaire, itemLevelVariables);\n  if (Object.keys(itemLevelVariables).length > 0) {\n    for (const [, variables] of Object.entries(itemLevelVariables)) {\n      await evaluateFhirPathVariables(\n        variables,\n        fhirPathContext,\n        issues,\n        fetchTerminologyRequestConfig,\n        fetchResourceRequestConfig\n      );\n    }\n  }\n}\n\n/**\n * Recursively extracts FHIRPath variable definitions from questionnaire items at all nesting levels.\n * This function traverses the questionnaire's hierarchical structure to find variable extensions defined\n * on individual items, which allows for item-specific variables that can be used in expressions within\n * that item's scope or by other items that reference them.\n */\nexport function extractItemLevelFhirPathVariables(\n  questionnaire: Questionnaire,\n  variables: Record<string, Expression[]>\n): Record<string, Expression[]> {\n  if (!questionnaire.item || questionnaire.item.length === 0) {\n    return variables;\n  }\n\n  for (const topLevelItem of questionnaire.item) {\n    const isRepeatGroup = !!topLevelItem.repeats && topLevelItem.type === 'group';\n    extractItemLevelFhirPathVariablesRecursive({\n      item: topLevelItem,\n      variables,\n      parentRepeatGroupLinkId: isRepeatGroup ? topLevelItem.linkId : undefined\n    });\n  }\n\n  return variables;\n}\n\ninterface ExtractItemLevelFhirPathVariablesRecursiveParams {\n  item: QuestionnaireItem;\n  variables: Record<string, Expression[]>;\n  parentRepeatGroupLinkId?: string;\n}\n\n/**\n * Recursively processes a single questionnaire item and its children to extract FHIRPath variable definitions.\n * This helper function handles the recursive traversal logic for extractItemLevelFhirPathVariables,\n * properly tracking parent repeat group context and ensuring variables are extracted from all\n * nested items regardless of the questionnaire's structural complexity.\n */\nexport function extractItemLevelFhirPathVariablesRecursive(\n  params: ExtractItemLevelFhirPathVariablesRecursiveParams\n) {\n  const { item, variables, parentRepeatGroupLinkId } = params;\n\n  const items = item.item;\n  const isRepeatGroup = !!item.repeats && item.type === 'group';\n  if (items && items.length > 0) {\n    // iterate through items of item recursively\n    for (const childItem of items) {\n      extractItemLevelFhirPathVariablesRecursive({\n        ...params,\n        item: childItem,\n        parentRepeatGroupLinkId: isRepeatGroup ? item.linkId : parentRepeatGroupLinkId\n      });\n    }\n  }\n\n  if (item.extension) {\n    variables[item.linkId] = getFhirPathVariables(item.extension);\n  }\n\n  return {\n    variables\n  };\n}\n\n/**\n * Evaluates an array of FHIRPath variable expressions and adds their results to the FHIRPath context.\n * Each variable's expression is evaluated against the current context and the result is stored\n * using the variable's name, making it available for reference in other FHIRPath expressions\n * throughout the questionnaire using %variableName syntax.\n */\nexport async function evaluateFhirPathVariables(\n  variables: Expression[],\n  fhirPathContext: Record<string, any>,\n  issues: OperationOutcomeIssue[],\n  fetchTerminologyRequestConfig?: FetchTerminologyRequestConfig,\n  fetchResourceRequestConfig?: FetchResourceRequestConfig\n) {\n  if (variables.length === 0) {\n    return;\n  }\n\n  const terminologyServerUrl = fetchTerminologyRequestConfig?.terminologyServerUrl ?? null;\n  const fhirServerUrl = fetchResourceRequestConfig?.sourceServerUrl ?? null;\n\n  for (const variable of variables) {\n    if (variable.expression) {\n      try {\n        const fhirPathResult = fhirpath.evaluate(\n          {},\n          variable.expression,\n          fhirPathContext,\n          fhirpath_r4_model,\n          {\n            async: true,\n            terminologyUrl: terminologyServerUrl ?? TERMINOLOGY_SERVER_URL,\n            ...(fhirServerUrl && { fhirServerUrl })\n          }\n        );\n\n        fhirPathContext[`${variable.name}`] = await handleFhirPathResult(fhirPathResult);\n      } catch (e) {\n        // e is not thrown as an Error type in fhirpath.js, so we can't use `if (e instanceof Error)` here\n        console.warn(\n          `SDC-Populate Error: fhirpath evaluation for Questionnaire-level FHIRPath variable ${variable.expression} failed. Details below:` +\n            e\n        );\n        issues.push(createInvalidWarningIssue(String(e)));\n      }\n    }\n  }\n}\n\n/**\n * Get fhirpath variables from an array of extensions\n */\nexport function getFhirPathVariables(extensions: Extension[]): Expression[] {\n  return (\n    extensions\n      .filter(\n        (extension) =>\n          extension.url === 'http://hl7.org/fhir/StructureDefinition/variable' &&\n          extension.valueExpression?.language === 'text/fhirpath'\n      )\n      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n      .map((extension) => extension.valueExpression!)\n  );\n}\n\n/**\n * Resolves reference-based context parameters by fetching the actual FHIR resources they point to.\n * Reference contexts contain URLs or references to FHIR resources that need to be retrieved from\n * external servers before they can be used in FHIRPath expressions. This function handles the\n * asynchronous fetching process and populates the context map with the resolved resources.\n */\nexport async function populateReferenceContextsIntoContextMap(\n  referenceContexts: ReferenceContext[],\n  contextMap: Record<string, any>,\n  fetchResourceCallback: FetchResourceCallback,\n  fetchResourceRequestConfig: FetchResourceRequestConfig,\n  issues: OperationOutcomeIssue[]\n) {\n  // Get promises from context references\n  let referenceContextTuples = referenceContexts.map((referenceContext) =>\n    createReferenceContextTuple(referenceContext, fetchResourceCallback, fetchResourceRequestConfig)\n  );\n\n  try {\n    // Resolve promises for referenceContextsTuple\n    const promises: Promise<any>[] = referenceContextTuples.map(([, promise]) => promise);\n    const settledPromises = await Promise.allSettled(promises);\n    const resources: (FhirResource | null)[] = settledPromises.map((settledPromise) => {\n      if (settledPromise.status === 'rejected') {\n        return null;\n      }\n\n      let resource: FhirResource | null = null;\n\n      // Get lookupResult from response (fhirClient and fetch scenario)\n      if (responseDataIsFhirResource(settledPromise.value)) {\n        resource = settledPromise.value;\n      }\n      // Fallback to get valueSet from response.data (axios scenario)\n      if (\n        !resource &&\n        settledPromise.value.data &&\n        responseDataIsFhirResource(settledPromise.value.data)\n      ) {\n        resource = settledPromise.value.data;\n      }\n\n      return resource;\n    });\n\n    // Update referenceContextTuples with resolved resources\n    referenceContextTuples = referenceContextTuples.map((tuple, i) => {\n      const [referenceContext, promise] = tuple;\n      return [referenceContext, promise, resources[i] ?? null];\n    });\n  } catch (e) {\n    if (e instanceof Error) {\n      issues.push(createInvalidWarningIssue(e.message));\n    }\n  }\n\n  // Add resources to contextMap\n  for (let i = 0; i < referenceContextTuples.length; i++) {\n    const referenceContextTuple = referenceContextTuples[i];\n    if (!referenceContextTuple) {\n      continue;\n    }\n\n    const referenceContext = referenceContextTuple[0];\n    const resource = referenceContextTuple[2];\n    if (!resource) {\n      issues.push(\n        createNotFoundWarningIssue(\n          `The reference ${referenceContext.part[1]?.valueReference.reference} from context ${referenceContext.part[0]?.valueString} cannot be resolved`\n        )\n      );\n      continue;\n    }\n\n    // If resource is an OperationOutcome, add to issues array\n    if (resource.resourceType === 'OperationOutcome') {\n      issues.push(...resource.issue);\n      continue;\n    }\n\n    // Add resource to contextMap\n    const contextName = referenceContext.part[0].valueString;\n    if (contextName) {\n      contextMap[contextName] = resource;\n    }\n  }\n}\n\n/**\n * Processes batch context bundles by fetching the individual resources referenced in batch entries.\n * Batch contexts contain FHIR Bundle resources with batch-type entries that specify multiple resources\n * to be fetched. This function executes the batch requests and populates each bundle entry with\n * the corresponding fetched resource data for use in FHIRPath expressions.\n */\nexport async function populateBatchContextsIntoContextMap(\n  batchContexts: ResourceContext[],\n  contextMap: Record<string, any>,\n  fetchResourceCallback: FetchResourceCallback,\n  fetchResourceRequestConfig: FetchResourceRequestConfig,\n  issues: OperationOutcomeIssue[]\n) {\n  // Get promises from contained batch contexts\n  const batchContextTuples: [ResourceContext, Promise<any>, FhirResource | null][][] = [];\n  for (const batchContext of batchContexts) {\n    const batchBundle = batchContext.part[1].resource as Bundle;\n    // batch bundle empty\n    if (!batchBundle.entry || batchBundle.entry.length === 0) {\n      batchContextTuples.push([]);\n      continue;\n    }\n\n    // batch bundle contains entries, create a request for each entry\n    const batchContextEntryTuples = batchBundle.entry.map((entry) =>\n      createResourceContextTuple(\n        batchContext,\n        entry,\n        fetchResourceCallback,\n        fetchResourceRequestConfig\n      )\n    );\n\n    batchContextTuples.push(batchContextEntryTuples);\n  }\n\n  // Resolve promises for batchContextsTuples and add populated batch bundles to contextMap\n  try {\n    for (const batchContextEntryTuples of batchContextTuples) {\n      if (!batchContextEntryTuples[0]) {\n        continue;\n      }\n\n      // Ensure batch bundle is available\n      const resourceContext = batchContextEntryTuples[0][0];\n      const batchBundleName = resourceContext.part[0].valueString;\n      const batchBundle = resourceContext.part[1].resource as Bundle;\n      if (!batchBundle.entry || batchBundle.entry.length === 0) {\n        continue;\n      }\n\n      // Resolve promises for batchContextEntryTuples\n      const promises: Promise<any>[] = batchContextEntryTuples.map(([, promise]) => promise);\n      const settledPromises = await Promise.allSettled(promises);\n      const resources: (FhirResource | null)[] = settledPromises.map((settledPromise) => {\n        if (settledPromise.status === 'rejected') {\n          return null;\n        }\n\n        const response = settledPromise.value;\n        if (responseDataIsFhirResource(response?.data)) {\n          return response.data as FhirResource;\n        }\n\n        return null;\n      });\n\n      // Add resources to batch bundle\n      for (let i = 0; i < resources.length; i++) {\n        const resource = resources[i];\n        const entry = batchBundle.entry[i];\n\n        // If resource or entry is null, add a warning issue\n        if (!resource || !entry) {\n          issues.push(\n            createNotFoundWarningIssue(\n              `The resource for ${batchBundleName} entry ${i} could not be resolved.`\n            )\n          );\n          continue;\n        }\n\n        // If resource is an OperationOutcome, add issues to issues array\n        if (resource.resourceType === 'OperationOutcome') {\n          issues.push(...resource.issue);\n          continue;\n        }\n\n        // Add resource to batch bundle entry\n        entry.resource = resource;\n      }\n\n      // Add batch bundle to contextMap\n      contextMap[batchBundleName] = batchBundle;\n    }\n  } catch (e) {\n    if (e instanceof Error) {\n      issues.push(createInvalidWarningIssue(e.message));\n    }\n  }\n}\n\n/**\n * Type guard function to determine if response data represents a valid FHIR resource.\n * This function checks for the presence and type of the resourceType property which is\n * required for all FHIR resources. It's used to validate responses from FHIR servers\n * before attempting to process them as FHIR resources in the population context.\n */\nexport function responseDataIsFhirResource(responseData: any): responseData is FhirResource {\n  return !!(\n    responseData &&\n    responseData.resourceType &&\n    typeof responseData.resourceType === 'string'\n  );\n}\n\n/**\n * Processes and evaluates FHIRPath embeddings found in context references and batch contexts.\n * FHIRPath embeddings use {{%expression}} syntax within URLs and references to create dynamic\n * values based on launch context data. This function identifies these embeddings, evaluates them\n * against available launch contexts, and replaces them with their computed values.\n */\nexport async function replaceFhirPathEmbeddings(\n  parameters: InputParameters,\n  questionnaire: Questionnaire,\n  fetchTerminologyRequestConfig?: FetchTerminologyRequestConfig,\n  fetchResourceRequestConfig?: FetchResourceRequestConfig\n): Promise<{\n  launchContexts: ResourceContext[];\n  updatedReferenceContexts: ReferenceContext[];\n  updatedContainedBatchContexts: ResourceContext[];\n}> {\n  const launchContexts = parameters.parameter.filter(\n    (param) =>\n      isContextParameter(param) &&\n      param.part &&\n      !!param.part[1].resource &&\n      param.part[1].resource?.resourceType !== 'Bundle'\n  ) as ResourceContext[];\n\n  const referenceContexts = parameters.parameter.filter(\n    (param) => isContextParameter(param) && param.part && !!param.part[1].valueReference?.reference\n  ) as ReferenceContext[];\n\n  // Get and transform context references which references contained batchs into a separate array\n  const containedBatchContexts: ResourceContext[] = getContainedBatchContexts(\n    referenceContexts,\n    questionnaire\n  );\n\n  if (launchContexts.length > 0) {\n    // Get and store fhirpath embeddings from reference contexts and contained batch contexts into a map\n    const fhirPathEmbeddingsMap = getFhirPathEmbeddings(referenceContexts, containedBatchContexts);\n\n    // evaluate fhirpath embeddings with values from launch context map\n    const evaluatedFhirPathEmbeddingsMap = await evaluateFhirPathEmbeddings(\n      fhirPathEmbeddingsMap,\n      launchContexts,\n      fetchTerminologyRequestConfig,\n      fetchResourceRequestConfig\n    );\n\n    // Replace fhirpath embeddings with evaluated values\n    const { updatedReferenceContexts, updatedContainedBatchContexts } =\n      replaceEvaluatedFhirPathEmbeddingsInContexts(\n        evaluatedFhirPathEmbeddingsMap,\n        referenceContexts,\n        containedBatchContexts\n      );\n\n    return { launchContexts, updatedReferenceContexts, updatedContainedBatchContexts };\n  } else {\n    return {\n      launchContexts,\n      updatedReferenceContexts: referenceContexts,\n      updatedContainedBatchContexts: containedBatchContexts\n    };\n  }\n}\n\n/**\n * Extracts contained batch Bundle resources from reference contexts that point to questionnaire.contained resources.\n * When reference contexts use '#' prefixed references, they point to resources contained within the questionnaire\n * itself rather than external resources. This function identifies these contained batch bundles and converts\n * them into resource contexts for processing during population.\n */\nexport function getContainedBatchContexts(\n  referenceContexts: ReferenceContext[],\n  questionnaire: Questionnaire\n): ResourceContext[] {\n  const containedBatchContexts: ResourceContext[] = [];\n  const containedResources = questionnaire.contained;\n  for (const referenceContext of referenceContexts) {\n    const reference = referenceContext.part[1].valueReference.reference;\n    if (\n      reference &&\n      reference.startsWith('#') &&\n      containedResources &&\n      containedResources.length > 0\n    ) {\n      const containedReference = reference.slice(1);\n      const batch = containedResources.find(\n        (resource) => resource.id === containedReference && resource.resourceType === 'Bundle'\n      ) as Bundle | undefined;\n\n      if (batch && batch.entry && batch.id) {\n        containedBatchContexts.push({\n          name: 'context',\n          part: [\n            {\n              name: 'name',\n              valueString: referenceContext.part[0].valueString\n            },\n            {\n              name: 'content',\n              resource: batch\n            }\n          ]\n        });\n      }\n    }\n  }\n\n  return containedBatchContexts;\n}\n\n/**\n * Scans reference contexts and batch contexts to identify all FHIRPath embeddings that need evaluation.\n * FHIRPath embeddings use {{%expression}} syntax and are commonly found in URLs and references\n * where dynamic values from launch contexts need to be substituted. This function creates a map\n * of all unique embeddings found across all contexts for subsequent evaluation.\n */\nexport function getFhirPathEmbeddings(\n  referenceContexts: ReferenceContext[],\n  containedBatchContexts: ResourceContext[]\n): Record<string, string> {\n  const fhirPathEmbeddingsMap: Record<string, string> = {};\n\n  // Identify and store fhirpath embeddings from referenceContexts and containedBatchContexts in a map\n  for (const referenceContext of referenceContexts) {\n    const reference = referenceContext.part[1].valueReference.reference;\n    if (reference) {\n      const fhirPathEmbeddings = readFhirPathEmbeddingsFromStr(reference);\n      for (const embedding of fhirPathEmbeddings) {\n        if (embedding) {\n          fhirPathEmbeddingsMap[embedding] = '';\n        }\n      }\n    }\n  }\n\n  for (const containedBatchContext of containedBatchContexts) {\n    const batch = containedBatchContext.part[1].resource;\n    if (batch.resourceType === 'Bundle' && batch.entry && batch.entry.length > 0) {\n      for (const entry of batch.entry) {\n        if (entry.request?.url) {\n          const fhirPathEmbeddings = readFhirPathEmbeddingsFromStr(entry.request.url);\n          for (const embedding of fhirPathEmbeddings) {\n            if (embedding) {\n              fhirPathEmbeddingsMap[embedding] = '';\n            }\n          }\n        }\n      }\n    }\n  }\n\n  return fhirPathEmbeddingsMap;\n}\n\n/**\n * Evaluates FHIRPath embeddings against launch context data to produce concrete values for substitution.\n * Each embedding expression is evaluated using the appropriate launch context resource as the root,\n * allowing dynamic references like {{%patient.id}} to be resolved to actual patient IDs from\n * the launch context for use in URLs and resource references.\n */\nexport async function evaluateFhirPathEmbeddings(\n  fhirPathEmbeddingsMap: Record<string, string>,\n  launchContexts: ResourceContext[],\n  fetchTerminologyRequestConfig?: FetchTerminologyRequestConfig,\n  fetchResourceRequestConfig?: FetchResourceRequestConfig\n) {\n  const terminologyServerUrl = fetchTerminologyRequestConfig?.terminologyServerUrl ?? null;\n  const fhirServerUrl = fetchResourceRequestConfig?.sourceServerUrl ?? null;\n\n  // transform launch contexts to launch context map\n  const launchContextMap: Record<string, FhirResource> = {};\n  for (const launchContext of launchContexts) {\n    launchContextMap[launchContext.part[0].valueString] = launchContext.part[1].resource;\n  }\n\n  // evaluate fhirpath embeddings within map\n  for (const embedding of Object.keys(fhirPathEmbeddingsMap)) {\n    const contextName = embedding.split('.')[0];\n    const fhirPathQuery = embedding.split('.').slice(1).join('.');\n\n    if (contextName) {\n      try {\n        const fhirPathResult = fhirpath.evaluate(launchContextMap[contextName], fhirPathQuery, {\n          async: true,\n          terminologyUrl: terminologyServerUrl ?? TERMINOLOGY_SERVER_URL,\n          ...(fhirServerUrl && { fhirServerUrl })\n        });\n        fhirPathEmbeddingsMap[embedding] = (await handleFhirPathResult(fhirPathResult))[0];\n      } catch (e) {\n        console.warn('SDC-Populate Error: Evaluate fhirpath embeddings failed. Details below:' + e);\n      }\n    }\n  }\n\n  return fhirPathEmbeddingsMap;\n}\n\n/**\n * Replaces FHIRPath embeddings with their evaluated values throughout reference and batch contexts.\n * After embeddings have been evaluated, this function performs string replacement to substitute\n * all {{%expression}} patterns with their computed values in URLs, references, and other string\n * fields where dynamic content was specified using FHIRPath embedding syntax.\n */\nexport function replaceEvaluatedFhirPathEmbeddingsInContexts(\n  evaluatedFhirPathEmbeddingsMap: Record<string, string>,\n  referenceContexts: ReferenceContext[],\n  containedBatchContexts: ResourceContext[]\n): {\n  updatedReferenceContexts: ReferenceContext[];\n  updatedContainedBatchContexts: ResourceContext[];\n} {\n  const evaluatedFhirPathEmbeddingsTuple = Object.entries(evaluatedFhirPathEmbeddingsMap);\n\n  // Replace fhirpath embeddings with evaluated values\n  referenceContexts.forEach((referenceContext) => {\n    evaluatedFhirPathEmbeddingsTuple.forEach(([embedding, value]) => {\n      // Create a regex pattern to match the variable name within curly braces\n      const pattern = new RegExp(`{{%${embedding}}}`, 'g');\n\n      // Replace occurrences of the variable name with its value\n      if (referenceContext.part[1].valueReference.reference) {\n        referenceContext.part[1].valueReference.reference =\n          referenceContext.part[1].valueReference.reference.replace(pattern, value);\n      }\n    });\n  });\n\n  // Remove reference contexts which references contained resources\n  const filteredReferenceContexts = referenceContexts.filter(\n    (referenceContext) =>\n      referenceContext.part[1].valueReference.reference &&\n      !referenceContext.part[1].valueReference.reference.startsWith('#')\n  );\n\n  containedBatchContexts.forEach((containedBatchContext) => {\n    const batch = containedBatchContext.part[1].resource;\n    if (batch.resourceType === 'Bundle' && batch.entry && batch.entry.length > 0) {\n      for (const entry of batch.entry) {\n        evaluatedFhirPathEmbeddingsTuple.forEach(([embedding, value]) => {\n          // Create a regex pattern to match the variable name within curly braces\n          const pattern = new RegExp(`{{%${embedding}}}`, 'g');\n\n          if (entry.request?.url) {\n            entry.request.url = entry.request.url.replace(pattern, value);\n          }\n        });\n      }\n    }\n  });\n\n  return {\n    updatedReferenceContexts: filteredReferenceContexts,\n    updatedContainedBatchContexts: containedBatchContexts\n  };\n}\n\nconst FHIRPATH_EMBEDDING_REGEX = /{{%(.*?)}}/g;\n\n/**\n * Extracts FHIRPath embedding expressions from strings using regex pattern matching.\n * FHIRPath embeddings are enclosed in {{%...}} syntax within strings and this function\n * uses a regex pattern to find all such expressions and extract just the FHIRPath expression\n * part for evaluation, enabling dynamic content substitution in URLs and references.\n */\nexport function readFhirPathEmbeddingsFromStr(expression: string): string[] {\n  return [...expression.matchAll(FHIRPATH_EMBEDDING_REGEX)].map((match) => match[1] ?? '');\n}\n\n/**\n * Handles both synchronous and asynchronous FHIRPath evaluation results uniformly.\n * FHIRPath evaluation can return either direct results or promises depending on whether\n * async operations like terminology lookups are involved. This function provides a consistent\n * interface for handling both cases and ensuring all results are properly awaited when needed.\n */\nexport async function handleFhirPathResult(result: any[] | Promise<any[]>) {\n  if (result instanceof Promise) {\n    return await result;\n  }\n\n  return result;\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport const TERMINOLOGY_SERVER_URL = 'https://tx.ontoserver.csiro.au/fhir';\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { QuestionnaireResponse } from 'fhir/r4';\n\n/**\n * An empty QuestionnaireResponse resource with status 'in-progress'.\n * Used as a default or placeholder response object.\n */\nexport const emptyResponse: QuestionnaireResponse = {\n  resourceType: 'QuestionnaireResponse',\n  status: 'in-progress'\n};\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport type { ReferenceContext, ResourceContext } from '../interfaces/inputParameters.interface';\nimport type { BundleEntry, FhirResource } from 'fhir/r4';\nimport type { FetchResourceCallback, FetchResourceRequestConfig } from '../interfaces';\nimport { createInvalidWarningIssue } from './operationOutcome';\n\n/**\n * Creates a tuple for a reference context, including a promise to fetch the referenced resource.\n * Returns a warning issue if the reference is missing, helping to validate input parameters.\n */\nexport function createReferenceContextTuple(\n  referenceContext: ReferenceContext,\n  fetchResourceCallback: FetchResourceCallback,\n  fetchResourceRequestConfig: FetchResourceRequestConfig\n): [ReferenceContext, Promise<any>, FhirResource | null] {\n  const query = referenceContext.part[1]?.valueReference?.reference;\n\n  if (!query) {\n    return [\n      referenceContext,\n      Promise.resolve(\n        createInvalidWarningIssue(\n          `Reference Context ${\n            referenceContext.part[0]?.valueString ?? ''\n          } does not contain a reference`\n        )\n      ),\n      null\n    ];\n  }\n\n  return [referenceContext, fetchResourceCallback(query, fetchResourceRequestConfig), null];\n}\n\n/**\n * Creates a tuple for a resource context using a bundle entry and a fetch callback.\n * Returns a warning issue if the bundle entry does not contain a request, ensuring proper validation.\n */\nexport function createResourceContextTuple(\n  resourceContext: ResourceContext,\n  bundleEntry: BundleEntry,\n  fetchResourceCallback: FetchResourceCallback,\n  fetchResourceRequestConfig: FetchResourceRequestConfig\n): [ResourceContext, Promise<any>, FhirResource | null] {\n  const query = bundleEntry.request?.url;\n\n  if (!query) {\n    const resourceContextName = resourceContext.part[0]?.valueString;\n    return [\n      resourceContext,\n      Promise.resolve(\n        createInvalidWarningIssue(\n          `${resourceContextName} bundle entry ${\n            bundleEntry.fullUrl ?? ''\n          } does not contain a request`\n        )\n      ),\n      null\n    ];\n  }\n\n  return [resourceContext, fetchResourceCallback(query, fetchResourceRequestConfig), null];\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Expression, Extension, Questionnaire, QuestionnaireItem } from 'fhir/r4';\nimport type { PopulationExpressions } from '../interfaces/expressions.interface';\n\n/**\n * Recursively read the items within a questionnaire item and store their initial expressions in a <string, InitialExpression> key-value map\n *\n * @author Sean Fong\n */\nexport function readPopulationExpressions(questionnaire: Questionnaire): PopulationExpressions {\n  const populationExpressions = {\n    initialExpressions: {},\n    itemPopulationContexts: {}\n  };\n\n  if (!questionnaire.item) return populationExpressions;\n\n  questionnaire.item.forEach((item) => {\n    readQuestionnaireItemRecursive(item, populationExpressions);\n  });\n  return populationExpressions;\n}\n\n/**\n * Recursively read a single questionnaire item/group and save its initialExpression into the object if present.\n * initialExpressions belonging to children of an itemPopulationContext group are excluded from the global map —\n * they are evaluated per-item in constructRepeatGroupInstances and must not be pre-evaluated against the full collection.\n *\n * @author Sean Fong\n */\nfunction readQuestionnaireItemRecursive(\n  item: QuestionnaireItem,\n  populationExpressions: PopulationExpressions,\n  underItemPopulationContext = false\n): PopulationExpressions {\n  const items = item.item;\n  if (items && items.length > 0) {\n    // Read item population context of group item\n    const itemPopulationContext = getItemPopulationContext(item);\n    if (itemPopulationContext && itemPopulationContext.expression && itemPopulationContext.name) {\n      populationExpressions.itemPopulationContexts[itemPopulationContext.name] = {\n        linkId: item.linkId,\n        name: itemPopulationContext.name,\n        expression: itemPopulationContext.expression,\n        value: undefined\n      };\n    }\n\n    // Read initial expression of group item — skipped when under an itemPopulationContext\n    if (!underItemPopulationContext) {\n      const initialExpression = getInitialExpression(item);\n      if (initialExpression && initialExpression.expression) {\n        populationExpressions.initialExpressions[item.linkId] = {\n          expression: initialExpression.expression,\n          value: undefined\n        };\n      }\n    }\n\n    // Children of a *repeating* itemPopulationContext group are evaluated per-item in\n    // constructRepeatGroupInstances, so they must be excluded from the global map.\n    // Non-repeating groups (repeats: false) with itemPopulationContext are single-instance;\n    // their children are evaluated globally once the context variable is available.\n    const childrenUnderContext =\n      underItemPopulationContext || (!!itemPopulationContext && !!item.repeats);\n    items.forEach((item) => {\n      readQuestionnaireItemRecursive(item, populationExpressions, childrenUnderContext);\n    });\n\n    return populationExpressions;\n  }\n\n  // Read initial expression of qItem — skipped when under an itemPopulationContext\n  if (!underItemPopulationContext) {\n    const initialExpression = getInitialExpression(item);\n    if (initialExpression && initialExpression.expression) {\n      populationExpressions.initialExpressions[item.linkId] = {\n        expression: initialExpression.expression,\n        value: undefined\n      };\n    }\n  }\n\n  return populationExpressions;\n}\n\n/**\n * Check and returns it if a questionnaireItem contains an initialExpression\n *\n * @author Sean Fong\n */\nexport function getInitialExpression(qItem: QuestionnaireItem): Expression | null {\n  const itemControl = qItem.extension?.find(\n    (extension: Extension) =>\n      extension.url ===\n      'http://hl7.org/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-initialExpression'\n  );\n\n  if (itemControl) {\n    if (itemControl.valueExpression) {\n      return itemControl.valueExpression;\n    }\n  }\n  return null;\n}\n\n/**\n * Check and returns it if a questionnaireItem contains an itemPopulationContext\n *\n * @author Sean Fong\n */\nexport function getItemPopulationContext(qItem: QuestionnaireItem): Expression | null {\n  const itemControl = qItem.extension?.find(\n    (extension: Extension) =>\n      extension.url ===\n      'http://hl7.org/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-itemPopulationContext'\n  );\n\n  if (itemControl) {\n    if (itemControl.valueExpression) {\n      return itemControl.valueExpression;\n    }\n  }\n  return null;\n}\n\nexport function getItemPopulationContextName(itemPopulationContextExpression: string): string {\n  return itemPopulationContextExpression.substring(\n    itemPopulationContextExpression.indexOf('%') + 1,\n    itemPopulationContextExpression.indexOf('.')\n  );\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport fhirpath from 'fhirpath';\n// Need to specifically import from 'index.js' to get it working with ts\nimport fhirpath_r4_model from 'fhirpath/fhir-context/r4/index.js';\nimport type {\n  ItemPopulationContext,\n  PopulationExpressions\n} from '../interfaces/expressions.interface';\nimport type { OperationOutcomeIssue } from 'fhir/r4';\nimport { createInvalidWarningIssue } from './operationOutcome';\nimport type { FetchTerminologyRequestConfig, FetchResourceRequestConfig } from '../interfaces';\nimport { handleFhirPathResult } from './createFhirPathContext';\nimport { TERMINOLOGY_SERVER_URL } from '../../globals';\n\n/**\n * Use FHIRPath.js to evaluate initialExpressions and generate its values to be populated into the questionnaireResponse.\n * Removes unsupported functions from expressions to avoid errors. Populates values for each linkId.\n *\n * @author Sean Fong\n */\nexport async function generateExpressionValues(\n  populationExpressions: PopulationExpressions,\n  contextMap: Record<string, any>,\n  issues: OperationOutcomeIssue[],\n  fetchTerminologyRequestConfig?: FetchTerminologyRequestConfig,\n  fetchResourceRequestConfig?: FetchResourceRequestConfig\n) {\n  const { initialExpressions, itemPopulationContexts } = populationExpressions;\n\n  const terminologyServerUrl = fetchTerminologyRequestConfig?.terminologyServerUrl ?? null;\n  const fhirServerUrl = fetchResourceRequestConfig?.sourceServerUrl ?? null;\n\n  for (const linkId in initialExpressions) {\n    const initialExpression = initialExpressions[linkId];\n    if (initialExpression) {\n      const expression = initialExpression.expression;\n\n      // Evaluate expression by LaunchPatient or PrePopQuery\n      try {\n        const fhirPathResult = fhirpath.evaluate({}, expression, contextMap, fhirpath_r4_model, {\n          async: true,\n          terminologyUrl: terminologyServerUrl ?? TERMINOLOGY_SERVER_URL,\n          ...(fhirServerUrl && { fhirServerUrl })\n        });\n\n        initialExpression.value = await handleFhirPathResult(fhirPathResult);\n      } catch (e) {\n        // e is not thrown as an Error type in fhirpath.js, so we can't use `if (e instanceof Error)` here\n        console.warn(\n          `SDC-Populate Error: fhirpath evaluation for InitialExpression ${expression} failed. Details below:` +\n            e\n        );\n        issues.push(createInvalidWarningIssue(String(e)));\n        continue;\n      }\n\n      initialExpressions[linkId] = initialExpression;\n    }\n  }\n\n  for (const linkId in itemPopulationContexts) {\n    const itemPopulationContext = itemPopulationContexts[linkId];\n    if (itemPopulationContext) {\n      const expression = itemPopulationContext.expression;\n\n      try {\n        const fhirPathResult = fhirpath.evaluate({}, expression, contextMap, fhirpath_r4_model, {\n          async: true,\n          terminologyUrl: terminologyServerUrl ?? TERMINOLOGY_SERVER_URL,\n          ...(fhirServerUrl && { fhirServerUrl })\n        });\n        itemPopulationContext.value = await handleFhirPathResult(fhirPathResult);\n      } catch (e) {\n        // e is not thrown as an Error type in fhirpath.js, so we can't use `if (e instanceof Error)` here\n        console.warn(\n          `SDC-Populate Error: fhirpath evaluation for ItemPopulationContext ${expression} failed. Details below:` +\n            e\n        );\n        issues.push(createInvalidWarningIssue(String(e)));\n        continue;\n      }\n\n      // Save evaluated item population context result into context object\n      itemPopulationContexts[linkId] = itemPopulationContext;\n    }\n  }\n\n  return {\n    evaluatedInitialExpressions: initialExpressions,\n    evaluatedItemPopulationContexts: itemPopulationContexts\n  };\n}\n\n/**\n * Use FHIRPath.js to evaluate initialExpressions and generate its values to be populated into the questionnaireResponse.\n * There are some functions that are yet to be implemented in FHIRPath.js - these functions would be removed from the expressions to avoid errors.\n *\n * @author Sean Fong\n */\nexport async function evaluateItemPopulationContexts(\n  itemPopulationContexts: Record<string, ItemPopulationContext>,\n  contextMap: Record<string, any>,\n  issues: OperationOutcomeIssue[],\n  fetchTerminologyRequestConfig?: FetchTerminologyRequestConfig,\n  fetchResourceRequestConfig?: FetchResourceRequestConfig\n): Promise<Record<string, any>> {\n  const terminologyServerUrl = fetchTerminologyRequestConfig?.terminologyServerUrl ?? null;\n  const fhirServerUrl = fetchResourceRequestConfig?.sourceServerUrl ?? null;\n\n  for (const name in itemPopulationContexts) {\n    const itemPopulationContext = itemPopulationContexts[name];\n    if (itemPopulationContext) {\n      let evaluatedResult: any[];\n      const expression = itemPopulationContext.expression;\n\n      // Evaluate expression by LaunchPatient or PrePopQuery\n      try {\n        const fhirPathResult = fhirpath.evaluate({}, expression, contextMap, fhirpath_r4_model, {\n          async: true,\n          terminologyUrl: terminologyServerUrl ?? TERMINOLOGY_SERVER_URL,\n          ...(fhirServerUrl && { fhirServerUrl })\n        });\n        evaluatedResult = await handleFhirPathResult(fhirPathResult);\n      } catch (e) {\n        // e is not thrown as an Error type in fhirpath.js, so we can't use `if (e instanceof Error)` here\n        console.warn(\n          `SDC-Populate Error: fhirpath evaluation for ItemPopulationContext ${expression} failed. Details below:` +\n            e\n        );\n        issues.push(createInvalidWarningIssue(String(e)));\n\n        continue;\n      }\n\n      // Save evaluated item population context result into context object\n      contextMap[itemPopulationContext.name] = evaluatedResult;\n    }\n  }\n\n  return contextMap;\n}\n","import type { Coding } from 'fhir/r4';\n\n/**\n * Retrieves only the relevant properties of a Coding object.\n * Reason: https://tx.ontoserver.csiro.au/fhir returns a Coding with designation element, which is not in the FHIR spec, causing QRs with it to fail validation.\n *\n * @author Sean Fong\n */\nexport function getRelevantCodingProperties(coding: Coding): Coding {\n  return {\n    system: coding.system,\n    code: coding.code,\n    display: coding.display,\n    ...(coding.extension && { extension: coding.extension })\n  };\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n  Coding,\n  QuestionnaireItemAnswerOption,\n  QuestionnaireResponseItem,\n  QuestionnaireResponseItemAnswer,\n  ValueSet\n} from 'fhir/r4';\nimport type { ValueSetPromise } from '../interfaces/expressions.interface';\nimport { getRelevantCodingProperties } from './codingProperties';\n\nexport async function resolveValueSetPromises(\n  valueSetPromises: Record<string, ValueSetPromise>\n): Promise<Record<string, ValueSetPromise>> {\n  const newValueSetPromises: Record<string, ValueSetPromise> = {};\n\n  const valueSetPromiseKeys = Object.keys(valueSetPromises);\n  const valueSetPromiseValues = Object.values(valueSetPromises);\n  const promises = valueSetPromiseValues.map((valueSetPromise) => valueSetPromise.promise);\n  const settledPromises = await Promise.allSettled(promises);\n\n  for (const [i, settledPromise] of settledPromises.entries()) {\n    if (settledPromise.status === 'rejected') {\n      continue;\n    }\n\n    const key = valueSetPromiseKeys[i];\n    const valueSetPromise = valueSetPromiseValues[i];\n    if (key && valueSetPromise) {\n      // Promises can be generated by a fhirClient (internally) or fetch/axios (via callback function), so we need to handle both scenarios\n      const response = settledPromise.value;\n      // Get valueSet from response (fhirClient and fetch scenario)\n      if (responseIsValueSet(response)) {\n        valueSetPromise.valueSet = response;\n      }\n\n      // Fallback to get valueSet from response.data (axios scenario)\n      if (!valueSetPromise.valueSet && response.data && responseIsValueSet(response.data)) {\n        valueSetPromise.valueSet = response.data;\n      }\n\n      newValueSetPromises[key] = valueSetPromise;\n    }\n  }\n  return newValueSetPromises;\n}\n\nfunction responseIsValueSet(response: any): response is ValueSet {\n  return response && response.resourceType === 'ValueSet';\n}\n\n/**\n * Read a questionnaire response item recursively and retrieve valueSet answers if present\n *\n * @author Sean Fong\n */\nexport function filterValueSetAnswersRecursive(\n  qrItem: QuestionnaireResponseItem,\n  valueSetPromises: Record<string, ValueSetPromise>,\n  answerOptions: Record<string, QuestionnaireItemAnswerOption[]>,\n  containedResources: Record<string, ValueSet>\n): QuestionnaireResponseItem | null {\n  const items = qrItem.item;\n\n  if (items && items.length > 0) {\n    // iterate through items of item recursively\n    const qrItems: QuestionnaireResponseItem[] = items\n      .map((item) =>\n        filterValueSetAnswersRecursive(item, valueSetPromises, answerOptions, containedResources)\n      )\n      .filter((item): item is QuestionnaireResponseItem => item !== null);\n\n    return { ...qrItem, item: qrItems };\n  }\n\n  const linkId = qrItem.linkId;\n\n  const valueSetOptionCodings = valueSetPromises[linkId]?.valueSet?.expansion?.contains;\n  if (qrItem.answer && valueSetOptionCodings) {\n    return { ...qrItem, answer: filterAndNormaliseAnswers(qrItem.answer, valueSetOptionCodings) };\n  }\n\n  const answerOptionCodings = answerOptions[linkId]?.map((option) => option.valueCoding);\n  if (qrItem.answer && answerOptionCodings) {\n    return { ...qrItem, answer: filterAndNormaliseAnswers(qrItem.answer, answerOptionCodings) };\n  }\n\n  const containedValueSetOptionCodings = containedResources[linkId]?.expansion?.contains;\n  if (qrItem.answer && containedValueSetOptionCodings) {\n    const cleanedAnswers = filterAndNormaliseAnswers(qrItem.answer, containedValueSetOptionCodings);\n\n    return cleanedAnswers.length > 0\n      ? {\n          ...qrItem,\n          answer: filterAndNormaliseAnswers(qrItem.answer, containedValueSetOptionCodings)\n        }\n      : null;\n  }\n\n  // If item does not have any valueSet nor answerOption\n  return qrItem;\n}\n\n/**\n * Normalises a list of QuestionnaireResponse answers by:\n * - Filtering out valueCoding answers that are not present in the provided options\n * - Converting valueString answers to valueCoding when matching codes are found in options\n * - Preserving all other answers, including valueString answers that do not match any coding,\n *   to support open-choice questions where arbitrary strings are allowed\n */\nfunction filterAndNormaliseAnswers(\n  answers: QuestionnaireResponseItemAnswer[],\n  options: (Coding | undefined)[]\n) {\n  const newAnswers: QuestionnaireResponseItemAnswer[] = [];\n\n  for (const answer of answers) {\n    // answer is valueCoding, check if it is in options\n    if (answer.valueCoding) {\n      const valueCoding = codingIsInOptions(answer.valueCoding, options);\n      if (valueCoding) {\n        const newAnswer: QuestionnaireResponseItemAnswer = {\n          valueCoding: valueCoding\n        };\n        newAnswers.push(newAnswer);\n      }\n\n      // Add continue here to skip to the next iteration if answer coding is not in options\n      continue;\n    }\n\n    // answer is valueString, attempt to parse it to valueCoding\n    if (answer.valueString) {\n      // attempt to obtain valueCodings in valueSet from valueString\n      const newAnswer = parseStringToCoding(answer.valueString, options);\n      newAnswers.push(newAnswer);\n      continue;\n    }\n\n    // fallback to adding the answer as is\n    newAnswers.push(answer);\n  }\n\n  return newAnswers;\n}\n\nfunction parseStringToCoding(\n  value: string,\n  options: (Coding | undefined)[]\n): QuestionnaireResponseItemAnswer {\n  if (!options) {\n    return { valueString: value };\n  }\n\n  const coding = options.find((coding) => coding?.code === value);\n\n  // code is found in options, return as valueCoding\n  if (coding) {\n    return {\n      valueCoding: getRelevantCodingProperties(coding)\n    };\n  }\n\n  // fallback to returning as valueString if no coding found\n  return { valueString: value };\n}\n\nfunction codingIsInOptions(answerCoding: Coding, options: (Coding | undefined)[]): Coding | null {\n  if (!options) {\n    return null;\n  }\n\n  const foundCoding = options.find((option) => option?.code === answerCoding.code);\n  if (foundCoding) {\n    return getRelevantCodingProperties(foundCoding);\n  }\n\n  return null;\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n  Encounter,\n  FhirResource,\n  Questionnaire,\n  QuestionnaireItem,\n  QuestionnaireItemAnswerOption,\n  QuestionnaireResponse,\n  QuestionnaireResponseItem,\n  QuestionnaireResponseItemAnswer,\n  Reference,\n  ValueSet\n} from 'fhir/r4';\nimport type {\n  ItemPopulationContext,\n  PopulationExpressions,\n  ValueSetPromise\n} from '../interfaces/expressions.interface';\nimport { filterValueSetAnswersRecursive, resolveValueSetPromises } from './processValueSets';\nimport moment from 'moment';\nimport dayjs from 'dayjs';\nimport fhirpath from 'fhirpath';\n// Need to specifically import from 'index.js' to get it working with ts\nimport fhirpath_r4_model from 'fhirpath/fhir-context/r4/index.js';\nimport { getInitialExpression, getItemPopulationContextName } from './readPopulationExpressions';\nimport { createQuestionnaireReference } from './createQuestionnaireReference';\nimport { parseItemInitialToAnswer, parseValueToAnswer } from './parse';\nimport { getValueSetPromise } from '../api/expandValueSet';\nimport type {\n  FetchTerminologyCallback,\n  FetchTerminologyRequestConfig,\n  FetchResourceRequestConfig\n} from '../interfaces';\nimport { handleFhirPathResult } from './createFhirPathContext';\nimport { TERMINOLOGY_SERVER_URL } from '../../globals';\nimport { getDisplayName } from './humanName';\n\n/**\n * Constructs a questionnaireResponse recursively from a specified questionnaire, its subject and its initialExpressions.\n * Handles population, context, and author/encounter metadata for the response.\n *\n * @param questionnaire - The questionnaire resource to construct a response from\n * @param subject - A subject reference to form the subject within the response\n * @param populationExpressions - expressions used for pre-population i.e. initialExpressions, itemPopulationContexts\n * @param fhirPathContext - A FHIRContext object to be used for FHIRPath evaluation\n * @param user - An optional FHIR resource representing the user to form the questionnaireResponse.author property\n * @param encounter - An optional encounter resource to form the questionnaireResponse.encounter property\n * @param fetchTerminologyCallback - An optional callback function to fetch terminology resources\n * @param fetchTerminologyRequestConfig - An optional configuration object to pass to the fetchTerminologyCallback\n * @returns A populated questionnaire response wrapped within a Promise\n *\n * @author Sean Fong\n */\nexport async function constructResponse(\n  questionnaire: Questionnaire,\n  subject: Reference,\n  populationExpressions: PopulationExpressions,\n  fhirPathContext: Record<string, any>,\n  user?: FhirResource,\n  encounter?: Encounter,\n  fetchTerminologyCallback?: FetchTerminologyCallback,\n  fetchTerminologyRequestConfig?: FetchTerminologyRequestConfig,\n  fetchResourceRequestConfig?: FetchResourceRequestConfig\n): Promise<QuestionnaireResponse> {\n  const questionnaireResponse: QuestionnaireResponse = {\n    resourceType: 'QuestionnaireResponse',\n    status: 'in-progress'\n  };\n\n  let valueSetPromises: Record<string, ValueSetPromise> = {};\n  const answerOptions: Record<string, QuestionnaireItemAnswerOption[]> = {};\n  const containedValueSets: Record<string, ValueSet> = {};\n\n  if (!questionnaire.item || questionnaire.item.length === 0) {\n    return questionnaireResponse;\n  }\n\n  const containedResources = questionnaire.contained ?? [];\n\n  // Populate questionnaire response as a two-step process\n  // In first step, populate answers from initialExpressions and get answerValueSet promises wherever population of valueSet answers are required\n  // In second step, resolves all promises in parallel and populate valueSet answers by comparing their codes\n  const topLevelQRItems: QuestionnaireResponseItem[] = [];\n  for (const qItem of questionnaire.item) {\n    const newTopLevelQRItem = await constructResponseItemRecursive({\n      qItem,\n      qrItem: {\n        linkId: qItem.linkId,\n        text: qItem.text\n      },\n      qContainedResources: containedResources,\n      populationExpressions,\n      fhirPathContext,\n      valueSetPromises,\n      answerOptions,\n      containedValueSets,\n      fetchTerminologyCallback,\n      fetchTerminologyRequestConfig,\n      fetchResourceRequestConfig\n    });\n\n    if (Array.isArray(newTopLevelQRItem)) {\n      if (newTopLevelQRItem.length > 0) {\n        topLevelQRItems.push(...newTopLevelQRItem);\n      }\n      continue;\n    }\n\n    if (newTopLevelQRItem) {\n      topLevelQRItems.push(newTopLevelQRItem);\n      continue;\n    }\n\n    topLevelQRItems.push({\n      linkId: qItem.linkId,\n      text: qItem.text\n    });\n  }\n\n  // Step 2: populate valueSet answers\n  valueSetPromises = await resolveValueSetPromises(valueSetPromises);\n  const updatedTopLevelQRItems: QuestionnaireResponseItem[] = topLevelQRItems\n    .map((qrItem) =>\n      filterValueSetAnswersRecursive(qrItem, valueSetPromises, answerOptions, containedValueSets)\n    )\n    .filter((item): item is QuestionnaireResponseItem => item !== null);\n\n  questionnaireResponse.questionnaire = createQuestionnaireReference(questionnaire);\n  questionnaireResponse.item = updatedTopLevelQRItems;\n  questionnaireResponse.subject = subject;\n\n  // Add user reference to \"author\" and current dateTime to \"authored\" if user context present\n  if (user && user.id && user.resourceType) {\n    const displayName =\n      user.resourceType === 'Practitioner' ||\n      user.resourceType === 'RelatedPerson' ||\n      user.resourceType === 'Patient'\n        ? getDisplayName(user.name)\n        : undefined;\n    questionnaireResponse.author = {\n      type: user.resourceType,\n      reference: `${user.resourceType}/${user.id}`,\n      ...(displayName && { display: displayName })\n    };\n    questionnaireResponse.authored = new Date().toISOString();\n  }\n\n  // Add encounter reference if present\n  if (encounter && encounter.id) {\n    questionnaireResponse.encounter = {\n      type: 'Encounter',\n      reference: `Encounter/${encounter.id}`\n    };\n  }\n\n  // Add \"http://hl7.org/fhir/uv/sdc/StructureDefinition/sdc-questionnaireresponse\" profile\n  // const profiles: string[] = [\n  //   'http://hl7.org/fhir/uv/sdc/StructureDefinition/sdc-questionnaireresponse'\n  // ];\n  questionnaireResponse.meta = questionnaireResponse.meta || {};\n  questionnaireResponse.meta.source = 'https://smartforms.csiro.au';\n\n  return questionnaireResponse;\n}\n\ninterface ConstructResponseItemRecursiveParams {\n  qItem: QuestionnaireItem;\n  qrItem: QuestionnaireResponseItem;\n  qContainedResources: FhirResource[];\n  populationExpressions: PopulationExpressions;\n  fhirPathContext: Record<string, any>;\n  valueSetPromises: Record<string, ValueSetPromise>;\n  answerOptions: Record<string, QuestionnaireItemAnswerOption[]>;\n  containedValueSets: Record<string, ValueSet>;\n  fetchTerminologyCallback?: FetchTerminologyCallback;\n  fetchTerminologyRequestConfig?: FetchTerminologyRequestConfig;\n  fetchResourceRequestConfig?: FetchResourceRequestConfig;\n}\n\n/**\n * Read a single questionnaire item/group recursively and generating questionnaire response items from initialExpressions if present\n *\n * @author Sean Fong\n */\nasync function constructResponseItemRecursive(\n  params: ConstructResponseItemRecursiveParams\n): Promise<QuestionnaireResponseItem | QuestionnaireResponseItem[] | null> {\n  const {\n    qItem,\n    qrItem,\n    qContainedResources,\n    populationExpressions,\n    fhirPathContext,\n    valueSetPromises,\n    answerOptions,\n    containedValueSets,\n    fetchTerminologyCallback,\n    fetchTerminologyRequestConfig,\n    fetchResourceRequestConfig\n  } = params;\n\n  const items = qItem.item;\n\n  if (items && items.length > 0) {\n    // iterate through items of item recursively\n    const qrItems: QuestionnaireResponseItem[] = [];\n\n    // If qItem is a repeat group, populate instances of repeat groups containing child items\n    if (qItem.type === 'group' && qItem.repeats) {\n      // Create number of repeat group instances based on the number of answers that the first child item has\n      return await constructRepeatGroupInstances(\n        qItem,\n        qContainedResources,\n        populationExpressions,\n        fhirPathContext,\n        valueSetPromises,\n        answerOptions,\n        containedValueSets,\n        fetchTerminologyCallback,\n        fetchTerminologyRequestConfig,\n        fetchResourceRequestConfig\n      );\n    }\n\n    // Otherwise loop through qItem as usual\n    for (const item of items) {\n      const newQrItem = await constructResponseItemRecursive({\n        qItem: item,\n        qrItem,\n        qContainedResources,\n        populationExpressions,\n        fhirPathContext,\n        valueSetPromises,\n        answerOptions,\n        containedValueSets,\n        fetchTerminologyCallback: fetchTerminologyCallback,\n        fetchTerminologyRequestConfig: fetchTerminologyRequestConfig,\n        fetchResourceRequestConfig: fetchResourceRequestConfig\n      });\n\n      if (Array.isArray(newQrItem)) {\n        if (newQrItem.length > 0) {\n          qrItems.push(...newQrItem);\n        }\n      } else if (newQrItem) {\n        qrItems.push(newQrItem);\n      }\n    }\n\n    return constructGroupItem({\n      qItem,\n      qrItems,\n      qContainedResources,\n      populationExpressions,\n      valueSetPromises,\n      answerOptions,\n      containedValueSets,\n      fetchTerminologyCallback: fetchTerminologyCallback,\n      fetchTerminologyRequestConfig: fetchTerminologyRequestConfig\n    });\n  }\n\n  return constructSingleItem({\n    qItem,\n    qContainedResources,\n    populationExpressions,\n    valueSetPromises,\n    answerOptions,\n    containedValueSets,\n    fetchTerminologyCallback: fetchTerminologyCallback,\n    fetchTerminologyRequestConfig: fetchTerminologyRequestConfig\n  });\n}\n\ninterface ConstructGroupItemParams {\n  qItem: QuestionnaireItem;\n  qrItems: QuestionnaireResponseItem[];\n  qContainedResources: FhirResource[];\n  populationExpressions: PopulationExpressions;\n  valueSetPromises: Record<string, ValueSetPromise>;\n  answerOptions: Record<string, QuestionnaireItemAnswerOption[]>;\n  containedValueSets: Record<string, ValueSet>;\n  fetchTerminologyCallback?: FetchTerminologyCallback | undefined;\n  fetchTerminologyRequestConfig?: FetchTerminologyRequestConfig;\n}\n\nfunction constructGroupItem(params: ConstructGroupItemParams): QuestionnaireResponseItem | null {\n  const {\n    qItem,\n    qrItems,\n    qContainedResources,\n    populationExpressions,\n    valueSetPromises,\n    answerOptions,\n    containedValueSets,\n    fetchTerminologyCallback,\n    fetchTerminologyRequestConfig\n  } = params;\n\n  const { initialExpressions } = populationExpressions;\n\n  let populatedAnswers: QuestionnaireResponseItemAnswer[] | undefined;\n\n  // This only applies to question (non-group) items! 'group' items should not have item.answer\n  if (qItem.type !== 'group') {\n    // Populate answers from item.initial if present\n    // Process item.initial first, then can potentially overwrite with initialExpressions\n    if (qItem.initial) {\n      populatedAnswers = qItem.initial\n        .map((initial) => parseItemInitialToAnswer(initial))\n        .filter((answer): answer is QuestionnaireResponseItemAnswer => answer !== null);\n    }\n\n    // Populate answers from initialExpressions if present\n    const initialExpression = initialExpressions[qItem.linkId];\n    if (initialExpression) {\n      const initialValues = initialExpression.value;\n\n      if (initialValues && initialValues.length) {\n        const { newValues, expandRequired } = getAnswerValues(initialValues, qItem);\n        populatedAnswers = newValues;\n\n        if (expandRequired) {\n          recordAnswerValueSet(\n            qItem,\n            valueSetPromises,\n            fetchTerminologyCallback,\n            fetchTerminologyRequestConfig\n          );\n        }\n\n        recordAnswerOption(qItem, answerOptions);\n        recordContainedValueSet(qItem, qContainedResources, containedValueSets);\n      }\n    }\n  }\n\n  if (qrItems.length > 0) {\n    return {\n      linkId: qItem.linkId,\n      text: qItem.text,\n      item: qrItems,\n      ...(populatedAnswers ? { answer: populatedAnswers } : {})\n    };\n  }\n\n  if (populatedAnswers) {\n    return {\n      linkId: qItem.linkId,\n      text: qItem.text,\n      answer: populatedAnswers\n    };\n  }\n\n  return null;\n}\n\ninterface ConstructSingleItemParams {\n  qItem: QuestionnaireItem;\n  qContainedResources: FhirResource[];\n  populationExpressions: PopulationExpressions;\n  valueSetPromises: Record<string, ValueSetPromise>;\n  answerOptions: Record<string, QuestionnaireItemAnswerOption[]>;\n  containedValueSets: Record<string, ValueSet>;\n  fetchTerminologyCallback?: FetchTerminologyCallback | undefined;\n  fetchTerminologyRequestConfig?: FetchTerminologyRequestConfig;\n}\n\nfunction constructSingleItem(params: ConstructSingleItemParams): QuestionnaireResponseItem | null {\n  const {\n    qItem,\n    qContainedResources,\n    populationExpressions,\n    valueSetPromises,\n    answerOptions,\n    containedValueSets,\n    fetchTerminologyCallback,\n    fetchTerminologyRequestConfig\n  } = params;\n\n  const { initialExpressions } = populationExpressions;\n\n  // Populate answers from initialExpressions if present\n  const initialExpression = initialExpressions[qItem.linkId];\n  if (initialExpression) {\n    const initialValues = initialExpression.value;\n\n    if (initialValues && initialValues.length) {\n      const { newValues, expandRequired } = getAnswerValues(initialValues, qItem);\n\n      if (expandRequired) {\n        recordAnswerValueSet(\n          qItem,\n          valueSetPromises,\n          fetchTerminologyCallback,\n          fetchTerminologyRequestConfig\n        );\n      }\n\n      recordAnswerOption(qItem, answerOptions);\n      recordContainedValueSet(qItem, qContainedResources, containedValueSets);\n\n      return {\n        linkId: qItem.linkId,\n        answer: newValues,\n        ...(qItem.text ? { text: qItem.text } : {})\n      };\n    }\n  }\n\n  // Populate answers from item.initial if present\n  if (qItem.initial) {\n    return {\n      linkId: qItem.linkId,\n      answer: qItem.initial\n        .map((initial) => parseItemInitialToAnswer(initial))\n        .filter((answer): answer is QuestionnaireResponseItemAnswer => answer !== null),\n      ...(qItem.text ? { text: qItem.text } : {})\n    };\n  }\n\n  return null;\n}\n\nfunction recordAnswerValueSet(\n  qItem: QuestionnaireItem,\n  valueSetPromises: Record<string, ValueSetPromise>,\n  fetchTerminologyCallback?: FetchTerminologyCallback,\n  fetchTerminologyRequestConfig?: FetchTerminologyRequestConfig\n) {\n  if (qItem.answerValueSet) {\n    getValueSetPromise(\n      qItem,\n      qItem.answerValueSet,\n      valueSetPromises,\n      fetchTerminologyCallback,\n      fetchTerminologyRequestConfig\n    );\n  }\n}\n\nfunction recordAnswerOption(\n  qItem: QuestionnaireItem,\n  answerOptions: Record<string, QuestionnaireItemAnswerOption[]>\n) {\n  if (qItem.answerOption) {\n    answerOptions[qItem.linkId] = qItem.answerOption;\n  }\n}\n\nfunction recordContainedValueSet(\n  qItem: QuestionnaireItem,\n  qContainedResources: FhirResource[],\n  containedValueSets: Record<string, ValueSet>\n) {\n  if (qItem.answerValueSet && qItem.answerValueSet.startsWith('#')) {\n    const containedReference = qItem.answerValueSet.slice(1);\n    const containedValueSet = qContainedResources.find(\n      (resource) => resource.id === containedReference\n    );\n\n    if (containedValueSet) {\n      containedValueSets[qItem.linkId] = containedValueSet as ValueSet;\n    }\n  }\n}\n\n/**\n * Determine a specific value[x] type from an initialValue answer\n *\n * @author Sean Fong\n */\nfunction getAnswerValues(\n  initialValues: any[],\n  qItem: QuestionnaireItem\n): { newValues: QuestionnaireResponseItemAnswer[]; expandRequired: boolean } {\n  let expandRequired = false;\n\n  let newValues = initialValues.map((value: any) => {\n    const parsedAnswer = parseValueToAnswer(qItem, value);\n    if (parsedAnswer.valueString && qItem.answerValueSet && !qItem.answerValueSet.startsWith('#')) {\n      expandRequired = true;\n    }\n\n    return parsedAnswer;\n  });\n\n  // If qItem.repeats=false, it cannot have multiple answers\n  if (!qItem.repeats && newValues[0]) {\n    newValues = [newValues[0]];\n  }\n\n  return { newValues, expandRequired };\n}\n\n/**\n * Check if an answer is a datetime in the format YYYY, YYYY-MM, YYYY-MM-DD, YYYY-MM-DDThh:mm:ss+zz:zz\n *\n * @author Sean Fong\n */\nexport function checkIsDateTime(value: string): boolean {\n  const acceptedFormats = ['YYYY', 'YYYY-MM', 'YYYY-MM-DD', 'YYYY-MM-DDTHH:mm:ssZ'];\n  const formattedDate = dayjs(value).format();\n  return moment(formattedDate, acceptedFormats, true).isValid();\n}\n\nexport function convertDateTimeToDate(value: string): string {\n  const acceptedFormats = ['YYYY-MM-DDTHH:mm:ssZ'];\n  const formattedDate = dayjs(value).format();\n  const isDateTime = moment(formattedDate, acceptedFormats, true).isValid();\n\n  if (isDateTime) {\n    return moment(formattedDate).format('YYYY-MM-DD');\n  }\n\n  return value;\n}\n\n/**\n * Check if an answer is in a  time format - Regex: ([01][0-9]|2[0-3]):[0-5][0-9]:([0-5][0-9]|60)(\\.[0-9]+)?\n *\n * @author Sean Fong\n */\nexport function checkIsTime(value: string): boolean {\n  const timeRegex = /^([01][0-9]|2[0-3]):[0-5][0-9]:([0-5][0-9]|60)(\\.[0-9]+)?$/;\n  return timeRegex.test(value);\n}\n\n/**\n * Constructed populated repeat group instances based on its child items' answers from initialExpressions\n * Used with an itemPopulationContext extension at the parent-level and initialExpressions at the child-level\n * i.e. If there are four child items with five arrays of respective answers obtained from initialExpressions,\n *      five instances of repeat groups will be created.\n *\n * @author Sean Fong\n */\nasync function constructRepeatGroupInstances(\n  qRepeatGroupParent: QuestionnaireItem,\n  qContainedResources: FhirResource[],\n  populationExpressions: PopulationExpressions,\n  fhirPathContext: Record<string, any>,\n  valueSetPromises: Record<string, ValueSetPromise>,\n  answerOptions: Record<string, QuestionnaireItemAnswerOption[]>,\n  containedValueSets: Record<string, ValueSet>,\n  fetchTerminologyCallback?: FetchTerminologyCallback,\n  fetchTerminologyRequestConfig?: FetchTerminologyRequestConfig,\n  fetchResourceRequestConfig?: FetchResourceRequestConfig\n): Promise<QuestionnaireResponseItem[]> {\n  if (!qRepeatGroupParent.item || !qRepeatGroupParent.item[0]) {\n    return [];\n  }\n\n  const { initialExpressions, itemPopulationContexts } = populationExpressions;\n\n  const terminologyServerUrl = fetchTerminologyRequestConfig?.terminologyServerUrl ?? null;\n  const fhirServerUrl = fetchResourceRequestConfig?.sourceServerUrl ?? null;\n\n  // Look in child items to relate back to the itemPopulationContext being used\n  let itemPopulationContextExpression: string | undefined;\n  let itemPopulationContext: ItemPopulationContext | undefined;\n  for (const childItem of qRepeatGroupParent.item) {\n    const expression = getInitialExpression(childItem)?.expression;\n    if (!expression) continue;\n\n    const contextName = getItemPopulationContextName(expression);\n    const context = contextName ? itemPopulationContexts[contextName] : undefined;\n\n    if (context && context.value) {\n      itemPopulationContextExpression = expression;\n      itemPopulationContext = context;\n      break; // Stop at the first valid match\n    }\n  }\n\n  // No itemPopulationContext is found, return an empty array\n  if (!itemPopulationContextExpression || !itemPopulationContext || !itemPopulationContext.value) {\n    return [];\n  }\n\n  // Look for itemPopulationContexts which uses the parent itemPopulationContext\n  const associatedItemPopulationContexts: Record<string, ItemPopulationContext> = {};\n  for (const name in itemPopulationContexts) {\n    const lookupItemPopulationContext = itemPopulationContexts[name];\n    if (lookupItemPopulationContext) {\n      const itemPopulationContextName = getItemPopulationContextName(\n        lookupItemPopulationContext.expression\n      );\n\n      if (\n        itemPopulationContextName ===\n        getItemPopulationContextName(lookupItemPopulationContext.expression)\n      ) {\n        associatedItemPopulationContexts[lookupItemPopulationContext.linkId] =\n          lookupItemPopulationContext;\n      }\n    }\n  }\n\n  const itemPopulationContextValues = itemPopulationContext.value;\n\n  const qrRepeatGroupInstances: QuestionnaireResponseItem[] = [];\n  for (const itemPopulationContextValue of itemPopulationContextValues) {\n    const qrRepeatGroupInstance: QuestionnaireResponseItem = {\n      linkId: qRepeatGroupParent.linkId,\n      ...(qRepeatGroupParent.text ? { text: qRepeatGroupParent.text } : {}),\n      item: []\n    };\n\n    for (const childItem of qRepeatGroupParent.item) {\n      // Populate answers from initialExpression — read directly from the questionnaire item\n      // so that expressions are evaluated per-item against the scoped context, not the global one\n      const childInitialExpression = getInitialExpression(childItem);\n      if (childInitialExpression?.expression) {\n        // Allow child items consuming itemPopulationContext to access renderer-wide variables via fhirPathContext\n        const fhirPathContextWithItemPopulationContext = {\n          ...fhirPathContext,\n          [itemPopulationContext.name]: [itemPopulationContextValue]\n        };\n\n        try {\n          const fhirPathResult = fhirpath.evaluate(\n            {},\n            childInitialExpression.expression,\n            fhirPathContextWithItemPopulationContext,\n            fhirpath_r4_model,\n            {\n              async: true,\n              terminologyUrl: terminologyServerUrl ?? TERMINOLOGY_SERVER_URL,\n              ...(fhirServerUrl && { fhirServerUrl })\n            }\n          );\n          const initialValues = await handleFhirPathResult(fhirPathResult);\n\n          if (initialValues && initialValues.length > 0 && initialValues[0] !== '') {\n            const { newValues, expandRequired } = getAnswerValues(initialValues, childItem);\n\n            if (expandRequired) {\n              recordAnswerValueSet(\n                childItem,\n                valueSetPromises,\n                fetchTerminologyCallback,\n                fetchTerminologyRequestConfig\n              );\n            }\n\n            recordAnswerOption(childItem, answerOptions);\n            recordContainedValueSet(childItem, qContainedResources, containedValueSets);\n\n            qrRepeatGroupInstance.item?.push({\n              linkId: childItem.linkId,\n              answer: newValues,\n              ...(childItem.text ? { text: childItem.text } : {})\n            });\n          }\n        } catch (e) {\n          // e is not thrown as an Error type in fhirpath.js, so we can't use `if (e instanceof Error)` here\n          console.warn(\n            `SDC-Populate Error: fhirpath evaluation for ItemPopulationContext child for expression ${childInitialExpression.expression} failed. Details below:` +\n              e\n          );\n        }\n      }\n\n      // Populate answers from associated itemPopulationContexts\n      const associatedItemPopulationContext = associatedItemPopulationContexts[childItem.linkId];\n      if (associatedItemPopulationContext) {\n        const newQrItem = await constructResponseItemRecursive({\n          qItem: childItem,\n          qrItem: {\n            linkId: childItem.linkId,\n            text: childItem.text\n          },\n          qContainedResources,\n          populationExpressions: {\n            initialExpressions,\n            itemPopulationContexts: {\n              [associatedItemPopulationContext.name]: associatedItemPopulationContext\n            }\n          },\n          fhirPathContext,\n          valueSetPromises,\n          answerOptions,\n          containedValueSets,\n          fetchTerminologyCallback,\n          fetchTerminologyRequestConfig,\n          fetchResourceRequestConfig\n        });\n\n        if (Array.isArray(newQrItem)) {\n          if (newQrItem.length > 0) {\n            qrRepeatGroupInstance.item?.push(...newQrItem);\n          }\n        } else if (newQrItem) {\n          qrRepeatGroupInstance.item?.push(newQrItem);\n        }\n      }\n    }\n\n    qrRepeatGroupInstances.push(qrRepeatGroupInstance);\n  }\n\n  return qrRepeatGroupInstances;\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Questionnaire } from 'fhir/r4';\n\n/**\n * Creates a canonical reference string for a Questionnaire resource.\n * Uses url|version if available, otherwise falls back to Questionnaire/{id}.\n */\nexport function createQuestionnaireReference(questionnaire: Questionnaire) {\n  // Use {url}|{version}\n  if (questionnaire.url) {\n    let questionnaireReference = questionnaire.url;\n    if (questionnaire.version) {\n      questionnaireReference += '|' + questionnaire.version;\n    }\n    return questionnaireReference;\n  }\n\n  // If no url exists, use Questionnaire/{id}\n  if (questionnaire.id) {\n    return `Questionnaire/${questionnaire.id}`;\n  }\n\n  return '';\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { QuestionnaireItemAnswerOption, QuestionnaireResponseItemAnswer } from 'fhir/r4';\nimport { getRelevantCodingProperties } from './codingProperties';\n\n/**\n * Find and return corresponding answerOption based on selected answer in form.\n * Matches by code, display, string, or integer value.\n *\n * @author Sean Fong\n */\nexport function findInAnswerOptions(\n  options: QuestionnaireItemAnswerOption[],\n  str: string\n): QuestionnaireResponseItemAnswer | undefined {\n  for (const option of options) {\n    if (option.valueCoding) {\n      if (str === option.valueCoding.code) {\n        return {\n          valueCoding: getRelevantCodingProperties(option.valueCoding)\n        };\n      }\n\n      // handle case where valueCoding.code is not present\n      if (str === option.valueCoding.display) {\n        return {\n          valueCoding: getRelevantCodingProperties(option.valueCoding)\n        };\n      }\n    }\n\n    if (option.valueString) {\n      if (str === option.valueString) {\n        return {\n          valueString: option.valueString\n        };\n      }\n    }\n\n    if (option.valueInteger) {\n      if (str === option.valueInteger.toString()) {\n        return {\n          valueInteger: option.valueInteger\n        };\n      }\n    }\n  }\n\n  return;\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n  QuestionnaireItem,\n  QuestionnaireItemInitial,\n  QuestionnaireResponseItemAnswer\n} from 'fhir/r4';\nimport { findInAnswerOptions } from './answerOption';\nimport { checkIsDateTime, checkIsTime, convertDateTimeToDate } from './constructResponse';\nimport { getRelevantCodingProperties } from './codingProperties';\n\n/**\n * Parses a QuestionnaireItemInitial into a QuestionnaireResponseItemAnswer.\n * Handles all FHIR primitive and complex types for initial values.\n */\nexport function parseItemInitialToAnswer(\n  initial: QuestionnaireItemInitial\n): QuestionnaireResponseItemAnswer | null {\n  if (typeof initial.valueBoolean === 'boolean') {\n    return { valueBoolean: initial.valueBoolean };\n  }\n\n  if (typeof initial.valueDecimal === 'number') {\n    return { valueDecimal: initial.valueDecimal };\n  }\n\n  if (typeof initial.valueInteger === 'number') {\n    return { valueInteger: initial.valueInteger };\n  }\n\n  if (typeof initial.valueDate === 'string') {\n    return { valueDate: initial.valueDate };\n  }\n\n  if (typeof initial.valueDateTime === 'string') {\n    return { valueDateTime: initial.valueDateTime };\n  }\n\n  if (typeof initial.valueTime === 'string') {\n    return { valueTime: initial.valueTime };\n  }\n\n  if (typeof initial.valueString === 'string') {\n    return { valueString: initial.valueString };\n  }\n\n  if (typeof initial.valueUri === 'string') {\n    return { valueUri: initial.valueUri };\n  }\n\n  if (initial.valueAttachment) {\n    return { valueAttachment: initial.valueAttachment };\n  }\n\n  if (initial.valueCoding) {\n    return {\n      valueCoding: getRelevantCodingProperties(initial.valueCoding)\n    };\n  }\n\n  if (initial.valueQuantity) {\n    return { valueQuantity: initial.valueQuantity };\n  }\n\n  if (initial.valueReference) {\n    return { valueReference: initial.valueReference };\n  }\n\n  return null;\n}\n\n/**\n * Parses a value and QuestionnaireItem into a QuestionnaireResponseItemAnswer.\n * Handles answerOption matching, type conversion, and FHIR-specific logic.\n */\nexport function parseValueToAnswer(\n  qItem: QuestionnaireItem,\n  value: any\n): QuestionnaireResponseItemAnswer {\n  if (qItem.answerOption) {\n    const answerOption = findInAnswerOptions(qItem.answerOption, value);\n\n    if (answerOption) {\n      return answerOption;\n    }\n  }\n\n  if (typeof value === 'boolean' && qItem.type === 'boolean') {\n    return { valueBoolean: value };\n  }\n\n  if (typeof value === 'number') {\n    if (qItem.type === 'decimal') {\n      return { valueDecimal: value };\n    }\n    if (qItem.type === 'integer') {\n      return { valueInteger: value };\n    }\n  }\n\n  if (typeof value === 'object' && value.unit) {\n    return { valueQuantity: value };\n  }\n\n  if (typeof value === 'object' && value.system && value.code) {\n    return {\n      valueCoding: getRelevantCodingProperties(value)\n    };\n  }\n\n  // Value is string at this point\n  if (qItem.type === 'date' && checkIsDateTime(value)) {\n    return { valueDate: convertDateTimeToDate(value) };\n  }\n\n  if (qItem.type === 'dateTime' && checkIsDateTime(value)) {\n    return { valueDateTime: value };\n  }\n\n  if (qItem.type === 'time' && checkIsTime(value)) {\n    return { valueTime: value };\n  }\n\n  return { valueString: value };\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { TERMINOLOGY_SERVER_URL } from '../../globals';\n\nconst headers = {\n  'Content-Type': 'application/fhir+json;charset=utf-8',\n  Accept: 'application/json;charset=utf-8'\n};\n\nexport async function defaultTerminologyRequest(query: string) {\n  const requestUrl = TERMINOLOGY_SERVER_URL + '/' + query;\n  const response = await fetch(requestUrl, { headers });\n\n  if (!response.ok) {\n    throw `HTTP error when performing ${requestUrl}. Status: ${response.status}`;\n  }\n\n  return response.json();\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { ValueSetPromise } from '../interfaces/expressions.interface';\nimport type { QuestionnaireItem } from 'fhir/r4';\nimport type { FetchTerminologyCallback, FetchTerminologyRequestConfig } from '../interfaces';\nimport { defaultTerminologyRequest } from './defaultTerminologyRequest';\n\n/**\n * Adds a promise for ValueSet $expand to the promise map for the given questionnaire item.\n * Uses either a custom callback or the default request. This enables async expansion for value sets.\n */\nexport function getValueSetPromise(\n  qItem: QuestionnaireItem,\n  fullUrl: string,\n  valueSetPromiseMap: Record<string, ValueSetPromise>,\n  fetchTerminologyCallback?: FetchTerminologyCallback,\n  fetchTerminologyRequestConfig?: FetchTerminologyRequestConfig\n) {\n  let valueSetUrl = fullUrl;\n  if (fullUrl.includes('ValueSet/$expand?url=')) {\n    const splitUrl = fullUrl.split('ValueSet/$expand?url=');\n    if (splitUrl[1]) {\n      valueSetUrl = splitUrl[1];\n    }\n  }\n\n  valueSetUrl = valueSetUrl.replace('|', '&version=');\n  const query = `ValueSet/$expand?url=${valueSetUrl}`;\n\n  const valueSetPromise =\n    fetchTerminologyCallback && fetchTerminologyRequestConfig\n      ? fetchTerminologyCallback(query, fetchTerminologyRequestConfig)\n      : defaultTerminologyRequest(query);\n\n  valueSetPromiseMap[qItem.linkId] = {\n    promise: valueSetPromise\n  };\n}\n","import type { HumanName } from 'fhir/r4';\n\n/**\n * Returns a display name string from a FHIR HumanName array.\n * Uses the text field if available, otherwise constructs from prefix, given, and family.\n */\nexport function getDisplayName(name: HumanName[] | undefined): string {\n  if (name?.[0]?.text) {\n    return `${name?.[0].text ?? null}`;\n  }\n\n  const prefix = name?.[0]?.prefix?.[0] ?? '';\n  const givenName = name?.[0]?.given?.[0] ?? '';\n  const familyName = name?.[0]?.family ?? '';\n\n  const fullName = [prefix, givenName, familyName].filter(Boolean).join(' ');\n\n  if (fullName.length === 0) {\n    return 'null';\n  }\n\n  return fullName;\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { OperationOutcomeIssue, QuestionnaireResponse } from 'fhir/r4';\nimport type {\n  CustomContextResultParameter,\n  OutputParameters,\n  ResponseParameter\n} from '../interfaces';\nimport { Base64 } from 'js-base64';\n\n/**\n * Create output parameters as a response to be returned to the renderer. If they are issues, return with an issues parameter.\n * Encodes context results as a base64 JSON attachment for downstream use.\n */\nexport function createOutputParameters(\n  questionnaireResponse: QuestionnaireResponse,\n  issues: OperationOutcomeIssue[],\n  contextResult: Record<string, any>\n): OutputParameters {\n  const responseParameter: ResponseParameter = {\n    name: 'response',\n    resource: questionnaireResponse\n  };\n\n  const customContextResultParameter: CustomContextResultParameter = {\n    name: 'contextResult-custom',\n    valueAttachment: {\n      contentType: 'application/json',\n      data: Base64.encode(JSON.stringify(contextResult))\n    }\n  };\n\n  // No issues to report\n  if (issues.length === 0) {\n    return {\n      resourceType: 'Parameters',\n      parameter: [responseParameter, customContextResultParameter]\n    };\n  }\n\n  // There are issues, so include issues parameter\n  return {\n    resourceType: 'Parameters',\n    parameter: [\n      responseParameter,\n      {\n        name: 'issues',\n        resource: {\n          resourceType: 'OperationOutcome',\n          issue: issues\n        }\n      },\n      customContextResultParameter\n    ]\n  };\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* Directly lifted frpm packages/smart-forms-renderer repository\n\n/**\n * Generate an array of QuestionnaireResponseItems corresponding to its QuestionnaireItem indexes an array.\n * QuestionnaireItems without a corresponding QuestionnaireResponseItem is set as undefined.\n * i.e. QItems = [QItem0, QItem1, QItem2]. Only QItem0 and QItem2 have QrItems\n * Generated array: [QrItem0, undefined, QrItem2]\n * Note: There's a bug where if the qItems are child items from a repeat group, the function fails at the isRepeatGroup line.\n *       Ensure that repeat groups are handled prior to calling this function.\n *\n * @author Sean Fong\n */\nimport type {\n  Coding,\n  Extension,\n  Questionnaire,\n  QuestionnaireItem,\n  QuestionnaireResponseItem\n} from 'fhir/r4';\n\nexport function getQrItemsIndex(\n  qItems: QuestionnaireItem[],\n  qrItems: QuestionnaireResponseItem[],\n  qItemsIndexMap: Record<string, number>\n): (QuestionnaireResponseItem | QuestionnaireResponseItem[] | undefined)[] {\n  // Generate a <linkId, QrItem OR QrItems> dictionary\n  const qrItemsCollected: Record<string, QuestionnaireResponseItem | QuestionnaireResponseItem[]> =\n    {};\n  for (const qrItem of qrItems) {\n    const linkId = qrItem.linkId;\n\n    // If item already exists, it has multiple qrItems and is therefore a repeat group\n    if (qrItemsCollected[linkId]) {\n      let storedValue = qrItemsCollected[linkId];\n\n      // Create an array out of initial stored value if it is not an array initially\n      if (!Array.isArray(storedValue)) {\n        // @ts-ignore - tried to make this type-safe which breaks this whole implementation, getQrItemsIndex() is super battle tested so we ignore this\n        storedValue = [storedValue];\n      }\n\n      // Push new qrItem into array\n      // @ts-ignore - tried to make this type-safe which breaks this whole implementation, getQrItemsIndex() is super battle tested so we ignore this\n      storedValue.push(qrItem);\n      // @ts-ignore - tried to make this type-safe which breaks this whole implementation, getQrItemsIndex() is super battle tested so we ignore this\n      qrItemsCollected[linkId] = storedValue;\n    } else {\n      const qItemIndex = qItemsIndexMap[linkId];\n\n      // Assign either a qrItem array or a single qrItem based on whether it is a repeatGroup or not\n      const isRepeatGroup =\n        // @ts-ignore - tried to make this type-safe which breaks this whole implementation, getQrItemsIndex() is super battle tested so we ignore this\n        isRepeatItemAndNotCheckbox(qItems[qItemIndex]) && qItems[qItemIndex].type === 'group';\n\n      qrItemsCollected[linkId] = isRepeatGroup ? [qrItem] : qrItem;\n    }\n  }\n\n  // Generate an array of QuestionnaireResponseItems corresponding to its QuestionnaireItem indexes in sequence\n  // Qitems with no answers has a default value of undefined\n  return qItems.reduce(\n    (mapping: (QuestionnaireResponseItem | QuestionnaireResponseItem[])[], qItem, i) => {\n      const qrItemOrItems = qrItemsCollected[qItem.linkId];\n      // If qItem is a repeat group, default its value to an array instead of undefined\n      if (isRepeatItemAndNotCheckbox(qItem) && qItem.type === 'group') {\n        // @ts-ignore - tried to make this type-safe which breaks this whole implementation, getQrItemsIndex() is super battle tested so we ignore this\n        mapping[i] = qrItemOrItems ? qrItemsCollected[qItem.linkId] : [];\n      } else {\n        // @ts-ignore - tried to make this type-safe which breaks this whole implementation, getQrItemsIndex() is super battle tested so we ignore this\n        mapping[i] = qrItemsCollected[qItem.linkId];\n      }\n      return mapping;\n    },\n    []\n  );\n}\n\n/**\n * Generate a dictionary of QuestionnaireItems linkIds mapped to their respective array indexes `<linkId, QItemIndex>`\n * i.e. `{ ee2589d5: 0, f9aaa187: 1, 88cab112: 2 }`\n * where ee2589d5, f9aaa187 and 88cab112 are linkIds of QItem0, QItem1 and QItem2 respectively\n *\n * @author Sean Fong\n */\nexport function mapQItemsIndex(\n  questionnaireOrQItem: QuestionnaireItem | Questionnaire\n): Record<string, number> {\n  if (!questionnaireOrQItem.item) {\n    return {};\n  }\n\n  // generate a <linkId, QItemIndex> dictionary\n  return questionnaireOrQItem.item.reduce((mapping: Record<string, number>, item, i) => {\n    mapping[item.linkId] = i;\n    return mapping;\n  }, {});\n}\n\n/**\n * Check if qItem is a repeat item AND if it isn't a checkbox item\n * Note: repeat checkbox items are rendered as multi-select checkbox instead of being rendered as a traditional repeat item\n *\n * @author Sean Fong\n */\nexport function isRepeatItemAndNotCheckbox(qItem: QuestionnaireItem): boolean {\n  // Prevents form from crashing due to mismatched Q and QR\n  // In reality this should never happen\n  if (!qItem) {\n    return false;\n  }\n\n  // Check if qItem is a checkbox item\n  let isCheckbox = false;\n  const itemControl = qItem?.extension?.find(\n    (extension: Extension) =>\n      extension.url === 'http://hl7.org/fhir/StructureDefinition/questionnaire-itemControl'\n  );\n  if (itemControl) {\n    const isCheckboxItemControl = itemControl.valueCodeableConcept?.coding?.find(\n      (coding: Coding) => coding.code === 'check-box'\n    );\n    if (isCheckboxItemControl) {\n      isCheckbox = true;\n    }\n  }\n\n  return !!qItem['repeats'] && !isCheckbox;\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/* Directly lifted frpm packages/smart-forms-renderer repository */\n\nimport type {\n  Questionnaire,\n  QuestionnaireItem,\n  QuestionnaireResponse,\n  QuestionnaireResponseItem\n} from 'fhir/r4';\nimport { getQrItemsIndex, mapQItemsIndex } from './misc';\nimport { qrItemHasItemsOrAnswer } from './removeEmptyAnswers';\n\nexport type RecursiveUpdateFunction<T> = (\n  qItem: QuestionnaireItem,\n  qrItemOrItems: QuestionnaireResponseItem | QuestionnaireResponseItem[] | null,\n  extraData: T\n) => QuestionnaireResponseItem | QuestionnaireResponseItem[] | null;\n\n/**\n * A generic (and safe) way to update a QuestionnaireResponse given a recursive function and a set of data i.e. Record<linkId, calculated expression values>, Record<linkId, re-populated values>\n * This function relies heavily on mapQItemsIndex() and getQrItemsIndex() to accurately pinpoint the locations of QR items based on their positions in the Q, taking into account repeating group answers, non-filled questions, etc\n *\n * @author Sean Fong\n */\nexport function updateQuestionnaireResponse<T>(\n  questionnaire: Questionnaire,\n  questionnaireResponse: QuestionnaireResponse,\n  recursiveUpdateFunction: RecursiveUpdateFunction<T>,\n  extraData: T\n) {\n  if (\n    !questionnaire.item ||\n    questionnaire.item.length === 0 ||\n    !questionnaireResponse.item ||\n    questionnaireResponse.item.length === 0\n  ) {\n    return questionnaireResponse;\n  }\n\n  const qItemsIndexMap = mapQItemsIndex(questionnaire);\n  const topLevelQRItemsByIndex = getQrItemsIndex(\n    questionnaire.item,\n    questionnaireResponse.item,\n    qItemsIndexMap\n  );\n\n  const topLevelQrItems = [];\n  for (const [index, topLevelQItem] of questionnaire.item.entries()) {\n    const topLevelQRItemOrItems = topLevelQRItemsByIndex[index] ?? {\n      linkId: topLevelQItem.linkId,\n      text: topLevelQItem.text,\n      item: []\n    };\n\n    const updatedTopLevelQRItem = recursiveUpdateFunction(\n      topLevelQItem,\n      topLevelQRItemOrItems,\n      extraData\n    );\n\n    if (Array.isArray(updatedTopLevelQRItem)) {\n      if (updatedTopLevelQRItem.length > 0) {\n        topLevelQrItems.push(...updatedTopLevelQRItem);\n      }\n      continue;\n    }\n\n    if (updatedTopLevelQRItem && qrItemHasItemsOrAnswer(updatedTopLevelQRItem)) {\n      topLevelQrItems.push(updatedTopLevelQRItem);\n    }\n  }\n\n  return { ...questionnaireResponse, item: topLevelQrItems };\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n  Questionnaire,\n  QuestionnaireItem,\n  QuestionnaireResponse,\n  QuestionnaireResponseItem,\n  QuestionnaireResponseItemAnswer\n} from 'fhir/r4';\nimport { updateQuestionnaireResponse } from './genericRecursive';\nimport { getQrItemsIndex, mapQItemsIndex } from './misc';\n\n/**\n * Removes empty answers from a QuestionnaireResponse by recursively cleaning items.\n * Ensures the response only contains items with valid answers or child items.\n */\nexport function removeEmptyAnswersFromResponse(\n  questionnaire: Questionnaire,\n  questionnaireResponse: QuestionnaireResponse\n): QuestionnaireResponse {\n  return updateQuestionnaireResponse(\n    questionnaire,\n    questionnaireResponse,\n    removeEmptyAnswersFromItemRecursive,\n    null\n  );\n}\n\n/**\n * Recursively go through the questionnaireResponse and remove qrItems whose qItems are empty in the form.\n * Cleans up nested and repeating groups for a valid response structure.\n *\n * @author Sean Fong\n */\nexport function removeEmptyAnswersFromItemRecursive(\n  qItem: QuestionnaireItem,\n  qrItemOrItems: QuestionnaireResponseItem | QuestionnaireResponseItem[] | null\n): QuestionnaireResponseItem | QuestionnaireResponseItem[] | null {\n  // Process repeating group items separately\n  const hasMultipleAnswers = Array.isArray(qrItemOrItems);\n  if (hasMultipleAnswers) {\n    return removeEmptyAnswersFromRepeatGroup(qItem, qrItemOrItems);\n  }\n\n  // At this point, qrItemOrItems is a single QuestionnaireResponseItem\n  const qrItem = qrItemOrItems;\n\n  // If QR item is null, return null\n  if (qrItem === null) {\n    return null;\n  }\n\n  // If QR item don't have either item.item and item.answer, return null\n  if (!qrItemHasItemsOrAnswer(qrItem)) {\n    return null;\n  }\n\n  // Process items with child items\n  const childQItems = qItem.item ?? [];\n  const childQrItems = qrItem?.item ?? [];\n  const updatedChildQrItems: QuestionnaireResponseItem[] = [];\n  if (childQItems.length > 0) {\n    const indexMap = mapQItemsIndex(qItem);\n    const qrItemsByIndex = getQrItemsIndex(childQItems, childQrItems, indexMap);\n\n    // Iterate child items\n    for (const [index, childQItem] of childQItems.entries()) {\n      const childQRItemOrItems = qrItemsByIndex[index];\n\n      const updatedChildQRItemOrItems = removeEmptyAnswersFromItemRecursive(\n        childQItem,\n        childQRItemOrItems ?? null\n      );\n\n      if (Array.isArray(updatedChildQRItemOrItems)) {\n        if (updatedChildQRItemOrItems.length > 0) {\n          updatedChildQrItems.push(...updatedChildQRItemOrItems);\n        }\n        continue;\n      }\n\n      if (updatedChildQRItemOrItems) {\n        updatedChildQrItems.push(updatedChildQRItemOrItems);\n      }\n    }\n  }\n\n  // Construct updated qrItem\n  return removeEmptyAnswersFromItem(qItem, qrItem, updatedChildQrItems);\n}\n\nfunction removeEmptyAnswersFromRepeatGroup(\n  qItem: QuestionnaireItem,\n  qrItems: QuestionnaireResponseItem[]\n) {\n  if (!qItem.item) {\n    return [];\n  }\n\n  return qrItems\n    .flatMap((childQrItem) => removeEmptyAnswersFromItemRecursive(qItem, childQrItem))\n    .filter((childQRItem): childQRItem is QuestionnaireResponseItem => !!childQRItem);\n}\n\nfunction removeEmptyAnswersFromItem(\n  qItem: QuestionnaireItem,\n  qrItem: QuestionnaireResponseItem | null,\n  childQrItems: QuestionnaireResponseItem[]\n): QuestionnaireResponseItem | null {\n  if (!qrItem) {\n    return null;\n  }\n\n  // Remove empty answers\n  const updatedAnswers: QuestionnaireResponseItemAnswer[] =\n    qrItem.answer?.filter((answer) => !isEmptyAnswer(answer)) ?? [];\n\n  // Remove item if it has no answers and no children\n  if (updatedAnswers.length === 0 && childQrItems.length === 0) {\n    return null;\n  }\n\n  return {\n    linkId: qItem.linkId,\n    ...(qItem.text && { text: qItem.text }),\n    ...(childQrItems.length > 0 && { item: childQrItems }),\n    ...(updatedAnswers.length > 0 && { answer: updatedAnswers })\n  };\n}\n\nfunction isEmptyAnswer(answer: QuestionnaireResponseItemAnswer): boolean {\n  return answer?.valueString === '' || answer?.item?.length === 0;\n}\n\n/**\n * Check if a QuestionnaireResponseItem has either an item or an answer property.\n * Used to determine if an item should be kept in the cleaned response.\n *\n * @author Sean Fong\n */\nexport function qrItemHasItemsOrAnswer(qrItem: QuestionnaireResponseItem): boolean {\n  return (!!qrItem.item && qrItem.item.length > 0) || (!!qrItem.answer && qrItem.answer.length > 0);\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { Coding } from 'fhir/r4';\nimport type { CodeSystemLookupPromise } from '../interfaces/expressions.interface';\nimport type { FetchTerminologyCallback, FetchTerminologyRequestConfig } from '../interfaces';\nimport { defaultTerminologyRequest } from './defaultTerminologyRequest';\n\n/**\n * Adds a promise for CodeSystem $lookup to the lookup map for the given coding.\n * Uses either a custom callback or the default request. This enables async display resolution for codes.\n */\nexport function getCodeSystemLookupPromise(\n  coding: Coding,\n  codeSystemLookupPromiseMap: Record<string, CodeSystemLookupPromise>,\n  fetchTerminologyCallback?: FetchTerminologyCallback,\n  fetchTerminologyRequestConfig?: FetchTerminologyRequestConfig\n) {\n  const key = `system=${coding.system}&code=${coding.code}`;\n  const query = `CodeSystem/$lookup?${key}`;\n\n  const lookupPromise =\n    fetchTerminologyCallback && fetchTerminologyRequestConfig\n      ? fetchTerminologyCallback(query, fetchTerminologyRequestConfig)\n      : defaultTerminologyRequest(query);\n\n  codeSystemLookupPromiseMap[key] = {\n    promise: lookupPromise,\n    oldCoding: coding\n  };\n}\n\nexport interface LookupResponse {\n  parameter: [DisplayParameter];\n}\n\nexport interface DisplayParameter {\n  name: 'display';\n  valueString: string;\n}\n\n/**\n * Checks if the response is a valid CodeSystem $lookup Parameters result.\n * Ensures the response contains a display parameter for code display resolution.\n */\nexport function lookupResponseIsValid(response: any): response is LookupResponse {\n  return !!(\n    response &&\n    response.resourceType === 'Parameters' &&\n    Array.isArray(response.parameter) &&\n    response.parameter.find((p: any) => p.name === 'display' && p.valueString)\n  );\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { CodeSystemLookupPromise } from '../interfaces/expressions.interface';\nimport type { LookupResponse } from '../api/lookupCodeSystem';\nimport { lookupResponseIsValid } from '../api/lookupCodeSystem';\n\n/**\n * Resolves all CodeSystem $lookup promises and updates codings with display values.\n * Returns a map of updated CodeSystemLookupPromise objects keyed by system/code.\n */\nexport async function resolveLookupPromises(\n  codeSystemLookupPromises: Record<string, CodeSystemLookupPromise>\n): Promise<Record<string, CodeSystemLookupPromise>> {\n  const newCodeSystemLookupPromises: Record<string, CodeSystemLookupPromise> = {};\n\n  const lookupPromiseKeys = Object.keys(codeSystemLookupPromises);\n  const lookupPromiseValues = Object.values(codeSystemLookupPromises);\n\n  const promises = lookupPromiseValues.map((lookupPromise) => lookupPromise.promise);\n  const settledPromises = await Promise.allSettled(promises);\n\n  for (const [i, settledPromise] of settledPromises.entries()) {\n    if (settledPromise.status === 'rejected') {\n      continue;\n    }\n\n    let lookupResult: LookupResponse | null = null;\n\n    // Get lookupResult from response (fhirClient and fetch scenario)\n    if (lookupResponseIsValid(settledPromise.value)) {\n      lookupResult = settledPromise.value;\n    }\n    // Fallback to get valueSet from response.data (axios scenario)\n    if (\n      !lookupResult &&\n      settledPromise.value.data &&\n      lookupResponseIsValid(settledPromise.value.data)\n    ) {\n      lookupResult = settledPromise.value.data;\n    }\n\n    if (!lookupResult) {\n      continue;\n    }\n\n    const key = lookupPromiseKeys[i];\n    const lookupPromise = lookupPromiseValues[i];\n\n    if (key && lookupPromise) {\n      lookupPromise.newCoding = {\n        ...lookupPromise.oldCoding,\n        display: lookupResult.parameter.find((p) => p.name === 'display')?.valueString ?? undefined\n      };\n      newCodeSystemLookupPromises[key] = lookupPromise;\n    }\n  }\n\n  return newCodeSystemLookupPromises;\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { CodeSystemLookupPromise } from '../interfaces/expressions.interface';\nimport type { QuestionnaireResponseItem } from 'fhir/r4';\nimport { getCodeSystemLookupPromise } from '../api/lookupCodeSystem';\nimport type { FetchTerminologyCallback, FetchTerminologyRequestConfig } from '../interfaces';\nimport { resolveLookupPromises } from './resolveLookupPromises';\n\n/**\n * Adds display values to valueCoding answers in a QuestionnaireResponse by performing CodeSystem $lookup if needed.\n */\nexport async function addDisplayToQuestionnaireResponseCodings(\n  qrItems: QuestionnaireResponseItem[],\n  fetchTerminologyCallback?: FetchTerminologyCallback,\n  fetchTerminologyRequestConfig?: FetchTerminologyRequestConfig\n): Promise<void> {\n  const codeSystemLookupPromises: Record<string, CodeSystemLookupPromise> = {};\n  collectCodingsForLookup(\n    qrItems,\n    codeSystemLookupPromises,\n    fetchTerminologyCallback,\n    fetchTerminologyRequestConfig\n  );\n\n  const resolvedCodeSystemLookupPromises = await resolveLookupPromises(codeSystemLookupPromises);\n  applyResolvedDisplays(qrItems, resolvedCodeSystemLookupPromises);\n}\n\nfunction collectCodingsForLookup(\n  qrItems: QuestionnaireResponseItem[],\n  codeSystemLookupPromises: Record<string, CodeSystemLookupPromise>,\n  fetchTerminologyCallback?: FetchTerminologyCallback,\n  fetchTerminologyRequestConfig?: FetchTerminologyRequestConfig\n): void {\n  for (const item of qrItems) {\n    for (const answer of item.answer ?? []) {\n      if (answer.valueCoding && !answer.valueCoding.display) {\n        getCodeSystemLookupPromise(\n          answer.valueCoding,\n          codeSystemLookupPromises,\n          fetchTerminologyCallback,\n          fetchTerminologyRequestConfig\n        );\n      }\n      collectCodingsForLookup(\n        answer.item ?? [],\n        codeSystemLookupPromises,\n        fetchTerminologyCallback,\n        fetchTerminologyRequestConfig\n      );\n    }\n    collectCodingsForLookup(\n      item.item ?? [],\n      codeSystemLookupPromises,\n      fetchTerminologyCallback,\n      fetchTerminologyRequestConfig\n    );\n  }\n}\n\nfunction applyResolvedDisplays(\n  qrItems: QuestionnaireResponseItem[],\n  resolved: Record<string, CodeSystemLookupPromise>\n): void {\n  for (const item of qrItems) {\n    for (const answer of item.answer ?? []) {\n      if (answer.valueCoding?.system && answer.valueCoding?.code) {\n        const key = `system=${answer.valueCoding.system}&code=${answer.valueCoding.code}`;\n        const resolvedLookup = resolved[key];\n        if (resolvedLookup?.newCoding?.display) {\n          answer.valueCoding.display = resolvedLookup.newCoding.display;\n        }\n      }\n      applyResolvedDisplays(answer.item ?? [], resolved);\n    }\n    applyResolvedDisplays(item.item ?? [], resolved);\n  }\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n  FetchResourceCallback,\n  FetchResourceRequestConfig,\n  FetchTerminologyCallback,\n  FetchTerminologyRequestConfig,\n  InputParameters,\n  OutputParameters\n} from '../interfaces';\nimport type {\n  Encounter,\n  FhirResource,\n  OperationOutcome,\n  OperationOutcomeIssue,\n  Reference\n} from 'fhir/r4';\nimport { fetchQuestionnaire } from '../api/fetchQuestionnaire';\nimport { isSubjectParameter } from './index';\nimport { createFhirPathContext } from './createFhirPathContext';\nimport { readPopulationExpressions } from './readPopulationExpressions';\nimport { evaluateItemPopulationContexts, generateExpressionValues } from './evaluateExpressions';\nimport { constructResponse } from './constructResponse';\nimport { createOutputParameters } from './createOutputParameters';\nimport { removeEmptyAnswersFromResponse } from './removeEmptyAnswers';\nimport { isEncounterContextParameter, isUserContextParameter } from './typePredicates';\nimport { addDisplayToQuestionnaireResponseCodings } from './addDisplayToCodings';\n\n/**\n * Executes the SDC Populate Questionnaire operation - $populate.\n * Input and output specific parameters conformant to the SDC populate specification. Can be deployed as a $populate microservice.\n *\n * This function expects a nice set of populate input parameters to go. If you do you not have them, use https://github.com/aehrc/smart-forms/blob/main/packages/sdc-populate/src/inAppPopulation/utils/populateQuestionnaire.ts#L82 instead.\n * @see {@link https://hl7.org/fhir/uv/sdc/OperationDefinition-Questionnaire-populate.html}\n * Added custom output parameters populationContextResults for visual and debugging purposes.\n *\n * @author Sean Fong\n */\nexport async function populate(\n  parameters: InputParameters,\n  fetchResourceCallback: FetchResourceCallback,\n  fetchResourceRequestConfig: FetchResourceRequestConfig,\n  fetchTerminologyCallback?: FetchTerminologyCallback,\n  fetchTerminologyRequestConfig?: FetchTerminologyRequestConfig\n): Promise<OutputParameters | OperationOutcome> {\n  const issues: OperationOutcomeIssue[] = [];\n\n  // Fetch questionnaire resource to be populated\n  const questionnaire = await fetchQuestionnaire(\n    parameters,\n    fetchResourceCallback,\n    fetchResourceRequestConfig\n  );\n  if (questionnaire.resourceType === 'OperationOutcome') {\n    return questionnaire;\n  }\n\n  const subjectReference = parameters.parameter.find((param) => isSubjectParameter(param))\n    ?.valueReference as Reference;\n  const user = parameters.parameter.find((param) => isUserContextParameter(param))?.part?.[1]\n    .resource as FhirResource | undefined;\n  const encounter = parameters.parameter.find((param) => isEncounterContextParameter(param))\n    ?.part?.[1].resource as Encounter | undefined;\n\n  // Create contextMap to hold variables for population\n  let fhirPathContext = await createFhirPathContext(\n    parameters,\n    questionnaire,\n    fetchResourceCallback,\n    fetchResourceRequestConfig,\n    issues,\n    fetchTerminologyRequestConfig\n  );\n\n  // Read expressions to be populated from questionnaire recursively\n  // i.e. itemPopulationContext, initialExpression\n  const populationExpressions = readPopulationExpressions(questionnaire);\n\n  // Evaluate itemPopulationContexts and add them to contextMap\n  fhirPathContext = await evaluateItemPopulationContexts(\n    populationExpressions.itemPopulationContexts,\n    fhirPathContext,\n    issues,\n    fetchTerminologyRequestConfig,\n    fetchResourceRequestConfig\n  );\n\n  // Get values for expressions\n  const { evaluatedInitialExpressions, evaluatedItemPopulationContexts } =\n    await generateExpressionValues(\n      populationExpressions,\n      fhirPathContext,\n      issues,\n      fetchTerminologyRequestConfig,\n      fetchResourceRequestConfig\n    );\n\n  // Construct response from initialExpressions\n  const questionnaireResponse = await constructResponse(\n    questionnaire,\n    subjectReference,\n    {\n      initialExpressions: evaluatedInitialExpressions,\n      itemPopulationContexts: evaluatedItemPopulationContexts\n    },\n    fhirPathContext,\n    user,\n    encounter,\n    fetchTerminologyCallback,\n    fetchTerminologyRequestConfig,\n    fetchResourceRequestConfig\n  );\n\n  // Add display values to any valueCoding answers lacking them via CodeSystem $lookup.\n  // Done as a post-processing step on the final QR so that codings from all code paths\n  // are covered — including those only produced during per-instance repeat group evaluation.\n  await addDisplayToQuestionnaireResponseCodings(\n    questionnaireResponse.item ?? [],\n    fetchTerminologyCallback,\n    fetchTerminologyRequestConfig\n  );\n\n  const cleanQuestionnaireResponse = removeEmptyAnswersFromResponse(\n    questionnaire,\n    questionnaireResponse\n  );\n\n  return createOutputParameters(cleanQuestionnaireResponse, issues, fhirPathContext);\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n  Encounter,\n  OperationOutcome,\n  Patient,\n  Practitioner,\n  Questionnaire,\n  QuestionnaireResponse\n} from 'fhir/r4';\nimport type {\n  CustomContextResultParameter,\n  FetchResourceCallback,\n  FetchResourceRequestConfig,\n  FetchTerminologyCallback,\n  FetchTerminologyRequestConfig,\n  InputParameters,\n  IssuesParameter,\n  OutputParameters,\n  ResponseParameter\n} from '../../SDCPopulateQuestionnaireOperation';\nimport {\n  isInputParameters,\n  isOutputParameters,\n  populate\n} from '../../SDCPopulateQuestionnaireOperation';\nimport { Base64 } from 'js-base64';\nimport type { FhirContext } from '../interfaces/fhirContext.interface';\nimport { isRecord } from './isRecord';\nimport { initialiseInputParameters } from './inputParameters';\n\nexport interface PopulateResult {\n  populatedResponse: QuestionnaireResponse;\n  issues?: OperationOutcome;\n  populatedContext?: Record<string, any>;\n}\n\n/**\n * @property questionnaire - Questionnaire to populate\n * @property fetchResourceCallback - A callback function to fetch resources from your FHIR server\n * @property fetchResourceRequestConfig - Any request configuration to be passed to the fetchResourceCallback i.e. headers, auth etc.\n * @property patient - Patient resource as patient in context\n * @property user - Practitioner resource as user in context, optional\n * @property encounter - Encounter resource as encounter in context, optional\n * @property fhirContext - An array of contextual resources within a launch. See https://build.fhir.org/ig/HL7/smart-app-launch/scopes-and-launch-context.html#fhircontext-exp\n * @property fetchTerminologyCallback - A callback function to fetch terminology resources, optional\n * @property fetchTerminologyRequestConfig - Any request configuration to be passed to the fetchTerminologyCallback i.e. headers, auth etc., optional\n * @property timeoutMs - Timeout in milliseconds for the $populate operation, default is 30000ms (30 seconds)\n *\n * @author Sean Fong\n */\nexport interface PopulateQuestionnaireParams {\n  questionnaire: Questionnaire;\n  fetchResourceCallback: FetchResourceCallback;\n  fetchResourceRequestConfig: FetchResourceRequestConfig;\n  patient: Patient;\n  user?: Practitioner;\n  encounter?: Encounter;\n  fhirContext?: FhirContext[];\n  fetchTerminologyCallback?: FetchTerminologyCallback;\n  fetchTerminologyRequestConfig?: FetchTerminologyRequestConfig;\n  timeoutMs?: number;\n}\n\n/**\n * Performs an in-app population of the provided questionnaire.\n * By in-app, it means that a callback function is provided to fetch resources instead of it calling to a $populate service.\n * This function helps to you create a nice set of populate input parameters from the provided params.\n * If you already have them, use https://github.com/aehrc/smart-forms/blob/main/packages/sdc-populate/src/SDCPopulateQuestionnaireOperation/utils/populate.ts#L842 instead.\n *\n * @param params - Refer to PopulateQuestionnaireParams interface\n * @returns populateSuccess - A boolean indicating if the population was successful\n * @returns populateResult - An object containing populated response and issues if any\n *\n * @author Sean Fong\n */\nexport async function populateQuestionnaire(params: PopulateQuestionnaireParams): Promise<{\n  populateSuccess: boolean;\n  populateResult: PopulateResult | null;\n}> {\n  const {\n    questionnaire,\n    fetchResourceCallback,\n    fetchResourceRequestConfig,\n    patient,\n    user,\n    encounter,\n    fhirContext,\n    fetchTerminologyCallback,\n    fetchTerminologyRequestConfig,\n    timeoutMs = 30000\n  } = params;\n\n  const { inputParameters } = await initialiseInputParameters(\n    questionnaire,\n    patient,\n    user ?? null,\n    encounter ?? null,\n    fhirContext ?? null,\n    fetchResourceCallback,\n    fetchResourceRequestConfig,\n    timeoutMs\n  );\n\n  if (!inputParameters || !isInputParameters(inputParameters)) {\n    return {\n      populateSuccess: false,\n      populateResult: null\n    };\n  }\n\n  // Perform population if parameters satisfies input parameters\n  const outputParameters = await performInAppPopulation(\n    inputParameters,\n    fetchResourceCallback,\n    fetchResourceRequestConfig,\n    timeoutMs,\n    fetchTerminologyCallback,\n    fetchTerminologyRequestConfig\n  );\n\n  if (outputParameters.resourceType === 'OperationOutcome') {\n    return {\n      populateSuccess: false,\n      populateResult: null\n    };\n  }\n\n  const responseParameter = outputParameters.parameter.find(\n    (param) => param.name === 'response'\n  ) as ResponseParameter;\n  const issuesParameter = outputParameters.parameter.find((param) => param.name === 'issues') as\n    | IssuesParameter\n    | undefined;\n  const contextResultParameter = outputParameters.parameter.find(\n    (param) => param.name === 'contextResult-custom'\n  ) as CustomContextResultParameter | undefined;\n\n  const populateResult: PopulateResult = {\n    populatedResponse: responseParameter.resource\n  };\n\n  // Add populated context to populateResult if it exists\n  if (contextResultParameter?.valueAttachment.data) {\n    const contextResult = JSON.parse(Base64.decode(contextResultParameter.valueAttachment.data));\n\n    if (isRecord(contextResult)) {\n      populateResult.populatedContext = contextResult;\n    }\n  }\n\n  if (issuesParameter) {\n    populateResult.issues = issuesParameter.resource;\n  }\n\n  return {\n    populateSuccess: true,\n    populateResult: populateResult\n  };\n}\n\nasync function performInAppPopulation(\n  inputParameters: InputParameters,\n  fetchResourceCallback: FetchResourceCallback,\n  fetchResourceRequestConfig: FetchResourceRequestConfig,\n  timeoutMs: number,\n  fetchTerminologyCallback?: FetchTerminologyCallback,\n  fetchTerminologyRequestConfig?: FetchTerminologyRequestConfig\n): Promise<OutputParameters | OperationOutcome> {\n  const populatePromise = populate(\n    inputParameters,\n    fetchResourceCallback,\n    fetchResourceRequestConfig,\n    fetchTerminologyCallback,\n    fetchTerminologyRequestConfig\n  );\n\n  try {\n    const promiseResult = await addTimeoutToPromise(populatePromise, timeoutMs);\n\n    if (promiseResult.timeout) {\n      return {\n        resourceType: 'OperationOutcome',\n        issue: [\n          {\n            severity: 'error',\n            code: 'timeout',\n            details: { text: '$populate operation timed out.' }\n          }\n        ]\n      };\n    }\n\n    if (isOutputParameters(promiseResult)) {\n      return promiseResult;\n    }\n\n    return {\n      resourceType: 'OperationOutcome',\n      issue: [\n        {\n          severity: 'error',\n          code: 'invalid',\n          details: {\n            text: 'Output parameters do not match the specification.'\n          }\n        }\n      ]\n    };\n  } catch (error) {\n    console.error('Error:', error);\n    return {\n      resourceType: 'OperationOutcome',\n      issue: [\n        {\n          severity: 'error',\n          code: 'unknown',\n          details: { text: 'An unknown error occurred.' }\n        }\n      ]\n    };\n  }\n}\n\n/**\n * Adds a timeout to a promise, rejecting if the promise does not resolve within the specified time.\n * Useful for enforcing time limits on async operations such as $populate.\n */\nexport async function addTimeoutToPromise(promise: Promise<any>, timeoutMs: number) {\n  const timeoutPromise = new Promise((_, reject) => {\n    setTimeout(() => {\n      reject(new Error(`Promise timed out after ${timeoutMs} milliseconds`));\n    }, timeoutMs);\n  });\n\n  // Use Promise.race to wait for either the original promise or the timeout promise\n  return Promise.race([promise, timeoutPromise]);\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nexport function isRecord(obj: any): obj is Record<string, any> {\n  if (!obj) {\n    return false;\n  }\n\n  return Object.keys(obj).every((key) => typeof key === 'string');\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type { FhirContext } from '../interfaces/fhirContext.interface';\nimport type { FhirResource } from 'fhir/r4';\nimport type {\n  FetchResourceCallback,\n  FetchResourceRequestConfig\n} from '../../SDCPopulateQuestionnaireOperation';\nimport { addTimeoutToPromise } from './populateQuestionnaire';\n\n/**\n * Resolves FHIR context references by fetching each referenced resource asynchronously.\n * Returns a map of context type to fetched FHIR resource, enabling context-aware population.\n */\nexport async function resolveFhirContextReferences(\n  fhirContext: FhirContext[] | null,\n  fetchResourceCallback: FetchResourceCallback,\n  fetchResourceRequestConfig: FetchResourceRequestConfig,\n  timeoutMs: number\n): Promise<Record<string, FhirResource>> {\n  if (!fhirContext || fhirContext.length === 0) {\n    return {};\n  }\n\n  // Filter contexts that have a internal `reference`\n  const contextsWithReferences = fhirContext.filter((ctx) => typeof ctx.reference === 'string');\n\n  // Define fhirContext-fetch promises\n  const promises = contextsWithReferences.map((ctx) =>\n    addTimeoutToPromise(\n      fetchResourceCallback(ctx.reference ?? '', fetchResourceRequestConfig),\n      timeoutMs\n    )\n  );\n\n  const settledPromises = await Promise.allSettled(promises);\n\n  const fhirContextReferenceMap: Record<string, FhirResource> = {};\n  for (const [i, settledPromise] of settledPromises.entries()) {\n    const context = contextsWithReferences[i];\n\n    // This should never happen\n    if (!context) {\n      continue;\n    }\n\n    // If no type set in context, determine resource type from reference\n    const type = context.type ?? context.reference?.split('/')[0];\n\n    if (settledPromise.status === 'fulfilled' && type) {\n      // This assumes that there is one resource per resourceType in fhirContext\n      fhirContextReferenceMap[type] = settledPromise.value as FhirResource;\n    }\n\n    if (settledPromise.status === 'rejected') {\n      console.warn(\n        `SDC-Populate issue: fhirContext with reference \"${context?.reference}\" could not be resolved.\\nError: ${settledPromise.reason}`\n      );\n    }\n  }\n\n  return fhirContextReferenceMap;\n}\n","/*\n * Copyright 2025 Commonwealth Scientific and Industrial Research\n * Organisation (CSIRO) ABN 41 687 119 230.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport type {\n  Encounter,\n  Extension,\n  FhirResource,\n  Parameters,\n  ParametersParameter,\n  Patient,\n  Practitioner,\n  Questionnaire,\n  QuestionnaireItem,\n  Reference\n} from 'fhir/r4';\nimport type {\n  LaunchContext,\n  QuestionnaireLevelXFhirQueryVariable,\n  SourceQuery\n} from '../interfaces/inAppPopulation.interface';\nimport { getDisplayName } from '../../SDCPopulateQuestionnaireOperation/utils/humanName';\nimport type { FhirContext } from '../interfaces/fhirContext.interface';\nimport { resolveFhirContextReferences } from './resolveFhirContexts';\nimport type {\n  FetchResourceCallback,\n  FetchResourceRequestConfig\n} from '../../SDCPopulateQuestionnaireOperation';\n\n/**\n * Prepares input parameters and FHIRPath context for questionnaire population or evaluation.\n *\n * This function collects launch context variables, source queries, and x-fhir-query variables from the questionnaire,\n * and constructs a `Parameters` resource that can be used for FHIRPath evaluation or population.\n */\nexport async function initialiseInputParameters(\n  questionnaire: Questionnaire,\n  patient: Patient,\n  user: Practitioner | null,\n  encounter: Encounter | null,\n  fhirContext: FhirContext[] | null,\n  fetchResourceCallback: FetchResourceCallback,\n  fetchResourceRequestConfig: FetchResourceRequestConfig,\n  timeoutMs: number\n): Promise<{\n  inputParameters: Parameters | null;\n  fhirPathContext: Record<string, any>;\n}> {\n  // FHIRPath Context map that will be used to evaluate FHIRPath expressions, this is different from the fhirContext in the params.\n  const fhirPathContext: Record<string, any> = {};\n\n  // Get launch contexts, source queries and questionnaire-level variables\n  const launchContexts = getLaunchContexts(questionnaire);\n  const sourceQueries = getSourceQueries(questionnaire);\n  const questionnaireLevelVariables = getXFhirQueryVariables(questionnaire);\n\n  if (\n    launchContexts.length === 0 &&\n    sourceQueries.length === 0 &&\n    questionnaireLevelVariables.length === 0\n  ) {\n    return { inputParameters: null, fhirPathContext: fhirPathContext };\n  }\n\n  // Define population input parameters from launch contexts, source queries and questionnaire-level variables\n  const inputParameters = await constructPopulateInputParameters(\n    questionnaire,\n    patient,\n    user,\n    encounter,\n    fhirContext,\n    launchContexts,\n    sourceQueries,\n    questionnaireLevelVariables,\n    fhirPathContext,\n    fetchResourceCallback,\n    fetchResourceRequestConfig,\n    timeoutMs\n  );\n\n  return { inputParameters, fhirPathContext };\n}\n\nfunction isLaunchContext(extension: Extension): extension is LaunchContext {\n  const hasLaunchContextName =\n    extension.url ===\n      'http://hl7.org/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-launchContext' &&\n    !!extension.extension?.find(\n      (ext) => ext.url === 'name' && (ext.valueId || (ext.valueCoding && ext.valueCoding.code))\n    );\n\n  const hasLaunchContextType = !!extension.extension?.find(\n    (ext) => ext.url === 'type' && ext.valueCode\n  );\n\n  return (\n    extension.url ===\n      'http://hl7.org/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-launchContext' &&\n    hasLaunchContextName &&\n    hasLaunchContextType\n  );\n}\n\nfunction getLaunchContexts(questionnaire: Questionnaire): LaunchContext[] {\n  if (questionnaire.extension && questionnaire.extension.length > 0) {\n    return questionnaire.extension.filter((extension) =>\n      isLaunchContext(extension)\n    ) as LaunchContext[];\n  }\n\n  return [];\n}\n\nfunction isSourceQuery(extension: Extension): extension is SourceQuery {\n  return (\n    extension.url ===\n      'http://hl7.org/fhir/uv/sdc/StructureDefinition/sdc-questionnaire-sourceQueries' &&\n    !!extension.valueReference\n  );\n}\n\nfunction getSourceQueries(questionnaire: Questionnaire): SourceQuery[] {\n  if (questionnaire.extension && questionnaire.extension.length > 0) {\n    return questionnaire.extension.filter((extension) => isSourceQuery(extension)) as SourceQuery[];\n  }\n\n  return [];\n}\n\nfunction isXFhirQueryVariable(\n  extension: Extension\n): extension is QuestionnaireLevelXFhirQueryVariable {\n  return (\n    extension.url === 'http://hl7.org/fhir/StructureDefinition/variable' &&\n    !!extension.valueExpression?.name &&\n    extension.valueExpression?.language === 'application/x-fhir-query' &&\n    !!extension.valueExpression?.expression\n  );\n}\n\nfunction getXFhirQueryVariables(\n  questionnaire: Questionnaire\n): QuestionnaireLevelXFhirQueryVariable[] {\n  const xFhirQueryVariables: QuestionnaireLevelXFhirQueryVariable[] = [];\n  if (questionnaire.extension && questionnaire.extension.length > 0) {\n    xFhirQueryVariables.push(\n      ...(questionnaire.extension.filter((extension) =>\n        isXFhirQueryVariable(extension)\n      ) as QuestionnaireLevelXFhirQueryVariable[])\n    );\n  }\n\n  if (questionnaire.item && questionnaire.item.length > 0) {\n    for (const qItem of questionnaire.item) {\n      xFhirQueryVariables.push(\n        ...(getXFhirQueryVariablesRecursive(qItem) as QuestionnaireLevelXFhirQueryVariable[])\n      );\n    }\n  }\n\n  return xFhirQueryVariables;\n}\n\nfunction getXFhirQueryVariablesRecursive(qItem: QuestionnaireItem) {\n  let xFhirQueryVariables: Extension[] = [];\n\n  if (qItem.item) {\n    for (const childItem of qItem.item) {\n      xFhirQueryVariables = xFhirQueryVariables.concat(getXFhirQueryVariablesRecursive(childItem));\n    }\n  }\n\n  if (qItem.extension) {\n    xFhirQueryVariables.push(\n      ...qItem.extension.filter((extension) => isXFhirQueryVariable(extension))\n    );\n  }\n\n  return xFhirQueryVariables;\n}\n\nexport async function constructPopulateInputParameters(\n  questionnaire: Questionnaire,\n  patient: Patient,\n  user: Practitioner | null,\n  encounter: Encounter | null,\n  fhirContext: FhirContext[] | null,\n  launchContexts: LaunchContext[],\n  sourceQueries: SourceQuery[],\n  questionnaireLevelVariables: QuestionnaireLevelXFhirQueryVariable[],\n  fhirPathContext: Record<string, any>,\n  fetchResourceCallback: FetchResourceCallback,\n  fetchResourceRequestConfig: FetchResourceRequestConfig,\n  timeoutMs: number\n): Promise<Parameters | null> {\n  const patientSubject = createPatientSubject(questionnaire, patient);\n  if (!patientSubject) {\n    return null;\n  }\n\n  const inputParameters: Parameters = {\n    resourceType: 'Parameters',\n    parameter: [\n      {\n        name: 'questionnaire',\n        resource: questionnaire\n      },\n      {\n        name: 'subject',\n        valueReference: patientSubject\n      }\n    ]\n  };\n\n  // canonical\n  if (questionnaire.url) {\n    inputParameters.parameter?.push(createCanonicalParam(questionnaire.url));\n  }\n\n  // contexts\n  const contexts: ParametersParameter[] = [];\n\n  // resolve fhirContexts references if provided\n  const resolvedFhirContextReferences = await resolveFhirContextReferences(\n    fhirContext,\n    fetchResourceCallback,\n    fetchResourceRequestConfig,\n    timeoutMs\n  );\n\n  // add launch contexts\n  if (launchContexts.length > 0) {\n    for (const launchContext of launchContexts) {\n      const launchContextParam = createLaunchContextParam(\n        launchContext,\n        patient,\n        user,\n        encounter,\n        resolvedFhirContextReferences,\n        fhirPathContext\n      );\n      if (launchContextParam) {\n        contexts.push(launchContextParam);\n      }\n    }\n  }\n\n  // add source queries\n  if (sourceQueries.length > 0) {\n    for (let index = 0; index < sourceQueries.length; index++) {\n      const sourceQuery = sourceQueries[index];\n\n      if (sourceQuery) {\n        contexts.push(createSourceQueryParams(sourceQuery, index));\n      }\n    }\n  }\n\n  // add questionnaire-level variables\n  if (questionnaireLevelVariables.length > 0) {\n    for (const variable of questionnaireLevelVariables) {\n      contexts.push(createVariableParam(variable));\n    }\n  }\n\n  if (contexts.length > 0) {\n    inputParameters.parameter?.push(...contexts);\n  }\n\n  // local\n  inputParameters.parameter?.push(createLocalParam());\n\n  return inputParameters;\n}\n\n/**\n * Creates a Reference object for the patient subject if the Questionnaire allows Patient as subject.\n * Returns null if Patient is not a valid subject type for the Questionnaire.\n */\nfunction createPatientSubject(questionnaire: Questionnaire, patient: Patient): Reference | null {\n  const subjectTypes = questionnaire.subjectType;\n\n  // If subjectTypes array is not empty AND \"Patient\" is not in the array, we cannot create a Patient subject reference.\n  if (subjectTypes && subjectTypes.length > 0) {\n    const patientSubject = subjectTypes.find((subject) => subject === 'Patient');\n    if (!patientSubject) {\n      return null;\n    }\n  }\n\n  return {\n    type: 'Patient',\n    reference: 'Patient/' + patient.id,\n    display: getDisplayName(patient.name)\n  };\n}\n\n/**\n * Creates a ParametersParameter for the canonical URL of the Questionnaire.\n * Used to identify the Questionnaire resource in $populate input.\n */\nfunction createCanonicalParam(canonicalUrl: string): ParametersParameter {\n  return {\n    name: 'canonical',\n    valueString: canonicalUrl\n  };\n}\n\n/**\n * Creates a ParametersParameter for the local context, always set to false for in-app population.\n// Setting local parameter as false as we are calling $populate with an NPM package, not a server\n// Package doesn't contain any fhir resources to \"know\" the context from\n */\nfunction createLocalParam(): ParametersParameter {\n  return {\n    name: 'local',\n    valueBoolean: false\n  };\n}\n\n/**\n * Creates a ParametersParameter for a launch context resource (patient, user, encounter, etc).\n * Adds the resource to the FHIRPath context for use in population expressions.\n */\nfunction createLaunchContextParam(\n  launchContext: LaunchContext,\n  patient: Patient,\n  user: Practitioner | null,\n  encounter: Encounter | null,\n  resolvedFhirContextReferences: Record<string, FhirResource>,\n  fhirPathContext: Record<string, any>\n): ParametersParameter | null {\n  const name = launchContext.extension[0].valueId ?? launchContext.extension[0].valueCoding?.code;\n  if (!name) {\n    return null;\n  }\n\n  const resourceType = launchContext.extension[1].valueCode;\n  let resource: FhirResource | null = null;\n\n  if (name === 'patient' && resourceType === 'Patient') {\n    resource = patient;\n  } else if (name === 'user' && resourceType === 'Practitioner' && user) {\n    resource = user;\n  } else if (name === 'encounter' && resourceType === 'Encounter' && encounter) {\n    resource = encounter;\n  } else {\n    // Check resolved resources from FHIR context references\n    // This assumes that there is one resource per resourceType in fhirContext\n    const resolvedResource = resolvedFhirContextReferences[resourceType];\n    if (resolvedResource) {\n      resource = resolvedResource;\n    }\n  }\n\n  if (!resource) {\n    return null;\n  }\n\n  // Update context with launchContext resources\n  fhirPathContext[name] = resource;\n\n  return {\n    name: 'context',\n    part: [\n      {\n        name: 'name',\n        valueString: name\n      },\n      {\n        name: 'content',\n        resource: resource\n      }\n    ]\n  };\n}\n\n/**\n * Creates a ParametersParameter for a source query, referencing a contained resource or itself.\n * Used to provide additional context for population from source queries.\n */\nfunction createSourceQueryParams(sourceQuery: SourceQuery, index: number): ParametersParameter {\n  const reference = sourceQuery.valueReference.reference;\n  if (reference && reference.startsWith('#')) {\n    const containedReference = reference.slice(1);\n    return {\n      name: 'context',\n      part: [\n        {\n          name: 'name',\n          valueString: containedReference\n        },\n        {\n          name: 'content',\n          valueReference: sourceQuery.valueReference\n        }\n      ]\n    };\n  }\n\n  // if sourceQuery cannot be referenced to a contained bundle, return itself as a context\n  // this most likely shouldn't happen\n  return {\n    name: 'context',\n    part: [\n      {\n        name: 'name',\n        valueString: `sourceQuery${index}`\n      },\n      {\n        name: 'content',\n        valueReference: sourceQuery.valueReference\n      }\n    ]\n  };\n}\n\n/**\n * Creates a ParametersParameter for a questionnaire-level variable, referencing its FHIR query.\n * Used to provide context for population from variables defined in the Questionnaire.\n */\nfunction createVariableParam(variable: QuestionnaireLevelXFhirQueryVariable): ParametersParameter {\n  const query = variable.valueExpression.expression;\n  const resourceType = query.split('?')[0];\n\n  return {\n    name: 'context',\n    part: [\n      {\n        name: 'name',\n        valueString: variable.valueExpression.name\n      },\n      {\n        name: 'content',\n        valueReference: { reference: query, type: resourceType }\n      }\n    ]\n  };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiCO,SAAS,kBAAkB,YAAuD;AAjCzF;AAkCE,QAAM,uBAAuB,CAAC,GAAC,gBAAW,cAAX,mBAAsB,KAAK;AAE1D,QAAM,iBAAiB,CAAC,GAAC,gBAAW,cAAX,mBAAsB,KAAK;AAEpD,SAAO,wBAAwB;AACjC;AAKO,SAAS,6BACd,WACyC;AA9C3C;AA+CE,SACG,UAAU,SAAS,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;AAAA,QACd,OAAO;AAAA,UACL;AAAA,YACE,UAAU;AAAA,YACV,MAAM;AAAA,YACN,SAAS;AAAA,cACP,MAAM;AAAA,YACR;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF,SAAS,OAAO;AACd,cAAQ,MAAM,UAAU,KAAK;AAC7B,aAAO;AAAA,QACL,cAAc;AAAA,QACd,OAAO;AAAA,UACL;AAAA,YACE,UAAU;AAAA,YACV,MAAM;AAAA,YACN,SAAS,EAAE,MAAM,6BAA6B;AAAA,UAChD;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA;AAMA,SAAsB,oBAAoB,SAAuB,WAAmB;AAAA;AAClF,UAAM,iBAAiB,IAAI,QAAQ,CAAC,GAAG,WAAW;AAChD,iBAAW,MAAM;AACf,eAAO,IAAI,MAAM,2BAA2B,SAAS,eAAe,CAAC;AAAA,MACvE,GAAG,SAAS;AAAA,IACd,CAAC;AAGD,WAAO,QAAQ,KAAK,CAAC,SAAS,cAAc,CAAC;AAAA,EAC/C;AAAA;","names":["_a","fhirpath","fhirpath_r4_model","_a","item","import_fhirpath","import_r4","fhirpath","fhirpath_r4_model","coding","import_fhirpath","import_r4","dayjs","moment","fhirpath","fhirpath_r4_model","import_js_base64","_a"]}