@wirecat/cli-core 0.618.0 → 0.619.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 +339 -1
- package/README.md +1 -1
- package/THIRD_PARTY_NOTICES +3 -0
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/background/deliver.d.ts +5 -2
- package/dist/background/deliver.js +30 -12
- package/dist/background/report/render.d.ts +3 -1
- package/dist/background/report/render.js +3 -1
- package/dist/calendar/cli/answers.d.ts +1 -0
- package/dist/calendar/cli/answers.js +6 -1
- package/dist/calendar/cli/index.js +2 -14
- package/dist/calendar/cli/people-link.d.ts +3 -0
- package/dist/calendar/cli/people-link.js +23 -0
- package/dist/calendar/index.d.ts +1 -1
- package/dist/calendar/index.js +1 -1
- package/dist/calendar/mcp/index.d.ts +12 -12
- package/dist/cli/base-stages-command.d.ts +22 -0
- package/dist/cli/base-stages-command.js +174 -0
- package/dist/cli/command-runs.d.ts +2 -0
- package/dist/cli/command-runs.js +3 -1
- package/dist/cli/config-command.js +6 -1
- package/dist/cli/context.js +1 -0
- package/dist/cli/group-lock.d.ts +42 -0
- package/dist/cli/group-lock.js +130 -0
- package/dist/cli/index.d.ts +7 -2
- package/dist/cli/index.js +7 -2
- package/dist/cli/messenger/backfill-command.js +27 -15
- package/dist/cli/messenger/contacts-command.js +10 -3
- package/dist/cli/messenger/context.js +1 -0
- package/dist/cli/messenger/doctor-command.js +3 -1
- package/dist/cli/messenger/models-command.js +1 -1
- package/dist/cli/messenger/store-maintenance-command.d.ts +22 -2
- package/dist/cli/messenger/store-maintenance-command.js +9 -4
- package/dist/cli/model-catalogue-command.d.ts +3 -1
- package/dist/cli/model-catalogue-command.js +46 -2
- package/dist/cli/profile.d.ts +8 -0
- package/dist/cli/profile.js +25 -0
- package/dist/cli/program.js +2 -0
- package/dist/cli/runs/search-query.d.ts +1 -1
- package/dist/cli/runs/search-query.js +4 -0
- package/dist/cli/runs/search.d.ts +5 -1
- package/dist/cli/runs/search.js +12 -1
- package/dist/cli/search-left-out.d.ts +6 -1
- package/dist/cli/search-left-out.js +9 -4
- package/dist/cli/settings.d.ts +8 -0
- package/dist/cli/settings.js +17 -2
- package/dist/cli/shared-command-exports.d.ts +16 -0
- package/dist/cli/store-recover.d.ts +3 -3
- package/dist/cli/store-recover.js +26 -26
- package/dist/cli/store-settings.d.ts +2 -0
- package/dist/cli/store-settings.js +37 -9
- package/dist/crm/cli/index.js +38 -6
- package/dist/crm/group-hint.d.ts +8 -0
- package/dist/crm/group-hint.js +13 -0
- package/dist/crm/source.d.ts +12 -1
- package/dist/crm/sync.d.ts +31 -2
- package/dist/crm/sync.js +110 -3
- package/dist/crm/testing/acme-scenario.d.ts +40 -0
- package/dist/crm/testing/acme-scenario.js +170 -0
- package/dist/crm/testing/index.d.ts +1 -0
- package/dist/crm/testing/index.js +1 -0
- package/dist/crm/testing/source-contract.js +12 -0
- package/dist/crm/testing/source.d.ts +2 -0
- package/dist/crm/testing/source.js +1 -0
- package/dist/domain/addresses.d.ts +13 -0
- package/dist/domain/addresses.js +63 -0
- package/dist/domain/categories.d.ts +3 -0
- package/dist/domain/categories.js +2 -0
- package/dist/domain/crm.d.ts +23 -0
- package/dist/domain/crm.js +7 -0
- package/dist/domain/mentions.d.ts +2 -12
- package/dist/domain/mentions.js +2 -19
- package/dist/domain/orders.d.ts +8 -1
- package/dist/domain/orders.js +6 -2
- package/dist/domain/phones.d.ts +26 -0
- package/dist/domain/phones.js +48 -0
- package/dist/domain/record-types.d.ts +1 -1
- package/dist/domain/record-types.js +1 -0
- package/dist/domain/records.d.ts +5 -0
- package/dist/domain/ref-summaries.d.ts +39 -0
- package/dist/domain/ref-summaries.js +51 -3
- package/dist/domain/relations.d.ts +12 -2
- package/dist/domain/relations.js +14 -3
- package/dist/domain/vcard.d.ts +2 -2
- package/dist/domain/vcard.js +4 -10
- package/dist/embeddings/models.d.ts +11 -3
- package/dist/embeddings/models.js +28 -4
- package/dist/entities/business-context.d.ts +149 -0
- package/dist/entities/business-context.js +192 -0
- package/dist/entities/contact-activity.d.ts +2 -0
- package/dist/entities/contact-activity.js +7 -1
- package/dist/entities/contact-context.d.ts +157 -0
- package/dist/entities/contact-context.js +2 -0
- package/dist/entities/deal.d.ts +10 -0
- package/dist/entities/deal.js +2 -0
- package/dist/entities/index.d.ts +23 -3
- package/dist/entities/index.js +5 -0
- package/dist/entities/mention.d.ts +4 -3
- package/dist/entities/mention.js +2 -1
- package/dist/entities/message-transfer.d.ts +4 -2
- package/dist/entities/message-transfer.js +2 -2
- package/dist/entities/model.d.ts +2 -2
- package/dist/entities/model.js +1 -1
- package/dist/entities/relationship.d.ts +4 -0
- package/dist/entities/relationship.js +4 -0
- package/dist/errors/reasons.js +37 -4
- package/dist/fetch/page.js +2 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +3 -2
- package/dist/meetings/context-store.d.ts +2 -0
- package/dist/meetings/findings-rules.d.ts +4 -0
- package/dist/meetings/findings-rules.js +5 -2
- package/dist/meetings/result-items.d.ts +1 -0
- package/dist/meetings/result-items.js +1 -0
- package/dist/models/index.js +22 -5
- package/dist/runs/events.d.ts +11 -1
- package/dist/runs/events.js +3 -1
- package/dist/runs/log-attributes.js +4 -0
- package/dist/runs/log-events.js +2 -0
- package/dist/runs/recording.d.ts +3 -0
- package/dist/runs/recording.js +36 -12
- package/dist/runs/run.d.ts +12 -3
- package/dist/runs/run.js +32 -13
- package/dist/search/account-list.d.ts +6 -0
- package/dist/search/account-list.js +9 -3
- package/dist/search/groups.d.ts +68 -0
- package/dist/search/groups.js +172 -0
- package/dist/services/account-groups.d.ts +28 -0
- package/dist/services/account-groups.js +89 -0
- package/dist/services/archive.d.ts +7 -1
- package/dist/services/archive.js +19 -3
- package/dist/services/business-context.d.ts +113 -0
- package/dist/services/business-context.js +156 -0
- package/dist/services/communications.d.ts +50 -0
- package/dist/services/communications.js +140 -0
- package/dist/services/deal-context.d.ts +90 -0
- package/dist/services/deal-context.js +131 -0
- package/dist/services/deps.d.ts +2 -0
- package/dist/services/enrichment.d.ts +7 -2
- package/dist/services/enrichment.js +46 -5
- package/dist/services/events-search.js +2 -1
- package/dist/services/group-guard.d.ts +28 -0
- package/dist/services/group-guard.js +131 -0
- package/dist/services/index.d.ts +15 -2
- package/dist/services/index.js +9 -2
- package/dist/services/ingest.d.ts +12 -0
- package/dist/services/ingest.js +4 -0
- package/dist/services/meaning-model.d.ts +7 -0
- package/dist/services/meaning-model.js +20 -0
- package/dist/services/meeting-context.d.ts +6 -1
- package/dist/services/meeting-context.js +12 -5
- package/dist/services/message-resolution.js +2 -3
- package/dist/services/messages-meaning.js +4 -5
- package/dist/services/messages-search.d.ts +5 -1
- package/dist/services/messages-search.js +1 -1
- package/dist/services/model-downloads.d.ts +1 -1
- package/dist/services/model-downloads.js +6 -4
- package/dist/services/money-context.d.ts +73 -0
- package/dist/services/money-context.js +77 -0
- package/dist/services/notes-search.d.ts +4 -1
- package/dist/services/notes-search.js +19 -7
- package/dist/services/organization-context.d.ts +80 -0
- package/dist/services/organization-context.js +154 -0
- package/dist/services/people.d.ts +22 -6
- package/dist/services/people.js +38 -8
- package/dist/services/person-business.d.ts +43 -0
- package/dist/services/person-business.js +67 -0
- package/dist/services/person-context.d.ts +9 -1
- package/dist/services/person-context.js +5 -3
- package/dist/services/proposals/kinds/identity-link.d.ts +4 -0
- package/dist/services/proposals/kinds/identity-link.js +48 -0
- package/dist/services/proposals/kinds/orders.js +1 -1
- package/dist/services/proposals/registry.js +2 -0
- package/dist/services/search-kind.d.ts +12 -5
- package/dist/services/search-kind.js +49 -10
- package/dist/services/text-model-choice.js +1 -1
- package/dist/store/accounts.d.ts +18 -0
- package/dist/store/accounts.js +18 -3
- package/dist/store/damage.d.ts +43 -10
- package/dist/store/damage.js +119 -36
- package/dist/store/decisions.js +3 -1
- package/dist/store/evidence-findings.d.ts +14 -0
- package/dist/store/evidence-findings.js +2 -0
- package/dist/store/exports.d.ts +2 -1
- package/dist/store/identity-links.d.ts +92 -0
- package/dist/store/identity-links.js +6 -0
- package/dist/store/index.d.ts +11 -5
- package/dist/store/index.js +5 -2
- package/dist/store/journal.d.ts +10 -0
- package/dist/store/journal.js +33 -0
- package/dist/store/marks.d.ts +19 -1
- package/dist/store/marks.js +23 -1
- package/dist/store/people.d.ts +22 -0
- package/dist/store/people.js +15 -1
- package/dist/store/sqlite/accounts.js +2 -0
- package/dist/store/sqlite/base-stages.d.ts +122 -0
- package/dist/store/sqlite/base-stages.js +443 -0
- package/dist/store/sqlite/base-suggest.d.ts +13 -0
- package/dist/store/sqlite/base-suggest.js +62 -0
- package/dist/store/sqlite/business-contracts.js +10 -1
- package/dist/store/sqlite/crm-settings.d.ts +12 -2
- package/dist/store/sqlite/crm-settings.js +56 -13
- package/dist/store/sqlite/crm.d.ts +13 -1
- package/dist/store/sqlite/crm.js +20 -4
- package/dist/store/sqlite/deals.d.ts +33 -0
- package/dist/store/sqlite/deals.js +42 -4
- package/dist/store/sqlite/decision-requests.js +7 -3
- package/dist/store/sqlite/email-index.js +8 -4
- package/dist/store/sqlite/evidence-findings.js +29 -5
- package/dist/store/sqlite/findings-core.js +4 -2
- package/dist/store/sqlite/identity-link-rows.d.ts +50 -0
- package/dist/store/sqlite/identity-link-rows.js +146 -0
- package/dist/store/sqlite/identity-proposals.d.ts +53 -0
- package/dist/store/sqlite/identity-proposals.js +234 -0
- package/dist/store/sqlite/knowledge.js +2 -2
- package/dist/store/sqlite/link-kinds.d.ts +1 -0
- package/dist/store/sqlite/link-kinds.js +1 -0
- package/dist/store/sqlite/link-row.d.ts +6 -0
- package/dist/store/sqlite/link-row.js +35 -0
- package/dist/store/sqlite/link-source.d.ts +10 -0
- package/dist/store/sqlite/link-source.js +16 -0
- package/dist/store/sqlite/manifest.js +1 -0
- package/dist/store/sqlite/meeting-context-links.js +9 -6
- package/dist/store/sqlite/memories.js +9 -7
- package/dist/store/sqlite/mentions.d.ts +4 -1
- package/dist/store/sqlite/mentions.js +14 -9
- package/dist/store/sqlite/migrations.generated.js +8 -0
- package/dist/store/sqlite/notes.d.ts +1 -2
- package/dist/store/sqlite/notes.js +4 -29
- package/dist/store/sqlite/open-store.js +3 -0
- package/dist/store/sqlite/open.js +11 -2
- package/dist/store/sqlite/orders.d.ts +2 -0
- package/dist/store/sqlite/orders.js +9 -3
- package/dist/store/sqlite/organization-categories.d.ts +18 -0
- package/dist/store/sqlite/organization-categories.js +34 -0
- package/dist/store/sqlite/organizations.d.ts +5 -1
- package/dist/store/sqlite/organizations.js +14 -4
- package/dist/store/sqlite/person-links.d.ts +19 -4
- package/dist/store/sqlite/person-links.js +49 -11
- package/dist/store/sqlite/person-match-scan.d.ts +13 -0
- package/dist/store/sqlite/person-match-scan.js +251 -0
- package/dist/store/sqlite/person-matcher.d.ts +16 -0
- package/dist/store/sqlite/person-matcher.js +32 -0
- package/dist/store/sqlite/proposed-actions.js +6 -0
- package/dist/store/sqlite/record-matching.d.ts +2 -8
- package/dist/store/sqlite/record-matching.js +8 -40
- package/dist/store/sqlite/record-projectors-phone.js +2 -1
- package/dist/store/sqlite/record-relationships.d.ts +52 -0
- package/dist/store/sqlite/record-relationships.js +243 -0
- package/dist/store/sqlite/record-run.d.ts +5 -0
- package/dist/store/sqlite/record-run.js +62 -2
- package/dist/store/sqlite/record-writes.d.ts +1 -1
- package/dist/store/sqlite/record-writes.js +4 -2
- package/dist/store/sqlite/records.js +27 -2
- package/dist/store/sqlite/ref-accounts.d.ts +13 -0
- package/dist/store/sqlite/ref-accounts.js +117 -0
- package/dist/store/sqlite/ref-summaries.js +5 -1
- package/dist/store/sqlite/relation-list.d.ts +4 -1
- package/dist/store/sqlite/relation-list.js +18 -2
- package/dist/store/sqlite/relation-proposals.d.ts +6 -0
- package/dist/store/sqlite/relation-proposals.js +3 -0
- package/dist/store/sqlite/relation-roles.js +12 -6
- package/dist/store/sqlite/reported-relations.d.ts +11 -1
- package/dist/store/sqlite/reported-relations.js +59 -18
- package/dist/store/sqlite/schema.d.ts +32 -0
- package/dist/store/sqlite/schema.js +3 -0
- package/dist/store/sqlite/transaction.js +11 -1
- package/dist/store/store.d.ts +3 -0
- package/dist/store/store.js +5 -0
- package/dist/store/write-events.d.ts +18 -0
- package/dist/store/write-events.js +88 -0
- package/package.json +3 -3
- package/parity.json +11 -4
- package/schemas/records-envelope.v1.schema.json +3 -0
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { DECIDED_TABLES, isRecordType, RECORD_TYPES, roleOf, rolesOf, } from "../../domain/record-types.js";
|
|
2
|
+
import { pointerOf } from "../../domain/records.js";
|
|
3
|
+
import { isSymmetric, rolesOf as relationRolesOf, roleListOf } from "../../domain/relations.js";
|
|
4
|
+
import { IMPORTER } from "./record-projection.js";
|
|
5
|
+
import { extraRolesOf } from "./relation-roles.js";
|
|
6
|
+
import { syncReportedIn } from "./reported-relations.js";
|
|
7
|
+
import { referenceOfThing, storedThing } from "./things.js";
|
|
8
|
+
/** An import's links are its own writer's: another writer on the same account, a CRM's `crm`, never withdraws them. */
|
|
9
|
+
export const importSource = (provider) => `import:${provider}`;
|
|
10
|
+
export const noRelationships = () => ({
|
|
11
|
+
added: 0,
|
|
12
|
+
kept: 0,
|
|
13
|
+
restored: 0,
|
|
14
|
+
withdrawn: 0,
|
|
15
|
+
proposed: 0,
|
|
16
|
+
skippedOwnerRejected: 0,
|
|
17
|
+
});
|
|
18
|
+
/** One note as a receipt entry, for a run and for the owner's `map` and `match` alike. */
|
|
19
|
+
export const noteError = (note, place) => {
|
|
20
|
+
if (place?.index !== undefined)
|
|
21
|
+
return {
|
|
22
|
+
pointer: pointerOf("records", place.index, "relations"),
|
|
23
|
+
code: note.code,
|
|
24
|
+
message: note.message,
|
|
25
|
+
...(place.key === undefined ? {} : { key: place.key }),
|
|
26
|
+
};
|
|
27
|
+
return {
|
|
28
|
+
pointer: "",
|
|
29
|
+
code: note.code,
|
|
30
|
+
message: place ? `${place.type} ${place.externalId}: ${note.message}` : note.message,
|
|
31
|
+
...(place ? { record: { type: place.type, externalId: place.externalId } } : {}),
|
|
32
|
+
};
|
|
33
|
+
};
|
|
34
|
+
const kindsOf = (type) => [
|
|
35
|
+
...new Set(rolesOf(type).flatMap(([, role]) => (role.relationship ? [role.relationship] : []))),
|
|
36
|
+
];
|
|
37
|
+
const symmetricRolesOf = (type) => rolesOf(type).flatMap(([name, role]) => (role.relationship && isSymmetric(role.relationship) ? [name] : []));
|
|
38
|
+
const relationshipOf = (type, role) => roleOf(String(type), String(role))?.relationship;
|
|
39
|
+
const POSITION_MAX = 200;
|
|
40
|
+
/** A person's job title as the source gives it, never read as the role. */
|
|
41
|
+
const positionOf = (fields) => {
|
|
42
|
+
const value = JSON.parse(String(fields)).position;
|
|
43
|
+
const text = typeof value === "string" ? value.trim() : "";
|
|
44
|
+
return text && text.length <= POSITION_MAX ? text : undefined;
|
|
45
|
+
};
|
|
46
|
+
const sourceRolesOf = (relation) => relation.metadata?.source_role ?? [];
|
|
47
|
+
/** Two records saying the same relationship: every word either used is kept, the first one's position wins. */
|
|
48
|
+
const merged = (held, more) => {
|
|
49
|
+
const words = [...new Set([...sourceRolesOf(held), ...sourceRolesOf(more)])];
|
|
50
|
+
if (words.length === sourceRolesOf(held).length)
|
|
51
|
+
return held;
|
|
52
|
+
return { ...held, metadata: { ...held.metadata, source_role: words } };
|
|
53
|
+
};
|
|
54
|
+
/**
|
|
55
|
+
* The relationships an import's records report, through `relations.syncReported` under the import's account. An
|
|
56
|
+
* entity's set is what every live record of the account mapped to it says, so a second record of the same person, or
|
|
57
|
+
* a delete, never withdraws what another record still reports. An entity the owner rejected, or that is deleted,
|
|
58
|
+
* reports none.
|
|
59
|
+
*/
|
|
60
|
+
export const recordRelationshipsOver = (context) => {
|
|
61
|
+
const { database } = context;
|
|
62
|
+
const statements = new Map();
|
|
63
|
+
const sql = (text) => {
|
|
64
|
+
let statement = statements.get(text);
|
|
65
|
+
if (!statement) {
|
|
66
|
+
statement = database.prepare(text);
|
|
67
|
+
statements.set(text, statement);
|
|
68
|
+
}
|
|
69
|
+
return statement;
|
|
70
|
+
};
|
|
71
|
+
const refOf = (thing) => referenceOfThing(database, thing) ?? `${thing.type}:${thing.id}`;
|
|
72
|
+
const reportable = (type, id) => id != null && isRecordType(String(type)) && kindsOf(String(type)).length > 0
|
|
73
|
+
? storedThing(type, id)
|
|
74
|
+
: undefined;
|
|
75
|
+
/** The owner rejected the entity, or it is gone: whatever its records say, it reports nothing. */
|
|
76
|
+
const silent = (entity) => {
|
|
77
|
+
const spec = RECORD_TYPES[entity.type];
|
|
78
|
+
const reviewed = Object.hasOwn(DECIDED_TABLES, entity.type);
|
|
79
|
+
if (!reviewed && !spec.tombstone)
|
|
80
|
+
return false;
|
|
81
|
+
const row = sql(`SELECT ${reviewed ? "review" : "NULL"} AS review, ${spec.tombstone ? "deleted_at" : "NULL"} AS deleted_at ` +
|
|
82
|
+
`FROM ${spec.table} WHERE id = ?`).get(entity.id);
|
|
83
|
+
return !row || row.review === "rejected" || row.deleted_at != null;
|
|
84
|
+
};
|
|
85
|
+
const entitiesOf = (records) => sql("SELECT entity_type, entity_id FROM records WHERE id IN (SELECT value FROM json_each(?))")
|
|
86
|
+
.all(JSON.stringify(records))
|
|
87
|
+
.flatMap((row) => reportable(row.entity_type, row.entity_id) ?? []);
|
|
88
|
+
const dependentsOf = (changed) => sql("SELECT DISTINCT r.type, r.entity_type, r.entity_id, rr.role FROM record_relations rr " +
|
|
89
|
+
"JOIN records r ON r.id = rr.record_id WHERE rr.target_id IN (SELECT value FROM json_each(?)) " +
|
|
90
|
+
"AND r.entity_id IS NOT NULL AND r.deleted_at IS NULL")
|
|
91
|
+
.all(JSON.stringify(changed))
|
|
92
|
+
.flatMap((row) => (relationshipOf(row.type, row.role) ? (reportable(row.entity_type, row.entity_id) ?? []) : []));
|
|
93
|
+
/**
|
|
94
|
+
* A role only from its list, the owner's own roles included. Any other word, and any word on a relationship with no
|
|
95
|
+
* list, is kept as `metadata.source_role` on a link without a role; a word a list does not hold is also a notice.
|
|
96
|
+
*/
|
|
97
|
+
const shapeOf = (kind, from, toType, as, note) => {
|
|
98
|
+
const word = as == null ? null : String(as);
|
|
99
|
+
if (word === null)
|
|
100
|
+
return { role: null, metadata: {} };
|
|
101
|
+
const list = relationRolesOf(kind, from.type, toType);
|
|
102
|
+
if (list?.concat(extraRolesOf(database, kind, from.type, toType)).includes(word))
|
|
103
|
+
return { role: word, metadata: {} };
|
|
104
|
+
if (list)
|
|
105
|
+
note(word);
|
|
106
|
+
return { role: null, metadata: { source_role: [word] } };
|
|
107
|
+
};
|
|
108
|
+
const targetOf = (row) => {
|
|
109
|
+
if (row.target_type === "ref") {
|
|
110
|
+
const ref = String(row.target_external_id);
|
|
111
|
+
return { ref, type: ref.slice(0, ref.indexOf(":")) };
|
|
112
|
+
}
|
|
113
|
+
if (row.target_entity_id == null)
|
|
114
|
+
return undefined;
|
|
115
|
+
return {
|
|
116
|
+
ref: refOf(storedThing(row.target_entity_type, row.target_entity_id)),
|
|
117
|
+
type: String(row.target_entity_type),
|
|
118
|
+
};
|
|
119
|
+
};
|
|
120
|
+
/** Every relationship the account's live records report from `entity`, and a symmetric one reported to it. */
|
|
121
|
+
const reportedFrom = (accountId, entity, add, onNote) => {
|
|
122
|
+
if (silent(entity))
|
|
123
|
+
return;
|
|
124
|
+
const ref = refOf(entity);
|
|
125
|
+
const unlisted = (kind, from, toType, to, record) => (word) => onNote({
|
|
126
|
+
severity: "notice",
|
|
127
|
+
code: "relationship.role-unlisted",
|
|
128
|
+
message: `${word} is not one of the ${roleListOf(kind, from.type, toType)} roles: the ${kind} link has no role ` +
|
|
129
|
+
"and keeps the word as source_role",
|
|
130
|
+
record,
|
|
131
|
+
key: ["notice", record, kind, to, word].join("\0"),
|
|
132
|
+
});
|
|
133
|
+
// The most recently changed record first: its position is the one a person's link carries.
|
|
134
|
+
const outgoing = sql("SELECT r.id AS record_id, r.type, r.fields, rr.role, rr.as_role, rr.target_type, rr.target_external_id, " +
|
|
135
|
+
"t.entity_type AS target_entity_type, t.entity_id AS target_entity_id FROM records r " +
|
|
136
|
+
"JOIN record_relations rr ON rr.record_id = r.id LEFT JOIN records t ON t.id = rr.target_id " +
|
|
137
|
+
"AND t.deleted_at IS NULL WHERE r.account_id = ? AND r.entity_type = ? AND r.entity_id = ? " +
|
|
138
|
+
"AND r.deleted_at IS NULL ORDER BY r.updated_at DESC, r.id DESC, rr.id").all(accountId, entity.type, entity.id);
|
|
139
|
+
for (const row of outgoing) {
|
|
140
|
+
const kind = relationshipOf(row.type, row.role);
|
|
141
|
+
const target = kind && targetOf(row);
|
|
142
|
+
if (!kind || !target)
|
|
143
|
+
continue;
|
|
144
|
+
const record = Number(row.record_id);
|
|
145
|
+
const { role, metadata } = shapeOf(kind, entity, target.type, row.as_role, unlisted(kind, entity, target.type, target.ref, record));
|
|
146
|
+
const position = kind === "member-of" && entity.type === "person" ? positionOf(row.fields) : undefined;
|
|
147
|
+
if (position)
|
|
148
|
+
metadata.position = position;
|
|
149
|
+
add({ from: ref, to: target.ref, kind, role, ...(Object.keys(metadata).length ? { metadata } : {}) }, record);
|
|
150
|
+
}
|
|
151
|
+
const symmetric = symmetricRolesOf(entity.type);
|
|
152
|
+
if (symmetric.length === 0)
|
|
153
|
+
return;
|
|
154
|
+
// Two branches, not an OR, so each one reads an index of record_relations instead of every record of the account.
|
|
155
|
+
const incoming = sql("SELECT r.id AS record_id, r.type, r.entity_type, r.entity_id, rr.role, rr.as_role, rr.id AS relation_id " +
|
|
156
|
+
"FROM records t JOIN record_relations rr ON rr.target_id = t.id JOIN records r ON r.id = rr.record_id " +
|
|
157
|
+
"WHERE t.entity_type = ? AND t.entity_id = ? AND t.deleted_at IS NULL AND r.account_id = ? " +
|
|
158
|
+
"AND r.deleted_at IS NULL AND r.entity_id IS NOT NULL AND rr.role IN (SELECT value FROM json_each(?)) " +
|
|
159
|
+
"UNION ALL SELECT r.id, r.type, r.entity_type, r.entity_id, rr.role, rr.as_role, rr.id FROM record_relations rr " +
|
|
160
|
+
"JOIN records r ON r.id = rr.record_id WHERE rr.target_type = 'ref' AND rr.target_external_id = ? " +
|
|
161
|
+
"AND r.account_id = ? AND r.deleted_at IS NULL AND r.entity_id IS NOT NULL " +
|
|
162
|
+
"AND rr.role IN (SELECT value FROM json_each(?)) ORDER BY 1, 7").all(entity.type, entity.id, accountId, JSON.stringify(symmetric), ref, accountId, JSON.stringify(symmetric));
|
|
163
|
+
for (const row of incoming) {
|
|
164
|
+
const kind = relationshipOf(row.type, row.role);
|
|
165
|
+
if (!kind)
|
|
166
|
+
continue;
|
|
167
|
+
const other = storedThing(row.entity_type, row.entity_id);
|
|
168
|
+
if (silent(other))
|
|
169
|
+
continue;
|
|
170
|
+
const record = Number(row.record_id);
|
|
171
|
+
const { role, metadata } = shapeOf(kind, other, entity.type, row.as_role, unlisted(kind, other, entity.type, ref, record));
|
|
172
|
+
add({ from: refOf(other), to: ref, kind, role, ...(Object.keys(metadata).length ? { metadata } : {}) }, record);
|
|
173
|
+
}
|
|
174
|
+
};
|
|
175
|
+
/**
|
|
176
|
+
* Reports every relationship of the covered entities, one `syncReported` call per entity type so that a type's kinds
|
|
177
|
+
* never withdraw what another type's entity holds. Inside the caller's transaction: a dry run rolls it back.
|
|
178
|
+
*/
|
|
179
|
+
const report = (key, accountId, { records, changed = [], entities = [] }, { onNote = () => { }, onOutcome } = {}) => {
|
|
180
|
+
const counts = noRelationships();
|
|
181
|
+
const byType = new Map();
|
|
182
|
+
for (const thing of [...entitiesOf(records), ...dependentsOf(changed), ...entities]) {
|
|
183
|
+
if (!reportable(thing.type, thing.id))
|
|
184
|
+
continue;
|
|
185
|
+
const type = thing.type;
|
|
186
|
+
const things = byType.get(type) ?? new Map();
|
|
187
|
+
things.set(`${thing.type}:${thing.id}`, thing);
|
|
188
|
+
byType.set(type, things);
|
|
189
|
+
}
|
|
190
|
+
const options = { source: importSource(key.provider), by: IMPORTER, ...(onOutcome ? { onOutcome } : {}) };
|
|
191
|
+
for (const [type, things] of byType) {
|
|
192
|
+
const relationships = new Map();
|
|
193
|
+
const recordOf = new Map();
|
|
194
|
+
for (const entity of things.values())
|
|
195
|
+
reportedFrom(accountId, entity, (relation, record) => {
|
|
196
|
+
const ends = isSymmetric(relation.kind) ? [relation.from, relation.to].sort() : [relation.from, relation.to];
|
|
197
|
+
const same = [relation.kind, ...ends, relation.role ?? ""].join("\0");
|
|
198
|
+
const held = relationships.get(same);
|
|
199
|
+
relationships.set(same, held ? merged(held, relation) : relation);
|
|
200
|
+
const pair = [relation.kind, relation.from, relation.to].join("\0");
|
|
201
|
+
if (!recordOf.has(pair))
|
|
202
|
+
recordOf.set(pair, record);
|
|
203
|
+
}, onNote);
|
|
204
|
+
const { issues, ...tally } = syncReportedIn(context, key, [...relationships.values()], { from: [...things.values()].map(refOf), kinds: kindsOf(type) }, options);
|
|
205
|
+
for (const name of Object.keys(counts))
|
|
206
|
+
counts[name] += tally[name];
|
|
207
|
+
for (const issue of issues) {
|
|
208
|
+
const record = recordOf.get([issue.kind, issue.from, issue.to].join("\0")) ?? null;
|
|
209
|
+
onNote({
|
|
210
|
+
severity: "issue",
|
|
211
|
+
code: issue.reason,
|
|
212
|
+
message: issue.message,
|
|
213
|
+
record,
|
|
214
|
+
key: ["issue", record, issue.kind, issue.from, issue.to, issue.reason].join("\0"),
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
return counts;
|
|
219
|
+
};
|
|
220
|
+
/** Where a note's record is, for one that is not in a run. */
|
|
221
|
+
const placeOf = (record) => {
|
|
222
|
+
if (record === null)
|
|
223
|
+
return undefined;
|
|
224
|
+
const row = sql("SELECT type, external_id FROM records WHERE id = ?").get(record);
|
|
225
|
+
return row ? { type: String(row.type), externalId: String(row.external_id) } : undefined;
|
|
226
|
+
};
|
|
227
|
+
/**
|
|
228
|
+
* The owner rejected `entity`: every account whose records stand for it withdraws what it reported from it, at once,
|
|
229
|
+
* in the rejection's transaction.
|
|
230
|
+
*/
|
|
231
|
+
const withdrawFrom = (entity) => {
|
|
232
|
+
if (!reportable(entity.type, entity.id))
|
|
233
|
+
return;
|
|
234
|
+
const accounts = sql("SELECT DISTINCT a.id, a.provider, a.external_id FROM records r JOIN accounts a ON a.id = r.account_id " +
|
|
235
|
+
"WHERE r.entity_type = ? AND r.entity_id = ?").all(entity.type, entity.id);
|
|
236
|
+
for (const account of accounts)
|
|
237
|
+
report({ provider: String(account.provider), account: String(account.external_id) }, Number(account.id), {
|
|
238
|
+
records: [],
|
|
239
|
+
entities: [entity],
|
|
240
|
+
});
|
|
241
|
+
};
|
|
242
|
+
return { report, placeOf, withdrawFrom };
|
|
243
|
+
};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { EnvelopeOptions, EnvelopeRecord, EnvelopeSource, IngestError } from "../../domain/records.js";
|
|
2
2
|
import type { StoreContext } from "./open.js";
|
|
3
|
+
import { type RelationshipCounts } from "./record-relationships.js";
|
|
3
4
|
import type { Flag, recordWritesOver } from "./record-writes.js";
|
|
4
5
|
/** One line of a run: its place in the envelope or stream, the record, and why it was refused before the store. */
|
|
5
6
|
export interface RunItem {
|
|
@@ -59,6 +60,10 @@ export interface RecordsRun {
|
|
|
59
60
|
at: (string | number)[];
|
|
60
61
|
reason: string;
|
|
61
62
|
}[];
|
|
63
|
+
/** What the records' relationships did to the links this account reports, each link counted once per run. */
|
|
64
|
+
relationships: RelationshipCounts;
|
|
65
|
+
/** Taken, but not as the source put it: a relationship's word off its role list, kept as `source_role`. */
|
|
66
|
+
notices: IngestError[];
|
|
62
67
|
/** A list stopped at `limit`. */
|
|
63
68
|
truncated: boolean;
|
|
64
69
|
}
|
|
@@ -3,6 +3,7 @@ import { pointerOf } from "../../domain/records.js";
|
|
|
3
3
|
import { accountPk } from "./accounts.js";
|
|
4
4
|
import { codeOf } from "./record-projection.js";
|
|
5
5
|
import { isDerived } from "./record-relations.js";
|
|
6
|
+
import { noRelationships, noteError, recordRelationshipsOver, } from "./record-relationships.js";
|
|
6
7
|
import { outsideRehearsal, read, write } from "./transaction.js";
|
|
7
8
|
let runs = 0;
|
|
8
9
|
const PAGE = 500;
|
|
@@ -13,17 +14,30 @@ const PAGE = 500;
|
|
|
13
14
|
export const recordRunOver = (context, writes) => {
|
|
14
15
|
const { database } = context;
|
|
15
16
|
const { writeOne, completeDependents, entityRef, missingOf } = writes;
|
|
17
|
+
const reported = recordRelationshipsOver(context);
|
|
16
18
|
return async (source, items, { chunk = 1000, options = {}, limit = 1000, onIssue }) => {
|
|
17
19
|
runs += 1;
|
|
18
20
|
const table = `records_run_${runs}`;
|
|
19
21
|
const proposedTable = `records_run_${runs}_proposed`;
|
|
22
|
+
const linksTable = `records_run_${runs}_links`;
|
|
23
|
+
const notesTable = `records_run_${runs}_notes`;
|
|
20
24
|
database.exec(`CREATE TEMP TABLE ${table} (idx INTEGER NOT NULL, key TEXT NOT NULL UNIQUE, identity TEXT NOT NULL UNIQUE, ` +
|
|
21
25
|
"record_id INTEGER, flagged TEXT, unmatched TEXT, ignored TEXT)");
|
|
26
|
+
database.exec(`CREATE INDEX temp.${table}_by_record ON ${table} (record_id)`);
|
|
22
27
|
database.exec(`CREATE TEMP TABLE ${proposedTable} (ref TEXT PRIMARY KEY)`);
|
|
28
|
+
// A link and a note are counted once per run however many chunks report them: an entity's set is whole each time.
|
|
29
|
+
database.exec(`CREATE TEMP TABLE ${linksTable} (key TEXT PRIMARY KEY, outcome TEXT NOT NULL)`);
|
|
30
|
+
database.exec(`CREATE TEMP TABLE ${notesTable} (key TEXT PRIMARY KEY)`);
|
|
23
31
|
try {
|
|
24
32
|
let truncated = false;
|
|
25
33
|
const errors = [];
|
|
34
|
+
const notices = [];
|
|
26
35
|
const counts = { created: 0, updated: 0, unchanged: 0, deleted: 0, refused: 0 };
|
|
36
|
+
const outcome = database.prepare(`INSERT INTO temp.${linksTable} (key, outcome) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET outcome = ` +
|
|
37
|
+
"CASE WHEN excluded.outcome = 'kept' AND outcome <> 'withdrawn' THEN outcome ELSE excluded.outcome END");
|
|
38
|
+
const noted = database.prepare(`INSERT OR IGNORE INTO temp.${notesTable} (key) VALUES (?)`);
|
|
39
|
+
const placeOf = database.prepare(`SELECT run.idx, run.key, r.type, r.external_id FROM records r LEFT JOIN temp.${table} run ` +
|
|
40
|
+
"ON run.record_id = r.id WHERE r.id = ?");
|
|
27
41
|
const issue = (error) => {
|
|
28
42
|
if (errors.length < limit)
|
|
29
43
|
errors.push(error);
|
|
@@ -36,12 +50,35 @@ export const recordRunOver = (context, writes) => {
|
|
|
36
50
|
counts.refused += 1;
|
|
37
51
|
issue(error);
|
|
38
52
|
};
|
|
53
|
+
const note = (one) => {
|
|
54
|
+
if (noted.run(one.key).changes === 0)
|
|
55
|
+
return;
|
|
56
|
+
const list = one.severity === "issue" ? errors : notices;
|
|
57
|
+
if (list.length >= limit && (one.severity === "notice" || !onIssue)) {
|
|
58
|
+
truncated = true;
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
const row = one.record === null ? undefined : placeOf.get(one.record);
|
|
62
|
+
const place = row && {
|
|
63
|
+
...(row.idx == null ? {} : { index: Number(row.idx), key: String(row.key) }),
|
|
64
|
+
type: String(row.type),
|
|
65
|
+
externalId: String(row.external_id),
|
|
66
|
+
};
|
|
67
|
+
if (one.severity === "issue")
|
|
68
|
+
issue(noteError(one, place));
|
|
69
|
+
// Only this envelope's records: an earlier batch's words were noticed when it came.
|
|
70
|
+
else if (place?.index !== undefined)
|
|
71
|
+
notices.push(noteError(one, place));
|
|
72
|
+
};
|
|
39
73
|
const proposed = (ref) => {
|
|
40
74
|
database.prepare(`INSERT OR IGNORE INTO temp.${proposedTable} (ref) VALUES (?)`).run(ref);
|
|
41
75
|
};
|
|
42
76
|
const takeChunk = (batch) => write(database, () => {
|
|
43
|
-
const
|
|
77
|
+
const key = { provider: source.provider, account: source.account };
|
|
78
|
+
const accountId = accountPk(context, key);
|
|
44
79
|
const complete = [];
|
|
80
|
+
const written = [];
|
|
81
|
+
const changed = [];
|
|
45
82
|
for (const { index, record, errors: before } of batch) {
|
|
46
83
|
if (before?.length) {
|
|
47
84
|
counts.refused += 1;
|
|
@@ -74,6 +111,9 @@ export const recordRunOver = (context, writes) => {
|
|
|
74
111
|
try {
|
|
75
112
|
const done = write(database, () => writeOne(accountId, source, record, options, proposed));
|
|
76
113
|
counts[done.status] += 1;
|
|
114
|
+
written.push(done.id);
|
|
115
|
+
if (done.complete || done.status === "deleted")
|
|
116
|
+
changed.push(done.id);
|
|
77
117
|
database
|
|
78
118
|
.prepare(`UPDATE temp.${table} SET record_id = ?, flagged = ?, unmatched = ?, ignored = ? WHERE key = ?`)
|
|
79
119
|
.run(done.id, done.flagged === undefined ? null : JSON.stringify(done.flagged), done.unmatched === undefined ? null : JSON.stringify(done.unmatched), done.ignored?.length ? JSON.stringify(done.ignored) : null, record.key);
|
|
@@ -92,8 +132,16 @@ export const recordRunOver = (context, writes) => {
|
|
|
92
132
|
});
|
|
93
133
|
}
|
|
94
134
|
}
|
|
135
|
+
const made = (id) => {
|
|
136
|
+
written.push(id);
|
|
137
|
+
changed.push(id);
|
|
138
|
+
};
|
|
95
139
|
for (const id of complete)
|
|
96
|
-
completeDependents(id, source, proposed, issue);
|
|
140
|
+
completeDependents(id, source, proposed, issue, made);
|
|
141
|
+
reported.report(key, accountId, { records: written, changed }, {
|
|
142
|
+
onNote: note,
|
|
143
|
+
onOutcome: (one) => outcome.run(one.key, one.outcome === "skipped" ? "skippedOwnerRejected" : one.outcome),
|
|
144
|
+
});
|
|
97
145
|
});
|
|
98
146
|
let batch = [];
|
|
99
147
|
for await (const item of items) {
|
|
@@ -151,6 +199,14 @@ export const recordRunOver = (context, writes) => {
|
|
|
151
199
|
ignored.push({ index: Number(row.idx), key: String(row.key), ...one });
|
|
152
200
|
else
|
|
153
201
|
truncated = true;
|
|
202
|
+
const relationshipsOf = () => {
|
|
203
|
+
const tally = noRelationships();
|
|
204
|
+
for (const row of database
|
|
205
|
+
.prepare(`SELECT outcome, count(*) AS n FROM temp.${linksTable} GROUP BY outcome`)
|
|
206
|
+
.all())
|
|
207
|
+
tally[String(row.outcome)] = Number(row.n);
|
|
208
|
+
return tally;
|
|
209
|
+
};
|
|
154
210
|
const proposedRefs = listed(`SELECT ref, rowid AS position FROM temp.${proposedTable}`, "", (row) => String(row.ref), "rowid");
|
|
155
211
|
return {
|
|
156
212
|
...counts,
|
|
@@ -160,6 +216,8 @@ export const recordRunOver = (context, writes) => {
|
|
|
160
216
|
unmatched,
|
|
161
217
|
flagged,
|
|
162
218
|
ignored,
|
|
219
|
+
relationships: relationshipsOf(),
|
|
220
|
+
notices: notices.sort((a, b) => a.pointer.localeCompare(b.pointer, "en", { numeric: true })),
|
|
163
221
|
truncated,
|
|
164
222
|
};
|
|
165
223
|
});
|
|
@@ -167,6 +225,8 @@ export const recordRunOver = (context, writes) => {
|
|
|
167
225
|
finally {
|
|
168
226
|
database.exec(`DROP TABLE IF EXISTS temp.${table}`);
|
|
169
227
|
database.exec(`DROP TABLE IF EXISTS temp.${proposedTable}`);
|
|
228
|
+
database.exec(`DROP TABLE IF EXISTS temp.${linksTable}`);
|
|
229
|
+
database.exec(`DROP TABLE IF EXISTS temp.${notesTable}`);
|
|
170
230
|
}
|
|
171
231
|
};
|
|
172
232
|
};
|
|
@@ -36,7 +36,7 @@ interface Projected {
|
|
|
36
36
|
export declare const recordWritesOver: (context: StoreContext) => {
|
|
37
37
|
writeOne: (accountId: number, source: EnvelopeSource, record: EnvelopeRecord, options: EnvelopeOptions, proposed: (ref: string) => void) => WriteOutcome;
|
|
38
38
|
project: (row: Row, source: EnvelopeSource, options?: EnvelopeOptions) => Projected;
|
|
39
|
-
completeDependents: (target: number, source: EnvelopeSource, proposed: (ref: string) => void, laterError: (error: IngestError) => void) => void;
|
|
39
|
+
completeDependents: (target: number, source: EnvelopeSource, proposed: (ref: string) => void, laterError: (error: IngestError) => void, made?: (id: number) => void) => void;
|
|
40
40
|
entityRef: (type: unknown, id: unknown) => string | null;
|
|
41
41
|
missingOf: (id: number) => string[] | null;
|
|
42
42
|
};
|
|
@@ -117,7 +117,7 @@ export const recordWritesOver = (context) => {
|
|
|
117
117
|
return { made: ref, missing: [], ...(isProposed(type, entity.id) ? { proposed: ref } : {}) };
|
|
118
118
|
};
|
|
119
119
|
/** Records that waited on `target` and may now have their entity, and theirs in turn. */
|
|
120
|
-
const completeDependents = (target, source, proposed, laterError) => {
|
|
120
|
+
const completeDependents = (target, source, proposed, laterError, made) => {
|
|
121
121
|
const queue = [target];
|
|
122
122
|
while (queue.length > 0) {
|
|
123
123
|
const rows = sql("SELECT DISTINCT r.* FROM record_relations rr JOIN records r ON r.id = rr.record_id WHERE rr.target_id = ? " +
|
|
@@ -127,8 +127,10 @@ export const recordWritesOver = (context) => {
|
|
|
127
127
|
const done = write(database, () => project(row, source));
|
|
128
128
|
if (done.proposed)
|
|
129
129
|
proposed(done.proposed);
|
|
130
|
-
if (done.made)
|
|
130
|
+
if (done.made) {
|
|
131
131
|
queue.push(Number(row.id));
|
|
132
|
+
made?.(Number(row.id));
|
|
133
|
+
}
|
|
132
134
|
}
|
|
133
135
|
catch (error) {
|
|
134
136
|
if (!(error instanceof CliError))
|
|
@@ -4,9 +4,11 @@ import { findAccountPk } from "./accounts.js";
|
|
|
4
4
|
import { requiredThing } from "./notes.js";
|
|
5
5
|
import { codeOf, refusal } from "./record-projection.js";
|
|
6
6
|
import { isDerived } from "./record-relations.js";
|
|
7
|
+
import { noteError, recordRelationshipsOver } from "./record-relationships.js";
|
|
7
8
|
import { recordRemapOver } from "./record-remap.js";
|
|
8
9
|
import { recordRunOver } from "./record-run.js";
|
|
9
10
|
import { recordWritesOver } from "./record-writes.js";
|
|
11
|
+
import { storedThing } from "./things.js";
|
|
10
12
|
import { read, rehearse, write } from "./transaction.js";
|
|
11
13
|
export { waitingPointer } from "./record-run.js";
|
|
12
14
|
const LIMIT = 1000;
|
|
@@ -23,6 +25,19 @@ export const recordStoreOver = (context) => {
|
|
|
23
25
|
const { entityRef, project, completeDependents } = writes;
|
|
24
26
|
const run = recordRunOver(context, writes);
|
|
25
27
|
const { pointedAt, remap } = recordRemapOver(context);
|
|
28
|
+
const reported = recordRelationshipsOver(context);
|
|
29
|
+
/** A report's issues outside a run, each once: there is no envelope to point into, so each names its record. */
|
|
30
|
+
const issuesTo = (push) => {
|
|
31
|
+
const seen = new Set();
|
|
32
|
+
return {
|
|
33
|
+
onNote: (note) => {
|
|
34
|
+
if (note.severity !== "issue" || seen.has(note.key))
|
|
35
|
+
return;
|
|
36
|
+
seen.add(note.key);
|
|
37
|
+
push(noteError(note, reported.placeOf(note.record)));
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
};
|
|
26
41
|
const sourceRecordOf = (row) => ({
|
|
27
42
|
provider: String(row.provider),
|
|
28
43
|
account: String(row.account),
|
|
@@ -168,6 +183,11 @@ export const recordStoreOver = (context) => {
|
|
|
168
183
|
refusal(`a ${key.type} record maps to a ${key.type}:, not ${entity}`, "record.map-type");
|
|
169
184
|
const same = row.entity_type === thing.type && Number(row.entity_id) === thing.id;
|
|
170
185
|
const from = row.entity_id != null && !same ? { type: String(row.entity_type), id: Number(row.entity_id) } : null;
|
|
186
|
+
const moved = from === null
|
|
187
|
+
? [Number(row.id)]
|
|
188
|
+
: sql("SELECT id FROM records WHERE account_id = ? AND entity_type = ? AND entity_id = ?")
|
|
189
|
+
.all(Number(row.account_id), from.type, from.id)
|
|
190
|
+
.map((one) => Number(one.id));
|
|
171
191
|
if (from !== null) {
|
|
172
192
|
if (Number(row.created_entity) !== 1)
|
|
173
193
|
refusal(`${key.type} ${key.externalId} is already ${entityRef(row.entity_type, row.entity_id)}`, "record.mapped");
|
|
@@ -179,7 +199,9 @@ export const recordStoreOver = (context) => {
|
|
|
179
199
|
sql("UPDATE records SET entity_type = ?, entity_id = ?, created_entity = 0, " +
|
|
180
200
|
"projected_fingerprint = fingerprint WHERE id = ?").run(thing.type, thing.id, Number(row.id));
|
|
181
201
|
const source = { provider: key.provider, account: key.account, batch_id: String(row.batch_id) };
|
|
182
|
-
completeDependents(Number(row.id), source, (ref) => proposed.add(ref), (error) => errors.push(error));
|
|
202
|
+
completeDependents(Number(row.id), source, (ref) => proposed.add(ref), (error) => errors.push(error), (id) => moved.push(id));
|
|
203
|
+
const account = { provider: key.provider, account: key.account };
|
|
204
|
+
reported.report(account, Number(row.account_id), { records: moved, changed: moved, entities: from === null ? [] : [storedThing(from.type, from.id)] }, issuesTo((error) => errors.push(error)));
|
|
183
205
|
});
|
|
184
206
|
return read(database, () => ({
|
|
185
207
|
...sourceRecordOf(rowOf(key)),
|
|
@@ -205,6 +227,7 @@ export const recordStoreOver = (context) => {
|
|
|
205
227
|
.prepare("SELECT * FROM records WHERE account_id = ? AND entity_id IS NULL AND deleted_at IS NULL " +
|
|
206
228
|
`AND type IN (${IDENTITY_SQL}) ORDER BY id`)
|
|
207
229
|
.all(accountId);
|
|
230
|
+
const made = [];
|
|
208
231
|
for (const row of rows) {
|
|
209
232
|
const source = { provider, account, batch_id: String(row.batch_id) };
|
|
210
233
|
const recordKey = { provider, account, type: String(row.type), externalId: String(row.external_id) };
|
|
@@ -216,12 +239,13 @@ export const recordStoreOver = (context) => {
|
|
|
216
239
|
continue;
|
|
217
240
|
const created = sql("SELECT created_entity FROM records WHERE id = ?").get(Number(row.id))?.created_entity;
|
|
218
241
|
counts[Number(created) === 1 ? "created" : "linked"] += 1;
|
|
242
|
+
made.push(Number(row.id));
|
|
219
243
|
completeDependents(Number(row.id), source, (ref) => {
|
|
220
244
|
if (proposed.size < LIMIT)
|
|
221
245
|
proposed.add(ref);
|
|
222
246
|
else if (!proposed.has(ref))
|
|
223
247
|
flag();
|
|
224
|
-
}, errors.push);
|
|
248
|
+
}, errors.push, (id) => made.push(id));
|
|
225
249
|
}
|
|
226
250
|
catch (error) {
|
|
227
251
|
if (!(error instanceof CliError))
|
|
@@ -233,6 +257,7 @@ export const recordStoreOver = (context) => {
|
|
|
233
257
|
});
|
|
234
258
|
}
|
|
235
259
|
}
|
|
260
|
+
reported.report({ provider, account }, accountId, { records: made, changed: made }, issuesTo(errors.push));
|
|
236
261
|
});
|
|
237
262
|
return { ...counts, unmatched: unmatched.list, proposed: [...proposed], errors: errors.list, truncated };
|
|
238
263
|
},
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { CacheDatabase } from "../driver.js";
|
|
2
|
+
import type { AccountKey } from "../types.js";
|
|
3
|
+
/**
|
|
4
|
+
* The accounts a referenced thing belongs to. `[]` is a thing no account brought, such as one the owner made;
|
|
5
|
+
* `undefined` is a reference the store holds nothing for, which the command itself then reports.
|
|
6
|
+
*/
|
|
7
|
+
export type RefAccounts = AccountKey[] | undefined;
|
|
8
|
+
/**
|
|
9
|
+
* Each part a referenced thing belongs to, every one of which a group must hold: one part for most things; a proposed
|
|
10
|
+
* action's own account and its target; a link's two ends. `undefined` when the store holds nothing for it.
|
|
11
|
+
*/
|
|
12
|
+
export declare const refEndsOf: (database: CacheDatabase, text: string) => AccountKey[][] | undefined;
|
|
13
|
+
export declare const refAccountsOf: (database: CacheDatabase, text: string) => RefAccounts;
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { isDocumentAccountProvider, isFolderProvider } from "../../domain/providers.js";
|
|
2
|
+
import { parseReference } from "../../domain/references.js";
|
|
3
|
+
import { ENTITY_TABLES, isEntityType } from "./entity-types.js";
|
|
4
|
+
import { storedThing, thingOf } from "./things.js";
|
|
5
|
+
const accountKeys = (database, ids) => {
|
|
6
|
+
const unique = [...new Set(ids)];
|
|
7
|
+
if (unique.length === 0)
|
|
8
|
+
return [];
|
|
9
|
+
return database
|
|
10
|
+
.prepare(`SELECT id, provider, external_id FROM accounts WHERE id IN (${unique.map(() => "?").join(",")})`)
|
|
11
|
+
.all(...unique)
|
|
12
|
+
.map(({ id, provider, external_id }) =>
|
|
13
|
+
// A notes folder or a documents account is `notes:<its store id>`, as source lists and groups name it.
|
|
14
|
+
isFolderProvider(String(provider)) || isDocumentAccountProvider(String(provider))
|
|
15
|
+
? { provider: "notes", account: String(id) }
|
|
16
|
+
: { provider: String(provider), account: String(external_id) });
|
|
17
|
+
};
|
|
18
|
+
const hasAccountColumn = new Map();
|
|
19
|
+
const accountColumnIn = (database, table) => {
|
|
20
|
+
const known = hasAccountColumn.get(table);
|
|
21
|
+
if (known !== undefined)
|
|
22
|
+
return known;
|
|
23
|
+
const has = database
|
|
24
|
+
.prepare(`PRAGMA table_info(${table})`)
|
|
25
|
+
.all()
|
|
26
|
+
.some((column) => column.name === "account_id");
|
|
27
|
+
hasAccountColumn.set(table, has);
|
|
28
|
+
return has;
|
|
29
|
+
};
|
|
30
|
+
const ids = (rows) => rows.flatMap(({ account_id }) => (account_id === null || account_id === undefined ? [] : [Number(account_id)]));
|
|
31
|
+
/** Every source record of the row, as a CRM's or another import's copy of it. */
|
|
32
|
+
const recordAccounts = (database, type, id) => ids(database.prepare("SELECT account_id FROM records WHERE entity_type = ? AND entity_id = ?").all(type, id));
|
|
33
|
+
/** The accounts that hold one of the person's identities. */
|
|
34
|
+
const personAccounts = (database, id) => ids(database
|
|
35
|
+
.prepare("SELECT ai.account_id FROM identity_links l JOIN account_identities ai ON ai.identity_id = l.identity_id " +
|
|
36
|
+
"WHERE l.person_id = ?")
|
|
37
|
+
.all(id));
|
|
38
|
+
const thingAccountIds = (database, thing) => {
|
|
39
|
+
switch (thing.type) {
|
|
40
|
+
// A note written in memo, never a file of a folder (`document:`), is the owner's: no account brought it.
|
|
41
|
+
case "note":
|
|
42
|
+
return [];
|
|
43
|
+
case "account":
|
|
44
|
+
return [thing.id];
|
|
45
|
+
case "message":
|
|
46
|
+
return ids(database
|
|
47
|
+
.prepare("SELECT c.account_id FROM messages m JOIN chats c ON c.id = m.chat_id WHERE m.id = ?")
|
|
48
|
+
.all(thing.id));
|
|
49
|
+
// An event is its copies' calendars' and its meetings' accounts; one with no copy is the owner's own.
|
|
50
|
+
case "event":
|
|
51
|
+
return [
|
|
52
|
+
...ids(database
|
|
53
|
+
.prepare("SELECT c.account_id FROM calendar_entries e JOIN calendars c ON c.id = e.calendar_id WHERE e.event_id = ?")
|
|
54
|
+
.all(thing.id)),
|
|
55
|
+
...ids(database.prepare("SELECT account_id FROM meetings WHERE event_id = ?").all(thing.id)),
|
|
56
|
+
];
|
|
57
|
+
case "identity":
|
|
58
|
+
return ids(database.prepare("SELECT account_id FROM account_identities WHERE identity_id = ?").all(thing.id));
|
|
59
|
+
}
|
|
60
|
+
if (!isEntityType(thing.type))
|
|
61
|
+
return [];
|
|
62
|
+
const table = ENTITY_TABLES[thing.type];
|
|
63
|
+
const own = accountColumnIn(database, table)
|
|
64
|
+
? ids(database.prepare(`SELECT account_id FROM ${table} WHERE id = ?`).all(thing.id))
|
|
65
|
+
: [];
|
|
66
|
+
return [
|
|
67
|
+
...own,
|
|
68
|
+
...recordAccounts(database, thing.type, thing.id),
|
|
69
|
+
...(thing.type === "person" ? personAccounts(database, thing.id) : []),
|
|
70
|
+
];
|
|
71
|
+
};
|
|
72
|
+
const endOf = (database, type, id) => type === null || type === undefined || id === null || id === undefined
|
|
73
|
+
? []
|
|
74
|
+
: [accountKeys(database, thingAccountIds(database, storedThing(type, id)))];
|
|
75
|
+
/** A proposed action (`action:<id>`) and a suggested link (`link:<id>`): ids of the proposal registry, not references. */
|
|
76
|
+
const PROPOSAL = /^(action|link):([1-9]\d*)$/;
|
|
77
|
+
/**
|
|
78
|
+
* Each part a referenced thing belongs to, every one of which a group must hold: one part for most things; a proposed
|
|
79
|
+
* action's own account and its target; a link's two ends. `undefined` when the store holds nothing for it.
|
|
80
|
+
*/
|
|
81
|
+
export const refEndsOf = (database, text) => {
|
|
82
|
+
const proposal = PROPOSAL.exec(text.trim());
|
|
83
|
+
if (proposal) {
|
|
84
|
+
const [, kind, id] = proposal;
|
|
85
|
+
if (kind === "action") {
|
|
86
|
+
const row = database
|
|
87
|
+
.prepare("SELECT account_id, target_type, target_id FROM proposed_actions WHERE id = ?")
|
|
88
|
+
.get(Number(id));
|
|
89
|
+
if (!row)
|
|
90
|
+
return undefined;
|
|
91
|
+
return [
|
|
92
|
+
...(row.account_id === null ? [] : [accountKeys(database, [Number(row.account_id)])]),
|
|
93
|
+
...endOf(database, row.target_type, row.target_id),
|
|
94
|
+
];
|
|
95
|
+
}
|
|
96
|
+
const link = database.prepare("SELECT from_type, from_id, to_type, to_id FROM links WHERE id = ?").get(Number(id));
|
|
97
|
+
if (!link)
|
|
98
|
+
return undefined;
|
|
99
|
+
return [...endOf(database, link.from_type, link.from_id), ...endOf(database, link.to_type, link.to_id)];
|
|
100
|
+
}
|
|
101
|
+
let reference;
|
|
102
|
+
try {
|
|
103
|
+
reference = parseReference(text);
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
return undefined;
|
|
107
|
+
}
|
|
108
|
+
if (reference.type === "message" || reference.type === "chat")
|
|
109
|
+
return [[{ provider: reference.provider, account: reference.account }]];
|
|
110
|
+
const thing = thingOf(database, reference);
|
|
111
|
+
if (!thing)
|
|
112
|
+
return undefined;
|
|
113
|
+
if (reference.type === "meeting")
|
|
114
|
+
return [accountKeys(database, [reference.accountId])];
|
|
115
|
+
return [accountKeys(database, thingAccountIds(database, thing))];
|
|
116
|
+
};
|
|
117
|
+
export const refAccountsOf = (database, text) => refEndsOf(database, text)?.flat();
|