@wirecat/cli-core 0.695.0 → 0.697.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 (66) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/dist/cli/bot/api-http.d.ts +1 -1
  3. package/dist/cli/bot/api-http.js +77 -5
  4. package/dist/cli/bot/api-input.d.ts +5 -0
  5. package/dist/cli/bot/api-input.js +55 -0
  6. package/dist/cli/bot/api.d.ts +2 -0
  7. package/dist/cli/bot/api.js +22 -4
  8. package/dist/cli/index.d.ts +3 -3
  9. package/dist/cli/index.js +3 -3
  10. package/dist/cli/messenger/store-maintenance-command.js +3 -2
  11. package/dist/cli/profile-token.d.ts +10 -2
  12. package/dist/cli/profile-token.js +19 -3
  13. package/dist/cli/service-api-call.d.ts +2 -0
  14. package/dist/cli/service-api-call.js +1 -1
  15. package/dist/cli/service-api-manifest.d.ts +9 -3
  16. package/dist/cli/service-api-manifest.js +70 -11
  17. package/dist/cli/service-api.d.ts +5 -0
  18. package/dist/cli/service-api.js +13 -6
  19. package/dist/cli/token-session.d.ts +27 -1
  20. package/dist/cli/token-session.js +52 -13
  21. package/dist/crm/manifest/manifest.d.ts +2 -0
  22. package/dist/crm/manifest/manifest.js +2 -1
  23. package/dist/crm/manifest/map.d.ts +2 -1
  24. package/dist/crm/manifest/map.js +2 -1
  25. package/dist/domain/tracker.d.ts +100 -0
  26. package/dist/domain/tracker.js +28 -0
  27. package/dist/errors/reasons.js +1 -0
  28. package/dist/manifest/index.d.ts +9 -5
  29. package/dist/manifest/index.js +18 -7
  30. package/dist/store/exports.d.ts +1 -0
  31. package/dist/store/exports.js +1 -0
  32. package/dist/store/recover.js +2 -0
  33. package/dist/store/sqlite/account-purge.js +1 -0
  34. package/dist/store/sqlite/crm-files.d.ts +3 -0
  35. package/dist/store/sqlite/crm-files.js +2 -2
  36. package/dist/store/sqlite/manifest.js +2 -0
  37. package/dist/store/sqlite/migrations.generated.js +17 -0
  38. package/dist/store/sqlite/schema.d.ts +252 -0
  39. package/dist/store/sqlite/schema.js +28 -0
  40. package/dist/store/sqlite/tracker.d.ts +82 -0
  41. package/dist/store/sqlite/tracker.js +210 -0
  42. package/dist/store/store.d.ts +3 -0
  43. package/dist/store/store.js +5 -0
  44. package/dist/tracker/cli/index.d.ts +24 -0
  45. package/dist/tracker/cli/index.js +279 -0
  46. package/dist/tracker/index.d.ts +8 -0
  47. package/dist/tracker/index.js +7 -0
  48. package/dist/tracker/manifest/manifest.d.ts +76 -0
  49. package/dist/tracker/manifest/manifest.js +139 -0
  50. package/dist/tracker/manifest/map.d.ts +10 -0
  51. package/dist/tracker/manifest/map.js +86 -0
  52. package/dist/tracker/manifest/source.d.ts +18 -0
  53. package/dist/tracker/manifest/source.js +174 -0
  54. package/dist/tracker/source.d.ts +55 -0
  55. package/dist/tracker/source.js +1 -0
  56. package/dist/tracker/sync.d.ts +60 -0
  57. package/dist/tracker/sync.js +254 -0
  58. package/dist/tracker/tasks.d.ts +18 -0
  59. package/dist/tracker/tasks.js +29 -0
  60. package/dist/tracker/testing/index.d.ts +2 -0
  61. package/dist/tracker/testing/index.js +2 -0
  62. package/dist/tracker/testing/source-contract.d.ts +46 -0
  63. package/dist/tracker/testing/source-contract.js +246 -0
  64. package/dist/tracker/testing/source.d.ts +31 -0
  65. package/dist/tracker/testing/source.js +141 -0
  66. package/package.json +12 -4
@@ -2,30 +2,83 @@ import { CliError } from "@wirecat/cli-base";
2
2
  import { signInPlace, signInRequirements, } from "@wirecat/cli-base/codegen";
3
3
  import { apiJson, parseApiJson } from "./bot/api-input.js";
4
4
  /**
5
- * The first server the spec names. A variable is filled with its default only when its `enum` lists the choices: a
6
- * free one (`{subdomain}`) names the owner's own host, which the default would send the token past.
5
+ * The first server the spec names. A variable is filled from `variables` first, such as the site a profile signed in
6
+ * to; else with its default, only when its `enum` lists the choices: a free one (`{site}`) names the owner's own host,
7
+ * which the default would send the token past.
7
8
  */
8
- export const manifestBaseUrl = (manifest, given) => {
9
+ export const manifestBaseUrl = (manifest, given, variables = {}) => {
9
10
  const server = manifest.servers?.[0];
10
11
  if (given === undefined && !server)
11
12
  throw new CliError("configuration_error", "the manifest names no server; give the api a baseUrl");
12
13
  const url = given ??
13
14
  server.url.replace(/\{([^}]+)\}/g, (_, name) => {
15
+ const value = variables[name];
16
+ // Only a variable that is the whole host takes a host with a port or a path: `{subdomain}.example.com` given
17
+ // `evil.test/x` would send the token to evil.test.
18
+ if (value !== undefined)
19
+ return wholeHost(server, name) ? serverValue(name, value) : labelValue(name, value);
14
20
  const variable = server?.variables?.[name];
15
21
  if (variable?.default === undefined || !variable.enum?.includes(variable.default))
16
- throw new CliError("configuration_error", `the server's {${name}} is the owner's own; give the api a baseUrl`);
22
+ throw new CliError("configuration_error", `the server's {${name}} is the owner's own; sign in with session start --${name}, or give the api a baseUrl`);
17
23
  return variable.default;
18
24
  });
19
25
  if (!/^https:\/\//.test(url))
20
26
  throw new CliError("configuration_error", `the api's server ${url} is not https`);
27
+ if (!URL.canParse(url) || new URL(url).username || new URL(url).password)
28
+ throw new CliError("configuration_error", `the api's server ${url} is not a URL without a user name`);
21
29
  return url;
22
30
  };
31
+ /**
32
+ * The site an owner types, as a server's free variable takes it: a host with a port or a path if any, from
33
+ * `blog.example.com` or `https://blog.example.com/`. Only https: an `http://` address is refused, not rewritten.
34
+ */
35
+ export const siteValue = (raw) => {
36
+ const text = raw
37
+ .trim()
38
+ .replace(/^https:\/\//i, "")
39
+ .replace(/\/+$/, "");
40
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(text))
41
+ throw new CliError("validation_error", `--site takes an https address or a host, not ${JSON.stringify(raw)}`);
42
+ const [host = "", ...path] = serverValue("site", text, "validation_error").split("/");
43
+ const site = [host.toLowerCase(), ...path].join("/");
44
+ // What a URL makes of it must be what was typed: `0x7f.1`, `a.test/..` or a port past 65535 lands elsewhere.
45
+ const url = URL.canParse(`https://${site}`) ? new URL(`https://${site}`) : undefined;
46
+ if (!url ||
47
+ url.host !== site.split("/")[0] ||
48
+ url.pathname.replace(/\/$/, "") !== site.slice(site.split("/")[0]?.length))
49
+ throw new CliError("validation_error", `--site ${JSON.stringify(raw)} is not a plain https address`);
50
+ return site;
51
+ };
52
+ const wholeHost = (server, name) => server.url === `https://{${name}}` || server.url.startsWith(`https://{${name}}/`);
53
+ const labelValue = (name, value) => {
54
+ if (!/^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?$/.test(value))
55
+ throw new CliError("configuration_error", `{${name}} ${JSON.stringify(value)} is not one name without dots`);
56
+ return value;
57
+ };
58
+ // A value only names a place: a user name, query or fragment in it would change where the token goes, or add to it.
59
+ const serverValue = (name, value, code = "configuration_error") => {
60
+ if (!/^[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(:\d+)?(\/[A-Za-z0-9._~%-]+)*$/.test(value))
61
+ throw new CliError(code, `{${name}} ${JSON.stringify(value)} is not a host, with a port or a path if any`);
62
+ return value;
63
+ };
23
64
  /**
24
65
  * Where the sign-in goes for one operation: the first place its requirements' schemes name that a token can be sent
25
66
  * to, a header before a key in the query, which a proxy or a server log could keep. `undefined` for a call that needs
26
67
  * none: its security, its own or else the document's, is absent, as in a spec that says nothing about sign-in, or
27
68
  * empty (`[]`, `[{}]`). An optional sign-in (`[{}, { oauth: [] }]`) still sends the token.
28
69
  */
70
+ // cli-base reads no basic scheme yet; the token of one is `<user>:<password>`, as `session start --login` keeps it.
71
+ const basicPlace = (scheme) => scheme.type === "http" && /^basic$/i.test(scheme.scheme ?? "")
72
+ ? {
73
+ in: "header",
74
+ name: "authorization",
75
+ value: (token) => {
76
+ if (!token.includes(":"))
77
+ throw new CliError("authentication_error", "this service signs in with a user name and a password: run session start --login <name>");
78
+ return `Basic ${Buffer.from(token).toString("base64")}`;
79
+ },
80
+ }
81
+ : undefined;
29
82
  const authOf = (manifest, operation) => {
30
83
  const requirements = signInRequirements(operation, manifest.security);
31
84
  if (!requirements)
@@ -33,10 +86,13 @@ const authOf = (manifest, operation) => {
33
86
  const names = requirements.flatMap((one) => Object.keys(one));
34
87
  const sendable = names.flatMap((name) => {
35
88
  const scheme = manifest.securitySchemes?.[name];
36
- const place = scheme && signInPlace(scheme);
37
- return place ? [place] : [];
89
+ const place = scheme && (signInPlace(scheme) ?? basicPlace(scheme));
90
+ return place ? [{ place, basic: !signInPlace(scheme) }] : [];
38
91
  });
39
- const auth = sendable.find((one) => one.in === "header") ?? sendable[0];
92
+ // Basic only when nothing else is offered: it needs a user name a token sign-in does not keep.
93
+ const auth = (sendable.find((one) => one.place.in === "header" && !one.basic) ??
94
+ sendable.find((one) => !one.basic) ??
95
+ sendable[0])?.place;
40
96
  if (auth)
41
97
  return auth;
42
98
  throw new CliError("configuration_error", `${operation.command} signs in by ${names.join(" or ")}, which the api cannot send`);
@@ -70,14 +126,17 @@ const numberOf = (value) => {
70
126
  };
71
127
  export const parameterValue = (input, parameter) => parameter.in === "query"
72
128
  ? input.query[parameter.name]
73
- : input.body === undefined
74
- ? undefined
75
- : parseApiJson(input.body)?.[parameter.name];
129
+ : (input.fields[parameter.name] ??
130
+ (input.body === undefined
131
+ ? undefined
132
+ : parseApiJson(input.body)?.[parameter.name]));
76
133
  export const withValue = (input, parameter, value) => {
77
134
  if (parameter.in === "query")
78
135
  return { ...input, query: { ...input.query, [parameter.name]: String(value) } };
79
136
  const body = input.body === undefined ? {} : parseApiJson(input.body);
80
- return { ...input, body: apiJson({ ...body, [parameter.name]: value }) };
137
+ // A flag of the same name would stand over the body, and every page would ask for the first.
138
+ const { [parameter.name]: _, ...fields } = input.fields;
139
+ return { ...input, fields, body: apiJson({ ...body, [parameter.name]: value }) };
81
140
  };
82
141
  /** Reads one answer by the manifest's pagination: where its items are and what the next request is. */
83
142
  export const nextPage = (pagination, input, answer) => {
@@ -30,6 +30,11 @@ export interface ServiceApiOptions extends ServiceApiPermissionsInput {
30
30
  service: string;
31
31
  /** In place of the manifest's first server. */
32
32
  baseUrl?: string;
33
+ /**
34
+ * The values of the server's free variables for this run, such as `{ site }` from the profile's sign-in
35
+ * (`recalledSite`). Read only when a call is sent, so `api list` and `api show` work before sign-in.
36
+ */
37
+ serverVariables?: (command: Command) => Readonly<Record<string, string>>;
33
38
  /** The host-checked fetch with the CLI's pace and its retry of reads (cli-base `retrying` over `hostFetch`). */
34
39
  fetch: (command: Command) => FetchLike;
35
40
  /**
@@ -83,8 +83,12 @@ export const serviceApiPermissions = (input) => {
83
83
  };
84
84
  const rowOf = (operation) => ({
85
85
  command: operation.command,
86
- method: operation.binding.kind === "http" ? operation.binding.method : "",
87
- path: operation.binding.kind === "http" ? operation.binding.path : "",
86
+ method: operation.binding.kind === "http" ? operation.binding.method : operation.binding.kind === "graphql" ? "POST" : "",
87
+ path: operation.binding.kind === "http"
88
+ ? operation.binding.path
89
+ : operation.binding.kind === "graphql"
90
+ ? `${operation.binding.operation} ${operation.binding.field}`
91
+ : "",
88
92
  effect: operation.effect,
89
93
  summary: operation.summary ?? "",
90
94
  });
@@ -106,8 +110,10 @@ const API_QUERY = {
106
110
  export const serviceApiCommand = (options) => {
107
111
  const { app, configuration, manifest } = options;
108
112
  const { offered: operations, left } = serviceApiOperations(manifest);
109
- const baseUrl = manifestBaseUrl(manifest, options.baseUrl);
110
- const base = new URL(baseUrl);
113
+ // Without variables the server is known now, and a CLI built against a manifest it cannot reach fails at once.
114
+ if (!options.serverVariables)
115
+ manifestBaseUrl(manifest, options.baseUrl);
116
+ const baseUrlOf = (command) => manifestBaseUrl(manifest, options.baseUrl, options.serverVariables?.(command));
111
117
  const own = serviceApiPermissions(options);
112
118
  // The group's own levels hold even where the CLI's permissions left them out.
113
119
  const defaults = { ...own.defaults, ...configuration.permissions?.defaults };
@@ -172,6 +178,7 @@ export const serviceApiCommand = (options) => {
172
178
  throw new CliError("validation_error", `--all on ${operation.command} needs the first page: give --${pagination.page.name} 0 or 1, as ${options.service} counts`);
173
179
  const items = [];
174
180
  const asked = new Set();
181
+ const baseUrl = baseUrlOf(command);
175
182
  let call = input;
176
183
  let url;
177
184
  await baseContext(command, configuration.resolveSettings).run(async () => {
@@ -194,7 +201,7 @@ export const serviceApiCommand = (options) => {
194
201
  return;
195
202
  if ("url" in step.next) {
196
203
  url = new URL(step.next.url, request.url);
197
- if (url.origin !== base.origin)
204
+ if (url.origin !== new URL(baseUrl).origin)
198
205
  throw new CliError("invalid_response", `${options.service} pointed the next page at another host`);
199
206
  }
200
207
  else
@@ -230,7 +237,7 @@ export const serviceApiCommand = (options) => {
230
237
  throw new CliError("validation_error", `--all reads only; this call of ${operation.command} is guarded by ${extra.join(", ") || "its write"}`);
231
238
  return allPages(command, operation, input);
232
239
  }
233
- const request = await signed(command, operation, httpApiRequest(operation, input, baseUrl));
240
+ const request = await signed(command, operation, httpApiRequest(operation, input, baseUrlOf(command)));
234
241
  const answer = operation.effect === "read" && extra.length === 0
235
242
  ? await baseContext(command, configuration.resolveSettings).run(() => send(command, operation, request))
236
243
  : await write(command, operation, extra, request);
@@ -12,10 +12,28 @@ export interface TokenSessionOptions {
12
12
  * Asks the service whose the token is. `id` names the account, so one profile stays one account; `account` is what
13
13
  * `session start` and `session status --check` show.
14
14
  */
15
- verify: (command: Command, token: string, events: EventSink) => Promise<{
15
+ verify: (command: Command, token: string, events: EventSink, site: string | undefined) => Promise<{
16
16
  id: string;
17
17
  account: Readonly<Record<string, unknown>>;
18
18
  }>;
19
+ /**
20
+ * The service runs on the owner's own site, its server's `{site}`: `session start` takes `--site`, verifies the
21
+ * token there and keeps the site in the token's own entry, written and forgotten with it, so the token only ever
22
+ * goes to that site (`signedInSite`). `<PREFIX>_TOKEN` needs `<PREFIX>_TOKEN_SITE` beside it. The example is a site
23
+ * for the help, such as "blog.example.com".
24
+ */
25
+ site?: {
26
+ example: string;
27
+ };
28
+ /**
29
+ * The secret is a password for a user name, as WordPress's application passwords: `session start --login <name>`
30
+ * asks only the password hidden, and the profile keeps `<name>:<password>`, which a `basic` scheme sends.
31
+ * `page` names where the owner makes one, shown before the question. `<PREFIX>_TOKEN` then holds
32
+ * `<name>:<password>` too.
33
+ */
34
+ login?: {
35
+ page?: (site: string | undefined) => string;
36
+ };
19
37
  /** Keeps the account a profile signed in to; by default only remembers it. A CLI that refuses a taken one says so. */
20
38
  claim?: (env: NodeJS.ProcessEnv, profile: string, id: string, tokens: ProfileTokenStore) => void;
21
39
  /** What the token is, for the prompt and help: "API token" when not given. */
@@ -31,3 +49,11 @@ export declare const storageOf: (raw: string) => TokenStorage;
31
49
  * or read from stdin, checked with the service, and only then kept in the keyring or a private file.
32
50
  */
33
51
  export declare const tokenSessionCommand: (options: TokenSessionOptions) => Command;
52
+ /**
53
+ * The site this run's profile signed in to, as the `{ site }` server variable of `serviceApiCommand` (give it as is)
54
+ * and `serviceApiCall` (give it the command's). It comes from where the token does: the profile's entry, or
55
+ * `<PREFIX>_TOKEN_SITE` beside `<PREFIX>_TOKEN`; never one of each.
56
+ */
57
+ export declare const signedInSite: (app: AppIdentity, resolveSettings: TokenSessionOptions["resolveSettings"]) => ((command: Command) => {
58
+ site: string;
59
+ });
@@ -9,6 +9,7 @@ import { itemOf, listOf, renderAnswer } from "./envelope.js";
9
9
  import { profilesHere, rememberAccount } from "./messenger/accounts.js";
10
10
  import { commandWords, profileFree, refuseCommandName, rootOf } from "./profile.js";
11
11
  import { ProfileTokenStore } from "./profile-token.js";
12
+ import { siteValue } from "./service-api-manifest.js";
12
13
  export const storageOf = (raw) => {
13
14
  if (raw === "keyring" || raw === "file")
14
15
  return raw;
@@ -20,7 +21,7 @@ export const storageOf = (raw) => {
20
21
  */
21
22
  export const tokenSessionCommand = (options) => {
22
23
  const { app, service } = options;
23
- const word = options.token ?? "API token";
24
+ const word = options.token ?? (options.login ? "password" : "API token");
24
25
  const contextOf = (command) => {
25
26
  const base = baseContext(command, options.resolveSettings);
26
27
  const tokens = new ProfileTokenStore({
@@ -32,12 +33,13 @@ export const tokenSessionCommand = (options) => {
32
33
  return { ...base, profile: base.settings.profile, tokens };
33
34
  };
34
35
  const answer = (command, item) => renderAnswer(command, outputFor(command), itemOf(item));
36
+ const siteOf = (site) => (options.site ? { site: site ?? null } : {});
35
37
  const start = logsInOrOut(annotate(new Command("start"), {
36
38
  effects: FETCH,
37
39
  lifetime: "interactive",
38
40
  mcp: false,
39
41
  examples: [
40
- `${app.command} personal session start`,
42
+ `${app.command} personal session start${options.site ? ` --site ${options.site.example}` : ""}${options.login ? " --login <name>" : ""}`,
41
43
  `${app.command} personal session start --credential-storage file`,
42
44
  ],
43
45
  }))
@@ -45,19 +47,36 @@ export const tokenSessionCommand = (options) => {
45
47
  .description(`sign this profile in: the ${service} ${word} is asked hidden or read from stdin, never taken as an argument, ` +
46
48
  `checked with ${service}, and only then kept in the keyring, or in a private file` +
47
49
  (options.about ? `. ${options.about}` : ""))
48
- .option("--credential-storage <storage>", "where the token is kept: keyring, which falls back to a private file by itself, or file", storageOf, "keyring")
49
- .action(async function (args) {
50
- const { env, profile, tokens, run } = contextOf(this);
50
+ .option("--credential-storage <storage>", "where the token is kept: keyring, which falls back to a private file by itself, or file", storageOf, "keyring");
51
+ if (options.login)
52
+ start.option("--login <name>", `the ${service} user name the password belongs to`);
53
+ if (options.site)
54
+ start.option("--site <address>", `the ${service} site, as https://${options.site.example} or ${options.site.example}`);
55
+ start.action(async function (args) {
56
+ const { env, profile, tokens, run, renderer } = contextOf(this);
51
57
  refuseCommandName(profile, commandWords(rootOf(this)), app.command);
58
+ if (options.site && args.site === undefined)
59
+ throw new CliError("validation_error", `give the ${service} site: --site ${options.site.example}`);
60
+ const site = options.site && args.site !== undefined ? siteValue(args.site) : undefined;
61
+ const login = args.login?.trim();
62
+ if (options.login && !login)
63
+ throw new CliError("validation_error", `give the ${service} user name: --login <name>`);
64
+ // Basic sign-in splits at the first colon, so a colon in the name would move part of it into the password.
65
+ if (login?.includes(":"))
66
+ throw new CliError("validation_error", "a user name with a colon cannot sign in");
52
67
  refuseOffline(this, service);
68
+ const page = options.login?.page?.(site);
69
+ if (page)
70
+ renderer.note(`the ${word} of ${login}: make one at ${page}, then paste it here`);
53
71
  // A secret is never an argument: it would land in shell history and in the run record (WC-SECR-5).
54
- const token = (await readSecret(`${service} ${word}: `, secretInputOf(this))).trim();
55
- if (!token)
56
- throw new CliError("validation_error", "no token was given");
57
- const { id, account } = await run((events) => options.verify(this, token, events));
72
+ const secret = (await readSecret(`${service} ${word}: `, secretInputOf(this))).trim();
73
+ if (!secret)
74
+ throw new CliError("validation_error", `no ${word} was given`);
75
+ const token = login === undefined ? secret : `${login}:${secret}`;
76
+ const { id, account } = await run((events) => options.verify(this, token, events, site));
58
77
  (options.claim ?? ((at, name, key) => rememberAccount(app, name, key, at)))(env, profile, id, tokens);
59
- const storedIn = tokens.write(profile, token, args.credentialStorage);
60
- answer(this, { profile, state: "saved", stored_in: storedIn, verified: true, ...account });
78
+ const storedIn = tokens.write(profile, token, args.credentialStorage, site === undefined ? {} : { site });
79
+ answer(this, { profile, state: "saved", stored_in: storedIn, verified: true, ...siteOf(site), ...account });
61
80
  });
62
81
  const status = annotate(new Command("status"), {
63
82
  effects: REMOTE_READ,
@@ -70,11 +89,14 @@ export const tokenSessionCommand = (options) => {
70
89
  .action(async function (args) {
71
90
  const { profile, tokens, run } = contextOf(this);
72
91
  const saved = tokens.read(profile);
73
- const state = { profile, state: saved ? "saved" : "missing", token_from: saved?.source ?? null };
92
+ const site = options.site ? tokens.readWith(profile, SITE)?.secret : undefined;
93
+ const state = { profile, state: saved ? "saved" : "missing", token_from: saved?.source ?? null, ...siteOf(site) };
74
94
  if (!args.check || !saved)
75
95
  return answer(this, { ...state, verified: false });
96
+ if (options.site && site === undefined)
97
+ throw noSite(app, profile);
76
98
  refuseOffline(this, service);
77
- const { account } = await run((events) => options.verify(this, saved.secret, events));
99
+ const { account } = await run((events) => options.verify(this, saved.secret, events, site));
78
100
  answer(this, { ...state, verified: true, ...account });
79
101
  });
80
102
  const end = logsInOrOut(annotate(new Command("end"), {
@@ -119,3 +141,20 @@ export const tokenSessionCommand = (options) => {
119
141
  .addCommand(end)
120
142
  .addCommand(list);
121
143
  };
144
+ const SITE = "site";
145
+ const noSite = (app, profile) => new CliError("authentication_error", `profile ${profile} is not signed in to a site — run \`${app.command} ${profile} session start --site <address>\``, { reason: "session.missing" });
146
+ /**
147
+ * The site this run's profile signed in to, as the `{ site }` server variable of `serviceApiCommand` (give it as is)
148
+ * and `serviceApiCall` (give it the command's). It comes from where the token does: the profile's entry, or
149
+ * `<PREFIX>_TOKEN_SITE` beside `<PREFIX>_TOKEN`; never one of each.
150
+ */
151
+ export const signedInSite = (app, resolveSettings) => {
152
+ return (command) => {
153
+ const { env, keyring, settings } = baseContext(command, resolveSettings);
154
+ const tokens = new ProfileTokenStore({ app, env, ...(keyring ? { keyring } : {}) });
155
+ const site = tokens.readWith(settings.profile, SITE)?.secret;
156
+ if (site === undefined)
157
+ throw noSite(app, settings.profile);
158
+ return { site };
159
+ };
160
+ };
@@ -1,3 +1,4 @@
1
+ import * as v from "valibot";
1
2
  import type { ServiceApiCall } from "../../cli/service-api-call.js";
2
3
  import type { ServiceApiManifest } from "../../cli/service-api-manifest.js";
3
4
  import { type CrmKind, type CrmRecords } from "../../domain/crm.js";
@@ -188,6 +189,7 @@ export interface CrmManifestHooks {
188
189
  /** Adds or replaces source methods (`self`, `activities`, a live `list`); `base` is what the manifest built. */
189
190
  extend?: (base: CrmSource) => Partial<CrmSource>;
190
191
  }
192
+ export declare const crmRuleSchema: v.GenericSchema<CrmRule>;
191
193
  /**
192
194
  * The manifest checked against its shape and the generated API: each operation exists, a list pages or says where its
193
195
  * rows are, a change call places `{since}`, a deal or lead kind has pipelines. Every error names where it is.
@@ -6,7 +6,7 @@ import { editDistance } from "../../search/correct.js";
6
6
  import { FIELDS } from "./map.js";
7
7
  const path = v.pipe(v.string(), v.regex(/^[^.\s]+(\.[^.\s]+)*$/, "a dotted path such as properties.name"));
8
8
  const paths = v.pipe(v.array(path), v.minLength(1));
9
- const rule = v.union([
9
+ export const crmRuleSchema = v.union([
10
10
  path,
11
11
  v.strictObject({ first: paths }),
12
12
  v.strictObject({ join: paths }),
@@ -18,6 +18,7 @@ const rule = v.union([
18
18
  v.strictObject({ value: v.unknown() }),
19
19
  v.function(),
20
20
  ], "a path, one of first, join, all, path, each, value, or a function");
21
+ const rule = crmRuleSchema;
21
22
  const call = v.strictObject({
22
23
  operation: v.pipe(v.string(), v.minLength(1)),
23
24
  path: v.optional(v.record(v.string(), v.string())),
@@ -1,5 +1,5 @@
1
1
  import type { CrmField, CrmKind, CrmRecords } from "../../domain/crm.js";
2
- import { type CrmRaw, id, text } from "../values.js";
2
+ import { type CrmRaw, id, number, text } from "../values.js";
3
3
  import type { CrmRule } from "./manifest.js";
4
4
  /** The service sent nothing at this path: the field is left out, so the stored copy keeps what it held. */
5
5
  export declare const MISSING: unique symbol;
@@ -18,6 +18,7 @@ declare const CONVERT: {
18
18
  epoch: typeof epochOf;
19
19
  day: typeof dayOf;
20
20
  bool: typeof yes;
21
+ number: typeof number;
21
22
  texts: (value: unknown) => string[];
22
23
  ids: (value: unknown) => string[];
23
24
  status: (value: unknown) => string | null;
@@ -1,5 +1,5 @@
1
1
  import { DEAL_STATUSES } from "../../domain/deals.js";
2
- import { amountOf, crmValuesOf, epoch, fullName, id, isRaw, text } from "../values.js";
2
+ import { amountOf, crmValuesOf, epoch, fullName, id, isRaw, number, text } from "../values.js";
3
3
  /** The service sent nothing at this path: the field is left out, so the stored copy keeps what it held. */
4
4
  export const MISSING = Symbol("missing");
5
5
  /** A dotted path; a number steps into a list (`results.0.id`), and `.` is the value itself. */
@@ -86,6 +86,7 @@ const CONVERT = {
86
86
  epoch: epochOf,
87
87
  day: dayOf,
88
88
  bool: yes,
89
+ number,
89
90
  texts: (value) => unique(listOf(value).map(text)),
90
91
  ids: (value) => linksOf(value).map(({ externalId }) => externalId),
91
92
  status: (value) => {
@@ -0,0 +1,100 @@
1
+ /**
2
+ * What an issue tracker holds that the store copies (Linear, and any tracker after it): its teams, users, workflow
3
+ * states, labels, projects, issues and the comments on them. Teams, users, states and labels come before the
4
+ * projects and issues that name them.
5
+ */
6
+ export declare const TRACKER_KINDS: readonly ["team", "user", "state", "label", "project", "issue", "comment"];
7
+ export type TrackerKind = (typeof TRACKER_KINDS)[number];
8
+ /** Where an issue in a state stands in its work, whatever the team named the state. */
9
+ export declare const STATE_TYPES: readonly ["triage", "backlog", "unstarted", "started", "completed", "canceled"];
10
+ export type StateType = (typeof STATE_TYPES)[number];
11
+ /**
12
+ * Every record has the tracker's id. A field left out means the tracker did not say, and the store keeps what it
13
+ * held; `null` means the tracker said there is none. Times are epoch milliseconds.
14
+ */
15
+ interface TrackerRecord {
16
+ externalId: string;
17
+ createdAt?: number | null;
18
+ updatedAt?: number | null;
19
+ /** The tracker archived it: it still exists, and a read that asks for archived rows lists it. */
20
+ archivedAt?: number | null;
21
+ }
22
+ export interface TrackerTeam extends TrackerRecord {
23
+ name: string;
24
+ /** The short key an issue's key starts with: `ENG`. */
25
+ key?: string | null;
26
+ }
27
+ export interface TrackerUser extends TrackerRecord {
28
+ name: string;
29
+ /** How the store joins the user to a person it already knows: by this exact address. */
30
+ email?: string | null;
31
+ active?: boolean | null;
32
+ }
33
+ export interface TrackerState extends TrackerRecord {
34
+ name: string;
35
+ type: StateType;
36
+ team?: string | null;
37
+ /** Any numbers; the order they give is the board's. */
38
+ position?: number | null;
39
+ }
40
+ export interface TrackerLabel extends TrackerRecord {
41
+ name: string;
42
+ team?: string | null;
43
+ }
44
+ export interface TrackerProject extends TrackerRecord {
45
+ name: string;
46
+ description?: string | null;
47
+ /** The tracker's own word for where the project stands: `planned`, `started`. */
48
+ status?: string | null;
49
+ /** A user's id. */
50
+ lead?: string | null;
51
+ teams?: string[];
52
+ /** `YYYY-MM-DD`. */
53
+ targetDate?: string | null;
54
+ url?: string | null;
55
+ }
56
+ export interface TrackerIssue extends TrackerRecord {
57
+ title: string;
58
+ /** The readable key people say: `ENG-12`. */
59
+ key?: string | null;
60
+ description?: string | null;
61
+ state?: string | null;
62
+ team?: string | null;
63
+ project?: string | null;
64
+ /** Users' ids. */
65
+ assignee?: string | null;
66
+ creator?: string | null;
67
+ labels?: string[];
68
+ /** The issue this one is a part of. */
69
+ parent?: string | null;
70
+ /** 0 is none, then 1 the most urgent: Linear's scale, which a tracker with another one maps onto. */
71
+ priority?: number | null;
72
+ /** `YYYY-MM-DD`. */
73
+ dueDate?: string | null;
74
+ completedAt?: number | null;
75
+ canceledAt?: number | null;
76
+ url?: string | null;
77
+ }
78
+ export interface TrackerComment extends TrackerRecord {
79
+ issue: string;
80
+ body: string;
81
+ /** A user's id; none when an integration wrote it. */
82
+ author?: string | null;
83
+ url?: string | null;
84
+ }
85
+ export interface TrackerRecords {
86
+ team: TrackerTeam;
87
+ user: TrackerUser;
88
+ state: TrackerState;
89
+ label: TrackerLabel;
90
+ project: TrackerProject;
91
+ issue: TrackerIssue;
92
+ comment: TrackerComment;
93
+ }
94
+ /** The record's title in lists and search: an issue's title, a comment's start, anything else's name. */
95
+ export declare const trackerTitleOf: <K extends TrackerKind>(kind: K, record: TrackerRecords[K]) => string;
96
+ /** The record's text that search reads beside its title: a description or a comment's body. */
97
+ export declare const trackerBodyOf: <K extends TrackerKind>(kind: K, record: TrackerRecords[K]) => string | null | undefined;
98
+ /** The record its row hangs under: a comment's issue, a state's or a label's team. */
99
+ export declare const trackerParentOf: <K extends TrackerKind>(kind: K, record: TrackerRecords[K]) => string | null | undefined;
100
+ export {};
@@ -0,0 +1,28 @@
1
+ /**
2
+ * What an issue tracker holds that the store copies (Linear, and any tracker after it): its teams, users, workflow
3
+ * states, labels, projects, issues and the comments on them. Teams, users, states and labels come before the
4
+ * projects and issues that name them.
5
+ */
6
+ export const TRACKER_KINDS = ["team", "user", "state", "label", "project", "issue", "comment"];
7
+ /** Where an issue in a state stands in its work, whatever the team named the state. */
8
+ export const STATE_TYPES = ["triage", "backlog", "unstarted", "started", "completed", "canceled"];
9
+ /** The record's title in lists and search: an issue's title, a comment's start, anything else's name. */
10
+ export const trackerTitleOf = (kind, record) => kind === "issue"
11
+ ? record.title
12
+ : kind === "comment"
13
+ ? record.body.split("\n")[0]?.slice(0, 120) || "(comment)"
14
+ : record.name;
15
+ /** The record's text that search reads beside its title: a description or a comment's body. */
16
+ export const trackerBodyOf = (kind, record) => kind === "comment"
17
+ ? record.body
18
+ : kind === "issue" || kind === "project"
19
+ ? record.description
20
+ : null;
21
+ /** The record its row hangs under: a comment's issue, a state's or a label's team. */
22
+ export const trackerParentOf = (kind, record) => kind === "comment"
23
+ ? record.issue
24
+ : kind === "state" || kind === "label"
25
+ ? record.team
26
+ : kind === "issue"
27
+ ? record.team
28
+ : null;
@@ -487,6 +487,7 @@ const OTHERS = [
487
487
  validation("crm.owner-unknown", "owner: names no CRM user: me without a known sign-in user, or not a user id"),
488
488
  validation("crm.write-unsupported", "the CRM does not take this write, or does not recognise a repeated one"),
489
489
  validation("crm.unlisted-held", "a list of every id would mark most of a kind deleted; nothing was, until --rescan"),
490
+ validation("tracker.unlisted-held", "a tracker's id list would mark too much deleted, or the sign-in read only part; nothing was, until --rescan"),
490
491
  validation("crm.narrowing-held", "the default scope mine would mark most of a kind's stored rows deleted; none is, until the owner sets the scope"),
491
492
  validation("crm.unassigned-dropped", "the CRM does not let this sign-in choose a user in unassigned; that user's deals are not copied"),
492
493
  validation("crm.not-reported", "the CRM did not list users or departments; what they would say is unknown, nothing withdrawn"),
@@ -1,5 +1,6 @@
1
1
  import type { CrmManifest } from "../crm/manifest/manifest.js";
2
2
  import type { OAuthProvider } from "../oauth/provider.js";
3
+ import type { TrackerManifest } from "../tracker/manifest/manifest.js";
3
4
  /**
4
5
  * The operation that answers whose the token is, and where its answer holds the account's id (and a name to show):
5
6
  * `{ operation: "getV2Self", id: "workspace_id", name: "workspace_name" }`. `session start` checks a token with it.
@@ -29,7 +30,7 @@ export type CliAuth = {
29
30
  /** The provider sends a new refresh token on each refresh; the spec cannot say so. */
30
31
  rotating?: boolean;
31
32
  };
32
- export declare const CLI_CATEGORIES: readonly ["messenger", "mail", "notes", "files", "meetings", "calendar", "crm", "other"];
33
+ export declare const CLI_CATEGORIES: readonly ["messenger", "mail", "notes", "files", "meetings", "calendar", "crm", "tracker", "other"];
33
34
  export type CliCategory = (typeof CLI_CATEGORIES)[number];
34
35
  /** One file, `wirecat.config.ts`, that `new --from-config` builds a CLI from. */
35
36
  export interface CliConfig {
@@ -47,21 +48,24 @@ export interface CliConfig {
47
48
  };
48
49
  /** `from`: the https URL the description is published at. */
49
50
  spec: {
50
- kind: "openapi" | "swagger";
51
+ kind: "openapi" | "swagger" | "graphql";
51
52
  from: string;
52
53
  };
53
54
  auth: CliAuth;
54
55
  /** cli-template's `--category`; `other` is any API outside them. */
55
56
  category: CliCategory;
56
- /** The CRM source; checked against the generated API by `parseCrmManifest` once the api group exists. */
57
- source?: CrmManifest;
57
+ /**
58
+ * A crm or tracker CLI's source; checked against the generated API by `parseCrmManifest` or `parseTrackerManifest`
59
+ * once the api group exists.
60
+ */
61
+ source?: CrmManifest | TrackerManifest;
58
62
  /** The module of named hooks, relative to the config: `./src/hooks.ts`. */
59
63
  hooks?: string;
60
64
  }
61
65
  /** Types the config in the editor; it returns what it is given. */
62
66
  export declare const defineCli: (config: CliConfig) => CliConfig;
63
67
  /**
64
- * The config checked against its shape; every error names where it is. A CRM CLI needs its source. `source` comes back
68
+ * The config checked against its shape; every error names where it is. A crm or tracker CLI needs its source. `source` comes back
65
69
  * unchecked: `parseCrmManifest` checks it against the generated API.
66
70
  */
67
71
  export declare const parseCliConfig: (input: unknown) => CliConfig;