@skillre/dsh-plugin-sticky-wall 0.7.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 +34 -11
- package/README.md +35 -14
- package/UNINSTALL.md +22 -7
- package/compatibility.json +78 -1
- package/lib/client.js +1062 -337
- 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/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 +14 -3
- package/lib/types.d.ts +87 -6
- 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/index.js
CHANGED
|
@@ -7,23 +7,58 @@
|
|
|
7
7
|
* route, and the optional agent tool — belongs to this plugin's Fiber, so
|
|
8
8
|
* stopping or updating the row releases all three with no residue.
|
|
9
9
|
*/
|
|
10
|
-
import {
|
|
10
|
+
import { homedir } from 'node:os';
|
|
11
|
+
import { Config, resolveConfig, resolveNotesDir } from './config.js';
|
|
11
12
|
import { StickyWallStore } from './store.js';
|
|
12
13
|
import { createExecuteRoute } from './transport.js';
|
|
13
|
-
import { LIMITS } from './types.js';
|
|
14
|
+
import { LEGACY_DOMAIN_NAME, LEGACY_DOMAIN_VERSION, LIMITS } from './types.js';
|
|
14
15
|
export { Config, StickyWallStore };
|
|
15
16
|
export const name = 'skillre-sticky-wall';
|
|
16
17
|
/**
|
|
17
|
-
* Required services.
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
18
|
+
* Required services.
|
|
19
|
+
*
|
|
20
|
+
* `connection` provides the authenticated Client route and is a hard dependency:
|
|
21
|
+
* without it the wall could never be reached, so mounting should fail loudly.
|
|
22
|
+
*
|
|
23
|
+
* `storageDomain` is deliberately NOT listed. Notes live on disk now, and the
|
|
24
|
+
* domain is consulted only when a 0.7.x install still needs migrating, so it is
|
|
25
|
+
* read through `ctx.get()` and its absence is a normal, supported state (a fresh
|
|
26
|
+
* install has nothing to migrate).
|
|
21
27
|
*/
|
|
22
|
-
export const inject = ['
|
|
28
|
+
export const inject = ['connection'];
|
|
23
29
|
/** Read an optional Cordis service without declaring it required. */
|
|
24
30
|
function service(ctx, key) {
|
|
25
31
|
return ctx.get(key);
|
|
26
32
|
}
|
|
33
|
+
/**
|
|
34
|
+
* Drain a 0.7.x install's storage-domain notes so they can be migrated.
|
|
35
|
+
*
|
|
36
|
+
* The domain's `notes` table is the ONLY thing read here: the migration writes
|
|
37
|
+
* `.md` files and never writes back, so a failed migration leaves the legacy
|
|
38
|
+
* records untouched and the next start retries. The handle is always closed,
|
|
39
|
+
* even when reading throws, because an open domain reserves its name for the
|
|
40
|
+
* whole process.
|
|
41
|
+
*/
|
|
42
|
+
async function readLegacyNotes(facility) {
|
|
43
|
+
const domain = await facility.open({
|
|
44
|
+
name: LEGACY_DOMAIN_NAME,
|
|
45
|
+
version: LEGACY_DOMAIN_VERSION,
|
|
46
|
+
layout: 'per-record',
|
|
47
|
+
invalidRecords: 'backup-and-skip',
|
|
48
|
+
tables: { notes: {} },
|
|
49
|
+
});
|
|
50
|
+
try {
|
|
51
|
+
const notes = [];
|
|
52
|
+
for (const [, value] of domain.table('notes').entries()) {
|
|
53
|
+
if (value !== null && typeof value === 'object' && 'id' in value)
|
|
54
|
+
notes.push(value);
|
|
55
|
+
}
|
|
56
|
+
return notes;
|
|
57
|
+
}
|
|
58
|
+
finally {
|
|
59
|
+
await domain.close();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
27
62
|
/** Model-facing text for one tool result; short, deterministic and readable. */
|
|
28
63
|
function renderWall(value) {
|
|
29
64
|
const data = (value ?? {});
|
|
@@ -41,6 +76,22 @@ function renderWall(value) {
|
|
|
41
76
|
});
|
|
42
77
|
return [`${String(data.total ?? notes.length)} notes (${String(data.archived ?? 0)} archived):`, ...lines].join('\n');
|
|
43
78
|
}
|
|
79
|
+
if (action === 'read') {
|
|
80
|
+
// The whole point of this action: the model gets the note's FULL text, not a
|
|
81
|
+
// 140-character head. Without it an agent asked to expand a note had to ask
|
|
82
|
+
// the user to paste it back, which is exactly the friction this removes.
|
|
83
|
+
const note = data.note;
|
|
84
|
+
if (note === undefined)
|
|
85
|
+
return 'No such note.';
|
|
86
|
+
const meta = [
|
|
87
|
+
`id: ${note.id}`,
|
|
88
|
+
note.title !== '' ? `title: ${note.title}` : '',
|
|
89
|
+
`color: ${note.color}${note.pinned ? ' · pinned' : ''}${note.archived ? ' · archived' : ''}`,
|
|
90
|
+
note.tags.length > 0 ? `tags: ${note.tags.join(', ')}` : '',
|
|
91
|
+
typeof data.path === 'string' ? `file: ${data.path}` : '',
|
|
92
|
+
].filter((line) => line !== '');
|
|
93
|
+
return [...meta, '', note.body].join('\n');
|
|
94
|
+
}
|
|
44
95
|
if (action === 'arrange') {
|
|
45
96
|
const notes = Array.isArray(data.changed) ? data.changed : [];
|
|
46
97
|
return notes.length === 0 ? 'The wall was already tidy.' : `Tidied ${notes.length} note${notes.length === 1 ? '' : 's'} into the shelf arrangement.`;
|
|
@@ -54,8 +105,10 @@ function renderWall(value) {
|
|
|
54
105
|
return notes.length === 0 ? 'No note changed.' : notes.map((note) => `${note.id} ${note.archived ? 'archived' : 'restored'}`).join('\n');
|
|
55
106
|
}
|
|
56
107
|
const note = data.note;
|
|
57
|
-
if (note)
|
|
58
|
-
|
|
108
|
+
if (note) {
|
|
109
|
+
const where = note.layout === null ? '' : ` at (${String(note.layout.x)}, ${String(note.layout.y)})`;
|
|
110
|
+
return `${action === 'create' ? 'Created' : 'Updated'} note ${note.id}${note.title ? ` (${note.title})` : ''}${where}: ${note.body.replace(/\s+/g, ' ').slice(0, 140)}`;
|
|
111
|
+
}
|
|
59
112
|
return 'Done.';
|
|
60
113
|
}
|
|
61
114
|
/** Register the model-facing capture tool when the registry is present. */
|
|
@@ -66,30 +119,48 @@ function registerAgentTool(ctx, ready) {
|
|
|
66
119
|
ctx.effect(() => {
|
|
67
120
|
const disposer = tools.register({
|
|
68
121
|
name: 'sticky_wall',
|
|
69
|
-
description: "Capture and manage sticky notes on the user's DSH note wall (便签墙): quick inspiration, temporary tasks and short reminders.
|
|
122
|
+
description: "Capture and manage sticky notes on the user's DSH note wall (便签墙): quick inspiration, temporary tasks and short reminders. " +
|
|
123
|
+
'Each note is a real Markdown file under the notes directory: its attributes (title, colour, tags, pin, size, canvas position) live in the YAML frontmatter block at the top, and everything after that block is the note body. ' +
|
|
124
|
+
"Use `read` to get a note's full text, `list` to scan titles, `create`/`update` to write attributes or text, and `move` to place a card on the canvas. " +
|
|
125
|
+
"To revise a note's PROSE you may edit the backing file directly with the file tools — but never modify the frontmatter between the `---` lines; change attributes with this tool's `update` action instead.",
|
|
70
126
|
parameters: {
|
|
71
127
|
type: 'object',
|
|
72
128
|
additionalProperties: false,
|
|
73
129
|
required: ['action'],
|
|
74
130
|
properties: {
|
|
75
|
-
action: {
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
131
|
+
action: {
|
|
132
|
+
type: 'string',
|
|
133
|
+
enum: ['list', 'read', 'create', 'update', 'move', 'archive', 'delete', 'clear-archived', 'arrange'],
|
|
134
|
+
description: 'list: scan notes. read: one note in full. create/update: write attributes or text. move: place one card on the canvas. archive/delete: batch state changes. clear-archived: permanent sweep. arrange: tidy the whole wall.',
|
|
135
|
+
},
|
|
136
|
+
id: { type: 'string', description: 'Exact note id; required by read, update and move.' },
|
|
137
|
+
ids: { type: 'array', items: { type: 'string' }, description: `Note ids; required by archive and delete (1–${LIMITS.bulk} entries).` },
|
|
138
|
+
body: { type: 'string', description: `The note text. Required by create; optional patch field for update. Max ${LIMITS.body} characters.` },
|
|
139
|
+
title: { type: 'string', description: `Short heading (max ${LIMITS.title} characters); '' clears it.` },
|
|
140
|
+
tags: { type: 'array', items: { type: 'string' }, description: `Lowercase tags (max ${LIMITS.tags}, each max ${LIMITS.tag} characters); [] clears them.` },
|
|
141
|
+
color: { type: 'string', enum: ['yellow', 'pink', 'green', 'blue', 'purple', 'orange'], description: 'Pastel note colour.' },
|
|
82
142
|
pinned: { type: 'boolean', description: 'Pin the note to the top of the wall.' },
|
|
83
|
-
archived: {
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
143
|
+
archived: {
|
|
144
|
+
type: 'boolean',
|
|
145
|
+
// Required rather than defaulted: a model asked to RESTORE a note that
|
|
146
|
+
// merely omits this field used to re-archive it, silently doing the
|
|
147
|
+
// opposite of the request. A destructive flag must never default.
|
|
148
|
+
description: 'Required by archive: true archives, false restores. Never omitted.',
|
|
149
|
+
},
|
|
150
|
+
includeArchived: { type: 'boolean', description: 'list only: include archived notes (default false).' },
|
|
151
|
+
x: { type: 'number', description: 'Canvas horizontal position of the card, in canvas pixels. Used by create and move.' },
|
|
152
|
+
y: { type: 'number', description: 'Canvas vertical position of the card, in canvas pixels. Used by create and move.' },
|
|
153
|
+
width: { type: 'string', enum: ['sm', 'md', 'lg'], description: 'Card width preset. Used by create and move.' },
|
|
154
|
+
rotate: { type: 'number', description: 'Card tilt in degrees, clamped to ±12. Used by create and move.' },
|
|
155
|
+
limit: { type: 'integer', description: `list only: how many notes to return (1–${LIMITS.listLimit}, default 20).` },
|
|
88
156
|
},
|
|
89
157
|
},
|
|
90
158
|
timeoutMs: 20_000,
|
|
91
159
|
isConcurrencySafe(args) {
|
|
92
|
-
|
|
160
|
+
if (typeof args !== 'object' || args === null)
|
|
161
|
+
return false;
|
|
162
|
+
const action = args.action;
|
|
163
|
+
return action === 'list' || action === 'read';
|
|
93
164
|
},
|
|
94
165
|
output: {
|
|
95
166
|
schema: { type: 'object', additionalProperties: true },
|
|
@@ -101,10 +172,31 @@ function registerAgentTool(ctx, ready) {
|
|
|
101
172
|
execution.signal.throwIfAborted();
|
|
102
173
|
const store = await ready;
|
|
103
174
|
const args = (raw ?? {});
|
|
175
|
+
/** A complete placement from the flat coordinates, when all of them exist. */
|
|
176
|
+
const layoutFrom = () => {
|
|
177
|
+
if (typeof args.x !== 'number' || typeof args.y !== 'number')
|
|
178
|
+
return undefined;
|
|
179
|
+
const width = args.width === 'sm' || args.width === 'md' || args.width === 'lg' ? args.width : 'md';
|
|
180
|
+
return { x: args.x, y: args.y, rotate: typeof args.rotate === 'number' ? args.rotate : 0, width };
|
|
181
|
+
};
|
|
104
182
|
switch (args.action) {
|
|
105
|
-
case 'list':
|
|
106
|
-
|
|
107
|
-
|
|
183
|
+
case 'list': {
|
|
184
|
+
// `includeArchived` was declared but ignored: `summary()` always read
|
|
185
|
+
// every note, so the tool's own description was false. Filter here so
|
|
186
|
+
// the flag means what it says.
|
|
187
|
+
const summary = store.summary(typeof args.limit === 'number' ? args.limit : 20);
|
|
188
|
+
const notes = args.includeArchived === true ? summary.notes : summary.notes.filter((note) => !note.archived);
|
|
189
|
+
return { action: 'list', ...summary, notes, archived: summary.archived, total: summary.total };
|
|
190
|
+
}
|
|
191
|
+
case 'read': {
|
|
192
|
+
const id = String(args.id ?? '');
|
|
193
|
+
const note = store.read(id);
|
|
194
|
+
if (note === null)
|
|
195
|
+
throw new Error(`No note with id ${JSON.stringify(id)}.`);
|
|
196
|
+
return { action: 'read', note, path: store.pathOf(id) };
|
|
197
|
+
}
|
|
198
|
+
case 'create': {
|
|
199
|
+
const placement = layoutFrom();
|
|
108
200
|
return {
|
|
109
201
|
action: 'create',
|
|
110
202
|
note: await store.create({
|
|
@@ -113,11 +205,10 @@ function registerAgentTool(ctx, ready) {
|
|
|
113
205
|
...(Array.isArray(args.tags) ? { tags: args.tags.map(String) } : {}),
|
|
114
206
|
...(typeof args.color === 'string' ? { color: args.color } : {}),
|
|
115
207
|
...(typeof args.pinned === 'boolean' ? { pinned: args.pinned } : {}),
|
|
116
|
-
...(
|
|
117
|
-
? { layout: { x: args.x, y: args.y, rotate: 0, width: 'md' } }
|
|
118
|
-
: {}),
|
|
208
|
+
...(placement === undefined ? {} : { layout: placement }),
|
|
119
209
|
}),
|
|
120
210
|
};
|
|
211
|
+
}
|
|
121
212
|
case 'update':
|
|
122
213
|
return {
|
|
123
214
|
action: 'update',
|
|
@@ -130,8 +221,27 @@ function registerAgentTool(ctx, ready) {
|
|
|
130
221
|
...(typeof args.archived === 'boolean' ? { archived: args.archived } : {}),
|
|
131
222
|
}),
|
|
132
223
|
};
|
|
224
|
+
case 'move': {
|
|
225
|
+
const id = String(args.id ?? '');
|
|
226
|
+
const current = store.read(id);
|
|
227
|
+
if (current === null)
|
|
228
|
+
throw new Error(`No note with id ${JSON.stringify(id)}.`);
|
|
229
|
+
// A move keeps whatever the caller did not restate, so positioning a
|
|
230
|
+
// card does not silently change its size or straighten its tilt.
|
|
231
|
+
const base = current.layout;
|
|
232
|
+
const layout = {
|
|
233
|
+
x: typeof args.x === 'number' ? args.x : base?.x ?? 0,
|
|
234
|
+
y: typeof args.y === 'number' ? args.y : base?.y ?? 0,
|
|
235
|
+
rotate: typeof args.rotate === 'number' ? args.rotate : base?.rotate ?? 0,
|
|
236
|
+
width: args.width === 'sm' || args.width === 'md' || args.width === 'lg' ? args.width : base?.width ?? 'md',
|
|
237
|
+
};
|
|
238
|
+
return { action: 'move', note: await store.move(id, layout) };
|
|
239
|
+
}
|
|
133
240
|
case 'archive':
|
|
134
|
-
|
|
241
|
+
// A destructive flag must be stated, never inferred.
|
|
242
|
+
if (typeof args.archived !== 'boolean')
|
|
243
|
+
throw new Error('archive requires `archived: true` to archive or `archived: false` to restore.');
|
|
244
|
+
return { action: 'archive', notes: await store.setArchived(args.ids ?? [], args.archived) };
|
|
135
245
|
case 'delete':
|
|
136
246
|
return { action: 'delete', removed: await store.remove(args.ids ?? []) };
|
|
137
247
|
case 'clear-archived':
|
|
@@ -151,17 +261,22 @@ export function apply(ctx, rawConfig = {}) {
|
|
|
151
261
|
const connection = service(ctx, 'connection');
|
|
152
262
|
if (!connection?.fetch?.register)
|
|
153
263
|
throw new Error('Sticky wall requires the current DSH Connection exact Fetch-route registry.');
|
|
264
|
+
const notesDir = resolveNotesDir(config.notesDir, process.env, homedir());
|
|
265
|
+
// The legacy storage domain is now OPTIONAL: notes live on disk, and the
|
|
266
|
+
// domain is only opened once, to drain a 0.7.x install's records into `.md`
|
|
267
|
+
// files. A profile that never had the domain simply has nothing to migrate.
|
|
154
268
|
const facility = service(ctx, 'storageDomain');
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
const ready = StickyWallStore.open((spec) => facility.open(spec), {
|
|
269
|
+
const ready = StickyWallStore.open({
|
|
270
|
+
notesDir,
|
|
158
271
|
maxNotes: config.maxNotes,
|
|
159
272
|
seedWelcomeNote: config.seedWelcomeNote,
|
|
273
|
+
readLegacy: facility?.open === undefined ? undefined : () => readLegacyNotes(facility),
|
|
274
|
+
log: (message) => ctx.logger?.warn?.(`sticky-wall: ${message}`),
|
|
160
275
|
});
|
|
161
276
|
ready.catch((error) => {
|
|
162
277
|
// The route and the tool both await `ready`, so the failure also reaches the
|
|
163
278
|
// first caller; log it once so it is never silent in the Host log.
|
|
164
|
-
ctx.logger?.error?.(`sticky-wall:
|
|
279
|
+
ctx.logger?.error?.(`sticky-wall: notes directory failed to open: ${error instanceof Error ? error.message : String(error)}`);
|
|
165
280
|
});
|
|
166
281
|
ctx.effect(() => () => {
|
|
167
282
|
void ready.then((store) => store.close()).catch(() => { });
|
|
@@ -170,13 +285,15 @@ export function apply(ctx, rawConfig = {}) {
|
|
|
170
285
|
const store = await ready;
|
|
171
286
|
return {
|
|
172
287
|
list: (includeArchived, sort) => store.list(includeArchived, sort),
|
|
173
|
-
|
|
288
|
+
revisionOf: () => store.revision,
|
|
289
|
+
notesDir: store.notesDir,
|
|
290
|
+
create: (input, id, options) => store.create(input, id, options),
|
|
174
291
|
update: (id, patch) => store.update(id, patch),
|
|
175
292
|
setArchived: (ids, archived) => store.setArchived(ids, archived),
|
|
176
293
|
remove: (ids) => store.remove(ids),
|
|
177
294
|
clearArchived: () => store.clearArchived(),
|
|
178
295
|
move: (id, layout) => store.move(id, layout),
|
|
179
|
-
arrange: () => store.arrange(),
|
|
296
|
+
arrange: (options) => store.arrange(options),
|
|
180
297
|
};
|
|
181
298
|
})), 'skillre-sticky-wall client route');
|
|
182
299
|
if (config.enableAgentTool)
|
package/lib/migrate.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One-time migration from the 0.7.x storage domain to real `.md` files.
|
|
3
|
+
*
|
|
4
|
+
* The old build kept a wall in a JSON storage domain. 0.8.0 stores one file per
|
|
5
|
+
* note instead, so an existing user's wall has to be carried across exactly once,
|
|
6
|
+
* without losing a note and without ever leaving a half-migrated directory that
|
|
7
|
+
* the next start would mistake for a finished one.
|
|
8
|
+
*
|
|
9
|
+
* The whole design follows from one requirement: **the notes directory must
|
|
10
|
+
* never be observable in a partial state.** So the notes are written into a
|
|
11
|
+
* sibling staging directory and published with a single `rename`, which is
|
|
12
|
+
* atomic within one parent directory. A crash before the rename leaves the legacy
|
|
13
|
+
* wall untouched and the staging directory removable; a crash after it leaves a
|
|
14
|
+
* complete wall that the marker then declares migrated.
|
|
15
|
+
*
|
|
16
|
+
* Nothing here is on the hot path, and nothing here runs when the directory
|
|
17
|
+
* already holds notes: a user who has been on 0.8.0 for months must not have a
|
|
18
|
+
* stale legacy domain re-imported over edits they have made since.
|
|
19
|
+
*/
|
|
20
|
+
import { type Note } from './types.js';
|
|
21
|
+
/** What one migration attempt did, and why it did nothing when it did nothing. */
|
|
22
|
+
export interface MigrateResult {
|
|
23
|
+
/** True only when this call published the notes directory. */
|
|
24
|
+
migrated: boolean;
|
|
25
|
+
/**
|
|
26
|
+
* Stable outcome: `migrated`, `already-present`, `no-legacy`, or `failed`.
|
|
27
|
+
*
|
|
28
|
+
* `already-present` is the normal steady state, not an error — it is what a
|
|
29
|
+
* second start reports after a successful migration.
|
|
30
|
+
*/
|
|
31
|
+
reason: string;
|
|
32
|
+
/** Notes carried across, set only when `migrated` is true. */
|
|
33
|
+
count?: number;
|
|
34
|
+
/** Human-readable cause, set only when `reason` is `failed`. */
|
|
35
|
+
error?: string;
|
|
36
|
+
}
|
|
37
|
+
/** Everything the migration needs; `now` is injectable for a deterministic marker. */
|
|
38
|
+
export interface MigrateOptions {
|
|
39
|
+
/** Destination directory, `<DSH_HOME>/sticky-notes`. */
|
|
40
|
+
notesDir: string;
|
|
41
|
+
/** Drains the legacy storage domain; resolves to every note it held. */
|
|
42
|
+
readLegacy: () => Promise<Note[]>;
|
|
43
|
+
/** Clock for the marker's `at` field. */
|
|
44
|
+
now?: (() => Date) | undefined;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Move the legacy notes into `notesDir`, or explain why there was nothing to do.
|
|
48
|
+
*
|
|
49
|
+
* Never throws for an expected outcome: a failed migration is reported as
|
|
50
|
+
* `{ migrated: false, reason: 'failed' }` with the notes directory left absent,
|
|
51
|
+
* so the next start retries with the legacy wall still intact.
|
|
52
|
+
*/
|
|
53
|
+
export declare function migrateNotes(options: MigrateOptions): Promise<MigrateResult>;
|
package/lib/migrate.js
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One-time migration from the 0.7.x storage domain to real `.md` files.
|
|
3
|
+
*
|
|
4
|
+
* The old build kept a wall in a JSON storage domain. 0.8.0 stores one file per
|
|
5
|
+
* note instead, so an existing user's wall has to be carried across exactly once,
|
|
6
|
+
* without losing a note and without ever leaving a half-migrated directory that
|
|
7
|
+
* the next start would mistake for a finished one.
|
|
8
|
+
*
|
|
9
|
+
* The whole design follows from one requirement: **the notes directory must
|
|
10
|
+
* never be observable in a partial state.** So the notes are written into a
|
|
11
|
+
* sibling staging directory and published with a single `rename`, which is
|
|
12
|
+
* atomic within one parent directory. A crash before the rename leaves the legacy
|
|
13
|
+
* wall untouched and the staging directory removable; a crash after it leaves a
|
|
14
|
+
* complete wall that the marker then declares migrated.
|
|
15
|
+
*
|
|
16
|
+
* Nothing here is on the hot path, and nothing here runs when the directory
|
|
17
|
+
* already holds notes: a user who has been on 0.8.0 for months must not have a
|
|
18
|
+
* stale legacy domain re-imported over edits they have made since.
|
|
19
|
+
*/
|
|
20
|
+
import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
21
|
+
import { dirname, join, resolve } from 'node:path';
|
|
22
|
+
import { fileNameOf, idOfFile, isNoteId, parseNoteFile, serializeNoteFile } from './frontmatter.js';
|
|
23
|
+
import { LEGACY_DOMAIN_NAME, LIMITS, MIGRATION_MARKER } from './types.js';
|
|
24
|
+
/** The staging directory the migration writes into before publishing. */
|
|
25
|
+
function stagingDirOf(notesDir) {
|
|
26
|
+
return `${notesDir}.migrating`;
|
|
27
|
+
}
|
|
28
|
+
/** True when the directory already holds something this migration must not touch. */
|
|
29
|
+
async function isAlreadyPresent(notesDir) {
|
|
30
|
+
let entries;
|
|
31
|
+
try {
|
|
32
|
+
entries = await readdir(notesDir);
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
const code = error.code;
|
|
36
|
+
// No directory, or the path is not a directory at all: nothing to protect.
|
|
37
|
+
// Any other failure is a real I/O problem and is reported as a failure by
|
|
38
|
+
// the caller rather than being read as "empty".
|
|
39
|
+
if (code === 'ENOENT' || code === 'ENOTDIR')
|
|
40
|
+
return false;
|
|
41
|
+
throw error;
|
|
42
|
+
}
|
|
43
|
+
return entries.some((name) => name === MIGRATION_MARKER || idOfFile(name) !== null);
|
|
44
|
+
}
|
|
45
|
+
/** Two timestamps name the same instant, tolerating format-only differences. */
|
|
46
|
+
function sameInstant(left, right) {
|
|
47
|
+
if (left === right)
|
|
48
|
+
return true;
|
|
49
|
+
const a = new Date(left).getTime();
|
|
50
|
+
const b = new Date(right).getTime();
|
|
51
|
+
return !Number.isNaN(a) && !Number.isNaN(b) && a === b;
|
|
52
|
+
}
|
|
53
|
+
/** One field-by-field read-back comparison between the legacy note and its file. */
|
|
54
|
+
function sameNote(expected, actual) {
|
|
55
|
+
return (expected.id === actual.id &&
|
|
56
|
+
expected.title === actual.title &&
|
|
57
|
+
expected.body === actual.body &&
|
|
58
|
+
expected.color === actual.color &&
|
|
59
|
+
expected.pinned === actual.pinned &&
|
|
60
|
+
expected.archived === actual.archived &&
|
|
61
|
+
expected.tags.length === actual.tags.length &&
|
|
62
|
+
expected.tags.every((tag, index) => tag === actual.tags[index]) &&
|
|
63
|
+
sameLayout(expected.layout, actual.layout) &&
|
|
64
|
+
sameInstant(expected.createdAt, actual.createdAt) &&
|
|
65
|
+
sameInstant(expected.updatedAt, actual.updatedAt));
|
|
66
|
+
}
|
|
67
|
+
/** Compare two placements, treating two `null`s as equal. */
|
|
68
|
+
function sameLayout(left, right) {
|
|
69
|
+
if (left === null || right === null)
|
|
70
|
+
return left === right;
|
|
71
|
+
return left.x === right.x && left.y === right.y && left.rotate === right.rotate && left.width === right.width;
|
|
72
|
+
}
|
|
73
|
+
/** Remove the staging directory, ignoring the case where it is already gone. */
|
|
74
|
+
async function discardStaging(staging) {
|
|
75
|
+
await rm(staging, { recursive: true, force: true });
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Move the legacy notes into `notesDir`, or explain why there was nothing to do.
|
|
79
|
+
*
|
|
80
|
+
* Never throws for an expected outcome: a failed migration is reported as
|
|
81
|
+
* `{ migrated: false, reason: 'failed' }` with the notes directory left absent,
|
|
82
|
+
* so the next start retries with the legacy wall still intact.
|
|
83
|
+
*/
|
|
84
|
+
export async function migrateNotes(options) {
|
|
85
|
+
const notesDir = resolve(options.notesDir);
|
|
86
|
+
const staging = stagingDirOf(notesDir);
|
|
87
|
+
let renamed = false;
|
|
88
|
+
try {
|
|
89
|
+
if (await isAlreadyPresent(notesDir))
|
|
90
|
+
return { migrated: false, reason: 'already-present' };
|
|
91
|
+
const legacy = await options.readLegacy();
|
|
92
|
+
if (legacy.length === 0)
|
|
93
|
+
return { migrated: false, reason: 'no-legacy' };
|
|
94
|
+
// The id becomes a file name, so it has to be one this build would accept
|
|
95
|
+
// from disk. Ids are NOT filtered by shape otherwise: a 0.7.x wall could hold
|
|
96
|
+
// `welcome` (the seeded note does), and rewriting it to a UUID would break
|
|
97
|
+
// every link the user has to that note.
|
|
98
|
+
const invalid = legacy.find((note) => !isNoteId(note.id));
|
|
99
|
+
if (invalid !== undefined)
|
|
100
|
+
throw new Error(`legacy note id ${JSON.stringify(invalid.id)} is not a valid file name`);
|
|
101
|
+
// A leftover staging directory is debris from an interrupted attempt; its
|
|
102
|
+
// contents are untrusted, so it is discarded rather than resumed into.
|
|
103
|
+
await discardStaging(staging);
|
|
104
|
+
await mkdir(dirname(notesDir), { recursive: true });
|
|
105
|
+
await mkdir(staging, { recursive: true });
|
|
106
|
+
for (const note of legacy) {
|
|
107
|
+
await writeFile(join(staging, fileNameOf(note.id)), serializeNoteFile(note), 'utf8');
|
|
108
|
+
}
|
|
109
|
+
// Publish. A directory left by an earlier attempt is empty — a `.md` or a
|
|
110
|
+
// marker in it would have ended this run at `already-present` — and POSIX
|
|
111
|
+
// `rename` replaces an empty destination directory atomically. A destination
|
|
112
|
+
// holding anything else is NOT touched: this plugin never removes files it
|
|
113
|
+
// did not create, so that is a failure the user has to resolve.
|
|
114
|
+
const target = await stat(notesDir).catch(() => null);
|
|
115
|
+
if (target !== null && !target.isDirectory())
|
|
116
|
+
throw new Error(`${notesDir} exists and is not a directory`);
|
|
117
|
+
await rename(staging, notesDir);
|
|
118
|
+
renamed = true;
|
|
119
|
+
// Read the published directory back. The rename guarantees the FILE SET is
|
|
120
|
+
// the one just written, but only a parse proves the bytes survived the
|
|
121
|
+
// round-trip, and a silently mangled note is the one failure a user would
|
|
122
|
+
// never notice until the text was already wrong.
|
|
123
|
+
const files = (await readdir(notesDir)).filter((name) => idOfFile(name) !== null);
|
|
124
|
+
if (files.length !== legacy.length) {
|
|
125
|
+
throw new Error(`migrated ${String(files.length)} files from ${String(legacy.length)} legacy notes`);
|
|
126
|
+
}
|
|
127
|
+
for (const note of legacy) {
|
|
128
|
+
const path = join(notesDir, fileNameOf(note.id));
|
|
129
|
+
const info = await stat(path);
|
|
130
|
+
if (info.size > LIMITS.fileBytes)
|
|
131
|
+
throw new Error(`migrated file for ${note.id} exceeds the size cap`);
|
|
132
|
+
const parsed = parseNoteFile(await readFile(path, 'utf8'), {
|
|
133
|
+
fallbackId: note.id,
|
|
134
|
+
fallbackTime: info.mtime.toISOString(),
|
|
135
|
+
});
|
|
136
|
+
if (!sameNote(note, parsed.note))
|
|
137
|
+
throw new Error(`migrated file for ${note.id} does not round-trip`);
|
|
138
|
+
}
|
|
139
|
+
const at = (options.now ?? (() => new Date()))().toISOString();
|
|
140
|
+
// Best-effort: the marker is documentation of what happened, and the notes
|
|
141
|
+
// themselves already prove the migration. Failing here would delete a good
|
|
142
|
+
// directory over a cosmetic file, so a write error is swallowed — the next
|
|
143
|
+
// start sees the notes and reports `already-present` either way.
|
|
144
|
+
await writeFile(join(notesDir, MIGRATION_MARKER), `${JSON.stringify({ from: LEGACY_DOMAIN_NAME, count: legacy.length, at, sourceCount: legacy.length }, null, 2)}\n`, 'utf8').catch(() => { });
|
|
145
|
+
return { migrated: true, reason: 'migrated', count: legacy.length };
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
// Leave no partial state behind: a published-but-unverified directory is
|
|
149
|
+
// removed so the next start retries instead of treating a bad migration as
|
|
150
|
+
// finished. The staging directory goes too, in every case.
|
|
151
|
+
await discardStaging(staging).catch(() => { });
|
|
152
|
+
if (renamed)
|
|
153
|
+
await rm(notesDir, { recursive: true, force: true }).catch(() => { });
|
|
154
|
+
return { migrated: false, reason: 'failed', error: error instanceof Error ? error.message : String(error) };
|
|
155
|
+
}
|
|
156
|
+
}
|