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

simcapture-sdk

v1.0.0

Published

Opinionated, strongly-typed SimCapture SDK — entity handles, fluent builders, and value objects over the SimCapture REST API.

Readme

simcapture-sdk

SDK tipado para la API REST de SimCapture. Entidades navegables, builders fluidos y value objects; auth, cache de token y reintento ante 401 resueltos por dentro.

Instalación

npm install simcapture-sdk
pnpm add simcapture-sdk
bun add simcapture-sdk

Node ≥ 18. axios es la única dependencia.

Quick start

import { SimCapture, TimeWindow, Location, Reservation } from "simcapture-sdk";

const sc = new SimCapture({
  apiUrl: process.env.SIMCAPTURE_API!,                 // https://api.simcapture.com
  inventoryUrl: process.env.SIMCAPTURE_INVENTORY_API!,
  credentials: {
    username: process.env.SIMCAPTURE_USER!,
    password: process.env.SIMCAPTURE_PASSWORD!,
    clientSubdomain: process.env.SIMCAPTURE_SUBDOMAIN!, // tu tenant
  },
});

const org  = await sc.Organization.named("Facultad de Medicina");
const room = new Location({ name: "P3-H1" });          // referencia, sin red
const date = new TimeWindow("2026-06-05").start().at("23:00").end().at("23:10");

const reserva = await new Reservation()
  .titled("Reserva de prueba")
  .inOrganization(org)        // handle, UUID o nombre
  .at(room)
  .when(date)
  .save();

await reserva.organization();   // navegación: fetch bajo demanda
reserva.date.durationMinutes();

Namespaces

| Namespace | Métodos | |---|---| | sc.Course | named · get · all · page · create · build | | sc.Scenario | get · build(course) | | sc.Reservation | get · between · isAvailable · build | | sc.Organization | named · get · all · create · build · replace | | sc.Location | named · get · all | | sc.User | named · get · all · page · groups · create · build | | sc.Simulator | named · get · all · configs | | sc.InventoryItem | named · get · all | | sc.Live | locations | | sc.Notification | send({ recipients, subject?, body? }) | | sc.Profile | get |

named() matchea exacto, sin distinguir mayúsculas: sin match lanza NotFoundError; con varios, AmbiguousMatchError con los ids para desambiguar vía get(id).

Listados

all() significa todo: recorre las páginas por dentro y concatena. Corta solo con página vacía; si el servidor nunca la devuelve, lanza en vez de entregar media lista.

await sc.Course.all();                  // todas las páginas
await sc.Course.page(0);                // → { items, total }
await sc.User.all({ search: "jdoe" });

/organizations, /locations, /simulators, /items, /simulator-configs y /userGroups no paginan: ahí all() es una sola request.

Builders: draft → save()

Encadenás setters; save() valida local (todos los faltantes en un solo ValidationError) y hace el POST. Después, la misma instancia es la entidad cargada.

const course = await new Course()
  .titled("CURSO DEMO").inOrganization(org)     // requeridos
  .withPublicTitle("Demo").passingPercentage(70)
  .save();

const esc = await new Scenario()
  .forCourse(course).titled("ESC 1")             // requeridos
  .withSimulators([simulator]).selfRecorded()
  .save();

await new User()
  .withUserName("jdoe").withPassword("s3cret").withEmail("[email protected]")
  .inOrganizations([org]).inGroup((await sc.User.groups())[0]!)
  .save();

await sc.Organization.build({ name: "Enfermería" }).save();

El contexto del cliente se infiere del primer handle que adjuntás. Si solo usás strings, pre-vinculá con las fábricas (sc.Course.build(...), sc.Reservation.build(...), …). Los getters lanzan error claro sobre un draft sin guardar.

Reservas

await reserva.reschedule(date);
await reserva.rename("Nuevo título");
await reserva.recolor("#07f");
await reserva.setSetupTime(60);         // preserva endTs/participantes como la web app
await reserva.setTakedownTime(15);
await reserva.setPublicNotes("visible");
await reserva.setPrivateNotes("interna");
await reserva.updateDetails({ privateNotes: "..." });
await reserva.delete();

await sc.Reservation.between(date);                             // solapan la ventana
await sc.Reservation.isAvailable(date, { locations: [room] });  // ¿libre?

Opcionales del builder: .setupTime · .takedownTime · .withPublicNotes · .withPrivateNotes · .withColor · .withExpectedParticipants · .selfEnroll · .consumeInventory · .withSimulators · .withInventory.

Evaluaciones y adjuntos

const tpl = await new EvaluationTemplate()
  .forScenario(esc).titled("Evaluación").duringSession()   // o .beforeSession() / .afterSession()
  .withQuestions([
    { text: "¿Correcto?", answers: [{ text: "SI", points: 1 }, { text: "NO", points: 0 }] },
  ])
  .save();

const results = await esc.evaluations(tpl);                // los métodos aceptan el handle
await course.assignEvaluation({ template: tpl, when: date, scenario: esc, students: [student] });

await esc.attach(new Attachment("invite.ics", await readFile("invite.ics")));
const bytes = await esc.downloadAttachment("invite.ics");

Detalles que importan

  • TimeWindow: "HH:mm" sin offset se interpreta en UTC (SimCapture guarda ISO-Z). Para hora local pasá un Date o un string con offset. overlaps es half-open.
  • isAvailable: el servidor solo filtra por ventana; salas, cursos y organizaciones se filtran client-side (AND entre categorías).
  • attach(): el registro bulk reemplaza la lista completa, así que relee los adjuntos actuales y los reenvía junto con los nuevos.
  • .addCourse() no viaja en el payload: el endpoint de creación no acepta courseIds (el curso entra por el escenario). Queda para vincular contexto.
  • .raw en cada entidad expone el registro completo de la API, incluso lo que el SDK no modela.

Errores

Todos extienden SimCaptureError, así que instanceof SimCaptureError alcanza como red.

| Error | Cuándo | status | |---|---|---| | NotFoundError | lookup sin match | 0 | | AmbiguousMatchError | lookup con >1 match (err.matches trae ids) | 0 | | ValidationError | builder incompleto, VO inválido, draft sin guardar | 0 | | SimCaptureError | fallo HTTP upstream, o listado que supera PAGE_SCAN_CAP | real / 0 |

Auth

  • Token cacheado hasta vencer su TTL suave (tokenTtlMs, default 30 min).
  • Un 401 limpia la cache, re-loguea una vez y reintenta.
  • Llamadas concurrentes comparten un único /auth en vuelo.

Migración desde 0.x

Cambia la superficie, no el motor (auth, transporte y retry son los mismos).

| 0.x | 1.x | |---|---| | new SimCaptureClient(...) | new SimCapture(...) | | sc.organizations.findAll() | sc.Organization.all() | | sc.courses.find(query) | sc.Course.page(n) (una página) · sc.Course.all() (todas) | | sc.courses.create(input) | new Course().titled(...).inOrganization(org).save() | | sc.courses.createScenario(id, i) | (await sc.Course.get(id)).addScenario(i) | | sc.reservations.create(input) | sc.Reservation.build({...}).save() | | sc.reservations.findAll({start,end}) | sc.Reservation.between(date) | | sc.users.find({search}) | sc.User.all({ search }) · sc.User.named(term) | | sc.scenarios.uploadAttachment + setAttachments | scenario.attach(new Attachment(...)) | | sc.scenarios.delete(id) | (await sc.Scenario.get(id)).delete() | | sc.simulators.getConfigs() | sc.Simulator.configs() | | sc.profile() | sc.Profile.get() | | start/end como strings | new TimeWindow(día).start().at(hh).end().at(hh) |

Los tipos wire (ReservationRecord, CourseRow, EvaluationResult, …) siguen exportados.

Arquitectura

domain/          value objects, errors, ports (HttpClient, TokenStore)
application/     entities + services (los namespaces sc.X), Authenticator, recursos
infrastructure/  axios transport + in-memory token store
config/          SimCaptureConfig + validación
simcapture.ts    composition root

Las dependencias apuntan hacia adentro: entidades y servicios solo conocen los puertos, testeables con fakes. Podés inyectar transporte o token store propios en el 2º argumento.

Desarrollo

bun install
bun run typecheck   # tsc --noEmit (strict)
bun test            # contra los puertos, sin red
bun run build       # bun build → ESM+CJS + tsc → .d.ts

Licencia

MIT