@wirecat/cli-core 0.683.0 → 0.685.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 (55) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/dist/cli/bot/api-http.d.ts +10 -2
  3. package/dist/cli/bot/api-http.js +50 -45
  4. package/dist/cli/context.d.ts +6 -1
  5. package/dist/cli/context.js +16 -2
  6. package/dist/cli/documents/testing/index.d.ts +1 -1
  7. package/dist/cli/documents/testing/index.js +1 -1
  8. package/dist/cli/documents/testing/source-contract.d.ts +34 -1
  9. package/dist/cli/documents/testing/source-contract.js +153 -1
  10. package/dist/cli/documents/testing/source.d.ts +2 -0
  11. package/dist/cli/documents/testing/source.js +8 -1
  12. package/dist/cli/index.d.ts +5 -2
  13. package/dist/cli/index.js +5 -2
  14. package/dist/cli/profile-token.js +13 -3
  15. package/dist/cli/program.js +6 -4
  16. package/dist/cli/service-api-manifest.d.ts +40 -0
  17. package/dist/cli/service-api-manifest.js +106 -0
  18. package/dist/cli/service-api.d.ts +73 -0
  19. package/dist/cli/service-api.js +260 -0
  20. package/dist/cli/shared-command-exports.d.ts +1 -0
  21. package/dist/cli/shared-command-exports.js +2 -0
  22. package/dist/crm/cli/index.js +25 -38
  23. package/dist/crm/digest.d.ts +1 -1
  24. package/dist/crm/digest.js +9 -1
  25. package/dist/crm/index.d.ts +1 -1
  26. package/dist/crm/index.js +1 -1
  27. package/dist/crm/testing/index.d.ts +1 -1
  28. package/dist/crm/testing/source-contract.d.ts +26 -1
  29. package/dist/crm/testing/source-contract.js +102 -0
  30. package/dist/crm/testing/source.d.ts +2 -0
  31. package/dist/crm/testing/source.js +6 -0
  32. package/dist/crm/viewer.d.ts +14 -1
  33. package/dist/crm/viewer.js +38 -1
  34. package/dist/http/link-fetch.d.ts +10 -0
  35. package/dist/http/link-fetch.js +28 -0
  36. package/dist/meetings/import.d.ts +1 -1
  37. package/dist/meetings/import.js +2 -0
  38. package/dist/meetings/index.d.ts +1 -0
  39. package/dist/meetings/index.js +1 -0
  40. package/dist/meetings/pull.d.ts +2 -0
  41. package/dist/meetings/pull.js +18 -0
  42. package/dist/meetings/search-store.d.ts +2 -0
  43. package/dist/meetings/search-store.js +16 -1
  44. package/dist/meetings/store.d.ts +3 -0
  45. package/dist/oauth/requests.js +48 -13
  46. package/dist/services/deal-context.d.ts +1 -1
  47. package/dist/services/deal-context.js +2 -1
  48. package/dist/services/meeting-hit-search.d.ts +2 -3
  49. package/dist/services/meeting-hit-search.js +2 -17
  50. package/dist/services/organization-context.js +22 -12
  51. package/dist/services/search-all-meetings.d.ts +1 -1
  52. package/dist/store/sqlite/crm-activities.js +9 -3
  53. package/dist/store/sqlite/deals.d.ts +0 -2
  54. package/dist/store/sqlite/deals.js +0 -1
  55. package/package.json +3 -3
@@ -12,19 +12,18 @@ import { listQuery, nativeField, nativeTerms, queryTerms, termField, timeBounds,
12
12
  import { terminalAsker } from "../../cli/messenger/ask.js";
13
13
  import { addStoreMaintenanceCommands } from "../../cli/messenger/store-maintenance-command.js";
14
14
  import { lineOf } from "../../cli/steps.js";
15
- import { CRM_KINDS, isCrmUserId, normalCrmUserId } from "../../domain/crm.js";
15
+ import { CRM_KINDS } from "../../domain/crm.js";
16
16
  import { DEAL_KINDS, DEAL_STATUSES } from "../../domain/deals.js";
17
17
  import { deal as dealEntity } from "../../entities/deal.js";
18
18
  import { count, text } from "../../entities/fields.js";
19
19
  import { dateWindow } from "../../services/moment.js";
20
20
  import { readableAccounts } from "../../services/person-context.js";
21
21
  import { personMeetings } from "../../services/person-meetings.js";
22
- import { crmIdentityId } from "../../store/sqlite/crm-rows.js";
23
22
  import { CRM_SCOPES, crmSettingKey } from "../../store/sqlite/crm-settings.js";
24
23
  import { seenBy } from "../../store/store.js";
25
24
  import { openStageTasks } from "../stage-tasks.js";
26
25
  import { crmStatus, syncRecorded } from "../sync.js";
27
- import { shortened, viewerOf } from "../viewer.js";
26
+ import { ownerOf, shortened, viewerOf, withReadableDeal } from "../viewer.js";
28
27
  import { closeCrmItem, createCrmItem, fieldPairsOf, moveCrmItem, pipelineOf, removeCrmItem, updateCrmItem, } from "../writes.js";
29
28
  import { addCrmChangeCommands } from "./changes.js";
30
29
  import { csvFormatOption, renderCsv } from "./csv.js";
@@ -187,25 +186,6 @@ const collect = (value, previous = []) => {
187
186
  throw new InvalidArgumentError("expected key=value");
188
187
  return [...previous, value];
189
188
  };
190
- /** `owner:` as the identity a deal's assignee is stored as; `none` is no assignee. */
191
- const ownerOf = async (run, owner) => {
192
- if (owner === "none")
193
- return null;
194
- if (owner === "me") {
195
- const self = run.user ?? (await run.store.crm.ownUser(run.account));
196
- if (!self)
197
- throw new CliError("validation_error", "this CRM names no user for the sign-in: use owner:<user id>", {
198
- reason: "crm.owner-unknown",
199
- });
200
- return crmIdentityId(run.account, normalCrmUserId(self), "user");
201
- }
202
- if (!isCrmUserId(owner))
203
- throw new CliError("validation_error", `owner takes me, none or the CRM's user id, not ${owner}`, {
204
- reason: "crm.owner-unknown",
205
- });
206
- return crmIdentityId(run.account, normalCrmUserId(owner), "user");
207
- };
208
- /** Whose deals and leads of the copy this profile reads offline; undefined is every one. */
209
189
  /** The words below the program, as `page.next` and `sync`'s next step run it again. */
210
190
  const pathOf = (command) => command.parent?.parent ? [...pathOf(command.parent), command.name()] : [command.name()];
211
191
  /** A CRM's own field codes are its keys, never ours to rename. */
@@ -349,21 +329,28 @@ const addCrmCommandsDefinition = (program, options) => {
349
329
  const timezone = metas.find((one) => one.timezone)?.timezone;
350
330
  // One window names one field's bounds; with two time terms it would name only the first.
351
331
  const window = metas.length === 1 ? metas[0] : timezone ? { timezone } : undefined;
352
- const read = async (run) => run.store.deals.list({
353
- kind,
354
- account: run.account,
355
- viewer: await viewerOf(run),
356
- ...(terms.has("status") ? { status: terms.get("status") } : {}),
357
- ...(terms.has("stage") ? { stage: terms.get("stage") } : {}),
358
- ...(terms.has("pipeline") ? { pipeline: terms.get("pipeline") } : {}),
359
- ...(terms.has("organization") ? { organization: terms.get("organization") } : {}),
360
- ...(terms.has("owner") ? { owner: await ownerOf(run, terms.get("owner")) } : {}),
361
- ...(times.has("updated") ? { updated: bounds.updated } : {}),
362
- ...(times.has("created") ? { created: bounds.created } : {}),
363
- ...(times.has("closed") ? { closed: bounds.closed, zone: window?.timezone } : {}),
364
- limit: Math.min(opts.limit, MOST),
365
- offset: (opts.page - 1) * opts.limit,
366
- });
332
+ const read = async (run) => {
333
+ const viewer = await viewerOf(run);
334
+ const found = await run.store.deals.list({
335
+ kind,
336
+ account: run.account,
337
+ viewer,
338
+ ...(terms.has("status") ? { status: terms.get("status") } : {}),
339
+ ...(terms.has("stage") ? { stage: terms.get("stage") } : {}),
340
+ ...(terms.has("pipeline") ? { pipeline: terms.get("pipeline") } : {}),
341
+ ...(terms.has("organization") ? { organization: terms.get("organization") } : {}),
342
+ ...(terms.has("owner") ? { owner: await ownerOf(run, terms.get("owner")) } : {}),
343
+ ...(times.has("updated") ? { updated: bounds.updated } : {}),
344
+ ...(times.has("created") ? { created: bounds.created } : {}),
345
+ ...(times.has("closed") ? { closed: bounds.closed, zone: window?.timezone } : {}),
346
+ limit: Math.min(opts.limit, MOST),
347
+ offset: (opts.page - 1) * opts.limit,
348
+ });
349
+ return {
350
+ ...found,
351
+ items: await Promise.all(found.items.map((one) => withReadableDeal(run.store, [viewer], one))),
352
+ };
353
+ };
367
354
  if (opts.format === "csv")
368
355
  return renderCsv(command, options.open, async (run) => {
369
356
  const found = await read(run);
@@ -454,7 +441,7 @@ const addCrmCommandsDefinition = (program, options) => {
454
441
  const viewer = await viewerOf(run);
455
442
  if (!seenBy(viewer, { ...run.account, assignee: found.assignee }))
456
443
  throw new CliError("not_found", `${reference} is not a copy this profile may read${shortened.has(run) ? `: ${shortened.get(run)}` : ""}`);
457
- return found;
444
+ return withReadableDeal(run.store, [viewer], found);
458
445
  };
459
446
  const writes = options.writes;
460
447
  const addWrites = (group, kind) => {
@@ -8,7 +8,7 @@ export interface CrmDigestOptions {
8
8
  now: number;
9
9
  /** The owner's zone: the end of today. */
10
10
  zone: string;
11
- /** The owner's language, `ru` or `en`, for the few words the digest writes itself. */
11
+ /** The owner's language, `ru`, `es` or `en`, for the few words the digest writes itself. */
12
12
  language: string;
13
13
  /** The profile's name, for the sync's age. */
14
14
  profile: string;
@@ -24,6 +24,14 @@ const WORDS = {
24
24
  contacts: "новые контакты",
25
25
  hidden: "Часть копии CRM скрыта от этого профиля: см. примечание команды",
26
26
  },
27
+ es: {
28
+ won: "ganada",
29
+ lost: "perdida",
30
+ newDeal: "nueva",
31
+ newOwner: "nuevo responsable",
32
+ contacts: "contactos nuevos",
33
+ hidden: "Parte de la copia del CRM está oculta para este perfil: consulta la nota del comando",
34
+ },
27
35
  };
28
36
  const iso = (at) => (at === null ? null : new Date(at).toISOString());
29
37
  /** The last moment of `now`'s day in `zone`. */
@@ -40,7 +48,7 @@ const endOfDay = (now, zone) => {
40
48
  */
41
49
  export const crmDigest = async (store, account, options) => {
42
50
  const { since, until, now, zone, viewer } = options;
43
- const words = options.language === "ru" ? WORDS.ru : WORDS.en;
51
+ const words = WORDS[options.language] ?? WORDS.en;
44
52
  const cap = SECTION_CAPS.crm;
45
53
  const window = { since, until, ...(viewer ? { viewer } : {}) };
46
54
  const counts = await store.crm.changeCounts(account, window);
@@ -5,7 +5,7 @@ export type { CrmCallContext, CrmChanges, CrmCondition, CrmGap, CrmIdPage, CrmLi
5
5
  export { type CrmCursor, type CrmSyncIssue, type CrmSyncOptions, type CrmSyncReport, type CrmSyncResult, crmGapsOf, crmStatus, cursorName, parseCrmCursor, syncCrm, } from "./sync.js";
6
6
  /** An adapter's readers of a CRM's raw JSON: `crmValues.text(raw.name)`, `crmValues.time(raw.created_at)`. */
7
7
  export * as crmValues from "./values.js";
8
- export { type CrmViewing, crmViewerOf } from "./viewer.js";
8
+ export { type CrmViewing, crmViewerOf, withReadableDeal } from "./viewer.js";
9
9
  export { type CrmRows, type CrmWindow, crmWindowOf, walk } from "./walk.js";
10
10
  export { CRM_ASSIGN_OTHERS_KEY, CRM_VERBS, CRM_WRITE_DEFAULTS, CRM_WRITE_KEYS, type CrmDraft, type CrmDrafts, type CrmFields, type CrmOrganizationFields, type CrmPersonFields, type CrmVerb, type CrmWriteCapabilities, type CrmWriteFields, type CrmWriteOptions, type CrmWriter, crmAlsoChecks, } from "./writer.js";
11
11
  export { type CrmFieldsInput, type CrmRecordInput, type CrmRecordKind, type CrmRecordWritten, type CrmWriteContext, type CrmWrites, type CrmWritten, closeCrmItem, createCrmItem, createCrmRecord, crmCustomValues, fieldNamed, fieldPairsOf, foldFieldName, moveCrmItem, type NamedField, optionOf, removeCrmItem, unknownField, updateCrmItem, updateCrmRecord, } from "./writes.js";
package/dist/crm/index.js CHANGED
@@ -4,7 +4,7 @@ export { conditionsOf, customConditions, customNames, filterableFields, selected
4
4
  export { crmGapsOf, crmStatus, cursorName, parseCrmCursor, syncCrm, } from "./sync.js";
5
5
  /** An adapter's readers of a CRM's raw JSON: `crmValues.text(raw.name)`, `crmValues.time(raw.created_at)`. */
6
6
  export * as crmValues from "./values.js";
7
- export { crmViewerOf } from "./viewer.js";
7
+ export { crmViewerOf, withReadableDeal } from "./viewer.js";
8
8
  export { crmWindowOf, walk } from "./walk.js";
9
9
  export { CRM_ASSIGN_OTHERS_KEY, CRM_VERBS, CRM_WRITE_DEFAULTS, CRM_WRITE_KEYS, crmAlsoChecks, } from "./writer.js";
10
10
  export { closeCrmItem, createCrmItem, createCrmRecord, crmCustomValues, fieldNamed, fieldPairsOf, foldFieldName, moveCrmItem, optionOf, removeCrmItem, unknownField, updateCrmItem, updateCrmRecord, } from "./writes.js";
@@ -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
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";
3
- export { type CrmSourceFixture, crmSourceContract } from "./source-contract.js";
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,6 +1,29 @@
1
1
  import { type CrmKind } from "../../domain/crm.js";
2
2
  import type { ContractCase } from "../../meetings/index.js";
3
- import type { CrmSource } from "../source.js";
3
+ import type { CrmLiveKind, CrmSource } from "../source.js";
4
+ /** Faults a case injects; each is opt-in, and a case whose hook is absent passes without running. */
5
+ export interface CrmSourceFaults {
6
+ /** Makes one contact or company answer HTTP `status` from now on, as the CRM would, and names it. */
7
+ deny?(status: 403 | 404): {
8
+ kind: CrmLiveKind;
9
+ id: string;
10
+ } | Promise<{
11
+ kind: CrmLiveKind;
12
+ id: string;
13
+ }>;
14
+ /** A source over the same CRM whose own clock runs `ms` ahead of the CRM's, behind when negative. */
15
+ skewed?(ms: number): CrmSource | Promise<CrmSource>;
16
+ /** Changes one row on the CRM's side, for the next `changes()` to list. */
17
+ change?(): {
18
+ kind: CrmKind;
19
+ id: string;
20
+ } | Promise<{
21
+ kind: CrmKind;
22
+ id: string;
23
+ }>;
24
+ /** A source for a second profile signed in with the same token. */
25
+ sameToken?(): CrmSource | Promise<CrmSource>;
26
+ }
4
27
  /**
5
28
  * One adapter over recorded or faked responses, fresh for each case. Every kind its traits name must list at least
6
29
  * one row, so the checks have something to look at.
@@ -17,6 +40,8 @@ export interface CrmSourceFixture {
17
40
  kind: CrmKind;
18
41
  cursor: string;
19
42
  };
43
+ /** Faults for the opt-in fault cases; given, the cases that need no hook run too. */
44
+ faults?: CrmSourceFaults;
20
45
  }
21
46
  /** What every CRM adapter answers, whatever the CRM: run each case in the adapter's tests. */
22
47
  export declare const crmSourceContract: (make: () => CrmSourceFixture | Promise<CrmSourceFixture>) => ContractCase[];
@@ -1,6 +1,10 @@
1
1
  import assert from "node:assert/strict";
2
+ import { CliError } from "@wirecat/cli-base";
2
3
  import { isItemKind } from "../../domain/crm.js";
3
4
  import { DEAL_KINDS, STAGE_OUTCOMES } from "../../domain/deals.js";
5
+ /** Within any change feed's overlap: a computer's clock that is off by more is broken, not skewed. */
6
+ const SKEW_MS = 10 * 60_000;
7
+ const idsOf = (items) => items.map((item) => item.externalId);
4
8
  const MAX_PAGES = 1_000;
5
9
  const DAY = /^\d{4}-\d{2}-\d{2}$/;
6
10
  const DECIMAL = /^\d{1,16}(\.\d{1,6})?$/;
@@ -205,6 +209,7 @@ export const crmSourceContract = (make) => {
205
209
  });
206
210
  return [
207
211
  ...cases,
212
+ ...faultCases(make),
208
213
  {
209
214
  name: "changes: a dead cursor answers reset",
210
215
  async run() {
@@ -216,3 +221,100 @@ export const crmSourceContract = (make) => {
216
221
  },
217
222
  ];
218
223
  };
224
+ const faultCases = (make) => [
225
+ ...[403, 404].map((status) => ({
226
+ name: `faults: a contact or company that answers ${status} is null from get, not a failure`,
227
+ async run() {
228
+ const { source, faults } = await make();
229
+ if (!faults?.deny || !source.get)
230
+ return;
231
+ const { kind, id } = await faults.deny(status);
232
+ assert.equal(await source.get(kind, id), null, `get(${kind}, ${id}) after a ${status}`);
233
+ },
234
+ })),
235
+ {
236
+ name: "faults: a clock off by ten minutes either way loses no change",
237
+ async run() {
238
+ const first = await make();
239
+ if (!first.faults?.skewed || !first.faults.change)
240
+ return;
241
+ for (const ms of [SKEW_MS, -SKEW_MS]) {
242
+ const { faults } = ms === SKEW_MS ? first : await make();
243
+ const source = (await faults?.skewed?.(ms));
244
+ const read = await Promise.all(source.traits.kinds.map(async (kind) => [kind, await listAll(source, kind, null)]));
245
+ const { kind, id } = await faults.change();
246
+ const cursor = read.find(([one]) => one === kind)?.[1].cursor ?? null;
247
+ assert.ok(cursor !== null, `${kind}: a full list gives a cursor for the change to be read after`);
248
+ const { items } = await listAll(source, kind, cursor);
249
+ assert.ok(idsOf(items).includes(id), `${kind} ${id} is in the changes with this computer's clock ${ms / 60_000} min off`);
250
+ }
251
+ },
252
+ },
253
+ {
254
+ name: "faults: a second profile on the same token is the same user and lists the same rows",
255
+ async run() {
256
+ const { source, faults } = await make();
257
+ const other = await faults?.sameToken?.();
258
+ if (!other)
259
+ return;
260
+ if (source.self)
261
+ assert.equal(await other.self?.(), await source.self(), "both profiles name one user");
262
+ for (const kind of source.traits.kinds)
263
+ assert.deepEqual(idsOf((await listAll(other, kind, null)).items).sort(), idsOf((await listAll(source, kind, null)).items).sort(), `${kind}: both profiles list the same rows`);
264
+ },
265
+ },
266
+ {
267
+ name: "faults: a full list cut after its first page goes on from that page in a new run, nothing lost or repeated",
268
+ async run() {
269
+ const { source, faults } = await make();
270
+ if (!faults)
271
+ return;
272
+ let cut = false;
273
+ for (const kind of source.traits.kinds) {
274
+ const whole = idsOf((await listAll(source, kind, null)).items);
275
+ const first = (await source.changes(kind, null));
276
+ if (!first.hasMore)
277
+ continue;
278
+ cut = true;
279
+ const { source: resumed } = await make();
280
+ const rest = [];
281
+ let page = first.nextCursor;
282
+ for (let read = 0; page !== undefined && read < MAX_PAGES; read += 1) {
283
+ const answer = (await resumed.changes(kind, null, page));
284
+ rest.push(...answer.items);
285
+ page = answer.nextCursor;
286
+ }
287
+ const joined = [...idsOf(first.items), ...idsOf(rest)];
288
+ assert.equal(new Set(joined).size, joined.length, `${kind}: no row twice across the cut`);
289
+ assert.deepEqual(joined.sort(), whole.sort(), `${kind}: the cut list adds up to the whole one`);
290
+ }
291
+ assert.ok(cut, "the fixture holds more than one page of some kind, so a list can be cut");
292
+ },
293
+ },
294
+ {
295
+ // A source that never pages inside one call never asks, and passes: the deadline itself is the engine's to keep.
296
+ name: "faults: a call that pages inside stops when the run's budget is spent, and says so",
297
+ async run() {
298
+ const { source, faults } = await make();
299
+ if (!faults)
300
+ return;
301
+ const spent = new CliError("provider_error", "the run's budget is spent", { reason: "sync.partial" });
302
+ let asked = false;
303
+ const context = {
304
+ spend: () => {
305
+ asked = true;
306
+ throw spent;
307
+ },
308
+ gap: () => { },
309
+ };
310
+ for (const kind of source.traits.kinds) {
311
+ asked = false;
312
+ const ended = await source.changes(kind, null, undefined, context).then(() => undefined, (error) => error);
313
+ if (asked)
314
+ assert.equal(ended, spent, `${kind}: a spent budget ends the call with its own error, not swallowed`);
315
+ else
316
+ assert.equal(ended, undefined, `${kind}: a call that asks for no more requests is not stopped`);
317
+ }
318
+ },
319
+ },
320
+ ];
@@ -43,6 +43,8 @@ export interface FakeCrmSource extends CrmSource, CrmWriter {
43
43
  expireCursors(kind: CrmKind): void;
44
44
  /** Lists no id at all, as a CRM does for a sign-in that lost its rights. */
45
45
  hideAll(hidden: boolean): void;
46
+ /** One record the sign-in may no longer read: `get` answers it as the CRM's 403 or 404, with nothing. */
47
+ deny(kind: CrmKind, externalId: string): void;
46
48
  /** The next write is carried out and its answer lost: it throws `outcome_unknown`. */
47
49
  loseNextAnswer(): void;
48
50
  /** The next write is carried out and its item cannot be read back: it throws with `sent: true`. */
@@ -49,6 +49,7 @@ export const fakeCrmSource = (options = {}) => {
49
49
  const fields = { deal: [SOURCE_FIELD], lead: [], person: [], organization: [] };
50
50
  let version = 0;
51
51
  const expired = new Map();
52
+ const denied = new Set();
52
53
  let hidden = false;
53
54
  const calls = { pipelines: 0, fields: 0, changes: 0, ids: 0, list: 0, get: 0 };
54
55
  const capabilities = {
@@ -287,6 +288,8 @@ export const fakeCrmSource = (options = {}) => {
287
288
  },
288
289
  async get(kind, externalId) {
289
290
  calls.get += 1;
291
+ if (denied.has(`${kind}:${externalId}`))
292
+ return null;
290
293
  const found = of(kind).get(externalId);
291
294
  return (found && !found.deleted ? found.record : null);
292
295
  },
@@ -348,6 +351,9 @@ export const fakeCrmSource = (options = {}) => {
348
351
  hideAll(value) {
349
352
  hidden = value;
350
353
  },
354
+ deny(kind, externalId) {
355
+ denied.add(`${kind}:${externalId}`);
356
+ },
351
357
  async pipelines(kind) {
352
358
  calls.pipelines += 1;
353
359
  return pipelines[kind];
@@ -1,4 +1,4 @@
1
- import type { CopyViewer, MessageStore } from "../store/store.js";
1
+ import { type CopyViewer, type MessageStore } from "../store/store.js";
2
2
  import type { AccountKey } from "../store/types.js";
3
3
  import type { CrmSource } from "./source.js";
4
4
  /**
@@ -26,3 +26,16 @@ export declare const viewerOf: (run: {
26
26
  account: AccountKey;
27
27
  user: string | null;
28
28
  }) => Promise<CopyViewer | undefined>;
29
+ /**
30
+ * The row with `deal`, the deal a lead became, left out when a viewer may not read that deal (SEC-197): a lead the
31
+ * profile reads must not name a colleague's deal.
32
+ */
33
+ export declare const withReadableDeal: <T extends {
34
+ deal: string | null;
35
+ }>(store: MessageStore, viewers: readonly (CopyViewer | undefined)[], row: T) => Promise<T>;
36
+ /** `owner:` as the identity a deal's assignee is stored as; `none` is no assignee. */
37
+ export declare const ownerOf: (run: {
38
+ store: MessageStore;
39
+ account: AccountKey;
40
+ user: string | null;
41
+ }, owner: string) => Promise<string | null>;
@@ -1,5 +1,7 @@
1
- import { normalCrmUserId } from "../domain/crm.js";
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { isCrmUserId, normalCrmUserId } from "../domain/crm.js";
2
3
  import { crmIdentityId } from "../store/sqlite/crm-rows.js";
4
+ import { seenBy } from "../store/store.js";
3
5
  // A sync state, not a CRM setting: `config set` must never make a profile the administrator.
4
6
  const VIEWERS = "crm:viewers";
5
7
  const viewersOf = async (store, account) => {
@@ -61,3 +63,38 @@ export const viewerOf = async (run) => {
61
63
  shortened.set(run, note);
62
64
  return viewer;
63
65
  };
66
+ /**
67
+ * The row with `deal`, the deal a lead became, left out when a viewer may not read that deal (SEC-197): a lead the
68
+ * profile reads must not name a colleague's deal.
69
+ */
70
+ export const withReadableDeal = async (store, viewers, row) => {
71
+ const limiting = viewers.filter((one) => one !== undefined);
72
+ if (row.deal === null || limiting.length === 0)
73
+ return row;
74
+ const target = await store.deals.get(row.deal).catch(() => undefined);
75
+ const seen = target !== undefined &&
76
+ limiting.every((viewer) => seenBy(viewer, {
77
+ provider: target.account?.provider,
78
+ account: target.account?.account,
79
+ assignee: target.assignee,
80
+ }));
81
+ return seen ? row : { ...row, deal: null };
82
+ };
83
+ /** `owner:` as the identity a deal's assignee is stored as; `none` is no assignee. */
84
+ export const ownerOf = async (run, owner) => {
85
+ if (owner === "none")
86
+ return null;
87
+ if (owner === "me") {
88
+ const self = run.user ?? (await run.store.crm.ownUser(run.account));
89
+ if (!self)
90
+ throw new CliError("validation_error", "this CRM names no user for the sign-in: use owner:<user id>", {
91
+ reason: "crm.owner-unknown",
92
+ });
93
+ return crmIdentityId(run.account, normalCrmUserId(self), "user");
94
+ }
95
+ if (!isCrmUserId(owner))
96
+ throw new CliError("validation_error", `owner takes me, none or the CRM's user id, not ${owner}`, {
97
+ reason: "crm.owner-unknown",
98
+ });
99
+ return crmIdentityId(run.account, normalCrmUserId(owner), "user");
100
+ };
@@ -0,0 +1,10 @@
1
+ import { type FetchLike, type HostFetchOptions } from "@wirecat/cli-base/http";
2
+ /**
3
+ * `fetch` for a URL the service handed back: a download or upload link, a signed file URL. Such a link lives on
4
+ * another host (Yandex Disk's `downloader.disk.yandex.ru`, Notion's file store) and carries its own grant, so it goes
5
+ * only to the hosts listed, over https, and never with the sign-in: a request carrying one is refused before it leaves.
6
+ * `signIn` names a service's own sign-in headers (an API key's `X-Api-Key`) to refuse beside the standard ones.
7
+ */
8
+ export declare const linkFetch: (options: HostFetchOptions & {
9
+ signIn?: readonly string[];
10
+ }) => FetchLike;
@@ -0,0 +1,28 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { hostFetch } from "@wirecat/cli-base/http";
3
+ const CREDENTIALS = ["authorization", "cookie", "proxy-authorization"];
4
+ /**
5
+ * `fetch` for a URL the service handed back: a download or upload link, a signed file URL. Such a link lives on
6
+ * another host (Yandex Disk's `downloader.disk.yandex.ru`, Notion's file store) and carries its own grant, so it goes
7
+ * only to the hosts listed, over https, and never with the sign-in: a request carrying one is refused before it leaves.
8
+ * `signIn` names a service's own sign-in headers (an API key's `X-Api-Key`) to refuse beside the standard ones.
9
+ */
10
+ export const linkFetch = (options) => {
11
+ const { signIn = [], ...rest } = options;
12
+ const send = hostFetch(rest);
13
+ const refused = [...CREDENTIALS, ...signIn.map((name) => name.toLowerCase())];
14
+ return async (input, init = {}) => {
15
+ const url = new URL(input instanceof Request ? input.url : String(input));
16
+ if (url.protocol !== "https:")
17
+ throw new CliError("validation_error", `a link the service returned must be https, not ${url.protocol}`, {
18
+ sent: false,
19
+ });
20
+ const headers = new Headers(init.headers ?? (input instanceof Request ? input.headers : undefined));
21
+ const carried = refused.filter((name) => headers.has(name));
22
+ if (carried.length > 0)
23
+ throw new CliError("configuration_error", `a link the service returned is never sent ${carried.join(" or ")}`, {
24
+ sent: false,
25
+ });
26
+ return send(input, init);
27
+ };
28
+ };
@@ -1,4 +1,4 @@
1
- import type { RunReport } from "./pull.js";
1
+ import { type RunReport } from "./pull.js";
2
2
  import type { MeetingInput, MeetingStore, ParticipantInput } from "./store.js";
3
3
  export interface ImportFile {
4
4
  meeting: MeetingInput;
@@ -1,5 +1,6 @@
1
1
  import { linkEvent } from "./events.js";
2
2
  import { transcriptInput } from "./ingest.js";
3
+ import { indexSaved } from "./pull.js";
3
4
  import { parseTranscriptText } from "./transcript-text.js";
4
5
  import { parseVtt } from "./vtt.js";
5
6
  /** The caller reads files and supplies provider-neutral occurrence metadata. */
@@ -29,6 +30,7 @@ export const importFiles = async (files, store, now = Date.now()) => {
29
30
  });
30
31
  }
31
32
  }
33
+ await indexSaved(store, files.map((file) => file.meeting.accountId), report);
32
34
  const zones = new Set(files.map((file) => file.meeting.timezone).filter((zone) => zone !== null && zone !== undefined));
33
35
  const [zone] = zones;
34
36
  if (zones.size === 1 && zone)
@@ -51,6 +51,7 @@ export { MEETING_RESULT_ENTITIES } from "./result-items.js";
51
51
  export { type MeetingReview, type MeetingReviewInput, type MeetingReviewItem, type MeetingReviewSpeaker, type MeetingReviewStore, REVIEW_LIMIT, } from "./review.js";
52
52
  export { SAVE_HELP, SAVE_INSTRUCTION } from "./save-hints.js";
53
53
  export type { MeetingHitSearchRequest, MeetingSearchIndexInput, MeetingSearchIndexReceipt, MeetingSearchIndexStore, MeetingSearchOptions, MeetingSearchPage, MeetingSearchStore, } from "./search-store.js";
54
+ export { refreshMeetingIndex } from "./search-store.js";
54
55
  export { validateMeetingHitSearch } from "./search-validation.js";
55
56
  export { type MeetingHistoryEntry, type MeetingSeriesContext, type MeetingSeriesHistory, type MeetingSeriesHistoryRequest, type MeetingSeriesHistoryStore, validateMeetingSeriesHistory, } from "./series-history.js";
56
57
  export { createMeetingSeriesInventoryReader } from "./series-inventory.js";
@@ -40,6 +40,7 @@ export { validateMeetingRelatedHistory, } from "./related-history.js";
40
40
  export { MEETING_RESULT_ENTITIES } from "./result-items.js";
41
41
  export { REVIEW_LIMIT, } from "./review.js";
42
42
  export { SAVE_HELP, SAVE_INSTRUCTION } from "./save-hints.js";
43
+ export { refreshMeetingIndex } from "./search-store.js";
43
44
  export { validateMeetingHitSearch } from "./search-validation.js";
44
45
  export { validateMeetingSeriesHistory, } from "./series-history.js";
45
46
  export { createMeetingSeriesInventoryReader } from "./series-inventory.js";
@@ -56,4 +56,6 @@ export declare const saveSourceMeeting: (source: Pick<MeetingSource, "provider"
56
56
  now: number;
57
57
  kept?: Meeting;
58
58
  }) => Promise<MeetingDetails>;
59
+ /** Search reads only the index, so what a sync or an import saved is indexed before it answers. */
60
+ export declare const indexSaved: (store: MeetingStore, accountIds: Iterable<number>, report: RunReport) => Promise<void>;
59
61
  export declare const pull: (source: MeetingSource, store: MeetingStore, options: PullOptions) => Promise<RunReport>;
@@ -1,5 +1,6 @@
1
1
  import { linkEvent } from "./events.js";
2
2
  import { speakerPosition, timestamp, transcriptInput } from "./ingest.js";
3
+ import { refreshMeetingIndex } from "./search-store.js";
3
4
  const participantInput = (p, provider, occurrenceId, position, accountId) => {
4
5
  const { identityExternalId, phone, ...fields } = p;
5
6
  const externalId = identityExternalId ??
@@ -124,6 +125,22 @@ const startOf = (m) => {
124
125
  const at = Date.parse(m.occurrence.startedAt);
125
126
  return Number.isFinite(at) ? at : Number.POSITIVE_INFINITY;
126
127
  };
128
+ /** Search reads only the index, so what a sync or an import saved is indexed before it answers. */
129
+ export const indexSaved = async (store, accountIds, report) => {
130
+ const indexSearch = store.indexSearch?.bind(store);
131
+ if (!indexSearch || report.meetings === 0)
132
+ return;
133
+ for (const accountId of new Set(accountIds))
134
+ try {
135
+ await refreshMeetingIndex({ indexSearch }, accountId);
136
+ }
137
+ catch (error) {
138
+ report.warnings.push({
139
+ externalId: String(accountId),
140
+ message: `search index not updated: ${error instanceof Error ? error.message : "failed"}`,
141
+ });
142
+ }
143
+ };
127
144
  export const pull = async (source, store, options) => {
128
145
  const now = options.now ?? Date.now();
129
146
  for (const [name, ms] of [
@@ -217,6 +234,7 @@ export const pull = async (source, store, options) => {
217
234
  }
218
235
  }
219
236
  await linkCallers();
237
+ await indexSaved(store, [options.accountId], report);
220
238
  // A failed occurrence must remain inside the next pull's retry window.
221
239
  if (!failed)
222
240
  await store.setCursor(options.accountId, new Date(now).toISOString(), now);
@@ -61,3 +61,5 @@ export interface MeetingHitSearchRequest extends MeetingSearchOptions {
61
61
  tag?: string;
62
62
  topic?: string;
63
63
  }
64
+ /** Each batch commits on its own, so a search or sync cut short by its deadline keeps the progress it made. */
65
+ export declare const refreshMeetingIndex: (meetings: MeetingSearchIndexStore, accountId: number, signal?: AbortSignal) => Promise<void>;
@@ -1 +1,16 @@
1
- export {};
1
+ /** Each batch commits on its own, so a search or sync cut short by its deadline keeps the progress it made. */
2
+ export const refreshMeetingIndex = async (meetings, accountId, signal) => {
3
+ let before = Number.POSITIVE_INFINITY;
4
+ for (;;) {
5
+ signal?.throwIfAborted();
6
+ const { indexed, remaining } = await meetings.indexSearch({
7
+ accountId,
8
+ limit: 1000,
9
+ maxReadBytes: 64 * 1024 ** 2,
10
+ signal,
11
+ });
12
+ if (remaining === 0 || indexed === 0 || remaining >= before)
13
+ return;
14
+ before = remaining;
15
+ }
16
+ };
@@ -2,6 +2,7 @@ import type { QueryAst } from "@wirecat/cli-base/query";
2
2
  import type { ListResult } from "@wirecat/cli-base/standards";
3
3
  import type { MeetingOwner } from "./item.js";
4
4
  import type { Attachment, ChatLine, Event, EventSeries, Meeting, MeetingSeries, Metadata, Participant, Summary, Transcript, TranscriptRow } from "./model.js";
5
+ import type { MeetingSearchIndexStore } from "./search-store.js";
5
6
  export type NewRecord<T> = Omit<T, "id" | "createdAt" | "updatedAt">;
6
7
  export interface IdentityInput {
7
8
  /** Explicit stable provider key; false or absent must not create a person association. */
@@ -189,6 +190,8 @@ export interface MeetingStore {
189
190
  setCursor(accountId: number, value: string, now: number): Promise<void>;
190
191
  /** Links the callers a sync saved, by `provider` and identity external id, to the people with their number. */
191
192
  linkCallers?(provider: string, externalIds: readonly string[]): Promise<void>;
193
+ /** Brings the account's search index up to what is saved; a sync and an import run it so search finds their text. */
194
+ indexSearch?: MeetingSearchIndexStore["indexSearch"];
192
195
  /** Detects the language of the account's transcripts that have none; stores it only with `apply`. */
193
196
  fillTranscriptLanguages?(input: {
194
197
  accountId: number;