@wirecat/cli-core 0.691.0 → 0.693.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 +62 -0
- package/README.md +141 -203
- package/dist/calendar/prepare.d.ts +11 -0
- package/dist/cli/bot/api-http.d.ts +4 -1
- package/dist/cli/bot/api-http.js +17 -4
- package/dist/cli/bot/api-input.d.ts +4 -0
- package/dist/cli/bot/api-input.js +9 -0
- package/dist/cli/bot/api.d.ts +4 -0
- package/dist/cli/bot/api.js +16 -2
- package/dist/cli/documents/folders.js +1 -1
- package/dist/cli/documents/search.js +3 -3
- package/dist/cli/documents/words.d.ts +2 -0
- package/dist/cli/documents/words.js +1 -0
- package/dist/cli/envelope.d.ts +22 -0
- package/dist/cli/index.d.ts +7 -4
- package/dist/cli/index.js +7 -4
- package/dist/cli/oauth-session.d.ts +60 -0
- package/dist/cli/oauth-session.js +224 -0
- package/dist/cli/service-api-call.d.ts +27 -0
- package/dist/cli/service-api-call.js +32 -0
- package/dist/cli/service-api-manifest.d.ts +14 -10
- package/dist/cli/service-api-manifest.js +38 -34
- package/dist/cli/service-api.d.ts +17 -2
- package/dist/cli/service-api.js +42 -24
- package/dist/cli/token-session.d.ts +33 -0
- package/dist/cli/token-session.js +121 -0
- package/dist/crm/index.d.ts +3 -0
- package/dist/crm/index.js +3 -0
- package/dist/crm/manifest/manifest.d.ts +195 -0
- package/dist/crm/manifest/manifest.js +161 -0
- package/dist/crm/manifest/map.d.ts +58 -0
- package/dist/crm/manifest/map.js +240 -0
- package/dist/crm/manifest/paths.d.ts +11 -0
- package/dist/crm/manifest/paths.js +161 -0
- package/dist/crm/manifest/source.d.ts +18 -0
- package/dist/crm/manifest/source.js +385 -0
- package/dist/errors/reasons.js +1 -0
- package/dist/manifest/index.d.ts +53 -0
- package/dist/manifest/index.js +61 -0
- package/package.json +8 -3
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
import { CliError, isCliError } from "@wirecat/cli-base";
|
|
2
|
+
import { nextPage, parameterValue, withValue } from "../../cli/service-api-manifest.js";
|
|
3
|
+
import { id, isRaw, number, rawsOf, text } from "../values.js";
|
|
4
|
+
import { parseCrmManifest, } from "./manifest.js";
|
|
5
|
+
import { at, convert, evaluate, MISSING, mapFields, mapRecord, selectedOf } from "./map.js";
|
|
6
|
+
const OVERLAP_MS = 10 * 60_000;
|
|
7
|
+
/** How far one read of every page goes: a service that never stops paging must not hold a sync forever. */
|
|
8
|
+
const MOST_PAGES = 500;
|
|
9
|
+
const DROP = Symbol("drop");
|
|
10
|
+
/** Fills `"{since}"`, `"{select}"` and `"{id}"`; an empty select drops the parameter it stands for. */
|
|
11
|
+
const fill = (value, slots) => {
|
|
12
|
+
if (value === "{since}")
|
|
13
|
+
return slots.since ?? DROP;
|
|
14
|
+
if (value === "{select}")
|
|
15
|
+
return slots.select?.length ? [...slots.select] : DROP;
|
|
16
|
+
if (value === "{id}")
|
|
17
|
+
return slots.id ?? DROP;
|
|
18
|
+
if (Array.isArray(value))
|
|
19
|
+
return value.map((one) => fill(one, slots)).filter((one) => one !== DROP);
|
|
20
|
+
if (isRaw(value))
|
|
21
|
+
return Object.fromEntries(Object.entries(value).flatMap(([key, one]) => {
|
|
22
|
+
const filled = fill(one, slots);
|
|
23
|
+
return filled === DROP ? [] : [[key, filled]];
|
|
24
|
+
}));
|
|
25
|
+
return value;
|
|
26
|
+
};
|
|
27
|
+
const inputOf = (call, slots) => {
|
|
28
|
+
const path = fill(call.path ?? {}, slots);
|
|
29
|
+
const query = fill(call.query ?? {}, slots);
|
|
30
|
+
const body = call.body === undefined ? undefined : fill(call.body, slots);
|
|
31
|
+
return {
|
|
32
|
+
path: Object.fromEntries(Object.entries(path).map(([key, one]) => [key, String(one)])),
|
|
33
|
+
query: Object.fromEntries(Object.entries(query).map(([key, one]) => [key, Array.isArray(one) ? one.join(",") : String(one)])),
|
|
34
|
+
headers: {},
|
|
35
|
+
fields: {},
|
|
36
|
+
...(body === undefined || body === DROP ? {} : { body: JSON.stringify(body) }),
|
|
37
|
+
};
|
|
38
|
+
};
|
|
39
|
+
const SINCE = {
|
|
40
|
+
ms: (ms) => String(ms),
|
|
41
|
+
seconds: (ms) => String(Math.floor(ms / 1000)),
|
|
42
|
+
iso: (ms) => new Date(ms).toISOString(),
|
|
43
|
+
datetime: (ms) => new Date(ms).toISOString().slice(0, 19).replace("T", " "),
|
|
44
|
+
};
|
|
45
|
+
const pageParameter = (pagination) => pagination.style === "cursor"
|
|
46
|
+
? pagination.cursor
|
|
47
|
+
: pagination.style === "offset"
|
|
48
|
+
? pagination.offset
|
|
49
|
+
: pagination.style === "page"
|
|
50
|
+
? pagination.page
|
|
51
|
+
: undefined;
|
|
52
|
+
/** `<the service's page token>@<when the round started>`: a round spread over runs ends with its first page's time. */
|
|
53
|
+
const pageOf = (page, now) => {
|
|
54
|
+
const cut = page?.lastIndexOf("@") ?? -1;
|
|
55
|
+
const started = Number(page?.slice(cut + 1));
|
|
56
|
+
if (page === undefined || cut < 0 || !Number.isSafeInteger(started))
|
|
57
|
+
return { token: undefined, started: now };
|
|
58
|
+
return { token: page.slice(0, cut) || undefined, started };
|
|
59
|
+
};
|
|
60
|
+
const unseen = (error) => isCliError(error) && (error.code === "not_found" || error.code === "permission_error");
|
|
61
|
+
/**
|
|
62
|
+
* A `CrmSource` read from a manifest: every kind listed and read for changes by the operations it names, paged by each
|
|
63
|
+
* operation's own `pagination`, each row mapped onto the shared schema. Deletions are found by a pass over every id.
|
|
64
|
+
* What the manifest cannot say comes from `hooks`.
|
|
65
|
+
*/
|
|
66
|
+
export const crmSourceFromManifest = (input, options) => {
|
|
67
|
+
const manifest = parseCrmManifest(input, options.api);
|
|
68
|
+
const now = options.now ?? Date.now;
|
|
69
|
+
const hooks = options.hooks ?? {};
|
|
70
|
+
const overlap = manifest.overlapMs ?? OVERLAP_MS;
|
|
71
|
+
const operations = new Map(options.api.operations.map((one) => [one.id, one]));
|
|
72
|
+
/** The engine paid for a call's first request; each further one is spent from the run's budget. */
|
|
73
|
+
const metered = (context) => {
|
|
74
|
+
let paid = false;
|
|
75
|
+
return (operation, request) => {
|
|
76
|
+
if (paid)
|
|
77
|
+
context?.spend();
|
|
78
|
+
paid = true;
|
|
79
|
+
return options.call(operation, request);
|
|
80
|
+
};
|
|
81
|
+
};
|
|
82
|
+
/** One page: its rows, and the service's token for the next one, absent on the last. */
|
|
83
|
+
const readPage = async (call, slots, token, send) => {
|
|
84
|
+
const pagination = operations.get(call.operation)?.pagination;
|
|
85
|
+
const parameter = pagination && pageParameter(pagination);
|
|
86
|
+
let request = inputOf(call, slots);
|
|
87
|
+
if (token !== undefined && parameter)
|
|
88
|
+
request = withValue(request, parameter, pagination.style === "cursor" ? token : Number(token));
|
|
89
|
+
const answer = await send(call.operation, request);
|
|
90
|
+
if (!pagination || !parameter) {
|
|
91
|
+
const listed = call.items === undefined ? answer : at(answer, call.items);
|
|
92
|
+
return { rows: rawsOf(listed), next: undefined };
|
|
93
|
+
}
|
|
94
|
+
const step = nextPage(pagination, request, answer);
|
|
95
|
+
const rows = rawsOf(call.items === undefined ? step.items : at(answer, call.items));
|
|
96
|
+
const value = step.next && "input" in step.next ? parameterValue(step.next.input, parameter) : undefined;
|
|
97
|
+
return { rows, next: value === undefined || value === null ? undefined : String(value) };
|
|
98
|
+
};
|
|
99
|
+
const readAll = async (call, send) => {
|
|
100
|
+
const rows = [];
|
|
101
|
+
let token;
|
|
102
|
+
for (let read = 0; read < MOST_PAGES; read += 1) {
|
|
103
|
+
const page = await readPage(call, {}, token, send);
|
|
104
|
+
for (const row of page.rows)
|
|
105
|
+
rows.push(row);
|
|
106
|
+
if (page.next === undefined)
|
|
107
|
+
return rows;
|
|
108
|
+
token = page.next;
|
|
109
|
+
}
|
|
110
|
+
throw new CliError("provider_error", `${call.operation} gave more than ${MOST_PAGES} pages`);
|
|
111
|
+
};
|
|
112
|
+
const entityOf = (kind) => {
|
|
113
|
+
const found = manifest.entities[kind];
|
|
114
|
+
if (!found)
|
|
115
|
+
throw new CliError("configuration_error", `the source manifest has no ${kind}`);
|
|
116
|
+
return found;
|
|
117
|
+
};
|
|
118
|
+
const loaded = new Map();
|
|
119
|
+
/** A sign-in without the right to read field definitions still syncs its records, with no custom values. */
|
|
120
|
+
const fieldsOf = (kind, send, context) => {
|
|
121
|
+
const spec = manifest.fields?.[kind];
|
|
122
|
+
if (!spec)
|
|
123
|
+
return Promise.resolve([]);
|
|
124
|
+
let found = loaded.get(kind);
|
|
125
|
+
if (!found) {
|
|
126
|
+
found = readAll(spec.call, send)
|
|
127
|
+
.then((rows) => rows.flatMap((raw) => toField(spec, raw) ?? []))
|
|
128
|
+
.catch((error) => {
|
|
129
|
+
if (isCliError(error) && error.code === "permission_error") {
|
|
130
|
+
gap(context, {
|
|
131
|
+
kind,
|
|
132
|
+
message: `the service refused the ${kind} field definitions: no custom values are read`,
|
|
133
|
+
});
|
|
134
|
+
return [];
|
|
135
|
+
}
|
|
136
|
+
loaded.delete(kind);
|
|
137
|
+
throw error;
|
|
138
|
+
});
|
|
139
|
+
loaded.set(kind, found);
|
|
140
|
+
}
|
|
141
|
+
return found;
|
|
142
|
+
};
|
|
143
|
+
/** Each gap once per call: a round of a hundred pages would otherwise store the same gap a hundred times. */
|
|
144
|
+
const said = new WeakMap();
|
|
145
|
+
const gap = (context, one) => {
|
|
146
|
+
if (!context)
|
|
147
|
+
return;
|
|
148
|
+
const seen = said.get(context) ?? new Set();
|
|
149
|
+
said.set(context, seen);
|
|
150
|
+
const key = `${one.kind} ${one.message}`;
|
|
151
|
+
if (seen.has(key))
|
|
152
|
+
return;
|
|
153
|
+
seen.add(key);
|
|
154
|
+
context.gap(one);
|
|
155
|
+
};
|
|
156
|
+
/**
|
|
157
|
+
* The names `{select}` asks for: every mapped one, then the account's own while they fit `max` (a request line past
|
|
158
|
+
* about 8 KB is refused); the call says how many it left out.
|
|
159
|
+
*/
|
|
160
|
+
const selectOf = (kind, defined, context) => {
|
|
161
|
+
const entity = entityOf(kind);
|
|
162
|
+
if (!entity.select)
|
|
163
|
+
return [];
|
|
164
|
+
const own = [...new Set([...selectedOf(entity.map, entity.select.from), ...(entity.select.also ?? [])])];
|
|
165
|
+
const custom = entity.custom?.from === entity.select.from ? defined.map(({ code }) => code) : [];
|
|
166
|
+
const { max } = entity.select;
|
|
167
|
+
if (max === undefined)
|
|
168
|
+
return [...new Set([...own, ...custom])];
|
|
169
|
+
const kept = [...own];
|
|
170
|
+
let length = own.join(",").length;
|
|
171
|
+
for (const name of custom)
|
|
172
|
+
if (!kept.includes(name) && length + name.length + 1 <= max) {
|
|
173
|
+
kept.push(name);
|
|
174
|
+
length += name.length + 1;
|
|
175
|
+
}
|
|
176
|
+
const left = custom.filter((name) => !kept.includes(name)).length;
|
|
177
|
+
if (left)
|
|
178
|
+
gap(context, {
|
|
179
|
+
kind,
|
|
180
|
+
message: `${left} of the account's own ${kind} fields do not fit one request and were not read`,
|
|
181
|
+
});
|
|
182
|
+
return kept;
|
|
183
|
+
};
|
|
184
|
+
/** A refusal of a kind the manifest marks optional is a gap; the other kinds still sync. */
|
|
185
|
+
const optionalRefused = (kind, error, context) => {
|
|
186
|
+
const optional = manifest.entities[kind]?.optional;
|
|
187
|
+
if (!optional || !isCliError(error) || error.code !== "permission_error")
|
|
188
|
+
return false;
|
|
189
|
+
gap(context, { kind, message: optional.message, ...(optional.scope ? { scope: optional.scope } : {}) });
|
|
190
|
+
return true;
|
|
191
|
+
};
|
|
192
|
+
const mapped = async (kind, rows, defined, send) => {
|
|
193
|
+
const entity = entityOf(kind);
|
|
194
|
+
const after = hooks.after?.[kind];
|
|
195
|
+
const enrich = hooks.enrich?.[kind];
|
|
196
|
+
const records = [];
|
|
197
|
+
for (const raw of enrich && rows.length ? await enrich([...rows], { call: send }) : rows) {
|
|
198
|
+
const record = mapRecord(kind, entity, raw, defined);
|
|
199
|
+
if (record !== null)
|
|
200
|
+
records.push(after ? await after(record, raw, { call: send }) : record);
|
|
201
|
+
}
|
|
202
|
+
return records;
|
|
203
|
+
};
|
|
204
|
+
/**
|
|
205
|
+
* One page of a change read sorted by modified time: the next page starts at the last row's time, or further along
|
|
206
|
+
* the same time when the whole page shares it. A service's own page token is an offset into a list that moves when
|
|
207
|
+
* a row changes mid-round, and would skip the row behind it. Past `cap`, only a full list reads them all.
|
|
208
|
+
*/
|
|
209
|
+
const keysetPage = async (changes, slots, since, token, send) => {
|
|
210
|
+
const [fromText, offsetText] = (token ?? "").split(".");
|
|
211
|
+
const from = token === undefined ? since : Number(fromText);
|
|
212
|
+
const offset = token === undefined ? 0 : Number(offsetText);
|
|
213
|
+
if (!Number.isSafeInteger(from) || !Number.isSafeInteger(offset))
|
|
214
|
+
return { reset: true };
|
|
215
|
+
const { rows, next } = await readPage(changes, { ...slots, since: SINCE[changes.since](from) }, offset ? String(offset) : undefined, send);
|
|
216
|
+
if (next === undefined)
|
|
217
|
+
return { rows, next: undefined };
|
|
218
|
+
const last = convert("epoch", at(rows.at(-1), changes.keyset.field));
|
|
219
|
+
const spot = typeof last === "number" && last > from ? { from: last, offset: 0 } : { from, offset: offset + rows.length };
|
|
220
|
+
if (changes.keyset.cap !== undefined && spot.offset + rows.length > changes.keyset.cap)
|
|
221
|
+
return { reset: true };
|
|
222
|
+
return { rows, next: `${spot.from}.${spot.offset}` };
|
|
223
|
+
};
|
|
224
|
+
const readChanges = async (kind, cursor, page, context) => {
|
|
225
|
+
const entity = entityOf(kind);
|
|
226
|
+
const since = cursor === null ? null : Date.parse(cursor);
|
|
227
|
+
if (since !== null && Number.isNaN(since))
|
|
228
|
+
return { reset: true };
|
|
229
|
+
const { token, started } = pageOf(page, now());
|
|
230
|
+
const send = metered(context);
|
|
231
|
+
const defined = entity.custom ? await fieldsOf(kind, send, context) : [];
|
|
232
|
+
const changes = since !== null ? entity.changes : undefined;
|
|
233
|
+
const slots = { select: selectOf(kind, defined, context) };
|
|
234
|
+
const read = changes?.keyset && since !== null
|
|
235
|
+
? await keysetPage({ ...changes, keyset: changes.keyset }, slots, since - overlap, token, send)
|
|
236
|
+
: await readPage(changes ?? entity.list, changes && since !== null ? { ...slots, since: SINCE[changes.since](since - overlap) } : slots, token, send);
|
|
237
|
+
if ("reset" in read)
|
|
238
|
+
return { reset: true };
|
|
239
|
+
const { rows, next } = read;
|
|
240
|
+
const items = await mapped(kind, rows, defined, send);
|
|
241
|
+
return next === undefined
|
|
242
|
+
? { items, hasMore: false, cursor: new Date(started).toISOString() }
|
|
243
|
+
: { items, hasMore: true, nextCursor: `${next}@${started}` };
|
|
244
|
+
};
|
|
245
|
+
const readIds = async (kind, page, context) => {
|
|
246
|
+
const entity = entityOf(kind);
|
|
247
|
+
const { rows, next } = await readPage(entity.ids ?? entity.list, {}, page, metered(context));
|
|
248
|
+
const items = rows.flatMap((raw) => {
|
|
249
|
+
const found = evaluate(entity.map.externalId, raw);
|
|
250
|
+
const externalId = found === MISSING ? null : id(found);
|
|
251
|
+
return externalId === null ? [] : [externalId];
|
|
252
|
+
});
|
|
253
|
+
return next === undefined ? { items, hasMore: false } : { items, hasMore: true, nextCursor: next };
|
|
254
|
+
};
|
|
255
|
+
const base = {
|
|
256
|
+
provider: manifest.provider,
|
|
257
|
+
traits: { kinds: manifest.kinds, removedInChanges: false },
|
|
258
|
+
async pipelines(kind, context) {
|
|
259
|
+
const spec = manifest.pipelines?.[kind];
|
|
260
|
+
if (!spec)
|
|
261
|
+
return [];
|
|
262
|
+
try {
|
|
263
|
+
const rows = await readAll(spec.call, metered(context));
|
|
264
|
+
return rows.flatMap((raw) => toPipeline(spec, raw) ?? []);
|
|
265
|
+
}
|
|
266
|
+
catch (error) {
|
|
267
|
+
if (optionalRefused(kind, error, context))
|
|
268
|
+
return [];
|
|
269
|
+
throw error;
|
|
270
|
+
}
|
|
271
|
+
},
|
|
272
|
+
async changes(kind, cursor, page, context) {
|
|
273
|
+
try {
|
|
274
|
+
return await readChanges(kind, cursor, page, context);
|
|
275
|
+
}
|
|
276
|
+
catch (error) {
|
|
277
|
+
if (optionalRefused(kind, error, context))
|
|
278
|
+
return { items: [], hasMore: false, cursor: null };
|
|
279
|
+
throw error;
|
|
280
|
+
}
|
|
281
|
+
},
|
|
282
|
+
async ids(kind, page, context) {
|
|
283
|
+
try {
|
|
284
|
+
return await readIds(kind, page, context);
|
|
285
|
+
}
|
|
286
|
+
catch (error) {
|
|
287
|
+
// Refused part way through a pass, the ids read so far would mark every unread row deleted.
|
|
288
|
+
if (page === undefined && optionalRefused(kind, error, context))
|
|
289
|
+
return { items: [], hasMore: false };
|
|
290
|
+
throw error;
|
|
291
|
+
}
|
|
292
|
+
},
|
|
293
|
+
async get(kind, externalId, context) {
|
|
294
|
+
const entity = entityOf(kind);
|
|
295
|
+
if (!entity.get)
|
|
296
|
+
return null;
|
|
297
|
+
const send = metered(context);
|
|
298
|
+
const defined = entity.custom ? await fieldsOf(kind, send, context) : [];
|
|
299
|
+
let answer;
|
|
300
|
+
try {
|
|
301
|
+
answer = await send(entity.get.operation, inputOf(entity.get, { id: externalId, select: selectOf(kind, defined, context) }));
|
|
302
|
+
}
|
|
303
|
+
catch (error) {
|
|
304
|
+
if (unseen(error))
|
|
305
|
+
return null;
|
|
306
|
+
throw error;
|
|
307
|
+
}
|
|
308
|
+
const raw = entity.get.items === undefined ? answer : at(answer, entity.get.items);
|
|
309
|
+
return isRaw(raw) ? ((await mapped(kind, [raw], defined, send))[0] ?? null) : null;
|
|
310
|
+
},
|
|
311
|
+
...(manifest.fields
|
|
312
|
+
? { fields: (kind, context) => fieldsOf(kind, metered(context), context) }
|
|
313
|
+
: {}),
|
|
314
|
+
...(manifest.users
|
|
315
|
+
? {
|
|
316
|
+
async users(context) {
|
|
317
|
+
const spec = manifest.users;
|
|
318
|
+
const rows = await readAll(spec.call, metered(context));
|
|
319
|
+
const users = rows.flatMap((raw) => {
|
|
320
|
+
const user = mapFields(spec.map, { externalId: "id", name: "text", email: "text", position: "text", active: "bool" }, raw);
|
|
321
|
+
return typeof user.externalId === "string" ? [user] : [];
|
|
322
|
+
});
|
|
323
|
+
return [...new Map(users.map((user) => [user.externalId, user])).values()];
|
|
324
|
+
},
|
|
325
|
+
}
|
|
326
|
+
: {}),
|
|
327
|
+
};
|
|
328
|
+
return { ...base, ...hooks.extend?.(base) };
|
|
329
|
+
};
|
|
330
|
+
const outcomeOf = (spec, stage, pipeline) => {
|
|
331
|
+
if (typeof spec === "function")
|
|
332
|
+
return spec(stage, pipeline);
|
|
333
|
+
if ("value" in spec)
|
|
334
|
+
return spec.value;
|
|
335
|
+
const found = text(at(stage, spec.path)) ?? "";
|
|
336
|
+
if (spec.won?.includes(found))
|
|
337
|
+
return "won";
|
|
338
|
+
return spec.lost?.includes(found) ? "lost" : "open";
|
|
339
|
+
};
|
|
340
|
+
const toPipeline = (spec, raw) => {
|
|
341
|
+
const { externalId, name } = mapFields(spec.map, { externalId: "id", name: "text" }, raw);
|
|
342
|
+
if (typeof externalId !== "string")
|
|
343
|
+
return null;
|
|
344
|
+
return {
|
|
345
|
+
externalId,
|
|
346
|
+
name: typeof name === "string" ? name : externalId,
|
|
347
|
+
stages: rawsOf(at(raw, spec.stages.each)).flatMap((stage, place) => {
|
|
348
|
+
const found = mapFields(spec.stages.map, { externalId: "id", name: "text", position: "text" }, stage);
|
|
349
|
+
if (typeof found.externalId !== "string")
|
|
350
|
+
return [];
|
|
351
|
+
return [
|
|
352
|
+
{
|
|
353
|
+
externalId: found.externalId,
|
|
354
|
+
name: typeof found.name === "string" ? found.name : found.externalId,
|
|
355
|
+
position: number(found.position) ?? place,
|
|
356
|
+
outcome: outcomeOf(spec.stages.outcome, stage, raw),
|
|
357
|
+
},
|
|
358
|
+
];
|
|
359
|
+
}),
|
|
360
|
+
};
|
|
361
|
+
};
|
|
362
|
+
const toField = (spec, raw) => {
|
|
363
|
+
if (spec.keep && !spec.keep(raw))
|
|
364
|
+
return null;
|
|
365
|
+
const { options: optionsRule, ...rules } = spec.map;
|
|
366
|
+
const found = mapFields(rules, { code: "text", label: "text", type: "text", multiple: "bool", filterable: "bool" }, raw);
|
|
367
|
+
if (typeof found.code !== "string")
|
|
368
|
+
return null;
|
|
369
|
+
const options = typeof optionsRule === "function"
|
|
370
|
+
? optionsRule(raw)
|
|
371
|
+
: optionsRule === undefined
|
|
372
|
+
? undefined
|
|
373
|
+
: rawsOf(at(raw, optionsRule.each)).flatMap((one) => {
|
|
374
|
+
const option = convert("text", at(one, optionsRule.id));
|
|
375
|
+
return typeof option === "string" ? [{ id: option, label: text(at(one, optionsRule.label)) ?? option }] : [];
|
|
376
|
+
});
|
|
377
|
+
return {
|
|
378
|
+
code: found.code,
|
|
379
|
+
label: typeof found.label === "string" ? found.label : null,
|
|
380
|
+
type: typeof found.type === "string" ? found.type : "string",
|
|
381
|
+
multiple: found.multiple === true,
|
|
382
|
+
filterable: found.filterable !== false,
|
|
383
|
+
...(options?.length ? { options: [...new Map(options.map((one) => [one.id, one])).values()] } : {}),
|
|
384
|
+
};
|
|
385
|
+
};
|
package/dist/errors/reasons.js
CHANGED
|
@@ -62,6 +62,7 @@ const PROVIDER_API = [
|
|
|
62
62
|
["offline.refused", "permission_error", "this command needs the provider; --offline was given"],
|
|
63
63
|
validation("api.unknown-method", "the provider has no method by this name"),
|
|
64
64
|
["api.disabled", "configuration_error", "the provider's API is turned off for this OAuth project"],
|
|
65
|
+
["manifest.invalid", "configuration_error", "the source manifest does not match its shape or the generated API"],
|
|
65
66
|
["provider.usage-limit", "rate_limited", "the account's usage limit at the provider is reached; wait, do not retry"],
|
|
66
67
|
["access.denied", "permission_error", "the provider refused this account access to the item"],
|
|
67
68
|
["item.not-found", "not_found", "the provider has no item by this id, or this account cannot see it"],
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { CrmManifest } from "../crm/manifest/manifest.js";
|
|
2
|
+
import type { OAuthProvider } from "../oauth/provider.js";
|
|
3
|
+
export type CliAuth = {
|
|
4
|
+
preset: "none";
|
|
5
|
+
}
|
|
6
|
+
/** A token or key, sent where the spec's `securitySchemes` say: a bearer header, an API key header or query. */
|
|
7
|
+
| {
|
|
8
|
+
preset: "token";
|
|
9
|
+
}
|
|
10
|
+
/** The browser sign-in the spec's authorization code flow declares; the redirect is what the app registered. */
|
|
11
|
+
| {
|
|
12
|
+
preset: "oauth2-pkce";
|
|
13
|
+
scopes: readonly string[];
|
|
14
|
+
scheme?: string;
|
|
15
|
+
redirect?: OAuthProvider["redirect"];
|
|
16
|
+
revokeUrl?: string;
|
|
17
|
+
authorizeParams?: Record<string, string>;
|
|
18
|
+
/** The provider sends a new refresh token on each refresh; the spec cannot say so. */
|
|
19
|
+
rotating?: boolean;
|
|
20
|
+
};
|
|
21
|
+
export declare const CLI_CATEGORIES: readonly ["messenger", "mail", "notes", "files", "meetings", "calendar", "crm", "other"];
|
|
22
|
+
export type CliCategory = (typeof CLI_CATEGORIES)[number];
|
|
23
|
+
/** One file, `wirecat.config.ts`, that `new --from-config` builds a CLI from. */
|
|
24
|
+
export interface CliConfig {
|
|
25
|
+
identity: {
|
|
26
|
+
/** The word people type: `attio`. */
|
|
27
|
+
command: string;
|
|
28
|
+
/** `@wirecat/attio-cli`. */
|
|
29
|
+
package: string;
|
|
30
|
+
/** The environment variables' prefix: `WCATTIO`. */
|
|
31
|
+
prefix: string;
|
|
32
|
+
/** The name people know: `Attio`. */
|
|
33
|
+
service: string;
|
|
34
|
+
/** The GitHub owner of the repository. */
|
|
35
|
+
owner: string;
|
|
36
|
+
};
|
|
37
|
+
/** `from`: the https URL the description is published at. */
|
|
38
|
+
spec: {
|
|
39
|
+
kind: "openapi" | "swagger";
|
|
40
|
+
from: string;
|
|
41
|
+
};
|
|
42
|
+
auth: CliAuth;
|
|
43
|
+
/** cli-template's `--category`; `other` is any API outside them. */
|
|
44
|
+
category: CliCategory;
|
|
45
|
+
/** The CRM source; checked against the generated API by `parseCrmManifest` once the api group exists. */
|
|
46
|
+
source?: CrmManifest;
|
|
47
|
+
/** The module of named hooks, relative to the config: `./src/hooks.ts`. */
|
|
48
|
+
hooks?: string;
|
|
49
|
+
}
|
|
50
|
+
/** Types the config in the editor; it returns what it is given. */
|
|
51
|
+
export declare const defineCli: (config: CliConfig) => CliConfig;
|
|
52
|
+
/** The config checked against its shape; every error names where it is. A CRM CLI needs its source. */
|
|
53
|
+
export declare const parseCliConfig: (input: unknown) => CliConfig;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { isAbsolute } from "node:path";
|
|
2
|
+
import { CliError } from "@wirecat/cli-base";
|
|
3
|
+
import * as v from "valibot";
|
|
4
|
+
export const CLI_CATEGORIES = ["messenger", "mail", "notes", "files", "meetings", "calendar", "crm", "other"];
|
|
5
|
+
/** Types the config in the editor; it returns what it is given. */
|
|
6
|
+
export const defineCli = (config) => config;
|
|
7
|
+
const word = v.pipe(v.string(), v.regex(/^[a-z][a-z0-9]*(-[a-z0-9]+)*$/, "lower-case letters and digits, words joined by one dash"));
|
|
8
|
+
/** In the project: no absolute path, no `..`, no scheme. */
|
|
9
|
+
const projectPath = (text) => !isAbsolute(text) && !text.split(/[\\/]/).includes("..") && !/^[a-z][a-z0-9+.-]*:/i.test(text);
|
|
10
|
+
const schema = v.strictObject({
|
|
11
|
+
identity: v.strictObject({
|
|
12
|
+
command: word,
|
|
13
|
+
package: v.pipe(v.string(), v.regex(/^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/, "an npm package name")),
|
|
14
|
+
prefix: v.pipe(v.string(), v.regex(/^[A-Z][A-Z0-9_]*$/, "upper-case letters, digits and underscores")),
|
|
15
|
+
service: v.pipe(v.string(), v.minLength(1)),
|
|
16
|
+
owner: v.pipe(v.string(), v.regex(/^[A-Za-z0-9](?:-?[A-Za-z0-9]){0,38}$/, "a GitHub owner")),
|
|
17
|
+
}),
|
|
18
|
+
spec: v.strictObject({
|
|
19
|
+
kind: v.picklist(["openapi", "swagger"]),
|
|
20
|
+
from: v.pipe(v.string(), v.check((text) => /^https:\/\/[^/\s]+/.test(text), "the https URL the description is published at")),
|
|
21
|
+
}),
|
|
22
|
+
auth: v.variant("preset", [
|
|
23
|
+
v.strictObject({ preset: v.literal("none") }),
|
|
24
|
+
v.strictObject({ preset: v.literal("token") }),
|
|
25
|
+
v.strictObject({
|
|
26
|
+
preset: v.literal("oauth2-pkce"),
|
|
27
|
+
scopes: v.array(v.string()),
|
|
28
|
+
scheme: v.optional(v.string()),
|
|
29
|
+
revokeUrl: v.optional(v.pipe(v.string(), v.startsWith("https://"))),
|
|
30
|
+
authorizeParams: v.optional(v.record(v.string(), v.string())),
|
|
31
|
+
rotating: v.optional(v.boolean()),
|
|
32
|
+
redirect: v.optional(v.variant("kind", [
|
|
33
|
+
v.strictObject({ kind: v.literal("loopback"), host: v.optional(v.literal("localhost")) }),
|
|
34
|
+
v.strictObject({ kind: v.literal("relay"), url: v.pipe(v.string(), v.startsWith("https://")) }),
|
|
35
|
+
])),
|
|
36
|
+
}),
|
|
37
|
+
]),
|
|
38
|
+
category: v.picklist(CLI_CATEGORIES),
|
|
39
|
+
source: v.optional(v.looseObject({})),
|
|
40
|
+
hooks: v.optional(v.pipe(v.string(), v.startsWith("./"), v.check(projectPath, "a module in the project"))),
|
|
41
|
+
});
|
|
42
|
+
/** The config checked against its shape; every error names where it is. A CRM CLI needs its source. */
|
|
43
|
+
export const parseCliConfig = (input) => {
|
|
44
|
+
const parsed = v.safeParse(schema, input);
|
|
45
|
+
if (!parsed.success) {
|
|
46
|
+
const [issue] = parsed.issues;
|
|
47
|
+
throw new CliError("configuration_error", `wirecat.config: ${v.getDotPath(issue) ?? "(root)"}: ${issue.message}`, {
|
|
48
|
+
reason: "manifest.invalid",
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
const config = parsed.output;
|
|
52
|
+
if (config.category !== "crm" && config.source)
|
|
53
|
+
throw new CliError("configuration_error", "wirecat.config: source: only a crm CLI reads a source yet", {
|
|
54
|
+
reason: "manifest.invalid",
|
|
55
|
+
});
|
|
56
|
+
if (config.category === "crm" && !config.source)
|
|
57
|
+
throw new CliError("configuration_error", "wirecat.config: source: a crm CLI needs its source", {
|
|
58
|
+
reason: "manifest.invalid",
|
|
59
|
+
});
|
|
60
|
+
return config;
|
|
61
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@wirecat/cli-core",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.693.0",
|
|
4
4
|
"description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Viacheslav Ptsarev",
|
|
@@ -143,6 +143,10 @@
|
|
|
143
143
|
"types": "./dist/calendar/testing/index.d.ts",
|
|
144
144
|
"default": "./dist/calendar/testing/index.js"
|
|
145
145
|
},
|
|
146
|
+
"./manifest": {
|
|
147
|
+
"types": "./dist/manifest/index.d.ts",
|
|
148
|
+
"default": "./dist/manifest/index.js"
|
|
149
|
+
},
|
|
146
150
|
"./crm": {
|
|
147
151
|
"types": "./dist/crm/index.d.ts",
|
|
148
152
|
"default": "./dist/crm/index.js"
|
|
@@ -239,6 +243,7 @@
|
|
|
239
243
|
"search:docs": "pnpm build && node scripts/search-docs.ts",
|
|
240
244
|
"check:agent-process": "pnpm build && node --experimental-strip-types scripts/check-agent-process.ts",
|
|
241
245
|
"standards:check": "node config/wirecat/check.mjs",
|
|
246
|
+
"docs:images": "node docs/images/src/render.ts",
|
|
242
247
|
"docs:lint": "markdownlint-cli2",
|
|
243
248
|
"docs:spell": "cspell lint --config cspell.json --no-progress README.md",
|
|
244
249
|
"ci:quick": "pnpm typecheck && vitest run src/cli/command-lint.test.ts",
|
|
@@ -300,7 +305,7 @@
|
|
|
300
305
|
"@types/pngjs": "6.0.5",
|
|
301
306
|
"@types/ssh2": "1.15.5",
|
|
302
307
|
"@vitest/coverage-v8": "^5.0.5",
|
|
303
|
-
"@wirecat/cli-base": "0.
|
|
308
|
+
"@wirecat/cli-base": "0.112.0",
|
|
304
309
|
"@wirecat/cli-core-legacy-tags": "npm:@wirecat/cli-core@0.414.0",
|
|
305
310
|
"ajv": "8.17.1",
|
|
306
311
|
"commander": "15.0.0",
|
|
@@ -324,7 +329,7 @@
|
|
|
324
329
|
},
|
|
325
330
|
"peerDependencies": {
|
|
326
331
|
"@napi-rs/canvas": ">=0.1.69 <2",
|
|
327
|
-
"@wirecat/cli-base": ">=0.
|
|
332
|
+
"@wirecat/cli-base": ">=0.112.0 <1.0.0",
|
|
328
333
|
"commander": ">=15",
|
|
329
334
|
"mysql2": "^3.24.6",
|
|
330
335
|
"pg": "^8.23.1",
|