@wirecat/cli-core 1.2.0 → 2.0.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.
- package/CHANGELOG.md +170 -0
- package/dist/attachments/container.d.ts +1 -1
- package/dist/attachments/container.js +16 -7
- package/dist/attachments/limits.d.ts +10 -0
- package/dist/attachments/limits.js +30 -1
- package/dist/attachments/transfer.js +2 -2
- package/dist/cli/app-doctor-command.d.ts +61 -7
- package/dist/cli/app-doctor-command.js +24 -11
- package/dist/cli/contract-templates.js +3 -0
- package/dist/cli/documents/file-edit.js +6 -6
- package/dist/cli/documents/library.js +4 -2
- package/dist/cli/help/first-screen.js +2 -2
- package/dist/cli/index.d.ts +7 -6
- package/dist/cli/index.js +3 -2
- package/dist/cli/messenger/account-command.js +0 -10
- package/dist/cli/messenger/accounts.d.ts +1 -1
- package/dist/cli/messenger/accounts.js +1 -1
- package/dist/cli/messenger/context.d.ts +17 -1
- package/dist/cli/messenger/doctor-command.js +16 -1
- package/dist/cli/messenger/flooded.js +9 -1
- package/dist/cli/messenger/serve-relay.d.ts +2 -0
- package/dist/cli/messenger/session-commands.d.ts +1 -1
- package/dist/cli/messenger/session-commands.js +1 -1
- package/dist/cli/oauth-session.d.ts +3 -2
- package/dist/cli/oauth-session.js +19 -3
- package/dist/cli/profile-store.d.ts +24 -10
- package/dist/cli/profile-store.js +43 -28
- package/dist/cli/program.js +2 -2
- package/dist/cli/settings.d.ts +3 -3
- package/dist/cli/shared-command-exports.d.ts +1 -1
- package/dist/cli/token-session.d.ts +21 -2
- package/dist/cli/token-session.js +27 -11
- package/dist/crm/cli/files.js +7 -7
- package/dist/documents.d.ts +1 -1
- package/dist/documents.js +1 -1
- package/dist/domain/person-kinds.d.ts +7 -3
- package/dist/domain/person-kinds.js +7 -3
- package/dist/domain/ref-summaries.js +1 -0
- package/dist/domain/references.d.ts +3 -2
- package/dist/domain/references.js +19 -10
- package/dist/entities/deal.d.ts +2 -2
- package/dist/entities/deal.js +1 -1
- package/dist/entities/fact.d.ts +2 -2
- package/dist/entities/fact.js +1 -1
- package/dist/entities/fields.d.ts +1 -1
- package/dist/entities/fields.js +1 -1
- package/dist/entities/index.d.ts +15 -15
- package/dist/entities/mail-findings.d.ts +2 -2
- package/dist/entities/mail-findings.js +1 -1
- package/dist/entities/meeting-findings.d.ts +2 -2
- package/dist/entities/meeting-findings.js +1 -1
- package/dist/entities/memory.d.ts +1 -1
- package/dist/entities/store-maintenance.js +1 -1
- package/dist/entities/task-results.d.ts +5 -5
- package/dist/entities/task-results.js +1 -1
- package/dist/entities/task.d.ts +1 -1
- package/dist/entities/task.js +1 -1
- package/dist/errors/failures.d.ts +6 -0
- package/dist/errors/failures.js +18 -4
- package/dist/errors/reasons.js +2 -1
- package/dist/errors/store-reasons.js +1 -0
- package/dist/fetch/page.js +1 -2
- package/dist/mail/headers.d.ts +4 -3
- package/dist/mail/headers.js +21 -3
- package/dist/mail/sort-rules.d.ts +13 -6
- package/dist/mail/sort-rules.js +20 -16
- package/dist/mail/sync.js +2 -0
- package/dist/mcp/tool.js +2 -2
- package/dist/mcp/tools/attachments.js +1 -1
- package/dist/office/zip.js +1 -1
- package/dist/ports/messenger.d.ts +31 -1
- package/dist/runs/recording.js +2 -2
- package/dist/services/archive.js +61 -11
- package/dist/services/attachments.js +4 -4
- package/dist/services/documents/file-text.js +2 -2
- package/dist/services/metadata.d.ts +1 -1
- package/dist/services/proposals/kinds/shared.d.ts +1 -1
- package/dist/services/proposals/kinds/shared.js +2 -2
- package/dist/services/proposals/kinds/task-close.js +1 -1
- package/dist/store/areas.d.ts +2 -0
- package/dist/store/areas.js +1 -0
- package/dist/store/decisions.d.ts +1 -1
- package/dist/store/decisions.js +4 -4
- package/dist/store/evidence-findings.d.ts +2 -2
- package/dist/store/index.d.ts +3 -1
- package/dist/store/index.js +2 -1
- package/dist/store/mail-findings.d.ts +2 -2
- package/dist/store/meeting-findings.d.ts +2 -2
- package/dist/store/people.d.ts +4 -4
- package/dist/store/people.js +2 -1
- package/dist/store/project-transfer/manifest.js +3 -3
- package/dist/store/public.d.ts +1 -1
- package/dist/store/public.js +1 -1
- package/dist/store/sqlite/actors.d.ts +1 -1
- package/dist/store/sqlite/actors.js +6 -6
- package/dist/store/sqlite/agent-actions.js +2 -2
- package/dist/store/sqlite/agent-links.js +1 -1
- package/dist/store/sqlite/bot-sends.d.ts +19 -0
- package/dist/store/sqlite/bot-sends.js +36 -0
- package/dist/store/sqlite/business-contracts.js +1 -1
- package/dist/store/sqlite/deals.js +1 -1
- package/dist/store/sqlite/document-transfer/plan.js +1 -1
- package/dist/store/sqlite/document-transfer/snapshot.js +1 -1
- package/dist/store/sqlite/email-index.d.ts +11 -2
- package/dist/store/sqlite/email-index.js +56 -5
- package/dist/store/sqlite/email-types.d.ts +15 -3
- package/dist/store/sqlite/email-types.js +32 -1
- package/dist/store/sqlite/emails.d.ts +2 -1
- package/dist/store/sqlite/emails.js +6 -1
- package/dist/store/sqlite/entity-types.d.ts +1 -1
- package/dist/store/sqlite/entity-types.js +1 -1
- package/dist/store/sqlite/evidence-findings.js +1 -1
- package/dist/store/sqlite/facts.js +1 -1
- package/dist/store/sqlite/finance.js +2 -2
- package/dist/store/sqlite/knowledge.js +1 -0
- package/dist/store/sqlite/mail-findings.js +1 -1
- package/dist/store/sqlite/mail-sorting.d.ts +1 -1
- package/dist/store/sqlite/mail-sorting.js +96 -60
- package/dist/store/sqlite/mail-subscriptions.d.ts +70 -0
- package/dist/store/sqlite/mail-subscriptions.js +132 -0
- package/dist/store/sqlite/manifest.js +45 -0
- package/dist/store/sqlite/meeting-findings.js +1 -1
- package/dist/store/sqlite/memories.js +3 -3
- package/dist/store/sqlite/migrations.generated.js +80 -0
- package/dist/store/sqlite/money-transactions.js +1 -1
- package/dist/store/sqlite/note-index.d.ts +4 -1
- package/dist/store/sqlite/note-index.js +40 -17
- package/dist/store/sqlite/orders.js +1 -1
- package/dist/store/sqlite/payment-facts.js +2 -2
- package/dist/store/sqlite/products.js +1 -1
- package/dist/store/sqlite/project-transfer/sources.js +2 -2
- package/dist/store/sqlite/proposed-actions.js +3 -3
- package/dist/store/sqlite/record-projection.js +1 -1
- package/dist/store/sqlite/ref-summaries.js +2 -1
- package/dist/store/sqlite/relation-proposals.js +1 -1
- package/dist/store/sqlite/reviewed.d.ts +2 -2
- package/dist/store/sqlite/reviewed.js +1 -1
- package/dist/store/sqlite/sender-bots.d.ts +19 -4
- package/dist/store/sqlite/sender-bots.js +48 -4
- package/dist/store/sqlite/subscriptions.js +2 -2
- package/dist/store/sqlite/task-close.js +1 -1
- package/dist/store/sqlite/task-comments.js +1 -1
- package/dist/store/sqlite/things.js +1 -1
- package/dist/store/sqlite/transaction.d.ts +5 -0
- package/dist/store/sqlite/transaction.js +6 -1
- package/dist/store/sqlite/wallets.js +1 -1
- package/dist/store/sqlite/work-tasks.js +2 -2
- package/dist/tracker/tasks.js +4 -2
- package/package.json +7 -5
- package/parity.json +9 -3
|
@@ -107,7 +107,7 @@ export const typesCurrent = (database) => rulesOf(database) === TYPE_RULES && !a
|
|
|
107
107
|
* changed, a batch per write so another process never waits long for the lock. A query-only open keeps nothing.
|
|
108
108
|
* Answers whether every stored type is current.
|
|
109
109
|
*/
|
|
110
|
-
export const storeMailTypes = (database) => {
|
|
110
|
+
export const storeMailTypes = (database, until = () => false) => {
|
|
111
111
|
if (isQueryOnly(database))
|
|
112
112
|
return typesCurrent(database);
|
|
113
113
|
if (rulesOf(database) !== TYPE_RULES)
|
|
@@ -130,6 +130,8 @@ export const storeMailTypes = (database) => {
|
|
|
130
130
|
const keep = database.prepare("UPDATE emails SET mail_type = ?, reach = ?, type_signal = ?, sort_checked = 1 WHERE id = ?");
|
|
131
131
|
const senders = new Map();
|
|
132
132
|
for (;;) {
|
|
133
|
+
if (until())
|
|
134
|
+
return false;
|
|
133
135
|
const more = writeBatch(database, () => {
|
|
134
136
|
const ids = database
|
|
135
137
|
.prepare("SELECT id FROM emails WHERE mail_type IS NULL LIMIT ?")
|
|
@@ -143,6 +145,35 @@ export const storeMailTypes = (database) => {
|
|
|
143
145
|
return true;
|
|
144
146
|
}
|
|
145
147
|
};
|
|
148
|
+
/** How many emails whose type was cleared before this save one save also types: the rest fill as mail syncs. */
|
|
149
|
+
const BACKLOG_ON_SAVE = 500;
|
|
150
|
+
/**
|
|
151
|
+
* Types the mail of these threads inside the save's own write, plus a little of what is untyped from before: a
|
|
152
|
+
* read-only open cannot keep types, so a store typed only by its first search made that search work out every email
|
|
153
|
+
* (1.5–1.8 s of a 2 s limit on 100,000, cli-testing performance/mail/types). Skipped while a rules change waits to
|
|
154
|
+
* clear the stored types: those are typed again in batches by the next filtered read.
|
|
155
|
+
*/
|
|
156
|
+
export const typeSavedMail = (database, threadIds) => {
|
|
157
|
+
if (rulesOf(database) !== TYPE_RULES) {
|
|
158
|
+
if (database.prepare("SELECT 1 FROM emails WHERE mail_type IS NOT NULL LIMIT 1").get() !== undefined)
|
|
159
|
+
return;
|
|
160
|
+
database
|
|
161
|
+
.prepare("INSERT INTO store_settings (key, value, at) VALUES (?, ?, ?) " +
|
|
162
|
+
"ON CONFLICT (key) DO UPDATE SET value = excluded.value, at = excluded.at")
|
|
163
|
+
.run(RULES_KEY, TYPE_RULES, Date.now());
|
|
164
|
+
}
|
|
165
|
+
const ids = (sql, param) => database
|
|
166
|
+
.prepare(sql)
|
|
167
|
+
.all(param)
|
|
168
|
+
.map((row) => Number(row.id));
|
|
169
|
+
const untyped = new Set([
|
|
170
|
+
...ids("SELECT id FROM emails WHERE email_thread_id IN (SELECT value FROM json_each(?)) AND mail_type IS NULL", JSON.stringify(threadIds)),
|
|
171
|
+
...ids("SELECT id FROM emails WHERE mail_type IS NULL LIMIT ?", BACKLOG_ON_SAVE),
|
|
172
|
+
]);
|
|
173
|
+
const keep = database.prepare("UPDATE emails SET mail_type = ?, reach = ?, type_signal = ?, sort_checked = 1 WHERE id = ?");
|
|
174
|
+
for (const [id, { type, reach, signal }] of typesOf(database, [...untyped]))
|
|
175
|
+
keep.run(type, reach, signal, id);
|
|
176
|
+
};
|
|
146
177
|
/** Each email's stored type, or for one the store has not typed yet, the type worked out for this read. */
|
|
147
178
|
export const withTypes = (database, emails) => {
|
|
148
179
|
const missing = emails.filter((email) => email.mailType === null).map((email) => email.id);
|
|
@@ -9,6 +9,7 @@ import { type EmailLocationInput, type FolderEmail, type PartialMailStore } from
|
|
|
9
9
|
import { type MailTypeStore, type TypeFilter } from "./email-types.js";
|
|
10
10
|
import { type MailRulesStore } from "./mail-rules.js";
|
|
11
11
|
import { type MailSorting } from "./mail-sorting.js";
|
|
12
|
+
import { type MailSubscriptionStore } from "./mail-subscriptions.js";
|
|
12
13
|
import { type AttachmentInput } from "./meetings.js";
|
|
13
14
|
import type { StoreContext } from "./open.js";
|
|
14
15
|
import type { Reach } from "./sender-signals.js";
|
|
@@ -216,7 +217,7 @@ export interface SenderScore {
|
|
|
216
217
|
demoted?: boolean;
|
|
217
218
|
}
|
|
218
219
|
/** Mail in tables of its own: threads, emails, recipients and mailboxes, keyed by account and Message-ID. */
|
|
219
|
-
export interface MailStore extends PartialMailStore, MailActivityStore, MailTypeStore {
|
|
220
|
+
export interface MailStore extends PartialMailStore, MailActivityStore, MailTypeStore, MailSubscriptionStore {
|
|
220
221
|
saveThread(input: ThreadSave): Promise<ThreadDetails>;
|
|
221
222
|
/** Several threads and sync state in one transaction: a slice of mail commits with its resume point, or not at all. */
|
|
222
223
|
saveThreads(inputs: ThreadSave[], states?: SyncStateSave[]): Promise<ThreadDetails[]>;
|
|
@@ -2,7 +2,7 @@ import { formatLocator } from "../../domain/locator.js";
|
|
|
2
2
|
import { formatReference } from "../../domain/references.js";
|
|
3
3
|
import { fold, normalize } from "../normalize.js";
|
|
4
4
|
import { mailActivity, threadEmailIds } from "./email-activity.js";
|
|
5
|
-
import { chunkAttachments, drainEmailIndex, dropAttachmentChunks, MAIL_PIECES, queueThreads, threadPieces, titleOf, } from "./email-index.js";
|
|
5
|
+
import { catchUpMail, chunkAttachments, drainEmailIndex, dropAttachmentChunks, indexSavedMail, 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
8
|
import { mailTypeStore, typeWhere, withTypes } from "./email-types.js";
|
|
@@ -13,6 +13,7 @@ import { ensurePerson } from "./identities.js";
|
|
|
13
13
|
import { nearestMailPieces } from "./mail-nearest.js";
|
|
14
14
|
import { mailRulesOver } from "./mail-rules.js";
|
|
15
15
|
import { mailSortingOver, settleThreads } from "./mail-sorting.js";
|
|
16
|
+
import { mailSubscriptionStore } from "./mail-subscriptions.js";
|
|
16
17
|
import { attachmentOf, saveAttachment, wordsQuery } from "./meetings.js";
|
|
17
18
|
import { stemmerCache } from "./stems.js";
|
|
18
19
|
import { writeState } from "./sync.js";
|
|
@@ -444,6 +445,7 @@ export const mailStoreOver = ({ database, orm, now }, stemmerFor = stemmerCache(
|
|
|
444
445
|
const id = write(database, () => {
|
|
445
446
|
const saved = saveThread(database, orm, input);
|
|
446
447
|
settleThreads({ database, orm, now }, [saved]);
|
|
448
|
+
indexSavedMail(database, stemmerFor, [saved]);
|
|
447
449
|
return saved;
|
|
448
450
|
});
|
|
449
451
|
return threadDetails(database, id);
|
|
@@ -452,6 +454,7 @@ export const mailStoreOver = ({ database, orm, now }, stemmerFor = stemmerCache(
|
|
|
452
454
|
const ids = write(database, () => {
|
|
453
455
|
const saved = inputs.map((input) => saveThread(database, orm, input));
|
|
454
456
|
settleThreads({ database, orm, now }, saved);
|
|
457
|
+
indexSavedMail(database, stemmerFor, saved);
|
|
455
458
|
for (const { accountId, name, value } of states)
|
|
456
459
|
writeState({ orm, now }, accountId, name, value);
|
|
457
460
|
return saved;
|
|
@@ -497,6 +500,8 @@ export const mailStoreOver = ({ database, orm, now }, stemmerFor = stemmerCache(
|
|
|
497
500
|
...partialMail(database),
|
|
498
501
|
...mailActivity(database),
|
|
499
502
|
...mailTypeStore(database),
|
|
503
|
+
catchUp: async (until) => catchUpMail(database, stemmerFor, until),
|
|
504
|
+
...mailSubscriptionStore(database),
|
|
500
505
|
async emailFacts(filter = {}) {
|
|
501
506
|
const [where, params] = emailWhere(database, filter);
|
|
502
507
|
return database
|
|
@@ -20,7 +20,7 @@ export declare const ENTITY_TABLES: {
|
|
|
20
20
|
readonly pipeline: "pipelines";
|
|
21
21
|
readonly account: "accounts";
|
|
22
22
|
readonly attachment: "attachments";
|
|
23
|
-
readonly
|
|
23
|
+
readonly agent: "bots";
|
|
24
24
|
readonly calendar_entry: "calendar_entries";
|
|
25
25
|
readonly chat: "chats";
|
|
26
26
|
readonly conversation: "conversations";
|
|
@@ -236,7 +236,7 @@ export const evidenceFindingsStoreOver = (context) => {
|
|
|
236
236
|
return stale();
|
|
237
237
|
}
|
|
238
238
|
}
|
|
239
|
-
if (proposal.proposedBy.type !== "
|
|
239
|
+
if (proposal.proposedBy.type !== "agent" || !proposal.proposedBy.name)
|
|
240
240
|
return invalid("a findings author must be an agent");
|
|
241
241
|
const agent = {
|
|
242
242
|
bot: proposal.proposedBy.name,
|
|
@@ -11,7 +11,7 @@ import { requiredThing } from "./notes.js";
|
|
|
11
11
|
import { pageOfRows } from "./rows-page.js";
|
|
12
12
|
import { closeSourceReviews, eraseSourceReviews, sourceReviewOf } from "./source-review-marks.js";
|
|
13
13
|
import { write } from "./transaction.js";
|
|
14
|
-
const NAMED = "SELECT f.*, b.name AS author_name, b.kind AS author_kind FROM facts f LEFT JOIN bots b ON f.author_type = '
|
|
14
|
+
const NAMED = "SELECT f.*, b.name AS author_name, b.kind AS author_kind FROM facts f LEFT JOIN bots b ON f.author_type = 'agent' AND b.id = f.author_id";
|
|
15
15
|
const iso = (value) => new Date(Number(value)).toISOString();
|
|
16
16
|
const oneOf = (value, allowed, what) => {
|
|
17
17
|
if (typeof value !== "string" || !allowed.includes(value))
|
|
@@ -15,9 +15,9 @@ const isFinanceType = (type) => FINANCE_TYPES.includes(type);
|
|
|
15
15
|
/** Money settled by confirmed payments only: a proposed payment promises nothing yet. */
|
|
16
16
|
const PAID = netPaidSql("i.id");
|
|
17
17
|
const INVOICES = `SELECT i.*, ${PAID} AS paid, b.name AS author_name, b.kind AS author_kind FROM invoices i ` +
|
|
18
|
-
"LEFT JOIN bots b ON i.author_type = '
|
|
18
|
+
"LEFT JOIN bots b ON i.author_type = 'agent' AND b.id = i.author_id";
|
|
19
19
|
const PAYMENTS = "SELECT p.*, (SELECT coalesce(sum(amount), 0) FROM payment_allocations WHERE payment_id = p.id) AS allocated, " +
|
|
20
|
-
"b.name AS author_name, b.kind AS author_kind FROM payments p LEFT JOIN bots b ON p.author_type = '
|
|
20
|
+
"b.name AS author_name, b.kind AS author_kind FROM payments p LEFT JOIN bots b ON p.author_type = 'agent' AND b.id = p.author_id";
|
|
21
21
|
export const financeOperationsOver = (context) => {
|
|
22
22
|
const { database, now } = context;
|
|
23
23
|
const { partyOf, partyThing, reviewedOf, written, keepEvidence, ownerOnly, linkedId, decideRow, mayChangeParts } = reviewedRowsOver(context);
|
|
@@ -161,6 +161,7 @@ export const knowledgeStoreOver = (context) => {
|
|
|
161
161
|
if (parsed.type === "entity" ||
|
|
162
162
|
parsed.type === "memory" ||
|
|
163
163
|
parsed.type === "fact" ||
|
|
164
|
+
parsed.type === "agent" ||
|
|
164
165
|
parsed.type === "bot" ||
|
|
165
166
|
parsed.type === "event" ||
|
|
166
167
|
parsed.type === "meeting" ||
|
|
@@ -527,7 +527,7 @@ export const mailFindingsStoreOver = (context) => {
|
|
|
527
527
|
const chosen = pendingOf(batch.input, input.decided).findings.filter((finding) => accepted.includes(finding.id));
|
|
528
528
|
if (chosen.length)
|
|
529
529
|
cite(chosen, account, true);
|
|
530
|
-
if (proposal.proposedBy.type !== "
|
|
530
|
+
if (proposal.proposedBy.type !== "agent" || !proposal.proposedBy.name)
|
|
531
531
|
return invalid("a findings author must be an agent");
|
|
532
532
|
const agent = {
|
|
533
533
|
bot: proposal.proposedBy.name,
|
|
@@ -100,7 +100,7 @@ export interface MailSorting {
|
|
|
100
100
|
/** Takes back the owner's newest add or removal not yet undone; `null` when there is none. */
|
|
101
101
|
undo(by: Decider): Promise<SortUndo | null>;
|
|
102
102
|
/**
|
|
103
|
-
* The owner's manual sorting of one sender, an address or a `person:` or `
|
|
103
|
+
* The owner's manual sorting of one sender, an address or a `person:` or `bot:` ref, removed: its address
|
|
104
104
|
* rules and its one-mail rules. Domain and list rules stay. Answers the rules removed.
|
|
105
105
|
*/
|
|
106
106
|
reset(sender: string, by: Decider): Promise<SortRule[]>;
|
|
@@ -2,15 +2,16 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import { CliError } from "@wirecat/cli-base";
|
|
3
3
|
import { isPackFreeMailDomain } from "../../domain/domain-lists.js";
|
|
4
4
|
import { isFreeMailDomain } from "../../domain/organization-sectors.js";
|
|
5
|
-
import { SENDER_BOT_PREFIX } from "../../domain/person-kinds.js";
|
|
5
|
+
import { SENDER_BOT_PREFIX, senderBotRef } from "../../domain/person-kinds.js";
|
|
6
6
|
import { listIdOf } from "../../mail/headers.js";
|
|
7
7
|
import { MAIL_TYPES } from "../../mail/mail-types.js";
|
|
8
8
|
import { FREE_MAIL, isDisposableDomain } from "../../mail/score.js";
|
|
9
9
|
import { SORT_SCOPES, sortIndexOf, sortRuleFor, sortValueOf, } from "../../mail/sort-rules.js";
|
|
10
10
|
import { holdAddress } from "./address-organization.js";
|
|
11
|
-
import {
|
|
11
|
+
import { currentPerson } from "./merged-persons.js";
|
|
12
|
+
import { holdingAuthorOf, moveToBot, moveToPerson, putBack } from "./sender-bots.js";
|
|
12
13
|
import { LIST_ID } from "./sender-signals.js";
|
|
13
|
-
import { read, write } from "./transaction.js";
|
|
14
|
+
import { letWaitersIn, read, write } from "./transaction.js";
|
|
14
15
|
const COLUMNS = "id, scope, value, mail_type, sender, organization_id, over_addresses, past, author, decided_by, reason, " +
|
|
15
16
|
"created_at, updated_at, removed_at";
|
|
16
17
|
const ruleOf = (row) => ({
|
|
@@ -73,7 +74,7 @@ const inScope = (database, scope, value) => {
|
|
|
73
74
|
.filter((row) => sortRuleFor(alone, row) !== undefined);
|
|
74
75
|
};
|
|
75
76
|
const ADDRESS_ONLY = { subject: null, list: null, at: Number.MAX_SAFE_INTEGER };
|
|
76
|
-
/** Where an identity sits now: `
|
|
77
|
+
/** Where an identity sits now: `bot:<id>`, `person:<id>` or `null`. */
|
|
77
78
|
const holderOf = (database, identity) => {
|
|
78
79
|
const bot = database.prepare("SELECT bot_id FROM sender_bot_identities WHERE identity_id = ?").get(identity);
|
|
79
80
|
if (bot !== undefined)
|
|
@@ -81,6 +82,12 @@ const holderOf = (database, identity) => {
|
|
|
81
82
|
const person = database.prepare("SELECT person_id FROM identity_links WHERE identity_id = ?").get(identity);
|
|
82
83
|
return person === undefined ? null : `person:${person.person_id}`;
|
|
83
84
|
};
|
|
85
|
+
/** Where an identity sits now and who put it there, as an effect's `before` keeps it: `bot:4 rules`. */
|
|
86
|
+
const heldOf = (database, identity) => {
|
|
87
|
+
const holder = holderOf(database, identity);
|
|
88
|
+
return holder === null ? null : `${holder} ${holdingAuthorOf(database, identity)}`;
|
|
89
|
+
};
|
|
90
|
+
const holderIn = (held) => (held === null ? null : (held.split(" ")[0] ?? null));
|
|
84
91
|
const isWhere = (holder, sender) => holder?.startsWith(sender === "bot" ? SENDER_BOT_PREFIX : "person:") === true;
|
|
85
92
|
const sendersOf = (database, identities) => database
|
|
86
93
|
.prepare("SELECT DISTINCT e.from_identity_id AS identity, i.external_id AS address FROM emails e " +
|
|
@@ -122,7 +129,7 @@ export const settleSenders = (context, identities) => {
|
|
|
122
129
|
const at = context.now();
|
|
123
130
|
const mover = sortRuleFor(rules.sender, mail);
|
|
124
131
|
if (mover?.sender && !hasEffect(database, mover.id, identity, "sender")) {
|
|
125
|
-
const before =
|
|
132
|
+
const before = heldOf(database, identity);
|
|
126
133
|
if (!isWhere(before, mover.sender))
|
|
127
134
|
moveSender(context, address, mover);
|
|
128
135
|
recordEffect(database, {
|
|
@@ -168,41 +175,59 @@ const moveSender = (context, address, rule) => {
|
|
|
168
175
|
throw error;
|
|
169
176
|
}
|
|
170
177
|
};
|
|
171
|
-
/**
|
|
172
|
-
|
|
178
|
+
/**
|
|
179
|
+
* Senders per write. A move to a bot takes about 10 ms, so 100 keep one write near 1 s, far from another writer's 5 s
|
|
180
|
+
* wait; putting one back is cheaper, but a write's commit costs the same.
|
|
181
|
+
*/
|
|
182
|
+
const SETTLE_CHUNK = 100;
|
|
183
|
+
/** Whether the sender is still where the rule put it: else the owner moved it since, and that stands. */
|
|
184
|
+
const stillAfter = (database, identity, after) => {
|
|
185
|
+
const now = holderOf(database, identity);
|
|
186
|
+
if (now === after)
|
|
187
|
+
return true;
|
|
188
|
+
return (after?.startsWith("person:") === true &&
|
|
189
|
+
now === `person:${currentPerson(database, Number(after.slice("person:".length)))}`);
|
|
190
|
+
};
|
|
191
|
+
/**
|
|
192
|
+
* Puts back what removed rules did to up to `SETTLE_CHUNK` senders, newest effect first, each to its holder and author
|
|
193
|
+
* before the rule, then lets the rules still live settle them. Answers whether more may be left. The caller holds
|
|
194
|
+
* the write lock.
|
|
195
|
+
*/
|
|
196
|
+
const putBackChunk = (context) => {
|
|
173
197
|
const { database } = context;
|
|
198
|
+
const identities = database
|
|
199
|
+
.prepare("SELECT DISTINCT f.identity_id AS identity FROM mail_sort_effects f JOIN mail_sort_rules r ON r.id = f.rule_id " +
|
|
200
|
+
"WHERE r.removed_at IS NOT NULL AND f.undone_at IS NULL ORDER BY f.identity_id LIMIT ?")
|
|
201
|
+
.all(SETTLE_CHUNK)
|
|
202
|
+
.map((row) => Number(row.identity));
|
|
203
|
+
if (identities.length === 0)
|
|
204
|
+
return false;
|
|
174
205
|
const effects = database
|
|
175
|
-
.prepare("SELECT f.id, f.identity_id, f.action, f.before, f.after
|
|
176
|
-
"JOIN
|
|
177
|
-
.
|
|
206
|
+
.prepare("SELECT f.id, f.identity_id, f.action, f.before, f.after FROM mail_sort_effects f " +
|
|
207
|
+
"JOIN mail_sort_rules r ON r.id = f.rule_id WHERE r.removed_at IS NOT NULL AND f.undone_at IS NULL " +
|
|
208
|
+
"AND f.identity_id IN (SELECT value FROM json_each(?)) ORDER BY f.id DESC")
|
|
209
|
+
.all(JSON.stringify(identities));
|
|
178
210
|
const at = context.now();
|
|
179
211
|
for (const effect of effects) {
|
|
180
212
|
const identity = Number(effect.identity_id);
|
|
181
|
-
const subject = { provider: "email", id: String(effect.address) };
|
|
182
213
|
const before = effect.before == null ? null : String(effect.before);
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
if (before.startsWith(SENDER_BOT_PREFIX) && !isWhere(now, "bot"))
|
|
188
|
-
moveToBot(context, subject, {
|
|
189
|
-
reason: "undo",
|
|
190
|
-
...(database
|
|
191
|
-
.prepare("SELECT 1 FROM sender_bots WHERE id = ?")
|
|
192
|
-
.get(Number(before.slice(SENDER_BOT_PREFIX.length)))
|
|
193
|
-
? { bot: before }
|
|
194
|
-
: {}),
|
|
195
|
-
});
|
|
196
|
-
}
|
|
214
|
+
const after = effect.after == null ? null : String(effect.after);
|
|
215
|
+
const holder = holderIn(before);
|
|
216
|
+
if (effect.action === "sender" && holder !== null && holder !== after && stillAfter(database, identity, after))
|
|
217
|
+
putBack(context, identity, holder, before?.endsWith(" owner") ? "owner" : "rules");
|
|
197
218
|
if (effect.action === "organization" && before === null)
|
|
198
219
|
database
|
|
199
220
|
.prepare("DELETE FROM organization_identities WHERE identity_id = ? AND organization_id = ? AND method = ?")
|
|
200
|
-
.run(identity, Number(String(
|
|
221
|
+
.run(identity, Number(String(after).slice("organization:".length)), SORT_METHOD);
|
|
201
222
|
database.prepare("UPDATE mail_sort_effects SET undone_at = ? WHERE id = ?").run(at, Number(effect.id));
|
|
202
223
|
}
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
224
|
+
settleSenders(context, identities);
|
|
225
|
+
return identities.length === SETTLE_CHUNK;
|
|
226
|
+
};
|
|
227
|
+
/** Each removed rule's senders put back a write at a time; a stopped run resumes on the next change of rules. */
|
|
228
|
+
const putBackInChunks = (context) => {
|
|
229
|
+
while (write(context.database, () => putBackChunk(context)))
|
|
230
|
+
letWaitersIn();
|
|
206
231
|
};
|
|
207
232
|
const clearTypes = (database, ids) => database
|
|
208
233
|
.prepare("UPDATE emails SET mail_type = NULL, reach = NULL, type_signal = NULL " +
|
|
@@ -325,24 +350,26 @@ const applyRule = (context, rule) => {
|
|
|
325
350
|
if (!rule.past)
|
|
326
351
|
for (const { identity } of sendersOf(database, identities)) {
|
|
327
352
|
const holder = holderOf(database, identity);
|
|
353
|
+
const held = heldOf(database, identity);
|
|
328
354
|
for (const action of [...(rule.sender ? ["sender"] : []), ...(rule.organization ? ["organization"] : [])])
|
|
329
355
|
recordEffect(database, {
|
|
330
356
|
rule: rule.id,
|
|
331
357
|
identity,
|
|
332
358
|
action,
|
|
333
|
-
before: action === "sender" ?
|
|
359
|
+
before: action === "sender" ? held : "held",
|
|
334
360
|
after: action === "sender" ? holder : "held",
|
|
335
361
|
at: context.now(),
|
|
336
362
|
});
|
|
337
363
|
}
|
|
338
364
|
return identities;
|
|
339
365
|
};
|
|
340
|
-
/** Each move takes about 10 ms: 100 per write keeps another writer's 5 s wait for the lock far away. */
|
|
341
|
-
const SETTLE_CHUNK = 100;
|
|
342
366
|
/** Settles senders a write at a time; a sender already settled is skipped, so a stopped run resumes on the next. */
|
|
343
367
|
const settleInChunks = (context, identities) => {
|
|
344
|
-
for (let at = 0; at < identities.length; at += SETTLE_CHUNK)
|
|
368
|
+
for (let at = 0; at < identities.length; at += SETTLE_CHUNK) {
|
|
369
|
+
if (at > 0)
|
|
370
|
+
letWaitersIn();
|
|
345
371
|
write(context.database, () => settleSenders(context, identities.slice(at, at + SETTLE_CHUNK)));
|
|
372
|
+
}
|
|
346
373
|
};
|
|
347
374
|
/** A change's time, later than every change before it, so undo takes changes back in order within one millisecond. */
|
|
348
375
|
const stampOf = ({ database, now }) => Math.max(now(), Number(database.prepare("SELECT coalesce(max(updated_at), 0) + 1 AS at FROM mail_sort_rules").get()?.at));
|
|
@@ -353,20 +380,20 @@ const takeOut = (context, rule, undone) => {
|
|
|
353
380
|
.run(at, at, undone ? at : null, rule.id);
|
|
354
381
|
const removed = ruleById(context.database, rule.id);
|
|
355
382
|
clearRuleTypes(context.database, removed);
|
|
356
|
-
undoEffects(context, rule.id);
|
|
357
383
|
return removed;
|
|
358
384
|
};
|
|
359
385
|
const ownerOnly = (by, what) => {
|
|
360
386
|
if (by !== "owner")
|
|
361
387
|
fail(`only the owner ${what}`, "mail-sort.owner-only");
|
|
362
388
|
};
|
|
363
|
-
const addressesOf = (database,
|
|
364
|
-
if (
|
|
365
|
-
return [
|
|
389
|
+
const addressesOf = (database, given) => {
|
|
390
|
+
if (given.includes("@") && !given.includes(":"))
|
|
391
|
+
return [given.trim().toLowerCase()];
|
|
392
|
+
const sender = senderBotRef(given);
|
|
366
393
|
const bot = sender.startsWith(SENDER_BOT_PREFIX) ? Number(sender.slice(SENDER_BOT_PREFIX.length)) : undefined;
|
|
367
394
|
const person = sender.startsWith("person:") ? Number(sender.slice("person:".length)) : undefined;
|
|
368
395
|
if (bot === undefined && person === undefined)
|
|
369
|
-
return fail(`${sender} names no sender: give an address, a person: or a
|
|
396
|
+
return fail(`${sender} names no sender: give an address, a person: or a bot: ref`, "mail-sort.sender-ref");
|
|
370
397
|
return database
|
|
371
398
|
.prepare("SELECT lower(i.external_id) AS address FROM identities i WHERE i.provider = 'email' AND i.id IN " +
|
|
372
399
|
(bot === undefined
|
|
@@ -422,14 +449,18 @@ export const mailSortingOver = (context) => {
|
|
|
422
449
|
settleInChunks(context, identities);
|
|
423
450
|
return result;
|
|
424
451
|
},
|
|
425
|
-
remove: async (id, by) =>
|
|
426
|
-
const
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
452
|
+
remove: async (id, by) => {
|
|
453
|
+
const removed = write(database, () => {
|
|
454
|
+
const rule = ruleById(database, id);
|
|
455
|
+
if (by !== "owner" && (rule.author !== "program" || rule.decidedBy !== by.bot))
|
|
456
|
+
fail("a program removes only the rules it made", "mail-sort.owner-only");
|
|
457
|
+
if (rule.removedAt !== null)
|
|
458
|
+
return rule;
|
|
459
|
+
return takeOut(context, rule, false);
|
|
460
|
+
});
|
|
461
|
+
putBackInChunks(context);
|
|
462
|
+
return removed;
|
|
463
|
+
},
|
|
433
464
|
undo: async (by) => {
|
|
434
465
|
const { identities, undone } = write(database, () => {
|
|
435
466
|
ownerOnly(by, "undoes a sorting change");
|
|
@@ -449,23 +480,28 @@ export const mailSortingOver = (context) => {
|
|
|
449
480
|
const back = ruleById(database, rule.id);
|
|
450
481
|
return { identities: applyRule(context, back), undone: { undid: "remove", rule: back } };
|
|
451
482
|
});
|
|
483
|
+
putBackInChunks(context);
|
|
452
484
|
settleInChunks(context, identities);
|
|
453
485
|
return undone;
|
|
454
486
|
},
|
|
455
|
-
reset: async (sender, by) =>
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
487
|
+
reset: async (sender, by) => {
|
|
488
|
+
const removed = write(database, () => {
|
|
489
|
+
ownerOnly(by, "resets the manual sorting of a sender");
|
|
490
|
+
const addresses = addressesOf(database, sender);
|
|
491
|
+
const mails = database
|
|
492
|
+
.prepare("SELECT id FROM emails WHERE lower(from_address) IN (SELECT value FROM json_each(?)) AND outgoing IS NOT 1")
|
|
493
|
+
.all(JSON.stringify(addresses))
|
|
494
|
+
.map((row) => String(row.id));
|
|
495
|
+
return database
|
|
496
|
+
.prepare(`SELECT ${COLUMNS} FROM mail_sort_rules WHERE removed_at IS NULL AND author = 'owner' AND ` +
|
|
497
|
+
"((scope = 'address' AND value IN (SELECT value FROM json_each(?))) OR " +
|
|
498
|
+
"(scope = 'mail' AND value IN (SELECT value FROM json_each(?)))) ORDER BY id DESC")
|
|
499
|
+
.all(JSON.stringify(addresses), JSON.stringify(mails))
|
|
500
|
+
.map((row) => takeOut(context, ruleOf(row), false));
|
|
501
|
+
});
|
|
502
|
+
putBackInChunks(context);
|
|
503
|
+
return removed;
|
|
504
|
+
},
|
|
469
505
|
};
|
|
470
506
|
};
|
|
471
507
|
/** The senders of mail just saved in these threads, settled by the rules that move or file senders. */
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import type { MailType } from "../../mail/mail-types.js";
|
|
2
|
+
import type { CacheDatabase } from "../driver.js";
|
|
3
|
+
/** Where an unsubscribe goes, as the newest mail of a subscription that names one gave it. @experimental */
|
|
4
|
+
export interface UnsubscribeTarget {
|
|
5
|
+
/** The https target of List-Unsubscribe. */
|
|
6
|
+
https: string | null;
|
|
7
|
+
/** The mailto target of List-Unsubscribe. */
|
|
8
|
+
mailto: string | null;
|
|
9
|
+
/**
|
|
10
|
+
* RFC 8058 one-click: the mail also carries `List-Unsubscribe-Post: List-Unsubscribe=One-Click`, and its From
|
|
11
|
+
* domain signed both fields, so a POST to `https` unsubscribes without opening a page.
|
|
12
|
+
*/
|
|
13
|
+
oneClick: boolean;
|
|
14
|
+
/** The mail the target was read from. */
|
|
15
|
+
emailId: number;
|
|
16
|
+
}
|
|
17
|
+
/** One list, or one sender of broadcast mail with no List-Id: a row of Subscriptions. @experimental */
|
|
18
|
+
export interface MailSubscription {
|
|
19
|
+
/** `list:<List-Id>`, else the sender: `bot:<id>`, `person:<id>` or `address:<address>`. */
|
|
20
|
+
key: string;
|
|
21
|
+
listId: string | null;
|
|
22
|
+
/** The display name on its newest email, else its address. */
|
|
23
|
+
name: string | null;
|
|
24
|
+
/** Who sent its newest email: `bot:<id>`, `person:<id>`, or `null` when the address is linked to neither. */
|
|
25
|
+
sender: string | null;
|
|
26
|
+
/** The From address of its newest email, lower case. */
|
|
27
|
+
address: string | null;
|
|
28
|
+
/** Its broadcast emails the filter takes in. */
|
|
29
|
+
emails: number;
|
|
30
|
+
newest: {
|
|
31
|
+
id: number;
|
|
32
|
+
externalId: string;
|
|
33
|
+
subject: string | null;
|
|
34
|
+
at: number | null;
|
|
35
|
+
};
|
|
36
|
+
/** `null` when none of its emails names a target its sender's DKIM signature vouches for. */
|
|
37
|
+
unsubscribe: UnsubscribeTarget | null;
|
|
38
|
+
}
|
|
39
|
+
/** @experimental */
|
|
40
|
+
export interface MailSubscriptionFilter {
|
|
41
|
+
/** Only mail of these accounts; every account when left out. */
|
|
42
|
+
accountIds?: readonly number[];
|
|
43
|
+
since?: number;
|
|
44
|
+
/** Exclusive. */
|
|
45
|
+
until?: number;
|
|
46
|
+
/** Only emails of these types: the promotions of a shop, without its receipts. */
|
|
47
|
+
types?: readonly MailType[];
|
|
48
|
+
limit?: number;
|
|
49
|
+
offset?: number;
|
|
50
|
+
}
|
|
51
|
+
/** @experimental */
|
|
52
|
+
export interface MailSubscriptionList {
|
|
53
|
+
items: MailSubscription[];
|
|
54
|
+
total: number;
|
|
55
|
+
hasMore: boolean;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Broadcast mail grouped by List-Id, else by its sender, newest group first, grouped, counted and paged in SQL. Each
|
|
59
|
+
* group carries its newest email and the unsubscribe target of its newest email that names one.
|
|
60
|
+
*/
|
|
61
|
+
export declare const mailSubscriptions: (database: CacheDatabase, filter: MailSubscriptionFilter) => MailSubscriptionList;
|
|
62
|
+
/** @experimental */
|
|
63
|
+
export interface MailSubscriptionStore {
|
|
64
|
+
/**
|
|
65
|
+
* Subscriptions: broadcast mail grouped by List-Id, else by sender, newest first, each with its mail count, newest
|
|
66
|
+
* email and unsubscribe target. Nothing is unsubscribed.
|
|
67
|
+
*/
|
|
68
|
+
subscriptions(filter?: MailSubscriptionFilter): Promise<MailSubscriptionList>;
|
|
69
|
+
}
|
|
70
|
+
export declare const mailSubscriptionStore: (database: CacheDatabase) => MailSubscriptionStore;
|