@wirecat/cli-core 0.723.0 → 0.725.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 (59) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/dist/cli/documents/file-conflicts.d.ts +7 -2
  3. package/dist/cli/documents/file-conflicts.js +5 -4
  4. package/dist/cli/documents/file-edit.js +4 -4
  5. package/dist/cli/documents/history.js +2 -2
  6. package/dist/cli/documents/index.d.ts +1 -1
  7. package/dist/cli/documents/words.d.ts +1 -1
  8. package/dist/cli/messenger/search-answers.js +4 -0
  9. package/dist/cli/search-left-out.d.ts +1 -0
  10. package/dist/cli/search-left-out.js +1 -0
  11. package/dist/content/writes.d.ts +3 -9
  12. package/dist/content/writes.js +3 -13
  13. package/dist/crm/manifest/writer.js +1 -1
  14. package/dist/crm/testing/manifest-fake.js +2 -2
  15. package/dist/crm/writes.d.ts +4 -13
  16. package/dist/crm/writes.js +2 -9
  17. package/dist/domain/providers.d.ts +1 -1
  18. package/dist/domain/providers.js +4 -1
  19. package/dist/entities/hit.d.ts +3 -2
  20. package/dist/entities/hit.js +5 -1
  21. package/dist/entities/index.d.ts +1 -1
  22. package/dist/errors/reasons.js +27 -1
  23. package/dist/office/docx.js +10 -10
  24. package/dist/office/xlsx.js +17 -17
  25. package/dist/search/account-list.js +1 -0
  26. package/dist/sends/profile-writes.d.ts +22 -0
  27. package/dist/sends/profile-writes.js +20 -0
  28. package/dist/services/metadata.d.ts +1 -1
  29. package/dist/services/search-all.d.ts +7 -3
  30. package/dist/services/search-all.js +51 -1
  31. package/dist/tracker/cli/index.d.ts +10 -1
  32. package/dist/tracker/cli/index.js +20 -1
  33. package/dist/tracker/cli/writes.d.ts +27 -0
  34. package/dist/tracker/cli/writes.js +74 -0
  35. package/dist/tracker/index.d.ts +5 -2
  36. package/dist/tracker/index.js +5 -2
  37. package/dist/tracker/manifest/manifest.d.ts +25 -0
  38. package/dist/tracker/manifest/manifest.js +59 -8
  39. package/dist/tracker/manifest/source.d.ts +10 -1
  40. package/dist/tracker/manifest/source.js +12 -9
  41. package/dist/tracker/manifest/writer.d.ts +20 -0
  42. package/dist/tracker/manifest/writer.js +72 -0
  43. package/dist/tracker/sync.d.ts +5 -0
  44. package/dist/tracker/sync.js +12 -0
  45. package/dist/tracker/testing/index.d.ts +3 -1
  46. package/dist/tracker/testing/index.js +3 -1
  47. package/dist/tracker/testing/manifest-fake.d.ts +2 -0
  48. package/dist/tracker/testing/manifest-fake.js +123 -41
  49. package/dist/tracker/testing/manifest-writes.d.ts +16 -0
  50. package/dist/tracker/testing/manifest-writes.js +70 -0
  51. package/dist/tracker/testing/source.d.ts +9 -1
  52. package/dist/tracker/testing/source.js +63 -0
  53. package/dist/tracker/testing/write-contract.d.ts +20 -0
  54. package/dist/tracker/testing/write-contract.js +94 -0
  55. package/dist/tracker/writer.d.ts +57 -0
  56. package/dist/tracker/writer.js +25 -0
  57. package/dist/tracker/writes.d.ts +53 -0
  58. package/dist/tracker/writes.js +226 -0
  59. package/package.json +2 -2
@@ -30,7 +30,7 @@ const parseAddress = (address) => {
30
30
  const column = match ? [...match[1]].reduce((sum, letter) => sum * 26 + letter.charCodeAt(0) - 64, 0) : 0;
31
31
  const row = Number(match?.[2]);
32
32
  if (!match || column > MAX_COLUMN || row > MAX_ROW)
33
- throw refuse(`${address} is not a cell address like B7`, "office.invalid_cell");
33
+ throw refuse(`${address} is not a cell address like B7`, "office.invalid-cell");
34
34
  return { row, column };
35
35
  };
36
36
  const parseRange = (range) => {
@@ -61,14 +61,14 @@ class Workbook {
61
61
  this.workbook = pack.part(path);
62
62
  this.ns = this.workbook.root.ns;
63
63
  if (this.workbook.root.local !== "workbook" || !SHEET_NAMESPACES.includes(this.ns))
64
- throw refuse("the file is not an Excel workbook", "office.wrong_format");
64
+ throw refuse("the file is not an Excel workbook", "office.wrong-format");
65
65
  const rels = pack.relationships(path);
66
66
  const sheetsElement = childrenOf(this.workbook.root, this.ns, "sheets")[0];
67
67
  this.sheets = (sheetsElement ? childrenOf(sheetsElement, this.ns, "sheet") : []).map((sheet) => {
68
68
  const id = attributeOf(sheet, REL, "id") ?? attributeOf(sheet, STRICT_REL, "id") ?? "";
69
69
  const target = rels.get(id);
70
70
  if (!target?.type.endsWith("/worksheet"))
71
- throw refuse("a sheet of the workbook is not a worksheet (a chart sheet or a missing part)", "office.wrong_format");
71
+ throw refuse("a sheet of the workbook is not a worksheet (a chart sheet or a missing part)", "office.wrong-format");
72
72
  return { name: attributeOf(sheet, "", "name") ?? "", path: target.path };
73
73
  });
74
74
  const shared = pack.related(path, "sharedStrings");
@@ -88,7 +88,7 @@ class Workbook {
88
88
  sheet(name) {
89
89
  const found = this.sheets.find((sheet) => sheet.name === name);
90
90
  if (!found)
91
- throw refuse(`the workbook has no sheet "${name}"; it has ${this.sheets.map((sheet) => `"${sheet.name}"`).join(", ")}`, "office.no_sheet");
91
+ throw refuse(`the workbook has no sheet "${name}"; it has ${this.sheets.map((sheet) => `"${sheet.name}"`).join(", ")}`, "office.no-sheet");
92
92
  return found;
93
93
  }
94
94
  }
@@ -119,7 +119,7 @@ const rowsOf = (sheetData, ns) => {
119
119
  if (reference) {
120
120
  const address = parseAddress(reference);
121
121
  if (address.row !== number)
122
- throw refuse(`cell ${reference} sits in row ${number}`, "office.wrong_format");
122
+ throw refuse(`cell ${reference} sits in row ${number}`, "office.wrong-format");
123
123
  column = address.column;
124
124
  }
125
125
  else
@@ -158,7 +158,7 @@ const cellOf = (workbook, text, node) => {
158
158
  if (type === "s") {
159
159
  const string = workbook.strings[Number(saved)];
160
160
  if (!/^\d+$/.test(saved) || string === undefined)
161
- throw refuse(`cell ${columnName(node.column)}${node.row} points at a missing shared string`, "office.wrong_format");
161
+ throw refuse(`cell ${columnName(node.column)}${node.row} points at a missing shared string`, "office.wrong-format");
162
162
  value = string;
163
163
  kind = "string";
164
164
  }
@@ -195,10 +195,10 @@ const cellOf = (workbook, text, node) => {
195
195
  };
196
196
  const sheetDataOf = (part, ns) => {
197
197
  if (part.root.local !== "worksheet" || part.root.ns !== ns)
198
- throw refuse(`${part.path} is not a worksheet`, "office.wrong_format");
198
+ throw refuse(`${part.path} is not a worksheet`, "office.wrong-format");
199
199
  const sheetData = childrenOf(part.root, ns, "sheetData")[0];
200
200
  if (!sheetData)
201
- throw refuse(`${part.path} has no cell data`, "office.wrong_format");
201
+ throw refuse(`${part.path} has no cell data`, "office.wrong-format");
202
202
  return sheetData;
203
203
  };
204
204
  /** The workbook's sheets and their stored cells, with each cell's type, formula and format index. */
@@ -278,7 +278,7 @@ const valueXml = (cell, value, strings) => {
278
278
  return { type: "b", content: `<${v}>${value ? 1 : 0}</${v}>` };
279
279
  if (typeof value === "number") {
280
280
  if (!Number.isFinite(value))
281
- throw refuse("a cell number must be finite", "office.invalid_value");
281
+ throw refuse("a cell number must be finite", "office.invalid-value");
282
282
  return { type: undefined, content: `<${v}>${String(value)}</${v}>` };
283
283
  }
284
284
  if (strings)
@@ -336,7 +336,7 @@ const editSheet = (workbook, sheet, planned, options, strings) => {
336
336
  for (const label of tableLabels(workbook, sheet))
337
337
  for (const item of planned)
338
338
  if (item.row >= label.top && item.row <= label.bottom && item.column >= label.left && item.column <= label.right)
339
- throw refuse(`${sheet.name}!${item.address} is a ${label.kind} of the table "${label.table}", whose part repeats the text; change it in Excel`, "office.table_header");
339
+ throw refuse(`${sheet.name}!${item.address} is a ${label.kind} of the table "${label.table}", whose part repeats the text; change it in Excel`, "office.table-header");
340
340
  const splices = [];
341
341
  const changed = [];
342
342
  let formulaRemoved = false;
@@ -354,7 +354,7 @@ const editSheet = (workbook, sheet, planned, options, strings) => {
354
354
  const row = rows.find((candidate) => candidate.row === rowNumber);
355
355
  if (!row) {
356
356
  if (rows.some((candidate) => !candidate.explicit))
357
- throw refuse(`${sheet.name} has rows without numbers, so row ${rowNumber} cannot be added`, "office.implicit_rows");
357
+ throw refuse(`${sheet.name} has rows without numbers, so row ${rowNumber} cannot be added`, "office.implicit-rows");
358
358
  const next = rows.find((candidate) => candidate.row > rowNumber);
359
359
  const r = qualified(sheetData, "row");
360
360
  const xml = `<${r} r="${rowNumber}">${items.map((item) => newCell(item)).join("")}</${r}>`;
@@ -378,7 +378,7 @@ const editSheet = (workbook, sheet, planned, options, strings) => {
378
378
  const existing = row.cells.find((cell) => cell.column === item.column);
379
379
  if (!existing) {
380
380
  if (row.cells.some((cell) => attributeOf(cell.element, "", "r") === undefined))
381
- throw refuse(`row ${rowNumber} of ${sheet.name} has cells without addresses, so ${item.address} cannot be added`, "office.implicit_cells");
381
+ throw refuse(`row ${rowNumber} of ${sheet.name} has cells without addresses, so ${item.address} cannot be added`, "office.implicit-cells");
382
382
  const next = row.cells.find((cell) => cell.column > item.column);
383
383
  inserts.push({ at: next ? next.element.start : -1, xml: newCell(item, rowStyle) });
384
384
  changed.push({ sheet: sheet.name, cell: item.address, before: null, after: item.edit.value, created: true });
@@ -387,7 +387,7 @@ const editSheet = (workbook, sheet, planned, options, strings) => {
387
387
  const before = cellOf(workbook, text, existing);
388
388
  const element = existing.element;
389
389
  if (attributeOf(element, "", "vm") !== undefined)
390
- throw refuse(`${sheet.name}!${item.address} holds a picture or a linked data type, which this editor does not replace`, "office.rich_value");
390
+ throw refuse(`${sheet.name}!${item.address} holds a picture or a linked data type, which this editor does not replace`, "office.rich-value");
391
391
  const formula = childrenOf(element, ns, "f")[0];
392
392
  const array = arrays.find((entry) => item.row >= entry.range.top &&
393
393
  item.row <= entry.range.bottom &&
@@ -395,12 +395,12 @@ const editSheet = (workbook, sheet, planned, options, strings) => {
395
395
  item.column <= entry.range.right &&
396
396
  (entry.range.top !== entry.range.bottom || entry.range.left !== entry.range.right));
397
397
  if (array)
398
- throw refuse(`${sheet.name}!${item.address} is part of an array formula; change it in Excel`, "office.array_formula");
398
+ throw refuse(`${sheet.name}!${item.address} is part of an array formula; change it in Excel`, "office.array-formula");
399
399
  if (formula) {
400
400
  if (!options.overwriteFormulas)
401
- throw refuse(`${sheet.name}!${item.address} holds the formula =${before.formula}; pass overwriteFormulas to replace it with a value`, "office.formula_cell");
401
+ throw refuse(`${sheet.name}!${item.address} holds the formula =${before.formula}; pass overwriteFormulas to replace it with a value`, "office.formula-cell");
402
402
  if (attributeOf(formula, "", "t") === "shared" && attributeOf(formula, "", "ref") !== undefined)
403
- throw refuse(`${sheet.name}!${item.address} holds a formula that other cells share; replacing it would break theirs`, "office.shared_formula");
403
+ throw refuse(`${sheet.name}!${item.address} holds a formula that other cells share; replacing it would break theirs`, "office.shared-formula");
404
404
  formulaRemoved = true;
405
405
  }
406
406
  if (attributeOf(element, "", "t") === "s" && strings)
@@ -516,7 +516,7 @@ export const editXlsxCells = async (bytes, edits, options = {}) => {
516
516
  const address = `${columnName(column)}${row}`;
517
517
  const key = `${sheet.name}!${address}`;
518
518
  if (seen.has(key))
519
- throw refuse(`${key} is edited twice in one call`, "office.duplicate_edit");
519
+ throw refuse(`${key} is edited twice in one call`, "office.duplicate-edit");
520
520
  seen.add(key);
521
521
  bySheet.set(sheet, [...(bySheet.get(sheet) ?? []), { edit, row, column, address }]);
522
522
  }
@@ -246,6 +246,7 @@ const READS = {
246
246
  meetings: "meetings — search all reads them",
247
247
  events: "calendar events — no search reads them yet",
248
248
  crm: "CRM deals and leads — search all reads them",
249
+ tracker: "a tracker's issues, projects and comments — search all reads them",
249
250
  };
250
251
  /**
251
252
  * The accounts of `kinds` the entries name, and each entry that names none of them with the reason. A search
@@ -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;
@@ -10,15 +10,15 @@ import type { SearchCoverage } from "./messages-search.js";
10
10
  import { type MeetingAccountCoverage, type MeetingSearchItem } from "./search-all-meetings.js";
11
11
  import { type HarderOptions, type HarderResult } from "./search-harder.js";
12
12
  import type { Backend, ServerOptions, ServerSearched } from "./server-search.js";
13
- export declare const RESOURCES_SEARCHED: readonly ["messages", "mail", "notes", "events", "crm", "business", "meetings"];
13
+ export declare const RESOURCES_SEARCHED: readonly ["messages", "mail", "notes", "events", "crm", "business", "meetings", "tracker"];
14
14
  export type SearchedResource = (typeof RESOURCES_SEARCHED)[number];
15
15
  /** One hit of `search all`: a stored record, or a passage of a meeting. */
16
16
  export type SearchAllItem = SearchAllRecordItem | MeetingSearchItem;
17
17
  export interface SearchAllRecordItem {
18
- kind: "message" | "mail" | "note" | "document" | "event" | "deal" | "lead" | "crm_file" | BusinessKind;
18
+ kind: "message" | "mail" | "note" | "document" | "event" | "deal" | "lead" | "crm_file" | TrackerHitKind | BusinessKind;
19
19
  /**
20
20
  * `msg:…` for a message or a mail, `note:…`, `event:…`, `deal:…`, `lead:…`, `crmfile:<file id>` for a downloaded CRM
21
- * file, or a business ref: `invoice:…`.
21
+ * file, `tracker:<provider>/<account>/<kind>/<id>` for an issue, a project or a comment, or a business ref: `invoice:…`.
22
22
  */
23
23
  ref: string;
24
24
  provider: string;
@@ -178,6 +178,10 @@ export declare const titleWords: (text: string, refused?: string) => {
178
178
  words: string[];
179
179
  anyWord: boolean;
180
180
  };
181
+ /** A tracker hit's kind: a comment is named for the issue it is on, beside a CRM's and a message's kinds. */
182
+ export type TrackerHitKind = "issue" | "project" | "issue_comment";
183
+ /** The accounts of every tracker the store holds copies of. */
184
+ export declare const trackerAccounts: (store: MessageStore) => Promise<AccountKey[]>;
181
185
  /** The accounts of every CRM the store holds copies of. */
182
186
  export declare const crmAccounts: (store: MessageStore) => Promise<AccountKey[]>;
183
187
  /**
@@ -5,6 +5,7 @@ import { hitFiles } from "../domain/attachments.js";
5
5
  import { parseLocator } from "../domain/locator.js";
6
6
  import { senderIsMe } from "../domain/models.js";
7
7
  import { holdsKind, INTERNAL_NOTES } from "../domain/providers.js";
8
+ import { trackerTitleOf } from "../domain/tracker.js";
8
9
  import { runEmbedders } from "../embeddings/embed.js";
9
10
  import { chosenTextModel } from "../embeddings/models.js";
10
11
  import { formatMeetingReference } from "../meetings/index.js";
@@ -23,7 +24,16 @@ import { BUSINESS_WORDS_ONLY, searchBusiness } from "./search-all-business.js";
23
24
  import { meetingLane } from "./search-all-meetings.js";
24
25
  import { HARDER_CANDIDATES, reorderHarder } from "./search-harder.js";
25
26
  import { listContextOf } from "./search-kind.js";
26
- export const RESOURCES_SEARCHED = ["messages", "mail", "notes", "events", "crm", "business", "meetings"];
27
+ export const RESOURCES_SEARCHED = [
28
+ "messages",
29
+ "mail",
30
+ "notes",
31
+ "events",
32
+ "crm",
33
+ "business",
34
+ "meetings",
35
+ "tracker",
36
+ ];
27
37
  const refusal = (error, text) => {
28
38
  const { reason, span } = (error.details ?? {});
29
39
  const why = typeof reason === "string" ? reason : undefined;
@@ -117,6 +127,15 @@ const copyViewers = async (store) => {
117
127
  }
118
128
  return viewers;
119
129
  };
130
+ const TRACKER_HIT_KINDS = { issue: "issue", project: "project", comment: "issue_comment" };
131
+ /** The accounts of every tracker the store holds copies of. */
132
+ export const trackerAccounts = async (store) => (await store.accounts.accounts()).filter(({ provider }) => holdsKind(provider, "tracker"));
133
+ /** An issue is titled as people say it, `ENG-12 Fix login`; anything else by its name or its first line. */
134
+ const trackerTitle = ({ kind, record }) => {
135
+ const title = trackerTitleOf(kind, record);
136
+ const key = kind === "issue" ? record.key : undefined;
137
+ return key ? `${key} ${title}` : title;
138
+ };
120
139
  /** The accounts of every CRM the store holds copies of. */
121
140
  export const crmAccounts = async (store) => (await store.accounts.accounts()).filter(({ provider }) => holdsKind(provider, "crm"));
122
141
  /**
@@ -388,6 +407,37 @@ export const searchAll = async (store, account, asked, messenger = {}, searchMes
388
407
  for (const { provider, account } of read)
389
408
  accounts.push({ resource, provider, account });
390
409
  }
410
+ else if (resource === "tracker") {
411
+ // The registry says which providers are trackers; reading every account's rows would show hits the listed
412
+ // accounts do not account for.
413
+ const read = scope?.tracker ?? (await trackerAccounts(store));
414
+ if (!read.length)
415
+ continue;
416
+ const { words, anyWord } = titleWords(request.text, "issues, projects and comments are found by the words of their title and text only");
417
+ const found = await store.tracker.find({
418
+ words,
419
+ anyWord: anyWord || discover,
420
+ ...(request.exact ? { exact: true } : {}),
421
+ kinds: ["issue", "project", "comment"],
422
+ limit: Math.min(depth, 500),
423
+ accounts: read,
424
+ });
425
+ hasMore ||= found.hasMore;
426
+ lists.push(found.items.map(({ account: at, item, excerpt: text }) => ({
427
+ kind: TRACKER_HIT_KINDS[item.kind],
428
+ // Two sign-ins see the same issue under the same id, so the account keeps their hits apart.
429
+ ref: `tracker:${at.provider}/${at.account}/${item.kind}/${item.record.externalId}`,
430
+ provider: at.provider,
431
+ account: at.account,
432
+ ...(item.record.url ? { url: item.record.url } : {}),
433
+ title: trackerTitle(item),
434
+ timestamp: new Date(item.record.updatedAt ?? item.syncedAt).toISOString(),
435
+ text,
436
+ foundBy: ["words"],
437
+ })));
438
+ for (const { provider, account } of read)
439
+ accounts.push({ resource, provider, account });
440
+ }
391
441
  else if (resource === "business") {
392
442
  const { words, anyWord } = titleWords(request.text, BUSINESS_WORDS_ONLY);
393
443
  const found = await searchBusiness(store, {
@@ -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: {