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

@nighthq/model

v0.3.0

Published

The framework-neutral view kernel: one semantic model both a desktop and a compact presentation bind to.

Downloads

1,130

Readme

@nighthq/model

The framework-neutral view kernel: one semantic model both a desktop and a compact presentation bind to.

npm install @nighthq/model
import { createCollection, visible } from '@nighthq/model';

const fleet = createCollection({
  fields: [
    { id: 'label', label: 'Node', role: 'label' },
    { id: 'latency', label: 'Latency', role: 'quantity' }
  ],
  items: [
    { id: 'a', values: { label: 'edge-1', latency: 120 } },
    { id: 'b', values: { label: 'edge-2', latency: 940 } }
  ]
});

fleet.sortBy('latency', 'descending'); // { kind: 'accepted', value: … }
fleet.sortBy('nope'); // { kind: 'refused', reason: 'unknown-field' }
visible(fleet.state).map((item) => item.id); // ['b', 'a']

That is the shape of the whole package: you declare what a screen is, you call verbs on it, and every verb tells you what it did.

A model declares, a host performs

A model here owns semantics and nothing else. It holds which item is selected, whether the overlay is open, what the sort is, and what any presentation of the screen is obliged to let a person perceive. It does not hold a sheet's drag offset, a dropdown's flip-to-top decision, or scroll momentum — presentation-local state in the model is exactly how a model ends up able to serve one presentation and not the other.

When something has to happen outside the model — push a history entry, set the document title, announce a route change to assistive technology, move focus — the model does not do it. It emits an Effect describing it, and something else performs it. @nighthq/host is that something in a browser; a recording handler is that something in a test; on a server render it can be a set that writes a title and drops the rest.

That split is why this package imports nothing: not Svelte, not React, not the DOM, not a runtime dependency. Its own lib is ["ES2022"] with no DOM entry at all, so a stray document or window fails to compile here rather than shipping to you. Two things follow, and together they are the reason to use it:

  • A screen's behaviour is testable with no browser in the room. Sorting, paging, refusals, guards, and the effects a flow declares all run in a plain unit test at plain unit-test speed.
  • The same model can drive a host that is not your framework. The kernel is the part you would otherwise rewrite when the view layer changes.

Anatomy of a model

Every protocol below is built with defineModel, and so is anything you write yourself. Five parts:

import { defineModel, no, ok } from '@nighthq/model';

const createCounter = defineModel({
  meta: { kind: 'counter', version: 1 },
  initialState: { count: 0, max: 8 },
  guards: [(next) => (next.count <= next.max ? ok : no('above-max'))],
  capabilities: { canIncrement: (s) => s.count < s.max },
  actions: (ctx) => ({
    increment: () => ctx.propose({ ...ctx.get(), count: ctx.get().count + 1 })
  })
});

| part | what it is | | -------------- | ---------------------------------------------------------------------------------------- | | meta | { kind, version } — the declaration is versioned like any other declaration | | initialState | the state shape; the returned factory takes Partial<S> overrides | | guards | run on every proposed state; a refusal names why, and the transition does not happen | | capabilities | derived predicates, recomputed from state on every read, never assignable | | actions | the verbs, each returning an Outcome |

defineModel returns a factory, and the factory returns a model with its actions on the instance:

const counter = createCounter({ max: 2 });

counter.state; // { count: 0, max: 2 } — read-only
counter.can.canIncrement; // true — derived fresh from state
counter.increment(); // { kind: 'accepted', value: { count: 1, max: 2 } }

const stop = counter.subscribe((state) => console.log(state.count));
stop(); // unsubscribe

Capabilities are derived, never stored. canGoBack computed in two places is two places that can disagree, and the disagreement surfaces as one presentation offering an action the other refuses. Read model.can.x instead of restating the rule at the call site; that is the entire reason it is there.

Verdicts, and why a refusal is a value

A guard returns a Verdict — ok, or no('some-reason'). The reason is a stable, machine-readable name rather than prose, because it travels: into an Outcome, into a test assertion, into a log line a year from now.

type Verdict = { valid: true } | { valid: false; reason: string };

Guards run inside propose, so they hold for every door into a state, not only the action you had in mind when you wrote the rule. A check written inside one action validates the programmer and waves the pasted URL through.

Actions return an Outcome, which has four cases rather than two:

type Outcome<T = void, R = string> =
  | { kind: 'accepted'; value: T }
  | { kind: 'refused'; reason: R }
  | { kind: 'pending'; token: string }
  | { kind: 'cancelled'; reason?: string };

pending and cancelled are there because in-flight work and cancellation are part of an operation's meaning, not conventions arranged around a state machine. A UI whose model cannot say "pending" invents a parallel notion of in-flight somewhere else. For work whose completion is not local there is also Lifecycle — 'requested' | 'acknowledged' | 'running' | 'cancelling' | 'completed' | 'failed' | 'unknown-after-disconnect' — and the TERMINAL set of states after which no further command should be sent.

A guard refuses; it never clamps. setZoom(17) against a maximum of 8 must not quietly become 8, because the caller then believes something false about the state it just set. A near-miss accepted as a hit is the failure this rule exists to make impossible:

const outcome = fleet.goToPage(9);
if (outcome.kind === 'refused') {
  outcome.reason; // 'page-out-of-range' — and state.page is untouched
}

The model never half-applies. When a guard refuses, the state is unchanged and any effects that action staged are dropped — an effect requested by a refused action would have the world act on a state the model rejected.

One protocol, end to end

Here is createCollection driving a sortable, filterable, paged screen, from declaration to rendered markup.

1. Declare what the screen is about

Fields carry a role, and the role is not decoration: it is what says which obligations a field can honestly carry. A chronology obligation over a moment is meaningful; the same obligation over a category is nonsense, and the role is what makes that visible to a reader rather than only to whoever wrote it.

import type { Field, Item, Obligation } from '@nighthq/model';

const FIELDS: readonly Field[] = [
  { id: 'label', label: 'Node', role: 'label' },
  { id: 'region', label: 'Region', role: 'category' },
  { id: 'status', label: 'Status', role: 'category' },
  { id: 'latency', label: 'Latency', role: 'quantity' },
  { id: 'sessions', label: 'Sessions', role: 'quantity' },
  { id: 'lastSeen', label: 'Last seen', role: 'moment' }
];

Items are { id, values }, with values keyed by field id and deliberately open, so your record shape stays your own:

const toItem = (node: FleetNode): Item => ({
  id: node.id,
  values: {
    label: node.label,
    region: node.region,
    status: node.status,
    latency: node.latency,
    sessions: node.sessions,
    lastSeen: node.lastSeen
  }
});

2. Declare what any presentation of it must preserve

This is the part most model layers do not have, and it is what stops a well-meaning redesign from destroying a screen while breaking no rule it was given. In prose: an operator comparing a fleet needs to see latency and session load across nodes at a glance, see which node is worst without reading every row, see how recently each reported as a shape rather than as a list of dates, and keep a node's identity and latency in view while selecting it.

As data:

const OBLIGATIONS: readonly Obligation[] = [
  { kind: 'comparable', fields: ['latency', 'sessions'] },
  { kind: 'ordering', field: 'latency' },
  { kind: 'anomaly', field: 'latency' },
  { kind: 'chronology', field: 'lastSeen' },
  { kind: 'visible-during', fields: ['label', 'latency'], operation: 'select' }
];

Write these before the presentations. Obligations declared after a view is built are obligations that view happens to satisfy, which proves nothing.

3. Create the collection

import { createCollection } from '@nighthq/model';

export const collection = createCollection({
  fields: FIELDS,
  items: ITEMS,
  obligations: OBLIGATIONS,
  pageSize: 6,
  sort: { field: 'latency', direction: 'descending' }
});

Create it once, at module scope, if there is one such screen. One instance shared by every presentation of it is what makes sort, filter, page and selection survive a switch between them — and it is what lets you attribute any difference between two presentations to perception rather than to state.

4. Drive it

The actions, all returning Outcome:

collection.sortBy('latency', 'descending'); // 'unknown-field' if not declared
collection.clearSort();
collection.setQuery('edge'); // substring match over label-role fields
collection.nextPage(); // 'at-last-page' at the end
collection.previousPage(); // 'at-first-page' at the start
collection.goToPage(2); // 'page-out-of-range' rather than an empty screen
collection.select('nnode_7'); // 'unknown-item' rather than selecting nothing
collection.setItems(nextItems);

Two behaviours are decisions rather than accidents, and both are worth knowing before you work around them:

  • Sorting or filtering returns to page 0. Staying on page 3 of a reordered or re-filtered set keeps the position and discards its meaning.
  • A selection whose item is gone clears rather than sliding to a neighbour. setItems keeps the selection if its id survived and drops it otherwise; moving it would be the model inventing an intent nobody expressed. A shorter result set also pulls the page back into range instead of stranding it past the end.

The derived reads are free functions over state, so each presentation takes the one it needs:

import { pageItems, visible } from '@nighthq/model';

visible(collection.state); // filtered, in sort order — every row
pageItems(collection.state); // just the current page

Sorting puts a missing value last in both directions: an absent number is not a small one, and letting it lead a descending sort reads as a real extreme. An explicit null counts as missing alongside undefined, because to a person reading the column they are the same fact.

And the capabilities, so a pager never restates the paging rule:

collection.can.canGoNextPage;
collection.can.canGoPreviousPage;
collection.can.canClearQuery;
collection.can.canClearSort;

5. Render it

Nothing above knows what a table is. A presentation reads state and calls actions — here it is wired to Table from @nighthq/components, which is column-driven and hands sorting back to whoever knows whether it holds the whole set or one page of it:

<script lang="ts">
  import { Table } from '@nighthq/components';
  import { visible } from '@nighthq/model';

  import { collection, state } from './compare.svelte.ts';

  // `Table` is column-driven over a flat record and `Item` nests its data under
  // `values`, so flatten once, here, rather than in every snippet.
  const rows = $derived(visible(state.value).map((row) => ({ ...row.values, id: row.id })));

  // It takes the sort as one key, `-` prefixed for descending.
  const sortKey = $derived(
    state.value.sort
      ? `${state.value.sort.direction === 'descending' ? '-' : ''}${state.value.sort.field}`
      : ''
  );

  const onsort = (key: string) => {
    const descending = key.startsWith('-');
    collection.sortBy(descending ? key.slice(1) : key, descending ? 'descending' : 'ascending');
  };
</script>

<Table
  columns={[
    { key: 'label', label: 'Node', sortable: true },
    { key: 'region', label: 'Region', sortable: true },
    { key: 'latency', label: 'Latency', numeric: true, sortable: true },
    { key: 'sessions', label: 'Sessions', numeric: true, sortable: true }
  ]}
  {rows}
  rowKey={(row) => row.id}
  label="Fleet comparison"
  sort={sortKey}
  {onsort}
  onrowclick={(row) => collection.select(row.id)}
/>

A pager is the same shape — read a capability, call a verb:

<Button disabled={!state.canGoPreviousPage} onclick={() => collection.previousPage()}>
  Previous
</Button>
<span>Page {state.value.page + 1}</span>
<Button disabled={!state.canGoNextPage} onclick={() => collection.nextPage()}>Next</Button>

6. Bridging to a reactive framework — read this before you debug it

The model is a plain object with a subscribe, which is what makes it portable and is also the one place a consumer reliably gets hurt. A reactive framework cannot see into a plain object. Mirror a handful of fields out of the model and then derive your rows straight from collection.state, and the derivation computes once at mount and never again: the filter box updates the model correctly, and the list never moves. Nothing throws, nothing fails to compile, and the screen is inert.

Mirror the whole state, once, in one place, so that a derivation reads one reactive source and cannot half-subscribe to it. In Svelte 5:

// compare.svelte.ts
import { collection } from './collection.ts';

const mirror = $state({
  value: collection.state,
  canGoNextPage: collection.can.canGoNextPage,
  canGoPreviousPage: collection.can.canGoPreviousPage,
  canClearQuery: collection.can.canClearQuery
});

collection.subscribe((next) => {
  mirror.value = next;
  // Re-read from the model rather than deriving here — a second copy of the
  // paging rule is a second thing that can disagree with it.
  mirror.canGoNextPage = collection.can.canGoNextPage;
  mirror.canGoPreviousPage = collection.can.canGoPreviousPage;
  mirror.canClearQuery = collection.can.canClearQuery;
});

export { collection };
export const state = mirror;

The seed is load-bearing, not tidiness. subscribe is called after every accepted transition and never with the current state, so a mirror built from the subscription alone starts empty and stays that way until something moves. If the model already held a value when you subscribed — which it does whenever something adopted an address or a selection before your code ran — nothing will ever notify you of it. Read state first, subscribe second. @nighthq/host makes this reachable at boot, and its README says where.

Bridge once per model, not once per component. Two components each writing their own subscription is two places for it to be subtly different.

Representation obligations

The obligations declared in step 2 are not documentation. A presentation declares what a viewer of it can perceptually afford, and unmet reports what that pairing would break:

import { unmet, type Affordances } from '@nighthq/model';

const TABLE: Affordances = {
  alignedAcrossItems: ['label', 'region', 'status', 'latency', 'sessions', 'lastSeen'],
  ordered: true,
  spatial: ['lastSeen'],
  distinguished: ['latency'],
  persistentDuring: ['label', 'region', 'status', 'latency', 'sessions', 'lastSeen'],
  operations: ['sort', 'filter', 'select']
};

const CARDS: Affordances = {
  alignedAcrossItems: ['label', 'latency'],
  ordered: true,
  spatial: [],
  distinguished: ['latency'],
  persistentDuring: ['label', 'latency'],
  operations: ['sort', 'filter', 'select']
};

unmet(OBLIGATIONS, TABLE); // []
unmet(OBLIGATIONS, CARDS); // chronology-not-spatial, not-aligned-across-items, …

Both of those expose the same records and the same operations. A model that recorded only state and operations would rate them equal — and a redesign told "make this work on a phone" would produce the card stack, be able to prove that no operation was lost, and remove the comparison the screen existed for. The breach is what says so out loud. Each one names the fields responsible, so the repair is actionable ("add a sessions line to the card") rather than a verdict on the whole presentation.

The five kinds, and what each asks:

| kind | met when | | ---------------- | ---------------------------------------------------------------------------------------------- | | comparable | every named field is in alignedAcrossItems | | ordering | the sort field is aligned across items and ordered is true | | chronology | the field is in spatial — encoded in position, not only printed | | anomaly | the field is in distinguished | | visible-during | the named fields are in persistentDuring, if the presentation performs that operation at all |

Three traps, each easy to walk into:

  • alignedAcrossItems means across items. A detail pane shows every field of one record at the same time and compares nothing, so it may list only what it aligns down the collection — usually the label column beside the pane, and often nothing at all. A pane that declares its full field set passes a comparison obligation with nothing comparable in it.
  • An obligation nobody declared cannot be breached. unmet([], CARDS) is []. Empty means the pairing is honest, not that the presentation is good.
  • An operation the presentation never performs cannot hide anything during it. A read-only projection meets visible-during vacuously rather than failing it.

An obligation naming a field that does not exist is a promise about nothing, and would be reported as met — so it is a guard rather than a lint, and the next proposal on that model refuses with obligation-names-unknown-field.

unmet is a pure function rather than a guard on the collection itself, because a breach is not an invalid state: the state is fine, and it is the pairing with a presentation that is wrong. Guarding it would make the model refuse transitions on behalf of a projection it cannot see.

Effects

A model never performs a side effect. It declares one, and the union of what it can declare is closed:

type Effect =
  | { kind: 'navigate'; to: Route; replace?: boolean; depth?: number }
  | { kind: 'navigate.back' }
  | { kind: 'title.set'; title: string }
  | { kind: 'announce'; message: string; urgency: 'polite' | 'assertive' }
  | { kind: 'focus'; targetId: string };

Closed on purpose. An open union — { kind: string; payload: any } — lets any app invent an effect no handler knows about, and the failure is silence at runtime rather than a type error. Handlers is a total map for the same reason: a set that forgets a kind fails to compile instead of dropping that effect forever. exhaustive() turns a newly added kind into a compile error at every interpreter, and perform(effect, handlers) dispatches one through a set.

import { perform } from '@nighthq/model';

const stop = navigation.onEffect((effect) => perform(effect, handlers));

A model with no effect listener drops its effects, deliberately. A model has to stay usable with no host at all — in a unit test asserting state, or a replay that only cares about transitions. The host is what makes effects happen, not what makes the model work.

Effects are emitted after the transition they accompany and only if it was accepted, so a refused action emits nothing.

In a browser, the handler set you want is browserHandlers() from @nighthq/host, which performs all five against the document. That package also owns the route registry and the URL grammar.

The protocols in the box

Each is a defineModel declaration you can use directly, and a worked example of the shape if you write your own.

createSelection — options and a current one. select refuses unknown-option and option-disabled; next and previous walk the selectable options only, take an optional wrap, and refuse at-end / at-start rather than silently staying put. With nothing selected, a step lands on the first or last option instead of refusing — the alternative is a keyboard user pressing ArrowRight on a fresh strip and getting nothing. setOptions keeps the selection if its id is still present and still selectable.

createOverlay — one surface at a time, with the two properties kept apart that are usually conflated. persistent answers "may this be dismissed"; blocking answers "does the rest of the interface remain available". A dismissable confirmation is still blocking, and a persistent side panel need not be. open refuses already-open rather than silently switching surfaces; close is the deliberate one and is always allowed; dismiss is the scrim-or-Escape one and refuses when it must, which is what canDismiss reports. returnFocusTo holds a correspondence id rather than an element, because the element does not survive a reprojection and the id does. Nothing in the state names a dialog or a sheet: a projection reads blocking and chooses.

createCollection — fields, items, sorting, filtering, paging, selection, and representation obligations. Walked end to end above.

createNavigation — where a person is and how they got there. A route registry is one declaration that many consumers read: the app, a navigation instrument, titleOf for the tab, trailOf for breadcrumbs, and a coverage test. go narrows to the registry's literal ids when the registry is written as a literal, so a typo is a compile error rather than a runtime refusal in a log; syncFromHost deliberately does not narrow, because it is the door outside strings come through and its job is to refuse them. title is required on every route, because a route with no title is a tab, a history entry and a bookmark that all read the same. Most consumers reach this through createHost in @nighthq/host, which wires it to real history.

createCommand — one operation whose completion is not local. outcome.ts had declared a Lifecycle for exactly this since it was written, and nothing read it; the shape was meanwhile built by hand in a consumer's transport, with in-flight ids in a private Set. request returns pending(token) and refuses in-flight rather than double-submitting. A response names its attempt, so acknowledge, start, complete and fail refuse stale-token — a completion for a superseded attempt is ignored with a reason instead of resurrecting work nobody is waiting for. cancel() returns pending, never cancelled, and the distinction is the protocol's point rather than a nicety: the model does not own the work, so it can ask for a stop and cannot declare one. The world closes the operation with complete or fail(token, 'cancelled'). Tokens come from the caller and there is no clock — staleness is a question about identity, not about age, which is what keeps the model replayable with no host in the room.

createChoiceMany — several of N as one pick, with bounds. createSelection is one-of-N, which is why RadioGroup and TabStrip can mark an option unavailable and refuse option-disabled by name; the several-of-N half had no protocol, so CheckboxGroup and every consumer composing checkboxes into one pick owned its own state and could express none of that. The refusal a bare string[] cannot express is the reason this is a protocol: unchecking the last of a required set, or checking one past a cap, are both just "the array changed", discovered afterwards if at all. Here they are at-min and at-max, refused before the state moves.

selected is in OPTION order, never insertion order — select('c') then select('a') over a, b, c yields ['a', 'c']. CheckboxGroup's value already promises option order, so insertion order would have the two disagreeing the moment a consumer rendered from one and compared with the other, and the disagreement would read as a sorting bug in the component rather than a contract nobody stated. selectAll refuses at-max rather than selecting a prefix, because a partial "all" cannot be told from success. setOptions refuses nothing itself — it keeps the survivors that are still selectable, and the bounds guard answers below-min if that strands the selection, so the caller learns why with the state untouched.

createText — a value, the rules it is held to, and the moment they are checked. Field and Input are props with nothing behind them, so every consumer decided for itself when a value was invalid and — the part that actually varied — when to say so. input refuses nothing, and that is the protocol's point rather than an omission: a field that rejects a keystroke loses it silently, turns a paste one character over into a value nobody agreed to, and cannot represent the half-typed state a form spends most of its life in. So validity is derived rather than enforced at entry. problems(state) lists every broken rule in a declared order — required, too-long, pattern, then whatever a custom check returned — and commit is the gate, refusing invalid with a single id while any of them stands; the specifics travel in the derived read, because a reason that tried to carry which rules were broken would have to be a sentence. revert restores the committed value and refuses not-dirty. The one guard says committed always satisfies the rules, so tightening them past an already-saved value is refused committed-invalid rather than leaving a form whose stored value fails its own validation.

createToggle and createDisclosure — the two booleans, each with the one thing a bare boolean cannot say. Both look too small to be protocols until that rule is written down.

A switch that must not flip while the command it controls is in flight is a locked toggle. Today every consumer re-implements that by wiring disabled to something else's pending state — and disabled names the wrong thing: it is a statement about the CONTROL, where what the consumer means is a statement about the VALUE. locked says it, set and toggle refuse locked by name, and the control stays focusable and announced. A switch that ignores a click and a switch that refuses one are the same pixel and different facts.

⭐ createToggle is the first protocol here with an empty guards array, and that is a decision rather than an omission: on and locked have no invariant between them, so all four combinations are legal and reachable — including on and locked together, which is the point. A guard added for symmetry would encode no rule, and the first reader to inspect it would go looking for the one it seemed to promise.

A section that must not close while it holds an invalid field is a pinned disclosure, and nothing expressed it: a consumer either let it close and lost the error, or removed the affordance so it could never be collapsed again. pin() from closed opens and pins in ONE transition — two proposals would pass through a section that is closed and cannot be opened, and defineModel notifies on every accepted proposal, so every consumer would render that frame. The guard pinned ⇒ open is that step's backstop.

Testing, with no DOM in the room

This is what the no-imports rule buys, so it is worth the two lines. A protocol test is a plain unit test:

import { describe, expect, it } from 'vitest';
import { createCollection, pageItems, visible } from '@nighthq/model';

const fresh = (overrides = {}) =>
  createCollection({ fields: FIELDS, items: ITEMS, obligations: OBLIGATIONS, ...overrides });

describe('filtering and paging', () => {
  it('filters over label fields only', () => {
    const m = fresh();
    m.setQuery('bill');
    expect(visible(m.state).map((i) => i.id)).toEqual(['b']);
  });

  it('pages, and refuses past the ends', () => {
    const m = fresh({ pageSize: 2 });
    expect(pageItems(m.state).map((i) => i.id)).toEqual(['a', 'b']);
    expect(m.previousPage()).toEqual({ kind: 'refused', reason: 'at-first-page' });
    expect(m.nextPage().kind).toBe('accepted');
    expect(pageItems(m.state).map((i) => i.id)).toEqual(['c', 'd']);
    expect(m.nextPage()).toEqual({ kind: 'refused', reason: 'at-last-page' });
  });

  it('refuses an unknown field BY NAME and does not half-apply', () => {
    const m = fresh();
    expect(m.sortBy('nope')).toEqual({ kind: 'refused', reason: 'unknown-field' });
    expect(m.state.sort).toBeNull();
  });
});

Two habits that make these tests worth having:

Assert on the reason, not just on the refusal. expect(outcome.kind).toBe('refused') also passes for a guard that refuses everything. The reason is what makes the assertion about the rule you meant.

Give a refusal test a positive control in the same file. A guard that refuses every proposal makes every refusal assertion pass, and the suite reads green:

it('accepts a selection whose item exists', () => {
  const m = fresh();
  expect(m.select('a').kind).toBe('accepted');
});

For a model that emits effects, install recordingHandlers() from @nighthq/host and assert on the effects that were requested — a sharper assertion than their visible consequence, and one that needs no document. That recipe is in that package's manual.

What is deliberately not here

  • Any notion of a URL. The model holds route ids and parameters; turning those into a path, a hash or a query is the host's job, because it differs between a static file server, an app with a rewrite rule, and a test. A model that knew about location could not run without one.
  • Layout. Abstract the interaction intent and the state machine; never abstract the layout. Every general abstract-UI language died of the same thing: it could express only the intersection of its targets, so the first time a product needed something one platform does well, it escaped — and once escaping is normal, the abstraction is overhead on everything that did not.
  • Column widths, virtualisation, sticky headers, or whether a detail pane is a side panel or a pushed route. The model says the ordering must be perceptible; it does not say by what means.
  • A real effect system. What is here is the shape of algebraic effect handlers — a closed tagged union with exhaustive interpreters — not an implementation of them. TypeScript has no effect system: nothing proves a handler exists, and nothing suspends a computation. Stated plainly, because a layer that promised more would be promising static guarantees the language cannot deliver.

Requirements

This package ships compiled ES2022 ESM with type declarations, so your tsconfig does not compile it and no bundler setting is needed. It has no runtime dependencies and no DOM dependency: lib: ["ES2022"] is enough to consume it, and it runs unchanged in a browser, in Node, and in a test runner.

The family

Five packages, published together from one repository:

| package | what it is | | -------------------------------------------------------------------------- | ------------------------------------------------------------------------ | | @nighthq/tokens | the colour system, and the base stylesheets that depend only on it | | @nighthq/components | the Svelte 5 interface primitives, plus an opt-in atmospheric tier | | @nighthq/icons | line-work icons and the brand mark, as path data — no framework | | @nighthq/model | the framework-neutral view kernel: one semantic model, two presentations | | @nighthq/host | the effect boundary — history, titles, announcements, focus |

Start with tokens + components. Add icons when you need glyphs, and model + host when one screen has to render as both a desktop and a compact presentation.

The repository is private, so homepage and repository links on these npm pages will not resolve for you — these READMEs and the tarballs are the whole documented surface, which is why they carry more than a link would.

(No counts in this table on purpose: a number repeated across five files is five places for it to go stale, and only each package's own README has a check-docs claim behind its figures.)

MIT © Bitspark