@wirecat/cli-core 0.723.0 → 0.724.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 +34 -0
- package/dist/cli/documents/history.js +2 -2
- package/dist/cli/documents/words.d.ts +1 -1
- package/dist/content/writes.d.ts +3 -9
- package/dist/content/writes.js +3 -13
- package/dist/crm/writes.d.ts +4 -13
- package/dist/crm/writes.js +2 -9
- package/dist/errors/reasons.js +5 -0
- package/dist/sends/profile-writes.d.ts +22 -0
- package/dist/sends/profile-writes.js +20 -0
- package/dist/services/metadata.d.ts +1 -1
- package/dist/tracker/cli/index.d.ts +10 -1
- package/dist/tracker/cli/index.js +20 -1
- package/dist/tracker/cli/writes.d.ts +27 -0
- package/dist/tracker/cli/writes.js +74 -0
- package/dist/tracker/index.d.ts +5 -2
- package/dist/tracker/index.js +5 -2
- package/dist/tracker/manifest/manifest.d.ts +25 -0
- package/dist/tracker/manifest/manifest.js +59 -8
- package/dist/tracker/manifest/source.d.ts +10 -1
- package/dist/tracker/manifest/source.js +12 -9
- package/dist/tracker/manifest/writer.d.ts +20 -0
- package/dist/tracker/manifest/writer.js +72 -0
- package/dist/tracker/sync.d.ts +5 -0
- package/dist/tracker/sync.js +12 -0
- package/dist/tracker/testing/index.d.ts +3 -1
- package/dist/tracker/testing/index.js +3 -1
- package/dist/tracker/testing/manifest-fake.d.ts +2 -0
- package/dist/tracker/testing/manifest-fake.js +123 -41
- package/dist/tracker/testing/manifest-writes.d.ts +16 -0
- package/dist/tracker/testing/manifest-writes.js +70 -0
- package/dist/tracker/testing/source.d.ts +9 -1
- package/dist/tracker/testing/source.js +63 -0
- package/dist/tracker/testing/write-contract.d.ts +20 -0
- package/dist/tracker/testing/write-contract.js +94 -0
- package/dist/tracker/writer.d.ts +57 -0
- package/dist/tracker/writer.js +25 -0
- package/dist/tracker/writes.d.ts +53 -0
- package/dist/tracker/writes.js +226 -0
- package/package.json +1 -1
|
@@ -6,6 +6,11 @@ import { rulePaths } from "../../crm/manifest/map.js";
|
|
|
6
6
|
import { TRACKER_KINDS } from "../../domain/tracker.js";
|
|
7
7
|
import { editDistance } from "../../search/correct.js";
|
|
8
8
|
import { TRACKER_FIELDS } from "./map.js";
|
|
9
|
+
/** The fields a write of each kind may name. */
|
|
10
|
+
export const TRACKER_WRITE_FIELDS = {
|
|
11
|
+
issue: ["title", "description", "team", "state", "assignee", "priority", "labels", "project", "parent"],
|
|
12
|
+
comment: ["issue", "body"],
|
|
13
|
+
};
|
|
9
14
|
const path = v.pipe(v.string(), v.regex(/^[^.\s]+(\.[^.\s]+)*$/, "a dotted path such as state.id"));
|
|
10
15
|
const call = v.strictObject({
|
|
11
16
|
operation: v.pipe(v.string(), v.minLength(1)),
|
|
@@ -14,6 +19,11 @@ const call = v.strictObject({
|
|
|
14
19
|
items: v.optional(path),
|
|
15
20
|
});
|
|
16
21
|
const kind = v.picklist(TRACKER_KINDS);
|
|
22
|
+
const write = v.strictObject({
|
|
23
|
+
create: v.optional(call),
|
|
24
|
+
update: v.optional(call),
|
|
25
|
+
fields: v.record(v.string(), v.strictObject({ to: path })),
|
|
26
|
+
});
|
|
17
27
|
const schema = v.strictObject({
|
|
18
28
|
provider: v.pipe(v.string(), v.regex(/^[a-z][a-z0-9-]*$/, "a registry name such as linear")),
|
|
19
29
|
kinds: v.pipe(v.array(kind), v.minLength(1)),
|
|
@@ -26,15 +36,16 @@ const schema = v.strictObject({
|
|
|
26
36
|
optional: v.optional(v.strictObject({ message: v.pipe(v.string(), v.minLength(1)), scope: v.optional(v.string()) })),
|
|
27
37
|
}))),
|
|
28
38
|
self: v.optional(v.strictObject({ call, path })),
|
|
39
|
+
writes: v.optional(v.strictObject({ issue: v.optional(write), comment: v.optional(write) })),
|
|
29
40
|
});
|
|
30
41
|
const invalid = (where, message) => new CliError("configuration_error", `source manifest: ${where}: ${message}`, { reason: "manifest.invalid" });
|
|
31
42
|
const nearest = (wanted, known) => known
|
|
32
43
|
.map((one) => ({ one, edits: editDistance(wanted, one, 2) }))
|
|
33
44
|
.filter(({ edits }) => edits <= 2)
|
|
34
45
|
.sort((a, b) => a.edits - b.edits)[0]?.one;
|
|
35
|
-
const
|
|
36
|
-
(Array.isArray(value) && value.some(
|
|
37
|
-
(typeof value === "object" && value !== null && Object.values(value).some(
|
|
46
|
+
const holds = (value, placeholder) => value === placeholder ||
|
|
47
|
+
(Array.isArray(value) && value.some((one) => holds(one, placeholder))) ||
|
|
48
|
+
(typeof value === "object" && value !== null && Object.values(value).some((one) => holds(one, placeholder)));
|
|
38
49
|
/** The selection a call sends, as a tree: its own, else the operation's default; none for an operation over HTTP. */
|
|
39
50
|
export const selectionOf = (one, api) => {
|
|
40
51
|
const binding = api.operations.find((operation) => operation.id === one.operation)?.binding;
|
|
@@ -78,15 +89,17 @@ export const parseTrackerManifest = (input, api) => {
|
|
|
78
89
|
throw invalid("kinds", `list them once each, in this order: ${TRACKER_KINDS.join(", ")}`);
|
|
79
90
|
const operations = new Map(api.operations.map((one) => [one.id, one]));
|
|
80
91
|
const known = [...operations.keys()];
|
|
81
|
-
const checkCall = (where, one, map) => {
|
|
92
|
+
const checkCall = (where, one, map, writes = false) => {
|
|
82
93
|
const operation = operations.get(one.operation);
|
|
83
94
|
if (!operation) {
|
|
84
95
|
const near = nearest(one.operation, known);
|
|
85
96
|
throw invalid(`${where}.operation`, `no operation ${one.operation} in the API${near ? `; did you mean ${near}?` : ""}`);
|
|
86
97
|
}
|
|
87
|
-
if (operation.effect
|
|
98
|
+
if (writes && operation.effect === "read")
|
|
99
|
+
throw invalid(`${where}.operation`, `${one.operation} is a read, and a write names a mutation`);
|
|
100
|
+
if (!writes && operation.effect !== "read")
|
|
88
101
|
throw invalid(`${where}.operation`, `${one.operation} is a ${operation.effect}, and a source only reads`);
|
|
89
|
-
if (operation.pagination && operation.pagination.style === "link")
|
|
102
|
+
if (!writes && operation.pagination && operation.pagination.style === "link")
|
|
90
103
|
throw invalid(`${where}.operation`, `${one.operation} pages by a link, which a source does not read yet`);
|
|
91
104
|
let tree;
|
|
92
105
|
try {
|
|
@@ -99,7 +112,7 @@ export const parseTrackerManifest = (input, api) => {
|
|
|
99
112
|
throw invalid(`${where}.selection`, `${one.operation} is not a GraphQL operation, so it takes no selection`);
|
|
100
113
|
if (!tree || !map)
|
|
101
114
|
return;
|
|
102
|
-
const row = rowSelection(tree, one.items ?? operation.pagination?.items);
|
|
115
|
+
const row = rowSelection(tree, one.items ?? (writes ? undefined : operation.pagination?.items));
|
|
103
116
|
if (!row)
|
|
104
117
|
throw invalid(`${where}.selection`, "selects no rows where the operation's items are");
|
|
105
118
|
for (const [field, rule] of Object.entries(map))
|
|
@@ -124,7 +137,7 @@ export const parseTrackerManifest = (input, api) => {
|
|
|
124
137
|
checkCall(`entities.${kind}.list`, one.list, one.map);
|
|
125
138
|
if (one.changes) {
|
|
126
139
|
checkCall(`entities.${kind}.changes`, one.changes, one.map);
|
|
127
|
-
if (!
|
|
140
|
+
if (!holds(one.changes.variables, "{since}"))
|
|
128
141
|
throw invalid(`entities.${kind}.changes`, 'no "{since}" in its variables');
|
|
129
142
|
}
|
|
130
143
|
if (one.ids)
|
|
@@ -135,5 +148,43 @@ export const parseTrackerManifest = (input, api) => {
|
|
|
135
148
|
throw invalid(`entities.${kind}`, `${kind} has an entity but is not in kinds`);
|
|
136
149
|
if (manifest.self)
|
|
137
150
|
checkCall("self.call", manifest.self.call, { self: manifest.self.path });
|
|
151
|
+
for (const [kind, one] of Object.entries(manifest.writes ?? {}))
|
|
152
|
+
if (one)
|
|
153
|
+
checkWrite(kind, one, manifest, checkCall);
|
|
138
154
|
return manifest;
|
|
139
155
|
};
|
|
156
|
+
const checkWrite = (kind, one, manifest, checkCall) => {
|
|
157
|
+
const where = `writes.${kind}`;
|
|
158
|
+
const entity = manifest.entities[kind];
|
|
159
|
+
if (!entity)
|
|
160
|
+
throw invalid(where, `${kind} is not in kinds, so its written row has no map`);
|
|
161
|
+
if (!one.create && !one.update)
|
|
162
|
+
throw invalid(where, "names no create or update");
|
|
163
|
+
if (kind === "comment" && one.update)
|
|
164
|
+
throw invalid(`${where}.update`, "a comment is only added");
|
|
165
|
+
const fields = TRACKER_WRITE_FIELDS[kind];
|
|
166
|
+
for (const field of Object.keys(one.fields))
|
|
167
|
+
if (!fields.includes(field)) {
|
|
168
|
+
const near = nearest(field, fields);
|
|
169
|
+
throw invalid(`${where}.fields.${field}`, `a ${kind} writes no such field${near ? `; did you mean ${near}?` : ""}`);
|
|
170
|
+
}
|
|
171
|
+
const needed = kind === "comment" ? ["issue", "body"] : ["title"];
|
|
172
|
+
const missing = one.create ? needed.find((field) => one.fields[field] === undefined) : undefined;
|
|
173
|
+
if (missing)
|
|
174
|
+
throw invalid(`${where}.fields.${missing}`, `a new ${kind} needs its ${missing}`);
|
|
175
|
+
for (const verb of ["create", "update"]) {
|
|
176
|
+
const sent = one[verb];
|
|
177
|
+
if (!sent)
|
|
178
|
+
continue;
|
|
179
|
+
checkCall(`${where}.${verb}`, sent, entity.map, true);
|
|
180
|
+
if (!holds(sent.variables, "{values}"))
|
|
181
|
+
throw invalid(`${where}.${verb}`, 'no "{values}" in its variables');
|
|
182
|
+
// A write fills only its own slots: a "{since}" or a create's "{id}" would go out as the literal text.
|
|
183
|
+
if (holds(sent.variables, "{since}"))
|
|
184
|
+
throw invalid(`${where}.${verb}`, '"{since}" is for a change read, not a write');
|
|
185
|
+
if (verb === "create" && holds(sent.variables, "{id}"))
|
|
186
|
+
throw invalid(`${where}.${verb}`, 'a create has no "{id}" yet; only an update names one');
|
|
187
|
+
if (verb === "update" && !holds(sent.variables, "{id}"))
|
|
188
|
+
throw invalid(`${where}.${verb}`, 'no "{id}" in its variables');
|
|
189
|
+
}
|
|
190
|
+
};
|
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import type { ApiCommandInput } from "../../cli/bot/api.js";
|
|
1
2
|
import type { ServiceApiCall } from "../../cli/service-api-call.js";
|
|
2
3
|
import { type ServiceApiManifest } from "../../cli/service-api-manifest.js";
|
|
3
4
|
import type { TrackerSource } from "../source.js";
|
|
4
|
-
import { type TrackerManifestHooks } from "./manifest.js";
|
|
5
|
+
import { type TrackerManifestHooks, type TrackerOperationCall } from "./manifest.js";
|
|
5
6
|
export interface TrackerManifestSourceOptions {
|
|
6
7
|
/** The generated API manifest the operations are named in: their bindings, paging and sign-in. */
|
|
7
8
|
api: ServiceApiManifest;
|
|
@@ -10,6 +11,14 @@ export interface TrackerManifestSourceOptions {
|
|
|
10
11
|
now?: () => number;
|
|
11
12
|
hooks?: TrackerManifestHooks;
|
|
12
13
|
}
|
|
14
|
+
/** What the engine puts in a call's variables: `"{since}"`, and a write's `"{id}"` and `"{values}"`. */
|
|
15
|
+
export interface TrackerSlots {
|
|
16
|
+
since?: string;
|
|
17
|
+
id?: string;
|
|
18
|
+
values?: Readonly<Record<string, unknown>>;
|
|
19
|
+
}
|
|
20
|
+
/** The variables travel as the body: each GraphQL argument is a body parameter of the operation. */
|
|
21
|
+
export declare const trackerInputOf: (call: TrackerOperationCall, slots?: TrackerSlots) => ApiCommandInput;
|
|
13
22
|
/**
|
|
14
23
|
* A `TrackerSource` read from a manifest: each kind listed and read for changes by the operations it names, paged by
|
|
15
24
|
* each operation's own `pagination`, each row mapped onto the tracker domain. Deletions are found by a pass over
|
|
@@ -6,25 +6,28 @@ import { parseTrackerManifest, } from "./manifest.js";
|
|
|
6
6
|
import { mapTrackerRecord } from "./map.js";
|
|
7
7
|
const OVERLAP_MS = 10 * 60_000;
|
|
8
8
|
const DROP = Symbol("drop");
|
|
9
|
-
const
|
|
10
|
-
|
|
11
|
-
|
|
9
|
+
const SLOT = /^\{(since|id|values)\}$/;
|
|
10
|
+
// A slot's value goes in as it is, never filled again: an owner's title may say "{since}".
|
|
11
|
+
const fill = (value, slots) => {
|
|
12
|
+
const slot = typeof value === "string" ? SLOT.exec(value)?.[1] : undefined;
|
|
13
|
+
if (slot !== undefined)
|
|
14
|
+
return slots[slot] ?? DROP;
|
|
12
15
|
if (Array.isArray(value))
|
|
13
|
-
return value.map((one) => fill(one,
|
|
16
|
+
return value.map((one) => fill(one, slots)).filter((one) => one !== DROP);
|
|
14
17
|
if (crmValues.isRaw(value))
|
|
15
18
|
return Object.fromEntries(Object.entries(value).flatMap(([key, one]) => {
|
|
16
|
-
const filled = fill(one,
|
|
19
|
+
const filled = fill(one, slots);
|
|
17
20
|
return filled === DROP ? [] : [[key, filled]];
|
|
18
21
|
}));
|
|
19
22
|
return value;
|
|
20
23
|
};
|
|
21
24
|
/** The variables travel as the body: each GraphQL argument is a body parameter of the operation. */
|
|
22
|
-
const
|
|
25
|
+
export const trackerInputOf = (call, slots = {}) => ({
|
|
23
26
|
path: {},
|
|
24
27
|
query: {},
|
|
25
28
|
headers: {},
|
|
26
29
|
fields: {},
|
|
27
|
-
...(call.variables ? { body: JSON.stringify(fill(call.variables,
|
|
30
|
+
...(call.variables ? { body: JSON.stringify(fill(call.variables, slots)) } : {}),
|
|
28
31
|
...(call.selection ? { selection: call.selection } : {}),
|
|
29
32
|
});
|
|
30
33
|
const SINCE = {
|
|
@@ -71,7 +74,7 @@ export const trackerSourceFromManifest = (input, options) => {
|
|
|
71
74
|
const readPage = async (call, since, token, send) => {
|
|
72
75
|
const pagination = operations.get(call.operation)?.pagination;
|
|
73
76
|
const parameter = pagination && cursorParameter(pagination);
|
|
74
|
-
let request =
|
|
77
|
+
let request = trackerInputOf(call, since === undefined ? {} : { since });
|
|
75
78
|
if (token !== undefined && parameter)
|
|
76
79
|
request = { ...withValue(request, parameter, pagination.style === "cursor" ? token : Number(token)) };
|
|
77
80
|
const answer = await send(call.operation, request);
|
|
@@ -162,7 +165,7 @@ export const trackerSourceFromManifest = (input, options) => {
|
|
|
162
165
|
? {
|
|
163
166
|
async self(context) {
|
|
164
167
|
const self = manifest.self;
|
|
165
|
-
const found = crmValues.id(at(await metered(context)(self.call.operation,
|
|
168
|
+
const found = crmValues.id(at(await metered(context)(self.call.operation, trackerInputOf(self.call)), self.path));
|
|
166
169
|
if (found === null)
|
|
167
170
|
throw new CliError("invalid_response", `${manifest.provider} named no signed-in user`);
|
|
168
171
|
return found;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { Command } from "commander";
|
|
2
|
+
import type { ServiceApiWrite } from "../../cli/service-api.js";
|
|
3
|
+
import type { ServiceApiManifest } from "../../cli/service-api-manifest.js";
|
|
4
|
+
import type { TrackerWriter } from "../writer.js";
|
|
5
|
+
export interface TrackerManifestWriterOptions {
|
|
6
|
+
/** The generated API manifest the operations are named in. */
|
|
7
|
+
api: ServiceApiManifest;
|
|
8
|
+
/**
|
|
9
|
+
* Sends one write the way the `api` group does: `serviceApiWriter`, which checks the operation's own keys
|
|
10
|
+
* (`api.issue-create`) and the body against its schema. Nothing else may write for a CLI.
|
|
11
|
+
*/
|
|
12
|
+
write: ServiceApiWrite;
|
|
13
|
+
/** The command the owner ran, for the write's checks and question. */
|
|
14
|
+
command: Command;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* A `TrackerWriter` from the manifest's `writes`: each of our fields goes where its rule says inside `"{values}"`, and
|
|
18
|
+
* the row the tracker answers is read by the kind's `map`, as a sync reads it.
|
|
19
|
+
*/
|
|
20
|
+
export declare const trackerWriterFromManifest: (input: unknown, options: TrackerManifestWriterOptions) => TrackerWriter;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { apiPathOf } from "../../cli/bot/api.js";
|
|
3
|
+
import { crmValues } from "../../crm/index.js";
|
|
4
|
+
import { at } from "../../crm/manifest/map.js";
|
|
5
|
+
import { parseTrackerManifest } from "./manifest.js";
|
|
6
|
+
import { mapTrackerRecord } from "./map.js";
|
|
7
|
+
import { trackerInputOf } from "./source.js";
|
|
8
|
+
const unsupported = (message) => new CliError("validation_error", message, { reason: "tracker.write-unsupported", sent: false });
|
|
9
|
+
const put = (into, path, value) => {
|
|
10
|
+
const keys = path.split(".");
|
|
11
|
+
const last = keys.pop();
|
|
12
|
+
let inner = into;
|
|
13
|
+
for (const key of keys) {
|
|
14
|
+
if (!crmValues.isRaw(inner[key]))
|
|
15
|
+
inner[key] = {};
|
|
16
|
+
inner = inner[key];
|
|
17
|
+
}
|
|
18
|
+
inner[last] = value;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* A `TrackerWriter` from the manifest's `writes`: each of our fields goes where its rule says inside `"{values}"`, and
|
|
22
|
+
* the row the tracker answers is read by the kind's `map`, as a sync reads it.
|
|
23
|
+
*/
|
|
24
|
+
export const trackerWriterFromManifest = (input, options) => {
|
|
25
|
+
const manifest = parseTrackerManifest(input, options.api);
|
|
26
|
+
const writes = manifest.writes ?? {};
|
|
27
|
+
const operations = new Map(options.api.operations.map((one) => [one.id, one]));
|
|
28
|
+
const valuesOf = (kind, fields) => {
|
|
29
|
+
const rules = writes[kind]?.fields ?? {};
|
|
30
|
+
const values = {};
|
|
31
|
+
for (const [field, value] of Object.entries(fields)) {
|
|
32
|
+
if (value === undefined)
|
|
33
|
+
continue;
|
|
34
|
+
const rule = rules[field];
|
|
35
|
+
if (!rule)
|
|
36
|
+
throw unsupported(`${manifest.provider} takes no ${field} on a written ${kind}`);
|
|
37
|
+
put(values, rule.to, value);
|
|
38
|
+
}
|
|
39
|
+
return values;
|
|
40
|
+
};
|
|
41
|
+
const send = async (kind, verb, slots, confirmed) => {
|
|
42
|
+
const call = writes[kind]?.[verb];
|
|
43
|
+
if (!call)
|
|
44
|
+
throw unsupported(`${manifest.provider} takes no ${kind} ${verb}`);
|
|
45
|
+
// The owner said yes to this write in the tracker's command, so the operation's own key is not asked again.
|
|
46
|
+
const operation = operations.get(call.operation);
|
|
47
|
+
const own = operation ? [["api", ...apiPathOf(operation)].join(".")] : [];
|
|
48
|
+
const { result } = await options.write(options.command, call.operation, trackerInputOf(call, slots), {
|
|
49
|
+
confirmed: confirmed?.length ? [...confirmed, ...own] : [],
|
|
50
|
+
});
|
|
51
|
+
const raw = call.items === undefined ? result : at(result, call.items);
|
|
52
|
+
const entity = manifest.entities[kind];
|
|
53
|
+
const record = entity && crmValues.isRaw(raw) ? mapTrackerRecord(kind, entity.map, raw) : null;
|
|
54
|
+
// An answer with no row (Linear's `success: false` and no error) does not say the write was made, so the copy
|
|
55
|
+
// is not told it was.
|
|
56
|
+
if (!record)
|
|
57
|
+
throw new CliError("invalid_response", `${manifest.provider} answered the ${kind} ${verb} with no ${kind}; sync and look before writing again`, { reason: "tracker.no-record" });
|
|
58
|
+
return record;
|
|
59
|
+
};
|
|
60
|
+
const offered = [
|
|
61
|
+
...(writes.issue?.create ? ["create"] : []),
|
|
62
|
+
...(writes.issue?.update ? ["update"] : []),
|
|
63
|
+
...(writes.comment?.create ? ["comment"] : []),
|
|
64
|
+
];
|
|
65
|
+
return {
|
|
66
|
+
provider: manifest.provider,
|
|
67
|
+
writes: offered,
|
|
68
|
+
createIssue: async (draft, { confirmed }) => send("issue", "create", { values: valuesOf("issue", draft) }, confirmed),
|
|
69
|
+
updateIssue: async (externalId, patch, { confirmed }) => send("issue", "update", { id: externalId, values: valuesOf("issue", patch) }, confirmed),
|
|
70
|
+
comment: async (issue, body, { confirmed }) => send("comment", "create", { values: valuesOf("comment", { issue, body }) }, confirmed),
|
|
71
|
+
};
|
|
72
|
+
};
|
package/dist/tracker/sync.d.ts
CHANGED
|
@@ -64,5 +64,10 @@ export interface TrackerSyncReport {
|
|
|
64
64
|
* and the next one goes on from there. A kind that fails is named and the others still sync.
|
|
65
65
|
*/
|
|
66
66
|
export declare const syncTracker: (source: TrackerSource, store: MessageStore, account: AccountKey, options?: TrackerSyncOptions) => Promise<TrackerSyncReport>;
|
|
67
|
+
/**
|
|
68
|
+
* The sign-in's own user id, as a sync keeps it; asked of the tracker once when none is kept yet. `undefined` when the
|
|
69
|
+
* tracker cannot say: then every user is somebody else.
|
|
70
|
+
*/
|
|
71
|
+
export declare const trackerSelfOf: (store: MessageStore, account: AccountKey, source?: TrackerSource) => Promise<string | undefined>;
|
|
67
72
|
/** The gaps the account's last sync recorded; none before its first. */
|
|
68
73
|
export declare const trackerGapsOf: (store: MessageStore, account: AccountKey) => Promise<TrackerGap[]>;
|
package/dist/tracker/sync.js
CHANGED
|
@@ -271,6 +271,18 @@ const ownTasks = async (run, self) => {
|
|
|
271
271
|
return { skipped: error instanceof Error ? error.message : String(error) };
|
|
272
272
|
}
|
|
273
273
|
};
|
|
274
|
+
/**
|
|
275
|
+
* The sign-in's own user id, as a sync keeps it; asked of the tracker once when none is kept yet. `undefined` when the
|
|
276
|
+
* tracker cannot say: then every user is somebody else.
|
|
277
|
+
*/
|
|
278
|
+
export const trackerSelfOf = async (store, account, source) => {
|
|
279
|
+
const kept = (await store.sync.syncState(account, SELF))?.value;
|
|
280
|
+
if (kept || !source?.self)
|
|
281
|
+
return kept || undefined;
|
|
282
|
+
const id = await source.self();
|
|
283
|
+
await store.sync.setSyncState(account, SELF, id);
|
|
284
|
+
return id;
|
|
285
|
+
};
|
|
274
286
|
/** The gaps the account's last sync recorded; none before its first. */
|
|
275
287
|
export const trackerGapsOf = async (store, account) => {
|
|
276
288
|
try {
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
-
export { type TrackerManifestFake, type TrackerManifestFakeOptions, type TrackerManifestFixtureOptions, trackerManifestContract, trackerManifestFake, trackerManifestFixture, } from "./manifest-fake.js";
|
|
1
|
+
export { failingOnRefusals, type TrackerManifestFake, type TrackerManifestFakeOptions, type TrackerManifestFixtureOptions, trackerManifestContract, trackerManifestFake, trackerManifestFixture, } from "./manifest-fake.js";
|
|
2
|
+
export { trackerManifestWriteContract, trackerManifestWriteFixture } from "./manifest-writes.js";
|
|
2
3
|
export { exampleTrackerRows, type FakeTrackerRows, type FakeTrackerSource, type FakeTrackerSourceOptions, fakeTrackerSource, } from "./source.js";
|
|
3
4
|
export { type TrackerSourceFaults, type TrackerSourceFixture, trackerSourceContract, } from "./source-contract.js";
|
|
5
|
+
export { type TrackerWriteFixture, trackerWriteContract } from "./write-contract.js";
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
-
export { trackerManifestContract, trackerManifestFake, trackerManifestFixture, } from "./manifest-fake.js";
|
|
1
|
+
export { failingOnRefusals, trackerManifestContract, trackerManifestFake, trackerManifestFixture, } from "./manifest-fake.js";
|
|
2
|
+
export { trackerManifestWriteContract, trackerManifestWriteFixture } from "./manifest-writes.js";
|
|
2
3
|
export { exampleTrackerRows, fakeTrackerSource, } from "./source.js";
|
|
3
4
|
export { trackerSourceContract, } from "./source-contract.js";
|
|
5
|
+
export { trackerWriteContract } from "./write-contract.js";
|
|
@@ -48,4 +48,6 @@ export declare const trackerManifestFixture: (manifest: unknown, options: Tracke
|
|
|
48
48
|
* generated test runs, `for (const { name, run } of trackerManifestContract(SOURCE, { api, definitions })) it(name, run)`.
|
|
49
49
|
*/
|
|
50
50
|
export declare const trackerManifestContract: (manifest: unknown, options: TrackerManifestFixtureOptions) => ContractCase[];
|
|
51
|
+
/** Each case failing too when a fake it built refused a call: the refusal says why, the error only that it was refused. */
|
|
52
|
+
export declare const failingOnRefusals: (cases: readonly ContractCase[], fakes: TrackerManifestFake[]) => ContractCase[];
|
|
51
53
|
export {};
|
|
@@ -6,7 +6,7 @@ import { at, evaluate, MISSING, rulePaths } from "../../crm/manifest/map.js";
|
|
|
6
6
|
import { resolve, step } from "../../crm/manifest/paths.js";
|
|
7
7
|
import { FAKE_MANIFEST_TOKEN } from "../../crm/testing/index.js";
|
|
8
8
|
import { STATE_TYPES } from "../../domain/tracker.js";
|
|
9
|
-
import { parseTrackerManifest, rowSelection, selectionOf, } from "../manifest/manifest.js";
|
|
9
|
+
import { parseTrackerManifest, rowSelection, selectionOf, TRACKER_WRITE_FIELDS, } from "../manifest/manifest.js";
|
|
10
10
|
import { TRACKER_FIELDS } from "../manifest/map.js";
|
|
11
11
|
import { trackerSourceFromManifest } from "../manifest/source.js";
|
|
12
12
|
import { trackerSourceContract } from "./source-contract.js";
|
|
@@ -167,39 +167,49 @@ export const trackerManifestFake = (input, options) => {
|
|
|
167
167
|
const rule = manifest.entities[kind]?.map[field];
|
|
168
168
|
return typeof rule === "string" ? rule : typeof rule === "object" && "path" in rule ? rule.path : undefined;
|
|
169
169
|
};
|
|
170
|
+
const writeCalls = (kind) => {
|
|
171
|
+
const one = manifest.writes?.[kind];
|
|
172
|
+
return [one?.create, one?.update].filter((call) => call !== undefined);
|
|
173
|
+
};
|
|
170
174
|
const items = new Map();
|
|
175
|
+
const selections = new Map();
|
|
171
176
|
const rows = {};
|
|
177
|
+
const seed = (kind, n) => {
|
|
178
|
+
const entity = manifest.entities[kind];
|
|
179
|
+
const item = items.get(kind);
|
|
180
|
+
const made = item ? sampled(item, selections.get(kind) ?? {}) : {};
|
|
181
|
+
const row = crmValues.isRaw(made) ? made : {};
|
|
182
|
+
for (const [field, rule] of Object.entries(entity.map)) {
|
|
183
|
+
if (typeof rule === "function" || (typeof rule === "object" && "value" in rule && !("each" in rule)))
|
|
184
|
+
continue;
|
|
185
|
+
const [first, inside] = rulePaths(rule);
|
|
186
|
+
if (!first)
|
|
187
|
+
continue;
|
|
188
|
+
if (inside?.inside !== undefined) {
|
|
189
|
+
const one = {};
|
|
190
|
+
put(one, inside.path, pointed(field));
|
|
191
|
+
put(row, first.path, [one]);
|
|
192
|
+
}
|
|
193
|
+
else if (typeof rule === "object" && "map" in rule)
|
|
194
|
+
put(row, first.path, Object.keys(rule.map)[0] ?? null);
|
|
195
|
+
else
|
|
196
|
+
write(row, item, first.path, sampleValue(kind, field, n));
|
|
197
|
+
}
|
|
198
|
+
return row;
|
|
199
|
+
};
|
|
172
200
|
for (const kind of manifest.kinds) {
|
|
173
201
|
const entity = manifest.entities[kind];
|
|
174
202
|
const calls = [entity.list, entity.changes, entity.ids].filter((one) => one !== undefined);
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
.
|
|
178
|
-
|
|
179
|
-
|
|
203
|
+
// A written row is answered within the write's selection too, so the rows hold what it reads.
|
|
204
|
+
const selection = [
|
|
205
|
+
...calls.map((call) => rowSelection(selectionOf(call, api) ?? {}, itemsOf(call)) ?? {}),
|
|
206
|
+
...writeCalls(kind).map((call) => rowSelection(selectionOf(call, api) ?? {}, call.items) ?? {}),
|
|
207
|
+
].reduce((all, one) => merge(all, one), {});
|
|
208
|
+
selections.set(kind, selection);
|
|
209
|
+
items.set(kind, nodeAt(responseOf(entity.list), itemsOf(entity.list)));
|
|
180
210
|
if (entity.changes && timePath(kind, "updatedAt") === undefined)
|
|
181
211
|
throw new Error(`${kind}: map updatedAt to a path, so the fake can read a change time`);
|
|
182
|
-
rows[kind] = Array.from({ length: ROWS }, (_, n) =>
|
|
183
|
-
const made = item ? sampled(item, selection) : {};
|
|
184
|
-
const row = crmValues.isRaw(made) ? made : {};
|
|
185
|
-
for (const [field, rule] of Object.entries(entity.map)) {
|
|
186
|
-
if (typeof rule === "function" || (typeof rule === "object" && "value" in rule && !("each" in rule)))
|
|
187
|
-
continue;
|
|
188
|
-
const [first, inside] = rulePaths(rule);
|
|
189
|
-
if (!first)
|
|
190
|
-
continue;
|
|
191
|
-
if (inside?.inside !== undefined) {
|
|
192
|
-
const one = {};
|
|
193
|
-
put(one, inside.path, pointed(field));
|
|
194
|
-
put(row, first.path, [one]);
|
|
195
|
-
}
|
|
196
|
-
else if (typeof rule === "object" && "map" in rule)
|
|
197
|
-
put(row, first.path, Object.keys(rule.map)[0] ?? null);
|
|
198
|
-
else
|
|
199
|
-
write(row, item, first.path, sampleValue(kind, field, n));
|
|
200
|
-
}
|
|
201
|
-
return row;
|
|
202
|
-
});
|
|
212
|
+
rows[kind] = Array.from({ length: ROWS }, (_, n) => seed(kind, n));
|
|
203
213
|
}
|
|
204
214
|
const filterProblem = (kind, call, place) => {
|
|
205
215
|
const filter = fixedOf(call.variables?.[FILTER] ?? {});
|
|
@@ -331,6 +341,76 @@ export const trackerManifestFake = (input, options) => {
|
|
|
331
341
|
put(body, self.path, pointed("assignee"));
|
|
332
342
|
return { data: project(body, selection) };
|
|
333
343
|
};
|
|
344
|
+
/** One of our fields onto a row where the map reads it: a list of ids under its `each`, a cleared link as null. */
|
|
345
|
+
const assign = (kind, row, field, value) => {
|
|
346
|
+
const rule = manifest.entities[kind]?.map[field];
|
|
347
|
+
const [first, inside] = rulePaths(rule);
|
|
348
|
+
if (!first)
|
|
349
|
+
return;
|
|
350
|
+
if (inside?.inside !== undefined && Array.isArray(value))
|
|
351
|
+
put(row, first.path, value.map((id) => {
|
|
352
|
+
const one = {};
|
|
353
|
+
put(one, inside.path, id);
|
|
354
|
+
return one;
|
|
355
|
+
}));
|
|
356
|
+
else if (value === null && TRACKER_FIELDS[kind][field] === "id" && first.path.includes("."))
|
|
357
|
+
put(row, first.path.slice(0, first.path.lastIndexOf(".")), null);
|
|
358
|
+
else
|
|
359
|
+
write(row, items.get(kind), first.path, value);
|
|
360
|
+
};
|
|
361
|
+
const writeRoutes = Object.keys(manifest.writes ?? {}).flatMap((kind) => {
|
|
362
|
+
const one = manifest.writes?.[kind];
|
|
363
|
+
return ["create", "update"].flatMap((verb) => {
|
|
364
|
+
const call = one?.[verb];
|
|
365
|
+
return call ? [{ kind, verb, call, fields: one.fields }] : [];
|
|
366
|
+
});
|
|
367
|
+
});
|
|
368
|
+
/**
|
|
369
|
+
* A create adds a row, an update changes the row its `"{id}"` names; each answers the row within the call's
|
|
370
|
+
* selection. The variables were checked against the schema first, as the tracker checks them.
|
|
371
|
+
*/
|
|
372
|
+
const answerWrite = (call) => {
|
|
373
|
+
const route = writeRoutes.find((one) => one.call.operation === call.operation);
|
|
374
|
+
if (!route)
|
|
375
|
+
return refuse(`${call.operation}: no write of the source manifest sends it`);
|
|
376
|
+
const { kind } = route;
|
|
377
|
+
const values = at(call.variables, placeOf(route.call.variables, "{values}"));
|
|
378
|
+
if (!crmValues.isRaw(values))
|
|
379
|
+
return refuse(`${call.operation}: no "{values}" object in its variables`);
|
|
380
|
+
const named = new Set(Object.values(route.fields).map(({ to }) => to.split(".")[0]));
|
|
381
|
+
const stray = Object.keys(values).find((key) => !named.has(key));
|
|
382
|
+
if (stray)
|
|
383
|
+
return refuse(`${call.operation}: ${stray} is not a field the manifest writes`);
|
|
384
|
+
let row;
|
|
385
|
+
if (route.verb === "create") {
|
|
386
|
+
row = seed(kind, rows[kind]?.length ?? 0);
|
|
387
|
+
// What the tracker sets itself (the key, the creator, the times) keeps its sample; the rest is what was sent.
|
|
388
|
+
for (const field of TRACKER_WRITE_FIELDS[kind])
|
|
389
|
+
assign(kind, row, field, field === "labels" ? [] : null);
|
|
390
|
+
rows[kind] ??= [];
|
|
391
|
+
rows[kind].push(row);
|
|
392
|
+
}
|
|
393
|
+
else {
|
|
394
|
+
const id = at(call.variables, placeOf(route.call.variables, "{id}"));
|
|
395
|
+
row = rows[kind]?.find((one) => externalIdOf(manifest, kind, one) === id);
|
|
396
|
+
// The tracker's own refusal, not the fake's: an issue deleted since the last sync.
|
|
397
|
+
if (!row)
|
|
398
|
+
return { errors: [{ message: `Entity not found: ${String(id)}`, extensions: { code: "INVALID_INPUT" } }] };
|
|
399
|
+
}
|
|
400
|
+
for (const [field, rule] of Object.entries(route.fields)) {
|
|
401
|
+
const value = at(values, rule.to);
|
|
402
|
+
if (value !== undefined)
|
|
403
|
+
assign(kind, row, field, value);
|
|
404
|
+
}
|
|
405
|
+
stamp(kind, row, "updatedAt");
|
|
406
|
+
const selection = call.selection ?? {};
|
|
407
|
+
const made = sampled(responseOf(route.call), selection);
|
|
408
|
+
const body = crmValues.isRaw(made) ? made : {};
|
|
409
|
+
if (route.call.items === undefined)
|
|
410
|
+
return { data: project(row, selection) };
|
|
411
|
+
put(body, route.call.items, project(row, rowSelection(selection, route.call.items) ?? true));
|
|
412
|
+
return { data: project(body, selection) };
|
|
413
|
+
};
|
|
334
414
|
const scheme = Object.values(api.securitySchemes ?? {})[0];
|
|
335
415
|
const fake = graphqlFake({
|
|
336
416
|
operations: api.operations,
|
|
@@ -346,6 +426,7 @@ export const trackerManifestFake = (input, options) => {
|
|
|
346
426
|
answers: {
|
|
347
427
|
...Object.fromEntries(routes.map((route) => [route.call.operation, answer])),
|
|
348
428
|
...(manifest.self ? { [manifest.self.call.operation]: answerSelf } : {}),
|
|
429
|
+
...Object.fromEntries(writeRoutes.map((route) => [route.call.operation, answerWrite])),
|
|
349
430
|
},
|
|
350
431
|
});
|
|
351
432
|
return {
|
|
@@ -442,21 +523,22 @@ export const trackerManifestFixture = (manifest, options) => {
|
|
|
442
523
|
*/
|
|
443
524
|
export const trackerManifestContract = (manifest, options) => {
|
|
444
525
|
const fakes = [];
|
|
445
|
-
return trackerSourceContract(() => {
|
|
526
|
+
return failingOnRefusals(trackerSourceContract(() => {
|
|
446
527
|
const fixture = trackerManifestFixture(manifest, options);
|
|
447
528
|
fakes.push(fixture.fake);
|
|
448
529
|
return fixture;
|
|
449
|
-
})
|
|
450
|
-
name,
|
|
451
|
-
async run() {
|
|
452
|
-
fakes.length = 0;
|
|
453
|
-
const failed = await run().then(() => undefined, (error) => error);
|
|
454
|
-
// A refused call fails the source too; the refusal says why, its error only that the tracker said no.
|
|
455
|
-
const refused = fakes.flatMap((fake) => fake.refusals);
|
|
456
|
-
if (refused.length)
|
|
457
|
-
throw new Error(`the fake refused calls the source made:\n${refused.join("\n")}`, { cause: failed });
|
|
458
|
-
if (failed)
|
|
459
|
-
throw failed;
|
|
460
|
-
},
|
|
461
|
-
}));
|
|
530
|
+
}), fakes);
|
|
462
531
|
};
|
|
532
|
+
/** Each case failing too when a fake it built refused a call: the refusal says why, the error only that it was refused. */
|
|
533
|
+
export const failingOnRefusals = (cases, fakes) => cases.map(({ name, run }) => ({
|
|
534
|
+
name,
|
|
535
|
+
async run() {
|
|
536
|
+
fakes.length = 0;
|
|
537
|
+
const failed = await run().then(() => undefined, (error) => error);
|
|
538
|
+
const refused = fakes.flatMap((fake) => fake.refusals);
|
|
539
|
+
if (refused.length)
|
|
540
|
+
throw new Error(`the fake refused calls the source made:\n${refused.join("\n")}`, { cause: failed });
|
|
541
|
+
if (failed)
|
|
542
|
+
throw failed;
|
|
543
|
+
},
|
|
544
|
+
}));
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { ContractCase } from "../../meetings/index.js";
|
|
2
|
+
import { type TrackerManifestFake, type TrackerManifestFakeOptions } from "./manifest-fake.js";
|
|
3
|
+
import { type TrackerWriteFixture } from "./write-contract.js";
|
|
4
|
+
/**
|
|
5
|
+
* A `trackerWriteContract` fixture for a writer built from a manifest's `writes`, over `trackerManifestFake`: the
|
|
6
|
+
* variables of each write are checked against the generated schema (an unknown field, a missing required one), and
|
|
7
|
+
* the fake's `refusals` say why.
|
|
8
|
+
*/
|
|
9
|
+
export declare const trackerManifestWriteFixture: (manifest: unknown, options: TrackerManifestFakeOptions) => TrackerWriteFixture & {
|
|
10
|
+
fake: TrackerManifestFake;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* `trackerWriteContract` over `trackerManifestWriteFixture`, each case failing too when the fake refused a call: what
|
|
14
|
+
* a generated test runs, `for (const { name, run } of trackerManifestWriteContract(SOURCE, { api, definitions }))`.
|
|
15
|
+
*/
|
|
16
|
+
export declare const trackerManifestWriteContract: (manifest: unknown, options: TrackerManifestFakeOptions) => ContractCase[];
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { Command } from "commander";
|
|
3
|
+
import { serviceApiCall } from "../../cli/service-api-call.js";
|
|
4
|
+
import { crmValues } from "../../crm/index.js";
|
|
5
|
+
import { FAKE_MANIFEST_TOKEN } from "../../crm/testing/index.js";
|
|
6
|
+
import { parseTrackerManifest } from "../manifest/manifest.js";
|
|
7
|
+
import { trackerWriterFromManifest } from "../manifest/writer.js";
|
|
8
|
+
import { failingOnRefusals, trackerManifestFake, } from "./manifest-fake.js";
|
|
9
|
+
import { trackerWriteContract } from "./write-contract.js";
|
|
10
|
+
/**
|
|
11
|
+
* A `trackerWriteContract` fixture for a writer built from a manifest's `writes`, over `trackerManifestFake`: the
|
|
12
|
+
* variables of each write are checked against the generated schema (an unknown field, a missing required one), and
|
|
13
|
+
* the fake's `refusals` say why.
|
|
14
|
+
*/
|
|
15
|
+
export const trackerManifestWriteFixture = (manifest, options) => {
|
|
16
|
+
const fake = trackerManifestFake(manifest, options);
|
|
17
|
+
const parsed = parseTrackerManifest(manifest, options.api);
|
|
18
|
+
// serviceApiCall sends reads only; through it a write is built and signed as the CLI's serviceApiWriter builds it,
|
|
19
|
+
// without the profile's guard, which the tracker writes hold above the writer.
|
|
20
|
+
const call = serviceApiCall({
|
|
21
|
+
manifest: { ...options.api, operations: options.api.operations.map((one) => ({ ...one, effect: "read" })) },
|
|
22
|
+
service: parsed.provider,
|
|
23
|
+
fetch: fake.fetch,
|
|
24
|
+
token: () => FAKE_MANIFEST_TOKEN,
|
|
25
|
+
...(options.baseUrl ? { baseUrl: options.baseUrl } : {}),
|
|
26
|
+
});
|
|
27
|
+
const writeOperations = new Set(Object.values(parsed.writes ?? {}).flatMap((one) => [one?.create, one?.update].flatMap((sent) => (sent ? [sent.operation] : []))));
|
|
28
|
+
let lose = false;
|
|
29
|
+
const write = async (_command, operation, input) => {
|
|
30
|
+
const result = await call(operation, input);
|
|
31
|
+
if (lose) {
|
|
32
|
+
lose = false;
|
|
33
|
+
throw new CliError("outcome_unknown", "the connection dropped after the tracker got the write");
|
|
34
|
+
}
|
|
35
|
+
return { operation_id: `fake-${fake.calls.length}`, result };
|
|
36
|
+
};
|
|
37
|
+
const idOf = (kind) => {
|
|
38
|
+
const row = fake.rows[kind]?.[0];
|
|
39
|
+
const rule = parsed.entities[kind]?.map.externalId;
|
|
40
|
+
const id = row && typeof rule === "string" ? crmValues.id(row[rule]) : null;
|
|
41
|
+
if (id === null)
|
|
42
|
+
throw new Error(`the fake holds no ${kind} to write with`);
|
|
43
|
+
return id;
|
|
44
|
+
};
|
|
45
|
+
return {
|
|
46
|
+
writer: trackerWriterFromManifest(manifest, { api: options.api, write, command: new Command("fake") }),
|
|
47
|
+
fake,
|
|
48
|
+
team: idOf("team"),
|
|
49
|
+
state: idOf("state"),
|
|
50
|
+
user: idOf("user"),
|
|
51
|
+
label: idOf("label"),
|
|
52
|
+
project: idOf("project"),
|
|
53
|
+
loseNextAnswer: () => {
|
|
54
|
+
lose = true;
|
|
55
|
+
},
|
|
56
|
+
requests: () => fake.calls.filter((one) => one.operation && writeOperations.has(one.operation)).length,
|
|
57
|
+
};
|
|
58
|
+
};
|
|
59
|
+
/**
|
|
60
|
+
* `trackerWriteContract` over `trackerManifestWriteFixture`, each case failing too when the fake refused a call: what
|
|
61
|
+
* a generated test runs, `for (const { name, run } of trackerManifestWriteContract(SOURCE, { api, definitions }))`.
|
|
62
|
+
*/
|
|
63
|
+
export const trackerManifestWriteContract = (manifest, options) => {
|
|
64
|
+
const fakes = [];
|
|
65
|
+
return failingOnRefusals(trackerWriteContract(() => {
|
|
66
|
+
const fixture = trackerManifestWriteFixture(manifest, options);
|
|
67
|
+
fakes.push(fixture.fake);
|
|
68
|
+
return fixture;
|
|
69
|
+
}), fakes);
|
|
70
|
+
};
|