@skillre/dsh-plugin-sticky-wall 0.6.0 → 0.8.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/README.en.md +38 -15
- package/README.md +39 -18
- package/UNINSTALL.md +22 -7
- package/compatibility.json +83 -4
- package/lib/client.js +1174 -369
- package/lib/config.d.ts +18 -0
- package/lib/config.js +27 -0
- package/lib/frontmatter.d.ts +81 -0
- package/lib/frontmatter.js +440 -0
- package/lib/index.d.ts +9 -4
- package/lib/index.js +153 -36
- package/lib/layout.d.ts +27 -5
- package/lib/layout.js +82 -25
- package/lib/migrate.d.ts +53 -0
- package/lib/migrate.js +156 -0
- package/lib/store.d.ts +123 -68
- package/lib/store.js +305 -96
- package/lib/transport.d.ts +7 -4
- package/lib/transport.js +25 -4
- package/lib/types.d.ts +117 -7
- package/lib/types.js +38 -5
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +3 -3
- package/docs/PREVIEW.md +0 -39
package/lib/store.js
CHANGED
|
@@ -1,23 +1,34 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Durable note store over the
|
|
2
|
+
* Durable note store over the real `.md` files under the notes directory.
|
|
3
3
|
*
|
|
4
4
|
* The Host owns all data: the Client renders snapshots and submits intents, and
|
|
5
5
|
* every write goes through {@link StickyWallStore} — validate, persist, then
|
|
6
|
-
* hand back the changed records.
|
|
7
|
-
* per-domain write chain, so concurrent writes cannot interleave, and its
|
|
8
|
-
* `per-record` layout keeps one file per note: one damaged record cannot take
|
|
9
|
-
* the whole wall down.
|
|
6
|
+
* hand back the changed records.
|
|
10
7
|
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
8
|
+
* 0.8.0 moved the notes off the storage domain and onto plain files the user can
|
|
9
|
+
* open in any editor: one `.md` per note, frontmatter for the attributes, the
|
|
10
|
+
* body being the note text itself. That shape is why this store looks the way it
|
|
11
|
+
* does:
|
|
12
|
+
*
|
|
13
|
+
* - **Reads are synchronous.** Every note is loaded once at `open()` into the
|
|
14
|
+
* in-memory map, which stays the AUTHORITATIVE cache. The wall polls with the
|
|
15
|
+
* cheap `revision` call, so a read must never touch the disk.
|
|
16
|
+
* - **Writes go to disk FIRST, then to the cache.** A resolved mutation means
|
|
17
|
+
* the bytes are on disk; the cache can never run ahead of the file, and a
|
|
18
|
+
* failed write leaves the previous state intact.
|
|
19
|
+
* - **Every mutation is serialised** on one chain, so a check-then-write pair —
|
|
20
|
+
* the `maxNotes` count followed by the write — cannot interleave with another
|
|
21
|
+
* request. The filesystem gives us no such guarantee on its own.
|
|
22
|
+
* - **One unreadable file never takes the wall down.** A file that is too large,
|
|
23
|
+
* misnamed or carries a broken frontmatter block is skipped, or degraded to a
|
|
24
|
+
* note with `metaError`, but never thrown away.
|
|
17
25
|
*/
|
|
18
|
-
import {
|
|
26
|
+
import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
27
|
+
import { join, resolve } from 'node:path';
|
|
19
28
|
import { arrangeLayouts, clampLayout, findFreeLayout, normalizeReserve, normalizeWidth, sameLayout } from './layout.js';
|
|
20
|
-
import {
|
|
29
|
+
import { fileNameOf, idOfFile, isNoteId, parseNoteFile, serializeNoteFile } from './frontmatter.js';
|
|
30
|
+
import { migrateNotes } from './migrate.js';
|
|
31
|
+
import { CENTRE_RESERVE, COLORS, LIMITS, } from './types.js';
|
|
21
32
|
/** Failure carrying a stable code the transport maps onto the RPC envelope. */
|
|
22
33
|
export class WallError extends Error {
|
|
23
34
|
code;
|
|
@@ -29,40 +40,6 @@ export class WallError extends Error {
|
|
|
29
40
|
this.name = 'WallError';
|
|
30
41
|
}
|
|
31
42
|
}
|
|
32
|
-
/** Record schema; every stored note is validated at domain open and on write. */
|
|
33
|
-
const NoteSchema = z
|
|
34
|
-
.object({
|
|
35
|
-
id: z.string().min(1).max(128),
|
|
36
|
-
title: z.string().max(LIMITS.title).default(''),
|
|
37
|
-
body: z.string().min(1).max(LIMITS.body),
|
|
38
|
-
tags: z.array(z.string().min(1).max(LIMITS.tag)).max(LIMITS.tags).default([]),
|
|
39
|
-
color: z.enum(COLORS).default('yellow'),
|
|
40
|
-
pinned: z.boolean().default(false),
|
|
41
|
-
archived: z.boolean().default(false),
|
|
42
|
-
createdAt: z.string().min(1),
|
|
43
|
-
updatedAt: z.string().min(1),
|
|
44
|
-
// `null` means "never placed": the Client derives a preview position from
|
|
45
|
-
// the note id. A stored layout is owned by the Host, so a wall opened in
|
|
46
|
-
// two windows shows the same arrangement.
|
|
47
|
-
layout: z
|
|
48
|
-
.object({
|
|
49
|
-
x: z.number(),
|
|
50
|
-
y: z.number(),
|
|
51
|
-
rotate: z.number(),
|
|
52
|
-
width: z.enum(WIDTHS),
|
|
53
|
-
})
|
|
54
|
-
.nullable()
|
|
55
|
-
.default(null),
|
|
56
|
-
})
|
|
57
|
-
.passthrough();
|
|
58
|
-
/** The domain declaration handed to `ctx.storageDomain.open()`. */
|
|
59
|
-
export const DOMAIN_SPEC = {
|
|
60
|
-
name: DOMAIN_NAME,
|
|
61
|
-
version: DOMAIN_VERSION,
|
|
62
|
-
layout: 'per-record',
|
|
63
|
-
invalidRecords: 'backup-and-skip',
|
|
64
|
-
tables: { notes: { valueSchema: NoteSchema } },
|
|
65
|
-
};
|
|
66
43
|
/** Normalize one tag: trim, lowercase, collapse inner whitespace, bound length. */
|
|
67
44
|
function normalizeTag(raw) {
|
|
68
45
|
const value = String(raw ?? '').trim().toLowerCase().replace(/\s+/g, ' ');
|
|
@@ -83,13 +60,47 @@ function normalizeTags(raw) {
|
|
|
83
60
|
}
|
|
84
61
|
return [...seen];
|
|
85
62
|
}
|
|
86
|
-
/**
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
63
|
+
/**
|
|
64
|
+
* The stored body for a submitted string.
|
|
65
|
+
*
|
|
66
|
+
* Line endings are normalized, and NOTHING ELSE is touched — in particular the
|
|
67
|
+
* body is never trimmed. The card-height estimate walks this text line by line
|
|
68
|
+
* and the file round-trip has to give back exactly what was written, so a stray
|
|
69
|
+
* `.trim()` here would change every card's geometry and silently eat the blank
|
|
70
|
+
* lines a user indented with.
|
|
71
|
+
*/
|
|
72
|
+
function readBody(raw) {
|
|
73
|
+
return String(raw ?? '').replace(/\r\n?/g, '\n');
|
|
74
|
+
}
|
|
75
|
+
/** Validate the body length against {@link LIMITS.body}. */
|
|
76
|
+
function assertBodyLength(value) {
|
|
91
77
|
if (value.length > LIMITS.body)
|
|
92
78
|
throw new WallError('body-too-long', `A note is limited to ${LIMITS.body} characters.`, { limit: LIMITS.body, length: value.length });
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Validate a body for CREATE, where a note must actually say something.
|
|
82
|
+
*
|
|
83
|
+
* Emptiness is judged on the trimmed text so a note of three spaces is still
|
|
84
|
+
* refused, but the STORED value keeps every character the caller sent.
|
|
85
|
+
*/
|
|
86
|
+
function normalizeBody(raw) {
|
|
87
|
+
const value = readBody(raw);
|
|
88
|
+
if (value.trim() === '')
|
|
89
|
+
throw new WallError('empty-body', 'A note needs some text.');
|
|
90
|
+
assertBodyLength(value);
|
|
91
|
+
return value;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Validate a body for an UPDATE.
|
|
95
|
+
*
|
|
96
|
+
* An existing note may be saved EMPTY. Deleting the last character of a note is
|
|
97
|
+
* a legitimate edit — the user is clearing the card to retype it, or keeping a
|
|
98
|
+
* card as a title only — and refusing it left the editor unable to save at all,
|
|
99
|
+
* with the old text still on disk. Length is still capped.
|
|
100
|
+
*/
|
|
101
|
+
function normalizeBodyForUpdate(raw) {
|
|
102
|
+
const value = readBody(raw);
|
|
103
|
+
assertBodyLength(value);
|
|
93
104
|
return value;
|
|
94
105
|
}
|
|
95
106
|
/** Validate and trim a title; an absent title is the empty string. */
|
|
@@ -122,19 +133,24 @@ function normalizeLayout(raw) {
|
|
|
122
133
|
}
|
|
123
134
|
return clampLayout({ x, y, rotate, width: normalizeWidth(value.width) });
|
|
124
135
|
}
|
|
125
|
-
/**
|
|
136
|
+
/**
|
|
137
|
+
* Reject ids that cannot name a note file before anything is touched.
|
|
138
|
+
*
|
|
139
|
+
* The id is now a BASENAME, so this is also the path-traversal guard: `../x`
|
|
140
|
+
* must never reach `pathOf`.
|
|
141
|
+
*/
|
|
126
142
|
function assertIds(raw) {
|
|
127
143
|
if (!Array.isArray(raw) || raw.length === 0)
|
|
128
144
|
throw new WallError('invalid-ids', 'Select at least one note.');
|
|
129
145
|
if (raw.length > LIMITS.bulk)
|
|
130
146
|
throw new WallError('too-many-ids', `At most ${LIMITS.bulk} notes per request.`, { limit: LIMITS.bulk });
|
|
131
147
|
const ids = [...new Set(raw.map((id) => String(id ?? '')))];
|
|
132
|
-
if (ids.some((id) => id
|
|
148
|
+
if (ids.some((id) => !isNoteId(id)))
|
|
133
149
|
throw new WallError('invalid-ids', 'One of the selected note ids is invalid.');
|
|
134
150
|
return ids;
|
|
135
151
|
}
|
|
136
152
|
/**
|
|
137
|
-
* One
|
|
153
|
+
* One note's sort weight: pinned first, then the requested ordering, with the
|
|
138
154
|
* id as a final tiebreaker so two notes written in the same millisecond still
|
|
139
155
|
* render in a stable order.
|
|
140
156
|
*/
|
|
@@ -150,41 +166,83 @@ function compareNotes(sort) {
|
|
|
150
166
|
}
|
|
151
167
|
/** The store facade the Host endpoint and the agent tool share. */
|
|
152
168
|
export class StickyWallStore {
|
|
153
|
-
|
|
169
|
+
/** Absolute directory the notes live in. */
|
|
170
|
+
notesDir;
|
|
171
|
+
notes = new Map();
|
|
154
172
|
maxNotes;
|
|
155
173
|
now;
|
|
156
|
-
|
|
174
|
+
log;
|
|
175
|
+
/** Backing counter for {@link revision}. */
|
|
176
|
+
counter = 0;
|
|
157
177
|
closed = false;
|
|
158
178
|
/**
|
|
159
179
|
* Store-level mutation chain.
|
|
160
180
|
*
|
|
161
|
-
*
|
|
162
|
-
*
|
|
163
|
-
*
|
|
164
|
-
*
|
|
165
|
-
* write are one indivisible step.
|
|
181
|
+
* A read-then-write pair (the `maxNotes` check followed by the file write) is
|
|
182
|
+
* two steps, and two concurrent creates at the boundary would both read the
|
|
183
|
+
* pre-write count and both succeed. Every mutation therefore runs on this
|
|
184
|
+
* chain, so each check and its write are one indivisible step.
|
|
166
185
|
*/
|
|
167
186
|
chain = Promise.resolve();
|
|
168
|
-
constructor(
|
|
169
|
-
this.
|
|
170
|
-
this.maxNotes = maxNotes;
|
|
171
|
-
this.now = now;
|
|
172
|
-
this.
|
|
173
|
-
}
|
|
174
|
-
/**
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
187
|
+
constructor(options) {
|
|
188
|
+
this.notesDir = resolve(options.notesDir);
|
|
189
|
+
this.maxNotes = options.maxNotes;
|
|
190
|
+
this.now = options.now ?? (() => new Date());
|
|
191
|
+
this.log = options.log ?? (() => { });
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Open the notes directory and load every note.
|
|
195
|
+
*
|
|
196
|
+
* Order matters: the one-time migration runs BEFORE the directory is created,
|
|
197
|
+
* because the migration publishes its result with a single atomic `rename` of
|
|
198
|
+
* a staging directory and would otherwise have to rename over a directory this
|
|
199
|
+
* method had just made. Once the directory and the cache agree, the store is
|
|
200
|
+
* usable; every later read is served from memory.
|
|
201
|
+
*/
|
|
202
|
+
static async open(options) {
|
|
203
|
+
const store = new StickyWallStore(options);
|
|
204
|
+
if (options.readLegacy !== undefined) {
|
|
205
|
+
const result = await migrateNotes({
|
|
206
|
+
notesDir: store.notesDir,
|
|
207
|
+
readLegacy: options.readLegacy,
|
|
208
|
+
...(options.now === undefined ? {} : { now: options.now }),
|
|
209
|
+
});
|
|
210
|
+
if (!result.migrated && result.reason === 'failed') {
|
|
211
|
+
// The legacy wall is untouched and the next start retries, so the plugin
|
|
212
|
+
// still opens — empty rather than broken. Say so loudly enough that the
|
|
213
|
+
// Host log explains why the user's notes are missing.
|
|
214
|
+
store.log(`sticky-wall: legacy migration failed, opening an empty wall: ${result.error ?? 'unknown error'}`);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
await mkdir(store.notesDir, { recursive: true });
|
|
218
|
+
await store.load();
|
|
178
219
|
if (options.seedWelcomeNote)
|
|
179
220
|
await store.seedWelcomeNote();
|
|
180
221
|
return store;
|
|
181
222
|
}
|
|
182
|
-
/**
|
|
223
|
+
/**
|
|
224
|
+
* Monotonic change counter; bumps once per mutation that actually changed
|
|
225
|
+
* something.
|
|
226
|
+
*
|
|
227
|
+
* The Client cannot be pushed to, so it polls. An unchanged number means the
|
|
228
|
+
* caller must not touch component state at all — that is what keeps a
|
|
229
|
+
* background refresh from interrupting someone mid-composition in the editor.
|
|
230
|
+
*/
|
|
231
|
+
get revision() {
|
|
232
|
+
return this.counter;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Close the store: drain queued writes, then refuse new ones.
|
|
236
|
+
*
|
|
237
|
+
* Draining is the point. A mutation that started before `close()` may still be
|
|
238
|
+
* writing its file; dropping the chain would acknowledge a note to the Client
|
|
239
|
+
* and then lose it on shutdown.
|
|
240
|
+
*/
|
|
183
241
|
async close() {
|
|
184
242
|
if (this.closed)
|
|
185
243
|
return;
|
|
186
244
|
this.closed = true;
|
|
187
|
-
await this.
|
|
245
|
+
await this.chain;
|
|
188
246
|
}
|
|
189
247
|
assertOpen() {
|
|
190
248
|
if (this.closed)
|
|
@@ -196,9 +254,97 @@ export class StickyWallStore {
|
|
|
196
254
|
this.chain = result.then(() => undefined, () => undefined);
|
|
197
255
|
return result;
|
|
198
256
|
}
|
|
257
|
+
/** Absolute `.md` path for a note id. */
|
|
258
|
+
pathOf(id) {
|
|
259
|
+
if (!isNoteId(id))
|
|
260
|
+
throw new WallError('invalid-ids', `Note id ${JSON.stringify(id)} cannot be a file name.`, { id });
|
|
261
|
+
return join(this.notesDir, fileNameOf(id));
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Read every note file into the cache.
|
|
265
|
+
*
|
|
266
|
+
* The directory is the source of truth, so this is deliberately forgiving: a
|
|
267
|
+
* subdirectory, a file that is not named after a valid note id, a file too
|
|
268
|
+
* large to be a note, or one that cannot be read is skipped with a log line
|
|
269
|
+
* and the rest of the wall still opens.
|
|
270
|
+
*/
|
|
271
|
+
async load() {
|
|
272
|
+
let entries;
|
|
273
|
+
try {
|
|
274
|
+
entries = await readdir(this.notesDir, { withFileTypes: true });
|
|
275
|
+
}
|
|
276
|
+
catch (error) {
|
|
277
|
+
// The directory was removed between `mkdir` and here; an empty wall is the
|
|
278
|
+
// right answer, and the first write recreates it.
|
|
279
|
+
if (error.code === 'ENOENT')
|
|
280
|
+
return;
|
|
281
|
+
throw error;
|
|
282
|
+
}
|
|
283
|
+
for (const entry of entries) {
|
|
284
|
+
if (!entry.isFile())
|
|
285
|
+
continue;
|
|
286
|
+
const id = idOfFile(entry.name);
|
|
287
|
+
if (id === null)
|
|
288
|
+
continue;
|
|
289
|
+
const path = join(this.notesDir, entry.name);
|
|
290
|
+
try {
|
|
291
|
+
// Size is checked BEFORE the read: the point of the cap is not to hand a
|
|
292
|
+
// 200 MB accidental paste to the parser at all.
|
|
293
|
+
const info = await stat(path);
|
|
294
|
+
if (info.size > LIMITS.fileBytes) {
|
|
295
|
+
this.log(`sticky-wall: skipping oversized note file ${entry.name} (${String(info.size)} bytes)`);
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
const parsed = parseNoteFile(await readFile(path, 'utf8'), {
|
|
299
|
+
fallbackId: id,
|
|
300
|
+
// The file's own mtime is the only honest timestamp a hand-written
|
|
301
|
+
// note has; a note WITH frontmatter keeps its authored `created`.
|
|
302
|
+
fallbackTime: info.mtime.toISOString(),
|
|
303
|
+
});
|
|
304
|
+
// The file name is the identity on disk. A frontmatter `id` that
|
|
305
|
+
// disagrees (a hand-copied file, a rename) must not become a second
|
|
306
|
+
// address for the same note: the next write would then land in a
|
|
307
|
+
// different file and leave the loaded one behind.
|
|
308
|
+
this.notes.set(id, { ...parsed.note, id });
|
|
309
|
+
}
|
|
310
|
+
catch (error) {
|
|
311
|
+
this.log(`sticky-wall: skipping unreadable note file ${entry.name}: ${error instanceof Error ? error.message : String(error)}`);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Persist one note.
|
|
317
|
+
*
|
|
318
|
+
* The bytes go to a sibling temp file and are then `rename`d over the target:
|
|
319
|
+
* within one directory that is atomic, so a reader — or a crash — sees either
|
|
320
|
+
* the old note or the new one and never a half-written file. Writing the
|
|
321
|
+
* target directly would truncate it first, and a crash in that window loses
|
|
322
|
+
* the note outright.
|
|
323
|
+
*/
|
|
324
|
+
async writeNote(note) {
|
|
325
|
+
const target = this.pathOf(note.id);
|
|
326
|
+
const temporary = `${target}.tmp`;
|
|
327
|
+
await mkdir(this.notesDir, { recursive: true });
|
|
328
|
+
// The temp name never ends in `.md`, so a crash that strands one here is
|
|
329
|
+
// skipped by {@link load} as "not a note file" instead of being read back as
|
|
330
|
+
// a half-written note or a duplicate.
|
|
331
|
+
try {
|
|
332
|
+
await writeFile(temporary, serializeNoteFile(note), 'utf8');
|
|
333
|
+
await rename(temporary, target);
|
|
334
|
+
}
|
|
335
|
+
catch (error) {
|
|
336
|
+
// A failed write must not leave debris beside a note the user can see.
|
|
337
|
+
await rm(temporary, { force: true }).catch(() => { });
|
|
338
|
+
throw error;
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
/** Remove one note file; already gone is not an error. */
|
|
342
|
+
async dropFile(id) {
|
|
343
|
+
await rm(this.pathOf(id), { force: true });
|
|
344
|
+
}
|
|
199
345
|
liveCount() {
|
|
200
346
|
let count = 0;
|
|
201
|
-
for (const
|
|
347
|
+
for (const note of this.notes.values())
|
|
202
348
|
if (!note.archived)
|
|
203
349
|
count += 1;
|
|
204
350
|
return count;
|
|
@@ -247,17 +393,35 @@ export class StickyWallStore {
|
|
|
247
393
|
// the first ring keeps the invariant true from the very first note.
|
|
248
394
|
layout: { x: 300, y: -420, rotate: -1.6, width: 'md' },
|
|
249
395
|
};
|
|
250
|
-
await this.
|
|
396
|
+
await this.writeNote(note);
|
|
397
|
+
this.notes.set(note.id, note);
|
|
398
|
+
this.counter += 1;
|
|
399
|
+
}
|
|
400
|
+
/** One note by id, or `null` when the wall has no such note. */
|
|
401
|
+
read(id) {
|
|
402
|
+
this.assertOpen();
|
|
403
|
+
return this.notes.get(id) ?? null;
|
|
251
404
|
}
|
|
252
405
|
/** Every stored note, newest-relevant first; archived ones only on request. */
|
|
253
406
|
list(includeArchived = false, sort = 'pinned') {
|
|
254
407
|
this.assertOpen();
|
|
408
|
+
return this.gathered(includeArchived, sort);
|
|
409
|
+
}
|
|
410
|
+
/**
|
|
411
|
+
* The snapshot the store's own mutations work from.
|
|
412
|
+
*
|
|
413
|
+
* Deliberately does NOT check `closed`: {@link close} drains queued writes
|
|
414
|
+
* AFTER flipping the flag, so a mutation that was already acknowledged still
|
|
415
|
+
* has to run to completion — refusing it here would lose a note the caller
|
|
416
|
+
* was told was saved. It is private for exactly that reason: an outside caller
|
|
417
|
+
* always goes through {@link list}, which does check.
|
|
418
|
+
*/
|
|
419
|
+
gathered(includeArchived, sort) {
|
|
255
420
|
const notes = [];
|
|
256
|
-
for (const
|
|
257
|
-
|
|
258
|
-
if (value.archived && !includeArchived)
|
|
421
|
+
for (const note of this.notes.values()) {
|
|
422
|
+
if (note.archived && !includeArchived)
|
|
259
423
|
continue;
|
|
260
|
-
notes.push(
|
|
424
|
+
notes.push(note);
|
|
261
425
|
}
|
|
262
426
|
return notes.sort(compareNotes(sort));
|
|
263
427
|
}
|
|
@@ -277,6 +441,21 @@ export class StickyWallStore {
|
|
|
277
441
|
async createNow(input, id, options = {}) {
|
|
278
442
|
const body = normalizeBody(input?.body);
|
|
279
443
|
const title = normalizeTitle(input?.title);
|
|
444
|
+
// An explicit id becomes a file name, so it has to be one we would accept
|
|
445
|
+
// from disk as well; a generated UUID already satisfies this.
|
|
446
|
+
if (id !== undefined && !isNoteId(id))
|
|
447
|
+
throw new WallError('invalid-ids', `Note id ${JSON.stringify(id)} cannot be a file name.`, { id });
|
|
448
|
+
if (id !== undefined) {
|
|
449
|
+
// The FILE is the identity, not the cache entry: a note file big enough to
|
|
450
|
+
// be skipped at load, or one written by another tool while this store was
|
|
451
|
+
// open, is not in `notes` but is very much on disk. Overwriting it with a
|
|
452
|
+
// fresh note would destroy a file the user still has.
|
|
453
|
+
if (this.notes.has(id))
|
|
454
|
+
throw new WallError('duplicate-id', `A note with id ${JSON.stringify(id)} already exists.`);
|
|
455
|
+
const taken = await stat(this.pathOf(id)).then(() => true, () => false);
|
|
456
|
+
if (taken)
|
|
457
|
+
throw new WallError('duplicate-id', `A note file named ${JSON.stringify(fileNameOf(id))} already exists.`, { id });
|
|
458
|
+
}
|
|
280
459
|
this.assertRoom(1);
|
|
281
460
|
const stamp = this.now().toISOString();
|
|
282
461
|
const note = {
|
|
@@ -291,16 +470,17 @@ export class StickyWallStore {
|
|
|
291
470
|
updatedAt: stamp,
|
|
292
471
|
layout: input?.layout === undefined ? null : normalizeLayout(input.layout),
|
|
293
472
|
};
|
|
294
|
-
if (this.notes.get(note.id) !== undefined)
|
|
295
|
-
throw new WallError('duplicate-id', `A note with id ${JSON.stringify(note.id)} already exists.`);
|
|
296
473
|
// A note with no explicit placement gets the nearest free spot on the wall,
|
|
297
474
|
// not `null`. `null` means "derive a position from my index", and that spiral
|
|
298
475
|
// grows outward — so the user's tenth capture could land a screen away from
|
|
299
476
|
// where they were looking, which reads as the capture having failed.
|
|
300
477
|
if (note.layout === null) {
|
|
301
|
-
note.layout = findFreeLayout(note, this.
|
|
478
|
+
note.layout = findFreeLayout(note, this.gathered(true, 'pinned'), { centreReserve: normalizeReserve(options.centreReserve ?? CENTRE_RESERVE) });
|
|
302
479
|
}
|
|
303
|
-
|
|
480
|
+
// Disk first, then the cache: a resolution means the note exists as a file.
|
|
481
|
+
await this.writeNote(note);
|
|
482
|
+
this.notes.set(note.id, note);
|
|
483
|
+
this.counter += 1;
|
|
304
484
|
return note;
|
|
305
485
|
}
|
|
306
486
|
/** Apply one patch; `updatedAt` moves only when a field actually changed. */
|
|
@@ -312,9 +492,12 @@ export class StickyWallStore {
|
|
|
312
492
|
const current = this.notes.get(id);
|
|
313
493
|
if (current === undefined)
|
|
314
494
|
throw new WallError('not-found', `No note with id ${JSON.stringify(id)}.`, { id });
|
|
495
|
+
// The patch is applied OVER the current note, so `extra` (unknown
|
|
496
|
+
// frontmatter keys the user or a newer build owns) and `metaError` (why this
|
|
497
|
+
// file's frontmatter is suspect) ride through untouched.
|
|
315
498
|
const next = { ...current };
|
|
316
499
|
if (patch?.body !== undefined)
|
|
317
|
-
next.body =
|
|
500
|
+
next.body = normalizeBodyForUpdate(patch.body);
|
|
318
501
|
if (patch?.title !== undefined)
|
|
319
502
|
next.title = normalizeTitle(patch.title);
|
|
320
503
|
if (patch?.tags !== undefined)
|
|
@@ -330,10 +513,15 @@ export class StickyWallStore {
|
|
|
330
513
|
this.assertRoom(1);
|
|
331
514
|
const changed = ['body', 'title', 'color', 'pinned', 'archived'].some((key) => next[key] !== current[key]) ||
|
|
332
515
|
JSON.stringify(next.tags) !== JSON.stringify(current.tags);
|
|
516
|
+
// A patch that changes nothing writes nothing: no file churn, no revision
|
|
517
|
+
// bump, so a polling Client sees no reason to re-render.
|
|
333
518
|
if (!changed)
|
|
334
519
|
return current;
|
|
335
520
|
next.updatedAt = this.now().toISOString();
|
|
336
|
-
|
|
521
|
+
await this.writeNote(next);
|
|
522
|
+
this.notes.set(id, next);
|
|
523
|
+
this.counter += 1;
|
|
524
|
+
return next;
|
|
337
525
|
}
|
|
338
526
|
/**
|
|
339
527
|
* Flip the archived flag on a batch; returns the notes that actually moved.
|
|
@@ -361,10 +549,15 @@ export class StickyWallStore {
|
|
|
361
549
|
if (!archived)
|
|
362
550
|
this.assertRoom(targets.length);
|
|
363
551
|
const changed = [];
|
|
552
|
+
const stamp = this.now().toISOString();
|
|
364
553
|
for (const current of targets) {
|
|
365
|
-
const next = { ...current, archived, updatedAt:
|
|
366
|
-
|
|
554
|
+
const next = { ...current, archived, updatedAt: stamp };
|
|
555
|
+
await this.writeNote(next);
|
|
556
|
+
this.notes.set(next.id, next);
|
|
557
|
+
changed.push(next);
|
|
367
558
|
}
|
|
559
|
+
if (changed.length > 0)
|
|
560
|
+
this.counter += 1;
|
|
368
561
|
return changed;
|
|
369
562
|
}
|
|
370
563
|
/**
|
|
@@ -382,14 +575,17 @@ export class StickyWallStore {
|
|
|
382
575
|
async removeNow(ids) {
|
|
383
576
|
const selected = assertIds(ids);
|
|
384
577
|
for (const id of selected) {
|
|
385
|
-
if (this.notes.
|
|
578
|
+
if (!this.notes.has(id))
|
|
386
579
|
throw new WallError('not-found', `No note with id ${JSON.stringify(id)}.`, { id });
|
|
387
580
|
}
|
|
388
581
|
const removed = [];
|
|
389
582
|
for (const id of selected) {
|
|
390
|
-
await this.
|
|
583
|
+
await this.dropFile(id);
|
|
584
|
+
this.notes.delete(id);
|
|
391
585
|
removed.push(id);
|
|
392
586
|
}
|
|
587
|
+
if (removed.length > 0)
|
|
588
|
+
this.counter += 1;
|
|
393
589
|
return removed;
|
|
394
590
|
}
|
|
395
591
|
/**
|
|
@@ -409,9 +605,14 @@ export class StickyWallStore {
|
|
|
409
605
|
if (current === undefined)
|
|
410
606
|
throw new WallError('not-found', `No note with id ${JSON.stringify(id)}.`, { id });
|
|
411
607
|
const next = normalizeLayout(layout);
|
|
608
|
+
// The same placement again is a no-op: no write, no revision bump.
|
|
412
609
|
if (sameLayout(current.layout, next))
|
|
413
610
|
return current;
|
|
414
|
-
|
|
611
|
+
const moved = { ...current, layout: next };
|
|
612
|
+
await this.writeNote(moved);
|
|
613
|
+
this.notes.set(id, moved);
|
|
614
|
+
this.counter += 1;
|
|
615
|
+
return moved;
|
|
415
616
|
}
|
|
416
617
|
/**
|
|
417
618
|
* Tidy the wall: repack every note into a deterministic shelf arrangement.
|
|
@@ -429,15 +630,20 @@ export class StickyWallStore {
|
|
|
429
630
|
// archived-but-visible card at its dragged position, on top of the freshly
|
|
430
631
|
// tidied ones — the wall has to be tidy in every filter, not just the
|
|
431
632
|
// default one.
|
|
432
|
-
const current = this.
|
|
633
|
+
const current = this.gathered(true, 'pinned');
|
|
433
634
|
const planned = arrangeLayouts(current, { centreReserve: normalizeReserve(options.centreReserve ?? CENTRE_RESERVE) });
|
|
434
635
|
const changed = [];
|
|
435
636
|
for (const note of current) {
|
|
436
637
|
const target = planned.get(note.id);
|
|
437
638
|
if (target === undefined || sameLayout(note.layout, target))
|
|
438
639
|
continue;
|
|
439
|
-
|
|
640
|
+
const moved = { ...note, layout: target };
|
|
641
|
+
await this.writeNote(moved);
|
|
642
|
+
this.notes.set(note.id, moved);
|
|
643
|
+
changed.push(moved);
|
|
440
644
|
}
|
|
645
|
+
if (changed.length > 0)
|
|
646
|
+
this.counter += 1;
|
|
441
647
|
return changed;
|
|
442
648
|
}
|
|
443
649
|
/**
|
|
@@ -452,12 +658,15 @@ export class StickyWallStore {
|
|
|
452
658
|
return this.mutate(() => this.clearArchivedNow());
|
|
453
659
|
}
|
|
454
660
|
async clearArchivedNow() {
|
|
455
|
-
const archived = this.
|
|
661
|
+
const archived = this.gathered(true, 'pinned').filter((note) => note.archived).map((note) => note.id);
|
|
456
662
|
const removed = [];
|
|
457
663
|
for (const id of archived) {
|
|
458
|
-
await this.
|
|
664
|
+
await this.dropFile(id);
|
|
665
|
+
this.notes.delete(id);
|
|
459
666
|
removed.push(id);
|
|
460
667
|
}
|
|
668
|
+
if (removed.length > 0)
|
|
669
|
+
this.counter += 1;
|
|
461
670
|
return removed;
|
|
462
671
|
}
|
|
463
672
|
/** Compact plain-text digest of the wall for the model-facing tool. */
|
|
@@ -467,7 +676,7 @@ export class StickyWallStore {
|
|
|
467
676
|
return {
|
|
468
677
|
total: all.length,
|
|
469
678
|
archived: all.filter((note) => note.archived).length,
|
|
470
|
-
notes: all.slice(0, Math.max(1, Math.min(limit,
|
|
679
|
+
notes: all.slice(0, Math.max(1, Math.min(limit, LIMITS.listLimit))),
|
|
471
680
|
};
|
|
472
681
|
}
|
|
473
682
|
}
|
package/lib/transport.d.ts
CHANGED
|
@@ -30,7 +30,13 @@ export interface HostConnection {
|
|
|
30
30
|
/** The store operations the route dispatches onto. */
|
|
31
31
|
export interface WallActions {
|
|
32
32
|
list(includeArchived?: boolean, sort?: NoteSort): Note[];
|
|
33
|
-
|
|
33
|
+
/** The Host's current change counter, for the Client's cheap poll. */
|
|
34
|
+
revisionOf(): number;
|
|
35
|
+
/** Absolute directory the notes live in. */
|
|
36
|
+
readonly notesDir: string;
|
|
37
|
+
create(input: NoteInput, id?: string, options?: {
|
|
38
|
+
centreReserve?: CentreReserve | undefined;
|
|
39
|
+
}): Promise<Note>;
|
|
34
40
|
update(id: string, patch: NotePatch): Promise<Note>;
|
|
35
41
|
setArchived(ids: string[], archived: boolean): Promise<Note[]>;
|
|
36
42
|
remove(ids: string[]): Promise<string[]>;
|
|
@@ -39,9 +45,6 @@ export interface WallActions {
|
|
|
39
45
|
arrange(options?: {
|
|
40
46
|
centreReserve?: CentreReserve | undefined;
|
|
41
47
|
}): Promise<Note[]>;
|
|
42
|
-
create(input: NoteInput, id?: string, options?: {
|
|
43
|
-
centreReserve?: CentreReserve | undefined;
|
|
44
|
-
}): Promise<Note>;
|
|
45
48
|
}
|
|
46
49
|
/**
|
|
47
50
|
* Build the exact route Connection registers; every failure stays inside the
|