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
package/src/ops.js ADDED
@@ -0,0 +1,1251 @@
1
+ // Transport-neutral mailbox operations: plain args in, plain JSON out.
2
+ // The Chrome bridge (src/bridge.js) calls these; the MCP server has the same
3
+ // logic inline today and can move onto this file as the bridge grows.
4
+ //
5
+ // Reads: accounts, whoami, list, search, read, thread, attachment, contacts, files.
6
+ // Writes: markRead, move (to the archive, the trash, junk, or back to the inbox), saveDraft, addAttachment, removeAttachment, deleteDraft — and sendDraft, the only one that
7
+ // reaches other people. The bridge serves a person pressing Send in the side
8
+ // panel, so it is not behind mcp.allowSend (that gate is for agents).
9
+ // Calendar: events, event (reads); saveEvent, deleteEvent and respondToEvent.
10
+ // Inviting people, changing or cancelling a meeting, and answering an
11
+ // invitation all mail other people: the person's click, like Send.
12
+ // Settings: rules, saveRule, removeRule, moveRule, setQuietHours, playSound
13
+ // (rules.yaml — what a rule matches and how it alerts, never what it runs);
14
+ // signatures, saveSignature, removeSignature, setSignatureDetails, setIdentity (config.json — the
15
+ // signatures, and per account the name it writes as and the one it uses).
16
+ // Sender pictures: senderPictures (looked up here, cached; see pictures.js),
17
+ // pictureSettings, setPictureSettings (config.json "pictures").
18
+ // calendarView, setCalendarView (config.json "calendarsHidden": the calendars the panel does not show, on every device).
19
+ // People and suggestions also read the Google contacts of accounts signed in
20
+ // to Google with contacts allowed (google-contacts.js: kept in the core database, src/core-db.js).
21
+
22
+ import { labelOf } from './labels.js';
23
+ // (mail, calendars and contacts only through their contracts: src/mail-port.js)
24
+ import { mail, mailCache, mailText, calendar, contacts as directory } from './mail-port.js';
25
+
26
+ import { loadConfig, updateConfig, calendarProvider, getAccount, mailAccountNames as namesWithMail } from './config.js';
27
+ import { pictures, pictureSettings as picturesOf } from './pictures.js';
28
+ import { googleContacts } from './google-contacts.js';
29
+ import * as identity from './identity.js';
30
+ import * as rulesStore from './rules-store.js';
31
+ import { findCode } from './otp.js';
32
+ import { fileAt, mailAt } from './attached-mail.js';
33
+ import { filesIndex, gone, keptAccounts } from './files-index.js';
34
+ import { playSound as play } from './notify.js';
35
+
36
+ const mailPort = mail; // (where a function has a `mail` of its own)
37
+
38
+ const FOLDERS = ['inbox', 'junk', 'sent', 'drafts', 'trash', 'archive'];
39
+ const MAX_ATTACHMENT = 30 * 1024 * 1024;
40
+ const MAX_UPLOAD = 20 * 1024 * 1024;
41
+
42
+ // Listings span accounts and skip one that fails. When the failures leave
43
+ // nothing, they are the answer: an empty list would read as "no mail".
44
+ async function across(run) {
45
+ const failed = [];
46
+ const r = await run((name, e) => { if (name !== 'cache') failed.push(`${name}: ${e.message}`); });
47
+ if (failed.length && !r.length) throw new Error(failed.join('; '));
48
+ return r;
49
+ }
50
+
51
+ const str = (v) => (typeof v === 'string' && v.trim() ? v.trim() : undefined);
52
+ const iso = (v) => { const d = v ? new Date(v) : null; return d && !isNaN(d) ? d.toISOString() : undefined; };
53
+ const folder = (v) => (FOLDERS.includes(v) ? v : undefined);
54
+ const limit = (v, dflt) => Math.min(100, Math.max(1, Number(v) || dflt));
55
+
56
+ function emails(v, what) {
57
+ const list = (Array.isArray(v) ? v : String(v || '').split(/[,;\s]+/)).map((s) => String(s).trim()).filter(Boolean);
58
+ for (const e of list) if (!/^[^\s@<>,;]+@[^\s@<>,;]+\.[^\s@<>,;]+$/.test(e)) throw new Error(`"${e}" is not an email address (${what})`);
59
+ return list;
60
+ }
61
+
62
+ /** Page cursor: pass it back as `until` with the same filters. */
63
+ function page(items, max, where) {
64
+ // the size of its thread belongs on a received mail, not on a draft or a sent copy
65
+ let listed = withPreviews(items);
66
+ if (where === 'inbox') listed = withThreadCounts(listed);
67
+ // a code is as likely to land in Junk; there only a subject can give it (the cache holds bodies of the inbox alone)
68
+ if (where === 'inbox' || where === 'junk') listed = withCodes(listed);
69
+ const out = { items: listed };
70
+ if (items.length >= max && items.length) out.cursor = new Date(new Date(items[items.length - 1].received).getTime() - 1000).toISOString();
71
+ return out;
72
+ }
73
+
74
+ /** Adds `preview` (start of the body) to the items whose body is in the cache. */
75
+ function withPreviews(items) {
76
+ try {
77
+ const found = mailCache.snippets(items.map((i) => i.id));
78
+ return found.size ? items.map((i) => (found.has(i.id) ? { ...i, preview: found.get(i.id) } : i)) : items;
79
+ } catch {
80
+ return items;
81
+ }
82
+ }
83
+
84
+ export function listAccounts() {
85
+ const cfg = loadConfig();
86
+ return Object.values(cfg.accounts).map((a) => ({
87
+ name: a.name,
88
+ ...(labelOf(a.label) ? { label: labelOf(a.label).slice(0, 40) } : {}),
89
+ provider: a.provider,
90
+ mail: ['ews', 'imap', 'jmap'].includes(a.provider),
91
+ calendar: calendarProvider(a) || null,
92
+ email: a.email || undefined,
93
+ // the other addresses it writes or receives as (a reply leaves them out of its recipients)
94
+ ...(() => { const more = [a.username, ...(Array.isArray(a.aliases) ? a.aliases : [])].filter((v) => typeof v === 'string' && v.includes('@')); return more.length ? { aliases: more } : {}; })()
95
+ }));
96
+ }
97
+
98
+ /** { items, cursor? } — newest first, all accounts unless `account` is given. `flagged`: only mail flagged for follow-up (asked of the servers: the cache holds the last weeks only). */
99
+ export async function listMail(a = {}) {
100
+ const max = limit(a.limit, 40);
101
+ const opts = { limit: max, unreadOnly: !!a.unread, flaggedOnly: !!a.flagged || undefined, folder: folder(a.folder), untilIso: iso(a.until), live: !!a.live || undefined };
102
+ return page(await across((onError) => mail.find(str(a.account), opts, onError)), max, opts.folder || 'inbox');
103
+ }
104
+
105
+ /** Full-text search (subject and body) plus the usual filters. */
106
+ export async function searchMail(a = {}) {
107
+ const max = limit(a.limit, 40);
108
+ const opts = {
109
+ limit: max,
110
+ text: str(a.text),
111
+ senderContains: str(a.sender),
112
+ toContains: str(a.to) || undefined,
113
+ subjectContains: str(a.subject),
114
+ hasAttachments: !!a.hasAttachments || undefined,
115
+ unreadOnly: !!a.unread,
116
+ flaggedOnly: !!a.flagged || undefined,
117
+ folder: folder(a.folder),
118
+ sinceIso: iso(a.since),
119
+ untilIso: iso(a.until),
120
+ live: !!a.live || undefined
121
+ };
122
+ return page(await across((onError) => mail.find(str(a.account), opts, onError)), max, opts.folder || 'inbox');
123
+ }
124
+
125
+ /**
126
+ * One message; the HTML body when there is one, else text (see bodyType).
127
+ * `quoteAt` is the offset in `body` where the quoted thread of a reply
128
+ * starts (null when there is none, or nothing is written above it).
129
+ */
130
+ export async function readMail(a = {}) {
131
+ if (!str(a.id)) throw new Error('read needs an id');
132
+ const msg = await mail.read(a.id, { bodyType: a.format === 'text' ? 'Text' : 'HTML', ...(a.live ? { live: true } : {}) });
133
+ const { head, tail } = mailText.splitQuoted(msg.body, msg.bodyType);
134
+ const written = msg.bodyType === 'HTML' ? head.replace(/<style[\s\S]*?<\/style>|<head[\s\S]*?<\/head>|<[^>]+>|&nbsp;/gi, '') : head;
135
+ return { ...msg, quoteAt: tail && written.trim() ? head.length : null };
136
+ }
137
+
138
+ /**
139
+ * Headers of the whole conversation, oldest first; each carries `folder`:
140
+ * inbox, sent, or drafts (an unsent answer, wherever it was written, belongs
141
+ * at the end of its thread).
142
+ */
143
+ export async function thread(a = {}) {
144
+ if (!str(a.id)) throw new Error('thread needs an id');
145
+ // the drafts are listed alongside the thread search (the account is in the id), not after it
146
+ const draftsOf = mail.findIn(a.id, { folder: 'drafts', limit: 50, live: true }).catch(() => null);
147
+ const items = await across((onError) => mail.thread({ id: a.id, days: 90, onError }));
148
+ const conversations = new Set(items.map((i) => i.conversationId).filter(Boolean));
149
+ const drafts = await draftsOf; // none: the thread without its drafts is still the thread
150
+ noteSent(items[0]?.account, items.filter((i) => i.folder === 'sent')); // an opened thread is counted right from now on
151
+ if (conversations.size && drafts) {
152
+ const known = new Set(items.map((i) => i.id));
153
+ for (const d of drafts) if (conversations.has(d.conversationId) && !known.has(d.id)) items.push({ ...d, folder: 'drafts' });
154
+ items.sort((x, y) => new Date(x.received) - new Date(y.received));
155
+ }
156
+ return { items: withPreviews(items) };
157
+ }
158
+
159
+ /** One attachment's bytes, base64 (the panel hands it to the browser's download, or inlines a cid image). */
160
+ export async function attachment(a = {}) {
161
+ if (!str(a.id) || !str(a.attachmentId)) throw new Error('attachment needs the message id and the attachment id');
162
+ const file = await mail.attachment(a.id, a.attachmentId);
163
+ if (file.content.length > MAX_ATTACHMENT) throw new Error('this attachment is over 30 MB — save it with: sideora attachments --save');
164
+ return { name: file.name, contentType: file.contentType, contentId: file.contentId || null, size: file.content.length, data: file.content.toString('base64') };
165
+ }
166
+
167
+ // the last attached mails read, for a minute: opening one, then its files and the mails inside it, asks the server once
168
+ const outerKept = new Map();
169
+ const OUTER_KEPT = 4;
170
+ const OUTER_MS = 60e3;
171
+
172
+ /** A mail's attachment, read for the steps below (the outer one, from the server, or as read in the last minute). */
173
+ const outerFile = (id) => async (attachmentId) => {
174
+ const key = `${id}\n${attachmentId}`;
175
+ const was = outerKept.get(key);
176
+ if (was && Date.now() - was.at < OUTER_MS) return was.file;
177
+ const file = await mail.attachment(id, attachmentId);
178
+ if (file.content.length > MAX_ATTACHMENT) throw new Error('this attachment is over 30 MB: download it to open it');
179
+ outerKept.delete(key);
180
+ outerKept.set(key, { file, at: Date.now() });
181
+ while (outerKept.size > OUTER_KEPT) outerKept.delete(outerKept.keys().next().value);
182
+ return file;
183
+ };
184
+
185
+ /** A mail that came attached to a mail, read to be shown (attached-mail.js): `path` is the attachment's id, then those inside. */
186
+ export async function attachedMail(a = {}) {
187
+ if (!str(a.id) || !Array.isArray(a.path)) throw new Error('attachedMail needs the message id and the path of the attached mail');
188
+ return mailAt(a.path, outerFile(a.id));
189
+ }
190
+
191
+ /** The bytes of a file inside a mail that came attached (at `path`), as `attachment` gives an attachment's. */
192
+ export async function attachmentAt(a = {}) {
193
+ if (!str(a.id) || !Array.isArray(a.path)) throw new Error('attachmentAt needs the message id and the path of the file');
194
+ const file = await fileAt(a.path, outerFile(a.id));
195
+ if (file.content.length > MAX_ATTACHMENT) throw new Error('this attachment is over 30 MB: download the mail it is in');
196
+ return { name: file.name, contentType: file.contentType, contentId: file.contentId || null, size: file.content.length, data: file.content.toString('base64') };
197
+ }
198
+
199
+ /**
200
+ * Mark one message read (or unread with read: false). A stale changeKey
201
+ * (cached listing) is refreshed from the server once. A message that is no
202
+ * longer there (moved or deleted in another client while the cache still
203
+ * listed it) is dropped from the cache: { ok: true, gone: true }.
204
+ */
205
+ export async function markRead(a = {}) {
206
+ if (!str(a.id)) throw new Error('markRead needs an id');
207
+ const read = a.read !== false;
208
+ const mark = (ck) => mail.markRead(a.id, ck, read);
209
+ try {
210
+ await mark(a.changeKey || '');
211
+ } catch {
212
+ // a stale change key, or a message that is gone: a fresh read tells which, and the second try may still find it gone
213
+ try {
214
+ const fresh = await mail.read(a.id, { live: true });
215
+ await mark(fresh.changeKey || '');
216
+ } catch (e) {
217
+ if (!/not found|ItemNotFound|no such/i.test(e.message)) throw e;
218
+ mail.noteRemoved(a.id);
219
+ return { ok: true, gone: true };
220
+ }
221
+ }
222
+ mail.noteRead(a.id, read);
223
+ return { ok: true };
224
+ }
225
+
226
+ /**
227
+ * Flag a message for follow-up, or clear it: { id, changeKey?, flagged? }
228
+ * (a star in Gmail). Like markRead, a stale change key is refreshed once, and
229
+ * a message that is no longer there answers `gone`.
230
+ */
231
+ export async function flag(a = {}) {
232
+ if (!str(a.id)) throw new Error('flag needs an id');
233
+ const flagged = a.flagged !== false;
234
+ const set = (ck) => mail.setFlag(a.id, ck, flagged);
235
+ try {
236
+ await set(a.changeKey || '');
237
+ } catch {
238
+ // a stale change key, or a message that is gone: a fresh read tells which, and the second try may still find it gone
239
+ try {
240
+ const fresh = await mail.read(a.id, { live: true });
241
+ await set(fresh.changeKey || '');
242
+ } catch (e) {
243
+ if (!/not found|ItemNotFound|no such/i.test(e.message)) throw e;
244
+ mail.noteRemoved(a.id);
245
+ return { ok: true, gone: true };
246
+ }
247
+ }
248
+ mail.noteFlagged(a.id, flagged);
249
+ return { ok: true };
250
+ }
251
+
252
+ const MOVE_TO = ['inbox', 'archive', 'trash', 'junk', 'sent']; // sent: only so that a mail deleted from Sent can be put back
253
+
254
+ /**
255
+ * Move messages to another folder: `to` is inbox, archive, trash, junk or sent
256
+ * (deleting is a move to the trash: nothing is destroyed). A moved message
257
+ * has a new id: { moved: [{ from, id }], gone: [ids] }, with `from` the id it
258
+ * had, so the move can be taken back, and `gone` the messages that were no
259
+ * longer there (moved or deleted in another mail client): those are dropped
260
+ * from the cache, which still listed them.
261
+ */
262
+ export async function move(a = {}) {
263
+ const ids = (Array.isArray(a.ids) ? a.ids : [a.id]).filter((x) => typeof x === 'string' && x);
264
+ if (!ids.length) throw new Error('move needs the ids of the messages');
265
+ if (ids.length > 200) throw new Error('move: at most 200 messages at a time');
266
+ if (!MOVE_TO.includes(a.to)) throw new Error(`move: to is one of ${MOVE_TO.join(', ')}`);
267
+ const byAccount = new Map();
268
+ for (const id of ids) { const { account } = mailText.splitId(id); byAccount.set(account, [...(byAccount.get(account) || []), id]); }
269
+ const moved = [];
270
+ const gone = [];
271
+ const failed = []; // { ids, error }: not moved, and still where they were
272
+ for (const [, list] of byAccount) {
273
+ // one account failing does not undo what another already did: each says what became of its own
274
+ let map;
275
+ try {
276
+ // (back in the inbox, an archive or a delete taken back, a restore: the cache is told at once, src/mail-port.js)
277
+ map = await mail.moveItems(list, a.to);
278
+ } catch (e) {
279
+ failed.push({ ids: list, error: e.message || String(e) });
280
+ continue;
281
+ }
282
+ for (const [from, id] of map) { mail.noteRemoved(from); if (id == null) gone.push(from); else moved.push({ from, id }); }
283
+ // (nor among the files kept of the folder it left: src/files-index.js)
284
+ try { const index = await (await import('./files-index.js')).filesIndex(); for (const folder of ['inbox', 'sent']) index.remove(folder, [...map.keys()]); } catch { /* let go at the next look */ }
285
+ // asked for and not answered for (refused one by one, or a batch that failed after others went)
286
+ const missing = list.filter((id) => !map.has(id));
287
+ if (missing.length) failed.push({ ids: missing, error: 'the server did not move these' });
288
+ }
289
+ if (!moved.length && !gone.length) throw new Error(failed[0]?.error || 'none of these messages could be moved');
290
+ return failed.length ? { moved, gone, failed } : { moved, gone };
291
+ }
292
+
293
+ /**
294
+ * Create or update a DRAFT; never sends. The body is HTML (`html`).
295
+ * kind 'new' a new mail
296
+ * kind 'reply' | 'replyAll' an answer to message `id`: the server sets recipients, subject and the quoted thread
297
+ * kind 'forward' message `id` forwarded: the server adds the original and its attachments
298
+ * kind 'edit' a draft that already exists (`draftId`)
299
+ * With `draftId` (+ `changeKey`) the existing draft is updated. `keepQuoted`
300
+ * replaces only what is written above its quoted thread. `to`/`cc` are sent
301
+ * only when the person set them (a reply keeps the server's otherwise),
302
+ * `bcc` too;
303
+ * `subject` likewise.
304
+ * Returns { draftId, changeKey } for the next update, attachment or send.
305
+ */
306
+ export async function saveDraft(a = {}) {
307
+ const kind = ['new', 'reply', 'replyAll', 'forward', 'edit'].includes(a.kind) ? a.kind : null;
308
+ if (!kind) throw new Error('saveDraft: unknown kind');
309
+ const body = String(a.html ?? '');
310
+ const who = a.to !== undefined || a.cc !== undefined || a.bcc !== undefined
311
+ ? { to: emails(a.to, 'To'), cc: emails(a.cc, 'Cc'), ...(a.bcc !== undefined ? { bcc: emails(a.bcc, 'Bcc') } : {}) }
312
+ : null;
313
+ const subject = a.subject !== undefined ? { subject: String(a.subject) } : {};
314
+ const done = (r, fallbackId) => {
315
+ const draftId = r?.draftId || fallbackId;
316
+ if (!draftId) throw new Error('the server did not return the draft');
317
+ return { draftId, changeKey: r?.changeKey || '' };
318
+ };
319
+
320
+ if (str(a.draftId)) {
321
+ const r = await mail.updateDraft(a.draftId, { id: a.draftId, changeKey: a.changeKey || '', body, bodyType: 'HTML', keepQuoted: !!a.keepQuoted, ...(who || {}), ...subject });
322
+ mail.noteRemoved(a.draftId); // its cached copy is stale now
323
+ return done(r, a.draftId);
324
+ }
325
+ if (kind === 'edit') throw new Error('saveDraft: editing needs the draftId');
326
+ if (kind === 'new') {
327
+ return done(await mail.createMessage(str(a.account), { to: who?.to || [], cc: who?.cc || [], bcc: who?.bcc || [], subject: subject.subject || '', body, bodyType: 'HTML', send: false }));
328
+ }
329
+ if (!str(a.id)) throw new Error('saveDraft: a reply or forward needs the id of the message');
330
+ if (kind === 'forward') {
331
+ return done(await mail.draftForward(a.id, '', body, { bodyType: 'HTML', to: who?.to || [], cc: who?.cc || [], bcc: who?.bcc || [] }));
332
+ }
333
+ let r = done(await (kind === 'replyAll' ? mail.draftReplyAll(a.id, '', body, { bodyType: 'HTML' }) : mail.draftReply(a.id, '', body, { bodyType: 'HTML' })));
334
+ if (who || subject.subject !== undefined) r = done(await mail.updateDraft(r.draftId, { id: r.draftId, changeKey: r.changeKey, ...(who || {}), ...subject }), r.draftId);
335
+ return r;
336
+ }
337
+
338
+ /**
339
+ * A draft as the composer needs it: recipients, subject, the part written
340
+ * above the quoted thread (as HTML), and its attachments. Always read from
341
+ * the server.
342
+ */
343
+ // a picture of a draft read a moment ago (a draft is asked for again at every refresh): not read from the mailbox once more
344
+ const pictureRead = new Map(); // "<message id>|<attachment id>" -> { contentType, data }
345
+ function keptPicture(key, file) {
346
+ if (file.data.length > 3_000_000) return;
347
+ pictureRead.set(key, file);
348
+ if (pictureRead.size > 12) pictureRead.delete(pictureRead.keys().next().value);
349
+ }
350
+
351
+ /**
352
+ * The pictures the side panel put in a draft's text (its signature's, those
353
+ * placed in what is written) under the names it gave them. An HTML mail names
354
+ * a picture it carries by content id (`<img src="cid:…">`); read back from an
355
+ * IMAP mailbox, the picture itself stands there instead (`src="data:…"`: the
356
+ * mail parser writes each carried picture into the HTML), and the panel no
357
+ * longer knows its own: a signature read so is taken for typed text, and
358
+ * saved as such.
359
+ *
360
+ * `head` is what the draft itself says (above what it quotes or forwards).
361
+ * Each of the panel's pictures (their content ids end in @sideora, or @mailwatcher in drafts saved before the rename) is
362
+ * read and named again there, the last attached first: a draft's own are
363
+ * attached after those of a mail it forwards, which may hold the very same
364
+ * picture (my signature, in a mail of mine) under another name. It stops
365
+ * once nothing is left to name. A picture that cannot be read is an error:
366
+ * opened without its name, the signature would be saved as text.
367
+ * `read(attachment)` gives { contentType, data (base64) }.
368
+ */
369
+ export async function ownPicturesNamed(head, attachments, read) {
370
+ let html = String(head ?? '');
371
+ const unnamed = () => /\bsrc\s*=\s*["']?data:image\//i.test(html);
372
+ if (!unnamed()) return html;
373
+ const own = (attachments || []).filter((x) => x.inline && /@(?:sideora|mailwatcher)$/.test(x.contentId || '') && !html.includes(`cid:${x.contentId}`));
374
+ for (const x of own.reverse()) {
375
+ if (!unnamed()) break;
376
+ let file;
377
+ try { file = await read(x); } catch (e) { throw new Error(`a picture of this draft could not be read (${e?.message || e}): open it again in a moment`); }
378
+ if (!file?.data || !/^image\/[a-z0-9.+-]+$/i.test(file.contentType || '')) continue;
379
+ html = html.split(`data:${file.contentType};base64,${file.data}`).join(`cid:${x.contentId}`);
380
+ }
381
+ return html;
382
+ }
383
+
384
+ export async function readDraft(a = {}) {
385
+ if (!str(a.draftId)) throw new Error('draft needs a draftId');
386
+ const m = await mail.read(a.draftId, { bodyType: 'HTML', live: true });
387
+ const split = mailText.splitQuoted(m.body, m.bodyType);
388
+ const tail = split.tail;
389
+ const head = m.bodyType !== 'HTML' ? split.head : await ownPicturesNamed(split.head, m.attachments, async (x) => {
390
+ const key = `${m.id}|${x.id}`;
391
+ const had = pictureRead.get(key);
392
+ if (had) return had;
393
+ const file = await attachment({ id: m.id, attachmentId: x.id });
394
+ const read = { contentType: file.contentType, data: file.data };
395
+ keptPicture(key, read);
396
+ return read;
397
+ });
398
+ const address = (p) => (typeof p === 'string' ? p : p?.email || '');
399
+ return {
400
+ draftId: m.id,
401
+ // IMAP has no change key: a draft written again gets a new id, which is its change key (as saveDraft hands it out)
402
+ changeKey: m.changeKey || m.id,
403
+ to: (m.to || []).map(address).filter(Boolean).join(', '),
404
+ cc: (m.cc || []).map(address).filter(Boolean).join(', '),
405
+ bcc: (m.bcc || []).map(address).filter(Boolean).join(', '),
406
+ subject: m.subject || '',
407
+ // (without the breaks a reply puts between the text and its quote: they are kept where they are, not typed)
408
+ html: m.bodyType === 'HTML' ? (tail ? mailText.splitBreaks(head).text : head) : mailText.textToHtml(head),
409
+ keepQuoted: !!tail,
410
+ attachments: (m.attachments || []).filter((x) => !x.inline).map((x) => ({ id: x.id, name: x.name, size: x.size, contentType: x.contentType || '' })),
411
+ // pictures placed in the text written here (those of the quoted thread are not this draft's to manage)
412
+ inline: (m.attachments || []).filter((x) => x.inline && x.contentId && head.includes('cid:' + x.contentId)).map((x) => ({ id: x.id, cid: x.contentId, contentType: x.contentType || '' }))
413
+ };
414
+ }
415
+
416
+ // --- people ------------------------------------------------------------------------
417
+
418
+ // a sender address that names what it sends, not who: pncalerts@, stats@, mynews@…
419
+ const SERVICE = /(alerts?|notifications?|notify|news|newsletters?|stats|digest|updates?|reports?)$/i;
420
+
421
+ /** My own addresses, on every account (+tags folded): I am not one of "my people". Asked once a minute at most. */
422
+ let mineKept = null;
423
+ async function myAddresses() {
424
+ if (mineKept && Date.now() - mineKept.at < 60e3) return mineKept.isMe;
425
+ const isMe = await readMyAddresses();
426
+ mineKept = { at: Date.now(), isMe };
427
+ return isMe;
428
+ }
429
+ async function readMyAddresses() {
430
+ const cfg = loadConfig();
431
+ const mine = new Set();
432
+ for (const a of Object.values(cfg.accounts)) for (const v of [a.email, a.username, ...(a.aliases || [])]) if (typeof v === 'string' && v.includes('@')) mine.add(v.toLowerCase());
433
+ await Promise.all(Object.values(cfg.accounts).filter((a) => ['ews', 'imap', 'jmap'].includes(a.provider)).map((a) =>
434
+ mail.selfEmail(a.name).then((e) => { if (e) mine.add(String(e).toLowerCase()); }, () => {})));
435
+ const plain = (e) => String(e || '').toLowerCase().replace(/\+[^@]*@/, '@');
436
+ return (e) => mine.has(String(e || '').toLowerCase()) || [...mine].some((m) => plain(m) === plain(e));
437
+ }
438
+
439
+ /** A service guessed from an address (no-reply, alerts@, newsletters…): not someone I write with. */
440
+ const isService = (email) => mailText.looksBulk({ fromEmail: email }) || SERVICE.test(String(email).split('@')[0]);
441
+
442
+ /** The Google contacts kept (google-contacts.js), of one account or all; `wait`: how long to wait for an account's first reading. Never a failure: none then. */
443
+ async function googleKept(wait, account) {
444
+ try { return await (await googleContacts()).contacts({ wait, account }); } catch { return { people: [], list: [], byEmail: new Map(), cards: [] }; }
445
+ }
446
+
447
+ /** Kept of a contact for a row of People: what tells one person from another at a glance. */
448
+ const ROW_FIELDS = ['company', 'title', 'starred'];
449
+ /** What a person's page shows besides, from every contact of theirs (Exchange, Google). */
450
+ const LIST_FIELDS = { phones: (x) => String(x.number).replace(/[^\d+]/g, ''), addresses: (x) => x.text.toLowerCase(), urls: (x) => x.url.toLowerCase(), relations: (x) => `${x.kind}:${x.name}`.toLowerCase(), dates: (x) => `${x.kind}:${x.date}` };
451
+ const ONE_FIELDS = ['company', 'title', 'department', 'nickname', 'birthday', 'note'];
452
+
453
+ /**
454
+ * The people of my mail and my address book: my contacts, whole (Exchange's, Google's saved ones: those without an
455
+ * address too), everyone I write with (the cache: most often first), and for a search Google's "other contacts" and
456
+ * the organisation's directory. Services (no-reply, newsletters, billing…) and my own addresses are left out of
457
+ * what the mail and Google's collecting suggest. A contact's own name (Exchange, a saved Google contact) is the one
458
+ * shown over the one of the mail. `all`: the whole book (up to 5000), else the `limit` (60) most written with.
459
+ * { people: [{ key, name, email, emails?, sources, n, saved?, starred?, company?, title?, phones? }], failed? }
460
+ */
461
+ export async function people(a = {}) {
462
+ const q = (str(a.q) || '').slice(0, 80);
463
+ const all = a.all === true && !q;
464
+ const limit = all ? 5000 : Math.min(200, Math.max(1, Number(a.limit) || 60));
465
+ const isMe = await myAddresses();
466
+ const failed = [];
467
+ const byKey = new Map();
468
+ const named = new Set(); // whose name is a contact's (not the mail's)
469
+ const needle = q.toLowerCase();
470
+ const matches = (c) => !needle || `${c.name || ''} ${c.nickname || ''} ${(c.emails || [c.email]).join(' ')} ${c.company || ''} ${(c.phones || []).map((x) => x.number).join(' ')}`.toLowerCase().includes(needle);
471
+ /**
472
+ * Under which key: an address of it already listed, else the one searched for, else its first; one without any,
473
+ * its own (`ref`). A contact of mine joins a row by a second address of theirs only when no other contact of mine
474
+ * is there: two people sharing an address (a family's) stay two.
475
+ */
476
+ const keyOf = (emails, ref) => {
477
+ const mine = emails.filter((e) => !isMe(e.toLowerCase()));
478
+ const free = (e) => { const row = byKey.get(e.toLowerCase()); return row && (!ref || !row.refs?.length || e.toLowerCase() === mine[0]?.toLowerCase()); };
479
+ const email = mine.find(free) || (needle && mine.find((e) => e.toLowerCase().includes(needle) && (!ref || !byKey.get(e.toLowerCase())?.refs?.length))) || mine.find((e) => !ref || !byKey.get(e.toLowerCase())?.refs?.length) || (ref ? '' : mine[0]);
480
+ return email ? { key: email.toLowerCase(), email, emails: mine } : ref ? { key: ref, email: '', emails: [] } : null;
481
+ };
482
+ const put = (p, source, { own = false, ref } = {}) => {
483
+ const at = keyOf((p.emails?.length ? p.emails : [p.email]).filter((e) => typeof e === 'string' && e.includes('@')), own ? ref : undefined);
484
+ if (!at) return;
485
+ // a service guessed from an address is left out of what the mail (or Google, collecting) suggests, never out of my contacts or the directory
486
+ if (at.email && !own && source !== 'directory' && isService(at.key)) return;
487
+ const cur = byKey.get(at.key) || { key: at.key, name: '', email: at.email, sources: [], n: 0 };
488
+ const name = p.name && p.name.toLowerCase() !== at.key ? p.name : '';
489
+ if (name && (!cur.name || (own && !named.has(at.key)))) { cur.name = name; if (own) named.add(at.key); }
490
+ if (own) { cur.saved = true; if (ref && !(cur.refs ||= []).includes(ref)) cur.refs.push(ref); }
491
+ if (!cur.sources.includes(source)) cur.sources.push(source);
492
+ cur.n += p.n || 0;
493
+ for (const k of ROW_FIELDS) if (p[k] && !cur[k]) cur[k] = p[k];
494
+ if (p.phones?.length && !cur.phones) cur.phones = p.phones;
495
+ const more = at.emails.filter((e) => e.toLowerCase() !== at.key && !(cur.emails || []).some((x) => x.toLowerCase() === e.toLowerCase()));
496
+ if (more.length) cur.emails = [...(cur.emails || []), ...more];
497
+ byKey.set(at.key, cur);
498
+ };
499
+ try { for (const p of mailCache.people(q, { limit: q ? 40 : 300 })) put(p, 'mail'); } catch { /* no cache: the servers still answer */ }
500
+ let google = { people: [], cards: [] };
501
+ // the accounts at once; each account's contacts kept a minute (a search is typed a letter at a time)
502
+ await Promise.all([...namesWithMail(loadConfig()).map(async (name) => {
503
+ try {
504
+ for (const c of await contactsOf(name)) if (matches(c)) put(c, 'contacts', { own: true, ref: refOf('x', name, c) });
505
+ } catch (e) { failed.push(`${name}: ${e.message}`); }
506
+ if (q.length >= 2) {
507
+ try { for (const p of await directory.resolveNames(name, q)) put(p, 'directory'); } catch { /* no directory there */ }
508
+ }
509
+ }), googleKept(4000).then((g) => { google = g; })]);
510
+ // the Google contacts: the saved ones whole; the "other contacts" (Google collecting whom I wrote with) for a search, or joining someone listed
511
+ for (const c of google.cards || []) if (matches(c)) put(c, 'google', { own: true, ref: refOf('g', c.account, c) });
512
+ for (const c of google.people) {
513
+ if (c.kind === 'saved' || !matches(c)) continue;
514
+ if (!needle && !c.emails.some((e) => byKey.has(e.toLowerCase()))) continue;
515
+ put(c, 'google');
516
+ }
517
+ // most written with first; among equals, a contact of my own before a stranger of the directory
518
+ const rank = (p) => p.n * 10 + (p.saved ? 2 : 0) + (p.sources.includes('mail') ? 1 : 0);
519
+ const list = [...byKey.values()].sort((x, y) => rank(y) - rank(x) || (x.name || x.email).localeCompare(y.name || y.email)).slice(0, limit);
520
+ return failed.length ? { people: list, failed } : { people: list };
521
+ }
522
+
523
+ /** A contact of mine by where it is kept: g (Google) or x (Exchange), its account and its own id (its name without one), each part as it is (ids tell case apart). */
524
+ const refOf = (where, account, c) => `${where}:${encodeURIComponent(account)}:${encodeURIComponent(c.id || `name:${c.name || ''}`)}`;
525
+ const REF = /^[gx]:[^:]{1,200}:[^:]{1,1600}$/;
526
+
527
+ const contactsKept = new Map(); // account → { at, list }
528
+ async function contactsOf(name) {
529
+ const k = contactsKept.get(name);
530
+ if (k && Date.now() - k.at < 60e3) return k.list;
531
+ const list = await directory.list(name);
532
+ contactsKept.set(name, { at: Date.now(), list });
533
+ return list;
534
+ }
535
+
536
+ /**
537
+ * One person, by an address of theirs or by the key People listed them under (one without an address): what is
538
+ * known of them from every contact of theirs (phones, addresses, birthday, note, links, groups…, where to change
539
+ * it in Google), and the mail with them, both ways (and where both of us were written to), newest first (up to 30).
540
+ */
541
+ export async function person(a = {}) {
542
+ const raw = str(a.key) || str(a.email) || '';
543
+ const byRef = REF.test(raw);
544
+ const key = byRef ? raw : raw.toLowerCase();
545
+ if (!byRef && (!key.includes('@') || key.length > 320)) throw new Error('person needs an email address or a key');
546
+ const failed = [];
547
+ const onError = (n, e) => failed.push(`${n}: ${e.message}`);
548
+ const N = 30; // the newest 30 of all
549
+ // The mail with them as this Mac has it at hand (its cache: the inbox of the last weeks), at once, for the page to
550
+ // show while the servers are asked (the same call without `quick`). Their addresses are the page's word here
551
+ // (it has them from the list): they only say which mail to list.
552
+ if (a.quick) {
553
+ const theirs = [...new Set([...(byRef ? [] : [key]), ...(Array.isArray(a.emails) ? a.emails : [])].filter((e) => typeof e === 'string' && e.includes('@') && e.length <= 320).map((e) => e.toLowerCase()))].slice(0, 4);
554
+ let mail = [];
555
+ try {
556
+ const names = namesWithMail(loadConfig()).filter((n) => mailCache.cachedAccounts().includes(n));
557
+ if (theirs.length && names.length) mail = mailCache.findCached(names, { withAny: theirs, limit: N }).map((m) => ({ ...m, folder: 'inbox' }));
558
+ } catch { /* none at hand */ }
559
+ return { person: { key, name: '', email: byRef ? '' : key, sources: [], n: 0 }, mail: withPreviews(mail), quick: true };
560
+ }
561
+ const listed = (await people(byRef ? { all: true } : { q: key, limit: 200 }).catch(() => ({ people: [] }))).people;
562
+ const row = listed.find((p) => p.key === key) || (!byRef && listed.find((p) => (p.emails || []).some((e) => e.toLowerCase() === key)));
563
+ // their own contacts: those the row was made of (never another's that merely shares an address)
564
+ const refs = new Set(row?.refs || (byRef ? [key] : [])); // (a contact no longer listed so: still itself)
565
+ const own = [];
566
+ if (refs.size) {
567
+ for (const name of namesWithMail(loadConfig())) {
568
+ try { for (const c of await contactsOf(name)) if (refs.has(refOf('x', name, c))) own.push({ ...c, from: 'exchange', account: name }); } catch { /* listed without it */ }
569
+ }
570
+ for (const c of (await googleKept(1500)).cards || []) if (refs.has(refOf('g', c.account, c))) own.push({ ...c, from: 'google' });
571
+ }
572
+ const first = own[0];
573
+ const detail = { ...(row || { key, name: first?.name || '', email: byRef ? first?.email || '' : key, sources: first ? [first.from === 'google' ? 'google' : 'contacts'] : [], n: 0, ...(first ? { saved: true } : {}) }) };
574
+ delete detail.refs;
575
+ for (const k of ONE_FIELDS) for (const c of own) if (!detail[k] && typeof c[k] === 'string' && c[k]) detail[k] = c[k];
576
+ for (const [k, same] of Object.entries(LIST_FIELDS)) {
577
+ const seen = new Set();
578
+ const out = [];
579
+ for (const c of own) for (const x of c[k] || []) { const id = same(x); if (id && !seen.has(id)) { seen.add(id); out.push(x); } }
580
+ if (out.length) detail[k] = out;
581
+ }
582
+ const groups = [...new Set(own.flatMap((c) => c.groups || []))];
583
+ if (groups.length) detail.groups = groups;
584
+ if (own.some((c) => c.starred)) detail.starred = true;
585
+ const g = own.find((c) => c.from === 'google' && typeof c.id === 'string' && c.id.startsWith('people/'));
586
+ if (g) detail.google = { account: g.account, url: `https://contacts.google.com/person/${encodeURIComponent(g.id.slice(7))}` };
587
+ // The mail with them, under all of their addresses (four at most), both ways: one search of what was received
588
+ // (from them, to them, or with them in copy) and one of what was sent (to them, or with them in copy).
589
+ const addresses = [...new Set([detail.email, ...(detail.emails || [])].filter(Boolean).map((e) => e.toLowerCase()))].slice(0, 4);
590
+ let mail = [];
591
+ if (addresses.length) {
592
+ const [got, sent] = await Promise.all([
593
+ mailPort.find(undefined, { limit: N, withAny: addresses, live: true }, onError).then((l) => l.map((m) => ({ ...m, folder: 'inbox' })), () => []),
594
+ mailPort.find(undefined, { limit: N, folder: 'sent', withAny: addresses, live: true }, onError).then((l) => l.map((m) => ({ ...m, folder: 'sent' })), () => [])
595
+ ]);
596
+ const seen = new Set();
597
+ mail = [...got, ...sent].filter((m) => !seen.has(m.id) && seen.add(m.id)).sort((x, y) => new Date(y.received) - new Date(x.received)).slice(0, N);
598
+ }
599
+ return { person: detail, mail: withPreviews(mail), ...(failed.length ? { failed } : {}) }; // (with what the cache has of each one's first words, as the quick answer has)
600
+ }
601
+
602
+ /**
603
+ * My day: the mail that waits, both ways, over the last `days` (1, 7 or 30):
604
+ * threads where someone waits on me (their message last, addressed to me,
605
+ * not bulk) and threads where I wait on someone (mine last, to someone
606
+ * else). The events ahead are the `events` op's. { waitingOnMe, waitingOnThem, failed? }
607
+ */
608
+ export async function myDay(a = {}) {
609
+ const days = [1, 7, 30].includes(Number(a.days)) ? Number(a.days) : 7;
610
+ const failed = [];
611
+ const onError = (name, e) => { const why = `${name}: ${e?.message || e}`; if (!failed.includes(why)) failed.push(why); };
612
+ // what someone sent in the last day may wait from before: a day's view looks two days back
613
+ const back = days === 1 ? 2 : days;
614
+ const memo = new Map(); // each account's mail is read once for both: the same window, to the millisecond
615
+ const sinceIso = new Date(Date.now() - back * 86400e3).toISOString();
616
+ const [me, them] = await Promise.all([
617
+ mail.awaitingReply({ account: str(a.account), days: back, limit: 60, includeCc: false, onError, memo, sinceIso }),
618
+ mail.awaitingThem({ account: str(a.account), days: back, limit: 30, onError, memo, sinceIso })
619
+ ]);
620
+ // a conversation I took part in, or a question, comes before the rest (statements, and what slipped past the bulk checks)
621
+ const weight = (t) => (t.myLastReplyAt ? 2 : 0) + (t.askedSomething ? 1 : 0);
622
+ const waitingOnMe = me.threads
623
+ .map((t, k) => ({ t, k })).sort((x, y) => weight(y.t) - weight(x.t) || x.k - y.k).slice(0, 30)
624
+ .map(({ t }) => ({ account: t.account, id: t.lastMessageId, subject: t.subject, from: t.from, fromEmail: t.fromEmail, received: t.received, messages: t.messages, isRead: t.isRead, asked: t.askedSomething, replied: !!t.myLastReplyAt, snippet: t.snippet }));
625
+ const waitingOnThem = them.threads.map((t) => ({ account: t.account, id: t.lastMessageId, subject: t.subject, to: t.to, sent: t.sent, messages: t.messages }));
626
+ return failed.length ? { waitingOnMe, waitingOnThem, failed } : { waitingOnMe, waitingOnThem };
627
+ }
628
+
629
+ /** Who an account writes as: { email, name }: the name set for it (displayName), else the one the directory has; '' when there is none. */
630
+ export async function whoami(a = {}) {
631
+ // the name the person gave this account, when they gave one
632
+ let own = '';
633
+ try { own = identity.displayNameOf(getAccount(loadConfig(), str(a.account) || undefined)); } catch { /* no such account: the call below says so */ }
634
+ return mail.whoami(str(a.account), own);
635
+ }
636
+
637
+ /**
638
+ * The files of the mail: every attachment of the messages that have one,
639
+ * newest first, each with the message it came in. `folder` is inbox
640
+ * (received, the default) or sent; `q` narrows by words of the file name,
641
+ * the subject or the body; `until` is the cursor of the previous page.
642
+ * Pictures that are part of a mail's text (logos, signatures) are left out.
643
+ * { items: [{ id, name, size, contentType, message }], cursor? }
644
+ */
645
+ export async function files(a = {}) {
646
+ const max = Math.min(50, Math.max(1, Number(a.limit) || 30)); // messages per page
647
+ const where = a.folder === 'sent' ? 'sent' : 'inbox';
648
+ const account = str(a.account);
649
+ const q = str(a.q);
650
+ const until = iso(a.until);
651
+ const index = await filesIndex();
652
+ // What is kept is of the accounts whose mail is cached, as they are now, and no older than each one's cache keeps
653
+ // (src/files-index.js keptAccounts): an account that is not cached has nothing of its files kept between two looks.
654
+ const { owners: allOwners, since } = await keptAccounts();
655
+ const owners = new Map([...allOwners].filter(([n]) => !account || n === account));
656
+ const untilMs = until ? Date.parse(until) : undefined;
657
+ const itemsOf = (rows) => rows.flatMap((e) => e.files.map((f) => ({ id: f.id, name: f.name, size: f.size, contentType: f.contentType || '', message: e.message })));
658
+ // What this Mac found the last times it looked (src/files-index.js): at once, for the page to show while the
659
+ // servers are asked again (the same call without `quick`). By words of the files' names and of their mail's
660
+ // subject and sender only: the servers also search the mail's text.
661
+ if (a.quick) {
662
+ const rows = index.page(where, { owners, since, until: untilMs, q, limit: max });
663
+ const out = { items: itemsOf(rows), quick: true };
664
+ if (rows.length >= max) out.cursor = new Date(rows[rows.length - 1].received - 1000).toISOString();
665
+ return out;
666
+ }
667
+ const failed = new Set(); // accounts that did not answer: nothing kept of theirs is touched
668
+ const messages = await across((onError) => mail.find(account, { limit: max, hasAttachments: true, folder: where, text: q, untilIso: until, live: true }, (name, e) => { failed.add(name); onError(name, e); }));
669
+ const byAccount = new Map();
670
+ for (const m of messages) byAccount.set(m.account, [...(byAccount.get(m.account) || []), m.id]);
671
+ const found = new Map(); // message → its attachments, where they could be read (not in it: not known, this time)
672
+ await Promise.all([...byAccount].map(async ([name, ids]) => {
673
+ try {
674
+ for (const [id, list] of await mail.attachmentsOf(name, ids)) found.set(id, list);
675
+ } catch { failed.add(name); /* that account's files are missing from this page */ }
676
+ }));
677
+ let more; // (when the page ends on what is kept by name, not on what the servers found: where the next one starts)
678
+ let rows = messages.map((m) => ({ account: m.account, id: m.id, received: Date.parse(m.received), message: m, known: found.has(m.id), files: (found.get(m.id) || []).filter((f) => !f.inline && f.name).map((f) => ({ id: f.id, name: f.name, size: f.size, contentType: f.contentType || '' })) }));
679
+ try {
680
+ const answered = [...owners.keys()].filter((n) => !failed.has(n));
681
+ const mine = rows.filter((r) => answered.includes(r.account) && Number.isFinite(r.received));
682
+ if (!q) {
683
+ // what is kept of the stretch this look covered, and was not found, is let go (not for a search, which finds only what matches)
684
+ // (What looks gone is asked of its server before it is let go: a listing is by arrival, not by date, and a mail
685
+ // put back in the folder makes the stretch look longer than what was looked at. A few at a look: the rest
686
+ // wait for the next one.)
687
+ const kept = index.rows(where, { owners });
688
+ const maybe = gone(kept, { messages: mine.map((r) => r.message), until: untilMs, answered }).map((id) => [Math.random(), id]).sort((x, y) => x[0] - y[0]).map(([, id]) => id).slice(0, 24); // (by chance: not the same ones every look)
689
+ if (maybe.length) {
690
+ const of = new Map(kept.map((e) => [e.id, e.account]));
691
+ const still = new Set();
692
+ const unsure = new Set(); // accounts that did not answer this: nothing of theirs is let go
693
+ await Promise.all([...new Set(maybe.map((id) => of.get(id)))].map(async (name) => {
694
+ try { for (const [id] of await mail.attachmentsOf(name, maybe.filter((id) => of.get(id) === name))) still.add(id); } catch { unsure.add(name); }
695
+ }));
696
+ index.remove(where, maybe.filter((id) => !still.has(id) && !unsure.has(of.get(id))));
697
+ }
698
+ index.remove(where, mine.filter((r) => r.known && !r.files.length).map((r) => r.id)); // (read, and only pictures of its text: no file)
699
+ }
700
+ index.put(where, mine.filter((r) => r.known && r.files.length && !(r.received < (since.get(r.account) ?? -Infinity))).map((r) => ({ ...r, owner: owners.get(r.account) })));
701
+ index.prune({ owners: allOwners, since });
702
+ // a search: the servers look in the mail's words, not in the names of its files. What is kept and matches by
703
+ // name (or subject, or sender) is among the answer too.
704
+ // (Of the stretch this page covers only: when the servers have more, down to their oldest here; the rest is the next page's.)
705
+ if (q) {
706
+ const have = new Set(rows.map((r) => r.id));
707
+ const floor = messages.length >= max ? Math.min(...rows.map((r) => r.received).filter(Number.isFinite)) : -Infinity;
708
+ const kept = index.page(where, { owners, since, until: untilMs, q, limit: max });
709
+ const named = kept.filter((e) => !have.has(e.id) && e.received >= floor);
710
+ rows = [...rows, ...named].sort((x, y) => y.received - x.received);
711
+ // (what is kept by that name fills a page, where the servers found less: there may be more, and it is the next
712
+ // page's; counted before what the servers also found is taken out of it)
713
+ if (kept.length >= max && messages.length < max) { rows = rows.slice(0, max); more = rows[rows.length - 1].received; }
714
+ }
715
+ } catch { /* looked at again next time */ }
716
+ const out = { items: itemsOf(rows.filter((r) => r.files.length)) };
717
+ if (messages.length >= max) out.cursor = new Date(new Date(messages[messages.length - 1].received).getTime() - 1000).toISOString();
718
+ else if (Number.isFinite(more)) out.cursor = new Date(more - 1000).toISOString();
719
+ return out;
720
+ }
721
+
722
+ /**
723
+ * People to write to, for what is being typed in To, Cc or Bcc.
724
+ * Without `directory`: who the cached mail knows and my Google contacts (kept here: instant, no network), ranked
725
+ * together (see suggestions); with `account`, the mail and the Google contacts of that account only. With it: the account's directory and contacts (Exchange; one request).
726
+ * { people: [{ name, email, source: 'mail' | 'google' | 'directory' }] }
727
+ */
728
+ export async function contacts(a = {}) {
729
+ const q = str(a.q);
730
+ if (!q || q.length > 80) return { people: [] };
731
+ if (!a.directory) {
732
+ let found = [];
733
+ try { found = mailCache.people(q, { accounts: str(a.account) ? [a.account] : undefined, limit: 30 }); } catch { /* no cache: the directory still answers */ }
734
+ // Google's are waited for only while none was ever read (a second and a half), else what is kept answers at once;
735
+ // writing from an account (or about its mail), that account's Google contacts only
736
+ return { people: suggestions(q, found, (await googleKept(1500, str(a.account))).list) };
737
+ }
738
+ if (q.length < 2) return { people: [] };
739
+ const found = await directory.resolveNames(str(a.account), q);
740
+ return { people: found.slice(0, 12).map(({ name, email }) => ({ name: name && name.toLowerCase() !== email.toLowerCase() ? name : '', email, source: 'directory' })) };
741
+ }
742
+
743
+ /**
744
+ * The suggestions for `q` from the mail (cache.people: { name, email, n }, n how much mail there is with them: theirs, and what they were in copy of) and the Google
745
+ * contacts (one entry per address), at most 12, deduplicated by address: how much we wrote counts most (on a
746
+ * log scale), then being a saved contact (worth a few mails), then an "other contact" (Google collected it),
747
+ * then the words typed starting a name or the address. A saved contact's name goes over the mail's.
748
+ */
749
+ export function suggestions(q, mail, google) {
750
+ const needle = String(q || '').trim().toLowerCase();
751
+ const by = new Map();
752
+ for (const p of mail || []) {
753
+ const key = String(p.email || '').toLowerCase();
754
+ if (!key.includes('@') || by.has(key)) continue;
755
+ by.set(key, { name: p.name || '', email: p.email, n: p.n || 0, kind: null, last: p.last });
756
+ }
757
+ for (const c of google || []) {
758
+ const key = String(c.email || '').toLowerCase();
759
+ if (!key.includes('@') || !(key.includes(needle) || String(c.name || '').toLowerCase().includes(needle))) continue;
760
+ if (c.kind !== 'saved' && isService(key)) continue;
761
+ const cur = by.get(key);
762
+ if (cur) {
763
+ if (c.kind === 'saved' && c.name) cur.name = c.name;
764
+ if (!cur.kind || c.kind === 'saved') cur.kind = c.kind;
765
+ } else by.set(key, { name: c.name || '', email: c.email, n: 0, kind: c.kind });
766
+ }
767
+ const starts = (p) => `${p.name} `.toLowerCase().split(/[\s.'-]+/).some((w) => w && w.startsWith(needle)) || p.email.toLowerCase().startsWith(needle);
768
+ const score = (p) => Math.log2(1 + p.n) * 10 + (p.kind === 'saved' ? 20 : p.kind === 'other' ? 5 : 0) + (starts(p) ? 6 : 0);
769
+ return [...by.values()]
770
+ .map((p) => ({ p, s: score(p) }))
771
+ .sort((x, y) => y.s - x.s || (x.p.name || x.p.email).localeCompare(y.p.name || y.p.email))
772
+ .slice(0, 12)
773
+ // (`saved`: a contact the person saved; `other`: one Google collected because the person wrote to them. Someone
774
+ // who only ever wrote in has neither: `n` counts their mail too, and says nothing of whom the person knows.)
775
+ .map(({ p }) => ({ name: p.name && p.name.toLowerCase() !== p.email.toLowerCase() ? p.name : '', email: p.email, source: p.kind ? 'google' : 'mail', ...(p.last ? { last: p.last } : {}), ...(p.kind === 'saved' ? { saved: true } : {}), ...(p.kind === 'other' ? { other: true } : {}) }));
776
+ }
777
+
778
+ /** How long a verification code is worth offering: most are dead after ten minutes. */
779
+ const CODE_MINUTES = 15;
780
+
781
+ /**
782
+ * Adds `code` to mail of the last minutes that carries a verification code
783
+ * (see otp.js), read in its subject and in its body where the cache has it.
784
+ * Only here, for the panel: the MCP tools list mail without it.
785
+ */
786
+ function withCodes(items) {
787
+ const now = Date.now();
788
+ // from the last minutes, and not from the future beyond what two clocks differ by: a mail dated tomorrow would keep its code a day
789
+ const recent = items.filter((i) => { const at = new Date(i.received).getTime(); return at >= now - CODE_MINUTES * 60e3 && at <= now + 2 * 60e3; });
790
+ if (!recent.length) return items;
791
+ let bodies = new Map();
792
+ try { bodies = mailCache.texts(recent.map((i) => i.id), 12000); } catch { /* subjects alone, then */ }
793
+ const codes = new Map();
794
+ for (const i of recent) { const code = findCode(i.subject, bodies.get(i.id)); if (code) codes.set(i.id, code); }
795
+ return codes.size ? items.map((i) => (codes.has(i.id) ? { ...i, code: codes.get(i.id) } : i)) : items;
796
+ }
797
+
798
+ /** Adds `threadCount` to the items of a thread the cache knows more than one message of (sent ones included). */
799
+ function withThreadCounts(items) {
800
+ try {
801
+ const counts = mailCache.threadCounts(items);
802
+ const of = (i) => counts.get(`${i.account}|${i.conversationId}`) || 0;
803
+ return counts.size ? items.map((i) => (i.conversationId && of(i) > 1 ? { ...i, threadCount: of(i) } : i)) : items;
804
+ } catch {
805
+ return items;
806
+ }
807
+ }
808
+
809
+ /** Keep the sent messages of a listing in the cache's thread table (accounts that are cached only). */
810
+ function noteSent(account, items) {
811
+ try {
812
+ if (account && items.length && mailCache.cachedAccounts().includes(account) && mailCache.available()) mailCache.noteSent(account, items);
813
+ } catch { /* the count on the list waits for the daemon's next pass */ }
814
+ }
815
+
816
+ /** After a send: the new message is in Sent a moment later, and the thread it belongs to holds one more. */
817
+ function noteSentSoon(id) {
818
+ const { account } = mailText.splitId(id);
819
+ try { if (!mailCache.cachedAccounts().includes(account)) return; } catch { return; }
820
+ const look = () => mail.findIn(id, { folder: 'sent', limit: 10 }).then((items) => noteSent(account, items), () => {});
821
+ for (const ms of [1500, 10000]) setTimeout(look, ms).unref?.();
822
+ }
823
+
824
+ /**
825
+ * Attach a file (base64 in `data`) to a draft. With `inline` and a `contentId` it is a picture of the text,
826
+ * shown where the body says <img src="cid:<contentId>">. Returns the draft's new changeKey and the attachment.
827
+ */
828
+ export async function addAttachment(a = {}) {
829
+ if (!str(a.draftId) || !str(a.name) || typeof a.data !== 'string') throw new Error('addAttachment needs draftId, name and data');
830
+ const size = Math.floor((a.data.length * 3) / 4);
831
+ if (size > MAX_UPLOAD) throw new Error(`"${a.name}" is over 20 MB`);
832
+ const inline = !!a.inline;
833
+ if (inline && !/^[\w.@-]{1,120}$/.test(String(a.contentId || ''))) throw new Error('addAttachment: an inline picture needs a plain contentId');
834
+ const r = await mail.addAttachment(a.draftId, a.changeKey || '', { name: a.name, contentBase64: a.data, contentType: str(a.contentType) || 'application/octet-stream', ...(inline ? { inline: true, contentId: a.contentId } : {}) });
835
+ mail.noteRemoved(a.draftId);
836
+ return { draftId: r.draftId || a.draftId, changeKey: r.changeKey || '', attachment: { id: r.attachmentId || a.name, name: a.name, size, contentType: str(a.contentType) || '' } };
837
+ }
838
+
839
+ /** Remove one attachment from a draft. Returns the draft's new changeKey. */
840
+ export async function removeAttachment(a = {}) {
841
+ if (!str(a.draftId) || !str(a.attachmentId)) throw new Error('removeAttachment needs draftId and attachmentId');
842
+ const r = await mail.removeAttachment(a.draftId, a.changeKey || '', a.attachmentId);
843
+ mail.noteRemoved(a.draftId);
844
+ return { draftId: r.draftId || a.draftId, changeKey: r.changeKey || '' };
845
+ }
846
+
847
+ /** Send a draft saved by saveDraft. This is the one operation that mails other people. */
848
+ export async function sendDraft(a = {}) {
849
+ if (!str(a.draftId)) throw new Error('sendDraft needs a draftId');
850
+ await mail.sendItem(a.draftId, a.changeKey || '');
851
+ mail.noteRemoved(a.draftId);
852
+ noteSentSoon(a.draftId);
853
+ return { sent: true };
854
+ }
855
+
856
+ /** Move a draft to Deleted Items. */
857
+ export async function deleteDraft(a = {}) {
858
+ if (!str(a.draftId)) throw new Error('deleteDraft needs a draftId');
859
+ await mail.deleteItem(a.draftId, a.changeKey || '');
860
+ mail.noteRemoved(a.draftId);
861
+ return { ok: true };
862
+ }
863
+
864
+ // --- calendar -------------------------------------------------------------------
865
+
866
+ const DAY_MS = 86400e3;
867
+ const MAX_SPAN_DAYS = 100; // a month's grid is six weeks; a year is asked for a quarter at a time
868
+ // where a meeting happens online, when the invitation says so
869
+ const JOIN = /https?:\/\/[^\s<>"')\]]*(?:teams\.microsoft\.com\/l\/meetup-join|teams\.live\.com\/meet|zoom\.us\/[jw]\/|meet\.google\.com\/|webex\.com\/(?:meet|join|[\w-]+\/j\.php)|gotomeet\.me\/|gotomeeting\.com\/join|whereby\.com\/|chime\.aws\/)[^\s<>"')\]]*/i;
870
+ const joinUrl = (...texts) => { for (const t of texts) { const m = JOIN.exec(String(t || '')); if (m) return m[0]; } return null; };
871
+
872
+ /**
873
+ * Events between `start` and `end` (ISO; default: today and the six days
874
+ * after), soonest first, from every calendar of every calendar account
875
+ * (unless `account` is given): the person's own, and the shared ones they
876
+ * have open. `calendars` lists them; one that could not be read is `failed`
877
+ * there. An account that fails is skipped and named in `failed`; when every
878
+ * one fails that is the error.
879
+ * { items, calendars, start, end, failed? }
880
+ */
881
+ export async function events(a = {}) {
882
+ const from = iso(a.start) || new Date(new Date().setHours(0, 0, 0, 0)).toISOString();
883
+ const to = iso(a.end) || new Date(new Date(from).getTime() + 7 * DAY_MS).toISOString();
884
+ if (new Date(to) <= new Date(from)) throw new Error('events: end is not after start');
885
+ if (new Date(to) - new Date(from) > MAX_SPAN_DAYS * DAY_MS) throw new Error(`events: at most ${MAX_SPAN_DAYS} days at a time`);
886
+ const failed = [];
887
+ const names = calendar.accounts(str(a.account));
888
+ const { items, calendars } = await calendar.list({ account: str(a.account), start: from, end: to, limit: Math.min(500, Math.max(1, Number(a.limit) || 200)), onError: (name, e) => failed.push(`${name}: ${e.message}`) });
889
+ if (failed.length >= names.length) throw new Error(failed.join('; '));
890
+ return { items: items.map((e) => ({ ...e, joinUrl: joinUrl(e.location) })), calendars, start: from, end: to, ...(failed.length ? { failed } : {}) };
891
+ }
892
+
893
+ /** One event in full: description (text), attendees with their answers, and `joinUrl` when it is held online. */
894
+ export async function event(a = {}) {
895
+ if (!str(a.id)) throw new Error('event needs an id');
896
+ const e = await calendar.read(a.id);
897
+ return { ...e, joinUrl: joinUrl(e.location, e.body) };
898
+ }
899
+
900
+ /**
901
+ * Answer an invitation: response 'accept' | 'tentative' | 'decline', with an
902
+ * optional `message`. The organizer is told (that is mail to another person).
903
+ */
904
+ export async function respondToEvent(a = {}) {
905
+ if (!str(a.id)) throw new Error('respondToEvent needs an id');
906
+ if (!['accept', 'tentative', 'decline'].includes(a.response)) throw new Error('respondToEvent: response is accept, tentative or decline');
907
+ await calendar.respond(a.id, a.response, { message: str(a.message), notify: true });
908
+ return { ok: true };
909
+ }
910
+
911
+ const SHOW_AS = ['Free', 'Tentative', 'Busy', 'OOF', 'WorkingElsewhere'];
912
+
913
+ /**
914
+ * Create an event (no `id`) or change one (`id`; only the fields passed
915
+ * change). Fields: subject, start, end (ISO), allDay (then start is the
916
+ * midnight of the first day and end the midnight after the last, local
917
+ * time), location, body (text), attendees, optionalAttendees (addresses),
918
+ * reminderMinutes (null: none), showAs. For a new event `calendar` is the
919
+ * key of a calendar that is `writable` (events → calendars): one of my own,
920
+ * or a shared one I may add to; the default one otherwise.
921
+ * With attendees it is a meeting: invitations, and later updates, are mailed.
922
+ * { id, changeKey, invitationsSent }
923
+ */
924
+ export async function saveEvent(a = {}) {
925
+ const f = {};
926
+ const text = (k, max) => {
927
+ if (a[k] === undefined) return;
928
+ if (typeof a[k] !== 'string' || a[k].length > max) throw new Error(`event ${k}: text, at most ${max} characters`);
929
+ f[k] = a[k];
930
+ };
931
+ text('subject', 255);
932
+ text('location', 255);
933
+ text('body', 100000);
934
+ for (const k of ['start', 'end']) {
935
+ if (a[k] === undefined) continue;
936
+ if (!iso(a[k])) throw new Error(`event ${k}: not a date`);
937
+ f[k] = iso(a[k]);
938
+ }
939
+ if (f.start && f.end && new Date(f.end) <= new Date(f.start)) throw new Error('the event ends before it starts');
940
+ if (a.allDay !== undefined) f.allDay = !!a.allDay;
941
+ if (a.attendees !== undefined) f.attendees = emails(a.attendees, 'attendees');
942
+ if (a.optionalAttendees !== undefined) f.optionalAttendees = emails(a.optionalAttendees, 'optional attendees');
943
+ if (a.reminderMinutes !== undefined) {
944
+ const m = a.reminderMinutes === null ? -1 : Number(a.reminderMinutes);
945
+ if (!Number.isFinite(m) || m > 40320) throw new Error('event reminder: minutes before the start, or null');
946
+ f.reminderMinutes = m;
947
+ }
948
+ if (a.showAs !== undefined) {
949
+ if (!SHOW_AS.includes(a.showAs)) throw new Error(`event showAs: one of ${SHOW_AS.join(', ')}`);
950
+ f.showAs = a.showAs;
951
+ }
952
+
953
+ if (!str(a.id)) {
954
+ if (!str(f.subject)) throw new Error('give the event a title');
955
+ if (!f.start || !f.end) throw new Error('an event needs a start and an end');
956
+ // the key of a calendar: "<account>|default", "<account>|<its id>", or "<account>|mailbox:<owner>" for one shared with me
957
+ const [account, where] = str(a.calendar) ? [a.calendar.slice(0, a.calendar.indexOf('|')), a.calendar.slice(a.calendar.indexOf('|') + 1)] : [str(a.account), 'default'];
958
+ const shared = where.startsWith('mailbox:');
959
+ let r;
960
+ try {
961
+ r = await calendar.create({ ...f, reminderMinutes: f.reminderMinutes ?? 15, account: account || undefined, calendar: where === 'default' ? undefined : shared ? where.slice(8) : where, allowShared: true, notify: true });
962
+ } catch (e) {
963
+ if (shared && /AccessDenied|permission|not have (?:the )?(?:rights|access)/i.test(e.message)) throw new Error('that calendar does not let you add events to it');
964
+ throw e;
965
+ }
966
+ return { id: r.id, changeKey: r.changeKey || '', invitationsSent: !!r.invitationsSent };
967
+ }
968
+ if (f.subject !== undefined && !str(f.subject)) throw new Error('give the event a title');
969
+ if (!Object.keys(f).length) throw new Error('saveEvent: nothing to change');
970
+ return calendar.update(a.id, f, () => loadConfig().timeZone);
971
+ }
972
+
973
+ /** Delete an event (to Deleted Items). A meeting I organize is cancelled: the people invited are told. */
974
+ export async function deleteEvent(a = {}) {
975
+ if (!str(a.id)) throw new Error('deleteEvent needs an id');
976
+ await calendar.remove(a.id, { notify: true });
977
+ return { ok: true };
978
+ }
979
+
980
+ // --- contacts added ----------------------------------------------------------------
981
+
982
+ /** The accounts whose Google sign-in allows adding contacts, the default one first; and those that only allow reading them. */
983
+ async function contactBooksOf() {
984
+ const { googleAccessKnown } = await import('./google-signin.js');
985
+ const cfg = loadConfig();
986
+ const books = [], readOnly = [];
987
+ for (const a of Object.values(cfg.accounts || {})) {
988
+ if (calendarProvider(a) !== 'google') continue;
989
+ const g = googleAccessKnown(a.name);
990
+ if (g.state === 'expired' || g.state === 'unknown' || g.state === 'not-signed-in') continue;
991
+ if (g.addContacts) books.push({ account: a.name, label: labelOf(a), ...(g.email ? { email: g.email } : {}) });
992
+ else if (g.contacts) readOnly.push(a.name);
993
+ }
994
+ books.sort((x, y) => Number(y.account === cfg.defaultAccount) - Number(x.account === cfg.defaultAccount));
995
+ return { books, readOnly };
996
+ }
997
+
998
+ /** Where a contact can be added: { books: [{ account, label, email? }], readOnly: [account] } (signed in to Google, contacts allowed only to be read: signed in again, they can be added). */
999
+ export async function contactBooks() {
1000
+ return contactBooksOf();
1001
+ }
1002
+
1003
+ /**
1004
+ * Adds a contact to an account's own Google contacts: { account?, contact: { name, emails, phones, addresses, company,
1005
+ * title, note, urls } } (see mailcore's googleCreateContact). Without an account, the first that allows it (the
1006
+ * default one first). → { id, account, name }. Its Google contacts are read again soon after.
1007
+ */
1008
+ export async function addContact(a = {}) {
1009
+ const c = a.contact;
1010
+ if (!c || typeof c !== 'object' || Array.isArray(c)) throw new Error('addContact needs a contact');
1011
+ const { books, readOnly } = await contactBooksOf();
1012
+ const asked = str(a.account);
1013
+ const book = asked ? books.find((b) => b.account === asked) : books[0];
1014
+ if (!book) {
1015
+ if (asked ? readOnly.includes(asked) : readOnly.length) throw Object.assign(new Error(`Google allows reading the contacts of ${asked || readOnly[0]}, not adding to them: sign in to Google again (Settings, Accounts) to allow it`), { code: 'GOOGLE_SCOPE' });
1016
+ throw new Error(asked ? `${asked} cannot have contacts added (no Google sign-in)` : 'No account signed in to Google to add the contact to');
1017
+ }
1018
+ let made;
1019
+ try {
1020
+ made = await directory.addToGoogle(book.account, c);
1021
+ } catch (e) {
1022
+ // (no answer in time: Google may have made it all the same; pressing Add again would make a second)
1023
+ if (/timeout|timed out|aborted|fetch failed|network|ECONNRESET|socket/i.test(`${e?.name} ${e?.message}`)) throw Object.assign(new Error('Google did not answer in time: the contact may have been added. Check Google Contacts before adding it again.'), { code: 'GOOGLE_UNSURE' });
1024
+ throw e;
1025
+ }
1026
+ const { contactsChanged } = await import('./google-contacts.js');
1027
+ contactsChanged(book.account);
1028
+ return { id: made.id, account: book.account, name: made.name || made.email || '' };
1029
+ }
1030
+
1031
+ // --- sender pictures --------------------------------------------------------------
1032
+
1033
+ /**
1034
+ * Pictures of senders, for the rows the panel shows: { items: [{ email, id? }] }
1035
+ * (`id`: the message beside which it is shown, for a brand's picture).
1036
+ * → { pictures: { "<email>\n<id>": imageKey | null }, images: { [imageKey]: { src, fit } }, pending? }
1037
+ */
1038
+ let instanceMade = false;
1039
+ export async function senderPictures(a = {}) {
1040
+ instanceMade = true;
1041
+ return (await pictures()).lookup(Array.isArray(a.items) ? a.items : []);
1042
+ }
1043
+
1044
+ /** { enabled, gravatar, otherIcons }: sender pictures at all (on by default), Gravatar/Libravatar among them (off by default), the icons of other senders' domains through DuckDuckGo (on by default). */
1045
+ export function pictureSettings() {
1046
+ return picturesOf(loadConfig());
1047
+ }
1048
+
1049
+ /** { hidden }: the calendars (by key) the panel does not show, the same on every device; null when never chosen here. */
1050
+ export function calendarView() {
1051
+ const raw = loadConfig().calendarsHidden;
1052
+ return { hidden: Array.isArray(raw) ? raw.filter((k) => typeof k === 'string') : null };
1053
+ }
1054
+
1055
+ /** The calendars not shown: a list of keys (the calendars' own, as `events` gives them). Returns calendarView(). */
1056
+ export function setCalendarView(a = {}) {
1057
+ const hidden = a.hidden;
1058
+ if (!Array.isArray(hidden) || hidden.length > 500 || hidden.some((k) => typeof k !== 'string' || !k || k.length > 400)) throw new Error('hidden is a list of calendar keys');
1059
+ const next = [...new Set(hidden)];
1060
+ updateConfig((raw) => {
1061
+ if (JSON.stringify(raw.calendarsHidden) === JSON.stringify(next)) return false;
1062
+ raw.calendarsHidden = next;
1063
+ });
1064
+ return calendarView();
1065
+ }
1066
+
1067
+ /** Change either; only what is passed changes. Returns pictureSettings(). */
1068
+ export function setPictureSettings(a = {}) {
1069
+ updateConfig((raw) => {
1070
+ const cur = raw.pictures && typeof raw.pictures === 'object' && !Array.isArray(raw.pictures) ? raw.pictures : {};
1071
+ const next = { ...cur };
1072
+ if (a.enabled !== undefined) next.enabled = !!a.enabled;
1073
+ if (a.gravatar !== undefined) next.gravatar = !!a.gravatar;
1074
+ if (a.otherIcons !== undefined) next.otherIcons = !!a.otherIcons;
1075
+ if (JSON.stringify(next) === JSON.stringify(cur)) return false;
1076
+ raw.pictures = next;
1077
+ });
1078
+ // the lookups of this process see it at once: what is queued stops when turned off
1079
+ if (instanceMade) pictures().then((p) => p.invalidate(), () => {});
1080
+ return pictureSettings();
1081
+ }
1082
+
1083
+ // --- settings: signatures, and the name an account writes as ---------------------
1084
+ //
1085
+ // identity.js. A signature is HTML of the person's own: it is stored as given
1086
+ // and cleaned by whoever shows or sends it.
1087
+
1088
+ /** { signatures, accounts, defaultAccount, details } */
1089
+ export function signatures() { return identity.identities(); }
1090
+ // `was` (what the form started from) goes along: changed elsewhere since, nothing is saved over it
1091
+ export function saveSignature(a = {}) { return identity.saveSignature({ ...(a.id !== undefined ? { id: a.id } : {}), ...(a.name !== undefined ? { name: a.name } : {}), ...(a.html !== undefined ? { html: a.html } : {}), ...(a.template !== undefined ? { template: a.template } : {}), ...(a.was !== undefined ? { was: a.was } : {}) }); }
1092
+ export function setSignatureDetails(a = {}) { return identity.setSignatureDetails({ details: a.details, signatures: a.signatures, ...(a.was !== undefined ? { was: a.was } : {}) }); }
1093
+ export function removeSignature(a = {}) { return identity.removeSignature({ id: a.id }); }
1094
+ export function setIdentity(a = {}) { return identity.setIdentity({ account: a.account, ...(a.name !== undefined ? { name: a.name } : {}), ...(a.signature !== undefined ? { signature: a.signature } : {}) }); }
1095
+
1096
+ // --- settings: rules and quiet hours --------------------------------------------
1097
+ //
1098
+ // The panel edits what a rule matches and how it alerts: name, senders,
1099
+ // subjects, account, sound, notify, enabled. What a rule runs (wake, webhook,
1100
+ // exec) is never set or changed from here: a browser extension that could
1101
+ // write those could run commands on this machine. Such rules are listed with
1102
+ // `runs`, keep those fields through an edit, and are written in rules.yaml.
1103
+
1104
+ const { RUNS } = rulesStore;
1105
+ const TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
1106
+ /** "7:00" is a time to the daemon too: shown as the 07:00 it means. */
1107
+ const clock = (v, fallback) => { const t = String(v ?? '').trim().padStart(5, '0'); return TIME.test(t) ? t : fallback; };
1108
+ const listText = (v) => (Array.isArray(v) ? v.join(', ') : String(v ?? '')).trim();
1109
+ /** What says which mail a rule is for. On a rule that runs something, that is part of what it runs. */
1110
+ const MATCH = ['name', 'senders', 'subjects', 'account'];
1111
+
1112
+ function ruleView(r, i) {
1113
+ r = r || {};
1114
+ return {
1115
+ n: i + 1,
1116
+ rev: rulesStore.revOf(r),
1117
+ name: String(r.name ?? ''),
1118
+ enabled: r.enabled !== false,
1119
+ senders: listText(r.senders),
1120
+ subjects: listText(r.subjects),
1121
+ account: listText(r.account),
1122
+ // a name of the user's own (a key of config.sounds) is shown as it is, and kept
1123
+ sound: r.sound === false ? false : typeof r.sound === 'string' && r.sound ? r.sound : 'chime',
1124
+ notify: r.notify !== false,
1125
+ runs: RUNS.filter((k) => r[k])
1126
+ };
1127
+ }
1128
+
1129
+ /** { rules, quietHours, sounds }: every rule in file order (the first that matches a mail alerts), disabled ones too. */
1130
+ export function rules() {
1131
+ const doc = rulesStore.listRules();
1132
+ const q = doc.quietHours || {};
1133
+ return {
1134
+ rules: doc.rules.map(ruleView),
1135
+ quietHours: { enabled: !!q.enabled, start: clock(q.start, '18:00'), end: clock(q.end, '08:00') },
1136
+ sounds: rulesStore.SOUNDS
1137
+ };
1138
+ }
1139
+
1140
+ /**
1141
+ * Which rule the panel means: its position `n`, and `expect`, the `rev` it
1142
+ * was shown with. The file is also edited by hand, so the store refuses when
1143
+ * the rule at that position is no longer that one.
1144
+ */
1145
+ function ruleRef(a) {
1146
+ const n = Number(a.n);
1147
+ if (!Number.isInteger(n) || n < 1 || typeof a.expect !== 'string') throw new Error(rulesStore.CHANGED);
1148
+ return { n, expect: a.expect };
1149
+ }
1150
+
1151
+ /** The fields of a rule the panel may set, checked. Only the keys present in `a` come back. */
1152
+ function ruleFields(a) {
1153
+ const out = {};
1154
+ const text = (k, max) => {
1155
+ if (a[k] === undefined) return;
1156
+ // one line of plain text: a rule's name goes into the prompt and the environment of what a rule runs
1157
+ if (typeof a[k] !== 'string' || a[k].length > max || /[\u0000-\u001f\u007f\u2028\u2029]/.test(a[k])) throw new Error(`rule ${k}: one line of text, at most ${max} characters`);
1158
+ out[k] = a[k].trim();
1159
+ };
1160
+ text('name', 80);
1161
+ text('senders', 2000);
1162
+ text('subjects', 2000);
1163
+ text('account', 200);
1164
+ if (a.sound !== undefined) {
1165
+ if (a.sound !== false && (typeof a.sound !== 'string' || a.sound.length > 80)) throw new Error('rule sound: a sound name, or false');
1166
+ out.sound = a.sound;
1167
+ }
1168
+ for (const k of ['notify', 'enabled']) if (a[k] !== undefined) out[k] = !!a[k];
1169
+ return out;
1170
+ }
1171
+
1172
+ function knownSound(sound) {
1173
+ if (sound !== false && !rulesStore.SOUNDS.includes(sound)) throw new Error(`sound must be one of: ${rulesStore.SOUNDS.join(', ')} (or false)`);
1174
+ }
1175
+
1176
+ function knownAccounts(text) {
1177
+ const known = listAccounts().map((x) => x.name);
1178
+ for (const name of String(text || '').split(/[,;]/).map((x) => x.trim()).filter(Boolean)) if (!known.includes(name)) throw new Error(`no account named "${name}"`);
1179
+ }
1180
+
1181
+ /**
1182
+ * Create a rule (no `n`) or change the one at position `n` (with `expect`,
1183
+ * the `rev` it was shown with). Only the fields passed change, and on a rule
1184
+ * that runs something, not the ones that say which mail it is for. Returns
1185
+ * rules().
1186
+ */
1187
+ export function saveRule(a = {}) {
1188
+ const f = ruleFields(a);
1189
+ if (a.n === undefined) {
1190
+ if (!f.name) throw new Error('give the rule a name');
1191
+ if (!mailText.splitList(f.senders).length && !mailText.splitList(f.subjects).length) throw new Error('say who the mail is from, or what its subject contains');
1192
+ knownAccounts(f.account);
1193
+ const rule = { name: f.name };
1194
+ if (f.account) rule.account = f.account;
1195
+ if (f.senders) rule.senders = f.senders;
1196
+ if (f.subjects) rule.subjects = f.subjects;
1197
+ rule.sound = f.sound ?? 'chime';
1198
+ knownSound(rule.sound);
1199
+ if (f.notify === false) rule.notify = false;
1200
+ if (f.enabled === false) rule.enabled = false;
1201
+ rulesStore.addRule(rule);
1202
+ return rules();
1203
+ }
1204
+ const { n, expect } = ruleRef(a);
1205
+ rulesStore.updateRule(String(n), (raw) => {
1206
+ const cur = ruleView(raw, n - 1);
1207
+ // only what differs is written, so a hand-written form (a YAML list of senders, say) survives an edit of something else
1208
+ const patch = {};
1209
+ for (const [k, v] of Object.entries(f)) if (v !== cur[k]) patch[k] = v;
1210
+ if (cur.runs.length && MATCH.some((k) => k in patch)) throw new Error('this rule also runs something: its name and the mail it is for are changed in rules.yaml');
1211
+ for (const k of MATCH) if (patch[k] === '') patch[k] = null; // emptied: the field goes
1212
+ if (patch.name === null && cur.name) throw new Error('give the rule a name');
1213
+ if (patch.account) knownAccounts(patch.account);
1214
+ if (patch.sound !== undefined) knownSound(patch.sound);
1215
+ const next = { ...cur, ...f };
1216
+ if (!mailText.splitList(next.senders).length && !mailText.splitList(next.subjects).length) throw new Error('say who the mail is from, or what its subject contains');
1217
+ return patch;
1218
+ }, { expect });
1219
+ return rules();
1220
+ }
1221
+
1222
+ export function removeRule(a = {}) {
1223
+ const { n, expect } = ruleRef(a);
1224
+ rulesStore.removeRule(String(n), { expect });
1225
+ return rules();
1226
+ }
1227
+
1228
+ /** Move the rule at `n` to position `to` (1-based). */
1229
+ export function moveRule(a = {}) {
1230
+ if (!Number.isInteger(a.to)) throw new Error('moveRule needs the position to move to');
1231
+ const { n, expect } = ruleRef(a);
1232
+ rulesStore.moveRule(String(n), a.to, { expect });
1233
+ return rules();
1234
+ }
1235
+
1236
+ /** Quiet hours: { enabled?, start?, end? } with times as "HH:MM". Returns rules(). */
1237
+ export function setQuietHours(a = {}) {
1238
+ for (const k of ['start', 'end']) if (a[k] !== undefined && (typeof a[k] !== 'string' || !TIME.test(a[k]))) throw new Error(`quiet hours: ${k} is a time like 18:00`);
1239
+ rulesStore.setQuietHours({ enabled: a.enabled === undefined ? undefined : !!a.enabled, start: a.start, end: a.end });
1240
+ return rules();
1241
+ }
1242
+
1243
+ /** Play one of the alert sounds on this Mac, the way a matching rule would. */
1244
+ export function playSound(a = {}) {
1245
+ const config = loadConfig();
1246
+ // the built-in alerts, and the names the user gave their own in config.sounds
1247
+ const own = typeof a.sound === 'string' && Object.hasOwn(config.sounds || {}, a.sound);
1248
+ if (!rulesStore.SOUNDS.includes(a.sound) && !own) throw new Error(`sound must be one of: ${rulesStore.SOUNDS.join(', ')}`);
1249
+ play(a.sound, config);
1250
+ return { ok: true };
1251
+ }