@soffits/dsh-card-board 0.17.4 → 0.18.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,15 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.18.1
4
+
5
+ A broken language file is skipped with a warning instead of failing the page's words in every language. The people mapping, the words, the live stream and the client build come from the shared `@soffits/dsh-host-kit` instead of copies kept here.
6
+
7
+ ## 0.18.0
8
+
9
+ A press names its row by the row's `key` (`source.row` in the event is now that key), so it lands on the row the person tapped even when the card was rewritten in between. Before, it named the row by its place: after a handled row dropped out, or a quick second tick, a press could answer or tick the row below it, since rows often share button ids. A row without a key still goes by its place; an index that points at a keyed row is refused. Rows ticked this visit are kept apart by key too, so ticking a second one no longer hides the first.
10
+
11
+ Open live streams now end when the plugin is unloaded or reloaded, so pages reconnect instead of waiting on a stream that will never send again (the cleanup was registered on an event Cordis doesn't send, so file watches leaked too). A card that can be found but not read shows as a broken card instead of failing the whole board, an unreadable action log no longer blocks every board, and a failing change listener is logged instead of escaping.
12
+
3
13
  ## 0.17.4
4
14
 
5
15
  The opened view wraps a long unbroken word (an id, a key, a path) in its heading and text instead of growing wider than a phone screen and scrolling sideways, and an opened row's tick box flows in one row with its other buttons.
package/README.md CHANGED
@@ -329,16 +329,18 @@ The plugin doesn't act on a press itself. It checks that the person may see the
329
329
  "person": "alex",
330
330
  "user": "<verified user id>",
331
331
  "at": "2026-03-02T09:41:12.000Z",
332
- "source": { "plugin": "dsh-card-board", "board": "home", "card": "chores", "row": 1 }
332
+ "source": { "plugin": "dsh-card-board", "board": "home", "card": "chores", "row": "chore-2" }
333
333
  }
334
334
  ```
335
335
 
336
+ `source.row` names the row by its `key`, so a press lands on the row the person saw even when the card was rewritten in between; a row without a key goes by its place in `rows`, which a rewrite can shift, so give every row with buttons a key.
337
+
336
338
  It's appended to the action log, emitted in-process as the Cordis event `card-board/action`, and published on channel `ui.action.<kind>` through [dsh-cron-jobs](https://github.com/soffits/dsh-cron-jobs) when that's installed, so a job subscribed to `ui.action.done` can mark the thing done wherever it lives. `person` is `owner` on a single-person DSH.
337
339
 
338
340
  Taking a press back is another press, appended to the same log, so every record says who, when, what and whether it was undone. Its `action` is `undo` (channel `ui.action.undo`), `undoes` names the press, `of` is the kind it takes back, `inverse` the declared name, and `payload` is the action's own payload without the time the person picked, plus the inverse's. The press keeps the inverse as the card offered it, so an undo works after the card was rewritten, and a press taken back shows as `undone`. A handler that receives a press and its undo in one batch should treat the pair as nothing happening.
339
341
 
340
342
  ```json
341
- { "press": "5d0f…", "action": "undo", "of": "done", "id": "library-books:done", "undoes": "fcb114dd-3890-42e6-af4b-b23173edf8e0", "inverse": "reopen", "payload": {}, "person": "alex", "at": "2026-03-02T09:41:15.000Z", "source": { "plugin": "dsh-card-board", "board": "home", "card": "chores", "row": 1 } }
343
+ { "press": "5d0f…", "action": "undo", "of": "done", "id": "library-books:done", "undoes": "fcb114dd-3890-42e6-af4b-b23173edf8e0", "inverse": "reopen", "payload": {}, "person": "alex", "at": "2026-03-02T09:41:15.000Z", "source": { "plugin": "dsh-card-board", "board": "home", "card": "chores", "row": "chore-2" } }
342
344
  ```
343
345
 
344
346
  The press log is never a second source of the item's state: a press only marks the gap until the owner of the item writes the card again, and after that a row's box follows the card's `checked`.
package/client.js CHANGED
@@ -1,4 +1,4 @@
1
- /* @soffits/dsh-card-board 0.17.4: built by scripts/build.mjs from src/client/. Do not edit. */
1
+ /* @soffits/dsh-card-board 0.18.1: built from src/client/. Do not edit. */
2
2
  window.__ModuleLoader__.load({
3
3
  id: "@soffits/dsh-card-board",
4
4
  factory: (require) => {
@@ -982,12 +982,14 @@ function dropAfter(rect, x, y, single) {
982
982
 
983
983
  // src/client/ticks.js
984
984
  var doneOf = (row) => row?.actions?.find((action) => action.kind === "done" && action.label === void 0);
985
+ var rowRef = (row, index) => row?.key ?? index;
986
+ var keptId = (row) => row.key ?? doneOf(row)?.id;
985
987
  function keepOf(row, index) {
986
988
  const done = doneOf(row);
987
- return done === void 0 ? void 0 : { id: done.id, index, row: { ...row, checked: true, actions: [done] } };
989
+ return done === void 0 ? void 0 : { id: keptId(row), index, row: { ...row, checked: true, actions: [done] } };
988
990
  }
989
991
  function keepTicked(rows, kept = []) {
990
- const present = new Set(rows.map((row) => doneOf(row)?.id));
992
+ const present = new Set(rows.map(keptId));
991
993
  const missing = kept.filter((entry) => !present.has(entry.id)).sort((a, b) => a.index - b.index);
992
994
  if (missing.length === 0) return rows;
993
995
  const merged = [...rows];
@@ -1118,13 +1120,14 @@ function Row({ lead, title, sub, meta, value, spark, row, index, washCount, fres
1118
1120
  buttons?.length > 0 && (0, import_react6.createElement)(
1119
1121
  "span",
1120
1122
  { className: "cb-rowActions" },
1121
- buttons.some((action) => action.kind === "step") && rowActions(index, buttons, "steps"),
1122
- rowActions(index, buttons, "buttons")
1123
+ buttons.some((action) => action.kind === "step") && rowActions(rowRef(row, index), buttons, "steps"),
1124
+ rowActions(rowRef(row, index), buttons, "buttons")
1123
1125
  )
1124
1126
  );
1125
1127
  }
1126
1128
  function DoneBox({ row, index, done, rowControls, t, labelled = false }) {
1127
- const { checked, undo } = doneState(row, rowControls.latest(index, done.id));
1129
+ const ref = rowRef(row, index);
1130
+ const { checked, undo } = doneState(row, rowControls.latest(ref, done.id));
1128
1131
  const label = t(checked ? undo ? "markNotDone" : "checked" : "markDone");
1129
1132
  return (0, import_react6.createElement)(
1130
1133
  "span",
@@ -1135,7 +1138,7 @@ function DoneBox({ row, index, done, rowControls, t, labelled = false }) {
1135
1138
  title: label,
1136
1139
  label: (0, import_react6.createElement)("span", { className: labelled ? void 0 : "cb-visuallyHidden" }, label),
1137
1140
  onChange: (value) => {
1138
- if (value) rowControls.press(index, done);
1141
+ if (value) rowControls.press(ref, done);
1139
1142
  else if (undo) rowControls.undo(undo);
1140
1143
  }
1141
1144
  })
@@ -1150,7 +1153,7 @@ function ListCard({ data, live, locale, t, rowActions, ask, all = false, onOpenR
1150
1153
  const hidden = listed.length - rows.length;
1151
1154
  const ticked = (row) => {
1152
1155
  const done = doneOf(row);
1153
- return done !== void 0 && rowControls !== void 0 ? doneState(row, rowControls.latest(data.rows.indexOf(row), done.id)).checked : row.checked === true;
1156
+ return done !== void 0 && rowControls !== void 0 ? doneState(row, rowControls.latest(rowRef(row, data.rows.indexOf(row)), done.id)).checked : row.checked === true;
1154
1157
  };
1155
1158
  const progress = data.progress;
1156
1159
  return (0, import_react6.createElement)(
@@ -1224,12 +1227,12 @@ function OpenedRow({ row, kind, index, live, locale, t, rowActions, ask, rowCont
1224
1227
  (buttons.length > 0 || done && rowControls) && (0, import_react6.createElement)(
1225
1228
  "footer",
1226
1229
  { className: "cb-openActions" },
1227
- buttons.some((action) => action.kind === "step") && rowActions(index, buttons, "steps", false),
1230
+ buttons.some((action) => action.kind === "step") && rowActions(rowRef(row, index), buttons, "steps", false),
1228
1231
  (0, import_react6.createElement)(
1229
1232
  "div",
1230
1233
  { className: "cb-openButtons" },
1231
1234
  done && rowControls && (0, import_react6.createElement)(DoneBox, { row, index, done, rowControls, t, labelled: true }),
1232
- buttons.some((action) => action.kind !== "step") && rowActions(index, buttons, "buttons", false)
1235
+ buttons.some((action) => action.kind !== "step") && rowActions(rowRef(row, index), buttons, "buttons", false)
1233
1236
  )
1234
1237
  )
1235
1238
  );
@@ -1561,10 +1564,14 @@ function Card({ entry, live, boardId, assistant, tracks, active, locale, t, pres
1561
1564
  lines: row === void 0 ? summaryLines(card, locale, t).slice(0, 15) : [line],
1562
1565
  context: { board: boardId, card: entry.id, ...row === void 0 ? {} : { row }, type: card.type, updatedAt: card.updatedAt }
1563
1566
  });
1564
- const rowLine = (row) => card.type === "status" ? statusRowLine(card.data.rows[row], locale) : listRowLine(card.data.rows[row]);
1567
+ const indexOf = (row) => typeof row === "string" ? card.data.rows.findIndex((other) => other.key === row) : row;
1568
+ const rowLine = (row) => card.type === "status" ? statusRowLine(card.data.rows[indexOf(row)], locale) : listRowLine(card.data.rows[indexOf(row)]);
1565
1569
  const askName = assistant ? t("action.chatNamed", { name: assistant }) : void 0;
1566
1570
  const named = (list) => assistant ? list?.map((action) => action.kind === "chat" && action.label === void 0 ? { ...action, label: askName } : action) : list;
1567
- const onPress = (target) => (action, extra) => press(action, extra, { card: entry.id, ...target }, target.row === void 0 ? void 0 : card.data.rows?.[target.row]);
1571
+ const onPress = (target) => (action, extra) => {
1572
+ const index = target.row === void 0 ? -1 : indexOf(target.row);
1573
+ return press(action, extra, { card: entry.id, ...target }, index >= 0 ? { row: card.data.rows[index], index } : void 0);
1574
+ };
1568
1575
  const rowActions = actions && ((row, list, part2, compact = true) => (0, import_react10.createElement)(actions.ActionBar, {
1569
1576
  actions: named(list),
1570
1577
  part: part2,
@@ -2048,11 +2055,11 @@ function BoardsPage() {
2048
2055
  showToast({ text: "toast.undoFailed" });
2049
2056
  }
2050
2057
  }, [post, showToast]);
2051
- const press = (0, import_react15.useCallback)(async (action, extra, target, row) => {
2058
+ const press = (0, import_react15.useCallback)(async (action, extra, target, at2) => {
2052
2059
  const answer = await post({ ...target, id: action.id, ...extra });
2053
2060
  if (answer?.undoable) {
2054
2061
  showToast({ text: TOAST_KEYS[action.kind] ?? "toast.event", undo: () => undo(answer.press, target.card) });
2055
- const keep = action.kind === "done" && row !== void 0 ? keepOf(row, target.row) : void 0;
2062
+ const keep = action.kind === "done" && at2 !== void 0 ? keepOf(at2.row, at2.index) : void 0;
2056
2063
  if (keep) setKept((prev) => ({ ...prev, [target.card]: withKept(prev[target.card], keep) }));
2057
2064
  }
2058
2065
  return answer;
package/index.js CHANGED
@@ -11,9 +11,8 @@ import { homedir } from 'node:os'
11
11
  import { isAbsolute, join, resolve } from 'node:path'
12
12
  import { fileURLToPath } from 'node:url'
13
13
  import z from '@deepseek-ai/schemastery'
14
- import { createPeople, expandHome } from './src/access.js'
14
+ import { createEventStreams, createPeople, expandHome, readLocales, tableFor } from '@soffits/dsh-host-kit'
15
15
  import { createArrangeStore } from './src/arrange-store.js'
16
- import { createMessages } from './src/messages.js'
17
16
  import { createPresses } from './src/presses.js'
18
17
  import { createRoutes } from './src/routes.js'
19
18
  import { createSeenStore } from './src/seen.js'
@@ -68,8 +67,11 @@ export function apply(ctx, config) {
68
67
  timeoutSeconds: config.actionTimeoutSeconds ?? 300,
69
68
  warn: message => logger.warn(message),
70
69
  })
71
- const watches = createWatches()
72
- ctx.on('dispose', () => watches.close())
70
+ const watches = createWatches({ warn: message => logger.warn(message) })
71
+ ctx.effect(() => () => watches.close())
72
+ const streams = createEventStreams()
73
+ ctx.effect(() => () => streams.close())
74
+ const localeDir = fileURLToPath(new URL('./locale', import.meta.url))
73
75
  const routes = createRoutes({
74
76
  dataDir,
75
77
  people,
@@ -79,7 +81,9 @@ export function apply(ctx, config) {
79
81
  seen: createSeenStore(join(dataDir, '.seen')),
80
82
  arrange: createArrangeStore(join(dataDir, '.arrange')),
81
83
  watches,
82
- messages: createMessages(fileURLToPath(new URL('./locale', import.meta.url))),
84
+ // Read on each request, so an update that changes only words shows without a restart.
85
+ messages: async tag => tableFor(await readLocales(localeDir, { warn: message => logger.warn(message) }), tag),
86
+ streams,
83
87
  version,
84
88
  })
85
89
  for (const route of routes) ctx.connection.fetch.register(route)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soffits/dsh-card-board",
3
- "version": "0.17.4",
3
+ "version": "0.18.1",
4
4
  "description": "A data-driven card board for DeepSeek Harness: scripts write small JSON cards, the Web UI shows each person the boards they may see.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -72,6 +72,9 @@
72
72
  "check": "node scripts/build.mjs --check && for f in index.js client.js bin/*.js src/*.js src/client/*.js test/*.js; do node --check \"$f\" || exit 1; done && node bin/dsh-card-board.js check --dir examples/boards",
73
73
  "test": "node --test test/*.test.js"
74
74
  },
75
+ "dependencies": {
76
+ "@soffits/dsh-host-kit": "^0.1.0"
77
+ },
75
78
  "devDependencies": {
76
79
  "@deepseek-ai/cordis": "^4.1.0",
77
80
  "@deepseek-ai/dsh-client-connection": "0.2.2-rc.3",
package/src/access.js CHANGED
@@ -1,11 +1,9 @@
1
1
  /**
2
2
  * Who may see which board.
3
3
  *
4
- * The caller comes from a `requestIdentity` service, if one is installed: any
5
- * plugin that verifies the person behind an `/api` request can provide it
6
- * (`current()` returns `{ id, ... }` or null). The verified user id maps to a
7
- * person id through the configured mapping, and a board lists the person ids
8
- * that may see it in `viewers`. A board can also say who may act on it (use the buttons it declares) in `actors`;
4
+ * Who is asking comes from the shared people mapping (`viewerOf` in
5
+ * `@soffits/dsh-host-kit`), and a board lists the person ids that may see it
6
+ * in `viewers`. A board can also say who may act on it (use the buttons it declares) in `actors`;
9
7
  * without `actors` the viewers may, so a board that never heard of the field behaves as before.
10
8
  * Acting needs seeing: a name in `actors` that isn't in `viewers` gets nothing extra.
11
9
  *
@@ -16,75 +14,7 @@
16
14
  * - owner: no mapping. Everyone DSH lets in is its owner and sees every board,
17
15
  * which is what a single-person DSH wants.
18
16
  */
19
- import { readFile, stat } from 'node:fs/promises'
20
-
21
- /** Person ids compare without regard to case or surrounding space. */
22
- export function personKey(value) {
23
- return typeof value === 'string' ? value.trim().normalize('NFKC').toLowerCase() : ''
24
- }
25
-
26
- /** Expand a leading `~/` to the home folder. */
27
- export function expandHome(path, home) {
28
- return typeof path === 'string' && (path === '~' || path.startsWith('~/')) ? home + path.slice(1) : path
29
- }
30
-
31
- /**
32
- * The configured user id → person id mapping, re-read from `peopleFile`
33
- * whenever that file changes. A file that can't be read or parsed maps nobody
34
- * (and is reported once per change), so a broken file never widens access.
35
- */
36
- export function createPeople({ people = {}, peopleFile = '', peopleKey = '' }, { warn = () => {} } = {}) {
37
- const inline = Object.entries(people)
38
- const enabled = inline.length > 0 || peopleFile !== ''
39
- let cached = { tag: undefined, entries: [] }
40
-
41
- async function fromFile() {
42
- if (peopleFile === '') return []
43
- let tag
44
- try {
45
- const info = await stat(peopleFile)
46
- tag = `${info.size}:${info.mtimeMs}`
47
- } catch (error) {
48
- tag = `error:${error.code}`
49
- }
50
- if (tag === cached.tag) return cached.entries
51
- let entries = []
52
- try {
53
- let value = JSON.parse(await readFile(peopleFile, 'utf8'))
54
- if (peopleKey !== '') value = value?.[peopleKey]
55
- if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error(peopleKey ? `no object at key ${peopleKey}` : 'not a JSON object')
56
- entries = Object.entries(value).filter(([, person]) => typeof person === 'string')
57
- } catch (error) {
58
- warn(`people file ${peopleFile}: ${error.message}; nobody is mapped from it`)
59
- }
60
- cached = { tag, entries }
61
- return entries
62
- }
63
-
64
- return {
65
- enabled,
66
- /** The person id for a verified user id, or undefined. Inline entries win over the file. */
67
- async personFor(userId) {
68
- if (typeof userId !== 'string' || userId === '') return undefined
69
- const map = new Map([...(await fromFile()), ...inline])
70
- const person = map.get(userId)
71
- return person === undefined ? undefined : personKey(person)
72
- },
73
- }
74
- }
75
-
76
- /**
77
- * Decide who the current request is. Returns `{ mode: 'owner' }`,
78
- * `{ mode: 'people', person }` (person may be undefined: sees nothing) or
79
- * `{ mode: 'people', unavailable: true }` when a mapping is configured but no
80
- * identity provider is installed.
81
- */
82
- export async function viewerOf(people, identityService) {
83
- if (!people.enabled) return { mode: 'owner' }
84
- if (identityService === undefined || typeof identityService?.current !== 'function') return { mode: 'people', unavailable: true }
85
- const identity = identityService.current()
86
- return { mode: 'people', person: await people.personFor(identity?.id) }
87
- }
17
+ import { personKey } from '@soffits/dsh-host-kit'
88
18
 
89
19
  /**
90
20
  * Whether a viewer who may see `board` may also see its card `card`: a card listed in the board's `cardViewers`
package/src/presses.js CHANGED
@@ -64,7 +64,10 @@ async function readTail(path) {
64
64
  */
65
65
  export function createPresses({ logPath, publisher, notify = () => {}, timeoutSeconds, warn = () => {}, now = Date.now }) {
66
66
  let recent
67
- const loaded = readTail(logPath).then(events => { recent = events })
67
+ const loaded = readTail(logPath).then(events => { recent = events }, error => {
68
+ warn(`action log ${logPath} unreadable, starting without recent presses: ${error.message}`)
69
+ recent = []
70
+ })
68
71
 
69
72
  async function list() {
70
73
  await loaded
package/src/routes.js CHANGED
@@ -17,10 +17,10 @@
17
17
  * in it is new since the viewer last looked, `fresh: { card: true, rows: [keys] }`.
18
18
  */
19
19
  import { join } from 'node:path'
20
- import { mayAct, maySee, maySeeCard, viewerOf, withoutActions } from './access.js'
20
+ import { TAG, viewerOf } from '@soffits/dsh-host-kit'
21
+ import { mayAct, maySee, maySeeCard, withoutActions } from './access.js'
21
22
  import { parseArrangement } from './arrange.js'
22
- import { LANGUAGE_ID } from './messages.js'
23
- import { ID_PATTERN, PRESS_KINDS, findAction } from './schema.js'
23
+ import { ID_PATTERN, KEY_PATTERN, PRESS_KINDS, findAction } from './schema.js'
24
24
  import { cardVersions, freshness, parseSeen } from './seen.js'
25
25
  import { boardTag, cardPath, cardTag, listBoards, readBoard, readCard, readCards, resolveDataDir } from './store.js'
26
26
 
@@ -33,8 +33,6 @@ export const ARRANGE_PATH = '/api/card-board/arrange'
33
33
  export const ACTION_PATH = '/api/card-board/action'
34
34
  export const LOCALE_PATH = '/api/card-board/locale'
35
35
  const DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/
36
- /** A comment line now and then keeps proxies from closing a quiet stream. */
37
- export const HEARTBEAT_MS = 25_000
38
36
 
39
37
  const HEADERS = {
40
38
  'content-type': 'application/json; charset=utf-8',
@@ -51,7 +49,7 @@ const NO_PROVIDER = 'This board needs a sign-in plugin that provides requestIden
51
49
  /**
52
50
  * @param {object} options
53
51
  * @param {string} options.dataDir - the data folder (absolute)
54
- * @param {ReturnType<import('./access.js').createPeople>} options.people
52
+ * @param {ReturnType<import('@soffits/dsh-host-kit').createPeople>} options.people
55
53
  * @param {() => object | undefined} options.identity - the requestIdentity service right now, if any
56
54
  * @param {number} options.pollSeconds
57
55
  * @param {ReturnType<import('./presses.js').createPresses>} options.presses
@@ -60,9 +58,10 @@ const NO_PROVIDER = 'This board needs a sign-in plugin that provides requestIden
60
58
  * @param {ReturnType<import('./watch.js').createWatches>} options.watches
61
59
  * @param {(tag: string) => Promise<object>} options.messages - the page's words for a language
62
60
  * @param {string} [options.version] - mixed into ETags, so a plugin update refreshes open pages
63
- * @param {number} [options.heartbeatMs]
61
+ * @param {ReturnType<import('@soffits/dsh-host-kit').createEventStreams>} options.streams - the open event streams, ended when the plugin unloads
64
62
  */
65
- export function createRoutes({ dataDir, people, identity, pollSeconds, presses, seen, arrange, watches, messages, version = '', heartbeatMs = HEARTBEAT_MS }) {
63
+ export function createRoutes({ dataDir, people, identity, pollSeconds, presses, seen, arrange, watches, messages, streams, version = '' }) {
64
+
66
65
  /** The viewer and their board, or the Response that refuses them. */
67
66
  async function access(board) {
68
67
  const viewer = await viewerOf(people, identity())
@@ -88,7 +87,7 @@ export function createRoutes({ dataDir, people, identity, pollSeconds, presses,
88
87
 
89
88
  async function locale(request) {
90
89
  const tag = new URL(request.url).searchParams.get('tag') ?? 'en'
91
- if (!LANGUAGE_ID.test(tag)) return json(400, { error: 'Not a language id.' })
90
+ if (!TAG.test(tag)) return json(400, { error: 'Not a language id.' })
92
91
  return json(200, await messages(tag))
93
92
  }
94
93
 
@@ -144,36 +143,18 @@ export function createRoutes({ dataDir, people, identity, pollSeconds, presses,
144
143
  if (!ID_PATTERN.test(id)) return json(400, { error: 'Not a board id.' })
145
144
  const found = await access(id)
146
145
  if (found.refused) return found.refused
147
- const encoder = new TextEncoder()
148
- let finish = () => {}
149
- const body = new ReadableStream({
150
- async start(controller) {
151
- let open = true
152
- const send = text => { if (open) controller.enqueue(encoder.encode(text)) }
153
- const data = value => send(`data: ${JSON.stringify(value)}\n\n`)
154
- let unwatch = () => {}
155
- let unarrange = () => {}
156
- const heartbeat = setInterval(() => send(': ping\n\n'), heartbeatMs)
157
- finish = () => {
158
- if (!open) return
159
- open = false
160
- clearInterval(heartbeat)
161
- unwatch()
162
- unarrange()
163
- request.signal?.removeEventListener?.('abort', finish)
164
- }
165
- request.signal?.addEventListener?.('abort', finish)
166
- send(': connected\n\n')
167
- // The viewer's own arrangement changing elsewhere (another device) reaches this page too.
168
- unarrange = arrange.subscribe((who, board) => { if (who === found.person && board === id) data({ type: 'arrange' }) })
146
+ return streams.respond(request, async ({ send, end }) => {
147
+ // The viewer's own arrangement changing elsewhere (another device) reaches this page too.
148
+ const unarrange = arrange.subscribe((who, board) => { if (who === found.person && board === id) send({ type: 'arrange' }) })
149
+ let unwatch
150
+ try {
169
151
  unwatch = await watches.watch(join(found.root, id), async change => {
170
152
  if (change.type === 'board') {
171
153
  // Viewers may have changed: someone who may no longer see the board hears that and nothing else.
172
154
  const again = await access(id)
173
155
  if (again.refused) {
174
- data({ type: 'gone' })
175
- finish()
176
- try { controller.close() } catch { /* already closed */ }
156
+ send({ type: 'gone' })
157
+ end()
177
158
  return
178
159
  }
179
160
  }
@@ -181,16 +162,17 @@ export function createRoutes({ dataDir, people, identity, pollSeconds, presses,
181
162
  const now = await readBoard(found.root, id)
182
163
  if (!maySeeCard(found.viewer, now?.board, change.id)) return
183
164
  }
184
- data(change)
165
+ send(change)
185
166
  })
186
- if (!open) unwatch()
187
- else data({ type: 'hello' })
188
- },
189
- cancel() { finish() },
190
- })
191
- return new Response(body, {
192
- status: 200,
193
- headers: { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache, no-transform', 'x-accel-buffering': 'no', 'x-content-type-options': 'nosniff' },
167
+ } catch (error) {
168
+ unarrange()
169
+ throw error
170
+ }
171
+ send({ type: 'hello' })
172
+ return () => {
173
+ unwatch()
174
+ unarrange()
175
+ }
194
176
  })
195
177
  }
196
178
 
@@ -250,7 +232,7 @@ export function createRoutes({ dataDir, people, identity, pollSeconds, presses,
250
232
  if (undo !== undefined) return undoPress({ board, card, undo })
251
233
  if (typeof board !== 'string' || !ID_PATTERN.test(board) || typeof card !== 'string' || !ID_PATTERN.test(card) || typeof id !== 'string')
252
234
  return json(400, { error: 'Say which board, card and action.' })
253
- if (row !== undefined && !(Number.isInteger(row) && row >= 0)) return json(400, { error: 'row must be a row index.' })
235
+ if (row !== undefined && !(Number.isInteger(row) && row >= 0) && !(typeof row === 'string' && KEY_PATTERN.test(row))) return json(400, { error: 'row must be a row key, or the index of a row without one.' })
254
236
  if (until !== undefined && (typeof until !== 'string' || !DATE_TIME.test(until) || Number.isNaN(Date.parse(until))))
255
237
  return json(400, { error: 'until must be an ISO date-time with a zone.' })
256
238
  const viewer = await viewerOf(people, identity())
@@ -288,7 +270,7 @@ export function createRoutes({ dataDir, people, identity, pollSeconds, presses,
288
270
  return json(200, { press: result.event.press, state: 'pending', at: result.event.at, undoes: result.event.undoes })
289
271
  }
290
272
 
291
- return [
273
+ const routes = [
292
274
  { path: BOARDS_PATH, methods: ['GET'], requestBody: 'buffered', fetch: boards },
293
275
  { path: BOARD_PATH, methods: ['GET'], requestBody: 'buffered', fetch: board },
294
276
  { path: CARD_PATH, methods: ['GET'], requestBody: 'buffered', fetch: card },
@@ -298,4 +280,5 @@ export function createRoutes({ dataDir, people, identity, pollSeconds, presses,
298
280
  { path: LOCALE_PATH, methods: ['GET'], requestBody: 'buffered', fetch: locale },
299
281
  { path: ACTION_PATH, methods: ['POST'], requestBody: 'buffered', fetch: action },
300
282
  ]
283
+ return routes
301
284
  }
package/src/schema.js CHANGED
@@ -603,14 +603,25 @@ export function checkCard(card) {
603
603
  return c.problems
604
604
  }
605
605
 
606
+ /**
607
+ * The row a press names: by its `key`, so a press still finds it after the card
608
+ * was rewritten; only a row without a key goes by its place.
609
+ */
610
+ export function findRow(card, row) {
611
+ const rows = card?.data?.rows
612
+ if (!Array.isArray(rows)) return undefined
613
+ if (typeof row === 'string') return rows.find(candidate => candidate?.key === row)
614
+ return rows[row]?.key === undefined ? rows[row] : undefined
615
+ }
616
+
606
617
  /**
607
618
  * The action a press names, looked up in the card as written: on the card
608
- * itself, or on row `row` of a list or status card, among its own buttons and
609
- * those its detail shows when opened. Undefined when there is no such action,
610
- * so a browser can only press what the data offers.
619
+ * itself, or on a row of a list or status card (`findRow`), among its own
620
+ * buttons and those its detail shows when opened. Undefined when there is no
621
+ * such action, so a browser can only press what the data offers.
611
622
  */
612
623
  export function findAction(card, actionId, row) {
613
- const holder = row === undefined ? card : card?.data?.rows?.[row]
624
+ const holder = row === undefined ? card : findRow(card, row)
614
625
  const list = [holder?.actions, holder?.detail?.actions].flatMap(value => (Array.isArray(value) ? value : []))
615
626
  return list.find(action => action?.id === actionId)
616
627
  }
package/src/store.js CHANGED
@@ -19,17 +19,17 @@ const MAX_BOARD_BYTES = 64 * 1024
19
19
 
20
20
  /** A file's content if it is a regular file inside `root` and not too big; else a reason. */
21
21
  async function readInside(root, path, maxBytes) {
22
- let real
23
22
  try {
24
- real = await realpath(path)
23
+ const real = await realpath(path)
24
+ if (!real.startsWith(root + sep)) return { problem: 'points outside the data folder' }
25
+ const info = await stat(real)
26
+ if (!info.isFile()) return { problem: 'is not a file' }
27
+ if (info.size > maxBytes) return { problem: `is larger than ${Math.round(maxBytes / 1024)} KB` }
28
+ return { text: await readFile(real, 'utf8') }
25
29
  } catch (error) {
30
+ // Gone between two of the reads (a producer replacing it) counts as missing, like gone before them.
26
31
  return { missing: error.code === 'ENOENT', problem: error.code === 'ENOENT' ? 'file not found' : `cannot read: ${error.code ?? error.message}` }
27
32
  }
28
- if (!real.startsWith(root + sep)) return { problem: 'points outside the data folder' }
29
- const info = await stat(real)
30
- if (!info.isFile()) return { problem: 'is not a file' }
31
- if (info.size > maxBytes) return { problem: `is larger than ${Math.round(maxBytes / 1024)} KB` }
32
- return { text: await readFile(real, 'utf8') }
33
33
  }
34
34
 
35
35
  async function readJson(root, path, maxBytes, check) {
package/src/watch.js CHANGED
@@ -40,8 +40,9 @@ export function changes(before, after) {
40
40
  * @param {object} [options]
41
41
  * @param {number} [options.pollMs] - the stat poll's interval (default 10 s)
42
42
  * @param {number} [options.settleMs] - how long a burst of file events is gathered before one scan (default 120 ms)
43
+ * @param {(message: string) => void} [options.warn] - told when a change listener fails
43
44
  */
44
- export function createWatches({ pollMs = 10_000, settleMs = 120 } = {}) {
45
+ export function createWatches({ pollMs = 10_000, settleMs = 120, warn = () => {} } = {}) {
45
46
  const boards = new Map()
46
47
 
47
48
  function open(dir) {
@@ -55,7 +56,9 @@ export function createWatches({ pollMs = 10_000, settleMs = 120 } = {}) {
55
56
  const files = await snapshot(dir)
56
57
  const events = entry.files === null ? [] : changes(entry.files, files)
57
58
  entry.files = files
58
- for (const event of events) for (const listener of entry.listeners) listener(event)
59
+ for (const event of events)
60
+ for (const listener of entry.listeners)
61
+ Promise.resolve().then(() => listener(event)).catch(error => warn(`a change listener failed: ${error.message}`))
59
62
  } while (entry.again)
60
63
  })().finally(() => { entry.scanning = null })
61
64
  return entry.scanning
package/src/messages.js DELETED
@@ -1,52 +0,0 @@
1
- /**
2
- * The page's own words. One file per language in `locale/<tag>.json` (the same
3
- * layout DSH packages use for their titles); a file's `ui` object holds the
4
- * page's messages next to its `meta`. Which languages exist is whatever files
5
- * are there: nothing in the code names one.
6
- *
7
- * A request for a language gets English overlaid by the language's primary
8
- * tag and then by the exact tag, so a half-translated file still shows whole
9
- * pages (`pt-BR` → `pt` → `en`).
10
- */
11
- import { readFile, readdir } from 'node:fs/promises'
12
- import { join } from 'node:path'
13
-
14
- export const LANGUAGE_ID = /^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/
15
- const REFERENCE = 'en'
16
-
17
- /** Every language file in `directory`: lowercase id → its `ui` messages. */
18
- export async function readLanguages(directory) {
19
- const languages = new Map()
20
- for (const name of (await readdir(directory)).sort()) {
21
- if (!name.endsWith('.json') || !LANGUAGE_ID.test(name.slice(0, -5))) continue
22
- const parsed = JSON.parse(await readFile(join(directory, name), 'utf8'))
23
- if (typeof parsed.ui === 'object' && parsed.ui !== null) languages.set(name.slice(0, -5).toLowerCase(), parsed.ui)
24
- }
25
- return languages
26
- }
27
-
28
- /** The tags to try for `tag`, most specific first, ending with English: `fr-CA` → fr-ca, fr, en. */
29
- export function fallbackChain(tag) {
30
- const parts = String(tag).toLowerCase().split('-')
31
- const chain = parts.map((_, i) => parts.slice(0, parts.length - i).join('-'))
32
- return chain.includes(REFERENCE) ? chain : [...chain, REFERENCE]
33
- }
34
-
35
- /** The merged messages for `tag`, and the tags that contributed (most specific first). */
36
- export function messagesFor(languages, tag) {
37
- const used = fallbackChain(tag).filter(id => languages.has(id))
38
- const messages = {}
39
- for (const id of [...used].reverse()) Object.assign(messages, languages.get(id))
40
- return { tag: used[0] ?? REFERENCE, messages }
41
- }
42
-
43
- /**
44
- * The words for a language, read from the folder on every request. DSH swaps a plugin's browser half as
45
- * soon as its files change, before the host half is reloaded, so words kept from start would hand a
46
- * freshly updated page the old table (raw keys for every new message).
47
- * @param {string} directory - the package's `locale` folder
48
- * @returns {(tag: string) => Promise<{ tag: string, messages: Record<string, string> }>}
49
- */
50
- export function createMessages(directory) {
51
- return async tag => messagesFor(await readLanguages(directory), tag)
52
- }