@wirecat/cli-core 0.722.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.
Files changed (56) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/dist/cli/documents/history.js +2 -2
  3. package/dist/cli/documents/words.d.ts +1 -1
  4. package/dist/cli/service-api-call.d.ts +6 -0
  5. package/dist/cli/service-api-call.js +21 -9
  6. package/dist/cli/service-api.d.ts +5 -0
  7. package/dist/cli/service-api.js +11 -0
  8. package/dist/content/writes.d.ts +3 -9
  9. package/dist/content/writes.js +3 -13
  10. package/dist/crm/index.d.ts +3 -2
  11. package/dist/crm/index.js +1 -0
  12. package/dist/crm/manifest/manifest.d.ts +60 -1
  13. package/dist/crm/manifest/manifest.js +88 -0
  14. package/dist/crm/manifest/source.d.ts +22 -3
  15. package/dist/crm/manifest/source.js +10 -3
  16. package/dist/crm/manifest/writer.d.ts +39 -0
  17. package/dist/crm/manifest/writer.js +298 -0
  18. package/dist/crm/testing/index.d.ts +1 -1
  19. package/dist/crm/testing/index.js +1 -1
  20. package/dist/crm/testing/manifest-fake.d.ts +14 -0
  21. package/dist/crm/testing/manifest-fake.js +252 -27
  22. package/dist/crm/writes.d.ts +4 -13
  23. package/dist/crm/writes.js +2 -9
  24. package/dist/errors/reasons.js +5 -0
  25. package/dist/ports/wirecat-tools.js +7 -0
  26. package/dist/sends/profile-writes.d.ts +22 -0
  27. package/dist/sends/profile-writes.js +20 -0
  28. package/dist/tracker/cli/index.d.ts +10 -1
  29. package/dist/tracker/cli/index.js +20 -1
  30. package/dist/tracker/cli/writes.d.ts +27 -0
  31. package/dist/tracker/cli/writes.js +74 -0
  32. package/dist/tracker/index.d.ts +5 -2
  33. package/dist/tracker/index.js +5 -2
  34. package/dist/tracker/manifest/manifest.d.ts +25 -0
  35. package/dist/tracker/manifest/manifest.js +59 -8
  36. package/dist/tracker/manifest/source.d.ts +10 -1
  37. package/dist/tracker/manifest/source.js +12 -9
  38. package/dist/tracker/manifest/writer.d.ts +20 -0
  39. package/dist/tracker/manifest/writer.js +72 -0
  40. package/dist/tracker/sync.d.ts +5 -0
  41. package/dist/tracker/sync.js +12 -0
  42. package/dist/tracker/testing/index.d.ts +3 -1
  43. package/dist/tracker/testing/index.js +3 -1
  44. package/dist/tracker/testing/manifest-fake.d.ts +2 -0
  45. package/dist/tracker/testing/manifest-fake.js +123 -41
  46. package/dist/tracker/testing/manifest-writes.d.ts +16 -0
  47. package/dist/tracker/testing/manifest-writes.js +70 -0
  48. package/dist/tracker/testing/source.d.ts +9 -1
  49. package/dist/tracker/testing/source.js +63 -0
  50. package/dist/tracker/testing/write-contract.d.ts +20 -0
  51. package/dist/tracker/testing/write-contract.js +94 -0
  52. package/dist/tracker/writer.d.ts +57 -0
  53. package/dist/tracker/writer.js +25 -0
  54. package/dist/tracker/writes.d.ts +53 -0
  55. package/dist/tracker/writes.js +226 -0
  56. package/package.json +1 -1
@@ -0,0 +1,74 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { annotate } from "@wirecat/cli-base/commands";
3
+ import { answerEntity } from "../../cli/answer-entity.js";
4
+ import { REMOTE_WRITE } from "../../cli/effects.js";
5
+ import { itemOf } from "../../cli/envelope.js";
6
+ import { terminalAsker } from "../../cli/messenger/ask.js";
7
+ import { commentTrackerIssue, createTrackerIssue, updateTrackerIssue, } from "../writes.js";
8
+ const collect = (value, previous = []) => [...previous, value];
9
+ const inputOf = ({ label, ...rest }) => ({
10
+ ...Object.fromEntries(Object.entries(rest).filter(([, value]) => value !== undefined)),
11
+ // The empty default marks the flag as repeatable; left empty, the labels are not changed.
12
+ ...(label?.length ? { labels: label } : {}),
13
+ });
14
+ /** `issues create|update|comment` for each write the tracker takes, under the `issues` group. */
15
+ export const addTrackerWriteCommands = (issues, options) => {
16
+ const contextOf = (run, command) => {
17
+ if (!run.writes)
18
+ throw new CliError("configuration_error", "this profile cannot write to its tracker");
19
+ return {
20
+ store: run.store,
21
+ account: run.account,
22
+ writes: run.writes(command),
23
+ ask: terminalAsker(command),
24
+ ...(run.source ? { source: run.source } : {}),
25
+ now: options.now,
26
+ };
27
+ };
28
+ const answered = async (run, operationId, kind, item) => {
29
+ const shown = await options.view(run, item);
30
+ return itemOf({
31
+ operation_id: operationId,
32
+ [kind]: shown,
33
+ untrusted: shown.untrusted.map((field) => `${kind}.${field}`),
34
+ });
35
+ };
36
+ const write = (name, description) => answerEntity(annotate(issues.command(name), { effects: REMOTE_WRITE, offline: false }), "tracker_write", options.answer).description(description);
37
+ const fields = (command) => command
38
+ .option("--description <text>", "the issue's text; an empty value clears it")
39
+ .option("--team <team>", "the team, by its id, key or name; left out, the copy's only team")
40
+ .option("--state <state>", "the workflow state, by its id or a name only one of the team's states has")
41
+ .option("--assignee <user>", "the user, by id, name or e-mail; empty for none; anyone but you checks issues.assign-others")
42
+ .option("--priority <priority>", "0 to 4, or none, urgent, high, medium, low; empty for none")
43
+ .option("--label <label>", "a label by its id or name; repeat it for each; replaces the issue's labels, and one empty value clears them", collect, [])
44
+ .option("--project <project>", "the project, by its id or name; empty for none")
45
+ .option("--parent <issue>", "the issue this one is part of, by its key or id; empty for none");
46
+ const reference = (command) => command.argument("<issue>", "the issue's key (ENG-12) or id");
47
+ if (options.writes.includes("create"))
48
+ options
49
+ .example(fields(write("create", "make an issue in the tracker, then store the tracker's copy of it").requiredOption("--title <title>", "the issue's title")), 'issues create --title "Example: invoices fail for EUR" --team ENG --label Bug', 'issues create --title "Example: write the guide" --assignee ada@example.com --priority high')
50
+ .action(async (typed, command) => {
51
+ await options.within(command, false, async (run) => {
52
+ const done = await createTrackerIssue(contextOf(run, command), inputOf(typed));
53
+ return answered(run, done.operationId, "issue", done.issue);
54
+ });
55
+ });
56
+ if (options.writes.includes("update"))
57
+ options
58
+ .example(fields(reference(write("update", "change an issue in the tracker; what is left out keeps its value; the tracker's copy is stored again")).option("--title <title>", "the issue's title")), 'issues update ENG-12 --state "In Progress"', 'issues update ENG-12 --assignee ""')
59
+ .action(async (issue, typed, command) => {
60
+ await options.within(command, false, async (run) => {
61
+ const done = await updateTrackerIssue(contextOf(run, command), issue, inputOf(typed));
62
+ return answered(run, done.operationId, "issue", done.issue);
63
+ });
64
+ });
65
+ if (options.writes.includes("comment"))
66
+ options
67
+ .example(reference(write("comment", "add a comment to an issue in the tracker, then store it")).requiredOption("--body <text>", "the comment, as it is to read"), 'issues comment ENG-12 --body "Example: fixed in the next release"')
68
+ .action(async (issue, typed, command) => {
69
+ await options.within(command, false, async (run) => {
70
+ const done = await commentTrackerIssue(contextOf(run, command), issue, typed.body);
71
+ return answered(run, done.operationId, "comment", done.comment);
72
+ });
73
+ });
74
+ };
@@ -1,8 +1,11 @@
1
1
  export { STATE_TYPES, type StateType, TRACKER_KINDS, type TrackerComment, type TrackerIssue, type TrackerKind, type TrackerLabel, type TrackerProject, type TrackerRecords, type TrackerState, type TrackerTeam, type TrackerUser, } from "../domain/tracker.js";
2
2
  export { addTrackerCommands, type TrackerCommandOptions, type TrackerRun } from "./cli/index.js";
3
- export { parseTrackerManifest, type TrackerAfterHook, type TrackerChangesCall, type TrackerManifest, type TrackerManifestEntity, type TrackerManifestHooks, type TrackerOperationCall, } from "./manifest/manifest.js";
3
+ export { parseTrackerManifest, TRACKER_WRITE_FIELDS, type TrackerAfterHook, type TrackerChangesCall, type TrackerManifest, type TrackerManifestEntity, type TrackerManifestHooks, type TrackerManifestWrite, type TrackerOperationCall, type TrackerWriteKind, type TrackerWriteRule, } from "./manifest/manifest.js";
4
4
  export { TRACKER_FIELDS } from "./manifest/map.js";
5
5
  export { type TrackerManifestSourceOptions, trackerSourceFromManifest, } from "./manifest/source.js";
6
+ export { type TrackerManifestWriterOptions, trackerWriterFromManifest } from "./manifest/writer.js";
6
7
  export type { TrackerCallContext, TrackerChanges, TrackerGap, TrackerIdPage, TrackerPage, TrackerSource, TrackerSourceTraits, } from "./source.js";
7
- export { syncTracker, type TrackerSyncOptions, type TrackerSyncReport, type TrackerSyncResult, trackerCursorName, trackerGapsOf, } from "./sync.js";
8
+ export { syncTracker, type TrackerSyncOptions, type TrackerSyncReport, type TrackerSyncResult, trackerCursorName, trackerGapsOf, trackerSelfOf, } from "./sync.js";
8
9
  export { syncTrackerTasks, TRACKER_ISSUE_TASK, type TrackerTaskChanges, trackerIssueSource, trackerIssueTask, trackerIssueTitle, } from "./tasks.js";
10
+ export { TRACKER_ASSIGN_OTHERS_KEY, TRACKER_WRITE_DEFAULTS, TRACKER_WRITE_EXTRA_KEYS, TRACKER_WRITE_KEYS, TRACKER_WRITES, type TrackerIssueDraft, type TrackerIssueFields, type TrackerWrite, type TrackerWriteOptions, type TrackerWriter, trackerAlsoChecks, } from "./writer.js";
11
+ export { commentTrackerIssue, createTrackerIssue, type TrackerCommentWritten, type TrackerIssueInput, type TrackerIssueWritten, type TrackerWriteContext, type TrackerWrites, trackerIssueOf, updateTrackerIssue, } from "./writes.js";
@@ -1,7 +1,10 @@
1
1
  export { STATE_TYPES, TRACKER_KINDS, } from "../domain/tracker.js";
2
2
  export { addTrackerCommands } from "./cli/index.js";
3
- export { parseTrackerManifest, } from "./manifest/manifest.js";
3
+ export { parseTrackerManifest, TRACKER_WRITE_FIELDS, } from "./manifest/manifest.js";
4
4
  export { TRACKER_FIELDS } from "./manifest/map.js";
5
5
  export { trackerSourceFromManifest, } from "./manifest/source.js";
6
- export { syncTracker, trackerCursorName, trackerGapsOf, } from "./sync.js";
6
+ export { trackerWriterFromManifest } from "./manifest/writer.js";
7
+ export { syncTracker, trackerCursorName, trackerGapsOf, trackerSelfOf, } from "./sync.js";
7
8
  export { syncTrackerTasks, TRACKER_ISSUE_TASK, trackerIssueSource, trackerIssueTask, trackerIssueTitle, } from "./tasks.js";
9
+ export { TRACKER_ASSIGN_OTHERS_KEY, TRACKER_WRITE_DEFAULTS, TRACKER_WRITE_EXTRA_KEYS, TRACKER_WRITE_KEYS, TRACKER_WRITES, trackerAlsoChecks, } from "./writer.js";
10
+ export { commentTrackerIssue, createTrackerIssue, trackerIssueOf, updateTrackerIssue, } from "./writes.js";
@@ -37,6 +37,28 @@ export interface TrackerManifestEntity<K extends TrackerKind = TrackerKind> {
37
37
  scope?: string;
38
38
  };
39
39
  }
40
+ /** Where one of our fields goes inside the write's `"{values}"`: Linear takes our `state` as `stateId`. */
41
+ export interface TrackerWriteRule {
42
+ to: string;
43
+ }
44
+ /**
45
+ * The writes of one kind. Each call's variables hold `"{values}"`, the object of the fields given, and an update's
46
+ * also `"{id}"`. The tracker answers the written row, at the call's `items`, read by the kind's `map`: its selection
47
+ * names every path the map reads, as a list's does, so the copy is stored whole.
48
+ */
49
+ export interface TrackerManifestWrite {
50
+ create?: TrackerOperationCall;
51
+ /** An issue only. */
52
+ update?: TrackerOperationCall;
53
+ /** Our fields by their names in `TRACKER_WRITE_FIELDS`; a field with no rule is refused before anything is sent. */
54
+ fields: Readonly<Record<string, TrackerWriteRule>>;
55
+ }
56
+ /** The fields a write of each kind may name. */
57
+ export declare const TRACKER_WRITE_FIELDS: {
58
+ readonly issue: readonly ["title", "description", "team", "state", "assignee", "priority", "labels", "project", "parent"];
59
+ readonly comment: readonly ["issue", "body"];
60
+ };
61
+ export type TrackerWriteKind = keyof typeof TRACKER_WRITE_FIELDS;
40
62
  /** A tracker account described as data: what to call for each kind and where each of our fields is in the answer. */
41
63
  export interface TrackerManifest {
42
64
  /** The registry name: `linear`. */
@@ -53,6 +75,9 @@ export interface TrackerManifest {
53
75
  call: TrackerOperationCall;
54
76
  path: string;
55
77
  };
78
+ writes?: {
79
+ readonly [K in TrackerWriteKind]?: TrackerManifestWrite;
80
+ };
56
81
  }
57
82
  /** Corrects one record after the map; `call` reads more from the service, spent from the run's budget. */
58
83
  export type TrackerAfterHook<K extends TrackerKind> = (record: TrackerRecords[K], raw: crmValues.CrmRaw, service: {
@@ -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 hasSince = (value) => value === "{since}" ||
36
- (Array.isArray(value) && value.some(hasSince)) ||
37
- (typeof value === "object" && value !== null && Object.values(value).some(hasSince));
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 !== "read")
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 (!hasSince(one.changes.variables))
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 fill = (value, since) => {
10
- if (value === "{since}")
11
- return since ?? DROP;
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, since)).filter((one) => one !== DROP);
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, since);
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 inputOf = (call, since) => ({
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, since)) } : {}),
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 = inputOf(call, since);
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, inputOf(self.call)), self.path));
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
+ };
@@ -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[]>;
@@ -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 {};