@soffits/dsh-card-board 0.5.0 → 0.7.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/src/routes.js CHANGED
@@ -1,24 +1,37 @@
1
1
  /**
2
- * The two read-only routes the page polls. They are exact Fetch routes under
3
- * DSH's `/api`, so DSH admits the browser first and a `requestIdentity`
4
- * provider sees the request; every answer is decided here, per request, from
5
- * the server's own view of who is asking.
2
+ * The page's routes. They are exact Fetch routes under DSH's `/api`, so DSH
3
+ * admits the browser first and a `requestIdentity` provider sees the request;
4
+ * every answer is decided here, per request, from the server's own view of who
5
+ * is asking.
6
6
  *
7
- * GET /api/card-board/boards the boards this viewer may see
8
- * GET /api/card-board/board?id=<id> one board with its cards (ETag, 304)
9
- * GET /api/card-board/locale?tag=fr the page's own words for a language (from locale/*.json)
10
- * POST /api/card-board/action press a done, snooze or event action
7
+ * GET /api/card-board/boards the boards this viewer may see
8
+ * GET /api/card-board/board?id=<id> one board with its cards (ETag, 304)
9
+ * GET /api/card-board/card?board=<id>&id=<card> one card (ETag, 304)
10
+ * GET /api/card-board/events?board=<id> Server-Sent Events: which card or board.json changed
11
+ * POST /api/card-board/seen the card versions the viewer has seen
12
+ * GET /api/card-board/locale?tag=fr the page's own words for a language (from locale/*.json)
13
+ * POST /api/card-board/action press a step, done, snooze or event action
14
+ *
15
+ * Every card entry carries its content `version` (and `rows`, the versions of its keyed rows) and, when something
16
+ * in it is new since the viewer last looked, `fresh: { card: true, rows: [keys] }`.
11
17
  */
18
+ import { join } from 'node:path'
12
19
  import { maySee, viewerOf } from './access.js'
13
20
  import { LANGUAGE_ID } from './messages.js'
14
21
  import { ID_PATTERN, PRESS_KINDS, findAction } from './schema.js'
15
- import { boardTag, cardPath, listBoards, readBoard, readCard, readCards, resolveDataDir } from './store.js'
22
+ import { cardVersions, freshness, parseSeen } from './seen.js'
23
+ import { boardTag, cardPath, cardTag, listBoards, readBoard, readCard, readCards, resolveDataDir } from './store.js'
16
24
 
17
25
  export const BOARDS_PATH = '/api/card-board/boards'
18
26
  export const BOARD_PATH = '/api/card-board/board'
27
+ export const CARD_PATH = '/api/card-board/card'
28
+ export const EVENTS_PATH = '/api/card-board/events'
29
+ export const SEEN_PATH = '/api/card-board/seen'
19
30
  export const ACTION_PATH = '/api/card-board/action'
20
31
  export const LOCALE_PATH = '/api/card-board/locale'
21
32
  const DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/
33
+ /** A comment line now and then keeps proxies from closing a quiet stream. */
34
+ export const HEARTBEAT_MS = 25_000
22
35
 
23
36
  const HEADERS = {
24
37
  'content-type': 'application/json; charset=utf-8',
@@ -39,10 +52,35 @@ const NO_PROVIDER = 'This board needs a sign-in plugin that provides requestIden
39
52
  * @param {() => object | undefined} options.identity - the requestIdentity service right now, if any
40
53
  * @param {number} options.pollSeconds
41
54
  * @param {ReturnType<import('./presses.js').createPresses>} options.presses
55
+ * @param {ReturnType<import('./seen.js').createSeenStore>} options.seen
56
+ * @param {ReturnType<import('./watch.js').createWatches>} options.watches
42
57
  * @param {(tag: string) => Promise<object>} options.messages - the page's words for a language
43
58
  * @param {string} [options.version] - mixed into ETags, so a plugin update refreshes open pages
59
+ * @param {number} [options.heartbeatMs]
44
60
  */
45
- export function createRoutes({ dataDir, people, identity, pollSeconds, presses, messages, version = '' }) {
61
+ export function createRoutes({ dataDir, people, identity, pollSeconds, presses, seen, watches, messages, version = '', heartbeatMs = HEARTBEAT_MS }) {
62
+ /** The viewer and their board, or the Response that refuses them. */
63
+ async function access(board) {
64
+ const viewer = await viewerOf(people, identity())
65
+ if (viewer.unavailable) return { refused: json(503, { error: NO_PROVIDER }) }
66
+ const root = await resolveDataDir(dataDir)
67
+ const entry = root === undefined ? undefined : await readBoard(root, board)
68
+ // In people mode a missing board and a forbidden one answer the same, so ids don't leak.
69
+ if (viewer.mode === 'people' && !maySee(viewer, entry?.board)) return { refused: json(403, { error: 'You can’t see this board.' }) }
70
+ if (entry === undefined) return { refused: json(404, { error: 'No such board.' }) }
71
+ return { viewer, root, entry, person: viewer.mode === 'owner' ? 'owner' : viewer.person }
72
+ }
73
+
74
+ /** A card entry with its versions, its press states and what is new in it for this viewer. */
75
+ function decorate(card, states, seenBoard) {
76
+ let entry = states[card.id] ? { ...card, presses: states[card.id] } : card
77
+ if (card.card === undefined) return entry
78
+ const versions = cardVersions(card.card)
79
+ entry = { ...entry, ...versions }
80
+ const fresh = freshness(seenBoard, { id: card.id, ...versions })
81
+ return fresh ? { ...entry, fresh } : entry
82
+ }
83
+
46
84
  async function locale(request) {
47
85
  const tag = new URL(request.url).searchParams.get('tag') ?? 'en'
48
86
  if (!LANGUAGE_ID.test(tag)) return json(400, { error: 'Not a language id.' })
@@ -64,20 +102,95 @@ export function createRoutes({ dataDir, people, identity, pollSeconds, presses,
64
102
  async function board(request) {
65
103
  const id = new URL(request.url).searchParams.get('id') ?? ''
66
104
  if (!ID_PATTERN.test(id)) return json(400, { error: 'Not a board id.' })
67
- const viewer = await viewerOf(people, identity())
68
- if (viewer.unavailable) return json(503, { error: NO_PROVIDER })
69
- const root = await resolveDataDir(dataDir)
70
- const entry = root === undefined ? undefined : await readBoard(root, id)
71
- // In people mode a missing board and a forbidden one answer the same, so ids don't leak.
72
- if (viewer.mode === 'people' && !maySee(viewer, entry?.board)) return json(403, { error: 'You can’t see this board.' })
73
- if (entry === undefined) return json(404, { error: 'No such board.' })
105
+ const found = await access(id)
106
+ if (found.refused) return found.refused
107
+ const { viewer, root, entry, person } = found
74
108
  const states = await pressStates(root, id)
75
- const tag = await boardTag(root, id, `${version}\0${viewer.mode}\0${viewer.person ?? ''}\0${JSON.stringify(states)}`)
109
+ const tag = await boardTag(root, id, `${version}\0${viewer.mode}\0${person ?? ''}\0${await seen.tag(person)}\0${JSON.stringify(states)}`)
76
110
  if (request.headers.get('if-none-match') === tag) return new Response(null, { status: 304, headers: { ...HEADERS, etag: tag } })
77
- const cards = (await readCards(root, id, entry.board)).map(card => (states[card.id] ? { ...card, presses: states[card.id] } : card))
111
+ const seenBoard = await seen.board(person, id)
112
+ const cards = (await readCards(root, id, entry.board)).map(card => decorate(card, states, seenBoard))
78
113
  return json(200, { id, title: entry.board?.title ?? id, ...(entry.board?.assistant ? { assistant: entry.board.assistant } : {}), problems: entry.problems, cards }, { etag: tag })
79
114
  }
80
115
 
116
+ async function card(request) {
117
+ const params = new URL(request.url).searchParams
118
+ const boardId = params.get('board') ?? ''
119
+ const id = params.get('id') ?? ''
120
+ if (!ID_PATTERN.test(boardId) || !ID_PATTERN.test(id)) return json(400, { error: 'Say which board and card.' })
121
+ const found = await access(boardId)
122
+ if (found.refused) return found.refused
123
+ const { viewer, root, entry, person } = found
124
+ const states = await pressStates(root, boardId)
125
+ const tag = await cardTag(root, boardId, id, `${version}\0${viewer.mode}\0${person ?? ''}\0${await seen.tag(person)}\0${JSON.stringify(states[id] ?? null)}`)
126
+ if (request.headers.get('if-none-match') === tag) return new Response(null, { status: 304, headers: { ...HEADERS, etag: tag } })
127
+ const one = (await readCards(root, boardId, entry.board, id))[0]
128
+ if (one === undefined) return json(404, { error: 'No such card.' })
129
+ return json(200, decorate(one, states, await seen.board(person, boardId)), { etag: tag })
130
+ }
131
+
132
+ async function events(request) {
133
+ const id = new URL(request.url).searchParams.get('board') ?? ''
134
+ if (!ID_PATTERN.test(id)) return json(400, { error: 'Not a board id.' })
135
+ const found = await access(id)
136
+ if (found.refused) return found.refused
137
+ const encoder = new TextEncoder()
138
+ let finish = () => {}
139
+ const body = new ReadableStream({
140
+ async start(controller) {
141
+ let open = true
142
+ const send = text => { if (open) controller.enqueue(encoder.encode(text)) }
143
+ const data = value => send(`data: ${JSON.stringify(value)}\n\n`)
144
+ let unwatch = () => {}
145
+ const heartbeat = setInterval(() => send(': ping\n\n'), heartbeatMs)
146
+ finish = () => {
147
+ if (!open) return
148
+ open = false
149
+ clearInterval(heartbeat)
150
+ unwatch()
151
+ request.signal?.removeEventListener?.('abort', finish)
152
+ }
153
+ request.signal?.addEventListener?.('abort', finish)
154
+ send(': connected\n\n')
155
+ unwatch = await watches.watch(join(found.root, id), async change => {
156
+ if (change.type === 'board') {
157
+ // Viewers may have changed: someone who may no longer see the board hears that and nothing else.
158
+ const again = await access(id)
159
+ if (again.refused) {
160
+ data({ type: 'gone' })
161
+ finish()
162
+ try { controller.close() } catch { /* already closed */ }
163
+ return
164
+ }
165
+ }
166
+ data(change)
167
+ })
168
+ if (!open) unwatch()
169
+ else data({ type: 'hello' })
170
+ },
171
+ cancel() { finish() },
172
+ })
173
+ return new Response(body, {
174
+ status: 200,
175
+ headers: { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache, no-transform', 'x-accel-buffering': 'no', 'x-content-type-options': 'nosniff' },
176
+ })
177
+ }
178
+
179
+ async function seenRoute(request) {
180
+ let body
181
+ try {
182
+ body = parseSeen(await request.json())
183
+ } catch {
184
+ body = undefined
185
+ }
186
+ if (body === undefined) return json(400, { error: 'The body must be { board, cards: { <id>: { v, rows? } } }.' })
187
+ const found = await access(body.board)
188
+ if (found.refused) return found.refused
189
+ const present = new Set((await readCards(found.root, body.board, found.entry.board)).map(entry => entry.id))
190
+ await seen.record(found.person, body.board, body.cards, present)
191
+ return json(200, { ok: true })
192
+ }
193
+
81
194
  /** Press states of every card on a board that has recent presses, by card id. */
82
195
  async function pressStates(root, board) {
83
196
  const cards = new Set((await presses.list()).filter(event => event.source.board === board).map(event => event.source.card))
@@ -125,6 +238,9 @@ export function createRoutes({ dataDir, people, identity, pollSeconds, presses,
125
238
  return [
126
239
  { path: BOARDS_PATH, methods: ['GET'], requestBody: 'buffered', fetch: boards },
127
240
  { path: BOARD_PATH, methods: ['GET'], requestBody: 'buffered', fetch: board },
241
+ { path: CARD_PATH, methods: ['GET'], requestBody: 'buffered', fetch: card },
242
+ { path: EVENTS_PATH, methods: ['GET'], requestBody: 'buffered', fetch: events },
243
+ { path: SEEN_PATH, methods: ['POST'], requestBody: 'buffered', fetch: seenRoute },
128
244
  { path: LOCALE_PATH, methods: ['GET'], requestBody: 'buffered', fetch: locale },
129
245
  { path: ACTION_PATH, methods: ['POST'], requestBody: 'buffered', fetch: action },
130
246
  ]
package/src/schema.js CHANGED
@@ -8,14 +8,22 @@
8
8
  * fails at write time instead of quietly not showing.
9
9
  */
10
10
 
11
- export const CARD_TYPES = Object.freeze(['stat', 'line', 'bar', 'donut', 'list', 'timeline', 'status'])
12
- export const TONES = Object.freeze(['ok', 'warn', 'bad', 'muted', 'accent'])
13
- export const ACTION_KINDS = Object.freeze(['chat', 'done', 'snooze', 'event', 'link'])
11
+ export const CARD_TYPES = Object.freeze(['summary', 'countdown', 'stat', 'line', 'bar', 'donut', 'list', 'timeline', 'status'])
12
+ export const TONES = Object.freeze(['ok', 'warn', 'bad', 'muted', 'accent', 'violet'])
13
+ /** Icon names: the page draws the ones its icon set has (Lucide names) and nothing for the rest. */
14
+ export const ICON_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/
15
+ export const ACTION_KINDS = Object.freeze(['chat', 'step', 'done', 'snooze', 'event', 'link'])
14
16
  /** Kinds the server records as events; chat and link happen in the browser only. */
15
- export const PRESS_KINDS = Object.freeze(['done', 'snooze', 'event'])
17
+ export const PRESS_KINDS = Object.freeze(['step', 'done', 'snooze', 'event'])
18
+ /** Suggested steps per card or row: a few clear next moves, not a menu. */
19
+ export const MAX_STEPS = 3
16
20
  export const ACTION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$/
21
+ /** Row keys: stable ids, so the page can tell which row changed. The same shape as action ids. */
22
+ export const KEY_PATTERN = ACTION_ID_PATTERN
17
23
  const MAX_ACTIONS = 6
18
24
  const MAX_PAYLOAD_BYTES = 4096
25
+ /** Which way a stat's change goes, for its arrow. */
26
+ export const DIRECTIONS = Object.freeze(['up', 'down', 'flat'])
19
27
  export const TIMELINE_KINDS = Object.freeze(['travel', 'due', 'event', 'health', 'home', 'money'])
20
28
  /** Board and card ids: also folder and file names, so nothing that can climb out of the data folder. */
21
29
  export const ID_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/
@@ -142,9 +150,34 @@ function tone(c, value, path) {
142
150
  c.optional(value, 'tone', v => c.oneOf(v, join(path, 'tone'), TONES))
143
151
  }
144
152
 
153
+ function icon(c, value, path) {
154
+ c.optional(value, 'icon', v => (typeof v === 'string' && v.length <= 48 && ICON_PATTERN.test(v)) || c.fail(join(path, 'icon'), 'must be an icon name like plane-takeoff'))
155
+ }
156
+
157
+ /** A window of time, `{ from, to }`, both ISO date-times with a zone, `to` after `from`. */
158
+ function timeWindow(c, value, path) {
159
+ if (!c.object(value, path, ['from', 'to'])) return
160
+ const fromOk = c.dateTime(value.from, join(path, 'from'))
161
+ const toOk = c.dateTime(value.to, join(path, 'to'))
162
+ if (fromOk && toOk && Date.parse(value.to) <= Date.parse(value.from)) c.fail(join(path, 'to'), 'must be after from')
163
+ }
164
+
165
+ /** The optional icon, tone, key and active window of a list or status row; keys must not repeat within a card. */
166
+ function rowLook(c, row, path, keys, { toneRequired = false } = {}) {
167
+ icon(c, row, path)
168
+ if (!toneRequired) tone(c, row, path)
169
+ c.optional(row, 'key', v => {
170
+ if (typeof v !== 'string' || !KEY_PATTERN.test(v)) return c.fail(join(path, 'key'), 'must be letters, digits and . _ : - (up to 100), starting with a letter or digit')
171
+ if (keys.has(v)) return c.fail(join(path, 'key'), 'repeats another row\'s key')
172
+ keys.add(v)
173
+ })
174
+ c.optional(row, 'active', v => timeWindow(c, v, join(path, 'active')))
175
+ }
176
+
145
177
  /** Problems with an `actions` list (on a card, a list row or a status row). */
146
178
  function actions(c, list, path) {
147
179
  if (!c.array(list, path, { max: MAX_ACTIONS })) return
180
+ if (list.filter(action => action?.kind === 'step').length > MAX_STEPS) c.fail(path, `has more than ${MAX_STEPS} steps`)
148
181
  const seen = new Set()
149
182
  list.forEach((action, i) => {
150
183
  const p = join(path, i)
@@ -153,8 +186,8 @@ function actions(c, list, path) {
153
186
  if (typeof action.id !== 'string' || !ACTION_ID_PATTERN.test(action.id)) c.fail(join(p, 'id'), 'must be letters, digits and . _ : - (up to 100), starting with a letter or digit')
154
187
  else if (seen.has(action.id)) c.fail(join(p, 'id'), 'repeats another action id here')
155
188
  else seen.add(action.id)
156
- if ('label' in action) c.label(action.label, join(p, 'label'), { max: 40 })
157
- else if (action.kind === 'event') c.fail(join(p, 'label'), 'is required for an event action')
189
+ if ('label' in action) c.label(action.label, join(p, 'label'), { max: action.kind === 'step' ? 80 : 40 })
190
+ else if (action.kind === 'event' || action.kind === 'step') c.fail(join(p, 'label'), `is required for ${action.kind === 'step' ? 'a step: it says the step plainly' : 'an event action'}`)
158
191
  const payload = action.payload
159
192
  if ('payload' in action) {
160
193
  const pp = join(p, 'payload')
@@ -166,7 +199,7 @@ function actions(c, list, path) {
166
199
  if (!isSafeLink(payload?.url)) c.fail(join(join(p, 'payload'), 'url'), 'is required: an http(s) URL or a path starting with /')
167
200
  }
168
201
  if (action.kind === 'snooze' && payload !== undefined && 'until' in payload) c.dateTime(payload.until, join(join(p, 'payload'), 'until'))
169
- if (action.kind === 'chat' && payload !== undefined) {
202
+ if ((action.kind === 'chat' || action.kind === 'step') && payload !== undefined) {
170
203
  const pp = join(p, 'payload')
171
204
  if ('prompt' in payload) c.label(payload.prompt, join(pp, 'prompt'), { max: 2000 })
172
205
  if ('session' in payload) c.text(payload.session, join(pp, 'session'), { max: 200 })
@@ -179,7 +212,7 @@ function statData(c, data, path) {
179
212
  if (!c.array(data.items, join(path, 'items'), { min: 1, max: 6 })) return
180
213
  data.items.forEach((item, i) => {
181
214
  const p = join(join(path, 'items'), i)
182
- if (!c.object(item, p, ['label', 'value'], ['unit', 'delta', 'sub', 'tone'])) return
215
+ if (!c.object(item, p, ['label', 'value'], ['unit', 'delta', 'sub', 'tone', 'spark', 'progress', 'strip'])) return
183
216
  c.label(item.label, join(p, 'label'))
184
217
  c.labelOrNumber(item.value, join(p, 'value'))
185
218
  c.optional(item, 'unit', v => c.label(v, join(p, 'unit'), { max: 20 }))
@@ -187,10 +220,32 @@ function statData(c, data, path) {
187
220
  tone(c, item, p)
188
221
  c.optional(item, 'delta', delta => {
189
222
  const dp = join(p, 'delta')
190
- if (!c.object(delta, dp, ['value'], ['unit', 'tone'])) return
191
- c.number(delta.value, join(dp, 'value'))
192
- c.optional(delta, 'unit', v => c.label(v, join(dp, 'unit'), { max: 20 }))
223
+ if (!c.object(delta, dp, ['text'], ['tone', 'dir'])) return
224
+ c.label(delta.text, join(dp, 'text'), { max: 80 })
193
225
  tone(c, delta, dp)
226
+ c.optional(delta, 'dir', v => c.oneOf(v, join(dp, 'dir'), DIRECTIONS))
227
+ })
228
+ c.optional(item, 'spark', spark => {
229
+ if (!c.array(spark, join(p, 'spark'), { min: 2, max: 400 })) return
230
+ spark.forEach((v, j) => v === null || c.number(v, join(join(p, 'spark'), j)))
231
+ })
232
+ c.optional(item, 'progress', progress => {
233
+ const pp = join(p, 'progress')
234
+ if (!c.object(progress, pp, ['value', 'max'], ['text'])) return
235
+ c.number(progress.value, join(pp, 'value'), { min: 0 })
236
+ c.number(progress.max, join(pp, 'max'), { min: 0 })
237
+ c.optional(progress, 'text', v => c.label(v, join(pp, 'text')))
238
+ })
239
+ c.optional(item, 'strip', strip => {
240
+ if (!c.array(strip, join(p, 'strip'), { min: 1, max: 24 })) return
241
+ strip.forEach((cell, j) => {
242
+ const sp = join(join(p, 'strip'), j)
243
+ if (!c.object(cell, sp, ['label', 'value'], ['icon', 'on'])) return
244
+ c.label(cell.label, join(sp, 'label'), { max: 20 })
245
+ c.labelOrNumber(cell.value, join(sp, 'value'))
246
+ icon(c, cell, sp)
247
+ c.optional(cell, 'on', v => c.boolean(v, join(sp, 'on')))
248
+ })
194
249
  })
195
250
  })
196
251
  }
@@ -288,10 +343,12 @@ function donutData(c, data, path) {
288
343
 
289
344
  function listData(c, data, path) {
290
345
  if (!c.object(data, path, ['rows'], ['empty', 'progress'])) return
346
+ const keys = new Set()
291
347
  if (c.array(data.rows, join(path, 'rows'), { max: 100 }))
292
348
  data.rows.forEach((row, i) => {
293
349
  const p = join(join(path, 'rows'), i)
294
- if (!c.object(row, p, ['title'], ['sub', 'chip', 'checked', 'date', 'actions'])) return
350
+ if (!c.object(row, p, ['title'], ['sub', 'chip', 'checked', 'date', 'actions', 'icon', 'tone', 'key', 'active'])) return
351
+ rowLook(c, row, p, keys)
295
352
  c.optional(row, 'actions', v => actions(c, v, join(p, 'actions')))
296
353
  c.label(row.title, join(p, 'title'))
297
354
  c.optional(row, 'sub', v => c.label(v, join(p, 'sub')))
@@ -307,11 +364,12 @@ function listData(c, data, path) {
307
364
  c.optional(data, 'empty', v => c.label(v, join(path, 'empty')))
308
365
  c.optional(data, 'progress', progress => {
309
366
  const p = join(path, 'progress')
310
- if (!c.object(progress, p, ['done', 'total'], ['label'])) return
367
+ if (!c.object(progress, p, ['done', 'total'], ['label', 'sub'])) return
311
368
  const done = c.number(progress.done, join(p, 'done'), { min: 0 })
312
369
  const total = c.number(progress.total, join(p, 'total'), { min: 0 })
313
370
  if (done && total && progress.done > progress.total) c.fail(join(p, 'done'), 'must not be more than total')
314
371
  c.optional(progress, 'label', v => c.label(v, join(p, 'label'), { max: 40 }))
372
+ c.optional(progress, 'sub', v => c.label(v, join(p, 'sub')))
315
373
  })
316
374
  }
317
375
 
@@ -348,9 +406,11 @@ function timelineData(c, data, path) {
348
406
  function statusData(c, data, path) {
349
407
  if (!c.object(data, path, ['rows'])) return
350
408
  if (!c.array(data.rows, join(path, 'rows'), { min: 1, max: 50 })) return
409
+ const keys = new Set()
351
410
  data.rows.forEach((row, i) => {
352
411
  const p = join(join(path, 'rows'), i)
353
- if (!c.object(row, p, ['label', 'value', 'tone'], ['sub', 'spark', 'actions'])) return
412
+ if (!c.object(row, p, ['label', 'value', 'tone'], ['sub', 'spark', 'actions', 'icon', 'key', 'active'])) return
413
+ rowLook(c, row, p, keys, { toneRequired: true })
354
414
  c.optional(row, 'actions', v => actions(c, v, join(p, 'actions')))
355
415
  c.label(row.label, join(p, 'label'))
356
416
  c.labelOrNumber(row.value, join(p, 'value'))
@@ -363,7 +423,55 @@ function statusData(c, data, path) {
363
423
  })
364
424
  }
365
425
 
366
- const DATA = { stat: statData, line: lineData, bar: barData, donut: donutData, list: listData, timeline: timelineData, status: statusData }
426
+ function summaryData(c, data, path) {
427
+ if (!c.object(data, path, ['text'], ['chips'])) return
428
+ c.label(data.text, join(path, 'text'), { max: 400 })
429
+ c.optional(data, 'chips', chips => {
430
+ if (!c.array(chips, join(path, 'chips'), { max: 8 })) return
431
+ chips.forEach((chip, i) => {
432
+ const p = join(join(path, 'chips'), i)
433
+ if (!c.object(chip, p, ['text'], ['icon', 'tone', 'to'])) return
434
+ c.label(chip.text, join(p, 'text'), { max: 60 })
435
+ icon(c, chip, p)
436
+ tone(c, chip, p)
437
+ c.optional(chip, 'to', v => c.dateTime(v, join(p, 'to')))
438
+ })
439
+ })
440
+ }
441
+
442
+ function countdownData(c, data, path) {
443
+ if (!c.object(data, path, ['to', 'label'], ['sub', 'steps', 'expiresAt'])) return
444
+ const toOk = c.dateTime(data.to, join(path, 'to'))
445
+ c.label(data.label, join(path, 'label'))
446
+ c.optional(data, 'sub', v => c.label(v, join(path, 'sub')))
447
+ c.optional(data, 'expiresAt', v => {
448
+ if (c.dateTime(v, join(path, 'expiresAt')) && toOk && Date.parse(v) < Date.parse(data.to)) c.fail(join(path, 'expiresAt'), 'must not be before to')
449
+ })
450
+ c.optional(data, 'steps', steps => {
451
+ if (!c.array(steps, join(path, 'steps'), { min: 1, max: 8 })) return
452
+ steps.forEach((step, i) => {
453
+ const p = join(join(path, 'steps'), i)
454
+ if (!c.object(step, p, ['at', 'label'], ['sub', 'zone'])) return
455
+ c.dateTime(step.at, join(p, 'at'))
456
+ c.label(step.label, join(p, 'label'), { max: 80 })
457
+ c.optional(step, 'sub', v => c.label(v, join(p, 'sub'), { max: 80 }))
458
+ c.optional(step, 'zone', v => (typeof v === 'string' && isTimeZone(v)) || c.fail(join(p, 'zone'), 'must be an IANA time zone like Europe/Paris'))
459
+ })
460
+ })
461
+ }
462
+
463
+ /** A time zone name this runtime knows. */
464
+ function isTimeZone(value) {
465
+ if (value.length > 64) return false
466
+ try {
467
+ new Intl.DateTimeFormat('en', { timeZone: value })
468
+ return true
469
+ } catch {
470
+ return false
471
+ }
472
+ }
473
+
474
+ const DATA = { summary: summaryData, countdown: countdownData, stat: statData, line: lineData, bar: barData, donut: donutData, list: listData, timeline: timelineData, status: statusData }
367
475
 
368
476
  /** Links a card may open: web pages and paths on the same site, nothing that runs script. */
369
477
  export function isSafeLink(value) {
@@ -380,14 +488,16 @@ export function isSafeLink(value) {
380
488
  /** Problems with one card file's parsed content. */
381
489
  export function checkCard(card) {
382
490
  const c = new Check()
383
- if (!c.object(card, '', ['type', 'title', 'updatedAt', 'data'], ['staleAfter', 'link', 'stat', 'actions'])) return c.problems
491
+ if (!c.object(card, '', ['type', 'title', 'updatedAt', 'data'], ['staleAfter', 'link', 'stat', 'actions', 'icon', 'tone'])) return c.problems
384
492
  if (!c.oneOf(card.type, 'type', CARD_TYPES)) return c.problems
385
493
  c.label(card.title, 'title', { max: 120 })
386
494
  c.dateTime(card.updatedAt, 'updatedAt')
495
+ icon(c, card, '')
496
+ tone(c, card, '')
387
497
  c.optional(card, 'staleAfter', v => c.number(v, 'staleAfter', { min: 1 }))
388
498
  c.optional(card, 'link', v => isSafeLink(v) || c.fail('link', 'must be an http(s) URL or a path starting with /'))
389
499
  c.optional(card, 'stat', v => {
390
- if (card.type === 'stat') return c.fail('stat', 'is for chart cards; a stat card has its numbers in data')
500
+ if (['stat', 'summary', 'countdown'].includes(card.type)) return c.fail('stat', `doesn't go on a ${card.type} card; it heads a card's chart or rows`)
391
501
  statData(c, v, 'stat')
392
502
  })
393
503
  c.optional(card, 'actions', v => actions(c, v, 'actions'))
package/src/seen.js ADDED
@@ -0,0 +1,111 @@
1
+ /**
2
+ * "New since you last looked", kept per person on the server so it holds
3
+ * across devices.
4
+ *
5
+ * Each card has a content version (a hash of the card without `updatedAt`, so
6
+ * a producer rewriting the same data changes nothing), and each list or status
7
+ * row with a `key` has its own. The page tells the server which versions the
8
+ * person has seen; a later version is new for them. A person who never looked
9
+ * at a board sees nothing marked new there.
10
+ *
11
+ * <dataDir>/.seen/<hash of the person>.json
12
+ * { "boards": { "<board>": { "<card>": { "v": "…", "rows": { "<key>": "…" } } } } }
13
+ */
14
+ import { createHash } from 'node:crypto'
15
+ import { mkdir, readFile, rename, stat, writeFile } from 'node:fs/promises'
16
+ import { join } from 'node:path'
17
+ import { ID_PATTERN, KEY_PATTERN } from './schema.js'
18
+
19
+ const VERSION = /^[A-Za-z0-9_-]{1,32}$/
20
+ const MAX_ROWS = 100
21
+
22
+ function hash(value) {
23
+ return createHash('sha256').update(JSON.stringify(value)).digest('base64url').slice(0, 12)
24
+ }
25
+
26
+ /** The content version of a card, and of each of its keyed rows. */
27
+ export function cardVersions(card) {
28
+ const { updatedAt, ...content } = card
29
+ const rows = {}
30
+ if (card.type === 'list' || card.type === 'status') for (const row of card.data?.rows ?? []) if (typeof row.key === 'string') rows[row.key] = hash(row)
31
+ return Object.keys(rows).length > 0 ? { version: hash(content), rows } : { version: hash(content) }
32
+ }
33
+
34
+ /**
35
+ * What is new for a person in one card: `{ card: true }` when its version differs from the one they saw (or they
36
+ * never saw the card), with `rows` listing keyed rows that are new or changed. Undefined when nothing is new, or
37
+ * when they have never looked at the board at all.
38
+ */
39
+ export function freshness(seenBoard, versions) {
40
+ if (seenBoard === undefined) return undefined
41
+ const seen = seenBoard[versions.id]
42
+ if (seen === undefined) return { card: true, rows: [] }
43
+ if (seen.v === versions.version) return undefined
44
+ const rows = Object.entries(versions.rows ?? {}).filter(([key, v]) => seen.rows?.[key] !== v).map(([key]) => key)
45
+ return { card: true, rows }
46
+ }
47
+
48
+ /** The body of a "seen" report from the page, checked: `{ board, cards: { <id>: { v, rows? } } }`; undefined when malformed. */
49
+ export function parseSeen(body) {
50
+ if (typeof body !== 'object' || body === null || typeof body.board !== 'string' || !ID_PATTERN.test(body.board)) return undefined
51
+ const cards = body.cards
52
+ if (typeof cards !== 'object' || cards === null || Array.isArray(cards) || Object.keys(cards).length > 100) return undefined
53
+ const clean = {}
54
+ for (const [id, seen] of Object.entries(cards)) {
55
+ if (!ID_PATTERN.test(id) || typeof seen?.v !== 'string' || !VERSION.test(seen.v)) return undefined
56
+ const rows = {}
57
+ const given = seen.rows ?? {}
58
+ if (typeof given !== 'object' || given === null || Object.keys(given).length > MAX_ROWS) return undefined
59
+ for (const [key, v] of Object.entries(given)) {
60
+ if (!KEY_PATTERN.test(key) || typeof v !== 'string' || !VERSION.test(v)) return undefined
61
+ rows[key] = v
62
+ }
63
+ clean[id] = Object.keys(rows).length > 0 ? { v: seen.v, rows } : { v: seen.v }
64
+ }
65
+ return { board: body.board, cards: clean }
66
+ }
67
+
68
+ /** The seen marks of every person, one small file each, written one at a time and atomically. */
69
+ export function createSeenStore(dir) {
70
+ const fileOf = person => join(dir, `${hash(String(person).toLowerCase())}.json`)
71
+ const queues = new Map()
72
+
73
+ async function readFileOf(person) {
74
+ try {
75
+ const value = JSON.parse(await readFile(fileOf(person), 'utf8'))
76
+ return typeof value?.boards === 'object' && value.boards !== null ? value : { boards: {} }
77
+ } catch {
78
+ return { boards: {} }
79
+ }
80
+ }
81
+
82
+ return {
83
+ /** What a person has seen on a board, by card id; undefined when they never looked at it. */
84
+ async board(person, board) {
85
+ return (await readFileOf(person)).boards[board]
86
+ },
87
+
88
+ /** A tag that changes whenever this person's marks change, for ETags. */
89
+ async tag(person) {
90
+ const info = await stat(fileOf(person)).catch(() => undefined)
91
+ return info ? `${info.size}:${info.mtimeMs}` : '-'
92
+ },
93
+
94
+ /** Record cards a person has seen on a board, keeping only cards that still exist (`present`). */
95
+ record(person, board, cards, present) {
96
+ const path = fileOf(person)
97
+ const previous = queues.get(path) ?? Promise.resolve()
98
+ const next = previous.catch(() => {}).then(async () => {
99
+ const value = await readFileOf(person)
100
+ const kept = Object.fromEntries(Object.entries({ ...value.boards[board], ...cards }).filter(([id]) => present.has(id)))
101
+ value.boards[board] = kept
102
+ await mkdir(dir, { recursive: true, mode: 0o700 })
103
+ const tmp = `${path}.${process.pid}.tmp`
104
+ await writeFile(tmp, JSON.stringify(value), { mode: 0o600 })
105
+ await rename(tmp, path)
106
+ })
107
+ queues.set(path, next)
108
+ return next.finally(() => { if (queues.get(path) === next) queues.delete(path) })
109
+ },
110
+ }
111
+ }
package/src/store.js CHANGED
@@ -116,6 +116,16 @@ export async function boardTag(root, id, salt = '') {
116
116
  return `W/"${hash.digest('base64url').slice(0, 27)}"`
117
117
  }
118
118
 
119
+ /** A cheap version tag for one card: its file, board.json (the card's size lives there) and `salt`. */
120
+ export async function cardTag(root, board, card, salt = '') {
121
+ const hash = createHash('sha256').update(salt)
122
+ for (const path of [join(root, board, 'board.json'), cardPath(root, board, card)]) {
123
+ const info = await stat(path).catch(() => undefined)
124
+ hash.update(`${info ? `${info.size}:${info.mtimeMs}` : '-'}\n`)
125
+ }
126
+ return `W/"${hash.digest('base64url').slice(0, 27)}"`
127
+ }
128
+
119
129
  /** The path of a card file (ids already checked). */
120
130
  export function cardPath(root, board, card) {
121
131
  return join(root, board, 'cards', `${card}.json`)
@@ -128,11 +138,15 @@ export async function readCard(root, board, card) {
128
138
  return result.problems.length === 0 ? result.value : undefined
129
139
  }
130
140
 
131
- /** Every card of a board in order, each with its size on the grid and either the card or its problems. */
132
- export async function readCards(root, id, board) {
141
+ /**
142
+ * Every card of a board in order, each with its size on the grid and either the card or its problems; with `only`,
143
+ * just that card (an empty list when it isn't there).
144
+ */
145
+ export async function readCards(root, id, board, only) {
133
146
  const layout = board?.layout ?? {}
134
147
  const cards = []
135
- for (const card of await cardFiles(root, id, board?.order)) {
148
+ const ids = await cardFiles(root, id, board?.order)
149
+ for (const card of only === undefined ? ids : ids.filter(card => card === only)) {
136
150
  const size = { w: layout[card]?.w ?? 1, h: layout[card]?.h ?? 1 }
137
151
  const result = await readJson(root, join(root, id, 'cards', `${card}.json`), MAX_CARD_BYTES, checkCard)
138
152
  cards.push(result.problems.length > 0 ? { id: card, ...size, problems: result.problems.slice(0, 5) } : { id: card, ...size, card: result.value })