@soffits/dsh-card-board 0.0.0-stage → 0.2.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 ADDED
@@ -0,0 +1,121 @@
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.
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
+ * POST /api/card-board/action press a done, snooze or event action
10
+ */
11
+ import { maySee, viewerOf } from './access.js'
12
+ import { ID_PATTERN, PRESS_KINDS, findAction } from './schema.js'
13
+ import { boardTag, cardPath, listBoards, readBoard, readCard, readCards, resolveDataDir } from './store.js'
14
+
15
+ export const BOARDS_PATH = '/api/card-board/boards'
16
+ export const BOARD_PATH = '/api/card-board/board'
17
+ export const ACTION_PATH = '/api/card-board/action'
18
+ const DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/
19
+
20
+ const HEADERS = {
21
+ 'content-type': 'application/json; charset=utf-8',
22
+ 'cache-control': 'private, no-cache',
23
+ 'x-content-type-options': 'nosniff',
24
+ }
25
+
26
+ function json(status, body, extra = {}) {
27
+ return new Response(JSON.stringify(body), { status, headers: { ...HEADERS, ...extra } })
28
+ }
29
+
30
+ const NO_PROVIDER = 'This board needs a sign-in plugin that provides requestIdentity, and none is running.'
31
+
32
+ /**
33
+ * @param {object} options
34
+ * @param {string} options.dataDir - the data folder (absolute)
35
+ * @param {ReturnType<import('./access.js').createPeople>} options.people
36
+ * @param {() => object | undefined} options.identity - the requestIdentity service right now, if any
37
+ * @param {number} options.pollSeconds
38
+ * @param {ReturnType<import('./presses.js').createPresses>} options.presses
39
+ * @param {string} [options.ownerPerson] - the person for requests DSH admits without a sign-in identity
40
+ * @param {string} [options.version] - mixed into ETags, so a plugin update refreshes open pages
41
+ */
42
+ export function createRoutes({ dataDir, people, identity, pollSeconds, presses, ownerPerson = '', version = '' }) {
43
+ async function boards() {
44
+ const viewer = await viewerOf(people, identity(), ownerPerson)
45
+ if (viewer.unavailable) return json(503, { error: NO_PROVIDER })
46
+ const root = await resolveDataDir(dataDir)
47
+ const visible = root === undefined ? [] : (await listBoards(root)).filter(entry => viewer.mode === 'owner' || maySee(viewer, entry.board))
48
+ return json(200, {
49
+ mode: viewer.mode,
50
+ pollSeconds,
51
+ boards: visible.map(entry => ({ id: entry.id, title: entry.board?.title ?? entry.id })),
52
+ })
53
+ }
54
+
55
+ async function board(request) {
56
+ const id = new URL(request.url).searchParams.get('id') ?? ''
57
+ if (!ID_PATTERN.test(id)) return json(400, { error: 'Not a board id.' })
58
+ const viewer = await viewerOf(people, identity(), ownerPerson)
59
+ if (viewer.unavailable) return json(503, { error: NO_PROVIDER })
60
+ const root = await resolveDataDir(dataDir)
61
+ const entry = root === undefined ? undefined : await readBoard(root, id)
62
+ // In people mode a missing board and a forbidden one answer the same, so ids don't leak.
63
+ if (viewer.mode === 'people' && !maySee(viewer, entry?.board)) return json(403, { error: 'You can’t see this board.' })
64
+ if (entry === undefined) return json(404, { error: 'No such board.' })
65
+ const states = await pressStates(root, id)
66
+ const tag = await boardTag(root, id, `${version}\0${viewer.mode}\0${viewer.person ?? ''}\0${JSON.stringify(states)}`)
67
+ if (request.headers.get('if-none-match') === tag) return new Response(null, { status: 304, headers: { ...HEADERS, etag: tag } })
68
+ const cards = (await readCards(root, id, entry.board)).map(card => (states[card.id] ? { ...card, presses: states[card.id] } : card))
69
+ return json(200, { id, title: entry.board?.title ?? id, problems: entry.problems, cards }, { etag: tag })
70
+ }
71
+
72
+ /** Press states of every card on a board that has recent presses, by card id. */
73
+ async function pressStates(root, board) {
74
+ const cards = new Set((await presses.list()).filter(event => event.source.board === board).map(event => event.source.card))
75
+ const states = {}
76
+ for (const card of [...cards].sort()) {
77
+ if (!ID_PATTERN.test(card)) continue
78
+ states[card] = await presses.statesFor(board, card, cardPath(root, board, card))
79
+ }
80
+ return states
81
+ }
82
+
83
+ async function action(request) {
84
+ let body
85
+ try {
86
+ body = await request.json()
87
+ } catch {
88
+ return json(400, { error: 'The body must be JSON.' })
89
+ }
90
+ const { board, card, row, id, until } = body ?? {}
91
+ if (typeof board !== 'string' || !ID_PATTERN.test(board) || typeof card !== 'string' || !ID_PATTERN.test(card) || typeof id !== 'string')
92
+ return json(400, { error: 'Say which board, card and action.' })
93
+ if (row !== undefined && !(Number.isInteger(row) && row >= 0)) return json(400, { error: 'row must be a row index.' })
94
+ if (until !== undefined && (typeof until !== 'string' || !DATE_TIME.test(until) || Number.isNaN(Date.parse(until))))
95
+ return json(400, { error: 'until must be an ISO date-time with a zone.' })
96
+ const viewer = await viewerOf(people, identity(), ownerPerson)
97
+ if (viewer.unavailable) return json(503, { error: NO_PROVIDER })
98
+ const root = await resolveDataDir(dataDir)
99
+ const entry = root === undefined ? undefined : await readBoard(root, board)
100
+ if (!maySee(viewer, entry?.board) || entry === undefined) return json(403, { error: 'You can’t act on this board.' })
101
+ const found = findAction(await readCard(root, board, card), id, row)
102
+ if (found === undefined || !PRESS_KINDS.includes(found.kind)) return json(409, { error: 'This action isn’t on the card any more.' })
103
+ const payload = { ...(found.payload ?? {}), ...(found.kind === 'snooze' && until !== undefined && found.payload?.until === undefined ? { until } : {}) }
104
+ const event = await presses.press({
105
+ action: found,
106
+ person: viewer.mode === 'owner' ? 'owner' : viewer.person,
107
+ user: identity()?.current?.()?.id,
108
+ board,
109
+ card,
110
+ row,
111
+ payload,
112
+ })
113
+ return json(200, { press: event.press, state: 'pending', at: event.at })
114
+ }
115
+
116
+ return [
117
+ { path: BOARDS_PATH, methods: ['GET'], requestBody: 'buffered', fetch: boards },
118
+ { path: BOARD_PATH, methods: ['GET'], requestBody: 'buffered', fetch: board },
119
+ { path: ACTION_PATH, methods: ['POST'], requestBody: 'buffered', fetch: action },
120
+ ]
121
+ }
package/src/schema.js ADDED
@@ -0,0 +1,412 @@
1
+ /**
2
+ * The card and board file format, checked the same way by the plugin when it
3
+ * reads a file and by the CLI before it writes one. Plain functions, no
4
+ * dependencies, so producers can also import it directly.
5
+ *
6
+ * Every check returns a list of problems as `path: what is wrong`; an empty
7
+ * list means the value is valid. Unknown fields are problems too, so a typo
8
+ * fails at write time instead of quietly not showing.
9
+ */
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'])
14
+ /** Kinds the server records as events; chat and link happen in the browser only. */
15
+ export const PRESS_KINDS = Object.freeze(['done', 'snooze', 'event'])
16
+ export const ACTION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,99}$/
17
+ const MAX_ACTIONS = 6
18
+ const MAX_PAYLOAD_BYTES = 4096
19
+ export const TIMELINE_KINDS = Object.freeze(['travel', 'due', 'event', 'health', 'home', 'money'])
20
+ /** Board and card ids: also folder and file names, so nothing that can climb out of the data folder. */
21
+ export const ID_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/
22
+ export const MAX_CARD_BYTES = 256 * 1024
23
+
24
+ const MAX_TEXT = 200
25
+ const MAX_ITEMS = 500
26
+ const MAX_POINTS = 2000
27
+ const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/
28
+ const DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/
29
+
30
+ /** A small builder that collects problems with their paths. A missing required field is reported once, by object(), so the checks of its value skip undefined. */
31
+ class Check {
32
+ constructor() {
33
+ this.problems = []
34
+ }
35
+
36
+ fail(path, message) {
37
+ this.problems.push(`${path || '(root)'}: ${message}`)
38
+ return false
39
+ }
40
+
41
+ object(value, path, required, optional = []) {
42
+ if (value === undefined) return false
43
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return this.fail(path, 'must be an object')
44
+ for (const key of required) if (!(key in value)) this.fail(join(path, key), 'is required')
45
+ const known = new Set([...required, ...optional])
46
+ for (const key of Object.keys(value)) if (!known.has(key)) this.fail(join(path, key), 'is not a known field')
47
+ return true
48
+ }
49
+
50
+ array(value, path, { min = 0, max = MAX_ITEMS } = {}) {
51
+ if (value === undefined) return false
52
+ if (!Array.isArray(value)) return this.fail(path, 'must be an array')
53
+ if (value.length < min) return this.fail(path, `needs at least ${min} item${min === 1 ? '' : 's'}`)
54
+ if (value.length > max) return this.fail(path, `has more than ${max} items`)
55
+ return true
56
+ }
57
+
58
+ text(value, path, { max = MAX_TEXT, empty = false } = {}) {
59
+ if (value === undefined) return false
60
+ if (typeof value !== 'string') return this.fail(path, 'must be a string')
61
+ if (!empty && value.trim() === '') return this.fail(path, 'must not be empty')
62
+ if (value.length > max) return this.fail(path, `is longer than ${max} characters`)
63
+ return true
64
+ }
65
+
66
+ number(value, path, { min = -Infinity } = {}) {
67
+ if (value === undefined) return false
68
+ if (typeof value !== 'number' || !Number.isFinite(value)) return this.fail(path, 'must be a finite number')
69
+ if (value < min) return this.fail(path, `must be at least ${min}`)
70
+ return true
71
+ }
72
+
73
+ boolean(value, path) {
74
+ if (value === undefined) return false
75
+ return typeof value === 'boolean' || this.fail(path, 'must be true or false')
76
+ }
77
+
78
+ oneOf(value, path, allowed) {
79
+ if (value === undefined) return false
80
+ return allowed.includes(value) || this.fail(path, `must be one of ${allowed.join(', ')}`)
81
+ }
82
+
83
+ textOrNumber(value, path) {
84
+ if (value === undefined) return false
85
+ if (typeof value === 'number') return this.number(value, path)
86
+ return this.text(value, path)
87
+ }
88
+
89
+ date(value, path) {
90
+ if (value === undefined) return false
91
+ if (typeof value !== 'string' || !(DATE_ONLY.test(value) || DATE_TIME.test(value)) || Number.isNaN(Date.parse(value)))
92
+ return this.fail(path, 'must be a date (YYYY-MM-DD) or an ISO date-time with a zone')
93
+ return true
94
+ }
95
+
96
+ dateTime(value, path) {
97
+ if (value === undefined) return false
98
+ if (typeof value !== 'string' || !DATE_TIME.test(value) || Number.isNaN(Date.parse(value)))
99
+ return this.fail(path, 'must be an ISO date-time with a zone, like 2026-03-02T09:30:00Z')
100
+ return true
101
+ }
102
+
103
+ optional(value, key, fn) {
104
+ if (key in value) fn(value[key])
105
+ }
106
+ }
107
+
108
+ function join(path, key) {
109
+ if (typeof key === 'number') return `${path}[${key}]`
110
+ return path ? `${path}.${key}` : key
111
+ }
112
+
113
+ function tone(c, value, path) {
114
+ c.optional(value, 'tone', v => c.oneOf(v, join(path, 'tone'), TONES))
115
+ }
116
+
117
+ /** Problems with an `actions` list (on a card, a list row or a status row). */
118
+ function actions(c, list, path) {
119
+ if (!c.array(list, path, { max: MAX_ACTIONS })) return
120
+ const seen = new Set()
121
+ list.forEach((action, i) => {
122
+ const p = join(path, i)
123
+ if (!c.object(action, p, ['kind', 'id'], ['label', 'payload'])) return
124
+ const kindOk = c.oneOf(action.kind, join(p, 'kind'), ACTION_KINDS)
125
+ 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')
126
+ else if (seen.has(action.id)) c.fail(join(p, 'id'), 'repeats another action id here')
127
+ else seen.add(action.id)
128
+ if ('label' in action) c.text(action.label, join(p, 'label'), { max: 40 })
129
+ else if (action.kind === 'event') c.fail(join(p, 'label'), 'is required for an event action')
130
+ const payload = action.payload
131
+ if ('payload' in action) {
132
+ const pp = join(p, 'payload')
133
+ if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) return c.fail(pp, 'must be an object')
134
+ if (Buffer.byteLength(JSON.stringify(payload)) > MAX_PAYLOAD_BYTES) c.fail(pp, `is larger than ${MAX_PAYLOAD_BYTES} bytes`)
135
+ }
136
+ if (!kindOk) return
137
+ if (action.kind === 'link') {
138
+ if (!isSafeLink(payload?.url)) c.fail(join(join(p, 'payload'), 'url'), 'is required: an http(s) URL or a path starting with /')
139
+ }
140
+ if (action.kind === 'snooze' && payload !== undefined && 'until' in payload) c.dateTime(payload.until, join(join(p, 'payload'), 'until'))
141
+ if (action.kind === 'chat' && payload !== undefined) {
142
+ const pp = join(p, 'payload')
143
+ if ('prompt' in payload) c.text(payload.prompt, join(pp, 'prompt'), { max: 2000 })
144
+ if ('session' in payload) c.text(payload.session, join(pp, 'session'), { max: 200 })
145
+ }
146
+ })
147
+ }
148
+
149
+ function statData(c, data, path) {
150
+ if (!c.object(data, path, ['items'])) return
151
+ if (!c.array(data.items, join(path, 'items'), { min: 1, max: 6 })) return
152
+ data.items.forEach((item, i) => {
153
+ const p = join(join(path, 'items'), i)
154
+ if (!c.object(item, p, ['label', 'value'], ['unit', 'delta', 'sub', 'tone'])) return
155
+ c.text(item.label, join(p, 'label'))
156
+ c.textOrNumber(item.value, join(p, 'value'))
157
+ c.optional(item, 'unit', v => c.text(v, join(p, 'unit'), { max: 20 }))
158
+ c.optional(item, 'sub', v => c.text(v, join(p, 'sub')))
159
+ tone(c, item, p)
160
+ c.optional(item, 'delta', delta => {
161
+ const dp = join(p, 'delta')
162
+ if (!c.object(delta, dp, ['value'], ['unit', 'tone'])) return
163
+ c.number(delta.value, join(dp, 'value'))
164
+ c.optional(delta, 'unit', v => c.text(v, join(dp, 'unit'), { max: 20 }))
165
+ tone(c, delta, dp)
166
+ })
167
+ })
168
+ }
169
+
170
+ function points(c, list, path) {
171
+ if (!c.array(list, path, { min: 1, max: MAX_POINTS })) return
172
+ list.forEach((point, i) => {
173
+ const p = join(path, i)
174
+ if (!c.object(point, p, ['x', 'y'])) return
175
+ c.textOrNumber(point.x, join(p, 'x'))
176
+ if (point.y !== null) c.number(point.y, join(p, 'y'))
177
+ })
178
+ }
179
+
180
+ function goalLine(c, goal, path, allowPoints) {
181
+ if (typeof goal !== 'object' || goal === null) return c.fail(path, 'must be an object')
182
+ if (allowPoints && 'points' in goal) {
183
+ if (!c.object(goal, path, ['points'], ['label'])) return
184
+ points(c, goal.points, join(path, 'points'))
185
+ } else {
186
+ if (!c.object(goal, path, ['y'], ['label'])) return
187
+ c.number(goal.y, join(path, 'y'))
188
+ }
189
+ c.optional(goal, 'label', v => c.text(v, join(path, 'label')))
190
+ }
191
+
192
+ function lineData(c, data, path) {
193
+ if (!c.object(data, path, ['series'], ['unit', 'area', 'goal', 'markers'])) return
194
+ if (c.array(data.series, join(path, 'series'), { min: 1, max: 6 }))
195
+ data.series.forEach((series, i) => {
196
+ const p = join(join(path, 'series'), i)
197
+ if (!c.object(series, p, ['name', 'points'], ['tone'])) return
198
+ c.text(series.name, join(p, 'name'), { empty: true })
199
+ points(c, series.points, join(p, 'points'))
200
+ tone(c, series, p)
201
+ })
202
+ c.optional(data, 'unit', v => c.text(v, join(path, 'unit'), { max: 20 }))
203
+ c.optional(data, 'area', v => c.boolean(v, join(path, 'area')))
204
+ c.optional(data, 'goal', v => goalLine(c, v, join(path, 'goal'), true))
205
+ c.optional(data, 'markers', markers => {
206
+ if (!c.array(markers, join(path, 'markers'), { max: 50 })) return
207
+ markers.forEach((marker, i) => {
208
+ const p = join(join(path, 'markers'), i)
209
+ if (!c.object(marker, p, ['x', 'label'])) return
210
+ c.textOrNumber(marker.x, join(p, 'x'))
211
+ c.text(marker.label, join(p, 'label'))
212
+ })
213
+ })
214
+ }
215
+
216
+ function barData(c, data, path) {
217
+ if (!c.object(data, path, ['bars'], ['stacked', 'unit', 'goal'])) return
218
+ if (c.array(data.bars, join(path, 'bars'), { min: 1, max: 400 }))
219
+ data.bars.forEach((bar, i) => {
220
+ const p = join(join(path, 'bars'), i)
221
+ if (!c.object(bar, p, ['x'], ['value', 'values'])) return
222
+ c.textOrNumber(bar.x, join(p, 'x'))
223
+ if (!('value' in bar) && !('values' in bar)) c.fail(p, 'needs value or values')
224
+ if ('value' in bar && 'values' in bar) c.fail(p, 'has both value and values; use one')
225
+ c.optional(bar, 'value', v => c.number(v, join(p, 'value')))
226
+ c.optional(bar, 'values', values => {
227
+ const vp = join(p, 'values')
228
+ if (typeof values !== 'object' || values === null || Array.isArray(values)) return c.fail(vp, 'must be an object of series name to number')
229
+ const keys = Object.keys(values)
230
+ if (keys.length === 0 || keys.length > 8) return c.fail(vp, 'needs 1 to 8 series')
231
+ for (const key of keys) {
232
+ c.text(key, join(vp, key), { max: 60 })
233
+ c.number(values[key], join(vp, key))
234
+ }
235
+ })
236
+ })
237
+ c.optional(data, 'stacked', v => c.boolean(v, join(path, 'stacked')))
238
+ c.optional(data, 'unit', v => c.text(v, join(path, 'unit'), { max: 20 }))
239
+ c.optional(data, 'goal', v => goalLine(c, v, join(path, 'goal'), false))
240
+ }
241
+
242
+ function donutData(c, data, path) {
243
+ if (!c.object(data, path, ['segments'], ['centre', 'unit'])) return
244
+ if (c.array(data.segments, join(path, 'segments'), { min: 1, max: 12 }))
245
+ data.segments.forEach((segment, i) => {
246
+ const p = join(join(path, 'segments'), i)
247
+ if (!c.object(segment, p, ['label', 'value'], ['tone'])) return
248
+ c.text(segment.label, join(p, 'label'))
249
+ c.number(segment.value, join(p, 'value'), { min: 0 })
250
+ tone(c, segment, p)
251
+ })
252
+ c.optional(data, 'centre', centre => {
253
+ const p = join(path, 'centre')
254
+ if (!c.object(centre, p, ['text'], ['sub'])) return
255
+ c.text(centre.text, join(p, 'text'), { max: 40 })
256
+ c.optional(centre, 'sub', v => c.text(v, join(p, 'sub'), { max: 40 }))
257
+ })
258
+ c.optional(data, 'unit', v => c.text(v, join(path, 'unit'), { max: 20 }))
259
+ }
260
+
261
+ function listData(c, data, path) {
262
+ if (!c.object(data, path, ['rows'], ['empty', 'progress'])) return
263
+ if (c.array(data.rows, join(path, 'rows'), { max: 100 }))
264
+ data.rows.forEach((row, i) => {
265
+ const p = join(join(path, 'rows'), i)
266
+ if (!c.object(row, p, ['title'], ['sub', 'chip', 'checked', 'date', 'actions'])) return
267
+ c.optional(row, 'actions', v => actions(c, v, join(p, 'actions')))
268
+ c.text(row.title, join(p, 'title'))
269
+ c.optional(row, 'sub', v => c.text(v, join(p, 'sub')))
270
+ c.optional(row, 'checked', v => c.boolean(v, join(p, 'checked')))
271
+ c.optional(row, 'date', v => c.date(v, join(p, 'date')))
272
+ c.optional(row, 'chip', chip => {
273
+ const cp = join(p, 'chip')
274
+ if (!c.object(chip, cp, ['text'], ['tone'])) return
275
+ c.text(chip.text, join(cp, 'text'), { max: 40 })
276
+ tone(c, chip, cp)
277
+ })
278
+ })
279
+ c.optional(data, 'empty', v => c.text(v, join(path, 'empty')))
280
+ c.optional(data, 'progress', progress => {
281
+ const p = join(path, 'progress')
282
+ if (!c.object(progress, p, ['done', 'total'], ['label'])) return
283
+ const done = c.number(progress.done, join(p, 'done'), { min: 0 })
284
+ const total = c.number(progress.total, join(p, 'total'), { min: 0 })
285
+ if (done && total && progress.done > progress.total) c.fail(join(p, 'done'), 'must not be more than total')
286
+ c.optional(progress, 'label', v => c.text(v, join(p, 'label'), { max: 40 }))
287
+ })
288
+ }
289
+
290
+ function timelineData(c, data, path) {
291
+ if (!c.object(data, path, ['from', 'to'], ['points', 'spans'])) return
292
+ const fromOk = c.date(data.from, join(path, 'from'))
293
+ const toOk = c.date(data.to, join(path, 'to'))
294
+ if (fromOk && toOk && Date.parse(data.to) <= Date.parse(data.from)) c.fail(join(path, 'to'), 'must be after from')
295
+ c.optional(data, 'points', list => {
296
+ if (!c.array(list, join(path, 'points'), { max: 100 })) return
297
+ list.forEach((point, i) => {
298
+ const p = join(join(path, 'points'), i)
299
+ if (!c.object(point, p, ['date', 'label'], ['kind', 'tone'])) return
300
+ c.date(point.date, join(p, 'date'))
301
+ c.text(point.label, join(p, 'label'))
302
+ c.optional(point, 'kind', v => c.text(v, join(p, 'kind'), { max: 20 }))
303
+ tone(c, point, p)
304
+ })
305
+ })
306
+ c.optional(data, 'spans', list => {
307
+ if (!c.array(list, join(path, 'spans'), { max: 20 })) return
308
+ list.forEach((span, i) => {
309
+ const p = join(join(path, 'spans'), i)
310
+ if (!c.object(span, p, ['from', 'to', 'label'], ['tone'])) return
311
+ const fromValid = c.date(span.from, join(p, 'from'))
312
+ const toValid = c.date(span.to, join(p, 'to'))
313
+ if (fromValid && toValid && Date.parse(span.to) < Date.parse(span.from)) c.fail(join(p, 'to'), 'must not be before from')
314
+ c.text(span.label, join(p, 'label'))
315
+ tone(c, span, p)
316
+ })
317
+ })
318
+ }
319
+
320
+ function statusData(c, data, path) {
321
+ if (!c.object(data, path, ['rows'])) return
322
+ if (!c.array(data.rows, join(path, 'rows'), { min: 1, max: 50 })) return
323
+ data.rows.forEach((row, i) => {
324
+ const p = join(join(path, 'rows'), i)
325
+ if (!c.object(row, p, ['label', 'value', 'tone'], ['sub', 'spark', 'actions'])) return
326
+ c.optional(row, 'actions', v => actions(c, v, join(p, 'actions')))
327
+ c.text(row.label, join(p, 'label'))
328
+ c.textOrNumber(row.value, join(p, 'value'))
329
+ c.oneOf(row.tone, join(p, 'tone'), TONES)
330
+ c.optional(row, 'sub', v => c.text(v, join(p, 'sub')))
331
+ c.optional(row, 'spark', spark => {
332
+ if (!c.array(spark, join(p, 'spark'), { min: 2, max: MAX_POINTS })) return
333
+ spark.forEach((v, j) => c.number(v, join(join(p, 'spark'), j)))
334
+ })
335
+ })
336
+ }
337
+
338
+ const DATA = { stat: statData, line: lineData, bar: barData, donut: donutData, list: listData, timeline: timelineData, status: statusData }
339
+
340
+ /** Links a card may open: web pages and paths on the same site, nothing that runs script. */
341
+ export function isSafeLink(value) {
342
+ if (typeof value !== 'string' || value.length > 2000) return false
343
+ if (value.startsWith('/') && !value.startsWith('//')) return true
344
+ try {
345
+ const url = new URL(value)
346
+ return url.protocol === 'https:' || url.protocol === 'http:'
347
+ } catch {
348
+ return false
349
+ }
350
+ }
351
+
352
+ /** Problems with one card file's parsed content. */
353
+ export function checkCard(card) {
354
+ const c = new Check()
355
+ if (!c.object(card, '', ['type', 'title', 'updatedAt', 'data'], ['staleAfter', 'link', 'stat', 'actions'])) return c.problems
356
+ if (!c.oneOf(card.type, 'type', CARD_TYPES)) return c.problems
357
+ c.text(card.title, 'title', { max: 120 })
358
+ c.dateTime(card.updatedAt, 'updatedAt')
359
+ c.optional(card, 'staleAfter', v => c.number(v, 'staleAfter', { min: 1 }))
360
+ c.optional(card, 'link', v => isSafeLink(v) || c.fail('link', 'must be an http(s) URL or a path starting with /'))
361
+ c.optional(card, 'stat', v => {
362
+ if (card.type === 'stat') return c.fail('stat', 'is for chart cards; a stat card has its numbers in data')
363
+ statData(c, v, 'stat')
364
+ })
365
+ c.optional(card, 'actions', v => actions(c, v, 'actions'))
366
+ DATA[card.type](c, card.data, 'data')
367
+ return c.problems
368
+ }
369
+
370
+ /**
371
+ * The action a press names, looked up in the card as written: on the card
372
+ * itself, or on row `row` of a list or status card. Undefined when there is
373
+ * no such action, so a browser can only press what the data offers.
374
+ */
375
+ export function findAction(card, actionId, row) {
376
+ const list = row === undefined ? card?.actions : card?.data?.rows?.[row]?.actions
377
+ return Array.isArray(list) ? list.find(action => action?.id === actionId) : undefined
378
+ }
379
+
380
+ /** Problems with a board.json's parsed content. */
381
+ export function checkBoard(board) {
382
+ const c = new Check()
383
+ if (!c.object(board, '', ['title'], ['viewers', 'order', 'layout'])) return c.problems
384
+ c.text(board.title, 'title', { max: 80 })
385
+ c.optional(board, 'viewers', viewers => {
386
+ if (c.array(viewers, 'viewers', { max: 100 })) viewers.forEach((v, i) => c.text(v, join('viewers', i), { max: 100 }))
387
+ })
388
+ c.optional(board, 'order', order => {
389
+ if (c.array(order, 'order', { max: 200 }))
390
+ order.forEach((id, i) => (typeof id === 'string' && ID_PATTERN.test(id)) || c.fail(join('order', i), 'must be a card id'))
391
+ })
392
+ c.optional(board, 'layout', layout => {
393
+ if (typeof layout !== 'object' || layout === null || Array.isArray(layout)) return c.fail('layout', 'must be an object of card id to size')
394
+ for (const [id, size] of Object.entries(layout)) {
395
+ const p = join('layout', id)
396
+ if (!ID_PATTERN.test(id)) c.fail(p, 'is not a card id')
397
+ if (!c.object(size, p, [], ['w', 'h'])) continue
398
+ c.optional(size, 'w', v => (Number.isInteger(v) && v >= 1 && v <= 3) || c.fail(join(p, 'w'), 'must be 1, 2 or 3'))
399
+ c.optional(size, 'h', v => (Number.isInteger(v) && v >= 1 && v <= 3) || c.fail(join(p, 'h'), 'must be 1, 2 or 3'))
400
+ }
401
+ })
402
+ return c.problems
403
+ }
404
+
405
+ /** Parse JSON text into a value plus problems; never throws. */
406
+ export function parseJson(text) {
407
+ try {
408
+ return { value: JSON.parse(text), problems: [] }
409
+ } catch (error) {
410
+ return { value: undefined, problems: [`not valid JSON: ${error.message}`] }
411
+ }
412
+ }
package/src/store.js ADDED
@@ -0,0 +1,141 @@
1
+ /**
2
+ * Reading boards and cards from the data folder:
3
+ *
4
+ * <dataDir>/<boardId>/board.json
5
+ * <dataDir>/<boardId>/cards/<cardId>.json
6
+ *
7
+ * Only ids matching ID_PATTERN are read, and only regular files that resolve
8
+ * inside the data folder, so a link or a strange name can't make the plugin
9
+ * read anything else. A card that can't be read or fails the schema comes
10
+ * back as an error entry for its slot; nothing here throws for bad data.
11
+ */
12
+ import { createHash } from 'node:crypto'
13
+ import { lstat, readFile, readdir, realpath, stat } from 'node:fs/promises'
14
+ import { join, sep } from 'node:path'
15
+ import { ID_PATTERN, MAX_CARD_BYTES, checkBoard, checkCard, parseJson } from './schema.js'
16
+
17
+ const MAX_CARDS = 100
18
+ const MAX_BOARD_BYTES = 64 * 1024
19
+
20
+ /** A file's content if it is a regular file inside `root` and not too big; else a reason. */
21
+ async function readInside(root, path, maxBytes) {
22
+ let real
23
+ try {
24
+ real = await realpath(path)
25
+ } catch (error) {
26
+ return { missing: error.code === 'ENOENT', problem: error.code === 'ENOENT' ? 'file not found' : `cannot read: ${error.code ?? error.message}` }
27
+ }
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
+ }
34
+
35
+ async function readJson(root, path, maxBytes, check) {
36
+ const file = await readInside(root, path, maxBytes)
37
+ if (file.text === undefined) return { missing: file.missing === true, problems: [file.problem] }
38
+ const parsed = parseJson(file.text)
39
+ if (parsed.problems.length > 0) return { problems: parsed.problems }
40
+ const problems = check(parsed.value)
41
+ return problems.length > 0 ? { problems } : { value: parsed.value, problems: [] }
42
+ }
43
+
44
+ /** The data folder as an absolute real path, or undefined when it doesn't exist. */
45
+ export async function resolveDataDir(dataDir) {
46
+ try {
47
+ return await realpath(dataDir)
48
+ } catch {
49
+ return undefined
50
+ }
51
+ }
52
+
53
+ /** Every board folder with a readable board.json, valid or not, sorted by id. */
54
+ export async function listBoards(root) {
55
+ let entries
56
+ try {
57
+ entries = await readdir(root, { withFileTypes: true })
58
+ } catch {
59
+ return []
60
+ }
61
+ const boards = []
62
+ for (const entry of entries) {
63
+ if (!ID_PATTERN.test(entry.name)) continue
64
+ const dir = join(root, entry.name)
65
+ const info = await lstat(dir).catch(() => undefined)
66
+ if (info === undefined || !(info.isDirectory() || info.isSymbolicLink())) continue
67
+ const board = await readJson(root, join(dir, 'board.json'), MAX_BOARD_BYTES, checkBoard)
68
+ if (board.missing) continue
69
+ boards.push({ id: entry.name, board: board.value, problems: board.problems })
70
+ }
71
+ return boards.sort((a, b) => a.id.localeCompare(b.id))
72
+ }
73
+
74
+ /** One board's board.json (validated), or undefined when the board doesn't exist. */
75
+ export async function readBoard(root, id) {
76
+ if (!ID_PATTERN.test(id)) return undefined
77
+ const board = await readJson(root, join(root, id, 'board.json'), MAX_BOARD_BYTES, checkBoard)
78
+ if (board.missing) return undefined
79
+ return { id, board: board.value, problems: board.problems }
80
+ }
81
+
82
+ /** The card ids in a board's cards folder, in board order: `order` first, then the rest by id. */
83
+ async function cardFiles(root, id, order) {
84
+ let names
85
+ try {
86
+ names = await readdir(join(root, id, 'cards'))
87
+ } catch {
88
+ return []
89
+ }
90
+ const ids = names.filter(name => name.endsWith('.json')).map(name => name.slice(0, -5)).filter(card => ID_PATTERN.test(card)).sort()
91
+ const present = new Set(ids)
92
+ const first = (order ?? []).filter((card, i, list) => present.has(card) && list.indexOf(card) === i)
93
+ const placed = new Set(first)
94
+ return [...first, ...ids.filter(card => !placed.has(card))].slice(0, MAX_CARDS)
95
+ }
96
+
97
+ /**
98
+ * A cheap version tag for a board: changes whenever board.json or any card
99
+ * file is added, removed or rewritten. Built from file sizes and times only,
100
+ * so an unchanged board answers a poll without reading a single card.
101
+ */
102
+ export async function boardTag(root, id, salt = '') {
103
+ const hash = createHash('sha256').update(salt)
104
+ const add = async (label, path) => {
105
+ const info = await stat(path).catch(() => undefined)
106
+ hash.update(`${label}\0${info ? `${info.size}:${info.mtimeMs}` : '-'}\n`)
107
+ }
108
+ await add('board.json', join(root, id, 'board.json'))
109
+ let names = []
110
+ try {
111
+ names = (await readdir(join(root, id, 'cards'))).filter(name => name.endsWith('.json')).sort()
112
+ } catch {
113
+ // no cards folder yet
114
+ }
115
+ for (const name of names) await add(name, join(root, id, 'cards', name))
116
+ return `W/"${hash.digest('base64url').slice(0, 27)}"`
117
+ }
118
+
119
+ /** The path of a card file (ids already checked). */
120
+ export function cardPath(root, board, card) {
121
+ return join(root, board, 'cards', `${card}.json`)
122
+ }
123
+
124
+ /** One valid card, or undefined. */
125
+ export async function readCard(root, board, card) {
126
+ if (!ID_PATTERN.test(board) || !ID_PATTERN.test(card)) return undefined
127
+ const result = await readJson(root, cardPath(root, board, card), MAX_CARD_BYTES, checkCard)
128
+ return result.problems.length === 0 ? result.value : undefined
129
+ }
130
+
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) {
133
+ const layout = board?.layout ?? {}
134
+ const cards = []
135
+ for (const card of await cardFiles(root, id, board?.order)) {
136
+ const size = { w: layout[card]?.w ?? 1, h: layout[card]?.h ?? 1 }
137
+ const result = await readJson(root, join(root, id, 'cards', `${card}.json`), MAX_CARD_BYTES, checkCard)
138
+ cards.push(result.problems.length > 0 ? { id: card, ...size, problems: result.problems.slice(0, 5) } : { id: card, ...size, card: result.value })
139
+ }
140
+ return cards
141
+ }