@wirecat/cli-core 0.686.0 → 0.688.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 (97) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/cli/account-remove.js +21 -3
  4. package/dist/cli/documents/testing/source-contract.js +18 -9
  5. package/dist/cli/documents/words.d.ts +1 -1
  6. package/dist/cli/envelope.js +2 -3
  7. package/dist/cli/meeting-batch.js +5 -1
  8. package/dist/cli/meeting-passage-text.d.ts +1 -1
  9. package/dist/cli/meeting-passage-text.js +3 -5
  10. package/dist/cli/messenger/conversations-command.js +4 -0
  11. package/dist/cli/messenger/messages-search-command.js +6 -1
  12. package/dist/cli/messenger/search-answers.js +2 -0
  13. package/dist/cli/messenger/store-maintenance-command.js +3 -2
  14. package/dist/cli/search-left-out.d.ts +3 -0
  15. package/dist/cli/search-left-out.js +12 -0
  16. package/dist/cli/store-settings.js +23 -4
  17. package/dist/cli/untrusted-marks.d.ts +2 -0
  18. package/dist/cli/untrusted-marks.js +6 -0
  19. package/dist/crm/cli/files.d.ts +68 -0
  20. package/dist/crm/cli/files.js +616 -0
  21. package/dist/crm/cli/index.d.ts +1 -0
  22. package/dist/crm/cli/index.js +3 -0
  23. package/dist/crm/cli/search-all.js +3 -2
  24. package/dist/crm/file-fetch.d.ts +15 -0
  25. package/dist/crm/file-fetch.js +61 -0
  26. package/dist/crm/files.d.ts +16 -0
  27. package/dist/crm/files.js +56 -0
  28. package/dist/crm/foreign-contacts.d.ts +16 -4
  29. package/dist/crm/foreign-contacts.js +8 -4
  30. package/dist/crm/index.d.ts +3 -1
  31. package/dist/crm/index.js +3 -0
  32. package/dist/crm/source.d.ts +37 -0
  33. package/dist/crm/source.js +2 -1
  34. package/dist/crm/testing/files-contract.d.ts +17 -0
  35. package/dist/crm/testing/files-contract.js +142 -0
  36. package/dist/crm/testing/index.d.ts +2 -1
  37. package/dist/crm/testing/index.js +2 -1
  38. package/dist/crm/testing/source.d.ts +36 -1
  39. package/dist/crm/testing/source.js +55 -1
  40. package/dist/crm/values.d.ts +2 -1
  41. package/dist/crm/values.js +4 -2
  42. package/dist/entities/hit.d.ts +3 -3
  43. package/dist/entities/hit.js +14 -3
  44. package/dist/entities/index.d.ts +1 -1
  45. package/dist/errors/reasons.js +12 -1
  46. package/dist/files/safe-name.d.ts +2 -1
  47. package/dist/files/safe-name.js +21 -3
  48. package/dist/meetings/cli/index.d.ts +1 -1
  49. package/dist/meetings/cli/index.js +10 -6
  50. package/dist/meetings/mcp/index.d.ts +15 -15
  51. package/dist/meetings/mcp/passage.d.ts +6 -2
  52. package/dist/meetings/mcp/passage.js +7 -3
  53. package/dist/meetings/read-through.d.ts +2 -0
  54. package/dist/meetings/read-through.js +7 -2
  55. package/dist/meetings/source.d.ts +2 -2
  56. package/dist/oauth/storage.js +21 -4
  57. package/dist/search/lucene/resolved.d.ts +2 -0
  58. package/dist/search/respell.d.ts +10 -0
  59. package/dist/search/respell.js +63 -0
  60. package/dist/search/stem.d.ts +16 -3
  61. package/dist/search/stem.js +32 -4
  62. package/dist/services/documents/plan.js +26 -5
  63. package/dist/services/documents/sync.js +4 -1
  64. package/dist/services/embeddings-search.js +190 -140
  65. package/dist/services/embeddings.d.ts +8 -0
  66. package/dist/services/messages-archive-search.js +55 -3
  67. package/dist/services/messages-search.d.ts +2 -1
  68. package/dist/services/messages-search.js +19 -7
  69. package/dist/services/messages.d.ts +8 -0
  70. package/dist/services/metadata.d.ts +1 -1
  71. package/dist/services/named-chat.d.ts +20 -0
  72. package/dist/services/named-chat.js +63 -0
  73. package/dist/services/search-all.d.ts +7 -2
  74. package/dist/services/search-all.js +35 -1
  75. package/dist/store/accounts.d.ts +2 -1
  76. package/dist/store/exports.d.ts +2 -1
  77. package/dist/store/exports.js +2 -1
  78. package/dist/store/recover.js +2 -0
  79. package/dist/store/search-index.d.ts +2 -0
  80. package/dist/store/search-index.js +1 -0
  81. package/dist/store/sqlite/account-purge.js +1 -0
  82. package/dist/store/sqlite/crm-files.d.ts +70 -0
  83. package/dist/store/sqlite/crm-files.js +174 -0
  84. package/dist/store/sqlite/crm-settings.d.ts +42 -1
  85. package/dist/store/sqlite/crm-settings.js +46 -2
  86. package/dist/store/sqlite/lucene-fields.d.ts +2 -0
  87. package/dist/store/sqlite/lucene-fields.js +6 -2
  88. package/dist/store/sqlite/lucene.js +13 -7
  89. package/dist/store/sqlite/manifest.js +2 -0
  90. package/dist/store/sqlite/migrations.generated.js +17 -0
  91. package/dist/store/sqlite/schema.d.ts +329 -0
  92. package/dist/store/sqlite/schema.js +28 -0
  93. package/dist/store/sqlite/stems.d.ts +2 -0
  94. package/dist/store/sqlite/stems.js +5 -0
  95. package/dist/store/store.d.ts +3 -0
  96. package/dist/store/store.js +5 -0
  97. package/package.json +2 -2
@@ -0,0 +1,15 @@
1
+ import { type FetchLike } from "@wirecat/cli-base/http";
2
+ export interface CrmFileFetchOptions {
3
+ /** The account's own hosts, such as the Bitrix24 portal or amoCRM's `drive_url` host: the only ones asked. */
4
+ hosts: readonly string[];
5
+ /** Sent only to those hosts, such as a Bearer token. */
6
+ headers?: Record<string, string>;
7
+ signal?: AbortSignal;
8
+ fetch?: FetchLike;
9
+ }
10
+ /**
11
+ * A file's bytes behind a CRM link, for an adapter's `CrmOpenableFile.open`. https only, the account's own hosts only,
12
+ * redirects followed only on them, so the credentials go nowhere else. An HTML page is a CRM's answer to a link that is
13
+ * not a server link: refused. No error carries the link, which holds a token.
14
+ */
15
+ export declare const fetchCrmFile: (link: string, options: CrmFileFetchOptions) => Promise<ReadableStream<Uint8Array>>;
@@ -0,0 +1,61 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { hostFetch } from "@wirecat/cli-base/http";
3
+ /** A large file on a slow line; the command's own deadline and `--timeout` stop it sooner. */
4
+ const EXCHANGE_MS = 60 * 60 * 1000;
5
+ const MOST_REDIRECTS = 5;
6
+ /**
7
+ * A file's bytes behind a CRM link, for an adapter's `CrmOpenableFile.open`. https only, the account's own hosts only,
8
+ * redirects followed only on them, so the credentials go nowhere else. An HTML page is a CRM's answer to a link that is
9
+ * not a server link: refused. No error carries the link, which holds a token.
10
+ */
11
+ export const fetchCrmFile = async (link, options) => {
12
+ const send = options.fetch ?? hostFetch({ hosts: options.hosts, timeoutMs: EXCHANGE_MS });
13
+ const refused = (why) => new CliError("provider_error", `the CRM's file link was refused: ${why}`, { reason: "crm.file-unavailable" });
14
+ let at = link;
15
+ for (let hop = 0; hop <= MOST_REDIRECTS; hop += 1) {
16
+ let url;
17
+ try {
18
+ url = new URL(at);
19
+ }
20
+ catch {
21
+ throw refused("it is not a link");
22
+ }
23
+ if (url.protocol !== "https:")
24
+ throw refused("it is not https");
25
+ if (!options.hosts.includes(url.hostname.toLowerCase()))
26
+ throw refused("it points to another host than the account's");
27
+ let answer;
28
+ try {
29
+ answer = await send(url, {
30
+ redirect: "manual",
31
+ ...(options.headers ? { headers: options.headers } : {}),
32
+ ...(options.signal ? { signal: options.signal } : {}),
33
+ });
34
+ }
35
+ catch {
36
+ if (options.signal?.aborted)
37
+ throw new CliError("cancelled", "the file download was stopped");
38
+ throw new CliError("network_error", "the CRM's file server could not be reached", {
39
+ reason: "crm.file-unavailable",
40
+ });
41
+ }
42
+ const next = answer.headers.get("location");
43
+ if (answer.status >= 300 && answer.status < 400 && next) {
44
+ await answer.body?.cancel().catch(() => { });
45
+ at = new URL(next, url).href;
46
+ continue;
47
+ }
48
+ if (!answer.ok || !answer.body) {
49
+ await answer.body?.cancel().catch(() => { });
50
+ throw new CliError("provider_error", `the CRM's file server answered ${answer.status}`, {
51
+ reason: "crm.file-unavailable",
52
+ });
53
+ }
54
+ if ((answer.headers.get("content-type") ?? "").toLowerCase().startsWith("text/html")) {
55
+ await answer.body.cancel().catch(() => { });
56
+ throw refused("the CRM answered a web page, not the file");
57
+ }
58
+ return answer.body;
59
+ }
60
+ throw refused("too many redirects");
61
+ };
@@ -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,9 @@
1
+ export { type CrmFileFetchOptions, fetchCrmFile } from "./file-fetch.js";
2
+ export { crmFileId, LINK_REMOVED, parseCrmFileId, withoutFileLinks } from "./files.js";
1
3
  export { DAILY_FOREIGN_CONTACTS, type ForeignContacts, foreignContacts, foreignContactsPathFor, refuseForeignClientReads, } from "./foreign-contacts.js";
2
4
  export { type ProviderCallOptions, providerCall } from "./provider-call.js";
3
5
  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";
6
+ 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
7
  export { type CrmCursor, type CrmSyncIssue, type CrmSyncOptions, type CrmSyncReport, type CrmSyncResult, crmGapsOf, crmStatus, cursorName, parseCrmCursor, syncCrm, } from "./sync.js";
6
8
  /** An adapter's readers of a CRM's raw JSON: `crmValues.text(raw.name)`, `crmValues.time(raw.created_at)`. */
7
9
  export * as crmValues from "./values.js";
package/dist/crm/index.js CHANGED
@@ -1,6 +1,9 @@
1
+ export { fetchCrmFile } from "./file-fetch.js";
2
+ export { crmFileId, LINK_REMOVED, parseCrmFileId, withoutFileLinks } from "./files.js";
1
3
  export { DAILY_FOREIGN_CONTACTS, foreignContacts, foreignContactsPathFor, refuseForeignClientReads, } from "./foreign-contacts.js";
2
4
  export { providerCall } from "./provider-call.js";
3
5
  export { conditionsOf, customConditions, customNames, filterableFields, selectedCodes, wantedCodes, withCustomFields, } from "./query.js";
6
+ export { CRM_FILE_SOURCES, } from "./source.js";
4
7
  export { crmGapsOf, crmStatus, cursorName, parseCrmCursor, syncCrm, } from "./sync.js";
5
8
  /** An adapter's readers of a CRM's raw JSON: `crmValues.text(raw.name)`, `crmValues.time(raw.created_at)`. */
6
9
  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"];
@@ -0,0 +1,17 @@
1
+ import type { ContractCase } from "../../meetings/index.js";
2
+ import { type CrmFileOwner, type CrmSource } from "../source.js";
3
+ /** One adapter with `files`, over recorded or faked responses, fresh for each case. */
4
+ export interface CrmFilesFixture {
5
+ source: CrmSource;
6
+ /** A record of the sign-in's own with at least one file whose text holds `word`. */
7
+ own: CrmFileOwner;
8
+ word: string;
9
+ /** A colleague's record with a file; needed when the source has `isAdmin`. */
10
+ foreign?: CrmFileOwner;
11
+ /** What every file link the fixture serves carries, such as its token: it must reach no answer, file or error. */
12
+ token: string;
13
+ /** Ids of files whose download the adapter must refuse: a link to another host, a web page instead of the file. */
14
+ refused?: readonly string[];
15
+ }
16
+ /** What every CRM adapter's `files` answers, whatever the CRM: run each case in the adapter's tests. */
17
+ export declare const crmFilesContract: (make: () => CrmFilesFixture | Promise<CrmFilesFixture>) => ContractCase[];
@@ -0,0 +1,142 @@
1
+ import assert from "node:assert/strict";
2
+ import { existsSync, mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { isCliError } from "@wirecat/cli-base";
6
+ import { openStore } from "../../store/store.js";
7
+ import { downloadCrmFile } from "../cli/files.js";
8
+ import { parseCrmFileId } from "../files.js";
9
+ import { DAILY_FOREIGN_CONTACTS, foreignContacts } from "../foreign-contacts.js";
10
+ import { CRM_FILE_SOURCES } from "../source.js";
11
+ const APP = {
12
+ command: "crm",
13
+ appName: "crm-files-contract",
14
+ envPrefix: "CRMFILES",
15
+ description: "contract",
16
+ version: "0.0.0",
17
+ };
18
+ const ACCOUNT = { provider: "contract-crm", account: "portal" };
19
+ const without = (token, what, value) => assert.ok(!JSON.stringify(value ?? null).includes(token) && !String(value?.message ?? "").includes(token), `${what} holds the file link's token`);
20
+ const filesOf = (root) => existsSync(root)
21
+ ? readdirSync(root, { recursive: true, withFileTypes: true })
22
+ .filter((entry) => entry.isFile())
23
+ .map((entry) => join(entry.parentPath, entry.name))
24
+ : [];
25
+ /** A store and a state folder of their own, and a run over the fixture's source. */
26
+ const runOver = async (source) => {
27
+ const home = mkdtempSync(join(tmpdir(), "crm-files-contract-"));
28
+ const path = join(home, "store.db");
29
+ const store = await openStore({ path });
30
+ const user = source.self ? String(await source.self()) : null;
31
+ const run = {
32
+ profile: "contract",
33
+ user,
34
+ account: ACCOUNT,
35
+ store,
36
+ source: () => source,
37
+ env: { HOME: home, XDG_STATE_HOME: home, CRMFILES_STATE_DIR: join(home, "state") },
38
+ };
39
+ return { run, store, path, state: join(home, "state"), context: { app: APP, run, now: () => Date.now() } };
40
+ };
41
+ /** What every CRM adapter's `files` answers, whatever the CRM: run each case in the adapter's tests. */
42
+ export const crmFilesContract = (make) => [
43
+ {
44
+ name: "files: one record's files, each with an id naming that record, a known source and no link anywhere",
45
+ async run() {
46
+ const { source, own, token } = await make();
47
+ assert.ok(source.files, "the source has files");
48
+ const found = await source.files(own);
49
+ assert.ok(found && found.files.length > 0, "the own record lists a file");
50
+ for (const file of found.files) {
51
+ const { owner, source: kind } = parseCrmFileId(file.id);
52
+ assert.deepEqual(owner, own, `${file.id} names its record`);
53
+ assert.equal(kind, file.source);
54
+ assert.ok(CRM_FILE_SOURCES.includes(file.source));
55
+ assert.ok(file.name.length > 0, "a file has a name");
56
+ assert.ok(file.size === null || file.size >= 0);
57
+ const { open: _open, ...listed } = file;
58
+ without(token, `the listed ${file.id}`, { id: listed.id, name: listed.name, owner: listed.owner });
59
+ }
60
+ assert.equal(await source.files({ kind: own.kind, id: "999999999" }), null, "a record the CRM lacks is null");
61
+ },
62
+ },
63
+ {
64
+ name: "files: a download is saved 600 in 700 folders, its text stored and found, and its token kept nowhere",
65
+ async run() {
66
+ const { source, own, word, token, refused = [] } = await make();
67
+ const { run, store, path, state, context } = await runOver(source);
68
+ try {
69
+ const found = await source.files?.(own);
70
+ assert.ok(found);
71
+ const rows = [];
72
+ for (const file of found.files.filter((one) => !refused.includes(one.id)))
73
+ rows.push(await downloadCrmFile(context, file, found.assignee, {
74
+ capBytes: 100 * 1024 * 1024,
75
+ capMb: 100,
76
+ flag: false,
77
+ limits: await store.crmFiles.limits(ACCOUNT),
78
+ }));
79
+ assert.ok(rows.some((one) => one.row.text?.toLowerCase().includes(word.toLowerCase())), `a file's text holds ${word}`);
80
+ for (const saved of filesOf(state)) {
81
+ assert.equal(statSync(saved).mode & 0o777, 0o600, `${saved} is the OS user's alone`);
82
+ without(token, saved, readFileSync(saved, "latin1"));
83
+ }
84
+ assert.equal(statSync(join(state, "crm", "files")).mode & 0o777, 0o700);
85
+ const hits = await store.crmFiles.find({ words: [word] });
86
+ assert.ok(hits.items.length > 0, "search finds the text");
87
+ if (found.assignee !== null && run.user !== null) {
88
+ const other = { account: ACCOUNT, assignee: `${ACCOUNT.account}/user/0` };
89
+ assert.equal((await store.crmFiles.find({ words: [word], viewers: [other] })).items.length, 0);
90
+ }
91
+ await store.close();
92
+ assert.ok(!readFileSync(path, "latin1").includes(token), "the store file holds the token");
93
+ }
94
+ finally {
95
+ await store.close().catch(() => { });
96
+ }
97
+ },
98
+ },
99
+ {
100
+ name: "files: a refused link (another host, a web page) fails without its token and leaves no part",
101
+ async run() {
102
+ const { source, token, refused = [] } = await make();
103
+ if (!refused.length)
104
+ return;
105
+ const { store, state, context } = await runOver(source);
106
+ try {
107
+ for (const id of refused) {
108
+ const { owner } = parseCrmFileId(id);
109
+ const found = await source.files?.(owner);
110
+ const file = found?.files.find((one) => one.id === id);
111
+ assert.ok(file, `${id} is listed for ${owner.kind} ${owner.id}`);
112
+ const error = await downloadCrmFile(context, file, found?.assignee ?? null, {
113
+ capBytes: 1024 * 1024,
114
+ capMb: 1,
115
+ flag: false,
116
+ limits: await store.crmFiles.limits(ACCOUNT),
117
+ }).then(() => undefined, (caught) => caught);
118
+ assert.ok(isCliError(error), `${id} is refused`);
119
+ without(token, `the refusal of ${id}`, error);
120
+ }
121
+ assert.deepEqual(filesOf(state), [], "a refused download keeps no file");
122
+ }
123
+ finally {
124
+ await store.close();
125
+ }
126
+ },
127
+ },
128
+ {
129
+ name: "files: a colleague's record costs one of the day's slots, and the 101st is refused",
130
+ async run() {
131
+ const { source, foreign } = await make();
132
+ if (!source.isAdmin || !foreign || (await source.isAdmin()))
133
+ return;
134
+ const found = await source.files?.(foreign);
135
+ assert.ok(found, "the colleague's record lists its files");
136
+ const file = join(mkdtempSync(join(tmpdir(), "crm-files-quota-")), "count.json");
137
+ const day = new Date().toISOString().slice(0, 10);
138
+ writeFileSync(file, JSON.stringify({ day, seen: Array.from({ length: DAILY_FOREIGN_CONTACTS }, (_, at) => `x:${at}`) }));
139
+ await assert.rejects(foreignContacts(source, () => file).spend(foreign.kind, { externalId: foreign.id, assignee: found.assignee }), (error) => isCliError(error) && error.details.reason === "crm.foreign-contacts-spent");
140
+ },
141
+ },
142
+ ];
@@ -1,5 +1,6 @@
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 { type CrmFilesFixture, crmFilesContract } from "./files-contract.js";
3
+ 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
4
  export { type CrmSourceFaults, type CrmSourceFixture, crmSourceContract } from "./source-contract.js";
4
5
  export { CRM_TRAIT_COMBINATIONS, type CrmSyncFixture, crmSyncContract } from "./sync-contract.js";
5
6
  export { type CrmWriteFixture, crmWriteContract } from "./write-contract.js";
@@ -1,5 +1,6 @@
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 { crmFilesContract } from "./files-contract.js";
3
+ export { exampleDeal, exampleLead, exampleOrganization, examplePerson, FAKE_CRM_ALIASES, FAKE_FILE_TOKEN, fakeCrmSource, LEAD_PIPELINE, SALES_PIPELINE, SOURCE_FIELD, } from "./source.js";
3
4
  export { crmSourceContract } from "./source-contract.js";
4
5
  export { CRM_TRAIT_COMBINATIONS, crmSyncContract } from "./sync-contract.js";
5
6
  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,39 @@ 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
+ /** Kinds of file the sign-in may not read: each `files()` reports them as a gap naming the scope. */
27
+ fileGaps?: {
28
+ scope: string;
29
+ message: string;
30
+ }[];
31
+ }
32
+ /** The token in every fake file link: it must reach no output, store, file or error. */
33
+ export declare const FAKE_FILE_TOKEN = "fake-file-token-5f2a9c";
34
+ /** A file of one of the fake's records. */
35
+ export interface FakeCrmFile {
36
+ owner: CrmFileOwner;
37
+ /** `record` when absent. */
38
+ source?: CrmFileSourceKind;
39
+ /** The CRM's own id of the file. */
40
+ id: string;
41
+ name: string;
42
+ bytes: string | Uint8Array;
43
+ mime?: string | null;
44
+ /** Epoch ms. */
45
+ created?: number | null;
46
+ /** What the CRM says the size is; the bytes' length when absent, unknown when null. */
47
+ size?: number | null;
48
+ /** `open` fails with an error that names the tokened link, as a raw fetch error would. */
49
+ broken?: boolean;
50
+ /** `open` answers an HTML page, as a CRM does for a link that is not a server link. */
51
+ html?: boolean;
52
+ /** The link answers from this host instead of the account's own. */
53
+ host?: string;
21
54
  }
22
55
  /** One write the fake CRM was sent, in order. */
23
56
  export interface FakeCrmWrite {
@@ -57,6 +90,8 @@ export interface FakeCrmSource extends CrmSource, CrmWriter {
57
90
  ids: number;
58
91
  list: number;
59
92
  get: number;
93
+ files: number;
94
+ open: number;
60
95
  };
61
96
  /** Writes sent, refused ones included. */
62
97
  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,23 @@ 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, context) => {
276
+ calls.files += 1;
277
+ for (const gap of options.fileGaps ?? [])
278
+ context?.gap({ kind: owner.kind, ...gap });
279
+ const record = of(owner.kind).get(owner.id);
280
+ if (!record || record.deleted)
281
+ return null;
282
+ const listed = options.files.filter((one) => one.owner.kind === owner.kind && one.owner.id === owner.id);
283
+ return {
284
+ assignee: record.record.assignee ?? null,
285
+ files: listed.map((one) => fakeFile(one, () => (calls.open += 1))),
286
+ };
287
+ },
288
+ }),
269
289
  ...(options.ownClients === undefined
270
290
  ? {}
271
291
  : {
@@ -413,3 +433,37 @@ export const exampleOrganization = (externalId, extra = {}) => ({
413
433
  name: `Example company ${externalId}`,
414
434
  ...extra,
415
435
  });
436
+ const fakeFile = (file, opened) => {
437
+ const bytes = typeof file.bytes === "string" ? new TextEncoder().encode(file.bytes) : file.bytes;
438
+ const link = `https://${file.host ?? "portal.example"}/download/${file.id}?token=${FAKE_FILE_TOKEN}`;
439
+ const listed = {
440
+ id: crmFileId(file.owner, file.source ?? "record", file.id),
441
+ name: file.name,
442
+ size: file.size === undefined ? bytes.byteLength : file.size,
443
+ mime: file.mime ?? null,
444
+ created: file.created ?? null,
445
+ owner: { ...file.owner },
446
+ source: file.source ?? "record",
447
+ url: link,
448
+ async open() {
449
+ opened();
450
+ if (file.broken)
451
+ throw new Error(`GET ${link} failed: socket hang up`);
452
+ if (file.host && file.host !== "portal.example")
453
+ throw new CliError("provider_error", `the file link points to another host than the account's: ${link}`);
454
+ if (file.html)
455
+ throw new CliError("provider_error", `the CRM answered a web page, not the file: ${link}`);
456
+ return new ReadableStream({
457
+ start(controller) {
458
+ // Two chunks, so a cap is checked between them.
459
+ const half = Math.ceil(bytes.byteLength / 2);
460
+ controller.enqueue(bytes.slice(0, half));
461
+ if (half < bytes.byteLength)
462
+ controller.enqueue(bytes.slice(half));
463
+ controller.close();
464
+ },
465
+ });
466
+ },
467
+ };
468
+ return listed;
469
+ };
@@ -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>;