@soffits/dsh-card-board 0.18.0 → 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,9 @@
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
+
3
7
  ## 0.18.0
4
8
 
5
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.
package/client.js CHANGED
@@ -1,4 +1,4 @@
1
- /* @soffits/dsh-card-board 0.18.0: 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) => {
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'
@@ -70,7 +69,10 @@ export function apply(ctx, config) {
70
69
  })
71
70
  const watches = createWatches({ warn: message => logger.warn(message) })
72
71
  ctx.effect(() => () => watches.close())
73
- const { routes, close } = createRoutes({
72
+ const streams = createEventStreams()
73
+ ctx.effect(() => () => streams.close())
74
+ const localeDir = fileURLToPath(new URL('./locale', import.meta.url))
75
+ const routes = createRoutes({
74
76
  dataDir,
75
77
  people,
76
78
  identity: () => ctx.get('requestIdentity'),
@@ -79,10 +81,11 @@ 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
- ctx.effect(() => close)
86
89
  for (const route of routes) ctx.connection.fetch.register(route)
87
90
  logger.info(`serving boards from ${dataDir} (${people.enabled ? 'per person' : 'single owner'})`)
88
91
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soffits/dsh-card-board",
3
- "version": "0.18.0",
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/routes.js CHANGED
@@ -17,9 +17,9 @@
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
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'
@@ -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,11 +58,9 @@ 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 }) {
66
- /** Ends each open events stream. DSH only drops a route on unload, so a stream it already answered would live on. */
67
- const streams = new Set()
63
+ export function createRoutes({ dataDir, people, identity, pollSeconds, presses, seen, arrange, watches, messages, streams, version = '' }) {
68
64
 
69
65
  /** The viewer and their board, or the Response that refuses them. */
70
66
  async function access(board) {
@@ -91,7 +87,7 @@ export function createRoutes({ dataDir, people, identity, pollSeconds, presses,
91
87
 
92
88
  async function locale(request) {
93
89
  const tag = new URL(request.url).searchParams.get('tag') ?? 'en'
94
- 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.' })
95
91
  return json(200, await messages(tag))
96
92
  }
97
93
 
@@ -147,40 +143,17 @@ export function createRoutes({ dataDir, people, identity, pollSeconds, presses,
147
143
  if (!ID_PATTERN.test(id)) return json(400, { error: 'Not a board id.' })
148
144
  const found = await access(id)
149
145
  if (found.refused) return found.refused
150
- const encoder = new TextEncoder()
151
- let finish = () => {}
152
- const body = new ReadableStream({
153
- async start(controller) {
154
- let open = true
155
- const send = text => { if (open) controller.enqueue(encoder.encode(text)) }
156
- const data = value => send(`data: ${JSON.stringify(value)}\n\n`)
157
- let unwatch = () => {}
158
- let unarrange = () => {}
159
- const heartbeat = setInterval(() => send(': ping\n\n'), heartbeatMs)
160
- const end = () => {
161
- finish()
162
- try { controller.close() } catch { /* already closed */ }
163
- }
164
- finish = () => {
165
- if (!open) return
166
- open = false
167
- clearInterval(heartbeat)
168
- unwatch()
169
- unarrange()
170
- streams.delete(end)
171
- request.signal?.removeEventListener?.('abort', finish)
172
- }
173
- streams.add(end)
174
- request.signal?.addEventListener?.('abort', finish)
175
- send(': connected\n\n')
176
- // The viewer's own arrangement changing elsewhere (another device) reaches this page too.
177
- 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 {
178
151
  unwatch = await watches.watch(join(found.root, id), async change => {
179
152
  if (change.type === 'board') {
180
153
  // Viewers may have changed: someone who may no longer see the board hears that and nothing else.
181
154
  const again = await access(id)
182
155
  if (again.refused) {
183
- data({ type: 'gone' })
156
+ send({ type: 'gone' })
184
157
  end()
185
158
  return
186
159
  }
@@ -189,16 +162,17 @@ export function createRoutes({ dataDir, people, identity, pollSeconds, presses,
189
162
  const now = await readBoard(found.root, id)
190
163
  if (!maySeeCard(found.viewer, now?.board, change.id)) return
191
164
  }
192
- data(change)
165
+ send(change)
193
166
  })
194
- if (!open) unwatch()
195
- else data({ type: 'hello' })
196
- },
197
- cancel() { finish() },
198
- })
199
- return new Response(body, {
200
- status: 200,
201
- 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
+ }
202
176
  })
203
177
  }
204
178
 
@@ -306,5 +280,5 @@ export function createRoutes({ dataDir, people, identity, pollSeconds, presses,
306
280
  { path: LOCALE_PATH, methods: ['GET'], requestBody: 'buffered', fetch: locale },
307
281
  { path: ACTION_PATH, methods: ['POST'], requestBody: 'buffered', fetch: action },
308
282
  ]
309
- return { routes, close: () => { for (const end of [...streams]) end() } }
283
+ return routes
310
284
  }
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
- }