npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@opencharts/mapper

v0.0.1

Published

Mapper utilities for OpenCharts

Readme

@opencharts/mapper

Pure, deterministic record-to-canonical-resource mapper with a fluent DSL.

npm License: MIT

Overview

@opencharts/mapper maps source records (CSV rows, FHIR resources, API responses, …) to canonical resource instances declaratively. It is:

  • Pure & deterministic: same (mapping, record) always yields the same output. No I/O, no clocks, no global state.
  • Source-agnostic: the mapper only sees a flat key→value record. Source format is irrelevant.
  • Catalog-decoupled: catalog validation is opt-in (validateMappedResources), so map() stays pure.

What's included

| Export | Description | |---|---| | PureResourceMapper | The mapping engine | | PureMappingDefinition | Validated mapping declaration | | PureMappingRegistry | Store and look up mapping definitions by id or source | | dsl | Fluent authoring DSL (namespace) | | resolveBinding, validateBinding, isBinding | Binding primitives | | validateMappedResources | Opt-in catalog validation for mapper output |

Installation

npm install @opencharts/mapper

Quick Start

import { PureResourceMapper, dsl as d } from '@opencharts/mapper';

const mapper = new PureResourceMapper();

const { resources } = mapper.map(
  {
    id: 'patient-feed', version: 1,
    source: { type: 'csv', system: 'epic' },
    resources: [{
      key: 'patient',
      type: 'Patient',
      parameters: {
        identifiers: d.list(
          d.record({ system: d.constant('mrn'), value: d.read('MRN').trim() })
        ),
        birth_date: d.read('DOB').asIsoDate(),
        gender:     d.read('SEX').asGender(),
      },
    }],
  },
  { MRN: ' 12345 ', DOB: '19850101', SEX: 'F' },
);

console.log(resources[0].parameters);
// { identifiers: [{ system: 'mrn', value: '12345' }], birth_date: '1985-01-01', gender: 'female' }

The Binding Grammar

A binding is a plain object with exactly one kind key:

| Kind | Shape | Description | |---|---|---| | from | { from: 'field', required?, default? } | Read record[field] | | literal | { literal: value } | Constant value | | template | { template: 'hello {name}' } | Substitute {key} from the record | | object | { object: { k: binding\|value } } | Build a nested object | | array | { array: [binding\|value, …] } | Build a list | | concat | { concat: [binding\|value, …] } | Flat-merge multiple array sources | | each | { each: binding, as?: binding } | Iterate an array-valued source | | coalesce | { coalesce: [binding, …] } | First non-null value | | if | { if: condition, then: binding, else?: binding } | Conditional | | select | { select: [{when, then}], else?: binding } | Multi-branch |

Any binding can carry transforms: [{ name, version }] applied via the normalizer registry.

DSL Reference

Value builders

import { dsl as d } from '@opencharts/mapper';

d.read('FieldName')             // { from: 'FieldName' }
d.constant(42)                  // { literal: 42 }
d.template('{First} {Last}')    // { template: '{First} {Last}' }
d.record({ k: expr })           // { object: { k: expr } }
d.list(a, b, c)                 // { array: [a, b, c] }
d.concat(a, b)                  // { concat: [a, b] }  (flat merge)
d.each(source, as?)             // { each: source, as }
d.coalesce(a, b, c)             // first non-null
d.when(cond, then, else?)       // conditional
d.select([{when, then}], else?) // multi-branch

Chained transforms on read()

d.read('DOB').asIsoDate()         // → YYYY-MM-DD
d.read('SEX').asGender()          // → FHIR AdministrativeGender
d.read('Name').trim()
d.read('IDS').split({ delimiter: ',' })
d.read('PAIRS').delimited({ item: ',', pair: '|', fields: ['value','system'] })
d.read('CODE').mapValues({ table: { '1': 'active', '2': 'inactive' } })
d.read('DATE').asIsoDateTime()
d.read('CODE').use('my-transform', 1)  // custom transform

Condition builders

d.present('Field')                    // { exists: { from: 'Field' } }
d.absent('Field')                     // { absent: { from: 'Field' } }
d.eq(d.read('F'), d.constant('x'))    // { eq: [binding, binding] }
d.ne(d.read('F'), d.constant('x'))
d.oneOf(d.read('F'), ['a','b'])       // { in: [...] }
d.notOneOf(d.read('F'), ['a','b'])    // { nin: [...] }
d.matches(d.read('F'), '^\\d+$')      // { matches: [binding, pattern] }
d.all(cond1, cond2)                   // { and: [...] }
d.any(cond1, cond2)                   // { or: [...] }
d.negate(cond)                        // { not: cond }

Full mapping definition builder

import { dsl as d } from '@opencharts/mapper';

const mapping = d.defineMapping('patient-feed', 1, {
  source: d.csv('epic'),
  identity: d.keyBy('Patient', 'ehr', { mrn: d.read('MRN') }),
  resources: [
    d.resource('Patient', 'patient', {
      identifiers: d.list(
        d.record({ system: d.constant('mrn'), value: d.read('MRN').trim() })
      ),
      birth_date: d.read('DOB').asIsoDate(),
      gender:     d.read('SEX').asGender(),
    }).resolveBy('epic-patient', { mrn: d.read('MRN').trim() }),
  ],
});

Using the Registry

import { PureMappingRegistry, PureResourceMapper } from '@opencharts/mapper';

const registry = new PureMappingRegistry();
registry.register(mapping);

// Look up by id
const def = registry.get('patient-feed');

// Auto-route by source type and system
const def2 = registry.findBySource('csv', 'epic');

const mapper = new PureResourceMapper({ normalizers });
const { resources } = mapper.map(def, sourceRecord);

Opt-in Catalog Validation

import { validateMappedResources } from '@opencharts/mapper';

// resourceValidator from @opencharts/resources
const { valid, errors } = validateMappedResources(resources, resourceValidator);

Identity Resolution (resolve directive)

A resource that needs identity resolution carries a resolve block. The mapper carries the inputs through verbatim for a downstream assembler:

{
  key: 'patient',
  type: 'Patient',
  parameters: { identifiers: [...] },
  resolve: {
    profile: { id: 'epic-patient', version: 1 },
    identity_parameters: { mrn: d.read('MRN').trim() },
  },
}

License

MIT

Why it exists

The legacy SourceMappingEngine conflates three jobs in one apply():

  1. transform — source record → canonical resources (the deterministic part);
  2. resolution planning — building shared_resolutions seeds that couple to the IdentityResolution aggregate and stamping a resolution.status;
  3. case assembly — packing demand, workflow, business_key, provenance for an OperationCase.

That conflation is behind three concrete problems:

  • shared_resolutions is not a canonical resource. It sits as a sibling array next to case_resources, yet it is really "resolve the identity of a resolvable canonical resource" — an asymmetry.
  • The mapper materializes canonical resource instances to "seed the case context." But the spec's target (OperationCase.context.resources) does not exist on the entity — the case stores resource_parameters + ResourceRequirement[], and the real ingestion path (ClinicalOperationFileLoader) uses resource_parameters and never touches case_resources. So the validated-instance path is largely vestigial.
  • It isn't a pure mapper. Jobs (2) and (3) are side concerns bolted onto a transform.

What this mapper does (and only this)

PureResourceMapper.map(mapping, record) → { resources, business_key? }

  • Deterministic & pure: same (mapping, record) → same output. No I/O, no clock, no random, no global state. The only dependency is an optional injected normalizer registry (pure functions) used for a binding's transforms.

  • No coupling to IdentityResolution, OperationCase, demand, or workflow.

  • Everything is a canonical resource. There is no shared_resolutions. A resolvable resource carries an inline resolve directive:

    {
      key: 'patient', type: 'Patient',
      parameters: { identifiers: { from: 'MRN' } },
      resolve: {                                  // resolution INPUTS, as data
        profile: { id: 'epic-patient', version: 1 },
        identity_parameters: { mrn: { from: 'MRN' } },
      },
    }

    The mapper resolves the identity_parameters from the record and carries the block through verbatim — it never performs resolution or sets a resolution.status. A downstream assembler feeds resolve to the identity subsystem and builds the case.

  • Optional catalog validation is separate (validateMappedResources), so map() stays pure. Wrap the output with a CanonicalResourceValidator only when you want a catalog check.

Usage

import { PureResourceMapper } from 'opencharts/puremapper/index.js';
import { createCanonicalSystem } from 'opencharts';

const { normalizers, resourceValidator } = createCanonicalSystem();
const mapper = new PureResourceMapper({ normalizers }); // normalizers optional

const { resources, business_key } = mapper.map(
  {
    id: 'csv-mini', version: 1,
    source: { type: 'csv', system: 'demo' },
    business_key: { namespace: 'demo', type: 'Patient',
      components: { mrn: { from: 'MRN', transforms: [{ name: 'trim', version: 1 }] } } },
    resources: [{
      key: 'patient', type: 'Patient',
      parameters: { identifiers: { array: [ { object: { system: { literal: 'mrn' }, value: { from: 'MRN' } } } ] } },
      resolve: { profile: { id: 'epic-patient', version: 1 }, identity_parameters: { mrn: { from: 'MRN' } } },
    }],
  },
  { MRN: '  MRN-1  ' },
);

// opt-in catalog validation (separate from the pure transform):
import { validateMappedResources } from 'opencharts/puremapper/index.js';
const report = validateMappedResources(resources, resourceValidator); // { valid, errors }

Open question (deferred)

Whether this pure mapper or the imperative ClinicalOperationMapper (the one the file loader actually uses) becomes THE canonical mapper is not decided yet. This folder exists so the pure approach can be built and evaluated without disturbing the legacy path. When we decide, the loser is retired and the winner absorbs the remaining concerns (assembly, resolution planning) as separate composable steps.