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

survey-data-dictionary

v2.0.0

Published

Generate JSON/CSV survey data dictionaries and translate response payloads from SurveyStructure.

Readme

survey-data-dictionary

Biblioteca TypeScript pura para construir diccionarios de datos y usar esos diccionarios para interpretar respuestas. Recibe SurveyStructure; no analiza LimeSurvey, no hace solicitudes HTTP, no accede a Redis y no depende del navegador.

Instalación

npm install survey-data-dictionary survey-structure

Operaciones públicas

  • buildSurveyDictionary(structure, options?): convierte una definición SurveyStructure en columnas de respuesta, valores permitidos y aliases.
  • dictionaryToCsv(dictionary): serializa el mismo diccionario como CSV.
  • translateResponse(dictionary, response): interpreta un registro de respuestas.
  • translateDataset(dictionary, responses): interpreta varios registros.
  • mapTabularDataset(dictionary, headers, rows, ignoredHeaders?, missingValues?): alinea un archivo tabular por posición sin perder encabezados repetidos.
  • translatedDatasetToCsv(result): serializa el resultado traducido.

Generar un diccionario

El siguiente ejemplo es sintético:

import { buildSurveyDictionary, dictionaryToCsv } from 'survey-data-dictionary';
import type { SurveyStructure } from 'survey-structure';

const structure: SurveyStructure = {
  contractVersion: '2.0.0',
  id: 'survey-123',
  title: 'Encuesta de demostración',
  fields: [{
    id: 'q1',
    code: 'Q1',
    type: 'single-choice',
    label: 'Consentimiento',
    options: [
      { code: 'A1', label: 'Sí' },
      { code: 'A2', label: 'No' },
    ],
  }],
};

const dictionary = buildSurveyDictionary(structure);
const csv = dictionaryToCsv(dictionary);

La entrada describe la encuesta. La salida describe cómo leer sus respuestas:

{
  "contractVersion": "1.0.0",
  "surveyId": "survey-123",
  "fields": [{
    "questionCode": "Q1",
    "questionLabel": "Consentimiento",
    "responseKey": "Q1",
    "dataType": "code",
    "cardinality": "single",
    "values": [
      { "code": "A1", "label": "Sí" },
      { "code": "A2", "label": "No" }
    ]
  }],
  "issues": []
}

responseKey es la clave canónica que debe buscarse en un registro de respuestas. Los aliases manuales se declaran como encabezado externo → responseKey:

buildSurveyDictionary(structure, {
  aliases: { external_consent_column: 'Q1' },
});

Los campos estructuralmente inválidos producen incidencias. Con { strict: true }, cualquier incidencia de nivel error detiene la generación.

Traducir una respuesta

import { translateResponse } from 'survey-data-dictionary';

const result = translateResponse(dictionary, { Q1: 'A1' });

Salida abreviada:

{
  "fields": [{
    "responseKey": "Q1",
    "questionCode": "Q1",
    "questionLabel": "Consentimiento",
    "dataType": "code",
    "sourceValue": "A1",
    "displayValue": "Sí",
    "missing": false
  }],
  "issues": []
}

sourceValue conserva el dato recibido y displayValue contiene su etiqueta legible. missing es true únicamente cuando el valor no llegó, es null o es una cadena vacía. Si el código no existe en el diccionario, la biblioteca lo conserva como displayValue y agrega UNKNOWN_RESPONSE_VALUE; no inventa una etiqueta.

Traducir un dataset

SurveyResponseRecord representa un registro y SurveyResponseDataset = SurveyResponseRecord[] representa la colección de entrada:

import {
  translateDataset,
  translatedDatasetToCsv,
  type SurveyResponseDataset,
} from 'survey-data-dictionary';

const responses: SurveyResponseDataset = [
  { Q1: 'A1' },
  { Q1: 'A2' },
  { Q1: null },
];

const translated = translateDataset(dictionary, responses);
const translatedCsv = translatedDatasetToCsv(translated);

El dataset sólo contiene respuestas; no vuelve a incluir la definición de la encuesta. El diccionario aporta las etiquetas y reglas necesarias para interpretarlas.

Dataset tabular

Cuando una exportación se lee como encabezados y filas, la biblioteca puede alinearla sin convertir antes cada fila manualmente:

import { mapTabularDataset } from 'survey-data-dictionary';

const mapped = mapTabularDataset(
  dictionary,
  ['Response ID', 'Q1'],
  [[1, 'A1'], [2, 'A2']],
  ['Response ID'],
  ['', 'N/A'],
);

const translated = translateDataset(dictionary, mapped.responses);

La lista missingValues es explícita: sólo los valores proporcionados se normalizan a null. Los encabezados desconocidos se reportan como incidencias y las columnas repetidas se relacionan por posición.

Verificación local

npm run demo
npm test
npm run pack:dry-run