@hollis-labs/surface-cards 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,25 @@
1
- # Temporary Holding Version
1
+ # @hollis-labs/surface-cards
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Cards without any styling. A card is something an app shows the user outside a window: a
4
+ notice, a question, a request to approve, progress on work.
5
+
6
+ | File | What it is |
7
+ |---|---|
8
+ | `src/response.ts` | What a card reports (`CardOutcome`: answered or declined) and how it reads the status the server recorded (`classifyPriorResponse`, total over any string) |
9
+ | `src/engine/` | The lifecycle engine: rules as data decide where each card shows (inline, tray, toast, modal), with dedupe, supersession and held updates while a card is being edited. No React, no timers, no transport |
10
+ | `src/form.ts` | A form compiled from a JSON Schema subset, with validation and coercion |
11
+ | `src/registry.ts` | The table of renderers by kind and version; an unknown kind resolves to a miss, never to nothing |
12
+ | `src/react.ts` | `useAnswerable`: the state every answerable card shares |
13
+
14
+ The visuals are the `@surface` registry's `card-*` components, which take props only and
15
+ do not import this package. An app joins the two: see `web/src/cards` in Surface.
16
+
17
+ The server owns a card's state. The page never decides a card expired or closed; it draws
18
+ what the server recorded. In Surface the server side is `core/internal/cards`, reached by
19
+ modules through `Host.Cards()` and by the agent through `card_show`, `card_ask` and
20
+ `card_update`.
21
+
22
+ The engine, the outcome contract and the form subset are ported from `@hollis-labs/kit-cards`
23
+ (hollis-labs/frontend-support), with their tests.
24
+
25
+ Unpublished: Surface resolves it through an alias (`web/tsconfig.json`, `web/vite.config.ts`).
@@ -0,0 +1,38 @@
1
+ import type { CardInput, CardStatus, CardViewModel, EngineOptions, EngineSnapshot, EngineStore, Surface } from "./types.ts";
2
+ /**
3
+ * The surface/lifecycle engine: rules as data in, a store of card view-models out.
4
+ *
5
+ * THE FIVE RULES THIS FILE EXISTS TO KEEP
6
+ * 1. A toast never holds the only copy of an answerable card — it gets a durable
7
+ * `home` and the toast links to it.
8
+ * 2. Dedupe and supersede never reorder, and never steal focus mid-edit: while a
9
+ * card is `editing` the replacement is HELD, the old card shows
10
+ * `updatedAvailable`, and the swap waits for `applyPending`.
11
+ * 3. Expiry is DISPLAY only. `expired` is a server status applied via
12
+ * `applyServerState`; the engine never derives it from a clock.
13
+ * 4. Server state is authoritative: a lower revision for a known id is ignored.
14
+ * 5. Nothing here knows a wire kind, a transport or a component.
15
+ */
16
+ export interface CardEngine {
17
+ /** Add or update a card. Returns its view-model, or `null` when no rule matched. */
18
+ ingest(card: CardInput): CardViewModel | null;
19
+ /** Record what the server says. `supersededBy` links the replacement. */
20
+ applyServerState(id: string, status: CardStatus, extra?: {
21
+ supersededBy?: string;
22
+ revision?: number;
23
+ }): void;
24
+ /** The person started/stopped editing this card. Stopping does NOT apply a held swap. */
25
+ setEditing(id: string, editing: boolean): void;
26
+ /** Apply a held update/replacement for `id` (the person asked for it, or is idle). */
27
+ applyPending(id: string): void;
28
+ dismissToast(id: string): void;
29
+ /** Dismiss non-answerable toasts whose ttl has passed. Answerable cards are never touched. */
30
+ dismissExpiredToasts(): readonly string[];
31
+ /** Cards for a surface, in arrival order. Held replacements are not visible yet. */
32
+ select(surface: Surface): readonly CardViewModel[];
33
+ get(id: string): CardViewModel | undefined;
34
+ snapshot(): EngineSnapshot;
35
+ subscribe(listener: () => void): () => void;
36
+ }
37
+ export declare function memoryStore(initial?: EngineSnapshot): EngineStore;
38
+ export declare function createCardEngine(options: EngineOptions): CardEngine;
@@ -0,0 +1,275 @@
1
+ import { dedupeKeyFor, pickRule } from "./match.js";
2
+ function maxRev(a, b) {
3
+ if (a == null)
4
+ return b ?? null;
5
+ if (b == null)
6
+ return a;
7
+ return Math.max(a, b);
8
+ }
9
+ const EMPTY = { order: [], cards: {}, held: {} };
10
+ export function memoryStore(initial = EMPTY) {
11
+ let state = initial;
12
+ return {
13
+ get: () => state,
14
+ set: (next) => {
15
+ state = next;
16
+ },
17
+ };
18
+ }
19
+ function homeOf(rule, card) {
20
+ if (rule.escalateBlocking && card.blocking)
21
+ return "modal";
22
+ if (rule.surface !== "toast")
23
+ return rule.surface;
24
+ // A toast alone would be the only copy. Answerable cards live in the tray.
25
+ return "tray";
26
+ }
27
+ export function createCardEngine(options) {
28
+ const store = options.store ?? memoryStore();
29
+ const listeners = new Set();
30
+ const commit = (next) => {
31
+ store.set(next);
32
+ for (const l of listeners)
33
+ l();
34
+ };
35
+ function build(card, rule, prior) {
36
+ const actions = rule.actions ?? [];
37
+ const answerable = actions.length > 0;
38
+ const home = homeOf(rule, card);
39
+ const wantsToast = rule.surface === "toast";
40
+ const surfaces = wantsToast ? (answerable ? [home, "toast"] : ["toast"]) : [home];
41
+ return {
42
+ id: card.id,
43
+ kind: card.kind,
44
+ input: card,
45
+ ruleId: rule.id,
46
+ home,
47
+ surfaces,
48
+ answerable,
49
+ actions,
50
+ status: prior?.status ?? null,
51
+ supersededBy: prior?.supersededBy ?? null,
52
+ dedupeKey: dedupeKeyFor(rule, card),
53
+ expiresAt: card.expiresAt ?? (rule.ttlMs != null ? options.now() + rule.ttlMs : null),
54
+ editing: prior?.editing ?? false,
55
+ updatedAvailable: false,
56
+ toastDismissed: prior?.toastDismissed ?? false,
57
+ revisionFloor: maxRev(prior?.revisionFloor, card.revision),
58
+ };
59
+ }
60
+ /**
61
+ * Held same-id work is obsolete once the card has moved past its revision, by a newer
62
+ * ingest or by server state. Such work is discarded, never applied.
63
+ */
64
+ function obsolete(held, current) {
65
+ if (held?.mode !== "update")
66
+ return false;
67
+ const r = held.card.revision;
68
+ if (r == null)
69
+ return false;
70
+ return ((current.revisionFloor != null && r < current.revisionFloor) ||
71
+ (current.input.revision != null && r <= current.input.revision));
72
+ }
73
+ /** Remove obsolete held work for `id` from a snapshot about to be committed. */
74
+ function sweep(held, id, current) {
75
+ if (!obsolete(held[id], current))
76
+ return { held, card: current };
77
+ const rest = { ...held };
78
+ delete rest[id];
79
+ return { held: rest, card: { ...current, updatedAvailable: false } };
80
+ }
81
+ /** Hold work for `targetId`, never letting an older arrival replace a newer held one. */
82
+ function hold(snap, targetId, entry, target) {
83
+ const current = snap.held[targetId];
84
+ const r = entry.card.revision;
85
+ if (current &&
86
+ current.card.id === entry.card.id &&
87
+ r != null &&
88
+ current.card.revision != null &&
89
+ r <= current.card.revision) {
90
+ return target; // stale against what is already held
91
+ }
92
+ commit({
93
+ ...snap,
94
+ held: { ...snap.held, [targetId]: entry },
95
+ cards: {
96
+ ...snap.cards,
97
+ [targetId]: {
98
+ ...target,
99
+ updatedAvailable: true,
100
+ revisionFloor: entry.mode === "update" ? maxRev(target.revisionFloor, r) : target.revisionFloor,
101
+ },
102
+ },
103
+ });
104
+ return store.get().cards[targetId];
105
+ }
106
+ function ingest(card) {
107
+ const rule = pickRule(options.rules, card);
108
+ if (!rule)
109
+ return null;
110
+ const snap = store.get();
111
+ const existing = snap.cards[card.id];
112
+ // Same id: an update. Lower or equal revision is stale and ignored.
113
+ if (existing) {
114
+ if (card.revision != null && existing.revisionFloor != null && card.revision <= existing.revisionFloor) {
115
+ return existing;
116
+ }
117
+ if (existing.editing)
118
+ return hold(snap, card.id, { card, mode: "update" }, existing);
119
+ const built = build(card, rule, existing);
120
+ const swept = sweep(snap.held, card.id, built);
121
+ commit({ ...snap, held: swept.held, cards: { ...snap.cards, [card.id]: swept.card } });
122
+ return swept.card;
123
+ }
124
+ const next = build(card, rule);
125
+ // A different id with the same live dedupe key.
126
+ const twin = next.dedupeKey == null
127
+ ? undefined
128
+ : snap.order
129
+ .map((id) => snap.cards[id])
130
+ .find((c) => c.dedupeKey === next.dedupeKey && c.status == null && c.supersededBy == null);
131
+ if (twin) {
132
+ if (rule.supersedes === "dedupe-key") {
133
+ if (twin.editing) {
134
+ // HOLD the replacement: the old card stays live and tells the person.
135
+ return hold(snap, twin.id, { card, mode: "supersede" }, twin);
136
+ }
137
+ commit({
138
+ order: [...snap.order, next.id],
139
+ held: snap.held,
140
+ cards: {
141
+ ...snap.cards,
142
+ [twin.id]: { ...twin, status: "superseded", supersededBy: next.id },
143
+ [next.id]: next,
144
+ },
145
+ });
146
+ return next;
147
+ }
148
+ // Plain dedupe: fold into the existing card IN PLACE (no new row, no reorder).
149
+ if (twin.editing)
150
+ return hold(snap, twin.id, { card, mode: "dedupe" }, twin);
151
+ const merged = build({ ...card, id: twin.id }, rule, twin);
152
+ commit({ ...snap, cards: { ...snap.cards, [twin.id]: merged } });
153
+ return merged;
154
+ }
155
+ commit({ ...snap, order: [...snap.order, next.id], cards: { ...snap.cards, [next.id]: next } });
156
+ return next;
157
+ }
158
+ function applyServerState(id, status, extra) {
159
+ const snap = store.get();
160
+ const card = snap.cards[id];
161
+ if (!card)
162
+ return;
163
+ if (extra?.revision != null && card.revisionFloor != null && extra.revision < card.revisionFloor)
164
+ return;
165
+ const updated = {
166
+ ...card,
167
+ status,
168
+ supersededBy: extra?.supersededBy ?? card.supersededBy,
169
+ revisionFloor: maxRev(card.revisionFloor, extra?.revision),
170
+ };
171
+ const swept = sweep(snap.held, id, updated);
172
+ commit({ ...snap, held: swept.held, cards: { ...snap.cards, [id]: swept.card } });
173
+ }
174
+ function setEditing(id, editing) {
175
+ const snap = store.get();
176
+ const card = snap.cards[id];
177
+ if (!card || card.editing === editing)
178
+ return;
179
+ commit({ ...snap, cards: { ...snap.cards, [id]: { ...card, editing } } });
180
+ }
181
+ function applyPending(id) {
182
+ const snap = store.get();
183
+ const card = snap.cards[id];
184
+ const held = snap.held[id];
185
+ if (!card || !held)
186
+ return;
187
+ const rest = { ...snap.held };
188
+ delete rest[id];
189
+ const rule = pickRule(options.rules, held.card);
190
+ if (!rule) {
191
+ commit({ ...snap, held: rest, cards: { ...snap.cards, [id]: { ...card, updatedAvailable: false } } });
192
+ return;
193
+ }
194
+ const idle = { ...card, editing: false };
195
+ if (obsolete(held, card)) {
196
+ // The card moved past this work while it waited; applying it would roll the card back.
197
+ commit({
198
+ ...snap,
199
+ held: rest,
200
+ cards: { ...snap.cards, [id]: { ...idle, editing: card.editing, updatedAvailable: false } },
201
+ });
202
+ return;
203
+ }
204
+ if (held.mode === "update") {
205
+ commit({ ...snap, held: rest, cards: { ...snap.cards, [id]: build(held.card, rule, idle) } });
206
+ return;
207
+ }
208
+ if (held.mode === "dedupe") {
209
+ // Plain dedupe stays plain: fold into the existing card in place, never supersede.
210
+ commit({ ...snap, held: rest, cards: { ...snap.cards, [id]: build({ ...held.card, id }, rule, idle) } });
211
+ return;
212
+ }
213
+ // A held replacement under a different id: supersede now, append the new card.
214
+ const next = build(held.card, rule);
215
+ commit({
216
+ order: [...snap.order, next.id],
217
+ held: rest,
218
+ cards: {
219
+ ...snap.cards,
220
+ [id]: { ...idle, status: "superseded", supersededBy: next.id, updatedAvailable: false },
221
+ [next.id]: next,
222
+ },
223
+ });
224
+ }
225
+ function dismissToast(id) {
226
+ const snap = store.get();
227
+ const card = snap.cards[id];
228
+ if (!card || card.toastDismissed)
229
+ return;
230
+ commit({ ...snap, cards: { ...snap.cards, [id]: { ...card, toastDismissed: true } } });
231
+ }
232
+ function dismissExpiredToasts() {
233
+ const now = options.now();
234
+ const due = store.get().order.filter((id) => {
235
+ const c = store.get().cards[id];
236
+ return (c &&
237
+ !c.answerable &&
238
+ c.surfaces.includes("toast") &&
239
+ !c.toastDismissed &&
240
+ c.expiresAt != null &&
241
+ c.expiresAt <= now);
242
+ });
243
+ if (due.length === 0)
244
+ return due;
245
+ const snap = store.get();
246
+ const cards = { ...snap.cards };
247
+ for (const id of due)
248
+ cards[id] = { ...cards[id], toastDismissed: true };
249
+ commit({ ...snap, cards });
250
+ return due;
251
+ }
252
+ function select(surface) {
253
+ const snap = store.get();
254
+ return snap.order
255
+ .map((id) => snap.cards[id])
256
+ .filter((c) => c.surfaces.includes(surface) && (surface !== "toast" || !c.toastDismissed));
257
+ }
258
+ return {
259
+ ingest,
260
+ applyServerState,
261
+ setEditing,
262
+ applyPending,
263
+ dismissToast,
264
+ dismissExpiredToasts,
265
+ select,
266
+ get: (id) => store.get().cards[id],
267
+ snapshot: () => store.get(),
268
+ subscribe(listener) {
269
+ listeners.add(listener);
270
+ return () => {
271
+ listeners.delete(listener);
272
+ };
273
+ },
274
+ };
275
+ }
@@ -0,0 +1,13 @@
1
+ import type { CardViewModel } from "./types.ts";
2
+ export interface ExpiryDisplay {
3
+ /** Absolute expiry, ms since epoch. Always what is shown first. */
4
+ readonly at: number;
5
+ /** Whole seconds left, ONLY inside the final minute; null before that. */
6
+ readonly countdownSeconds: number | null;
7
+ }
8
+ /**
9
+ * How to DISPLAY an expiry. This never changes a card's state: `expired` arrives from
10
+ * the server like any other terminal status. A client that flipped a card to expired
11
+ * from its own clock would draw a ghost card against a server still accepting answers.
12
+ */
13
+ export declare function describeExpiry(card: Pick<CardViewModel, "expiresAt">, now: number): ExpiryDisplay | null;
@@ -0,0 +1,11 @@
1
+ /**
2
+ * How to DISPLAY an expiry. This never changes a card's state: `expired` arrives from
3
+ * the server like any other terminal status. A client that flipped a card to expired
4
+ * from its own clock would draw a ghost card against a server still accepting answers.
5
+ */
6
+ export function describeExpiry(card, now) {
7
+ if (card.expiresAt == null)
8
+ return null;
9
+ const left = card.expiresAt - now;
10
+ return { at: card.expiresAt, countdownSeconds: left > 0 && left <= 60_000 ? Math.ceil(left / 1000) : null };
11
+ }
@@ -0,0 +1,6 @@
1
+ export type { CardEngine } from "./engine.ts";
2
+ export { createCardEngine, memoryStore } from "./engine.ts";
3
+ export type { ExpiryDisplay } from "./expiry.ts";
4
+ export { describeExpiry } from "./expiry.ts";
5
+ export { dedupeKeyFor, matches, pickRule } from "./match.ts";
6
+ export type { CardInput, CardRule, CardStatus, CardViewModel, EngineOptions, EngineSnapshot, EngineStore, HeldEntry, MatchValue, RuleAction, RuleMatch, Surface, } from "./types.ts";
@@ -0,0 +1,3 @@
1
+ export { createCardEngine, memoryStore } from "./engine.js";
2
+ export { describeExpiry } from "./expiry.js";
3
+ export { dedupeKeyFor, matches, pickRule } from "./match.js";
@@ -0,0 +1,4 @@
1
+ import type { CardInput, CardRule, RuleMatch } from "./types.ts";
2
+ export declare function matches(match: RuleMatch, card: CardInput): boolean;
3
+ export declare function pickRule(rules: readonly CardRule[], card: CardInput): CardRule | null;
4
+ export declare function dedupeKeyFor(rule: CardRule, card: CardInput): string | null;
@@ -0,0 +1,22 @@
1
+ function fits(pattern, actual) {
2
+ if (pattern === undefined)
3
+ return true;
4
+ if (actual === undefined)
5
+ return false;
6
+ const list = typeof pattern === "string" ? [pattern] : pattern;
7
+ return list.some((p) => (p.endsWith("*") ? actual.startsWith(p.slice(0, -1)) : p === actual));
8
+ }
9
+ export function matches(match, card) {
10
+ return (fits(match.kind, card.kind) &&
11
+ fits(match.source, card.source) &&
12
+ fits(match.risk, card.risk) &&
13
+ (match.blocking === undefined || match.blocking === (card.blocking === true)));
14
+ }
15
+ export function pickRule(rules, card) {
16
+ return rules.find((r) => matches(r.match, card)) ?? null;
17
+ }
18
+ export function dedupeKeyFor(rule, card) {
19
+ if (!rule.dedupeBy || rule.dedupeBy.length === 0)
20
+ return null;
21
+ return rule.dedupeBy.map((f) => card[f] ?? "").join(":");
22
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * The lifecycle engine's vocabulary. Headless: no React, no DOM, no timers, no
3
+ * transport, and NO WIRE KINDS — `kind` is an opaque string the host chose, and the
4
+ * engine only compares it. Everything that varies by app is rule DATA.
5
+ */
6
+ export type Surface = "inline" | "tray" | "toast" | "modal";
7
+ /** What the host knows about a card when it arrives. `payload` is opaque to the engine. */
8
+ export interface CardInput {
9
+ readonly id: string;
10
+ readonly kind: string;
11
+ readonly source?: string;
12
+ /** What the card is about (an operation, a run). Used for dedupe, never interpreted. */
13
+ readonly subject?: string;
14
+ readonly risk?: string;
15
+ /** The sender is waiting on the answer. Blocking cards may escalate to a modal. */
16
+ readonly blocking?: boolean;
17
+ /** Server revision. A lower revision for a known id is ignored, never applied. */
18
+ readonly revision?: number;
19
+ /** Absolute expiry from the server, ms since epoch. Wins over a rule `ttlMs`. */
20
+ readonly expiresAt?: number;
21
+ readonly payload?: unknown;
22
+ }
23
+ /** Equality, list membership, or a trailing-`*` prefix, per field. All given fields must match. */
24
+ export type MatchValue = string | readonly string[];
25
+ export interface RuleMatch {
26
+ readonly kind?: MatchValue;
27
+ readonly source?: MatchValue;
28
+ readonly risk?: MatchValue;
29
+ readonly blocking?: boolean;
30
+ }
31
+ export interface RuleAction {
32
+ readonly id: string;
33
+ readonly label: string;
34
+ readonly tone?: "danger" | "neutral";
35
+ }
36
+ /**
37
+ * A rule, as data. The first rule whose `match` fits wins; a card no rule matches is
38
+ * not ingested (the host gets `null` and decides what to do — nothing is dropped
39
+ * silently inside the engine).
40
+ */
41
+ export interface CardRule {
42
+ readonly id: string;
43
+ readonly match: RuleMatch;
44
+ readonly surface: Surface;
45
+ /** Card fields joined with `:` form the dedupe key. Absent fields join as empty. */
46
+ readonly dedupeBy?: readonly ("kind" | "source" | "subject" | "risk")[];
47
+ /**
48
+ * `dedupe-key`: a newer card with the same key supersedes the older one (the older
49
+ * becomes `superseded`, linked to the newer). Without it a same-key card UPDATES the
50
+ * existing one in place.
51
+ */
52
+ readonly supersedes?: "dedupe-key";
53
+ /** Lifetime from arrival, ms. Display only for answerable cards — see `expiry.ts`. */
54
+ readonly ttlMs?: number;
55
+ /** Presence of actions is what makes a card answerable. */
56
+ readonly actions?: readonly RuleAction[];
57
+ /** A blocking card escalates to a modal when true. Default: stays on `surface`. */
58
+ readonly escalateBlocking?: boolean;
59
+ }
60
+ /** Server-recorded status. Opaque string, like `classifyPriorResponse` takes. */
61
+ export type CardStatus = string;
62
+ export interface CardViewModel {
63
+ readonly id: string;
64
+ readonly kind: string;
65
+ readonly input: CardInput;
66
+ readonly ruleId: string;
67
+ /** Where the card LIVES. Answerable cards always live somewhere durable (tray/inline/modal). */
68
+ readonly home: Exclude<Surface, "toast">;
69
+ /** Every surface showing it. A toast here always links to `home`. */
70
+ readonly surfaces: readonly Surface[];
71
+ readonly answerable: boolean;
72
+ readonly actions: readonly RuleAction[];
73
+ readonly status: CardStatus | null;
74
+ readonly supersededBy: string | null;
75
+ readonly dedupeKey: string | null;
76
+ /** Absolute ms since epoch, or null. Never turned into a state by the engine. */
77
+ readonly expiresAt: number | null;
78
+ readonly editing: boolean;
79
+ /** A swap/update is waiting because the person is editing; show an "updated" affordance. */
80
+ readonly updatedAvailable: boolean;
81
+ readonly toastDismissed: boolean;
82
+ /**
83
+ * Highest revision accepted for this card from ANY entry point (ingest, a held arrival,
84
+ * or server state). Anything at or below it is stale and rejected.
85
+ */
86
+ readonly revisionFloor: number | null;
87
+ }
88
+ /** Work waiting because its target card is being edited, with the policy it matched. */
89
+ export interface HeldEntry {
90
+ readonly card: CardInput;
91
+ /** `update`: same id. `supersede`/`dedupe`: a new id that matched a dedupe key. */
92
+ readonly mode: "update" | "supersede" | "dedupe";
93
+ }
94
+ export interface EngineSnapshot {
95
+ /** Arrival order, stable: updates and supersession never reorder. */
96
+ readonly order: readonly string[];
97
+ readonly cards: Readonly<Record<string, CardViewModel>>;
98
+ /** Held replacements keyed by the id they will replace. */
99
+ readonly held: Readonly<Record<string, HeldEntry>>;
100
+ }
101
+ /** The host owns persistence. The default store is memory. */
102
+ export interface EngineStore {
103
+ get(): EngineSnapshot;
104
+ set(next: EngineSnapshot): void;
105
+ }
106
+ export interface EngineOptions {
107
+ readonly rules: readonly CardRule[];
108
+ /** The host's clock, ms since epoch. The engine never reads `Date`. */
109
+ readonly now: () => number;
110
+ readonly store?: EngineStore;
111
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * The lifecycle engine's vocabulary. Headless: no React, no DOM, no timers, no
3
+ * transport, and NO WIRE KINDS — `kind` is an opaque string the host chose, and the
4
+ * engine only compares it. Everything that varies by app is rule DATA.
5
+ */
6
+ export {};
package/dist/form.d.ts ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The JSON-Schema SUBSET a form card understands, and the compile step that reads it.
3
+ *
4
+ * REUSE CHECK. `kit-settings` already has a schema reader (`inspectSettingsGroup`),
5
+ * but it is private to that package, flat-only, and fused to a stored-model
6
+ * dirty/save engine; a form card is one-shot and ephemeral. Wrapping it would couple
7
+ * two lifecycles. So this is its own small layer, deliberately shaped like the
8
+ * settings one (same keyword vocabulary, `writeOnly` for secrets) so a later
9
+ * downward extraction into a shared package is mechanical. That extraction is a
10
+ * recorded follow-up, not done here.
11
+ *
12
+ * SUPPORTED: an object schema with `properties` / `required`; per property `type`
13
+ * (string | number | integer | boolean | array-of-enum), `title`, `description`,
14
+ * `default`, `enum`, `minimum`, `maximum`, `minLength`, `maxLength`, `pattern`,
15
+ * `format` (`date`, `textarea`, `secret`), `writeOnly`, `readOnly`, `items.enum`.
16
+ *
17
+ * NOT SUPPORTED: `$ref`, `oneOf`/`anyOf`/`allOf`, `if`/`then`, nested objects,
18
+ * `additionalProperties` schemas, anything else. A property with an unsupported
19
+ * keyword is NEVER silently dropped or half-rendered: it compiles to a `fallback`
20
+ * field — a visible text box taking raw JSON — carrying the keyword names so the
21
+ * card can say what it could not honour.
22
+ *
23
+ * SECRET is reserved: `format: 'secret'` or `writeOnly: true` on a string. The card
24
+ * masks it, never echoes it, and delivers it to the host by reference only.
25
+ */
26
+ export type FormFieldKind = "text" | "textarea" | "number" | "integer" | "boolean" | "enum" | "multi" | "date" | "secret" | "fallback";
27
+ export interface FormField {
28
+ readonly key: string;
29
+ readonly kind: FormFieldKind;
30
+ readonly title: string;
31
+ readonly description?: string;
32
+ readonly required: boolean;
33
+ readonly readOnly: boolean;
34
+ /** Sensitive fields are redacted from receipts and logs. Secrets always are. */
35
+ readonly sensitive: boolean;
36
+ readonly options?: readonly (string | number)[];
37
+ readonly default?: unknown;
38
+ readonly minimum?: number;
39
+ readonly maximum?: number;
40
+ readonly minLength?: number;
41
+ readonly maxLength?: number;
42
+ readonly pattern?: string;
43
+ /** Keywords present on the property that this subset does not honour. */
44
+ readonly unsupported: readonly string[];
45
+ /** A declaration that cannot be honoured safely. Non-empty makes the form unsubmittable. */
46
+ readonly problem?: string;
47
+ }
48
+ export interface CompiledForm {
49
+ readonly fields: readonly FormField[];
50
+ /** Schema-level problems. Non-empty means the form must not be submittable. */
51
+ readonly issues: readonly string[];
52
+ }
53
+ export declare function compileFormSchema(schema: unknown): CompiledForm;
54
+ export type FormValues = Readonly<Record<string, unknown>>;
55
+ export type FormErrors = Readonly<Record<string, string>>;
56
+ /** Validate a field's current value. Returns an error sentence or null. */
57
+ export declare function validateField(field: FormField, value: unknown): string | null;
58
+ export declare function validateForm(fields: readonly FormField[], values: FormValues): FormErrors;
59
+ /** Coerce raw control values into the typed answer. Fallback fields parse as JSON when they can. */
60
+ export declare function coerceValue(field: FormField, value: unknown): unknown;
package/dist/form.js ADDED
@@ -0,0 +1,257 @@
1
+ /**
2
+ * The JSON-Schema SUBSET a form card understands, and the compile step that reads it.
3
+ *
4
+ * REUSE CHECK. `kit-settings` already has a schema reader (`inspectSettingsGroup`),
5
+ * but it is private to that package, flat-only, and fused to a stored-model
6
+ * dirty/save engine; a form card is one-shot and ephemeral. Wrapping it would couple
7
+ * two lifecycles. So this is its own small layer, deliberately shaped like the
8
+ * settings one (same keyword vocabulary, `writeOnly` for secrets) so a later
9
+ * downward extraction into a shared package is mechanical. That extraction is a
10
+ * recorded follow-up, not done here.
11
+ *
12
+ * SUPPORTED: an object schema with `properties` / `required`; per property `type`
13
+ * (string | number | integer | boolean | array-of-enum), `title`, `description`,
14
+ * `default`, `enum`, `minimum`, `maximum`, `minLength`, `maxLength`, `pattern`,
15
+ * `format` (`date`, `textarea`, `secret`), `writeOnly`, `readOnly`, `items.enum`.
16
+ *
17
+ * NOT SUPPORTED: `$ref`, `oneOf`/`anyOf`/`allOf`, `if`/`then`, nested objects,
18
+ * `additionalProperties` schemas, anything else. A property with an unsupported
19
+ * keyword is NEVER silently dropped or half-rendered: it compiles to a `fallback`
20
+ * field — a visible text box taking raw JSON — carrying the keyword names so the
21
+ * card can say what it could not honour.
22
+ *
23
+ * SECRET is reserved: `format: 'secret'` or `writeOnly: true` on a string. The card
24
+ * masks it, never echoes it, and delivers it to the host by reference only.
25
+ */
26
+ const KNOWN = new Set([
27
+ "type",
28
+ "title",
29
+ "description",
30
+ "default",
31
+ "enum",
32
+ "minimum",
33
+ "maximum",
34
+ "minLength",
35
+ "maxLength",
36
+ "pattern",
37
+ "format",
38
+ "writeOnly",
39
+ "readOnly",
40
+ "items",
41
+ "examples",
42
+ "$comment",
43
+ ]);
44
+ const TOP_KNOWN = new Set([
45
+ "$schema",
46
+ "$id",
47
+ "$comment",
48
+ "type",
49
+ "title",
50
+ "description",
51
+ "properties",
52
+ "required",
53
+ "additionalProperties",
54
+ ]);
55
+ const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
56
+ const isScalarList = (v) => Array.isArray(v) && v.length > 0 && v.every((x) => typeof x === "string" || typeof x === "number");
57
+ function compileProperty(key, raw, required) {
58
+ const base = { key, required, readOnly: false, sensitive: false, unsupported: [] };
59
+ if (!isRecord(raw)) {
60
+ return { ...base, kind: "fallback", title: key, unsupported: ["schema"] };
61
+ }
62
+ const unsupported = Object.keys(raw).filter((k) => !KNOWN.has(k));
63
+ const title = typeof raw.title === "string" && raw.title ? raw.title : key;
64
+ const common = {
65
+ key,
66
+ title,
67
+ description: typeof raw.description === "string" ? raw.description : undefined,
68
+ required,
69
+ readOnly: raw.readOnly === true,
70
+ sensitive: raw.writeOnly === true || raw.format === "secret",
71
+ default: raw.default,
72
+ minimum: typeof raw.minimum === "number" ? raw.minimum : undefined,
73
+ maximum: typeof raw.maximum === "number" ? raw.maximum : undefined,
74
+ minLength: typeof raw.minLength === "number" ? raw.minLength : undefined,
75
+ maxLength: typeof raw.maxLength === "number" ? raw.maxLength : undefined,
76
+ pattern: typeof raw.pattern === "string" ? raw.pattern : undefined,
77
+ unsupported,
78
+ };
79
+ const fallback = (extra = []) => ({
80
+ ...common,
81
+ kind: "fallback",
82
+ unsupported: [...unsupported, ...extra],
83
+ });
84
+ // SECRET FIRST, BEFORE ANY OTHER SHAPE. A secret declaration must stay masked and go by
85
+ // reference whatever else the property says; letting `enum` or an unsupported keyword win
86
+ // would render an unmasked control and send the value as ordinary data. It stays a
87
+ // `secret` field; a combination that cannot be honoured is a form-level problem
88
+ // (fail closed), never a quieter field kind.
89
+ if (common.sensitive) {
90
+ const problems = [];
91
+ if (raw.type !== "string")
92
+ problems.push("a secret must be a string");
93
+ if (unsupported.length > 0)
94
+ problems.push(`unsupported keyword(s) ${unsupported.join(", ")}`);
95
+ return {
96
+ ...common,
97
+ kind: "secret",
98
+ sensitive: true,
99
+ ...(problems.length ? { problem: `Field "${key}" is declared secret but ${problems.join(" and ")}.` } : {}),
100
+ };
101
+ }
102
+ if (unsupported.length > 0)
103
+ return fallback();
104
+ switch (raw.type) {
105
+ case "string": {
106
+ if (raw.enum !== undefined) {
107
+ return isScalarList(raw.enum) ? { ...common, kind: "enum", options: raw.enum } : fallback(["enum"]);
108
+ }
109
+ if (raw.format === "secret" || raw.writeOnly === true)
110
+ return { ...common, kind: "secret", sensitive: true };
111
+ if (raw.format === "date")
112
+ return { ...common, kind: "date" };
113
+ if (raw.format === "textarea")
114
+ return { ...common, kind: "textarea" };
115
+ if (raw.format !== undefined)
116
+ return fallback([`format:${String(raw.format)}`]);
117
+ return { ...common, kind: "text" };
118
+ }
119
+ case "number":
120
+ case "integer":
121
+ if (raw.enum !== undefined)
122
+ return isScalarList(raw.enum) ? { ...common, kind: "enum", options: raw.enum } : fallback(["enum"]);
123
+ return { ...common, kind: raw.type };
124
+ case "boolean":
125
+ return { ...common, kind: "boolean" };
126
+ case "array": {
127
+ const items = raw.items;
128
+ if (isRecord(items) &&
129
+ isScalarList(items.enum) &&
130
+ Object.keys(items).every((k) => k === "type" || k === "enum")) {
131
+ return { ...common, kind: "multi", options: items.enum };
132
+ }
133
+ return fallback(["items"]);
134
+ }
135
+ default:
136
+ return fallback(["type"]);
137
+ }
138
+ }
139
+ export function compileFormSchema(schema) {
140
+ if (!isRecord(schema) || schema.type !== "object" || !isRecord(schema.properties)) {
141
+ return { fields: [], issues: ["Unsupported form schema: expected an object schema with properties."] };
142
+ }
143
+ const issues = [];
144
+ const extra = Object.keys(schema).filter((k) => !TOP_KNOWN.has(k));
145
+ if (extra.length)
146
+ issues.push(`Unsupported schema keyword(s) at the top level: ${extra.join(", ")}.`);
147
+ const requiredList = Array.isArray(schema.required)
148
+ ? schema.required.filter((k) => typeof k === "string")
149
+ : [];
150
+ const keys = Object.keys(schema.properties);
151
+ for (const r of requiredList)
152
+ if (!keys.includes(r))
153
+ issues.push(`Required field "${r}" has no property.`);
154
+ const fields = keys.map((key) => compileProperty(key, schema.properties[key], requiredList.includes(key)));
155
+ for (const f of fields)
156
+ if (f.problem)
157
+ issues.push(f.problem);
158
+ return { fields, issues };
159
+ }
160
+ const isEmpty = (v) => v === undefined || v === null || v === "" || (Array.isArray(v) && v.length === 0);
161
+ /** Validate a field's current value. Returns an error sentence or null. */
162
+ export function validateField(field, value) {
163
+ if (field.kind === "boolean")
164
+ return null;
165
+ if (isEmpty(value))
166
+ return field.required ? `${field.title} is required.` : null;
167
+ switch (field.kind) {
168
+ case "text":
169
+ case "textarea":
170
+ case "secret":
171
+ case "date": {
172
+ const s = String(value);
173
+ if (field.minLength != null && s.length < field.minLength)
174
+ return `${field.title} must be at least ${field.minLength} characters.`;
175
+ if (field.maxLength != null && s.length > field.maxLength)
176
+ return `${field.title} must be at most ${field.maxLength} characters.`;
177
+ if (field.pattern) {
178
+ try {
179
+ if (!new RegExp(field.pattern).test(s))
180
+ return `${field.title} is not in the expected format.`;
181
+ }
182
+ catch {
183
+ return `${field.title} has a pattern this form cannot check.`;
184
+ }
185
+ }
186
+ if (field.kind === "date" && !/^\d{4}-\d{2}-\d{2}$/.test(s))
187
+ return `${field.title} must be a date (YYYY-MM-DD).`;
188
+ return null;
189
+ }
190
+ case "number":
191
+ case "integer": {
192
+ const n = typeof value === "number" ? value : Number(value);
193
+ if (!Number.isFinite(n))
194
+ return `${field.title} must be a number.`;
195
+ if (field.kind === "integer" && !Number.isInteger(n))
196
+ return `${field.title} must be a whole number.`;
197
+ if (field.minimum != null && n < field.minimum)
198
+ return `${field.title} must be at least ${field.minimum}.`;
199
+ if (field.maximum != null && n > field.maximum)
200
+ return `${field.title} must be at most ${field.maximum}.`;
201
+ return null;
202
+ }
203
+ case "enum":
204
+ return field.options?.some((o) => String(o) === String(value))
205
+ ? null
206
+ : `${field.title} must be one of the listed options.`;
207
+ case "multi":
208
+ return Array.isArray(value) && value.every((v) => field.options?.some((o) => String(o) === String(v)))
209
+ ? null
210
+ : `${field.title} has an option that is not listed.`;
211
+ case "fallback":
212
+ if (typeof value !== "string")
213
+ return null;
214
+ try {
215
+ JSON.parse(value);
216
+ return null;
217
+ }
218
+ catch {
219
+ return null; // plain text is an accepted fallback answer
220
+ }
221
+ }
222
+ }
223
+ export function validateForm(fields, values) {
224
+ const errors = {};
225
+ for (const f of fields) {
226
+ if (f.readOnly)
227
+ continue;
228
+ const e = validateField(f, values[f.key]);
229
+ if (e)
230
+ errors[f.key] = e;
231
+ }
232
+ return errors;
233
+ }
234
+ /** Coerce raw control values into the typed answer. Fallback fields parse as JSON when they can. */
235
+ export function coerceValue(field, value) {
236
+ if (isEmpty(value) && field.kind !== "boolean")
237
+ return undefined;
238
+ switch (field.kind) {
239
+ case "number":
240
+ case "integer":
241
+ return typeof value === "number" ? value : Number(value);
242
+ case "boolean":
243
+ return value === true;
244
+ case "fallback":
245
+ if (typeof value === "string") {
246
+ try {
247
+ return JSON.parse(value);
248
+ }
249
+ catch {
250
+ return value;
251
+ }
252
+ }
253
+ return value;
254
+ default:
255
+ return value;
256
+ }
257
+ }
@@ -0,0 +1,10 @@
1
+ export type { CardEngine, CardInput, CardRule, CardViewModel, EngineSnapshot, EngineStore, ExpiryDisplay, RuleAction, RuleMatch, Surface, } from "./engine/index.ts";
2
+ export { createCardEngine, describeExpiry, memoryStore } from "./engine/index.ts";
3
+ export type { CompiledForm, FormErrors, FormField, FormFieldKind, FormValues } from "./form.ts";
4
+ export { coerceValue, compileFormSchema, validateField, validateForm } from "./form.ts";
5
+ export type { AnswerableInput, AnswerableState } from "./react.ts";
6
+ export { useAnswerable } from "./react.ts";
7
+ export type { CardMiss, CardRegistry, CardResolution } from "./registry.ts";
8
+ export { createCardRegistry } from "./registry.ts";
9
+ export type { CardAnswer, CardDecision, CardOutcome, CardResponder, PriorResponseState } from "./response.ts";
10
+ export { acceptsInput, classifyPriorResponse } from "./response.ts";
package/dist/index.js ADDED
@@ -0,0 +1,5 @@
1
+ export { createCardEngine, describeExpiry, memoryStore } from "./engine/index.js";
2
+ export { coerceValue, compileFormSchema, validateField, validateForm } from "./form.js";
3
+ export { useAnswerable } from "./react.js";
4
+ export { createCardRegistry } from "./registry.js";
5
+ export { acceptsInput, classifyPriorResponse } from "./response.js";
@@ -0,0 +1,23 @@
1
+ import { type PriorResponseState } from "./response.ts";
2
+ export interface AnswerableInput {
3
+ /** Whatever the server last recorded for the card, verbatim. */
4
+ readonly status?: string | null;
5
+ /** The host is mid-submit. */
6
+ readonly busy?: boolean;
7
+ /** The host got a 409: the card changed under the person. Their input is kept. */
8
+ readonly stale?: boolean;
9
+ }
10
+ export interface AnswerableState {
11
+ readonly state: PriorResponseState;
12
+ /** The card is open and nothing blocks it from being answered. */
13
+ readonly live: boolean;
14
+ /** Controls should be disabled: not live, stale, or a submit is running. */
15
+ readonly disabled: boolean;
16
+ readonly busy: boolean;
17
+ /** The card was open in this mount and is now closed: the person, or the server, just
18
+ * resolved it. A card that mounts closed never sets this, so a reload does not steal focus. */
19
+ readonly transitioned: boolean;
20
+ /** Runs a responder with the busy flag set around it. */
21
+ readonly run: (fn: () => void | Promise<void>) => Promise<void>;
22
+ }
23
+ export declare function useAnswerable({ status, busy: hostBusy, stale }: AnswerableInput): AnswerableState;
package/dist/react.js ADDED
@@ -0,0 +1,25 @@
1
+ /** The one React piece: the state every answerable card shares. No markup. */
2
+ import { useState } from "react";
3
+ import { acceptsInput, classifyPriorResponse } from "./response.js";
4
+ export function useAnswerable({ status, busy: hostBusy, stale }) {
5
+ const state = classifyPriorResponse(status);
6
+ const [localBusy, setLocalBusy] = useState(false);
7
+ const busy = localBusy || hostBusy === true;
8
+ const live = acceptsInput(state);
9
+ const [wasLive, setWasLive] = useState(live);
10
+ if (live && !wasLive)
11
+ setWasLive(true);
12
+ const disabled = !live || busy || stale === true;
13
+ async function run(fn) {
14
+ if (disabled)
15
+ return;
16
+ setLocalBusy(true);
17
+ try {
18
+ await fn();
19
+ }
20
+ finally {
21
+ setLocalBusy(false);
22
+ }
23
+ }
24
+ return { state, live, disabled, busy, transitioned: wasLive && !live, run };
25
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * The table of renderers: which component draws a card of a kind at a version. It is an
3
+ * instance an app creates, not module state, and it is generic over the component type so
4
+ * nothing here knows React. An unknown kind or version resolves to a miss the app draws
5
+ * plainly; a card is never drawn blank.
6
+ */
7
+ export type CardMiss = {
8
+ readonly code: "unknown-kind";
9
+ readonly kind: string;
10
+ readonly version: string;
11
+ } | {
12
+ readonly code: "version-skew";
13
+ readonly kind: string;
14
+ readonly version: string;
15
+ readonly known: readonly string[];
16
+ };
17
+ export type CardResolution<C> = {
18
+ readonly ok: true;
19
+ readonly component: C;
20
+ readonly version: string;
21
+ } | {
22
+ readonly ok: false;
23
+ readonly miss: CardMiss;
24
+ };
25
+ export interface CardRegistry<C> {
26
+ /** Registers a renderer. The same kind and version twice throws: order never decides. */
27
+ register(kind: string, version: string, component: C): void;
28
+ resolve(kind: string, version?: string): CardResolution<C>;
29
+ kinds(): readonly string[];
30
+ }
31
+ export declare function createCardRegistry<C>(): CardRegistry<C>;
@@ -0,0 +1,23 @@
1
+ export function createCardRegistry() {
2
+ const table = new Map();
3
+ return {
4
+ register(kind, version, component) {
5
+ const versions = table.get(kind) ?? new Map();
6
+ if (versions.has(version))
7
+ throw new Error(`cards: ${kind}@${version} is registered twice`);
8
+ versions.set(version, component);
9
+ table.set(kind, versions);
10
+ },
11
+ resolve(kind, version = "1") {
12
+ const versions = table.get(kind);
13
+ if (!versions)
14
+ return { ok: false, miss: { code: "unknown-kind", kind, version } };
15
+ const component = versions.get(version);
16
+ if (component === undefined) {
17
+ return { ok: false, miss: { code: "version-skew", kind, version, known: [...versions.keys()] } };
18
+ }
19
+ return { ok: true, component, version };
20
+ },
21
+ kinds: () => [...table.keys()],
22
+ };
23
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * How a card says what the person decided, and how it reads back what was decided before.
3
+ *
4
+ * The two directions are treated differently on purpose. What a card EMITS is a closed
5
+ * union: answered or declined. There is no "partial": a half answer that claims the card
6
+ * leaves it in a state nothing can complete. What a card READS is an open string, because
7
+ * the server's recorded status is whatever the server says, including values this build
8
+ * has never heard of; `classifyPriorResponse` is total over it, and an unknown value is
9
+ * drawn honestly and stays locked rather than re-opening the card.
10
+ *
11
+ * A card never builds the wire response. It reports an outcome; the host adds the card's
12
+ * id and sends it.
13
+ *
14
+ * Ported from @hollis-labs/kit-cards (hollis-labs/frontend-support), with the logic kept
15
+ * and the styling left behind.
16
+ */
17
+ /** One answer to one question. Mirrors the wire's `answers[]` element. */
18
+ export interface CardAnswer {
19
+ readonly questionId: string;
20
+ readonly value: unknown;
21
+ /** The person took a suggestion as offered rather than composing their own. */
22
+ readonly acceptedSuggestion?: boolean;
23
+ readonly note?: string;
24
+ }
25
+ /** One decision about one item. Mirrors the wire's `decisions[]` element. */
26
+ export interface CardDecision {
27
+ readonly itemId: string;
28
+ /** Domain vocabulary — `approve`, `skip`, `retry`. The card does not interpret it. */
29
+ readonly action: string;
30
+ readonly note?: string;
31
+ }
32
+ /**
33
+ * What a card reports when the person is done with it.
34
+ *
35
+ * THREE SEPARATED CHANNELS, kept from the wire's own shape because the separation is
36
+ * the good part: free-form `data`, question/answer pairs, and per-item decisions are
37
+ * genuinely different things, and collapsing them into one bag is what made the
38
+ * previous generation of envelope payloads unreadable.
39
+ *
40
+ * `error` IS NOT HERE EITHER, and for a different reason than `partial`. The wire has
41
+ * an `error` status, but it describes a HANDLER that failed — the server's account of
42
+ * itself. A card is the person's side of the exchange, and the two things a person
43
+ * can do are answer and decline.
44
+ */
45
+ export type CardOutcome = {
46
+ readonly status: "submitted";
47
+ readonly data?: Readonly<Record<string, unknown>>;
48
+ readonly answers?: readonly CardAnswer[];
49
+ readonly decisions?: readonly CardDecision[];
50
+ } | {
51
+ readonly status: "canceled";
52
+ };
53
+ /**
54
+ * The seam. A host adds `v`, the envelope id and transport; the card supplies only
55
+ * what happened.
56
+ *
57
+ * Returning a promise is optional and a card must not depend on it resolving — a
58
+ * host that fires and forgets is a legitimate host. Cards drive their own busy state
59
+ * from props, not from awaiting this.
60
+ */
61
+ export type CardResponder = (outcome: CardOutcome) => void | Promise<void>;
62
+ /**
63
+ * What a card should draw, given whatever the wire recorded last.
64
+ *
65
+ * `open` COVERS BOTH "NOTHING YET" AND "A PARTIAL", which is the one place this
66
+ * classification encodes protocol rather than reporting it — and it is the protocol's
67
+ * own rule. `ResponseStatus.IsTerminal()` shipped in go-envelopes precisely so a
68
+ * non-terminal status does not claim the envelope: a `partial` is replaced by the
69
+ * next submission, so a card that finds one is still open for business. Deriving that
70
+ * from the protocol beats each host reinventing it, which is what the function exists
71
+ * for.
72
+ */
73
+ export type PriorResponseState = {
74
+ readonly kind: "open";
75
+ }
76
+ /** Claimed, handler still running. Controls should be disabled, not hidden. */
77
+ | {
78
+ readonly kind: "pending";
79
+ } | {
80
+ readonly kind: "submitted";
81
+ } | {
82
+ readonly kind: "canceled";
83
+ }
84
+ /** The server says the ask lapsed. Terminal; the client never infers this from a clock. */
85
+ | {
86
+ readonly kind: "expired";
87
+ }
88
+ /** Replaced by a newer card. Terminal; the host may link the replacement. */
89
+ | {
90
+ readonly kind: "superseded";
91
+ }
92
+ /** The handler failed. Terminal on the wire; a host may still offer a retry. */
93
+ | {
94
+ readonly kind: "failed";
95
+ readonly status: string;
96
+ }
97
+ /**
98
+ * A value this build does not know. NOT an error, and not silently treated as
99
+ * open: a card that re-enables its controls against an unknown terminal state
100
+ * invites a second submission that 409s. Draw it, say so, and stay locked.
101
+ */
102
+ | {
103
+ readonly kind: "unrecognized";
104
+ readonly status: string;
105
+ };
106
+ /**
107
+ * Total over `string`. See the header for why the input is not a union.
108
+ *
109
+ * `cancelled` is the legacy British spelling still on the wire; go-envelopes keeps it
110
+ * as a compatibility value and canonicalises it, so a card that only matched the
111
+ * American spelling would show a cancelled envelope as open.
112
+ */
113
+ export declare function classifyPriorResponse(status: string | null | undefined): PriorResponseState;
114
+ /**
115
+ * Whether a card should still accept input.
116
+ *
117
+ * Expressed against the classification rather than against the raw string so there is
118
+ * ONE place that knows which states are live. `unrecognized` is deliberately not
119
+ * interactive — see the note on that variant.
120
+ */
121
+ export declare function acceptsInput(state: PriorResponseState): boolean;
@@ -0,0 +1,57 @@
1
+ /**
2
+ * How a card says what the person decided, and how it reads back what was decided before.
3
+ *
4
+ * The two directions are treated differently on purpose. What a card EMITS is a closed
5
+ * union: answered or declined. There is no "partial": a half answer that claims the card
6
+ * leaves it in a state nothing can complete. What a card READS is an open string, because
7
+ * the server's recorded status is whatever the server says, including values this build
8
+ * has never heard of; `classifyPriorResponse` is total over it, and an unknown value is
9
+ * drawn honestly and stays locked rather than re-opening the card.
10
+ *
11
+ * A card never builds the wire response. It reports an outcome; the host adds the card's
12
+ * id and sends it.
13
+ *
14
+ * Ported from @hollis-labs/kit-cards (hollis-labs/frontend-support), with the logic kept
15
+ * and the styling left behind.
16
+ */
17
+ /**
18
+ * Total over `string`. See the header for why the input is not a union.
19
+ *
20
+ * `cancelled` is the legacy British spelling still on the wire; go-envelopes keeps it
21
+ * as a compatibility value and canonicalises it, so a card that only matched the
22
+ * American spelling would show a cancelled envelope as open.
23
+ */
24
+ export function classifyPriorResponse(status) {
25
+ if (status == null || status === "")
26
+ return { kind: "open" };
27
+ switch (status) {
28
+ case "submitted":
29
+ return { kind: "submitted" };
30
+ case "canceled":
31
+ case "cancelled":
32
+ return { kind: "canceled" };
33
+ case "expired":
34
+ return { kind: "expired" };
35
+ case "superseded":
36
+ return { kind: "superseded" };
37
+ case "error":
38
+ case "failed":
39
+ return { kind: "failed", status };
40
+ case "handling":
41
+ return { kind: "pending" };
42
+ case "partial":
43
+ return { kind: "open" };
44
+ default:
45
+ return { kind: "unrecognized", status };
46
+ }
47
+ }
48
+ /**
49
+ * Whether a card should still accept input.
50
+ *
51
+ * Expressed against the classification rather than against the raw string so there is
52
+ * ONE place that knows which states are live. `unrecognized` is deliberately not
53
+ * interactive — see the note on that variant.
54
+ */
55
+ export function acceptsInput(state) {
56
+ return state.kind === "open";
57
+ }
package/package.json CHANGED
@@ -1,6 +1,41 @@
1
1
  {
2
2
  "name": "@hollis-labs/surface-cards",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Cards without any styling: the outcome a card reports and the status it reads back, a lifecycle engine that decides where each card shows, a form compiled from a JSON Schema subset, and a table of renderers by kind and version. Visuals are the Surface registry's card components.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/hollis-labs/surface.git",
9
+ "directory": "packages/cards"
10
+ },
11
+ "homepage": "https://github.com/hollis-labs/surface/tree/main/packages/cards#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/hollis-labs/surface/issues"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public",
17
+ "registry": "https://registry.npmjs.org/"
18
+ },
19
+ "type": "module",
20
+ "sideEffects": false,
21
+ "main": "./dist/index.js",
22
+ "types": "./dist/index.d.ts",
23
+ "exports": {
24
+ ".": {
25
+ "types": "./dist/index.d.ts",
26
+ "default": "./dist/index.js"
27
+ },
28
+ "./package.json": "./package.json"
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "README.md"
33
+ ],
34
+ "scripts": {
35
+ "build": "rm -rf dist && tsc -p tsconfig.build.json",
36
+ "prepack": "npm run build"
37
+ },
38
+ "peerDependencies": {
39
+ "react": ">=19"
40
+ }
41
+ }