@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,139 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { parseSelection } from "@wirecat/cli-base/codegen";
3
+ import * as v from "valibot";
4
+ import { crmRuleSchema } from "../../crm/manifest/manifest.js";
5
+ import { rulePaths } from "../../crm/manifest/map.js";
6
+ import { TRACKER_KINDS } from "../../domain/tracker.js";
7
+ import { editDistance } from "../../search/correct.js";
8
+ import { TRACKER_FIELDS } from "./map.js";
9
+ const path = v.pipe(v.string(), v.regex(/^[^.\s]+(\.[^.\s]+)*$/, "a dotted path such as state.id"));
10
+ const call = v.strictObject({
11
+ operation: v.pipe(v.string(), v.minLength(1)),
12
+ variables: v.optional(v.record(v.string(), v.unknown())),
13
+ selection: v.optional(v.pipe(v.string(), v.minLength(1))),
14
+ items: v.optional(path),
15
+ });
16
+ const kind = v.picklist(TRACKER_KINDS);
17
+ const schema = v.strictObject({
18
+ provider: v.pipe(v.string(), v.regex(/^[a-z][a-z0-9-]*$/, "a registry name such as linear")),
19
+ kinds: v.pipe(v.array(kind), v.minLength(1)),
20
+ overlapMs: v.optional(v.pipe(v.number(), v.integer(), v.minValue(0))),
21
+ entities: v.record(kind, v.optional(v.strictObject({
22
+ list: call,
23
+ changes: v.optional(v.strictObject({ ...call.entries, since: v.picklist(["iso", "ms", "seconds"]) })),
24
+ ids: v.optional(call),
25
+ map: v.record(v.string(), crmRuleSchema),
26
+ optional: v.optional(v.strictObject({ message: v.pipe(v.string(), v.minLength(1)), scope: v.optional(v.string()) })),
27
+ }))),
28
+ self: v.optional(v.strictObject({ call, path })),
29
+ });
30
+ const invalid = (where, message) => new CliError("configuration_error", `source manifest: ${where}: ${message}`, { reason: "manifest.invalid" });
31
+ const nearest = (wanted, known) => known
32
+ .map((one) => ({ one, edits: editDistance(wanted, one, 2) }))
33
+ .filter(({ edits }) => edits <= 2)
34
+ .sort((a, b) => a.edits - b.edits)[0]?.one;
35
+ const hasSince = (value) => value === "{since}" ||
36
+ (Array.isArray(value) && value.some(hasSince)) ||
37
+ (typeof value === "object" && value !== null && Object.values(value).some(hasSince));
38
+ /** The selection a call sends, as a tree: its own, else the operation's default; none for an operation over HTTP. */
39
+ export const selectionOf = (one, api) => {
40
+ const binding = api.operations.find((operation) => operation.id === one.operation)?.binding;
41
+ if (binding?.kind !== "graphql")
42
+ return undefined;
43
+ return parseSelection(one.selection ?? binding.selection);
44
+ };
45
+ /** Whether `path`, read in a row, is selected: each step a field the selection names, and a leaf where it ends. */
46
+ const selects = (tree, steps) => {
47
+ const [first, ...rest] = steps;
48
+ if (first === undefined)
49
+ return true;
50
+ if (/^\d+$/.test(first))
51
+ return selects(tree, rest);
52
+ const found = tree[first];
53
+ if (found === undefined)
54
+ return false;
55
+ return found === true ? rest.every((step) => /^\d+$/.test(step)) : selects(found, rest);
56
+ };
57
+ /** The selection of one row: under the operation's `items` (a connection's `nodes`) or the call's own. */
58
+ const rowSelection = (tree, items) => {
59
+ let inside = tree;
60
+ for (const step of items?.split(".") ?? [])
61
+ inside = inside === true ? undefined : inside?.[step];
62
+ return inside === true ? undefined : inside;
63
+ };
64
+ /**
65
+ * The manifest checked against its shape and the generated API: each operation exists and reads, a list pages or
66
+ * says where its rows are, a change call places `{since}`, and over GraphQL every path the map reads is selected, so
67
+ * a field is never left out of a request by mistake and read as "the tracker cleared it". Every error names where.
68
+ */
69
+ export const parseTrackerManifest = (input, api) => {
70
+ const parsed = v.safeParse(schema, input);
71
+ if (!parsed.success) {
72
+ const [issue] = parsed.issues;
73
+ throw invalid(v.getDotPath(issue) ?? "(root)", issue.message);
74
+ }
75
+ const manifest = parsed.output;
76
+ const order = manifest.kinds.map((one) => TRACKER_KINDS.indexOf(one));
77
+ if (order.some((at, index) => index > 0 && at <= order[index - 1]))
78
+ throw invalid("kinds", `list them once each, in this order: ${TRACKER_KINDS.join(", ")}`);
79
+ const operations = new Map(api.operations.map((one) => [one.id, one]));
80
+ const known = [...operations.keys()];
81
+ const checkCall = (where, one, map) => {
82
+ const operation = operations.get(one.operation);
83
+ if (!operation) {
84
+ const near = nearest(one.operation, known);
85
+ throw invalid(`${where}.operation`, `no operation ${one.operation} in the API${near ? `; did you mean ${near}?` : ""}`);
86
+ }
87
+ if (operation.effect !== "read")
88
+ throw invalid(`${where}.operation`, `${one.operation} is a ${operation.effect}, and a source only reads`);
89
+ if (operation.pagination && operation.pagination.style === "link")
90
+ throw invalid(`${where}.operation`, `${one.operation} pages by a link, which a source does not read yet`);
91
+ let tree;
92
+ try {
93
+ tree = selectionOf(one, api);
94
+ }
95
+ catch (error) {
96
+ throw invalid(`${where}.selection`, error instanceof Error ? error.message : String(error));
97
+ }
98
+ if (one.selection !== undefined && tree === undefined)
99
+ throw invalid(`${where}.selection`, `${one.operation} is not a GraphQL operation, so it takes no selection`);
100
+ if (!tree || !map)
101
+ return;
102
+ const row = rowSelection(tree, one.items ?? operation.pagination?.items);
103
+ if (!row)
104
+ throw invalid(`${where}.selection`, "selects no rows where the operation's items are");
105
+ for (const [field, rule] of Object.entries(map))
106
+ for (const { path: read, inside } of rulePaths(rule)) {
107
+ const steps = [...(inside?.split(".") ?? []), ...read.split(".")];
108
+ if (!selects(row, steps))
109
+ throw invalid(`${where}.selection`, `map.${field} reads ${steps.join(".")}, which the selection leaves out`);
110
+ }
111
+ };
112
+ for (const kind of manifest.kinds) {
113
+ const one = manifest.entities[kind];
114
+ if (!one)
115
+ throw invalid(`entities.${kind}`, `${kind} is in kinds but has no entity`);
116
+ if (one.map.externalId === undefined)
117
+ throw invalid(`entities.${kind}.map.externalId`, "every kind maps its id");
118
+ const fields = Object.keys(TRACKER_FIELDS[kind]);
119
+ for (const field of Object.keys(one.map))
120
+ if (!fields.includes(field)) {
121
+ const near = nearest(field, fields);
122
+ throw invalid(`entities.${kind}.map.${field}`, `${kind} has no such field${near ? `; did you mean ${near}?` : ""}`);
123
+ }
124
+ checkCall(`entities.${kind}.list`, one.list, one.map);
125
+ if (one.changes) {
126
+ checkCall(`entities.${kind}.changes`, one.changes, one.map);
127
+ if (!hasSince(one.changes.variables))
128
+ throw invalid(`entities.${kind}.changes`, 'no "{since}" in its variables');
129
+ }
130
+ if (one.ids)
131
+ checkCall(`entities.${kind}.ids`, one.ids, { externalId: one.map.externalId });
132
+ }
133
+ for (const [kind, one] of Object.entries(manifest.entities))
134
+ if (one && !manifest.kinds.includes(kind))
135
+ throw invalid(`entities.${kind}`, `${kind} has an entity but is not in kinds`);
136
+ if (manifest.self)
137
+ checkCall("self.call", manifest.self.call, { self: manifest.self.path });
138
+ return manifest;
139
+ };
@@ -0,0 +1,10 @@
1
+ import { crmValues } from "../../crm/index.js";
2
+ import type { CrmRule } from "../../crm/manifest/manifest.js";
3
+ import type { Conversion } from "../../crm/manifest/map.js";
4
+ import { type TrackerKind, type TrackerRecords } from "../../domain/tracker.js";
5
+ /** Each of our fields and how a value the tracker sent becomes it. */
6
+ export declare const TRACKER_FIELDS: {
7
+ readonly [K in TrackerKind]: Readonly<Record<string, Conversion>>;
8
+ };
9
+ /** One row as our record of the kind, or null for a row without an id, or a state whose type is none of ours. */
10
+ export declare const mapTrackerRecord: <K extends TrackerKind>(kind: K, map: Readonly<Record<string, CrmRule | undefined>>, raw: crmValues.CrmRaw) => TrackerRecords[K] | null;
@@ -0,0 +1,86 @@
1
+ import { crmValues } from "../../crm/index.js";
2
+ import { convert, mapFields, rulePaths } from "../../crm/manifest/map.js";
3
+ import { STATE_TYPES } from "../../domain/tracker.js";
4
+ const TIMES = { externalId: "id", createdAt: "epoch", updatedAt: "epoch", archivedAt: "epoch" };
5
+ // A literal after `key:` reads as a permission key to src/cli/permission-keys.test.ts.
6
+ const KEY = "text";
7
+ /** Each of our fields and how a value the tracker sent becomes it. */
8
+ export const TRACKER_FIELDS = {
9
+ team: { ...TIMES, name: "text", key: KEY },
10
+ user: { ...TIMES, name: "text", email: "text", active: "bool" },
11
+ state: { ...TIMES, name: "text", type: "text", team: "id", position: "number" },
12
+ label: { ...TIMES, name: "text", team: "id" },
13
+ project: {
14
+ ...TIMES,
15
+ name: "text",
16
+ description: "text",
17
+ status: "text",
18
+ lead: "id",
19
+ teams: "ids",
20
+ targetDate: "day",
21
+ url: "text",
22
+ },
23
+ issue: {
24
+ ...TIMES,
25
+ title: "text",
26
+ key: KEY,
27
+ description: "text",
28
+ state: "id",
29
+ team: "id",
30
+ project: "id",
31
+ assignee: "id",
32
+ creator: "id",
33
+ labels: "ids",
34
+ parent: "id",
35
+ priority: "number",
36
+ dueDate: "day",
37
+ completedAt: "epoch",
38
+ canceledAt: "epoch",
39
+ url: "text",
40
+ },
41
+ comment: { ...TIMES, issue: "id", body: "text", author: "id", url: "text" },
42
+ };
43
+ /** The fields a record of the kind always has; a missing one gets its empty value, never a guess. */
44
+ const REQUIRED = {
45
+ team: { name: "" },
46
+ user: { name: "" },
47
+ state: { name: "" },
48
+ label: { name: "" },
49
+ project: { name: "" },
50
+ issue: { title: "" },
51
+ comment: { body: "" },
52
+ };
53
+ /** A selected object the tracker answered null (`project: null`): the field is none, not "not sent". */
54
+ const nulled = (raw, path) => {
55
+ let inner = raw;
56
+ for (const step of path.split(".")) {
57
+ if (inner === null)
58
+ return true;
59
+ if (!crmValues.isRaw(inner))
60
+ return false;
61
+ inner = inner[step];
62
+ }
63
+ return false;
64
+ };
65
+ /** One row as our record of the kind, or null for a row without an id, or a state whose type is none of ours. */
66
+ export const mapTrackerRecord = (kind, map, raw) => {
67
+ const out = mapFields(map, TRACKER_FIELDS[kind], raw);
68
+ for (const [field, rule] of Object.entries(map)) {
69
+ const type = TRACKER_FIELDS[kind][field];
70
+ if (out[field] !== undefined || type === undefined)
71
+ continue;
72
+ if (rulePaths(rule).some(({ path, inside }) => inside === undefined && nulled(raw, path)))
73
+ out[field] = convert(type, null);
74
+ }
75
+ if (typeof out.externalId !== "string")
76
+ return null;
77
+ for (const [field, empty] of Object.entries(REQUIRED[kind]))
78
+ if (out[field] == null)
79
+ out[field] = empty;
80
+ // "Open work" is read by the type, so a state of an unknown type would hide its issues from every filter.
81
+ if (kind === "state" && !STATE_TYPES.includes(out.type))
82
+ return null;
83
+ if (kind === "comment" && typeof out.issue !== "string")
84
+ return null;
85
+ return out;
86
+ };
@@ -0,0 +1,18 @@
1
+ import type { ServiceApiCall } from "../../cli/service-api-call.js";
2
+ import { type ServiceApiManifest } from "../../cli/service-api-manifest.js";
3
+ import type { TrackerSource } from "../source.js";
4
+ import { type TrackerManifestHooks } from "./manifest.js";
5
+ export interface TrackerManifestSourceOptions {
6
+ /** The generated API manifest the operations are named in: their bindings, paging and sign-in. */
7
+ api: ServiceApiManifest;
8
+ /** Sends one operation: `serviceApiCall` over the CLI's fetch and token, or a test's fake. */
9
+ call: ServiceApiCall;
10
+ now?: () => number;
11
+ hooks?: TrackerManifestHooks;
12
+ }
13
+ /**
14
+ * A `TrackerSource` read from a manifest: each kind listed and read for changes by the operations it names, paged by
15
+ * each operation's own `pagination`, each row mapped onto the tracker domain. Deletions are found by a pass over
16
+ * every id. What the manifest cannot say comes from `hooks`.
17
+ */
18
+ export declare const trackerSourceFromManifest: (input: unknown, options: TrackerManifestSourceOptions) => TrackerSource;
@@ -0,0 +1,174 @@
1
+ import { CliError, isCliError } from "@wirecat/cli-base";
2
+ import { nextPage, parameterValue, withValue } from "../../cli/service-api-manifest.js";
3
+ import { crmValues } from "../../crm/index.js";
4
+ import { at, evaluate, MISSING } from "../../crm/manifest/map.js";
5
+ import { parseTrackerManifest, } from "./manifest.js";
6
+ import { mapTrackerRecord } from "./map.js";
7
+ const OVERLAP_MS = 10 * 60_000;
8
+ const DROP = Symbol("drop");
9
+ const fill = (value, since) => {
10
+ if (value === "{since}")
11
+ return since ?? DROP;
12
+ if (Array.isArray(value))
13
+ return value.map((one) => fill(one, since)).filter((one) => one !== DROP);
14
+ if (crmValues.isRaw(value))
15
+ return Object.fromEntries(Object.entries(value).flatMap(([key, one]) => {
16
+ const filled = fill(one, since);
17
+ return filled === DROP ? [] : [[key, filled]];
18
+ }));
19
+ return value;
20
+ };
21
+ /** The variables travel as the body: each GraphQL argument is a body parameter of the operation. */
22
+ const inputOf = (call, since) => ({
23
+ path: {},
24
+ query: {},
25
+ headers: {},
26
+ fields: {},
27
+ ...(call.variables ? { body: JSON.stringify(fill(call.variables, since)) } : {}),
28
+ ...(call.selection ? { selection: call.selection } : {}),
29
+ });
30
+ const SINCE = {
31
+ iso: (ms) => new Date(ms).toISOString(),
32
+ ms: (ms) => String(ms),
33
+ seconds: (ms) => String(Math.floor(ms / 1000)),
34
+ };
35
+ const cursorParameter = (pagination) => pagination.style === "cursor"
36
+ ? pagination.cursor
37
+ : pagination.style === "offset"
38
+ ? pagination.offset
39
+ : pagination.style === "page"
40
+ ? pagination.page
41
+ : undefined;
42
+ /** `<the tracker's page token>@<when the round started>`: a round spread over runs ends with its first page's time. */
43
+ const pageOf = (page, now) => {
44
+ const cut = page?.lastIndexOf("@") ?? -1;
45
+ const started = Number(page?.slice(cut + 1));
46
+ if (page === undefined || cut < 0 || !Number.isSafeInteger(started))
47
+ return { token: undefined, started: now };
48
+ return { token: page.slice(0, cut) || undefined, started };
49
+ };
50
+ /**
51
+ * A `TrackerSource` read from a manifest: each kind listed and read for changes by the operations it names, paged by
52
+ * each operation's own `pagination`, each row mapped onto the tracker domain. Deletions are found by a pass over
53
+ * every id. What the manifest cannot say comes from `hooks`.
54
+ */
55
+ export const trackerSourceFromManifest = (input, options) => {
56
+ const manifest = parseTrackerManifest(input, options.api);
57
+ const now = options.now ?? Date.now;
58
+ const hooks = options.hooks ?? {};
59
+ const overlap = manifest.overlapMs ?? OVERLAP_MS;
60
+ const operations = new Map(options.api.operations.map((one) => [one.id, one]));
61
+ /** The engine paid for a call's first request; each further one is spent from the run's budget. */
62
+ const metered = (context) => {
63
+ let paid = false;
64
+ return (operation, request) => {
65
+ if (paid)
66
+ context?.spend();
67
+ paid = true;
68
+ return options.call(operation, request);
69
+ };
70
+ };
71
+ const readPage = async (call, since, token, send) => {
72
+ const pagination = operations.get(call.operation)?.pagination;
73
+ const parameter = pagination && cursorParameter(pagination);
74
+ let request = inputOf(call, since);
75
+ if (token !== undefined && parameter)
76
+ request = { ...withValue(request, parameter, pagination.style === "cursor" ? token : Number(token)) };
77
+ const answer = await send(call.operation, request);
78
+ if (!pagination || !parameter) {
79
+ const listed = call.items === undefined ? answer : at(answer, call.items);
80
+ return { rows: crmValues.rawsOf(listed), next: undefined };
81
+ }
82
+ const step = nextPage(pagination, request, answer);
83
+ const rows = crmValues.rawsOf(call.items === undefined ? step.items : at(answer, call.items));
84
+ const value = step.next && "input" in step.next ? parameterValue(step.next.input, parameter) : undefined;
85
+ return { rows, next: value === undefined || value === null ? undefined : String(value) };
86
+ };
87
+ const entityOf = (kind) => {
88
+ const found = manifest.entities[kind];
89
+ if (!found)
90
+ throw new CliError("configuration_error", `the source manifest has no ${kind}`);
91
+ return found;
92
+ };
93
+ /** A refusal of a kind the manifest marks optional is a gap; the other kinds still sync. */
94
+ const optionalRefused = (kind, error, context) => {
95
+ const optional = manifest.entities[kind]?.optional;
96
+ if (!optional || !isCliError(error) || error.code !== "permission_error")
97
+ return false;
98
+ context?.gap({ kind, message: optional.message, ...(optional.scope ? { scope: optional.scope } : {}) });
99
+ return true;
100
+ };
101
+ const mapped = async (kind, rows, send) => {
102
+ const entity = entityOf(kind);
103
+ const after = hooks.after?.[kind];
104
+ const records = [];
105
+ for (const raw of rows) {
106
+ const record = mapTrackerRecord(kind, entity.map, raw);
107
+ if (record !== null)
108
+ records.push(after ? await after(record, raw, { call: send }) : record);
109
+ }
110
+ return records;
111
+ };
112
+ const readChanges = async (kind, cursor, page, context) => {
113
+ const entity = entityOf(kind);
114
+ const since = cursor === null ? null : Date.parse(cursor);
115
+ if (since !== null && Number.isNaN(since))
116
+ return { reset: true };
117
+ const { token, started } = pageOf(page, now());
118
+ const send = metered(context);
119
+ const changes = since !== null ? entity.changes : undefined;
120
+ const { rows, next } = await readPage(changes ?? entity.list, changes && since !== null ? SINCE[changes.since](since - overlap) : undefined, token, send);
121
+ const items = await mapped(kind, rows, send);
122
+ return next === undefined
123
+ ? { items, hasMore: false, cursor: new Date(started).toISOString() }
124
+ : { items, hasMore: true, nextCursor: `${next}@${started}` };
125
+ };
126
+ const readIds = async (kind, page, context) => {
127
+ const entity = entityOf(kind);
128
+ const { rows, next } = await readPage(entity.ids ?? entity.list, undefined, page, metered(context));
129
+ const rule = entity.map.externalId;
130
+ const items = rows.flatMap((raw) => {
131
+ const found = evaluate(rule, raw);
132
+ const externalId = found === MISSING ? null : crmValues.id(found);
133
+ return externalId === null ? [] : [externalId];
134
+ });
135
+ return next === undefined ? { items, hasMore: false } : { items, hasMore: true, nextCursor: next };
136
+ };
137
+ const base = {
138
+ provider: manifest.provider,
139
+ traits: { kinds: manifest.kinds },
140
+ async changes(kind, cursor, page, context) {
141
+ try {
142
+ return await readChanges(kind, cursor, page, context);
143
+ }
144
+ catch (error) {
145
+ if (optionalRefused(kind, error, context))
146
+ return { items: [], hasMore: false, cursor: null };
147
+ throw error;
148
+ }
149
+ },
150
+ async ids(kind, page, context) {
151
+ try {
152
+ return await readIds(kind, page, context);
153
+ }
154
+ catch (error) {
155
+ // Refused part way through a pass, the ids read so far would mark every unread row deleted.
156
+ if (page === undefined && optionalRefused(kind, error, context))
157
+ return { items: [], hasMore: false };
158
+ throw error;
159
+ }
160
+ },
161
+ ...(manifest.self
162
+ ? {
163
+ async self(context) {
164
+ const self = manifest.self;
165
+ const found = crmValues.id(at(await metered(context)(self.call.operation, inputOf(self.call)), self.path));
166
+ if (found === null)
167
+ throw new CliError("invalid_response", `${manifest.provider} named no signed-in user`);
168
+ return found;
169
+ },
170
+ }
171
+ : {}),
172
+ };
173
+ return { ...base, ...hooks.extend?.(base) };
174
+ };
@@ -0,0 +1,55 @@
1
+ import type { TrackerKind, TrackerRecords } from "../domain/tracker.js";
2
+ export interface TrackerSourceTraits {
3
+ /** What this tracker has, in `TRACKER_KINDS` order: one without labels leaves `label` out. */
4
+ kinds: readonly TrackerKind[];
5
+ }
6
+ export interface TrackerPage<T> {
7
+ items: T[];
8
+ /** More pages in this round, read from `nextCursor`. */
9
+ hasMore: boolean;
10
+ nextCursor?: string;
11
+ /** On the last page: the cursor the next run reads changes after; `null` when the tracker keeps none. */
12
+ cursor?: string | null;
13
+ }
14
+ /** `reset`: the cursor is dead, and the kind must be listed in full again. */
15
+ export type TrackerChanges<T> = TrackerPage<T> | {
16
+ reset: true;
17
+ };
18
+ export interface TrackerIdPage {
19
+ items: string[];
20
+ hasMore: boolean;
21
+ nextCursor?: string;
22
+ }
23
+ /** What the last sync could not read, so an answer can name it: a kind the sign-in's scope refused. */
24
+ export interface TrackerGap {
25
+ kind: TrackerKind;
26
+ message: string;
27
+ scope?: string;
28
+ }
29
+ /** What the engine hands every source call; a source that ignores it works as before. */
30
+ export interface TrackerCallContext {
31
+ /** Takes one request from the run's budget for each request beyond the first; throws once it is spent. */
32
+ spend(): void;
33
+ /** Says what the call could not read without failing it. */
34
+ gap(gap: TrackerGap): void;
35
+ }
36
+ /**
37
+ * One tracker account, as an adapter reads it. Archived rows are listed, with `archivedAt`: the copy keeps them marked.
38
+ * A row the tracker deleted outright is found by `ids()`, a list of every id that exists, archived ones too.
39
+ */
40
+ export interface TrackerSource {
41
+ /** The registry name: `linear`. */
42
+ readonly provider: string;
43
+ readonly traits: TrackerSourceTraits;
44
+ /** The sign-in's own user id, which `mine` filters read; absent, the tracker cannot say. */
45
+ self?(context?: TrackerCallContext): Promise<string>;
46
+ /**
47
+ * What changed since `cursor`, a page at a time; `cursor: null` lists everything. A tracker without a change feed
48
+ * reads by its own modified time, with an overlap, and gives back as the last page's cursor the time the round's
49
+ * first page was read, never the last one's: a round spread over runs must not skip what changed while it ran.
50
+ * `page` tokens carry that time along.
51
+ */
52
+ changes<K extends TrackerKind>(kind: K, cursor: string | null, page?: string, context?: TrackerCallContext): Promise<TrackerChanges<TrackerRecords[K]>>;
53
+ /** Every id the tracker holds of the kind, archived ones too, a page at a time: how deletions are found. */
54
+ ids(kind: TrackerKind, page?: string, context?: TrackerCallContext): Promise<TrackerIdPage>;
55
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,60 @@
1
+ import { type BudgetStop, type RunBudget } from "../background/budget.js";
2
+ import { type TrackerKind } from "../domain/tracker.js";
3
+ import type { MessageStore } from "../store/store.js";
4
+ import type { AccountKey } from "../store/types.js";
5
+ import type { TrackerGap, TrackerSource } from "./source.js";
6
+ export declare const trackerCursorName: (kind: TrackerKind) => string;
7
+ export interface TrackerSyncOptions {
8
+ now?: number;
9
+ /** List everything again and every id, dropping a round in progress: `sync --rescan`. */
10
+ rescan?: boolean;
11
+ /** Asked before every request; without one the run goes until every kind is done. */
12
+ budget?: RunBudget;
13
+ signal?: AbortSignal;
14
+ /** How long a complete id pass holds before the next one; a day when absent. */
15
+ passEvery?: number;
16
+ }
17
+ export interface TrackerSyncResult {
18
+ kind: TrackerKind;
19
+ /** `full`: everything was listed; `changes`: only what changed since the cursor. */
20
+ round: "full" | "changes";
21
+ /** The cursor was dead, so the round became a full one. */
22
+ reset: boolean;
23
+ state: "partial" | "complete";
24
+ saved: number;
25
+ /** Rows a complete id pass did not list, now marked deleted. */
26
+ unlisted: number;
27
+ /**
28
+ * `complete`: a full list of ids arrived; `partial`: it stopped and goes on next run; `held`: it would mark too many
29
+ * deleted, or the sign-in could not read all of the kind, so nothing was. Absent: none was due.
30
+ */
31
+ pass?: "complete" | "partial" | "held";
32
+ /** Why the pass was held, and how to let it through. */
33
+ held?: string;
34
+ /** Set when the kind failed; its cursor stays at its last saved page. */
35
+ error?: string;
36
+ }
37
+ export interface TrackerSyncReport {
38
+ provider: string;
39
+ account: string;
40
+ synced: TrackerSyncResult[];
41
+ /** What the sign-in could not read, each once. */
42
+ gaps: TrackerGap[];
43
+ /** Every kind finished its round and none failed. */
44
+ complete: boolean;
45
+ state: "partial" | "complete";
46
+ stopped?: BudgetStop;
47
+ progress: {
48
+ requests: number;
49
+ saved: number;
50
+ steps: number;
51
+ };
52
+ }
53
+ /**
54
+ * Brings one tracker account's copy up to date: each kind's changes since its cursor, then, once a day, a pass over
55
+ * every id that marks deleted what the tracker no longer has. A run that hits its budget stops where it is, saved,
56
+ * and the next one goes on from there. A kind that fails is named and the others still sync.
57
+ */
58
+ export declare const syncTracker: (source: TrackerSource, store: MessageStore, account: AccountKey, options?: TrackerSyncOptions) => Promise<TrackerSyncReport>;
59
+ /** The gaps the account's last sync recorded; none before its first. */
60
+ export declare const trackerGapsOf: (store: MessageStore, account: AccountKey) => Promise<TrackerGap[]>;