@wirecat/cli-core 0.751.0 → 0.753.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 (50) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/dist/cli/messenger/backfill-command.js +3 -1
  3. package/dist/crm/index.d.ts +1 -1
  4. package/dist/crm/index.js +1 -1
  5. package/dist/crm/manifest/writer.d.ts +23 -4
  6. package/dist/crm/manifest/writer.js +46 -8
  7. package/dist/crm/writer.d.ts +3 -2
  8. package/dist/crm/writer.js +9 -3
  9. package/dist/crm/writes.d.ts +2 -0
  10. package/dist/crm/writes.js +7 -4
  11. package/dist/domain/addresses.d.ts +8 -3
  12. package/dist/domain/addresses.js +24 -6
  13. package/dist/domain/person-kinds.d.ts +1 -1
  14. package/dist/errors/reasons.js +1 -0
  15. package/dist/mail/email-input.d.ts +1 -1
  16. package/dist/mail/email-input.js +3 -2
  17. package/dist/mail/folders.d.ts +6 -1
  18. package/dist/mail/folders.js +10 -5
  19. package/dist/mail/headers.d.ts +9 -5
  20. package/dist/mail/headers.js +63 -5
  21. package/dist/mail/own.d.ts +15 -0
  22. package/dist/mail/own.js +35 -0
  23. package/dist/mail/partial.js +4 -1
  24. package/dist/mail/server-search.js +3 -1
  25. package/dist/mail/source.d.ts +5 -1
  26. package/dist/mail/sync-types.d.ts +2 -0
  27. package/dist/mail/sync.js +16 -4
  28. package/dist/mail/testing/fake.d.ts +4 -0
  29. package/dist/mail/testing/fake.js +3 -1
  30. package/dist/mail/whole.js +3 -1
  31. package/dist/store/index.d.ts +1 -0
  32. package/dist/store/index.js +1 -0
  33. package/dist/store/messages.js +1 -0
  34. package/dist/store/sqlite/email-activity.d.ts +1 -1
  35. package/dist/store/sqlite/email-activity.js +4 -1
  36. package/dist/store/sqlite/email-state.d.ts +8 -0
  37. package/dist/store/sqlite/email-state.js +23 -0
  38. package/dist/store/sqlite/emails.d.ts +9 -0
  39. package/dist/store/sqlite/emails.js +2 -1
  40. package/dist/store/sqlite/messages.d.ts +5 -0
  41. package/dist/store/sqlite/messages.js +13 -3
  42. package/dist/store/sqlite/own-identities.d.ts +2 -0
  43. package/dist/store/sqlite/own-identities.js +24 -1
  44. package/dist/store/sqlite/people-list.d.ts +12 -0
  45. package/dist/store/sqlite/people-list.js +31 -7
  46. package/dist/store/sqlite/person-match-scan.js +34 -4
  47. package/dist/store/sqlite/record-projectors-phone.js +2 -1
  48. package/dist/store/sqlite/sender-signals.d.ts +42 -0
  49. package/dist/store/sqlite/sender-signals.js +106 -0
  50. package/package.json +1 -1
@@ -1,6 +1,7 @@
1
1
  import { type KindSignal, type PersonKind } from "../../domain/person-kinds.js";
2
2
  import { type CacheDatabase } from "../driver.js";
3
3
  import { type ShownBecause } from "./person-ties.js";
4
+ import { type Reach, type SenderSignal } from "./sender-signals.js";
4
5
  export declare const PEOPLE_SORTS: readonly ["interactions", "recent", "name", "tasks"];
5
6
  export type PeopleSort = (typeof PEOPLE_SORTS)[number];
6
7
  export interface PeopleListOptions {
@@ -39,6 +40,10 @@ export interface ListedPerson {
39
40
  lastContact: string | null;
40
41
  /** Why they are shown; empty for someone hidden by default. */
41
42
  ties: ShownBecause[];
43
+ /** How their messages reached the owner (`senderSignalsOf`); `null` when nothing says. Worked out for the page. */
44
+ reach: Reach | null;
45
+ /** What their mail and addresses show about who writes and how it reached the owner. Worked out for the page. */
46
+ signals: SenderSignal[];
42
47
  }
43
48
  export interface PeopleList {
44
49
  items: ListedPerson[];
@@ -52,6 +57,13 @@ export interface SimilarPerson extends ListedPerson {
52
57
  /** The same name once case, quotes, punctuation and word order are set aside: maybe the same person. */
53
58
  sameName: boolean;
54
59
  }
60
+ /**
61
+ * Works out and keeps the kind, name order and counts of every person whose stored ones the triggers cleared.
62
+ * A few, as a sync leaves, are worked out under the write lock. Everyone, after an upgrade, would hold the lock for
63
+ * seconds: that pass runs outside it and is kept only when no other process wrote meanwhile, else it runs again.
64
+ * Answers whether every stored one is current.
65
+ */
66
+ export declare const storeKinds: (database: CacheDatabase) => boolean;
55
67
  /** How many people of each kind match the query, every kind at once. */
56
68
  export declare const countPeople: (database: CacheDatabase, query?: string) => Record<PersonKind, number>;
57
69
  /** People of one kind, the owner first, in the order asked; `counts` says how many each kind holds. */
@@ -1,5 +1,5 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
- import { isNoReplyAddress, isPersonLikeRoleAddress, isRoleAddress } from "../../domain/addresses.js";
2
+ import { isNoReplyAddress, isNotificationAddress, isPersonLikeRoleAddress, isRoleAddress, } from "../../domain/addresses.js";
3
3
  import { displayName, isReadable, nameKey, noFallbacks, takeFallbacks } from "../../domain/display-names.js";
4
4
  import { spellings, variantKey } from "../../domain/name-variants.js";
5
5
  import { isAutomatedName, isCompanyName, PERSON_KINDS, } from "../../domain/person-kinds.js";
@@ -7,6 +7,7 @@ import { isQueryOnly } from "../driver.js";
7
7
  import { fold } from "../normalize.js";
8
8
  import { mergedAwaySql } from "./merged-persons.js";
9
9
  import { ALWAYS_SHOWN, shownReasons } from "./person-ties.js";
10
+ import { senderSignalsOf, sentMailOf } from "./sender-signals.js";
10
11
  import { mergedAssignees } from "./task-board.js";
11
12
  import { hiddenTestPeople } from "./test-people.js";
12
13
  import { read, writeBatch } from "./transaction.js";
@@ -48,7 +49,9 @@ const TWO_WAY = "SELECT DISTINCT s.sender_identity_id AS identity_id FROM messag
48
49
  "AND s.sender_identity_id IS NOT NULL AND s.chat_id IN (SELECT c.id FROM chats c WHERE c.kind = 'dialog' " +
49
50
  "AND EXISTS (SELECT 1 FROM messages o WHERE o.chat_id = c.id AND o.outgoing = 1))";
50
51
  const MAIL_COUNTS = (scope) => "SELECT l.person_id AS person, count(*) AS n, sum(EXISTS (SELECT 1 FROM email_mailboxes m " +
51
- "JOIN mailboxes b ON b.id = m.mailbox_id WHERE m.email_id = e.id AND b.kind = 'bulk')) AS bulk " +
52
+ "JOIN mailboxes b ON b.id = m.mailbox_id WHERE m.email_id = e.id AND b.kind = 'bulk')) AS bulk, " +
53
+ "sum(json_extract(e.headers, '$.\"auto-submitted\"') IS NOT NULL) AS auto, " +
54
+ "sum(json_extract(e.headers, '$.\"null-return-path\"') IS 1) AS null_return " +
52
55
  "FROM emails e JOIN identity_links l ON l.identity_id = e.from_identity_id " +
53
56
  `WHERE e.outgoing IS NOT 1 AND e.deleted_at IS NULL AND ${IN_SCOPE(scope, "l.person_id")} GROUP BY 1`;
54
57
  const IDENTITIES = (scope) => "SELECT l.person_id AS person, i.id, i.provider, i.external_id, i.name, i.username, i.phone, i.email, i.bot " +
@@ -164,9 +167,15 @@ const kindOf = (shown, facts, ties, mail, test) => {
164
167
  const automated = [
165
168
  ...(facts?.bot ? ["bot"] : []),
166
169
  ...(emails.some(isNoReplyAddress) ? ["no-reply"] : []),
170
+ ...(emails.some(isNotificationAddress) ? ["notification-address"] : []),
167
171
  ...(mail !== undefined && mail.n >= BULK_MIN && mail.bulk * 2 > mail.n ? ["bulk-mail"] : []),
168
172
  ...(facts?.neverReplied ? ["bulk-never-replied"] : []),
169
173
  ...(isAutomatedName(shown) ? ["automated-name"] : []),
174
+ // A guess from headers never outweighs mail the owner wrote them.
175
+ ...(mail !== undefined && !ties.includes("mail") && mail.auto * 2 > mail.n ? ["auto-submitted"] : []),
176
+ ...(mail !== undefined && !ties.includes("mail") && mail.nullReturn * 2 > mail.n
177
+ ? ["null-return-path"]
178
+ : []),
170
179
  ];
171
180
  // One mailbox's newsletter signal must not hide someone the owner talks to in a private chat.
172
181
  if (automated.length > 0 && (facts?.bot || !facts?.twoWay))
@@ -194,7 +203,10 @@ const classified = (database, people, scope, reasons = shownReasons(database, sc
194
203
  const mail = new Map(database
195
204
  .prepare(MAIL_COUNTS(scope))
196
205
  .all(...scopeParams(scope))
197
- .map((row) => [Number(row.person), { n: Number(row.n), bulk: Number(row.bulk) }]));
206
+ .map((row) => [
207
+ Number(row.person),
208
+ { n: Number(row.n), bulk: Number(row.bulk), auto: Number(row.auto), nullReturn: Number(row.null_return) },
209
+ ]));
198
210
  return people.map(({ id, name, owner }) => {
199
211
  const own = facts.get(id);
200
212
  const contact = { username: own?.username ?? null, phone: own?.phone ?? null, email: own?.email ?? null };
@@ -216,15 +228,27 @@ const classified = (database, people, scope, reasons = shownReasons(database, sc
216
228
  usernameSource: own?.usernameSource ?? null,
217
229
  messagesFrom: (own?.messages ?? 0) + (mail.get(id)?.n ?? 0),
218
230
  ties,
231
+ emails: own?.emails ?? [],
232
+ twoWay: own?.twoWay ?? false,
219
233
  };
220
234
  });
221
235
  };
222
236
  const withLastContact = (database, people, known) => {
223
237
  const at = known ??
224
238
  lastContacts(database, people.map(({ id }) => id));
225
- return people.map(({ id, nameOrder: _, ...person }) => {
239
+ const sent = sentMailOf(database, people.map(({ id }) => id));
240
+ return people.map(({ id, nameOrder: _, emails, twoWay, ...person }) => {
226
241
  const time = at.get(id);
227
- return { ...person, lastContact: time === undefined ? null : new Date(time).toISOString() };
242
+ const { ties } = person;
243
+ return {
244
+ ...person,
245
+ lastContact: time === undefined ? null : new Date(time).toISOString(),
246
+ ...senderSignalsOf(sent.get(id) ?? [], {
247
+ addresses: emails,
248
+ ownerWrote: twoWay || ties.includes("mail"),
249
+ chatted: ties.includes("chat") || ties.includes("small-group"),
250
+ }),
251
+ };
228
252
  });
229
253
  };
230
254
  /** Sorted as read, case and accents aside; a name with nothing to read goes last. */
@@ -234,7 +258,7 @@ const byName = (a, b) => a.nameOrder < b.nameOrder ? -1 : a.nameOrder > b.nameOr
234
258
  * Bump when what decides a kind, a name's order or a count changes in code (the word lists, `BULK_MIN`, the ties):
235
259
  * every stored one is worked out again on the next list.
236
260
  */
237
- const KIND_RULES = "4";
261
+ const KIND_RULES = "6";
238
262
  const RULES_KEY = "people.kind_rules";
239
263
  /** Past this many people to work out, one pass over everyone beats a lookup per person. */
240
264
  const WHOLE_PASS = 20_000;
@@ -288,7 +312,7 @@ const keep = (database, worked) => {
288
312
  * seconds: that pass runs outside it and is kept only when no other process wrote meanwhile, else it runs again.
289
313
  * Answers whether every stored one is current.
290
314
  */
291
- const storeKinds = (database) => {
315
+ export const storeKinds = (database) => {
292
316
  if (isQueryOnly(database))
293
317
  return (rulesOf(database) === KIND_RULES &&
294
318
  database.prepare("SELECT 1 FROM persons WHERE kind IS NULL LIMIT 1").get() === undefined);
@@ -2,9 +2,10 @@ import { isEmailAddress, isNoReplyAddress, isPersonLikeRoleAddress, isRoleAddres
2
2
  import { displayName, isReadable } from "../../domain/display-names.js";
3
3
  import { variantKey } from "../../domain/name-variants.js";
4
4
  import { BARE_INTERNATIONAL_PROVIDERS, isMobilePhone, nationalPhone, storedPhone } from "../../domain/phones.js";
5
- import { linkIndex, settleLinks } from "./identity-link-rows.js";
5
+ import { linkIndex, linkRows, settleLinks } from "./identity-link-rows.js";
6
6
  import { openIdentityLink } from "./identity-proposals.js";
7
7
  import { peopleByNameKey, sharedTraces } from "./name-traces.js";
8
+ import { storeKinds } from "./people-list.js";
8
9
  import { isOwner, mergePerson } from "./person-links.js";
9
10
  import { personsByIdentifiers } from "./person-matcher.js";
10
11
  import { resolvePersonLinks } from "./person-resolution.js";
@@ -19,7 +20,7 @@ export const RULE = { bot: "rule", kind: "rule" };
19
20
  const MOST_SHARING = 6;
20
21
  const CURSOR = "people.scan";
21
22
  /** Raised when a rule changes what a pass finds in values nobody touched: the next pass then reads everything once. */
22
- const RULES = 6;
23
+ const RULES = 7;
23
24
  /**
24
25
  * NEED-2526: a shared mailbox says little alone, so its proposal is scored by what else the two people have in common.
25
26
  * The owner's word (2026-11-11): `hr@` is often one person's, so it starts below `info@`.
@@ -391,7 +392,14 @@ const strongEnough = (context, from, to, trace) => {
391
392
  * One name and a shared trace (a phone, an address, a chat, a company's domain) only proposes: a name is common, so
392
393
  * the owner decides every merge. More than `MOST_SHARING` people on one name is too common to propose from.
393
394
  */
394
- const sameName = (pass, people, name) => {
395
+ const sameName = (pass, named, name) => {
396
+ const people = named.filter((one) => !pass.notByName.has(one));
397
+ if (people.length < named.length)
398
+ pass.result.skipped.push({
399
+ persons: named.filter((one) => pass.notByName.has(one)).map(String),
400
+ signal: "name",
401
+ reason: "identity.not-a-person",
402
+ });
395
403
  if (people.length > MOST_SHARING) {
396
404
  pass.result.skipped.push({ persons: people.map(String), signal: "name", reason: "identity.common-name" });
397
405
  return;
@@ -445,7 +453,7 @@ const sameNameInChats = (pass, holders) => {
445
453
  const people = new Map();
446
454
  for (const holder of holders) {
447
455
  const person = personOf(pass.context, holder.identity);
448
- if (person !== undefined && !people.has(person))
456
+ if (person !== undefined && !pass.notByName.has(person) && !people.has(person))
449
457
  people.set(person, holder);
450
458
  }
451
459
  if (people.size < 2)
@@ -536,6 +544,24 @@ const guestRows = (database) => database
536
544
  email: row.email,
537
545
  meeting: Number(row.meeting),
538
546
  }));
547
+ /**
548
+ * Kinds are worked out first, since a join above clears them; anyone whose kind is still not worked out (another
549
+ * writer won the race) is taken for a person this pass.
550
+ */
551
+ const notByNameOf = (database) => {
552
+ storeKinds(database);
553
+ return new Set(database
554
+ .prepare("SELECT id FROM persons WHERE kind IN ('automated', 'organization') UNION SELECT l.person_id " +
555
+ `FROM identity_links l JOIN identities i ON i.id = l.identity_id WHERE NOT (${NOT_A_BOT})`)
556
+ .all()
557
+ .map((row) => Number(row.id)));
558
+ };
559
+ /** Open name proposals made before one side was known to be no person, which nobody should review now. */
560
+ const forgetNameProposals = (database, notByName) => {
561
+ for (const row of linkRows(database, ["proposed"]))
562
+ if (row.payload.signal === "name" && row.pair?.some((person) => notByName.has(person)))
563
+ database.prepare("DELETE FROM proposed_actions WHERE id = ?").run(Number(row.id));
564
+ };
539
565
  /**
540
566
  * One pass of the people matcher. It reads what may match outside any transaction and takes the write lock only for
541
567
  * each group it changes, so other writers are never kept waiting for the whole pass. After the first pass, only the
@@ -554,6 +580,7 @@ export const scanMatches = (context, { full = false } = {}) => {
554
580
  index: linkIndex(database),
555
581
  result: { full: changed === undefined, merged: [], proposed: [], skipped: [] },
556
582
  shared: [],
583
+ notByName: new Set(),
557
584
  };
558
585
  for (const [address, holders] of emailHolders(database))
559
586
  if (holders.length > 1 && touched(holders))
@@ -566,6 +593,8 @@ export const scanMatches = (context, { full = false } = {}) => {
566
593
  for (const row of guestRows(database))
567
594
  if ((changed === undefined || changed.has(row.identity)) && !pass.index.names(row.ref))
568
595
  write(database, () => guestEmail(pass, row));
596
+ pass.notByName = notByNameOf(database);
597
+ write(database, () => forgetNameProposals(database, pass.notByName));
569
598
  const changedPeople = changed === undefined ? undefined : peopleOfIdentities(context, changed);
570
599
  for (const { people, name } of peopleByNameKey(database).values())
571
600
  if (people.length > 1 && (changedPeople === undefined || people.some((one) => changedPeople.has(one))))
@@ -592,6 +621,7 @@ export const linkPhones = (context, identities) => {
592
621
  index: linkIndex(database),
593
622
  result: { full: false, merged: [], proposed: [], skipped: [] },
594
623
  shared: [],
624
+ notByName: new Set(),
595
625
  };
596
626
  for (const [phone, holders] of phoneHolders(database))
597
627
  if (holders.length > 1 && holders.some(({ identity }) => identities.has(identity)))
@@ -5,7 +5,7 @@ import { calendarWritesOver } from "./calendar.js";
5
5
  import { chatPkFor, findChatPk, raiseLastMessageAt, upsertChat, writeMembers } from "./chats.js";
6
6
  import { seenIdentity } from "./identities.js";
7
7
  import { COUNTERPART_ROLE, linkKind } from "./link-kinds.js";
8
- import { tombstone, upsertMessage } from "./messages.js";
8
+ import { linkThreadChildren, tombstone, upsertMessage } from "./messages.js";
9
9
  import { requiredThing } from "./notes.js";
10
10
  import { e164Of } from "./person-matcher.js";
11
11
  import { importedIdentity, linkToPerson } from "./record-matching.js";
@@ -88,6 +88,7 @@ const saveSms = (projection, tools, revive = false) => {
88
88
  };
89
89
  // Seen after its tombstone, the messenger path takes a deleted message back, its text with it.
90
90
  upsertMessage(context, account, account.pk, chatKey, message, importedBy(source).source, revive ? context.now() + 1 : undefined);
91
+ linkThreadChildren(context, chatKey, [message.id]);
91
92
  raiseLastMessageAt(context, chatKey, sentAt);
92
93
  return formatReference({
93
94
  type: "message",
@@ -0,0 +1,42 @@
1
+ import type { CacheDatabase } from "../driver.js";
2
+ /**
3
+ * How a sender's messages reached the owner: written to them or a few people, in a large group or a discussion list,
4
+ * or sent to many readers who cannot answer in place.
5
+ */
6
+ export declare const REACHES: readonly ["direct", "group", "broadcast"];
7
+ export type Reach = (typeof REACHES)[number];
8
+ /** What the mail of one sender shows about who writes and how it reached the owner. */
9
+ export type SenderSignal = "auto-submitted" | "null-return-path" | "no-reply" | "one-click-unsubscribe" | "feedback-id" | "bulk-mail" | "discussion-list" | "many-recipients" | "undisclosed-recipients";
10
+ /** One email a sender sent the owner, as the store keeps it (`mailHeadersOf`, the mailboxes, the recipients). */
11
+ export interface SentMail {
12
+ autoSubmitted: boolean;
13
+ nullReturnPath: boolean;
14
+ oneClick: boolean;
15
+ feedbackId: boolean;
16
+ /** In the bulk box: List-Id, List-Unsubscribe or `Precedence: bulk`. */
17
+ bulk: boolean;
18
+ /** A List-Id at least `DISCUSSION_SENDERS` addresses send to. */
19
+ discussionList: boolean;
20
+ /** To and Cc together; `null` when the store holds no recipients for it (mail recorded as an envelope). */
21
+ recipients: number | null;
22
+ }
23
+ /** A list three people write to is a discussion; one sender, even under `+tag` addresses, is a newsletter. */
24
+ export declare const DISCUSSION_SENDERS = 3;
25
+ /**
26
+ * A sender's signals and reach, worked out from their mail alone. Reach is the one most of their mail reached the
27
+ * owner by, the wider on a tie. Mail the owner wrote them, or a private chat both wrote in, makes it `direct`
28
+ * whatever their other mail shows; with no mail, a one-to-one chat or a small group does. `null`: nothing says.
29
+ */
30
+ export declare const senderSignalsOf: (mail: readonly SentMail[], { addresses, ownerWrote, chatted }: {
31
+ addresses: readonly string[];
32
+ ownerWrote: boolean;
33
+ chatted: boolean;
34
+ }) => {
35
+ signals: SenderSignal[];
36
+ reach: Reach | null;
37
+ };
38
+ /**
39
+ * The mail each of these people sent the owner, as `senderSignalsOf` reads it. Asked for a page of people only: it
40
+ * reads every stored email's List-Id once to tell a discussion list from a newsletter.
41
+ */
42
+ export declare const sentMailOf: (database: CacheDatabase, people: readonly number[]) => Map<number, SentMail[]>;
@@ -0,0 +1,106 @@
1
+ import { isNoReplyAddress } from "../../domain/addresses.js";
2
+ import { SMALL_GROUP_MEMBERS } from "./person-ties.js";
3
+ /**
4
+ * How a sender's messages reached the owner: written to them or a few people, in a large group or a discussion list,
5
+ * or sent to many readers who cannot answer in place.
6
+ */
7
+ export const REACHES = ["direct", "group", "broadcast"];
8
+ /** A list three people write to is a discussion; one sender, even under `+tag` addresses, is a newsletter. */
9
+ export const DISCUSSION_SENDERS = 3;
10
+ const reachOfOne = (mail) => {
11
+ if (mail.discussionList)
12
+ return { reach: "group", signal: "discussion-list" };
13
+ if (mail.oneClick)
14
+ return { reach: "broadcast", signal: "one-click-unsubscribe" };
15
+ if (mail.feedbackId)
16
+ return { reach: "broadcast", signal: "feedback-id" };
17
+ if (mail.bulk)
18
+ return { reach: "broadcast", signal: "bulk-mail" };
19
+ // The owner missing from a To or Cc that names others proves nothing: an alias the store does not know looks so.
20
+ if (mail.recipients === 0)
21
+ return { reach: "broadcast", signal: "undisclosed-recipients" };
22
+ if (mail.recipients !== null && mail.recipients > SMALL_GROUP_MEMBERS)
23
+ return { reach: "group", signal: "many-recipients" };
24
+ return { reach: "direct" };
25
+ };
26
+ /** More than half of their mail: one misfiled letter decides nothing. */
27
+ const most = (mail, holds) => mail.filter(holds).length * 2 > mail.length;
28
+ /**
29
+ * A sender's signals and reach, worked out from their mail alone. Reach is the one most of their mail reached the
30
+ * owner by, the wider on a tie. Mail the owner wrote them, or a private chat both wrote in, makes it `direct`
31
+ * whatever their other mail shows; with no mail, a one-to-one chat or a small group does. `null`: nothing says.
32
+ */
33
+ export const senderSignalsOf = (mail, { addresses, ownerWrote, chatted }) => {
34
+ const signals = new Set();
35
+ if (mail.length > 0 && most(mail, (one) => one.autoSubmitted))
36
+ signals.add("auto-submitted");
37
+ if (mail.length > 0 && most(mail, (one) => one.nullReturnPath))
38
+ signals.add("null-return-path");
39
+ if (addresses.some(isNoReplyAddress))
40
+ signals.add("no-reply");
41
+ const votes = new Map();
42
+ for (const one of mail) {
43
+ const { reach, signal } = reachOfOne(one);
44
+ votes.set(reach, (votes.get(reach) ?? 0) + 1);
45
+ if (signal !== undefined)
46
+ signals.add(signal);
47
+ }
48
+ const voted = [...REACHES].reverse().reduce((best, reach) => {
49
+ const n = votes.get(reach) ?? 0;
50
+ return n > 0 && (best === null || n > (votes.get(best) ?? 0)) ? reach : best;
51
+ }, null);
52
+ const reach = ownerWrote ? "direct" : (voted ?? (chatted ? "direct" : null));
53
+ return { signals: [...signals], reach };
54
+ };
55
+ const LIST_ID = "coalesce(json_extract(e.headers, '$.\"list-id\"'), json_extract(e.metadata, '$.listId'))";
56
+ /** `bob+news@x` and `bob@x` are one sender. */
57
+ const senderKey = (address) => address.toLowerCase().replace(/\+[^@]*@/, "@");
58
+ /**
59
+ * The mail each of these people sent the owner, as `senderSignalsOf` reads it. Asked for a page of people only: it
60
+ * reads every stored email's List-Id once to tell a discussion list from a newsletter.
61
+ */
62
+ export const sentMailOf = (database, people) => {
63
+ const found = new Map();
64
+ if (people.length === 0)
65
+ return found;
66
+ const rows = database
67
+ .prepare("SELECT l.person_id AS person, " +
68
+ `${LIST_ID} AS list, json_extract(e.headers, '$."auto-submitted"') IS NOT NULL AS auto, ` +
69
+ "json_extract(e.headers, '$.\"null-return-path\"') IS 1 AS null_return, " +
70
+ "json_extract(e.headers, '$.\"list-unsubscribe-post\"') IS 1 AS one_click, " +
71
+ "json_extract(e.headers, '$.\"feedback-id\"') IS 1 AS feedback, " +
72
+ "EXISTS (SELECT 1 FROM email_mailboxes m JOIN mailboxes b ON b.id = m.mailbox_id " +
73
+ "WHERE m.email_id = e.id AND b.kind = 'bulk') AS bulk, " +
74
+ "CASE WHEN json_extract(e.metadata, '$.rule') IS NOT NULL THEN NULL ELSE " +
75
+ "(SELECT count(*) FROM email_recipients r WHERE r.email_id = e.id AND r.role IN ('to', 'cc')) END AS recipients " +
76
+ "FROM emails e JOIN identity_links l ON l.identity_id = e.from_identity_id " +
77
+ "WHERE e.outgoing IS NOT 1 AND e.deleted_at IS NULL AND l.person_id IN (SELECT value FROM json_each(?))")
78
+ .all(JSON.stringify(people));
79
+ const lists = [...new Set(rows.flatMap((row) => (typeof row.list === "string" ? [row.list] : [])))];
80
+ const senders = new Map();
81
+ if (lists.length > 0)
82
+ for (const row of database
83
+ .prepare(`SELECT DISTINCT ${LIST_ID} AS list, e.from_address AS address FROM emails e ` +
84
+ `WHERE e.from_address IS NOT NULL AND ${LIST_ID} IN (SELECT value FROM json_each(?))`)
85
+ .all(JSON.stringify(lists))) {
86
+ const list = String(row.list);
87
+ const held = senders.get(list) ?? new Set();
88
+ held.add(senderKey(String(row.address)));
89
+ senders.set(list, held);
90
+ }
91
+ for (const row of rows) {
92
+ const person = Number(row.person);
93
+ const held = found.get(person) ?? [];
94
+ held.push({
95
+ autoSubmitted: Number(row.auto) === 1,
96
+ nullReturnPath: Number(row.null_return) === 1,
97
+ oneClick: Number(row.one_click) === 1,
98
+ feedbackId: Number(row.feedback) === 1,
99
+ bulk: Number(row.bulk) === 1,
100
+ discussionList: typeof row.list === "string" && (senders.get(row.list)?.size ?? 0) >= DISCUSSION_SENDERS,
101
+ recipients: row.recipients == null ? null : Number(row.recipients),
102
+ });
103
+ found.set(person, held);
104
+ }
105
+ return found;
106
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.751.0",
3
+ "version": "0.753.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",