@wirecat/cli-core 1.0.0-rc.0 → 1.1.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 (96) hide show
  1. package/CHANGELOG.md +186 -0
  2. package/THIRD_PARTY_NOTICES +47 -0
  3. package/dist/cli/account-rename.js +1 -1
  4. package/dist/cli/bot/api-input.d.ts +5 -0
  5. package/dist/cli/bot/api-input.js +6 -1
  6. package/dist/cli/bot/api.js +7 -1
  7. package/dist/cli/domain-lists-command.d.ts +16 -0
  8. package/dist/cli/domain-lists-command.js +88 -0
  9. package/dist/cli/index.d.ts +4 -3
  10. package/dist/cli/index.js +3 -2
  11. package/dist/cli/model-catalogue-command.d.ts +6 -0
  12. package/dist/cli/model-catalogue-command.js +1 -1
  13. package/dist/cli/oauth-session.d.ts +38 -4
  14. package/dist/cli/oauth-session.js +66 -22
  15. package/dist/cli/service-api.js +3 -1
  16. package/dist/cli/shared-command-exports.d.ts +2 -0
  17. package/dist/cli/shared-command-exports.js +3 -0
  18. package/dist/cli/token-session.d.ts +9 -0
  19. package/dist/cli/token-session.js +29 -2
  20. package/dist/crm/manifest/map.d.ts +5 -2
  21. package/dist/crm/manifest/map.js +14 -2
  22. package/dist/domain/domain-lists.d.ts +86 -0
  23. package/dist/domain/domain-lists.js +110 -0
  24. package/dist/domain/free-mail-domains.generated.d.ts +1 -0
  25. package/dist/domain/free-mail-domains.generated.js +4 -0
  26. package/dist/domain/organization-sectors.d.ts +16 -0
  27. package/dist/domain/organization-sectors.generated.d.ts +12 -0
  28. package/dist/domain/organization-sectors.generated.js +15 -0
  29. package/dist/domain/organization-sectors.js +22 -0
  30. package/dist/domain/person-kinds.d.ts +5 -0
  31. package/dist/domain/person-kinds.js +5 -0
  32. package/dist/entities/domain-list.d.ts +27 -0
  33. package/dist/entities/domain-list.js +28 -0
  34. package/dist/entities/index.d.ts +20 -1
  35. package/dist/entities/index.js +3 -1
  36. package/dist/entities/knowledge-lists.d.ts +1 -0
  37. package/dist/entities/knowledge-lists.js +2 -0
  38. package/dist/errors/reasons.js +14 -3
  39. package/dist/mail/mail-types.d.ts +48 -0
  40. package/dist/mail/mail-types.js +218 -0
  41. package/dist/mail/score.d.ts +2 -0
  42. package/dist/mail/score.js +9 -2
  43. package/dist/oauth/index.d.ts +1 -1
  44. package/dist/oauth/storage.d.ts +10 -2
  45. package/dist/oauth/storage.js +23 -9
  46. package/dist/services/domain-lists-download.d.ts +26 -0
  47. package/dist/services/domain-lists-download.js +155 -0
  48. package/dist/services/search-all-rank.d.ts +44 -0
  49. package/dist/services/search-all-rank.js +112 -0
  50. package/dist/services/search-all-tracker.d.ts +58 -0
  51. package/dist/services/search-all-tracker.js +155 -0
  52. package/dist/services/search-all.d.ts +1 -8
  53. package/dist/services/search-all.js +18 -199
  54. package/dist/services/tracker-meaning.js +1 -1
  55. package/dist/store/areas.d.ts +1 -0
  56. package/dist/store/index.d.ts +2 -1
  57. package/dist/store/index.js +1 -1
  58. package/dist/store/people.d.ts +30 -0
  59. package/dist/store/people.js +16 -1
  60. package/dist/store/sqlite/accounts.js +3 -1
  61. package/dist/store/sqlite/domain-organizations.d.ts +36 -0
  62. package/dist/store/sqlite/domain-organizations.js +288 -0
  63. package/dist/store/sqlite/email-types.d.ts +79 -0
  64. package/dist/store/sqlite/email-types.js +261 -0
  65. package/dist/store/sqlite/emails.d.ts +11 -2
  66. package/dist/store/sqlite/emails.js +18 -7
  67. package/dist/store/sqlite/identities.d.ts +4 -1
  68. package/dist/store/sqlite/identities.js +11 -2
  69. package/dist/store/sqlite/identity-rekey.js +2 -0
  70. package/dist/store/sqlite/knowledge.d.ts +2 -9
  71. package/dist/store/sqlite/manifest.js +6 -0
  72. package/dist/store/sqlite/merged-persons.d.ts +3 -2
  73. package/dist/store/sqlite/merged-persons.js +5 -3
  74. package/dist/store/sqlite/migrations.generated.js +77 -0
  75. package/dist/store/sqlite/organizations.d.ts +12 -1
  76. package/dist/store/sqlite/organizations.js +9 -1
  77. package/dist/store/sqlite/people-list.js +69 -11
  78. package/dist/store/sqlite/person-links.js +13 -3
  79. package/dist/store/sqlite/person-match-scan.js +14 -1
  80. package/dist/store/sqlite/schema/sender-bots.d.ts +344 -0
  81. package/dist/store/sqlite/schema/sender-bots.js +30 -0
  82. package/dist/store/sqlite/schema.d.ts +49 -0
  83. package/dist/store/sqlite/schema.js +7 -0
  84. package/dist/store/sqlite/sender-bots.d.ts +108 -0
  85. package/dist/store/sqlite/sender-bots.js +431 -0
  86. package/dist/store/sqlite/sender-signals.d.ts +13 -3
  87. package/dist/store/sqlite/sender-signals.js +17 -13
  88. package/dist/store/sqlite/tracker.d.ts +11 -9
  89. package/dist/store/sqlite/tracker.js +27 -12
  90. package/dist/store/sqlite/work-tasks.js +2 -0
  91. package/dist/tracker/cli/index.d.ts +1 -1
  92. package/dist/tracker/cli/index.js +83 -24
  93. package/dist/tracker/sync.js +43 -20
  94. package/dist/tracker/writes.d.ts +28 -0
  95. package/dist/tracker/writes.js +141 -19
  96. package/package.json +3 -3
@@ -3,16 +3,16 @@ import { annotate } from "@wirecat/cli-base/commands";
3
3
  import { hostFetch } from "@wirecat/cli-base/http";
4
4
  import { Command } from "commander";
5
5
  import { tokenKeeper } from "../oauth/keeper.js";
6
- import { credentialStorage, oauthAccount, standardCodec } from "../oauth/storage.js";
6
+ import { credentialStorage, oauthAccount, standardCodec, } from "../oauth/storage.js";
7
7
  import { editDistance } from "../search/correct.js";
8
- import { signInSteps } from "../terminal/sign-in-steps.js";
8
+ import { answerStdinOption, signInSteps } from "../terminal/sign-in-steps.js";
9
9
  import { baseContext, environmentOf, outputFor } from "./context.js";
10
10
  import { refuseOffline } from "./early-refusal.js";
11
11
  import { LOCAL_READ, LOCAL_WRITE, logsInOrOut, REMOTE_READ, REMOTE_WRITE } from "./effects.js";
12
12
  import { itemOf, listOf, renderAnswer } from "./envelope.js";
13
13
  import { profilesHere, rememberAccount } from "./messenger/accounts.js";
14
14
  import { commandWords, profileFree, refuseCommandName, rootOf } from "./profile.js";
15
- import { storageOf } from "./token-session.js";
15
+ import { storageOf, unknownSignIn } from "./token-session.js";
16
16
  /**
17
17
  * The authorization code flow an OpenAPI spec declares; a GraphQL service (Linear) writes the same object by hand.
18
18
  * @experimental
@@ -58,6 +58,7 @@ export const oauthPreset = (flow, options) => {
58
58
  };
59
59
  return { provider, scopes: [...options.scopes], rotating: options.rotating === true };
60
60
  };
61
+ const PASTE_PROMPT = "the address the browser shows after you allow access, when it does not come back here";
61
62
  /**
62
63
  * `session start | status | end | list` for a service signed in in the browser (WC-SECR-22): PKCE on the loopback,
63
64
  * the account checked before the tokens are kept, refreshes under one lock, and a run with moved folders that never
@@ -66,6 +67,7 @@ export const oauthPreset = (flow, options) => {
66
67
  */
67
68
  export const oauthSessionCommand = (options) => {
68
69
  const { app, providerId, service } = options;
70
+ const codec = options.codec ?? standardCodec(providerId);
69
71
  const pathsOf = (env) => ({ appName: app.appName, prefix: app.envPrefix, env });
70
72
  const storageFor = (where, profile, storage = "auto", rotating = false) => credentialStorage({
71
73
  credentials: {
@@ -78,7 +80,8 @@ export const oauthSessionCommand = (options) => {
78
80
  ...(where.warn ? { warn: where.warn } : {}),
79
81
  },
80
82
  account: oauthAccount(providerId, profile),
81
- codec: rotating ? { ...standardCodec(providerId), rotating: true } : standardCodec(providerId),
83
+ ...(options.legacyAccounts ? { legacyAccounts: options.legacyAccounts(where.env, profile) } : {}),
84
+ codec: rotating && !codec.rotating ? { ...codec, rotating: true } : codec,
82
85
  });
83
86
  const contextOf = (command) => {
84
87
  const base = baseContext(command, options.resolveSettings);
@@ -86,8 +89,8 @@ export const oauthSessionCommand = (options) => {
86
89
  const where = { env: base.env, keyring: base.keyring, warn: base.renderer.warn };
87
90
  const { profile } = base.settings;
88
91
  /** The preset is asked only here, after the refusals: a CLI's client choice may fail on its own. */
89
- const keeperOf = (storage) => {
90
- const { provider, scopes, rotating } = options.preset(command);
92
+ const keeperOf = async (storage, steps) => {
93
+ const { provider, scopes, rotating } = await options.preset(command, steps);
91
94
  const keeper = tokenKeeper({
92
95
  provider,
93
96
  storage: storageFor(where, profile, storage ?? "auto", rotating),
@@ -102,7 +105,7 @@ export const oauthSessionCommand = (options) => {
102
105
  signInCommand: `${app.command} ${profile} session start`,
103
106
  ...(environment.signal ? { signal: environment.signal } : {}),
104
107
  });
105
- return { keeper, scopes };
108
+ return { keeper, scopes, client: provider.client };
106
109
  };
107
110
  const saved = () => storageFor(where, profile).read();
108
111
  return { ...base, environment, where, profile, keeperOf, saved };
@@ -112,31 +115,48 @@ export const oauthSessionCommand = (options) => {
112
115
  effects: REMOTE_WRITE,
113
116
  lifetime: "interactive",
114
117
  mcp: false,
115
- examples: [`${app.command} personal session start`, `${app.command} personal session start --no-browser`],
118
+ examples: [
119
+ `${app.command} personal session start`,
120
+ `${app.command} personal session start --no-browser`,
121
+ `${app.command} personal session start --json --answer-stdin`,
122
+ ],
116
123
  }))
117
124
  .summary(`sign in to ${service} in the browser`)
118
125
  .description(`sign this profile in to ${service} in the browser; the account is checked before anything is kept, in the ` +
119
126
  "keyring or, with --credential-storage file, a private file")
120
127
  .option("--no-browser", "print the sign-in URL instead of opening a browser")
121
128
  .option("--credential-storage <storage>", "where the sign-in is kept: keyring, which falls back to a private file by itself, or file", storageOf, "keyring")
122
- .action(async function (args) {
129
+ .addOption(answerStdinOption());
130
+ for (const option of options.startOptions ?? [])
131
+ start.addOption(option);
132
+ start.action(async function (args) {
123
133
  const context = contextOf(this);
124
134
  refuseCommandName(context.profile, commandWords(rootOf(this)), app.command);
125
135
  refuseOffline(this, service);
126
- const { keeper, scopes: asked } = context.keeperOf(args.credentialStorage === "file" ? "file" : undefined);
127
136
  const { streams } = outputFor(this);
128
137
  const steps = signInSteps({
129
138
  diagnostic: (line) => streams.diagnostic(`${line}\n`),
130
139
  json: context.format !== "pretty" || context.environment.tty === false,
131
- answers: false,
140
+ answers: args.answerStdin === true,
141
+ ...(context.environment.stdin ? { input: context.environment.stdin } : {}),
132
142
  });
143
+ const { keeper, scopes: asked, client, } = await context.keeperOf(args.credentialStorage === "file" ? "file" : undefined, steps);
133
144
  let shown = {};
145
+ let accountId = "";
134
146
  const { scopes } = await context.run((events) => keeper.signIn({
135
147
  scopes: asked,
136
148
  openBrowser: async (url) => {
137
149
  if (args.browser)
138
150
  await context.environment.openBrowser?.(url, this);
139
151
  },
152
+ ...(steps.answers
153
+ ? {
154
+ readPaste: (stop) => steps
155
+ .ask({ field: "redirect", secret: true, prompt: PASTE_PROMPT }, stop)
156
+ // The browser's callback won the race; the question is withdrawn, not failed.
157
+ .catch((error) => (stop.aborted ? new Promise(() => { }) : Promise.reject(error))),
158
+ }
159
+ : {}),
140
160
  showUrl: (url) => {
141
161
  steps.openUrl(url, `Sign in to ${service} and allow access`);
142
162
  streams.diagnostic(`Open ${service} sign-in: ${url}\n`);
@@ -145,10 +165,11 @@ export const oauthSessionCommand = (options) => {
145
165
  accept: async (tokens) => {
146
166
  if (!tokens.accessToken)
147
167
  throw new CliError("authentication_error", `${service} returned no access token`);
148
- const { id, account } = await options.verify(this, tokens.accessToken, events);
168
+ const { id, account, extra } = await options.verify(this, tokens.accessToken, events);
149
169
  (options.claim ?? ((env, profile, key) => rememberAccount(app, profile, key, env)))(context.env, context.profile, id);
150
170
  shown = account;
151
- return undefined;
171
+ accountId = id;
172
+ return extra;
152
173
  },
153
174
  }));
154
175
  // The owner chose the file: an older keyring copy must not outlive it with a live refresh token.
@@ -159,6 +180,14 @@ export const oauthSessionCommand = (options) => {
159
180
  catch {
160
181
  // No keyring on this computer: there is no copy to forget.
161
182
  }
183
+ await options.afterSignIn?.(this, {
184
+ env: context.env,
185
+ profile: context.profile,
186
+ id: accountId,
187
+ account: shown,
188
+ client,
189
+ scopes,
190
+ });
162
191
  answer(this, { ...shown, profile: context.profile, signed_in: true, scopes });
163
192
  });
164
193
  const status = annotate(new Command("status"), {
@@ -173,11 +202,18 @@ export const oauthSessionCommand = (options) => {
173
202
  const saved = context.saved();
174
203
  if (!saved)
175
204
  return answer(this, { profile: context.profile, state: "missing", verified: false });
176
- const state = { profile: context.profile, state: "saved", scopes: saved.tokens.scopes };
205
+ const { expiresAt } = saved.tokens;
206
+ const state = {
207
+ profile: context.profile,
208
+ state: "saved",
209
+ scopes: saved.tokens.scopes,
210
+ // The access token's end, which a refresh moves on; a sign-in itself ends only at session end or in the service.
211
+ expires_at: expiresAt ? new Date(expiresAt).toISOString() : null,
212
+ };
177
213
  if (!args.check)
178
214
  return answer(this, { ...state, verified: false });
179
215
  refuseOffline(this, service);
180
- const { keeper } = context.keeperOf();
216
+ const { keeper } = await context.keeperOf();
181
217
  const { account } = await context.run(async (events) => options.verify(this, await keeper.accessToken(), events));
182
218
  answer(this, { ...account, ...state, verified: true });
183
219
  });
@@ -193,7 +229,7 @@ export const oauthSessionCommand = (options) => {
193
229
  const context = contextOf(this);
194
230
  if (!context.saved())
195
231
  return answer(this, { profile: context.profile, ended: false });
196
- const { removed } = await context.keeperOf().keeper.signOut();
232
+ const { removed } = await (await context.keeperOf()).keeper.signOut();
197
233
  if (!context.saved())
198
234
  return answer(this, { profile: context.profile, ended: true, removed });
199
235
  answer(this, {
@@ -214,12 +250,20 @@ export const oauthSessionCommand = (options) => {
214
250
  .action(function () {
215
251
  const environment = environmentOf(this);
216
252
  const env = environment.env ?? process.env;
217
- const { configuredProfiles } = options.resolveSettings({}, { env, needsProfile: false });
218
- const where = { env, keyring: environment.keyring, warn: outputFor(this).renderer.warn };
219
- const items = profilesHere(app, configuredProfiles, env).map((profile) => ({
220
- profile,
221
- signed_in: storageFor(where, profile).read() !== undefined,
222
- }));
253
+ const { warn } = outputFor(this).renderer;
254
+ const where = { env, keyring: environment.keyring, warn };
255
+ const profiles = options.profiles?.(env) ??
256
+ profilesHere(app, options.resolveSettings({}, { env, needsProfile: false }).configuredProfiles, env);
257
+ const unknown = unknownSignIn(warn);
258
+ const items = profiles.map((profile) => {
259
+ try {
260
+ const saved = storageFor(where, profile).read() !== undefined;
261
+ return { profile, signed_in: saved, state: saved ? "saved" : "missing" };
262
+ }
263
+ catch (error) {
264
+ return unknown(profile, error);
265
+ }
266
+ });
223
267
  renderAnswer(this, outputFor(this), listOf("session list", { items, limit: Math.max(1, items.length), has_more: false }));
224
268
  });
225
269
  return annotate(new Command("session"), { effects: LOCAL_READ })
@@ -9,7 +9,7 @@ import { newOperationId } from "../sends/send-id.js";
9
9
  import { refusedPlace } from "../sends/upload.js";
10
10
  import { apiPathOf, generatedApiCommand } from "./bot/api.js";
11
11
  import { httpApiExchange, httpApiRequest, unsendableBody } from "./bot/api-http.js";
12
- import { apiJson, checkApiBody, checkApiParameter, graphqlVariables, parseApiJson, readApiBody, readApiBytes, sendsBytes, } from "./bot/api-input.js";
12
+ import { apiJson, checkApiBody, checkApiParameter, graphqlVariables, isBlank, parseApiJson, readApiBody, readApiBytes, sendsBytes, } from "./bot/api-input.js";
13
13
  import { baseContext, outputFor } from "./context.js";
14
14
  import { NO_EFFECTS } from "./effects.js";
15
15
  import { itemOf, listOf, renderAnswer } from "./envelope.js";
@@ -459,6 +459,8 @@ export const serviceApiWriter = (options) => {
459
459
  : parameter.in === "query" || parameter.in === "path"
460
460
  ? input[parameter.in][parameter.name]
461
461
  : undefined;
462
+ if (parameter.required && raw !== undefined && isBlank(flagText(raw)))
463
+ throw new CliError("validation_error", `${parameter.name} of ${operation.command} is empty`, { sent: false });
462
464
  const problem = raw === undefined ? undefined : checkApiParameter(parameter.name, parameter.schema, flagText(raw), schemas);
463
465
  if (problem)
464
466
  throw new CliError("validation_error", problem);
@@ -1048,4 +1048,6 @@ export declare const skillCommand: (app: import("./entry.js").AppIdentity, skill
1048
1048
  export declare const upgradeCommand: (app: import("./entry.js").AppIdentity, packageName: string, contextFor: (command: import("commander").Command) => import("./upgrade-command.js").UpgradeContext) => import("commander").Command;
1049
1049
  export declare const modelCatalogueCommand: (app: import("./entry.js").AppIdentity, options: import("./model-catalogue-command.js").ModelCatalogueOptions) => import("commander").Command;
1050
1050
  /** @experimental */
1051
+ export declare const domainListsCommand: (app: import("./entry.js").AppIdentity, options: import("./domain-lists-command.js").DomainListsCommandOptions) => import("commander").Command;
1052
+ /** @experimental */
1051
1053
  export declare const templatesCommand: (app: import("./entry.js").AppIdentity, options: import("./templates-command.js").TemplatesOptions) => import("commander").Command;
@@ -151,8 +151,11 @@ export const watchCommand = sharedCommand(watchCommandDefinition);
151
151
  export const runsCommand = sharedCommand(runsCommandDefinition);
152
152
  export const skillCommand = sharedCommand(skillCommandDefinition);
153
153
  export const upgradeCommand = sharedCommand(upgradeCommandDefinition);
154
+ import { domainListsCommand as domainListsDefinition } from "./domain-lists-command.js";
154
155
  import { modelCatalogueCommand as modelCatalogueDefinition } from "./model-catalogue-command.js";
155
156
  import { templatesCommand as templatesDefinition } from "./templates-command.js";
156
157
  export const modelCatalogueCommand = sharedCommand(modelCatalogueDefinition);
157
158
  /** @experimental */
159
+ export const domainListsCommand = sharedCommand(domainListsDefinition);
160
+ /** @experimental */
158
161
  export const templatesCommand = sharedCommand(templatesDefinition);
@@ -74,6 +74,15 @@ export interface ManifestVerifyOptions {
74
74
  * answer does not call active is refused, and the account is the id and name the answer holds.
75
75
  */
76
76
  export declare const manifestVerify: ({ manifest, service, verify, fetch }: ManifestVerifyOptions) => TokenSessionOptions["verify"];
77
+ /**
78
+ * `session list`'s row for a profile whose sign-in cannot be read: a keyring this run cannot reach or a broken entry
79
+ * must not hide the other profiles (WC-ACCT-12), and `session status` names the cause. Warns once per cause.
80
+ */
81
+ export declare const unknownSignIn: (warn: (message: string) => void) => (profile: string, error: unknown) => {
82
+ readonly profile: string;
83
+ readonly signed_in: null;
84
+ readonly state: "unknown";
85
+ };
77
86
  export declare const storageOf: (raw: string) => TokenStorage;
78
87
  /**
79
88
  * `session start | status | end | list` for a service signed in with one token (WC-ACCT-12): the token is asked hidden
@@ -38,6 +38,22 @@ export const manifestVerify = ({ manifest, service, verify, fetch }) => async (c
38
38
  const name = verify.name === undefined ? undefined : valueAt(answer, verify.name);
39
39
  return { id: String(id), account: { id: String(id), ...(typeof name === "string" ? { name } : {}) } };
40
40
  };
41
+ const UNREADABLE = new Set(["keyring.unreachable", "oauth.not-saved", "oauth.invalid", "session.unreadable"]);
42
+ /**
43
+ * `session list`'s row for a profile whose sign-in cannot be read: a keyring this run cannot reach or a broken entry
44
+ * must not hide the other profiles (WC-ACCT-12), and `session status` names the cause. Warns once per cause.
45
+ */
46
+ export const unknownSignIn = (warn) => {
47
+ const warned = new Set();
48
+ return (profile, error) => {
49
+ if (!(error instanceof CliError) || !UNREADABLE.has(String(error.details.reason)))
50
+ throw error;
51
+ if (!warned.has(error.message))
52
+ warn(error.message);
53
+ warned.add(error.message);
54
+ return { profile, signed_in: null, state: "unknown" };
55
+ };
56
+ };
41
57
  export const storageOf = (raw) => {
42
58
  if (raw === "keyring" || raw === "file")
43
59
  return raw;
@@ -166,9 +182,20 @@ export const tokenSessionCommand = (options) => {
166
182
  ...(environment.keyring ? { keyring: environment.keyring } : {}),
167
183
  warn: outputFor(this).renderer.warn,
168
184
  });
185
+ const unknown = unknownSignIn(outputFor(this).renderer.warn);
169
186
  const items = profilesHere(app, configuredProfiles, env).map((profile) => {
170
- const saved = tokens.read(profile);
171
- return { profile, signed_in: saved !== undefined, token_from: saved?.source ?? null };
187
+ try {
188
+ const saved = tokens.read(profile);
189
+ return {
190
+ profile,
191
+ signed_in: saved !== undefined,
192
+ state: saved ? "saved" : "missing",
193
+ token_from: saved?.source ?? null,
194
+ };
195
+ }
196
+ catch (error) {
197
+ return { ...unknown(profile, error), token_from: null };
198
+ }
172
199
  });
173
200
  renderAnswer(this, outputFor(this), listOf("session list", { items, limit: Math.max(1, items.length), has_more: false }));
174
201
  });
@@ -44,8 +44,11 @@ export declare const FIELDS: {
44
44
  export declare const convert: (conversion: Conversion, value: unknown) => unknown;
45
45
  /** Our fields from the rules, each converted by `types`; a rule whose path is missing gives no key. */
46
46
  export declare const mapFields: (rules: Readonly<Record<string, CrmRule | undefined>>, types: Readonly<Record<string, Conversion>>, raw: CrmRaw) => Record<string, unknown>;
47
- /** Where a typed entry keeps its value, by its type, as Attio names them; a manifest's `typed.paths` adds or replaces. */
48
- export declare const TYPED_VALUE_PATHS: Readonly<Record<string, string>>;
47
+ /**
48
+ * Where a typed entry keeps its value, by its type, as Attio names them; a manifest's `typed.paths` adds or replaces.
49
+ * A list of paths is one text of the parts present: an address is kept in parts, and searched as one line.
50
+ */
51
+ export declare const TYPED_VALUE_PATHS: Readonly<Record<string, string | readonly string[]>>;
49
52
  export interface RecordRules {
50
53
  map: Readonly<Record<string, CrmRule | undefined>>;
51
54
  custom?: {
@@ -178,7 +178,10 @@ export const mapFields = (rules, types, raw) => {
178
178
  }
179
179
  return out;
180
180
  };
181
- /** Where a typed entry keeps its value, by its type, as Attio names them; a manifest's `typed.paths` adds or replaces. */
181
+ /**
182
+ * Where a typed entry keeps its value, by its type, as Attio names them; a manifest's `typed.paths` adds or replaces.
183
+ * A list of paths is one text of the parts present: an address is kept in parts, and searched as one line.
184
+ */
182
185
  export const TYPED_VALUE_PATHS = {
183
186
  text: "value",
184
187
  number: "value",
@@ -196,6 +199,15 @@ export const TYPED_VALUE_PATHS = {
196
199
  "phone-number": "phone_number",
197
200
  "personal-name": "full_name",
198
201
  interaction: "interacted_at",
202
+ location: ["line_1", "line_2", "line_3", "line_4", "locality", "region", "postcode", "country_code"],
203
+ };
204
+ const typedValue = (entry, path) => {
205
+ if (typeof path === "string")
206
+ return at(entry, path);
207
+ return path
208
+ ?.map((one) => text(at(entry, one)))
209
+ .filter((part) => part !== null)
210
+ .join(", ");
199
211
  };
200
212
  /** The current entries' values: one alone is the value, several a list, none no value. */
201
213
  const typedOf = (entries, typed) => {
@@ -206,7 +218,7 @@ const typedOf = (entries, typed) => {
206
218
  return [];
207
219
  const type = text(at(entry, typed.by));
208
220
  const path = type === null ? undefined : (typed.paths?.[type] ?? TYPED_VALUE_PATHS[type]);
209
- const value = path === undefined ? null : at(entry, path);
221
+ const value = typedValue(entry, path);
210
222
  return value === null || value === undefined || value === "" ? [] : [value];
211
223
  });
212
224
  return values.length > 1 ? values : (values[0] ?? null);
@@ -0,0 +1,86 @@
1
+ import { type Sector } from "./organization-sectors.js";
2
+ /**
3
+ * The domain-list pack: lists too big, too often updated or share-alike to build into the package. Published as
4
+ * assets of a WireCat GitHub release, downloaded whole by `domain-lists update` and matched only on this computer:
5
+ * a lookup per sender would tell a third party who writes to the owner.
6
+ */
7
+ export declare const PACK_TAG = "domain-lists";
8
+ export declare const PACK_MANIFEST_URL = "https://github.com/WireCatLabs/cli-core/releases/download/domain-lists/manifest.json";
9
+ /**
10
+ * `commercial-ok`: any use, paid services included. `non-commercial`: WireCat, which is free, may use it; a paid
11
+ * service built around WireCat may not, and leaves it out with `--commercial-only`.
12
+ */
13
+ export type LicenceClass = "commercial-ok" | "non-commercial";
14
+ /**
15
+ * One list. `sector` files give an organization its sector; `freemail` files name mailbox providers, which never
16
+ * make an organization; `bad` files only say a host is known for spam, phishing or malware, and never set a sector. A line is a domain, or a domain, a tab and a sector (or a source's own
17
+ * category, for `bad`). `upstream` lists may not be redistributed: the command fetches them from their source, whole.
18
+ */
19
+ export interface PackSource {
20
+ id: string;
21
+ title: string;
22
+ signal: "sector" | "freemail" | "bad";
23
+ /** The sector or category of a line that names none. */
24
+ tag?: string;
25
+ licence: string;
26
+ licence_url: string;
27
+ class: LicenceClass;
28
+ attribution: string;
29
+ homepage: string;
30
+ /** Where the file is: the release asset, or the source itself for `upstream`. */
31
+ url: string;
32
+ /** The gzip file as published; absent for `upstream`, whose file changes at its source. */
33
+ sha256?: string;
34
+ bytes?: number;
35
+ /** The most an `upstream` file may weigh. */
36
+ max_bytes?: number;
37
+ upstream?: boolean;
38
+ /** Lines in the published file; absent for `upstream`. */
39
+ count?: number;
40
+ /** Lines per tag, for `domain-lists list`. */
41
+ tags?: Record<string, number>;
42
+ fetched_at?: string;
43
+ }
44
+ export interface PackManifest {
45
+ /** The build date, `YYYY-MM-DD`, newest wins. */
46
+ version: string;
47
+ built_at: string;
48
+ sources: PackSource[];
49
+ }
50
+ /** The pack as this computer holds it: what was installed from which manifest. */
51
+ export interface InstalledPack extends PackManifest {
52
+ installed_at: string;
53
+ commercial_only: boolean;
54
+ /** The files in place, by source id: their sha256 as checked, and their lines. */
55
+ files: Record<string, {
56
+ sha256: string;
57
+ lines: number;
58
+ bytes: number;
59
+ }>;
60
+ }
61
+ /** Shared by every CLI of the family, like the models: one pack per computer. */
62
+ export declare const domainListsDirectory: (env?: NodeJS.ProcessEnv) => string;
63
+ export declare const listFile: (directory: string, id: string) => string;
64
+ export declare const installedPack: (env?: NodeJS.ProcessEnv) => InstalledPack | undefined;
65
+ export interface DomainHits {
66
+ /** The pack's sectors of each domain looked up, in list order. */
67
+ sectors: Map<string, Sector[]>;
68
+ /** The `bad` sources that name each host exactly, as `source` or `source:category`. */
69
+ bad: Map<string, string[]>;
70
+ }
71
+ export interface LookupOptions {
72
+ env?: NodeJS.ProcessEnv;
73
+ /** Leave out `non-commercial` sources even when they are installed: a paid service sets it. */
74
+ commercialOnly?: boolean;
75
+ }
76
+ /**
77
+ * Reads each list once from disk, a megabyte at a time, keeping only the lines naming `hosts`. Exact names only: an
78
+ * entry `click.mail.brand.example` says nothing about `brand.example`. The pack's biggest list has millions of lines,
79
+ * so it is never held in memory; the caller passes the few hosts it needs.
80
+ */
81
+ export declare const lookupDomains: (hosts: ReadonlySet<string>, options?: LookupOptions) => DomainHits;
82
+ /**
83
+ * A mailbox provider from the pack's `freemail` lists (UT1 `webmail`). They are small, so they are held in memory and
84
+ * read again only when `domain-lists update` replaced the pack.
85
+ */
86
+ export declare const isPackFreeMailDomain: (domain: string, env?: NodeJS.ProcessEnv) => boolean;
@@ -0,0 +1,110 @@
1
+ import { closeSync, openSync, readFileSync, readSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { StringDecoder } from "node:string_decoder";
4
+ import { wirecatDirectory } from "../store/path.js";
5
+ import { isSector } from "./organization-sectors.js";
6
+ /**
7
+ * The domain-list pack: lists too big, too often updated or share-alike to build into the package. Published as
8
+ * assets of a WireCat GitHub release, downloaded whole by `domain-lists update` and matched only on this computer:
9
+ * a lookup per sender would tell a third party who writes to the owner.
10
+ */
11
+ export const PACK_TAG = "domain-lists";
12
+ export const PACK_MANIFEST_URL = `https://github.com/WireCatLabs/cli-core/releases/download/${PACK_TAG}/manifest.json`;
13
+ /** Shared by every CLI of the family, like the models: one pack per computer. */
14
+ export const domainListsDirectory = (env = process.env) => join(wirecatDirectory(env), "lists", "domains");
15
+ export const listFile = (directory, id) => join(directory, `${id}.txt`);
16
+ export const installedPack = (env = process.env) => {
17
+ try {
18
+ return JSON.parse(readFileSync(join(domainListsDirectory(env), "manifest.json"), "utf8"));
19
+ }
20
+ catch {
21
+ return undefined;
22
+ }
23
+ };
24
+ const CHUNK = 1 << 20;
25
+ /**
26
+ * Reads each list once from disk, a megabyte at a time, keeping only the lines naming `hosts`. Exact names only: an
27
+ * entry `click.mail.brand.example` says nothing about `brand.example`. The pack's biggest list has millions of lines,
28
+ * so it is never held in memory; the caller passes the few hosts it needs.
29
+ */
30
+ export const lookupDomains = (hosts, options = {}) => {
31
+ const hits = { sectors: new Map(), bad: new Map() };
32
+ const pack = installedPack(options.env);
33
+ if (pack === undefined || hosts.size === 0)
34
+ return hits;
35
+ const directory = domainListsDirectory(options.env);
36
+ for (const source of pack.sources) {
37
+ if (pack.files[source.id] === undefined || source.signal === "freemail")
38
+ continue;
39
+ if (options.commercialOnly && source.class !== "commercial-ok")
40
+ continue;
41
+ scanLines(listFile(directory, source.id), (line) => {
42
+ const tab = line.indexOf("\t");
43
+ const host = tab === -1 ? line : line.slice(0, tab);
44
+ if (!hosts.has(host))
45
+ return;
46
+ const tag = tab === -1 ? source.tag : line.slice(tab + 1);
47
+ if (source.signal === "bad") {
48
+ const name = tag === undefined ? source.id : `${source.id}:${tag}`;
49
+ hits.bad.set(host, [...(hits.bad.get(host) ?? []), name]);
50
+ }
51
+ else if (tag !== undefined && isSector(tag))
52
+ hits.sectors.set(host, [...(hits.sectors.get(host) ?? []), tag]);
53
+ });
54
+ }
55
+ return hits;
56
+ };
57
+ let freeMail;
58
+ const manifestStamp = (env) => {
59
+ try {
60
+ return statSync(join(domainListsDirectory(env), "manifest.json")).mtimeMs;
61
+ }
62
+ catch {
63
+ return 0;
64
+ }
65
+ };
66
+ /**
67
+ * A mailbox provider from the pack's `freemail` lists (UT1 `webmail`). They are small, so they are held in memory and
68
+ * read again only when `domain-lists update` replaced the pack.
69
+ */
70
+ export const isPackFreeMailDomain = (domain, env) => {
71
+ const stamp = manifestStamp(env);
72
+ if (freeMail?.stamp !== stamp) {
73
+ const set = new Set();
74
+ const pack = installedPack(env);
75
+ for (const source of pack?.sources ?? [])
76
+ if (source.signal === "freemail" && pack?.files[source.id] !== undefined)
77
+ scanLines(listFile(domainListsDirectory(env), source.id), (line) => set.add(line.split("\t")[0] ?? line));
78
+ freeMail = { set, stamp };
79
+ }
80
+ return freeMail.set.has(domain);
81
+ };
82
+ const scanLines = (path, line) => {
83
+ let descriptor;
84
+ try {
85
+ descriptor = openSync(path, "r");
86
+ }
87
+ catch {
88
+ return;
89
+ }
90
+ try {
91
+ const buffer = Buffer.allocUnsafe(CHUNK);
92
+ const text = new StringDecoder("utf8");
93
+ let rest = "";
94
+ for (;;) {
95
+ const read = readSync(descriptor, buffer, 0, CHUNK, null);
96
+ if (read === 0)
97
+ break;
98
+ const lines = (rest + text.write(buffer.subarray(0, read))).split("\n");
99
+ rest = lines.pop() ?? "";
100
+ for (const one of lines)
101
+ if (one !== "")
102
+ line(one);
103
+ }
104
+ if (rest !== "")
105
+ line(rest);
106
+ }
107
+ finally {
108
+ closeSync(descriptor);
109
+ }
110
+ };