cortico-world-bottle 0.7.0 → 0.7.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/CHANGELOG.md CHANGED
@@ -1,5 +1,10 @@
1
1
  # CHANGELOG
2
2
 
3
+ ## 0.7.1
4
+
5
+ - 修复旧信绑定已撤下字体时无法显示笔迹的问题,优先从当前浏览器已缓存的字体中补选,保留有效绑定。
6
+ - 字体下载等待时间从 20 秒延长至 3 分钟,给慢速网络多留一些时间。
7
+
3
8
  ## 0.7.0 · 把每封信,好好展开
4
9
 
5
10
  **大更新 · 2026-11-03**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cortico-world-bottle",
3
- "version": "0.7.0",
3
+ "version": "0.7.1",
4
4
  "type": "module",
5
5
  "description": "Coo 写一封不超过 120 字的信,寄不寄由人类在本地信箱页上决定;别人家的 Coo 捞到后看不到字,只有人类点了回信,那一封才会被读。",
6
6
  "keywords": [
@@ -4,13 +4,13 @@
4
4
 
5
5
  ## 字体绑定
6
6
 
7
- 每位发信人(种子信按署名)固定一种笔迹,字典位于部署数据 `bottle-font-map.json`。云端清单里启用的字体参与新绑定,停用字体仍可用于已有绑定。增加字体不重洗已有信件,字体资源 ID 继续由原始文件名派生。旧映射若指向已撤下字体则使用系统字体,字典值保留,不偷偷换笔迹。
7
+ 每位发信人(种子信按署名)固定一种笔迹,字典位于部署数据 `bottle-font-map.json`。云端清单里启用的字体参与新绑定,停用字体仍可用于已有绑定。增加字体不重洗已有信件,字体资源 ID 继续由原始文件名派生。旧映射若指向已从清单撤下的字体,下次打开信箱会自动补选并保存:优先使用当前浏览器已缓存、且清单仍启用的字体,没有可用缓存时从当前启用字库选择。只修复失效绑定,正常绑定与仍在清单中的停用字体不变;其他设备沿用修复后的字典。
8
8
 
9
9
  ## 浏览器缓存与多端
10
10
 
11
- 每个浏览器按字体摘要 URL 将字节缓存在 IndexedDB 的 `bottle-letter-fonts` 数据库,可兼容 HTTP 局域网信箱。下次阅读先查缓存,缓存被清理后重新下载。读取失败、浏览器禁用存储或空间不足时仍可直接联网加载;字体加载失败时正文用系统字体显示。支持 Web Crypto 的环境会验证摘要,所有环境校验字体头与长度,浏览器本身再解析字体。
11
+ 每个浏览器按字体摘要 URL 将字节缓存在 IndexedDB 的 `bottle-letter-fonts` 数据库,可兼容 HTTP 局域网信箱。下次阅读先查缓存,缓存被清理后重新下载。读取失败、浏览器禁用存储或空间不足时仍可直接联网加载;单次字体下载最多等待 3 分钟,期间正文先用系统字体显示;失败后保留正文,并沿用原有的稍后重试机制。支持 Web Crypto 的环境会验证摘要,所有环境校验字体头与长度,浏览器本身再解析字体。
12
12
 
13
- 清单与字体地址仅允许指定的 HTTPS 字库域名;不向 R2 发送正文、署名、配对 cookie 或令牌。各设备共享同一宿主的绑定字典,分别保存字体缓存。
13
+ 清单与字体地址仅允许指定的 HTTPS 字库域名;浏览器仅通过本机信箱请求头报告最多 32 个公开字体摘要,用于补选失效绑定;不向 R2 发送正文、署名、配对 cookie 或令牌。各设备共享同一宿主的绑定字典,分别保存字体缓存。
14
14
 
15
15
  ## 自定义我的字体
16
16
 
package/world/fonts.ts CHANGED
@@ -48,7 +48,7 @@ export function fontAsset(id: string, dir = FONT_DIR): { bytes: Buffer; mime: st
48
48
  return { bytes: readFileSync(file.path), mime: file.mime }; } catch { return null; }
49
49
  }
50
50
 
51
- /** No reassignment on import/removal. Shared by loopback and LAN page dependencies. */
51
+ /** Preserve valid assignments; repair removed fonts once. Shared by loopback and LAN. */
52
52
  export class LetterFonts {
53
53
  private readonly file: string;
54
54
  private assignments: Record<string, string> = Object.create(null);
@@ -56,7 +56,7 @@ export class LetterFonts {
56
56
  private readonly remote?:RemoteFontCatalog;
57
57
  constructor(dataDir: string, private readonly directory = FONT_DIR, remote?:RemoteFontCatalog) { this.file = join(dataDir, 'bottle-font-map.json'); this.remote = remote ?? (directory === FONT_DIR ? new RemoteFontCatalog(dataDir) : undefined); }
58
58
  refresh():Promise<void> { return this.remote?.refresh() ?? Promise.resolve(); }
59
- decorate(snapshot: PageSnapshot): PageSnapshot {
59
+ decorate(snapshot: PageSnapshot, cachedFontDigests: readonly string[] = []): PageSnapshot {
60
60
  if (!this.loaded) {
61
61
  try {
62
62
  const stored = JSON.parse(readFileSync(this.file, 'utf8'));
@@ -74,6 +74,10 @@ export class LetterFonts {
74
74
  const catalog=this.remote?.current();
75
75
  const fonts:FontFile[] = catalog ? catalog.fonts.map(font=>({...font,path:'',mime:'font/woff2'})) : fontLibrary(this.directory);
76
76
  const available=fonts.filter(font=>font.enabled!==false);
77
+ // Cache contents belong to each browser. Only recognize digests from our current,
78
+ // enabled catalog; keep the repaired assignment in the shared host dictionary.
79
+ const cached = new Set(cachedFontDigests.slice(0, 32));
80
+ const downloaded = available.filter(font => font.sha256 && cached.has(font.sha256));
77
81
  if (catalog) snapshot={...snapshot,fontResources:Object.fromEntries(catalog.fonts.map(font=>[font.id,{url:font.url,sha256:font.sha256,bytes:font.bytes}])),defaultFont:writingFont(catalog)};
78
82
  if (!fonts.length) return snapshot;
79
83
  const next = { ...this.assignments }; let changed = false;
@@ -81,12 +85,19 @@ export class LetterFonts {
81
85
  const identity = seed ? 'seed:' + (signature || from) : 'visitor:' + from;
82
86
  if (!(signature || from)) return undefined;
83
87
  const key = hash(identity);
84
- if (!next[key]) {
85
- if (!available.length) return undefined;
88
+ const previous = next[key];
89
+ const existing = fonts.find(font => font.name === previous);
90
+ // A disabled font still exists and keeps its old assignments. A removed font
91
+ // cannot be rendered, so replace only that stale binding, never the whole map.
92
+ if (existing) return existing.id;
93
+ if (!available.length) return undefined;
94
+ let candidates = downloaded;
95
+ if (!previous || !downloaded.length) {
86
96
  const counts = available.map(font => Object.values(next).filter(name => name === font.name).length);
87
- const min = Math.min(...counts), candidates = available.filter((_, index) => counts[index] === min);
88
- next[key] = candidates[randomInt(candidates.length)].name; changed = true;
97
+ const min = Math.min(...counts);
98
+ candidates = available.filter((_, index) => counts[index] === min);
89
99
  }
100
+ next[key] = candidates[randomInt(candidates.length)].name; changed = true;
90
101
  return fonts.find(font => font.name === next[key])?.id;
91
102
  };
92
103
  const result: PageSnapshot = {
@@ -31,7 +31,11 @@ export const customizationScript = String.raw`
31
31
  var customColors = JSON.parse(document.getElementById('custom-palettes').textContent || '{}');
32
32
  var customColorRequest = 0, backgroundRequest = 0, requestedBackground;
33
33
  var letterFaces = Object.create(null), fontResources = Object.create(null), backgroundLayer = 0;
34
- var fontDbPromise;
34
+ var fontDbPromise, cachedFontHeadersReady;
35
+ var cachedFontDigests = Object.create(null);
36
+ // Slow direct connections may take minutes for a full CJK font. Reading stays
37
+ // available while this background download completes.
38
+ var remoteFontDownloadTimeoutMs = 180000;
35
39
  function fontDatabase() {
36
40
  if (!fontDbPromise) fontDbPromise = new Promise(function (resolve) {
37
41
  var database;try{database=window.indexedDB;}catch(error){resolve(null);return;}
@@ -51,15 +55,26 @@ export const customizationScript = String.raw`
51
55
  if(!db){resolve(null);return;}
52
56
  var timer=setTimeout(function(){resolve(null);},1500);
53
57
  try {
54
- var tx=db.transaction('fonts',action==='get'?'readonly':'readwrite'),store=tx.objectStore('fonts');
55
- var request=action==='get'?store.get(key):action==='delete'?store.delete(key):store.put(value,key);
56
- request.onsuccess=function(){if(action==='get'){clearTimeout(timer);resolve(request.result);}};
58
+ var tx=db.transaction('fonts',action==='get'||action==='keys'?'readonly':'readwrite'),store=tx.objectStore('fonts');
59
+ var request=action==='get'?store.get(key):action==='keys'?store.getAllKeys():action==='delete'?store.delete(key):store.put(value,key);
60
+ request.onsuccess=function(){if(action==='get'||action==='keys'){clearTimeout(timer);resolve(request.result);}};
57
61
  tx.oncomplete=function(){clearTimeout(timer);resolve(null);};
58
62
  request.onerror=function(){clearTimeout(timer);resolve(null);};
59
63
  tx.onabort=function(){clearTimeout(timer);resolve(null);};
60
64
  } catch(error){clearTimeout(timer);resolve(null);}
61
65
  });});
62
66
  }
67
+ function fontSnapshotHeaders() {
68
+ if (!cachedFontHeadersReady) cachedFontHeadersReady = fontCache('keys').then(function(keys) {
69
+ (Array.isArray(keys) ? keys : []).forEach(function(url) {
70
+ var match = typeof url === 'string' && /^https:\/\/fontsforletters\.sqnori\.com\/fonts\/([a-f0-9]{64})\.woff2$/.exec(url);
71
+ if (match) cachedFontDigests[match[1]] = true;
72
+ });
73
+ });
74
+ return cachedFontHeadersReady.then(function() {
75
+ return { 'x-bottle-cached-fonts': Object.keys(cachedFontDigests).slice(0, 32).join(',') };
76
+ });
77
+ }
63
78
  function validFontResource(resource) {
64
79
  return resource && /^[a-f0-9]{64}$/.test(resource.sha256||'') && Number.isSafeInteger(resource.bytes) && resource.bytes>=48 && resource.bytes<=33554432 && resource.url==='https://fontsforletters.sqnori.com/fonts/'+resource.sha256+'.woff2';
65
80
  }
@@ -72,11 +87,11 @@ export const customizationScript = String.raw`
72
87
  async function remoteFontFace(family,resource) {
73
88
  var bytes=await fontCache('get',resource.url);
74
89
  if(bytes)try{await checkFontBytes(bytes,resource);var cached=new FontFace(family,bytes,{display:'swap'});await cached.load();return cached;}catch(error){await fontCache('delete',resource.url);}
75
- var response=await fetch(resource.url,{mode:'cors',credentials:'omit',cache:'force-cache',redirect:'error',signal:AbortSignal.timeout(20000)});
90
+ var response=await fetch(resource.url,{mode:'cors',credentials:'omit',cache:'force-cache',redirect:'error',signal:AbortSignal.timeout(remoteFontDownloadTimeoutMs)});
76
91
  if(!response.ok)throw Error('Font unavailable');
77
92
  bytes=await response.arrayBuffer();await checkFontBytes(bytes,resource);
78
93
  var face=new FontFace(family,bytes,{display:'swap'});await face.load();
79
- await fontCache('put',resource.url,bytes);return face;
94
+ await fontCache('put',resource.url,bytes);cachedFontDigests[resource.sha256]=true;return face;
80
95
  }
81
96
  function fontNode(node, fontId, own) {
82
97
  if (own) { node.dataset.myLetter = 'true'; fontId = myFontId || defaultMyFont.id; }
@@ -916,7 +916,7 @@ var wakePolicies = ${JSON.stringify(WAKE_POLICIES)};
916
916
  refreshHostTheme(false);
917
917
  refreshAnnouncement();
918
918
  var sequence = ++refreshSequence;
919
- fetch('/draft').then(function (res) { return res.json(); }).then(function (snapshot) {
919
+ fontSnapshotHeaders().then(function (headers) { return fetch('/draft', { headers: headers }); }).then(function (res) { return res.json(); }).then(function (snapshot) {
920
920
  if (sequence !== refreshSequence) return;
921
921
  if (window.bottleSound) window.bottleSound.snapshot(snapshot);
922
922
  state = snapshot;
package/world/page.ts CHANGED
@@ -141,7 +141,7 @@ export interface PageDeps {
141
141
  uploadBackground?(input: unknown): string;
142
142
  theme?(): Promise<MailboxTheme>;
143
143
  appearance?(preference?: ThemePreference): Promise<CardAppearance>;
144
- snapshot(): PageSnapshot;
144
+ snapshot(cachedFontDigests?: readonly string[]): PageSnapshot;
145
145
  announcement?(): Promise<AnnouncementSummary | null>;
146
146
  refresh?(): Promise<void>;
147
147
  wakeControl?(action: WakeAction, command: 'pause' | 'resume' | 'interval', hours?: number, dayLimit?: number): Promise<PageResult>;
@@ -170,6 +170,8 @@ export interface PageResponse {
170
170
 
171
171
  export interface PageRequestOptions {
172
172
  surface?: Surface;
173
+ /** Browser cache hints contain only public font digests, never letter identities. */
174
+ cachedFontDigests?: readonly string[];
173
175
  /** POST 的 JSON 体;只有 /forget 用得上。 */
174
176
  body?: unknown;
175
177
  }
@@ -244,7 +246,7 @@ export async function handlePage(
244
246
  try { return { status: 200, json: { announcement: await deps.announcement?.() ?? null } }; }
245
247
  catch { return { status: 503, json: { announcement: null } }; }
246
248
  }
247
- if (method === 'GET' && route === '/draft') { await deps.refresh?.(); return { status: 200, json: deps.snapshot() }; }
249
+ if (method === 'GET' && route === '/draft') { await deps.refresh?.(); return { status: 200, json: deps.snapshot(opts.cachedFontDigests) }; }
248
250
 
249
251
  if (method === 'POST' && route === '/forget') {
250
252
  const letterId = letterIdOf(opts.body);
@@ -367,7 +369,11 @@ export function pageHandler(deps: PageDeps, log?: (line: string) => void, remote
367
369
  res.end(JSON.stringify({ ok: false, message: '请求体读不出来,这个动作没有执行。' }));
368
370
  return null;
369
371
  }
370
- return handlePage(deps, method, path, { surface, body: read.value });
372
+ const cacheHeader = req.headers['x-bottle-cached-fonts'];
373
+ const cachedFontDigests = typeof cacheHeader === 'string' && cacheHeader.length <= 2079
374
+ ? [...new Set(cacheHeader.split(',').filter(value => /^[a-f0-9]{64}$/.test(value)))].slice(0, 32)
375
+ : [];
376
+ return handlePage(deps, method, path, { surface, body: read.value, cachedFontDigests });
371
377
  })
372
378
  .then((result) => {
373
379
  if (result === null) return; // 上面已经回过 400
package/world/world.ts CHANGED
@@ -1192,7 +1192,7 @@ export class BottleWorld implements World {
1192
1192
  if (preference) saveThemePreference(this.ctx.dataDir, preference);
1193
1193
  return cardAppearance(readThemePreference(this.ctx.dataDir) ?? DEFAULT_APPEARANCE, await readMailboxTheme(this.ctx.botDir));
1194
1194
  },
1195
- snapshot: () => this.letterFonts!.decorate(this.snapshot()),
1195
+ snapshot: cachedFontDigests => this.letterFonts!.decorate(this.snapshot(), cachedFontDigests),
1196
1196
  refresh: () => { void this.letterFonts!.refresh(); return this.refreshVisibleQuota(); },
1197
1197
  wakeControl: (action, command, hours, dayLimit) => this.wakeControl(action, command, hours, dayLimit),
1198
1198
  announcement: () => this.pageAnnouncement(),