sideora 0.0.1-alpha.0 → 0.1.0-alpha.2

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.
Files changed (221) hide show
  1. package/LICENSE.md +9 -0
  2. package/README.md +57 -6
  3. package/assets/sounds/freesound_community-mail-40275.mp3 +0 -0
  4. package/assets/sounds/mixkit-clear-announce-tones-2861.wav +0 -0
  5. package/assets/sounds/mixkit-happy-bells-notification-937.wav +0 -0
  6. package/assets/sounds/mixkit-musical-alert-notification-2309.wav +0 -0
  7. package/assets/sounds/nice-chime.mp3 +0 -0
  8. package/bin/sideora.js +2430 -12
  9. package/extension/dist/assets/background.ts-NW8YqAlO.js +1 -0
  10. package/extension/dist/assets/fillCode-Ci8IkBvY.js +1 -0
  11. package/extension/dist/assets/index.html-DrrPha1M.js +2 -0
  12. package/extension/dist/assets/modulepreload-polyfill-DcjICKwh.js +1 -0
  13. package/extension/dist/assets/shell-82MNMljp.css +1 -0
  14. package/extension/dist/assets/shell-QYBN1bx1.js +1 -0
  15. package/extension/dist/icons/icon-128.png +0 -0
  16. package/extension/dist/icons/icon-16.png +0 -0
  17. package/extension/dist/icons/icon-32.png +0 -0
  18. package/extension/dist/icons/icon-48.png +0 -0
  19. package/extension/dist/manifest.json +40 -0
  20. package/extension/dist/service-worker-loader.js +1 -0
  21. package/extension/dist/src/newtab/index.html +14 -0
  22. package/extension/dist/src/panel/index.html +15 -0
  23. package/extension/dist-web/assets/abnfDiagram-WEYOIA3C-CoXOc872.js +1 -0
  24. package/extension/dist-web/assets/apple-touch-icon-DSgRQASq.png +0 -0
  25. package/extension/dist-web/assets/architecture-WOLXFQ4H-BkJ4AerO.js +1 -0
  26. package/extension/dist-web/assets/architectureDiagram-ZHVYKT53-aPkSDlxA.js +36 -0
  27. package/extension/dist-web/assets/blockDiagram-RJAE7QA3-CH1G4NBZ.js +140 -0
  28. package/extension/dist-web/assets/c4Diagram-XDPPPE54-Baum1zDu.js +38 -0
  29. package/extension/dist-web/assets/channel-PsQg-mnK.js +1 -0
  30. package/extension/dist-web/assets/chunk-2E7WHVMD-CKvLrWRa.js +88 -0
  31. package/extension/dist-web/assets/chunk-2Q5K7J3B-C1jixKkw.js +1 -0
  32. package/extension/dist-web/assets/chunk-4EMNKR2T-6fjnroCZ.js +1 -0
  33. package/extension/dist-web/assets/chunk-55XCU76K-Ygs3sNpi.js +1 -0
  34. package/extension/dist-web/assets/chunk-5VM5RSS4-ZNzvKenW.js +15 -0
  35. package/extension/dist-web/assets/chunk-7S6XSTFO-iX5xYzfP.js +2 -0
  36. package/extension/dist-web/assets/chunk-AQDTSKZB-D9zwhFI8.js +72 -0
  37. package/extension/dist-web/assets/chunk-DSNLSHJZ-siGS-4qu.js +129 -0
  38. package/extension/dist-web/assets/chunk-DUW6YSOI-Dgx8z5s3.js +1 -0
  39. package/extension/dist-web/assets/chunk-HAGFOTED-_3dtnWXn.js +62 -0
  40. package/extension/dist-web/assets/chunk-HNE4Q36P-BPzRHi72.js +1 -0
  41. package/extension/dist-web/assets/chunk-J5ZVWO5B-oDCd-gWO.js +1 -0
  42. package/extension/dist-web/assets/chunk-JWPE2WC7-DVXcaiue.js +1 -0
  43. package/extension/dist-web/assets/chunk-NGNAAXSQ-DI_UYJZ4.js +136 -0
  44. package/extension/dist-web/assets/chunk-NQOKRVIF-AXbmOBjs.js +213 -0
  45. package/extension/dist-web/assets/chunk-UHW7PFBP-B3xrZ8sD.js +1 -0
  46. package/extension/dist-web/assets/chunk-VQ5W62QI-D_k7Pa6b.js +1 -0
  47. package/extension/dist-web/assets/chunk-WQQL4CDK-BBIrWwoZ.js +10 -0
  48. package/extension/dist-web/assets/chunk-XXDRQBXY-i7MKP1NY.js +1 -0
  49. package/extension/dist-web/assets/chunk-Y2CYZVJY-DsF7k-Jl.js +1 -0
  50. package/extension/dist-web/assets/chunk-YZO67HFG-Z7qp5QAI.js +1 -0
  51. package/extension/dist-web/assets/chunk-ZAUX2LTX-CSt3c0Rb.js +1 -0
  52. package/extension/dist-web/assets/chunk-ZCHMQSOR-g8XRABGK.js +2 -0
  53. package/extension/dist-web/assets/classDiagram-v2-4MYWR3UA-BL706wzc.js +217 -0
  54. package/extension/dist-web/assets/cose-bilkent-JH36ORCC-C6J2IoHg.js +1 -0
  55. package/extension/dist-web/assets/cynefin-EF2NZ3EQ-DLhQOiAy.js +1 -0
  56. package/extension/dist-web/assets/cynefinDiagram-WF24UDRP-Cv9Lx6_l.js +62 -0
  57. package/extension/dist-web/assets/cytoscape.esm-nTrd5EVq.js +321 -0
  58. package/extension/dist-web/assets/d3-scale-CElPUUud.js +1 -0
  59. package/extension/dist-web/assets/d3-selection-COWvaQNI.js +1 -0
  60. package/extension/dist-web/assets/dagre-NK4GIZVX-ngM-w2EC.js +4 -0
  61. package/extension/dist-web/assets/diagram-CBK3MWTC-kp8sayNG.js +24 -0
  62. package/extension/dist-web/assets/diagram-I5XIIV2D-BZ_Dgs6K.js +24 -0
  63. package/extension/dist-web/assets/diagram-ODIL2UCW-DWhUyArG.js +30 -0
  64. package/extension/dist-web/assets/diagram-PFBEJUXE-CBAdEK7l.js +3 -0
  65. package/extension/dist-web/assets/diagram-RJA3I4VV-kOdIr_3K.js +41 -0
  66. package/extension/dist-web/assets/diagram-TYUNFSNR-BrWGa0x5.js +200 -0
  67. package/extension/dist-web/assets/dist-DdXDFcej.js +1 -0
  68. package/extension/dist-web/assets/docx-preview-D1zbEiLy.js +20 -0
  69. package/extension/dist-web/assets/earth-Ce3xs8Cb.webp +0 -0
  70. package/extension/dist-web/assets/ebnfDiagram-V4P3TTPT-0r3weWmj.js +1 -0
  71. package/extension/dist-web/assets/elk-QONTBCTQ-D3oElRZ3.js +27 -0
  72. package/extension/dist-web/assets/erDiagram-KYQIGQAA-B9oU7_j_.js +99 -0
  73. package/extension/dist-web/assets/eventmodeling-K75KTNOO-CMKgc1nP.js +1 -0
  74. package/extension/dist-web/assets/favicon-D_X6tUVf.svg +5 -0
  75. package/extension/dist-web/assets/flowDiagram-IUGLLWBU-yRwks0Mw.js +1 -0
  76. package/extension/dist-web/assets/ganttDiagram-R7GPNTJY-cJqD1qwQ.js +292 -0
  77. package/extension/dist-web/assets/gitGraph-VSP46ZUC-CuBQqkbr.js +1 -0
  78. package/extension/dist-web/assets/gitGraphDiagram-PDYL7XHY-D7bHnQXC.js +106 -0
  79. package/extension/dist-web/assets/graphlib-DS17s2tU.js +1 -0
  80. package/extension/dist-web/assets/home-CV7-8Trs.js +1 -0
  81. package/extension/dist-web/assets/index-CQvw7Wy_.js +7 -0
  82. package/extension/dist-web/assets/index-CVKnZ21i.css +1 -0
  83. package/extension/dist-web/assets/info-OHQRW6UA-B8kyzV4O.js +1 -0
  84. package/extension/dist-web/assets/infoDiagram-MVDRKAX5-CEm6lezX.js +2 -0
  85. package/extension/dist-web/assets/ishikawaDiagram-HPEHV2GE-Ce3uv2wr.js +70 -0
  86. package/extension/dist-web/assets/journeyDiagram-BOSHW7O7-QgdahHCP.js +139 -0
  87. package/extension/dist-web/assets/jszip.min-3XXygzvy.js +2 -0
  88. package/extension/dist-web/assets/kanban-definition-FNSA4HC5-DPuTtWgR.js +89 -0
  89. package/extension/dist-web/assets/katex-MEuSR36T.js +257 -0
  90. package/extension/dist-web/assets/mermaid-parser.core-h7U7YGn_.js +7 -0
  91. package/extension/dist-web/assets/mermaid.core-DkGhophj.js +44 -0
  92. package/extension/dist-web/assets/mindmap-definition-6OY57UG3-D7VQxbda.js +98 -0
  93. package/extension/dist-web/assets/mount-CBzzf6KQ.js +195 -0
  94. package/extension/dist-web/assets/mount-DtvYnQXt.css +1 -0
  95. package/extension/dist-web/assets/officeparser.browser.slim-kEjhTrQ1.js +1989 -0
  96. package/extension/dist-web/assets/packet-JDAUHWVQ-oafHgw6X.js +1 -0
  97. package/extension/dist-web/assets/pegDiagram-ECIUJNBX-C3zo1naj.js +1 -0
  98. package/extension/dist-web/assets/peoria-B5TBlKDG.jpg +0 -0
  99. package/extension/dist-web/assets/peoria-thumb-CN8upAdZ.jpg +0 -0
  100. package/extension/dist-web/assets/pie-XZMESJXO-DXzeBQqF.js +1 -0
  101. package/extension/dist-web/assets/pieDiagram-GNMPY74T-S5NzPthl.js +39 -0
  102. package/extension/dist-web/assets/quadrantDiagram-D57K4MC3-C9glHQmk.js +7 -0
  103. package/extension/dist-web/assets/radar-ABXABTNO-CWTNqtbu.js +1 -0
  104. package/extension/dist-web/assets/railroad-I3PHUGI6-BTpD5_Bu.js +1 -0
  105. package/extension/dist-web/assets/railroad-abnf-LNEFI6M7-bWyxoXQG.js +1 -0
  106. package/extension/dist-web/assets/railroad-ebnf-DWYD2UWJ-ri5733DQ.js +1 -0
  107. package/extension/dist-web/assets/railroad-peg-JR7BVNR7-CmGfTubP.js +1 -0
  108. package/extension/dist-web/assets/railroadDiagram-Y72NRBL7-DTfe6Dh1.js +1 -0
  109. package/extension/dist-web/assets/requirementDiagram-EQYSW5RA-DQDzcS3L.js +84 -0
  110. package/extension/dist-web/assets/rolldown-runtime-COiEfhsA.js +1 -0
  111. package/extension/dist-web/assets/rough.esm-Dy-Kn_BL.js +1 -0
  112. package/extension/dist-web/assets/sankeyDiagram-SY24JHO5-DyMKWxdB.js +40 -0
  113. package/extension/dist-web/assets/sequenceDiagram-BLEHNHQU-dIkB1mCn.js +169 -0
  114. package/extension/dist-web/assets/sizeCapture-INFHLROL-3uHXrFqA.js +1 -0
  115. package/extension/dist-web/assets/stateDiagram-v2-A6IESKWZ-Bj_vxEVF.js +291 -0
  116. package/extension/dist-web/assets/swimlanes-B3ENRKFQ-BSkWEwHR.js +1 -0
  117. package/extension/dist-web/assets/swimlanesDiagram-AYQRV4AK-BTzSDlSM.js +8 -0
  118. package/extension/dist-web/assets/timeline-definition-JXYKGLGB-TwfWS0pw.js +120 -0
  119. package/extension/dist-web/assets/treeView-D4JQ5SDB-BzA_8YYb.js +1 -0
  120. package/extension/dist-web/assets/treemap-SAJKECNS-BI9d6--2.js +1 -0
  121. package/extension/dist-web/assets/usecaseDiagram-WPOLBNNX-BOVbAUPk.js +328 -0
  122. package/extension/dist-web/assets/vennDiagram-Q3Y3IDCW-X2kYAWaj.js +34 -0
  123. package/extension/dist-web/assets/wardley-7MLQ67FV-CItxqJ8G.js +1 -0
  124. package/extension/dist-web/assets/wardleyDiagram-IVAIDKWA-BnUXvKD_.js +78 -0
  125. package/extension/dist-web/assets/xychartDiagram-4URNHDU4-ysvBXvyE.js +7 -0
  126. package/extension/dist-web/icon-192.png +0 -0
  127. package/extension/dist-web/icon-512.png +0 -0
  128. package/extension/dist-web/index.html +25 -0
  129. package/extension/dist-web/manifest.webmanifest +14 -0
  130. package/package.json +64 -12
  131. package/plugin/.claude-plugin/icon.png +0 -0
  132. package/plugin/.claude-plugin/plugin.json +6 -0
  133. package/plugin/.mcp.json +8 -0
  134. package/plugin/README.md +72 -0
  135. package/plugin/mcp-launcher.mjs +48 -0
  136. package/src/account-probe.js +45 -0
  137. package/src/accounts.js +687 -0
  138. package/src/ai.js +269 -0
  139. package/src/assistant-runs.js +32 -0
  140. package/src/attached-mail.js +76 -0
  141. package/src/auth-gate.js +70 -0
  142. package/src/backup-cli.js +158 -0
  143. package/src/backup.js +329 -0
  144. package/src/bimi.js +233 -0
  145. package/src/bridge.js +101 -0
  146. package/src/calendar-alerts.js +56 -0
  147. package/src/chats.js +27 -0
  148. package/src/compose-editor.js +58 -0
  149. package/src/config.js +420 -0
  150. package/src/connections.d.ts +24 -0
  151. package/src/connections.js +37 -0
  152. package/src/core/agent.js +92 -0
  153. package/src/core/assistant.d.ts +13 -0
  154. package/src/core/assistant.js +790 -0
  155. package/src/core/chats.js +323 -0
  156. package/src/core/markdown.d.ts +8 -0
  157. package/src/core/markdown.js +239 -0
  158. package/src/core/notes.js +445 -0
  159. package/src/core/otp.js +152 -0
  160. package/src/core/rules.js +196 -0
  161. package/src/core/runs.d.ts +9 -0
  162. package/src/core/runs.js +211 -0
  163. package/src/core/thread.js +526 -0
  164. package/src/core/write.js +247 -0
  165. package/src/core-db.js +131 -0
  166. package/src/core.js +174 -0
  167. package/src/credentials.js +320 -0
  168. package/src/daemon.js +564 -0
  169. package/src/events.js +213 -0
  170. package/src/extension-id.d.ts +2 -0
  171. package/src/extension-id.js +5 -0
  172. package/src/file-lock.js +27 -0
  173. package/src/files-index.js +154 -0
  174. package/src/google-contacts.js +315 -0
  175. package/src/google-signin.js +306 -0
  176. package/src/host/assistant-html.js +44 -0
  177. package/src/host/chats-files.js +137 -0
  178. package/src/host/file-prep.js +122 -0
  179. package/src/host/notes-files.js +158 -0
  180. package/src/host/office-text.js +224 -0
  181. package/src/host/office-worker.js +8 -0
  182. package/src/host/rules-file.js +20 -0
  183. package/src/host/secrets-file.js +91 -0
  184. package/src/host/systemd.js +90 -0
  185. package/src/hub.js +245 -0
  186. package/src/identity.js +316 -0
  187. package/src/labels.js +5 -0
  188. package/src/mail-port.d.ts +79 -0
  189. package/src/mail-port.js +148 -0
  190. package/src/mcp-server.js +747 -0
  191. package/src/microsoft-app.js +20 -0
  192. package/src/microsoft-signin.js +194 -0
  193. package/src/migrate.js +327 -0
  194. package/src/notes-html.js +450 -0
  195. package/src/notes.js +19 -0
  196. package/src/notify.js +105 -0
  197. package/src/onepassword.js +223 -0
  198. package/src/op-registry.d.ts +14 -0
  199. package/src/op-registry.js +150 -0
  200. package/src/ops.js +1251 -0
  201. package/src/otp.js +6 -0
  202. package/src/panel-ops.js +273 -0
  203. package/src/pictures.js +735 -0
  204. package/src/postinstall.js +25 -0
  205. package/src/relay-passkey.js +122 -0
  206. package/src/relay-request.js +155 -0
  207. package/src/relay-seal.js +56 -0
  208. package/src/relay-settings.js +139 -0
  209. package/src/relay.js +876 -0
  210. package/src/render.js +82 -0
  211. package/src/rules-store.js +8 -0
  212. package/src/safe-fetch.js +215 -0
  213. package/src/sender-auth.js +270 -0
  214. package/src/site-match.js +77 -0
  215. package/src/tui-agenda.js +266 -0
  216. package/src/tui.js +670 -0
  217. package/src/vmc.js +376 -0
  218. package/src/wake.js +96 -0
  219. package/src/web-access.js +185 -0
  220. package/src/web-server.js +241 -0
  221. package/src/web-service.js +152 -0
@@ -0,0 +1,137 @@
1
+ // The chats' store on this Mac (src/core/chats.js asks it): one file a chat in a folder, ~/.sideora/chats.
2
+ //
3
+ // <dir>/k3f9a2c1b7.json a chat, as the core hands it over
4
+ // <dir>/trash/<id>.<when>.json a chat removed, named by when (the oldest go first, past what is kept)
5
+ // <dir>/files/3f9a… a file attached to a question, named by what it holds
6
+ //
7
+ // Any process may write (the hub, and the web app's server until it asks it): a change is made under a lock across
8
+ // processes (<dir>/.lock, naming the process that holds it), and each file is written whole or not at all.
9
+
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import crypto from 'node:crypto';
13
+
14
+ const FILE = /^([a-z0-9]{6,24})\.json$/;
15
+ const FILE_ID = /^[0-9a-f]{32}$/;
16
+ const LOCK_STALE_MS = 30_000;
17
+ const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
18
+ const names = (dir) => { try { return fs.readdirSync(dir).filter((n) => n.endsWith('.json')); } catch (e) { if (e.code === 'ENOENT') return []; throw e; } };
19
+
20
+ /**
21
+ * A lock left by a process that is gone is taken away, by one process at a time: two that both saw it stale must
22
+ * not each remove "it" (the second would remove the lock a third has taken meanwhile). Whoever holds
23
+ * <lock>.takeover looks again and removes it; a takeover file left behind is itself let go after a while.
24
+ */
25
+ function clearStale(lock) {
26
+ const takeover = `${lock}.takeover`;
27
+ try { fs.writeFileSync(takeover, String(process.pid), { flag: 'wx', mode: 0o600 }); } catch (e) {
28
+ if (e.code !== 'EEXIST') throw e;
29
+ try { if (Date.now() - fs.statSync(takeover).mtimeMs > 5000) fs.unlinkSync(takeover); } catch { /* gone already */ }
30
+ return;
31
+ }
32
+ try {
33
+ const said = fs.readFileSync(lock, 'utf8');
34
+ const pid = parseInt(said, 10);
35
+ // (just made and not written in yet: its owner is about to say who it is)
36
+ // (a lock is held for a moment: one older than LOCK_STALE_MS is stale, whoever's number is in it: a number may be another process's by now)
37
+ const age = Date.now() - fs.statSync(lock).mtimeMs;
38
+ const stale = age > LOCK_STALE_MS || (Number.isFinite(pid) ? !alive(pid) : age > 2000);
39
+ if (stale && fs.readFileSync(lock, 'utf8') === said) fs.unlinkSync(lock);
40
+ } catch { /* gone already */ } finally { try { fs.unlinkSync(takeover); } catch { /* gone already */ } }
41
+ }
42
+
43
+ /** The store over `dir`. */
44
+ export function chatsFiles(dir) {
45
+ const trash = path.join(dir, 'trash');
46
+ const files = path.join(dir, 'files');
47
+ const fileOf = (id) => path.join(dir, `${id}.json`);
48
+ const at = (id) => path.join(files, id);
49
+
50
+ return {
51
+ /** One writer at a time, across processes: fn() runs while this process holds <dir>/.lock (one left by a process that is gone is taken over). */
52
+ locked(fn) {
53
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
54
+ const lock = path.join(dir, '.lock');
55
+ const mine = `${process.pid} ${crypto.randomBytes(6).toString('hex')}`;
56
+ const until = Date.now() + 5000;
57
+ for (;;) {
58
+ try { fs.writeFileSync(lock, mine, { flag: 'wx', mode: 0o600 }); break; } catch (e) {
59
+ if (e.code !== 'EEXIST') throw e;
60
+ clearStale(lock);
61
+ if (Date.now() > until) throw new Error('the chats are being changed by another process: try again in a moment');
62
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20); // a short wait, without a busy loop
63
+ }
64
+ }
65
+ try { return fn(); } finally { try { if (fs.readFileSync(lock, 'utf8') === mine) fs.unlinkSync(lock); } catch { /* gone already */ } }
66
+ },
67
+
68
+ /** How many chats are kept (the trash not counted). */
69
+ count: () => names(dir).length,
70
+
71
+ /** The chats kept: { id, at } (when each was last written). */
72
+ list() {
73
+ const out = [];
74
+ for (const name of names(dir)) {
75
+ const id = FILE.exec(name)?.[1];
76
+ if (!id) continue;
77
+ try { out.push({ id, at: fs.statSync(fileOf(id)).mtimeMs }); } catch { /* gone as it was looked at */ }
78
+ }
79
+ return out;
80
+ },
81
+
82
+ /** A chat's text as written; null when there is none. */
83
+ read(id) {
84
+ try { return fs.readFileSync(fileOf(id), 'utf8'); } catch (e) { if (e.code === 'ENOENT') return null; throw e; }
85
+ },
86
+
87
+ /** Write a chat's text whole, under `id`. */
88
+ write(id, text) {
89
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
90
+ const tmp = path.join(dir, `.${id}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`);
91
+ fs.writeFileSync(tmp, text, { mode: 0o600 });
92
+ fs.renameSync(tmp, fileOf(id));
93
+ },
94
+
95
+ /** Move a chat to the trash; the last `keep` removed are kept there, the ones before go for good. */
96
+ trash(id, keep) {
97
+ fs.mkdirSync(trash, { recursive: true, mode: 0o700 });
98
+ fs.renameSync(fileOf(id), path.join(trash, `${id}.${Date.now()}.json`));
99
+ // (named <id>.<when removed>.json: the oldest removed first)
100
+ const old = names(trash).map((n) => ({ n, at: Number(n.split('.')[1]) || 0 })).sort((x, y) => y.at - x.at).slice(keep);
101
+ for (const { n } of old) { try { fs.unlinkSync(path.join(trash, n)); } catch { /* gone already */ } }
102
+ },
103
+
104
+ /** `visit(text)` for every chat, the trash's included, one at a time; false when one of them could not be read (the rest then not visited). */
105
+ eachText(visit) {
106
+ for (const where of [dir, trash]) for (const n of names(where)) {
107
+ let text;
108
+ try { text = fs.readFileSync(path.join(where, n), 'utf8'); } catch { return false; }
109
+ visit(text);
110
+ }
111
+ return true;
112
+ },
113
+
114
+ files: {
115
+ /** The files kept: { id, size, at }. */
116
+ list() {
117
+ try {
118
+ return fs.readdirSync(files).filter((n) => FILE_ID.test(n)).map((n) => { try { const st = fs.statSync(at(n)); return { id: n, size: st.size, at: st.mtimeMs }; } catch { return null; } }).filter(Boolean);
119
+ } catch (e) { if (e.code === 'ENOENT') return []; throw e; }
120
+ },
121
+ /** Its bytes; null when it is not kept. */
122
+ read(id) { try { return fs.readFileSync(at(id)); } catch (e) { if (e.code === 'ENOENT') return null; throw e; } },
123
+ /** Its size; -1 when it is not kept. */
124
+ size(id) { try { return fs.statSync(at(id)).size; } catch { return -1; } },
125
+ /** Keep `bytes` under `id`, whole or not at all. */
126
+ put(id, bytes) {
127
+ fs.mkdirSync(files, { recursive: true, mode: 0o700 });
128
+ const tmp = `${at(id)}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
129
+ fs.writeFileSync(tmp, bytes, { mode: 0o600 });
130
+ fs.renameSync(tmp, at(id));
131
+ },
132
+ /** Its time starts again (attached again). */
133
+ touch(id) { try { const now = new Date(); fs.utimesSync(at(id), now, now); } catch { /* as it is */ } },
134
+ remove(id) { try { fs.unlinkSync(at(id)); } catch { /* gone already */ } }
135
+ }
136
+ };
137
+ }
@@ -0,0 +1,122 @@
1
+ // A file made ready for a model, on the Mac, for the assistant (src/core/assistant.js's read_attachment): what the
2
+ // page does in a browser for the files picked with a question (extension/src/panel/lib/chatFiles.ts), done here for
3
+ // those it reads from mail.
4
+ //
5
+ // - a picture (PNG, JPEG, GIF, WebP, known by how it starts): as it is when it is small enough; else drawn no larger
6
+ // than a model reads it (MAX_SIDE), as a JPEG, by macOS's own `sips` (on Linux, ImageMagick's, when it is there)
7
+ // - a PDF: as it is
8
+ // - a Word, Excel or PowerPoint file: its words (./office-text.js). A text file: its text.
9
+ // Anything else is refused, with why.
10
+ //
11
+ // prepareFile(base64, name, contentType) → { kind: 'image' | 'pdf' | 'text', data: base64, mediaType }
12
+
13
+ import { execFile } from 'node:child_process';
14
+ import crypto from 'node:crypto';
15
+ import fs from 'node:fs';
16
+ import os from 'node:os';
17
+ import path from 'node:path';
18
+ import { Worker } from 'node:worker_threads';
19
+ import { officeKind } from './office-text.js';
20
+
21
+ const MAX_SIDE = 1568; // pixels, the longer side of a picture as it is handed over
22
+ const KEEP_BYTES = 3.5 * 1024 * 1024; // a picture this small, and no larger than MAX_SIDE, goes as it is
23
+ const MAX_PIXELS = 60_000_000;
24
+ const MAX_PDF = 6 * 1024 * 1024;
25
+ const MAX_OFFICE = 10 * 1024 * 1024;
26
+ const MAX_TEXT_BYTES = 1024 * 1024;
27
+ const MAX_TEXT = 60_000; // characters of a text handed over
28
+ const NOT_TEXT = /[\u0000-\u0008\u000e-\u001a\u001c-\u001f]/; // control characters a text file has none of
29
+
30
+ const starts = (b, ...x) => x.every((v, i) => b[i] === v);
31
+ const pictureType = (b) => (starts(b, 0x89, 0x50, 0x4e, 0x47) ? 'image/png' : starts(b, 0xff, 0xd8, 0xff) ? 'image/jpeg' : starts(b, 0x47, 0x49, 0x46, 0x38) ? 'image/gif' : starts(b, 0x52, 0x49, 0x46, 0x46) && starts(b.subarray(8), 0x57, 0x45, 0x42, 0x50) ? 'image/webp' : null);
32
+ const isPdf = (b) => starts(b, 0x25, 0x50, 0x44, 0x46, 0x2d);
33
+ const mb = (n) => `${Math.round(n / 1024 / 1024)} MB`;
34
+ const asText = (text) => ({ kind: 'text', data: Buffer.from(text.slice(0, MAX_TEXT), 'utf8').toString('base64'), mediaType: 'text/plain' });
35
+
36
+ const OFFICE_MS = 8000;
37
+ /** The words of an Office file, read on a thread of its own and given up after OFFICE_MS: '' when nothing could be read in time. */
38
+ function officeTextBounded(name, bytes) {
39
+ return new Promise((resolve) => {
40
+ let worker;
41
+ try {
42
+ worker = new Worker(new URL('./office-worker.js', import.meta.url), { workerData: { name, bytes }, resourceLimits: { maxOldGenerationSizeMb: 256 } });
43
+ } catch { resolve(''); return; }
44
+ const timer = setTimeout(() => { worker.terminate(); resolve(''); }, OFFICE_MS);
45
+ worker.once('message', (text) => { clearTimeout(timer); worker.terminate(); resolve(typeof text === 'string' ? text : ''); });
46
+ worker.once('error', () => { clearTimeout(timer); resolve(''); });
47
+ worker.once('exit', () => { clearTimeout(timer); resolve(''); });
48
+ });
49
+ }
50
+
51
+ const run = (cmd, args) => new Promise((resolve, reject) => execFile(cmd, args, { timeout: 30_000, maxBuffer: 1024 * 1024 }, (e, out) => (e ? reject(e) : resolve(String(out)))));
52
+
53
+ /** A picture no larger than a model reads: `sips` on the Mac, ImageMagick elsewhere; in a folder of its own that is removed after. */
54
+ async function smaller(bytes, name, type) {
55
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sideora-pic-'));
56
+ try {
57
+ const src = path.join(dir, `in-${crypto.randomBytes(4).toString('hex')}`);
58
+ const out = path.join(dir, 'out.jpg');
59
+ fs.writeFileSync(src, bytes, { mode: 0o600 });
60
+ if (process.platform !== 'darwin') {
61
+ // ImageMagick (`magick`, else `convert`/`identify`): read only as the kind of picture it starts as (never a
62
+ // decoder of its own choosing), its size read first and refused past MAX_PIXELS as on the Mac, and bounded in
63
+ // memory, disk and dimensions while it draws
64
+ const coder = { 'image/png': 'png', 'image/jpeg': 'jpeg', 'image/gif': 'gif', 'image/webp': 'webp' }[type];
65
+ if (!coder) throw new Error(`${name} could not be read as a picture`);
66
+ const seven = await run('magick', ['-version']).then(() => true, () => false);
67
+ const tool = seven ? 'magick' : await run('convert', ['-version']).then(() => 'convert', () => null);
68
+ if (!tool) throw new Error(`${name} is too large to hand to a model as it is, and this machine has no way to make it smaller (install ImageMagick)`);
69
+ const limits = ['-limit', 'memory', '256MiB', '-limit', 'map', '512MiB', '-limit', 'disk', '1GiB', '-limit', 'width', '20KP', '-limit', 'height', '20KP', '-limit', 'area', '128MP', '-limit', 'time', '25'];
70
+ const said = await run(seven ? 'magick' : 'identify', [...(seven ? ['identify'] : []), ...limits, '-ping', '-format', '%w %h\n', `${coder}:${src}[0]`]).catch(() => '');
71
+ const [w, h] = said.trim().split(/\s+/).map(Number);
72
+ if (!w || !h) throw new Error(`${name} could not be read as a picture`);
73
+ if (w * h > MAX_PIXELS) throw new Error(`${name} is too large a picture`);
74
+ await run(tool, [...limits, `${coder}:${src}[0]`, '-background', 'white', '-flatten', '-resize', `${MAX_SIDE}x${MAX_SIDE}>`, '-quality', '86', `jpeg:${out}`]).catch(() => { throw new Error(`${name} could not be made smaller`); });
75
+ return fs.readFileSync(out);
76
+ }
77
+ const said = await run('sips', ['-g', 'pixelWidth', '-g', 'pixelHeight', src]).catch(() => '');
78
+ const w = Number(/pixelWidth: (\d+)/.exec(said)?.[1]);
79
+ const h = Number(/pixelHeight: (\d+)/.exec(said)?.[1]);
80
+ if (!w || !h) throw new Error(`${name} could not be read as a picture`);
81
+ if (w * h > MAX_PIXELS) throw new Error(`${name} is too large a picture`);
82
+ const args = ['-s', 'format', 'jpeg', '-s', 'formatOptions', '86', ...(Math.max(w, h) > MAX_SIDE ? ['-Z', String(MAX_SIDE)] : []), src, '--out', out];
83
+ await run('sips', args).catch(() => { throw new Error(`${name} could not be made smaller`); });
84
+ return fs.readFileSync(out);
85
+ } finally {
86
+ fs.rmSync(dir, { recursive: true, force: true });
87
+ }
88
+ }
89
+
90
+ async function sidesOf(bytes) {
91
+ // (PNG and JPEG say their size in their first bytes; anything else is drawn again, to be sure)
92
+ if (starts(bytes, 0x89, 0x50, 0x4e, 0x47) && bytes.length > 24) return [bytes.readUInt32BE(16), bytes.readUInt32BE(20)];
93
+ return null;
94
+ }
95
+
96
+ export async function prepareFile(base64, name = 'file', contentType = '') {
97
+ const bytes = Buffer.from(String(base64 ?? ''), 'base64');
98
+ const head = bytes.subarray(0, 16);
99
+ const picture = pictureType(head);
100
+ if (picture) {
101
+ const sides = await sidesOf(bytes);
102
+ const fits = sides ? Math.max(...sides) <= MAX_SIDE && sides[0] * sides[1] <= MAX_PIXELS : false;
103
+ if (fits && bytes.length <= KEEP_BYTES) return { kind: 'image', data: bytes.toString('base64'), mediaType: picture };
104
+ return { kind: 'image', data: (await smaller(bytes, name, picture)).toString('base64'), mediaType: 'image/jpeg' };
105
+ }
106
+ if (isPdf(head)) {
107
+ if (bytes.length > MAX_PDF) throw new Error(`${name} is more than ${mb(MAX_PDF)}: too much to hand to a model`);
108
+ return { kind: 'pdf', data: bytes.toString('base64'), mediaType: 'application/pdf' };
109
+ }
110
+ if (officeKind(name)) {
111
+ if (bytes.length > MAX_OFFICE) throw new Error(`${name} is more than ${mb(MAX_OFFICE)}`);
112
+ const text = await officeTextBounded(name, bytes);
113
+ if (!text.trim()) throw new Error(`nothing could be read in ${name} (or it took too long to read)`);
114
+ return asText(text);
115
+ }
116
+ if (bytes.length > MAX_TEXT_BYTES) throw new Error(`${name} is not a picture or a PDF, and too large to be read as text`);
117
+ let text = '';
118
+ try { text = new TextDecoder('utf-8', { fatal: true }).decode(bytes); } catch { text = ''; }
119
+ if (NOT_TEXT.test(text)) text = ''; // (what a text does not hold: a file of another kind that happens to decode)
120
+ if (!text.trim()) throw new Error(/^text\//.test(contentType) || /\.(txt|csv|md|log|json|xml|html?)$/i.test(name) ? `${name} is empty` : `${name} is not something the assistant can read: a picture, a PDF, a Word, Excel or PowerPoint file, or a text file`);
121
+ return asText(text);
122
+ }
@@ -0,0 +1,158 @@
1
+ // The notes' store on this Mac (src/core/notes.js asks it): one file a note in a folder, ~/.sideora/notes.
2
+ //
3
+ // <dir>/k3f9a2c1b7.json a note, as the core hands it over
4
+ // <dir>/trash/… a note removed (moved there, never deleted)
5
+ // <dir>/pictures/3f9a….png a picture of the notes, named by what it holds
6
+ //
7
+ // Any process may write (the hub, and until they ask it, the MCP server and the CLI): every change is made under a
8
+ // lock across processes (<dir>/.lock, naming the process that holds it), and each file is written whole or not at
9
+ // all (written, flushed to the disk, then moved into place).
10
+
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import crypto from 'node:crypto';
14
+
15
+ const FILE = /^([a-z0-9]{6,24})\.json$/;
16
+
17
+ /** The store over `dir`. */
18
+ export function notesFiles(dir) {
19
+ const TRASH_DIR = path.join(dir, 'trash');
20
+ const PICTURES_DIR = path.join(dir, 'pictures');
21
+ const LOCK = path.join(dir, '.lock');
22
+ const TAKEOVER = `${LOCK}.takeover`;
23
+ const fileOf = (id, where = 'notes') => path.join(where === 'trash' ? TRASH_DIR : dir, `${id}.json`);
24
+ const pictureFile = (name) => path.join(PICTURES_DIR, name);
25
+ let held = null; // the lock this process holds: what its file says
26
+
27
+ function ensureDirs() {
28
+ fs.mkdirSync(TRASH_DIR, { recursive: true, mode: 0o700 });
29
+ fs.mkdirSync(PICTURES_DIR, { recursive: true, mode: 0o700 });
30
+ }
31
+
32
+ /** Is the process that wrote this lock still there? (One that cannot be asked about, another user's, is.) */
33
+ function alive(pid) {
34
+ if (!Number.isInteger(pid) || pid <= 0) return false;
35
+ try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
36
+ }
37
+
38
+ /**
39
+ * A lock nobody holds any more: the process that wrote it is gone. (Never by its age alone: a writer stopped for
40
+ * long is still a writer, and would write over whoever took its place.) It is removed by one process at a time (a
41
+ * second lock, held for that only), which looks again once it is the one: two that both found it stale cannot each
42
+ * remove it, the second removing the lock the first has just taken.
43
+ */
44
+ function clearStale() {
45
+ try { fs.writeFileSync(TAKEOVER, String(process.pid), { flag: 'wx', mode: 0o600 }); } catch (e) {
46
+ if (e.code !== 'EEXIST') throw e;
47
+ try { if (Date.now() - fs.statSync(TAKEOVER).mtimeMs > 5000) fs.unlinkSync(TAKEOVER); } catch { /* gone already */ }
48
+ return;
49
+ }
50
+ try {
51
+ const said = fs.readFileSync(LOCK, 'utf8');
52
+ // (just made and not written in yet: its owner is about to say who it is)
53
+ const stale = said.trim() ? !alive(parseInt(said, 10)) : Date.now() - fs.statSync(LOCK).mtimeMs > 2000;
54
+ if (stale && fs.readFileSync(LOCK, 'utf8') === said) fs.unlinkSync(LOCK);
55
+ } catch { /* gone already */ } finally { try { fs.unlinkSync(TAKEOVER); } catch { /* gone already */ } }
56
+ }
57
+
58
+ return {
59
+ /** One writer at a time, across processes: `fn` runs holding the lock. */
60
+ locked(fn) {
61
+ ensureDirs();
62
+ const mine = `${process.pid} ${crypto.randomBytes(6).toString('hex')}`;
63
+ const until = Date.now() + 10_000;
64
+ for (;;) {
65
+ try {
66
+ fs.writeFileSync(LOCK, mine, { flag: 'wx', mode: 0o600 });
67
+ break;
68
+ } catch (e) {
69
+ if (e.code !== 'EEXIST') throw e;
70
+ clearStale();
71
+ if (Date.now() > until) throw new Error('the notes are being changed by another process: try again in a moment');
72
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 25); // a short wait, without a busy loop
73
+ }
74
+ }
75
+ held = mine;
76
+ try { return fn(); } finally {
77
+ held = null;
78
+ // only the lock that is still this one: taken over meanwhile (this process was stopped for long), it is another's
79
+ try { if (fs.readFileSync(LOCK, 'utf8') === mine) fs.unlinkSync(LOCK); } catch { /* gone already */ }
80
+ }
81
+ },
82
+
83
+ /** The ids of the notes (`where`: 'notes', or 'trash'). */
84
+ ids(where = 'notes') {
85
+ let names;
86
+ try { names = fs.readdirSync(where === 'trash' ? TRASH_DIR : dir); } catch { return []; }
87
+ return names.map((f) => FILE.exec(f)?.[1]).filter(Boolean);
88
+ },
89
+
90
+ /** A note as it was written (parsed), or null when there is none or it cannot be read. */
91
+ read(id, where = 'notes') {
92
+ try { return JSON.parse(fs.readFileSync(fileOf(id, where), 'utf8')); } catch { return null; }
93
+ },
94
+
95
+ has(id, where = 'notes') { return fs.existsSync(fileOf(id, where)); },
96
+
97
+ /** What changes whenever a note is written (null when it is not there): the core keeps what it worked out of one until then. */
98
+ stamp(id) {
99
+ try { const st = fs.statSync(fileOf(id)); return `${st.mtimeMs}:${st.size}:${st.ino}`; } catch { return null; }
100
+ },
101
+
102
+ /** Write a note whole, only while holding the lock (inside `locked`). */
103
+ write(note) {
104
+ const file = fileOf(note.id);
105
+ const tmp = `${file}.${process.pid}.tmp`;
106
+ try {
107
+ // on the disk before it takes the note's place: a power cut leaves the note as it was, or as it is now
108
+ const fd = fs.openSync(tmp, 'w', 0o600);
109
+ try { fs.writeSync(fd, JSON.stringify(note, null, 1) + '\n'); fs.fsyncSync(fd); } finally { fs.closeSync(fd); }
110
+ // stopped for so long that the lock was taken over: another writer is at work, and this write would undo theirs
111
+ if (held === null || fs.readFileSync(LOCK, 'utf8') !== held) throw new Error('the notes are being changed by another process: try again');
112
+ fs.renameSync(tmp, file);
113
+ } catch (e) {
114
+ fs.rmSync(tmp, { force: true });
115
+ throw e;
116
+ }
117
+ },
118
+
119
+ /** Move a note between the notes and the trash ('notes' → 'trash', or back). */
120
+ move(id, from, to) { fs.renameSync(fileOf(id, from), fileOf(id, to)); },
121
+
122
+ pictures: {
123
+ /** The size of a picture kept under `name` ("<id>.<ext>"), or -1. */
124
+ size(name) { try { return fs.statSync(pictureFile(name)).size; } catch { return -1; } },
125
+ /** Its bytes, or null (not there, or more than `max`: not read at all). */
126
+ get(name, max) {
127
+ try {
128
+ if (fs.statSync(pictureFile(name)).size > max) return null;
129
+ return fs.readFileSync(pictureFile(name));
130
+ } catch { return null; }
131
+ },
132
+ /** Keep `bytes` under `name`: whole or not at all (two writers of the same picture write the same bytes). */
133
+ put(name, bytes) {
134
+ ensureDirs();
135
+ const file = pictureFile(name);
136
+ const tmp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`;
137
+ try { fs.writeFileSync(tmp, bytes, { mode: 0o600 }); fs.renameSync(tmp, file); } catch (e) { fs.rmSync(tmp, { force: true }); throw e; }
138
+ }
139
+ },
140
+
141
+ /** Tell `onChange(id)` each time a note's file changes, whoever wrote it. Returns the function that stops it. */
142
+ watch(onChange) {
143
+ ensureDirs();
144
+ const soon = new Map();
145
+ let watcher;
146
+ try {
147
+ watcher = fs.watch(dir, (_kind, name) => {
148
+ const id = FILE.exec(String(name || ''))?.[1];
149
+ if (!id) return;
150
+ clearTimeout(soon.get(id));
151
+ soon.set(id, setTimeout(() => { soon.delete(id); onChange(id); }, 60)); // a write is a file made, then moved: one telling
152
+ });
153
+ watcher.on('error', () => {});
154
+ } catch { return () => {}; }
155
+ return () => { for (const t of soon.values()) clearTimeout(t); watcher.close(); };
156
+ }
157
+ };
158
+ }
@@ -0,0 +1,224 @@
1
+ // The text of a Word document, an Excel workbook or a PowerPoint deck, for the assistant (src/core/assistant.js's
2
+ // read_attachment), on the Mac: these are zip files of XML. Nothing is run; only the words are kept, and only so
3
+ // many: a file made to be large once unpacked (or to make the XML parser work) is cut short, not read whole.
4
+ // The page's own reader (extension/src/panel/lib/officeText.ts) does the same in a browser; this one reads the XML
5
+ // with htmlparser2 (a dependency already, through html-to-text).
6
+
7
+ import zlib from 'node:zlib';
8
+ import { parseDocument } from 'htmlparser2';
9
+
10
+ const MAX_ENTRY = 8 * 1024 * 1024; // one part, unpacked
11
+ const MAX_TOTAL = 20 * 1024 * 1024; // all the parts of one file, unpacked
12
+ const MAX_ENTRIES = 400;
13
+ const MAX_TEXT = 20_000; // what is kept of a file's words (the assistant is given 15,000)
14
+
15
+ /** The entries of a zip file, from its central directory. */
16
+ function entries(zip) {
17
+ let end = -1;
18
+ for (let i = zip.length - 22; i >= Math.max(0, zip.length - 22 - 65_535); i--) if (zip.readUInt32LE(i) === 0x06054b50) { end = i; break; }
19
+ if (end < 0) throw new Error('not a zip file');
20
+ const count = zip.readUInt16LE(end + 10);
21
+ let at = zip.readUInt32LE(end + 16);
22
+ const out = [];
23
+ for (let k = 0; k < Math.min(count, MAX_ENTRIES) && at + 46 <= zip.length; k++) {
24
+ if (zip.readUInt32LE(at) !== 0x02014b50) break;
25
+ const nameLen = zip.readUInt16LE(at + 28);
26
+ const extra = zip.readUInt16LE(at + 30);
27
+ const comment = zip.readUInt16LE(at + 32);
28
+ out.push({ name: zip.subarray(at + 46, at + 46 + nameLen).toString('utf8'), method: zip.readUInt16LE(at + 10), compressed: zip.readUInt32LE(at + 20), offset: zip.readUInt32LE(at + 42) });
29
+ at += 46 + nameLen + extra + comment;
30
+ }
31
+ return out;
32
+ }
33
+
34
+ /** One entry's bytes, unpacked (stored or deflated), within the file's budget; null past it. */
35
+ function unpack(zip, e, budget) {
36
+ if (!e || e.offset + 30 > zip.length || budget.bytes <= 0) return null;
37
+ if (zip.readUInt32LE(e.offset) !== 0x04034b50) return null;
38
+ const start = e.offset + 30 + zip.readUInt16LE(e.offset + 26) + zip.readUInt16LE(e.offset + 28);
39
+ if (start + e.compressed > zip.length) return null;
40
+ const data = zip.subarray(start, start + e.compressed);
41
+ const cap = Math.min(MAX_ENTRY, budget.bytes);
42
+ let out;
43
+ if (e.method === 0) out = data;
44
+ else if (e.method === 8) {
45
+ try { out = zlib.inflateRawSync(data, { maxOutputLength: cap }); } catch { return null; } // (what it says its size is, is not trusted: past the cap, it throws)
46
+ } else return null;
47
+ if (out.length > cap) return null;
48
+ budget.bytes -= out.length;
49
+ return out;
50
+ }
51
+
52
+ // --- the XML, as a tree of elements with their local names ---------------------------------------------------------
53
+
54
+ const local = (name) => name.slice(name.indexOf(':') + 1);
55
+ const elements = (node) => (node.children ?? []).filter((c) => c.type === 'tag');
56
+ /** Every element under `root`, in document order. */
57
+ function* all(root) { for (const c of elements(root)) { yield c; yield* all(c); } }
58
+ const byLocal = (root, name) => [...all(root)].filter((el) => local(el.name) === name);
59
+ const textOf = (node) => (node.type === 'text' ? node.data : (node.children ?? []).map(textOf).join(''));
60
+ const attr = (el, name) => el.attribs?.[name] ?? null;
61
+ function* ancestors(el) { for (let a = el.parent; a && a.type === 'tag'; a = a.parent) yield a; }
62
+ /** The namespace a prefix stands for at an element (xmlns:r="…"), looked up through its ancestors. */
63
+ const namespaceOf = (el, prefix) => { for (let a = el; a && a.type === 'tag'; a = a.parent) { const ns = a.attribs?.[`xmlns:${prefix}`]; if (ns) return ns; } return ''; };
64
+ /** The relationship id of an element (r:id): a slide's own id attribute has the same local name. */
65
+ const relId = (el) => {
66
+ for (const [k, v] of Object.entries(el.attribs ?? {})) if (k.includes(':') && local(k) === 'id' && namespaceOf(el, k.slice(0, k.indexOf(':'))).includes('relationships')) return v;
67
+ return null;
68
+ };
69
+
70
+ /**
71
+ * A part as XML. One that declares a document type is not parsed: OOXML never does, and its entities are what
72
+ * would make a parser expand a few kilobytes into megabytes.
73
+ */
74
+ function xml(bytes) {
75
+ if (!bytes) return null;
76
+ const text = bytes.toString('utf8');
77
+ if (/<!DOCTYPE|<!ENTITY/i.test(text)) return null;
78
+ try { return parseDocument(text, { xmlMode: true }); } catch { return null; }
79
+ }
80
+ const keep = (budget, s) => { const kept = s.slice(0, Math.max(0, budget.text)); budget.text -= kept.length; return kept; };
81
+
82
+ /** The parts named by a relationships file, by id: where a workbook's sheets or a deck's slides are. */
83
+ function rels(zip, list, path, base, budget) {
84
+ const doc = xml(unpack(zip, list.find((x) => x.name === path), budget));
85
+ const out = new Map();
86
+ if (!doc) return out;
87
+ for (const r of byLocal(doc, 'Relationship')) {
88
+ const id = attr(r, 'Id');
89
+ const target = attr(r, 'Target') ?? '';
90
+ if (id) out.set(id, target.startsWith('/') ? target.slice(1) : `${base}${target}`);
91
+ }
92
+ return out;
93
+ }
94
+
95
+ /** The words of a paragraph in reading order: tabs and line breaks kept; a text box (a paragraph inside it) and an alternative's fallback copy left to themselves. */
96
+ function wordsOf(p) {
97
+ let s = '';
98
+ const walk = (el) => {
99
+ for (const c of elements(el)) {
100
+ const n = local(c.name);
101
+ if (n === 'Fallback' || n === 'txbxContent' || n === 'p' || n === 'instrText' || n === 'delText' || n === 'rPh') continue;
102
+ if (n === 't') s += textOf(c);
103
+ else if (n === 'tab') s += '\t';
104
+ else if (n === 'br' || n === 'cr') s += '\n';
105
+ else walk(c);
106
+ }
107
+ };
108
+ walk(p);
109
+ return s;
110
+ }
111
+ const inFallback = (el) => [...ancestors(el)].some((a) => local(a.name) === 'Fallback');
112
+
113
+ /** Word: a paragraph a line; a table row on one line, its cells separated by tabs (a cell's paragraphs by spaces). */
114
+ function docx(zip, list, budget) {
115
+ const doc = xml(unpack(zip, list.find((x) => x.name === 'word/document.xml'), budget));
116
+ if (!doc) return '';
117
+ const lines = [];
118
+ let row = null;
119
+ let cells = new Map();
120
+ const endRow = () => { if (row) { lines.push(keep(budget, [...cells.values()].map((c) => c.join(' ')).join('\t'))); row = null; cells = new Map(); } };
121
+ for (const p of byLocal(doc, 'p')) {
122
+ if (budget.text <= 0) break;
123
+ if (inFallback(p)) continue; // the same words again, for old readers
124
+ const text = wordsOf(p);
125
+ const tc = [...ancestors(p)].find((a) => local(a.name) === 'tc') ?? null;
126
+ const tr = tc?.parent?.type === 'tag' && local(tc.parent.name) === 'tr' ? tc.parent : null;
127
+ if (!tr || !tc) { endRow(); lines.push(keep(budget, text)); continue; }
128
+ if (tr !== row) { endRow(); row = tr; }
129
+ const cell = cells.get(tc);
130
+ if (cell) cell.push(text); else cells.set(tc, [text]);
131
+ }
132
+ endRow();
133
+ return lines.join('\n').replace(/\n{3,}/g, '\n\n').trim();
134
+ }
135
+
136
+ /** "C12" → its column, from 0. */
137
+ const columnOf = (ref) => { const m = /^([A-Z]+)\d+$/.exec(ref ?? ''); if (!m) return -1; let n = 0; for (const ch of m[1]) n = n * 26 + (ch.charCodeAt(0) - 64); return n - 1; };
138
+ /** A day as Excel counts them (from 1900, or from 1904), as a date. */
139
+ const excelDate = (serial, from1904) => new Date(Date.UTC(from1904 ? 1904 : 1899, from1904 ? 0 : 11, from1904 ? 1 : 30) + Math.round(serial * 86400e3)).toISOString().replace(/T00:00:00\.000Z$/, '').replace(/\.000Z$/, 'Z');
140
+
141
+ /** Excel: each sheet by its name, in the workbook's order, as lines of tab-separated cells in their columns. */
142
+ function xlsx(zip, list, budget) {
143
+ const read = (name) => xml(unpack(zip, list.find((x) => x.name === name), budget));
144
+ const book = read('xl/workbook.xml');
145
+ const from1904 = !!book && byLocal(book, 'workbookPr').some((w) => ['1', 'true'].includes(attr(w, 'date1904') ?? ''));
146
+ const where = rels(zip, list, 'xl/_rels/workbook.xml.rels', 'xl/', budget);
147
+ let sheets = book ? byLocal(book, 'sheet').map((s) => ({ name: attr(s, 'name') ?? 'Sheet', part: where.get(relId(s) ?? '') })).filter((s) => s.part) : [];
148
+ // no workbook to say (a file put together by hand): the sheets as their files are numbered
149
+ if (!sheets.length) sheets = list.filter((x) => /^xl\/worksheets\/sheet\d+\.xml$/.test(x.name)).sort((x, y) => Number(/(\d+)\.xml$/.exec(x.name)?.[1]) - Number(/(\d+)\.xml$/.exec(y.name)?.[1])).map((x, k) => ({ name: `Sheet ${k + 1}`, part: x.name }));
150
+ // which styles are dates (the built-in date formats, and those of the workbook that look like one)
151
+ const styles = read('xl/styles.xml');
152
+ const dateFormats = new Set([14, 15, 16, 17, 18, 19, 20, 21, 22, 45, 46, 47]);
153
+ if (styles) for (const f of byLocal(styles, 'numFmt')) if (/[dy]/i.test((attr(f, 'formatCode') ?? '').replace(/"[^"]*"|\[[^\]]*\]/g, ''))) dateFormats.add(Number(attr(f, 'numFmtId')));
154
+ const xfs = styles ? byLocal(styles, 'cellXfs').flatMap((c) => elements(c).filter((x) => local(x.name) === 'xf')) : [];
155
+ const isDate = (s) => s !== null && dateFormats.has(Number((xfs[Number(s)] && attr(xfs[Number(s)], 'numFmtId')) ?? -1));
156
+ const sharedDoc = read('xl/sharedStrings.xml');
157
+ const shared = sharedDoc ? byLocal(sharedDoc, 'si').map((si) => byLocal(si, 't').filter((t) => ![...ancestors(t)].some((a) => local(a.name) === 'rPh')).map(textOf).join('')) : [];
158
+ const out = [];
159
+ for (const s of sheets.slice(0, 10)) {
160
+ if (budget.text <= 0) break;
161
+ const doc = read(s.part);
162
+ if (!doc) continue;
163
+ const lines = [];
164
+ for (const row of byLocal(doc, 'row').slice(0, 500)) {
165
+ if (budget.text <= 0) break;
166
+ const cols = [];
167
+ let next = 0;
168
+ for (const c of elements(row).filter((x) => local(x.name) === 'c')) {
169
+ const at = columnOf(attr(c, 'r'));
170
+ const col = at >= 0 ? at : next;
171
+ if (col > 200) break;
172
+ next = col + 1;
173
+ const vEl = elements(c).find((x) => local(x.name) === 'v');
174
+ const v = vEl ? textOf(vEl) : '';
175
+ const t = attr(c, 't');
176
+ cols[col] = t === 's' ? shared[Number(v)] ?? ''
177
+ : t === 'inlineStr' ? byLocal(c, 't').map(textOf).join('')
178
+ : t === 'b' ? (v === '1' ? 'TRUE' : 'FALSE')
179
+ : v !== '' && isDate(attr(c, 's')) && Number.isFinite(Number(v)) ? excelDate(Number(v), from1904)
180
+ : v;
181
+ }
182
+ lines.push(keep(budget, Array.from(cols, (x) => x ?? '').join('\t')));
183
+ }
184
+ out.push(`[${s.name}]\n${lines.join('\n')}`);
185
+ }
186
+ return out.join('\n\n').trim();
187
+ }
188
+
189
+ /** PowerPoint: each slide's text, in the deck's order. */
190
+ function pptx(zip, list, budget) {
191
+ const deck = xml(unpack(zip, list.find((x) => x.name === 'ppt/presentation.xml'), budget));
192
+ const where = rels(zip, list, 'ppt/_rels/presentation.xml.rels', 'ppt/', budget);
193
+ let order = deck ? byLocal(deck, 'sldId').map((s) => where.get(relId(s) ?? '')).filter(Boolean) : [];
194
+ if (!order.length) order = list.filter((x) => /^ppt\/slides\/slide\d+\.xml$/.test(x.name)).map((x) => x.name).sort((x, y) => Number(/(\d+)\.xml$/.exec(x)?.[1]) - Number(/(\d+)\.xml$/.exec(y)?.[1]));
195
+ const out = [];
196
+ for (const [k, name] of order.slice(0, 100).entries()) {
197
+ if (budget.text <= 0) break;
198
+ const doc = xml(unpack(zip, list.find((x) => x.name === name), budget));
199
+ if (!doc) continue;
200
+ const lines = byLocal(doc, 'p').filter((p) => !inFallback(p)).map(wordsOf).filter(Boolean);
201
+ out.push(keep(budget, `[Slide ${k + 1}]\n${lines.join('\n')}`));
202
+ }
203
+ return out.join('\n\n').trim();
204
+ }
205
+
206
+ /** The kind of office document a file is, by its name: what officeText reads. */
207
+ export const officeKind = (name) => {
208
+ const e = /\.([a-z0-9]+)$/i.exec(name)?.[1]?.toLowerCase();
209
+ return e === 'docx' || e === 'xlsx' || e === 'pptx' ? e : null;
210
+ };
211
+
212
+ /** The words of a .docx, .xlsx or .pptx file (its bytes); '' when nothing could be read. */
213
+ export function officeText(name, bytes) {
214
+ const kind = officeKind(name);
215
+ if (!kind) return '';
216
+ try {
217
+ const zip = Buffer.isBuffer(bytes) ? bytes : Buffer.from(bytes);
218
+ const list = entries(zip);
219
+ const budget = { bytes: MAX_TOTAL, text: MAX_TEXT };
220
+ return kind === 'docx' ? docx(zip, list, budget) : kind === 'xlsx' ? xlsx(zip, list, budget) : pptx(zip, list, budget);
221
+ } catch {
222
+ return '';
223
+ }
224
+ }
@@ -0,0 +1,8 @@
1
+ // Runs officeText (./office-text.js) on its own thread, for prepareFile (./file-prep.js): a file made to make the
2
+ // reading slow (deep nesting, a great many empty paragraphs) then holds up only this thread, which is ended after a
3
+ // few seconds, and never the daemon that answers everything else.
4
+
5
+ import { parentPort, workerData } from 'node:worker_threads';
6
+ import { officeText } from './office-text.js';
7
+
8
+ parentPort.postMessage(officeText(workerData.name, Buffer.from(workerData.bytes)));