@wirecat/cli-core 0.684.0 → 0.686.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.
- package/CHANGELOG.md +75 -0
- package/dist/cli/bot/api-http.d.ts +10 -2
- package/dist/cli/bot/api-http.js +50 -45
- package/dist/cli/context.d.ts +6 -1
- package/dist/cli/context.js +16 -2
- package/dist/cli/documents/testing/index.d.ts +1 -1
- package/dist/cli/documents/testing/index.js +1 -1
- package/dist/cli/documents/testing/source-contract.d.ts +34 -1
- package/dist/cli/documents/testing/source-contract.js +153 -1
- package/dist/cli/documents/testing/source.d.ts +2 -0
- package/dist/cli/documents/testing/source.js +8 -1
- package/dist/cli/index.d.ts +4 -2
- package/dist/cli/index.js +4 -2
- package/dist/cli/profile-token.js +13 -3
- package/dist/cli/program.js +6 -4
- package/dist/cli/service-api-manifest.d.ts +40 -0
- package/dist/cli/service-api-manifest.js +106 -0
- package/dist/cli/service-api.d.ts +29 -30
- package/dist/cli/service-api.js +133 -53
- package/dist/crm/digest.d.ts +1 -1
- package/dist/crm/digest.js +9 -1
- package/dist/crm/testing/index.d.ts +1 -1
- package/dist/crm/testing/source-contract.d.ts +26 -1
- package/dist/crm/testing/source-contract.js +102 -0
- package/dist/crm/testing/source.d.ts +2 -0
- package/dist/crm/testing/source.js +6 -0
- package/dist/documents/model.d.ts +1 -0
- package/dist/http/link-fetch.d.ts +10 -0
- package/dist/http/link-fetch.js +28 -0
- package/dist/meetings/import.d.ts +1 -1
- package/dist/meetings/import.js +2 -0
- package/dist/meetings/index.d.ts +1 -0
- package/dist/meetings/index.js +1 -0
- package/dist/meetings/pull.d.ts +2 -0
- package/dist/meetings/pull.js +18 -0
- package/dist/meetings/search-store.d.ts +2 -0
- package/dist/meetings/search-store.js +16 -1
- package/dist/meetings/store.d.ts +3 -0
- package/dist/services/documents/ingestion.d.ts +4 -1
- package/dist/services/documents/ingestion.js +11 -0
- package/dist/services/documents/knowledge.js +18 -3
- package/dist/services/documents/ports.d.ts +2 -0
- package/dist/services/documents/sync.js +2 -0
- package/dist/services/meeting-hit-search.d.ts +2 -3
- package/dist/services/meeting-hit-search.js +2 -17
- package/dist/services/search-all-meetings.d.ts +1 -1
- package/dist/store/sqlite/deals.d.ts +0 -2
- package/dist/store/sqlite/deals.js +0 -1
- package/dist/store/sqlite/note-search.js +4 -3
- package/package.json +3 -3
package/dist/cli/program.js
CHANGED
|
@@ -22,7 +22,7 @@ import { commandPathOf } from "./command-contract.js";
|
|
|
22
22
|
import { enterCommandServer } from "./command-server.js";
|
|
23
23
|
import { exitCodeSet } from "./command-server-request.js";
|
|
24
24
|
import { entityRows } from "./compact.js";
|
|
25
|
-
import { outputFieldsOf, outputFor, provide } from "./context.js";
|
|
25
|
+
import { outputFieldsOf, outputFor, provide, withoutOwnPaging } from "./context.js";
|
|
26
26
|
import { refuseByCommandPermissions, refuseOfflineCommand, refuseWriteBeforeConnecting } from "./early-refusal.js";
|
|
27
27
|
import { admittedUnderLock, changesAuthorityAt, changesAuthorityNow, fetchesOnlyAt, fileOptionOf, isLogin, isStoreChange, judgedEffects, judgedTargets, storeChangeRefusal, } from "./effects.js";
|
|
28
28
|
import { itemOf, renderAnswer, snakeKeys } from "./envelope.js";
|
|
@@ -272,7 +272,8 @@ const runOnce = async (argv, definition, options) => {
|
|
|
272
272
|
runCommand: (words, given) => run(words, definition, given),
|
|
273
273
|
discoveryAvailability: (info) => {
|
|
274
274
|
const inspected = info.path.reduce((parent, word) => parent?.commands.find((one) => one.name() === word), program);
|
|
275
|
-
const
|
|
275
|
+
const shown = inspected ?? program;
|
|
276
|
+
const flags = withoutOwnPaging(shown, shown.optsWithGlobals());
|
|
276
277
|
const env = options.env ?? process.env;
|
|
277
278
|
if (!flags.profile && !env[envName(definition.app, "PROFILE")])
|
|
278
279
|
return undefined;
|
|
@@ -308,6 +309,7 @@ const runOnce = async (argv, definition, options) => {
|
|
|
308
309
|
provide(program, environment);
|
|
309
310
|
program.hook("preAction", async (_root, action) => {
|
|
310
311
|
const flags = action.optsWithGlobals();
|
|
312
|
+
const own = withoutOwnPaging(action, flags);
|
|
311
313
|
const commandEnv = options.env ?? process.env;
|
|
312
314
|
const argvLog = commandEnv[envName(definition.app, "TEST_ARGV_LOG")];
|
|
313
315
|
if (argvLog)
|
|
@@ -412,7 +414,7 @@ const runOnce = async (argv, definition, options) => {
|
|
|
412
414
|
process.on("SIGINT", sigint).on("SIGTERM", sigterm);
|
|
413
415
|
const target = options.relayed || options.agent || flags.dryRun
|
|
414
416
|
? undefined
|
|
415
|
-
: relayTarget(definition.app, action, flags, () => (definition.configuration ?? settingsFor(definition.app)).resolveSettings(
|
|
417
|
+
: relayTarget(definition.app, action, flags, () => (definition.configuration ?? settingsFor(definition.app)).resolveSettings(own, {
|
|
416
418
|
env: commandEnv,
|
|
417
419
|
needsProfile: false,
|
|
418
420
|
readOnly: true,
|
|
@@ -461,7 +463,7 @@ const runOnce = async (argv, definition, options) => {
|
|
|
461
463
|
throw control.failure();
|
|
462
464
|
}
|
|
463
465
|
if (flags.dryRun && !localPreview) {
|
|
464
|
-
const resolved = (definition.configuration ?? settingsFor(definition.app)).resolveSettings(
|
|
466
|
+
const resolved = (definition.configuration ?? settingsFor(definition.app)).resolveSettings(own, {
|
|
465
467
|
kind: path[0] === "bot" ? "bot" : "personal",
|
|
466
468
|
env: options.env ?? process.env,
|
|
467
469
|
readOnly: true,
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { ApiServer, ManifestOperation, Pagination, SecurityRequirement, SecurityScheme } from "@wirecat/cli-base/codegen";
|
|
2
|
+
import type { ApiCommandInput } from "./bot/api.js";
|
|
3
|
+
/** What `generate` writes into a CLI's `generated/manifest.ts`: `import * as manifest from "./generated/manifest.js"`. */
|
|
4
|
+
export interface ServiceApiManifest {
|
|
5
|
+
operations: readonly ManifestOperation[];
|
|
6
|
+
servers?: readonly ApiServer[];
|
|
7
|
+
securitySchemes?: Readonly<Record<string, SecurityScheme>>;
|
|
8
|
+
security?: readonly SecurityRequirement[];
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* The first server the spec names. A variable is filled with its default only when its `enum` lists the choices: a
|
|
12
|
+
* free one (`{subdomain}`) names the owner's own host, which the default would send the token past.
|
|
13
|
+
*/
|
|
14
|
+
export declare const manifestBaseUrl: (manifest: ServiceApiManifest, given?: string) => string;
|
|
15
|
+
type Auth = {
|
|
16
|
+
name: string;
|
|
17
|
+
value: (token: string) => string;
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* The header that carries the sign-in for one operation, from the first scheme of its requirements the api can send;
|
|
21
|
+
* `undefined` for one that needs none (`security: []`, or only `{}`). A manifest without schemes signs in with a bearer
|
|
22
|
+
* token, as most services do. An optional sign-in (`[{}, { oauth: [] }]`) still sends the token.
|
|
23
|
+
*/
|
|
24
|
+
export declare const authHeader: (manifest: ServiceApiManifest, operation: ManifestOperation) => Auth | undefined;
|
|
25
|
+
export declare const parameterValue: (input: ApiCommandInput, parameter: {
|
|
26
|
+
in: "query" | "body";
|
|
27
|
+
name: string;
|
|
28
|
+
}) => unknown;
|
|
29
|
+
/** One page's items, and how to ask for the next: new flags, the next page's whole URL, or `undefined` at the end. */
|
|
30
|
+
export interface PageStep {
|
|
31
|
+
items: readonly unknown[];
|
|
32
|
+
next?: {
|
|
33
|
+
input: ApiCommandInput;
|
|
34
|
+
} | {
|
|
35
|
+
url: string;
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/** Reads one answer by the manifest's pagination: where its items are and what the next request is. */
|
|
39
|
+
export declare const nextPage: (pagination: Pagination, input: ApiCommandInput, answer: unknown) => PageStep;
|
|
40
|
+
export {};
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { CliError } from "@wirecat/cli-base";
|
|
2
|
+
import { apiJson, parseApiJson } from "./bot/api-input.js";
|
|
3
|
+
/**
|
|
4
|
+
* The first server the spec names. A variable is filled with its default only when its `enum` lists the choices: a
|
|
5
|
+
* free one (`{subdomain}`) names the owner's own host, which the default would send the token past.
|
|
6
|
+
*/
|
|
7
|
+
export const manifestBaseUrl = (manifest, given) => {
|
|
8
|
+
const server = manifest.servers?.[0];
|
|
9
|
+
if (given === undefined && !server)
|
|
10
|
+
throw new CliError("configuration_error", "the manifest names no server; give the api a baseUrl");
|
|
11
|
+
const url = given ??
|
|
12
|
+
server.url.replace(/\{([^}]+)\}/g, (_, name) => {
|
|
13
|
+
const variable = server?.variables?.[name];
|
|
14
|
+
if (variable?.default === undefined || !variable.enum?.includes(variable.default))
|
|
15
|
+
throw new CliError("configuration_error", `the server's {${name}} is the owner's own; give the api a baseUrl`);
|
|
16
|
+
return variable.default;
|
|
17
|
+
});
|
|
18
|
+
if (!/^https:\/\//.test(url))
|
|
19
|
+
throw new CliError("configuration_error", `the api's server ${url} is not https`);
|
|
20
|
+
return url;
|
|
21
|
+
};
|
|
22
|
+
const BEARER = { name: "authorization", value: (token) => `Bearer ${token}` };
|
|
23
|
+
/** The header one scheme signs in with; `undefined` for one the api cannot send (basic, a key in the query). */
|
|
24
|
+
const headerOf = (scheme) => {
|
|
25
|
+
if (scheme.type === "apiKey")
|
|
26
|
+
return scheme.in === "header" && scheme.name
|
|
27
|
+
? { name: scheme.name.toLowerCase(), value: (token) => token }
|
|
28
|
+
: undefined;
|
|
29
|
+
if (scheme.type === "http") {
|
|
30
|
+
if (!scheme.scheme || /^bearer$/i.test(scheme.scheme))
|
|
31
|
+
return BEARER;
|
|
32
|
+
return /^(basic|digest)$/i.test(scheme.scheme)
|
|
33
|
+
? undefined
|
|
34
|
+
: { name: "authorization", value: (token) => `${scheme.scheme} ${token}` };
|
|
35
|
+
}
|
|
36
|
+
return scheme.type === "oauth2" || scheme.type === "openIdConnect" ? BEARER : undefined;
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* The header that carries the sign-in for one operation, from the first scheme of its requirements the api can send;
|
|
40
|
+
* `undefined` for one that needs none (`security: []`, or only `{}`). A manifest without schemes signs in with a bearer
|
|
41
|
+
* token, as most services do. An optional sign-in (`[{}, { oauth: [] }]`) still sends the token.
|
|
42
|
+
*/
|
|
43
|
+
export const authHeader = (manifest, operation) => {
|
|
44
|
+
const requirements = operation.security ?? manifest.security;
|
|
45
|
+
if (requirements?.every((one) => Object.keys(one).length === 0))
|
|
46
|
+
return undefined;
|
|
47
|
+
if (!manifest.securitySchemes)
|
|
48
|
+
return BEARER;
|
|
49
|
+
const names = (requirements ?? []).flatMap((one) => Object.keys(one));
|
|
50
|
+
for (const name of names) {
|
|
51
|
+
const scheme = manifest.securitySchemes[name];
|
|
52
|
+
const auth = scheme && headerOf(scheme);
|
|
53
|
+
if (auth)
|
|
54
|
+
return auth;
|
|
55
|
+
}
|
|
56
|
+
if (names.length === 0)
|
|
57
|
+
return BEARER;
|
|
58
|
+
throw new CliError("configuration_error", `${operation.command} signs in by ${names.join(" or ")}, which the api cannot send`);
|
|
59
|
+
};
|
|
60
|
+
const at = (value, path) => path
|
|
61
|
+
.split(".")
|
|
62
|
+
.reduce((inner, key) => (inner && typeof inner === "object" ? inner[key] : undefined), value);
|
|
63
|
+
const numberOf = (value) => {
|
|
64
|
+
const number = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number(String(value));
|
|
65
|
+
return Number.isFinite(number) ? number : undefined;
|
|
66
|
+
};
|
|
67
|
+
export const parameterValue = (input, parameter) => parameter.in === "query"
|
|
68
|
+
? input.query[parameter.name]
|
|
69
|
+
: input.body === undefined
|
|
70
|
+
? undefined
|
|
71
|
+
: parseApiJson(input.body)?.[parameter.name];
|
|
72
|
+
const withValue = (input, parameter, value) => {
|
|
73
|
+
if (parameter.in === "query")
|
|
74
|
+
return { ...input, query: { ...input.query, [parameter.name]: String(value) } };
|
|
75
|
+
const body = input.body === undefined ? {} : parseApiJson(input.body);
|
|
76
|
+
return { ...input, body: apiJson({ ...body, [parameter.name]: value }) };
|
|
77
|
+
};
|
|
78
|
+
/** Reads one answer by the manifest's pagination: where its items are and what the next request is. */
|
|
79
|
+
export const nextPage = (pagination, input, answer) => {
|
|
80
|
+
const listed = pagination.items === undefined ? [answer] : at(answer, pagination.items);
|
|
81
|
+
const items = Array.isArray(listed) ? listed : [];
|
|
82
|
+
switch (pagination.style) {
|
|
83
|
+
case "cursor": {
|
|
84
|
+
const cursor = at(answer, pagination.next);
|
|
85
|
+
const more = pagination.hasMore === undefined || at(answer, pagination.hasMore) !== false;
|
|
86
|
+
return more && typeof cursor === "string" && cursor !== ""
|
|
87
|
+
? { items, next: { input: withValue(input, pagination.cursor, cursor) } }
|
|
88
|
+
: { items };
|
|
89
|
+
}
|
|
90
|
+
case "offset":
|
|
91
|
+
case "page": {
|
|
92
|
+
const parameter = pagination.style === "offset" ? pagination.offset : pagination.page;
|
|
93
|
+
const total = pagination.total === undefined ? undefined : numberOf(at(answer, pagination.total));
|
|
94
|
+
const current = numberOf(parameterValue(input, parameter)) ?? (pagination.style === "offset" ? 0 : 1);
|
|
95
|
+
const next = pagination.style === "offset" ? current + items.length : current + 1;
|
|
96
|
+
// A short page is not the last: a service may cap the page below the limit asked for. Only a total or an
|
|
97
|
+
// empty page ends it.
|
|
98
|
+
const last = items.length === 0 || (total !== undefined && pagination.style === "offset" && next >= total);
|
|
99
|
+
return last ? { items } : { items, next: { input: withValue(input, parameter, next) } };
|
|
100
|
+
}
|
|
101
|
+
case "link": {
|
|
102
|
+
const url = at(answer, pagination.next);
|
|
103
|
+
return typeof url === "string" && url !== "" ? { items, next: { url } } : { items };
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
};
|
|
@@ -5,40 +5,37 @@ import { Command } from "commander";
|
|
|
5
5
|
import type * as v from "valibot";
|
|
6
6
|
import type { AppIdentity } from "../ports/app.js";
|
|
7
7
|
import type { Level, PermissionKey } from "../sends/permissions.js";
|
|
8
|
+
import { type ApiCommandInput } from "./bot/api.js";
|
|
8
9
|
import type { ConditionalKey } from "./permission-keys.js";
|
|
10
|
+
import { type ServiceApiManifest } from "./service-api-manifest.js";
|
|
9
11
|
import type { Configuration } from "./settings.js";
|
|
10
|
-
/**
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
*/
|
|
14
|
-
|
|
15
|
-
/** The
|
|
16
|
-
|
|
17
|
-
/** Body fields that delete when `true`, as `in_trash` or `archived`. */
|
|
18
|
-
deletingFields?: readonly string[];
|
|
12
|
+
/** A key a call's body implies in a way no flag names, as notion's `agent-batch` with an action `delete`. */
|
|
13
|
+
export interface BodyPermission {
|
|
14
|
+
key: PermissionKey;
|
|
15
|
+
/** When it applies, in a few words, for `--dry-run` and discovery. */
|
|
16
|
+
when: string;
|
|
17
|
+
/** The body parsed by lossless-json: a number is a `LosslessNumber`. */
|
|
18
|
+
applies: (body: unknown) => boolean;
|
|
19
19
|
}
|
|
20
20
|
/** What both halves of the group, the permissions and the command, are built from. */
|
|
21
21
|
export interface ServiceApiPermissionsInput {
|
|
22
|
-
|
|
23
|
-
/**
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* Operations, by command name, whose body can delete in a way no top-level field names: `agent-batch` with an action
|
|
27
|
-
* `delete`. The body comes parsed by lossless-json, so a number is a `LosslessNumber`.
|
|
28
|
-
*/
|
|
29
|
-
deletingBodies?: Readonly<Record<string, (body: unknown) => boolean>>;
|
|
22
|
+
manifest: ServiceApiManifest;
|
|
23
|
+
/** By command name: keys beside the manifest's `permissions`, for a body the generator cannot read. */
|
|
24
|
+
bodyPermissions?: Readonly<Record<string, readonly BodyPermission[]>>;
|
|
30
25
|
}
|
|
31
26
|
export interface ServiceApiOptions extends ServiceApiPermissionsInput {
|
|
32
27
|
app: AppIdentity;
|
|
33
28
|
configuration: Configuration;
|
|
34
29
|
/** The service's name in messages: "Notion". */
|
|
35
30
|
service: string;
|
|
36
|
-
/**
|
|
37
|
-
baseUrl
|
|
31
|
+
/** In place of the manifest's first server. */
|
|
32
|
+
baseUrl?: string;
|
|
38
33
|
/** The host-checked fetch with the CLI's pace and its retry of reads (cli-base `retrying` over `hostFetch`). */
|
|
39
34
|
fetch: (command: Command) => FetchLike;
|
|
40
|
-
/** The
|
|
41
|
-
|
|
35
|
+
/** The profile's token, sent in the header the operation's security scheme names. Read before any guard asks. */
|
|
36
|
+
token: (command: Command) => string | Promise<string>;
|
|
37
|
+
/** Headers beside the sign-in, such as the API version. */
|
|
38
|
+
headers?: (command: Command, operation: ManifestOperation) => Record<string, string>;
|
|
42
39
|
/** Loaded only once an operation is about to check its input: a large spec is megabytes of code. */
|
|
43
40
|
schemas: () => Promise<Readonly<Record<string, v.GenericSchema>>>;
|
|
44
41
|
/** Loaded only by `api show`. */
|
|
@@ -52,23 +49,25 @@ export interface ServiceApiOptions extends ServiceApiPermissionsInput {
|
|
|
52
49
|
shown?: Readonly<Record<string, unknown>>;
|
|
53
50
|
failure?: (status: number, answer: unknown, operation: ManifestOperation) => CliError | undefined;
|
|
54
51
|
}
|
|
55
|
-
/**
|
|
56
|
-
export declare const
|
|
52
|
+
/** The keys one call checks beside `api.<operation>`: the manifest's that apply, and the CLI's from the body. */
|
|
53
|
+
export declare const serviceApiKeys: (input: ServiceApiPermissionsInput, operation: ManifestOperation, call: ApiCommandInput) => PermissionKey[];
|
|
57
54
|
/**
|
|
58
|
-
* The group's half of `commandPermissions`: the
|
|
59
|
-
* and
|
|
60
|
-
* over the other. `ask` stops at a terminal; over MCP it goes ahead, so `deny` is what stops an
|
|
55
|
+
* The group's half of `commandPermissions`: the keys each operation also checks, for `--dry-run` and discovery, and
|
|
56
|
+
* `ask` for each of them and for every operation that deletes. A CLI with keys of its own merges each field with its
|
|
57
|
+
* own, never spreads one over the other. `ask` stops at a terminal; over MCP it goes ahead, so `deny` is what stops an
|
|
58
|
+
* agent.
|
|
61
59
|
*/
|
|
62
60
|
export declare const serviceApiPermissions: (input: ServiceApiPermissionsInput) => {
|
|
63
61
|
alsoChecks: (path: readonly string[]) => readonly (PermissionKey | ConditionalKey)[];
|
|
64
62
|
defaults: Readonly<Record<PermissionKey, Level>>;
|
|
65
|
-
/** The
|
|
63
|
+
/** The keys, so a profile may name one that no command path spells. */
|
|
66
64
|
extra: readonly PermissionKey[];
|
|
67
65
|
};
|
|
68
66
|
/**
|
|
69
67
|
* The raw API of an OpenAPI service as one group: `api list` and `api show` without a request, and one command per
|
|
70
|
-
* operation
|
|
71
|
-
*
|
|
72
|
-
*
|
|
68
|
+
* operation of the generated manifest, sent to its server with the sign-in its security scheme names. Every write goes
|
|
69
|
+
* through the profile's guard on `api.<operation>` and on each manifest key that applies to the call (`files.delete`
|
|
70
|
+
* when `permanently` is true); the journal records that it ran, never its body. A read that pages takes `--all`. There
|
|
71
|
+
* is no free-form `api call`: a request is always one operation of the spec, with its own key (SEC-196).
|
|
73
72
|
*/
|
|
74
73
|
export declare const serviceApiCommand: (options: ServiceApiOptions) => Command;
|
package/dist/cli/service-api.js
CHANGED
|
@@ -8,45 +8,61 @@ import { levelFor } from "../sends/permissions.js";
|
|
|
8
8
|
import { newOperationId } from "../sends/send-id.js";
|
|
9
9
|
import { refusedPlace } from "../sends/upload.js";
|
|
10
10
|
import { generatedApiCommand } from "./bot/api.js";
|
|
11
|
-
import {
|
|
11
|
+
import { httpApiRequest, httpApiSend } from "./bot/api-http.js";
|
|
12
12
|
import { checkApiBody, checkApiParameter, parseApiJson, readApiBody } 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";
|
|
16
16
|
import { queryTerms, termField, withQuery } from "./list-query.js";
|
|
17
17
|
import { terminalAsker } from "./messenger/ask.js";
|
|
18
|
+
import { authHeader, manifestBaseUrl, nextPage, parameterValue, } from "./service-api-manifest.js";
|
|
19
|
+
/** How far `--all` reads: a service that never stops paging must not run a command forever. */
|
|
20
|
+
const MOST_PAGES = 500;
|
|
18
21
|
const isObject = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
19
22
|
const keyOf = (operation) => `api.${operation.command}`;
|
|
20
|
-
const
|
|
23
|
+
const permissionsOf = (operation) => operation.permissions ?? [];
|
|
21
24
|
/** By its method too: an override may have marked a DELETE as a plain write. */
|
|
22
25
|
const destructive = (operation) => operation.effect === "destructive" || (operation.binding.kind === "http" && operation.binding.method === "DELETE");
|
|
23
|
-
const
|
|
24
|
-
/**
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
26
|
+
const flagsOf = ({ body = [], query = [] }) => [...body, ...query];
|
|
27
|
+
/** A flag counts unless it is absent or plainly false: a service may read `1` or `True` as true. */
|
|
28
|
+
const set = (value) => value !== undefined && value !== null && value !== false && value !== "false";
|
|
29
|
+
/** Whether a manifest key applies to this call: always, or when one of its flags is set. */
|
|
30
|
+
const applies = (permission, body, input) => flagsOf(permission).length === 0 ||
|
|
31
|
+
(permission.body ?? []).some((field) => isObject(body) && set(body[field])) ||
|
|
32
|
+
(permission.query ?? []).some((name) => set(input.query[name]));
|
|
33
|
+
/** The keys one call checks beside `api.<operation>`: the manifest's that apply, and the CLI's from the body. */
|
|
34
|
+
export const serviceApiKeys = (input, operation, call) => {
|
|
35
|
+
const body = call.body?.trim() ? parseApiJson(call.body) : undefined;
|
|
36
|
+
const keys = [
|
|
37
|
+
...permissionsOf(operation)
|
|
38
|
+
.filter((permission) => applies(permission, body, call))
|
|
39
|
+
.map(({ key }) => key),
|
|
40
|
+
...(input.bodyPermissions?.[operation.command] ?? []).filter((one) => one.applies(body)).map(({ key }) => key),
|
|
41
|
+
];
|
|
42
|
+
return [...new Set(keys)];
|
|
43
|
+
};
|
|
28
44
|
/**
|
|
29
|
-
* The group's half of `commandPermissions`: the
|
|
30
|
-
* and
|
|
31
|
-
* over the other. `ask` stops at a terminal; over MCP it goes ahead, so `deny` is what stops an
|
|
45
|
+
* The group's half of `commandPermissions`: the keys each operation also checks, for `--dry-run` and discovery, and
|
|
46
|
+
* `ask` for each of them and for every operation that deletes. A CLI with keys of its own merges each field with its
|
|
47
|
+
* own, never spreads one over the other. `ask` stops at a terminal; over MCP it goes ahead, so `deny` is what stops an
|
|
48
|
+
* agent.
|
|
32
49
|
*/
|
|
33
50
|
export const serviceApiPermissions = (input) => {
|
|
34
|
-
const
|
|
35
|
-
const
|
|
51
|
+
const checks = new Map();
|
|
52
|
+
for (const operation of input.manifest.operations)
|
|
53
|
+
checks.set(operation.command, [
|
|
54
|
+
...permissionsOf(operation).map((permission) => flagsOf(permission).length === 0
|
|
55
|
+
? permission.key
|
|
56
|
+
: { key: permission.key, when: `with ${flagsOf(permission).join(" or ")} set` }),
|
|
57
|
+
...(input.bodyPermissions?.[operation.command] ?? []).map(({ key, when }) => ({ key, when })),
|
|
58
|
+
]);
|
|
59
|
+
const keys = [...new Set([...checks.values()].flat().map((one) => (typeof one === "string" ? one : one.key)))];
|
|
36
60
|
return {
|
|
37
|
-
extra:
|
|
38
|
-
alsoChecks: (path) =>
|
|
39
|
-
if (path[0] !== "api" || path.length !== 2)
|
|
40
|
-
return [];
|
|
41
|
-
const operation = deleting.find((one) => one.command === path[1]);
|
|
42
|
-
const key = operation && deleteKeyOf(input, operation);
|
|
43
|
-
if (!operation || !key)
|
|
44
|
-
return [];
|
|
45
|
-
return destructive(operation) ? [key] : [{ key, when: "the body deletes, trashes or archives" }];
|
|
46
|
-
},
|
|
61
|
+
extra: keys,
|
|
62
|
+
alsoChecks: (path) => (path[0] === "api" && path.length === 2 ? (checks.get(path[1] ?? "") ?? []) : []),
|
|
47
63
|
defaults: {
|
|
48
|
-
...Object.fromEntries(
|
|
49
|
-
...Object.fromEntries(input.operations.filter(destructive).map((operation) => [keyOf(operation), "ask"])),
|
|
64
|
+
...Object.fromEntries(keys.map((key) => [key, "ask"])),
|
|
65
|
+
...Object.fromEntries(input.manifest.operations.filter(destructive).map((operation) => [keyOf(operation), "ask"])),
|
|
50
66
|
},
|
|
51
67
|
};
|
|
52
68
|
};
|
|
@@ -67,46 +83,72 @@ const API_QUERY = {
|
|
|
67
83
|
};
|
|
68
84
|
/**
|
|
69
85
|
* The raw API of an OpenAPI service as one group: `api list` and `api show` without a request, and one command per
|
|
70
|
-
* operation
|
|
71
|
-
*
|
|
72
|
-
*
|
|
86
|
+
* operation of the generated manifest, sent to its server with the sign-in its security scheme names. Every write goes
|
|
87
|
+
* through the profile's guard on `api.<operation>` and on each manifest key that applies to the call (`files.delete`
|
|
88
|
+
* when `permanently` is true); the journal records that it ran, never its body. A read that pages takes `--all`. There
|
|
89
|
+
* is no free-form `api call`: a request is always one operation of the spec, with its own key (SEC-196).
|
|
73
90
|
*/
|
|
74
91
|
export const serviceApiCommand = (options) => {
|
|
75
|
-
const { app, configuration } = options;
|
|
92
|
+
const { app, configuration, manifest } = options;
|
|
76
93
|
// A credential-returning operation needs a bot's `--store-token`; a service CLI signs in through `session` instead.
|
|
77
|
-
const operations =
|
|
94
|
+
const operations = manifest.operations.filter((operation) => !operation.response?.sensitive);
|
|
95
|
+
const baseUrl = manifestBaseUrl(manifest, options.baseUrl);
|
|
96
|
+
const base = new URL(baseUrl);
|
|
78
97
|
const own = serviceApiPermissions(options);
|
|
79
98
|
// The group's own levels hold even where the CLI's permissions left them out.
|
|
80
99
|
const defaults = { ...own.defaults, ...configuration.permissions?.defaults };
|
|
81
|
-
const
|
|
82
|
-
if (
|
|
83
|
-
throw new CliError("configuration_error", `${
|
|
100
|
+
const unguarded = operations.filter((operation) => destructive(operation) && !permissionsOf(operation).some(({ key }) => key.endsWith(".delete")));
|
|
101
|
+
if (unguarded.length > 0)
|
|
102
|
+
throw new CliError("configuration_error", `${unguarded.map(({ command }) => command).join(", ")} can delete, but the manifest gives no delete key: generate with \`permissions\``);
|
|
103
|
+
const named = new Set(manifest.operations.flatMap((operation) => permissionsOf(operation).map(({ key }) => key)));
|
|
104
|
+
const unnamed = Object.values(options.bodyPermissions ?? {})
|
|
105
|
+
.flat()
|
|
106
|
+
.filter(({ key }) => !named.has(key));
|
|
107
|
+
if (unnamed.length > 0)
|
|
108
|
+
throw new CliError("configuration_error", `bodyPermissions name ${unnamed.map(({ key }) => key).join(", ")}, which the manifest does not: the keys come from \`permissions\``);
|
|
84
109
|
let schemas;
|
|
85
110
|
const loaded = () => {
|
|
86
111
|
if (!schemas)
|
|
87
112
|
throw new CliError("configuration_error", "the api schemas were not loaded before the command ran");
|
|
88
113
|
return schemas;
|
|
89
114
|
};
|
|
115
|
+
const send = httpApiSend({
|
|
116
|
+
service: options.service,
|
|
117
|
+
fetch: options.fetch,
|
|
118
|
+
...(options.failure ? { failure: options.failure } : {}),
|
|
119
|
+
});
|
|
90
120
|
const operationOf = (name) => {
|
|
91
121
|
const found = operations.find((operation) => operation.command === name || operation.id === name);
|
|
92
122
|
if (found)
|
|
93
123
|
return found;
|
|
94
124
|
const left = options.excluded?.find((one) => one.id === name) ??
|
|
95
|
-
(
|
|
125
|
+
(manifest.operations.some((one) => one.command === name || one.id === name)
|
|
96
126
|
? { reason: "it returns a credential, which is never printed" }
|
|
97
127
|
: undefined);
|
|
98
128
|
throw new CliError("not_found", left
|
|
99
129
|
? `${name} is not offered: ${left.reason}`
|
|
100
130
|
: `no ${options.service} API operation ${name}; see ${app.command} api list`);
|
|
101
131
|
};
|
|
102
|
-
const
|
|
132
|
+
const signed = async (command, operation, request) => {
|
|
133
|
+
const auth = authHeader(manifest, operation);
|
|
134
|
+
if (auth)
|
|
135
|
+
request.headers.set(auth.name, auth.value(await options.token(command)));
|
|
136
|
+
// A redirect to another host drops only the standard sign-in headers; an API key header would go along.
|
|
137
|
+
if (auth && auth.name !== "authorization")
|
|
138
|
+
request.redirect = "manual";
|
|
139
|
+
for (const [name, value] of Object.entries(options.headers?.(command, operation) ?? {}))
|
|
140
|
+
request.headers.set(name, value);
|
|
141
|
+
return request;
|
|
142
|
+
};
|
|
143
|
+
const write = async (command, operation, extra, request) => {
|
|
103
144
|
const { settings, env, renderer, run } = baseContext(command, configuration.resolveSettings);
|
|
104
145
|
const operationId = newOperationId();
|
|
105
146
|
const guard = keyedGuard((ask) => guardFor(app, { ...settings, sendsPerHour: Number.MAX_SAFE_INTEGER, permissionDefaults: defaults }, renderer.warn, env, ask), terminalAsker(command), (key) => levelFor(settings.permissions, key, defaults).level, extra);
|
|
106
|
-
const
|
|
107
|
-
guard.refuse(
|
|
147
|
+
const guarded = { chatId: null, kind: "edit", key: keyOf(operation), operationId };
|
|
148
|
+
guard.refuse(guarded);
|
|
108
149
|
try {
|
|
109
|
-
|
|
150
|
+
const result = await guardedWrite(guard, guarded, () => run(() => send(command, operation, request)));
|
|
151
|
+
return { operation_id: operationId, result };
|
|
110
152
|
}
|
|
111
153
|
catch (error) {
|
|
112
154
|
if (isCliError(error) && error.code === "outcome_unknown")
|
|
@@ -114,15 +156,43 @@ export const serviceApiCommand = (options) => {
|
|
|
114
156
|
throw error;
|
|
115
157
|
}
|
|
116
158
|
};
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
159
|
+
/** Every page, in one run; a next page on another host is never sent the sign-in. */
|
|
160
|
+
const allPages = async (command, operation, input) => {
|
|
161
|
+
const pagination = operation.pagination;
|
|
162
|
+
// Services number pages from 0 or from 1, and the manifest does not say which.
|
|
163
|
+
if (pagination.style === "page" && parameterValue(input, pagination.page) === undefined)
|
|
164
|
+
throw new CliError("validation_error", `--all on ${operation.command} needs the first page: give --${pagination.page.name} 0 or 1, as ${options.service} counts`);
|
|
165
|
+
const items = [];
|
|
166
|
+
const asked = new Set();
|
|
167
|
+
let call = input;
|
|
168
|
+
let url;
|
|
169
|
+
await baseContext(command, configuration.resolveSettings).run(async () => {
|
|
170
|
+
for (let page = 0;; page++) {
|
|
171
|
+
if (page >= MOST_PAGES)
|
|
172
|
+
throw new CliError("validation_error", `${operation.command} has more than ${MOST_PAGES} pages; narrow it with its own flags, or page it yourself`);
|
|
173
|
+
const request = await signed(command, operation, httpApiRequest(operation, call, baseUrl));
|
|
174
|
+
if (url !== undefined)
|
|
175
|
+
request.url = url;
|
|
176
|
+
const key = `${request.url.href} ${request.body ?? ""}`;
|
|
177
|
+
if (asked.has(key))
|
|
178
|
+
throw new CliError("invalid_response", `${options.service} gave the same next page twice; nothing more read`);
|
|
179
|
+
asked.add(key);
|
|
180
|
+
const step = nextPage(pagination, call, await send(command, operation, request));
|
|
181
|
+
for (const item of step.items)
|
|
182
|
+
items.push(item);
|
|
183
|
+
if (!step.next)
|
|
184
|
+
return;
|
|
185
|
+
if ("url" in step.next) {
|
|
186
|
+
url = new URL(step.next.url, request.url);
|
|
187
|
+
if (url.origin !== base.origin)
|
|
188
|
+
throw new CliError("invalid_response", `${options.service} pointed the next page at another host`);
|
|
189
|
+
}
|
|
190
|
+
else
|
|
191
|
+
call = step.next.input;
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
renderAnswer(command, outputFor(command), listOf(`api ${operation.command}`, { items, limit: items.length, has_more: false }));
|
|
195
|
+
};
|
|
126
196
|
const generated = generatedApiCommand({
|
|
127
197
|
operations,
|
|
128
198
|
checkParameter: (name, schema, raw) => checkApiParameter(name, schema, raw, loaded()),
|
|
@@ -135,12 +205,18 @@ export const serviceApiCommand = (options) => {
|
|
|
135
205
|
}
|
|
136
206
|
return readApiBody(body);
|
|
137
207
|
},
|
|
138
|
-
execute: (command, operation, input) => {
|
|
139
|
-
const
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
208
|
+
execute: async (command, operation, input) => {
|
|
209
|
+
const extra = serviceApiKeys(options, operation, input);
|
|
210
|
+
if (operation.pagination && command.opts().all === true) {
|
|
211
|
+
if (operation.effect !== "read" || extra.length > 0)
|
|
212
|
+
throw new CliError("validation_error", `--all reads only; this call of ${operation.command} is guarded by ${extra.join(", ") || "its write"}`);
|
|
213
|
+
return allPages(command, operation, input);
|
|
214
|
+
}
|
|
215
|
+
const request = await signed(command, operation, httpApiRequest(operation, input, baseUrl));
|
|
216
|
+
const answer = operation.effect === "read" && extra.length === 0
|
|
217
|
+
? await baseContext(command, configuration.resolveSettings).run(() => send(command, operation, request))
|
|
218
|
+
: await write(command, operation, extra, request);
|
|
219
|
+
renderAnswer(command, outputFor(command), itemOf(answer));
|
|
144
220
|
},
|
|
145
221
|
});
|
|
146
222
|
const list = withQuery(annotate(new Command("list"), {
|
|
@@ -174,7 +250,11 @@ export const serviceApiCommand = (options) => {
|
|
|
174
250
|
const load = async () => {
|
|
175
251
|
schemas ??= await options.schemas();
|
|
176
252
|
};
|
|
177
|
-
for (const child of generated.commands)
|
|
253
|
+
for (const child of generated.commands) {
|
|
254
|
+
const operation = operations.find((one) => one.command === child.name());
|
|
255
|
+
if (operation?.pagination && !operation.parameters.some(({ name }) => name === "all"))
|
|
256
|
+
child.option("--all", "read every page, as the API pages it");
|
|
178
257
|
group.addCommand(child.hook("preAction", load));
|
|
258
|
+
}
|
|
179
259
|
return group;
|
|
180
260
|
};
|
package/dist/crm/digest.d.ts
CHANGED
|
@@ -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;
|
package/dist/crm/digest.js
CHANGED
|
@@ -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
|
|
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);
|
|
@@ -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";
|