@wirecat/cli-core 0.723.0 → 0.724.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/dist/cli/documents/history.js +2 -2
  3. package/dist/cli/documents/words.d.ts +1 -1
  4. package/dist/content/writes.d.ts +3 -9
  5. package/dist/content/writes.js +3 -13
  6. package/dist/crm/writes.d.ts +4 -13
  7. package/dist/crm/writes.js +2 -9
  8. package/dist/errors/reasons.js +5 -0
  9. package/dist/sends/profile-writes.d.ts +22 -0
  10. package/dist/sends/profile-writes.js +20 -0
  11. package/dist/services/metadata.d.ts +1 -1
  12. package/dist/tracker/cli/index.d.ts +10 -1
  13. package/dist/tracker/cli/index.js +20 -1
  14. package/dist/tracker/cli/writes.d.ts +27 -0
  15. package/dist/tracker/cli/writes.js +74 -0
  16. package/dist/tracker/index.d.ts +5 -2
  17. package/dist/tracker/index.js +5 -2
  18. package/dist/tracker/manifest/manifest.d.ts +25 -0
  19. package/dist/tracker/manifest/manifest.js +59 -8
  20. package/dist/tracker/manifest/source.d.ts +10 -1
  21. package/dist/tracker/manifest/source.js +12 -9
  22. package/dist/tracker/manifest/writer.d.ts +20 -0
  23. package/dist/tracker/manifest/writer.js +72 -0
  24. package/dist/tracker/sync.d.ts +5 -0
  25. package/dist/tracker/sync.js +12 -0
  26. package/dist/tracker/testing/index.d.ts +3 -1
  27. package/dist/tracker/testing/index.js +3 -1
  28. package/dist/tracker/testing/manifest-fake.d.ts +2 -0
  29. package/dist/tracker/testing/manifest-fake.js +123 -41
  30. package/dist/tracker/testing/manifest-writes.d.ts +16 -0
  31. package/dist/tracker/testing/manifest-writes.js +70 -0
  32. package/dist/tracker/testing/source.d.ts +9 -1
  33. package/dist/tracker/testing/source.js +63 -0
  34. package/dist/tracker/testing/write-contract.d.ts +20 -0
  35. package/dist/tracker/testing/write-contract.js +94 -0
  36. package/dist/tracker/writer.d.ts +57 -0
  37. package/dist/tracker/writer.js +25 -0
  38. package/dist/tracker/writes.d.ts +53 -0
  39. package/dist/tracker/writes.js +226 -0
  40. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -5,6 +5,40 @@ Notable changes to `@wirecat/cli-core` (`@wirecat/cli-messaging` up to 0.261.0,
5
5
  minor version may break callers, and says how under "Changed — may break callers". `pnpm docs:check` checks the
6
6
  shape of this file.
7
7
 
8
+ ## 0.724.0 — 23.11.2026
9
+
10
+ ### Added
11
+
12
+ - **CRM writes described by a source manifest.** `writes.<kind>` names a service's create, update and remove calls
13
+ and how each of our fields is sent (`to`, `each`, `list`, `number`, `decimals`, `implied`, a fixed currency,
14
+ `clear`), so a CRM CLI built from `wirecat.config.ts` gets `deals create|update|move|close|delete` and
15
+ `people create|update` with no writer of its own. A field with no rule, and a `--field` code the service does not
16
+ define, are refused before anything is sent. `crmManifestWrites` builds
17
+ `CrmRun.writes` over the CLI's fetch and token, and each write also checks its operation's `api` keys;
18
+ `crmManifestWriteCapabilities` and `crmManifestWriteKeys` give `addCrmCommands` and `crmAlsoChecks` the same.
19
+ `crmManifestWriteContract` runs `crmWriteContract` against `crmManifestFake`, which now answers writes, with
20
+ `loseNextAnswer()` and `requests()` ([CRM.md](docs/dev/CRM.md#writes-from-a-manifest)).
21
+ - **`crmSourceFromManifest` reads one record of any kind**: `record(kind, id)` by the entity's `get`, as a writer's
22
+ read-back.
23
+ - **attio in "Works with".** `WIRECAT_TOOLS` lists `attio` (`@wirecat/attio-cli`) beside the other CRM CLIs.
24
+ - **A tracker CLI creates, changes and comments on issues with its own commands.** `addTrackerCommands({ writes })`
25
+ mounts `issues create`, `issues update <issue>` and `issues comment <issue>`: a team, state, label, project or user
26
+ is named by its id or by a name only one row of the copy has (a label among the issue's team's and the workspace's),
27
+ an empty value clears a field, and a reference the copy does not hold is refused before anything is sent. Each write
28
+ passes the profile's guard on `issues.create`, `issues.update` or `issues.comment`, is journaled with the
29
+ `operation_id` it answers, previews under `--dry-run`, and stores the tracker's answer as a sync does, so
30
+ `issues show` has it at once. An `--assignee` other than the sign-in's own user also checks `issues.assign-others`,
31
+ denied by default as `crm.assign-others` is. A manifest's `writes` section maps each write to a mutation (Linear's
32
+ `issueCreate`, `issueUpdate`, `commentCreate`); `trackerWriterFromManifest` sends it through `serviceApiWriter`, so
33
+ the operation's own `api.*` key still applies. `trackerWriteContract` and `trackerManifestWriteContract` check a
34
+ writer, over a fake that answers the mutations strictly by the schema ([TRACKER.md](docs/dev/TRACKER.md#writes)).
35
+
36
+ ### Fixed
37
+
38
+ - **`changes` takes `--since <time>` and `--until <time>`**, the vocabulary's value name, where it said `<when>`. With
39
+ cli-base 0.129.0, which adds the `changes` view, `--since` and `--event`, the shared history commands pass
40
+ `cli-dev lint` in a documents CLI with no override. The flags take the same values as before.
41
+
8
42
  ## 0.723.0 — 23.11.2026
9
43
 
10
44
  ### Added
@@ -55,8 +55,8 @@ const addDocumentHistoryCommandsDefinition = (program, helpers) => {
55
55
  helpers.output(itemOf(await history.versions(ref)));
56
56
  }));
57
57
  return examples(annotate(program.command("changes"), { effects: LOCAL_READ }).description("list the documents the sync added, changed, removed or brought back, newest first"), [`${prefix} changes`, `${prefix} changes --since 7d --event deleted,unavailable`])
58
- .option("--since <when>", "from this time: an ISO 8601 time, today, yesterday, or 30m, 2h, 1d ago", "1d")
59
- .option("--until <when>", "up to this time, in the same forms")
58
+ .option("--since <time>", "from this time: an ISO 8601 time, today, yesterday, or 30m, 2h, 1d ago", "1d")
59
+ .option("--until <time>", "up to this time, in the same forms")
60
60
  .option(`--event <events>`, `only these, comma separated: ${DOCUMENT_EVENTS.join(", ")}`, eventList)
61
61
  .option("--limit <n>", "how many changes to return", positive, 50)
62
62
  .option("--page <n>", "which page to return", positive, 1)
@@ -58,8 +58,8 @@ export interface CopyAge {
58
58
  }
59
59
  export declare const ageOf: (lastSync: string | undefined, now?: number) => CopyAge;
60
60
  export declare const staleCopy: (provider: string, lastSync: string | undefined, now?: number) => {
61
- next?: undefined;
62
61
  missing?: undefined;
62
+ next?: undefined;
63
63
  meta?: undefined;
64
64
  } | {
65
65
  missing: {
@@ -1,19 +1,13 @@
1
1
  import type { ContentPost } from "../domain/content.js";
2
- import type { AppIdentity } from "../ports/app.js";
3
- import type { Warn } from "../runs/events.js";
4
- import { type Asker, type GuardSettings } from "../sends/guard.js";
2
+ import type { Asker } from "../sends/guard.js";
3
+ import { type ProfileWrites } from "../sends/profile-writes.js";
5
4
  import type { MessageStore } from "../store/store.js";
6
5
  import type { AccountKey } from "../store/types.js";
7
6
  import type { ContentSource } from "./source.js";
8
7
  import { type ContentDraft, type ContentFields, type ContentWriter } from "./writer.js";
9
8
  /** What a CLI hands the content writes for one profile. */
10
- export interface ContentWrites {
9
+ export interface ContentWrites extends ProfileWrites {
11
10
  writer: ContentWriter;
12
- app: AppIdentity;
13
- /** The profile's levels, read on every write so a config change applies at once. */
14
- settings: () => Omit<GuardSettings, "sendsPerHour"> & Partial<Pick<GuardSettings, "sendsPerHour">>;
15
- env?: NodeJS.ProcessEnv;
16
- warn?: Warn;
17
11
  }
18
12
  export interface ContentWriteContext {
19
13
  store: MessageStore;
@@ -1,24 +1,14 @@
1
1
  import { CliError, isCliError } from "@wirecat/cli-base";
2
- import { guardFor } from "../sends/guard.js";
3
2
  import { guardedWrite } from "../sends/guarded.js";
4
- import { keyedGuard } from "../sends/keyed-guard.js";
5
- import { DEFAULT_PERMISSIONS, levelFor } from "../sends/permissions.js";
3
+ import { askedKeys, profileWriteGuard } from "../sends/profile-writes.js";
6
4
  import { newOperationId } from "../sends/send-id.js";
7
5
  import { CONTENT_WRITE_DEFAULTS, contentConflict, POSTS_DELETE_FORCE_KEY, POSTS_PUBLISH_KEY, } from "./writer.js";
8
6
  const PUBLIC = new Set(["published", "scheduled"]);
9
- const guardOf = (context, extra) => {
10
- const settings = context.writes.settings();
11
- const defaults = { ...DEFAULT_PERMISSIONS, ...CONTENT_WRITE_DEFAULTS, ...settings.permissionDefaults };
12
- return keyedGuard((ask) => guardFor(context.writes.app, { ...settings, sendsPerHour: Number.MAX_SAFE_INTEGER, permissionDefaults: defaults }, context.writes.warn ?? (() => { }), context.writes.env, ask), context.ask, (key) => levelFor(settings.permissions, key, defaults).level, extra);
13
- };
7
+ const guardOf = (context, extra) => profileWriteGuard(context.writes, context.ask, CONTENT_WRITE_DEFAULTS, extra);
14
8
  /** Checked and journaled once; a lost answer is `outcome_unknown`, and the owner syncs before writing again. */
15
9
  const written = async (context, key, extra, operationId, act) => {
16
10
  try {
17
- // The keys the owner was asked about here (an `ask` level) need not be asked again by a writer's own call; a key
18
- // allowed here was asked about by nobody, so it confirms nothing.
19
- const settings = context.writes.settings();
20
- const defaults = { ...DEFAULT_PERMISSIONS, ...CONTENT_WRITE_DEFAULTS, ...settings.permissionDefaults };
21
- const asked = [key, ...extra].filter((one) => levelFor(settings.permissions, one, defaults).level === "ask");
11
+ const asked = askedKeys(context.writes, CONTENT_WRITE_DEFAULTS, [key, ...extra]);
22
12
  return await guardedWrite(guardOf(context, extra), { chatId: null, kind: "edit", key, operationId }, () => act(asked));
23
13
  }
24
14
  catch (error) {
@@ -1,28 +1,19 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import type { CrmField, CrmKind, CrmOrganization, CrmPerson } from "../domain/crm.js";
3
3
  import type { DealKind } from "../domain/deals.js";
4
- import type { AppIdentity } from "../ports/app.js";
5
- import type { Warn } from "../runs/events.js";
6
- import { type Asker, type GuardSettings } from "../sends/guard.js";
7
- import { type PermissionKey } from "../sends/permissions.js";
4
+ import type { Asker } from "../sends/guard.js";
5
+ import type { PermissionKey } from "../sends/permissions.js";
6
+ import { type ProfileWrites } from "../sends/profile-writes.js";
8
7
  import type { Deal, PipelineOptions, PipelineReport } from "../store/sqlite/deals.js";
9
8
  import type { MessageStore } from "../store/store.js";
10
9
  import type { AccountKey } from "../store/types.js";
11
10
  import type { CrmSource } from "./source.js";
12
11
  import { type CrmVerb, type CrmWriter } from "./writer.js";
13
12
  /** What a CLI hands the CRM writes for one profile. */
14
- export interface CrmWrites {
13
+ export interface CrmWrites extends ProfileWrites {
15
14
  writer: CrmWriter;
16
- app: AppIdentity;
17
- /**
18
- * The profile's levels, read on every write so a config change applies at once. A CRM limits its own rate, so
19
- * `sendsPerHour` is not read: the guard is there for the levels and the journal.
20
- */
21
- settings: () => Omit<GuardSettings, "sendsPerHour"> & Partial<Pick<GuardSettings, "sendsPerHour">>;
22
15
  /** The CRM user the sign-in acts as. An owner other than it checks `crm.assign-others`; left out, every owner does. */
23
16
  self?: string;
24
- env?: NodeJS.ProcessEnv;
25
- warn?: Warn;
26
17
  /**
27
18
  * The CLI's own keys a write also checks, such as Bitrix24's `api.crm.deal.update`; pass the same function to
28
19
  * `crmAlsoChecks` so `--dry-run` names them.
@@ -2,10 +2,8 @@ import { CliError, isCliError } from "@wirecat/cli-base";
2
2
  import { currencyOf, minorUnits } from "../domain/money.js";
3
3
  import { e164Of } from "../domain/phones.js";
4
4
  import { foldName } from "../resolve.js";
5
- import { guardFor } from "../sends/guard.js";
6
5
  import { guardedWrite } from "../sends/guarded.js";
7
- import { keyedGuard } from "../sends/keyed-guard.js";
8
- import { DEFAULT_PERMISSIONS, levelFor } from "../sends/permissions.js";
6
+ import { profileWriteGuard } from "../sends/profile-writes.js";
9
7
  import { newOperationId } from "../sends/send-id.js";
10
8
  import { foreignContacts } from "./foreign-contacts.js";
11
9
  import { CRM_ASSIGN_OTHERS_KEY, CRM_WRITE_DEFAULTS, } from "./writer.js";
@@ -250,12 +248,7 @@ const keysOf = (context, kind, verb, { stage, owner }) => {
250
248
  extra.push(CRM_ASSIGN_OTHERS_KEY);
251
249
  return { key: keyOf(kind, verb), extra: [...extra, ...(context.writes.alsoChecks?.(kind, verb) ?? [])] };
252
250
  };
253
- /** The profile's guard over the write's own key and the keys its fields imply (`keyedGuard`). */
254
- const guardOf = (context, extra) => {
255
- const settings = context.writes.settings();
256
- const defaults = { ...DEFAULT_PERMISSIONS, ...CRM_WRITE_DEFAULTS, ...settings.permissionDefaults };
257
- return keyedGuard((ask) => guardFor(context.writes.app, { ...settings, sendsPerHour: Number.MAX_SAFE_INTEGER, permissionDefaults: defaults }, context.writes.warn ?? (() => { }), context.writes.env, ask), context.ask, (key) => levelFor(settings.permissions, key, defaults).level, extra);
258
- };
251
+ const guardOf = (context, extra) => profileWriteGuard(context.writes, context.ask, CRM_WRITE_DEFAULTS, extra);
259
252
  /** Sends the write once, never again: a lost answer is `outcome_unknown`, with what the owner may do about it. */
260
253
  const written = async (context, { key, extra }, operationId, act) => {
261
254
  try {
@@ -540,6 +540,11 @@ const OTHERS = [
540
540
  validation("crm.write-unsupported", "the CRM does not take this write, or does not recognise a repeated one"),
541
541
  validation("crm.unlisted-held", "a list of every id would mark most of a kind deleted; nothing was, until --rescan"),
542
542
  validation("tracker.unlisted-held", "a tracker's id list would mark too much deleted, or the sign-in read only part; nothing was, until --rescan"),
543
+ validation("tracker.write-unsupported", "the tracker does not take this write, or does not recognise a repeated one"),
544
+ validation("tracker.field", "a field of an issue or a comment the tracker's write does not take as given"),
545
+ validation("tracker.reference", "a team, state, label, project or user no single row of the copy has by that name"),
546
+ validation("tracker.team-required", "a new issue needs its team: name one, or sync a copy that holds one"),
547
+ ["tracker.no-record", "invalid_response", "the tracker answered a write with no record and no error; sync and look"],
543
548
  validation("content.unlisted-held", "a content id list would mark too much deleted, the sign-in read only part, or the site moved; nothing was"),
544
549
  validation("content.conflict", "the post changed at the source since the last sync; sync, then write again"),
545
550
  validation("content.lossy-body", "the post's text holds blocks or embeds Markdown does not keep; --replace-body"),
@@ -0,0 +1,22 @@
1
+ import type { AppIdentity } from "../ports/app.js";
2
+ import type { Warn } from "../runs/events.js";
3
+ import { type Asker, type GuardSettings, type SendGuard } from "./guard.js";
4
+ import { type Level, type PermissionKey } from "./permissions.js";
5
+ /** What a CLI hands a service's writes (a CRM's, a site's, a tracker's) for one profile. */
6
+ export interface ProfileWrites {
7
+ app: AppIdentity;
8
+ /**
9
+ * The profile's levels, read on every write so a config change applies at once. A service limits its own rate, so
10
+ * `sendsPerHour` is not read: the guard is there for the levels and the journal.
11
+ */
12
+ settings: () => Omit<GuardSettings, "sendsPerHour"> & Partial<Pick<GuardSettings, "sendsPerHour">>;
13
+ env?: NodeJS.ProcessEnv;
14
+ warn?: Warn;
15
+ }
16
+ /** The profile's guard over a write's own key and the keys its fields imply (`keyedGuard`). */
17
+ export declare const profileWriteGuard: (writes: ProfileWrites, ask: Asker, builtIn: Readonly<Record<PermissionKey, Level>>, extra: readonly PermissionKey[]) => SendGuard;
18
+ /**
19
+ * The keys at level `ask`: the owner is asked about them here, so a writer over the `api` group need not ask again. A
20
+ * key at `allow` was asked about by nobody and confirms nothing.
21
+ */
22
+ export declare const askedKeys: (writes: ProfileWrites, builtIn: Readonly<Record<PermissionKey, Level>>, keys: readonly PermissionKey[]) => PermissionKey[];
@@ -0,0 +1,20 @@
1
+ import { guardFor } from "./guard.js";
2
+ import { keyedGuard } from "./keyed-guard.js";
3
+ import { DEFAULT_PERMISSIONS, levelFor } from "./permissions.js";
4
+ const levelsOf = (writes, defaults) => {
5
+ const settings = writes.settings();
6
+ return { settings, defaults: { ...DEFAULT_PERMISSIONS, ...defaults, ...settings.permissionDefaults } };
7
+ };
8
+ /** The profile's guard over a write's own key and the keys its fields imply (`keyedGuard`). */
9
+ export const profileWriteGuard = (writes, ask, builtIn, extra) => {
10
+ const { settings, defaults } = levelsOf(writes, builtIn);
11
+ return keyedGuard((asker) => guardFor(writes.app, { ...settings, sendsPerHour: Number.MAX_SAFE_INTEGER, permissionDefaults: defaults }, writes.warn ?? (() => { }), writes.env, asker), ask, (key) => levelFor(settings.permissions, key, defaults).level, extra);
12
+ };
13
+ /**
14
+ * The keys at level `ask`: the owner is asked about them here, so a writer over the `api` group need not ask again. A
15
+ * key at `allow` was asked about by nobody and confirms nothing.
16
+ */
17
+ export const askedKeys = (writes, builtIn, keys) => {
18
+ const { settings, defaults } = levelsOf(writes, builtIn);
19
+ return keys.filter((key) => levelFor(settings.permissions, key, defaults).level === "ask");
20
+ };
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
14
14
  dryRun?: boolean;
15
15
  }) => Promise<{
16
16
  items: ({
17
- error?: undefined;
18
17
  chatId: string;
19
18
  tags: import("../domain/channel-tags.js").ChannelTagMatch[];
20
19
  algorithm: string;
21
20
  fetchedAt: string | null;
22
21
  source: string;
22
+ error?: undefined;
23
23
  } | {
24
24
  tags?: undefined;
25
25
  algorithm?: undefined;
@@ -3,12 +3,16 @@ import type { AppIdentity } from "../../ports/app.js";
3
3
  import type { MessageStore } from "../../store/store.js";
4
4
  import type { AccountKey } from "../../store/types.js";
5
5
  import type { TrackerSource } from "../source.js";
6
+ import type { TrackerWrite } from "../writer.js";
7
+ import type { TrackerWrites } from "../writes.js";
6
8
  /** The selected profile's tracker account, opened for one command and closed before its answer is printed. */
7
9
  export interface TrackerRun {
8
10
  account: AccountKey;
9
11
  store: MessageStore;
10
12
  /** The tracker, built on first use: a command that only reads the store never reads the sign-in. */
11
13
  source: () => TrackerSource;
14
+ /** The tracker's writer and the profile's levels, built for the command run; needed by every write command. */
15
+ writes?: (command: Command) => TrackerWrites;
12
16
  close?: () => Promise<void>;
13
17
  }
14
18
  export interface TrackerCommandOptions {
@@ -18,7 +22,12 @@ export interface TrackerCommandOptions {
18
22
  open: (command: Command, access: {
19
23
  readOnly: boolean;
20
24
  }) => Promise<TrackerRun>;
25
+ /** What the tracker's writer takes (`TrackerWriter.writes`): mounts `issues create`, `update` and `comment`. */
26
+ writes?: readonly TrackerWrite[];
21
27
  now?: () => number;
22
28
  }
23
- /** The tracker's commands: `sync`, `issues list|show|search|assign`, and a `list` of each other kind. */
29
+ /**
30
+ * The tracker's commands: `sync`, `issues list|show|search|assign`, `issues create|update|comment` for the writes in
31
+ * `writes`, and a `list` of each other kind.
32
+ */
24
33
  export declare const addTrackerCommands: (program: Command, options: TrackerCommandOptions) => void;
@@ -12,6 +12,7 @@ import { STATE_TYPES, TRACKER_KINDS, } from "../../domain/tracker.js";
12
12
  import { count, text } from "../../entities/fields.js";
13
13
  import { syncTracker } from "../sync.js";
14
14
  import { trackerIssueTask } from "../tasks.js";
15
+ import { addTrackerWriteCommands } from "./writes.js";
15
16
  const MOST = 500;
16
17
  const integer = (most) => (value) => {
17
18
  const number = Number(value);
@@ -89,6 +90,12 @@ const trackerSync = v.strictObject({
89
90
  v.strictObject({ skipped: text }),
90
91
  ])),
91
92
  });
93
+ const trackerWrite = v.strictObject({
94
+ operation_id: text,
95
+ issue: v.optional(trackerView),
96
+ comment: v.optional(trackerView),
97
+ untrusted: v.array(text),
98
+ });
92
99
  const trackerTask = v.strictObject({ task_id: text, key: v.optional(text), issue: text, created: v.boolean() });
93
100
  /** Each issue with its state's name and type, and its assignee's name and person, read from the same copy. */
94
101
  const withNames = async (run, items) => {
@@ -263,6 +270,15 @@ const addTrackerCommandsDefinition = (program, options) => {
263
270
  return itemOf({ task_id: task.id, ...(task.key ? { key: task.key } : {}), issue: task.source, created });
264
271
  });
265
272
  });
273
+ if (options.writes?.length)
274
+ addTrackerWriteCommands(issues, {
275
+ writes: options.writes,
276
+ within,
277
+ example,
278
+ view: async (run, item) => item.kind === "issue" ? (await withNames(run, [item]))[0] : viewOf(item),
279
+ answer: trackerWrite,
280
+ now,
281
+ });
266
282
  for (const [kind, plural, what] of [
267
283
  ["project", "projects", "the tracker's projects: status, lead, teams and target date"],
268
284
  ["team", "teams", "the tracker's teams"],
@@ -294,5 +310,8 @@ const addTrackerCommandsDefinition = (program, options) => {
294
310
  });
295
311
  }
296
312
  };
297
- /** The tracker's commands: `sync`, `issues list|show|search|assign`, and a `list` of each other kind. */
313
+ /**
314
+ * The tracker's commands: `sync`, `issues list|show|search|assign`, `issues create|update|comment` for the writes in
315
+ * `writes`, and a `list` of each other kind.
316
+ */
298
317
  export const addTrackerCommands = honoursDryRun(sharedCommand(addTrackerCommandsDefinition));
@@ -0,0 +1,27 @@
1
+ import type { Command } from "commander";
2
+ import type * as v from "valibot";
3
+ import { type Body } from "../../cli/envelope.js";
4
+ import type { TrackerItem } from "../../store/sqlite/tracker.js";
5
+ import type { TrackerWrite } from "../writer.js";
6
+ import { type TrackerWriteContext, type TrackerWrites } from "../writes.js";
7
+ /** What the writes need of the open profile: the shared `TrackerRun` and its writes, built for the command run. */
8
+ interface WriteRun {
9
+ account: TrackerWriteContext["account"];
10
+ store: TrackerWriteContext["store"];
11
+ writes?: (command: Command) => TrackerWrites;
12
+ source?: TrackerWriteContext["source"];
13
+ }
14
+ export interface TrackerWriteCommandOptions<R extends WriteRun> {
15
+ writes: readonly TrackerWrite[];
16
+ within: (command: Command, readOnly: boolean, work: (run: R) => Promise<Body>) => Promise<void>;
17
+ example: (command: Command, ...lines: string[]) => Command;
18
+ /** An issue or comment as the read commands show it, with its `untrusted` fields. */
19
+ view: (run: R, item: TrackerItem) => Promise<Record<string, unknown> & {
20
+ untrusted: string[];
21
+ }>;
22
+ answer: v.GenericSchema;
23
+ now: () => number;
24
+ }
25
+ /** `issues create|update|comment` for each write the tracker takes, under the `issues` group. */
26
+ export declare const addTrackerWriteCommands: <R extends WriteRun>(issues: Command, options: TrackerWriteCommandOptions<R>) => void;
27
+ export {};
@@ -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: {