@wirecat/cli-core 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/CHANGELOG.md +144 -0
  2. package/THIRD_PARTY_NOTICES +43 -0
  3. package/dist/background/daily-archive-timer.d.ts +1 -1
  4. package/dist/cli/account-remove.d.ts +3 -0
  5. package/dist/cli/account-remove.js +1 -1
  6. package/dist/cli/documents/index.d.ts +2 -1
  7. package/dist/cli/documents/index.js +4 -1
  8. package/dist/cli/documents/words.d.ts +1 -1
  9. package/dist/cli/domain-lists-command.d.ts +16 -0
  10. package/dist/cli/domain-lists-command.js +88 -0
  11. package/dist/cli/index.d.ts +4 -3
  12. package/dist/cli/index.js +4 -3
  13. package/dist/cli/messenger/conversation-answers.d.ts +2 -0
  14. package/dist/cli/messenger/message-answers.d.ts +2 -0
  15. package/dist/cli/messenger/message-items.js +2 -0
  16. package/dist/cli/messenger/message-writes.d.ts +4 -0
  17. package/dist/cli/messenger/search-answers.js +2 -0
  18. package/dist/cli/model-catalogue-command.d.ts +6 -0
  19. package/dist/cli/model-catalogue-command.js +1 -1
  20. package/dist/cli/oauth-session.d.ts +38 -4
  21. package/dist/cli/oauth-session.js +72 -25
  22. package/dist/cli/shared-command-exports.d.ts +4 -0
  23. package/dist/cli/shared-command-exports.js +6 -0
  24. package/dist/cli/token-session.d.ts +9 -3
  25. package/dist/cli/token-session.js +34 -3
  26. package/dist/domain/domain-lists.d.ts +86 -0
  27. package/dist/domain/domain-lists.js +110 -0
  28. package/dist/domain/free-mail-domains.generated.d.ts +1 -0
  29. package/dist/domain/free-mail-domains.generated.js +4 -0
  30. package/dist/domain/models.d.ts +5 -0
  31. package/dist/domain/organization-sectors.d.ts +9 -3
  32. package/dist/domain/organization-sectors.generated.d.ts +1 -0
  33. package/dist/domain/organization-sectors.generated.js +1 -0
  34. package/dist/domain/organization-sectors.js +16 -3
  35. package/dist/domain/person-kinds.d.ts +6 -1
  36. package/dist/domain/person-kinds.js +5 -0
  37. package/dist/entities/contact-context.d.ts +4 -0
  38. package/dist/entities/conversation-results.d.ts +4 -0
  39. package/dist/entities/domain-list.d.ts +27 -0
  40. package/dist/entities/domain-list.js +28 -0
  41. package/dist/entities/evidence.d.ts +16 -0
  42. package/dist/entities/index.d.ts +56 -2
  43. package/dist/entities/index.js +3 -1
  44. package/dist/entities/knowledge-lists.d.ts +1 -1
  45. package/dist/entities/listener.d.ts +8 -0
  46. package/dist/entities/message-change.d.ts +2 -0
  47. package/dist/entities/message-context.d.ts +6 -0
  48. package/dist/entities/message-write.d.ts +8 -0
  49. package/dist/entities/message.d.ts +4 -0
  50. package/dist/entities/message.js +4 -0
  51. package/dist/entities/store-records.d.ts +2 -0
  52. package/dist/errors/reasons.js +20 -2
  53. package/dist/mail/cli/index.js +1 -1
  54. package/dist/mail/headers.d.ts +2 -0
  55. package/dist/mail/headers.js +2 -1
  56. package/dist/mail/mail-types.d.ts +48 -0
  57. package/dist/mail/mail-types.js +218 -0
  58. package/dist/mail/read.js +1 -0
  59. package/dist/mail/sort-rules.d.ts +58 -0
  60. package/dist/mail/sort-rules.js +79 -0
  61. package/dist/oauth/index.d.ts +1 -1
  62. package/dist/oauth/storage.d.ts +10 -2
  63. package/dist/oauth/storage.js +23 -9
  64. package/dist/search/lucene/registry.js +24 -0
  65. package/dist/services/domain-lists-download.d.ts +26 -0
  66. package/dist/services/domain-lists-download.js +155 -0
  67. package/dist/services/messages-search.js +1 -1
  68. package/dist/services/metadata.d.ts +1 -1
  69. package/dist/store/areas.d.ts +3 -1
  70. package/dist/store/areas.js +2 -0
  71. package/dist/store/index.d.ts +2 -2
  72. package/dist/store/index.js +1 -1
  73. package/dist/store/people.d.ts +18 -9
  74. package/dist/store/people.js +8 -7
  75. package/dist/store/public.d.ts +1 -1
  76. package/dist/store/public.js +1 -1
  77. package/dist/store/queries.js +9 -2
  78. package/dist/store/sqlite/accounts.js +3 -1
  79. package/dist/store/sqlite/domain-organizations.d.ts +7 -4
  80. package/dist/store/sqlite/domain-organizations.js +94 -36
  81. package/dist/store/sqlite/email-types.d.ts +87 -0
  82. package/dist/store/sqlite/email-types.js +296 -0
  83. package/dist/store/sqlite/emails.d.ts +14 -2
  84. package/dist/store/sqlite/emails.js +32 -12
  85. package/dist/store/sqlite/identities.d.ts +4 -1
  86. package/dist/store/sqlite/identities.js +11 -2
  87. package/dist/store/sqlite/identity-rekey.js +2 -0
  88. package/dist/store/sqlite/lucene-fields.d.ts +6 -0
  89. package/dist/store/sqlite/lucene-fields.js +10 -0
  90. package/dist/store/sqlite/lucene.js +6 -0
  91. package/dist/store/sqlite/mail-sorting.d.ts +122 -0
  92. package/dist/store/sqlite/mail-sorting.js +482 -0
  93. package/dist/store/sqlite/manifest.js +6 -0
  94. package/dist/store/sqlite/merged-persons.d.ts +3 -2
  95. package/dist/store/sqlite/merged-persons.js +5 -3
  96. package/dist/store/sqlite/migrations.generated.js +76 -0
  97. package/dist/store/sqlite/people-list.d.ts +1 -6
  98. package/dist/store/sqlite/people-list.js +97 -42
  99. package/dist/store/sqlite/person-links.js +13 -3
  100. package/dist/store/sqlite/person-match-scan.js +5 -2
  101. package/dist/store/sqlite/schema/mail-sorting.d.ts +384 -0
  102. package/dist/store/sqlite/schema/mail-sorting.js +31 -0
  103. package/dist/store/sqlite/schema/sender-bots.d.ts +56 -0
  104. package/dist/store/sqlite/schema/sender-bots.js +9 -1
  105. package/dist/store/sqlite/schema.d.ts +66 -1
  106. package/dist/store/sqlite/schema.js +9 -1
  107. package/dist/store/sqlite/sender-bots.d.ts +89 -15
  108. package/dist/store/sqlite/sender-bots.js +417 -136
  109. package/dist/store/sqlite/sender-signals.d.ts +11 -4
  110. package/dist/store/sqlite/sender-signals.js +14 -10
  111. package/package.json +2 -2
@@ -0,0 +1,87 @@
1
+ import { type MailType, type MailTypeOf } from "../../mail/mail-types.js";
2
+ import { type CacheDatabase } from "../driver.js";
3
+ import { type Reach } from "./sender-signals.js";
4
+ /** The type, reach and signal of each of these emails, worked out from the store; nothing is written. */
5
+ /**
6
+ * `senders` carries each List-Id's sender count from batch to batch: a newsletter's every issue would read all its
7
+ * issues again.
8
+ */
9
+ export declare const typesOf: (database: CacheDatabase, ids: readonly number[], senders?: Map<string, number>) => Map<number, MailTypeOf>;
10
+ /** Whether every email's stored type is current. */
11
+ export declare const typesCurrent: (database: CacheDatabase) => boolean;
12
+ /**
13
+ * Works out and keeps the type of every email whose stored one the triggers cleared, or every email after the rules
14
+ * changed, a batch per write so another process never waits long for the lock. A query-only open keeps nothing.
15
+ * Answers whether every stored type is current.
16
+ */
17
+ export declare const storeMailTypes: (database: CacheDatabase) => boolean;
18
+ /** Each email's stored type, or for one the store has not typed yet, the type worked out for this read. */
19
+ export declare const withTypes: <T extends {
20
+ id: number;
21
+ mailType: MailType | null;
22
+ }>(database: CacheDatabase, emails: T[]) => T[];
23
+ /** Which emails a filter by type and reach keeps. @experimental */
24
+ export interface TypeFilter {
25
+ types?: readonly MailType[];
26
+ reaches?: readonly Reach[];
27
+ }
28
+ /**
29
+ * The SQL of a filter by type and reach over `e`. Types are worked out and kept first; a query-only open that finds
30
+ * some not worked out works those out in memory, so a filtered list is never short.
31
+ */
32
+ export declare const typeWhere: (database: CacheDatabase, filter: TypeFilter) => {
33
+ sql: string[];
34
+ params: string[];
35
+ };
36
+ /**
37
+ * The same filter, without writing: inside a read, the mail not typed yet is worked out in memory. `check` runs
38
+ * between batches, so a search's time limit still stops it.
39
+ */
40
+ export declare const typeCondition: (database: CacheDatabase, filter: TypeFilter, current?: boolean, check?: () => void) => {
41
+ sql: string[];
42
+ params: string[];
43
+ };
44
+ /** One sender's mail, counted by type and reach: a shop's receipts and its sales side by side. @experimental */
45
+ export interface SenderMailTypes {
46
+ /** `person:<id>`, `sender-bot:<id>`, or `null` when the store links the address to neither. */
47
+ ref: string | null;
48
+ /** The addresses it sent from, lower case. */
49
+ addresses: string[];
50
+ /** The display name on its newest email. */
51
+ name: string | null;
52
+ /** Its live emails the filter's account and time take in. */
53
+ emails: number;
54
+ types: Partial<Record<MailType, number>>;
55
+ reaches: Partial<Record<Reach, number>>;
56
+ /** Its newest email, ms. */
57
+ lastAt: number | null;
58
+ }
59
+ /** Which senders `mailSenders` lists: those with at least one email of these types and reaches. @experimental */
60
+ export interface SenderTypesFilter extends TypeFilter {
61
+ accountId?: number;
62
+ since?: number;
63
+ until?: number;
64
+ limit?: number;
65
+ offset?: number;
66
+ }
67
+ /**
68
+ * Every sender of incoming mail with its mail counted by type and reach, most mail first. A sender is listed when
69
+ * any of its emails passes `types` and `reaches`, and its counts cover all its mail: Subscriptions shows a shop by
70
+ * its sales and still says it also sends receipts.
71
+ */
72
+ export declare const mailSenders: (database: CacheDatabase, filter: SenderTypesFilter) => {
73
+ items: SenderMailTypes[];
74
+ total: number;
75
+ };
76
+ /** @experimental */
77
+ export interface MailTypeStore {
78
+ /**
79
+ * Senders of incoming mail with their mail counted by type and reach, most mail first; a sender is listed when any of
80
+ * its emails passes `types` and `reaches`.
81
+ */
82
+ mailSenders(filter?: SenderTypesFilter): Promise<{
83
+ items: SenderMailTypes[];
84
+ total: number;
85
+ }>;
86
+ }
87
+ export declare const mailTypeStore: (database: CacheDatabase) => MailTypeStore;
@@ -0,0 +1,296 @@
1
+ import { SENDER_BOT_PREFIX } from "../../domain/person-kinds.js";
2
+ import { listIdOf } from "../../mail/headers.js";
3
+ import { MAIL_TYPES, mailTypeOf, schemaTypesOf } from "../../mail/mail-types.js";
4
+ import { sortRuleFor } from "../../mail/sort-rules.js";
5
+ import { isQueryOnly } from "../driver.js";
6
+ import { typeRulesOf } from "./mail-sorting.js";
7
+ import { NEWSLETTER_ONLY } from "./sender-bots.js";
8
+ import { LIST_ID, LIST_SENDERS, REACHES, senderKey } from "./sender-signals.js";
9
+ import { read, writeBatch } from "./transaction.js";
10
+ /** Bump when what decides a mail type changes in code: every stored one is worked out again on the next read. */
11
+ const TYPE_RULES = "1";
12
+ const RULES_KEY = "mail.type_rules";
13
+ /**
14
+ * Working out 5,000 types takes about 40 ms; the commit's sync to disk costs more, so fewer and larger batches finish
15
+ * sooner and still hold the lock well inside another writer's 5 s wait.
16
+ */
17
+ const BATCH = 5_000;
18
+ const INPUTS = "SELECT e.id, e.from_address, e.subject, e.headers, e.body_html, e.outgoing, " +
19
+ "coalesce(e.received_at, e.sent_at) AS at, " +
20
+ `${LIST_ID} AS list, ` +
21
+ "CASE WHEN json_extract(e.metadata, '$.rule') IS NOT NULL THEN NULL ELSE " +
22
+ "(SELECT count(*) FROM email_recipients r WHERE r.email_id = e.id AND r.role IN ('to', 'cc')) END AS recipients, " +
23
+ "(SELECT json_group_array(lower(a.mime)) FROM attachments a " +
24
+ "WHERE a.attachable_type = 'email' AND a.attachable_id = e.id AND a.mime IS NOT NULL) AS parts, " +
25
+ "e.outgoing IS 1 OR EXISTS (SELECT 1 FROM email_recipients r JOIN emails o ON o.id = r.email_id " +
26
+ "WHERE r.identity_id = e.from_identity_id AND o.outgoing = 1) AS owner_wrote, " +
27
+ "EXISTS (SELECT 1 FROM sender_bot_identities b JOIN sender_bots s ON s.id = b.bot_id " +
28
+ `WHERE b.identity_id = e.from_identity_id AND s.reason IS NOT '${NEWSLETTER_ONLY}') AS bot, ` +
29
+ "(SELECT json_extract(g.metadata, '$.sector') FROM organization_identities oi " +
30
+ "JOIN organizations g ON g.id = oi.organization_id " +
31
+ "WHERE oi.identity_id = e.from_identity_id AND g.deleted_at IS NULL ORDER BY g.id LIMIT 1) AS sector " +
32
+ "FROM emails e WHERE e.id IN (SELECT value FROM json_each(?))";
33
+ const parsed = (value) => {
34
+ if (typeof value !== "string")
35
+ return {};
36
+ try {
37
+ const found = JSON.parse(value);
38
+ return found !== null && typeof found === "object" && !Array.isArray(found)
39
+ ? found
40
+ : {};
41
+ }
42
+ catch {
43
+ return {};
44
+ }
45
+ };
46
+ /** The type, reach and signal of each of these emails, worked out from the store; nothing is written. */
47
+ /**
48
+ * `senders` carries each List-Id's sender count from batch to batch: a newsletter's every issue would read all its
49
+ * issues again.
50
+ */
51
+ export const typesOf = (database, ids, senders = new Map()) => {
52
+ const found = new Map();
53
+ if (ids.length === 0)
54
+ return found;
55
+ const rows = database.prepare(INPUTS).all(JSON.stringify(ids));
56
+ const rules = typeRulesOf(database);
57
+ const lists = [
58
+ ...new Set(rows.flatMap((row) => (typeof row.list === "string" && !senders.has(row.list) ? [row.list] : []))),
59
+ ];
60
+ if (lists.length > 0) {
61
+ const held = new Map(lists.map((list) => [list, new Set()]));
62
+ for (const row of database.prepare(LIST_SENDERS).all(JSON.stringify(lists)))
63
+ held.get(String(row.list))?.add(senderKey(String(row.address)));
64
+ for (const [list, addresses] of held)
65
+ senders.set(list, addresses.size);
66
+ }
67
+ for (const row of rows) {
68
+ const headers = parsed(row.headers);
69
+ const from = typeof row.from_address === "string" ? row.from_address.toLowerCase() : null;
70
+ const typed = mailTypeOf({
71
+ from,
72
+ subject: typeof row.subject === "string" ? row.subject : null,
73
+ headers: typeof row.list === "string" ? { ...headers, "list-id": row.list } : headers,
74
+ recipients: row.recipients == null ? null : Number(row.recipients),
75
+ parts: JSON.parse(String(row.parts ?? "[]")),
76
+ schemaTypes: schemaTypesOf(typeof row.body_html === "string" ? row.body_html : null),
77
+ listSenders: typeof row.list === "string" ? (senders.get(row.list) ?? 0) : 0,
78
+ ownerWrote: Number(row.owner_wrote) === 1,
79
+ bot: Number(row.bot) === 1,
80
+ sector: typeof row.sector === "string" ? row.sector : null,
81
+ });
82
+ const rule = Number(row.outgoing) === 1
83
+ ? undefined
84
+ : sortRuleFor(rules, {
85
+ id: Number(row.id),
86
+ from,
87
+ subject: typeof row.subject === "string" ? row.subject : null,
88
+ list: typeof row.list === "string" ? (listIdOf(row.list) ?? null) : null,
89
+ at: row.at == null ? null : Number(row.at),
90
+ });
91
+ found.set(Number(row.id), rule?.mailType == null ? typed : { ...typed, type: rule.mailType, signal: `rule:${rule.id}` });
92
+ }
93
+ return found;
94
+ };
95
+ const rulesOf = (database) => {
96
+ const row = database.prepare("SELECT value FROM store_settings WHERE key = ?").get(RULES_KEY);
97
+ return row === undefined ? undefined : String(row.value);
98
+ };
99
+ const anyLeft = (database) => database.prepare("SELECT 1 FROM emails WHERE mail_type IS NULL LIMIT 1").get() !== undefined;
100
+ const UNCHECKED = "SELECT id FROM emails WHERE mail_type IS NOT NULL AND sort_checked IS NULL";
101
+ /** A type a build before version 77 kept, while a sorting rule exists that it never read. */
102
+ const anyUnchecked = (database) => typeRulesOf(database).size > 0 && database.prepare(`${UNCHECKED} LIMIT 1`).get() !== undefined;
103
+ /** Whether every email's stored type is current. */
104
+ export const typesCurrent = (database) => rulesOf(database) === TYPE_RULES && !anyLeft(database) && !anyUnchecked(database);
105
+ /**
106
+ * Works out and keeps the type of every email whose stored one the triggers cleared, or every email after the rules
107
+ * changed, a batch per write so another process never waits long for the lock. A query-only open keeps nothing.
108
+ * Answers whether every stored type is current.
109
+ */
110
+ export const storeMailTypes = (database) => {
111
+ if (isQueryOnly(database))
112
+ return typesCurrent(database);
113
+ if (rulesOf(database) !== TYPE_RULES)
114
+ writeBatch(database, () => {
115
+ if (rulesOf(database) === TYPE_RULES)
116
+ return;
117
+ database
118
+ .prepare("UPDATE emails SET mail_type = NULL, reach = NULL, type_signal = NULL WHERE mail_type IS NOT NULL")
119
+ .run();
120
+ database
121
+ .prepare("INSERT INTO store_settings (key, value, at) VALUES (?, ?, ?) " +
122
+ "ON CONFLICT (key) DO UPDATE SET value = excluded.value, at = excluded.at")
123
+ .run(RULES_KEY, TYPE_RULES, Date.now());
124
+ });
125
+ if (anyUnchecked(database)) {
126
+ const clear = database.prepare(`UPDATE emails SET mail_type = NULL, reach = NULL, type_signal = NULL WHERE id IN (${UNCHECKED} LIMIT ?)`);
127
+ while (writeBatch(database, () => clear.run(BATCH).changes) === BATCH)
128
+ ;
129
+ }
130
+ const keep = database.prepare("UPDATE emails SET mail_type = ?, reach = ?, type_signal = ?, sort_checked = 1 WHERE id = ?");
131
+ const senders = new Map();
132
+ for (;;) {
133
+ const more = writeBatch(database, () => {
134
+ const ids = database
135
+ .prepare("SELECT id FROM emails WHERE mail_type IS NULL LIMIT ?")
136
+ .all(BATCH)
137
+ .map((row) => Number(row.id));
138
+ for (const [id, { type, reach, signal }] of typesOf(database, ids, senders))
139
+ keep.run(type, reach, signal, id);
140
+ return ids.length === BATCH;
141
+ });
142
+ if (!more)
143
+ return true;
144
+ }
145
+ };
146
+ /** Each email's stored type, or for one the store has not typed yet, the type worked out for this read. */
147
+ export const withTypes = (database, emails) => {
148
+ const missing = emails.filter((email) => email.mailType === null).map((email) => email.id);
149
+ if (missing.length === 0)
150
+ return emails;
151
+ const found = read(database, () => typesOf(database, missing));
152
+ return emails.map((email) => {
153
+ const typed = found.get(email.id);
154
+ return typed === undefined
155
+ ? email
156
+ : { ...email, mailType: typed.type, reach: typed.reach, typeSignal: typed.signal };
157
+ });
158
+ };
159
+ const passes = (filter, type, reach) => (filter.types === undefined || filter.types.includes(type)) &&
160
+ (filter.reaches === undefined || filter.reaches.includes(reach));
161
+ /**
162
+ * The SQL of a filter by type and reach over `e`. Types are worked out and kept first; a query-only open that finds
163
+ * some not worked out works those out in memory, so a filtered list is never short.
164
+ */
165
+ export const typeWhere = (database, filter) => filter.types === undefined && filter.reaches === undefined
166
+ ? { sql: [], params: [] }
167
+ : typeCondition(database, filter, storeMailTypes(database));
168
+ /**
169
+ * The same filter, without writing: inside a read, the mail not typed yet is worked out in memory. `check` runs
170
+ * between batches, so a search's time limit still stops it.
171
+ */
172
+ export const typeCondition = (database, filter, current = typesCurrent(database), check = () => { }) => {
173
+ if (filter.types === undefined && filter.reaches === undefined)
174
+ return { sql: [], params: [] };
175
+ const stored = [
176
+ ...(filter.types === undefined ? [] : ["e.mail_type IN (SELECT value FROM json_each(?))"]),
177
+ ...(filter.reaches === undefined ? [] : ["e.reach IN (SELECT value FROM json_each(?))"]),
178
+ ].join(" AND ");
179
+ const params = [
180
+ ...(filter.types === undefined ? [] : [JSON.stringify(filter.types)]),
181
+ ...(filter.reaches === undefined ? [] : [JSON.stringify(filter.reaches)]),
182
+ ];
183
+ if (current)
184
+ return { sql: [stored], params };
185
+ const pending = read(database, () => {
186
+ const ids = database
187
+ .prepare("SELECT id FROM emails WHERE mail_type IS NULL")
188
+ .all()
189
+ .map((row) => Number(row.id));
190
+ const kept = [];
191
+ const senders = new Map();
192
+ for (let at = 0; at < ids.length; at += BATCH) {
193
+ check();
194
+ for (const [id, typed] of typesOf(database, ids.slice(at, at + BATCH), senders))
195
+ if (passes(filter, typed.type, typed.reach))
196
+ kept.push(id);
197
+ }
198
+ return kept;
199
+ });
200
+ return {
201
+ sql: [`((${stored}) OR e.id IN (SELECT value FROM json_each(?)))`],
202
+ params: [...params, JSON.stringify(pending)],
203
+ };
204
+ };
205
+ const SENDER_ROWS = "SELECT e.id, lower(e.from_address) AS address, e.from_name AS name, e.mail_type, e.reach, " +
206
+ "coalesce(e.received_at, e.sent_at) AS at, b.bot_id, l.person_id " +
207
+ "FROM emails e LEFT JOIN sender_bot_identities b ON b.identity_id = e.from_identity_id " +
208
+ "LEFT JOIN identity_links l ON l.identity_id = e.from_identity_id AND b.bot_id IS NULL " +
209
+ "WHERE e.deleted_at IS NULL AND e.outgoing IS NOT 1 AND e.from_address IS NOT NULL";
210
+ /**
211
+ * Every sender of incoming mail with its mail counted by type and reach, most mail first. A sender is listed when
212
+ * any of its emails passes `types` and `reaches`, and its counts cover all its mail: Subscriptions shows a shop by
213
+ * its sales and still says it also sends receipts.
214
+ */
215
+ export const mailSenders = (database, filter) => {
216
+ const complete = storeMailTypes(database);
217
+ const where = [];
218
+ const params = [];
219
+ const add = (sql, value) => {
220
+ if (value === undefined)
221
+ return;
222
+ where.push(sql);
223
+ params.push(value);
224
+ };
225
+ add("e.account_id = ?", filter.accountId);
226
+ add("coalesce(e.received_at, e.sent_at) >= ?", filter.since);
227
+ add("coalesce(e.received_at, e.sent_at) < ?", filter.until);
228
+ const rows = read(database, () => {
229
+ const all = database.prepare([SENDER_ROWS, ...where].join(" AND ")).all(...params);
230
+ if (complete)
231
+ return all;
232
+ const missing = all.filter((row) => row.mail_type == null).map((row) => Number(row.id));
233
+ const found = new Map();
234
+ const senders = new Map();
235
+ for (let at = 0; at < missing.length; at += BATCH)
236
+ for (const [id, typed] of typesOf(database, missing.slice(at, at + BATCH), senders))
237
+ found.set(id, typed);
238
+ return all.map((row) => {
239
+ const typed = found.get(Number(row.id));
240
+ return typed === undefined ? row : { ...row, mail_type: typed.type, reach: typed.reach };
241
+ });
242
+ });
243
+ const tallies = new Map();
244
+ for (const row of rows) {
245
+ const address = String(row.address);
246
+ const ref = row.bot_id != null
247
+ ? `${SENDER_BOT_PREFIX}${row.bot_id}`
248
+ : row.person_id != null
249
+ ? `person:${row.person_id}`
250
+ : null;
251
+ const key = ref ?? `address:${address}`;
252
+ const at = row.at == null ? null : Number(row.at);
253
+ const tally = tallies.get(key) ?? {
254
+ ref,
255
+ addresses: [],
256
+ name: null,
257
+ emails: 0,
258
+ types: {},
259
+ reaches: {},
260
+ lastAt: null,
261
+ matched: false,
262
+ };
263
+ const type = String(row.mail_type);
264
+ const reach = String(row.reach);
265
+ if (!tally.addresses.includes(address))
266
+ tally.addresses.push(address);
267
+ if (at !== null && (tally.lastAt === null || at >= tally.lastAt)) {
268
+ tally.lastAt = at;
269
+ tally.name = typeof row.name === "string" ? row.name : tally.name;
270
+ }
271
+ tally.emails += 1;
272
+ tally.types[type] = (tally.types[type] ?? 0) + 1;
273
+ tally.reaches[reach] = (tally.reaches[reach] ?? 0) + 1;
274
+ if (passes(filter, type, reach))
275
+ tally.matched = true;
276
+ tallies.set(key, tally);
277
+ }
278
+ const listed = [...tallies.values()]
279
+ .filter((tally) => tally.matched)
280
+ .sort((a, b) => b.emails - a.emails || (b.lastAt ?? 0) - (a.lastAt ?? 0))
281
+ .map(({ matched: _, ...tally }) => ({
282
+ ...tally,
283
+ addresses: tally.addresses.sort(),
284
+ types: ordered(tally.types, MAIL_TYPES),
285
+ reaches: ordered(tally.reaches, REACHES),
286
+ }));
287
+ const offset = filter.offset ?? 0;
288
+ return {
289
+ items: listed.slice(offset, filter.limit === undefined ? undefined : offset + filter.limit),
290
+ total: listed.length,
291
+ };
292
+ };
293
+ const ordered = (counts, order) => Object.fromEntries(order.flatMap((key) => (counts[key] === undefined ? [] : [[key, counts[key]]])));
294
+ export const mailTypeStore = (database) => ({
295
+ mailSenders: async (filter = {}) => mailSenders(database, filter),
296
+ });
@@ -1,13 +1,17 @@
1
1
  import type { Message } from "../../domain/models.js";
2
+ import type { MailType } from "../../mail/mail-types.js";
2
3
  import type { Attachment, Metadata } from "../../meetings/index.js";
3
4
  import type { Stemmer, Stemmers } from "../../search/stem.js";
4
5
  import type { CacheDatabase } from "../driver.js";
5
6
  import type { ConversationSummary, StoredHit } from "../types.js";
6
7
  import { type MailActivityStore } from "./email-activity.js";
7
8
  import { type EmailLocationInput, type FolderEmail, type PartialMailStore } from "./email-locations.js";
9
+ import { type MailTypeStore, type TypeFilter } from "./email-types.js";
8
10
  import { type MailRulesStore } from "./mail-rules.js";
11
+ import { type MailSorting } from "./mail-sorting.js";
9
12
  import { type AttachmentInput } from "./meetings.js";
10
13
  import type { StoreContext } from "./open.js";
14
+ import type { Reach } from "./sender-signals.js";
11
15
  import { type SyncStateSave } from "./sync.js";
12
16
  import { type ThreadFilter } from "./thread-columns.js";
13
17
  export type { EmailLocationInput, FolderEmail, PartialEmail } from "./email-locations.js";
@@ -115,6 +119,12 @@ export interface Email {
115
119
  headers: Metadata;
116
120
  metadata: Metadata;
117
121
  mailRuleId: number | null;
122
+ /** What it is, apart from who sent it (docs/dev/GLOSSARY.md, "mail type"). @experimental */
123
+ mailType: MailType | null;
124
+ /** How it reached the owner. @experimental */
125
+ reach: Reach | null;
126
+ /** What decided `mailType`, such as `list-id`. @experimental */
127
+ typeSignal: string | null;
118
128
  recipients: EmailRecipient[];
119
129
  mailboxes: Mailbox[];
120
130
  attachments: EmailAttachment[];
@@ -150,7 +160,7 @@ export interface MailFilter {
150
160
  limit?: number;
151
161
  offset?: number;
152
162
  }
153
- export interface EmailFilter extends MailFilter {
163
+ export interface EmailFilter extends MailFilter, TypeFilter {
154
164
  threadExternalId?: string;
155
165
  /** An address in From, To, Cc, Bcc or Reply-To. */
156
166
  participant?: string;
@@ -206,7 +216,7 @@ export interface SenderScore {
206
216
  demoted?: boolean;
207
217
  }
208
218
  /** Mail in tables of its own: threads, emails, recipients and mailboxes, keyed by account and Message-ID. */
209
- export interface MailStore extends PartialMailStore, MailActivityStore {
219
+ export interface MailStore extends PartialMailStore, MailActivityStore, MailTypeStore {
210
220
  saveThread(input: ThreadSave): Promise<ThreadDetails>;
211
221
  /** Several threads and sync state in one transaction: a slice of mail commits with its resume point, or not at all. */
212
222
  saveThreads(inputs: ThreadSave[], states?: SyncStateSave[]): Promise<ThreadDetails[]>;
@@ -294,6 +304,8 @@ export interface MailStore extends PartialMailStore, MailActivityStore {
294
304
  }): Promise<EmailVectorHit[]>;
295
305
  /** The account's mail rules, and which rule decided each email. */
296
306
  readonly rules: MailRulesStore;
307
+ /** Sorting rules by mail, list, subject, address and domain, apart from the storage `rules`. @experimental */
308
+ readonly sorting: MailSorting;
297
309
  }
298
310
  /** An email as a message of its thread, the shape mail had when it was stored as messages. */
299
311
  export declare const messageOfEmail: (email: Email, thread: string) => Message;
@@ -5,12 +5,14 @@ import { mailActivity, threadEmailIds } from "./email-activity.js";
5
5
  import { chunkAttachments, drainEmailIndex, dropAttachmentChunks, MAIL_PIECES, queueThreads, threadPieces, titleOf, } from "./email-index.js";
6
6
  import { backfillSentAt, folderEmails, forgetLocations, locate, partialMail, setLocations, storedWhole, } from "./email-locations.js";
7
7
  import { markEmailsDeleted, markEmailsRestored, markOwnMail, recountEmailThread as recount, setEmailFlags, } from "./email-state.js";
8
+ import { mailTypeStore, typeWhere, withTypes } from "./email-types.js";
8
9
  import { EMAIL_ENRICHMENT, enrichmentText } from "./enrichments.js";
9
10
  import { bool, flag, fromJson, int, page, str, toJson } from "./events.js";
10
11
  import { folded } from "./folded.js";
11
12
  import { ensurePerson } from "./identities.js";
12
13
  import { nearestMailPieces } from "./mail-nearest.js";
13
14
  import { mailRulesOver } from "./mail-rules.js";
15
+ import { mailSortingOver, settleThreads } from "./mail-sorting.js";
14
16
  import { attachmentOf, saveAttachment, wordsQuery } from "./meetings.js";
15
17
  import { stemmerCache } from "./stems.js";
16
18
  import { writeState } from "./sync.js";
@@ -93,6 +95,9 @@ const emailOf = (database, row) => ({
93
95
  headers: fromJson(row.headers),
94
96
  metadata: fromJson(row.metadata),
95
97
  mailRuleId: int(row.mail_rule_id),
98
+ mailType: str(row.mail_type),
99
+ reach: str(row.reach),
100
+ typeSignal: str(row.type_signal),
96
101
  recipients: database
97
102
  .prepare("SELECT * FROM email_recipients WHERE email_id = ? ORDER BY position")
98
103
  .all(Number(row.id))
@@ -290,7 +295,7 @@ const saveThread = (database, orm, input) => {
290
295
  queueThreads(database, moved);
291
296
  return threadId;
292
297
  };
293
- const emailWhere = (filter) => {
298
+ const emailWhere = (database, filter) => {
294
299
  const where = ["(? OR e.deleted_at IS NULL)"];
295
300
  const params = [filter.includeDeleted ? 1 : 0];
296
301
  const add = (sql, ...values) => {
@@ -321,6 +326,11 @@ const emailWhere = (filter) => {
321
326
  AND extraction_error IN (${filter.attachmentErrors.map(() => "?").join(",") || "NULL"}))`, ...filter.attachmentErrors);
322
327
  if (filter.externalIds !== undefined)
323
328
  add("e.external_id IN (SELECT value FROM json_each(?))", JSON.stringify(filter.externalIds));
329
+ const typed = typeWhere(database, filter);
330
+ for (const sql of typed.sql)
331
+ add(sql);
332
+ for (const value of typed.params)
333
+ params.push(value);
324
334
  return [where.join(" AND "), params];
325
335
  };
326
336
  /** An email as a message of its thread, the shape mail had when it was stored as messages. */
@@ -382,6 +392,7 @@ const mailFieldsOf = (database, email, thread, key) => {
382
392
  thread: formatReference({ type: "chat", provider: key.provider, account: key.account, chat: thread }),
383
393
  read: email.read,
384
394
  flagged: email.flagged,
395
+ ...(email.mailType === null || email.reach === null ? {} : { mailType: email.mailType, reach: email.reach }),
385
396
  ...(scored === undefined
386
397
  ? {}
387
398
  : {
@@ -398,12 +409,13 @@ export const emailHitsByPk = (database, pks) => {
398
409
  const read = database.prepare(`SELECT e.*, t.external_id AS thread, t.subject AS thread_subject, a.provider, a.external_id AS account
399
410
  FROM emails e JOIN email_threads t ON t.id = e.email_thread_id JOIN accounts a ON a.id = e.account_id
400
411
  WHERE e.id = ?`);
401
- return pks.flatMap((pk) => {
402
- const row = read.get(pk);
403
- if (!row)
412
+ const rows = pks.map((pk) => read.get(pk)).filter((row) => row !== undefined);
413
+ const emails = withTypes(database, rows.map((row) => emailOf(database, row)));
414
+ return rows.flatMap((row, at) => {
415
+ const email = emails[at];
416
+ if (!email)
404
417
  return [];
405
418
  const thread = String(row.thread);
406
- const email = emailOf(database, row);
407
419
  const message = messageOfEmail(email, thread);
408
420
  const key = { provider: String(row.provider), account: String(row.account) };
409
421
  return [
@@ -427,13 +439,19 @@ export const emailHitsByPk = (database, pks) => {
427
439
  */
428
440
  export const mailStoreOver = ({ database, orm, now }, stemmerFor = stemmerCache()) => ({
429
441
  rules: mailRulesOver(database),
442
+ sorting: mailSortingOver({ database, orm, now }),
430
443
  async saveThread(input) {
431
- const id = write(database, () => saveThread(database, orm, input));
444
+ const id = write(database, () => {
445
+ const saved = saveThread(database, orm, input);
446
+ settleThreads({ database, orm, now }, [saved]);
447
+ return saved;
448
+ });
432
449
  return threadDetails(database, id);
433
450
  },
434
451
  async saveThreads(inputs, states = []) {
435
452
  const ids = write(database, () => {
436
453
  const saved = inputs.map((input) => saveThread(database, orm, input));
454
+ settleThreads({ database, orm, now }, saved);
437
455
  for (const { accountId, name, value } of states)
438
456
  writeState({ orm, now }, accountId, name, value);
439
457
  return saved;
@@ -450,19 +468,20 @@ export const mailStoreOver = ({ database, orm, now }, stemmerFor = stemmerCache(
450
468
  const row = database
451
469
  .prepare("SELECT * FROM emails WHERE account_id = ? AND external_id = ?")
452
470
  .get(accountId, externalId);
453
- return row ? emailOf(database, row) : null;
471
+ return row ? withTypes(database, [emailOf(database, row)])[0] : null;
454
472
  },
455
473
  async emails(filter = {}) {
456
474
  const [limit, offset] = page(filter);
457
- const [where, params] = emailWhere(filter);
458
- return database
475
+ const [where, params] = emailWhere(database, filter);
476
+ const emails = database
459
477
  .prepare(`SELECT e.* FROM emails e WHERE ${where}
460
478
  ORDER BY coalesce(e.sent_at, e.received_at) DESC, e.id DESC LIMIT ? OFFSET ?`)
461
479
  .all(...params, limit, offset)
462
480
  .map((row) => emailOf(database, row));
481
+ return withTypes(database, emails);
463
482
  },
464
483
  async emailRefs(filter = {}) {
465
- const [where, params] = emailWhere(filter);
484
+ const [where, params] = emailWhere(database, filter);
466
485
  return database
467
486
  .prepare(`SELECT e.external_id, e.deleted_at IS NOT NULL AS deleted,
468
487
  (SELECT json_group_array(json_object('externalId', b.external_id, 'kind', b.kind))
@@ -477,8 +496,9 @@ export const mailStoreOver = ({ database, orm, now }, stemmerFor = stemmerCache(
477
496
  },
478
497
  ...partialMail(database),
479
498
  ...mailActivity(database),
499
+ ...mailTypeStore(database),
480
500
  async emailFacts(filter = {}) {
481
- const [where, params] = emailWhere(filter);
501
+ const [where, params] = emailWhere(database, filter);
482
502
  return database
483
503
  .prepare(`SELECT e.external_id, e.from_address, e.from_name, e.subject, coalesce(e.received_at, e.sent_at) AS at, e.size,
484
504
  e.read, e.flagged,
@@ -641,7 +661,7 @@ export const mailStoreOver = ({ database, orm, now }, stemmerFor = stemmerCache(
641
661
  return [];
642
662
  const [limit, offset] = page(filter);
643
663
  drainEmailIndex(database, stemmerFor);
644
- const [where, params] = emailWhere({ ...filter, includeDeleted: false });
664
+ const [where, params] = emailWhere(database, { ...filter, includeDeleted: false });
645
665
  return database
646
666
  .prepare(`SELECT e.* FROM email_words w JOIN emails e ON e.id = w.rowid
647
667
  WHERE email_words MATCH ? AND ${where}
@@ -13,7 +13,10 @@ export interface SavedIdentity {
13
13
  /** The profile differs from an earlier one written. */
14
14
  revised: boolean;
15
15
  }
16
- /** A new identity's own person, as ingest gives every identity; one already linked keeps its person. */
16
+ /**
17
+ * A new identity's own person, as ingest gives every identity; one already linked keeps its person, and a sender
18
+ * bot's has none.
19
+ */
17
20
  export declare const ensurePerson: (orm: Orm, identity: number, name: string | null, at: number) => void;
18
21
  /** Every new identity gets its own person; linking two is a later, recorded act. */
19
22
  export declare const identityOf: (context: StoreContext, provider: Provider, nativeId: Id, name: string | null, facts?: Facts) => number;
@@ -6,7 +6,7 @@ import { folded } from "./folded.js";
6
6
  import { holdingText } from "./note-index.js";
7
7
  import { resolvePersonLinks } from "./person-resolution.js";
8
8
  import { bound } from "./query-filter.js";
9
- import { accountIdentities, accounts, aliases, chatMembers, chats, identities, identityLinkEvents, identityLinks, identityRevisions, messages, persons, } from "./schema.js";
9
+ import { accountIdentities, accounts, aliases, chatMembers, chats, identities, identityLinkEvents, identityLinks, identityRevisions, messages, persons, senderBotIdentities, } from "./schema.js";
10
10
  import { trigramPart } from "./trigram-match.js";
11
11
  import { toIso } from "./values.js";
12
12
  /** The source's every phone and address as a JSON patch of `metadata`; `undefined` when it gave no list. */
@@ -94,10 +94,19 @@ const revise = (orm, identity, next, at, before) => {
94
94
  writeRevision(orm, identity, { ...next, marks }, at);
95
95
  return last !== undefined;
96
96
  };
97
- /** A new identity's own person, as ingest gives every identity; one already linked keeps its person. */
97
+ /**
98
+ * A new identity's own person, as ingest gives every identity; one already linked keeps its person, and a sender
99
+ * bot's has none.
100
+ */
98
101
  export const ensurePerson = (orm, identity, name, at) => {
99
102
  if (orm.select({ id: identityLinks.identityId }).from(identityLinks).where(eq(identityLinks.identityId, identity)).get())
100
103
  return;
104
+ if (orm
105
+ .select({ id: senderBotIdentities.identityId })
106
+ .from(senderBotIdentities)
107
+ .where(eq(senderBotIdentities.identityId, identity))
108
+ .get())
109
+ return;
101
110
  const person = Number(orm.insert(persons).values({ name, createdAt: at, updatedAt: at }).returning({ pk: persons.id }).get()?.pk);
102
111
  orm
103
112
  .insert(identityLinks)
@@ -2,6 +2,7 @@ import { CliError } from "@wirecat/cli-base";
2
2
  import { pointerPairs } from "./entity-types.js";
3
3
  import { settleLinks } from "./identity-link-rows.js";
4
4
  import { mergePerson } from "./person-links.js";
5
+ import { rekeyIntoBot } from "./sender-bots.js";
5
6
  import { write } from "./transaction.js";
6
7
  const quoted = (name) => `"${name.replace(/"/g, '""')}"`;
7
8
  const columnsOf = (database, table) => database.prepare("SELECT name, pk, type FROM pragma_table_info(?)").all(table);
@@ -144,6 +145,7 @@ export const rekeyIdentity = (context, provider, { from, to, phone }, by) => {
144
145
  return "renamed";
145
146
  }
146
147
  const keptId = Number(kept.id);
148
+ rekeyIntoBot(database, oldId, keptId, context.now());
147
149
  const [mine, theirs] = [personOfIdentity(database, oldId), personOfIdentity(database, keptId)];
148
150
  if (mine !== undefined && theirs !== undefined && mine !== theirs)
149
151
  persons.push(mergePerson(context, mine, theirs, { method: "identity-rekey", by }));
@@ -2,6 +2,7 @@ import { type Automaton, type MatchBudget } from "../../search/lucene/automaton.
2
2
  import type { QueryExecution, ResolvedPredicate } from "../../search/lucene/resolved.js";
3
3
  import { type Stemmer } from "../../search/stem.js";
4
4
  import type { CacheDatabase, SqlValue } from "../driver.js";
5
+ import type { TypeFilter } from "./email-types.js";
5
6
  export interface Fragment {
6
7
  sql: string;
7
8
  params: SqlValue[];
@@ -78,6 +79,11 @@ export interface FieldScope {
78
79
  everywhere: (node: ResolvedPredicate, fragment: Fragment, start?: string) => Fragment;
79
80
  /** Counts the patterns' expanded words against the query's budget. */
80
81
  expand: (count: number) => number;
82
+ /** The emails that pass a filter by type and reach, as SQL over `e`; never writes. */
83
+ mailTypes: (filter: TypeFilter) => {
84
+ sql: string[];
85
+ params: string[];
86
+ };
81
87
  }
82
88
  /** A leaf's condition; a whole `Leaf` is a pattern already expanded by an earlier leaf, taken as it was. */
83
89
  type Compiled = {