Files
petvity/packages/commercekit/README.md
T
GandClaude Opus 5 02d847a016 feat(commerce): extract commercekit, and adopt it here (#53)
* feat(health): track what actually matters, per species

The seven metrics in health-metrics.ts are applied uniformly to all ten
species. That is tidy and, for several of them, wrong in ways that matter.

Body temperature is not a property a fish or a reptile has in the sense the
field implies. They are ectotherms: a fish's body temperature IS the water
temperature, and a reptile's depends on where it is sitting in a thermal
gradient. Heart rate is not measurable at home for a bird, a fish or a hamster.
Asking for either produces an empty field, and empty fields teach owners to
skip — a habit that generalises to the field that mattered.

Worse, none of the seven capture what actually kills these animals. A rabbit
that has not eaten and produced no droppings for twelve hours is a medical
emergency; gut stasis is the leading cause of death in pet rabbits. A male cat
straining without producing urine is fatal in 24-48 hours. A horse whose manure
output drops is the earliest practical warning of colic. A UVB bulb keeps
emitting visible light long after its UVB output has decayed, so the enclosure
looks fine while the animal develops metabolic bone disease.

lib/config/observations.ts is the SSOT for what is worth observing and for
which species. Each observation declares its species, cadence, whether an owner
can actually produce the answer, why it earns a tap, and what answer means
"call a vet" — with the reason, because an alert nobody believes is an alert
everybody dismisses. Records (microchip, parasite schedule, diet, farrier,
water changes) are modelled separately, since they are durable facts rather
than things that changed today.

The daily set is capped at five and the cap is a test that FAILS rather than a
slice that truncates. Printing the sets caught three real design faults that
the first round of tests passed: fish had an empty daily check-in because water
temperature is device-sourced and I was filtering device readings out; dogs and
cats had seven candidates silently cut to five by array order; and reptiles were
being asked about mood while the enclosure gradient that actually kills them was
excluded. Priority is now explicit and cadence can be overridden per species —
a snake fed weekly should not be asked daily whether it ate.

Clinical values are typical published ranges compiled for product design, NOT
clinically reviewed. REVIEW_STATUS records that, so it cannot quietly be
presented to an owner as authority.

Also adds docs/pet-health-science.md (the reasoning, species by species),
docs/digital-twin-and-legacy.md (twin staging, memorialisation, gamification
and revenue, including an explicit list of what not to build), and a first blog
draft. Nothing is published — that is a deliberate decision, not a side effect.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(commerce): extract commercekit, and adopt it here

Three shops in the fleet: evig, petvity and fitfoot. Before proposing anything
shared I checked what is actually duplicated rather than assuming — revampit
turned out to be a second clone of evig, so it is three codebases, not four,
which is exactly the rule of three.

They have three incompatible foundations, so a single shared "webshop" adopted
by all of them would be a rewrite of two. What IS shared is narrower and is the
part every shop rewrites and gets subtly wrong. That is what this extracts.

packages/commercekit — zero runtime dependencies, framework-free core, React
bindings behind a separate entry point.

  money      Integer minor units. `12.55 * 100` is 1254.9999999999998, so
             fromDecimal works on digits. The currency carries its own exponent,
             so JPY has no decimals and KWD has three without a special case.
             allocate() is largest-remainder: splitting 100 three ways gives
             [34,33,33] and never loses or invents a unit — asserted across 200
             amounts x 5 weight patterns. percent() takes an explicit rounding
             mode, because a marketplace computing its own commission should
             round down rather than over-charge a seller.

  cart       A line is an id and a quantity. Never a price — a cart open for a
             week would otherwise show one number and charge another. Cross-tab
             sync, clamping, and corrupt storage yielding an empty cart rather
             than a crashed shop. Stable snapshot reference, which is what
             useSyncExternalStore needs to avoid an infinite render loop.

  inventory  Conditional decrement, all-or-nothing, with compensation on partial
             failure and sorted lock order so opposite carts cannot deadlock.
             Duplicate lines are merged, or the availability check for the
             second is made against stock the first already took. The test
             suite demonstrates the bug it prevents: a read-then-write adapter
             tells 50 buyers "yes" against 10 units while recorded stock falls
             by one.

  buyer      Account XOR guest as a discriminated union rather than two nullable
             columns, so an order belonging to nobody cannot be represented. A
             type is a claim, so the matching Postgres CHECK ships beside it.
             Receipt tokens use the platform CSPRNG and refuse to run without
             one.

  address    ISO-3166 codes with names from Intl.DisplayNames — every locale the
             runtime supports, no translation files, no way for the German list
             to drift from the English one.

Petvity adopts all of it, which is the proof: lib/shop/cart.ts and
lib/config/countries.ts become thin bindings, and placeOrder's hand-rolled
reservation is replaced by reserveAll over a Drizzle adapter that is the only
Petvity-specific part. Cancellation goes through releaseAll, so there is now one
implementation of giving stock back instead of two.

One behaviour change worth naming: the old code skipped the UPDATE entirely for
unlimited-stock products, so the shared db mock's default empty return was never
exercised on that path. The new adapter always issues the conditional update
(`stock IS NULL OR stock >= n`, and NULL - n stays NULL), which is correct
against a real database but made the mock read as "sold out". The mock was
modelling an UPDATE that matches nothing; two tests now say what a matching
UPDATE returns.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 13:24:41 +00:00

6.3 KiB
Raw Blame History

commercekit

The correctness layer under a shop. Not a commerce framework — it knows nothing about your products, your database, your framework or your payment provider. It owns the four things every shop rewrites and gets subtly wrong.

Zero runtime dependencies. Framework-free core. React bindings are a separate entry point, so a Svelte or plain-JS consumer never imports React.

npm install commercekit

Why this exists

Building a shop is mostly not hard. There are four places it is hard, and they are the same four places every time:

The bug you ship without it
Money 12.55 * 100 is 1254.9999999999998. You lose a rappen, and later a threshold comparison that looked obviously true fails.
Cart You cache the price in localStorage. A week later the shopper sees one price and is charged another — and the one they saw is the one they will argue about.
Inventory You SELECT stock then UPDATE stock. Under load, two buyers get the same last unit.
Guest identity You model the buyer as a nullable user id and a nullable email, permitting an order that belongs to nobody. Money taken, no one to ship to, unrepairable.

Money

Amounts are integers in minor units. No operation in this module can produce a fraction.

import { money, fromDecimal, times, add, percent, allocate, format } from "commercekit";

const price = money(1250, "CHF");        // 12.50 CHF, stored as 1250
fromDecimal("12.55", "CHF").amount;      // 1255 — not 1254.99…
times(price, 3);                          // exact, always
format(price, "de-CH");                   // "CHF 12.50"
format(money(1250, "JPY"), "ja-JP");      // "¥1,250" — exponent comes from the currency

The currency carries its own exponent, so JPY has no decimals and KWD has three without a special case at the call site.

allocate — the one everybody gets wrong

Splitting 100 three ways gives 33.33 each. Round each down and you lose a unit; round each up and you invent two.

allocate(money(100, "CHF"), [1, 1, 1]).map(m => m.amount);  // [34, 33, 33] — sums to 100
allocate(money(1000, "CHF"), [3, 7]).map(m => m.amount);    // [300, 700]

Largest-remainder distribution, ties to the earlier share, so it is deterministic — the same split is recomputed identically on a refund. The test suite asserts conservation across 200 amounts × 5 weight patterns.

percent() takes an explicit rounding mode, because the right answer depends on who is paying: half-up matches invoice convention, but a marketplace computing its own commission should round down rather than over-charge a seller.


Cart

import { createCart, localStorageAdapter } from "commercekit";
import { useCartLines, useCartCount } from "commercekit/react";

export const cart = createCart({ storage: localStorageAdapter() });

cart.add("sku-1", 2);
cart.add("shoe", 1, "42");   // variants are separate lines
cart.count();                 // total units

A line stores an id and a quantity. Never a price. That is the whole design. Prices are re-read from the server at checkout, so a cart left open for a week cannot show one number and charge another.

Also handled: cross-tab sync, quantity clamping, line limits, and storage that has been corrupted or hand-edited — a bad payload yields an empty cart rather than a crashed shop. The snapshot reference is stable between changes, which is what useSyncExternalStore requires to avoid an infinite render loop.

Storage is injected (memoryStorage() for SSR and tests), so nothing here stubs globals.


Inventory

import { reserveAll, releaseAll } from "commercekit";

const result = await reserveAll(adapter, [
  { sku: "a", quantity: 2 },
  { sku: "b", quantity: 1 },
]);

if (!result.ok) {
  // result.failed      — the line that could not be satisfied
  // result.compensated — was everything taken before it put back?
  // result.stranded    — if not, exactly what is now unbuyable
}

You implement one method, and it must be one statement:

UPDATE stock SET quantity = quantity - $2
WHERE sku = $1 AND quantity >= $2

Then check the affected row count. A read followed by a write oversells, and the test suite contains a demonstration of exactly that — 50 buyers told "yes" against 10 units, with the recorded stock falling by one.

All-or-nothing is the other half. A three-line order whose third line fails must put the first two back, or that stock exists and nobody can ever buy it. compensated: false means a human needs to know; the result type makes that impossible to ignore silently.

Reservations are taken in sorted sku order, so two carts holding the same two products in opposite order cannot deadlock against row locks.


Buyer

import { buyerFromRow, buyerToRow, createReceiptToken, BUYER_IDENTITY_CHECK } from "commercekit";

buyerFromRow({ userId: "u1", guestEmail: null });   // { kind: "account", userId: "u1" }
buyerFromRow({ userId: null, guestEmail: "a@b.c" }); // { kind: "guest", email: "a@b.c" }
buyerFromRow({ userId: null, guestEmail: null });    // throws — nobody to ship to

A discriminated union, not two nullable fields. And because a type is a claim rather than an enforcement, the matching constraint ships with it:

ALTER TABLE orders ADD CONSTRAINT orders_buyer_identity
  CHECK ((user_id IS NOT NULL) <> (guest_email IS NOT NULL));

createReceiptToken() uses the platform CSPRNG and refuses to run without one — the token is the only thing between a stranger and someone's delivery address.


Addresses

ISO 3166-1 alpha-2 codes, with names from Intl.DisplayNames:

countryName("CH", "de");   // "Schweiz"
countryName("CH", "ar");   // "سويسرا"
countryOptions("ja");      // sorted for a Japanese reader
isCountryCode("XX");       // false — and so is "ZZ", which CLDR *does* name

Every locale the runtime supports, with no translation files to maintain and no way for the German list to drift from the English one.


What this is not

  • Not a product catalogue, an order state machine, or a payment integration. Those are your domain and they differ per shop.
  • Not an admin UI.
  • Not a replacement for Stripe, Medusa or Saleor. It is the layer you still have to write correctly underneath whatever you choose.

License

MIT