-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdomain.js
More file actions
314 lines (283 loc) · 11.7 KB
/
Copy pathdomain.js
File metadata and controls
314 lines (283 loc) · 11.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
import { MAX_LOCAL_DEPTH, WIKILINK_RE } from './constants.js'
export function hashStr(s) {
let h = 0;
for (let i = 0; i < s.length; i++) {
h = (h * 31 + s.charCodeAt(i)) | 0;
}
return Math.abs(h);
}
// Strip a leading YAML frontmatter block (between the first two '---' lines).
export function stripFrontmatter(md) {
if (!md) return '';
const m = md.match(/^---\s*\n([\s\S]*?)\n---\s*\n?/);
return m ? md.slice(m[0].length) : md;
}
// Pull a few useful fields out of frontmatter for the panel header.
export function parseFrontmatter(md) {
const out = {};
if (!md) return out;
const m = md.match(/^---\s*\n([\s\S]*?)\n---/);
if (!m) return out;
for (const line of m[1].split('\n')) {
const kv = line.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);
if (kv) out[kv[1].toLowerCase()] = kv[2].trim();
}
return out;
}
export function fmtBytes(n) {
if (n == null) return '—';
if (n < 1024) return n + ' B';
if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB';
return (n / (1024 * 1024)).toFixed(1) + ' MB';
}
export function parseDailyCronTime(cron) {
if (typeof cron !== 'string') return null;
const parts = cron.trim().split(/\s+/);
if (parts.length < 5) return null;
const [minuteRaw, hourRaw, day, month, weekday] = parts;
if (day !== '*' || month !== '*' || weekday !== '*') return null;
if (!/^\d{1,2}$/.test(minuteRaw) || !/^\d{1,2}$/.test(hourRaw)) return null;
const minute = Number(minuteRaw);
const hour = Number(hourRaw);
if (!Number.isInteger(minute) || minute < 0 || minute > 59) return null;
if (!Number.isInteger(hour) || hour < 0 || hour > 23) return null;
return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}`;
}
export function timeToDailyCron(value) {
if (typeof value !== 'string') return null;
const m = value.match(/^(\d{2}):(\d{2})$/);
if (!m) return null;
const hour = Number(m[1]);
const minute = Number(m[2]);
if (!Number.isInteger(hour) || hour < 0 || hour > 23) return null;
if (!Number.isInteger(minute) || minute < 0 || minute > 59) return null;
return `${minute} ${hour} * * *`;
}
const MEMORY_NOTE_INTENT_RE = /^note:([A-Za-z0-9][A-Za-z0-9._-]{0,127})$/;
export function memoryNoteIntent(value) {
if (typeof value !== 'string') return null;
return MEMORY_NOTE_INTENT_RE.exec(value.trim())?.[1] || null;
}
export function nodeRadius(node = {}) {
const accessCount = Number(node.access_count);
const safeAccessCount = Number.isFinite(accessCount) && accessCount > 0 ? accessCount : 0;
const base = 1 + Math.log2(1 + safeAccessCount);
// Keep dense graphs legible on phones: usage still changes prominence, but
// no individual circle should consume the space needed to read its links.
const radius = 2.6 + base * 1.28;
return node.type === 'moc' ? radius * 1.32 : radius;
}
// usage.json is cumulative and may be fresher than the immutable graph. A
// cached ledger can also be older, so the displayed value is the greater valid
// count rather than whichever source happened to arrive last.
export function effectiveReadCount(node = {}, usage = {}) {
const counts = usage && typeof usage === 'object' && !Array.isArray(usage)
? usage
: {};
const live = counts[node.id];
const published = node.access_count;
const publishedCount = Number.isInteger(published) && published >= 0 ? published : 0;
return Number.isInteger(live) && live >= 0
? Math.max(live, publishedCount)
: publishedCount;
}
export function buildTitleMap(nodes = []) {
const map = {};
for (const n of nodes || []) {
if (!n || !n.id) continue;
map[n.id] = n.title || n.id;
}
return map;
}
export function renderWikiLinks(md, nodes = []) {
if (!md) return '';
const titles = buildTitleMap(nodes);
return String(md).replace(WIKILINK_RE, (_, rawSlug, rawAlias) => {
const slug = String(rawSlug || '').trim();
if (!slug) return _;
const label = String(rawAlias || '').trim() || titles[slug] || slug;
return `[${escapeMarkdownLinkText(label)}](#memory-node-${encodeURIComponent(slug)})`;
});
}
export function buildLocalGraphData(graph, centerId, depth = 1) {
if (!graph || !centerId) return { nodes: [], links: [] };
const nodes = Array.isArray(graph.nodes) ? graph.nodes : [];
const edges = Array.isArray(graph.edges) ? graph.edges : [];
const byId = new Map(nodes.map((n) => [n.id, n]));
if (!byId.has(centerId)) return { nodes: [], links: [] };
const maxDepth = Math.max(0, Math.min(MAX_LOCAL_DEPTH, Number(depth) || 0));
const adj = new Map();
const add = (a, b) => {
if (!adj.has(a)) adj.set(a, new Set());
adj.get(a).add(b);
};
for (const e of edges) {
const s = typeof e.source === 'object' ? e.source.id : e.source;
const t = typeof e.target === 'object' ? e.target.id : e.target;
if (!byId.has(s) || !byId.has(t)) continue;
add(s, t); add(t, s);
}
const seen = new Map([[centerId, 0]]);
const q = [centerId];
while (q.length) {
const cur = q.shift();
const d = seen.get(cur) || 0;
if (d >= maxDepth) continue;
for (const next of adj.get(cur) || []) {
if (seen.has(next)) continue;
seen.set(next, d + 1);
q.push(next);
}
}
const keep = new Set(seen.keys());
const showLabelAlways = keep.size <= 150;
return {
nodes: [...keep].map((id) => ({
...byId.get(id),
localDepth: seen.get(id) || 0,
showLabelAlways,
})),
links: edges
.map((e) => ({
source: typeof e.source === 'object' ? e.source.id : e.source,
target: typeof e.target === 'object' ? e.target.id : e.target,
kind: e.kind,
}))
.filter((e) => keep.has(e.source) && keep.has(e.target)),
};
}
export function stepBackThroughNodeVisits(visits = [], nodesById = new Map()) {
if (!Array.isArray(visits) || typeof nodesById?.get !== 'function') {
return { visit: null, node: null, remaining: [] };
}
for (let index = visits.length - 1; index >= 0; index -= 1) {
const visit = visits[index];
const node = nodesById.get(visit?.id);
if (node) {
return { visit, node, remaining: visits.slice(0, index) };
}
}
return { visit: null, node: null, remaining: [] };
}
// A short, human relative-time from an ISO-ish frontmatter date string.
export function relDate(s) {
if (!s || s === 'null') return null;
const t = Date.parse(s);
if (Number.isNaN(t)) return null;
const days = Math.floor((Date.now() - t) / 86400000);
if (days <= 0) return 'today';
if (days === 1) return 'yesterday';
if (days < 30) return days + 'd ago';
if (days < 365) return Math.floor(days / 30) + 'mo ago';
return Math.floor(days / 365) + 'y ago';
}
export function escapeHtml(s) {
return String(s)
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
export function escapeMarkdownLinkText(s) {
return String(s).replace(/\\/g, '\\\\').replace(/]/g, '\\]');
}
// Note paths come from agent-written graph.json. Reject traversal, absolute
// paths, query/fragment smuggling, and non-markdown targets, and encode each
// segment so the fetch URL can't be reshaped by the path contents.
export function safeMemoryPath(path) {
if (typeof path !== 'string') return null;
const trimmed = path.trim();
if (!trimmed || trimmed.startsWith('/') || trimmed.includes('\\')) return null;
if (trimmed.includes('?') || trimmed.includes('#')) return null;
const parts = trimmed.split('/');
if (parts.some((part) => !part || part === '.' || part === '..')) return null;
if (!parts[parts.length - 1].endsWith('.md')) return null;
return parts.map((part) => encodeURIComponent(part)).join('/');
}
// DOMPurify policy for memory notes: on top of the html profile, forbid every
// network-bearing tag and attribute (the prod CSP blocks remote img/connect,
// but form-action is NOT covered by default-src and test instances run without
// the Caddy CSP entirely — so the app forbids these itself). href is the one
// URL attribute left allowed, because wikilink anchors need it;
// restrictNoteHtml then drops every href that isn't a #memory-node- fragment.
export const MEMORY_SANITIZE_OPTIONS = {
USE_PROFILES: { html: true },
FORBID_TAGS: ['img', 'picture', 'source', 'video', 'audio', 'iframe', 'object', 'embed', 'form', 'input', 'button'],
FORBID_ATTR: ['src', 'srcset', 'xlink:href', 'formaction'],
};
// Markdown-level twin of the sanitize policy: plain links keep their label
// but lose the URL, images collapse to their alt text. Wikilink syntax
// ([[slug]] / [[slug|alias]]) never matches either pattern, so running this
// before renderWikiLinks leaves wikilinks intact.
export function neutralizeMemoryMarkdown(md) {
return (md || '')
.replace(/!\[([^\]]*)\]\(([^)]+)\)/g, (_m, alt) => ` ${alt || 'image'} `)
.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1');
}
// Post-sanitize pass over already-DOMPurify-clean HTML: strip every anchor
// href except the #memory-node- fragments renderWikiLinks generates. Removal
// only — it cannot introduce markup the sanitizer didn't already allow.
export function restrictNoteHtml(html) {
const tpl = document.createElement('template');
tpl.innerHTML = html;
for (const a of tpl.content.querySelectorAll('a[href]')) {
if (!a.getAttribute('href').startsWith('#memory-node-')) a.removeAttribute('href');
}
return tpl.innerHTML;
}
export function clamp(v, min, max) {
return Math.max(min, Math.min(max, v));
}
export function labelScore(node = {}) {
const access = Number(node.access_count) || 0;
const mocBonus = node.type === 'moc' ? 1000 : 0;
const linkedBonus = Array.isArray(node.mocs) && node.mocs.length > 0 ? 18 : 0;
const localBonus = node.localDepth === 0 ? 800 : node.localDepth === 1 ? 120 : 0;
return mocBonus + localBonus + access * 4 + linkedBonus;
}
export function shouldShowScreenLabel(node = {}, scale = 1, labelRank = 0, opts = {}) {
const isHover = node.id === opts.hoverId;
const isSelected = node.id === opts.selectedId;
const isHub = node.type === 'moc';
const isLocalCenter = node.localDepth === 0;
if (isHover || isSelected || isLocalCenter) return true;
// Hub policy is per-mode, so it sits below the shared guard rather than in
// it: a bounded local neighbourhood always labels its hubs as navigation
// anchors, while the global view holds every hub at once and only lets a hub
// outrank others (scale < 0.9) so phone-width graphs stay readable.
if (opts.mode === 'local') {
if (isHub) return true;
if (node.localDepth === 1 && scale >= 0.72) return true;
if (node.localDepth === 2 && scale >= 1.15) return true;
return scale >= 1.7 && labelRank < 18;
}
const compact = opts.compact === true;
if (scale < 0.9) return isHub && labelRank < (compact ? 1 : 4);
if (scale < 1.25) return labelRank < (compact ? 2 : 6);
if (scale < 1.7) return labelRank < (compact ? 6 : 14);
if (scale < 2.2) return labelRank < (compact ? 10 : 26);
return labelRank < (compact ? 18 : 60);
}
// Read a CSS custom property off :root (computed) with a fallback.
// Re-read on each entry because the parent can swap the theme live
// (moebius:frame-theme); caching the computed style would freeze the old
// palette after a light/dark toggle.
export function cssVar(name, fallback) {
const v = getComputedStyle(document.documentElement).getPropertyValue(name).trim();
return v || fallback;
}
// Parse a CSS color string to [r,g,b]. Handles #rgb, #rrggbb, and rgb()/rgba().
export function parseRGB(c) {
if (!c) return null;
const s = c.trim();
let m = s.match(/^#?([0-9a-fA-F]{3})$/);
if (m) {
const h = m[1];
return [parseInt(h[0] + h[0], 16), parseInt(h[1] + h[1], 16), parseInt(h[2] + h[2], 16)];
}
m = s.match(/^#?([0-9a-fA-F]{6})$/);
if (m) {
const i = parseInt(m[1], 16);
return [(i >> 16) & 255, (i >> 8) & 255, i & 255];
}
m = s.match(/rgba?\(\s*([0-9.]+)[, ]+([0-9.]+)[, ]+([0-9.]+)/);
if (m) return [+m[1], +m[2], +m[3]];
return null;
}