@wirecat/cli-core 0.696.0 → 0.697.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/cli/bot/api-http.d.ts +1 -1
  3. package/dist/cli/bot/api-http.js +77 -5
  4. package/dist/cli/bot/api-input.d.ts +5 -0
  5. package/dist/cli/bot/api-input.js +55 -0
  6. package/dist/cli/bot/api.d.ts +2 -0
  7. package/dist/cli/bot/api.js +12 -3
  8. package/dist/cli/messenger/store-maintenance-command.js +3 -2
  9. package/dist/cli/service-api-manifest.js +7 -4
  10. package/dist/cli/service-api.js +6 -2
  11. package/dist/crm/manifest/manifest.d.ts +2 -0
  12. package/dist/crm/manifest/manifest.js +2 -1
  13. package/dist/crm/manifest/map.d.ts +2 -1
  14. package/dist/crm/manifest/map.js +2 -1
  15. package/dist/domain/tracker.d.ts +100 -0
  16. package/dist/domain/tracker.js +28 -0
  17. package/dist/errors/reasons.js +1 -0
  18. package/dist/manifest/index.d.ts +9 -5
  19. package/dist/manifest/index.js +18 -7
  20. package/dist/store/exports.d.ts +1 -0
  21. package/dist/store/exports.js +1 -0
  22. package/dist/store/recover.js +2 -0
  23. package/dist/store/sqlite/account-purge.js +1 -0
  24. package/dist/store/sqlite/crm-files.d.ts +3 -0
  25. package/dist/store/sqlite/crm-files.js +2 -2
  26. package/dist/store/sqlite/manifest.js +2 -0
  27. package/dist/store/sqlite/migrations.generated.js +17 -0
  28. package/dist/store/sqlite/schema.d.ts +252 -0
  29. package/dist/store/sqlite/schema.js +28 -0
  30. package/dist/store/sqlite/tracker.d.ts +82 -0
  31. package/dist/store/sqlite/tracker.js +210 -0
  32. package/dist/store/store.d.ts +3 -0
  33. package/dist/store/store.js +5 -0
  34. package/dist/tracker/cli/index.d.ts +24 -0
  35. package/dist/tracker/cli/index.js +279 -0
  36. package/dist/tracker/index.d.ts +8 -0
  37. package/dist/tracker/index.js +7 -0
  38. package/dist/tracker/manifest/manifest.d.ts +76 -0
  39. package/dist/tracker/manifest/manifest.js +139 -0
  40. package/dist/tracker/manifest/map.d.ts +10 -0
  41. package/dist/tracker/manifest/map.js +86 -0
  42. package/dist/tracker/manifest/source.d.ts +18 -0
  43. package/dist/tracker/manifest/source.js +174 -0
  44. package/dist/tracker/source.d.ts +55 -0
  45. package/dist/tracker/source.js +1 -0
  46. package/dist/tracker/sync.d.ts +60 -0
  47. package/dist/tracker/sync.js +254 -0
  48. package/dist/tracker/tasks.d.ts +18 -0
  49. package/dist/tracker/tasks.js +29 -0
  50. package/dist/tracker/testing/index.d.ts +2 -0
  51. package/dist/tracker/testing/index.js +2 -0
  52. package/dist/tracker/testing/source-contract.d.ts +46 -0
  53. package/dist/tracker/testing/source-contract.js +246 -0
  54. package/dist/tracker/testing/source.d.ts +31 -0
  55. package/dist/tracker/testing/source.js +141 -0
  56. package/package.json +12 -4
@@ -0,0 +1,254 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { runBudget } from "../background/budget.js";
3
+ import { TRACKER_KINDS } from "../domain/tracker.js";
4
+ const DAY = 86_400_000;
5
+ /** An id pass that would mark more than this share of a kind deleted is held: a tracker that lost rights lists none. */
6
+ const MOST_UNLISTED = 0.5;
7
+ const GUARDED_FROM = 10;
8
+ const fresh = () => ({ v: 1, token: null, round: null, passAt: 0 });
9
+ const parsed = (value) => {
10
+ try {
11
+ const found = JSON.parse(value ?? "null");
12
+ return found?.v === 1 ? found : null;
13
+ }
14
+ catch {
15
+ return null;
16
+ }
17
+ };
18
+ export const trackerCursorName = (kind) => `tracker:${kind}`;
19
+ const passName = (kind) => `tracker:${kind}:pass`;
20
+ const GAPS = "tracker:gaps";
21
+ const RESUME = "tracker:resume";
22
+ /** Thrown by `TrackerCallContext.spend` when the budget is spent; the engine turns it into a `partial` stop. */
23
+ class BudgetSpent extends Error {
24
+ why;
25
+ constructor(why) {
26
+ super(`the run's budget is spent: ${why}`);
27
+ this.why = why;
28
+ }
29
+ }
30
+ /** Reads one kind's changes from where it stood, page by page, saving each page and the cursor after it. */
31
+ const syncChanges = async (run, kind, result, mode) => {
32
+ const { source, store, account, budget } = run;
33
+ const name = trackerCursorName(kind);
34
+ let cursor = parsed((await store.sync.syncState(account, name))?.value) ?? fresh();
35
+ let round = mode.drop
36
+ ? { from: null, page: null }
37
+ : (cursor.round ?? { from: mode.full ? null : cursor.token, page: null });
38
+ const save = (patch) => {
39
+ cursor = { ...cursor, ...patch };
40
+ return store.sync.setSyncState(account, name, JSON.stringify(cursor));
41
+ };
42
+ const pages = new Set();
43
+ for (;;) {
44
+ result.round = round.from === null ? "full" : "changes";
45
+ const why = budget.take();
46
+ if (why) {
47
+ await save({ round });
48
+ return why;
49
+ }
50
+ run.report.progress.requests += 1;
51
+ const page = await source.changes(kind, round.from, round.page ?? undefined, run.context);
52
+ if (run.signal?.aborted) {
53
+ await save({ round });
54
+ return "cancelled";
55
+ }
56
+ if ("reset" in page) {
57
+ if (round.from === null)
58
+ throw new CliError("invalid_response", `${source.provider} refused a full list of ${kind}s`);
59
+ result.reset = true;
60
+ round = { from: null, page: null };
61
+ pages.clear();
62
+ continue;
63
+ }
64
+ if (page.items.length) {
65
+ result.saved += await store.tracker.save(account, kind, page.items, run.now);
66
+ run.report.progress.saved += page.items.length;
67
+ }
68
+ run.report.progress.steps += 1;
69
+ if (!page.hasMore) {
70
+ await save({ token: page.cursor ?? null, round: null });
71
+ return null;
72
+ }
73
+ if (page.nextCursor === undefined)
74
+ throw new CliError("invalid_response", `${source.provider} said there are more ${kind}s but gave no cursor`);
75
+ if (pages.has(page.nextCursor))
76
+ throw new CliError("invalid_response", `${source.provider} gave the same page of ${kind}s twice`);
77
+ pages.add(page.nextCursor);
78
+ round = { ...round, page: page.nextCursor };
79
+ await save({ round });
80
+ }
81
+ };
82
+ /**
83
+ * Lists every id of the kind and marks deleted each stored row the list lacks. Archived rows are listed, so only a row
84
+ * the tracker deleted outright goes. A pass that stops keeps its ids and goes on next run.
85
+ */
86
+ const passIds = async (run, kind, result, mode) => {
87
+ const { source, store, account, budget } = run;
88
+ const name = passName(kind);
89
+ const pending = mode.drop ? null : parsed((await store.sync.syncState(account, name))?.value);
90
+ let pass = pending ?? {
91
+ v: 1,
92
+ started: run.now,
93
+ page: null,
94
+ ids: [],
95
+ };
96
+ for (;;) {
97
+ const why = budget.take();
98
+ if (why) {
99
+ await store.sync.setSyncState(account, name, JSON.stringify(pass));
100
+ result.pass = "partial";
101
+ return why;
102
+ }
103
+ run.report.progress.requests += 1;
104
+ const page = await source.ids(kind, pass.page ?? undefined, run.context);
105
+ if (run.signal?.aborted) {
106
+ await store.sync.setSyncState(account, name, JSON.stringify(pass));
107
+ result.pass = "partial";
108
+ return "cancelled";
109
+ }
110
+ pass = { ...pass, ids: [...pass.ids, ...page.items] };
111
+ if (page.hasMore) {
112
+ // A pass that ended early would mark every unread row deleted.
113
+ if (page.nextCursor === undefined || page.nextCursor === pass.page)
114
+ throw new CliError("invalid_response", `${source.provider} gave no new page of ${kind} ids`);
115
+ pass = { ...pass, page: page.nextCursor };
116
+ await store.sync.setSyncState(account, name, JSON.stringify(pass));
117
+ continue;
118
+ }
119
+ const stored = await store.tracker.count(account, kind);
120
+ const unlisted = await store.tracker.removeUnlisted(account, kind, pass.ids, pass.started, run.now, {
121
+ dryRun: true,
122
+ });
123
+ const unread = run.report.gaps.some((gap) => gap.kind === kind);
124
+ const emptied = pass.ids.length === 0 && unlisted > 0;
125
+ const many = emptied || (stored >= GUARDED_FROM && unlisted > stored * MOST_UNLISTED);
126
+ // What the sign-in could not read is not gone: even a rescan never marks it deleted.
127
+ if (unlisted > 0 && (unread || (many && !mode.full))) {
128
+ result.pass = "held";
129
+ result.held = unread
130
+ ? `${source.provider} could not read all ${kind}s, so the ${unlisted} it did not list stay; nothing was ` +
131
+ "marked deleted. Check the sign-in's rights, then run sync again"
132
+ : `${source.provider} listed ${pass.ids.length} ${kind} ids, so ${unlisted} of the ${stored} stored would be ` +
133
+ "marked deleted; nothing was. Check the sign-in's rights, then run sync --rescan to let it through";
134
+ }
135
+ else {
136
+ result.unlisted += await store.tracker.removeUnlisted(account, kind, pass.ids, pass.started, run.now);
137
+ result.pass = "complete";
138
+ }
139
+ await store.sync.setSyncState(account, name, "null");
140
+ const cursor = parsed((await store.sync.syncState(account, trackerCursorName(kind)))?.value) ?? fresh();
141
+ await store.sync.setSyncState(account, trackerCursorName(kind), JSON.stringify({ ...cursor, passAt: pass.started }));
142
+ return null;
143
+ }
144
+ };
145
+ const stopping = async (step) => {
146
+ try {
147
+ return await step();
148
+ }
149
+ catch (error) {
150
+ if (error instanceof BudgetSpent)
151
+ return error.why;
152
+ throw error;
153
+ }
154
+ };
155
+ /**
156
+ * Brings one tracker account's copy up to date: each kind's changes since its cursor, then, once a day, a pass over
157
+ * every id that marks deleted what the tracker no longer has. A run that hits its budget stops where it is, saved,
158
+ * and the next one goes on from there. A kind that fails is named and the others still sync.
159
+ */
160
+ export const syncTracker = async (source, store, account, options = {}) => {
161
+ const now = options.now ?? Date.now();
162
+ const budget = options.budget ?? runBudget();
163
+ const passEvery = options.passEvery ?? DAY;
164
+ const report = {
165
+ provider: source.provider,
166
+ account: account.account,
167
+ synced: [],
168
+ gaps: [],
169
+ complete: true,
170
+ state: "complete",
171
+ progress: { requests: 0, saved: 0, steps: 0 },
172
+ };
173
+ const said = new Set();
174
+ const run = {
175
+ source,
176
+ store,
177
+ account,
178
+ now,
179
+ budget,
180
+ ...(options.signal ? { signal: options.signal } : {}),
181
+ report,
182
+ context: {
183
+ spend: () => {
184
+ const why = budget.take();
185
+ if (why)
186
+ throw new BudgetSpent(why);
187
+ report.progress.requests += 1;
188
+ },
189
+ gap: (gap) => {
190
+ const key = `${gap.kind} ${gap.message}`;
191
+ if (said.has(key))
192
+ return;
193
+ said.add(key);
194
+ report.gaps.push(gap);
195
+ },
196
+ },
197
+ };
198
+ const kinds = TRACKER_KINDS.filter((one) => source.traits.kinds.includes(one));
199
+ // A budget smaller than the kinds would spend itself re-reading the finished ones: a run that stopped leaves the kinds
200
+ // it finished, and the next one goes on with the rest.
201
+ const resumed = options.rescan
202
+ ? null
203
+ : parsed((await store.sync.syncState(account, RESUME))?.value);
204
+ const done = new Set(resumed?.done ?? []);
205
+ // A stopped rescan goes on as one: the kinds it had not reached still get their full list and their id pass.
206
+ const mode = { drop: options.rescan === true, full: options.rescan === true || resumed?.rescan === true };
207
+ // The kinds this run skips keep the gaps the runs that read them recorded.
208
+ if (resumed)
209
+ for (const gap of await trackerGapsOf(store, account))
210
+ if (done.has(gap.kind)) {
211
+ said.add(`${gap.kind} ${gap.message}`);
212
+ report.gaps.push(gap);
213
+ }
214
+ for (const kind of kinds.filter((one) => !done.has(one))) {
215
+ const result = { kind, round: "full", reset: false, state: "partial", saved: 0, unlisted: 0 };
216
+ report.synced.push(result);
217
+ let stop;
218
+ try {
219
+ stop = await stopping(() => syncChanges(run, kind, result, mode));
220
+ const cursor = parsed((await store.sync.syncState(account, trackerCursorName(kind)))?.value);
221
+ const pending = parsed((await store.sync.syncState(account, passName(kind)))?.value);
222
+ const due = mode.full || pending !== null || now - (cursor?.passAt ?? 0) >= passEvery;
223
+ if (!stop && due)
224
+ stop = await stopping(() => passIds(run, kind, result, mode));
225
+ }
226
+ catch (error) {
227
+ result.error = error instanceof Error ? error.message : String(error);
228
+ report.complete = false;
229
+ report.state = "partial";
230
+ continue;
231
+ }
232
+ if (stop) {
233
+ report.stopped = stop;
234
+ report.complete = false;
235
+ report.state = "partial";
236
+ break;
237
+ }
238
+ result.state = "complete";
239
+ done.add(kind);
240
+ }
241
+ await store.sync.setSyncState(account, RESUME, report.stopped ? JSON.stringify({ v: 1, done: [...done], ...(mode.full ? { rescan: true } : {}) }) : "null");
242
+ await store.sync.setSyncState(account, GAPS, JSON.stringify(report.gaps));
243
+ return report;
244
+ };
245
+ /** The gaps the account's last sync recorded; none before its first. */
246
+ export const trackerGapsOf = async (store, account) => {
247
+ try {
248
+ const found = JSON.parse((await store.sync.syncState(account, GAPS))?.value ?? "[]");
249
+ return Array.isArray(found) ? found : [];
250
+ }
251
+ catch {
252
+ return [];
253
+ }
254
+ };
@@ -0,0 +1,18 @@
1
+ import type { MessageStore } from "../store/store.js";
2
+ import type { AccountKey } from "../store/types.js";
3
+ import { type Task } from "../tasks/index.js";
4
+ export declare const TRACKER_ISSUE_TASK = "tracker_issue";
5
+ /** The task's locator: the issue in the tracker's copy, resolved when the task is read. */
6
+ export declare const trackerIssueSource: (externalId: string) => string;
7
+ /**
8
+ * Makes an issue the owner's task: the task points at the issue and keeps only its readable key as a title, so the
9
+ * issue's text stays in the tracker's copy and a sync that changes it changes what the task shows. The same issue
10
+ * twice answers the task it already has.
11
+ */
12
+ export declare const trackerIssueTask: (store: MessageStore, account: AccountKey, issue: string, { dueAt, now }?: {
13
+ dueAt?: Date;
14
+ now?: number;
15
+ }) => Promise<{
16
+ task: Task;
17
+ created: boolean;
18
+ }>;
@@ -0,0 +1,29 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { taskAccount } from "../services/task-rules.js";
3
+ import { createTaskService } from "../tasks/index.js";
4
+ export const TRACKER_ISSUE_TASK = "tracker_issue";
5
+ /** The task's locator: the issue in the tracker's copy, resolved when the task is read. */
6
+ export const trackerIssueSource = (externalId) => `tracker:issue/${externalId}`;
7
+ /**
8
+ * Makes an issue the owner's task: the task points at the issue and keeps only its readable key as a title, so the
9
+ * issue's text stays in the tracker's copy and a sync that changes it changes what the task shows. The same issue
10
+ * twice answers the task it already has.
11
+ */
12
+ export const trackerIssueTask = async (store, account, issue, { dueAt, now = Date.now() } = {}) => {
13
+ const found = (await store.tracker.get(account, "issue", issue)) ?? (await store.tracker.issueByKey(account, issue));
14
+ if (!found || found.deletedAt !== null)
15
+ throw new CliError("not_found", `no issue ${issue} in the copy of ${account.provider}; run sync, then try again`);
16
+ const { externalId, key } = found.record;
17
+ const { reviewDuplicates: _review, ...tasks } = store.tasks;
18
+ const { task, created } = await createTaskService({ store: tasks, now: () => new Date(now) }).add({
19
+ source: trackerIssueSource(externalId),
20
+ sourceKind: TRACKER_ISSUE_TASK,
21
+ account: taskAccount(account),
22
+ group: trackerIssueSource(externalId),
23
+ kind: "request",
24
+ origin: "owner",
25
+ title: key ?? externalId,
26
+ ...(dueAt ? { dueAt } : {}),
27
+ });
28
+ return { task, created };
29
+ };
@@ -0,0 +1,2 @@
1
+ export { exampleTrackerRows, type FakeTrackerRows, type FakeTrackerSource, type FakeTrackerSourceOptions, fakeTrackerSource, } from "./source.js";
2
+ export { type TrackerSourceFaults, type TrackerSourceFixture, trackerSourceContract, } from "./source-contract.js";
@@ -0,0 +1,2 @@
1
+ export { exampleTrackerRows, fakeTrackerSource, } from "./source.js";
2
+ export { trackerSourceContract, } from "./source-contract.js";
@@ -0,0 +1,46 @@
1
+ import { type TrackerKind } from "../../domain/tracker.js";
2
+ import type { ContractCase } from "../../meetings/index.js";
3
+ import type { TrackerSource } from "../source.js";
4
+ /** Faults a case injects; each is opt-in, and a case whose hook is absent passes without running. */
5
+ export interface TrackerSourceFaults {
6
+ /** A source over the same tracker whose own clock runs `ms` ahead of the tracker's, behind when negative. */
7
+ skewed?(ms: number): TrackerSource | Promise<TrackerSource>;
8
+ /** Changes one row on the tracker's side, for the next `changes()` to list. */
9
+ change?(): {
10
+ kind: TrackerKind;
11
+ id: string;
12
+ } | Promise<{
13
+ kind: TrackerKind;
14
+ id: string;
15
+ }>;
16
+ /** Archives one row on the tracker's side: it stays, listed with `archivedAt`. */
17
+ archive?(): {
18
+ kind: TrackerKind;
19
+ id: string;
20
+ } | Promise<{
21
+ kind: TrackerKind;
22
+ id: string;
23
+ }>;
24
+ /** Deletes one row on the tracker's side outright. */
25
+ remove?(): {
26
+ kind: TrackerKind;
27
+ id: string;
28
+ } | Promise<{
29
+ kind: TrackerKind;
30
+ id: string;
31
+ }>;
32
+ }
33
+ /** One adapter over recorded or faked answers, fresh for each case. Every kind its traits name lists at least one row. */
34
+ export interface TrackerSourceFixture {
35
+ source: TrackerSource;
36
+ /** The ids of every row of each kind, each changed before the overlap: a full list gives back each of them. */
37
+ held?: Partial<Record<TrackerKind, readonly string[]>>;
38
+ /** A cursor the tracker refuses; absent skips that case. */
39
+ deadCursor?: {
40
+ kind: TrackerKind;
41
+ cursor: string;
42
+ };
43
+ faults?: TrackerSourceFaults;
44
+ }
45
+ /** What every tracker adapter answers, whatever the tracker: run each case in the adapter's tests. */
46
+ export declare const trackerSourceContract: (make: () => TrackerSourceFixture | Promise<TrackerSourceFixture>) => ContractCase[];
@@ -0,0 +1,246 @@
1
+ import assert from "node:assert/strict";
2
+ import { CliError } from "@wirecat/cli-base";
3
+ import { STATE_TYPES } from "../../domain/tracker.js";
4
+ /** Within any change feed's overlap: a computer's clock that is off by more is broken, not skewed. */
5
+ const SKEW_MS = 10 * 60_000;
6
+ const MAX_PAGES = 1_000;
7
+ const DAY = /^\d{4}-\d{2}-\d{2}$/;
8
+ const idsOf = (items) => items.map((item) => item.externalId);
9
+ /** Every page of one kind from `cursor`, checking each page is new and the last one gives a cursor. */
10
+ const listAll = async (source, kind, cursor) => {
11
+ const items = [];
12
+ const pages = new Set();
13
+ let page;
14
+ for (let read = 0; read < MAX_PAGES; read += 1) {
15
+ const answer = await source.changes(kind, cursor, page);
16
+ assert.ok(!("reset" in answer), `${kind}: a full list is never a dead cursor`);
17
+ const listed = answer;
18
+ assert.ok(Array.isArray(listed.items), `${kind}: a page has items`);
19
+ items.push(...listed.items);
20
+ assert.equal(listed.hasMore, listed.nextCursor !== undefined, `${kind}: a next cursor exactly when there is more`);
21
+ if (!listed.hasMore) {
22
+ assert.ok(listed.cursor === null || typeof listed.cursor === "string", `${kind}: the last page gives a cursor`);
23
+ return { items, cursor: listed.cursor ?? null };
24
+ }
25
+ const next = listed.nextCursor;
26
+ assert.ok(!pages.has(next), `${kind}: the same page twice`);
27
+ pages.add(next);
28
+ page = next;
29
+ }
30
+ throw new assert.AssertionError({ message: `${kind}: more than ${MAX_PAGES} pages` });
31
+ };
32
+ const allIds = async (source, kind) => {
33
+ const listed = new Set();
34
+ let page;
35
+ for (let read = 0; read < MAX_PAGES; read += 1) {
36
+ const answer = await source.ids(kind, page);
37
+ for (const id of answer.items)
38
+ listed.add(id);
39
+ if (!answer.hasMore)
40
+ return listed;
41
+ assert.ok(answer.nextCursor !== undefined && answer.nextCursor !== page, `${kind}: ids() gives a new page`);
42
+ page = answer.nextCursor;
43
+ }
44
+ throw new assert.AssertionError({ message: `${kind}: more than ${MAX_PAGES} pages of ids` });
45
+ };
46
+ const optionalText = (value) => value === undefined || value === null || typeof value === "string";
47
+ const optionalTime = (value) => value === undefined || value === null || (typeof value === "number" && Number.isSafeInteger(value));
48
+ /** The shape every record of the kind keeps, in the tracker domain's fields. */
49
+ const checkShape = (kind, record) => {
50
+ const at = `${kind} ${String(record.externalId)}`;
51
+ assert.ok(typeof record.externalId === "string" && record.externalId.trim(), `${kind}: a record has an id`);
52
+ for (const field of ["createdAt", "updatedAt", "archivedAt", "completedAt", "canceledAt"])
53
+ assert.ok(optionalTime(record[field]), `${at}: ${field} is epoch ms or null`);
54
+ const named = kind === "issue" ? "title" : kind === "comment" ? "body" : "name";
55
+ assert.ok(typeof record[named] === "string", `${at} has its ${named}`);
56
+ if (kind === "state")
57
+ assert.ok(STATE_TYPES.includes(String(record.type)), `${at}: type is one of ${STATE_TYPES}`);
58
+ if (kind === "comment")
59
+ assert.ok(typeof record.issue === "string", `${at} names its issue`);
60
+ for (const field of ["team", "state", "project", "assignee", "creator", "lead", "author", "parent", "key", "email"])
61
+ assert.ok(optionalText(record[field]), `${at}: ${field} is an id or text, or null`);
62
+ for (const field of ["labels", "teams"])
63
+ if (record[field] !== undefined)
64
+ assert.ok(Array.isArray(record[field]) && record[field].every((one) => typeof one === "string"), `${at}: ${field} is a list of ids`);
65
+ for (const field of ["dueDate", "targetDate"])
66
+ if (record[field] !== undefined && record[field] !== null)
67
+ assert.match(String(record[field]), DAY, `${at}: ${field} is YYYY-MM-DD`);
68
+ if (record.priority !== undefined && record.priority !== null)
69
+ assert.ok(Number.isFinite(record.priority), `${at}: priority is a number`);
70
+ };
71
+ /** What every tracker adapter answers, whatever the tracker: run each case in the adapter's tests. */
72
+ export const trackerSourceContract = (make) => [
73
+ {
74
+ name: "changes: a full list pages to its end, each record in the tracker domain's shape",
75
+ async run() {
76
+ const { source } = await make();
77
+ assert.ok(source.traits.kinds.length > 0, "the tracker names its kinds");
78
+ const listed = new Map();
79
+ for (const kind of source.traits.kinds) {
80
+ const { items } = await listAll(source, kind, null);
81
+ assert.ok(items.length > 0, `${kind}: the fixture lists at least one`);
82
+ for (const item of items)
83
+ checkShape(kind, item);
84
+ const ids = idsOf(items);
85
+ assert.equal(new Set(ids).size, ids.length, `${kind}: no row twice in one full list`);
86
+ listed.set(kind, new Set(ids));
87
+ }
88
+ // An issue's state and team, when both kinds are read, are rows the copy will hold.
89
+ for (const issue of listed.has("issue") ? (await listAll(source, "issue", null)).items : [])
90
+ for (const [field, kind] of [
91
+ ["state", "state"],
92
+ ["team", "team"],
93
+ ]) {
94
+ const id = issue[field];
95
+ if (typeof id === "string" && listed.has(kind))
96
+ assert.ok(listed.get(kind)?.has(id), `issue ${issue.externalId}: its ${field} ${id} is listed`);
97
+ }
98
+ },
99
+ },
100
+ {
101
+ name: "changes: a full list gives every row the fixture holds, none lost between the tracker's pages",
102
+ async run() {
103
+ const { source, held } = await make();
104
+ if (!held)
105
+ return;
106
+ for (const kind of source.traits.kinds) {
107
+ const ids = held[kind];
108
+ if (!ids)
109
+ continue;
110
+ assert.deepEqual(idsOf((await listAll(source, kind, null)).items).sort(), [...ids].sort(), `${kind}: every row`);
111
+ }
112
+ },
113
+ },
114
+ {
115
+ name: "changes: the cursor a full list gave reads again without failing",
116
+ async run() {
117
+ const { source } = await make();
118
+ for (const kind of source.traits.kinds) {
119
+ const { cursor } = await listAll(source, kind, null);
120
+ if (cursor !== null)
121
+ await listAll(source, kind, cursor);
122
+ }
123
+ },
124
+ },
125
+ {
126
+ name: "ids: a list of every id holds every row a full list gave",
127
+ async run() {
128
+ const { source } = await make();
129
+ for (const kind of source.traits.kinds) {
130
+ const listed = await allIds(source, kind);
131
+ for (const id of idsOf((await listAll(source, kind, null)).items))
132
+ assert.ok(listed.has(id), `${kind} ${id} is missing from ids()`);
133
+ }
134
+ },
135
+ },
136
+ {
137
+ name: "changes: a dead cursor answers reset",
138
+ async run() {
139
+ const { source, deadCursor } = await make();
140
+ if (!deadCursor)
141
+ return;
142
+ const answer = await source.changes(deadCursor.kind, deadCursor.cursor);
143
+ assert.ok("reset" in answer, `${deadCursor.kind}: a cursor the tracker refuses answers reset`);
144
+ },
145
+ },
146
+ {
147
+ name: "faults: a clock off by ten minutes either way loses no change",
148
+ async run() {
149
+ for (const ms of [SKEW_MS, -SKEW_MS]) {
150
+ const { faults, held } = await make();
151
+ if (!faults?.skewed || !faults.change)
152
+ return;
153
+ const source = await faults.skewed(ms);
154
+ const cursors = new Map();
155
+ for (const kind of source.traits.kinds)
156
+ cursors.set(kind, (await listAll(source, kind, null)).cursor);
157
+ const { kind, id } = await faults.change();
158
+ const cursor = cursors.get(kind) ?? null;
159
+ assert.ok(cursor !== null, `${kind}: a full list gives a cursor for the change to be read after`);
160
+ const { items } = await listAll(source, kind, cursor);
161
+ assert.ok(idsOf(items).includes(id), `${kind} ${id} is in the changes with the clock ${ms / 60_000} min off`);
162
+ for (const one of held?.[kind]?.filter((other) => other !== id) ?? [])
163
+ assert.ok(!idsOf(items).includes(one), `${kind} ${one} did not change, yet a read of changes lists it`);
164
+ }
165
+ },
166
+ },
167
+ {
168
+ name: "faults: an archived row is still listed, in changes and ids, with its archive time",
169
+ async run() {
170
+ const { source, faults } = await make();
171
+ if (!faults?.archive)
172
+ return;
173
+ const cursors = new Map();
174
+ for (const kind of source.traits.kinds)
175
+ cursors.set(kind, (await listAll(source, kind, null)).cursor);
176
+ const { kind, id } = await faults.archive();
177
+ const { items } = await listAll(source, kind, cursors.get(kind) ?? null);
178
+ const found = items.find((one) => one.externalId === id);
179
+ assert.ok(found, `${kind} ${id}: an archived row is in the changes`);
180
+ assert.ok(typeof found.archivedAt === "number", `${kind} ${id} carries archivedAt`);
181
+ assert.ok((await allIds(source, kind)).has(id), `${kind} ${id}: an archived row is still in ids()`);
182
+ },
183
+ },
184
+ {
185
+ name: "faults: a row deleted outright leaves ids()",
186
+ async run() {
187
+ const { source, faults } = await make();
188
+ if (!faults?.remove)
189
+ return;
190
+ const { kind, id } = await faults.remove();
191
+ assert.ok(!(await allIds(source, kind)).has(id), `${kind} ${id}: a deleted row is not in ids()`);
192
+ },
193
+ },
194
+ {
195
+ name: "faults: a full list cut after its first page goes on from that page in a new run, nothing lost or repeated",
196
+ async run() {
197
+ const { source, faults } = await make();
198
+ if (!faults)
199
+ return;
200
+ let cut = false;
201
+ for (const kind of source.traits.kinds) {
202
+ const whole = idsOf((await listAll(source, kind, null)).items);
203
+ const first = (await source.changes(kind, null));
204
+ if (!first.hasMore)
205
+ continue;
206
+ cut = true;
207
+ const { source: resumed } = await make();
208
+ const rest = [];
209
+ let page = first.nextCursor;
210
+ for (let read = 0; page !== undefined && read < MAX_PAGES; read += 1) {
211
+ const answer = (await resumed.changes(kind, null, page));
212
+ rest.push(...answer.items);
213
+ page = answer.nextCursor;
214
+ }
215
+ const joined = [...idsOf(first.items), ...idsOf(rest)];
216
+ assert.equal(new Set(joined).size, joined.length, `${kind}: no row twice across the cut`);
217
+ assert.deepEqual(joined.sort(), whole.sort(), `${kind}: the cut list adds up to the whole one`);
218
+ }
219
+ assert.ok(cut, "the fixture holds more than one page of some kind, so a list can be cut");
220
+ },
221
+ },
222
+ {
223
+ name: "faults: a call that pages inside stops when the run's budget is spent, and says so",
224
+ async run() {
225
+ const { source, faults } = await make();
226
+ if (!faults)
227
+ return;
228
+ const spent = new CliError("provider_error", "the run's budget is spent", { reason: "sync.partial" });
229
+ for (const kind of source.traits.kinds) {
230
+ let asked = false;
231
+ const context = {
232
+ spend: () => {
233
+ asked = true;
234
+ throw spent;
235
+ },
236
+ gap: () => { },
237
+ };
238
+ const ended = await source.changes(kind, null, undefined, context).then(() => undefined, (error) => error);
239
+ if (asked)
240
+ assert.equal(ended, spent, `${kind}: a spent budget ends the call with its own error`);
241
+ else
242
+ assert.equal(ended, undefined, `${kind}: a call that asks for no more requests is not stopped`);
243
+ }
244
+ },
245
+ },
246
+ ];
@@ -0,0 +1,31 @@
1
+ import type { TrackerKind, TrackerRecords } from "../../domain/tracker.js";
2
+ import type { TrackerSource } from "../source.js";
3
+ export type FakeTrackerRows = {
4
+ [K in TrackerKind]?: TrackerRecords[K][];
5
+ };
6
+ export interface FakeTrackerSourceOptions {
7
+ rows: FakeTrackerRows;
8
+ /** The tracker's own clock, which stamps `updatedAt`; this computer's is `skew` off it. */
9
+ clock?: () => number;
10
+ skew?: number;
11
+ /** Rows on one page. */
12
+ pageSize?: number;
13
+ provider?: string;
14
+ }
15
+ export interface FakeTrackerSource extends TrackerSource {
16
+ /** Changes one row on the tracker's side: it gets a new `updatedAt`. */
17
+ touch(kind: TrackerKind, externalId: string): void;
18
+ archive(kind: TrackerKind, externalId: string): void;
19
+ /** Deletes one row outright, as only an id pass finds. */
20
+ remove(kind: TrackerKind, externalId: string): void;
21
+ /** The same tracker, read from a computer whose clock is `ms` off. */
22
+ skewed(ms: number): FakeTrackerSource;
23
+ }
24
+ /**
25
+ * A tracker in memory, read the way a GraphQL tracker is: changes by `updatedAt` from the cursor less an overlap, pages
26
+ * by offset, archived rows listed with their mark, deletions only by their absence from `ids()`. One call reads one
27
+ * page, so it never spends from the run's budget itself.
28
+ */
29
+ export declare const fakeTrackerSource: (options: FakeTrackerSourceOptions) => FakeTrackerSource;
30
+ /** A small Linear-like workspace: one team, two users, the six state types, a label, a project, three issues. */
31
+ export declare const exampleTrackerRows: () => Required<FakeTrackerRows>;