@creator-notes/cnotes 0.112.0 → 0.113.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/.claude-plugin/plugin.json +1 -1
- package/README.md +15 -0
- package/dist/commands/query.js +233 -0
- package/dist/lib/auth-store.js +4 -0
- package/dist/lib/local-db-store.js +200 -0
- package/dist/local-db/apply.js +222 -0
- package/dist/local-db/ops.js +106 -0
- package/dist/local-db/protocol.js +10 -0
- package/dist/local-db/query.js +184 -0
- package/dist/local-db/schema.js +107 -0
- package/dist/local-db/sync.js +270 -0
- package/dist/local-db/types.js +8 -0
- package/dist/mcp-server.js +32 -0
- package/dist/program.js +2 -0
- package/package.json +4 -3
- package/skills/cnotes/references/more-commands.md +22 -0
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
function deleteNote(db, id) {
|
|
2
|
+
db.run("DELETE FROM notes WHERE id = ?", [id]);
|
|
3
|
+
db.run("DELETE FROM note_tags WHERE note_id = ?", [id]);
|
|
4
|
+
db.run("DELETE FROM answers WHERE note_id = ?", [id]);
|
|
5
|
+
}
|
|
6
|
+
/** Upsert notes and drop removals. Returns the newest `updatedAt` seen. */
|
|
7
|
+
export function applyNotes(db, rows) {
|
|
8
|
+
let upserted = 0;
|
|
9
|
+
let removed = 0;
|
|
10
|
+
let newest = 0;
|
|
11
|
+
db.transaction(() => {
|
|
12
|
+
for (const row of rows) {
|
|
13
|
+
newest = Math.max(newest, row.updatedAt ?? 0);
|
|
14
|
+
if (row.removed) {
|
|
15
|
+
deleteNote(db, row.id);
|
|
16
|
+
removed++;
|
|
17
|
+
continue;
|
|
18
|
+
}
|
|
19
|
+
db.run(`INSERT INTO notes (id, display_id, title, type, created_by, source, created_at, updated_at)
|
|
20
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
|
21
|
+
ON CONFLICT (id) DO UPDATE SET
|
|
22
|
+
display_id = excluded.display_id, title = excluded.title, type = excluded.type,
|
|
23
|
+
created_by = excluded.created_by, source = excluded.source,
|
|
24
|
+
created_at = excluded.created_at, updated_at = excluded.updated_at`, [row.id, row.displayId, row.title, row.type, row.createdBy, row.createdBySource, row.createdAt, row.updatedAt]);
|
|
25
|
+
db.run("DELETE FROM note_tags WHERE note_id = ?", [row.id]);
|
|
26
|
+
for (const tag of new Set(row.tags))
|
|
27
|
+
db.run("INSERT INTO note_tags (note_id, tag) VALUES (?, ?)", [row.id, tag]);
|
|
28
|
+
upserted++;
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
return { upserted, removed, newest };
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Members, dimensions and boards from the sync head. Boards no longer in the
|
|
35
|
+
* head lose their placements. Returns the boards whose placements must be
|
|
36
|
+
* read again (new ones, and ones whose `changedAt` or note count moved since
|
|
37
|
+
* their placements were read) and the dimensions whose newest answer moved
|
|
38
|
+
* since their answers were read.
|
|
39
|
+
*/
|
|
40
|
+
export function applyHead(db, head) {
|
|
41
|
+
const canvasesToRefresh = [];
|
|
42
|
+
const dimensionsToRefresh = [];
|
|
43
|
+
db.transaction(() => {
|
|
44
|
+
db.run("DELETE FROM members");
|
|
45
|
+
for (const m of head.members)
|
|
46
|
+
db.run("INSERT INTO members (user_id, name) VALUES (?, ?)", [m.userId, m.name]);
|
|
47
|
+
// `answers_at` is when each dimension's answers were last read; it survives
|
|
48
|
+
// the replace so the next pass knows whether a judgment landed since.
|
|
49
|
+
const answersAt = new Map(db.all("SELECT type, key, answers_at FROM dimensions").map((d) => [
|
|
50
|
+
`${d.type}\u0000${d.key}`,
|
|
51
|
+
d.answers_at,
|
|
52
|
+
]));
|
|
53
|
+
db.run("DELETE FROM dimensions");
|
|
54
|
+
for (const d of head.dimensions) {
|
|
55
|
+
const prior = answersAt.get(`${d.type}\u0000${d.key}`) ?? null;
|
|
56
|
+
db.run("INSERT OR REPLACE INTO dimensions (type, key, label, kind, options, supertag_id, answers_at) VALUES (?, ?, ?, ?, ?, ?, ?)", [d.type, d.key, d.label, d.kind, JSON.stringify(d.options), d.supertagId, prior]);
|
|
57
|
+
if (prior !== d.newestAnswerAt)
|
|
58
|
+
dimensionsToRefresh.push({ type: d.type, key: d.key });
|
|
59
|
+
}
|
|
60
|
+
// Answers to a dimension that was removed from its type go with it.
|
|
61
|
+
db.run("DELETE FROM answers WHERE NOT EXISTS (SELECT 1 FROM dimensions d WHERE d.type = answers.type AND d.key = answers.key)");
|
|
62
|
+
const known = new Map(db
|
|
63
|
+
.all("SELECT id, placements_changed_at, placements_note_count FROM canvases")
|
|
64
|
+
.map((c) => [c.id, c]));
|
|
65
|
+
const live = new Set();
|
|
66
|
+
for (const c of head.canvases) {
|
|
67
|
+
live.add(c.id);
|
|
68
|
+
db.run(`INSERT INTO canvases (id, display_id, name, updated_at, note_count, is_default, branch_of)
|
|
69
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)
|
|
70
|
+
ON CONFLICT (id) DO UPDATE SET
|
|
71
|
+
display_id = excluded.display_id, name = excluded.name, updated_at = excluded.updated_at,
|
|
72
|
+
note_count = excluded.note_count, is_default = excluded.is_default, branch_of = excluded.branch_of`, [c.id, c.displayId, c.name, c.updatedAt, c.noteCount, c.isDefault ? 1 : 0, c.branchOf]);
|
|
73
|
+
const prior = known.get(c.id);
|
|
74
|
+
if (!prior || prior.placements_changed_at !== c.changedAt || prior.placements_note_count !== c.noteCount) {
|
|
75
|
+
canvasesToRefresh.push(c.id);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
for (const id of known.keys()) {
|
|
79
|
+
if (live.has(id))
|
|
80
|
+
continue;
|
|
81
|
+
db.run("DELETE FROM canvases WHERE id = ?", [id]);
|
|
82
|
+
db.run("DELETE FROM placements WHERE canvas_id = ?", [id]);
|
|
83
|
+
clearLayout(db, id);
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
return { canvasesToRefresh, dimensionsToRefresh };
|
|
87
|
+
}
|
|
88
|
+
function clearLayout(db, canvasId) {
|
|
89
|
+
db.run("DELETE FROM layout_nodes WHERE canvas_id = ?", [canvasId]);
|
|
90
|
+
db.run("DELETE FROM layout_edges WHERE canvas_id = ?", [canvasId]);
|
|
91
|
+
}
|
|
92
|
+
/** Replace one board's layout rows (the workspace map's source). */
|
|
93
|
+
function writeLayout(db, canvasId, layout) {
|
|
94
|
+
clearLayout(db, canvasId);
|
|
95
|
+
const node = (id, kind, noteId, x, y, w, h, data) => db.run("INSERT OR REPLACE INTO layout_nodes (canvas_id, node_id, kind, note_id, x, y, w, h, data) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)", [
|
|
96
|
+
canvasId,
|
|
97
|
+
id,
|
|
98
|
+
kind,
|
|
99
|
+
noteId,
|
|
100
|
+
x,
|
|
101
|
+
y,
|
|
102
|
+
w,
|
|
103
|
+
h,
|
|
104
|
+
JSON.stringify(data),
|
|
105
|
+
]);
|
|
106
|
+
for (const c of layout.cards)
|
|
107
|
+
node(c.id, "card", c.noteId, c.x, c.y, c.w, c.h, { quoteStyle: c.quoteStyle, quoteSize: c.quoteSize });
|
|
108
|
+
for (const s of layout.sections)
|
|
109
|
+
node(s.id, "section", null, s.x, s.y, s.w, s.h, { name: s.name, displayId: s.displayId, colorHex: s.colorHex });
|
|
110
|
+
for (const t of layout.texts)
|
|
111
|
+
node(t.id, "text", null, t.x, t.y, t.w, t.h, { text: t.text, size: t.size, colorHex: t.colorHex });
|
|
112
|
+
for (const l of layout.lists)
|
|
113
|
+
node(l.id, "list", null, l.x, l.y, l.w, l.h, { name: l.name, description: l.description, colorHex: l.colorHex, items: l.items });
|
|
114
|
+
for (const l of layout.links)
|
|
115
|
+
node(l.id, "link", null, l.x, l.y, l.w, l.h, { linkedCanvasId: l.linkedCanvasId });
|
|
116
|
+
for (const e of layout.edges) {
|
|
117
|
+
db.run("INSERT INTO layout_edges (canvas_id, source, target, arrow_start, arrow_end, line_style) VALUES (?, ?, ?, ?, ?, ?)", [
|
|
118
|
+
canvasId,
|
|
119
|
+
e.source,
|
|
120
|
+
e.target,
|
|
121
|
+
e.arrowStart == null ? null : e.arrowStart ? 1 : 0,
|
|
122
|
+
e.arrowEnd == null ? null : e.arrowEnd ? 1 : 0,
|
|
123
|
+
e.lineStyle,
|
|
124
|
+
]);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
/** Every board's layout joined to its notes, for the workspace map. Branch drafts are left out. */
|
|
128
|
+
export function readWorkspaceLayout(db) {
|
|
129
|
+
const canvases = db.all("SELECT id, display_id AS displayId, name, updated_at AS updatedAt, branch_of AS branchOf, is_default AS isDefault FROM canvases WHERE branch_of IS NULL");
|
|
130
|
+
const nodes = db.all(`SELECT l.canvas_id AS canvasId, l.node_id AS nodeId, l.kind, l.note_id AS noteId, l.x, l.y, l.w, l.h, l.data,
|
|
131
|
+
n.display_id AS displayId, n.title, n.type, n.updated_at AS updatedAt
|
|
132
|
+
FROM layout_nodes l
|
|
133
|
+
JOIN canvases c ON c.id = l.canvas_id AND c.branch_of IS NULL
|
|
134
|
+
LEFT JOIN notes n ON n.id = l.note_id
|
|
135
|
+
WHERE l.kind != 'card' OR n.id IS NOT NULL`);
|
|
136
|
+
const edges = db.all(`SELECT e.canvas_id AS canvasId, e.source, e.target, e.arrow_start AS arrowStart, e.arrow_end AS arrowEnd, e.line_style AS lineStyle
|
|
137
|
+
FROM layout_edges e JOIN canvases c ON c.id = e.canvas_id AND c.branch_of IS NULL`);
|
|
138
|
+
return { canvases, nodes, edges };
|
|
139
|
+
}
|
|
140
|
+
/** Replace each board's placements, and remember the board fields they were read at. */
|
|
141
|
+
export function applyPlacements(db, rows) {
|
|
142
|
+
db.transaction(() => {
|
|
143
|
+
for (const row of rows) {
|
|
144
|
+
db.run("DELETE FROM placements WHERE canvas_id = ?", [row.canvasId]);
|
|
145
|
+
if (row.removed) {
|
|
146
|
+
db.run("DELETE FROM canvases WHERE id = ?", [row.canvasId]);
|
|
147
|
+
clearLayout(db, row.canvasId);
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
if (row.layout)
|
|
151
|
+
writeLayout(db, row.canvasId, row.layout);
|
|
152
|
+
for (const noteId of row.cards) {
|
|
153
|
+
db.run("INSERT OR IGNORE INTO placements (canvas_id, note_id, via) VALUES (?, ?, 'card')", [row.canvasId, noteId]);
|
|
154
|
+
}
|
|
155
|
+
for (const noteId of row.listItems) {
|
|
156
|
+
db.run("INSERT OR IGNORE INTO placements (canvas_id, note_id, via) VALUES (?, ?, 'list')", [row.canvasId, noteId]);
|
|
157
|
+
}
|
|
158
|
+
db.run("UPDATE canvases SET placements_changed_at = ?, placements_note_count = ? WHERE id = ?", [
|
|
159
|
+
row.changedAt,
|
|
160
|
+
row.noteCount,
|
|
161
|
+
row.canvasId,
|
|
162
|
+
]);
|
|
163
|
+
}
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* One page of a dimension's answers. The first page of a pass clears that
|
|
168
|
+
* dimension, so answers the server no longer holds disappear. A note can hold
|
|
169
|
+
* several stored answers; the newest judgment wins. `answersAt` is the head's
|
|
170
|
+
* `newestAnswerAt` these pages were read for; the next head compares it.
|
|
171
|
+
*/
|
|
172
|
+
export function applyAnswers(db, type, key, rows, firstPage, answersAt) {
|
|
173
|
+
db.transaction(() => {
|
|
174
|
+
if (firstPage)
|
|
175
|
+
db.run("DELETE FROM answers WHERE type = ? AND key = ?", [type, key]);
|
|
176
|
+
db.run("UPDATE dimensions SET answers_at = ? WHERE type = ? AND key = ?", [answersAt, type, key]);
|
|
177
|
+
for (const row of rows) {
|
|
178
|
+
db.run(`INSERT INTO answers (note_id, type, key, state, value, judged_at) VALUES (?, ?, ?, ?, ?, ?)
|
|
179
|
+
ON CONFLICT (note_id, type, key) DO UPDATE SET
|
|
180
|
+
state = excluded.state, value = excluded.value, judged_at = excluded.judged_at
|
|
181
|
+
WHERE excluded.judged_at >= answers.judged_at`, [row.noteId, type, key, row.state, row.value, row.judgedAt]);
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Compare every note id the server holds with the copy. Local notes the server
|
|
187
|
+
* no longer lists, or now lists as removed, are deleted; ids that are missing
|
|
188
|
+
* locally or carry a different `updatedAt` are returned for fetching.
|
|
189
|
+
*/
|
|
190
|
+
export function reconcileNotes(db, server) {
|
|
191
|
+
const local = new Map(db.all("SELECT id, updated_at FROM notes").map((n) => [n.id, n.updated_at]));
|
|
192
|
+
const toFetch = [];
|
|
193
|
+
const keep = new Set();
|
|
194
|
+
for (const row of server) {
|
|
195
|
+
if (row.removed)
|
|
196
|
+
continue;
|
|
197
|
+
keep.add(row.id);
|
|
198
|
+
if (!local.has(row.id) || local.get(row.id) !== row.updatedAt)
|
|
199
|
+
toFetch.push(row.id);
|
|
200
|
+
}
|
|
201
|
+
let deleted = 0;
|
|
202
|
+
db.transaction(() => {
|
|
203
|
+
for (const id of local.keys()) {
|
|
204
|
+
if (keep.has(id))
|
|
205
|
+
continue;
|
|
206
|
+
deleteNote(db, id);
|
|
207
|
+
deleted++;
|
|
208
|
+
}
|
|
209
|
+
});
|
|
210
|
+
return { deleted, toFetch };
|
|
211
|
+
}
|
|
212
|
+
export function getMeta(db, key) {
|
|
213
|
+
const row = db.all("SELECT value FROM meta WHERE key = ?", [key])[0];
|
|
214
|
+
return row ? row.value : null;
|
|
215
|
+
}
|
|
216
|
+
export function setMeta(db, key, value) {
|
|
217
|
+
db.run("INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value", [key, value]);
|
|
218
|
+
}
|
|
219
|
+
export function countRows(db) {
|
|
220
|
+
const count = (table) => Number(db.all(`SELECT COUNT(*) AS n FROM ${table}`)[0]?.n ?? 0);
|
|
221
|
+
return { notes: count("notes"), canvases: count("canvases"), placements: count("placements"), answers: count("answers") };
|
|
222
|
+
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// GENERATED from lib/local-db in the repository root: do not edit here.
|
|
2
|
+
// Change the source and run `npm --prefix cli run sync:local-db`.
|
|
3
|
+
/**
|
|
4
|
+
* The local workspace database's operations over an open SQLite handle: what
|
|
5
|
+
* the sync loop writes (head, notes, placements, answers, reconcile) and what
|
|
6
|
+
* the panel and the CLI ask (filtered query, facets, a read-only SELECT).
|
|
7
|
+
*
|
|
8
|
+
* Storage-neutral: the browser worker (workers/localDb.worker.ts) runs these
|
|
9
|
+
* on a SQLite-wasm file in the origin private file system, the `cnotes` CLI
|
|
10
|
+
* on `node:sqlite` under its config directory. Opening, forgetting and wiping
|
|
11
|
+
* files stay with the storage, so they are not here.
|
|
12
|
+
*/
|
|
13
|
+
import { applyAnswers, applyHead, applyNotes, applyPlacements, countRows, getMeta, readWorkspaceLayout, reconcileNotes, setMeta } from "./apply.js";
|
|
14
|
+
import { buildCountQuery, buildFacetQuery, buildGroupCountsQuery, buildResultsQuery, checkReadOnlySql } from "./query.js";
|
|
15
|
+
import { ensureSchema } from "./schema.js";
|
|
16
|
+
export const NEWEST_KEY = "newest_note_updated_at";
|
|
17
|
+
export const RECONCILED_KEY = "last_reconciled_at";
|
|
18
|
+
const now = () => (typeof performance !== "undefined" ? performance.now() : Date.now());
|
|
19
|
+
/** Bytes the database takes, from its page count and size (works for a file and for memory). */
|
|
20
|
+
export function fileBytes(db) {
|
|
21
|
+
const pages = Number(db.all("PRAGMA page_count")[0]?.page_count ?? 0);
|
|
22
|
+
const size = Number(db.all("PRAGMA page_size")[0]?.page_size ?? 0);
|
|
23
|
+
return pages * size;
|
|
24
|
+
}
|
|
25
|
+
/** Prepare a freshly opened handle: tables present, and what the copy already holds. */
|
|
26
|
+
export function openCopy(db, persistent) {
|
|
27
|
+
const fresh = ensureSchema(db);
|
|
28
|
+
return {
|
|
29
|
+
counts: countRows(db),
|
|
30
|
+
persistent,
|
|
31
|
+
fresh,
|
|
32
|
+
newestNoteUpdatedAt: Number(getMeta(db, NEWEST_KEY) ?? 0),
|
|
33
|
+
reconciledAt: Number(getMeta(db, RECONCILED_KEY) ?? 0),
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Run one SELECT (or WITH ... SELECT) and return rows as arrays. The caller
|
|
38
|
+
* wraps it in `PRAGMA query_only` where the handle supports it; the text check
|
|
39
|
+
* here is for a readable error, not the guarantee.
|
|
40
|
+
*/
|
|
41
|
+
export function runReadOnlySql(db, sql, maxRows) {
|
|
42
|
+
const checked = checkReadOnlySql(sql);
|
|
43
|
+
if (!checked.ok)
|
|
44
|
+
throw new Error(checked.reason);
|
|
45
|
+
const start = now();
|
|
46
|
+
const wrapped = `SELECT * FROM (${checked.sql}) LIMIT ${maxRows + 1}`;
|
|
47
|
+
let columns;
|
|
48
|
+
let rows;
|
|
49
|
+
if (db.rows) {
|
|
50
|
+
({ columns, rows } = db.rows(wrapped));
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
const objects = db.all(wrapped);
|
|
54
|
+
columns = Object.keys(objects[0] ?? {});
|
|
55
|
+
rows = objects.map((o) => columns.map((c) => o[c] ?? null));
|
|
56
|
+
}
|
|
57
|
+
return { columns, rows: rows.slice(0, maxRows), truncated: rows.length > maxRows, ms: now() - start };
|
|
58
|
+
}
|
|
59
|
+
export function createLocalDbOps(db) {
|
|
60
|
+
return {
|
|
61
|
+
applyHead: (head) => applyHead(db, head),
|
|
62
|
+
applyNotes: (rows) => applyNotes(db, rows),
|
|
63
|
+
applyPlacements: (rows) => {
|
|
64
|
+
applyPlacements(db, rows);
|
|
65
|
+
return null;
|
|
66
|
+
},
|
|
67
|
+
applyAnswers: ({ type, key, rows, firstPage, answersAt }) => {
|
|
68
|
+
applyAnswers(db, type, key, rows, firstPage, answersAt);
|
|
69
|
+
return null;
|
|
70
|
+
},
|
|
71
|
+
reconcile: (rows) => reconcileNotes(db, rows),
|
|
72
|
+
setNewest: (newest) => {
|
|
73
|
+
setMeta(db, NEWEST_KEY, String(newest));
|
|
74
|
+
return null;
|
|
75
|
+
},
|
|
76
|
+
markReconciled: (at) => {
|
|
77
|
+
setMeta(db, RECONCILED_KEY, String(at));
|
|
78
|
+
return null;
|
|
79
|
+
},
|
|
80
|
+
counts: () => ({ ...countRows(db), bytes: fileBytes(db) }),
|
|
81
|
+
query: ({ filter, groupBy, limit }) => {
|
|
82
|
+
const start = now();
|
|
83
|
+
const results = buildResultsQuery(filter, groupBy, limit);
|
|
84
|
+
const rows = db.all(results.sql, results.params);
|
|
85
|
+
const count = buildCountQuery(filter);
|
|
86
|
+
const total = Number(db.all(count.sql, count.params)[0]?.count ?? 0);
|
|
87
|
+
const groupsQuery = buildGroupCountsQuery(filter, groupBy);
|
|
88
|
+
const groups = groupBy === "none" ? [] : db.all(groupsQuery.sql, groupsQuery.params);
|
|
89
|
+
return { rows, total, groups, ms: now() - start };
|
|
90
|
+
},
|
|
91
|
+
workspaceLayout: () => {
|
|
92
|
+
const start = now();
|
|
93
|
+
return { ...readWorkspaceLayout(db), ms: now() - start };
|
|
94
|
+
},
|
|
95
|
+
facets: ({ filter, fields, limit }) => {
|
|
96
|
+
const start = now();
|
|
97
|
+
const facets = {};
|
|
98
|
+
for (const field of fields) {
|
|
99
|
+
const q = buildFacetQuery(filter, field, limit);
|
|
100
|
+
facets[field] = db.all(q.sql, q.params);
|
|
101
|
+
}
|
|
102
|
+
return { facets, ms: now() - start };
|
|
103
|
+
},
|
|
104
|
+
sql: ({ sql, maxRows }) => runReadOnlySql(db, sql, maxRows),
|
|
105
|
+
};
|
|
106
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/** Where the SAH pool keeps its files in the origin private file system. */
|
|
2
|
+
export const LOCAL_DB_DIRECTORY = "/cn-local-db";
|
|
3
|
+
export const LOCAL_DB_VFS = "cn-local-db";
|
|
4
|
+
/** One file per member and workspace, so one person's copy never opens for another. */
|
|
5
|
+
export function localDbFileName(userId, workspaceId) {
|
|
6
|
+
return `${workspaceFilePrefix(workspaceId)}${userId}.sqlite3`;
|
|
7
|
+
}
|
|
8
|
+
export function workspaceFilePrefix(workspaceId) {
|
|
9
|
+
return `/ws-${workspaceId}-u-`;
|
|
10
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
export const UNJUDGED = "unjudged";
|
|
2
|
+
export const NO_CANVAS = "Not on a canvas";
|
|
3
|
+
export const NO_TAG = "No tag";
|
|
4
|
+
const placeholders = (n) => Array.from({ length: n }, () => "?").join(", ");
|
|
5
|
+
function escapeLike(word) {
|
|
6
|
+
return word.replace(/[\\%_]/g, (c) => `\\${c}`);
|
|
7
|
+
}
|
|
8
|
+
export function buildWhere(filter) {
|
|
9
|
+
const clauses = [];
|
|
10
|
+
const params = [];
|
|
11
|
+
const words = (filter.text ?? "").trim().split(/\s+/).filter(Boolean);
|
|
12
|
+
for (const word of words) {
|
|
13
|
+
clauses.push(`(n.title LIKE ? ESCAPE '\\' OR n.display_id LIKE ? ESCAPE '\\')`);
|
|
14
|
+
const pattern = `%${escapeLike(word)}%`;
|
|
15
|
+
params.push(pattern, pattern);
|
|
16
|
+
}
|
|
17
|
+
if (filter.types?.length) {
|
|
18
|
+
clauses.push(`n.type IN (${placeholders(filter.types.length)})`);
|
|
19
|
+
params.push(...filter.types);
|
|
20
|
+
}
|
|
21
|
+
if (filter.sources?.length) {
|
|
22
|
+
clauses.push(`n.source IN (${placeholders(filter.sources.length)})`);
|
|
23
|
+
params.push(...filter.sources);
|
|
24
|
+
}
|
|
25
|
+
if (filter.authors?.length) {
|
|
26
|
+
clauses.push(`n.created_by IN (${placeholders(filter.authors.length)})`);
|
|
27
|
+
params.push(...filter.authors);
|
|
28
|
+
}
|
|
29
|
+
if (filter.canvasIds?.length) {
|
|
30
|
+
clauses.push(`EXISTS (SELECT 1 FROM placements p WHERE p.note_id = n.id AND p.canvas_id IN (${placeholders(filter.canvasIds.length)}))`);
|
|
31
|
+
params.push(...filter.canvasIds);
|
|
32
|
+
}
|
|
33
|
+
if (filter.tags?.length) {
|
|
34
|
+
clauses.push(`EXISTS (SELECT 1 FROM note_tags t WHERE t.note_id = n.id AND t.tag IN (${placeholders(filter.tags.length)}))`);
|
|
35
|
+
params.push(...filter.tags);
|
|
36
|
+
}
|
|
37
|
+
if (filter.createdFrom != null) {
|
|
38
|
+
clauses.push("n.created_at >= ?");
|
|
39
|
+
params.push(filter.createdFrom);
|
|
40
|
+
}
|
|
41
|
+
if (filter.createdTo != null) {
|
|
42
|
+
clauses.push("n.created_at <= ?");
|
|
43
|
+
params.push(filter.createdTo);
|
|
44
|
+
}
|
|
45
|
+
for (const dim of filter.dimensions ?? []) {
|
|
46
|
+
if (dim.states.length === 0)
|
|
47
|
+
continue;
|
|
48
|
+
const judged = dim.states.filter((s) => s !== UNJUDGED);
|
|
49
|
+
const parts = [];
|
|
50
|
+
// A dimension belongs to one type, so filtering on it keeps that type only.
|
|
51
|
+
const scope = "n.type = ?";
|
|
52
|
+
if (judged.length) {
|
|
53
|
+
parts.push(`EXISTS (SELECT 1 FROM answers a WHERE a.note_id = n.id AND a.type = n.type AND a.key = ? AND a.state IN (${placeholders(judged.length)}))`);
|
|
54
|
+
}
|
|
55
|
+
if (judged.length !== dim.states.length) {
|
|
56
|
+
parts.push(`NOT EXISTS (SELECT 1 FROM answers a WHERE a.note_id = n.id AND a.type = n.type AND a.key = ?)`);
|
|
57
|
+
}
|
|
58
|
+
clauses.push(`(${scope} AND (${parts.join(" OR ")}))`);
|
|
59
|
+
params.push(dim.type);
|
|
60
|
+
if (judged.length)
|
|
61
|
+
params.push(dim.key, ...judged);
|
|
62
|
+
if (judged.length !== dim.states.length)
|
|
63
|
+
params.push(dim.key);
|
|
64
|
+
}
|
|
65
|
+
return { sql: clauses.length ? `WHERE ${clauses.join(" AND ")}` : "", params };
|
|
66
|
+
}
|
|
67
|
+
/** The join and the key/label expressions for one grouping. */
|
|
68
|
+
function grouping(groupBy) {
|
|
69
|
+
switch (groupBy) {
|
|
70
|
+
case "type":
|
|
71
|
+
return { join: "", key: "n.type", label: "n.type", params: [] };
|
|
72
|
+
case "canvas":
|
|
73
|
+
return {
|
|
74
|
+
join: "LEFT JOIN placements p ON p.note_id = n.id LEFT JOIN canvases c ON c.id = p.canvas_id",
|
|
75
|
+
key: "COALESCE(c.id, '')",
|
|
76
|
+
label: `COALESCE(c.name, '${NO_CANVAS}')`,
|
|
77
|
+
params: [],
|
|
78
|
+
};
|
|
79
|
+
case "tag":
|
|
80
|
+
return {
|
|
81
|
+
join: "LEFT JOIN note_tags t ON t.note_id = n.id",
|
|
82
|
+
key: "COALESCE(t.tag, '')",
|
|
83
|
+
label: `COALESCE(t.tag, '${NO_TAG}')`,
|
|
84
|
+
params: [],
|
|
85
|
+
};
|
|
86
|
+
case "month":
|
|
87
|
+
return {
|
|
88
|
+
join: "",
|
|
89
|
+
key: "COALESCE(strftime('%Y-%m', n.created_at / 1000, 'unixepoch'), '')",
|
|
90
|
+
label: "COALESCE(strftime('%Y-%m', n.created_at / 1000, 'unixepoch'), 'No date')",
|
|
91
|
+
params: [],
|
|
92
|
+
};
|
|
93
|
+
case "source":
|
|
94
|
+
return { join: "", key: "COALESCE(n.source, '')", label: "COALESCE(n.source, 'unknown')", params: [] };
|
|
95
|
+
case "author":
|
|
96
|
+
return {
|
|
97
|
+
join: "LEFT JOIN members m ON m.user_id = n.created_by",
|
|
98
|
+
key: "COALESCE(n.created_by, '')",
|
|
99
|
+
label: "COALESCE(m.name, 'Unnamed member')",
|
|
100
|
+
params: [],
|
|
101
|
+
};
|
|
102
|
+
case "none":
|
|
103
|
+
return { join: "", key: "''", label: "''", params: [] };
|
|
104
|
+
default: {
|
|
105
|
+
const [, type, key] = groupBy.split(":");
|
|
106
|
+
return {
|
|
107
|
+
join: "LEFT JOIN answers a ON a.note_id = n.id AND a.type = n.type AND a.type = ? AND a.key = ?",
|
|
108
|
+
key: `COALESCE(a.state, '${UNJUDGED}')`,
|
|
109
|
+
label: `COALESCE(a.state, '${UNJUDGED}')`,
|
|
110
|
+
params: [type ?? "", key ?? ""],
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Matching notes with the group each falls in. Groups come largest first (the
|
|
117
|
+
* order the facet chips use, so the list opens on the group the chips say
|
|
118
|
+
* dominates), months newest first, and inside a group the most recently
|
|
119
|
+
* written note leads. A note on two canvases (or with two tags) appears once
|
|
120
|
+
* per group when grouped by that field, and once in a group however many
|
|
121
|
+
* times it is placed there (DISTINCT: a card and a list item on one canvas
|
|
122
|
+
* join as two rows). Groups that share a label (two canvases both called
|
|
123
|
+
* "Untitled") still come out contiguous: the key breaks the tie, and the
|
|
124
|
+
* panel folds rows into groups by consecutive key.
|
|
125
|
+
*/
|
|
126
|
+
export function buildResultsQuery(filter, groupBy, limit) {
|
|
127
|
+
const where = buildWhere(filter);
|
|
128
|
+
const g = grouping(groupBy);
|
|
129
|
+
const order = groupBy === "month" ? "group_label DESC" : "sizes.group_size DESC, group_label COLLATE NOCASE";
|
|
130
|
+
const sql = `WITH matched AS (
|
|
131
|
+
SELECT DISTINCT n.id, n.display_id, n.title, n.type, n.updated_at, ${g.key} AS group_key, ${g.label} AS group_label
|
|
132
|
+
FROM notes n ${g.join} ${where.sql}
|
|
133
|
+
), sizes AS (SELECT group_key, COUNT(*) AS group_size FROM matched GROUP BY group_key)
|
|
134
|
+
SELECT matched.* FROM matched JOIN sizes USING (group_key)
|
|
135
|
+
ORDER BY ${order}, group_key, matched.updated_at DESC
|
|
136
|
+
LIMIT ?`;
|
|
137
|
+
return { sql, params: [...g.params, ...where.params, limit] };
|
|
138
|
+
}
|
|
139
|
+
/** How many notes match, each counted once. */
|
|
140
|
+
export function buildCountQuery(filter) {
|
|
141
|
+
const where = buildWhere(filter);
|
|
142
|
+
return { sql: `SELECT COUNT(*) AS count FROM notes n ${where.sql}`, params: where.params };
|
|
143
|
+
}
|
|
144
|
+
/** Group sizes, each note counted once per group. */
|
|
145
|
+
export function buildGroupCountsQuery(filter, groupBy) {
|
|
146
|
+
const where = buildWhere(filter);
|
|
147
|
+
const g = grouping(groupBy);
|
|
148
|
+
return {
|
|
149
|
+
sql: `SELECT ${g.key} AS value, ${g.label} AS label, COUNT(DISTINCT n.id) AS count
|
|
150
|
+
FROM notes n ${g.join} ${where.sql}
|
|
151
|
+
GROUP BY value, label ORDER BY label COLLATE NOCASE`,
|
|
152
|
+
params: [...g.params, ...where.params],
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
const FACET_GROUP = {
|
|
156
|
+
types: "type",
|
|
157
|
+
canvasIds: "canvas",
|
|
158
|
+
tags: "tag",
|
|
159
|
+
sources: "source",
|
|
160
|
+
};
|
|
161
|
+
/** Counts for one facet's chips, leaving that facet's own filter out. Largest first. */
|
|
162
|
+
export function buildFacetQuery(filter, field, limit) {
|
|
163
|
+
const rest = { ...filter, [field]: undefined };
|
|
164
|
+
const counts = buildGroupCountsQuery(rest, FACET_GROUP[field]);
|
|
165
|
+
return {
|
|
166
|
+
sql: `SELECT * FROM (${counts.sql}) WHERE value != '' ORDER BY count DESC, label COLLATE NOCASE LIMIT ?`,
|
|
167
|
+
params: [...counts.params, limit],
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* The SQL box runs one SELECT (or WITH ... SELECT) statement. The worker also
|
|
172
|
+
* runs it with `PRAGMA query_only` on, so this check is for a readable error,
|
|
173
|
+
* not the guarantee.
|
|
174
|
+
*/
|
|
175
|
+
export function checkReadOnlySql(sql) {
|
|
176
|
+
const trimmed = sql.trim().replace(/;\s*$/, "");
|
|
177
|
+
if (!trimmed)
|
|
178
|
+
return { ok: false, reason: "Type a SELECT statement." };
|
|
179
|
+
if (!/^(select|with)\b/i.test(trimmed))
|
|
180
|
+
return { ok: false, reason: "Only SELECT statements run here." };
|
|
181
|
+
if (/;/.test(trimmed.replace(/'(?:[^']|'')*'/g, "''")))
|
|
182
|
+
return { ok: false, reason: "Run one statement at a time." };
|
|
183
|
+
return { ok: true, sql: trimmed };
|
|
184
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
export const SCHEMA_VERSION = 3;
|
|
2
|
+
const TABLES = ["notes", "note_tags", "canvases", "placements", "layout_nodes", "layout_edges", "members", "dimensions", "answers", "meta"];
|
|
3
|
+
const CREATE = [
|
|
4
|
+
`CREATE TABLE notes (
|
|
5
|
+
id TEXT PRIMARY KEY,
|
|
6
|
+
display_id TEXT NOT NULL,
|
|
7
|
+
title TEXT,
|
|
8
|
+
type TEXT NOT NULL,
|
|
9
|
+
created_by TEXT,
|
|
10
|
+
source TEXT,
|
|
11
|
+
created_at INTEGER,
|
|
12
|
+
updated_at INTEGER
|
|
13
|
+
)`,
|
|
14
|
+
`CREATE TABLE note_tags (note_id TEXT NOT NULL, tag TEXT NOT NULL, PRIMARY KEY (note_id, tag)) WITHOUT ROWID`,
|
|
15
|
+
`CREATE TABLE canvases (
|
|
16
|
+
id TEXT PRIMARY KEY,
|
|
17
|
+
display_id TEXT,
|
|
18
|
+
name TEXT NOT NULL,
|
|
19
|
+
updated_at INTEGER,
|
|
20
|
+
note_count INTEGER,
|
|
21
|
+
is_default INTEGER NOT NULL DEFAULT 0,
|
|
22
|
+
branch_of TEXT,
|
|
23
|
+
placements_changed_at INTEGER,
|
|
24
|
+
placements_note_count INTEGER
|
|
25
|
+
)`,
|
|
26
|
+
`CREATE TABLE placements (
|
|
27
|
+
canvas_id TEXT NOT NULL,
|
|
28
|
+
note_id TEXT NOT NULL,
|
|
29
|
+
via TEXT NOT NULL,
|
|
30
|
+
PRIMARY KEY (canvas_id, note_id, via)
|
|
31
|
+
) WITHOUT ROWID`,
|
|
32
|
+
// Where everything on each board sits, for the WebGL workspace map. `data`
|
|
33
|
+
// is the rest of the row as JSON (a frame's name and SECTION id, a text
|
|
34
|
+
// card's words, a quote card's look, a portal's target, a list's count).
|
|
35
|
+
`CREATE TABLE layout_nodes (
|
|
36
|
+
canvas_id TEXT NOT NULL,
|
|
37
|
+
node_id TEXT NOT NULL,
|
|
38
|
+
kind TEXT NOT NULL,
|
|
39
|
+
note_id TEXT,
|
|
40
|
+
x REAL NOT NULL,
|
|
41
|
+
y REAL NOT NULL,
|
|
42
|
+
w REAL,
|
|
43
|
+
h REAL,
|
|
44
|
+
data TEXT NOT NULL,
|
|
45
|
+
PRIMARY KEY (canvas_id, node_id)
|
|
46
|
+
) WITHOUT ROWID`,
|
|
47
|
+
`CREATE TABLE layout_edges (
|
|
48
|
+
canvas_id TEXT NOT NULL,
|
|
49
|
+
source TEXT NOT NULL,
|
|
50
|
+
target TEXT NOT NULL,
|
|
51
|
+
arrow_start INTEGER,
|
|
52
|
+
arrow_end INTEGER,
|
|
53
|
+
line_style TEXT
|
|
54
|
+
)`,
|
|
55
|
+
`CREATE INDEX layout_edges_by_canvas ON layout_edges (canvas_id)`,
|
|
56
|
+
`CREATE TABLE members (user_id TEXT PRIMARY KEY, name TEXT)`,
|
|
57
|
+
`CREATE TABLE dimensions (
|
|
58
|
+
type TEXT NOT NULL,
|
|
59
|
+
key TEXT NOT NULL,
|
|
60
|
+
label TEXT,
|
|
61
|
+
kind TEXT,
|
|
62
|
+
options TEXT,
|
|
63
|
+
supertag_id TEXT,
|
|
64
|
+
answers_at INTEGER,
|
|
65
|
+
PRIMARY KEY (type, key)
|
|
66
|
+
)`,
|
|
67
|
+
`CREATE TABLE answers (
|
|
68
|
+
note_id TEXT NOT NULL,
|
|
69
|
+
type TEXT NOT NULL,
|
|
70
|
+
key TEXT NOT NULL,
|
|
71
|
+
state TEXT NOT NULL,
|
|
72
|
+
value REAL,
|
|
73
|
+
judged_at INTEGER,
|
|
74
|
+
PRIMARY KEY (note_id, type, key)
|
|
75
|
+
) WITHOUT ROWID`,
|
|
76
|
+
`CREATE TABLE meta (key TEXT PRIMARY KEY, value TEXT)`,
|
|
77
|
+
`CREATE INDEX notes_by_type ON notes (type)`,
|
|
78
|
+
`CREATE INDEX notes_by_updated ON notes (updated_at)`,
|
|
79
|
+
`CREATE INDEX notes_by_created ON notes (created_at)`,
|
|
80
|
+
`CREATE INDEX placements_by_note ON placements (note_id)`,
|
|
81
|
+
`CREATE INDEX tags_by_tag ON note_tags (tag)`,
|
|
82
|
+
`CREATE INDEX answers_by_key ON answers (type, key, state)`,
|
|
83
|
+
];
|
|
84
|
+
/** Create the tables, or drop and recreate them when the schema moved. Returns true when it (re)created. */
|
|
85
|
+
export function ensureSchema(db) {
|
|
86
|
+
const version = Number(db.all("PRAGMA user_version")[0]?.user_version ?? 0);
|
|
87
|
+
if (version === SCHEMA_VERSION)
|
|
88
|
+
return false;
|
|
89
|
+
db.transaction(() => {
|
|
90
|
+
for (const table of TABLES)
|
|
91
|
+
db.run(`DROP TABLE IF EXISTS ${table}`);
|
|
92
|
+
for (const statement of CREATE)
|
|
93
|
+
db.run(statement);
|
|
94
|
+
db.run(`PRAGMA user_version = ${SCHEMA_VERSION}`);
|
|
95
|
+
});
|
|
96
|
+
return true;
|
|
97
|
+
}
|
|
98
|
+
/** What the SQL box shows as the tables a reader can query. */
|
|
99
|
+
export const SCHEMA_HINT = [
|
|
100
|
+
"notes(id, display_id, title, type, created_by, source, created_at, updated_at)",
|
|
101
|
+
"note_tags(note_id, tag)",
|
|
102
|
+
"canvases(id, display_id, name, updated_at, note_count, is_default, branch_of)",
|
|
103
|
+
"placements(canvas_id, note_id, via) -- via: card | list",
|
|
104
|
+
"members(user_id, name)",
|
|
105
|
+
"dimensions(type, key, label, kind, options)",
|
|
106
|
+
"answers(note_id, type, key, state, value, judged_at)",
|
|
107
|
+
];
|