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

@case-framework/survey-core

v0.19.0

Published

Implementation of the survey core to use in typescript/javascript projects.

Readme

@case-framework/survey-core

Headless TypeScript contracts for defining, editing, running, and exporting CASE surveys. No React, network, persistence, or assistant dependency is required.

See Composable architecture for the complete document, identity, localization, expression, and host contracts.

Public entry points

  • @case-framework/survey-core: schemas, Survey, element registration, SurveyStateGraph, SurveySession, expressions, response values, and export.
  • @case-framework/survey-core/editor: SurveyEditor, field/history integration, copy/remapping, and response naming.
  • @case-framework/survey-core/editor/colors: editor color helpers.
  • @case-framework/survey-core/schema: data schemas for protocol consumers.

The survey format is version 3; submitted responses are version 3; retained participant session snapshots are version 1. Unsupported formats are rejected. There are no legacy readers or converters.

Breaking changes

The composition cutover intentionally replaces these APIs; there are no aliases:

  • SurveyEditor.undoRedo is now SurveyEditor.history.
  • The former survey, survey/utils, expressions, and engine source barrels are consolidated in the root export. Use the public entry points above.
  • Import SURVEY_EDITOR_ITEM_COLORS from @case-framework/survey-core/editor/colors, rather than the package root.
  • Responses are schema version 3: new SurveyResponse(responseId, definitionId), key is responseId, host context is customValues, and definitionId is required. Version 2 responses are rejected as unsupported.
  • validateSurveySubmission takes a required fourth argument with the loaded definitionId (see Load and run).
  • date_diff takes a unit ("years", "months" or "days"), and the owner state expression is ownerState (was conditionState). The date2string template value is formatDate.
  • Element responseSettings are exportSettings, and the mask setting maskChar is maskText.
  • responseNodeKey is no longer exported.
  • Response slot definitions returned by the registry (get(), definitions) are deeply frozen objects shared between reads, not copies. Copy before changing one.
  • Page breaks no longer accept authored metadata.itemLabel values, and the survey root no longer accepts visibility or disabled conditions. Survey.parse discards both from stored definitions, so hosts do not need a data migration.

Survey Mode must update its imports and history access when adopting this version.

Session entry points:

  • SurveySession.create no longer resumes. Use SurveySession.resume(survey, { binding, snapshot }), which is synchronous and throws (instead of rejecting) for an invalid snapshot. mode: "new" is now optional on create.
  • SessionInput is replaced by CreateSessionOptions and ResumeSessionOptions.

Load and run

import { Survey, SurveySession } from "@case-framework/survey-core";
import { defaultElementRegistry } from "@case-framework/survey-elements";

const survey = Survey.parse(savedDefinition, defaultElementRegistry);
const session = await SurveySession.create(survey, {
  binding: { sessionId: "session-1", definitionId: "release-1" },
  context: { locale: "en" },
});
session.write([{ slotId: "name-slot", value: { type: "string", value: "Example" } }]);
const submission = session.submission("response-1");
const snapshot = session.snapshot();
const resumed = SurveySession.resume(survey, {
  binding: { sessionId: "session-1", definitionId: "release-1" },
  snapshot,
});

The example slot must be declared by the loaded definition. Writes reject unknown slots, incompatible values, computed targets, and disabled controls. Hidden answers are retained but excluded from ordinary expressions and submission. Disabled visible answers remain active. Prefills run only for new sessions. Resume checks binding and restores retained values without reapplying prefills.

A host must authorize the participant and select the exact collecting definition. validateSurveySubmission(survey, input, trustedContext, { definitionId }) rejects a response recorded against another definition, validates the envelope and domains, recomputes active answers/validation, and records server-owned context. The host must record the session's currentDate at initialization, give it to the player, and supply that same day in trustedContext.currentDate on submission, including after midnight or a later resume. The response must record the same day. Missing, invalid, or mismatched dates are rejected before filtering answers; there is no date tolerance or wall-clock fallback. Do not derive trusted context from the submitted response. A deliberate date change must update the session and let the participant revalidate their answers before submission. Do not trust client-supplied visibility, disabling, or identity as authorization.

Session entry points

| Method | Starts from | Result | | ----------------------------------------------------------- | ------------------------------------ | ------------------------------------------------- | | await create(survey, options, sources?) | nothing (a new participant) | writable session; prefills run once | | resume(survey, { binding, snapshot }) | an unfinished session's snapshot() | the same writable session, exactly as it was left | | openResponse(survey, { binding, response, mode: "view" }) | a stored, submitted response | read-only session for review, plus diagnostics |

A snapshot is resumed by the participant who left it; a submitted response is opened by someone else to review it. Never resume from a response: it holds only the active answers, not the hidden ones or navigation.

Reviewing a submitted response

const opened = SurveySession.openResponse(survey, {
  binding: { sessionId: `review:${stored.responseId}`, definitionId: stored.definitionId },
  response: stored, // ResponseForReading: the host's admitted envelope
  mode: "view",
});

opened.session is read-only: writes, navigation, validation, submission and context changes throw. It evaluates visibility under the recorded context and runs no prefills, lookups or new events. opened.diagnostics lists stored answers that could not be used, opened.recordedEvents is the raw stored history (frozen; narrow its unknown entries before interpreting them), opened.ordering says whether the participant's shuffle order was reproduced ("recorded") or derived from the response ID ("fallback"), and itemMetadata and clientMetadata are passed through. session.authoredPages({ includeHidden? }) groups items by authored page breaks for a one-page view. The binding's definitionId must match the response's. mode: "edit" is reserved and throws. Render it with SurveyPlayer layout="single-page" from survey-ui. See Survey runtime for the full contract.

Stored responses

Stored answers are untrusted JSON: older versions, other writers and partial data all reach readers. decodeStoredAnswers(survey, rawAnswers) recovers what is usable against the exact definition, and decodeStoredAnswer(slot, raw) does the same for one value. Both power the exporter and openResponse; hosts can call them directly for their own checks.

const { answers, diagnostics } = decodeStoredAnswers(survey, stored.answers);
  • Unusable values are left out and reported; the raw input is never mutated, and malformed data never throws. Only a definition the decoder cannot read (ambiguous slot identities or an unsupported slot value type) throws.
  • Array entries are recovered one by one in order; bad entries, unknown options and (for reference[]) repeated selections are dropped and reported with entryIndexes. An all-invalid array is omitted; an originally empty one stays answered.
  • Issue codes (AnswerIssueCode): unknown-slot, computed-slot, invalid-type, invalid-value and unknown-option. Messages never contain answer contents.
  • Visibility, requiredness and selection limits are not checked: decoding answers "is this a valid value for this slot", not "was it allowed".
  • Extra envelope keys are ignored, getters are never invoked, and keys such as __proto__ are plain data.

SurveyResponse and ResponseForReading carry an optional clientMetadata record for host analytics (for example a device category). It is stored and exposed, but never collected, evaluated or exported by the toolkit.

Editing and extension

Elements are plain data with stateless definitions from defineElement. One annotated schema declares configuration, identities, references, wording, and follow-up bodies. createElementRegistry supplies the shared recursive body. See the architecture guide for a custom definition example.

import { SurveyEditor } from "@case-framework/survey-core/editor";
import { createBuiltInElement } from "@case-framework/survey-elements";

const editor = new SurveyEditor(survey);
const names = new Set(survey.slots.definitions.map((slot) => slot.variableName));
const element = createBuiltInElement("text", names);
const { itemId } = editor.insertElement(element);
editor.setLocalizedContent({ scope: "content", ownerId: itemId, role: "title" }, "en", {
  type: "plain",
  content: "Your name",
});

Without a layout target, insertElement creates a standalone content item. User and assistant edits share the same transactions and undo/redo. Parsing and rendering never allocate IDs. Copies allocate/remap owned identities; moves keep them. survey.slots, survey.owners, and survey.elements are derived indexes.

Expressions

Canonical JSON nodes replace runtime expression classes. Editor builders return these nodes directly with getExpression(). Array operand gaps are null. collectExpressionDependencies includes answer and disabled-state references; visitExpression, transformExpression, and remapExpression handle the grammar exhaustively. Never find or rewrite references by matching arbitrary JSON strings. Registered custom callbacks are not serialized expression behavior: hosts record custom values so server validation and export can replay the same context.

list_count(list, filter?) counts array entries (a missing list counts as 0), optionally only those also present in a same-typed filter list; a filter without a value counts 0. if_else(condition, then, else?) serializes as the if function: it evaluates only the chosen branch, returns missing for a missing condition, and takes its result type from the branches, which must match.

Export

import { compileResponseExport, createCsvSerializer } from "@case-framework/survey-core";

// Setup runs once: columns and headers are fixed before any response is read.
const exporter = compileResponseExport({
  batches: [{ definitionId: "release-1", schema: survey, profile }],
  onDiagnostic: (diagnostic) => log(diagnostic), // optional
});
const csv = createCsvSerializer(exporter.columns);
write(csv.header());
for await (const page of pagesOfStoredResponses())
  // host-owned paging
  write(csv.rows(page.map((response) => exporter.row(response, 0))));

row() takes one host-admitted ResponseForReading whose definitionId matches its batch. Answers are decoded tolerantly with decodeStoredAnswers: a bad answer leaves its cell at unusableMarker (default empty) and produces a diagnostic, while the rest of the row still exports. Stored answers are exported as stored; visibility, requiredness and other questionnaire rules are not re-evaluated, so a correctly typed answer to a hidden question is included. Computed values (such as matrix scores) are session-only: they drive in-survey conditions but are never exported, configured by a profile, or listed in the codebook. The codebook documents option scores on the answered variable, so analyses can score the exported codes themselves. diagnosticCounts() returns counters by code; the exporter keeps no per-response state, so memory stays flat.

Meta columns are submittedAt (a UTC ISO timestamp, so output does not depend on the exporting machine's time zone), participantId, responseId and definitionId; the host sets the first two on stored responses. Diagnostic codes (ExportDiagnosticCode) are the stored-answer issue codes plus undeclared-context-key (a customValues key no profile declares) and format-failed (a stored value the configured format cannot render, for example a months duration exported as seconds). Diagnostics never contain answer contents.

Default column order is meta, declared context, then responses in authored survey order. Combining several definitions requires an explicit codingPolicy; columns follow the first definition's order, then slots unique to later ones. Every CSV line, including the last, ends with the line ending, so pages concatenate exactly.

Names use unique lowercase snake_case (maximum 32 characters). Atomic naming edits use slot IDs or { elementId, prefix?, rows?, columns? } for matrices. Export codes and variable names never change answer identity. Categorical values use declared option IDs, including dropdowns and matrix cells.

Masking is an export decision, not a questionnaire property: only the dataset-wide profile passed to compileResponseExport can mask (mode: "mask"). Survey definitions and per-version batch profiles that set masking are rejected at setup.

Setup snapshots the batches and profiles: later edits by the caller have no effect on a compiled export. Meta and context presentation (headers, exclusions, order) comes from the dataset profile, or from the only batch's profile when there is one batch; batch declarations of one context key must agree unless the dataset profile declares it. Context columns accept only the default and mask transforms.

generateCodebook(survey, { locales?, profile? }) documents one definition, and generateExportCodebook(batches, { profile?, codingPolicy? }) the exact combined projection of an export. Both use the same column planner as compileResponseExport; planResponseExport(sources, settings) exposes that planner, so a host can list the columns an export will have (for example in a profile editor) without compiling it.

generateExportCodebook(batches, { profile?, codingPolicy?, locales?, unusableMarker? }) returns a resolved model with schemaVersion: 1, actual column names/positions, per-definition included/absent/excluded mappings, effective cell encodings, localized questionnaire content and explicit missing/unusable semantics. See the contract and complete multi-version example.

ResponseExportProfile has schemaVersion: 1. Slot overrides use exact slot IDs; columnHeaders, columnOrder and excludedColumns use stable encoded column IDs of any kind; contextColumns declares exported customValues keys. Existing categorical modes, boolean mappings, masks, date formatting, number precision, and duration units remain available. Missing answers are blank; answered empty selections differ from missing answers. Invalid codes, names, or profile targets fail at setup.

Presets and the profile check

Two ready-made ways to write choice answers ship in RESPONSE_EXPORT_PRESETS:

  • codes: option codes, and one 0/1 column per option of a multiple-choice question, named {variable}_{code} (for R, SPSS or pandas).
  • labels: option labels in the first survey's default language, with the selections of a multiple-choice question in one cell, separated by "; ".

A profile keys encodings by slot, so a preset is written out for the surveys of one export with applyExportPreset. The profile's own slot overrides win over the preset. Hosts keep their own context columns, meta headers and file settings in that profile.

import {
  applyExportPreset,
  checkExportProfile,
  compileResponseExport,
  RESPONSE_EXPORT_PRESETS,
} from "@case-framework/survey-core";

const surveys = versions.map((version) => version.survey);
const profile = applyExportPreset(RESPONSE_EXPORT_PRESETS.codes, surveys, hostProfile);

// On saving a profile, and before exporting: show the messages, don't export.
const issues = checkExportProfile(surveys, profile);
if (issues.length) return showIssues(issues.map((issue) => issue.message));

const exporter = compileResponseExport({ batches, profile, codingPolicy: "original" });

checkExportProfile(surveys, profile?) never throws. It returns two kinds of issue:

  • duplicate-header: two or more columns would get the same header. columns lists every one of them with what named it (namedBy): variable, optionCode, optionLabel or optionId after the variable name, a columnHeader set in the profile, or a fixed meta or context column. The message names both sides, for example Column "current_profession_other" is written by option "other" of "current_profession" and variable "current_profession_other".
  • invalid-encoding: a question whose answers cannot be written as the profile asks, for example two options with the same code or a missing label.

The survey definition already keeps variable names and every {variable}_{code} and {variable}_{id} of a multiple-choice question apart, so a valid survey has no clash under either preset. The check catches what a profile adds on top: changed option codes, labels used in column names, header overrides, and context columns. Excluded columns never clash. compileResponseExport still refuses a duplicate header at setup; the check gives the host the details to show first.

Calendar dates

Date responses and expression constants store calendar strings, not Unix timestamps: { type: "date", value: "2026-09-20" }. Year ("2026") and month ("2026-09") precision are preserved; date[] stores arrays of these strings. Numeric dates and ISO date-time strings are rejected. This is a breaking response and expression API change; there is no implicit conversion of old timestamp data. Actual event timestamps retain their existing instant semantics.

Use const_date("2026-09-20"), response_date(ref), and the date_eq, date_gt, date_gte, date_lt, date_lte, date_min, date_max builders. Equality includes precision; ordering/min/max require matching precision. date_add_days, date_add_months, and date_add_years accept a date expression and signed integer number expression. They preserve precision and clamp month-end dates. Nonzero offsets cannot require finer precision than the input. date_diff(a, b, unit) returns the signed number of completed "years", "months", or "days" in a-b, comparing mixed precisions at the coarser one; a unit finer than that precision returns undefined. Units are counted from the earlier date, so swapping the arguments only flips the sign. Missing values, ordering precision mismatches, and arithmetic outside years 0001–9999 return undefined. Calendar arithmetic uses date-fns on UTC dates, so results do not depend on the host timezone.

ctx_current_date() reads the session's current date. A new session defaults it to the participant-local day at start (context.currentDate, YYYY-MM-DD), keeps it across context refreshes and resume, and records it in the response's evaluationContext for export replay. Collecting hosts must supply their recorded session day explicitly at initialization and again for submission validation. Age in years is date_diff(ctx_current_date(), response_date(birthRef), "years").

Presence is the element's required flag. Number and date inputs (and matrix fields) take min/max bounds that are a literal or an expression of the input's type, with an optional fallback. For example:

const min = {
  expression: date_add_days(
    response_date({ slotId: "start-slot", method: "get" }),
    const_number(2),
  ).getExpression()!,
};

Bounds evaluate against current responses, including after the source answer changes. Date minimums use the start of their period, maximums the end; an answer's entire period must fit. Optional unanswered fields pass. A bound whose expression has no value does not apply unless it has a fallback; slider bounds from an expression require one. Other checks (lengths, pattern, email, url, integer, must be true) are element validations, and custom expression rules live on the content item. Registered domain validators receive an expression evaluator alongside the active-answer reader.

Default exports preserve the calendar string. Custom formatting and date templates are timezone-independent; partial dates retain their canonical value even if a pattern requests missing components. Use local Date adapters only at calendar-widget boundaries.