Written in ${formatDuration(s.writtenMs)}, ${s.words} words.
`);
+ if (s.low > 0 && s.high > 0) rows.push(`
${esc(letter.from || 'Their')}${letter.from ? '’s' : ''} heart ran between ${s.low} and ${s.high} beats a minute while writing.
`);
+ if (s.quickest) rows.push(`
Quickest at ${esc(excerpt(s.quickest.text))}${s.quickest.bpm} bpm
`);
+ if (s.steadiest) rows.push(`
Steadiest at ${esc(excerpt(s.steadiest.text))}${s.steadiest.bpm} bpm
`);
+ if (s.smiles) rows.push(`
${letter.from ? esc(letter.from) : 'They'} smiled ${s.smiles === 1 ? 'once' : `${s.smiles} times`}; the words glow where.
`);
+ if (s.tookBack) rows.push(`
${s.tookBack} characters were written and taken back.
`);
+ $('summary-body').innerHTML = rows.join('');
+ $('summary').hidden = false;
+ $('copy-text').onclick = async () => {
+ try { await navigator.clipboard.writeText(finalText(letter)); $('copy-text').textContent = 'Copied'; } catch { /* clipboard blocked */ }
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Controls
+
+function thump() {
+ if (!state.audio) state.audio = new AudioContext();
+ const ctx = state.audio;
+ const o = ctx.createOscillator();
+ const g = ctx.createGain();
+ o.frequency.setValueAtTime(64, ctx.currentTime);
+ o.frequency.exponentialRampToValueAtTime(38, ctx.currentTime + 0.16);
+ g.gain.setValueAtTime(0.0001, ctx.currentTime);
+ g.gain.exponentialRampToValueAtTime(0.5, ctx.currentTime + 0.012);
+ g.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + 0.22);
+ o.connect(g).connect(ctx.destination);
+ o.start();
+ o.stop(ctx.currentTime + 0.25);
+}
+
+function wireControls() {
+ for (const b of document.querySelectorAll('[data-speed]')) {
+ b.addEventListener('click', () => {
+ state.speed = Number(b.dataset.speed);
+ for (const o of document.querySelectorAll('[data-speed]')) o.setAttribute('aria-pressed', String(o === b));
+ });
+ }
+ $('skip').addEventListener('click', () => { if (state.player) state.at = Infinity; });
+ $('sound').addEventListener('click', () => {
+ state.sound = !state.sound;
+ $('sound').setAttribute('aria-pressed', String(state.sound));
+ $('sound').textContent = state.sound ? 'Heartbeat sound on' : 'Hear the heartbeat';
+ });
+ $('replay').addEventListener('click', () => {
+ document.body.classList.remove('finished');
+ $('summary').hidden = true;
+ startReplay(state.letter);
+ });
+ window.addEventListener('hashchange', () => location.reload());
+}
+
+if (typeof document !== 'undefined' && !globalThis.__HW_NO_AUTOBOOT__) {
+ wireControls();
+ boot();
+}
diff --git a/src/shared/letter-format.js b/src/shared/letter-format.js
new file mode 100644
index 0000000..efdb2c8
--- /dev/null
+++ b/src/shared/letter-format.js
@@ -0,0 +1,201 @@
+// letter-format.js
+// The wire format of a Heartwritten letter, and how it is packed into a link.
+//
+// A letter is plain data. It never goes to a server: the writer app packs it
+// into the #fragment of a link (browsers never send the fragment over the
+// network) or into a self-contained .html file.
+//
+// Decoded shape (version 1):
+// {
+// v: 1,
+// from: "Subomi", // optional, as typed by the writer
+// to: "Deola", // optional
+// day: "2026-11-12", // the day it was sealed, no time of day
+// sim: 0 | 1, // 1 when the signals were simulated (sample letters)
+// share: { edits: bool, smiles: bool },
+// ops: [[t, pos, del, ins], ...] // replayable edits, t = ms since start
+// vit: { hz, bpm: [...], br: [...], sm: [...] } // signals sampled over time
+// wave: { hz, v: [...] } // a few seconds of the pulse wave, for the seal
+// }
+//
+// On the wire the ops and samples are delta- and integer-coded, then the JSON
+// is deflated and base64url-encoded.
+
+export const FORMAT_VERSION = 1;
+export const LINK_PREFIX = 'v1.';
+// Times are stored in 10 ms ticks to keep the numbers small.
+const TICK_MS = 10;
+
+const MAX_TEXT = 20000;
+const MAX_OPS = 40000;
+const MAX_SAMPLES = 20000;
+
+/** Turn a decoded letter into the compact JSON-able form. */
+export function pack(letter) {
+ validate(letter);
+ let prevT = 0;
+ const ops = letter.ops.map(([t, pos, del, ins]) => {
+ const tick = Math.round(t / TICK_MS);
+ const dt = tick - prevT;
+ prevT = tick;
+ return ins ? [dt, pos, del, ins] : [dt, pos, del];
+ });
+ return {
+ v: FORMAT_VERSION,
+ f: letter.from || undefined,
+ to: letter.to || undefined,
+ d: letter.day || undefined,
+ s: letter.sim ? 1 : undefined,
+ sh: (letter.share.edits ? 1 : 0) | (letter.share.smiles ? 2 : 0),
+ o: ops,
+ vh: letter.vit.hz,
+ b: deltaCode(letter.vit.bpm),
+ r: deltaCode(letter.vit.br),
+ m: letter.share.smiles ? letter.vit.sm : undefined,
+ wh: letter.wave.hz,
+ w: deltaCode(letter.wave.v),
+ };
+}
+
+/** Inverse of pack(). Throws on anything malformed. */
+export function unpack(p) {
+ if (!p || p.v !== FORMAT_VERSION) throw new Error('Unsupported letter version');
+ let t = 0;
+ const ops = (p.o || []).map((op) => {
+ t += op[0];
+ return [t * TICK_MS, op[1], op[2], op[3] || ''];
+ });
+ const share = { edits: !!(p.sh & 1), smiles: !!(p.sh & 2) };
+ const bpm = deltaDecode(p.b || []);
+ const letter = {
+ v: FORMAT_VERSION,
+ from: p.f || '',
+ to: p.to || '',
+ day: p.d || '',
+ sim: p.s ? 1 : 0,
+ share,
+ ops,
+ vit: {
+ hz: p.vh || 1,
+ bpm,
+ br: deltaDecode(p.r || []),
+ sm: share.smiles && Array.isArray(p.m) ? p.m : new Array(bpm.length).fill(0),
+ },
+ wave: { hz: p.wh || 25, v: deltaDecode(p.w || []) },
+ };
+ validate(letter);
+ return letter;
+}
+
+/** Checks the shape and bounds of a decoded letter. */
+export function validate(letter) {
+ const fail = (why) => { throw new Error(`Invalid letter: ${why}`); };
+ if (!letter || typeof letter !== 'object') fail('not an object');
+ if (!Array.isArray(letter.ops) || letter.ops.length > MAX_OPS) fail('ops');
+ let len = 0;
+ let lastT = -1;
+ for (const op of letter.ops) {
+ if (!Array.isArray(op) || op.length < 3) fail('op shape');
+ const [t, pos, del, ins = ''] = op;
+ if (!isInt(t) || t < lastT) fail('op time');
+ if (!isInt(pos) || pos < 0 || pos > len) fail('op position');
+ if (!isInt(del) || del < 0 || pos + del > len) fail('op delete');
+ if (typeof ins !== 'string') fail('op insert');
+ len = len - del + ins.length;
+ if (len > MAX_TEXT) fail('text too long');
+ lastT = t;
+ }
+ const vit = letter.vit;
+ if (!vit || !(vit.hz > 0) || vit.hz > 50) fail('vit.hz');
+ for (const k of ['bpm', 'br', 'sm']) {
+ if (!Array.isArray(vit[k]) || vit[k].length > MAX_SAMPLES) fail(`vit.${k}`);
+ if (!vit[k].every(isInt)) fail(`vit.${k} values`);
+ }
+ if (!letter.wave || !Array.isArray(letter.wave.v) || letter.wave.v.length > 2000) fail('wave');
+ if (!(letter.wave.hz > 0) || letter.wave.hz > 120) fail('wave.hz');
+ for (const k of ['from', 'to']) {
+ if (letter[k] != null && (typeof letter[k] !== 'string' || letter[k].length > 80)) fail(k);
+ }
+ if (!letter.share || typeof letter.share !== 'object') fail('share');
+ return true;
+}
+
+/** Replays the ops and returns the final text. */
+export function finalText(letter) {
+ let s = '';
+ for (const [, pos, del, ins = ''] of letter.ops) s = s.slice(0, pos) + ins + s.slice(pos + del);
+ return s;
+}
+
+// ---------------------------------------------------------------------------
+// Link encoding
+
+/** Letter -> "v1." */
+export async function encodeLetter(letter) {
+ const json = JSON.stringify(pack(letter));
+ const bytes = await deflate(new TextEncoder().encode(json));
+ return LINK_PREFIX + toBase64Url(bytes);
+}
+
+/** "v1.<...>" (or a whole URL / fragment containing it) -> letter */
+export async function decodeLetter(token) {
+ const raw = extractToken(token);
+ if (!raw) throw new Error('No letter in this link');
+ const bytes = fromBase64Url(raw.slice(LINK_PREFIX.length));
+ if (bytes.length > 2_000_000) throw new Error('Letter too large');
+ const json = new TextDecoder().decode(await inflate(bytes));
+ return unpack(JSON.parse(json));
+}
+
+/** Pulls the letter token out of a URL, a hash or a bare token. */
+export function extractToken(input) {
+ if (typeof input !== 'string') return null;
+ const at = input.indexOf(LINK_PREFIX);
+ if (at === -1) return null;
+ const tok = input.slice(at).split(/[&\s]/)[0];
+ return /^v1\.[A-Za-z0-9_-]+$/.test(tok) ? tok : null;
+}
+
+export function buildLink(base, token) {
+ const clean = String(base || '').split('#')[0];
+ return `${clean}#${token}`;
+}
+
+// ---------------------------------------------------------------------------
+// helpers
+
+function isInt(n) { return Number.isInteger(n); }
+
+function deltaCode(arr) {
+ let prev = 0;
+ return arr.map((x) => { const d = x - prev; prev = x; return d; });
+}
+
+function deltaDecode(arr) {
+ let acc = 0;
+ return arr.map((d) => (acc += d));
+}
+
+async function pipeThrough(bytes, stream) {
+ const out = new Blob([bytes]).stream().pipeThrough(stream);
+ return new Uint8Array(await new Response(out).arrayBuffer());
+}
+
+async function deflate(bytes) { return pipeThrough(bytes, new CompressionStream('deflate-raw')); }
+async function inflate(bytes) { return pipeThrough(bytes, new DecompressionStream('deflate-raw')); }
+
+export function toBase64Url(bytes) {
+ let bin = '';
+ for (let i = 0; i < bytes.length; i += 0x8000) {
+ bin += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
+ }
+ return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
+}
+
+export function fromBase64Url(s) {
+ const b64 = s.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((s.length + 3) % 4);
+ const bin = atob(b64);
+ const out = new Uint8Array(bin.length);
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
+ return out;
+}
diff --git a/src/shared/playback.js b/src/shared/playback.js
new file mode 100644
index 0000000..d5fd830
--- /dev/null
+++ b/src/shared/playback.js
@@ -0,0 +1,145 @@
+// playback.js
+// Replays a letter: the words reappear at the pace they were written, long
+// pauses are shortened (but remembered), and every character keeps the
+// heart rate its writer had when it was typed. Pure logic; the reader page
+// draws what this returns.
+
+import { finalText } from './letter-format.js';
+
+export const DEFAULTS = {
+ maxGapMs: 1400, // no silence in the replay lasts longer than this
+ longPauseMs: 8000, // pauses longer than this get a quiet note in the margin
+ speed: 1, // 1 = the writer's real typing pace (after gap capping)
+};
+
+/**
+ * Build the replay timeline. Returns
+ * { ops: [{at, t, pos, del, ins}], pauses: [{at, t, ms, pos}], duration, writtenMs }
+ * where `t` is the writer's real time and `at` the replay time.
+ */
+export function buildTimeline(letter, opts = {}) {
+ const o = { ...DEFAULTS, ...opts };
+ const ops = [];
+ const pauses = [];
+ let at = 0;
+ let prevT = null;
+ let len = 0;
+ for (const [t, pos, del, ins = ''] of letter.ops) {
+ if (prevT != null) {
+ const gap = t - prevT;
+ at += Math.min(gap, o.maxGapMs) / o.speed;
+ if (gap >= o.longPauseMs) pauses.push({ at, t: prevT, ms: gap, pos });
+ } else {
+ at = 600 / o.speed; // a beat of stillness before the first word
+ }
+ // Long pastes would appear all at once; spread them like typing.
+ if (ins.length > 12 && del === 0) {
+ const chunk = 3;
+ for (let k = 0; k < ins.length; k += chunk) {
+ ops.push({ at: at + (k / chunk) * (24 / o.speed), t, pos: pos + k, del: 0, ins: ins.slice(k, k + chunk) });
+ }
+ at += Math.ceil(ins.length / chunk) * (24 / o.speed);
+ } else {
+ ops.push({ at, t, pos, del, ins });
+ }
+ len = len - del + ins.length;
+ prevT = t;
+ }
+ const writtenMs = letter.ops.length ? letter.ops[letter.ops.length - 1][0] - letter.ops[0][0] : 0;
+ return { ops, pauses, duration: at, writtenMs, length: len };
+}
+
+/** Value of a sampled series at writer-time t (ms). */
+export function sampleAt(series, hz, tMs) {
+ if (!series || !series.length) return 0;
+ const i = Math.min(series.length - 1, Math.max(0, Math.floor((tMs / 1000) * hz)));
+ return series[i];
+}
+
+/** Heart rate at writer-time t, looking a little either side when unknown. */
+export function bpmAt(letter, tMs) {
+ const { bpm, hz } = letter.vit;
+ if (!bpm.length) return 0;
+ const i = Math.min(bpm.length - 1, Math.max(0, Math.floor((tMs / 1000) * hz)));
+ for (let d = 0; d < hz * 4; d++) {
+ if (bpm[i - d] > 0) return bpm[i - d];
+ if (bpm[i + d] > 0) return bpm[i + d];
+ }
+ return 0;
+}
+
+/**
+ * Incremental player. Call advance(atMs) every frame; it applies every op
+ * due by then and reports what changed.
+ */
+export class Player {
+ constructor(letter, opts) {
+ this.letter = letter;
+ this.timeline = buildTimeline(letter, opts);
+ this.reset();
+ }
+
+ reset() {
+ this.i = 0;
+ this.chars = []; // [{ch, t}] the visible text, each char with its typing time
+ this.at = 0;
+ this.tookBack = 0;
+ }
+
+ get done() { return this.i >= this.timeline.ops.length; }
+
+ /** Writer-time currently being replayed. */
+ get writerTime() {
+ const ops = this.timeline.ops;
+ if (!ops.length) return 0;
+ const k = Math.min(this.i, ops.length) - 1;
+ return k < 0 ? ops[0].t : ops[k].t;
+ }
+
+ advance(atMs) {
+ this.at = atMs;
+ const ops = this.timeline.ops;
+ let changed = false;
+ while (this.i < ops.length && ops[this.i].at <= atMs) {
+ const { t, pos, del, ins } = ops[this.i++];
+ this.chars.splice(pos, del, ...splitUnits(ins, t));
+ this.tookBack += del;
+ changed = true;
+ }
+ return changed;
+ }
+
+ text() { return this.chars.map((c) => c.ch).join(''); }
+}
+
+function splitUnits(s, t) {
+ // One entry per UTF-16 unit, to stay aligned with editor positions. The two
+ // halves of an emoji share a time, so the reader draws them in one run.
+ const out = [];
+ for (let k = 0; k < s.length; k++) out.push({ ch: s[k], t });
+ return out;
+}
+
+/**
+ * Ink colour for a heartbeat relative to the writer's own resting level.
+ * Calm is deep ink blue, a quickened heart turns the ink warm red.
+ */
+export function inkFor(bpm, baseline) {
+ if (!(bpm > 0) || !(baseline > 0)) return 'rgb(31, 41, 66)';
+ const d = Math.max(-1, Math.min(1, (bpm - baseline) / 18));
+ const calm = [31, 41, 66];
+ const warm = [168, 38, 44];
+ const cool = [24, 54, 92];
+ const [a, b, f] = d >= 0 ? [calm, warm, d] : [calm, cool, -d];
+ const mix = a.map((x, k) => Math.round(x + (b[k] - x) * f));
+ return `rgb(${mix[0]}, ${mix[1]}, ${mix[2]})`;
+}
+
+/** Final characters of the letter, each with the time it was typed. */
+export function finalChars(letter) {
+ const p = new Player(letter, { maxGapMs: Infinity });
+ p.advance(Infinity);
+ return p.chars;
+}
+
+export { finalText };
diff --git a/src/shared/recorder.js b/src/shared/recorder.js
new file mode 100644
index 0000000..0d71836
--- /dev/null
+++ b/src/shared/recorder.js
@@ -0,0 +1,156 @@
+// recorder.js
+// Records a letter while it is being written: every edit with its time, and
+// the writer's signals sampled on a fixed clock. Pure logic, no DOM, so it is
+// tested in Node.
+
+import { FORMAT_VERSION } from './letter-format.js';
+
+export const VITALS_HZ = 4; // signals are sampled four times a second
+export const WAVE_HZ = 30; // the pulse wave kept for the seal
+export const WAVE_SECONDS = 6;
+
+/**
+ * Smallest single edit that turns `prev` into `next`:
+ * returns { pos, del, ins } or null when nothing changed.
+ * Works for typing, backspace, paste, cut, autocorrect and IME commits.
+ * With repeated characters ("aa" -> "aaa") the reported position may be one
+ * of several equivalent ones; the resulting text is the same either way.
+ */
+export function diffText(prev, next) {
+ if (prev === next) return null;
+ let start = 0;
+ const max = Math.min(prev.length, next.length);
+ while (start < max && prev[start] === next[start]) start++;
+ let endPrev = prev.length;
+ let endNext = next.length;
+ while (endPrev > start && endNext > start && prev[endPrev - 1] === next[endNext - 1]) {
+ endPrev--; endNext--;
+ }
+ return { pos: start, del: endPrev - start, ins: next.slice(start, endNext) };
+}
+
+export class LetterRecorder {
+ constructor({ now = () => Date.now() } = {}) {
+ this._now = now;
+ this.reset();
+ }
+
+ reset() {
+ this.t0 = null;
+ this.text = '';
+ this.charTimes = []; // insertion time of each character of `text`
+ this.ops = [];
+ this.samples = { bpm: [], br: [], sm: [] };
+ this.wave = []; // rolling pulse wave, values -127..127
+ this.tookBack = 0; // characters deleted along the way
+ }
+
+ /** ms since the first keystroke (or since start() was called). */
+ elapsed() {
+ if (this.t0 == null) return 0;
+ return Math.max(0, this._now() - this.t0);
+ }
+
+ start() { if (this.t0 == null) this.t0 = this._now(); }
+
+ /** Feed the full editor value after every input event. */
+ edit(nextText) {
+ this.start();
+ const d = diffText(this.text, nextText);
+ if (!d) return null;
+ const t = this.elapsed();
+ const last = this.ops[this.ops.length - 1];
+ const tRounded = Math.max(Math.round(t), last ? last[0] : 0);
+ this.ops.push([tRounded, d.pos, d.del, d.ins]);
+ this.charTimes.splice(d.pos, d.del, ...new Array(d.ins.length).fill(tRounded));
+ this.tookBack += d.del;
+ this.text = nextText;
+ return d;
+ }
+
+ /**
+ * Called on the sampling clock with the latest live signals.
+ * bpm: number|null, breath: -1..1|null, smile: 0..1|null
+ */
+ sample({ bpm, breath, smile }) {
+ if (this.t0 == null) return;
+ const due = Math.floor((this.elapsed() / 1000) * VITALS_HZ) + 1;
+ while (this.samples.bpm.length < due) {
+ this.samples.bpm.push(bpm > 0 ? Math.round(bpm) : 0);
+ this.samples.br.push(breath == null ? 0 : clampInt(breath * 100, -100, 100));
+ this.samples.sm.push(smile == null ? 0 : clampInt(smile * 9, 0, 9));
+ }
+ }
+
+ /** Append pulse-wave samples (already resampled to WAVE_HZ, any scale). */
+ pushWave(values) {
+ for (const v of values) this.wave.push(v);
+ const keep = WAVE_HZ * 20;
+ if (this.wave.length > keep) this.wave.splice(0, this.wave.length - keep);
+ }
+
+ /**
+ * Seal the letter. With share.edits off, the deletions are dropped and
+ * the letter is rebuilt as if each final character had been typed once,
+ * at the time it was typed.
+ */
+ finish({ from = '', to = '', day = '', sim = false, share = { edits: false, smiles: true } } = {}) {
+ const ops = share.edits ? this.ops.map((o) => o.slice()) : opsFromCharTimes(this.text, this.charTimes);
+ const sm = share.smiles ? this.samples.sm.slice() : this.samples.sm.map(() => 0);
+ return {
+ v: FORMAT_VERSION,
+ from: from.slice(0, 80),
+ to: to.slice(0, 80),
+ day,
+ sim: sim ? 1 : 0,
+ share: { edits: !!share.edits, smiles: !!share.smiles },
+ ops,
+ vit: { hz: VITALS_HZ, bpm: this.samples.bpm.slice(), br: this.samples.br.slice(), sm },
+ wave: { hz: WAVE_HZ, v: normalizeWave(this.wave.slice(-WAVE_HZ * WAVE_SECONDS)) },
+ };
+ }
+}
+
+/**
+ * Rebuild a forward-only edit list from the final text and the time each
+ * character was typed: characters appear in the order they were typed, each
+ * at its place in the final text. Runs typed at the same moment are merged.
+ */
+export function opsFromCharTimes(text, times) {
+ // Work in UTF-16 indices to stay aligned with the editor's value.
+ const idx = Array.from({ length: text.length }, (_, i) => i);
+ idx.sort((a, b) => times[a] - times[b] || a - b);
+ const ops = [];
+ // Fenwick tree for "how many revealed characters sit before index i".
+ const tree = new Int32Array(text.length + 1);
+ const add = (i) => { for (i++; i <= text.length; i += i & -i) tree[i]++; };
+ const before = (i) => { let s = 0; for (; i > 0; i -= i & -i) s += tree[i]; return s; };
+ for (const i of idx) {
+ const pos = before(i);
+ const t = times[i];
+ const last = ops[ops.length - 1];
+ if (last && last[0] === t && last[1] + last[3].length === pos) {
+ last[3] += text[i];
+ } else {
+ ops.push([t, pos, 0, text[i]]);
+ }
+ add(i);
+ }
+ return ops;
+}
+
+/** Scale a wave to integers in -100..100 around its median. */
+export function normalizeWave(values) {
+ const vals = values.filter((v) => Number.isFinite(v));
+ if (vals.length < 2) return [];
+ const sorted = [...vals].sort((a, b) => a - b);
+ const med = sorted[Math.floor(sorted.length / 2)];
+ let span = 0;
+ for (const v of vals) span = Math.max(span, Math.abs(v - med));
+ if (span === 0) return vals.map(() => 0);
+ return vals.map((v) => clampInt(((v - med) / span) * 100, -100, 100));
+}
+
+function clampInt(x, lo, hi) {
+ return Math.max(lo, Math.min(hi, Math.round(x)));
+}
diff --git a/src/shared/seal.js b/src/shared/seal.js
new file mode 100644
index 0000000..036cedb
--- /dev/null
+++ b/src/shared/seal.js
@@ -0,0 +1,114 @@
+// seal.js
+// A wax seal drawn from the writer's own pulse. The wave recorded in the last
+// seconds before sealing is wrapped once around the seal, so no two seals
+// look alike. Returns an SVG string; deterministic for the same input.
+
+const SIZE = 200;
+const C = SIZE / 2;
+
+function hash(values) {
+ let h = 2166136261;
+ for (const v of values) { h ^= (v + 1000) & 0xffff; h = Math.imul(h, 16777619); }
+ return h >>> 0;
+}
+
+function rng(seed) {
+ let s = seed || 1;
+ return () => { s ^= s << 13; s ^= s >>> 17; s ^= s << 5; return ((s >>> 0) % 10000) / 10000; };
+}
+
+function polar(r, a) { return [C + r * Math.cos(a), C + r * Math.sin(a)]; }
+
+function pathFrom(points) {
+ return `${points.map(([x, y], i) => `${i ? 'L' : 'M'}${x.toFixed(1)} ${y.toFixed(1)}`).join(' ')} Z`;
+}
+
+function smooth(values, k) {
+ if (!values.length) return values;
+ return values.map((_, i) => {
+ let s = 0; let n = 0;
+ for (let d = -k; d <= k; d++) {
+ const j = (i + d + values.length) % values.length;
+ s += values[j]; n++;
+ }
+ return s / n;
+ });
+}
+
+function escapeXml(s) {
+ return String(s).replace(/[<>&"']/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"', "'": ''' }[c]));
+}
+
+/**
+ * @param {number[]} wave pulse wave, -100..100 (may be empty)
+ * @param {object} opts { initial, bpm, id }
+ */
+export function sealSvg(wave, { initial = '', bpm = 0, id = 'seal' } = {}) {
+ const w = wave && wave.length >= 16 ? wave : flatline(120);
+ const rand = rng(hash(w));
+ const uid = `${id}-${hash(w).toString(36)}`;
+
+ // Melted wax edge: an irregular blob, a little different every time.
+ const edge = [];
+ const blobs = 7 + Math.floor(rand() * 4);
+ const phase = rand() * Math.PI * 2;
+ for (let i = 0; i < 160; i++) {
+ const a = (i / 160) * Math.PI * 2;
+ const r = 88 + 4.5 * Math.sin(a * blobs + phase) + 2.2 * Math.sin(a * (blobs + 5) + phase * 2) + (rand() - 0.5) * 1.6;
+ edge.push(polar(r, a));
+ }
+
+ // Pressed rim.
+ const rim = [];
+ for (let i = 0; i < 120; i++) rim.push(polar(70, (i / 120) * Math.PI * 2));
+
+ // The pulse ring: the wave wrapped once around the seal.
+ const sm = smooth(w, 1);
+ const ring = [];
+ const N = sm.length;
+ for (let i = 0; i < N; i++) {
+ const a = (i / N) * Math.PI * 2 - Math.PI / 2;
+ ring.push(polar(56 + (sm[i] / 100) * 9, a));
+ }
+
+ const letter = escapeXml((initial || '♥').slice(0, 2).toUpperCase());
+ const bpmText = bpm > 0 ? `${Math.round(bpm)} BPM` : '';
+
+ return ``;
+}
+
+function flatline(n) {
+ // A gentle placeholder beat when no wave was captured.
+ const out = [];
+ for (let i = 0; i < n; i++) {
+ const p = (i % 30) / 30;
+ out.push(Math.round(p < 0.12 ? Math.sin(p / 0.12 * Math.PI) * 80 : p < 0.3 ? -Math.sin((p - 0.12) / 0.18 * Math.PI) * 20 : 0));
+ }
+ return out;
+}
diff --git a/src/shared/sim-source.js b/src/shared/sim-source.js
new file mode 100644
index 0000000..e02647b
--- /dev/null
+++ b/src/shared/sim-source.js
@@ -0,0 +1,83 @@
+// sim-source.js
+// A stand-in for the camera, for development and tests only. It emits
+// packets shaped like SmartSpectra's decoded Metrics so the rest of the app
+// runs the same code path. The app labels every simulated session and every
+// letter written with it, so a simulated letter can't pass for a real one.
+
+export class SimulatedSource {
+ constructor({ seed = 7, restingBpm = 66, now = () => performance.now() } = {}) {
+ this.rest = restingBpm;
+ this.now = now;
+ this.seed = seed;
+ this.handlers = {};
+ this.timer = null;
+ this.excite = 0; // 0..1, nudged by bump()
+ }
+
+ on(event, fn) { this.handlers[event] = fn; return this; }
+
+ emit(event, ...args) { const h = this.handlers[event]; if (h) h(...args); }
+
+ /** Pretend something stirred the writer's heart. */
+ bump(amount = 0.6) { this.excite = Math.min(1, this.excite + amount); }
+
+ start() {
+ this.t0 = this.now();
+ this.lastUs = 0;
+ this.phase = 0;
+ this.breathPhase = 0;
+ this.smileUntil = 0;
+ this.emit('processingStatus', 3);
+ this.emit('validationStatus', 0, 0, '');
+ this.timer = setInterval(() => this.tick(), 200);
+ }
+
+ stop() {
+ clearInterval(this.timer);
+ this.timer = null;
+ this.emit('processingStatus', 1);
+ }
+
+ bpmNow(tS) {
+ const drift = 3 * Math.sin(tS / 23) + 1.5 * Math.sin(tS / 7.3 + this.seed);
+ return this.rest + drift + this.excite * 22;
+ }
+
+ /** Build one packet covering the time since the previous one. */
+ tick() {
+ const nowUs = Math.round((this.now() - this.t0) * 1000);
+ const fromUs = this.lastUs;
+ this.lastUs = nowUs;
+ this.excite *= 0.985;
+ const bpm = this.bpmNow(nowUs / 1e6);
+ const trace = [];
+ const breath = [];
+ for (let t = fromUs; t < nowUs; t += 33333) {
+ this.phase += (bpm / 60) * 0.033333;
+ this.breathPhase += (14 / 60) * 0.033333;
+ trace.push({ value: ppg(this.phase % 1), timestamp: t, stable: true, confidence: 80 });
+ breath.push({ value: Math.sin(this.breathPhase * Math.PI * 2), timestamp: t, stable: true });
+ }
+ const tS = nowUs / 1e6;
+ if (tS > this.smileUntil + 25 && Math.sin(tS * 1.7 + this.seed) > 0.995) this.smileUntil = tS + 2.5;
+ const happy = tS < this.smileUntil ? 82 : 4;
+ this.emit('metrics', {
+ cardio: {
+ pulseRate: [{ value: bpm, confidence: 78, stable: true, timestamp: nowUs }],
+ arterialPressureTrace: trace,
+ },
+ breathing: {
+ rate: [{ value: 14, confidence: 70, stable: true, timestamp: nowUs }],
+ upperTrace: breath,
+ },
+ face: { expression: [{ stable: true, timestamp: nowUs, scores: [{ type: 5, confidence: happy }, { type: 6, confidence: 100 - happy }] }] },
+ }, nowUs);
+ }
+}
+
+// A rough pulse-wave shape: quick rise, slow fall, a small notch.
+function ppg(p) {
+ if (p < 0.15) return Math.sin((p / 0.15) * (Math.PI / 2));
+ const d = (p - 0.15) / 0.85;
+ return Math.exp(-3.2 * d) + 0.12 * Math.exp(-((d - 0.28) ** 2) / 0.004) - 0.05;
+}
diff --git a/src/shared/summary.js b/src/shared/summary.js
new file mode 100644
index 0000000..142f576
--- /dev/null
+++ b/src/shared/summary.js
@@ -0,0 +1,98 @@
+// summary.js
+// The closing card a reader sees: how long the letter took, where the
+// writer's heart was quickest and steadiest, and how often they smiled.
+// Wellness wording only: these are camera estimates for feeling, not medicine.
+
+import { bpmAt, finalChars } from './playback.js';
+
+export function median(xs) {
+ const v = xs.filter((x) => x > 0).sort((a, b) => a - b);
+ if (!v.length) return 0;
+ const m = Math.floor(v.length / 2);
+ return v.length % 2 ? v[m] : Math.round((v[m - 1] + v[m]) / 2);
+}
+
+function percentile(xs, p) {
+ const v = xs.filter((x) => x > 0).sort((a, b) => a - b);
+ if (!v.length) return 0;
+ return v[Math.min(v.length - 1, Math.max(0, Math.round((p / 100) * (v.length - 1))))];
+}
+
+/** Split text into sentences with their start/end indices. */
+export function sentences(text) {
+ const out = [];
+ const re = /[^.!?\n]+[.!?]*["”’)]*|\n+/g;
+ let m;
+ while ((m = re.exec(text))) {
+ const raw = m[0];
+ const lead = raw.length - raw.trimStart().length;
+ const s = raw.trim();
+ if (!s) continue;
+ out.push({ text: s, start: m.index + lead, end: m.index + lead + s.length });
+ }
+ return out;
+}
+
+export function summarize(letter) {
+ const chars = finalChars(letter);
+ const text = chars.map((c) => c.ch).join('');
+ const baseline = median(letter.vit.bpm);
+ const scored = [];
+ for (const s of sentences(text)) {
+ if (s.text.replace(/\W/g, '').length < 12) continue; // too short to mean much
+ const bs = [];
+ for (let i = s.start; i < s.end; i++) {
+ const b = bpmAt(letter, chars[i].t);
+ if (b > 0) bs.push(b);
+ }
+ if (bs.length < 6) continue;
+ scored.push({ text: s.text, bpm: Math.round(bs.reduce((a, b) => a + b, 0) / bs.length) });
+ }
+ let quickest = null;
+ let steadiest = null;
+ for (const s of scored) {
+ if (!quickest || s.bpm > quickest.bpm) quickest = s;
+ if (!steadiest || s.bpm < steadiest.bpm) steadiest = s;
+ }
+ // Only call out a difference that is actually there.
+ if (quickest && steadiest && quickest.bpm - steadiest.bpm < 4) { quickest = null; steadiest = null; }
+ if (quickest && quickest === steadiest) steadiest = null;
+
+ let smiles = 0;
+ const sm = letter.vit.sm;
+ for (let i = 0; i < sm.length; i++) {
+ if (sm[i] >= 6 && (i === 0 || sm[i - 1] < 6)) smiles++;
+ }
+
+ const ops = letter.ops;
+ const writtenMs = ops.length ? ops[ops.length - 1][0] : 0;
+ return {
+ words: (text.match(/\S+/g) || []).length,
+ writtenMs,
+ baseline,
+ low: percentile(letter.vit.bpm, 5),
+ high: percentile(letter.vit.bpm, 95),
+ quickest,
+ steadiest,
+ smiles: letter.share.smiles ? smiles : null,
+ tookBack: letter.share.edits ? ops.reduce((n, op) => n + op[2], 0) : null,
+ };
+}
+
+export function formatDuration(ms) {
+ const s = Math.round(ms / 1000);
+ if (s < 60) return `${s} second${s === 1 ? '' : 's'}`;
+ const m = Math.floor(s / 60);
+ const r = s % 60;
+ if (m < 60) return r ? `${m} min ${r} s` : `${m} min`;
+ const h = Math.floor(m / 60);
+ return `${h} h ${m % 60} min`;
+}
+
+/** Short excerpt for quoting a sentence on the closing card. */
+export function excerpt(s, max = 64) {
+ if (s.length <= max) return s;
+ const cut = s.slice(0, max);
+ const sp = cut.lastIndexOf(' ');
+ return `${cut.slice(0, sp > max * 0.6 ? sp : max).trimEnd()}…`;
+}
diff --git a/src/shared/vitals.js b/src/shared/vitals.js
new file mode 100644
index 0000000..85d645a
--- /dev/null
+++ b/src/shared/vitals.js
@@ -0,0 +1,146 @@
+// vitals.js
+// Turns SmartSpectra `metrics` packets into the few live signals Heartwritten
+// uses. Each packet from the SDK is a windowed slice (only what is new since
+// the last packet), so this keeps its own small rolling state.
+//
+// Signals used:
+// cardio.pulseRate[] -> heart rate, only when `stable`
+// cardio.arterialPressureTrace[] -> the pulse wave (the seal, the live ink line)
+// breathing.upperTrace[] -> the breathing wave (the page breathes with it)
+// breathing.rate[] -> breaths per minute (shown live)
+// face.expression[] -> HAPPY confidence (a smile in the margin)
+
+export const HAPPY = 5; // presage.smartspectra.ExpressionType.HAPPY
+const PULSE_STALE_MS = 6000; // forget a heart rate this old
+const BREATH_WINDOW_S = 20;
+
+export function tsToUs(ts) {
+ if (ts == null) return 0;
+ if (typeof ts === 'number') return ts;
+ if (typeof ts === 'bigint') return Number(ts);
+ if (typeof ts.toNumber === 'function') return ts.toNumber();
+ return Number(ts);
+}
+
+export class VitalsTracker {
+ constructor() { this.reset(); }
+
+ reset() {
+ this.bpm = null; // latest stable heart rate
+ this.bpmAtUs = 0;
+ this.breathRate = null;
+ this.breathTrace = []; // [{t, v}] last BREATH_WINDOW_S seconds
+ this.pulseTrace = []; // [{t, v}] last 10 seconds
+ this.smile = 0; // 0..1
+ this.lastUs = 0;
+ this.packets = 0;
+ }
+
+ /** Feed one decoded Metrics message. Returns the list of new pulse-wave values. */
+ ingest(m) {
+ this.packets++;
+ const newWave = [];
+ const cardio = m && m.cardio;
+ const breathing = m && m.breathing;
+ const face = m && m.face;
+
+ for (const s of (cardio && cardio.pulseRate) || []) {
+ const t = tsToUs(s.timestamp);
+ this.lastUs = Math.max(this.lastUs, t);
+ if (s.stable && Number.isFinite(s.value) && s.value > 25 && s.value < 230) {
+ this.bpm = s.value;
+ this.bpmAtUs = t;
+ }
+ }
+ for (const s of (cardio && cardio.arterialPressureTrace) || []) {
+ if (!Number.isFinite(s.value)) continue;
+ const t = tsToUs(s.timestamp);
+ this.lastUs = Math.max(this.lastUs, t);
+ this.pulseTrace.push({ t, v: s.value });
+ newWave.push(s);
+ }
+ for (const s of (breathing && breathing.upperTrace) || []) {
+ if (!Number.isFinite(s.value)) continue;
+ const t = tsToUs(s.timestamp);
+ this.lastUs = Math.max(this.lastUs, t);
+ this.breathTrace.push({ t, v: s.value });
+ }
+ for (const s of (breathing && breathing.rate) || []) {
+ if (s.stable && Number.isFinite(s.value)) this.breathRate = s.value;
+ }
+ const expr = face && face.expression;
+ if (expr && expr.length) {
+ const latest = expr[expr.length - 1];
+ const happy = (latest.scores || []).find((x) => x.type === HAPPY);
+ this.smile = happy ? clamp01((happy.confidence || 0) / 100) : 0;
+ }
+
+ trimOlderThan(this.pulseTrace, this.lastUs - 10e6);
+ trimOlderThan(this.breathTrace, this.lastUs - BREATH_WINDOW_S * 1e6);
+ if (this.bpm != null && this.lastUs - this.bpmAtUs > PULSE_STALE_MS * 1000) this.bpm = null;
+ return resample(newWave, 30);
+ }
+
+ /** Where the latest breath sits within the recent range, -1 (out) .. 1 (in). */
+ breathPhase() {
+ const tr = this.breathTrace;
+ if (tr.length < 8) return null;
+ let lo = Infinity; let hi = -Infinity;
+ for (const { v } of tr) { if (v < lo) lo = v; if (v > hi) hi = v; }
+ if (hi - lo < 1e-9) return 0;
+ return ((tr[tr.length - 1].v - lo) / (hi - lo)) * 2 - 1;
+ }
+
+ /** The live signals the recorder samples. */
+ snapshot() {
+ return { bpm: this.bpm, breath: this.breathPhase(), smile: this.smile };
+ }
+}
+
+/** Resample timestamped samples ({timestamp, value}) to `hz`, linear. */
+export function resample(samples, hz) {
+ if (samples.length < 2) return samples.map((s) => s.value);
+ const pts = samples.map((s) => ({ t: tsToUs(s.timestamp), v: s.value })).sort((a, b) => a.t - b.t);
+ const step = 1e6 / hz;
+ const out = [];
+ let j = 0;
+ for (let t = pts[0].t; t <= pts[pts.length - 1].t; t += step) {
+ while (j < pts.length - 2 && pts[j + 1].t < t) j++;
+ const a = pts[j]; const b = pts[j + 1];
+ const f = b.t === a.t ? 0 : (t - a.t) / (b.t - a.t);
+ out.push(a.v + (b.v - a.v) * Math.max(0, Math.min(1, f)));
+ }
+ return out;
+}
+
+/** Plain-language hints for the SDK's validation codes. */
+export const HINTS = {
+ 0: 'Reading you clearly',
+ 1: 'I can’t see your face yet',
+ 2: 'Just one face, please',
+ 3: 'Slide a little to the centre',
+ 4: 'Move a little closer or further',
+ 5: 'A little more light, please',
+ 6: 'Too bright, ease the light',
+ 7: 'Sit back so your shoulders show',
+ 10: 'Tuning the camera…',
+ 11: 'The camera is running slowly',
+ 12: 'Keep your head still while you think',
+ 13: 'Lean back a little',
+ 14: 'Lean in a little',
+ 15: 'Lower the camera, or sit taller',
+ 16: 'Raise the camera a little',
+ 17: 'Look toward the screen',
+};
+
+export function hintFor(code, fallback) {
+ return HINTS[code] || fallback || 'Settling in…';
+}
+
+function clamp01(x) { return Math.max(0, Math.min(1, x)); }
+
+function trimOlderThan(arr, tMin) {
+ let k = 0;
+ while (k < arr.length && arr[k].t < tMin) k++;
+ if (k) arr.splice(0, k);
+}
diff --git a/src/writer/index.html b/src/writer/index.html
new file mode 100644
index 0000000..d7d49e9
--- /dev/null
+++ b/src/writer/index.html
@@ -0,0 +1,93 @@
+
+
+
+
+
+Heartwritten
+
+
+
+
+
+
+
+
+
Heartwritten
+
Write a letter. Your camera reads your heartbeat, your breathing and your smiles while you write, and the letter keeps them.
+
+
What the camera reads: heart rate, the pulse wave, breathing and smiles, estimated by the Presage SmartSpectra SDK from your face.
+
What the letter keeps: numbers only, a few a second. Never video, photos or your face.
+
Where it goes: nowhere until you seal it. A sealed letter lives inside its link or file, not on a server. You decide who gets it.
+
What leaves this computer while you write: the measurement runs on this computer. The SDK contacts Presage’s service only to check the key. Presage says frames and vitals are never in its telemetry, which stays off unless you turn it on below.
+
+
+
+
+
+
+
+
Camera estimates for feeling, not medicine. No diagnosis, no health advice.
+
+
+
+
+
+
+
+
+
+
+ — bpm
+ — breaths/min
+ ◡
+
+
+
+
Settling in…
+
Simulated signals
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Sealed.
+
+
+
+
+
+
+
+
+
+
+
+
The camera is off. This letter isn’t saved anywhere on this computer; it exists in that link and any file you save. Closing this window forgets it.
+
+
+
+
+
+
+
diff --git a/src/writer/preload.cjs b/src/writer/preload.cjs
new file mode 100644
index 0000000..4001726
--- /dev/null
+++ b/src/writer/preload.cjs
@@ -0,0 +1,14 @@
+// preload.cjs
+// Bundled into dist/preload.cjs. It installs SmartSpectra's own bridge
+// (window.__smartspectraBridge) and a tiny Heartwritten bridge. Nothing
+// else from Node or Electron reaches the page.
+'use strict';
+
+require('@smartspectra/node-sdk/preload');
+const { contextBridge, ipcRenderer } = require('electron');
+
+contextBridge.exposeInMainWorld('heartwritten', {
+ getConfig: () => ipcRenderer.invoke('hw:config'),
+ getApiKey: () => ipcRenderer.invoke('hw:api-key'),
+ openPreview: (token) => ipcRenderer.invoke('hw:preview', String(token)),
+});
diff --git a/src/writer/sdk-source.js b/src/writer/sdk-source.js
new file mode 100644
index 0000000..0cc9ac4
--- /dev/null
+++ b/src/writer/sdk-source.js
@@ -0,0 +1,77 @@
+// sdk-source.js
+// The live camera source: SmartSpectra's Electron renderer SDK. It emits the
+// same events as SimulatedSource, with each metrics packet already decoded.
+
+import {
+ SmartSpectraSDK, breathingMetrics, cardioMetrics, MetricType, SmartSpectraErrorCode,
+} from '@smartspectra/node-sdk/renderer';
+import { decodeMetrics } from '@smartspectra/node-sdk/messages';
+
+export class SmartSpectraSource {
+ constructor({ apiKey, telemetry = false, smiles = true }) {
+ this.apiKey = apiKey;
+ this.telemetry = telemetry;
+ this.smiles = smiles;
+ this.handlers = {};
+ this.sdk = null;
+ this.simulated = false;
+ }
+
+ on(event, fn) { this.handlers[event] = fn; return this; }
+
+ emit(event, ...args) { const h = this.handlers[event]; if (h) h(...args); }
+
+ metrics() {
+ // Breathing and cardio for the heart and the breath; EXPRESSIONS alone
+ // (not the whole face bundle) for smiles, since landmarks aren't needed.
+ const m = [...breathingMetrics, ...cardioMetrics];
+ if (this.smiles) m.push(MetricType.EXPRESSIONS);
+ return m;
+ }
+
+ build() {
+ this.sdk = new SmartSpectraSDK({
+ apiKey: this.apiKey,
+ requestedMetrics: this.metrics(),
+ enableTelemetry: this.telemetry,
+ enableAccumulatedOutput: false,
+ });
+ this.sdk.on('streamAvailable', (stream) => this.emit('stream', stream));
+ this.sdk.on('processingStatus', (s) => this.emit('processingStatus', s));
+ this.sdk.on('validationStatus', (code, ts, hint) => this.emit('validationStatus', code, ts, hint));
+ this.sdk.on('metrics', (buf, ts) => {
+ try { this.emit('metrics', decodeMetrics(buf), ts); } catch (e) { console.error('decode failed', e); }
+ });
+ this.sdk.on('error', (code, message, retryable) => this.onError(code, message, retryable));
+ }
+
+ async start() {
+ if (!this.sdk) this.build();
+ try {
+ await this.sdk.start();
+ } catch (err) {
+ this.onError(err.code, err.message, err.retryable);
+ }
+ }
+
+ async onError(code, message, retryable) {
+ // A key that isn't allowed expressions still gets the heart and breath.
+ if (code === SmartSpectraErrorCode.kMetricNotAuthorized && this.smiles) {
+ this.smiles = false;
+ this.emit('notice', 'Smiles aren’t available with this key, so they’re left out.');
+ await this.stop();
+ return this.start();
+ }
+ this.emit('error', code, message, retryable);
+ }
+
+ async stop() {
+ if (!this.sdk) return;
+ const sdk = this.sdk;
+ this.sdk = null;
+ try { await sdk.stop(); } catch { /* already stopped */ }
+ try { sdk.destroy(); } catch { /* already destroyed */ }
+ }
+}
+
+export { SmartSpectraErrorCode };
diff --git a/src/writer/writer.css b/src/writer/writer.css
new file mode 100644
index 0000000..cf5db27
--- /dev/null
+++ b/src/writer/writer.css
@@ -0,0 +1,78 @@
+:root {
+ --paper: #fbf6ec;
+ --paper-edge: #efe5d2;
+ --desk: #e7dcc7;
+ --ink: #1f2942;
+ --muted: #6d6556;
+ --line: rgba(31, 41, 66, 0.12);
+ --wax: #a3232a;
+ --serif: "Iowan Old Style", "Palatino Linotype", Palatino, Georgia, serif;
+ --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; height: 100%; }
+body { background: var(--desk); color: var(--ink); font: 16px/1.55 var(--serif); -webkit-font-smoothing: antialiased; }
+main { max-width: 900px; margin: 0 auto; padding: 28px 24px; min-height: 100%; }
+button { font: 15px var(--sans); cursor: pointer; border-radius: 99px; padding: 9px 18px; border: 1px solid rgba(31, 41, 66, 0.25); background: transparent; color: var(--ink); }
+button:disabled { opacity: 0.45; cursor: default; }
+button.primary { background: var(--ink); color: var(--paper); border-color: var(--ink); }
+button.quiet { border-color: transparent; color: var(--muted); }
+button:focus-visible, input:focus-visible, textarea:focus-visible { outline: 2px solid #c99a3b; outline-offset: 2px; }
+
+.step { display: none; }
+body[data-step="consent"] .step-consent,
+body[data-step="write"] .step-write,
+body[data-step="sealed"] .step-sealed { display: block; }
+
+.card { background: linear-gradient(165deg, var(--paper), var(--paper-edge)); border-radius: 6px; padding: 36px 40px; box-shadow: 0 24px 50px -28px rgba(40, 25, 5, 0.45), 0 1px 4px rgba(40, 25, 5, 0.1); }
+.card.center { text-align: center; }
+.wordmark { font-style: italic; font-weight: 400; font-size: 42px; margin: 0 0 6px; }
+.lede { font-size: 19px; margin: 0 0 18px; }
+.facts { padding-left: 18px; margin: 0 0 18px; }
+.facts li { margin-bottom: 8px; }
+.choices { border: 1px solid var(--line); border-radius: 6px; padding: 12px 16px; margin: 0 0 14px; font: 15px/1.5 var(--sans); }
+.choices legend { padding: 0 6px; color: var(--muted); }
+.choices label, .agree { display: block; margin: 6px 0; font: 15px/1.5 var(--sans); }
+.agree { font-weight: 600; margin: 12px 0 16px; }
+.row { display: flex; gap: 12px; align-items: center; flex-wrap: wrap; }
+.row.center { justify-content: center; margin-top: 18px; }
+.note { color: var(--muted); font: 13px/1.4 var(--sans); }
+.fine { color: var(--muted); font: 12px/1.5 var(--sans); margin-top: 18px; }
+
+/* Live strip */
+.live { display: grid; grid-template-columns: 88px 1fr 200px; gap: 16px; align-items: center; margin-bottom: 16px; }
+.cam { position: relative; width: 88px; height: 88px; border-radius: 50%; overflow: hidden; background: #2b2a28; box-shadow: 0 0 0 3px var(--paper); }
+.cam video { width: 100%; height: 100%; object-fit: cover; transform: scaleX(-1); }
+.rec { position: absolute; right: 10px; top: 10px; width: 9px; height: 9px; border-radius: 50%; background: #d23c3c; box-shadow: 0 0 0 2px var(--paper); }
+.camera-off .rec { background: #888; }
+.live-heart canvas { width: 100%; height: 64px; display: block; }
+.live-stats { display: flex; gap: 18px; font: 13px var(--sans); color: var(--muted); align-items: center; }
+.live-stats b { font: 600 20px var(--sans); color: var(--ink); font-variant-numeric: tabular-nums; }
+.smile-dot { font-size: 20px; opacity: 0.25; transition: opacity 0.4s, color 0.4s; }
+.smile-dot.on { opacity: 1; color: #c48a1a; }
+.live-side { text-align: right; }
+.hint { margin: 0 0 6px; font: 14px var(--sans); color: #8a4b18; }
+.hint[data-ok="true"] { color: #2f6b45; }
+.sim { display: inline-block; margin: 0 0 6px; font: 12px var(--sans); background: #f1e0b6; color: #5b4310; border-radius: 99px; padding: 2px 10px; }
+
+.paper { background: linear-gradient(170deg, var(--paper), var(--paper-edge)); border-radius: 4px; padding: 28px 40px 22px; box-shadow: 0 24px 50px -30px rgba(40, 25, 5, 0.45), 0 1px 4px rgba(40, 25, 5, 0.1); }
+.paper label { display: flex; gap: 10px; align-items: baseline; font-style: italic; color: var(--muted); }
+.paper input { border: 0; border-bottom: 1px solid var(--line); background: transparent; font: italic 20px var(--serif); color: var(--ink); padding: 2px 4px; flex: 0 1 260px; }
+.field-from { justify-content: flex-end; margin-top: 8px; }
+textarea { width: 100%; min-height: 46vh; border: 0; resize: vertical; background: repeating-linear-gradient(transparent 0 33px, var(--line) 33px 34px); background-attachment: local; font: 20px/34px var(--serif); color: var(--ink); padding: 8px 2px; margin: 10px 0; }
+textarea:focus { outline: none; }
+.write-foot { display: flex; gap: 16px; align-items: center; justify-content: space-between; margin-top: 14px; }
+
+/* Sealed */
+.seal { width: 190px; height: 190px; margin: 0 auto 6px; animation: press 0.7s cubic-bezier(.2,.9,.3,1.3); }
+.seal svg { width: 100%; height: 100%; }
+@keyframes press { from { transform: scale(1.6) rotate(-10deg); opacity: 0; } }
+.step-sealed h2 { font-style: italic; font-weight: 400; font-size: 34px; margin: 0; }
+.link-row { display: flex; gap: 8px; max-width: 620px; margin: 10px auto 4px; }
+.link-row input { flex: 1; font: 13px ui-monospace, Menlo, monospace; padding: 9px 12px; border-radius: 99px; border: 1px solid var(--line); background: #fff8; color: var(--ink); min-width: 0; }
+
+@media (prefers-color-scheme: dark) {
+ body { background: #1d1b18; }
+ .note, .fine, .live-stats { color: #a89f8e; }
+ .live-stats b { color: #f0e6d2; }
+}
diff --git a/src/writer/writer.js b/src/writer/writer.js
new file mode 100644
index 0000000..e17e491
--- /dev/null
+++ b/src/writer/writer.js
@@ -0,0 +1,234 @@
+// writer.js
+// The writing desk. Consent first, then the camera, then the letter.
+
+import { LetterRecorder } from '../shared/recorder.js';
+import { VitalsTracker, hintFor } from '../shared/vitals.js';
+import { encodeLetter, buildLink, finalText } from '../shared/letter-format.js';
+import { inkFor } from '../shared/playback.js';
+import { median, formatDuration } from '../shared/summary.js';
+import { sealSvg } from '../shared/seal.js';
+import { SimulatedSource } from '../shared/sim-source.js';
+import readerHtml from '../../dist/reader/index.html';
+
+const $ = (id) => document.getElementById(id);
+const bridge = window.heartwritten || null;
+
+const app = {
+ cfg: { hasKey: false, simulate: true, readerUrl: '' },
+ source: null,
+ simulated: true,
+ tracker: new VitalsTracker(),
+ recorder: new LetterRecorder(),
+ sampler: 0,
+ drawer: 0,
+ bpmHistory: [],
+ token: '',
+ letter: null,
+};
+
+function setStep(step) { document.body.dataset.step = step; }
+
+async function init() {
+ if (bridge) app.cfg = await bridge.getConfig();
+ app.simulated = app.cfg.simulate || !app.cfg.hasKey;
+ $('mode-note').textContent = app.simulated
+ ? 'No SmartSpectra key found, so the signals will be simulated and the letter marked as a sample. See the README to add your key.'
+ : '';
+ $('agree').addEventListener('change', () => { $('begin').disabled = !$('agree').checked; });
+ $('begin').addEventListener('click', begin);
+ $('body').addEventListener('input', onType);
+ $('seal-it').addEventListener('click', seal);
+ $('stop-camera').addEventListener('click', stopCamera);
+ $('copy').addEventListener('click', copyLink);
+ $('preview-letter').addEventListener('click', previewLetter);
+ $('save-file').addEventListener('click', saveFile);
+ $('again').addEventListener('click', () => location.reload());
+}
+
+// ---------------------------------------------------------------------------
+// Camera
+
+async function begin() {
+ $('begin').disabled = true;
+ const share = choices();
+ if (app.simulated) {
+ app.source = new SimulatedSource();
+ $('sim-flag').hidden = false;
+ } else {
+ const { SmartSpectraSource } = await import('./sdk-source.js');
+ const apiKey = await bridge.getApiKey();
+ app.source = new SmartSpectraSource({ apiKey, telemetry: share.telemetry, smiles: share.smiles });
+ }
+ const src = app.source;
+ src.on('stream', (stream) => { $('preview').srcObject = stream; $('preview').play().catch(() => {}); });
+ src.on('validationStatus', (code, _ts, hint) => {
+ $('hint').textContent = hintFor(code, hint);
+ $('hint').dataset.ok = String(code === 0);
+ });
+ src.on('metrics', (m) => onMetrics(m));
+ src.on('notice', (msg) => { $('notice').textContent = msg; });
+ src.on('error', (code, message) => {
+ $('hint').textContent = code === 2 ? 'Your SmartSpectra key wasn’t accepted.' : `The camera stopped: ${message}`;
+ $('hint').dataset.ok = 'false';
+ });
+ setStep('write');
+ await src.start();
+ app.sampler = setInterval(() => app.recorder.sample(app.tracker.snapshot()), 250);
+ app.drawer = requestAnimationFrame(drawWave);
+ $('body').focus();
+}
+
+async function stopCamera() {
+ const src = app.source;
+ app.source = null;
+ if (src) await src.stop();
+ app.tracker.reset();
+ $('preview').srcObject = null;
+ $('hint').textContent = 'Camera off. The rest of the letter keeps no heartbeat.';
+ $('hint').dataset.ok = 'false';
+ $('stop-camera').disabled = true;
+ document.body.classList.add('camera-off');
+}
+
+function onMetrics(m) {
+ const wave = app.tracker.ingest(m);
+ if (wave.length) app.recorder.pushWave(wave);
+ const t = app.tracker;
+ if (t.bpm) {
+ app.bpmHistory.push(t.bpm);
+ if (app.bpmHistory.length > 400) app.bpmHistory.shift();
+ }
+ $('live-bpm').textContent = t.bpm ? Math.round(t.bpm) : '—';
+ $('live-br').textContent = t.breathRate ? Math.round(t.breathRate) : '—';
+ $('live-smile').classList.toggle('on', choices().smiles && t.smile >= 0.6);
+}
+
+function drawWave() {
+ const c = $('wave');
+ const ctx = c.getContext && c.getContext('2d');
+ if (!ctx) return;
+ const W = c.width; const H = c.height;
+ ctx.clearRect(0, 0, W, H);
+ const tr = app.tracker.pulseTrace;
+ if (tr.length > 4) {
+ const tEnd = tr[tr.length - 1].t;
+ const span = 6e6;
+ let lo = Infinity; let hi = -Infinity;
+ for (const { t, v } of tr) if (t >= tEnd - span) { lo = Math.min(lo, v); hi = Math.max(hi, v); }
+ const range = hi - lo || 1;
+ ctx.lineWidth = 2.2;
+ ctx.lineJoin = 'round';
+ ctx.strokeStyle = inkFor(app.tracker.bpm, median(app.bpmHistory));
+ ctx.beginPath();
+ let first = true;
+ for (const { t, v } of tr) {
+ if (t < tEnd - span) continue;
+ const x = ((t - (tEnd - span)) / span) * W;
+ const y = H - 6 - ((v - lo) / range) * (H - 12);
+ if (first) { ctx.moveTo(x, y); first = false; } else ctx.lineTo(x, y);
+ }
+ ctx.stroke();
+ }
+ app.drawer = requestAnimationFrame(drawWave);
+}
+
+// ---------------------------------------------------------------------------
+// Writing
+
+function onType(e) {
+ app.recorder.edit(e.target.value);
+ if (app.simulated && app.source && e.data === '!') app.source.bump(0.5);
+ $('seal-it').disabled = !e.target.value.trim();
+ updateClock();
+}
+
+function updateClock() {
+ const words = (app.recorder.text.match(/\S+/g) || []).length;
+ $('clock').textContent = `Writing for ${formatDuration(app.recorder.elapsed())} · ${words} word${words === 1 ? '' : 's'} · nothing saved yet`;
+}
+setInterval(() => { if (app.recorder.t0 != null && document.body.dataset.step === 'write') updateClock(); }, 1000);
+
+function choices() {
+ return {
+ smiles: $('opt-smiles').checked,
+ edits: $('opt-edits').checked,
+ telemetry: $('opt-telemetry').checked,
+ };
+}
+
+function today() {
+ const d = new Date();
+ return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`;
+}
+
+// ---------------------------------------------------------------------------
+// Sealing
+
+async function seal() {
+ $('seal-it').disabled = true;
+ clearInterval(app.sampler);
+ cancelAnimationFrame(app.drawer);
+ const src = app.source;
+ app.source = null;
+ if (src) await src.stop();
+ $('preview').srcObject = null;
+
+ const { smiles, edits } = choices();
+ const letter = app.recorder.finish({
+ from: $('from').value.trim(),
+ to: $('to').value.trim(),
+ day: today(),
+ sim: app.simulated,
+ share: { smiles, edits },
+ });
+ app.letter = letter;
+ app.token = await encodeLetter(letter);
+ const base = median(letter.vit.bpm);
+ $('seal').innerHTML = sealSvg(letter.wave.v, { initial: letter.from.charAt(0), bpm: base });
+ const bits = [];
+ if (letter.to) bits.push(`For ${letter.to}`);
+ bits.push(`written in ${formatDuration(app.recorder.elapsed())}`);
+ if (base) bits.push(`your heart around ${base} bpm`);
+ $('sealed-sub').textContent = `${bits.join(' · ')}.`;
+ const link = app.cfg.readerUrl ? buildLink(app.cfg.readerUrl, app.token) : '';
+ $('link').value = link || 'Set a reader address to share by link, or save it as a file.';
+ $('copy').disabled = !link;
+ $('link-note').textContent = link.length > 6000
+ ? 'This is a long letter, so the link is long. Some chat apps cut long links; if it won’t open for them, send the file instead.'
+ : (app.simulated ? 'Marked as a sample letter, because the signals were simulated.' : '');
+ setStep('sealed');
+}
+
+async function copyLink() {
+ try {
+ await navigator.clipboard.writeText($('link').value);
+ $('copy').textContent = 'Copied';
+ setTimeout(() => { $('copy').textContent = 'Copy link'; }, 1600);
+ } catch {
+ $('link').select();
+ }
+}
+
+function previewLetter() {
+ if (bridge) return bridge.openPreview(app.token);
+ return window.open(`../reader/index.html#${app.token}`, '_blank', 'noopener');
+}
+
+export function letterFileHtml(token) {
+ return readerHtml.replace('',
+ ``);
+}
+
+function saveFile() {
+ const html = letterFileHtml(app.token);
+ const name = (app.letter.to || 'you').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'you';
+ const a = document.createElement('a');
+ a.href = URL.createObjectURL(new Blob([html], { type: 'text/html' }));
+ a.download = `a-letter-for-${name}.html`;
+ a.click();
+ setTimeout(() => URL.revokeObjectURL(a.href), 4000);
+}
+
+export { finalText };
+
+if (!globalThis.__HW_NO_AUTOBOOT__) init();
diff --git a/test/core.test.js b/test/core.test.js
new file mode 100644
index 0000000..a34bf3a
--- /dev/null
+++ b/test/core.test.js
@@ -0,0 +1,254 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+
+import {
+ encodeLetter, decodeLetter, pack, unpack, validate, finalText, extractToken, buildLink,
+} from '../src/shared/letter-format.js';
+import { diffText, LetterRecorder, opsFromCharTimes, normalizeWave, VITALS_HZ } from '../src/shared/recorder.js';
+import { VitalsTracker, resample, hintFor } from '../src/shared/vitals.js';
+import { Player, buildTimeline, bpmAt, inkFor, finalChars } from '../src/shared/playback.js';
+import { summarize, sentences, median, formatDuration, excerpt } from '../src/shared/summary.js';
+import { sealSvg } from '../src/shared/seal.js';
+import { SimulatedSource } from '../src/shared/sim-source.js';
+
+// A fake clock the recorder can read.
+function clock() {
+ let t = 1_000_000;
+ const now = () => t;
+ now.tick = (ms) => { t += ms; };
+ return now;
+}
+
+// Types `s` into the recorder one char at a time, `gap` ms apart.
+function type(rec, now, s, gap = 120) {
+ for (const ch of s) { now.tick(gap); rec.edit(rec.text + ch); }
+}
+
+function backspace(rec, now, n, gap = 90) {
+ for (let i = 0; i < n; i++) { now.tick(gap); rec.edit(rec.text.slice(0, -1)); }
+}
+
+function sampleLetter({ edits = true, smiles = true } = {}) {
+ const now = clock();
+ const rec = new LetterRecorder({ now });
+ let bpm = 64;
+ const feed = () => rec.sample({ bpm, breath: Math.sin(now() / 700), smile: bpm > 80 ? 0.9 : 0.1 });
+ for (const ch of 'Dear Deola, I have news. ') { now.tick(150); rec.edit(rec.text + ch); feed(); }
+ bpm = 88;
+ for (const ch of 'I got the job I told you about!') { now.tick(130); rec.edit(rec.text + ch); feed(); }
+ backspace(rec, now, 1); feed();
+ rec.edit(`${rec.text}.`); feed();
+ now.tick(12000); feed(); // a long pause
+ bpm = 62;
+ for (const ch of ' Thank you for believing in me when I did not.') { now.tick(160); rec.edit(rec.text + ch); feed(); }
+ rec.pushWave(Array.from({ length: 300 }, (_, i) => Math.sin(i / 4)));
+ return rec.finish({ from: 'Subomi', to: 'Deola', day: '2026-11-12', share: { edits, smiles } });
+}
+
+test('diffText finds the smallest edit', () => {
+ assert.deepEqual(diffText('', 'a'), { pos: 0, del: 0, ins: 'a' });
+ assert.deepEqual(diffText('abc', 'abXc'), { pos: 2, del: 0, ins: 'X' });
+ assert.deepEqual(diffText('hello world', 'hello'), { pos: 5, del: 6, ins: '' });
+ assert.deepEqual(diffText('I love it', 'I adore it'), { pos: 2, del: 3, ins: 'ador' });
+ assert.equal(diffText('same', 'same'), null);
+});
+
+test('recorder replays to the exact final text, with and without edits', () => {
+ for (const edits of [true, false]) {
+ const letter = sampleLetter({ edits });
+ const expected = 'Dear Deola, I have news. I got the job I told you about. Thank you for believing in me when I did not.';
+ assert.equal(finalText(letter), expected);
+ assert.equal(finalChars(letter).map((c) => c.ch).join(''), expected);
+ validate(letter);
+ }
+});
+
+test('with edits off, nothing deleted survives in the letter', () => {
+ const now = clock();
+ const rec = new LetterRecorder({ now });
+ type(rec, now, 'I miss you');
+ backspace(rec, now, 8);
+ type(rec, now, 'am fine');
+ const hidden = rec.finish({ share: { edits: false, smiles: true } });
+ const json = JSON.stringify(pack(hidden));
+ assert.ok(!json.includes('miss'), 'deleted words must not be in the payload');
+ assert.ok(hidden.ops.every((op) => op[2] === 0), 'no deletions');
+ assert.equal(finalText(hidden), 'I am fine');
+ const shown = rec.finish({ share: { edits: true, smiles: true } });
+ const p = new Player(shown);
+ let sawIt = false;
+ for (let at = 0; !p.done; at += 40) { p.advance(at); if (p.text().includes('I miss you')) sawIt = true; }
+ assert.ok(sawIt, 'with edits on, the reader sees the words that were taken back');
+});
+
+test('opsFromCharTimes keeps typing order for edits made mid-text', () => {
+ // "ac" typed first, then "b" inserted between them later.
+ const ops = opsFromCharTimes('abc', [0, 500, 10]);
+ const letter = { ops, vit: { hz: 1, bpm: [], br: [], sm: [] }, wave: { hz: 25, v: [] }, share: {} };
+ assert.equal(finalText(letter), 'abc');
+ assert.deepEqual(ops.map((o) => o[0]), [0, 10, 500]);
+});
+
+test('smiles off means no smile samples are kept', () => {
+ const letter = sampleLetter({ smiles: false });
+ assert.ok(letter.vit.sm.every((x) => x === 0));
+ const packed = pack(letter);
+ assert.equal(packed.m, undefined);
+});
+
+test('pack/unpack and link encoding round-trip', async () => {
+ const letter = sampleLetter();
+ assert.deepEqual(unpack(pack(letter)), letter);
+ const token = await encodeLetter(letter);
+ assert.match(token, /^v1\.[A-Za-z0-9_-]+$/);
+ const link = buildLink('https://example.test/read/', token);
+ const back = await decodeLetter(link);
+ assert.deepEqual(back, letter);
+ assert.equal(extractToken(`https://x.test/#${token}`), token);
+ assert.equal(extractToken('https://x.test/#nothing'), null);
+});
+
+test('a long letter still fits in a reasonable link', async () => {
+ const now = clock();
+ const rec = new LetterRecorder({ now });
+ const para = 'It has been a strange and lovely year, and I keep wanting to tell you about the small things. ';
+ for (let i = 0; i < 16; i++) { // ~1,500 characters over ~4 minutes
+ for (const ch of para) { now.tick(160); rec.edit(rec.text + ch); rec.sample({ bpm: 70 + (i % 5), breath: 0.2, smile: 0 }); }
+ }
+ rec.pushWave(Array.from({ length: 300 }, (_, i) => Math.sin(i / 4)));
+ const token = await encodeLetter(rec.finish({ share: { edits: true, smiles: true } }));
+ assert.ok(token.length < 12000, `token is ${token.length} chars`);
+});
+
+test('decoder rejects tampered or hostile letters', async () => {
+ const bad = [
+ { ...pack(sampleLetter()), v: 9 },
+ { ...pack(sampleLetter()), o: [[0, 5, 0, 'x']] }, // insert past the end
+ { ...pack(sampleLetter()), o: [[0, 0, 3, '']] }, // delete what isn't there
+ { ...pack(sampleLetter()), vh: 999 },
+ ];
+ for (const p of bad) assert.throws(() => unpack(p));
+ await assert.rejects(decodeLetter('v1.!!!'));
+ await assert.rejects(decodeLetter('no letter here'));
+});
+
+test('vitals tracker reads SDK-shaped packets', () => {
+ const v = new VitalsTracker();
+ v.ingest({ cardio: { pulseRate: [{ value: 72, stable: false, timestamp: 1e6 }] } });
+ assert.equal(v.bpm, null, 'unstable readings are ignored');
+ const wave = v.ingest({
+ cardio: {
+ pulseRate: [{ value: 71.6, stable: true, confidence: 60, timestamp: { toNumber: () => 2e6 } }],
+ arterialPressureTrace: Array.from({ length: 30 }, (_, i) => ({ value: Math.sin(i), timestamp: 2e6 + i * 33333 })),
+ },
+ breathing: { rate: [{ value: 13, stable: true }], upperTrace: Array.from({ length: 20 }, (_, i) => ({ value: i, timestamp: 2e6 + i * 50000 })) },
+ face: { expression: [{ scores: [{ type: 5, confidence: 90 }, { type: 6, confidence: 10 }] }] },
+ });
+ assert.equal(v.bpm, 71.6);
+ assert.equal(v.breathRate, 13);
+ assert.ok(wave.length >= 28 && wave.length <= 31);
+ const snap = v.snapshot();
+ assert.equal(snap.smile, 0.9);
+ assert.equal(snap.breath, 1, 'latest breath sample is the top of the range');
+ // Heart rate goes stale when no fresh stable value arrives.
+ v.ingest({ cardio: { arterialPressureTrace: [{ value: 0, timestamp: 9e6 }] } });
+ assert.equal(v.bpm, null);
+});
+
+test('resample produces evenly spaced values', () => {
+ const s = [{ value: 0, timestamp: 0 }, { value: 10, timestamp: 1e6 }];
+ const r = resample(s, 10);
+ assert.equal(r.length, 11);
+ assert.equal(r[5], 5);
+});
+
+test('hints read like a person talking', () => {
+ assert.equal(hintFor(5), 'A little more light, please');
+ assert.equal(hintFor(999, 'SDK hint'), 'SDK hint');
+});
+
+test('timeline shortens long pauses and remembers them', () => {
+ const letter = sampleLetter();
+ const tl = buildTimeline(letter);
+ assert.ok(tl.pauses.length >= 1, 'the 12 s pause is noted');
+ assert.ok(tl.pauses[0].ms >= 12000);
+ assert.ok(tl.duration < tl.writtenMs, 'replay is shorter than the writing');
+ for (let i = 1; i < tl.ops.length; i++) assert.ok(tl.ops[i].at >= tl.ops[i - 1].at);
+});
+
+test('player shows the writer taking a word back', () => {
+ const letter = sampleLetter({ edits: true });
+ const p = new Player(letter);
+ let sawBang = false;
+ for (let at = 0; !p.done; at += 50) {
+ p.advance(at);
+ if (p.text().endsWith('about!')) sawBang = true;
+ }
+ assert.ok(sawBang, 'the exclamation mark appears before it is replaced');
+ assert.equal(p.tookBack, 1);
+ assert.equal(p.text(), finalText(letter));
+});
+
+test('ink warms with a quicker heart and stays calm otherwise', () => {
+ assert.equal(inkFor(66, 66), 'rgb(31, 41, 66)');
+ assert.equal(inkFor(0, 66), 'rgb(31, 41, 66)');
+ const warm = inkFor(90, 66).match(/\d+/g).map(Number);
+ assert.ok(warm[0] > 150 && warm[2] < 50);
+});
+
+test('summary finds the quickest and steadiest sentences', () => {
+ const s = summarize(sampleLetter());
+ assert.match(s.quickest.text, /got the job/);
+ assert.match(s.steadiest.text, /believing in me/);
+ assert.ok(s.quickest.bpm > s.steadiest.bpm);
+ assert.equal(s.tookBack, 1);
+ assert.ok(s.smiles >= 1);
+ assert.ok(s.words > 15);
+ assert.equal(median([0, 60, 70, 80]), 70);
+ assert.equal(formatDuration(75_000), '1 min 15 s');
+ assert.equal(excerpt('a '.repeat(80)).endsWith('…'), true);
+});
+
+test('summary says nothing about the heart when it barely moved', () => {
+ const now = clock();
+ const rec = new LetterRecorder({ now });
+ for (const ch of 'One calm sentence here. And another calm sentence.') { now.tick(150); rec.edit(rec.text + ch); rec.sample({ bpm: 70, breath: 0, smile: 0 }); }
+ const s = summarize(rec.finish({}));
+ assert.equal(s.quickest, null);
+ assert.equal(s.steadiest, null);
+});
+
+test('sentences splits on punctuation and new lines', () => {
+ assert.deepEqual(sentences('Hi there. How are you?\nGood!').map((s) => s.text), ['Hi there.', 'How are you?', 'Good!']);
+});
+
+test('bpmAt looks past gaps in the signal', () => {
+ const letter = { vit: { hz: VITALS_HZ, bpm: [0, 0, 70, 0, 0], br: [], sm: [] } };
+ assert.equal(bpmAt(letter, 0), 70);
+ assert.equal(bpmAt(letter, 1000), 70);
+});
+
+test('seal is deterministic, unique per pulse and safe to inline', () => {
+ const a = sealSvg(normalizeWave(Array.from({ length: 180 }, (_, i) => Math.sin(i / 5))), { initial: 'S', bpm: 68 });
+ const b = sealSvg(normalizeWave(Array.from({ length: 180 }, (_, i) => Math.sin(i / 5))), { initial: 'S', bpm: 68 });
+ const c = sealSvg(normalizeWave(Array.from({ length: 180 }, (_, i) => Math.sin(i / 3))), { initial: 'S', bpm: 68 });
+ assert.equal(a, b);
+ assert.notEqual(a, c);
+ assert.match(a, /^