@coda-console/friends 0.5.0 → 0.6.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/lib/notes.mjs DELETED
@@ -1,65 +0,0 @@
1
- // 好友的本地备注:只存在本机插件的持久目录里(notes.json,卸载后保留),不发给好友,也不进 Accord 目录。
2
- // 按好友的 node 记名,原子写盘(临时文件 + rename);文件缺失或损坏时当空表。
3
- import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
4
- import { join } from 'node:path';
5
-
6
- export const MAX_NOTE = 40;
7
- const MAX_KEY = 200;
8
- const CONTROL = /[\p{Cc}\u2028\u2029]/gu, HAS_CONTROL = /[\p{Cc}\u2028\u2029]/u;
9
-
10
- /** 去掉控制字符、两端空白,最多 40 个字符(按码点)。 */
11
- export function cleanNote(text) {
12
- if (typeof text !== 'string') return '';
13
- return [...text.replace(CONTROL, '').trim()].slice(0, MAX_NOTE).join('').trim();
14
- }
15
-
16
- function validKey(key) {
17
- return typeof key === 'string' && key !== '' && [...key].length <= MAX_KEY && !HAS_CONTROL.test(key);
18
- }
19
-
20
- /** 从磁盘读出 `{ key: 备注 }`;缺失、损坏、不是对象时为空表。 */
21
- export async function readNotes(dir) {
22
- let parsed;
23
- try { parsed = JSON.parse(await readFile(join(dir, 'notes.json'), 'utf8')); } catch { return {}; }
24
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
25
- const notes = Object.create(null);
26
- for (const [key, value] of Object.entries(parsed)) {
27
- const note = cleanNote(value);
28
- if (validKey(key) && note) notes[key] = note;
29
- }
30
- return { ...notes };
31
- }
32
-
33
- let counter = 0;
34
- async function writeNotes(dir, notes) {
35
- await mkdir(dir, { recursive: true });
36
- const target = join(dir, 'notes.json'), temporary = join(dir, `notes.json.${process.pid}.${++counter}.tmp`);
37
- try {
38
- await writeFile(temporary, `${JSON.stringify(notes, null, 2)}\n`, { mode: 0o600 });
39
- await rename(temporary, target);
40
- } catch (e) { await rm(temporary, { force: true }).catch(() => {}); throw e; }
41
- }
42
-
43
- // 同一目录的写入排队,读改写不会互相覆盖。
44
- const queues = new Map();
45
- function exclusive(dir, work) {
46
- const run = (queues.get(dir) ?? Promise.resolve()).then(work, work);
47
- const tail = run.catch(() => {});
48
- queues.set(dir, tail);
49
- tail.then(() => { if (queues.get(dir) === tail) queues.delete(dir); });
50
- return run;
51
- }
52
-
53
- /** 设置一个好友的备注;清洗后为空串就是删除。返回现在的整张表。 */
54
- export function setNote(dir, key, text) {
55
- if (!validKey(key)) return Promise.reject(new Error('好友标识不合法'));
56
- return exclusive(dir, async () => {
57
- const notes = await readNotes(dir), note = cleanNote(text);
58
- if (note) notes[key] = note; else delete notes[key];
59
- await writeNotes(dir, notes);
60
- return notes;
61
- });
62
- }
63
-
64
- /** 删除一个好友的备注。返回现在的整张表。 */
65
- export function deleteNote(dir, key) { return setNote(dir, key, ''); }
@@ -1,218 +0,0 @@
1
- // 私信 friends/dm 与好友动态 friends/feed 的纯逻辑:发布入参的清洗、Accord 记录的投影,以及实时流的变更集与游标。不碰 Coda,也不碰磁盘。
2
- // 记录照旧由 coda/accord@1 签名与保存;这里只把一页页读回来的记录投影成规范项,并在内存里比对前后两份投影,算出增量帧。
3
- import { normalizeContentPointer, readContentPointer } from './friends.mjs';
4
-
5
- export const DM_KIND = 'friends/dm', FEED_KIND = 'friends/feed';
6
- export const MAX_TEXT = 8000, MAX_MEDIA = 4, MAX_HISTORY = 500;
7
- // 快照一帧的字节上限,远低于 readFrames 默认的一行 1 MiB:快照按它分片。
8
- export const MAX_SNAPSHOT_FRAME_BYTES = 256 * 1024;
9
- const MAX_ID = 200, MAX_ID_BYTES = 256, MAX_AUDIENCE = 500;
10
- const AUTHOR = /^ed25519:[0-9a-f]{64}$/, AUDIENCE = /^(?:public|ed25519:[0-9a-f]{64})$/;
11
- const CONTROL = /[\p{Cc}]/u;
12
- const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
13
- const CURSOR = new RegExp(`^(${UUID}):(0|[1-9][0-9]*)$`);
14
-
15
- const fail = message => { throw new Error(message); };
16
- const length = text => [...text].length;
17
- const encoder = new TextEncoder();
18
- const bytes = text => encoder.encode(text).length;
19
- const isPlain = value => value !== null && typeof value === 'object' && !Array.isArray(value);
20
- const isTime = value => Number.isSafeInteger(value) && value >= 0;
21
- const validLabel = text => typeof text === 'string' && text.length > 0 && length(text) <= MAX_ID && !CONTROL.test(text);
22
- export const isAuthor = value => typeof value === 'string' && AUTHOR.test(value);
23
-
24
- // ---- 发布入参 ----
25
-
26
- /**
27
- * 可选的 id、replyTo:原样至多 200 个字符(与 schema 的 maxLength 同样按码点数)、UTF-8 至多 256 字节(与 Accord 一致)、
28
- * 不含控制字符,去首尾空白后不能是空的;省略给 undefined(id 由调用方生成)。
29
- */
30
- function readLabel(value, name) {
31
- if (value === undefined) return undefined;
32
- if (typeof value !== 'string' || length(value) > MAX_ID || bytes(value) > MAX_ID_BYTES || CONTROL.test(value) || !value.trim())
33
- fail(`${name} 须是 1–${MAX_ID} 个字符、UTF-8 至多 ${MAX_ID_BYTES} 字节的文本,不含控制字符`);
34
- return value.trim();
35
- }
36
-
37
- /** text 原样至多 8000 个字(码点,与 schema 一致),再去首尾空白。 */
38
- function readText(text) {
39
- if (text === undefined) return '';
40
- if (typeof text !== 'string') fail('text 须是文本');
41
- if (length(text) > MAX_TEXT) fail(`text 最多 ${MAX_TEXT} 个字`);
42
- return text.trim();
43
- }
44
-
45
- function readPointers(list, name) {
46
- if (list === undefined) return [];
47
- if (!Array.isArray(list) || !list.length || list.length > MAX_MEDIA) fail(`${name} 须是 1–${MAX_MEDIA} 项的数组`);
48
- return list.map(normalizeContentPointer);
49
- }
50
-
51
- const createdAtOf = (existingCreatedAt, now) => {
52
- const at = isTime(existingCreatedAt) ? existingCreatedAt : now;
53
- if (!isTime(at)) fail('createdAt 须是非负整数');
54
- return at;
55
- };
56
-
57
- /**
58
- * 私信的入参 `{ to, id?, text?, attachments?, replyTo? }` → `{ id, to, audience: [to], body }`。只发给一个人,不能发给 public 或自己;
59
- * text 与 attachments 不能都空。createdAt 先用同一 id 已有记录的(重试时内容不变,才能按幂等跳过),没有再取 now。
60
- */
61
- export function normalizeDmInput(input, { selfAuthor, existingCreatedAt, now = Date.now() } = {}) {
62
- if (!isPlain(input)) fail('私信须是对象');
63
- const { to } = input;
64
- if (!isAuthor(to)) fail('to 须是一位好友的公钥 ed25519:<64 位小写十六进制>');
65
- if (to === selfAuthor) fail('不能给自己发私信');
66
- const id = readLabel(input.id, 'id'), text = readText(input.text), attachments = readPointers(input.attachments, 'attachments');
67
- if (!text && !attachments.length) fail('私信的 text 与 attachments 不能都空');
68
- const replyTo = readLabel(input.replyTo, 'replyTo'), createdAt = createdAtOf(existingCreatedAt, now);
69
- return { id, to, audience: [to], body: { to, text, ...(attachments.length ? { attachments } : {}), ...(replyTo ? { replyTo } : {}), createdAt } };
70
- }
71
-
72
- /**
73
- * 动态的入参 `{ id?, text?, media?, audience? }` → `{ id, audience, body }`。audience 省略是 `['public']`,写了须是 1–500 项、
74
- * 每项 public 或公钥,去重;`[]` 不收(撤回走 retract)。text 与 media 不能都空;createdAt 同私信。
75
- */
76
- export function normalizeFeedInput(input, { existingCreatedAt, now = Date.now() } = {}) {
77
- if (!isPlain(input)) fail('动态须是对象');
78
- const id = readLabel(input.id, 'id'), text = readText(input.text), media = readPointers(input.media, 'media');
79
- if (!text && !media.length) fail('动态的 text 与 media 不能都空');
80
- const { audience = ['public'] } = input;
81
- if (!Array.isArray(audience) || !audience.length || audience.length > MAX_AUDIENCE) fail(`audience 须是 1–${MAX_AUDIENCE} 项的数组;撤回用 retract`);
82
- if (!audience.every(item => typeof item === 'string' && AUDIENCE.test(item))) fail("audience 每项须是 'public' 或 ed25519:<64 位小写十六进制>");
83
- return { id, audience: [...new Set(audience)], body: { text, ...(media.length ? { media } : {}), createdAt: createdAtOf(existingCreatedAt, now) } };
84
- }
85
-
86
- // ---- 记录投影 ----
87
-
88
- // 每个 (author, id) 只留 version 最大的一条:最新的是撤回(空 body)或畸形,整条就算没了,不回落到旧版本。
89
- function latest(records) {
90
- const top = new Map();
91
- for (const record of records ?? []) {
92
- if (!isPlain(record) || typeof record.author !== 'string' || typeof record.id !== 'string') continue;
93
- const key = JSON.stringify([record.author, record.id]), version = Number.isSafeInteger(record.version) ? record.version : 0;
94
- if (!top.has(key) || version > top.get(key).version) top.set(key, { record, version });
95
- }
96
- return [...top.values()];
97
- }
98
-
99
- // 外来正文:text 是至多 8000 字的文本(不合法当空),图片指针只留校验通过的、至多 4 个;两样都空、或 createdAt 不对就是畸形(null)。
100
- function readBody(body, pointersKey) {
101
- if (!isPlain(body) || !isTime(body.createdAt)) return null;
102
- const text = typeof body.text === 'string' && length(body.text) <= MAX_TEXT ? body.text.trim() : '';
103
- const pointers = Array.isArray(body[pointersKey]) ? body[pointersKey].map(readContentPointer).filter(Boolean).slice(0, MAX_MEDIA) : [];
104
- return text || pointers.length ? { text, pointers, createdAt: body.createdAt } : null;
105
- }
106
-
107
- const compare = (a, b) => a.createdAt - b.createdAt || a.version - b.version || (a.author < b.author ? -1 : a.author > b.author ? 1 : 0) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
108
-
109
- /**
110
- * Accord 的 friends/dm 记录 → 私信规范项,按 (createdAt, version, author, id) 升序。只收真是本机与对方之间的:本机发出的须是本人签的、
111
- * 发给别人;收到的须是别人签的、发给本人。`peer` 是对面那个人。
112
- */
113
- export function projectDmRecords(records, { selfAuthor } = {}) {
114
- const items = [];
115
- for (const { record, version } of latest(records)) {
116
- const body = readBody(record.body, 'attachments'), to = record.body?.to;
117
- if (!body || !isAuthor(to)) continue;
118
- let peer;
119
- if (record.local === true && record.author === selfAuthor && to !== selfAuthor) peer = to;
120
- else if (record.local === false && record.author !== selfAuthor && to === selfAuthor) peer = record.author;
121
- else continue;
122
- const { replyTo } = record.body;
123
- items.push({ author: record.author, id: record.id, version, local: record.local, peer, to, text: body.text, attachments: body.pointers,
124
- ...(validLabel(replyTo) ? { replyTo } : {}), createdAt: body.createdAt });
125
- }
126
- return items.sort(compare);
127
- }
128
-
129
- /** Accord 的 friends/feed 记录 → 动态规范项,按 (createdAt, version, author, id) 降序(新的在前)。 */
130
- export function projectFeedRecords(records) {
131
- const items = [];
132
- for (const { record, version } of latest(records)) {
133
- const body = readBody(record.body, 'media');
134
- if (body) items.push({ author: record.author, id: record.id, version, local: record.local === true, text: body.text, media: body.pointers, createdAt: body.createdAt });
135
- }
136
- return items.sort((a, b) => compare(b, a));
137
- }
138
-
139
- // ---- 变更集与游标 ----
140
-
141
- /** 游标 `${epoch}:${seq}` → `{ epoch, seq }`;不合法给 null。 */
142
- export function parseCursor(after) {
143
- const match = typeof after === 'string' ? CURSOR.exec(after) : null;
144
- if (!match) return null;
145
- const seq = Number(match[2]);
146
- return Number.isSafeInteger(seq) ? { epoch: match[1], seq } : null;
147
- }
148
-
149
- const keyOf = item => JSON.stringify([item.author, item.id]);
150
- /** 一次变化里用来过滤的那一项:upsert 看它的 item,retract 看它自己(带 author、peer)。 */
151
- export const subjectOf = event => event.type === 'upsert' ? event.item : event;
152
- /** 变化 → 帧:seq 换成游标。 */
153
- export const frameOf = (epoch, { seq, ...event }) => ({ ...event, cursor: `${epoch}:${seq}` });
154
-
155
- /**
156
- * 快照的帧:items 按序切成每帧 JSON 至多 `maxBytes` 字节的几片,`{ type: 'snapshot', cursor, items, more }`,还有后续分片的
157
- * `more` 为 true,最后一片(空快照也有这一片,`items: []`)为 false;客户端收到 more 为 false 才把整份快照与游标落定。
158
- */
159
- export function snapshotFrames(cursor, items, maxBytes = MAX_SNAPSHOT_FRAME_BYTES) {
160
- const empty = bytes(JSON.stringify({ type: 'snapshot', cursor, items: [], more: false })), chunks = [[]];
161
- let size = empty;
162
- for (const item of items) {
163
- const one = bytes(JSON.stringify(item)) + 1;
164
- if (chunks.at(-1).length && size + one > maxBytes) { chunks.push([]); size = empty; }
165
- chunks.at(-1).push(item);
166
- size += one;
167
- }
168
- return chunks.map((chunk, i) => ({ type: 'snapshot', cursor, items: chunk, more: i < chunks.length - 1 }));
169
- }
170
-
171
- /**
172
- * 一条流的内存状态:启动时的 epoch、单调的 seq、当前投影(按 (author, id))、至多 `maxHistory` 条变化的环缓冲。
173
- * `applySnapshot` 换上新一份投影并给出这次的变化;`resume(after, match)` 按游标给出续上的增量,续不上就给全量快照。
174
- */
175
- export function createStreamHub({ epoch = globalThis.crypto.randomUUID(), maxHistory = MAX_HISTORY } = {}) {
176
- let seq = 0, current = new Map(), history = [];
177
- const oldestSeq = () => history.length ? history[0].seq : seq + 1;
178
- const cursor = () => `${epoch}:${seq}`;
179
- return {
180
- epoch,
181
- get seq() { return seq; },
182
- get oldestSeq() { return oldestSeq(); },
183
- cursor,
184
- items: () => [...current.values()],
185
- // 先在局部算好这次的变化,最后一并换上投影、seq 与历史:中途出错,hub 还是原来那份。
186
- applySnapshot(nextItems) {
187
- const next = new Map(nextItems.map(item => [keyOf(item), item])), events = [];
188
- let at = seq;
189
- for (const [key, item] of current) {
190
- if (!next.has(key)) events.push({ seq: ++at, type: 'retract', author: item.author, id: item.id, ...(item.peer ? { peer: item.peer } : {}) });
191
- }
192
- for (const [key, item] of next) {
193
- const old = current.get(key);
194
- if (old && old.version === item.version && JSON.stringify(old) === JSON.stringify(item)) continue;
195
- // 同一条私信换了收件人:旧会话那边先撤掉,新会话再收到它。
196
- if (old?.peer && old.peer !== item.peer) events.push({ seq: ++at, type: 'retract', author: old.author, id: old.id, peer: old.peer });
197
- events.push({ seq: ++at, type: 'upsert', item });
198
- }
199
- // 不把 events 展开成实参(一次几十万条会超出实参上限):够多就只取最后 maxHistory 条,否则逐条追加再裁。
200
- let kept;
201
- if (events.length >= maxHistory) kept = events.slice(-maxHistory);
202
- else {
203
- kept = history.slice();
204
- for (const event of events) kept.push(event);
205
- if (kept.length > maxHistory) kept.splice(0, kept.length - maxHistory);
206
- }
207
- current = next;
208
- seq = at;
209
- history = kept;
210
- return events;
211
- },
212
- resume(after, match = () => true) {
213
- const at = parseCursor(after);
214
- if (!at || at.epoch !== epoch || at.seq > seq || at.seq < oldestSeq() - 1) return { mode: 'snapshot', cursor: cursor(), items: [...current.values()].filter(match) };
215
- return { mode: 'delta', cursor: cursor(), events: history.filter(event => event.seq > at.seq && match(subjectOf(event))) };
216
- },
217
- };
218
- }
package/view/cropper.mjs DELETED
@@ -1,106 +0,0 @@
1
- // 头像裁剪:本地选的图放进 1:1 方框,拖动平移(Pointer Events,鼠标与触控都走它)、滑块缩放 1.0×–3.0×,
2
- // 导出 512×512 的压缩图。图片只经 URL.createObjectURL 读进来,换图、清除时回收地址。
3
- import { BLOB_MAX_BYTES } from '../lib/avatar.mjs';
4
- import { h } from './dom.mjs';
5
-
6
- export const OUTPUT_SIZE = 512;
7
- const VIEW = 440, MIN_ZOOM = 1, MAX_ZOOM = 3;
8
- const clamp = (value, low, high) => Math.min(high, Math.max(low, value));
9
- const toBlob = (canvas, type, quality) => new Promise(resolve => canvas.toBlob(resolve, type, quality));
10
-
11
- /** 先试 WebP 0.86;浏览器不会编 WebP(退回别的格式或给 null)或超限,就用 JPEG 0.86,仍超限降到 0.72。 */
12
- export async function encodeAvatar(canvas) {
13
- const webp = await toBlob(canvas, 'image/webp', 0.86);
14
- if (webp?.type === 'image/webp' && webp.size <= BLOB_MAX_BYTES) return webp;
15
- for (const quality of [0.86, 0.72]) {
16
- const jpeg = await toBlob(canvas, 'image/jpeg', quality);
17
- if (jpeg && jpeg.size <= BLOB_MAX_BYTES) return jpeg;
18
- }
19
- throw new Error('图片压缩后仍超过 5 MiB,请换一张');
20
- }
21
-
22
- /** onChange 在画面变化(载入、拖动、缩放、清除)后调用,给实时预览用。 */
23
- export function createCropper({ onChange } = {}) {
24
- let crop = null, url = null, drag = null, loading = 0;
25
- const canvas = h('canvas', { class: 'crop-canvas', width: VIEW, height: VIEW });
26
- const zoomText = h('span', { class: 'mono zoom-value' }, '1.0×');
27
- const zoom = h('input', { type: 'range', min: MIN_ZOOM, max: MAX_ZOOM, step: '0.01', value: '1', 'aria-label': '缩放',
28
- oninput: e => { if (crop) { crop.zoom = clamp(Number(e.target.value), MIN_ZOOM, MAX_ZOOM); draw(); } } });
29
- const box = h('div', { class: 'crop-box', role: 'img', 'aria-label': '拖动调整头像位置',
30
- onpointerdown: e => {
31
- if (!crop) return;
32
- box.setPointerCapture(e.pointerId);
33
- drag = { id: e.pointerId, x: e.clientX, y: e.clientY, ox: crop.x, oy: crop.y, ratio: VIEW / (box.clientWidth || VIEW) };
34
- box.className = 'crop-box dragging';
35
- },
36
- onpointermove: e => {
37
- if (!drag || e.pointerId !== drag.id) return;
38
- crop.x = drag.ox + (e.clientX - drag.x) * drag.ratio;
39
- crop.y = drag.oy + (e.clientY - drag.y) * drag.ratio;
40
- draw();
41
- },
42
- onpointerup: end, onpointercancel: end,
43
- }, canvas, h('div', { class: 'crop-grid', 'aria-hidden': 'true' }));
44
- function end() { drag = null; box.className = 'crop-box'; }
45
-
46
- // 图按「铺满方框」缩放后再乘 zoom;平移限制在不露出空白的范围里。
47
- function layout(size) {
48
- const { img } = crop, scale = Math.max(size / img.naturalWidth, size / img.naturalHeight) * crop.zoom;
49
- const width = img.naturalWidth * scale, height = img.naturalHeight * scale;
50
- return { scale, width, height, x: (size - width) / 2 + crop.x * (size / VIEW), y: (size - height) / 2 + crop.y * (size / VIEW) };
51
- }
52
- function draw() {
53
- const ctx = canvas.getContext('2d');
54
- ctx.clearRect(0, 0, VIEW, VIEW);
55
- if (crop) {
56
- const { width, height } = layout(VIEW);
57
- crop.x = clamp(crop.x, -(width - VIEW) / 2, (width - VIEW) / 2);
58
- crop.y = clamp(crop.y, -(height - VIEW) / 2, (height - VIEW) / 2);
59
- const at = layout(VIEW);
60
- ctx.drawImage(crop.img, at.x, at.y, at.width, at.height);
61
- zoomText.textContent = `${crop.zoom.toFixed(1)}×`;
62
- }
63
- onChange?.();
64
- }
65
-
66
- // 换一张:先回收上一张的地址;读的途中又换了或清除了,就不再用这张。
67
- async function load(file) {
68
- clear();
69
- const mine = ++loading, img = new Image();
70
- url = URL.createObjectURL(file);
71
- try {
72
- await new Promise((resolve, reject) => { img.onload = resolve; img.onerror = () => reject(new Error('读不出这张图片,请换一张')); img.src = url; });
73
- } catch (e) { if (mine === loading) clear(); throw e; }
74
- if (mine !== loading) return false;
75
- crop = { img, zoom: MIN_ZOOM, x: 0, y: 0 };
76
- zoom.value = String(MIN_ZOOM);
77
- draw();
78
- return true;
79
- }
80
- function reset() {
81
- if (!crop) return;
82
- Object.assign(crop, { zoom: MIN_ZOOM, x: 0, y: 0 });
83
- zoom.value = String(MIN_ZOOM);
84
- draw();
85
- }
86
- function clear() {
87
- loading++;
88
- if (url) URL.revokeObjectURL(url);
89
- url = null; crop = null; drag = null;
90
- box.className = 'crop-box';
91
- zoom.value = String(MIN_ZOOM); zoomText.textContent = '1.0×';
92
- draw();
93
- }
94
- // 方框里看到的部分画到 512×512 上(先铺白底,JPEG 没有透明);画面在调用时就定下,之后再换图不影响这次导出。
95
- function exportBlob() {
96
- const out = document.createElement('canvas');
97
- out.width = OUTPUT_SIZE; out.height = OUTPUT_SIZE;
98
- const ctx = out.getContext('2d'), at = layout(OUTPUT_SIZE);
99
- ctx.fillStyle = '#fff';
100
- ctx.fillRect(0, 0, OUTPUT_SIZE, OUTPUT_SIZE);
101
- ctx.drawImage(crop.img, at.x, at.y, at.width, at.height);
102
- return encodeAvatar(out);
103
- }
104
-
105
- return { box, canvas, zoom, zoomText, load, reset, clear, export: exportBlob, get ready() { return Boolean(crop); } };
106
- }