@wirecat/cli-core 1.1.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 (63) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/dist/cli/account-remove.d.ts +3 -0
  3. package/dist/cli/account-remove.js +1 -1
  4. package/dist/cli/documents/index.d.ts +2 -1
  5. package/dist/cli/documents/index.js +4 -1
  6. package/dist/cli/index.d.ts +2 -2
  7. package/dist/cli/index.js +2 -2
  8. package/dist/cli/messenger/conversation-answers.d.ts +2 -0
  9. package/dist/cli/messenger/message-answers.d.ts +2 -0
  10. package/dist/cli/messenger/message-items.js +2 -0
  11. package/dist/cli/messenger/message-writes.d.ts +4 -0
  12. package/dist/cli/messenger/search-answers.js +2 -0
  13. package/dist/cli/oauth-session.js +6 -3
  14. package/dist/cli/shared-command-exports.d.ts +2 -0
  15. package/dist/cli/shared-command-exports.js +3 -0
  16. package/dist/cli/token-session.d.ts +1 -4
  17. package/dist/cli/token-session.js +5 -1
  18. package/dist/domain/models.d.ts +5 -0
  19. package/dist/domain/person-kinds.d.ts +1 -1
  20. package/dist/entities/contact-context.d.ts +4 -0
  21. package/dist/entities/conversation-results.d.ts +4 -0
  22. package/dist/entities/evidence.d.ts +16 -0
  23. package/dist/entities/index.d.ts +36 -0
  24. package/dist/entities/listener.d.ts +8 -0
  25. package/dist/entities/message-change.d.ts +2 -0
  26. package/dist/entities/message-context.d.ts +6 -0
  27. package/dist/entities/message-write.d.ts +8 -0
  28. package/dist/entities/message.d.ts +4 -0
  29. package/dist/entities/message.js +4 -0
  30. package/dist/entities/store-records.d.ts +2 -0
  31. package/dist/errors/reasons.js +16 -0
  32. package/dist/mail/cli/index.js +1 -1
  33. package/dist/mail/headers.d.ts +2 -0
  34. package/dist/mail/headers.js +2 -1
  35. package/dist/mail/read.js +1 -0
  36. package/dist/mail/sort-rules.d.ts +58 -0
  37. package/dist/mail/sort-rules.js +79 -0
  38. package/dist/search/lucene/registry.js +24 -0
  39. package/dist/services/messages-search.js +1 -1
  40. package/dist/store/areas.d.ts +2 -0
  41. package/dist/store/areas.js +2 -0
  42. package/dist/store/public.d.ts +1 -1
  43. package/dist/store/public.js +1 -1
  44. package/dist/store/queries.js +9 -2
  45. package/dist/store/sqlite/email-types.d.ts +8 -0
  46. package/dist/store/sqlite/email-types.js +45 -10
  47. package/dist/store/sqlite/emails.d.ts +3 -0
  48. package/dist/store/sqlite/emails.js +14 -5
  49. package/dist/store/sqlite/lucene-fields.d.ts +6 -0
  50. package/dist/store/sqlite/lucene-fields.js +10 -0
  51. package/dist/store/sqlite/lucene.js +6 -0
  52. package/dist/store/sqlite/mail-sorting.d.ts +122 -0
  53. package/dist/store/sqlite/mail-sorting.js +482 -0
  54. package/dist/store/sqlite/manifest.js +2 -0
  55. package/dist/store/sqlite/migrations.generated.js +20 -0
  56. package/dist/store/sqlite/people-list.js +65 -16
  57. package/dist/store/sqlite/schema/mail-sorting.d.ts +384 -0
  58. package/dist/store/sqlite/schema/mail-sorting.js +31 -0
  59. package/dist/store/sqlite/schema.d.ts +17 -0
  60. package/dist/store/sqlite/schema.js +3 -0
  61. package/dist/store/sqlite/sender-bots.d.ts +10 -1
  62. package/dist/store/sqlite/sender-bots.js +47 -8
  63. package/package.json +2 -2
@@ -1,14 +1,21 @@
1
+ import { walkQuery } from "@wirecat/cli-base/query";
1
2
  import { adminStatisticsQuery } from "./sqlite/admin-statistics.js";
2
3
  import { conversationEligibility } from "./sqlite/conversation-eligibility.js";
3
4
  import { drainEmailIndex } from "./sqlite/email-index.js";
5
+ import { storeMailTypes } from "./sqlite/email-types.js";
4
6
  import * as lucene from "./sqlite/lucene.js";
5
7
  import { rankingEvidence } from "./sqlite/ranking-evidence.js";
6
8
  import { rankQuery } from "./sqlite/rankings.js";
7
9
  import { replyDelays, waitingChats, } from "./sqlite/reply-times.js";
10
+ // Outside the search's read and its time limit: the first such search after an upgrade types every email.
11
+ const asksMailType = ({ root }) => walkQuery(root).some(({ field }) => field === "type" || field === "reach");
8
12
  export const queriesStoreOver = (context, stemmerFor) => {
9
13
  const mailIndexed = (execution) => {
10
- if (execution.corpus === "mail")
11
- drainEmailIndex(context.database, stemmerFor);
14
+ if (execution.corpus !== "mail")
15
+ return execution;
16
+ drainEmailIndex(context.database, stemmerFor);
17
+ if (asksMailType(execution))
18
+ storeMailTypes(context.database);
12
19
  return execution;
13
20
  };
14
21
  return {
@@ -33,6 +33,14 @@ export declare const typeWhere: (database: CacheDatabase, filter: TypeFilter) =>
33
33
  sql: string[];
34
34
  params: string[];
35
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
+ };
36
44
  /** One sender's mail, counted by type and reach: a shop's receipts and its sales side by side. @experimental */
37
45
  export interface SenderMailTypes {
38
46
  /** `person:<id>`, `sender-bot:<id>`, or `null` when the store links the address to neither. */
@@ -1,6 +1,10 @@
1
1
  import { SENDER_BOT_PREFIX } from "../../domain/person-kinds.js";
2
+ import { listIdOf } from "../../mail/headers.js";
2
3
  import { MAIL_TYPES, mailTypeOf, schemaTypesOf } from "../../mail/mail-types.js";
4
+ import { sortRuleFor } from "../../mail/sort-rules.js";
3
5
  import { isQueryOnly } from "../driver.js";
6
+ import { typeRulesOf } from "./mail-sorting.js";
7
+ import { NEWSLETTER_ONLY } from "./sender-bots.js";
4
8
  import { LIST_ID, LIST_SENDERS, REACHES, senderKey } from "./sender-signals.js";
5
9
  import { read, writeBatch } from "./transaction.js";
6
10
  /** Bump when what decides a mail type changes in code: every stored one is worked out again on the next read. */
@@ -11,7 +15,8 @@ const RULES_KEY = "mail.type_rules";
11
15
  * sooner and still hold the lock well inside another writer's 5 s wait.
12
16
  */
13
17
  const BATCH = 5_000;
14
- const INPUTS = "SELECT e.id, e.from_address, e.subject, e.headers, e.body_html, " +
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, " +
15
20
  `${LIST_ID} AS list, ` +
16
21
  "CASE WHEN json_extract(e.metadata, '$.rule') IS NOT NULL THEN NULL ELSE " +
17
22
  "(SELECT count(*) FROM email_recipients r WHERE r.email_id = e.id AND r.role IN ('to', 'cc')) END AS recipients, " +
@@ -19,7 +24,8 @@ const INPUTS = "SELECT e.id, e.from_address, e.subject, e.headers, e.body_html,
19
24
  "WHERE a.attachable_type = 'email' AND a.attachable_id = e.id AND a.mime IS NOT NULL) AS parts, " +
20
25
  "e.outgoing IS 1 OR EXISTS (SELECT 1 FROM email_recipients r JOIN emails o ON o.id = r.email_id " +
21
26
  "WHERE r.identity_id = e.from_identity_id AND o.outgoing = 1) AS owner_wrote, " +
22
- "EXISTS (SELECT 1 FROM sender_bot_identities b WHERE b.identity_id = e.from_identity_id) AS bot, " +
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, ` +
23
29
  "(SELECT json_extract(g.metadata, '$.sector') FROM organization_identities oi " +
24
30
  "JOIN organizations g ON g.id = oi.organization_id " +
25
31
  "WHERE oi.identity_id = e.from_identity_id AND g.deleted_at IS NULL ORDER BY g.id LIMIT 1) AS sector " +
@@ -47,6 +53,7 @@ export const typesOf = (database, ids, senders = new Map()) => {
47
53
  if (ids.length === 0)
48
54
  return found;
49
55
  const rows = database.prepare(INPUTS).all(JSON.stringify(ids));
56
+ const rules = typeRulesOf(database);
50
57
  const lists = [
51
58
  ...new Set(rows.flatMap((row) => (typeof row.list === "string" && !senders.has(row.list) ? [row.list] : []))),
52
59
  ];
@@ -59,8 +66,9 @@ export const typesOf = (database, ids, senders = new Map()) => {
59
66
  }
60
67
  for (const row of rows) {
61
68
  const headers = parsed(row.headers);
62
- found.set(Number(row.id), mailTypeOf({
63
- from: typeof row.from_address === "string" ? row.from_address.toLowerCase() : null,
69
+ const from = typeof row.from_address === "string" ? row.from_address.toLowerCase() : null;
70
+ const typed = mailTypeOf({
71
+ from,
64
72
  subject: typeof row.subject === "string" ? row.subject : null,
65
73
  headers: typeof row.list === "string" ? { ...headers, "list-id": row.list } : headers,
66
74
  recipients: row.recipients == null ? null : Number(row.recipients),
@@ -70,7 +78,17 @@ export const typesOf = (database, ids, senders = new Map()) => {
70
78
  ownerWrote: Number(row.owner_wrote) === 1,
71
79
  bot: Number(row.bot) === 1,
72
80
  sector: typeof row.sector === "string" ? row.sector : null,
73
- }));
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}` });
74
92
  }
75
93
  return found;
76
94
  };
@@ -79,8 +97,11 @@ const rulesOf = (database) => {
79
97
  return row === undefined ? undefined : String(row.value);
80
98
  };
81
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;
82
103
  /** Whether every email's stored type is current. */
83
- export const typesCurrent = (database) => rulesOf(database) === TYPE_RULES && !anyLeft(database);
104
+ export const typesCurrent = (database) => rulesOf(database) === TYPE_RULES && !anyLeft(database) && !anyUnchecked(database);
84
105
  /**
85
106
  * Works out and keeps the type of every email whose stored one the triggers cleared, or every email after the rules
86
107
  * changed, a batch per write so another process never waits long for the lock. A query-only open keeps nothing.
@@ -101,7 +122,12 @@ export const storeMailTypes = (database) => {
101
122
  "ON CONFLICT (key) DO UPDATE SET value = excluded.value, at = excluded.at")
102
123
  .run(RULES_KEY, TYPE_RULES, Date.now());
103
124
  });
104
- const keep = database.prepare("UPDATE emails SET mail_type = ?, reach = ?, type_signal = ? WHERE id = ?");
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 = ?");
105
131
  const senders = new Map();
106
132
  for (;;) {
107
133
  const more = writeBatch(database, () => {
@@ -136,7 +162,14 @@ const passes = (filter, type, reach) => (filter.types === undefined || filter.ty
136
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
137
163
  * some not worked out works those out in memory, so a filtered list is never short.
138
164
  */
139
- export const typeWhere = (database, filter) => {
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 = () => { }) => {
140
173
  if (filter.types === undefined && filter.reaches === undefined)
141
174
  return { sql: [], params: [] };
142
175
  const stored = [
@@ -147,7 +180,7 @@ export const typeWhere = (database, filter) => {
147
180
  ...(filter.types === undefined ? [] : [JSON.stringify(filter.types)]),
148
181
  ...(filter.reaches === undefined ? [] : [JSON.stringify(filter.reaches)]),
149
182
  ];
150
- if (storeMailTypes(database))
183
+ if (current)
151
184
  return { sql: [stored], params };
152
185
  const pending = read(database, () => {
153
186
  const ids = database
@@ -156,10 +189,12 @@ export const typeWhere = (database, filter) => {
156
189
  .map((row) => Number(row.id));
157
190
  const kept = [];
158
191
  const senders = new Map();
159
- for (let at = 0; at < ids.length; at += BATCH)
192
+ for (let at = 0; at < ids.length; at += BATCH) {
193
+ check();
160
194
  for (const [id, typed] of typesOf(database, ids.slice(at, at + BATCH), senders))
161
195
  if (passes(filter, typed.type, typed.reach))
162
196
  kept.push(id);
197
+ }
163
198
  return kept;
164
199
  });
165
200
  return {
@@ -8,6 +8,7 @@ import { type MailActivityStore } from "./email-activity.js";
8
8
  import { type EmailLocationInput, type FolderEmail, type PartialMailStore } from "./email-locations.js";
9
9
  import { type MailTypeStore, type TypeFilter } from "./email-types.js";
10
10
  import { type MailRulesStore } from "./mail-rules.js";
11
+ import { type MailSorting } from "./mail-sorting.js";
11
12
  import { type AttachmentInput } from "./meetings.js";
12
13
  import type { StoreContext } from "./open.js";
13
14
  import type { Reach } from "./sender-signals.js";
@@ -303,6 +304,8 @@ export interface MailStore extends PartialMailStore, MailActivityStore, MailType
303
304
  }): Promise<EmailVectorHit[]>;
304
305
  /** The account's mail rules, and which rule decided each email. */
305
306
  readonly rules: MailRulesStore;
307
+ /** Sorting rules by mail, list, subject, address and domain, apart from the storage `rules`. @experimental */
308
+ readonly sorting: MailSorting;
306
309
  }
307
310
  /** An email as a message of its thread, the shape mail had when it was stored as messages. */
308
311
  export declare const messageOfEmail: (email: Email, thread: string) => Message;
@@ -12,6 +12,7 @@ import { folded } from "./folded.js";
12
12
  import { ensurePerson } from "./identities.js";
13
13
  import { nearestMailPieces } from "./mail-nearest.js";
14
14
  import { mailRulesOver } from "./mail-rules.js";
15
+ import { mailSortingOver, settleThreads } from "./mail-sorting.js";
15
16
  import { attachmentOf, saveAttachment, wordsQuery } from "./meetings.js";
16
17
  import { stemmerCache } from "./stems.js";
17
18
  import { writeState } from "./sync.js";
@@ -391,6 +392,7 @@ const mailFieldsOf = (database, email, thread, key) => {
391
392
  thread: formatReference({ type: "chat", provider: key.provider, account: key.account, chat: thread }),
392
393
  read: email.read,
393
394
  flagged: email.flagged,
395
+ ...(email.mailType === null || email.reach === null ? {} : { mailType: email.mailType, reach: email.reach }),
394
396
  ...(scored === undefined
395
397
  ? {}
396
398
  : {
@@ -407,12 +409,13 @@ export const emailHitsByPk = (database, pks) => {
407
409
  const read = database.prepare(`SELECT e.*, t.external_id AS thread, t.subject AS thread_subject, a.provider, a.external_id AS account
408
410
  FROM emails e JOIN email_threads t ON t.id = e.email_thread_id JOIN accounts a ON a.id = e.account_id
409
411
  WHERE e.id = ?`);
410
- return pks.flatMap((pk) => {
411
- const row = read.get(pk);
412
- 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)
413
417
  return [];
414
418
  const thread = String(row.thread);
415
- const email = emailOf(database, row);
416
419
  const message = messageOfEmail(email, thread);
417
420
  const key = { provider: String(row.provider), account: String(row.account) };
418
421
  return [
@@ -436,13 +439,19 @@ export const emailHitsByPk = (database, pks) => {
436
439
  */
437
440
  export const mailStoreOver = ({ database, orm, now }, stemmerFor = stemmerCache()) => ({
438
441
  rules: mailRulesOver(database),
442
+ sorting: mailSortingOver({ database, orm, now }),
439
443
  async saveThread(input) {
440
- 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
+ });
441
449
  return threadDetails(database, id);
442
450
  },
443
451
  async saveThreads(inputs, states = []) {
444
452
  const ids = write(database, () => {
445
453
  const saved = inputs.map((input) => saveThread(database, orm, input));
454
+ settleThreads({ database, orm, now }, saved);
446
455
  for (const { accountId, name, value } of states)
447
456
  writeState({ orm, now }, accountId, name, value);
448
457
  return saved;
@@ -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 = {
@@ -529,6 +529,14 @@ const list = ({ value }, { mail }) => {
529
529
  json_extract(metadata, '$.listId')) AS list_id FROM emails) WHERE list_id = ? OR list_id LIKE '%.' || ? ESCAPE '\\')`, wanted, wanted.replace(/[\\%_]/g, "\\$&"))
530
530
  : bound("0"));
531
531
  };
532
+ // Mail not typed yet is worked out in memory here: a search never writes, and the fill runs before it.
533
+ const mailType = (key) => ({ value }, scope) => {
534
+ if (!scope.mail)
535
+ return always(bound("0"));
536
+ const filter = { [key]: [value.toLowerCase()] };
537
+ const { sql, params } = scope.mailTypes(filter);
538
+ return always(bound(`m.id IN (SELECT e.id FROM emails e WHERE ${sql.join(" AND ")})`, ...params));
539
+ };
532
540
  const is = ({ value }, { mail }) => {
533
541
  const state = value.toLowerCase();
534
542
  return always(state === "starred"
@@ -634,5 +642,7 @@ export const FIELD_COMPILERS = {
634
642
  label: mailbox,
635
643
  list,
636
644
  is,
645
+ type: mailType("types"),
646
+ reach: mailType("reaches"),
637
647
  subject,
638
648
  };
@@ -4,6 +4,7 @@ import { isPresence, PRESENCE } from "../../search/lucene/registry.js";
4
4
  import { isStemmed } from "../../search/lucene/resolved.js";
5
5
  import { exhausted, outOfTime, QUERY_LIMITS, searchError, sqliteLimit, tooWideTerm } from "../../search/lucene/types.js";
6
6
  import { TIME_LIMIT_FUNCTION, TimeLimitReached } from "../driver.js";
7
+ import { typeCondition, typesCurrent } from "./email-types.js";
7
8
  import { emailHitsByPk } from "./emails.js";
8
9
  import { placeHits } from "./hit-places.js";
9
10
  import { combine, FIELD_COMPILERS, ftsMatch, MAIL, MESSAGES, present, quoted, SPEECH, } from "./lucene-fields.js";
@@ -107,6 +108,7 @@ const compileQuery = (context, execution, boundedAttachments = false) => {
107
108
  elsewhere,
108
109
  };
109
110
  };
111
+ let current;
110
112
  const fields = {
111
113
  database,
112
114
  execution,
@@ -124,6 +126,10 @@ const compileQuery = (context, execution, boundedAttachments = false) => {
124
126
  expansions += count;
125
127
  return expansions;
126
128
  },
129
+ mailTypes: (filter) => {
130
+ current ??= typesCurrent(database);
131
+ return typeCondition(database, filter, current, check);
132
+ },
127
133
  };
128
134
  const createLeaf = (node) => {
129
135
  const compiler = isPresence(node) && PRESENCE.has(node.field) ? present : FIELD_COMPILERS[node.field];
@@ -0,0 +1,122 @@
1
+ import { type MailType } from "../../mail/mail-types.js";
2
+ import { type SortAuthor, type SortIndex, type SortScope } from "../../mail/sort-rules.js";
3
+ import type { Decider } from "../decisions.js";
4
+ import type { CacheDatabase } from "../driver.js";
5
+ import type { StoreContext } from "./open.js";
6
+ /** One sorting rule. @experimental */
7
+ export interface SortRule {
8
+ id: number;
9
+ scope: SortScope;
10
+ /** The email's id, the List-Id, the subject pattern, the address or the registrable domain, as kept. */
11
+ value: string;
12
+ mailType: MailType | null;
13
+ sender: "bot" | "person" | null;
14
+ /** `organization:<id>`. */
15
+ organization: string | null;
16
+ overAddresses: boolean;
17
+ /** `false`: only mail dated from `createdAt` on. */
18
+ past: boolean;
19
+ author: SortAuthor;
20
+ decidedBy: string | null;
21
+ reason: string | null;
22
+ createdAt: number;
23
+ updatedAt: number;
24
+ removedAt: number | null;
25
+ }
26
+ /** A correction as the caller names it: its scope, and whether past mail is sorted too. @experimental */
27
+ export interface SortRuleInput {
28
+ scope: SortScope;
29
+ /** An email's id, a List-Id, a subject pattern, an address or a domain (kept as its registrable domain). */
30
+ value: string | number;
31
+ mailType?: MailType;
32
+ /** The owner's only; at `address` or `domain` scope; moves the sender for its whole history. */
33
+ sender?: "bot" | "person";
34
+ /** `organization:<id>`; the owner's only; at `address` or `domain` scope. */
35
+ organization?: string;
36
+ /** A domain rule that beats the address rules at its domain. */
37
+ overAddresses?: boolean;
38
+ /** `all`: mail already in the store too; `new`: only mail dated from now on. Always named. */
39
+ applyTo: "all" | "new";
40
+ reason?: string;
41
+ }
42
+ /** What a rule would touch, before it is set. @experimental */
43
+ export interface SortPreview {
44
+ scope: SortScope;
45
+ value: string;
46
+ /** The scope in words: "every mail from the domain gmail.com". */
47
+ label: string;
48
+ applyTo: "all" | "new";
49
+ /** The domain is a free-mail or throwaway one: the rule needs `confirm`. */
50
+ freeMail: boolean;
51
+ /** Distinct sender addresses its scope takes in. */
52
+ addresses: number;
53
+ /** Incoming emails its scope takes in. */
54
+ emails: number;
55
+ /** Of those, the emails whose type it would set now: a narrower rule or a past one left out. */
56
+ retyped: number;
57
+ /** Senders it would move to a bot or a person, or file under the organization. */
58
+ senders: number;
59
+ /** Pass to `add` to set a free-mail domain rule; it holds while these counts do. */
60
+ confirm: string | null;
61
+ }
62
+ /** @experimental */
63
+ export interface SortAddResult {
64
+ applied: boolean;
65
+ preview: SortPreview;
66
+ rule?: SortRule;
67
+ }
68
+ /** A scope a correction of one email may take, narrowest first: the domain is never offered first. @experimental */
69
+ export interface SortScopeChoice {
70
+ scope: SortScope;
71
+ value: string;
72
+ label: string;
73
+ /** A free-mail or throwaway domain: a rule there needs a dry run and its `confirm`. */
74
+ freeMail: boolean;
75
+ }
76
+ /** @experimental */
77
+ export interface SortUndo {
78
+ undid: "add" | "remove";
79
+ rule: SortRule;
80
+ }
81
+ /** @experimental */
82
+ export interface MailSorting {
83
+ /** Live rules, newest first; `removed` lists the removed ones instead. */
84
+ rules(options?: {
85
+ scope?: SortScope;
86
+ removed?: boolean;
87
+ }): Promise<SortRule[]>;
88
+ /** The scopes a correction of this email may take. */
89
+ scopes(email: number): Promise<SortScopeChoice[]>;
90
+ /**
91
+ * Sets a rule, or with `dryRun` only says what it would touch. A domain rule on a free-mail or throwaway domain is
92
+ * set only with the `confirm` of a dry run whose counts still hold. A program's rule sets a mail type only.
93
+ */
94
+ add(input: SortRuleInput, by: Decider, options?: {
95
+ dryRun?: boolean;
96
+ confirm?: string;
97
+ }): Promise<SortAddResult>;
98
+ /** Removes a rule: its mail is typed again without it, and the senders it moved go back. */
99
+ remove(rule: number, by: Decider): Promise<SortRule>;
100
+ /** Takes back the owner's newest add or removal not yet undone; `null` when there is none. */
101
+ undo(by: Decider): Promise<SortUndo | null>;
102
+ /**
103
+ * The owner's manual sorting of one sender, an address or a `person:` or `sender-bot:` ref, removed: its address
104
+ * rules and its one-mail rules. Domain and list rules stay. Answers the rules removed.
105
+ */
106
+ reset(sender: string, by: Decider): Promise<SortRule[]>;
107
+ }
108
+ /** The live rules that set a mail type, filed for `sortRuleFor`. */
109
+ export declare const typeRulesOf: (database: CacheDatabase) => SortIndex<SortRule>;
110
+ /** A free-mail or throwaway domain, whose addresses belong to anyone: a rule there sorts strangers together. */
111
+ export declare const isSharedMailDomain: (domain: string) => boolean;
112
+ /** Whether any rule moves senders or files them: sync then settles the senders it stored. */
113
+ export declare const hasSenderRules: (database: CacheDatabase) => boolean;
114
+ /**
115
+ * Each sender the winning rule has not acted on yet moves to a bot or a person through `moveToBot` and `moveToPerson`,
116
+ * or is filed under the rule's organization, and the effect is logged so a removal can put it back. A sender already
117
+ * where the rule says is logged as left. The caller holds the write lock.
118
+ */
119
+ export declare const settleSenders: (context: StoreContext, identities?: readonly number[]) => void;
120
+ export declare const mailSortingOver: (context: StoreContext) => MailSorting;
121
+ /** The senders of mail just saved in these threads, settled by the rules that move or file senders. */
122
+ export declare const settleThreads: (context: StoreContext, threads: readonly number[]) => void;