@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.
- package/CHANGELOG.md +144 -0
- package/THIRD_PARTY_NOTICES +43 -0
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/cli/account-remove.d.ts +3 -0
- package/dist/cli/account-remove.js +1 -1
- package/dist/cli/documents/index.d.ts +2 -1
- package/dist/cli/documents/index.js +4 -1
- package/dist/cli/documents/words.d.ts +1 -1
- package/dist/cli/domain-lists-command.d.ts +16 -0
- package/dist/cli/domain-lists-command.js +88 -0
- package/dist/cli/index.d.ts +4 -3
- package/dist/cli/index.js +4 -3
- package/dist/cli/messenger/conversation-answers.d.ts +2 -0
- package/dist/cli/messenger/message-answers.d.ts +2 -0
- package/dist/cli/messenger/message-items.js +2 -0
- package/dist/cli/messenger/message-writes.d.ts +4 -0
- package/dist/cli/messenger/search-answers.js +2 -0
- package/dist/cli/model-catalogue-command.d.ts +6 -0
- package/dist/cli/model-catalogue-command.js +1 -1
- package/dist/cli/oauth-session.d.ts +38 -4
- package/dist/cli/oauth-session.js +72 -25
- package/dist/cli/shared-command-exports.d.ts +4 -0
- package/dist/cli/shared-command-exports.js +6 -0
- package/dist/cli/token-session.d.ts +9 -3
- package/dist/cli/token-session.js +34 -3
- package/dist/domain/domain-lists.d.ts +86 -0
- package/dist/domain/domain-lists.js +110 -0
- package/dist/domain/free-mail-domains.generated.d.ts +1 -0
- package/dist/domain/free-mail-domains.generated.js +4 -0
- package/dist/domain/models.d.ts +5 -0
- package/dist/domain/organization-sectors.d.ts +9 -3
- package/dist/domain/organization-sectors.generated.d.ts +1 -0
- package/dist/domain/organization-sectors.generated.js +1 -0
- package/dist/domain/organization-sectors.js +16 -3
- package/dist/domain/person-kinds.d.ts +6 -1
- package/dist/domain/person-kinds.js +5 -0
- package/dist/entities/contact-context.d.ts +4 -0
- package/dist/entities/conversation-results.d.ts +4 -0
- package/dist/entities/domain-list.d.ts +27 -0
- package/dist/entities/domain-list.js +28 -0
- package/dist/entities/evidence.d.ts +16 -0
- package/dist/entities/index.d.ts +56 -2
- package/dist/entities/index.js +3 -1
- package/dist/entities/knowledge-lists.d.ts +1 -1
- package/dist/entities/listener.d.ts +8 -0
- package/dist/entities/message-change.d.ts +2 -0
- package/dist/entities/message-context.d.ts +6 -0
- package/dist/entities/message-write.d.ts +8 -0
- package/dist/entities/message.d.ts +4 -0
- package/dist/entities/message.js +4 -0
- package/dist/entities/store-records.d.ts +2 -0
- package/dist/errors/reasons.js +20 -2
- package/dist/mail/cli/index.js +1 -1
- package/dist/mail/headers.d.ts +2 -0
- package/dist/mail/headers.js +2 -1
- package/dist/mail/mail-types.d.ts +48 -0
- package/dist/mail/mail-types.js +218 -0
- package/dist/mail/read.js +1 -0
- package/dist/mail/sort-rules.d.ts +58 -0
- package/dist/mail/sort-rules.js +79 -0
- package/dist/oauth/index.d.ts +1 -1
- package/dist/oauth/storage.d.ts +10 -2
- package/dist/oauth/storage.js +23 -9
- package/dist/search/lucene/registry.js +24 -0
- package/dist/services/domain-lists-download.d.ts +26 -0
- package/dist/services/domain-lists-download.js +155 -0
- package/dist/services/messages-search.js +1 -1
- package/dist/services/metadata.d.ts +1 -1
- package/dist/store/areas.d.ts +3 -1
- package/dist/store/areas.js +2 -0
- package/dist/store/index.d.ts +2 -2
- package/dist/store/index.js +1 -1
- package/dist/store/people.d.ts +18 -9
- package/dist/store/people.js +8 -7
- package/dist/store/public.d.ts +1 -1
- package/dist/store/public.js +1 -1
- package/dist/store/queries.js +9 -2
- package/dist/store/sqlite/accounts.js +3 -1
- package/dist/store/sqlite/domain-organizations.d.ts +7 -4
- package/dist/store/sqlite/domain-organizations.js +94 -36
- package/dist/store/sqlite/email-types.d.ts +87 -0
- package/dist/store/sqlite/email-types.js +296 -0
- package/dist/store/sqlite/emails.d.ts +14 -2
- package/dist/store/sqlite/emails.js +32 -12
- package/dist/store/sqlite/identities.d.ts +4 -1
- package/dist/store/sqlite/identities.js +11 -2
- package/dist/store/sqlite/identity-rekey.js +2 -0
- package/dist/store/sqlite/lucene-fields.d.ts +6 -0
- package/dist/store/sqlite/lucene-fields.js +10 -0
- package/dist/store/sqlite/lucene.js +6 -0
- package/dist/store/sqlite/mail-sorting.d.ts +122 -0
- package/dist/store/sqlite/mail-sorting.js +482 -0
- package/dist/store/sqlite/manifest.js +6 -0
- package/dist/store/sqlite/merged-persons.d.ts +3 -2
- package/dist/store/sqlite/merged-persons.js +5 -3
- package/dist/store/sqlite/migrations.generated.js +76 -0
- package/dist/store/sqlite/people-list.d.ts +1 -6
- package/dist/store/sqlite/people-list.js +97 -42
- package/dist/store/sqlite/person-links.js +13 -3
- package/dist/store/sqlite/person-match-scan.js +5 -2
- package/dist/store/sqlite/schema/mail-sorting.d.ts +384 -0
- package/dist/store/sqlite/schema/mail-sorting.js +31 -0
- package/dist/store/sqlite/schema/sender-bots.d.ts +56 -0
- package/dist/store/sqlite/schema/sender-bots.js +9 -1
- package/dist/store/sqlite/schema.d.ts +66 -1
- package/dist/store/sqlite/schema.js +9 -1
- package/dist/store/sqlite/sender-bots.d.ts +89 -15
- package/dist/store/sqlite/sender-bots.js +417 -136
- package/dist/store/sqlite/sender-signals.d.ts +11 -4
- package/dist/store/sqlite/sender-signals.js +14 -10
- package/package.json +2 -2
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import { createReadStream, createWriteStream, mkdirSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { rename, rm } from "node:fs/promises";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { pipeline } from "node:stream/promises";
|
|
6
|
+
import { createGunzip } from "node:zlib";
|
|
7
|
+
import { CliError } from "@wirecat/cli-base";
|
|
8
|
+
import { hostFetch } from "@wirecat/cli-base/http";
|
|
9
|
+
import { domainListsDirectory, installedPack, listFile, PACK_MANIFEST_URL, } from "../domain/domain-lists.js";
|
|
10
|
+
import { installFiles, megabytes } from "../speech/install.js";
|
|
11
|
+
/** Where a release asset is served from: GitHub answers with a redirect to its asset host. */
|
|
12
|
+
const RELEASE_HOSTS = ["github.com", "release-assets.githubusercontent.com", "objects.githubusercontent.com"];
|
|
13
|
+
const DOWNLOAD_MS = 10 * 60_000;
|
|
14
|
+
/** The hosts a download may reach, each once: `hostFetch` refuses a list that names one twice. */
|
|
15
|
+
export const packHosts = (urls) => [
|
|
16
|
+
...new Set([...RELEASE_HOSTS, ...urls.map((url) => new URL(url).hostname)]),
|
|
17
|
+
];
|
|
18
|
+
const ID = /^[a-z0-9][a-z0-9-]{0,62}$/;
|
|
19
|
+
const SHA256 = /^[0-9a-f]{64}$/;
|
|
20
|
+
const DOMAIN = /^[a-z0-9_]([a-z0-9_.-]*[a-z0-9])?$/;
|
|
21
|
+
const invalid = (what) => new CliError("invalid_response", `the domain-list manifest ${what}`);
|
|
22
|
+
/** The manifest as a release serves it, refused whole when a source would write outside the pack or skip its check. */
|
|
23
|
+
export const parseManifest = (value) => {
|
|
24
|
+
const manifest = value;
|
|
25
|
+
if (typeof manifest?.version !== "string" || !Array.isArray(manifest.sources))
|
|
26
|
+
throw invalid("has no version or sources");
|
|
27
|
+
const ids = new Set();
|
|
28
|
+
for (const source of manifest.sources) {
|
|
29
|
+
if (typeof source.id !== "string" || !ID.test(source.id) || ids.has(source.id))
|
|
30
|
+
throw invalid(`names a bad or repeated source id: ${String(source.id)}`);
|
|
31
|
+
ids.add(source.id);
|
|
32
|
+
if (typeof source.url !== "string" || !source.url.startsWith("https://"))
|
|
33
|
+
throw invalid(`gives ${source.id} a url that is not https`);
|
|
34
|
+
if (!["sector", "freemail", "bad"].includes(source.signal))
|
|
35
|
+
throw invalid(`gives ${source.id} no signal`);
|
|
36
|
+
if (source.class !== "commercial-ok" && source.class !== "non-commercial")
|
|
37
|
+
throw invalid(`gives ${source.id} no licence class`);
|
|
38
|
+
if (source.upstream === true) {
|
|
39
|
+
if (!Number.isSafeInteger(source.max_bytes))
|
|
40
|
+
throw invalid(`gives upstream ${source.id} no size limit`);
|
|
41
|
+
}
|
|
42
|
+
else if (!SHA256.test(source.sha256 ?? "") || !Number.isSafeInteger(source.bytes))
|
|
43
|
+
throw invalid(`gives ${source.id} no sha256 and size`);
|
|
44
|
+
}
|
|
45
|
+
return manifest;
|
|
46
|
+
};
|
|
47
|
+
const fetchManifest = async (url, get) => {
|
|
48
|
+
const response = await get(url, { signal: AbortSignal.timeout(60_000) });
|
|
49
|
+
if (!response.ok) {
|
|
50
|
+
await response.body?.cancel();
|
|
51
|
+
throw new CliError("network_error", `the domain-list manifest could not be downloaded: HTTP ${response.status}`);
|
|
52
|
+
}
|
|
53
|
+
try {
|
|
54
|
+
return parseManifest(await response.json());
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
if (error instanceof CliError)
|
|
58
|
+
throw error;
|
|
59
|
+
throw invalid("is not JSON");
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
const gunzipTo = async (from, to) => pipeline(createReadStream(from), createGunzip(), createWriteStream(to, { flags: "wx", mode: 0o600 }));
|
|
63
|
+
/**
|
|
64
|
+
* A list the source does not let us redistribute, fetched from the source itself, whole. Nothing pins its bytes, so
|
|
65
|
+
* its sha256 is recorded as it arrived, and only lines that read as a domain are kept.
|
|
66
|
+
*/
|
|
67
|
+
const fetchUpstream = async (source, path, get) => {
|
|
68
|
+
const response = await get(source.url, { signal: AbortSignal.timeout(120_000) });
|
|
69
|
+
if (!response.ok || !response.body) {
|
|
70
|
+
await response.body?.cancel();
|
|
71
|
+
throw new CliError("network_error", `${source.id} could not be downloaded from its source: HTTP ${response.status}`);
|
|
72
|
+
}
|
|
73
|
+
const limit = source.max_bytes ?? 0;
|
|
74
|
+
const hash = createHash("sha256");
|
|
75
|
+
const chunks = [];
|
|
76
|
+
let bytes = 0;
|
|
77
|
+
for await (const chunk of response.body) {
|
|
78
|
+
bytes += chunk.length;
|
|
79
|
+
if (bytes > limit)
|
|
80
|
+
throw new CliError("invalid_response", `${source.id} is larger than ${megabytes(limit)}`);
|
|
81
|
+
hash.update(chunk);
|
|
82
|
+
chunks.push(Buffer.from(chunk));
|
|
83
|
+
}
|
|
84
|
+
const lines = [
|
|
85
|
+
...new Set(Buffer.concat(chunks)
|
|
86
|
+
.toString("utf8")
|
|
87
|
+
.split("\n")
|
|
88
|
+
.map((line) => line.trim().toLowerCase())
|
|
89
|
+
.filter((line) => DOMAIN.test(line) && line.includes("."))),
|
|
90
|
+
];
|
|
91
|
+
writeFileSync(path, lines.length === 0 ? "" : `${lines.join("\n")}\n`, { flag: "wx", mode: 0o600 });
|
|
92
|
+
return { sha256: hash.digest("hex"), lines: lines.length, bytes };
|
|
93
|
+
};
|
|
94
|
+
/**
|
|
95
|
+
* Brings the pack to the newest release: every file checked against the manifest's sha256 as it arrives, then the
|
|
96
|
+
* whole folder swapped at once, so a failed download leaves the pack as it was. Nothing is downloaded when the pack
|
|
97
|
+
* here is already that version with the same sources.
|
|
98
|
+
*/
|
|
99
|
+
export const updateDomainLists = async ({ env, commercialOnly = false, fetch: given, manifestUrl = PACK_MANIFEST_URL, progress = () => { }, bytes, }) => {
|
|
100
|
+
const manifest = await fetchManifest(manifestUrl, given ?? hostFetch({ hosts: packHosts([manifestUrl]), timeoutMs: 60_000 }));
|
|
101
|
+
const get = given ??
|
|
102
|
+
hostFetch({
|
|
103
|
+
hosts: packHosts(manifest.sources.map((one) => one.url)),
|
|
104
|
+
timeoutMs: DOWNLOAD_MS,
|
|
105
|
+
});
|
|
106
|
+
const before = installedPack(env);
|
|
107
|
+
const sources = manifest.sources.filter((one) => !commercialOnly || one.class === "commercial-ok");
|
|
108
|
+
if (before !== undefined &&
|
|
109
|
+
before.version === manifest.version &&
|
|
110
|
+
before.commercial_only === commercialOnly &&
|
|
111
|
+
sources.every((one) => before.files[one.id] !== undefined))
|
|
112
|
+
return { pack: before, updated: false, previous: before.version };
|
|
113
|
+
const directory = domainListsDirectory(env);
|
|
114
|
+
const staging = `${directory}.${randomUUID()}.part`;
|
|
115
|
+
mkdirSync(staging, { recursive: true, mode: 0o700 });
|
|
116
|
+
try {
|
|
117
|
+
const published = sources.filter((one) => !one.upstream);
|
|
118
|
+
const weight = published.reduce((sum, one) => sum + (one.bytes ?? 0), 0);
|
|
119
|
+
progress(`domain lists ${manifest.version}: ${megabytes(weight)} from the WireCat release`);
|
|
120
|
+
await installFiles(published.map((one) => [
|
|
121
|
+
{ name: `${one.id}.txt.gz`, url: one.url, sha256: one.sha256 ?? "", bytes: one.bytes ?? 0 },
|
|
122
|
+
`${listFile(staging, one.id)}.gz`,
|
|
123
|
+
]), { fetch: get, progress, ...(bytes ? { bytes } : {}) });
|
|
124
|
+
const files = {};
|
|
125
|
+
for (const source of published) {
|
|
126
|
+
const path = listFile(staging, source.id);
|
|
127
|
+
await gunzipTo(`${path}.gz`, path);
|
|
128
|
+
await rm(`${path}.gz`);
|
|
129
|
+
files[source.id] = { sha256: source.sha256 ?? "", lines: source.count ?? 0, bytes: source.bytes ?? 0 };
|
|
130
|
+
}
|
|
131
|
+
for (const source of sources.filter((one) => one.upstream)) {
|
|
132
|
+
progress(`${source.id}: from ${new URL(source.url).host}, under its own terms (${source.licence})`);
|
|
133
|
+
files[source.id] = await fetchUpstream(source, listFile(staging, source.id), get);
|
|
134
|
+
}
|
|
135
|
+
const pack = {
|
|
136
|
+
...manifest,
|
|
137
|
+
installed_at: new Date().toISOString(),
|
|
138
|
+
commercial_only: commercialOnly,
|
|
139
|
+
files,
|
|
140
|
+
};
|
|
141
|
+
writeFileSync(join(staging, "manifest.json"), `${JSON.stringify(pack, null, 2)}\n`, { mode: 0o600 });
|
|
142
|
+
mkdirSync(dirname(directory), { recursive: true, mode: 0o700 });
|
|
143
|
+
const old = `${directory}.${randomUUID()}.old`;
|
|
144
|
+
await rename(directory, old).catch((error) => {
|
|
145
|
+
if (error.code !== "ENOENT")
|
|
146
|
+
throw error;
|
|
147
|
+
});
|
|
148
|
+
await rename(staging, directory);
|
|
149
|
+
await rm(old, { recursive: true, force: true });
|
|
150
|
+
return { pack, updated: true, previous: before?.version ?? null };
|
|
151
|
+
}
|
|
152
|
+
finally {
|
|
153
|
+
await rm(staging, { recursive: true, force: true });
|
|
154
|
+
}
|
|
155
|
+
};
|
|
@@ -15,7 +15,7 @@ import { mailAround, mergeMail, withMailThreads } from "./mail-search.js";
|
|
|
15
15
|
import { chatAmong, chatsMatchingIn, senderAmong, sendersMatching } from "./message-resolution.js";
|
|
16
16
|
import { accountsOfKind, listedAccounts, MAIL } from "./search-kind.js";
|
|
17
17
|
const PERSON_FIELDS = new Set(["from", "to", "cc", "bcc"]);
|
|
18
|
-
const MAIL_FIELDS = new Set(["to", "cc", "bcc", "subject", "mailbox", "label", "is", "list"]);
|
|
18
|
+
const MAIL_FIELDS = new Set(["to", "cc", "bcc", "subject", "mailbox", "label", "is", "list", "type", "reach"]);
|
|
19
19
|
import { parseLucene, timezoneOf, walkQuery, } from "@wirecat/cli-base/query";
|
|
20
20
|
import { MESSAGE_PARSING, searchError } from "../search/lucene/types.js";
|
|
21
21
|
import { rangeOf } from "../search/service-query.js";
|
|
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
|
|
|
14
14
|
dryRun?: boolean;
|
|
15
15
|
}) => Promise<{
|
|
16
16
|
items: ({
|
|
17
|
-
error?: undefined;
|
|
18
17
|
chatId: string;
|
|
19
18
|
tags: import("../domain/channel-tags.js").ChannelTagMatch[];
|
|
20
19
|
algorithm: string;
|
|
21
20
|
fetchedAt: string | null;
|
|
22
21
|
source: string;
|
|
22
|
+
error?: undefined;
|
|
23
23
|
} | {
|
|
24
24
|
tags?: undefined;
|
|
25
25
|
algorithm?: undefined;
|
package/dist/store/areas.d.ts
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* Store area types and constants some CLIs use beyond the stable `@wirecat/cli-core/store`: experimental, so a
|
|
3
3
|
* minor release may change them.
|
|
4
4
|
*/
|
|
5
|
+
export { MAIL_TYPES, type MailType } from "../mail/mail-types.js";
|
|
5
6
|
export { type AddedSource, type AddedSourceContent, type AddedSourceInput, addedSourceKeyOf, } from "./sqlite/added-sources.js";
|
|
6
7
|
export type { ContractFilter } from "./sqlite/business-contracts.js";
|
|
7
8
|
export type { CatalogEntry, CatalogInput, CatalogQuery } from "./sqlite/catalog.js";
|
|
@@ -30,7 +31,8 @@ export type { ProductFilter } from "./sqlite/products.js";
|
|
|
30
31
|
export { PROPOSAL_STATUSES, type ProposedAction } from "./sqlite/proposed-actions.js";
|
|
31
32
|
export type { MatchRun, RecordKey } from "./sqlite/records.js";
|
|
32
33
|
export type { RelationListItem } from "./sqlite/relation-list.js";
|
|
33
|
-
export type { SenderBot } from "./sqlite/sender-bots.js";
|
|
34
|
+
export type { BotIdentity, BotList, BotListOptions, BotMove, SenderBot, SenderBotDetails, } from "./sqlite/sender-bots.js";
|
|
35
|
+
export { REACHES, type Reach } from "./sqlite/sender-signals.js";
|
|
34
36
|
export type { SubscriptionFilter } from "./sqlite/subscriptions.js";
|
|
35
37
|
export { PROJECT_TASK_FIELDS, TASK_SORTS, type TaskSort } from "./sqlite/task-board.js";
|
|
36
38
|
export { TASK_RELATION_KINDS, type TaskRelationKind } from "./sqlite/task-relations.js";
|
package/dist/store/areas.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
* Store area types and constants some CLIs use beyond the stable `@wirecat/cli-core/store`: experimental, so a
|
|
3
3
|
* minor release may change them.
|
|
4
4
|
*/
|
|
5
|
+
export { MAIL_TYPES } from "../mail/mail-types.js";
|
|
5
6
|
export { addedSourceKeyOf, } from "./sqlite/added-sources.js";
|
|
6
7
|
export { crmIdentityId } from "./sqlite/crm-rows.js";
|
|
7
8
|
export { crmSettingKey } from "./sqlite/crm-settings.js";
|
|
@@ -11,6 +12,7 @@ export { ORGANIZATION_KINDS, PROJECT_TYPES, SCOPES, } from "./sqlite/knowledge.j
|
|
|
11
12
|
export { PEOPLE_SORTS } from "./sqlite/people-list.js";
|
|
12
13
|
export { parseMergeId } from "./sqlite/person-merges.js";
|
|
13
14
|
export { PROPOSAL_STATUSES } from "./sqlite/proposed-actions.js";
|
|
15
|
+
export { REACHES } from "./sqlite/sender-signals.js";
|
|
14
16
|
export { PROJECT_TASK_FIELDS, TASK_SORTS } from "./sqlite/task-board.js";
|
|
15
17
|
export { TASK_RELATION_KINDS } from "./sqlite/task-relations.js";
|
|
16
18
|
export { TASK_ROLES, } from "./sqlite/work-tasks.js";
|
package/dist/store/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export type { ContextEvidenceItem, ContextEvidencePage, ContextEvidenceReader, ContextEvidenceRequest, ContextEvidenceSender, ContextSource, } from "../context/evidence.js";
|
|
2
2
|
export { BUSINESS_KINDS, type BusinessKind } from "../domain/business.js";
|
|
3
3
|
export { FACT_STATUSES, FACT_TYPES, MEMORY_KINDS, MEMORY_SCOPES, MEMORY_STATUSES, TASK_TYPES, WORK_TASK_TYPES, } from "../domain/knowledge.js";
|
|
4
|
-
export { type KindSignal, PERSON_KINDS, type PersonKind } from "../domain/person-kinds.js";
|
|
4
|
+
export { type KindSignal, PERSON_KINDS, type PersonKind, SENDER_BOT_PREFIX } from "../domain/person-kinds.js";
|
|
5
5
|
export type { RefState, RefSummary, RefSummaryKind, RefsStore } from "../domain/ref-summaries.js";
|
|
6
6
|
export type { TagConsolidationApplyOptions, TagConsolidationOptions, TagConsolidationPreview, TagConsolidationReceipt, TagConsolidationStore, } from "../domain/tag-consolidation.js";
|
|
7
7
|
export type { TagRedirectIndex, TagRedirectResolution, TagRedirectSnapshot } from "../domain/tag-redirects.js";
|
|
@@ -104,7 +104,7 @@ export type { RelationRole, RelationRoles } from "./sqlite/relation-roles.js";
|
|
|
104
104
|
export type { RelationsStore, ReportedIssue, ReportedRelation, ReportedScope, ReportedSync, } from "./sqlite/reported-relations.js";
|
|
105
105
|
export type { AuthorInfo, Party, Reviewed, Written } from "./sqlite/reviewed.js";
|
|
106
106
|
export { fillSearchIndex, resetSearchIndex, type SearchIndexFill, type SearchIndexState, searchIndexState, } from "./sqlite/search-index.js";
|
|
107
|
-
export type { SenderBot } from "./sqlite/sender-bots.js";
|
|
107
|
+
export type { BotIdentity, BotList, BotListOptions, BotMove, SenderBot, SenderBotDetails, } from "./sqlite/sender-bots.js";
|
|
108
108
|
export { REACHES, type Reach, type SenderSignal } from "./sqlite/sender-signals.js";
|
|
109
109
|
export type { ChallengeInput, SourceReviewDecision } from "./sqlite/source-review.js";
|
|
110
110
|
export type { PriceFilter, PriceInput, Subscription, SubscriptionDetail, SubscriptionFields, SubscriptionFilter, SubscriptionInput, SubscriptionPrice, SubscriptionsStore, SubscriptionUpdate, } from "./sqlite/subscriptions.js";
|
package/dist/store/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { BUSINESS_KINDS } from "../domain/business.js";
|
|
2
2
|
export { FACT_STATUSES, FACT_TYPES, MEMORY_KINDS, MEMORY_SCOPES, MEMORY_STATUSES, TASK_TYPES, WORK_TASK_TYPES, } from "../domain/knowledge.js";
|
|
3
|
-
export { PERSON_KINDS } from "../domain/person-kinds.js";
|
|
3
|
+
export { PERSON_KINDS, SENDER_BOT_PREFIX } from "../domain/person-kinds.js";
|
|
4
4
|
export { createTagRedirectIndex } from "../domain/tag-redirects.js";
|
|
5
5
|
export { note } from "../entities/note.js";
|
|
6
6
|
export { PAYMENT_DIRECTIONS, PAYMENT_STATES, paymentTitle, validatePayment } from "../meetings/index.js";
|
package/dist/store/people.d.ts
CHANGED
|
@@ -15,7 +15,7 @@ import { type PersonPreparationRead } from "./sqlite/person-preparation.js";
|
|
|
15
15
|
import { type ShownBecause } from "./sqlite/person-ties.js";
|
|
16
16
|
import type { PrivateContact, PrivateContactNote } from "./sqlite/private-people.js";
|
|
17
17
|
import type { ProposedAction } from "./sqlite/proposed-actions.js";
|
|
18
|
-
import { type SenderBot } from "./sqlite/sender-bots.js";
|
|
18
|
+
import { type BotList, type BotListOptions, type SenderBot, type SenderBotDetails } from "./sqlite/sender-bots.js";
|
|
19
19
|
import type { AccountKey, IdentityRef, LinkOptions, PersonFacts, PersonRecord, StoredAccount, UnlinkOptions } from "./types.js";
|
|
20
20
|
/** @experimental */
|
|
21
21
|
export interface AccountPeople {
|
|
@@ -207,13 +207,22 @@ export interface PeopleStore extends AccountPeople {
|
|
|
207
207
|
similar(name: string, options?: {
|
|
208
208
|
limit?: number;
|
|
209
209
|
}): Promise<SimilarPerson[]>;
|
|
210
|
-
/** Why each `person:<uid>` is shown by default, as `list` gives it; an empty list for one with no tie
|
|
210
|
+
/** Why each `person:<uid>` is shown by default, as `list` gives it; an empty list for one with no tie. */
|
|
211
211
|
ties(people: readonly string[]): Promise<Record<string, ShownBecause[]>>;
|
|
212
212
|
/**
|
|
213
|
-
* The
|
|
214
|
-
*
|
|
215
|
-
*
|
|
216
|
-
|
|
213
|
+
* The sender bots: programs that write to the owner, apart from people (`sender-bot:<id>`), by name. `query` looks in
|
|
214
|
+
* their names, addresses and usernames; `organization` (`organization:<id>`) keeps the ones that send for it.
|
|
215
|
+
* @experimental
|
|
216
|
+
*/
|
|
217
|
+
listBots(options: BotListOptions): Promise<BotList>;
|
|
218
|
+
/** One sender bot (`sender-bot:<id>`), its identities and every move to or from it. @experimental */
|
|
219
|
+
showBot(bot: string): Promise<SenderBotDetails>;
|
|
220
|
+
/**
|
|
221
|
+
* The owner says a sender is a program: a person (`person:<uid>`), a bot (`sender-bot:<id>`) or one identity moves
|
|
222
|
+
* to a sender bot for its whole history, and no rule gives it back. Its messages keep pointing at the identity. `bot`
|
|
223
|
+
* joins a stored bot; else a bot already holding it keeps it, or a new one takes it. A person every identity left is
|
|
224
|
+
* hidden from lists, and a move back gives their uid back. The owner's alone; refused for the owner's own person.
|
|
225
|
+
* @experimental
|
|
217
226
|
*/
|
|
218
227
|
moveToBot(subject: string | IdentityRef, by: Decider, options?: {
|
|
219
228
|
bot?: string;
|
|
@@ -221,9 +230,9 @@ export interface PeopleStore extends AccountPeople {
|
|
|
221
230
|
reason?: string;
|
|
222
231
|
}): Promise<SenderBot>;
|
|
223
232
|
/**
|
|
224
|
-
* The owner says a sender is a person: a bot (`sender-bot:<id>`
|
|
225
|
-
*
|
|
226
|
-
* a person.
|
|
233
|
+
* The owner says a sender is a person: a bot (`sender-bot:<id>`) or one identity of it moves to a person for its
|
|
234
|
+
* whole history, and no rule makes it a bot again. `person` takes it; else each identity goes back to the person it
|
|
235
|
+
* came from, or a person of its own. Said of a person, it keeps them one. The owner's alone. @experimental
|
|
227
236
|
*/
|
|
228
237
|
moveToPerson(subject: string | IdentityRef, by: Decider, options?: {
|
|
229
238
|
person?: string;
|
package/dist/store/people.js
CHANGED
|
@@ -7,7 +7,7 @@ import * as identityProposals from "./sqlite/identity-proposals.js";
|
|
|
7
7
|
import { rekeyIdentities } from "./sqlite/identity-rekey.js";
|
|
8
8
|
import * as identitySplits from "./sqlite/identity-split-proposals.js";
|
|
9
9
|
import { linkToOwner } from "./sqlite/own-identities.js";
|
|
10
|
-
import { countPeople, listPeople, similarPeople, } from "./sqlite/people-list.js";
|
|
10
|
+
import { countPeople, listPeople, similarPeople, storeKinds, } from "./sqlite/people-list.js";
|
|
11
11
|
import { keepPerson, markTestData, personDoubts, } from "./sqlite/person-doubts.js";
|
|
12
12
|
import { erasePerson } from "./sqlite/person-erase.js";
|
|
13
13
|
import * as personLinks from "./sqlite/person-links.js";
|
|
@@ -18,7 +18,7 @@ import { personPreparation } from "./sqlite/person-preparation.js";
|
|
|
18
18
|
import { personSeenInAccounts } from "./sqlite/person-scope.js";
|
|
19
19
|
import { shownReasons } from "./sqlite/person-ties.js";
|
|
20
20
|
import * as privatePeople from "./sqlite/private-people.js";
|
|
21
|
-
import { moveToBot, moveToPerson,
|
|
21
|
+
import { listBots, moveToBot, moveToPerson, showBot, } from "./sqlite/sender-bots.js";
|
|
22
22
|
import { write } from "./sqlite/transaction.js";
|
|
23
23
|
export const accountPeopleOver = (context) => {
|
|
24
24
|
const { database } = context;
|
|
@@ -165,12 +165,13 @@ export const peopleStoreOver = (context, keyed) => {
|
|
|
165
165
|
similar: async (name, { limit = 8 } = {}) => similarPeople(database, name, limit),
|
|
166
166
|
ties: async (people) => {
|
|
167
167
|
const reasons = shownReasons(database);
|
|
168
|
-
|
|
169
|
-
return Object.fromEntries(people.map((ref) => {
|
|
170
|
-
const id = Number(ref.replace(/^person:/, ""));
|
|
171
|
-
return [ref, bots.has(id) ? [] : (reasons.get(id) ?? [])];
|
|
172
|
-
}));
|
|
168
|
+
return Object.fromEntries(people.map((ref) => [ref, reasons.get(Number(ref.replace(/^person:/, ""))) ?? []]));
|
|
173
169
|
},
|
|
170
|
+
listBots: async (options) => {
|
|
171
|
+
storeKinds(database);
|
|
172
|
+
return listBots(database, options);
|
|
173
|
+
},
|
|
174
|
+
showBot: async (bot) => showBot(database, bot),
|
|
174
175
|
moveToBot: async (subject, by, options) => {
|
|
175
176
|
ownerOnly(by, "moves a sender to a bot");
|
|
176
177
|
return moveToBot(context, subject, options);
|
package/dist/store/public.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export type { ContextEvidenceItem, ContextEvidencePage, ContextEvidenceReader, ContextEvidenceRequest, ContextEvidenceSender, ContextSource, } from "../context/evidence.js";
|
|
2
2
|
export { BUSINESS_KINDS, type BusinessKind } from "../domain/business.js";
|
|
3
3
|
export { FACT_STATUSES, FACT_TYPES, MEMORY_KINDS, MEMORY_SCOPES, MEMORY_STATUSES, TASK_TYPES, WORK_TASK_TYPES, } from "../domain/knowledge.js";
|
|
4
|
-
export { type KindSignal, PERSON_KINDS, type PersonKind } from "../domain/person-kinds.js";
|
|
4
|
+
export { type KindSignal, PERSON_KINDS, type PersonKind, SENDER_BOT_PREFIX } from "../domain/person-kinds.js";
|
|
5
5
|
export type { RefState, RefSummary, RefSummaryKind, RefsStore } from "../domain/ref-summaries.js";
|
|
6
6
|
export type { TagConsolidationApplyOptions, TagConsolidationOptions, TagConsolidationPreview, TagConsolidationReceipt, TagConsolidationStore, } from "../domain/tag-consolidation.js";
|
|
7
7
|
export type { TagRedirectIndex, TagRedirectResolution, TagRedirectSnapshot } from "../domain/tag-redirects.js";
|
package/dist/store/public.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { BUSINESS_KINDS } from "../domain/business.js";
|
|
2
2
|
export { FACT_STATUSES, FACT_TYPES, MEMORY_KINDS, MEMORY_SCOPES, MEMORY_STATUSES, TASK_TYPES, WORK_TASK_TYPES, } from "../domain/knowledge.js";
|
|
3
|
-
export { PERSON_KINDS } from "../domain/person-kinds.js";
|
|
3
|
+
export { PERSON_KINDS, SENDER_BOT_PREFIX } from "../domain/person-kinds.js";
|
|
4
4
|
export { createTagRedirectIndex } from "../domain/tag-redirects.js";
|
|
5
5
|
export { note } from "../entities/note.js";
|
|
6
6
|
export { PAYMENT_DIRECTIONS, PAYMENT_STATES, paymentTitle, validatePayment } from "../meetings/index.js";
|
package/dist/store/queries.js
CHANGED
|
@@ -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
|
|
11
|
-
|
|
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 {
|
|
@@ -147,8 +147,10 @@ export const dropOrphanPeople = (database, unseenBefore) => {
|
|
|
147
147
|
const persons = database
|
|
148
148
|
.prepare(`SELECT person_id AS id FROM identity_links WHERE identity_id IN (SELECT value FROM json_each(?))
|
|
149
149
|
UNION SELECT from_person_id FROM identity_link_events WHERE identity_id IN (SELECT value FROM json_each(?))
|
|
150
|
+
AND from_person_id IS NOT NULL
|
|
151
|
+
UNION SELECT from_person_id FROM sender_bot_moves WHERE identity_id IN (SELECT value FROM json_each(?))
|
|
150
152
|
AND from_person_id IS NOT NULL`)
|
|
151
|
-
.all(gone, gone)
|
|
153
|
+
.all(gone, gone, gone)
|
|
152
154
|
.map(({ id }) => Number(id));
|
|
153
155
|
for (const table of ["identity_revisions", "identity_link_events", "identity_links"])
|
|
154
156
|
database.prepare(`DELETE FROM ${table} WHERE identity_id IN (SELECT value FROM json_each(?))`).run(gone);
|
|
@@ -11,22 +11,25 @@ export declare const REFUSED_DOMAIN = "organization-domain";
|
|
|
11
11
|
/** The registrable domain whose organization an address joins; none for free, throwaway and platform mail. */
|
|
12
12
|
export declare const companyDomainOf: (address: string) => string | undefined;
|
|
13
13
|
/**
|
|
14
|
-
* A person as the kind pass leaves them: `holds` for a bot or a shared
|
|
15
|
-
* never for one the owner kept as a person.
|
|
14
|
+
* A person or a sender bot (`bot`, its `sender_bots` id) as the kind pass leaves them: `holds` for a bot or a shared
|
|
15
|
+
* mailbox, whose addresses the organization owns; never for one the owner kept as a person.
|
|
16
16
|
*/
|
|
17
17
|
export interface Sorted {
|
|
18
18
|
id: number;
|
|
19
19
|
displayName: string | null;
|
|
20
20
|
holds: boolean;
|
|
21
|
+
bot?: boolean;
|
|
21
22
|
}
|
|
22
23
|
/**
|
|
23
|
-
* Plan step 5: a bot or a shared mailbox at a company domain joins that domain's organization, made when none holds
|
|
24
|
+
* Plan step 5: a sender bot or a shared mailbox at a company domain joins that domain's organization, made when none holds
|
|
24
25
|
* it; a human there becomes a `member-of` it, never merged. Free mail, throwaway mail and sending platforms make none.
|
|
25
|
-
* An organization holding a domain of the built-in Wikidata list gets its `metadata.sector`.
|
|
26
|
+
* An organization holding a domain of the built-in Wikidata list or of the domain-list pack gets its `metadata.sector`.
|
|
26
27
|
* The owner's word holds: a membership the owner removed and a domain whose organization the owner erased are not made
|
|
27
28
|
* again. The caller holds the write lock.
|
|
28
29
|
*/
|
|
29
30
|
export declare const groupByDomain: (database: CacheDatabase, people: readonly Sorted[], at: number) => void;
|
|
31
|
+
/** Which lists the sectors in the store come from: this build's table and the pack in place. */
|
|
32
|
+
export declare const SECTORS_FROM = "organizations.sectors_from";
|
|
30
33
|
/** The owner erased an organization: no rule makes one for the company domains it held again. */
|
|
31
34
|
export declare const refuseDomainsOf: (database: CacheDatabase, organization: number, at: number) => void;
|
|
32
35
|
/** The owner moved these identities to a person: the holds a rule gave them go, so they read as a person's again. */
|
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { getDomainWithoutSuffix } from "tldts";
|
|
2
2
|
import { isReadable } from "../../domain/display-names.js";
|
|
3
|
-
import {
|
|
3
|
+
import { installedPack, isPackFreeMailDomain, lookupDomains } from "../../domain/domain-lists.js";
|
|
4
|
+
import { SECTORS_BUILT } from "../../domain/organization-sectors.generated.js";
|
|
5
|
+
import { isFreeMailDomain, SECTORS, sectorOfDomain } from "../../domain/organization-sectors.js";
|
|
4
6
|
import { isCompanyName } from "../../domain/person-kinds.js";
|
|
5
7
|
import { FREE_MAIL, isDisposableDomain, registrableOf } from "../../mail/score.js";
|
|
6
8
|
import { fold } from "../normalize.js";
|
|
@@ -43,7 +45,12 @@ export const companyDomainOf = (address) => {
|
|
|
43
45
|
if (!address.includes("@"))
|
|
44
46
|
return undefined;
|
|
45
47
|
const domain = registrableOf(address);
|
|
46
|
-
return domain.includes(".") &&
|
|
48
|
+
return domain.includes(".") &&
|
|
49
|
+
!FREE_MAIL.has(domain) &&
|
|
50
|
+
!isFreeMailDomain(domain) &&
|
|
51
|
+
!isPackFreeMailDomain(domain) &&
|
|
52
|
+
!SENDING_PLATFORMS.has(domain) &&
|
|
53
|
+
!isDisposableDomain(domain)
|
|
47
54
|
? domain
|
|
48
55
|
: undefined;
|
|
49
56
|
};
|
|
@@ -55,18 +62,27 @@ const nameFor = (shown, domain) => {
|
|
|
55
62
|
? shown.trim()
|
|
56
63
|
: domain;
|
|
57
64
|
};
|
|
58
|
-
const
|
|
65
|
+
const keyOf = (one) => `${one.bot ? "bot" : "person"}:${one.id}`;
|
|
66
|
+
const mailOf = (database, sorted) => {
|
|
59
67
|
const found = new Map();
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
"
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
const
|
|
66
|
-
if (
|
|
68
|
+
const held = [
|
|
69
|
+
{ prefix: "person", sql: "SELECT l.person_id AS holder, l.identity_id FROM identity_links l" },
|
|
70
|
+
{ prefix: "bot", sql: "SELECT l.bot_id AS holder, l.identity_id FROM sender_bot_identities l" },
|
|
71
|
+
];
|
|
72
|
+
for (const { prefix, sql } of held) {
|
|
73
|
+
const ids = sorted.filter((one) => (prefix === "bot") === (one.bot === true)).map(({ id }) => id);
|
|
74
|
+
if (ids.length === 0)
|
|
67
75
|
continue;
|
|
68
|
-
const
|
|
69
|
-
|
|
76
|
+
for (const row of database
|
|
77
|
+
.prepare(`SELECT h.holder, i.id, lower(i.external_id) AS address FROM (${sql}) h JOIN identities i ON i.id = h.identity_id ` +
|
|
78
|
+
"WHERE i.provider = 'email' AND h.holder IN (SELECT value FROM json_each(?)) ORDER BY i.id")
|
|
79
|
+
.all(JSON.stringify(ids))) {
|
|
80
|
+
const domain = companyDomainOf(String(row.address));
|
|
81
|
+
if (domain === undefined)
|
|
82
|
+
continue;
|
|
83
|
+
const key = `${prefix}:${Number(row.holder)}`;
|
|
84
|
+
found.set(key, [...(found.get(key) ?? []), { identity: Number(row.id), domain }]);
|
|
85
|
+
}
|
|
70
86
|
}
|
|
71
87
|
return found;
|
|
72
88
|
};
|
|
@@ -106,7 +122,6 @@ const othersAt = (database, domains, seen) => {
|
|
|
106
122
|
.prepare("SELECT l.person_id AS person, i.id, lower(i.external_id) AS address FROM identity_links l " +
|
|
107
123
|
"JOIN identities i ON i.id = l.identity_id JOIN persons p ON p.id = l.person_id " +
|
|
108
124
|
"WHERE i.provider = 'email' AND p.owner = 0 AND p.kind IS NOT NULL AND p.kind NOT IN ('test', 'merged') " +
|
|
109
|
-
"AND NOT EXISTS (SELECT 1 FROM sender_bots b WHERE b.person_id = p.id) " +
|
|
110
125
|
"AND NOT EXISTS (SELECT 1 FROM organization_identities oi WHERE oi.identity_id = i.id) ORDER BY i.id")
|
|
111
126
|
.all()) {
|
|
112
127
|
const person = Number(row.person);
|
|
@@ -120,14 +135,15 @@ const othersAt = (database, domains, seen) => {
|
|
|
120
135
|
return found;
|
|
121
136
|
};
|
|
122
137
|
/**
|
|
123
|
-
* Plan step 5: a bot or a shared mailbox at a company domain joins that domain's organization, made when none holds
|
|
138
|
+
* Plan step 5: a sender bot or a shared mailbox at a company domain joins that domain's organization, made when none holds
|
|
124
139
|
* it; a human there becomes a `member-of` it, never merged. Free mail, throwaway mail and sending platforms make none.
|
|
125
|
-
* An organization holding a domain of the built-in Wikidata list gets its `metadata.sector`.
|
|
140
|
+
* An organization holding a domain of the built-in Wikidata list or of the domain-list pack gets its `metadata.sector`.
|
|
126
141
|
* The owner's word holds: a membership the owner removed and a domain whose organization the owner erased are not made
|
|
127
142
|
* again. The caller holds the write lock.
|
|
128
143
|
*/
|
|
129
144
|
export const groupByDomain = (database, people, at) => {
|
|
130
|
-
|
|
145
|
+
refreshSectors(database, at);
|
|
146
|
+
const mail = mailOf(database, people);
|
|
131
147
|
if (mail.size === 0)
|
|
132
148
|
return;
|
|
133
149
|
const { byDomain, held } = holdersOf(database);
|
|
@@ -137,7 +153,7 @@ export const groupByDomain = (database, people, at) => {
|
|
|
137
153
|
"RETURNING id");
|
|
138
154
|
const hold = database.prepare("INSERT INTO organization_identities (identity_id, organization_id, method, author, created_at, updated_at) " +
|
|
139
155
|
`VALUES (?, ?, '${BY_DOMAIN}', 'rules', ?, ?) ON CONFLICT (identity_id, organization_id) DO NOTHING`);
|
|
140
|
-
const sends = database.prepare("UPDATE sender_bots SET organization_id = ?, updated_at = ? WHERE
|
|
156
|
+
const sends = database.prepare("UPDATE sender_bots SET organization_id = ?, updated_at = ? WHERE id = ? AND organization_id IS NULL");
|
|
141
157
|
const holder = (domain) => {
|
|
142
158
|
const found = byDomain.get(domain);
|
|
143
159
|
return found?.size === 1 ? [...found][0] : undefined;
|
|
@@ -145,7 +161,7 @@ export const groupByDomain = (database, people, at) => {
|
|
|
145
161
|
for (const person of people) {
|
|
146
162
|
if (!person.holds)
|
|
147
163
|
continue;
|
|
148
|
-
for (const { identity, domain } of mail.get(person
|
|
164
|
+
for (const { identity, domain } of mail.get(keyOf(person)) ?? []) {
|
|
149
165
|
let organization = held.get(identity);
|
|
150
166
|
if (organization === undefined) {
|
|
151
167
|
if ((byDomain.get(domain)?.size ?? 0) > 1)
|
|
@@ -161,7 +177,8 @@ export const groupByDomain = (database, people, at) => {
|
|
|
161
177
|
hold.run(identity, organization, at, at);
|
|
162
178
|
held.set(identity, organization);
|
|
163
179
|
}
|
|
164
|
-
|
|
180
|
+
if (person.bot)
|
|
181
|
+
sends.run(organization, at, person.id);
|
|
165
182
|
}
|
|
166
183
|
}
|
|
167
184
|
const removed = removedMemberships(database);
|
|
@@ -178,31 +195,72 @@ export const groupByDomain = (database, people, at) => {
|
|
|
178
195
|
member.run(person, organization, `writes from ${domain}`, at, at, person, organization);
|
|
179
196
|
}
|
|
180
197
|
};
|
|
181
|
-
const
|
|
182
|
-
|
|
198
|
+
const humans = people.filter((one) => !one.bot);
|
|
199
|
+
const seen = new Set(humans.map(({ id }) => id));
|
|
200
|
+
for (const person of humans)
|
|
183
201
|
if (!person.holds)
|
|
184
|
-
join(person.id, mail.get(person
|
|
202
|
+
join(person.id, mail.get(keyOf(person)) ?? []);
|
|
185
203
|
if (created.size > 0)
|
|
186
204
|
for (const [person, addresses] of othersAt(database, created, seen))
|
|
187
205
|
join(person, addresses);
|
|
188
|
-
|
|
206
|
+
if (created.size > 0)
|
|
207
|
+
setSectors(database, byDomain, at, new Set([...created].flatMap((domain) => [...(byDomain.get(domain) ?? [])])));
|
|
189
208
|
};
|
|
190
|
-
/**
|
|
191
|
-
const
|
|
209
|
+
/** Which lists the sectors in the store come from: this build's table and the pack in place. */
|
|
210
|
+
export const SECTORS_FROM = "organizations.sectors_from";
|
|
211
|
+
const listsVersion = () => {
|
|
212
|
+
const pack = installedPack();
|
|
213
|
+
return [SECTORS_BUILT, pack?.version ?? "none", ...Object.keys(pack?.files ?? {}).sort()].join(" ");
|
|
214
|
+
};
|
|
215
|
+
/** A newer table or pack can give a sector, change it or take it away: every organization is worked out again once. */
|
|
216
|
+
const refreshSectors = (database, at) => {
|
|
217
|
+
const version = listsVersion();
|
|
218
|
+
if (database.prepare("SELECT value FROM store_settings WHERE key = ?").get(SECTORS_FROM)?.value === version)
|
|
219
|
+
return;
|
|
220
|
+
setSectors(database, holdersOf(database).byDomain, at);
|
|
221
|
+
database
|
|
222
|
+
.prepare("INSERT OR REPLACE INTO store_settings (key, value, at) VALUES (?, ?, ?)")
|
|
223
|
+
.run(SECTORS_FROM, version, at);
|
|
224
|
+
};
|
|
225
|
+
/**
|
|
226
|
+
* Each organization holding a company domain takes that domain's sector, the first in `SECTORS` order if several; the
|
|
227
|
+
* built-in table wins over the pack, which only fills its gaps. A rule's sector goes when no list gives one any more.
|
|
228
|
+
* `metadata.sector_by` is `rules` (or absent, as #3350 wrote it) for a rule's sector; any other value is the owner's,
|
|
229
|
+
* which no rule changes.
|
|
230
|
+
*/
|
|
231
|
+
const setSectors = (database, byDomain, at, only) => {
|
|
232
|
+
const scope = [...byDomain].filter(([, organizations]) => only === undefined || [...organizations].some((one) => only.has(one)));
|
|
233
|
+
if (scope.length === 0)
|
|
234
|
+
return;
|
|
235
|
+
const pack = lookupDomains(new Set(scope.map(([domain]) => domain))).sectors;
|
|
236
|
+
const rank = (sector, fromPack) => SECTORS.indexOf(sector) + (fromPack ? SECTORS.length : 0);
|
|
192
237
|
const found = new Map();
|
|
193
|
-
for (const [domain, organizations] of
|
|
194
|
-
const
|
|
238
|
+
for (const [domain, organizations] of scope) {
|
|
239
|
+
const core = sectorOfDomain(domain);
|
|
240
|
+
const ranks = [
|
|
241
|
+
...(core === undefined ? [] : [rank(core, false)]),
|
|
242
|
+
...(pack.get(domain) ?? []).map((one) => rank(one, true)),
|
|
243
|
+
];
|
|
244
|
+
const best = ranks.reduce((low, one) => (low === undefined || one < low ? one : low), undefined);
|
|
245
|
+
for (const organization of organizations) {
|
|
246
|
+
if (only !== undefined && !only.has(organization))
|
|
247
|
+
continue;
|
|
248
|
+
const before = found.get(organization);
|
|
249
|
+
found.set(organization, before === undefined ? best : best === undefined ? before : Math.min(before, best));
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
const byRules = "coalesce(json_extract(metadata, '$.sector_by'), 'rules') = 'rules'";
|
|
253
|
+
const set = database.prepare("UPDATE organizations SET metadata = json_set(coalesce(metadata, '{}'), '$.sector', ?, '$.sector_by', 'rules'), " +
|
|
254
|
+
`updated_at = ? WHERE id = ? AND deleted_at IS NULL AND ${byRules} AND json_extract(metadata, '$.sector') IS NOT ?`);
|
|
255
|
+
const clear = database.prepare("UPDATE organizations SET metadata = json_remove(metadata, '$.sector', '$.sector_by'), updated_at = ? " +
|
|
256
|
+
`WHERE id = ? AND deleted_at IS NULL AND ${byRules} AND json_extract(metadata, '$.sector') IS NOT NULL`);
|
|
257
|
+
for (const [organization, ranked] of found) {
|
|
258
|
+
const sector = ranked === undefined ? undefined : SECTORS[ranked % SECTORS.length];
|
|
195
259
|
if (sector === undefined)
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
if (rank < (found.get(organization) ?? SECTORS.length))
|
|
200
|
-
found.set(organization, rank);
|
|
260
|
+
clear.run(at, organization);
|
|
261
|
+
else
|
|
262
|
+
set.run(sector, at, organization, sector);
|
|
201
263
|
}
|
|
202
|
-
const set = database.prepare("UPDATE organizations SET metadata = json_set(coalesce(metadata, '{}'), '$.sector', ?), updated_at = ? " +
|
|
203
|
-
"WHERE id = ? AND deleted_at IS NULL AND json_extract(metadata, '$.sector') IS NOT ?");
|
|
204
|
-
for (const [organization, rank] of found)
|
|
205
|
-
set.run(SECTORS[rank] ?? null, at, organization, SECTORS[rank] ?? null);
|
|
206
264
|
};
|
|
207
265
|
/** The owner erased an organization: no rule makes one for the company domains it held again. */
|
|
208
266
|
export const refuseDomainsOf = (database, organization, at) => {
|