@soffits/dsh-card-board 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/LICENSE +21 -0
- package/README.md +274 -2
- package/bin/dsh-card-board.js +198 -0
- package/client.actions.js +259 -0
- package/client.js +954 -0
- package/cordis.patch.yml +7 -0
- package/examples/boards/home/board.json +9 -0
- package/examples/boards/home/cards/chores.json +57 -0
- package/examples/boards/home/cards/energy.json +19 -0
- package/examples/boards/home/cards/house.json +58 -0
- package/examples/boards/home/cards/next-weeks.json +16 -0
- package/examples/boards/home/cards/savings.json +26 -0
- package/examples/boards/home/cards/spending.json +17 -0
- package/examples/boards/home/cards/weather.json +12 -0
- package/icon.svg +7 -0
- package/index.js +76 -0
- package/locale/en.json +1 -0
- package/locale/zh.json +1 -0
- package/package.json +80 -4
- package/src/access.js +92 -0
- package/src/presses.js +117 -0
- package/src/routes.js +120 -0
- package/src/schema.js +412 -0
- package/src/store.js +141 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
- First release: boards of `stat`, `line`, `bar`, `donut`, `list`, `timeline` and `status` cards read from a data folder, with per-person access through any `requestIdentity` provider (or everything for a single-person DSH), ETag polling while the page is visible, stale and error cards, light and dark, and phone widths.
|
|
6
|
+
- Actions on cards and rows: chat (a prefilled draft in a new conversation), done, snooze, event and link. Presses are checked on the server, logged, emitted as `card-board/action` and published as `ui.action.<kind>` through dsh-cron-jobs when it runs.
|
|
7
|
+
- The `dsh-card-board` CLI: validate, write atomically, remove, check a whole folder.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sakina
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,275 @@
|
|
|
1
|
-
#
|
|
1
|
+
# dsh-card-board
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A card board for the [DeepSeek Harness](https://github.com/deepseek-ai/dsh) Web UI. Your own scripts write small JSON files, one per card; the plugin shows them as a page of numbers, charts and lists, and each signed-in person sees only the boards they're allowed to.
|
|
4
|
+
|
|
5
|
+
The plugin only displays. It makes no outbound requests, holds no credentials and never runs anything, so keeping data fresh is up to whatever writes the files: a cron job, a watcher, a script on another machine that syncs the folder. There's no model in the loop and no cost per refresh.
|
|
6
|
+
|
|
7
|
+

|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npx @deepseek-ai/dsh plugin --profile web add @soffits/dsh-card-board@latest
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
Restart `dsh web` afterwards. It adds one Host row, `card-board`, and a **Boards** entry in the sidebar. Boards live in `card-board` under the DSH home unless you set `dataDir`.
|
|
16
|
+
|
|
17
|
+
## Configuration
|
|
18
|
+
|
|
19
|
+
Override the row in your profile's `cordis.patch.yml`:
|
|
20
|
+
|
|
21
|
+
```yaml
|
|
22
|
+
- id: card-board
|
|
23
|
+
config:
|
|
24
|
+
dataDir: ~/boards
|
|
25
|
+
peopleFile: ~/people.json
|
|
26
|
+
peopleKey: users
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
| Option | Default | What it does |
|
|
30
|
+
| --- | --- | --- |
|
|
31
|
+
| `dataDir` | `<DSH home>/card-board` | The folder with the boards. `~/` means the home folder. |
|
|
32
|
+
| `people` | `{}` | Verified user id → person id, for a DSH several people sign in to. |
|
|
33
|
+
| `peopleFile` | | A JSON file with more of that mapping, re-read when it changes. `people` wins on a clash. |
|
|
34
|
+
| `peopleKey` | | The key in `peopleFile` that holds the mapping; empty means the whole file. |
|
|
35
|
+
| `pollSeconds` | `30` | How often an open, visible page checks for changes. A hidden tab doesn't poll. |
|
|
36
|
+
| `actionLog` | `<dataDir>/.actions.jsonl` | Where action presses are appended. |
|
|
37
|
+
| `actionTimeoutSeconds` | `300` | A press nobody handles within this time shows as not handled. |
|
|
38
|
+
|
|
39
|
+
## Who sees what
|
|
40
|
+
|
|
41
|
+
With no `people` and no `peopleFile`, the plugin assumes a single-person DSH: everyone DSH lets in sees every board.
|
|
42
|
+
|
|
43
|
+
With a mapping, each request is checked on the server. The plugin asks the `requestIdentity` service who made the request, maps that user id to a person id, and serves only boards whose `viewers` list that person. A request without a verified identity sees no boards; a board the person may not see answers 403, the same as one that doesn't exist. The tabs in the page come only from the server's list. Person ids compare without regard to case.
|
|
44
|
+
|
|
45
|
+
`requestIdentity` is a small service any sign-in plugin can provide. [dsh-oidc](https://github.com/soffits/dsh-oidc) (0.3.0-alpha.9 or later) does; another plugin can provide the same interface:
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
interface RequestIdentityService {
|
|
49
|
+
/** The verified person behind the /api request being handled, or null. */
|
|
50
|
+
current(): { provider: string; issuer: string; id: string; name?: string } | null
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
The card board reads it with `ctx.get('requestIdentity')` at request time, so it doesn't depend on any one sign-in plugin. With a mapping configured and no provider running, the board routes answer 503 rather than showing everything.
|
|
55
|
+
|
|
56
|
+
## Data layout
|
|
57
|
+
|
|
58
|
+
```
|
|
59
|
+
<dataDir>/
|
|
60
|
+
<board>/
|
|
61
|
+
board.json
|
|
62
|
+
cards/<card>.json
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Board and card ids are lowercase letters, digits, `-` and `_`, up to 64 characters.
|
|
66
|
+
|
|
67
|
+
`board.json`:
|
|
68
|
+
|
|
69
|
+
```json
|
|
70
|
+
{
|
|
71
|
+
"title": "Home",
|
|
72
|
+
"viewers": ["alex", "sam"],
|
|
73
|
+
"order": ["weather", "savings", "energy"],
|
|
74
|
+
"layout": { "next-weeks": { "w": 2, "h": 1 } }
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
`order` lists cards to put first; the rest follow by id. `layout` sets a card's width and height in grid cells (1 to 3). The grid has three columns on a wide screen, two on a medium one and one on a phone; a wide card shrinks to fit.
|
|
79
|
+
|
|
80
|
+
A card:
|
|
81
|
+
|
|
82
|
+
```json
|
|
83
|
+
{
|
|
84
|
+
"type": "stat",
|
|
85
|
+
"title": "Outside",
|
|
86
|
+
"updatedAt": "2026-03-02T09:30:00Z",
|
|
87
|
+
"staleAfter": 3600,
|
|
88
|
+
"link": "https://example.com/weather",
|
|
89
|
+
"data": { "items": [{ "label": "Temperature", "value": 4.5, "unit": "°C" }] }
|
|
90
|
+
}
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
| Field | |
|
|
94
|
+
| --- | --- |
|
|
95
|
+
| `type` | `stat`, `line`, `bar`, `donut`, `list`, `timeline` or `status` |
|
|
96
|
+
| `title` | Shown on the card. |
|
|
97
|
+
| `updatedAt` | ISO date-time with a zone. The CLI fills it in when you leave it out. |
|
|
98
|
+
| `staleAfter` | Seconds. Past this the card is dimmed and says how old it is. |
|
|
99
|
+
| `link` | An `http(s)` URL or a `/path` the title row links to. |
|
|
100
|
+
| `stat` | A headline above a chart: the same shape as a `stat` card's `data`. |
|
|
101
|
+
| `actions` | Buttons on the card; see [Actions](#actions). |
|
|
102
|
+
| `data` | Depends on the type, below. |
|
|
103
|
+
|
|
104
|
+
Unknown fields are errors, so a typo fails when the file is written instead of quietly not showing. A card that doesn't parse or fails the schema shows as a small error card with the reason; the rest of the board is unaffected.
|
|
105
|
+
|
|
106
|
+
Colours are never given directly. `tone` is one of `ok`, `warn`, `bad`, `muted` or `accent`, and the page maps it to DSH's theme, light or dark. Text can be in any language; nothing in the format assumes one. Dates are `YYYY-MM-DD` or ISO date-times.
|
|
107
|
+
|
|
108
|
+
### stat
|
|
109
|
+
|
|
110
|
+
One to six big numbers.
|
|
111
|
+
|
|
112
|
+
```json
|
|
113
|
+
{ "items": [
|
|
114
|
+
{ "label": "Temperature", "value": 4.5, "unit": "°C", "delta": { "value": -2.1, "unit": "°C", "tone": "accent" }, "sub": "feels like 1 °C" },
|
|
115
|
+
{ "label": "Humidity", "value": 71, "unit": "%" }
|
|
116
|
+
] }
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
`value` is a number or a string (for numbers you've already formatted). `tone` on an item colours its value.
|
|
120
|
+
|
|
121
|
+
### line
|
|
122
|
+
|
|
123
|
+
```json
|
|
124
|
+
{
|
|
125
|
+
"series": [{ "name": "Savings", "points": [{ "x": "2025-10-01", "y": 16100 }, { "x": "2026-03-01", "y": 18240 }] }],
|
|
126
|
+
"unit": "EUR",
|
|
127
|
+
"area": true,
|
|
128
|
+
"goal": { "label": "Goal 20k", "y": 20000 },
|
|
129
|
+
"markers": [{ "x": "2025-12-01", "label": "New laptop" }]
|
|
130
|
+
}
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
`x` is a date, a number or a label; dates are spaced by time. `y` may be `null` for a gap. A goal is a flat `y` or its own `points` (a rising target, say). Up to six series, each with an optional `tone`.
|
|
134
|
+
|
|
135
|
+
### bar
|
|
136
|
+
|
|
137
|
+
```json
|
|
138
|
+
{
|
|
139
|
+
"bars": [{ "x": "Mon", "values": { "Day": 5.2, "Night": 2.1 } }, { "x": "Tue", "values": { "Day": 4.8, "Night": 2.4 } }],
|
|
140
|
+
"stacked": true,
|
|
141
|
+
"unit": "kWh",
|
|
142
|
+
"goal": { "label": "Target", "y": 8 }
|
|
143
|
+
}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Each bar has a single `value` or named `values`; with `values` and no `stacked`, the series stand side by side.
|
|
147
|
+
|
|
148
|
+
### donut
|
|
149
|
+
|
|
150
|
+
```json
|
|
151
|
+
{
|
|
152
|
+
"segments": [{ "label": "Rent", "value": 950 }, { "label": "Groceries", "value": 310 }, { "label": "Other", "value": 64, "tone": "muted" }],
|
|
153
|
+
"centre": { "text": "1,324", "sub": "EUR" },
|
|
154
|
+
"unit": "EUR"
|
|
155
|
+
}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### list
|
|
159
|
+
|
|
160
|
+
```json
|
|
161
|
+
{
|
|
162
|
+
"progress": { "done": 1, "total": 3, "label": "done" },
|
|
163
|
+
"rows": [
|
|
164
|
+
{ "title": "Water the plants", "checked": true },
|
|
165
|
+
{ "title": "Return the library books", "checked": false, "chip": { "text": "due today", "tone": "warn" } },
|
|
166
|
+
{ "title": "Call the landlord", "sub": "waiting since Friday", "date": "2026-02-27" }
|
|
167
|
+
],
|
|
168
|
+
"empty": "Nothing left for today."
|
|
169
|
+
}
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
`checked` draws a checkbox (display only). `progress` draws a ring beside the rows.
|
|
173
|
+
|
|
174
|
+
### timeline
|
|
175
|
+
|
|
176
|
+
```json
|
|
177
|
+
{
|
|
178
|
+
"from": "2026-03-02",
|
|
179
|
+
"to": "2026-03-16",
|
|
180
|
+
"points": [{ "date": "2026-03-04", "label": "Train to Lyon", "kind": "travel" }, { "date": "2026-03-05", "label": "Phone bill", "kind": "due" }],
|
|
181
|
+
"spans": [{ "from": "2026-03-04", "to": "2026-03-09", "label": "In Lyon" }]
|
|
182
|
+
}
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
`kind` is `travel` (drawn as a plane), `due`, `event`, `health`, `home` or `money`; each has a default tone, and `tone` overrides it. Today gets a thin line.
|
|
186
|
+
|
|
187
|
+
### status
|
|
188
|
+
|
|
189
|
+
```json
|
|
190
|
+
{ "rows": [
|
|
191
|
+
{ "label": "Leak sensor", "value": "dry", "tone": "ok" },
|
|
192
|
+
{ "label": "Living room", "value": "20.5 °C", "tone": "ok", "spark": [19.8, 19.6, 20.4, 20.8, 20.5] },
|
|
193
|
+
{ "label": "Front door", "value": "unlocked", "tone": "warn", "sub": "since 08:12" }
|
|
194
|
+
] }
|
|
195
|
+
```
|
|
196
|
+
|
|
197
|
+
`spark` draws a small line beside the value.
|
|
198
|
+
|
|
199
|
+
The [examples](examples/boards/home) folder has a complete board with one card of each type.
|
|
200
|
+
|
|
201
|
+
## Actions
|
|
202
|
+
|
|
203
|
+
A card, a list row or a status row can carry up to six buttons:
|
|
204
|
+
|
|
205
|
+
```json
|
|
206
|
+
"actions": [
|
|
207
|
+
{ "kind": "done", "id": "library-books:done" },
|
|
208
|
+
{ "kind": "snooze", "id": "library-books:snooze" },
|
|
209
|
+
{ "kind": "chat", "id": "landlord:ask", "label": "Draft a message", "payload": { "prompt": "Help me write a short follow-up to the landlord." } },
|
|
210
|
+
{ "kind": "event", "id": "front-door:lock", "label": "Lock" },
|
|
211
|
+
{ "kind": "link", "id": "panel", "label": "Home panel", "payload": { "url": "https://example.com/home" } }
|
|
212
|
+
]
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
- `chat` opens a new conversation (or the session named in `payload.session`) with a draft that quotes the card or row and carries its ids as JSON, after `payload.prompt` if you gave one. Nothing is sent until the person sends it, so the message comes from them like any other. Every card also has a chat button in its corner without declaring one.
|
|
216
|
+
- `done`, `snooze` and `event` are pressed on the server. A snooze without `payload.until` asks: in 3 hours, tomorrow at 9:00, or a time.
|
|
217
|
+
- `link` opens `payload.url`.
|
|
218
|
+
|
|
219
|
+
`id` is yours: letters, digits and `. _ : -`, unique within the card or row. `label` is optional except for `event`. `payload` is any small object (up to 4 KB of JSON).
|
|
220
|
+
|
|
221
|
+
The plugin doesn't act on a press itself. It checks that the person may see the board and that the action is in the card as written, then records an event:
|
|
222
|
+
|
|
223
|
+
```json
|
|
224
|
+
{
|
|
225
|
+
"press": "fcb114dd-3890-42e6-af4b-b23173edf8e0",
|
|
226
|
+
"action": "done",
|
|
227
|
+
"id": "library-books:done",
|
|
228
|
+
"payload": {},
|
|
229
|
+
"person": "alex",
|
|
230
|
+
"user": "<verified user id>",
|
|
231
|
+
"at": "2026-03-02T09:41:12.000Z",
|
|
232
|
+
"source": { "plugin": "dsh-card-board", "board": "home", "card": "chores", "row": 1 }
|
|
233
|
+
}
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
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.
|
|
237
|
+
|
|
238
|
+
The button shows the press as pending until the card file is written again, then done. If nothing rewrites the card within `actionTimeoutSeconds`, it says nothing picked the press up. So a handler should rewrite the card when it has acted, even if only `updatedAt` changes.
|
|
239
|
+
|
|
240
|
+
The buttons come from [`client.actions.js`](client.actions.js), a dependency-free module other plugins can copy to draw actions the same way; its header says how.
|
|
241
|
+
|
|
242
|
+
## Writing cards: the CLI
|
|
243
|
+
|
|
244
|
+
`dsh-card-board` validates a card and writes it atomically (a temporary file, then a rename), so the page never reads half a file and bad data fails at write time:
|
|
245
|
+
|
|
246
|
+
```sh
|
|
247
|
+
export CARD_BOARD_DIR=~/boards
|
|
248
|
+
dsh-card-board board home board.json # write home/board.json
|
|
249
|
+
echo '{"type":"stat","title":"Outside","data":{"items":[{"label":"Now","value":4.5,"unit":"°C"}]}}' \
|
|
250
|
+
| dsh-card-board put home weather # write home/cards/weather.json
|
|
251
|
+
dsh-card-board rm home weather
|
|
252
|
+
dsh-card-board check card.json # validate only
|
|
253
|
+
dsh-card-board check --board board.json
|
|
254
|
+
dsh-card-board check --dir ~/boards # everything under a data folder
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
Input comes from the file argument, or stdin when it's `-` or left out. `--dir` overrides `CARD_BOARD_DIR`. An invalid card exits with status 1 and prints each problem with its path (`data.rows[0].title: is required`); usage errors exit with 2.
|
|
258
|
+
|
|
259
|
+
From JavaScript the same checks are `import { checkCard, checkBoard } from '@soffits/dsh-card-board/schema'`.
|
|
260
|
+
|
|
261
|
+
## How the page updates
|
|
262
|
+
|
|
263
|
+
The page polls `GET /api/card-board/board?id=<board>` while it's visible, with the last `ETag` in `If-None-Match`. The tag is built from file sizes and times, so an unchanged board answers 304 without reading a card. Coming back to the tab checks at once.
|
|
264
|
+
|
|
265
|
+
## Development
|
|
266
|
+
|
|
267
|
+
```sh
|
|
268
|
+
npm install
|
|
269
|
+
npm run check # syntax of every file, and the example board against the schema
|
|
270
|
+
npm test # node --test, including a run behind DSH's real Connection
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
## License
|
|
274
|
+
|
|
275
|
+
MIT
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Write card board files safely: validate, then write atomically.
|
|
4
|
+
*
|
|
5
|
+
* dsh-card-board put <board> <card> [file|-] write <dir>/<board>/cards/<card>.json
|
|
6
|
+
* dsh-card-board board <board> [file|-] write <dir>/<board>/board.json
|
|
7
|
+
* dsh-card-board rm <board> <card> remove a card
|
|
8
|
+
* dsh-card-board check [--board] <file|-> validate only
|
|
9
|
+
* dsh-card-board check --dir <dir> validate every board and card under a data folder
|
|
10
|
+
*
|
|
11
|
+
* The data folder comes from --dir or CARD_BOARD_DIR. Input is JSON from the
|
|
12
|
+
* file, or stdin when it is "-" or left out. `put` fills a missing updatedAt
|
|
13
|
+
* with the current time. Anything invalid exits 1 with the reasons on stderr
|
|
14
|
+
* and writes nothing.
|
|
15
|
+
*/
|
|
16
|
+
import { randomBytes } from 'node:crypto'
|
|
17
|
+
import { mkdir, open, readFile, readdir, rename, rm, unlink } from 'node:fs/promises'
|
|
18
|
+
import { realpathSync } from 'node:fs'
|
|
19
|
+
import { join } from 'node:path'
|
|
20
|
+
import { pathToFileURL } from 'node:url'
|
|
21
|
+
import { ID_PATTERN, MAX_CARD_BYTES, checkBoard, checkCard, parseJson } from '../src/schema.js'
|
|
22
|
+
|
|
23
|
+
const USAGE = `usage:
|
|
24
|
+
dsh-card-board put <board> <card> [file|-]
|
|
25
|
+
dsh-card-board board <board> [file|-]
|
|
26
|
+
dsh-card-board rm <board> <card>
|
|
27
|
+
dsh-card-board check [--board] <file|->
|
|
28
|
+
dsh-card-board check --dir <dir>
|
|
29
|
+
options:
|
|
30
|
+
--dir <dir> the data folder (default: $CARD_BOARD_DIR)`
|
|
31
|
+
|
|
32
|
+
class UsageError extends Error {}
|
|
33
|
+
class InvalidError extends Error {
|
|
34
|
+
constructor(problems) {
|
|
35
|
+
super(problems.join('\n'))
|
|
36
|
+
this.problems = problems
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function parseArgs(argv) {
|
|
41
|
+
const positional = []
|
|
42
|
+
const flags = {}
|
|
43
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
44
|
+
const arg = argv[i]
|
|
45
|
+
if (arg === '--dir') {
|
|
46
|
+
if (argv[i + 1] === undefined) throw new UsageError('--dir needs a folder')
|
|
47
|
+
flags.dir = argv[++i]
|
|
48
|
+
} else if (arg.startsWith('--dir=')) flags.dir = arg.slice(6)
|
|
49
|
+
else if (arg === '--board') flags.board = true
|
|
50
|
+
else if (arg === '-h' || arg === '--help') flags.help = true
|
|
51
|
+
else if (arg.startsWith('--')) throw new UsageError(`unknown option ${arg}`)
|
|
52
|
+
else positional.push(arg)
|
|
53
|
+
}
|
|
54
|
+
return { positional, flags }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function readInput(source, stdin) {
|
|
58
|
+
if (source === undefined || source === '-') {
|
|
59
|
+
const chunks = []
|
|
60
|
+
for await (const chunk of stdin) chunks.push(chunk)
|
|
61
|
+
return Buffer.concat(chunks).toString('utf8')
|
|
62
|
+
}
|
|
63
|
+
return readFile(source, 'utf8')
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function id(value, what) {
|
|
67
|
+
if (typeof value !== 'string' || !ID_PATTERN.test(value))
|
|
68
|
+
throw new UsageError(`${what} id must match ${ID_PATTERN} (lowercase letters, digits, - and _)`)
|
|
69
|
+
return value
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function dataDir(flags, env) {
|
|
73
|
+
const dir = flags.dir ?? env.CARD_BOARD_DIR
|
|
74
|
+
if (!dir) throw new UsageError('say where the data folder is: --dir <dir> or CARD_BOARD_DIR')
|
|
75
|
+
return dir
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Write `text` to `path` through a temporary file in the same folder, so readers see the old or the new file, never half. */
|
|
79
|
+
export async function writeAtomic(path, text) {
|
|
80
|
+
const temp = `${path}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`
|
|
81
|
+
const handle = await open(temp, 'w', 0o644)
|
|
82
|
+
try {
|
|
83
|
+
await handle.writeFile(text)
|
|
84
|
+
await handle.sync()
|
|
85
|
+
} finally {
|
|
86
|
+
await handle.close()
|
|
87
|
+
}
|
|
88
|
+
try {
|
|
89
|
+
await rename(temp, path)
|
|
90
|
+
} catch (error) {
|
|
91
|
+
await unlink(temp).catch(() => {})
|
|
92
|
+
throw error
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function validated(text, check) {
|
|
97
|
+
const parsed = parseJson(text)
|
|
98
|
+
if (parsed.problems.length > 0) throw new InvalidError(parsed.problems)
|
|
99
|
+
const problems = check(parsed.value)
|
|
100
|
+
if (problems.length > 0) throw new InvalidError(problems)
|
|
101
|
+
return parsed.value
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function checkDir(dir, out) {
|
|
105
|
+
let bad = 0
|
|
106
|
+
let count = 0
|
|
107
|
+
const boards = (await readdir(dir, { withFileTypes: true })).filter(entry => entry.isDirectory() && ID_PATTERN.test(entry.name))
|
|
108
|
+
for (const board of boards) {
|
|
109
|
+
const report = (file, problems) => {
|
|
110
|
+
count += 1
|
|
111
|
+
if (problems.length === 0) return
|
|
112
|
+
bad += 1
|
|
113
|
+
out.error(`${join(board.name, file)}:\n ${problems.join('\n ')}`)
|
|
114
|
+
}
|
|
115
|
+
const boardText = await readFile(join(dir, board.name, 'board.json'), 'utf8').catch(() => undefined)
|
|
116
|
+
if (boardText === undefined) continue
|
|
117
|
+
const parsed = parseJson(boardText)
|
|
118
|
+
report('board.json', parsed.problems.length > 0 ? parsed.problems : checkBoard(parsed.value))
|
|
119
|
+
const names = await readdir(join(dir, board.name, 'cards')).catch(() => [])
|
|
120
|
+
for (const name of names.filter(n => n.endsWith('.json')).sort()) {
|
|
121
|
+
const text = await readFile(join(dir, board.name, 'cards', name), 'utf8')
|
|
122
|
+
const card = parseJson(text)
|
|
123
|
+
report(join('cards', name), card.problems.length > 0 ? card.problems : checkCard(card.value))
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
out.log(`${count} file${count === 1 ? '' : 's'} checked, ${bad} with problems`)
|
|
127
|
+
return bad === 0 ? 0 : 1
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Run the CLI; returns the exit code. `io` is injectable for tests. */
|
|
131
|
+
export async function main(argv, { env = process.env, stdin = process.stdin, out = console, now = () => new Date() } = {}) {
|
|
132
|
+
try {
|
|
133
|
+
const { positional, flags } = parseArgs(argv)
|
|
134
|
+
const [command, ...rest] = positional
|
|
135
|
+
if (flags.help || command === undefined) {
|
|
136
|
+
out.log(USAGE)
|
|
137
|
+
return command === undefined && !flags.help ? 2 : 0
|
|
138
|
+
}
|
|
139
|
+
if (command === 'put') {
|
|
140
|
+
const [boardId, cardId, source] = rest
|
|
141
|
+
const dir = dataDir(flags, env)
|
|
142
|
+
id(boardId, 'board')
|
|
143
|
+
id(cardId, 'card')
|
|
144
|
+
const text = await readInput(source, stdin)
|
|
145
|
+
const parsed = parseJson(text)
|
|
146
|
+
if (parsed.problems.length > 0) throw new InvalidError(parsed.problems)
|
|
147
|
+
const card = parsed.value
|
|
148
|
+
if (typeof card === 'object' && card !== null && !Array.isArray(card) && !('updatedAt' in card))
|
|
149
|
+
card.updatedAt = now().toISOString().replace(/\.\d{3}Z$/, 'Z')
|
|
150
|
+
const problems = checkCard(card)
|
|
151
|
+
if (problems.length > 0) throw new InvalidError(problems)
|
|
152
|
+
const body = `${JSON.stringify(card, null, 2)}\n`
|
|
153
|
+
if (Buffer.byteLength(body) > MAX_CARD_BYTES) throw new InvalidError([`the card is larger than ${MAX_CARD_BYTES / 1024} KB`])
|
|
154
|
+
const folder = join(dir, boardId, 'cards')
|
|
155
|
+
await mkdir(folder, { recursive: true })
|
|
156
|
+
await writeAtomic(join(folder, `${cardId}.json`), body)
|
|
157
|
+
return 0
|
|
158
|
+
}
|
|
159
|
+
if (command === 'board') {
|
|
160
|
+
const [boardId, source] = rest
|
|
161
|
+
const dir = dataDir(flags, env)
|
|
162
|
+
id(boardId, 'board')
|
|
163
|
+
const board = validated(await readInput(source, stdin), checkBoard)
|
|
164
|
+
await mkdir(join(dir, boardId, 'cards'), { recursive: true })
|
|
165
|
+
await writeAtomic(join(dir, boardId, 'board.json'), `${JSON.stringify(board, null, 2)}\n`)
|
|
166
|
+
return 0
|
|
167
|
+
}
|
|
168
|
+
if (command === 'rm') {
|
|
169
|
+
const [boardId, cardId] = rest
|
|
170
|
+
const dir = dataDir(flags, env)
|
|
171
|
+
id(boardId, 'board')
|
|
172
|
+
id(cardId, 'card')
|
|
173
|
+
await rm(join(dir, boardId, 'cards', `${cardId}.json`), { force: true })
|
|
174
|
+
return 0
|
|
175
|
+
}
|
|
176
|
+
if (command === 'check') {
|
|
177
|
+
if (rest.length === 0 && flags.dir !== undefined) return await checkDir(flags.dir, out)
|
|
178
|
+
validated(await readInput(rest[0], stdin), flags.board ? checkBoard : checkCard)
|
|
179
|
+
out.log('ok')
|
|
180
|
+
return 0
|
|
181
|
+
}
|
|
182
|
+
throw new UsageError(`unknown command ${command}`)
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if (error instanceof UsageError) {
|
|
185
|
+
out.error(`${error.message}\n${USAGE}`)
|
|
186
|
+
return 2
|
|
187
|
+
}
|
|
188
|
+
if (error instanceof InvalidError) {
|
|
189
|
+
out.error(`invalid:\n ${error.problems.join('\n ')}`)
|
|
190
|
+
return 1
|
|
191
|
+
}
|
|
192
|
+
out.error(error.message)
|
|
193
|
+
return 1
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const invoked = process.argv[1] !== undefined && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href
|
|
198
|
+
if (invoked) process.exitCode = await main(process.argv.slice(2))
|