@wirecat/cli-core 0.686.0 → 0.687.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 (44) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/dist/cli/account-remove.js +21 -3
  3. package/dist/cli/documents/testing/source-contract.js +18 -9
  4. package/dist/cli/messenger/store-maintenance-command.js +3 -2
  5. package/dist/crm/files.d.ts +16 -0
  6. package/dist/crm/files.js +56 -0
  7. package/dist/crm/foreign-contacts.d.ts +16 -4
  8. package/dist/crm/foreign-contacts.js +8 -4
  9. package/dist/crm/index.d.ts +2 -1
  10. package/dist/crm/index.js +2 -0
  11. package/dist/crm/source.d.ts +37 -0
  12. package/dist/crm/source.js +2 -1
  13. package/dist/crm/testing/index.d.ts +1 -1
  14. package/dist/crm/testing/index.js +1 -1
  15. package/dist/crm/testing/source.d.ts +31 -1
  16. package/dist/crm/testing/source.js +53 -1
  17. package/dist/crm/values.d.ts +2 -1
  18. package/dist/crm/values.js +4 -2
  19. package/dist/meetings/cli/index.d.ts +1 -1
  20. package/dist/meetings/cli/index.js +10 -6
  21. package/dist/meetings/mcp/index.d.ts +15 -15
  22. package/dist/meetings/read-through.d.ts +2 -0
  23. package/dist/meetings/read-through.js +7 -2
  24. package/dist/meetings/source.d.ts +2 -2
  25. package/dist/oauth/storage.js +21 -4
  26. package/dist/search/lucene/resolved.d.ts +2 -0
  27. package/dist/services/documents/plan.js +26 -5
  28. package/dist/services/documents/sync.js +4 -1
  29. package/dist/services/embeddings-search.js +33 -11
  30. package/dist/store/accounts.d.ts +2 -1
  31. package/dist/store/exports.d.ts +1 -0
  32. package/dist/store/exports.js +1 -0
  33. package/dist/store/recover.js +2 -0
  34. package/dist/store/sqlite/account-purge.js +1 -0
  35. package/dist/store/sqlite/crm-files.d.ts +67 -0
  36. package/dist/store/sqlite/crm-files.js +172 -0
  37. package/dist/store/sqlite/lucene.js +11 -5
  38. package/dist/store/sqlite/manifest.js +2 -0
  39. package/dist/store/sqlite/migrations.generated.js +17 -0
  40. package/dist/store/sqlite/schema.d.ts +329 -0
  41. package/dist/store/sqlite/schema.js +28 -0
  42. package/dist/store/store.d.ts +3 -0
  43. package/dist/store/store.js +5 -0
  44. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -5,6 +5,64 @@ 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.687.0 — 16.11.2026
9
+
10
+ ### Added
11
+
12
+ - **CRM client files in the store (store version 68).** `crm_files` keeps each downloaded file of a deal, lead,
13
+ contact or company with its owner record, the record's assignee at download, the local path and the extracted
14
+ text, in its own word index `crm_file_words`; never a download link. `store.crmFiles` saves, lists and finds them,
15
+ a limited profile only those of records assigned to its user: a deal's or lead's as the copy assigns it now, so a
16
+ reassigned deal's files go with it. `store rebuild`, `store recover` and the
17
+ integrity check know the new index; an account's purge removes its rows.
18
+ - **`CrmSource.files(owner)`** (`@wirecat/cli-core/crm`): one record's files read live with the record's assignee,
19
+ each with an `open()` that keeps the tokened link inside the adapter; `crmFileId` and `parseCrmFileId` for the opaque
20
+ file id.
21
+ - **`withoutFileLinks(body)`** replaces every file link in a CRM answer with `[link removed]`, for `api call`: the
22
+ download keys (every `…Machine`, `DOWNLOAD_URL`, `publicUrl`, `CALL_RECORD_URL` and the like, amoCRM's
23
+ `_links.download`), a webhook, `auth`, `access_token`, `api_token` and `X-Amz-Signature` anywhere, and a portal
24
+ path with `token`. `crmValuesOf` applies it to every custom value, so a file field's
25
+ link reaches neither the store nor an answer.
26
+ - **`fakeCrmSource({ files })`** and `FAKE_FILE_TOKEN` in `@wirecat/cli-core/crm/testing`.
27
+
28
+ ### Changed — may break callers
29
+
30
+ - **The daily limit on other people's records covers deals and leads.** `foreignContacts(...).spend` takes any CRM
31
+ kind and a record with only `externalId` and `assignee`; a deal or lead is the sign-in's own when assigned to its
32
+ user. The refusal says "records that are not yours" instead of "contacts and companies".
33
+ - **`account remove --delete-data` lists and deletes the CRM files the CLI downloaded** under its state folder
34
+ (`store.crmFiles.savedPaths`), in `--dry-run` and the confirmation too; a copy saved elsewhere stays.
35
+
36
+ ### Fixed
37
+
38
+ - **A document the sign-in may not read (403) is skipped as a gone one (404) is**, listed among the skipped files with
39
+ the provider's reason. Before, it stayed pending with its error on every sync: the pass never completed, the change
40
+ cursor did not move, and later changes were not read.
41
+ - **A documents sync takes the start token, each root's own metadata in a full walk and each page of changes from the
42
+ request budget**, as it does a listing. Before, they were free, so under the MCP's 45 s deadline a provider with
43
+ slow reads ended the first run at the deadline itself, with no time to answer. A root's metadata is kept on the walk, so a run stopped before the
44
+ root's listing does not read it again.
45
+ - **`documentSourceContract`'s fault cases follow**: the 403 case requires the pass to complete and the next pass to
46
+ run, and the deadline case requires each run to leave the budget's answer reserve.
47
+ - **`search conversations` across several chats gives each chat a share**, so a large group no longer fills the
48
+ results with near matches and hides a small chat's clear answer. The meaning half reads the 500 nearest
49
+ conversations and ranks each chat's best 20 by how far they lead that chat's 20th best; the word half reads at most
50
+ 20 messages per chat. On a test store of 10 chats (4 large groups) with 40 questions, a key message reached the top
51
+ 20 for 19 questions instead of 10, and the top 5 for 11 instead of 8, at about 0.7 s more per query. One chat
52
+ (`--chat`) is searched as before. `QueryExecution` takes `perChat`, the most hits a page takes from one chat.
53
+ - **`meetings list` and `meetings show` stop when the run is stopped.** A read of the service that the run's stop
54
+ signal cut short was taken as a failed service and answered from the store. Now the stop is the answer, and the
55
+ service's `find` and `get` receive the signal as a new last argument. A host passes `signal` in
56
+ `addMeetingCommands`' deps; `MeetingServerAccess.signal` carries it for a direct call.
57
+ - **A sign-in with `storage: "keyring"` stops before the browser when the keyring does not answer.** #3041 made the
58
+ check before a sign-in read an unreachable keyring as "no old entry", so the browser opened and the save failed
59
+ after it. That holds only where the save can fall back to the file; with keyring-only storage the check fails up
60
+ front again, with cli-base's `keyring.unreachable`.
61
+ - **A sign-in store passes cli-base's own keyring errors through.** `credentialStorage` turned every failed read
62
+ into `oauth.not-saved`. A `CliError` from cli-base, such as `keyring.unreachable` (the keyring failed and the file
63
+ holds no entry), now reaches the answer with its own words. Before a sign-in, an old entry that cannot be read for
64
+ `keyring.unreachable` counts as no old entry, so a sign-in on a machine with no keyring still saves to the file.
65
+
8
66
  ## 0.686.0 — 16.11.2026
9
67
 
10
68
  ### Added
@@ -1,4 +1,4 @@
1
- import { existsSync, rmSync } from "node:fs";
1
+ import { existsSync, lstatSync, rmSync } from "node:fs";
2
2
  import { homedir } from "node:os";
3
3
  import { resolve as absolute, isAbsolute, join, sep } from "node:path";
4
4
  import { CliError, Credentials, isMovedRun, resolvePaths, saveConfigFile, } from "@wirecat/cli-base";
@@ -208,6 +208,19 @@ export const accountRemoveCommand = (app, removal, options = {}) => logsInOrOut(
208
208
  // The tool's own sign-out deletes its session where the run's state folder says; here that folder is the owner's.
209
209
  const signsOut = !(movedFolders && inOwners(state));
210
210
  const removed = signsOut ? [signIn] : [];
211
+ // Single files, removed without `recursive`: a path the store names is never a folder to empty.
212
+ const crmFiles = new Set();
213
+ const crmFilesOf = async (key, root, guard) => {
214
+ const store = await openStore({ env, command: app.command });
215
+ try {
216
+ // Only what the CLI downloaded into its state folder; a copy saved with --dir elsewhere is the owner's.
217
+ const saved = (await store.crmFiles.savedPaths(key)).map((path) => absolute(path));
218
+ return guard(saved.filter((path) => within(path, root))).filter((path) => existsSync(path) && lstatSync(path).isFile());
219
+ }
220
+ finally {
221
+ await store.close();
222
+ }
223
+ };
211
224
  const kept = [...ownersKept, ...(signsOut ? [] : [{ ...signIn, reason: ownersReason }])];
212
225
  // An entry the environment supplies is not this tool's to remove.
213
226
  const saved = (store, name) => (store.read(name)?.source ?? "environment") !== "environment";
@@ -233,8 +246,13 @@ export const accountRemoveCommand = (app, removal, options = {}) => logsInOrOut(
233
246
  removed.push({ kind: "file", target: file });
234
247
  if (accountName && storeHere && ownersStore)
235
248
  kept.push({ kind: "store", target: accountName, reason: ownersReason });
236
- else if (accountName && storeHere)
249
+ else if (accountName && storeHere && account) {
237
250
  removed.push({ kind: "store", target: accountName });
251
+ for (const file of await crmFilesOf(account, state, theRun)) {
252
+ removed.push({ kind: "file", target: file });
253
+ crmFiles.add(file);
254
+ }
255
+ }
238
256
  else
239
257
  kept.push({
240
258
  kind: "store",
@@ -316,7 +334,7 @@ export const accountRemoveCommand = (app, removal, options = {}) => logsInOrOut(
316
334
  await removeSchedules(app, system, state, schedules, env);
317
335
  for (const entry of removed)
318
336
  if (entry.kind === "file")
319
- rmSync(entry.target, { recursive: true, force: true });
337
+ rmSync(entry.target, crmFiles.has(entry.target) ? { force: true } : { recursive: true, force: true });
320
338
  if (removal.forgetConfig && !ownersConfig)
321
339
  for (const target of removal.forgetConfig(profile, hooks))
322
340
  removed.push({ kind: "config", target });
@@ -1,6 +1,6 @@
1
1
  import assert from "node:assert/strict";
2
2
  import { isCliError } from "@wirecat/cli-base";
3
- import { runBudget } from "../../../background/budget.js";
3
+ import { ANSWER_RESERVE_MS, runBudget } from "../../../background/budget.js";
4
4
  import { DEFAULT_AGENT_COOPERATIVE_MS } from "../../execution.js";
5
5
  const MAX_ENTRIES = 500;
6
6
  const walk = async ({ source, root, isFolder }) => {
@@ -45,19 +45,22 @@ const watched = (source, before) => new Proxy(source, {
45
45
  },
46
46
  });
47
47
  /**
48
- * Syncs until the walk is done and nothing is left but reported errors, and gives the last call's answer and ids and
49
- * how many reads the calls made. A file the provider refuses stays pending with its error, sync after sync.
48
+ * Syncs until the pass is complete, and gives the last call's answer and ids, every file the calls skipped, and how
49
+ * many reads they made.
50
50
  */
51
51
  const finish = async (sync) => {
52
52
  let reads = 0;
53
+ const skipped = new Set();
53
54
  for (let call = 1; call <= MOST_SYNCS; call++) {
54
55
  const { result, saved } = await sync({
55
56
  wrap: (source) => watched(source, () => {
56
57
  reads++;
57
58
  }),
58
59
  });
59
- if (!result.walk && result.pending === result.errors.length)
60
- return { result, saved: [...saved].sort(), reads };
60
+ for (const one of result.skipped)
61
+ skipped.add(one.id);
62
+ if (result.complete && result.pending === 0)
63
+ return { result, saved: [...saved].sort(), skipped, reads };
61
64
  }
62
65
  throw new assert.AssertionError({ message: `the sync is still unfinished after ${MOST_SYNCS} calls` });
63
66
  };
@@ -207,11 +210,17 @@ const faultCases = (make) => [
207
210
  const sync = fixture.faults?.sync;
208
211
  if (!sync)
209
212
  return;
210
- const { result, saved } = await finish(sync);
213
+ // A refused file is skipped as a gone one is, so the pass completes and its change cursor moves on.
214
+ const { saved, skipped } = await finish(sync);
211
215
  assert.ok(!saved.includes(id), `the sync does not hold ${id}, which answers ${status}`);
212
216
  assert.ok(saved.length > 0, `the sync imports the documents that still answer beside ${id}`);
213
217
  if (status === 403)
214
- assert.ok([...result.errors, ...result.skipped].some((one) => one.id === id), `the sync names ${id} among its errors or skipped files, not silently left out`);
218
+ assert.ok(skipped.has(id), `the sync names ${id} among its skipped files with the reason`);
219
+ if (!fixture.change)
220
+ return;
221
+ await fixture.change();
222
+ // Throws when the refused file holds the next pass too.
223
+ await finish(sync);
215
224
  },
216
225
  })),
217
226
  {
@@ -293,8 +302,8 @@ const faultCases = (make) => [
293
302
  clock += SLOW_CALL_MS;
294
303
  }),
295
304
  });
296
- assert.ok(clock <= deadline.endsAt, `sync ${call} ended by its deadline, ${clock - deadline.endsAt} ms late`);
297
- if (!result.walk && result.pending === result.errors.length) {
305
+ assert.ok(clock <= deadline.endsAt - ANSWER_RESERVE_MS, `sync ${call} left time to answer before its deadline: ended ${clock - deadline.endsAt} ms from it`);
306
+ if (result.complete && result.pending === 0) {
298
307
  assert.ok(stopped, "a slow provider's tree takes more than one run under the deadline");
299
308
  assert.deepEqual([...saved].sort(), expected.saved, "the runs together hold what one whole sync does");
300
309
  return;
@@ -16,7 +16,7 @@ import { migrate } from "../../store/migrations.js";
16
16
  import { openCache } from "../../store/open.js";
17
17
  import { storePath } from "../../store/path.js";
18
18
  import { deleteCopy, repairStore } from "../../store/repair.js";
19
- import { drainNoteIndex, dropAllUnusedVectors, fillSearchIndex, fillStems, involvementStoreOver, noteIndexState, openSqlite, openStore, orphanPointers, pendingNormalization, resetAttachmentWords, resetNoteIndex, resetSearchIndex, resetStems, rollBack, searchIndexState, stemmerCache, stemsState, vectorIndexCounts, } from "../../store/store.js";
19
+ import { drainNoteIndex, dropAllUnusedVectors, fillSearchIndex, fillStems, involvementStoreOver, noteIndexState, openSqlite, openStore, orphanPointers, pendingNormalization, resetAttachmentWords, resetCrmFileWords, resetNoteIndex, resetSearchIndex, resetStems, rollBack, searchIndexState, stemmerCache, stemsState, vectorIndexCounts, } from "../../store/store.js";
20
20
  import { environmentOf, outputFor } from "../context.js";
21
21
  import { destroysNothing, grantsAuthority, LOCAL_READ, LOCAL_WRITE } from "../effects.js";
22
22
  import { itemOf, renderAnswer, snakeKeys } from "../envelope.js";
@@ -326,6 +326,7 @@ const inspect = (path) => reading(path, (database) => {
326
326
  ...(wordIndex ? [[WORD_INDEX, indexIntegrity(database, WORD_INDEX, 0)]] : []),
327
327
  ...(stems ? [["message_stems", indexIntegrity(database, "message_stems", 0)]] : []),
328
328
  ...(schema.version > 0 ? [["attachment_words", indexIntegrity(database, "attachment_words", 0)]] : []),
329
+ ...(schema.version >= 68 ? [["crm_file_words", indexIntegrity(database, "crm_file_words", 0)]] : []),
329
330
  ]);
330
331
  const size = bytesOf(path) + bytesOf(`${path}-wal`);
331
332
  const { bavail, bsize } = statfsSync(dirname(path));
@@ -530,7 +531,7 @@ const reindexCommand = (owner) => destroysNothing(annotate(new Command("rebuild"
530
531
  throw new CliError("validation_error", `the store is behind this build — \`${lineOf(this, "store migrate")}\` first`);
531
532
  }
532
533
  resetSearchIndex(database);
533
- const fileTexts = resetAttachmentWords(database);
534
+ const fileTexts = resetAttachmentWords(database) + resetCrmFileWords(database);
534
535
  const words = buildWordIndex(database, (note) => renderer.note(note));
535
536
  return {
536
537
  path,
@@ -0,0 +1,16 @@
1
+ import { type CrmFileOwner, type CrmFileSourceKind } from "./source.js";
2
+ /** A file's id as `files list` prints it: the owner and the source first, so a download knows whom to ask. */
3
+ export declare const crmFileId: (owner: CrmFileOwner, source: CrmFileSourceKind, providerId: string) => string;
4
+ /** The parts of a file id; a malformed one is refused before anything is asked. */
5
+ export declare const parseCrmFileId: (id: string) => {
6
+ owner: CrmFileOwner;
7
+ source: CrmFileSourceKind;
8
+ providerId: string;
9
+ };
10
+ export declare const LINK_REMOVED = "[link removed]";
11
+ /**
12
+ * A provider's answer with every file link replaced by `[link removed]`, the rest as given: such a link lets anyone
13
+ * download the file, so it must reach no output, store or log. Covers the download keys, amoCRM's `_links.download`,
14
+ * and any string holding a webhook, a credential, or a portal path with a token.
15
+ */
16
+ export declare const withoutFileLinks: <T>(body: T) => T;
@@ -0,0 +1,56 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { CRM_KINDS } from "../domain/crm.js";
3
+ import { CRM_FILE_SOURCES } from "./source.js";
4
+ /** A file's id as `files list` prints it: the owner and the source first, so a download knows whom to ask. */
5
+ export const crmFileId = (owner, source, providerId) => `${owner.kind}:${owner.id}:${source}:${providerId}`;
6
+ /** The parts of a file id; a malformed one is refused before anything is asked. */
7
+ export const parseCrmFileId = (id) => {
8
+ const [kind = "", owner = "", source = "", ...rest] = id.trim().split(":");
9
+ const providerId = rest.join(":");
10
+ if (!CRM_KINDS.includes(kind) ||
11
+ !/^[\w.-]+$/u.test(owner) ||
12
+ !CRM_FILE_SOURCES.includes(source) ||
13
+ !providerId)
14
+ throw new CliError("validation_error", "a file id is <owner kind>:<owner id>:<source>:<id>, as files list prints it, such as deal:12:record:345", { reason: "ref.malformed" });
15
+ return { owner: { kind: kind, id: owner }, source: source, providerId };
16
+ };
17
+ const foldKey = (key) => key.replaceAll("_", "").toLowerCase();
18
+ /**
19
+ * The keys a file's download link sits under, folded: Bitrix24's "Types of Links in Responses" (apidocs
20
+ * files/how-to-download-files), a generated document's `publicUrl` (opens it with no sign-in), a call's record, and
21
+ * every `…Machine` key. A view link alone (`url`, `urlShow`) is not one: a link field holds `{ url, title }` the same way.
22
+ */
23
+ const DOWNLOAD_KEYS = new Set(["DOWNLOAD_URL", "downloadUrl", "fileUrl", "CALL_RECORD_URL", "archiveLink", "publicUrl"].map(foldKey));
24
+ const isDownloadKey = (key) => DOWNLOAD_KEYS.has(foldKey(key)) || foldKey(key).endsWith("machine");
25
+ // A webhook's `/rest/<user>/<code>/` is the webhook itself.
26
+ const WEBHOOK = /\/rest\/\d+\/[^/\s"'?#]+\//iu;
27
+ // A portal's tokened paths, relative ones too; a site the owner typed, `?token=promo` and all, is none.
28
+ const PORTAL_PATH = /\/rest\/|show_file\.php/iu;
29
+ // `&amp;` too: a link copied out of HTML, as a comment or a mail body holds one.
30
+ const TOKEN_QUERY = /(?:[?&]|&amp;)(?:auth|token|access_token)=[^&#\s]/iu;
31
+ // Credentials whatever the path: a Bitrix24 `auth`, an OAuth or API token, a signed storage link.
32
+ const CREDENTIAL = /(?:[?&]|&amp;)(?:auth|access_token|api_token|x-amz-signature)=[^&#\s]/iu;
33
+ const isTokened = (value) => WEBHOOK.test(value) || CREDENTIAL.test(value) || (PORTAL_PATH.test(value) && TOKEN_QUERY.test(value));
34
+ export const LINK_REMOVED = "[link removed]";
35
+ /**
36
+ * A provider's answer with every file link replaced by `[link removed]`, the rest as given: such a link lets anyone
37
+ * download the file, so it must reach no output, store or log. Covers the download keys, amoCRM's `_links.download`,
38
+ * and any string holding a webhook, a credential, or a portal path with a token.
39
+ */
40
+ export const withoutFileLinks = (body) => {
41
+ const walk = (value, key) => {
42
+ if (typeof value === "string")
43
+ return isTokened(value) ? LINK_REMOVED : value;
44
+ if (Array.isArray(value))
45
+ return value.map((one) => walk(one));
46
+ if (value === null || typeof value !== "object")
47
+ return value;
48
+ return Object.fromEntries(Object.entries(value).map(([name, one]) => [
49
+ name,
50
+ (isDownloadKey(name) || (key === "_links" && name === "download")) && one !== null && one !== ""
51
+ ? LINK_REMOVED
52
+ : walk(one, name),
53
+ ]));
54
+ };
55
+ return walk(body);
56
+ };
@@ -1,10 +1,18 @@
1
- import type { CrmOrganization, CrmPerson } from "../domain/crm.js";
1
+ import type { CrmKind, CrmOrganization, CrmPerson } from "../domain/crm.js";
2
2
  import type { AppIdentity } from "../ports/app.js";
3
3
  import type { AccountKey } from "../store/types.js";
4
4
  import type { CrmLiveKind, CrmSource } from "./source.js";
5
- /** The owner's rule (NEED-2487): a user sees at most this many other contacts' or companies' details a UTC day. */
5
+ /**
6
+ * The owner's rule (NEED-2487, NEED-2703 B): a user sees at most this many other people's records a UTC day: a
7
+ * contact's or company's details, or a deal's, lead's, contact's or company's files.
8
+ */
6
9
  export declare const DAILY_FOREIGN_CONTACTS = 100;
7
10
  type Live = CrmPerson | CrmOrganization;
11
+ /** What a spend needs of a record: its id and whom it is assigned to. */
12
+ type Owned = {
13
+ externalId: string;
14
+ assignee?: string | null;
15
+ };
8
16
  /** Where the day's count of one CRM user is kept: the CLI's state folder, a file per account and user. */
9
17
  export declare const foreignContactsPathFor: (app: AppIdentity, account: AccountKey, env?: NodeJS.ProcessEnv, user?: string) => string;
10
18
  export interface ForeignContacts {
@@ -12,8 +20,12 @@ export interface ForeignContacts {
12
20
  strip<T extends Live>(kind: CrmLiveKind, records: T[]): Promise<T[]>;
13
21
  /** Whether the sign-in may see this record whole: its own client, or an administrator's or unlimited CRM's. */
14
22
  own(kind: CrmLiveKind, record: Live): Promise<boolean>;
15
- /** One record shown whole: a foreign one spends one of the day's slots, the same one again that day is free. */
16
- spend(kind: CrmLiveKind, record: Live): Promise<void>;
23
+ /**
24
+ * One record shown whole, or its files read: a foreign one spends one of the day's slots, the same one again that
25
+ * day is free. A deal or lead is the sign-in's own when assigned to its user; a contact or company also when
26
+ * `ownClients` names it.
27
+ */
28
+ spend(kind: CrmKind, record: Owned): Promise<void>;
17
29
  }
18
30
  /**
19
31
  * The shared rule over one source, for anyone but the CRM's administrator. A source without `isAdmin` is not
@@ -2,7 +2,10 @@ import { readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { CliError, resolvePaths, writeSecurely } from "@wirecat/cli-base";
4
4
  import { withFileLockAsync } from "../sends/file-lock.js";
5
- /** The owner's rule (NEED-2487): a user sees at most this many other contacts' or companies' details a UTC day. */
5
+ /**
6
+ * The owner's rule (NEED-2487, NEED-2703 B): a user sees at most this many other people's records a UTC day: a
7
+ * contact's or company's details, or a deal's, lead's, contact's or company's files.
8
+ */
6
9
  export const DAILY_FOREIGN_CONTACTS = 100;
7
10
  /** Where the day's count of one CRM user is kept: the CLI's state folder, a file per account and user. */
8
11
  export const foreignContactsPathFor = (app, account, env = process.env, user) => join(resolvePaths({ appName: app.appName, prefix: app.envPrefix, env }).state, "crm", "foreign-contacts", `${[account.provider, account.account, ...(user ? [user] : [])].join("-").replace(/[^\w.-]+/gu, "_")}.json`);
@@ -52,7 +55,7 @@ file, options = {}) => {
52
55
  const self = source.self ? String(await source.self()) : undefined;
53
56
  const mine = new Set(records.filter((one) => self && one.assignee === self).map((one) => one.externalId));
54
57
  const rest = records.filter((one) => !mine.has(one.externalId)).map((one) => one.externalId);
55
- if (rest.length && source.ownClients)
58
+ if (rest.length && source.ownClients && (kind === "person" || kind === "organization"))
56
59
  for (const id of await source.ownClients(kind, rest))
57
60
  mine.add(id);
58
61
  return mine;
@@ -84,8 +87,9 @@ file, options = {}) => {
84
87
  if (shown.seen.includes(key))
85
88
  return;
86
89
  if (shown.seen.length >= DAILY_FOREIGN_CONTACTS)
87
- throw new CliError("permission_error", `${DAILY_FOREIGN_CONTACTS} contacts and companies that are not your clients were shown today, the ` +
88
- "most a day; your own clients are not counted, and the CRM's administrator has no limit", { reason: "crm.foreign-contacts-spent", limit: DAILY_FOREIGN_CONTACTS });
90
+ throw new CliError("permission_error", `${DAILY_FOREIGN_CONTACTS} records that are not yours (contacts, companies, or the files of deals, ` +
91
+ "leads, contacts and companies) were read today, the most a day; your own records are not counted, " +
92
+ "and the CRM's administrator has no limit", { reason: "crm.foreign-contacts-spent", limit: DAILY_FOREIGN_CONTACTS });
89
93
  writeSecurely(path, JSON.stringify({ day, seen: [...shown.seen, key] }), 0o600);
90
94
  }, options.lockWaitMs);
91
95
  },
@@ -1,7 +1,8 @@
1
+ export { crmFileId, LINK_REMOVED, parseCrmFileId, withoutFileLinks } from "./files.js";
1
2
  export { DAILY_FOREIGN_CONTACTS, type ForeignContacts, foreignContacts, foreignContactsPathFor, refuseForeignClientReads, } from "./foreign-contacts.js";
2
3
  export { type ProviderCallOptions, providerCall } from "./provider-call.js";
3
4
  export { type CrmConditionHooks, type CrmQueryField, conditionsOf, customConditions, customNames, filterableFields, selectedCodes, wantedCodes, withCustomFields, } from "./query.js";
4
- export type { CrmCallContext, CrmChanges, CrmCondition, CrmGap, CrmIdPage, CrmLiveKind, CrmLiveQuery, CrmPage, CrmSource, CrmSourceTraits, } from "./source.js";
5
+ export { CRM_FILE_SOURCES, type CrmCallContext, type CrmChanges, type CrmCondition, type CrmFile, type CrmFileOwner, type CrmFileSourceKind, type CrmFiles, type CrmGap, type CrmIdPage, type CrmLiveKind, type CrmLiveQuery, type CrmOpenableFile, type CrmPage, type CrmSource, type CrmSourceTraits, } from "./source.js";
5
6
  export { type CrmCursor, type CrmSyncIssue, type CrmSyncOptions, type CrmSyncReport, type CrmSyncResult, crmGapsOf, crmStatus, cursorName, parseCrmCursor, syncCrm, } from "./sync.js";
6
7
  /** An adapter's readers of a CRM's raw JSON: `crmValues.text(raw.name)`, `crmValues.time(raw.created_at)`. */
7
8
  export * as crmValues from "./values.js";
package/dist/crm/index.js CHANGED
@@ -1,6 +1,8 @@
1
+ export { crmFileId, LINK_REMOVED, parseCrmFileId, withoutFileLinks } from "./files.js";
1
2
  export { DAILY_FOREIGN_CONTACTS, foreignContacts, foreignContactsPathFor, refuseForeignClientReads, } from "./foreign-contacts.js";
2
3
  export { providerCall } from "./provider-call.js";
3
4
  export { conditionsOf, customConditions, customNames, filterableFields, selectedCodes, wantedCodes, withCustomFields, } from "./query.js";
5
+ export { CRM_FILE_SOURCES, } from "./source.js";
4
6
  export { crmGapsOf, crmStatus, cursorName, parseCrmCursor, syncCrm, } from "./sync.js";
5
7
  /** An adapter's readers of a CRM's raw JSON: `crmValues.text(raw.name)`, `crmValues.time(raw.created_at)`. */
6
8
  export * as crmValues from "./values.js";
@@ -81,6 +81,37 @@ export interface CrmCallContext {
81
81
  */
82
82
  scope?: CrmScope;
83
83
  }
84
+ /** The record a file hangs on. */
85
+ export interface CrmFileOwner {
86
+ kind: CrmKind;
87
+ /** The CRM's id of the record. */
88
+ id: string;
89
+ }
90
+ /** Where on its record a file hangs: the record's own files, a file field, a generated document, an activity, a comment. */
91
+ export declare const CRM_FILE_SOURCES: readonly ["record", "field", "document", "activity", "comment"];
92
+ export type CrmFileSourceKind = (typeof CRM_FILE_SOURCES)[number];
93
+ /** One file of a CRM record as the CRM lists it. Never a link: its bytes come through `open`. */
94
+ export interface CrmFile {
95
+ /** `<owner kind>:<owner id>:<source kind>:<provider id>` (`crmFileId`): opaque, never a link. */
96
+ id: string;
97
+ name: string;
98
+ /** Bytes, when the CRM says. */
99
+ size: number | null;
100
+ mime: string | null;
101
+ /** Epoch ms. */
102
+ created: number | null;
103
+ owner: CrmFileOwner;
104
+ source: CrmFileSourceKind;
105
+ }
106
+ /** A listed file with its download: each `open` asks the CRM for a fresh link, kept inside the adapter. */
107
+ export interface CrmOpenableFile extends CrmFile {
108
+ open(signal?: AbortSignal): Promise<ReadableStream<Uint8Array>>;
109
+ }
110
+ export interface CrmFiles {
111
+ /** The owner record's assignee, the CRM user's id, as `self()` names users; what the day's limit is checked by. */
112
+ assignee: string | null;
113
+ files: CrmOpenableFile[];
114
+ }
84
115
  /** One CRM account, as an adapter reads it. The engine never sees a provider word. */
85
116
  export interface CrmSource {
86
117
  /** The registry name: `bitrix24`, `pipedrive`, `hubspot`, `amocrm`. */
@@ -147,4 +178,10 @@ export interface CrmSource {
147
178
  * is kept and counts once the deal arrives.
148
179
  */
149
180
  stageHistory?(kind: DealKind, since: number, after?: string, context?: CrmCallContext): Promise<CrmPage<CrmStageEntry>>;
181
+ /**
182
+ * One record's files, read live, with the record's assignee. A link to a file never leaves the adapter: not in a
183
+ * record, an error or an answer. A kind of file the sign-in may not read is a `context.gap` naming the scope; the
184
+ * others are still listed. Null when the CRM has no such record or the sign-in cannot see it.
185
+ */
186
+ files?(owner: CrmFileOwner, context?: CrmCallContext): Promise<CrmFiles | null>;
150
187
  }
@@ -1 +1,2 @@
1
- export {};
1
+ /** Where on its record a file hangs: the record's own files, a file field, a generated document, an activity, a comment. */
2
+ export const CRM_FILE_SOURCES = ["record", "field", "document", "activity", "comment"];
@@ -1,5 +1,5 @@
1
1
  export { ACME_CALENDAR, ACME_MAIL, ACME_NOW, ACME_OPENED, ACME_PORTAL, ACME_TELEGRAM, type AcmeScenario, acmeScenario, } from "./acme-scenario.js";
2
- export { exampleDeal, exampleLead, exampleOrganization, examplePerson, FAKE_CRM_ALIASES, type FakeCrmSource, type FakeCrmSourceOptions, type FakeCrmWrite, fakeCrmSource, LEAD_PIPELINE, SALES_PIPELINE, SOURCE_FIELD, } from "./source.js";
2
+ export { exampleDeal, exampleLead, exampleOrganization, examplePerson, FAKE_CRM_ALIASES, FAKE_FILE_TOKEN, type FakeCrmFile, type FakeCrmSource, type FakeCrmSourceOptions, type FakeCrmWrite, fakeCrmSource, LEAD_PIPELINE, SALES_PIPELINE, SOURCE_FIELD, } from "./source.js";
3
3
  export { type CrmSourceFaults, type CrmSourceFixture, crmSourceContract } from "./source-contract.js";
4
4
  export { CRM_TRAIT_COMBINATIONS, type CrmSyncFixture, crmSyncContract } from "./sync-contract.js";
5
5
  export { type CrmWriteFixture, crmWriteContract } from "./write-contract.js";
@@ -1,5 +1,5 @@
1
1
  export { ACME_CALENDAR, ACME_MAIL, ACME_NOW, ACME_OPENED, ACME_PORTAL, ACME_TELEGRAM, acmeScenario, } from "./acme-scenario.js";
2
- export { exampleDeal, exampleLead, exampleOrganization, examplePerson, FAKE_CRM_ALIASES, fakeCrmSource, LEAD_PIPELINE, SALES_PIPELINE, SOURCE_FIELD, } from "./source.js";
2
+ export { exampleDeal, exampleLead, exampleOrganization, examplePerson, FAKE_CRM_ALIASES, FAKE_FILE_TOKEN, fakeCrmSource, LEAD_PIPELINE, SALES_PIPELINE, SOURCE_FIELD, } from "./source.js";
3
3
  export { crmSourceContract } from "./source-contract.js";
4
4
  export { CRM_TRAIT_COMBINATIONS, crmSyncContract } from "./sync-contract.js";
5
5
  export { crmWriteContract } from "./write-contract.js";
@@ -1,6 +1,6 @@
1
1
  import type { CrmActivity, CrmField, CrmItem, CrmKind, CrmOrganization, CrmPerson, CrmPipeline, CrmRecords, CrmStageEntry } from "../../domain/crm.js";
2
2
  import type { DealKind } from "../../domain/deals.js";
3
- import type { CrmLiveKind, CrmSource, CrmSourceTraits } from "../source.js";
3
+ import type { CrmFileOwner, CrmFileSourceKind, CrmLiveKind, CrmSource, CrmSourceTraits } from "../source.js";
4
4
  import { type CrmVerb, type CrmWriteCapabilities, type CrmWriter } from "../writer.js";
5
5
  export interface FakeCrmSourceOptions {
6
6
  traits?: Partial<CrmSourceTraits>;
@@ -18,6 +18,34 @@ export interface FakeCrmSourceOptions {
18
18
  stageHistory?: CrmStageEntry[];
19
19
  /** Gives the fake `activities()` over these, the array read on each call, by `updatedAt` after `since`. */
20
20
  activities?: CrmActivity[];
21
+ /**
22
+ * Gives the fake `files()` over these, the array read on each call. Each listed file also carries a `url` with
23
+ * `FAKE_FILE_TOKEN`, as a careless adapter's might, so a test sees whether the token gets out.
24
+ */
25
+ files?: FakeCrmFile[];
26
+ }
27
+ /** The token in every fake file link: it must reach no output, store, file or error. */
28
+ export declare const FAKE_FILE_TOKEN = "fake-file-token-5f2a9c";
29
+ /** A file of one of the fake's records. */
30
+ export interface FakeCrmFile {
31
+ owner: CrmFileOwner;
32
+ /** `record` when absent. */
33
+ source?: CrmFileSourceKind;
34
+ /** The CRM's own id of the file. */
35
+ id: string;
36
+ name: string;
37
+ bytes: string | Uint8Array;
38
+ mime?: string | null;
39
+ /** Epoch ms. */
40
+ created?: number | null;
41
+ /** What the CRM says the size is; the bytes' length when absent, unknown when null. */
42
+ size?: number | null;
43
+ /** `open` fails with an error that names the tokened link, as a raw fetch error would. */
44
+ broken?: boolean;
45
+ /** `open` answers an HTML page, as a CRM does for a link that is not a server link. */
46
+ html?: boolean;
47
+ /** The link answers from this host instead of the account's own. */
48
+ host?: string;
21
49
  }
22
50
  /** One write the fake CRM was sent, in order. */
23
51
  export interface FakeCrmWrite {
@@ -57,6 +85,8 @@ export interface FakeCrmSource extends CrmSource, CrmWriter {
57
85
  ids: number;
58
86
  list: number;
59
87
  get: number;
88
+ files: number;
89
+ open: number;
60
90
  };
61
91
  /** Writes sent, refused ones included. */
62
92
  readonly writes: FakeCrmWrite[];
@@ -1,7 +1,10 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { foldName } from "../../resolve.js";
3
+ import { crmFileId } from "../files.js";
3
4
  import { crmWindowOf, walk } from "../walk.js";
4
5
  import { CRM_VERBS, } from "../writer.js";
6
+ /** The token in every fake file link: it must reach no output, store, file or error. */
7
+ export const FAKE_FILE_TOKEN = "fake-file-token-5f2a9c";
5
8
  /** Custom codes the fake refuses: each is a neutral field under another name. */
6
9
  export const FAKE_CRM_ALIASES = ["stage", "pipeline", "owner", "status"];
7
10
  /** When the fake CRM's changes happened: well before any `now` a contract syncs at. */
@@ -51,7 +54,7 @@ export const fakeCrmSource = (options = {}) => {
51
54
  const expired = new Map();
52
55
  const denied = new Set();
53
56
  let hidden = false;
54
- const calls = { pipelines: 0, fields: 0, changes: 0, ids: 0, list: 0, get: 0 };
57
+ const calls = { pipelines: 0, fields: 0, changes: 0, ids: 0, list: 0, get: 0, files: 0, open: 0 };
55
58
  const capabilities = {
56
59
  kinds: ["deal", "lead", "person", "organization"],
57
60
  verbs: CRM_VERBS,
@@ -266,6 +269,21 @@ export const fakeCrmSource = (options = {}) => {
266
269
  return { items, hasMore: false, cursor: String(newest) };
267
270
  },
268
271
  }),
272
+ ...(options.files === undefined
273
+ ? {}
274
+ : {
275
+ files: async (owner) => {
276
+ calls.files += 1;
277
+ const record = of(owner.kind).get(owner.id);
278
+ if (!record || record.deleted)
279
+ return null;
280
+ const listed = options.files.filter((one) => one.owner.kind === owner.kind && one.owner.id === owner.id);
281
+ return {
282
+ assignee: record.record.assignee ?? null,
283
+ files: listed.map((one) => fakeFile(one, () => (calls.open += 1))),
284
+ };
285
+ },
286
+ }),
269
287
  ...(options.ownClients === undefined
270
288
  ? {}
271
289
  : {
@@ -413,3 +431,37 @@ export const exampleOrganization = (externalId, extra = {}) => ({
413
431
  name: `Example company ${externalId}`,
414
432
  ...extra,
415
433
  });
434
+ const fakeFile = (file, opened) => {
435
+ const bytes = typeof file.bytes === "string" ? new TextEncoder().encode(file.bytes) : file.bytes;
436
+ const link = `https://${file.host ?? "portal.example"}/download/${file.id}?token=${FAKE_FILE_TOKEN}`;
437
+ const listed = {
438
+ id: crmFileId(file.owner, file.source ?? "record", file.id),
439
+ name: file.name,
440
+ size: file.size === undefined ? bytes.byteLength : file.size,
441
+ mime: file.mime ?? null,
442
+ created: file.created ?? null,
443
+ owner: { ...file.owner },
444
+ source: file.source ?? "record",
445
+ url: link,
446
+ async open() {
447
+ opened();
448
+ if (file.broken)
449
+ throw new Error(`GET ${link} failed: socket hang up`);
450
+ if (file.host && file.host !== "portal.example")
451
+ throw new CliError("provider_error", `the file link points to another host than the account's: ${link}`);
452
+ if (file.html)
453
+ throw new CliError("provider_error", `the CRM answered a web page, not the file: ${link}`);
454
+ return new ReadableStream({
455
+ start(controller) {
456
+ // Two chunks, so a cap is checked between them.
457
+ const half = Math.ceil(bytes.byteLength / 2);
458
+ controller.enqueue(bytes.slice(0, half));
459
+ if (half < bytes.byteLength)
460
+ controller.enqueue(bytes.slice(half));
461
+ controller.close();
462
+ },
463
+ });
464
+ },
465
+ };
466
+ return listed;
467
+ };
@@ -28,6 +28,7 @@ export declare const amountOf: (value: unknown, currency: unknown) => {
28
28
  export declare const fullName: (...parts: unknown[]) => string | null;
29
29
  /**
30
30
  * A record's custom values, by code, as the port keeps them: each with its field's label, and a list field's option
31
- * ids turned into their labels with `option_id` beside (both lists on a multiple field).
31
+ * ids turned into their labels with `option_id` beside (both lists on a multiple field). A file field's tokened link
32
+ * is removed, so it reaches neither the store nor an answer.
32
33
  */
33
34
  export declare const crmValuesOf: (values: Readonly<Record<string, unknown>>, fields: readonly CrmField[]) => Record<string, CrmValue>;
@@ -1,3 +1,4 @@
1
+ import { withoutFileLinks } from "./files.js";
1
2
  export const isRaw = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
2
3
  export const fieldOf = (value, key) => (isRaw(value) ? value[key] : undefined);
3
4
  export const rawsOf = (value) => (Array.isArray(value) ? value.filter(isRaw) : []);
@@ -59,7 +60,8 @@ export const fullName = (...parts) => parts
59
60
  const optionLabel = (field, option) => field.options?.find(({ id }) => id === String(option))?.label ?? String(option);
60
61
  /**
61
62
  * A record's custom values, by code, as the port keeps them: each with its field's label, and a list field's option
62
- * ids turned into their labels with `option_id` beside (both lists on a multiple field).
63
+ * ids turned into their labels with `option_id` beside (both lists on a multiple field). A file field's tokened link
64
+ * is removed, so it reaches neither the store nor an answer.
63
65
  */
64
66
  export const crmValuesOf = (values, fields) => {
65
67
  const byCode = new Map(fields.map((field) => [field.code, field]));
@@ -67,7 +69,7 @@ export const crmValuesOf = (values, fields) => {
67
69
  const field = byCode.get(code);
68
70
  const label = field?.label ?? null;
69
71
  if (!field?.options)
70
- return [code, { label, value }];
72
+ return [code, { label, value: withoutFileLinks(value) }];
71
73
  if (Array.isArray(value))
72
74
  return [code, { label, value: value.map((one) => optionLabel(field, one)), option_id: value.map(String) }];
73
75
  return [code, { label, value: optionLabel(field, value), option_id: String(value) }];
@@ -52,7 +52,7 @@ export interface MeetingCommandDeps {
52
52
  * asks when the command's key is at `ask` and refuses when nobody can answer. Without it the writes refuse.
53
53
  */
54
54
  askFirst?: (command: Command) => Promise<void>;
55
- /** The run's stop signal; the meeting writes and `meetings invitation` pass it to the service. */
55
+ /** The run's stop signal; `list`, `show`, the meeting writes and `meetings invitation` pass it to the service. */
56
56
  signal?: () => AbortSignal | undefined;
57
57
  }
58
58
  export { addMeetingPassageCommand, createMeetingPassageCommand, type MeetingPassageFlags, meetingPassageRequest, } from "./passage.js";